/**
   Get a socket for reading from the server
*/
static int get_socket(void)
{
    get_socket_count++;

    int s = try_get_socket_once();
    if (s < 0)
    {
        if (start_fishd)
        {
            debug(2, L"Could not connect to socket %d, starting fishd", s);

            start_fishd();

            for (size_t i=0; s < 0 && i < DEFAULT_RETRY_COUNT; i++)
            {
                if (i > 0)
                {
                    // Wait before next try
                    usleep((useconds_t)(DEFAULT_RETRY_DELAY * 1E6));
                }
                s = try_get_socket_once();
            }
        }
    }

    if (s < 0)
    {
        debug(1, L"Could not connect to universal variable server, already tried manual restart (or no command supplied). You will not be able to share variable values between fish sessions. Is fish properly installed?");
        return -1;
    }

    return s;
}
/**
   Get a socket for reading from the server
*/
static int get_socket( int fork_ok )
{
	int s, len;
	struct sockaddr_un local;
	
	char *name;
	wchar_t *wdir;
	wchar_t *wuname;	
	char *dir =0, *uname=0;

	get_socket_count++;
	wdir = path;
	wuname = user;
	
	if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) 
	{
		wperror(L"socket");
		return -1;
	}
	
	if( wdir )
		dir = wcs2str(wdir );
	else
		dir = strdup("/tmp");
	
	if( wuname )
		uname = wcs2str(wuname );
	else
	{
		struct passwd *pw;
		pw = getpwuid( getuid() );
		uname = strdup( pw->pw_name );
	}
	
	name = (char *)malloc( strlen(dir) +
				   strlen(uname) + 
				   strlen(SOCK_FILENAME) + 
				   2 );
	
	strcpy( name, dir );
	strcat( name, "/" );
	strcat( name, SOCK_FILENAME );
	strcat( name, uname );
	
	free( dir );
	free( uname );
	
	debug( 3, L"Connect to socket %s at fd %2", name, s );
	
	local.sun_family = AF_UNIX;
	strcpy(local.sun_path, name );
	free( name );
	len = sizeof(local);
	
	if( connect( s, (struct sockaddr *)&local, len) == -1 ) 
	{
		close( s );
		if( fork_ok && start_fishd )
		{
			debug( 2, L"Could not connect to socket %d, starting fishd", s );
			
			start_fishd();
									
			return get_socket( 0 );
		}
		
		debug( 1, L"Could not connect to universal variable server, already tried manual restart (or no command supplied). You will not be able to share variable values between fish sessions. Is fish properly installed?" );
		return -1;
	}
	
	if( (fcntl( s, F_SETFL, O_NONBLOCK ) != 0) || (fcntl( s, F_SETFD, FD_CLOEXEC ) != 0) ) 
	{
		wperror( L"fcntl" );
		close( s );		
		
		return -1;
	}

	debug( 3, L"Connected to fd %d", s );
	
	return s;
}