Example #1
0
Socket platform_new_connection(SockAddr addr, char *hostname,
			       int port, int privport,
			       int oobinline, int nodelay, int keepalive,
			       Plug plug, Conf *conf)
{
    char *cmd;
    HANDLE us_to_cmd, us_from_cmd, cmd_to_us, cmd_from_us;
    SECURITY_ATTRIBUTES sa;
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    if (conf_get_int(conf, CONF_proxy_type) != PROXY_CMD)
	return NULL;

    cmd = format_telnet_command(addr, port, conf);

    /* We are responsible for this and don't need it any more */
    sk_addr_free(addr);

    {
	char *msg = dupprintf("Starting local proxy command: %s", cmd);
	/* We're allowed to pass NULL here, because we're part of the Windows
	 * front end so we know logevent doesn't expect any data. */
	logevent(NULL, msg);
	sfree(msg);
    }

    /*
     * Create the pipes to the proxy command, and spawn the proxy
     * command process.
     */
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;    /* default */
    sa.bInheritHandle = TRUE;
    if (!CreatePipe(&us_from_cmd, &cmd_to_us, &sa, 0)) {
	Socket ret =
            new_error_socket("Unable to create pipes for proxy command", plug);
        sfree(cmd);
	return ret;
    }

    if (!CreatePipe(&cmd_from_us, &us_to_cmd, &sa, 0)) {
	Socket ret =
            new_error_socket("Unable to create pipes for proxy command", plug);
        sfree(cmd);
	CloseHandle(us_from_cmd);
	CloseHandle(cmd_to_us);
	return ret;
    }

    SetHandleInformation(us_to_cmd, HANDLE_FLAG_INHERIT, 0);
    SetHandleInformation(us_from_cmd, HANDLE_FLAG_INHERIT, 0);

    si.cb = sizeof(si);
    si.lpReserved = NULL;
    si.lpDesktop = NULL;
    si.lpTitle = NULL;
    si.dwFlags = STARTF_USESTDHANDLES;
    si.cbReserved2 = 0;
    si.lpReserved2 = NULL;
    si.hStdInput = cmd_from_us;
    si.hStdOutput = cmd_to_us;
    si.hStdError = NULL;
    CreateProcess(NULL, cmd, NULL, NULL, TRUE,
		  CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS,
		  NULL, NULL, &si, &pi);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    sfree(cmd);

    CloseHandle(cmd_from_us);
    CloseHandle(cmd_to_us);

    return make_handle_socket(us_to_cmd, us_from_cmd, plug, FALSE);
}
Example #2
0
Socket new_connection(SockAddr addr, char *hostname,
		      int port, int privport,
		      int oobinline, int nodelay, int keepalive,
		      Plug plug, Conf *conf)
{
    static const struct socket_function_table socket_fn_table = {
	sk_proxy_plug,
	sk_proxy_close,
	sk_proxy_write,
	sk_proxy_write_oob,
	sk_proxy_write_eof,
	sk_proxy_flush,
	sk_proxy_set_frozen,
	sk_proxy_socket_error,
        NULL, /* peer_info */
    };

    static const struct plug_function_table plug_fn_table = {
	plug_proxy_log,
	plug_proxy_closing,
	plug_proxy_receive,
	plug_proxy_sent,
	plug_proxy_accepting
    };

    if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE &&
	proxy_for_destination(addr, hostname, port, conf))
    {
	Proxy_Socket ret;
	Proxy_Plug pplug;
	SockAddr proxy_addr;
	char *proxy_canonical_name;
	Socket sret;
	int type;

	if ((sret = platform_new_connection(addr, hostname, port, privport,
					    oobinline, nodelay, keepalive,
					    plug, conf)) !=
	    NULL)
	    return sret;

	ret = snew(struct Socket_proxy_tag);
	ret->fn = &socket_fn_table;
	ret->conf = conf_copy(conf);
	ret->plug = plug;
	ret->remote_addr = addr;       /* will need to be freed on close */
	ret->remote_port = port;

	ret->error = NULL;
	ret->pending_flush = 0;
	ret->pending_eof = 0;
	ret->freeze = 0;

	bufchain_init(&ret->pending_input_data);
	bufchain_init(&ret->pending_output_data);
	bufchain_init(&ret->pending_oob_output_data);

	ret->sub_socket = NULL;
	ret->state = PROXY_STATE_NEW;
	ret->negotiate = NULL;

	type = conf_get_int(conf, CONF_proxy_type);
	if (type == PROXY_HTTP) {
	    ret->negotiate = proxy_http_negotiate;
	} else if (type == PROXY_SOCKS4) {
            ret->negotiate = proxy_socks4_negotiate;
	} else if (type == PROXY_SOCKS5) {
            ret->negotiate = proxy_socks5_negotiate;
	} else if (type == PROXY_TELNET) {
	    ret->negotiate = proxy_telnet_negotiate;
	} else {
	    ret->error = "Proxy error: Unknown proxy method";
	    return (Socket) ret;
	}

	/* create the proxy plug to map calls from the actual
	 * socket into our proxy socket layer */
	pplug = snew(struct Plug_proxy_tag);
	pplug->fn = &plug_fn_table;
	pplug->proxy_socket = ret;

	/* look-up proxy */
	proxy_addr = sk_namelookup(conf_get_str(conf, CONF_proxy_host),
				   &proxy_canonical_name,
				   conf_get_int(conf, CONF_addressfamily));
	if (sk_addr_error(proxy_addr) != NULL) {
	    ret->error = "Proxy error: Unable to resolve proxy host name";
            sfree(pplug);
            sk_addr_free(proxy_addr);
	    return (Socket)ret;
	}
	sfree(proxy_canonical_name);

	/* create the actual socket we will be using,
	 * connected to our proxy server and port.
	 */
	ret->sub_socket = sk_new(proxy_addr,
				 conf_get_int(conf, CONF_proxy_port),
				 privport, oobinline,
				 nodelay, keepalive, (Plug) pplug);
	if (sk_socket_error(ret->sub_socket) != NULL)
	    return (Socket) ret;

	/* start the proxy negotiation process... */
	sk_set_frozen(ret->sub_socket, 0);
	ret->negotiate(ret, PROXY_CHANGE_NEW);

	return (Socket) ret;
    }
Example #3
0
int main(int argc, char **argv)
{
    int sending;
    int portnumber = -1;
    SOCKET *sklist;
    int skcount, sksize;
    int exitcode;
    int errors;
    int got_host = FALSE;
    int use_subsystem = 0;
    unsigned long now, next, then;

    sklist = NULL;
    skcount = sksize = 0;
    /*
     * Initialise port and protocol to sensible defaults. (These
     * will be overridden by more or less anything.)
     */
    default_protocol = PROT_SSH;
    default_port = 22;

    flags = FLAG_STDERR;
    /*
     * Process the command line.
     */
    conf = conf_new();
    do_defaults(NULL, conf);
    loaded_session = FALSE;
    default_protocol = conf_get_int(conf, CONF_protocol);
    default_port = conf_get_int(conf, CONF_port);
    errors = 0;
    {
	/*
	 * Override the default protocol if PLINK_PROTOCOL is set.
	 */
	char *p = getenv("PLINK_PROTOCOL");
	if (p) {
	    const Backend *b = backend_from_name(p);
	    if (b) {
		default_protocol = b->protocol;
		default_port = b->default_port;
		conf_set_int(conf, CONF_protocol, default_protocol);
		conf_set_int(conf, CONF_port, default_port);
	    }
	}
    }
    while (--argc) {
	char *p = *++argv;
	if (*p == '-') {
	    int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
					    1, conf);
	    if (ret == -2) {
		fprintf(stderr,
			"plink: option \"%s\" requires an argument\n", p);
		errors = 1;
	    } else if (ret == 2) {
		--argc, ++argv;
	    } else if (ret == 1) {
		continue;
	    } else if (!strcmp(p, "-batch")) {
		console_batch_mode = 1;
	    } else if (!strcmp(p, "-s")) {
		/* Save status to write to conf later. */
		use_subsystem = 1;
	    } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
                version();
	    } else if (!strcmp(p, "--help")) {
                usage();
            } else if (!strcmp(p, "-pgpfp")) {
                pgp_fingerprints();
                exit(1);
	    } else {
		fprintf(stderr, "plink: unknown option \"%s\"\n", p);
		errors = 1;
	    }
	} else if (*p) {
	    if (!conf_launchable(conf) || !(got_host || loaded_session)) {
		char *q = p;
		/*
		 * If the hostname starts with "telnet:", set the
		 * protocol to Telnet and process the string as a
		 * Telnet URL.
		 */
		if (!strncmp(q, "telnet:", 7)) {
		    char c;

		    q += 7;
		    if (q[0] == '/' && q[1] == '/')
			q += 2;
		    conf_set_int(conf, CONF_protocol, PROT_TELNET);
		    p = q;
		    while (*p && *p != ':' && *p != '/')
			p++;
		    c = *p;
		    if (*p)
			*p++ = '\0';
		    if (c == ':')
			conf_set_int(conf, CONF_port, atoi(p));
		    else
			conf_set_int(conf, CONF_port, -1);
		    conf_set_str(conf, CONF_host, q);
		    got_host = TRUE;
		} else {
		    char *r, *user, *host;
		    /*
		     * Before we process the [user@]host string, we
		     * first check for the presence of a protocol
		     * prefix (a protocol name followed by ",").
		     */
		    r = strchr(p, ',');
		    if (r) {
			const Backend *b;
			*r = '\0';
			b = backend_from_name(p);
			if (b) {
			    default_protocol = b->protocol;
			    conf_set_int(conf, CONF_protocol,
					 default_protocol);
			    portnumber = b->default_port;
			}
			p = r + 1;
		    }

		    /*
		     * A nonzero length string followed by an @ is treated
		     * as a username. (We discount an _initial_ @.) The
		     * rest of the string (or the whole string if no @)
		     * is treated as a session name and/or hostname.
		     */
		    r = strrchr(p, '@');
		    if (r == p)
			p++, r = NULL; /* discount initial @ */
		    if (r) {
			*r++ = '\0';
			user = p, host = r;
		    } else {
			user = NULL, host = p;
		    }

		    /*
		     * Now attempt to load a saved session with the
		     * same name as the hostname.
		     */
		    {
			Conf *conf2 = conf_new();
			do_defaults(host, conf2);
			if (loaded_session || !conf_launchable(conf2)) {
			    /* No settings for this host; use defaults */
			    /* (or session was already loaded with -load) */
			    conf_set_str(conf, CONF_host, host);
			    conf_set_int(conf, CONF_port, default_port);
			    got_host = TRUE;
			} else {
			    conf_copy_into(conf, conf2);
			    loaded_session = TRUE;
			}
			conf_free(conf2);
		    }

		    if (user) {
			/* Patch in specified username. */
			conf_set_str(conf, CONF_username, user);
		    }

		}
	    } else {
		char *command;
		int cmdlen, cmdsize;
		cmdlen = cmdsize = 0;
		command = NULL;

		while (argc) {
		    while (*p) {
			if (cmdlen >= cmdsize) {
			    cmdsize = cmdlen + 512;
			    command = sresize(command, cmdsize, char);
			}
			command[cmdlen++]=*p++;
		    }
		    if (cmdlen >= cmdsize) {
			cmdsize = cmdlen + 512;
			command = sresize(command, cmdsize, char);
		    }
		    command[cmdlen++]=' '; /* always add trailing space */
		    if (--argc) p = *++argv;
		}
		if (cmdlen) command[--cmdlen]='\0';
				       /* change trailing blank to NUL */
		conf_set_str(conf, CONF_remote_cmd, command);
		conf_set_str(conf, CONF_remote_cmd2, "");
		conf_set_int(conf, CONF_nopty, TRUE);  /* command => no tty */

		break;		       /* done with cmdline */
	    }
	}
Example #4
0
Socket platform_new_connection(SockAddr addr, char *hostname,
			       int port, int privport,
			       int oobinline, int nodelay, int keepalive,
			       Plug plug, Conf *conf)
{
    char *cmd;

    static const struct socket_function_table socket_fn_table = {
	sk_localproxy_plug,
	sk_localproxy_close,
	sk_localproxy_write,
	sk_localproxy_write_oob,
	sk_localproxy_flush,
	sk_localproxy_set_private_ptr,
	sk_localproxy_get_private_ptr,
	sk_localproxy_set_frozen,
	sk_localproxy_socket_error
    };

    Local_Proxy_Socket ret;
    HANDLE us_to_cmd, us_from_cmd, cmd_to_us, cmd_from_us;
    SECURITY_ATTRIBUTES sa;
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    if (conf_get_int(conf, CONF_proxy_type) != PROXY_CMD)
	return NULL;

    cmd = format_telnet_command(addr, port, conf);

    {
	char *msg = dupprintf("Starting local proxy command: %s", cmd);
	/* We're allowed to pass NULL here, because we're part of the Windows
	 * front end so we know logevent doesn't expect any data. */
	logevent(NULL, msg);
	sfree(msg);
    }

    ret = snew(struct Socket_localproxy_tag);
    ret->fn = &socket_fn_table;
    ret->plug = plug;
    ret->error = NULL;

    /*
     * Create the pipes to the proxy command, and spawn the proxy
     * command process.
     */
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;    /* default */
    sa.bInheritHandle = TRUE;
    if (!CreatePipe(&us_from_cmd, &cmd_to_us, &sa, 0)) {
	ret->error = dupprintf("Unable to create pipes for proxy command");
	return (Socket)ret;
    }

    if (!CreatePipe(&cmd_from_us, &us_to_cmd, &sa, 0)) {
	CloseHandle(us_from_cmd);
	CloseHandle(cmd_to_us);
	ret->error = dupprintf("Unable to create pipes for proxy command");
	return (Socket)ret;
    }

    SetHandleInformation(us_to_cmd, HANDLE_FLAG_INHERIT, 0);
    SetHandleInformation(us_from_cmd, HANDLE_FLAG_INHERIT, 0);

    si.cb = sizeof(si);
    si.lpReserved = NULL;
    si.lpDesktop = NULL;
    si.lpTitle = NULL;
    si.dwFlags = STARTF_USESTDHANDLES;
    si.cbReserved2 = 0;
    si.lpReserved2 = NULL;
    si.hStdInput = cmd_from_us;
    si.hStdOutput = cmd_to_us;
    si.hStdError = NULL;
    CreateProcess(NULL, cmd, NULL, NULL, TRUE,
		  CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS,
		  NULL, NULL, &si, &pi);

    sfree(cmd);

    CloseHandle(cmd_from_us);
    CloseHandle(cmd_to_us);

    ret->to_cmd_H = us_to_cmd;
    ret->from_cmd_H = us_from_cmd;

    ret->from_cmd_h = handle_input_new(ret->from_cmd_H, localproxy_gotdata,
				       ret, 0);
    ret->to_cmd_h = handle_output_new(ret->to_cmd_H, localproxy_sentdata,
				      ret, 0);

    /* We are responsible for this and don't need it any more */
    sk_addr_free(addr);

    return (Socket) ret;
}
Example #5
0
void SaveDumpConfig( FILE *fp, Conf * conf ) {
    char *buf=NULL ;
    CountUp();
    fprintf( fp, "MASTER_PASSWORD=%s\n", MASTER_PASSWORD ) ;
    fprintf( fp, "[[PuTTY structure configuration]]\n" ) ;
    fprintf( fp, "sessionname=%s\n", 		conf_get_str(conf,CONF_sessionname) ) ;
    /* Basic options */
    fprintf( fp, "host=%s\n", 			conf_get_str(conf,CONF_host) ) ;
    fprintf( fp, "port=%d\n", 			conf_get_int(conf,CONF_port) ) ;
    fprintf( fp, "protocol=%d\n", 			conf_get_int(conf,CONF_protocol) ) ;
    fprintf( fp, "addressfamily=%d\n",		conf_get_int(conf,CONF_addressfamily) ) ;
    fprintf( fp, "close_on_exit=%d\n",		conf_get_int(conf,CONF_close_on_exit) ) ;
    fprintf( fp, "warn_on_close=%d\n",		conf_get_int(conf,CONF_warn_on_close) ) ;
    fprintf( fp, "ping_interval=%d\n", 		conf_get_int(conf,CONF_ping_interval) ) ;
    fprintf( fp, "tcp_nodelay=%d\n", 		conf_get_int(conf,CONF_tcp_nodelay) ) ;
    fprintf( fp, "tcp_keepalives=%d\n", 		conf_get_int(conf,CONF_tcp_keepalives) ) ;
    /* Proxy options */
    fprintf( fp, "proxy_exclude_list=%s\n",		conf_get_str(conf,CONF_proxy_exclude_list) ) ;
    fprintf( fp, "proxy_dns=%d\n", 			conf_get_int(conf,CONF_proxy_dns) ) ;
    fprintf( fp, "even_proxy_localhost=%d\n",	conf_get_int(conf,CONF_even_proxy_localhost) ) ;
    fprintf( fp, "proxy_type=%d\n",			conf_get_int(conf,CONF_proxy_type) ) ;

    fprintf( fp, "proxy_host=%s\n", 		conf_get_str(conf,CONF_proxy_host) ) ;
    fprintf( fp, "proxy_port=%d\n", 		conf_get_int(conf,CONF_proxy_port) ) ;
    fprintf( fp, "proxy_username=%s\n", 		conf_get_str(conf,CONF_proxy_username) ) ;
    fprintf( fp, "proxy_password=%s\n", 		conf_get_str(conf,CONF_proxy_password) ) ;
    fprintf( fp, "proxy_telnet_command=%s\n", 	conf_get_str(conf,CONF_proxy_telnet_command) ) ;
    fprintf( fp, "proxy_log_to_term=%d\n", 		conf_get_int(conf,CONF_proxy_log_to_term) ) ;

    /* PERSOPORT Options */
    // fprintf( fp, "bcdelay=%d\n", 			conf_get_int(conf,CONF_bcdelay) ) ;		// Non present systematiquement
    // fprintf( fp, "initdelay=%d\n",			conf_get_int(conf,CONF_initdelay) ) ;		// Non present systematiquement
    fprintf( fp, "transparencynumber=%d\n", 	conf_get_int(conf,CONF_transparencynumber) ) ;
    fprintf( fp, "sendtotray=%d\n",			conf_get_int(conf,CONF_sendtotray) ) ;
    fprintf( fp, "maximize=%d\n",			conf_get_int(conf,CONF_maximize) ) ;
    fprintf( fp, "icone=%d\n",			conf_get_int(conf,CONF_icone) ) ;
    fprintf( fp, "iconefile=%s\n",			conf_get_filename(conf,CONF_iconefile)->path ) ;
    fprintf( fp, "folder=%s\n", 			conf_get_str(conf,CONF_folder) ) ;
    fprintf( fp, "sftpconnect=%s\n", 		conf_get_str(conf,CONF_sftpconnect) ) ;

    char bufpass[4096] ;
    memcpy( bufpass, conf_get_str(conf,CONF_password), 4095 ) ;
    bufpass[4095]='\0';
    MASKPASS(bufpass);
    fprintf( fp, "password=%s\n",			bufpass ) ;
    memset(bufpass,0,strlen(bufpass));

    fprintf( fp, "antiidle=%s\n",			conf_get_str(conf,CONF_antiidle) ) ;
    fprintf( fp, "autocommand=%s\n",		conf_get_str(conf,CONF_autocommand) ) ;
    fprintf( fp, "autocommandout=%s\n",		conf_get_str(conf,CONF_autocommandout) ) ;
    fprintf( fp, "scriptfile=%s\n",			conf_get_filename(conf,CONF_scriptfile)->path ) ;
    fprintf( fp, "scriptfilecontent=%s",		conf_get_str(conf,CONF_scriptfilecontent) ) ;

    buf=(char*)malloc( strlen(conf_get_str(conf,CONF_scriptfilecontent)) + 20 ) ;
    strcpy( buf, conf_get_str(conf,CONF_scriptfilecontent) ) ;
    long l=decryptstring( buf, MASTER_PASSWORD ) ;
    int i;
    for( i=0; i<l ; i++ ) {
        if( buf[i]=='\0' ) buf[i]='\n' ;
    }
    fprintf( fp, " (%s)\n", buf ) ;
    free(buf);
    buf=NULL;

    /* SSH options */
    fprintf( fp, "remote_cmd=%s\n",			conf_get_str(conf,CONF_remote_cmd) ) ;
    //char *remote_cmd_ptr;	       /* might point to a larger command but never for loading/saving */
    //char *remote_cmd_ptr2;	       /* might point to a larger command but never for loading/saving */
    fprintf( fp, "nopty=%d\n",			conf_get_int(conf,CONF_nopty) ) ;
    fprintf( fp, "compression=%d\n",		conf_get_int(conf,CONF_compression) ) ;
    fprintf( fp, "ssh_rekey_time=%d\n",		conf_get_int(conf,CONF_ssh_rekey_time) ) ;
    //int ssh_kexlist[KEX_MAX];
    fprintf( fp, "ssh_rekey_data=%s\n",		conf_get_str(conf,CONF_ssh_rekey_data) ) ;
    fprintf( fp, "tryagent=%d\n",			conf_get_int(conf,CONF_tryagent) ) ;
    fprintf( fp, "agentfwd=%d\n",			conf_get_int(conf,CONF_agentfwd) ) ;
    fprintf( fp, "change_username=%d\n",		conf_get_int(conf,CONF_change_username) ) ;
    //int ssh_cipherlist[CIPHER_MAX];
    fprintf( fp, "keyfile=%s\n",			conf_get_filename(conf,CONF_keyfile)->path ) ;
    fprintf( fp, "sshprot=%d\n",			conf_get_int(conf,CONF_sshprot) ) ;
    fprintf( fp, "ssh2_des_cbc=%d\n",		conf_get_int(conf,CONF_ssh2_des_cbc) ) ;
    fprintf( fp, "ssh_no_userauth=%d\n",		conf_get_int(conf,CONF_ssh_no_userauth) ) ;
    fprintf( fp, "ssh_show_banner=%d\n",		conf_get_int(conf,CONF_ssh_show_banner) ) ;
    fprintf( fp, "try_tis_auth=%d\n",		conf_get_int(conf,CONF_try_tis_auth) ) ;
    fprintf( fp, "try_ki_auth=%d\n",		conf_get_int(conf,CONF_try_ki_auth) ) ;
    fprintf( fp, "try_gssapi_auth=%d\n",		conf_get_int(conf,CONF_try_gssapi_auth) ) ;
    fprintf( fp, "gssapifwd=%d\n",			conf_get_int(conf,CONF_gssapifwd) ) ;
    //fprintf( fp, "ssh_gsslist=%d\n",		conf_get_int(conf,CONF_ssh_gsslist) ) ;
    fprintf( fp, "ssh_gss_custom=%s\n",		conf_get_filename(conf,CONF_ssh_gss_custom)->path ) ;
    //fprintf( fp, "ssh_subsys=%d\n",			conf_get_int(conf,CONF_ssh_subsys) ) ;
    //fprintf( fp, "ssh_subsys2=%d\n",		conf_get_int(conf,CONF_ssh_subsys2) ) ;
    fprintf( fp, "ssh_no_shell=%d\n",		conf_get_int(conf,CONF_ssh_no_shell) ) ;
    //fprintf( fp, "ssh_nc_host=%s\n",		conf_get_str(conf,CONF_ssh_nc_host) ) ;
    //fprintf( fp, "ssh_nc_port=%d\n",		conf_get_int(conf,CONF_ssh_nc_port) ) ;

#ifdef RUTTYPORT
    fprintf( fp, "ScriptFileName=%s\n",		conf_get_filename(conf,CONF_script_filename)->path ) ;
    fprintf( fp, "ScriptMode=%d\n",			conf_get_int(conf,CONF_script_mode) ) ;
    fprintf( fp, "ScriptLineDelay=%d\n",		conf_get_int(conf,CONF_script_line_delay) ) ;
    fprintf( fp, "ScriptCharDelay=%d\n",		conf_get_int(conf,CONF_script_char_delay) ) ;
    fprintf( fp, "ScriptCondLine=%s\n",		conf_get_str(conf,CONF_script_cond_line) ) ;
    fprintf( fp, "ScriptCondUse=%d\n",		conf_get_int(conf,CONF_script_cond_use) ) ;
    fprintf( fp, "ScriptCRLF=%d\n",			conf_get_int(conf,CONF_script_crlf) ) ;
    fprintf( fp, "ScriptEnable=%d\n",		conf_get_int(conf,CONF_script_enable) ) ;
    fprintf( fp, "ScriptExcept=%d\n",		conf_get_int(conf,CONF_script_except) ) ;
    fprintf( fp, "ScriptTimeout=%d\n",		conf_get_int(conf,CONF_script_timeout) ) ;
    fprintf( fp, "ScriptWait=%s\n",			conf_get_str(conf,CONF_script_waitfor) ) ;
    fprintf( fp, "ScriptHalt=%s\n",			conf_get_str(conf,CONF_script_halton) ) ;
#endif
    /* Telnet options */
    fprintf( fp, "termtype=%s\n",			conf_get_str(conf,CONF_termtype ) ) ;
    fprintf( fp, "termspeed=%s\n",			conf_get_str(conf,CONF_termspeed ) ) ;
    //fprintf( fp, "ttymodes=%s\n",			conf_get_str(conf,CONF_ttymodes ) ) ;
    //fprintf( fp, "environmt=%s\n",			conf_get_str(conf,CONF_environmt ) ) ;
    fprintf( fp, "username=%s\n",			conf_get_str(conf,CONF_username ) ) ;
    fprintf( fp, "localusername=%s\n",		conf_get_str(conf,CONF_localusername ) ) ;
    fprintf( fp, "rfc_environ=%d\n",		conf_get_int(conf,CONF_rfc_environ) ) ;
    fprintf( fp, "passive_telnet=%d\n",		conf_get_int(conf,CONF_passive_telnet) ) ;
    /* Serial port options */
    fprintf( fp, "serline=%s\n", 			conf_get_str(conf,CONF_serline) ) ;
    fprintf( fp, "serspeed=%d\n",			conf_get_int(conf,CONF_serspeed) ) ;
    fprintf( fp, "serdatabits=%d\n",		conf_get_int(conf,CONF_serdatabits) ) ;
    fprintf( fp, "serstopbits=%d\n",		conf_get_int(conf,CONF_serstopbits) ) ;
    fprintf( fp, "serparity=%d\n",			conf_get_int(conf,CONF_serparity) ) ;
    fprintf( fp, "serflow=%d\n",			conf_get_int(conf,CONF_serflow) ) ;
#ifdef IVPORT
    /* Background */
    fprintf( fp, "bg_wallpaper=%d\n", 		conf_get_int(conf, CONF_bg_wallpaper));
    fprintf( fp, "bg_effect=%d\n", 			conf_get_int(conf, CONF_bg_effect));
    fprintf( fp, "wp_file=%s\n", 			conf_get_filename(conf,CONF_wp_file)->path ) ;
    fprintf( fp, "wp_position=%d\n", 		conf_get_int(conf, CONF_wp_position));
    fprintf( fp, "wp_align=%d\n", 			conf_get_int(conf, CONF_wp_align));
    fprintf( fp, "wp_valign=%d\n", 			conf_get_int(conf, CONF_wp_valign));
    fprintf( fp, "wp_moving=%d\n", 			conf_get_int(conf, CONF_wp_moving));
#endif
#ifdef CYGTERMPORT
    /* Cygterm options */
    fprintf( fp, "cygcmd=%s\n", 			conf_get_str(conf,CONF_cygcmd) ) ;
    fprintf( fp, "alt_metabit=%d\n", 		conf_get_int(conf,CONF_alt_metabit) ) ;
#endif
    /* Keyboard options */
    fprintf( fp, "bksp_is_delete=%d\n", 		conf_get_int(conf,CONF_bksp_is_delete) ) ;
    fprintf( fp, "rxvt_homeend=%d\n", 		conf_get_int(conf,CONF_rxvt_homeend) ) ;
    fprintf( fp, "funky_type=%d\n", 		conf_get_int(conf,CONF_funky_type) ) ;
    fprintf( fp, "no_applic_c=%d\n", 		conf_get_int(conf,CONF_no_applic_c) ) ;
    fprintf( fp, "no_applic_k=%d\n", 		conf_get_int(conf,CONF_no_applic_k) ) ;
    fprintf( fp, "no_mouse_rep=%d\n", 		conf_get_int(conf,CONF_no_mouse_rep) ) ;
    fprintf( fp, "no_remote_resize=%d\n", 		conf_get_int(conf,CONF_no_remote_resize) ) ;
    fprintf( fp, "no_alt_screen=%d\n", 		conf_get_int(conf,CONF_no_alt_screen) ) ;
    fprintf( fp, "no_remote_wintitle=%d\n", 	conf_get_int(conf,CONF_no_remote_wintitle) ) ;
    fprintf( fp, "no_dbackspace=%d\n", 		conf_get_int(conf,CONF_no_dbackspace) ) ;
    fprintf( fp, "no_remote_charset=%d\n", 		conf_get_int(conf,CONF_no_remote_charset) ) ;
    fprintf( fp, "remote_qtitle_action=%d\n", 	conf_get_int(conf,CONF_remote_qtitle_action) ) ;
    fprintf( fp, "app_cursor=%d\n", 		conf_get_int(conf,CONF_app_cursor) ) ;
    fprintf( fp, "app_keypad=%d\n", 		conf_get_int(conf,CONF_app_keypad) ) ;
    fprintf( fp, "nethack_keypad=%d\n", 		conf_get_int(conf,CONF_nethack_keypad) ) ;
    fprintf( fp, "telnet_keyboard=%d\n", 		conf_get_int(conf,CONF_telnet_keyboard) ) ;
    fprintf( fp, "telnet_newline=%d\n", 		conf_get_int(conf,CONF_telnet_newline) ) ;
    fprintf( fp, "alt_f4=%d\n", 			conf_get_int(conf,CONF_alt_f4) ) ;
    fprintf( fp, "alt_space=%d\n", 			conf_get_int(conf,CONF_alt_space) ) ;
    fprintf( fp, "alt_only=%d\n", 			conf_get_int(conf,CONF_alt_only) ) ;
    fprintf( fp, "localecho=%d\n", 			conf_get_int(conf,CONF_localecho) ) ;
    fprintf( fp, "localedit=%d\n", 			conf_get_int(conf,CONF_localedit) ) ;
    fprintf( fp, "alwaysontop=%d\n", 		conf_get_int(conf,CONF_alwaysontop) ) ;
    fprintf( fp, "fullscreenonaltenter=%d\n", 	conf_get_int(conf,CONF_fullscreenonaltenter) ) ;
    fprintf( fp, "scroll_on_key=%d\n", 		conf_get_int(conf,CONF_scroll_on_key) ) ;
    fprintf( fp, "scroll_on_disp=%d\n", 		conf_get_int(conf,CONF_scroll_on_disp) ) ;
    fprintf( fp, "erase_to_scrollback=%d\n",	conf_get_int(conf,CONF_erase_to_scrollback) ) ;
    fprintf( fp, "compose_key=%d\n", 		conf_get_int(conf,CONF_compose_key) ) ;
    fprintf( fp, "ctrlaltkeys=%d\n", 		conf_get_int(conf,CONF_ctrlaltkeys) ) ;
#ifdef OSX_META_KEY_CONFIG
    fprintf( fp, "osx_option_meta=%d\n", 		conf_get_int(conf,CONF_osx_option_meta) ) ;
    fprintf( fp, "osx_command_meta=%d\n", 		conf_get_int(conf,CONF_osx_command_meta) ) ;
#endif
    fprintf( fp, "wintitle=%s\n",			conf_get_str(conf,CONF_wintitle) ) ;
    /* Terminal options */
    fprintf( fp, "savelines=%d\n", 			conf_get_int(conf,CONF_savelines) ) ;
    fprintf( fp, "dec_om=%d\n", 			conf_get_int(conf,CONF_dec_om) ) ;
    fprintf( fp, "wrap_mode=%d\n", 			conf_get_int(conf,CONF_wrap_mode) ) ;
    fprintf( fp, "lfhascr=%d\n", 			conf_get_int(conf,CONF_lfhascr) ) ;
    fprintf( fp, "cursor_type=%d\n", 		conf_get_int(conf,CONF_cursor_type) ) ;
    fprintf( fp, "blink_cur=%d\n", 			conf_get_int(conf,CONF_blink_cur) ) ;
    fprintf( fp, "beep=%d\n", 			conf_get_int(conf,CONF_beep) ) ;
    fprintf( fp, "beep_ind=%d\n", 			conf_get_int(conf,CONF_beep_ind) ) ;
    fprintf( fp, "bellovl=%d\n", 			conf_get_int(conf,CONF_bellovl) ) ;
    fprintf( fp, "bellovl_n=%d\n", 			conf_get_int(conf,CONF_bellovl_n) ) ;
    fprintf( fp, "bellovl_t=%d\n",			conf_get_int(conf,CONF_bellovl_t) ) ;
    fprintf( fp, "bellovl_s=%d\n",			conf_get_int(conf,CONF_bellovl_s) ) ;
    fprintf( fp, "scrollbar=%d\n",			conf_get_int(conf,CONF_scrollbar) ) ;
    fprintf( fp, "scrollbar_in_fullscreen=%d\n",	conf_get_int(conf,CONF_scrollbar_in_fullscreen) ) ;
    fprintf( fp, "resize_action=%d\n",		conf_get_int(conf,CONF_resize_action) ) ;
    fprintf( fp, "bce=%d\n",			conf_get_int(conf,CONF_bce) ) ;
    fprintf( fp, "blinktext=%d\n",			conf_get_int(conf,CONF_blinktext) ) ;
    fprintf( fp, "win_name_always=%d\n",		conf_get_int(conf,CONF_win_name_always) ) ;
    fprintf( fp, "width=%d\n",			conf_get_int(conf,CONF_width) ) ;
    fprintf( fp, "height=%d\n",			conf_get_int(conf,CONF_height) ) ;
    fprintf( fp, "font_quality=%d\n",		conf_get_int(conf,CONF_font_quality) ) ;
    fprintf( fp, "logtype=%d\n",			conf_get_int(conf,CONF_logtype) ) ;
    fprintf( fp, "logxfovr=%d\n",			conf_get_int(conf,CONF_logxfovr) ) ;
    fprintf( fp, "logflush=%d\n",			conf_get_int(conf,CONF_logflush) ) ;
    fprintf( fp, "logomitpass=%d\n",		conf_get_int(conf,CONF_logomitpass) ) ;
    fprintf( fp, "logomitdata=%d\n",		conf_get_int(conf,CONF_logomitdata) ) ;
    fprintf( fp, "hide_mouseptr=%d\n",		conf_get_int(conf,CONF_hide_mouseptr) ) ;
    fprintf( fp, "sunken_edge=%d\n",		conf_get_int(conf,CONF_sunken_edge) ) ;
    fprintf( fp, "window_border=%d\n",		conf_get_int(conf,CONF_window_border) ) ;
    fprintf( fp, "saveonexit=%d\n",			conf_get_int(conf,CONF_saveonexit) ) ;
    fprintf( fp, "XPos=%d\n",			conf_get_int(conf,CONF_xpos) ) ;
    fprintf( fp, "YPos=%d\n",			conf_get_int(conf,CONF_ypos) ) ;
    fprintf( fp, "fullscreen=%d\n",			conf_get_int(conf,CONF_fullscreen) ) ;
    fprintf( fp, "foreground_on_bell=%d\n",		conf_get_int(conf,CONF_foreground_on_bell) ) ;
    fprintf( fp, "bell_wavefile=%s\n",		conf_get_filename(conf,CONF_bell_wavefile)->path ) ;
    //FontSpec font;
    fprintf( fp, "logfilename=%s\n",		conf_get_filename(conf,CONF_logfilename)->path ) ;
#if (defined IMAGEPORT) && (!defined FDJ)
    /* IMAGEPORT Options */
    fprintf( fp, "bg_opacity=%d\n",			conf_get_int(conf,CONF_bg_opacity) ) ;
    fprintf( fp, "bg_slideshow=%d\n",		conf_get_int(conf,CONF_bg_slideshow) ) ;
    fprintf( fp, "bg_type=%d\n",			conf_get_int(conf,CONF_bg_type) ) ;
    fprintf( fp, "bg_image_style=%d\n",		conf_get_int(conf,CONF_bg_image_style) ) ;
    fprintf( fp, "bg_image_abs_x=%d\n",		conf_get_int(conf,CONF_bg_image_abs_x) ) ;
    fprintf( fp, "bg_image_abs_y=%d\n",		conf_get_int(conf,CONF_bg_image_abs_y) ) ;
    fprintf( fp, "bg_image_abs_fixed=%d\n",		conf_get_int(conf,CONF_bg_image_abs_fixed) ) ;
    fprintf( fp, "bg_image_filename=%s\n",		conf_get_filename(conf,CONF_bg_image_filename)->path ) ;
#endif
    fprintf( fp, "answerback=%s\n",			conf_get_str(conf,CONF_answerback) ) ;
    fprintf( fp, "printer=%s\n",			conf_get_str(conf,CONF_printer) ) ;
    fprintf( fp, "arabicshaping=%d\n",		conf_get_int(conf,CONF_arabicshaping) ) ;
#ifdef PRINTCLIPPORT
    fprintf( fp, "printclip=%d\n",			conf_get_int(conf,CONF_printclip) ) ;
#endif
    fprintf( fp, "bidi=%d\n",			conf_get_int(conf,CONF_bidi) ) ;
    /* Colour options */
    fprintf( fp, "ansi_colour=%d\n",		conf_get_int(conf,CONF_ansi_colour) ) ;
    fprintf( fp, "xterm_256_colour=%d\n",		conf_get_int(conf,CONF_xterm_256_colour) ) ;
    fprintf( fp, "system_colour=%d\n",		conf_get_int(conf,CONF_system_colour) ) ;
    fprintf( fp, "try_palette%d\n",			conf_get_int(conf,CONF_try_palette) ) ;
    fprintf( fp, "bold_style=%d\n",			conf_get_int(conf,CONF_bold_style) ) ;
    //unsigned char colours[22][3];
    /* Selection options */
    fprintf( fp, "mouse_is_xterm=%d\n",		conf_get_int(conf,CONF_mouse_is_xterm) ) ;
    fprintf( fp, "rect_select=%d\n",		conf_get_int(conf,CONF_rect_select) ) ;
    fprintf( fp, "rawcnp=%d\n",			conf_get_int(conf,CONF_rawcnp) ) ;
    fprintf( fp, "rtf_paste=%d\n",			conf_get_int(conf,CONF_rtf_paste) ) ;
    fprintf( fp, "mouse_override=%d\n",		conf_get_int(conf,CONF_mouse_override) ) ;
    //short wordness[256];
    /* translations */
    fprintf( fp, "vtmode=%d\n",			conf_get_int(conf,CONF_vtmode) ) ;
    fprintf( fp, "line_codepage=%s\n",		conf_get_str(conf,CONF_line_codepage) ) ;
    fprintf( fp, "cjk_ambig_wide=%d\n",		conf_get_int(conf,CONF_cjk_ambig_wide) ) ;
    fprintf( fp, "utf8_override=%d\n",		conf_get_int(conf,CONF_utf8_override) ) ;
    fprintf( fp, "xlat_capslockcyr=%d\n",		conf_get_int(conf,CONF_xlat_capslockcyr) ) ;
    /* X11 forwarding */
    fprintf( fp, "x11_forward=%d\n",		conf_get_int(conf,CONF_x11_forward) ) ;
    fprintf( fp, "x11_auth=%d\n",			conf_get_int(conf,CONF_x11_auth) ) ;
    fprintf( fp, "x11_display=%s\n",		conf_get_str(conf,CONF_x11_display) ) ;
    /* port forwarding */
    fprintf( fp, "lport_acceptall=%d\n",		conf_get_int(conf,CONF_lport_acceptall) ) ;
    fprintf( fp, "rport_acceptall=%d\n",		conf_get_int(conf,CONF_rport_acceptall) ) ;
    fprintf( fp, "portfwd=\n") ;
    char *key, *val;
    for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
            val != NULL;
            val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
        if (!strcmp(val, "D")) fprintf( fp, "	D%s\t\n", key+1 ) ;
        else fprintf( fp, "	%s\t%s\n", key, val);
    }
    /* SSH bug compatibility modes */
    fprintf( fp, "sshbug_ignore1=%d\n",		conf_get_int(conf,CONF_sshbug_ignore1) ) ;
    fprintf( fp, "sshbug_plainpw1=%d\n",		conf_get_int(conf,CONF_sshbug_plainpw1) ) ;
    fprintf( fp, "sshbug_rsa1=%d\n",		conf_get_int(conf,CONF_sshbug_rsa1) ) ;
    fprintf( fp, "sshbug_hmac2=%d\n",		conf_get_int(conf,CONF_sshbug_hmac2) ) ;
    fprintf( fp, "sshbug_derivekey2=%d\n",		conf_get_int(conf,CONF_sshbug_derivekey2) ) ;
    fprintf( fp, "sshbug_rsapad2=%d\n",		conf_get_int(conf,CONF_sshbug_rsapad2) ) ;
    fprintf( fp, "sshbug_pksessid2=%d\n",		conf_get_int(conf,CONF_sshbug_pksessid2) ) ;
    fprintf( fp, "sshbug_rekey2=%d\n",		conf_get_int(conf,CONF_sshbug_rekey2) ) ;
    /* Options for pterm. Should split out into platform-dependent part. */
    fprintf( fp, "stamp_utmp=%d\n",			conf_get_int(conf,CONF_stamp_utmp) ) ;
    fprintf( fp, "login_shell=%d\n",		conf_get_int(conf,CONF_login_shell) ) ;
    fprintf( fp, "scrollbar_on_left=%d\n",		conf_get_int(conf,CONF_scrollbar_on_left) ) ;
    fprintf( fp, "shadowbold=%d\n",			conf_get_int(conf,CONF_shadowbold) ) ;
    fprintf( fp, "shadowboldoffset=%d\n",		conf_get_int(conf,CONF_shadowboldoffset) ) ;
    fprintf( fp, "ctrl_tab_switch=%d\n", 		conf_get_int(conf, CONF_ctrl_tab_switch));
    fprintf( fp, "comment=%s\n",			conf_get_str(conf,CONF_comment) ) ;
    fprintf( fp, "acs_in_utf=%d\n", 		conf_get_int(conf, CONF_acs_in_utf));
    fprintf( fp, "scp_auto_pwd=%d\n", 		conf_get_int(conf, CONF_scp_auto_pwd));
#ifdef RECONNECTPORT
    fprintf( fp, "wakeup_reconnect=%d\n",		conf_get_int(conf,CONF_wakeup_reconnect) ) ;
    fprintf( fp, "failure_reconnect=%d\n",		conf_get_int(conf,CONF_failure_reconnect) ) ;
#endif
#ifdef HYPERLINKPORT
    fprintf( fp, "url_ctrl_click=%d\n",		conf_get_int(conf,CONF_url_ctrl_click) ) ;
    fprintf( fp, "url_underline=%d\n",		conf_get_int(conf,CONF_url_underline) ) ;
    fprintf( fp, "url_defbrowser=%d\n",		conf_get_int(conf,CONF_url_defbrowser) ) ;
    fprintf( fp, "url_defregex=%d\n",		conf_get_int(conf,CONF_url_defregex) ) ;
    fprintf( fp, "url_browser=%s\n",		conf_get_filename(conf,CONF_url_browser)->path ) ;
    fprintf( fp, "url_regex=%s\n",			conf_get_str(conf,CONF_url_regex) ) ;
    fprintf( fp, "urlhack_default_regex=%s\n",	urlhack_default_regex ) ;
    fprintf( fp, "urlhack_liberal_regex=%s\n",	urlhack_liberal_regex ) ;
#endif
#ifdef ZMODEMPORT
    fprintf( fp, "rzcommand=%s\n",			conf_get_filename(conf,CONF_rzcommand)->path ) ;
    fprintf( fp, "rzoptions=%s\n",			conf_get_str(conf,CONF_rzoptions) ) ;
    fprintf( fp, "szcommand=%s\n",			conf_get_filename(conf,CONF_szcommand)->path ) ;
    fprintf( fp, "szoptions=%s\n",			conf_get_str(conf,CONF_szoptions) ) ;
    fprintf( fp, "zdownloaddir=%s\n",		conf_get_str(conf,CONF_zdownloaddir) ) ;
#endif
#ifdef TUTTYPORT
    fprintf( fp, "window_closable=%d\n",		conf_get_int(conf,CONF_window_closable) ) ;
    fprintf( fp, "window_minimizable=%d\n",		conf_get_int(conf,CONF_window_minimizable) ) ;
    fprintf( fp, "window_maximizable=%d\n",		conf_get_int(conf,CONF_window_maximizable) ) ;
    fprintf( fp, "window_has_sysmenu=%d\n",		conf_get_int(conf,CONF_window_has_sysmenu) ) ;
    fprintf( fp, "bottom_buttons=%d\n",		conf_get_int(conf,CONF_bottom_buttons) ) ;
    fprintf( fp, "bold_colour=%d\n",		conf_get_int(conf,CONF_bold_colour) ) ;
    fprintf( fp, "under_colour=%d\n",		conf_get_int(conf,CONF_under_colour) ) ;
    fprintf( fp, "sel_colour=%d\n",			conf_get_int(conf,CONF_sel_colour) ) ;
#endif
#ifdef PORTKNOCKINGPORT
    fprintf( fp, "portknocking=%s\n",		conf_get_str(conf,CONF_portknockingoptions) ) ;
#endif
    //FontSpec boldfont; //FontSpec widefont; //FontSpec wideboldfont;

    fprintf( fp, "\n[[KiTTY specific configuration]]\n" ) ;
    fprintf( fp, "IniFileFlag=%d - ",IniFileFlag) ;
    switch(IniFileFlag) {
    case 0:
        fprintf( fp, "Registry\n" ) ;
        break ;
    case 1:
        fprintf( fp, "File\n" ) ;
        break ;
    case 2:
        fprintf( fp, "Directory\n" ) ;
        break ;
    }

    fprintf( fp, "internal_delay=%d\ninit_delay=%d\nautocommand_delay=%d\nbetween_char_delay=%d\nProtectFlag=%d\n",internal_delay,init_delay,autocommand_delay,between_char_delay,ProtectFlag );

    fprintf( fp, "HyperlinkFlag=%d\n", HyperlinkFlag );
    if( AutoCommand!= NULL ) fprintf( fp, "AutoCommand=%s\n", AutoCommand ) ;
    if( ScriptCommand!= NULL ) fprintf( fp, "ScriptCommand=%s\n", ScriptCommand ) ;
    if( PasteCommand!= NULL ) fprintf( fp, "PasteCommand=%s\n", PasteCommand ) ;
    fprintf( fp, "PasteCommandFlag=%d\n", PasteCommandFlag );
    if( ScriptFileContent!= NULL ) {
        char * pst = ScriptFileContent ;
        fprintf( fp, "ScriptFileContent=" ) ;
        while( strlen(pst) > 0 ) {
            fprintf( fp, "%s|", pst ) ;
            pst=pst+strlen(pst)+1 ;
        }
        fprintf( fp, "\n" )  ;
    }
    if( IconFile!= NULL ) fprintf( fp, "IconFile=%s\n", IconFile ) ;
    fprintf( fp, "AutoStoreSSHKeyFlag=%d\nDirectoryBrowseFlag=%d\nVisibleFlag=%d\nShortcutsFlag=%d\nMouseShortcutsFlag=%d\nIconeFlag=%d\nNumberOfIcons=%d\nSizeFlag=%d\nCapsLockFlag=%d\nTitleBarFlag=%d\nCtrlTabFlag=%d\nRuTTYFlag=%d\n"
             ,GetAutoStoreSSHKeyFlag(),DirectoryBrowseFlag,VisibleFlag,ShortcutsFlag,MouseShortcutsFlag,IconeFlag,NumberOfIcons,SizeFlag,CapsLockFlag,TitleBarFlag,CtrlTabFlag,RuTTYFlag);
    //static HINSTANCE hInstIcons =  NULL ;
    fprintf( fp, "WinHeight=%d\nAutoSendToTray=%d\nNoKittyFileFlag=%d\nConfigBoxHeight=%d\nConfigBoxWindowHeight=%d\nConfigBoxNoExitFlag=%d\nUserPassSSHNoSave=%d\nPuttyFlag=%d\n",WinHeight,AutoSendToTray,NoKittyFileFlag,ConfigBoxHeight,ConfigBoxWindowHeight,ConfigBoxNoExitFlag,UserPassSSHNoSave,PuttyFlag);
    fprintf( fp,"BackgroundImageFlag=%d\n",BackgroundImageFlag );
#ifdef RECONNECTPORT
    fprintf( fp,"AutoreconnectFlag=%d\nReconnectDelay=%d\n",AutoreconnectFlag,ReconnectDelay );
#endif
#ifdef IVPORT
    fprintf( fp,"BackgroundImageIVFlag=%d\n",BackgroundImageIVFlag );
#endif
#ifdef CYGTERMPORT
    fprintf( fp,"CygTermFlag=%d\n",cygterm_get_flag() );
#endif
#ifdef ADBPORT
    fprintf( fp,"ADBFlag=%d\n",GetADBFlag() );
#endif
    if( PasswordConf!= NULL ) fprintf( fp, "PasswordConf=%s\n", PasswordConf ) ;
    fprintf( fp, "SessionFilterFlag=%d\nSessionsInDefaultFlag=%d\nDefaultSettingsFlag=%d\nImageViewerFlag=%d\nImageSlideDelay=%d\nMaxBlinkingTime=%d\nPrintCharSize=%d\nPrintMaxLinePerPage=%d\nPrintMaxCharPerLine=%d\n"
             ,SessionFilterFlag,SessionsInDefaultFlag,DefaultSettingsFlag,ImageViewerFlag,ImageSlideDelay,MaxBlinkingTime,PrintCharSize,PrintMaxLinePerPage,PrintMaxCharPerLine);
    fprintf( fp, "AntiIdleCount=%d\nAntiIdleCountMax=%d\nIconeNum=%d\n"
             ,AntiIdleCount,AntiIdleCountMax,IconeNum);
    fprintf( fp, "AntiIdleStr=%s\nInitialDirectory=%s\nConfigDirectory=%s\nBuildVersionTime=%s\n",AntiIdleStr,InitialDirectory,ConfigDirectory,BuildVersionTime);
    if( WinSCPPath!= NULL ) fprintf( fp, "WinSCPPath=%s\n", WinSCPPath ) ;
    if( PSCPPath!= NULL ) fprintf( fp, "PSCPPath=%s\n", PSCPPath ) ;
    if( PlinkPath!= NULL ) fprintf( fp, "PlinkPath=%s\n", PlinkPath ) ;
    if( KittyIniFile!= NULL ) fprintf( fp, "KittyIniFile=%s\n", KittyIniFile ) ;
    if( KittySavFile!= NULL ) fprintf( fp, "KittySavFile=%s\n", KittySavFile ) ;
    if( KiTTYClassName != NULL ) fprintf( fp, "KiTTYClassName=%s\n", KiTTYClassName ) ;
    if( CtHelperPath!= NULL ) fprintf( fp, "CtHelperPath=%s\n", CtHelperPath ) ;
    if( strlen(ManagePassPhrase(NULL))>0 ) fprintf( fp, "PassPhrase=%s\n", ManagePassPhrase(NULL)) ;
}
Example #6
0
/*
 * Called to set up the raw connection.
 * 
 * Returns an error message, or NULL on success.
 *
 * Also places the canonical host name into `realhost'. It must be
 * freed by the caller.
 */
static const char *raw_init(void *frontend_handle, void **backend_handle,
			    Conf *conf,
			    char *host, int port, char **realhost, int nodelay,
			    int keepalive)
{
    static const struct plug_function_table fn_table = {
	raw_log,
	raw_closing,
	raw_receive,
	raw_sent
    };
    SockAddr addr;
    const char *err;
    Raw raw;
    int addressfamily;
    char *loghost;

    raw = snew(struct raw_backend_data);
    raw->fn = &fn_table;
    raw->s = NULL;
    raw->closed_on_socket_error = FALSE;
    *backend_handle = raw;
    raw->sent_console_eof = raw->sent_socket_eof = FALSE;
    raw->bufsize = 0;

    raw->frontend = frontend_handle;

    addressfamily = conf_get_int(conf, CONF_addressfamily);
    /*
     * Try to find host.
     */
    {
	char *buf;
	buf = dupprintf("Looking up host \"%s\"%s", host,
			(addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
			 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" :
			  "")));
	logevent(raw->frontend, buf);
	sfree(buf);
    }
    addr = name_lookup(host, port, realhost, conf, addressfamily);
    if ((err = sk_addr_error(addr)) != NULL) {
	sk_addr_free(addr);
	return err;
    }

    if (port < 0)
	port = 23;		       /* default telnet port */

    /*
     * Open socket.
     */
    raw->s = new_connection(addr, *realhost, port, 0, 1, nodelay, keepalive,
			    (Plug) raw, conf);
    if ((err = sk_socket_error(raw->s)) != NULL)
	return err;

    loghost = conf_get_str(conf, CONF_loghost);
    if (*loghost) {
	char *colon;

	sfree(*realhost);
	*realhost = dupstr(loghost);

	colon = host_strrchr(*realhost, ':');
	if (colon)
	    *colon++ = '\0';
    }

    return NULL;
}
Example #7
0
File: main.c Project: skoobe/riofs
/*{{{ application_finish_initialization_and_run */
static gint application_finish_initialization_and_run (Application *app)
{
    struct sigaction sigact;

/*{{{ create Pools */
    // create ClientPool for reading operations
    app->read_client_pool = client_pool_create (app, conf_get_int (app->conf, "pool.readers"),
        http_connection_create,
        http_connection_destroy,
        http_connection_set_on_released_cb,
        http_connection_check_rediness,
        http_connection_get_stats_info_caption,
        http_connection_get_stats_info_data
        );
    if (!app->read_client_pool) {
        LOG_err (APP_LOG, "Failed to create ClientPool !");
        application_exit (app);
        return -1;
    }

    // create ClientPool for writing operations
    app->write_client_pool = client_pool_create (app, conf_get_int (app->conf, "pool.writers"),
        http_connection_create,
        http_connection_destroy,
        http_connection_set_on_released_cb,
        http_connection_check_rediness,
        http_connection_get_stats_info_caption,
        http_connection_get_stats_info_data
        );
    if (!app->write_client_pool) {
        LOG_err (APP_LOG, "Failed to create ClientPool !");
        application_exit (app);
        return -1;
    }

    // create ClientPool for various operations
    app->ops_client_pool = client_pool_create (app, conf_get_int (app->conf, "pool.operations"),
        http_connection_create,
        http_connection_destroy,
        http_connection_set_on_released_cb,
        http_connection_check_rediness,
        http_connection_get_stats_info_caption,
        http_connection_get_stats_info_data
        );
    if (!app->ops_client_pool) {
        LOG_err (APP_LOG, "Failed to create ClientPool !");
        application_exit (app);
        return -1;
    }
/*}}}*/

/*{{{ CacheMng */
    app->cmng = cache_mng_create (app);
    if (!app->cmng) {
        LOG_err (APP_LOG, "Failed to create CacheMng !");
        application_exit (app);
        return -1;
    }
/*}}}*/

/*{{{ DirTree*/
    app->dir_tree = dir_tree_create (app);
    if (!app->dir_tree) {
        LOG_err (APP_LOG, "Failed to create DirTree !");
        application_exit (app);
        return -1;
    }
/*}}}*/

/*{{{ FUSE*/
    app->rfuse = rfuse_new (app, conf_get_string (app->conf, "app.mountpoint"), app->fuse_opts);
    if (!app->rfuse) {
        LOG_err (APP_LOG, "Failed to create FUSE fs ! Mount point: %s", conf_get_string (app->conf, "app.mountpoint"));
        application_exit (app);
        return -1;
    }
/*}}}*/

  // set global App variable
    _app = app;

/*{{{ signal handlers*/
    // SIGINT
    app->sigint_ev = evsignal_new (app->evbase, SIGINT, sigint_cb, app);
    event_add (app->sigint_ev, NULL);
    // SIGSEGV
    sigact.sa_sigaction = sigsegv_cb;
    sigact.sa_flags = (int)SA_RESETHAND | SA_SIGINFO;
    sigemptyset (&sigact.sa_mask);
    if (sigaction (SIGSEGV, &sigact, (struct sigaction *) NULL) != 0) {
        LOG_err (APP_LOG, "error setting signal handler for %d (%s)\n", SIGSEGV, strsignal(SIGSEGV));
        application_exit (app);
        return 1;
    }
    // SIGTERM
    app->sigterm_ev = evsignal_new (app->evbase, SIGTERM, sigterm_cb, app);
    event_add (app->sigterm_ev, NULL);
    // SIGABRT
    sigact.sa_sigaction = sigsegv_cb;
    sigact.sa_flags = (int)SA_RESETHAND | SA_SIGINFO;
    sigemptyset (&sigact.sa_mask);
    if (sigaction (SIGABRT, &sigact, (struct sigaction *) NULL) != 0) {
        LOG_err (APP_LOG, "error setting signal handler for %d (%s)\n", SIGABRT, strsignal(SIGABRT));
        application_exit (app);
        return 1;
    }
    // SIGPIPE
    app->sigpipe_ev = evsignal_new (app->evbase, SIGPIPE, sigpipe_cb, app);
    event_add (app->sigpipe_ev, NULL);

    // SIGUSR1
    app->sigusr1_ev = evsignal_new (app->evbase, SIGUSR1, sigusr1_cb, app);
    event_add (app->sigusr1_ev, NULL);

    // SIGUSR2
    app->sigusr2_ev = evsignal_new (app->evbase, SIGUSR2, sigusr2_cb, app);
    event_add (app->sigusr2_ev, NULL);

/*}}}*/

    if (!conf_get_boolean (app->conf, "app.foreground"))
        fuse_daemonize (0);

    return 0;
}
Example #8
0
void
check_opengl_features(void)
{
	GL_vendor = xstrdup((char*)gl(GetString, GL_VENDOR));
	GL_renderer = xstrdup((char*)gl(GetString, GL_RENDERER));
	GL_version = xstrdup((char*)gl(GetString, GL_VERSION));
	/* according to opengl spec, the version string of opengl and
	 * glsl is 
	 *
	 * <version number> <space> <vendor spec information>
	 *
	 * and <version number> is
	 *
	 * major.minor
	 *
	 * or
	 *
	 * major.minor.release
	 *
	 * */

	/* build gl version */
	int err;
	err = sscanf(GL_version, "%d.%d", &GL_major_version, &GL_minor_version);
	assert(err == 2);
	assert((GL_major_version > 0) && (GL_major_version <= 3));
	assert(GL_minor_version > 0);
	GL_full_version = MKVER(GL_major_version, GL_minor_version);

	const char * tmp = (const char *)gl(GetString, GL_SHADING_LANGUAGE_VERSION);
	if (GL_POP_ERROR() != GL_NO_ERROR) {
		WARNING(OPENGL, "Doesn't support glsl\n");
		GL_glsl_version = NULL;
	} else {
		GL_glsl_version = xstrdup(tmp);

		err = sscanf(GL_glsl_version, "%d.%d", &GLSL_major_version, &GLSL_minor_version);
		assert(err == 2);
		assert(GLSL_major_version > 0);
		assert(GLSL_minor_version > 0);
		GLSL_full_version = MKVER(GLSL_major_version, GLSL_minor_version);
	}

	VERBOSE(OPENGL, "OpenGL engine information:\n");
	VERBOSE(OPENGL, "\tvendor: %s\n", GL_vendor);
	VERBOSE(OPENGL, "\trenderer: %s\n", GL_renderer);
	VERBOSE(OPENGL, "\tversion: %s\n", GL_version);
	VERBOSE(OPENGL, "\tglsl version: %s\n", GL_glsl_version);

	int x;
	gl(GetIntegerv, GL_SAMPLES, &x);
	VERBOSE(OPENGL, "\tSamples : %d\n", x);
	gl(GetIntegerv, GL_SAMPLE_BUFFERS, &x);
	VERBOSE(OPENGL, "\tSample buffers : %d\n", x);
	if (x > 0)
		gl(Enable, GL_MULTISAMPLE);
	if (GL_POP_ERROR())
		WARNING(OPENGL, "platform does not support multisample\n");

	gl(GetIntegerv, GL_MAX_TEXTURE_SIZE, &GL_max_texture_size);
	DEBUG(OPENGL, "system max texture size: %d\n", GL_max_texture_size);
	int conf_mts = conf_get_int("video.opengl.texture.maxsize", 0);
	if (conf_mts != 0) {
		conf_mts = pow2roundup(conf_mts);
		if (conf_mts < GL_max_texture_size)
			GL_max_texture_size = conf_mts;
	}
	DEBUG(OPENGL, "max texture size is set to %d\n", GL_max_texture_size);

	gl(GetIntegerv, GL_MAX_VERTEX_ATTRIBS, &GL_max_vertex_attribs);
	DEBUG(OPENGL, "max vertex attributes is set to %d\n", GL_max_vertex_attribs);

	build_extensions();
	assert(GL_extensions_dict != NULL);
	GL_POP_ERROR();

#define verbose_feature(name, exp) do {\
	if (exp)	\
		DEBUG(OPENGL, name " is enabled\n");	\
	else		\
		DEBUG(OPENGL, name " is disabled\n");	\
	} while(0)

	GL_texture_NPOT = check_extension("video.opengl.texture.enableNPOT",
			"GL_ARB_texture_non_power_of_two",
			NULL);
	verbose_feature("NPOT texture", GL_texture_NPOT);

	GL_texture_RECT = check_extension("video.opengl.texture.enableRECT",
			"GL_ARB_texture_rectangle",
			"GL_EXT_texture_rectangle",
			"GL_NV_texture_rectangle",
			NULL);
	verbose_feature("RECT texture", GL_texture_RECT);

	GL_texture_COMPRESSION = check_extension("video.opengl.texture.enableCOMPRESSION",
			"GL_ARB_texture_compression",
			NULL);
	verbose_feature("texture compression", GL_texture_COMPRESSION);

	GL_vertex_buffer_object = check_extension("video.opengl.enableVBO",
			"GL_ARB_vertex_buffer_object",
			NULL);
	GL_pixel_buffer_object = check_extension("video.opengl.enablePBO",
			"GL_ARB_pixel_buffer_object",
			NULL);
	GL_vertex_array_object = check_extension("video.opengl.enableVAO",
			"GL_ARB_vertex_array_object",
			NULL);
#undef verbose_feature
}
Example #9
0
Socket platform_new_connection(SockAddr addr,
                               const char *hostname,
                               int port,
                               int privport,
                               int oobinline,
                               int nodelay,
                               int keepalive,
                               Plug plug,
                               Conf *conf)
{
  char *cmd;
  HANDLE us_to_cmd, cmd_from_us;
  HANDLE us_from_cmd, cmd_to_us;
  HANDLE us_from_cmd_err, cmd_err_to_us;
  SECURITY_ATTRIBUTES sa;
  STARTUPINFO si;
  PROCESS_INFORMATION pi;

  if (conf_get_int(conf, CONF_proxy_type) != PROXY_CMD)
    return NULL;

  cmd = format_telnet_command(addr, port, conf);

  /* We are responsible for this and don't need it any more */
  sk_addr_free(addr);

  {
    char *msg = dupprintf("Starting local proxy command: %s", cmd);
    plug_log(plug, 2, NULL, 0, msg, 0);
    sfree(msg);
  }

  /*
   * Create the pipes to the proxy command, and spawn the proxy
   * command process.
   */
  sa.nLength = sizeof(sa);
  sa.lpSecurityDescriptor = NULL; /* default */
  sa.bInheritHandle = TRUE;
  if (!CreatePipe(&us_from_cmd, &cmd_to_us, &sa, 0)) {
    Socket ret =
        new_error_socket("Unable to create pipes for proxy command", plug);
    sfree(cmd);
    return ret;
  }

  if (!CreatePipe(&cmd_from_us, &us_to_cmd, &sa, 0)) {
    Socket ret =
        new_error_socket("Unable to create pipes for proxy command", plug);
    sfree(cmd);
    CloseHandle(us_from_cmd);
    CloseHandle(cmd_to_us);
    return ret;
  }

  if (flags & FLAG_STDERR) {
    /* If we have a sensible stderr, the proxy command can send
     * its own standard error there, so we won't interfere. */
    us_from_cmd_err = cmd_err_to_us = NULL;
  } else {
    /* If we don't have a sensible stderr, we should catch the
     * proxy command's standard error to put in our event log. */
    if (!CreatePipe(&us_from_cmd_err, &cmd_err_to_us, &sa, 0)) {
      Socket ret =
          new_error_socket("Unable to create pipes for proxy command", plug);
      sfree(cmd);
      CloseHandle(us_from_cmd);
      CloseHandle(cmd_to_us);
      CloseHandle(us_to_cmd);
      CloseHandle(cmd_from_us);
      return ret;
    }
  }

  SetHandleInformation(us_to_cmd, HANDLE_FLAG_INHERIT, 0);
  SetHandleInformation(us_from_cmd, HANDLE_FLAG_INHERIT, 0);
  if (us_from_cmd_err != NULL)
    SetHandleInformation(us_from_cmd_err, HANDLE_FLAG_INHERIT, 0);

  si.cb = sizeof(si);
  si.lpReserved = NULL;
  si.lpDesktop = NULL;
  si.lpTitle = NULL;
  si.dwFlags = STARTF_USESTDHANDLES;
  si.cbReserved2 = 0;
  si.lpReserved2 = NULL;
  si.hStdInput = cmd_from_us;
  si.hStdOutput = cmd_to_us;
  si.hStdError = cmd_err_to_us;
  CreateProcess(NULL,
                cmd,
                NULL,
                NULL,
                TRUE,
                CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS,
                NULL,
                NULL,
                &si,
                &pi);
  CloseHandle(pi.hProcess);
  CloseHandle(pi.hThread);

  sfree(cmd);

  CloseHandle(cmd_from_us);
  CloseHandle(cmd_to_us);

  if (cmd_err_to_us != NULL)
    CloseHandle(cmd_err_to_us);

  return make_handle_socket(
      us_to_cmd, us_from_cmd, us_from_cmd_err, plug, FALSE);
}
Example #10
0
void server_init( char* conf_file_name, int map_szx, int map_szy, int tdepth, int speed_min, int speed_max,
					int apple_map_ratio, int apple_pl_ratio, int wall_map_ratio, int wall_pl_ratio, char* balname )
{
	int i;

	rand_seed = (unsigned int) time( NULL );
	srand( (unsigned int) time( NULL ) );

	conf_t* c = conf_create();	assert(c);
	conf_parse_file( c, conf_file_name );

	/* server */
	sv.port = conf_get_int( c, "server.port" );
	//sv.num_threads		= conf_get_int( c, "server.number_of_threads" );
	sv.update_interval = conf_get_int( c, "server.update_interval" );
	sv.stats_interval = conf_get_int( c, "server.stats_interval" );

	assert( sv.port > 1023 );
	assert( sv.num_threads > 0 && sv.num_threads <= MAX_THREADS );
	assert( sv.update_interval > 0 );
	assert( sv.stats_interval > 0 );

	/* quests */
	sv.quest_between = conf_get_int( c, "server.quest_between" );
	sv.quest_length = conf_get_int( c, "server.quest_length" );

	assert( sv.quest_between > 0 && sv.quest_length > 0 );
	assert( sv.quest_between > sv.update_interval && sv.quest_length > sv.update_interval );

	/* initialize clients array */
	sv.n_clients = 0;
	sv.clients = new tm_p_tm_sv_client_t[MAX_ENTITIES];
	assert( sv.clients );

	/* initialize world */
	server_traces_init();
	actions_init( c );
	server_init_multiple_actions();

	entity_types_init( c );
	// override the speed settings read from the config file
	entity_types[ ET_PLAYER ]->attr_types[ PL_SPEED ].min = speed_min;
	entity_types[ ET_PLAYER ]->attr_types[ PL_SPEED ].max = speed_max;
	// override the ratio settings read from the config file
	entity_types[ ET_APPLE ]->ratio    = apple_map_ratio;
	entity_types[ ET_APPLE ]->pl_ratio = apple_pl_ratio;
	entity_types[ ET_WALL ]->ratio    = wall_map_ratio;
	entity_types[ ET_WALL ]->pl_ratio = wall_pl_ratio;

	tm_worldmap_init( c, map_szx, map_szy, tdepth );
	server_init_quests();

	tm_worldmap_generate();
	tm_worldmap_is_valid();
/*
        //burceam: if heuristic1 is turned on, allocate structures for feedback/info
        sv.h1_dbg_num_ent = NULL;
        sv.h1_dbg_num_set = NULL;
        //temporarily turned it always on, for potential study; 
        //if (sv.heuristic1 != 0) 
        {
           sv.h1_dbg_num_ent = (int *) malloc (sv.wl_cycles * sizeof (int));
           sv.h1_dbg_num_set = (int *) malloc (sv.wl_cycles * sizeof (int));
           assert ((sv.h1_dbg_num_ent != NULL) && (sv.h1_dbg_num_set != NULL));
           int i;
           for (i = 0; i < sv.wl_cycles; i++) {
              sv.h1_dbg_num_ent [i] = 0;
              sv.h1_dbg_num_set [i] = 0;
           }
        }
        
        //burceam: for heuristic 2, hopefully temporary
        //note that this may need to be resized at some point: new players may join,
        //and existing players can drop out.
        //change_grain_to_entity_for_h3 is obviously meant to be used by heuristic h3.
        {
           sv.change_grain_to_entity = (unsigned char *) malloc (sv.wl_client_count * sizeof (unsigned char));
           sv.change_grain_to_entity_for_h3 = (unsigned char *) malloc (sv.wl_client_count * sizeof (unsigned char));
           int i;
           for (i = 0; i < sv.wl_client_count; i ++) {
              sv.change_grain_to_entity [i] = 0;
              sv.change_grain_to_entity_for_h3 [i] = 0;
           }
        }
        
        //burceam: this field is used for debugging
        sv.num_invocations_collision_detection [0] = 0;
        sv.num_invocations_collision_detection [1] = 0;
        sv.num_invocations_collision_detection [2] = 0;
        sv.num_invocations_collision_detection [3] = 0;
        
        //burceam: create and initialize the list of area node h_meta pointers.
        //this MUST be done after tm_worldmap_init(), where I think the area node tree is created
        //and initialized. We need the depth here.
        {
           int i, num_area_nodes = 1;
           //IMPORTANT: the _actual_ depth of the tree is tdepth+1 !! 
           //root is level "depth", and they keep building until level reaches 0, including for 0!
           //(nodes at level 0 are the leaves). So for depth=8 entered on cmd line, we really have 9 levels.
           num_area_nodes = 1 << (tm_wm.depth + 1);
           sv.hmeta_list = (ptr_t *) malloc (num_area_nodes * sizeof (ptr_t));
           for (i = 0; i < num_area_nodes; i++) 
              sv.hmeta_list [i] = NULL;
        }
*/
	/* initialize synthetic workload */
	server_generate_workload();
	tm_worldmap_is_valid();

	loadb_init( balname );

	/* initialize syncronization & server threads */
	barrier_init( &sv.barrier, sv.num_threads );
	server_stats_init();
	sv.done = 0;

	svts = (server_thread_t*) malloc( sv.num_threads * sizeof(server_thread_t) );
	for( i = 0; i < sv.num_threads; ++i )		server_thread_init( &svts[i], i );

	log_info( "[I] Server init done.\n" );
}
Example #11
0
void *thr_socket_end_engine(void *p)
{
	struct l7_worker_arg *arg = p;
	cJSON *conf = arg->conf;
	int pipe_fd = work_pipe[arg->index];
	int n, i, j, ret, val;
	struct epoll_event evarr[EVENT_BATCH_SIZE], ev;
	struct sockaddr_in client_addr;
	socklen_t client_addr_len;
	int epollwait_timeout;
	int client_sd;
	struct socket_end_st *se, *head;

	pthread_cleanup_push(socket_end_cleanup, NULL);

	/* SOCKET_END_MAX is restricted in range [CONCURRENT_UNDERLIMIT, CONCURRENT_UPPERLIMIT].
	 * CONCURRENT_UNDERLIMIT and CONCURRENT_UPPERLIMIT is defined in socket_end.h
	 */
	SOCKET_END_MAX = conf_get_int("ConcurrentMax", conf);
	if (SOCKET_END_MAX<CONCURRENT_UNDERLIMIT) {
		SOCKET_END_MAX = CONCURRENT_UNDERLIMIT;
	} else if (SOCKET_END_MAX > CONCURRENT_UPPERLIMIT) {
		SOCKET_END_MAX = CONCURRENT_UPPERLIMIT;
	}
	socket_end_arr_max = SOCKET_END_MAX/nr_threads+1;
	socket_end_arr = calloc(1, sizeof(*socket_end_arr)*socket_end_arr_max);
	if (socket_end_arr==NULL) {
		mylog(L_ERR, "Insufficent memory for socket_end_arr[].");
		goto quit;
	}

	timeout_index = olist_new(CONCURRENT_UPPERLIMIT, se_timeout_cmp);
	if (unlikely(timeout_index == NULL)) {
		mylog(L_ERR, "Init timeout index failed");
		goto quit;
	}

	http_xff = conf_get_bool("HttpXff", conf) ? 0 : 1;

	epollfd = epoll_create(EVENT_BATCH_SIZE);	// For old kernel compatible. 1 is OKZ too.
	if (unlikely(epollfd == -1)) {
		mylog(L_ERR, "Init epollfd failed");
		goto quit;
	}

	ev.events = EPOLLIN;
	ev.data.u32 = U32_SOCKET_CONNECT;
	ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, pipe_fd, &ev);
	if (unlikely(ret < 0)) {
		mylog(L_ERR, "Watch listen socket failed");
		goto quit;
	}

	client_addr_len = sizeof(client_addr);
	while (1) {
		now=systimestamp_ms();
		head = olist_peek_head(timeout_index);
		if (head) {
			epollwait_timeout = head->min_timeout_abs_ms - now;
			if (epollwait_timeout < 0) {
				epollwait_timeout = 0;
			}
		} else {
			epollwait_timeout = 500;
		}

		n=epoll_wait(epollfd, evarr, EVENT_BATCH_SIZE, epollwait_timeout);

		for (i=0; i<n; ++i) {
			if (evarr[i].data.u32 == U32_SOCKET_CONNECT) { /* accept is ready */
				evarr[i].data.ptr = NULL;
				mylog(L_DEBUG, "Socket end arr nr is %d", socket_end_arr_nr);
				while (1) {
					ret = read(pipe_fd, &client_sd, sizeof(int));
					if (ret < 0) {
						if (errno==EAGAIN) {
							break;
						} else {
							mylog(L_ERR, "get client sd from pipe error: %m");
							goto quit;
						}
					}
					if (ret == 0) {
						continue;
					}

					mylog(L_DEBUG, "Worker got a new fd: %d", client_sd);
					atomic_decrease(socket_in_pipe);

					if (likely((socket_end_arr_nr >= (socket_end_arr_max - 1)) && (socket_end_total_nr < SOCKET_END_MAX))) {
						mylog(L_ERR, "Thread process too many socket_ends, close");
						close(client_sd);
						break;
					} 

					if (unlikely(socket_end_total_nr >= SOCKET_END_MAX)) {
						mylog(L_ERR, "TOO many socket_ends! Ignored!");
						close(client_sd);
					} else {
						val = 1;
						if (setsockopt(client_sd, IPPROTO_TCP, TCP_CORK, &val, sizeof(val))< 0) {
							mylog(L_ERR, "Set client sd cork failed");
						}
						se = socket_end_new(client_sd);
						if (unlikely(se == NULL)) {
							mylog(L_ERR, "Create socket end failed");
							goto quit;
						}

						while (socket_end_arr[socket_end_arr_tail]!=NULL) {
							socket_end_arr_tail++;
							if (unlikely(socket_end_arr_tail>=socket_end_arr_max)) {
								socket_end_arr_tail=0;
								mylog(L_DEBUG, "Socket_end arr tail return to 0");
							}
						}
						socket_end_arr[socket_end_arr_tail] = se;
						socket_end_arr[socket_end_arr_tail]->id = socket_end_arr_tail;
						mylog(L_DEBUG, "Create socket end, se[%d]", se->id);

						socket_end_arr_nr++;
						mylog(L_DEBUG, "Socket end arr nr is %d", socket_end_arr_nr);
						atomic_increase(&socket_end_total_nr);
						mylog(L_DEBUG, "Socket end total nr is %d", socket_end_total_nr);
					}
				}
				break; /* break after while */
			}
		}

		for (i=0; i<n; ++i) {
			if (evarr[i].data.ptr == NULL) {
				continue;
			}
			/* evarr[] 排重 */
			for (j=i+1;j<n;++j) {
				if (evarr[i].data.ptr == evarr[j].data.ptr) {
					evarr[j].data.ptr = NULL;
				}
			}
			se = evarr[i].data.ptr;
			if (unlikely(socket_end_driver(se)==-EINVAL)) {
				mylog(L_DEBUG, "Remove entry engine %p, se[%d]", se, se->id);
				if (unlikely(olist_remove_entry_by_datap(timeout_index, se)!=0)) {
					/* should not be here */
					mylog(L_ERR, "Critical exception: socket end missed in epollfd, se[%d]", se->id);
					goto quit;
					//abort();
				}
				socket_end_arr[se->id]=NULL;
				socket_end_destroy(se);
				socket_end_arr_nr--;
				atomic_decrease(&socket_end_total_nr);
			}

		}

		now = systimestamp_ms();
		while (1) {
			se = olist_fetch_head(timeout_index);
			if (se == NULL) {
				//mylog(L_DEBUG, "timeout_index is empty.");
				break;
			} 
			if (se->min_timeout_abs_ms != 0 && se->min_timeout_abs_ms < now) {
				mylog(L_INFO, "Socket end is timed out, se[%d]", se->id);
				socket_end_process_timeout(se, now);
			} else {
				if (se->min_timeout_abs_ms != 0) {

					if (olist_add_entry(timeout_index, se)) {
						mylog(L_DEBUG, "Add entry engine %p failed, se[%d]", se, se->id);
					} else {
						mylog(L_DEBUG, "Add entry engine %p success, se[%d]", se, se->id);
					}
					break;
				}
			}
		}
	}

quit:

	mylog(L_DEBUG, "Quit thr engine");

	pthread_cleanup_pop(1);

	if (timeout_index) {
		olist_destroy(timeout_index);
		timeout_index = NULL;
	}

	if (socket_end_arr) {
		free(socket_end_arr);
	}

	if (likely(epollfd > 0)) {
		close(epollfd);
		epollfd = -1;
	}

	pthread_exit(NULL);
}
Example #12
0
int
main (int argc, char *argv[]) {
    int portable = 0;
#if STATICLINK
    int staticlink = 1;
#else
    int staticlink = 0;
#endif
#if PORTABLE
    portable = 1;
    if (!realpath (argv[0], dbinstalldir)) {
        strcpy (dbinstalldir, argv[0]);
    }
    char *e = strrchr (dbinstalldir, '/');
    if (e) {
        *e = 0;
    }
    else {
        fprintf (stderr, "couldn't determine install folder from path %s\n", argv[0]);
        exit (-1);
    }
#else
    if (!realpath (argv[0], dbinstalldir)) {
        strcpy (dbinstalldir, argv[0]);
    }
    char *e = strrchr (dbinstalldir, '/');
    if (e) {
        *e = 0;
        struct stat st;
        char checkpath[PATH_MAX];
        snprintf (checkpath, sizeof (checkpath), "%s/.ddb_portable", dbinstalldir);
        if (!stat (checkpath, &st)) {
            if (S_ISREG (st.st_mode)) {
                portable = 1;
            }
        }
    }
    if (!portable) {
        strcpy (dbinstalldir, PREFIX);
    }
#endif

#ifdef __GLIBC__
    signal (SIGSEGV, sigsegv_handler);
#endif
    setlocale (LC_ALL, "");
    setlocale (LC_NUMERIC, "C");
#ifdef ENABLE_NLS
//    fprintf (stderr, "enabling gettext support: package=" PACKAGE ", dir=" LOCALEDIR "...\n");
    if (portable) {
        char localedir[PATH_MAX];
        snprintf (localedir, sizeof (localedir), "%s/locale", dbinstalldir);
        bindtextdomain (PACKAGE, localedir);
    }
    else {
        bindtextdomain (PACKAGE, LOCALEDIR);
    }
	bind_textdomain_codeset (PACKAGE, "UTF-8");
	textdomain (PACKAGE);
#endif

    fprintf (stderr, "starting deadbeef " VERSION "%s%s\n", staticlink ? " [static]" : "", portable ? " [portable]" : "");
    srand (time (NULL));
#ifdef __linux__
    prctl (PR_SET_NAME, "deadbeef-main", 0, 0, 0, 0);
#endif

#if PORTABLE_FULL
    if (snprintf (confdir, sizeof (confdir), "%s/config", dbinstalldir) > sizeof (confdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }

    strcpy (dbconfdir, confdir);
#else
    char *homedir = getenv ("HOME");
    if (!homedir) {
        fprintf (stderr, "unable to find home directory. stopping.\n");
        return -1;
    }

    char *xdg_conf_dir = getenv ("XDG_CONFIG_HOME");
    if (xdg_conf_dir) {
        if (snprintf (confdir, sizeof (confdir), "%s", xdg_conf_dir) > sizeof (confdir)) {
            fprintf (stderr, "fatal: XDG_CONFIG_HOME value is too long: %s\n", xdg_conf_dir);
            return -1;
        }
    }
    else {
        if (snprintf (confdir, sizeof (confdir), "%s/.config", homedir) > sizeof (confdir)) {
            fprintf (stderr, "fatal: HOME value is too long: %s\n", homedir);
            return -1;
        }
    }
    if (snprintf (dbconfdir, sizeof (dbconfdir), "%s/deadbeef", confdir) > sizeof (dbconfdir)) {
        fprintf (stderr, "fatal: out of memory while configuring\n");
        return -1;
    }
    mkdir (confdir, 0755);
#endif


    if (portable) {
        if (snprintf (dbdocdir, sizeof (dbdocdir), "%s/doc", dbinstalldir) > sizeof (dbdocdir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
#ifdef HAVE_COCOAUI
        char respath[PATH_MAX];
        cocoautil_get_resources_path (respath, sizeof (respath));
        if (snprintf (dbplugindir, sizeof (dbplugindir), "%s", respath) > sizeof (dbplugindir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
#else
        if (snprintf (dbplugindir, sizeof (dbplugindir), "%s/plugins", dbinstalldir) > sizeof (dbplugindir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
#endif
        if (snprintf (dbpixmapdir, sizeof (dbpixmapdir), "%s/pixmaps", dbinstalldir) > sizeof (dbpixmapdir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
        mkdir (dbplugindir, 0755);
    }
    else {
        if (snprintf (dbdocdir, sizeof (dbdocdir), "%s", DOCDIR) > sizeof (dbdocdir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
        if (snprintf (dbplugindir, sizeof (dbplugindir), "%s/deadbeef", LIBDIR) > sizeof (dbplugindir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
        if (snprintf (dbpixmapdir, sizeof (dbpixmapdir), "%s/share/deadbeef/pixmaps", PREFIX) > sizeof (dbpixmapdir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
    }

    for (int i = 1; i < argc; i++) {
        // help, version and nowplaying are executed with any filter
        if (!strcmp (argv[i], "--help") || !strcmp (argv[i], "-h")) {
            print_help ();
            return 0;
        }
        else if (!strcmp (argv[i], "--version")) {
            fprintf (stderr, "DeaDBeeF " VERSION " Copyright © 2009-2013 Alexey Yakovenko\n");
            return 0;
        }
        else if (!strcmp (argv[i], "--gui")) {
            if (i == argc-1) {
                break;
            }
            i++;
            strncpy (use_gui_plugin, argv[i], sizeof(use_gui_plugin) - 1);
            use_gui_plugin[sizeof(use_gui_plugin) - 1] = 0;
        }
    }

    trace ("installdir: %s\n", dbinstalldir);
    trace ("confdir: %s\n", confdir);
    trace ("docdir: %s\n", dbdocdir);
    trace ("plugindir: %s\n", dbplugindir);
    trace ("pixmapdir: %s\n", dbpixmapdir);

    mkdir (dbconfdir, 0755);

    int size = 0;
    char *cmdline = prepare_command_line (argc, argv, &size);

    // try to connect to remote player
    int s, len;
    struct sockaddr_un remote;

    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    memset (&remote, 0, sizeof (remote));
    remote.sun_family = AF_UNIX;
#if USE_ABSTRACT_SOCKET_NAME
    memcpy (remote.sun_path, server_id, sizeof (server_id));
    len = offsetof(struct sockaddr_un, sun_path) + sizeof (server_id)-1;
#else
    char *socketdirenv = getenv ("DDB_SOCKET_DIR");
    snprintf (remote.sun_path, sizeof (remote.sun_path), "%s/socket", socketdirenv ? socketdirenv : dbconfdir);
    len = offsetof(struct sockaddr_un, sun_path) + strlen (remote.sun_path);
#endif
    if (connect(s, (struct sockaddr *)&remote, len) == 0) {
        // pass args to remote and exit
        if (send(s, cmdline, size, 0) == -1) {
            perror ("send");
            exit (-1);
        }
        // end of message
        shutdown(s, SHUT_WR);

        int sz = -1;
        char *out = read_entire_message(s, &sz);
        if (sz == -1) {
            fprintf (stderr, "failed to pass args to remote!\n");
            exit (-1);
        }
        else {
            // check if that's nowplaying response
            const char np[] = "nowplaying ";
            const char err[] = "error ";
            if (!strncmp (out, np, sizeof (np)-1)) {
                const char *prn = &out[sizeof (np)-1];
                fwrite (prn, 1, strlen (prn), stdout);
            }
            else if (!strncmp (out, err, sizeof (err)-1)) {
                const char *prn = &out[sizeof (err)-1];
                fwrite (prn, 1, strlen (prn), stderr);
            }
            else if (sz > 0 && out[0]) {
                fprintf (stderr, "%s\n", out);
            }
        }
        if (out) {
            free (out);
        }
        close (s);
        exit (0);
    }
//    else {
//        perror ("INFO: failed to connect to existing session:");
//    }
    close(s);

    // become a server
    if (server_start () < 0) {
        exit (-1);
    }

    // hack: report nowplaying
    if (!strcmp (cmdline, "--nowplaying")) {
        char nothing[] = "nothing";
        fwrite (nothing, 1, sizeof (nothing)-1, stdout);
        return 0;
    }

    pl_init ();
    conf_init ();
    conf_load (); // required by some plugins at startup

    if (use_gui_plugin[0]) {
        conf_set_str ("gui_plugin", use_gui_plugin);
    }

    conf_set_str ("deadbeef_version", VERSION);

    volume_set_db (conf_get_float ("playback.volume", 0)); // volume need to be initialized before plugins start

    messagepump_init (); // required to push messages while handling commandline
    if (plug_load_all ()) { // required to add files to playlist from commandline
        exit (-1);
    }
    pl_load_all ();
    plt_set_curr_idx (conf_get_int ("playlist.current", 0));

    // execute server commands in local context
    int noloadpl = 0;
    if (argc > 1) {
        int res = server_exec_command_line (cmdline, size, NULL, 0);
        // some of the server commands ran on 1st instance should terminate it
        if (res == 2) {
            noloadpl = 1;
        }
        else if (res > 0) {
            exit (0);
        }
        else if (res < 0) {
            exit (-1);
        }
    }

    free (cmdline);

#if 0
    signal (SIGTERM, sigterm_handler);
    atexit (atexit_handler); // helps to save in simple cases
#endif

    streamer_init ();

    plug_connect_all ();
    messagepump_push (DB_EV_PLUGINSLOADED, 0, 0, 0);

    if (!noloadpl) {
        restore_resume_state ();
    }

    server_tid = thread_start (server_loop, NULL);

    mainloop_tid = thread_start (mainloop_thread, NULL);

    DB_plugin_t *gui = plug_get_gui ();
    if (gui) {
        gui->start ();
    }

    fprintf (stderr, "gui plugin has quit; waiting for mainloop thread to finish\n");
    thread_join (mainloop_tid);

    // terminate server and wait for completion
    if (server_tid) {
        server_terminate = 1;
        thread_join (server_tid);
        server_tid = 0;
    }

    // save config
    pl_save_all ();
    conf_save ();

    // delete legacy session file
    {
        char sessfile[1024]; // $HOME/.config/deadbeef/session
        if (snprintf (sessfile, sizeof (sessfile), "%s/deadbeef/session", confdir) < sizeof (sessfile)) {
            unlink (sessfile);
        }
    }

    // stop receiving messages from outside
    server_close ();

    // plugins might still hold references to playitems,
    // and query configuration in background
    // so unload everything 1st before final cleanup
    plug_disconnect_all ();
    plug_unload_all ();

    // at this point we can simply do exit(0), but let's clean up for debugging
    pl_free (); // may access conf_*
    conf_free ();

    fprintf (stderr, "messagepump_free\n");
    messagepump_free ();
    fprintf (stderr, "plug_cleanup\n");
    plug_cleanup ();

    fprintf (stderr, "hej-hej!\n");

    return 0;
}
Example #13
0
// this function executes server-side commands only
// must be called only from within server
// -1 error, program must exit with error code -1
//  0 proceed normally as nothing happened
//  1 no error, but program must exit with error code 0
//  2 don't load playlist on startup
//  when executed in remote server -- error code will be ignored
int
server_exec_command_line (const char *cmdline, int len, char *sendback, int sbsize) {
    if (sendback) {
        sendback[0] = 0;
    }
    const uint8_t *parg = (const uint8_t *)cmdline;
    const uint8_t *pend = cmdline + len;
    int queue = 0;
    while (parg < pend) {
        const char *parg_c = parg;
        if (strlen (parg) >= 2 && parg[0] == '-' && parg[1] != '-') {
            parg += strlen (parg);
            parg++;
            return 0; // running under osx debugger?
        }
        else if (!strcmp (parg, "--nowplaying")) {
            parg += strlen (parg);
            parg++;
            if (parg >= pend) {
                if (sendback) {
                    snprintf (sendback, sbsize, "error --nowplaying expects format argument\n");
                    return 0;
                }
                else {
                    fprintf (stderr, "--nowplaying expects format argument\n");
                    return -1;
                }
            }
            if (sendback) {
                playItem_t *curr = streamer_get_playing_track ();
                DB_fileinfo_t *dec = streamer_get_current_fileinfo ();
                if (curr && dec) {
                    const char np[] = "nowplaying ";
                    memcpy (sendback, np, sizeof (np)-1);
                    pl_format_title (curr, -1, sendback+sizeof(np)-1, sbsize-sizeof(np)+1, -1, parg);
                }
                else {
                    strcpy (sendback, "nowplaying nothing");
                }
                if (curr) {
                    pl_item_unref (curr);
                }
            }
            else {
                char out[2048];
                playItem_t *curr = streamer_get_playing_track ();
                DB_fileinfo_t *dec = streamer_get_current_fileinfo();
                if (curr && dec) {
                    pl_format_title (curr, -1, out, sizeof (out), -1, parg);
                }
                else {
                    strcpy (out, "nothing");
                }
                if (curr) {
                    pl_item_unref (curr);
                }
                fwrite (out, 1, strlen (out), stdout);
                return 1; // exit
            }
        }
        else if (!strcmp (parg, "--next")) {
            messagepump_push (DB_EV_NEXT, 0, 0, 0);
            return 0;
        }
        else if (!strcmp (parg, "--prev")) {
            messagepump_push (DB_EV_PREV, 0, 0, 0);
            return 0;
        }
        else if (!strcmp (parg, "--play")) {
            messagepump_push (DB_EV_PLAY_CURRENT, 0, 0, 0);
            return 0;
        }
        else if (!strcmp (parg, "--stop")) {
            messagepump_push (DB_EV_STOP, 0, 0, 0);
            return 0;
        }
        else if (!strcmp (parg, "--pause")) {
            messagepump_push (DB_EV_PAUSE, 0, 0, 0);
            return 0;
        }
        else if (!strcmp (parg, "--toggle-pause")) {
            messagepump_push (DB_EV_TOGGLE_PAUSE, 0, 0, 0);
            return 0;
        }
        else if (!strcmp (parg, "--play-pause")) {
            int state = deadbeef->get_output ()->state ();
            if (state == OUTPUT_STATE_PLAYING) {
                deadbeef->sendmessage (DB_EV_PAUSE, 0, 0, 0);
            }
            else {
                deadbeef->sendmessage (DB_EV_PLAY_CURRENT, 0, 0, 0);
            }
            return 0;
        }
        else if (!strcmp (parg, "--random")) {
            messagepump_push (DB_EV_PLAY_RANDOM, 0, 0, 0);
            return 0;
        }
        else if (!strcmp (parg, "--queue")) {
            queue = 1;
        }
        else if (!strcmp (parg, "--quit")) {
            messagepump_push (DB_EV_TERMINATE, 0, 0, 0);
        }
        else if (!strcmp (parg, "--sm-client-id")) {
            parg += strlen (parg);
            parg++;
            if (parg < pend) {
                parg += strlen (parg);
                parg++;
            }
            continue;
        }
        else if (!strcmp (parg, "--gui")) {
            // need to skip --gui here, it is handled in the client cmdline
            parg += strlen (parg);
            parg++;
            if (parg >= pend) {
                break;
            }
            parg += strlen (parg);
            parg++;
            continue;
        }
        else if (parg[0] != '-') {
            break; // unknown option is filename
        }
        parg += strlen (parg);
        parg++;
    }
    if (parg < pend) {
        if (conf_get_int ("cli_add_to_specific_playlist", 1)) {
            char str[200];
            conf_get_str ("cli_add_playlist_name", "Default", str, sizeof (str));
            int idx = plt_find (str);
            if (idx < 0) {
                idx = plt_add (plt_get_count (), str);
            }
            if (idx >= 0) {
                plt_set_curr_idx (idx);
            }
        }
        playlist_t *curr_plt = plt_get_curr ();
        if (plt_add_files_begin (curr_plt, 0) != 0) {
            plt_unref (curr_plt);
            snprintf (sendback, sbsize, "it's not allowed to add files to playlist right now, because another file adding operation is in progress. please try again later.");
            return 0;
        }
        // add files
        if (!queue) {
            plt_clear (curr_plt);
            messagepump_push (DB_EV_PLAYLISTCHANGED, 0, 0, 0);
            plt_reset_cursor (curr_plt);
        }
        while (parg < pend) {
            char resolved[PATH_MAX];
            const char *pname;
            if (realpath (parg, resolved)) {
                pname = resolved;
            }
            else {
                pname = parg;
            }
            if (deadbeef->plt_add_dir2 (0, (ddb_playlist_t*)curr_plt, pname, NULL, NULL) < 0) {
                if (deadbeef->plt_add_file2 (0, (ddb_playlist_t*)curr_plt, pname, NULL, NULL) < 0) {
                    int ab = 0;
                    playItem_t *it = plt_load2 (0, curr_plt, NULL, pname, &ab, NULL, NULL);
                    if (!it) {
                        fprintf (stderr, "failed to add file or folder %s\n", pname);
                    }
                }
            }
            parg += strlen (parg);
            parg++;
        }
        messagepump_push (DB_EV_PLAYLIST_REFRESH, 0, 0, 0);
        plt_add_files_end (curr_plt, 0);
        plt_unref (curr_plt);
        if (!queue) {
            messagepump_push (DB_EV_PLAY_NUM, 0, 0, 0);
            return 2; // don't reload playlist at startup
        }
    }
    return 0;
}
Example #14
0
static const char *
cygterm_init(void *frontend_handle, void **backend_handle,
             Conf *conf,
             char *unused_host, int unused_port,
             char **realhost, int nodelay, int keepalive)
{
	/* XXX: I'm not sure if it is OK to overload Plug like this.
	 * cygterm_accepting should only be used for the listening socket
	 * (local->a) while the cygterm_closing, cygterm_receive, and cygterm_sent
	 * should be used only for the actual connection (local->s).
	 */
	static const struct plug_function_table fn_table = {
		cygterm_log,
		cygterm_closing,
		cygterm_receive,
		cygterm_sent,
		cygterm_accepting
	};
	Local local;
	const char *command;
	char cmdline[2 * MAX_PATH];
	int cport;
	const char *err;
	int cmdlinelen;

	cygterm_debug("top");

	local = snew(struct cygterm_backend_data);
	local->fn = &fn_table;
	local->a = NULL;
	local->s = NULL;
	local->conf = conf;
	local->editing = 0;
	local->echoing = 0;
	local->exitcode = 0;
	*backend_handle = local;

	local->frontend = frontend_handle;

	/* set up listen socket for communication with child */
	cygterm_debug("setupCygTerm");

	/* let sk use INADDR_LOOPBACK and let WinSock choose a port */
	local->a = sk_newlistener(0, 0, (Plug)local, 1, ADDRTYPE_IPV4);
	if ((err = sk_socket_error(local->a)) != NULL)
		goto fail_free;

	/* now, get the port that WinSock chose */
	/* XXX: Is there another function in PuTTY to do this? */
	cygterm_debug("getting port");
	cport = sk_getport(local->a);
	if (cport == -1) {
		err = "Failed to get port number for cthelper";
		goto fail_close;
	}

	if (strchr(conf_get_str(local->conf, CONF_termtype), ' ')) {
		err = "term type contains spaces";
		goto fail_close;
	}

	/*  Build cthelper command line */
	if(conf_get_int(conf, CONF_cygterm64)) {
		cmdlinelen = sprintf(cmdline, CTHELPER64" %u %s ", cport, conf_get_str(local->conf, CONF_termtype));
	}
	else {
		cmdlinelen = sprintf(cmdline, CTHELPER" %u %s ", cport, conf_get_str(local->conf, CONF_termtype));
	}
	cmdlinelen += makeAttributes(cmdline + cmdlinelen, conf);

	command = conf_get_str(conf, CONF_cygcmd);
	cygterm_debug("command is :%s:", command);
	/*  A command of  "."  or  "-"  tells us to pass no command arguments to
	 *  cthelper which will then run the user's shell under Cygwin.  */
	if ((command[0]=='-'||command[0]=='.') && command[1]=='\0')
		;
	else if (cmdlinelen + strlen(command) + 2 > sizeof cmdline) {
		err = "command is too long";
		goto fail_close;
	}
	else {
		cmdlinelen += sprintf(cmdline + cmdlinelen, " %s", command);
	}

	/* Add the Cygwin /bin path to the PATH. */
	if (conf_get_int(conf, CONF_cygautopath)) {
		char *cygwinBinPath = getCygwinBin(conf_get_int(conf, CONF_cygterm64));
		if (!cygwinBinPath) {
			/* we'll try anyway */
			cygterm_debug("cygwin bin directory not found");
		}
		else {
			cygterm_debug("found cygwin directory: %s", cygwinBinPath);
			appendPath(cygwinBinPath);
			sfree(cygwinBinPath);
		}
	}

	cygterm_debug("starting cthelper: %s", cmdline);
	if ((err = spawnChild(cmdline, &local->pi, &local->ctl)))
		goto fail_close;

	/*  This should be set to the local hostname, Apparently, realhost is used
	 *  only to set the window title.
	 */
	strcpy(*realhost = smalloc(sizeof CYGTERM_NAME), CYGTERM_NAME);
	cygterm_debug("OK");
	return 0;

fail_close:
	sk_close(local->a);
fail_free:
	sfree(local);
	return err;
}
Example #15
0
void load_open_settings(void *sesskey, Conf *conf)
{
    int i;
    char *prot;

    conf_set_int(conf, CONF_ssh_subsys, 0);   /* FIXME: load this properly */
    conf_set_str(conf, CONF_remote_cmd, "");
    conf_set_str(conf, CONF_remote_cmd2, "");
    conf_set_str(conf, CONF_ssh_nc_host, "");

    gpps(sesskey, "HostName", "", conf, CONF_host);
    gppfile(sesskey, "LogFileName", conf, CONF_logfilename);
    gppi(sesskey, "LogType", 0, conf, CONF_logtype);
    gppi(sesskey, "LogFileClash", LGXF_ASK, conf, CONF_logxfovr);
    gppi(sesskey, "LogFlush", 1, conf, CONF_logflush);
    gppi(sesskey, "SSHLogOmitPasswords", 1, conf, CONF_logomitpass);
    gppi(sesskey, "SSHLogOmitData", 0, conf, CONF_logomitdata);

    prot = gpps_raw(sesskey, "Protocol", "default");
    conf_set_int(conf, CONF_protocol, default_protocol);
    conf_set_int(conf, CONF_port, default_port);
    {
	const Backend *b = backend_from_name(prot);
	if (b) {
	    conf_set_int(conf, CONF_protocol, b->protocol);
	    gppi(sesskey, "PortNumber", default_port, conf, CONF_port);
	}
    }
    sfree(prot);

    /* Address family selection */
    gppi(sesskey, "AddressFamily", ADDRTYPE_UNSPEC, conf, CONF_addressfamily);

    /* The CloseOnExit numbers are arranged in a different order from
     * the standard FORCE_ON / FORCE_OFF / AUTO. */
    i = gppi_raw(sesskey, "CloseOnExit", 1); conf_set_int(conf, CONF_close_on_exit, (i+1)%3);
    gppi(sesskey, "WarnOnClose", 1, conf, CONF_warn_on_close);
    {
	/* This is two values for backward compatibility with 0.50/0.51 */
	int pingmin, pingsec;
	pingmin = gppi_raw(sesskey, "PingInterval", 0);
	pingsec = gppi_raw(sesskey, "PingIntervalSecs", 0);
	conf_set_int(conf, CONF_ping_interval, pingmin * 60 + pingsec);
    }
    gppi(sesskey, "TCPNoDelay", 1, conf, CONF_tcp_nodelay);
    gppi(sesskey, "TCPKeepalives", 0, conf, CONF_tcp_keepalives);
    gpps(sesskey, "TerminalType", "xterm", conf, CONF_termtype);
    gpps(sesskey, "TerminalSpeed", "38400,38400", conf, CONF_termspeed);
    if (!gppmap(sesskey, "TerminalModes", conf, CONF_ttymodes)) {
	/* This hardcodes a big set of defaults in any new saved
	 * sessions. Let's hope we don't change our mind. */
	for (i = 0; ttymodes[i]; i++)
	    conf_set_str_str(conf, CONF_ttymodes, ttymodes[i], "A");
    }

    /* proxy settings */
    gpps(sesskey, "ProxyExcludeList", "", conf, CONF_proxy_exclude_list);
    i = gppi_raw(sesskey, "ProxyDNS", 1); conf_set_int(conf, CONF_proxy_dns, (i+1)%3);
    gppi(sesskey, "ProxyLocalhost", 0, conf, CONF_even_proxy_localhost);
    gppi(sesskey, "ProxyMethod", -1, conf, CONF_proxy_type);
    if (conf_get_int(conf, CONF_proxy_type) == -1) {
        int i;
        i = gppi_raw(sesskey, "ProxyType", 0);
        if (i == 0)
            conf_set_int(conf, CONF_proxy_type, PROXY_NONE);
        else if (i == 1)
            conf_set_int(conf, CONF_proxy_type, PROXY_HTTP);
        else if (i == 3)
            conf_set_int(conf, CONF_proxy_type, PROXY_TELNET);
        else if (i == 4)
            conf_set_int(conf, CONF_proxy_type, PROXY_CMD);
        else {
            i = gppi_raw(sesskey, "ProxySOCKSVersion", 5);
            if (i == 5)
                conf_set_int(conf, CONF_proxy_type, PROXY_SOCKS5);
            else
                conf_set_int(conf, CONF_proxy_type, PROXY_SOCKS4);
        }
    }
    gpps(sesskey, "ProxyHost", "proxy", conf, CONF_proxy_host);
    gppi(sesskey, "ProxyPort", 80, conf, CONF_proxy_port);
    gpps(sesskey, "ProxyUsername", "", conf, CONF_proxy_username);
    gpps(sesskey, "ProxyPassword", "", conf, CONF_proxy_password);
    gpps(sesskey, "ProxyTelnetCommand", "connect %host %port\\n",
	 conf, CONF_proxy_telnet_command);
    gppmap(sesskey, "Environment", conf, CONF_environmt);
    gpps(sesskey, "UserName", "", conf, CONF_username);
    gppi(sesskey, "UserNameFromEnvironment", 0, conf, CONF_username_from_env);
    gpps(sesskey, "LocalUserName", "", conf, CONF_localusername);
    gppi(sesskey, "NoPTY", 0, conf, CONF_nopty);
    gppi(sesskey, "Compression", 0, conf, CONF_compression);
    gppi(sesskey, "TryAgent", 1, conf, CONF_tryagent);
    gppi(sesskey, "AgentFwd", 0, conf, CONF_agentfwd);
    gppi(sesskey, "ChangeUsername", 0, conf, CONF_change_username);
    gppi(sesskey, "GssapiFwd", 0, conf, CONF_gssapifwd);
    gprefs(sesskey, "Cipher", "\0",
	   ciphernames, CIPHER_MAX, conf, CONF_ssh_cipherlist);
    {
	/* Backward-compatibility: we used to have an option to
	 * disable gex under the "bugs" panel after one report of
	 * a server which offered it then choked, but we never got
	 * a server version string or any other reports. */
	char *default_kexes;
	i = 2 - gppi_raw(sesskey, "BugDHGEx2", 0);
	if (i == FORCE_ON)
	    default_kexes = "dh-group14-sha1,dh-group1-sha1,rsa,WARN,dh-gex-sha1";
	else
	    default_kexes = "dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN";
	gprefs(sesskey, "KEX", default_kexes,
	       kexnames, KEX_MAX, conf, CONF_ssh_kexlist);
    }
    gppi(sesskey, "RekeyTime", 60, conf, CONF_ssh_rekey_time);
    gpps(sesskey, "RekeyBytes", "1G", conf, CONF_ssh_rekey_data);
    /* SSH-2 only by default */
    gppi(sesskey, "SshProt", 3, conf, CONF_sshprot);
    gpps(sesskey, "LogHost", "", conf, CONF_loghost);
    gppi(sesskey, "SSH2DES", 0, conf, CONF_ssh2_des_cbc);
    gppi(sesskey, "SshNoAuth", 0, conf, CONF_ssh_no_userauth);
    gppi(sesskey, "SshBanner", 1, conf, CONF_ssh_show_banner);
    gppi(sesskey, "AuthTIS", 0, conf, CONF_try_tis_auth);
    gppi(sesskey, "AuthKI", 1, conf, CONF_try_ki_auth);
    gppi(sesskey, "AuthGSSAPI", 1, conf, CONF_try_gssapi_auth);
#ifndef NO_GSSAPI
    gprefs(sesskey, "GSSLibs", "\0",
	   gsslibkeywords, ngsslibs, conf, CONF_ssh_gsslist);
    gppfile(sesskey, "GSSCustom", conf, CONF_ssh_gss_custom);
#endif
    gppi(sesskey, "SshNoShell", 0, conf, CONF_ssh_no_shell);
    gppfile(sesskey, "PublicKeyFile", conf, CONF_keyfile);
    gpps(sesskey, "RemoteCommand", "", conf, CONF_remote_cmd);
    gppi(sesskey, "RFCEnviron", 0, conf, CONF_rfc_environ);
    gppi(sesskey, "PassiveTelnet", 0, conf, CONF_passive_telnet);
/* PuTTY CAPI start */
#ifdef _WINDOWS
    gppi(sesskey, "AuthCAPI", 0, conf, CONF_try_capi_auth);
    gpps(sesskey, "CAPICertID", "", conf, CONF_capi_certID);
#endif
/* PuTTY CAPI end */
    gppi(sesskey, "BackspaceIsDelete", 1, conf, CONF_bksp_is_delete);
    gppi(sesskey, "RXVTHomeEnd", 0, conf, CONF_rxvt_homeend);
    gppi(sesskey, "LinuxFunctionKeys", 0, conf, CONF_funky_type);
    gppi(sesskey, "NoApplicationKeys", 0, conf, CONF_no_applic_k);
    gppi(sesskey, "NoApplicationCursors", 0, conf, CONF_no_applic_c);
    gppi(sesskey, "NoMouseReporting", 0, conf, CONF_no_mouse_rep);
    gppi(sesskey, "NoRemoteResize", 0, conf, CONF_no_remote_resize);
    gppi(sesskey, "NoAltScreen", 0, conf, CONF_no_alt_screen);
    gppi(sesskey, "NoRemoteWinTitle", 0, conf, CONF_no_remote_wintitle);
    {
	/* Backward compatibility */
	int no_remote_qtitle = gppi_raw(sesskey, "NoRemoteQTitle", 1);
	/* We deliberately interpret the old setting of "no response" as
	 * "empty string". This changes the behaviour, but hopefully for
	 * the better; the user can always recover the old behaviour. */
	gppi(sesskey, "RemoteQTitleAction",
	     no_remote_qtitle ? TITLE_EMPTY : TITLE_REAL,
	     conf, CONF_remote_qtitle_action);
    }
    gppi(sesskey, "NoDBackspace", 0, conf, CONF_no_dbackspace);
    gppi(sesskey, "NoRemoteCharset", 0, conf, CONF_no_remote_charset);
    gppi(sesskey, "ApplicationCursorKeys", 0, conf, CONF_app_cursor);
    gppi(sesskey, "ApplicationKeypad", 0, conf, CONF_app_keypad);
    gppi(sesskey, "NetHackKeypad", 0, conf, CONF_nethack_keypad);
    gppi(sesskey, "AltF4", 1, conf, CONF_alt_f4);
    gppi(sesskey, "AltSpace", 0, conf, CONF_alt_space);
    gppi(sesskey, "AltOnly", 0, conf, CONF_alt_only);
    gppi(sesskey, "ComposeKey", 0, conf, CONF_compose_key);
    gppi(sesskey, "CtrlAltKeys", 1, conf, CONF_ctrlaltkeys);
    gppi(sesskey, "TelnetKey", 0, conf, CONF_telnet_keyboard);
    gppi(sesskey, "TelnetRet", 1, conf, CONF_telnet_newline);
    gppi(sesskey, "LocalEcho", AUTO, conf, CONF_localecho);
    gppi(sesskey, "LocalEdit", AUTO, conf, CONF_localedit);
    gpps(sesskey, "Answerback", "PuTTY", conf, CONF_answerback);
    gppi(sesskey, "AlwaysOnTop", 0, conf, CONF_alwaysontop);
    gppi(sesskey, "FullScreenOnAltEnter", 0, conf, CONF_fullscreenonaltenter);
    gppi(sesskey, "HideMousePtr", 0, conf, CONF_hide_mouseptr);
    gppi(sesskey, "SunkenEdge", 0, conf, CONF_sunken_edge);
    gppi(sesskey, "WindowBorder", 1, conf, CONF_window_border);
    gppi(sesskey, "CurType", 0, conf, CONF_cursor_type);
    gppi(sesskey, "BlinkCur", 0, conf, CONF_blink_cur);
    /* pedantic compiler tells me I can't use conf, CONF_beep as an int * :-) */
    gppi(sesskey, "Beep", 1, conf, CONF_beep);
    gppi(sesskey, "BeepInd", 0, conf, CONF_beep_ind);
    gppfile(sesskey, "BellWaveFile", conf, CONF_bell_wavefile);
    gppi(sesskey, "BellOverload", 1, conf, CONF_bellovl);
    gppi(sesskey, "BellOverloadN", 5, conf, CONF_bellovl_n);
    i = gppi_raw(sesskey, "BellOverloadT", 2*TICKSPERSEC
#ifdef PUTTY_UNIX_H
				   *1000
#endif
				   );
    conf_set_int(conf, CONF_bellovl_t, i
#ifdef PUTTY_UNIX_H
		 / 1000
#endif
		 );
    i = gppi_raw(sesskey, "BellOverloadS", 5*TICKSPERSEC
#ifdef PUTTY_UNIX_H
				   *1000
#endif
				   );
    conf_set_int(conf, CONF_bellovl_s, i
#ifdef PUTTY_UNIX_H
		 / 1000
#endif
		 );
    gppi(sesskey, "ScrollbackLines", 2000, conf, CONF_savelines);
    gppi(sesskey, "DECOriginMode", 0, conf, CONF_dec_om);
    gppi(sesskey, "AutoWrapMode", 1, conf, CONF_wrap_mode);
    gppi(sesskey, "LFImpliesCR", 0, conf, CONF_lfhascr);
    gppi(sesskey, "CRImpliesLF", 0, conf, CONF_crhaslf);
    gppi(sesskey, "DisableArabicShaping", 0, conf, CONF_arabicshaping);
    gppi(sesskey, "DisableBidi", 0, conf, CONF_bidi);
    gppi(sesskey, "WinNameAlways", 1, conf, CONF_win_name_always);
    gpps(sesskey, "WinTitle", "", conf, CONF_wintitle);
    gppi(sesskey, "TermWidth", 80, conf, CONF_width);
    gppi(sesskey, "TermHeight", 24, conf, CONF_height);
    gppfont(sesskey, "Font", conf, CONF_font);
    gppi(sesskey, "FontQuality", FQ_DEFAULT, conf, CONF_font_quality);
    gppi(sesskey, "FontVTMode", VT_UNICODE, conf, CONF_vtmode);
    gppi(sesskey, "UseSystemColours", 0, conf, CONF_system_colour);
    gppi(sesskey, "TryPalette", 0, conf, CONF_try_palette);
    gppi(sesskey, "ANSIColour", 1, conf, CONF_ansi_colour);
    gppi(sesskey, "Xterm256Colour", 1, conf, CONF_xterm_256_colour);
    i = gppi_raw(sesskey, "BoldAsColour", 1); conf_set_int(conf, CONF_bold_style, i+1);

    for (i = 0; i < 22; i++) {
	static const char *const defaults[] = {
	    "187,187,187", "255,255,255", "0,0,0", "85,85,85", "0,0,0",
	    "0,255,0", "0,0,0", "85,85,85", "187,0,0", "255,85,85",
	    "0,187,0", "85,255,85", "187,187,0", "255,255,85", "0,0,187",
	    "85,85,255", "187,0,187", "255,85,255", "0,187,187",
	    "85,255,255", "187,187,187", "255,255,255"
	};
	char buf[20], *buf2;
	int c0, c1, c2;
	sprintf(buf, "Colour%d", i);
	buf2 = gpps_raw(sesskey, buf, defaults[i]);
	if (sscanf(buf2, "%d,%d,%d", &c0, &c1, &c2) == 3) {
	    conf_set_int_int(conf, CONF_colours, i*3+0, c0);
	    conf_set_int_int(conf, CONF_colours, i*3+1, c1);
	    conf_set_int_int(conf, CONF_colours, i*3+2, c2);
	}
	sfree(buf2);
    }
    gppi(sesskey, "RawCNP", 0, conf, CONF_rawcnp);
    gppi(sesskey, "PasteRTF", 0, conf, CONF_rtf_paste);
    gppi(sesskey, "MouseIsXterm", 0, conf, CONF_mouse_is_xterm);
    gppi(sesskey, "RectSelect", 0, conf, CONF_rect_select);
    gppi(sesskey, "MouseOverride", 1, conf, CONF_mouse_override);
    for (i = 0; i < 256; i += 32) {
	static const char *const defaults[] = {
	    "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
	    "0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1",
	    "1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2",
	    "1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1",
	    "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1",
	    "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1",
	    "2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2",
	    "2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2"
	};
	char buf[20], *buf2, *p;
	int j;
	sprintf(buf, "Wordness%d", i);
	buf2 = gpps_raw(sesskey, buf, defaults[i / 32]);
	p = buf2;
	for (j = i; j < i + 32; j++) {
	    char *q = p;
	    while (*p && *p != ',')
		p++;
	    if (*p == ',')
		*p++ = '\0';
	    conf_set_int_int(conf, CONF_wordness, j, atoi(q));
	}
	sfree(buf2);
    }
    /*
     * The empty default for LineCodePage will be converted later
     * into a plausible default for the locale.
     */
    gpps(sesskey, "LineCodePage", "", conf, CONF_line_codepage);
    gppi(sesskey, "CJKAmbigWide", 0, conf, CONF_cjk_ambig_wide);
    gppi(sesskey, "UTF8Override", 1, conf, CONF_utf8_override);
    gpps(sesskey, "Printer", "", conf, CONF_printer);
    gppi(sesskey, "CapsLockCyr", 0, conf, CONF_xlat_capslockcyr);
    gppi(sesskey, "ScrollBar", 1, conf, CONF_scrollbar);
    gppi(sesskey, "ScrollBarFullScreen", 0, conf, CONF_scrollbar_in_fullscreen);
    gppi(sesskey, "ScrollOnKey", 0, conf, CONF_scroll_on_key);
    gppi(sesskey, "ScrollOnDisp", 1, conf, CONF_scroll_on_disp);
    gppi(sesskey, "EraseToScrollback", 1, conf, CONF_erase_to_scrollback);
    gppi(sesskey, "LockSize", 0, conf, CONF_resize_action);
    gppi(sesskey, "BCE", 1, conf, CONF_bce);
    gppi(sesskey, "BlinkText", 0, conf, CONF_blinktext);
    gppi(sesskey, "X11Forward", 0, conf, CONF_x11_forward);
    gpps(sesskey, "X11Display", "", conf, CONF_x11_display);
    gppi(sesskey, "X11AuthType", X11_MIT, conf, CONF_x11_auth);
    gppfile(sesskey, "X11AuthFile", conf, CONF_xauthfile);

    gppi(sesskey, "LocalPortAcceptAll", 0, conf, CONF_lport_acceptall);
    gppi(sesskey, "RemotePortAcceptAll", 0, conf, CONF_rport_acceptall);
    gppmap(sesskey, "PortForwardings", conf, CONF_portfwd);
    i = gppi_raw(sesskey, "BugIgnore1", 0); conf_set_int(conf, CONF_sshbug_ignore1, 2-i);
    i = gppi_raw(sesskey, "BugPlainPW1", 0); conf_set_int(conf, CONF_sshbug_plainpw1, 2-i);
    i = gppi_raw(sesskey, "BugRSA1", 0); conf_set_int(conf, CONF_sshbug_rsa1, 2-i);
    i = gppi_raw(sesskey, "BugIgnore2", 0); conf_set_int(conf, CONF_sshbug_ignore2, 2-i);
    {
	int i;
	i = gppi_raw(sesskey, "BugHMAC2", 0); conf_set_int(conf, CONF_sshbug_hmac2, 2-i);
	if (2-i == AUTO) {
	    i = gppi_raw(sesskey, "BuggyMAC", 0);
	    if (i == 1)
		conf_set_int(conf, CONF_sshbug_hmac2, FORCE_ON);
	}
    }
    i = gppi_raw(sesskey, "BugDeriveKey2", 0); conf_set_int(conf, CONF_sshbug_derivekey2, 2-i);
    i = gppi_raw(sesskey, "BugRSAPad2", 0); conf_set_int(conf, CONF_sshbug_rsapad2, 2-i);
    i = gppi_raw(sesskey, "BugPKSessID2", 0); conf_set_int(conf, CONF_sshbug_pksessid2, 2-i);
    i = gppi_raw(sesskey, "BugRekey2", 0); conf_set_int(conf, CONF_sshbug_rekey2, 2-i);
    i = gppi_raw(sesskey, "BugMaxPkt2", 0); conf_set_int(conf, CONF_sshbug_maxpkt2, 2-i);
    i = gppi_raw(sesskey, "BugOldGex2", 0); conf_set_int(conf, CONF_sshbug_oldgex2, 2-i);
    i = gppi_raw(sesskey, "BugWinadj", 0); conf_set_int(conf, CONF_sshbug_winadj, 2-i);
    i = gppi_raw(sesskey, "BugChanReq", 0); conf_set_int(conf, CONF_sshbug_chanreq, 2-i);
    conf_set_int(conf, CONF_ssh_simple, FALSE);
    gppi(sesskey, "StampUtmp", 1, conf, CONF_stamp_utmp);
    gppi(sesskey, "LoginShell", 1, conf, CONF_login_shell);
    gppi(sesskey, "ScrollbarOnLeft", 0, conf, CONF_scrollbar_on_left);
    gppi(sesskey, "ShadowBold", 0, conf, CONF_shadowbold);
    gppfont(sesskey, "BoldFont", conf, CONF_boldfont);
    gppfont(sesskey, "WideFont", conf, CONF_widefont);
    gppfont(sesskey, "WideBoldFont", conf, CONF_wideboldfont);
    gppi(sesskey, "ShadowBoldOffset", 1, conf, CONF_shadowboldoffset);
    gpps(sesskey, "SerialLine", "", conf, CONF_serline);
    gppi(sesskey, "SerialSpeed", 9600, conf, CONF_serspeed);
    gppi(sesskey, "SerialDataBits", 8, conf, CONF_serdatabits);
    gppi(sesskey, "SerialStopHalfbits", 2, conf, CONF_serstopbits);
    gppi(sesskey, "SerialParity", SER_PAR_NONE, conf, CONF_serparity);
    gppi(sesskey, "SerialFlowControl", SER_FLOW_XONXOFF, conf, CONF_serflow);
    gpps(sesskey, "WindowClass", "", conf, CONF_winclass);
    gppi(sesskey, "ConnectionSharing", 0, conf, CONF_ssh_connection_sharing);
    gppi(sesskey, "ConnectionSharingUpstream", 1, conf, CONF_ssh_connection_sharing_upstream);
    gppi(sesskey, "ConnectionSharingDownstream", 1, conf, CONF_ssh_connection_sharing_downstream);
    gppmap(sesskey, "SSHManualHostKeys", conf, CONF_ssh_manual_hostkeys);
}
Example #16
0
/**
 * Kick off the daap server and wait for events.
 *
 * This starts the initial db scan, sets up the signal
 * handling, starts the webserver, then sits back and waits
 * for events, as notified by the signal handler and the
 * web interface.  These events are communicated via flags
 * in the config structure.
 *
 * \param argc count of command line arguments
 * \param argv command line argument pointers
 * \returns 0 on success, -1 otherwise
 *
 * \todo split out a ws_init and ws_start, so that the
 * web space handlers can be registered before the webserver
 * starts.
 *
 */
int main(int argc, char *argv[]) {
    int option;
    char *configfile=CONFFILE;
    WSCONFIG ws_config;
    int reload=0;
    int start_time;
    int end_time;
    int rescan_counter=0;
    int old_song_count, song_count;
    int force_non_root=0;
    int skip_initial=1;
    int kill_server=0;
    int convert_conf=0;
    char *db_type,*db_parms,*web_root,*runas, *tmp;
    char **mp3_dir_array;
    char *servername, *iface;
    char *ffid = NULL;
    int appdir = 0;
    char *perr=NULL;
    char txtrecord[255];
    void *phandle;
    char *plugindir;

    int err;
    char *apppath;

    int debuglevel=0;
    int plugins_loaded = 0;

#ifdef ALPHA_CUSTOMIZE
    char *share_path;
    pthread_t thread1;
#endif

    config.use_mdns=1;
    err_setlevel(2);

    config.foreground=0;
    while((option=getopt(argc,argv,"D:d:c:P:mfrysiuvab:Vk")) != -1) {
        switch(option) {
        case 'a':
            appdir = 1;
            break;

        case 'b':
            ffid=optarg;
            break;

        case 'd':
            debuglevel = atoi(optarg);
            err_setlevel(debuglevel);
            break;

        case 'D':
            if(err_setdebugmask(optarg)) {
                usage(argv[0]);
                exit(EXIT_FAILURE);
            }
            break;

        case 'f':
            config.foreground=1;
            err_setdest(err_getdest() | LOGDEST_STDERR);
            break;

        case 'c':
            configfile=optarg;
            break;

        case 'm':
            config.use_mdns=0;
            break;

#ifndef WIN32
        case 'P':
            os_set_pidfile(optarg);
            break;
#endif
        case 'r':
            reload=1;
            break;

        case 's':
            skip_initial=0;
            break;

        case 'y':
            force_non_root=1;
            break;

#ifdef WIN32
        case 'i':
            os_register();
            exit(EXIT_SUCCESS);
            break;

        case 'u':
            os_unregister();
            exit(EXIT_SUCCESS);
            break;
#endif
        case 'v':
            convert_conf=1;
            break;

        case 'k':
            kill_server=1;
            break;

        case 'V':
            fprintf(stderr,"Firefly Media Server: Version %s\n",VERSION);
            exit(EXIT_SUCCESS);
            break;

        default:
            usage(argv[0]);
            exit(EXIT_FAILURE);
            break;
        }
    }

    if((getuid()) && (!force_non_root) && (!convert_conf)) {
        fprintf(stderr,"You are not root.  This is almost certainly wrong.  "
                "If you are\nsure you want to do this, use the -y "
                "command-line switch\n");
        exit(EXIT_FAILURE);
    }


    if(kill_server) {
        os_signal_server(S_STOP);
        exit(0);
    }

    io_init();
    io_set_errhandler(main_io_errhandler);
    ws_set_errhandler(main_ws_errhandler);

    /* read the configfile, if specified, otherwise
     * try defaults */
    config.stats.start_time=start_time=(int)time(NULL);
    config.stop=0;

    /* set appdir first, that way config resolves relative to appdir */
    if(appdir) {
        apppath = os_apppath(argv[0]);
        DPRINTF(E_INF,L_MAIN,"Changing cwd to %s\n",apppath);
        chdir(apppath);
        free(apppath);
        configfile="mt-daapd.conf";
    }

    if(CONF_E_SUCCESS != conf_read(configfile)) {
        fprintf(stderr,"Error reading config file (%s)\n",configfile);
        exit(EXIT_FAILURE);
    }

    if(debuglevel) /* was specified, should override the config file */
        err_setlevel(debuglevel);

    if(convert_conf) {
        fprintf(stderr,"Converting config file...\n");
        if(CONF_E_SUCCESS != conf_write()) {
            fprintf(stderr,"Error writing config file.\n");
            exit(EXIT_FAILURE);
        }
        exit(EXIT_SUCCESS);
    }

    DPRINTF(E_LOG,L_MAIN,"Firefly Version %s: Starting with debuglevel %d\n",
            VERSION,err_getlevel());


    /* load plugins before we drop privs?  Maybe... let the
     * plugins do stuff they might need to */
    plugin_init();
    if((plugindir=conf_alloc_string("plugins","plugin_dir",NULL)) != NULL) {
        /* instead of specifying plugins, let's walk through the directory
         * and load each of them */
        if(!load_plugin_dir(plugindir)) {
            DPRINTF(E_LOG,L_MAIN,"Warning: Could not load plugins\n");
        } else {
            plugins_loaded = TRUE;
        }
        free(plugindir);
    }

    if(!plugins_loaded) {
        if((!load_plugin_dir("/usr/lib/firefly/plugins")) &&
           (!load_plugin_dir("/usr/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/usr/local/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/usr/local/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/opt/share/firefly/plugins")) &&
           (!load_plugin_dir("/opt/share/mt-daapd/plugins")) &&
           (!load_plugin_dir("/opt/lib/firefly/plugins")) &&
           (!load_plugin_dir("/opt/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("plugins/.libs"))) {
            DPRINTF(E_FATAL,L_MAIN,"plugins/plugin_dir not specified\n");
        }
    }

    phandle=NULL;
    while((phandle=plugin_enum(phandle))) {
        DPRINTF(E_LOG,L_MAIN,"Plugin loaded: %s\n",plugin_get_description(phandle));
    }

    runas = conf_alloc_string("general","runas","nobody");

#ifndef WITHOUT_MDNS
    if(config.use_mdns) {
        DPRINTF(E_LOG,L_MAIN,"Starting rendezvous daemon\n");
        if(rend_init(runas)) {
            DPRINTF(E_FATAL,L_MAIN|L_REND,"Error in rend_init: %s\n",
                    strerror(errno));
        }
    }
#endif

    if(!os_init(config.foreground,runas)) {
        DPRINTF(E_LOG,L_MAIN,"Could not initialize server\n");
        os_deinit();
        exit(EXIT_FAILURE);
    }

    free(runas);

#ifdef UPNP
    upnp_init();
#endif

    /* this will require that the db be readable by the runas user */
    db_type = conf_alloc_string("general","db_type","sqlite");
    db_parms = conf_alloc_string("general","db_parms","/var/cache/mt-daapd");
    err=db_open(&perr,db_type,db_parms);

    if(err) {
        DPRINTF(E_LOG,L_MAIN|L_DB,"Error opening db: %s\n",perr);
#ifndef WITHOUT_MDNS
        if(config.use_mdns) {
            rend_stop();
        }
#endif
        os_deinit();
        exit(EXIT_FAILURE);
    }

    free(db_type);
    free(db_parms);

    /* Initialize the database before starting */
    DPRINTF(E_LOG,L_MAIN|L_DB,"Initializing database\n");
    if(db_init(reload)) {
        DPRINTF(E_FATAL,L_MAIN|L_DB,"Error in db_init: %s\n",strerror(errno));
    }

    err=db_get_song_count(&perr,&song_count);
    if(err != DB_E_SUCCESS) {
        DPRINTF(E_FATAL,L_MISC,"Error getting song count: %s\n",perr);
    }
    /* do a full reload if the db is empty */
    if(!song_count)
        reload = 1;

    if(conf_get_array("general","mp3_dir",&mp3_dir_array)) {
        if((!skip_initial) || (reload)) {
            DPRINTF(E_LOG,L_MAIN|L_SCAN,"Starting mp3 scan\n");
	#ifdef ALPHA_CUSTOMIZE
	    share_path = conf_alloc_string("general", "mp3_dir", "AAA");
		printf("mp3_dir_array[0] = [%s]\n", mp3_dir_array[0]);
	    if (strlen(share_path) > 0)
	    {
		Cnt_total_file(mp3_dir_array[0]);
		pthread_create( &thread1, NULL, (void*)process_bar, NULL);
		free(share_path);
	    }
	#endif
            plugin_event_dispatch(PLUGIN_EVENT_FULLSCAN_START,0,NULL,0);
            start_time=(int) time(NULL);
            if(scan_init(mp3_dir_array)) {
                DPRINTF(E_LOG,L_MAIN|L_SCAN,"Error scanning MP3 files: %s\n",strerror(errno));
            }
            if(!config.stop) { /* don't send popup when shutting down */
                plugin_event_dispatch(PLUGIN_EVENT_FULLSCAN_END,0,NULL,0);
                err=db_get_song_count(&perr,&song_count);
                end_time=(int) time(NULL);
                DPRINTF(E_LOG,L_MAIN|L_SCAN,"Scanned %d songs in %d seconds\n",
                        song_count,end_time - start_time);
            }
        }
        conf_dispose_array(mp3_dir_array);
    }
    
#ifdef ALPHA_CUSTOMIZE
    thread_exit = 1;
#endif

    /* start up the web server */
    web_root = conf_alloc_string("general","web_root",NULL);
    ws_config.web_root=web_root;
    ws_config.port=conf_get_int("general","port",0);

    DPRINTF(E_LOG,L_MAIN|L_WS,"Starting web server from %s on port %d\n",
            ws_config.web_root, ws_config.port);

    config.server=ws_init(&ws_config);
    if(!config.server) {
        /* pthreads or malloc error */
        DPRINTF(E_FATAL,L_MAIN|L_WS,"Error initializing web server\n");
    }

    if(E_WS_SUCCESS != ws_start(config.server)) {
        /* listen or pthread error */
        DPRINTF(E_FATAL,L_MAIN|L_WS,"Error starting web server\n");
    }

    ws_registerhandler(config.server, "/",main_handler,main_auth,
                       0,1);

#ifndef WITHOUT_MDNS
    if(config.use_mdns) { /* register services */
        servername = conf_get_servername();

        memset(txtrecord,0,sizeof(txtrecord));
        txt_add(txtrecord,"txtvers=1");
        txt_add(txtrecord,"Database ID=%0X",util_djb_hash_str(servername));
        txt_add(txtrecord,"Machine ID=%0X",util_djb_hash_str(servername));
        txt_add(txtrecord,"Machine Name=%s",servername);
        txt_add(txtrecord,"mtd-version=" VERSION);
        txt_add(txtrecord,"iTSh Version=131073"); /* iTunes 6.0.4 */
        txt_add(txtrecord,"Version=196610");      /* iTunes 6.0.4 */
        tmp = conf_alloc_string("general","password",NULL);
        if(tmp && (strlen(tmp)==0)) tmp=NULL;

        txt_add(txtrecord,"Password=%s",tmp ? "true" : "false");
        if(tmp) free(tmp);

        srand((unsigned int)time(NULL));

        if(ffid) {
            txt_add(txtrecord,"ffid=%s",ffid);
        } else {
            txt_add(txtrecord,"ffid=%08x",rand());
        }

        DPRINTF(E_LOG,L_MAIN|L_REND,"Registering rendezvous names\n");
        iface = conf_alloc_string("general","interface","");

        rend_register(servername,"_http._tcp",ws_config.port,iface,txtrecord);

        plugin_rend_register(servername,ws_config.port,iface,txtrecord);

        free(servername);
        free(iface);
    }
#endif

    end_time=(int) time(NULL);

    err=db_get_song_count(&perr,&song_count);
    if(err != DB_E_SUCCESS) {
        DPRINTF(E_FATAL,L_MISC,"Error getting song count: %s\n",perr);
    }

    DPRINTF(E_LOG,L_MAIN,"Serving %d songs.  Startup complete in %d seconds\n",
            song_count,end_time-start_time);

    if(conf_get_int("general","rescan_interval",0) && (!reload) &&
       (!conf_get_int("scanning","skip_first",0)))
        config.reload = 1; /* force a reload on start */

    while(!config.stop) {
        if((conf_get_int("general","rescan_interval",0) &&
            (rescan_counter > conf_get_int("general","rescan_interval",0)))) {
            if((conf_get_int("general","always_scan",0)) ||
                (config_get_session_count())) {
                config.reload=1;
            } else {
                DPRINTF(E_DBG,L_MAIN|L_SCAN|L_DB,"Skipped bground scan... no users\n");
            }
            rescan_counter=0;
        }

        if(config.reload) {
            old_song_count = song_count;
            start_time=(int) time(NULL);

            DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Rescanning database\n");

            if(conf_get_array("general","mp3_dir",&mp3_dir_array)) {
                if(config.full_reload) {
                    config.full_reload=0;
                    db_force_rescan(NULL);
                }

                if(scan_init(mp3_dir_array)) {
                    DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Error rescanning... bad path?\n");
                }

                conf_dispose_array(mp3_dir_array);
            }
            config.reload=0;
            db_get_song_count(NULL,&song_count);
            DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Scanned %d songs (was %d) in "
                    "%d seconds\n",song_count,old_song_count,
                    time(NULL)-start_time);
        }

        os_wait(MAIN_SLEEP_INTERVAL);
        rescan_counter += MAIN_SLEEP_INTERVAL;
    }

    DPRINTF(E_LOG,L_MAIN,"Stopping gracefully\n");

#ifndef WITHOUT_MDNS
    if(config.use_mdns) {
        DPRINTF(E_LOG,L_MAIN|L_REND,"Stopping rendezvous daemon\n");
        rend_stop();
    }
#endif

#ifdef UPNP
    upnp_deinit();
#endif


    /* Got to find a cleaner way to stop the web server.
     * Closing the fd of the socking accepting doesn't necessarily
     * cause the accept to fail on some libcs.
     *
    DPRINTF(E_LOG,L_MAIN|L_WS,"Stopping web server\n");
    ws_stop(config.server);
    */
    free(web_root);
    conf_close();

    DPRINTF(E_LOG,L_MAIN|L_DB,"Closing database\n");
    db_deinit();

    DPRINTF(E_LOG,L_MAIN,"Done!\n");

    os_deinit();
    io_deinit();
    mem_dump();
    return EXIT_SUCCESS;
}
Example #17
0
int WINAPI WinMain(HINSTANCE h,HINSTANCE hprev,LPSTR cmdline,int n){
	debug_init(LOG_FILE);
	uk_log("windows build: %s",BUILD);

	int full_throttle=0;
	nCmdShow=n;

	hinstance=h;
	symbol_mode=LOAD;

	// FIXME temporary debug shit

#else
int main(int argc,char *argv[]){
	debug_init(LOG_FILE);
	
	conf_init(CONFIG_PATH,veta_symbolsloaded);

	uk_log("build: %s",BUILD);
	int full_throttle=0;

	symbol_mode=LOAD;
	symbol_file=SYMBOLS_FILE;

	for(int i=1;i<argc;i++){
		if(!strcmp("--dump-symbols",argv[i])){
			symbol_mode=DUMP;	
			i++;
			if(i>=argc) usage(argv[0]);
			symbol_file=argv[i];
			uk_log("Dumping to %s\n",symbol_file);
		}else if(!strcmp("--load-symbols",argv[i])){
			symbol_mode=LOAD;	
			i++;
			if(i>=argc) usage(argv[0]);
			symbol_file=argv[i];
		}else if(!strcmp("--zoom",argv[i])){
			selection_mode=ZOOM;
		}else if(!strcmp("--highlight",argv[i])){
			selection_mode=HIGHLIGHT;
		}else if(!strcmp("--graphicsopt",argv[i])){
			full_throttle=1;
		}else{
			usage(argv[0]);
		}
	}
#endif

	// Set up callbacks 
	ui_onevent(veta_handleevent);
	ui_onclick(ui2_handle_click);
	ui_onrelease(ui2_handle_release);

	ui_haskeymap(veta_symbolsloaded);

	ui_render(veta_render);

	int x,y;
	conf_read_position(&x,&y);

	ui_init(conf_get_int("width",WIDTH),conf_get_int("height",HEIGHT),x,y);

	if(!symbolsloaded){
		fprintf(stderr,"Failed to load symbols\n");
		exit(1);
	}

// Set up low level graphics and load the keymap
//	ui_init(WIDTH,HEIGHT,st->x,st->y);

	ui2_init();

	ui2_add_widgets();

	ui_loop(full_throttle);

	return 1;
}
Example #18
0
/*
 * Called to set up the adb connection.
 * 
 * Returns an error message, or NULL on success.
 *
 * Also places the canonical host name into `realhost'. It must be
 * freed by the caller.
 */
static const char *adb_init(void *frontend_handle, void **backend_handle,
                            Conf *conf,
                            char *host, int port, char **realhost, int nodelay,
                            int keepalive)
{
    static const struct plug_function_table fn_table = {
        adb_log,
        adb_closing,
        adb_receive,
        adb_sent,
        NULL
    };
    SockAddr addr;
    const char *err;
    Adb adb;

    adb = snew(struct adb_backend_data);
    adb->fn = &fn_table;
    adb->s = NULL;
    adb->state = STATE_WARMING_UP;
    *backend_handle = adb;

    adb->frontend = frontend_handle;

    /*
     * Try to find host.
     */
    {
        char *buf;
        buf = dupprintf("Looking up host \"%s\"%s", "localhost",
                (conf_get_int(conf, CONF_addressfamily) == ADDRTYPE_IPV4 ? " (IPv4)" :
                 (conf_get_int(conf, CONF_addressfamily) == ADDRTYPE_IPV6 ? " (IPv6)" :
                  "")));
        logevent(adb->frontend, buf);
        sfree(buf);
    }
    addr = name_lookup("localhost", port, realhost, conf, conf_get_int(conf, CONF_addressfamily));
    if ((err = sk_addr_error(addr)) != NULL) {
        sk_addr_free(addr);
        return err;
    }

    if (port < 0)
        port = 5037; /* default adb port */

    /*
     * Open socket.
     */
    adb->s = new_connection(addr, *realhost, port, 0, 1, nodelay, keepalive,
                            (Plug) adb, conf);
    if ((err = sk_socket_error(adb->s)) != NULL)
        return err;
    if (*conf_get_str(conf, CONF_loghost)) {
        char *colon;

        sfree(*realhost);
        *realhost = conf_get_str(conf, CONF_loghost);
        colon = strrchr(*realhost, ':');
        if (colon) {
            /*
             * FIXME: if we ever update this aspect of ssh.c for
             * IPv6 literal management, this should change in line
             * with it.
             */
            *colon++ = '\0';
        }
    }

    /* send initial data to adb server */
#define ADB_SHELL_DEFAULT_STR "0012" "host:transport-any"
#define ADB_SHELL_DEFAULT_STR_LEN (sizeof(ADB_SHELL_DEFAULT_STR)-1)
#define ADB_SHELL_USB_STR "0012" "host:transport-usb"
#define ADB_SHELL_USB_STR_LEN (sizeof(ADB_SHELL_USB_STR)-1)
#define ADB_SHELL_LOCAL_STR "0015" "host:transport-local"
#define ADB_SHELL_LOCAL_STR_LEN (sizeof(ADB_SHELL_LOCAL_STR)-1)
#define ADB_SHELL_SERIAL_PREFIX "host:transport:"
#define ADB_SHELL_SERIAL_PREFIX_LEN (sizeof(ADB_SHELL_SERIAL_PREFIX)-1)

#   define write_hello(str, len) \
        sk_write(adb->s, str, len); \
        sk_flush(adb->s); \
        adb->state = STATE_SENT_HELLO;

    do {
        size_t len;
        if (host[0] == ':')
            ++host;

        len = strlen(host);

        if (len == 0 || !strcmp("-a", host) || !strcmp(host, "transport-any")) {
            write_hello(ADB_SHELL_DEFAULT_STR, ADB_SHELL_DEFAULT_STR_LEN);
        } else if (!strcmp("-d", host) || !strcmp(host, "transport-usb")) {
            write_hello(ADB_SHELL_USB_STR, ADB_SHELL_USB_STR_LEN);
        } else if (!strcmp("-e", host) || !strcmp(host, "transport-local")) {
            write_hello(ADB_SHELL_LOCAL_STR, ADB_SHELL_LOCAL_STR_LEN);
        } else {
            char sendbuf[512];
#           define ADB_SHELL_HOST_MAX_LEN (sizeof(sendbuf)-4-ADB_SHELL_SERIAL_PREFIX_LEN)
            if (len > ADB_SHELL_HOST_MAX_LEN)
                len = ADB_SHELL_HOST_MAX_LEN;
            sprintf(sendbuf,"%04lx" ADB_SHELL_SERIAL_PREFIX, (unsigned long)(len+ADB_SHELL_SERIAL_PREFIX_LEN));
            memcpy(sendbuf+4+ADB_SHELL_SERIAL_PREFIX_LEN, host, len);
            write_hello(sendbuf, len+4+ADB_SHELL_SERIAL_PREFIX_LEN);
        }
    } while (0);
    return NULL;
}
Example #19
0
File: proxy.c Project: Riatre/PuTTY
Socket new_connection(SockAddr addr, const char *hostname,
		      int port, int privport,
		      int oobinline, int nodelay, int keepalive,
		      Plug plug, Conf *conf)
{
    if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE &&
	proxy_for_destination(addr, hostname, port, conf))
    {
	ProxySocket *ret;
	SockAddr proxy_addr;
	char *proxy_canonical_name;
        const char *proxy_type;
	Socket sret;
	int type;

	if ((sret = platform_new_connection(addr, hostname, port, privport,
					    oobinline, nodelay, keepalive,
					    plug, conf)) !=
	    NULL)
	    return sret;

	ret = snew(ProxySocket);
	ret->sockvt = &ProxySocket_sockvt;
	ret->plugvt = &ProxySocket_plugvt;
	ret->conf = conf_copy(conf);
	ret->plug = plug;
	ret->remote_addr = addr;       /* will need to be freed on close */
	ret->remote_port = port;

	ret->error = NULL;
	ret->pending_flush = 0;
	ret->pending_eof = 0;
	ret->freeze = 0;

	bufchain_init(&ret->pending_input_data);
	bufchain_init(&ret->pending_output_data);
	bufchain_init(&ret->pending_oob_output_data);

	ret->sub_socket = NULL;
	ret->state = PROXY_STATE_NEW;
	ret->negotiate = NULL;

	type = conf_get_int(conf, CONF_proxy_type);
	if (type == PROXY_HTTP) {
	    ret->negotiate = proxy_http_negotiate;
            proxy_type = "HTTP";
	} else if (type == PROXY_SOCKS4) {
            ret->negotiate = proxy_socks4_negotiate;
            proxy_type = "SOCKS 4";
	} else if (type == PROXY_SOCKS5) {
            ret->negotiate = proxy_socks5_negotiate;
            proxy_type = "SOCKS 5";
	} else if (type == PROXY_TELNET) {
	    ret->negotiate = proxy_telnet_negotiate;
            proxy_type = "Telnet";
	} else {
	    ret->error = "Proxy error: Unknown proxy method";
	    return &ret->sockvt;
	}

        {
            char *logmsg = dupprintf("Will use %s proxy at %s:%d to connect"
                                      " to %s:%d", proxy_type,
                                      conf_get_str(conf, CONF_proxy_host),
                                      conf_get_int(conf, CONF_proxy_port),
                                      hostname, port);
            plug_log(plug, 2, NULL, 0, logmsg, 0);
            sfree(logmsg);
        }

        {
            char *logmsg = dns_log_msg(conf_get_str(conf, CONF_proxy_host),
                                       conf_get_int(conf, CONF_addressfamily),
                                       "proxy");
            plug_log(plug, 2, NULL, 0, logmsg, 0);
            sfree(logmsg);
        }

	/* look-up proxy */
	proxy_addr = sk_namelookup(conf_get_str(conf, CONF_proxy_host),
				   &proxy_canonical_name,
				   conf_get_int(conf, CONF_addressfamily));
	if (sk_addr_error(proxy_addr) != NULL) {
	    ret->error = "Proxy error: Unable to resolve proxy host name";
            sk_addr_free(proxy_addr);
	    return &ret->sockvt;
	}
	sfree(proxy_canonical_name);

        {
            char addrbuf[256], *logmsg;
            sk_getaddr(proxy_addr, addrbuf, lenof(addrbuf));
            logmsg = dupprintf("Connecting to %s proxy at %s port %d",
                               proxy_type, addrbuf,
                               conf_get_int(conf, CONF_proxy_port));
            plug_log(plug, 2, NULL, 0, logmsg, 0);
            sfree(logmsg);
        }

	/* create the actual socket we will be using,
	 * connected to our proxy server and port.
	 */
	ret->sub_socket = sk_new(proxy_addr,
				 conf_get_int(conf, CONF_proxy_port),
				 privport, oobinline,
				 nodelay, keepalive, &ret->plugvt);
	if (sk_socket_error(ret->sub_socket) != NULL)
	    return &ret->sockvt;

	/* start the proxy negotiation process... */
	sk_set_frozen(ret->sub_socket, 0);
	ret->negotiate(ret, PROXY_CHANGE_NEW);

	return &ret->sockvt;
    }

    /* no proxy, so just return the direct socket */
    return sk_new(addr, port, privport, oobinline, nodelay, keepalive, plug);
}
void hamlib_init(void)
{
	rig_model_t model;
	struct timespec sleep;
	freq_t freq;
	rmode_t mode;
	pbwidth_t width;
	gboolean enable;
	gchar *port, *conf, *spd;
	gint ret, speed;

	if (rig != NULL)
		return;

	enable = conf_get_bool("hamlib/enable");
	model = conf_get_int("hamlib/rig");
	port = conf_get_filename("hamlib/port");
	speed = conf_get_int("hamlib/speed");
	conf = conf_get_string("hamlib/conf");

	if (!enable || !model || port[0] == 0)
		return;

	rig_set_debug(RIG_DEBUG_ERR);

	rig = rig_init(model);

	if (rig == NULL) {
		errmsg(_("Hamlib init: rig_init failed (model=%d)"), model);
		return;
	}

	g_strstrip(conf);
	if (conf[0]) {
		gchar **v, **p, *q;

		v = g_strsplit(conf, ",", 0);

		for (p = v; *p; p++) {
			if ((q = strchr(*p, '=')) == NULL) {
				errmsg(_("Hamlib init: Bad param=value pair: '%s'"), *p);
				break;
			}
			*q++ = 0;

			g_strstrip(*p);
			g_strstrip(q);

			if (hamlib_set_param(*p, q) == FALSE)
				break;
		}

		g_strfreev(v);
	}
	g_free(conf);

	hamlib_set_param("rig_pathname", port);
	g_free(port);

	spd = g_strdup_printf("%d", speed);
	hamlib_set_param("serial_speed", spd);
	g_free(spd);

	ret = rig_open(rig);

	if (ret != RIG_OK) {
		errmsg(_("Hamlib init: rig_open failed: %s"), rigerror(ret));
		rig_cleanup(rig);
		rig = NULL;
		return;
	}

	/* Polling the rig sometimes fails right after opening it */
	sleep.tv_sec = 0;
	sleep.tv_nsec = 100000000L;	/* 100ms */
	nanosleep(&sleep, NULL);

	if (need_freq == TRUE && \
	    (ret = rig_get_freq(rig, RIG_VFO_CURR, &freq)) != RIG_OK) {
		errmsg(_("Hamlib init: rig_get_freq failed: %s"), rigerror(ret));

		hamlib_waterfall = FALSE;
		hamlib_qsodata = FALSE;

		need_freq = FALSE;
		need_mode = FALSE;
	}

	if (need_mode == TRUE &&
	    (ret = rig_get_mode(rig, RIG_VFO_CURR, &mode, &width)) != RIG_OK) {
		errmsg(_("Hamlib init: rig_get_mode failed: %s.\nAssuming USB mode."), rigerror(ret));

		need_mode = FALSE;
	}

	if (hamlib_ptt == TRUE && 
	    (ret = rig_set_ptt(rig, RIG_VFO_CURR, RIG_PTT_OFF)) != RIG_OK) {
		errmsg(_("Hamlib init: rig_set_ptt failed: %s.\nHamlib PTT disabled"), rigerror(ret));

		hamlib_ptt = FALSE;
	}

	/* Don't create the thread if frequency data is not needed */
	if (need_freq == FALSE) {
//		g_warning("Freq data not needed, thread not started.");
		/* If PTT isn't needed either then close everything */
		if (hamlib_ptt == FALSE) {
//			g_warning("PTT not needed, closing rig.");
			rig_close(rig);
			rig_cleanup(rig);
			rig = NULL;
		}
		return;
	}

	if (pthread_create(&hamlib_thread, NULL, hamlib_loop, NULL) < 0) {
		errmsg(_("Hamlib init: pthread_create: %m"));
		rig_close(rig);
		rig_cleanup(rig);
		rig = NULL;
	}
}
Example #21
0
File: main.c Project: skoobe/riofs
/*{{{ main */
int main (int argc, char *argv[])
{
    Application *app;
    gboolean verbose = FALSE;
    gboolean version = FALSE;
    GError *error = NULL;
    GOptionContext *context;
    gchar **s_params = NULL;
    gchar **s_config = NULL;
    gboolean foreground = FALSE;
    gchar conf_str[1023];
    struct stat st;
    gchar **cache_dir = NULL;
    gchar **s_fuse_opts = NULL;
    gchar **s_log_file = NULL;
    guint32 part_size = 0;
    gboolean disable_syslog = FALSE;
    gboolean disable_stats = FALSE;
    gboolean force_head_requests = FALSE;
    gint uid = -1;
    gint gid = -1;
    gint fmode = -1;
    gint dmode = -1;

    struct event_config *ev_config;

    srand (time (NULL));
    app = g_new0 (Application, 1);
    app->conf_path = g_build_filename (SYSCONFDIR, "riofs.conf.xml", NULL);
    g_snprintf (conf_str, sizeof (conf_str), "Path to configuration file. Default: %s", app->conf_path);

    GOptionEntry entries[] = {
        { G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_STRING_ARRAY, &s_params, NULL, NULL },
        { "config", 'c', 0, G_OPTION_ARG_FILENAME_ARRAY, &s_config, conf_str, NULL},

        { "uid", 0, 0, G_OPTION_ARG_INT, &uid, "Set UID of filesystem owner.", NULL },
        { "gid", 0, 0, G_OPTION_ARG_INT, &gid, "Set GID of filesystem owner.", NULL },
        { "fmode", 0, 0, G_OPTION_ARG_INT, &fmode, "Set mode for all files.", NULL },
        { "dmode", 0, 0, G_OPTION_ARG_INT, &dmode, "Set mode for all directories.", NULL },

        { "foreground", 'f', 0, G_OPTION_ARG_NONE, &foreground, "Flag. Do not daemonize process.", NULL },
        { "cache-dir", 0, 0, G_OPTION_ARG_STRING_ARRAY, &cache_dir, "Set cache directory.", NULL },
        { "fuse-options", 'o', 0, G_OPTION_ARG_STRING_ARRAY, &s_fuse_opts, "Fuse options.", "\"opt[,opt...]\"" },
        { "disable-syslog", 0, 0, G_OPTION_ARG_NONE, &disable_syslog, "Flag. Disable logging to syslog.", NULL },
        { "disable-stats", 0, 0, G_OPTION_ARG_NONE, &disable_stats, "Flag. Disable Statistics HTTP interface.", NULL },
        { "part-size", 0, 0, G_OPTION_ARG_INT, &part_size, "Set file part size (in bytes).", NULL },
        { "log-file", 'l', 0, G_OPTION_ARG_STRING_ARRAY, &s_log_file, "File to write output.", NULL },
        { "force-head-requests", 0, 0, G_OPTION_ARG_NONE, &force_head_requests, "Flag. Send HEAD request for each file.", NULL },
        { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Verbose output.", NULL },
        { "version", 'V', 0, G_OPTION_ARG_NONE, &version, "Show application version and exit.", NULL },
        { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL }
    };

    // init libraries
    CRYPTO_set_mem_functions (g_malloc0, g_realloc, g_free);
    ENGINE_load_builtin_engines ();
    ENGINE_register_all_complete ();
    ERR_load_crypto_strings ();
    OpenSSL_add_all_algorithms ();
#ifdef SSL_ENABLED
    SSL_load_error_strings ();
    SSL_library_init ();
#endif
    g_random_set_seed (time (NULL));

    // init main app structure
    ev_config = event_config_new ();

#if defined(__APPLE__)
    // method select is the preferred method on OS X. kqueue and poll are not supported.
    event_config_avoid_method (ev_config, "kqueue");
    event_config_avoid_method (ev_config, "poll");
#endif

    app->evbase = event_base_new_with_config (ev_config);
    event_config_free (ev_config);

    if (!app->evbase) {
        LOG_err (APP_LOG, "Failed to create event base !");
        application_destroy (app);
        return -1;
    }

    app->dns_base = evdns_base_new (app->evbase, 1);
    if (!app->dns_base) {
        LOG_err (APP_LOG, "Failed to create DNS base !");
        application_destroy (app);
        return -1;
    }

    app->f_log = NULL;
    app->log_file_name = NULL;

/*{{{ cmd line args */

    // parse command line options
    context = g_option_context_new ("[bucketname] [mountpoint]");
    g_option_context_add_main_entries (context, entries, NULL);
    g_option_context_set_description (context, "Please set both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables!");
    if (!g_option_context_parse (context, &argc, &argv, &error)) {
        g_fprintf (stderr, "Failed to parse command line options: %s\n", error->message);
        application_destroy (app);
        g_option_context_free (context);
        return -1;
    }
    g_option_context_free (context);

        // check if --version is specified
    if (version) {
        g_fprintf (stdout, "RioFS File System v%s\n", VERSION);
        g_fprintf (stdout, "Copyright (C) 2012-2014 Paul Ionkin <*****@*****.**>\n");
        g_fprintf (stdout, "Copyright (C) 2012-2014 Skoobe GmbH. All rights reserved.\n");
        g_fprintf (stdout, "Libraries:\n");
        g_fprintf (stdout, " GLib: %d.%d.%d   libevent: %s  fuse: %d.%d",
                GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION,
                LIBEVENT_VERSION,
                FUSE_MAJOR_VERSION, FUSE_MINOR_VERSION
        );
#if defined(__APPLE__) || defined(__FreeBSD__) || !defined(__GLIBC__)
        g_fprintf (stdout, "\n");
#else
        g_fprintf (stdout, "  glibc: %s\n", gnu_get_libc_version ());
#endif
        g_fprintf (stdout, "Features:\n");
        g_fprintf (stdout, " libevent backend method: %s\n", event_base_get_method(app->evbase));
#ifdef SSL_ENABLED
        g_fprintf (stdout, " SSL enabled\n");
#endif
        /*
        {
            int i;
            const char **methods = event_get_supported_methods ();

            g_fprintf (stdout, " Available libevent backend methods:\n");
            for (i = 0; methods[i] != NULL; ++i) {
                g_fprintf (stdout, "  %s\n", methods[i]);
            }
        }
        */

        return 0;
    }

    if (!s_params || g_strv_length (s_params) != 2) {
        LOG_err (APP_LOG, "Wrong number of provided arguments!\nTry `%s --help' for more information.", argv[0]);
        application_destroy (app);
        return -1;
    }

    if (verbose)
        log_level = LOG_debug;
    else
        log_level = LOG_msg;

/*}}}*/

/*{{{ parse config file */

    // user provided alternative config path
    if (s_config && g_strv_length (s_config) > 0) {
        g_free (app->conf_path);
        app->conf_path = g_strdup (s_config[0]);
        g_strfreev (s_config);
    }

    app->conf = conf_create ();
    if (access (app->conf_path, R_OK) == 0) {
        LOG_debug (APP_LOG, "Using config file: %s", app->conf_path);

        if (!conf_parse_file (app->conf, app->conf_path)) {
            LOG_err (APP_LOG, "Failed to parse configuration file: %s", app->conf_path);
            application_destroy (app);
            return -1;
        }

    } else {
        LOG_err (APP_LOG, "Configuration file is not found !");
        application_destroy (app);
        return -1;
    }

    if (!conf_check_keys (app->conf, conf_keys_str, conf_keys_len)) {
        LOG_err (APP_LOG, "Configuration file is missing keys, please re-check your configuration file: %s", app->conf_path);
        application_destroy (app);
        return -1;
    }

    if (disable_syslog) {
        conf_set_boolean (app->conf, "log.use_syslog", FALSE);
    }
    // update logging settings
    logger_set_syslog (conf_get_boolean (app->conf, "log.use_syslog"));
    logger_set_color (conf_get_boolean (app->conf, "log.use_color"));

    if (cache_dir && g_strv_length (cache_dir) > 0) {
        conf_set_string (app->conf, "filesystem.cache_dir", cache_dir[0]);
        g_strfreev (cache_dir);
    }

    if (!verbose)
        log_level = conf_get_int (app->conf, "log.level");

    if (uid >= 0)
        conf_set_int (app->conf, "filesystem.uid", uid);

    if (gid >= 0)
        conf_set_int (app->conf, "filesystem.gid", gid);

    if (fmode >= 0)
        conf_set_int (app->conf, "filesystem.file_mode", fmode);

    if (dmode >= 0)
        conf_set_int (app->conf, "filesystem.dir_mode", dmode);

/*}}}*/

    // try to get access parameters from the environment
    if (getenv ("AWS_ACCESS_KEY_ID")) {
        conf_set_string (app->conf, "s3.access_key_id", getenv ("AWS_ACCESS_KEY_ID"));
    // else check if it's set it the config file
    } else {
        if (!conf_node_exists (app->conf, "s3.access_key_id")) {
            LOG_err (APP_LOG, "Environment variables are not set!\nTry `%s --help' for more information.", argv[0]);
            application_destroy (app);
            return -1;
        }
    }
    if (getenv ("AWS_SECRET_ACCESS_KEY")) {
        conf_set_string (app->conf, "s3.secret_access_key", getenv ("AWS_SECRET_ACCESS_KEY"));
    } else {
        if (!conf_node_exists (app->conf, "s3.secret_access_key")) {
            LOG_err (APP_LOG, "Environment variables are not set!\nTry `%s --help' for more information.", argv[0]);
            application_destroy (app);
            return -1;
        }
    }

    // check if both strings are set
    if (!conf_get_string (app->conf, "s3.access_key_id") || !conf_get_string (app->conf, "s3.secret_access_key")) {
        LOG_err (APP_LOG, "Environment variables are not set!\nTry `%s --help' for more information.", argv[0]);
        application_destroy (app);
        return -1;
    }


    // foreground is set
    if (foreground)
        conf_set_boolean (app->conf, "app.foreground", foreground);

    if (part_size)
        conf_set_uint (app->conf, "s3.part_size", part_size);

    if (disable_stats)
        conf_set_boolean (app->conf, "statistics.enabled", FALSE);

    if (force_head_requests)
        conf_set_boolean (app->conf, "s3.force_head_requests_on_lookup", TRUE);
    else
        conf_set_boolean (app->conf, "s3.force_head_requests_on_lookup", FALSE);

    conf_set_string (app->conf, "s3.bucket_name", s_params[0]);
    if (!application_set_url (app, conf_get_string (app->conf, "s3.endpoint"))) {
        application_destroy (app);
        return -1;
    }

    if (s_fuse_opts && g_strv_length (s_fuse_opts) > 0) {
        app->fuse_opts = g_strdup (s_fuse_opts[0]);
        g_strfreev (s_fuse_opts);
    }

    if (s_log_file  && g_strv_length (s_log_file) > 0) {
        app->log_file_name = g_strdup (s_log_file[0]);
        app->f_log = fopen (s_log_file[0], "a+");
        if (!app->f_log) {
            LOG_err (APP_LOG, "Failed to open log file: %s Error: %s", s_log_file[0], strerror (errno));
            application_destroy (app);
            return -1;
        }

        LOG_debug (APP_LOG, "Using %s for storing application logs.", s_log_file[0]);
        logger_set_file (app->f_log);
        g_strfreev (s_log_file);
    }

    conf_set_string (app->conf, "app.mountpoint", s_params[1]);

    // check if directory exists
    if (stat (conf_get_string (app->conf, "app.mountpoint"), &st) == -1) {
        LOG_err (APP_LOG, "Mountpoint %s does not exist! Please check directory permissions!",
            conf_get_string (app->conf, "app.mountpoint"));
        application_destroy (app);
        return -1;
    }
    // check if it's a directory
    if (!S_ISDIR (st.st_mode)) {
        LOG_err (APP_LOG, "Mountpoint %s is not a directory!", conf_get_string (app->conf, "app.mountpoint"));
        application_destroy (app);
        return -1;
    }

    g_strfreev (s_params);

#ifdef SSL_ENABLED
    app->ssl_ctx = SSL_CTX_new (SSLv23_client_method ());
    if (!app->ssl_ctx) {
        LOG_err (APP_LOG, "Failed to initialize SSL engine !");
        application_exit (app);
        return -1;
    }
    SSL_CTX_set_options (app->ssl_ctx, SSL_OP_ALL);
#endif

#ifdef MAGIC_ENABLED
    app->magic_ctx = magic_open(MAGIC_MIME_TYPE);
    if (!app->magic_ctx) {
        LOG_err(APP_LOG, "Failed to initialize magic library\n");
        return -1;
    }
    if (magic_load(app->magic_ctx, NULL)) {
        LOG_err(APP_LOG, "Failed to load magic database: %s\n", magic_error(app->magic_ctx));
        magic_close(app->magic_ctx);
        return -1;
    }
#endif

    app->stat_srv = stat_srv_create (app);
    if (!app->stat_srv) {
        application_exit (app);
        return -1;
    }

    // perform the initial request to get  bucket ACL (handles redirect as well)
    app->service_con = http_connection_create (app);
    if (!app->service_con)  {
        application_destroy (app);
        return -1;
    }
    bucket_client_get (app->service_con, "/?acl", application_on_bucket_acl_cb, app);

    // start the loop
    event_base_dispatch (app->evbase);

    application_destroy (app);

    return 0;
}
Example #22
0
static const char *serial_configure(Serial serial, HANDLE serport, Conf *conf)
{
    DCB dcb;
    COMMTIMEOUTS timeouts;

    /*
     * Set up the serial port parameters. If we can't even
     * GetCommState, we ignore the problem on the grounds that the
     * user might have pointed us at some other type of two-way
     * device instead of a serial port.
     */
    if (GetCommState(serport, &dcb)) {
	char *msg;
	const char *str;

	/*
	 * Boilerplate.
	 */
	dcb.fBinary = TRUE;
	dcb.fDtrControl = DTR_CONTROL_ENABLE;
	dcb.fDsrSensitivity = FALSE;
	dcb.fTXContinueOnXoff = FALSE;
	dcb.fOutX = FALSE;
	dcb.fInX = FALSE;
	dcb.fErrorChar = FALSE;
	dcb.fNull = FALSE;
	dcb.fRtsControl = RTS_CONTROL_ENABLE;
	dcb.fAbortOnError = FALSE;
	dcb.fOutxCtsFlow = FALSE;
	dcb.fOutxDsrFlow = FALSE;

	/*
	 * Configurable parameters.
	 */
	dcb.BaudRate = conf_get_int(conf, CONF_serspeed);
	msg = dupprintf("Configuring baud rate %lu", dcb.BaudRate);
	logevent(serial->frontend, msg);
	sfree(msg);

	dcb.ByteSize = conf_get_int(conf, CONF_serdatabits);
	msg = dupprintf("Configuring %u data bits", dcb.ByteSize);
	logevent(serial->frontend, msg);
	sfree(msg);

	switch (conf_get_int(conf, CONF_serstopbits)) {
	  case 2: dcb.StopBits = ONESTOPBIT; str = "1"; break;
	  case 3: dcb.StopBits = ONE5STOPBITS; str = "1.5"; break;
	  case 4: dcb.StopBits = TWOSTOPBITS; str = "2"; break;
	  default: return "Invalid number of stop bits (need 1, 1.5 or 2)";
	}
	msg = dupprintf("Configuring %s data bits", str);
	logevent(serial->frontend, msg);
	sfree(msg);

	switch (conf_get_int(conf, CONF_serparity)) {
	  case SER_PAR_NONE: dcb.Parity = NOPARITY; str = "no"; break;
	  case SER_PAR_ODD: dcb.Parity = ODDPARITY; str = "odd"; break;
	  case SER_PAR_EVEN: dcb.Parity = EVENPARITY; str = "even"; break;
	  case SER_PAR_MARK: dcb.Parity = MARKPARITY; str = "mark"; break;
	  case SER_PAR_SPACE: dcb.Parity = SPACEPARITY; str = "space"; break;
	}
	msg = dupprintf("Configuring %s parity", str);
	logevent(serial->frontend, msg);
	sfree(msg);

	switch (conf_get_int(conf, CONF_serflow)) {
	  case SER_FLOW_NONE:
	    str = "no";
	    break;
	  case SER_FLOW_XONXOFF:
	    dcb.fOutX = dcb.fInX = TRUE;
	    str = "XON/XOFF";
	    break;
	  case SER_FLOW_RTSCTS:
	    dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
	    dcb.fOutxCtsFlow = TRUE;
	    str = "RTS/CTS";
	    break;
	  case SER_FLOW_DSRDTR:
	    dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
	    dcb.fOutxDsrFlow = TRUE;
	    str = "DSR/DTR";
	    break;
	}
	msg = dupprintf("Configuring %s flow control", str);
	logevent(serial->frontend, msg);
	sfree(msg);

	if (!SetCommState(serport, &dcb))
	    return "Unable to configure serial port";

	timeouts.ReadIntervalTimeout = 1;
	timeouts.ReadTotalTimeoutMultiplier = 0;
	timeouts.ReadTotalTimeoutConstant = 0;
	timeouts.WriteTotalTimeoutMultiplier = 0;
	timeouts.WriteTotalTimeoutConstant = 0;
	if (!SetCommTimeouts(serport, &timeouts))
	    return "Unable to configure serial timeouts";
    }

    return NULL;
}
Socket platform_new_connection(SockAddr addr, char *hostname,
			       int port, int privport,
			       int oobinline, int nodelay, int keepalive,
			       Plug plug, Conf *conf)
{
    char *cmd;

    static const struct socket_function_table socket_fn_table = {
	sk_localproxy_plug,
	sk_localproxy_close,
	sk_localproxy_write,
	sk_localproxy_write_oob,
	sk_localproxy_write_eof,
	sk_localproxy_flush,
	sk_localproxy_set_frozen,
	sk_localproxy_socket_error
    };

    Local_Proxy_Socket ret;
    int to_cmd_pipe[2], from_cmd_pipe[2], pid;

    if (conf_get_int(conf, CONF_proxy_type) != PROXY_CMD)
	return NULL;

    cmd = format_telnet_command(addr, port, conf);

    ret = snew(struct Socket_localproxy_tag);
    ret->fn = &socket_fn_table;
    ret->plug = plug;
    ret->error = NULL;
    ret->outgoingeof = EOF_NO;

    bufchain_init(&ret->pending_input_data);
    bufchain_init(&ret->pending_output_data);

    /*
     * Create the pipes to the proxy command, and spawn the proxy
     * command process.
     */
    if (pipe(to_cmd_pipe) < 0 ||
	pipe(from_cmd_pipe) < 0) {
	ret->error = dupprintf("pipe: %s", strerror(errno));
        sfree(cmd);
	return (Socket)ret;
    }
    cloexec(to_cmd_pipe[1]);
    cloexec(from_cmd_pipe[0]);

    pid = fork();

    if (pid < 0) {
	ret->error = dupprintf("fork: %s", strerror(errno));
        sfree(cmd);
	return (Socket)ret;
    } else if (pid == 0) {
	close(0);
	close(1);
	dup2(to_cmd_pipe[0], 0);
	dup2(from_cmd_pipe[1], 1);
	close(to_cmd_pipe[0]);
	close(from_cmd_pipe[1]);
	noncloexec(0);
	noncloexec(1);
	execl("/bin/sh", "sh", "-c", cmd, (void *)NULL);
	_exit(255);
    }

    sfree(cmd);

    close(to_cmd_pipe[0]);
    close(from_cmd_pipe[1]);

    ret->to_cmd = to_cmd_pipe[1];
    ret->from_cmd = from_cmd_pipe[0];

    if (!localproxy_by_fromfd)
	localproxy_by_fromfd = newtree234(localproxy_fromfd_cmp);
    if (!localproxy_by_tofd)
	localproxy_by_tofd = newtree234(localproxy_tofd_cmp);

    add234(localproxy_by_fromfd, ret);
    add234(localproxy_by_tofd, ret);

    uxsel_set(ret->from_cmd, 1, localproxy_select_result);

    /* We are responsible for this and don't need it any more */
    sk_addr_free(addr);

    return (Socket) ret;
}
Example #24
0
Backend *select_backend(Conf *conf)
{
    Backend *back = backend_from_proto(conf_get_int(conf, CONF_protocol));
    assert(back != NULL);
    return back;
}
Example #25
0
/*
 * This function can accept a NULL pointer as `addr', in which case
 * it will only check the host name.
 */
int proxy_for_destination (SockAddr addr, const char *hostname,
                           int port, Conf *conf)
{
    int s = 0, e = 0;
    char hostip[64];
    int hostip_len, hostname_len;
    const char *exclude_list;

    /*
     * Special local connections such as Unix-domain sockets
     * unconditionally cannot be proxied, even in proxy-localhost
     * mode. There just isn't any way to ask any known proxy type for
     * them.
     */
    if (addr && sk_address_is_special_local(addr))
        return 0;                      /* do not proxy */

    /*
     * Check the host name and IP against the hard-coded
     * representations of `localhost'.
     */
    if (!conf_get_int(conf, CONF_even_proxy_localhost) &&
	(sk_hostname_is_local(hostname) ||
	 (addr && sk_address_is_local(addr))))
	return 0;		       /* do not proxy */

    /* we want a string representation of the IP address for comparisons */
    if (addr) {
	sk_getaddr(addr, hostip, 64);
	hostip_len = strlen(hostip);
    } else
	hostip_len = 0;		       /* placate gcc; shouldn't be required */

    hostname_len = strlen(hostname);

    exclude_list = conf_get_str(conf, CONF_proxy_exclude_list);

    /* now parse the exclude list, and see if either our IP
     * or hostname matches anything in it.
     */

    while (exclude_list[s]) {
	while (exclude_list[s] &&
	       (isspace((unsigned char)exclude_list[s]) ||
		exclude_list[s] == ',')) s++;

	if (!exclude_list[s]) break;

	e = s;

	while (exclude_list[e] &&
	       (isalnum((unsigned char)exclude_list[e]) ||
		exclude_list[e] == '-' ||
		exclude_list[e] == '.' ||
		exclude_list[e] == '*')) e++;

	if (exclude_list[s] == '*') {
	    /* wildcard at beginning of entry */

	    if ((addr && strnicmp(hostip + hostip_len - (e - s - 1),
				  exclude_list + s + 1, e - s - 1) == 0) ||
		strnicmp(hostname + hostname_len - (e - s - 1),
			 exclude_list + s + 1, e - s - 1) == 0)
		return 0; /* IP/hostname range excluded. do not use proxy. */

	} else if (exclude_list[e-1] == '*') {
	    /* wildcard at end of entry */

	    if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
		strnicmp(hostname, exclude_list + s, e - s - 1) == 0)
		return 0; /* IP/hostname range excluded. do not use proxy. */

	} else {
	    /* no wildcard at either end, so let's try an absolute
	     * match (ie. a specific IP)
	     */

	    if (addr && strnicmp(hostip, exclude_list + s, e - s) == 0)
		return 0; /* IP/hostname excluded. do not use proxy. */
	    if (strnicmp(hostname, exclude_list + s, e - s) == 0)
		return 0; /* IP/hostname excluded. do not use proxy. */
	}

	s = e;

	/* Make sure we really have reached the next comma or end-of-string */
	while (exclude_list[s] &&
	       !isspace((unsigned char)exclude_list[s]) &&
	       exclude_list[s] != ',') s++;
    }

    /* no matches in the exclude list, so use the proxy */
    return 1;
}
Example #26
0
Socket platform_new_connection(SockAddr addr, const char *hostname,
			       int port, int privport,
			       int oobinline, int nodelay, int keepalive,
			       Plug plug, Conf *conf)
{
    char *cmd;

    static const struct socket_function_table socket_fn_table = {
	sk_localproxy_plug,
	sk_localproxy_close,
	sk_localproxy_write,
	sk_localproxy_write_oob,
	sk_localproxy_write_eof,
	sk_localproxy_flush,
	sk_localproxy_set_frozen,
	sk_localproxy_socket_error,
        NULL, /* peer_info */
    };

    Local_Proxy_Socket ret;
    int to_cmd_pipe[2], from_cmd_pipe[2], cmd_err_pipe[2], pid, proxytype;

    proxytype = conf_get_int(conf, CONF_proxy_type);
    if (proxytype != PROXY_CMD && proxytype != PROXY_FUZZ)
	return NULL;

    ret = snew(struct Socket_localproxy_tag);
    ret->fn = &socket_fn_table;
    ret->plug = plug;
    ret->error = NULL;
    ret->outgoingeof = EOF_NO;

    bufchain_init(&ret->pending_input_data);
    bufchain_init(&ret->pending_output_data);
    bufchain_init(&ret->pending_error_data);

    if (proxytype == PROXY_CMD) {
	cmd = format_telnet_command(addr, port, conf);

        if (flags & FLAG_STDERR) {
            /* If we have a sensible stderr, the proxy command can
             * send its own standard error there, so we won't
             * interfere. */
            cmd_err_pipe[0] = cmd_err_pipe[1] = -1;
        } else {
            /* If we don't have a sensible stderr, we should catch the
             * proxy command's standard error to put in our event
             * log. */
            cmd_err_pipe[0] = cmd_err_pipe[1] = 0;
        }

        {
            char *logmsg = dupprintf("Starting local proxy command: %s", cmd);
            plug_log(plug, 2, NULL, 0, logmsg, 0);
            sfree(logmsg);
        }

	/*
	 * Create the pipes to the proxy command, and spawn the proxy
	 * command process.
	 */
	if (pipe(to_cmd_pipe) < 0 ||
	    pipe(from_cmd_pipe) < 0 ||
            (cmd_err_pipe[0] == 0 && pipe(cmd_err_pipe) < 0)) {
	    ret->error = dupprintf("pipe: %s", strerror(errno));
	    sfree(cmd);
	    return (Socket)ret;
	}
	cloexec(to_cmd_pipe[1]);
	cloexec(from_cmd_pipe[0]);
	if (cmd_err_pipe[0] >= 0)
            cloexec(cmd_err_pipe[0]);

	pid = fork();

	if (pid < 0) {
	    ret->error = dupprintf("fork: %s", strerror(errno));
	    sfree(cmd);
	    return (Socket)ret;
	} else if (pid == 0) {
	    close(0);
	    close(1);
	    dup2(to_cmd_pipe[0], 0);
	    dup2(from_cmd_pipe[1], 1);
	    close(to_cmd_pipe[0]);
	    close(from_cmd_pipe[1]);
	    if (cmd_err_pipe[0] >= 0) {
                dup2(cmd_err_pipe[1], 2);
                close(cmd_err_pipe[1]);
            }
	    noncloexec(0);
	    noncloexec(1);
	    execl("/bin/sh", "sh", "-c", cmd, (void *)NULL);
	    _exit(255);
	}

	sfree(cmd);

	close(to_cmd_pipe[0]);
	close(from_cmd_pipe[1]);
        if (cmd_err_pipe[0] >= 0)
            close(cmd_err_pipe[1]);

	ret->to_cmd = to_cmd_pipe[1];
	ret->from_cmd = from_cmd_pipe[0];
	ret->cmd_err = cmd_err_pipe[0];
    } else {
	cmd = format_telnet_command(addr, port, conf);
	ret->to_cmd = open("/dev/null", O_WRONLY);
	if (ret->to_cmd == -1) {
	    ret->error = dupprintf("/dev/null: %s", strerror(errno));
	    sfree(cmd);
	    return (Socket)ret;
	}
	ret->from_cmd = open(cmd, O_RDONLY);
	if (ret->from_cmd == -1) {
	    ret->error = dupprintf("%s: %s", cmd, strerror(errno));
	    sfree(cmd);
	    return (Socket)ret;
	}
	sfree(cmd);
	ret->cmd_err = -1;
    }

    if (!localproxy_by_fromfd)
	localproxy_by_fromfd = newtree234(localproxy_fromfd_cmp);
    if (!localproxy_by_tofd)
	localproxy_by_tofd = newtree234(localproxy_tofd_cmp);
    if (!localproxy_by_errfd)
	localproxy_by_errfd = newtree234(localproxy_errfd_cmp);

    add234(localproxy_by_fromfd, ret);
    add234(localproxy_by_tofd, ret);
    if (ret->cmd_err >= 0)
        add234(localproxy_by_errfd, ret);

    uxsel_set(ret->from_cmd, 1, localproxy_select_result);
    if (ret->cmd_err >= 0)
        uxsel_set(ret->cmd_err, 1, localproxy_select_result);

    /* We are responsible for this and don't need it any more */
    sk_addr_free(addr);

    return (Socket) ret;
}
Example #27
0
	return;
    }

    next = schedule_timer(pinger->interval * TICKSPERSEC,
			  pinger_timer, pinger);
    if (!pinger->pending || next < pinger->next) {
	pinger->next = next;
	pinger->pending = TRUE;
    }
}

Pinger pinger_new(Conf *conf, Backend *back, void *backhandle)
{
    Pinger pinger = snew(struct pinger_tag);

    pinger->interval = conf_get_int(conf, CONF_ping_interval);
    pinger->pending = FALSE;
    pinger->back = back;
    pinger->backhandle = backhandle;
    pinger_schedule(pinger);

    return pinger;
}

void pinger_reconfig(Pinger pinger, Conf *oldconf, Conf *newconf)
{
    int newinterval = conf_get_int(newconf, CONF_ping_interval);
    if (conf_get_int(oldconf, CONF_ping_interval) != newinterval) {
	pinger->interval = newinterval;
	pinger_schedule(pinger);
    }
Example #28
0
void save_open_settings(void *sesskey, Conf *conf)
{
    int i;
    char *p;

    write_setting_i(sesskey, "Present", 1);
    write_setting_s(sesskey, "HostName", conf_get_str(conf, CONF_host));
    write_setting_filename(sesskey, "LogFileName", conf_get_filename(conf, CONF_logfilename));
    write_setting_i(sesskey, "LogType", conf_get_int(conf, CONF_logtype));
    write_setting_i(sesskey, "LogFileClash", conf_get_int(conf, CONF_logxfovr));
    write_setting_i(sesskey, "LogFlush", conf_get_int(conf, CONF_logflush));
    write_setting_i(sesskey, "SSHLogOmitPasswords", conf_get_int(conf, CONF_logomitpass));
    write_setting_i(sesskey, "SSHLogOmitData", conf_get_int(conf, CONF_logomitdata));
    p = "raw";
    {
	const Backend *b = backend_from_proto(conf_get_int(conf, CONF_protocol));
	if (b)
	    p = b->name;
    }
    write_setting_s(sesskey, "Protocol", p);
    write_setting_i(sesskey, "PortNumber", conf_get_int(conf, CONF_port));
    /* The CloseOnExit numbers are arranged in a different order from
     * the standard FORCE_ON / FORCE_OFF / AUTO. */
    write_setting_i(sesskey, "CloseOnExit", (conf_get_int(conf, CONF_close_on_exit)+2)%3);
    write_setting_i(sesskey, "WarnOnClose", !!conf_get_int(conf, CONF_warn_on_close));
    write_setting_i(sesskey, "PingInterval", conf_get_int(conf, CONF_ping_interval) / 60);	/* minutes */
    write_setting_i(sesskey, "PingIntervalSecs", conf_get_int(conf, CONF_ping_interval) % 60);	/* seconds */
    write_setting_i(sesskey, "TCPNoDelay", conf_get_int(conf, CONF_tcp_nodelay));
    write_setting_i(sesskey, "TCPKeepalives", conf_get_int(conf, CONF_tcp_keepalives));
    write_setting_s(sesskey, "TerminalType", conf_get_str(conf, CONF_termtype));
    write_setting_s(sesskey, "TerminalSpeed", conf_get_str(conf, CONF_termspeed));
    wmap(sesskey, "TerminalModes", conf, CONF_ttymodes, TRUE);

    /* Address family selection */
    write_setting_i(sesskey, "AddressFamily", conf_get_int(conf, CONF_addressfamily));

    /* proxy settings */
    write_setting_s(sesskey, "ProxyExcludeList", conf_get_str(conf, CONF_proxy_exclude_list));
    write_setting_i(sesskey, "ProxyDNS", (conf_get_int(conf, CONF_proxy_dns)+2)%3);
    write_setting_i(sesskey, "ProxyLocalhost", conf_get_int(conf, CONF_even_proxy_localhost));
    write_setting_i(sesskey, "ProxyMethod", conf_get_int(conf, CONF_proxy_type));
    write_setting_s(sesskey, "ProxyHost", conf_get_str(conf, CONF_proxy_host));
    write_setting_i(sesskey, "ProxyPort", conf_get_int(conf, CONF_proxy_port));
    write_setting_s(sesskey, "ProxyUsername", conf_get_str(conf, CONF_proxy_username));
    write_setting_s(sesskey, "ProxyPassword", conf_get_str(conf, CONF_proxy_password));
    write_setting_s(sesskey, "ProxyTelnetCommand", conf_get_str(conf, CONF_proxy_telnet_command));
    wmap(sesskey, "Environment", conf, CONF_environmt, TRUE);
    write_setting_s(sesskey, "UserName", conf_get_str(conf, CONF_username));
    write_setting_i(sesskey, "UserNameFromEnvironment", conf_get_int(conf, CONF_username_from_env));
    write_setting_s(sesskey, "LocalUserName", conf_get_str(conf, CONF_localusername));
    write_setting_i(sesskey, "NoPTY", conf_get_int(conf, CONF_nopty));
    write_setting_i(sesskey, "Compression", conf_get_int(conf, CONF_compression));
    write_setting_i(sesskey, "TryAgent", conf_get_int(conf, CONF_tryagent));
    write_setting_i(sesskey, "AgentFwd", conf_get_int(conf, CONF_agentfwd));
    write_setting_i(sesskey, "GssapiFwd", conf_get_int(conf, CONF_gssapifwd));
    write_setting_i(sesskey, "ChangeUsername", conf_get_int(conf, CONF_change_username));
    wprefs(sesskey, "Cipher", ciphernames, CIPHER_MAX, conf, CONF_ssh_cipherlist);
    wprefs(sesskey, "KEX", kexnames, KEX_MAX, conf, CONF_ssh_kexlist);
    write_setting_i(sesskey, "RekeyTime", conf_get_int(conf, CONF_ssh_rekey_time));
    write_setting_s(sesskey, "RekeyBytes", conf_get_str(conf, CONF_ssh_rekey_data));
    write_setting_i(sesskey, "SshNoAuth", conf_get_int(conf, CONF_ssh_no_userauth));
    write_setting_i(sesskey, "SshBanner", conf_get_int(conf, CONF_ssh_show_banner));
    write_setting_i(sesskey, "AuthTIS", conf_get_int(conf, CONF_try_tis_auth));
    write_setting_i(sesskey, "AuthKI", conf_get_int(conf, CONF_try_ki_auth));
    write_setting_i(sesskey, "AuthGSSAPI", conf_get_int(conf, CONF_try_gssapi_auth));
#ifndef NO_GSSAPI
    wprefs(sesskey, "GSSLibs", gsslibkeywords, ngsslibs, conf, CONF_ssh_gsslist);
    write_setting_filename(sesskey, "GSSCustom", conf_get_filename(conf, CONF_ssh_gss_custom));
#endif
    write_setting_i(sesskey, "SshNoShell", conf_get_int(conf, CONF_ssh_no_shell));
    write_setting_i(sesskey, "SshProt", conf_get_int(conf, CONF_sshprot));
    write_setting_s(sesskey, "LogHost", conf_get_str(conf, CONF_loghost));
    write_setting_i(sesskey, "SSH2DES", conf_get_int(conf, CONF_ssh2_des_cbc));
    write_setting_filename(sesskey, "PublicKeyFile", conf_get_filename(conf, CONF_keyfile));
    write_setting_s(sesskey, "RemoteCommand", conf_get_str(conf, CONF_remote_cmd));
    write_setting_i(sesskey, "RFCEnviron", conf_get_int(conf, CONF_rfc_environ));
/* PuTTY CAPI start */
#ifdef _WINDOWS
    write_setting_i(sesskey, "AuthCAPI", conf_get_int(conf, CONF_try_capi_auth));
    write_setting_s(sesskey, "CAPICertID", conf_get_str(conf, CONF_capi_certID));
#endif
/* PuTTY CAPI end */
    write_setting_i(sesskey, "PassiveTelnet", conf_get_int(conf, CONF_passive_telnet));
    write_setting_i(sesskey, "BackspaceIsDelete", conf_get_int(conf, CONF_bksp_is_delete));
    write_setting_i(sesskey, "RXVTHomeEnd", conf_get_int(conf, CONF_rxvt_homeend));
    write_setting_i(sesskey, "LinuxFunctionKeys", conf_get_int(conf, CONF_funky_type));
    write_setting_i(sesskey, "NoApplicationKeys", conf_get_int(conf, CONF_no_applic_k));
    write_setting_i(sesskey, "NoApplicationCursors", conf_get_int(conf, CONF_no_applic_c));
    write_setting_i(sesskey, "NoMouseReporting", conf_get_int(conf, CONF_no_mouse_rep));
    write_setting_i(sesskey, "NoRemoteResize", conf_get_int(conf, CONF_no_remote_resize));
    write_setting_i(sesskey, "NoAltScreen", conf_get_int(conf, CONF_no_alt_screen));
    write_setting_i(sesskey, "NoRemoteWinTitle", conf_get_int(conf, CONF_no_remote_wintitle));
    write_setting_i(sesskey, "RemoteQTitleAction", conf_get_int(conf, CONF_remote_qtitle_action));
    write_setting_i(sesskey, "NoDBackspace", conf_get_int(conf, CONF_no_dbackspace));
    write_setting_i(sesskey, "NoRemoteCharset", conf_get_int(conf, CONF_no_remote_charset));
    write_setting_i(sesskey, "ApplicationCursorKeys", conf_get_int(conf, CONF_app_cursor));
    write_setting_i(sesskey, "ApplicationKeypad", conf_get_int(conf, CONF_app_keypad));
    write_setting_i(sesskey, "NetHackKeypad", conf_get_int(conf, CONF_nethack_keypad));
    write_setting_i(sesskey, "AltF4", conf_get_int(conf, CONF_alt_f4));
    write_setting_i(sesskey, "AltSpace", conf_get_int(conf, CONF_alt_space));
    write_setting_i(sesskey, "AltOnly", conf_get_int(conf, CONF_alt_only));
    write_setting_i(sesskey, "ComposeKey", conf_get_int(conf, CONF_compose_key));
    write_setting_i(sesskey, "CtrlAltKeys", conf_get_int(conf, CONF_ctrlaltkeys));
    write_setting_i(sesskey, "TelnetKey", conf_get_int(conf, CONF_telnet_keyboard));
    write_setting_i(sesskey, "TelnetRet", conf_get_int(conf, CONF_telnet_newline));
    write_setting_i(sesskey, "LocalEcho", conf_get_int(conf, CONF_localecho));
    write_setting_i(sesskey, "LocalEdit", conf_get_int(conf, CONF_localedit));
    write_setting_s(sesskey, "Answerback", conf_get_str(conf, CONF_answerback));
    write_setting_i(sesskey, "AlwaysOnTop", conf_get_int(conf, CONF_alwaysontop));
    write_setting_i(sesskey, "FullScreenOnAltEnter", conf_get_int(conf, CONF_fullscreenonaltenter));
    write_setting_i(sesskey, "HideMousePtr", conf_get_int(conf, CONF_hide_mouseptr));
    write_setting_i(sesskey, "SunkenEdge", conf_get_int(conf, CONF_sunken_edge));
    write_setting_i(sesskey, "WindowBorder", conf_get_int(conf, CONF_window_border));
    write_setting_i(sesskey, "CurType", conf_get_int(conf, CONF_cursor_type));
    write_setting_i(sesskey, "BlinkCur", conf_get_int(conf, CONF_blink_cur));
    write_setting_i(sesskey, "Beep", conf_get_int(conf, CONF_beep));
    write_setting_i(sesskey, "BeepInd", conf_get_int(conf, CONF_beep_ind));
    write_setting_filename(sesskey, "BellWaveFile", conf_get_filename(conf, CONF_bell_wavefile));
    write_setting_i(sesskey, "BellOverload", conf_get_int(conf, CONF_bellovl));
    write_setting_i(sesskey, "BellOverloadN", conf_get_int(conf, CONF_bellovl_n));
    write_setting_i(sesskey, "BellOverloadT", conf_get_int(conf, CONF_bellovl_t)
#ifdef PUTTY_UNIX_H
		    * 1000
#endif
		    );
    write_setting_i(sesskey, "BellOverloadS", conf_get_int(conf, CONF_bellovl_s)
#ifdef PUTTY_UNIX_H
		    * 1000
#endif
		    );
    write_setting_i(sesskey, "ScrollbackLines", conf_get_int(conf, CONF_savelines));
    write_setting_i(sesskey, "DECOriginMode", conf_get_int(conf, CONF_dec_om));
    write_setting_i(sesskey, "AutoWrapMode", conf_get_int(conf, CONF_wrap_mode));
    write_setting_i(sesskey, "LFImpliesCR", conf_get_int(conf, CONF_lfhascr));
    write_setting_i(sesskey, "CRImpliesLF", conf_get_int(conf, CONF_crhaslf));
    write_setting_i(sesskey, "DisableArabicShaping", conf_get_int(conf, CONF_arabicshaping));
    write_setting_i(sesskey, "DisableBidi", conf_get_int(conf, CONF_bidi));
    write_setting_i(sesskey, "WinNameAlways", conf_get_int(conf, CONF_win_name_always));
    write_setting_s(sesskey, "WinTitle", conf_get_str(conf, CONF_wintitle));
    write_setting_i(sesskey, "TermWidth", conf_get_int(conf, CONF_width));
    write_setting_i(sesskey, "TermHeight", conf_get_int(conf, CONF_height));
    write_setting_fontspec(sesskey, "Font", conf_get_fontspec(conf, CONF_font));
    write_setting_i(sesskey, "FontQuality", conf_get_int(conf, CONF_font_quality));
    write_setting_i(sesskey, "FontVTMode", conf_get_int(conf, CONF_vtmode));
    write_setting_i(sesskey, "UseSystemColours", conf_get_int(conf, CONF_system_colour));
    write_setting_i(sesskey, "TryPalette", conf_get_int(conf, CONF_try_palette));
    write_setting_i(sesskey, "ANSIColour", conf_get_int(conf, CONF_ansi_colour));
    write_setting_i(sesskey, "Xterm256Colour", conf_get_int(conf, CONF_xterm_256_colour));
    write_setting_i(sesskey, "BoldAsColour", conf_get_int(conf, CONF_bold_style)-1);

    for (i = 0; i < 22; i++) {
	char buf[20], buf2[30];
	sprintf(buf, "Colour%d", i);
	sprintf(buf2, "%d,%d,%d",
		conf_get_int_int(conf, CONF_colours, i*3+0),
		conf_get_int_int(conf, CONF_colours, i*3+1),
		conf_get_int_int(conf, CONF_colours, i*3+2));
	write_setting_s(sesskey, buf, buf2);
    }
    write_setting_i(sesskey, "RawCNP", conf_get_int(conf, CONF_rawcnp));
    write_setting_i(sesskey, "PasteRTF", conf_get_int(conf, CONF_rtf_paste));
    write_setting_i(sesskey, "MouseIsXterm", conf_get_int(conf, CONF_mouse_is_xterm));
    write_setting_i(sesskey, "RectSelect", conf_get_int(conf, CONF_rect_select));
    write_setting_i(sesskey, "MouseOverride", conf_get_int(conf, CONF_mouse_override));
    for (i = 0; i < 256; i += 32) {
	char buf[20], buf2[256];
	int j;
	sprintf(buf, "Wordness%d", i);
	*buf2 = '\0';
	for (j = i; j < i + 32; j++) {
	    sprintf(buf2 + strlen(buf2), "%s%d",
		    (*buf2 ? "," : ""),
		    conf_get_int_int(conf, CONF_wordness, j));
	}
	write_setting_s(sesskey, buf, buf2);
    }
    write_setting_s(sesskey, "LineCodePage", conf_get_str(conf, CONF_line_codepage));
    write_setting_i(sesskey, "CJKAmbigWide", conf_get_int(conf, CONF_cjk_ambig_wide));
    write_setting_i(sesskey, "UTF8Override", conf_get_int(conf, CONF_utf8_override));
    write_setting_s(sesskey, "Printer", conf_get_str(conf, CONF_printer));
    write_setting_i(sesskey, "CapsLockCyr", conf_get_int(conf, CONF_xlat_capslockcyr));
    write_setting_i(sesskey, "ScrollBar", conf_get_int(conf, CONF_scrollbar));
    write_setting_i(sesskey, "ScrollBarFullScreen", conf_get_int(conf, CONF_scrollbar_in_fullscreen));
    write_setting_i(sesskey, "ScrollOnKey", conf_get_int(conf, CONF_scroll_on_key));
    write_setting_i(sesskey, "ScrollOnDisp", conf_get_int(conf, CONF_scroll_on_disp));
    write_setting_i(sesskey, "EraseToScrollback", conf_get_int(conf, CONF_erase_to_scrollback));
    write_setting_i(sesskey, "LockSize", conf_get_int(conf, CONF_resize_action));
    write_setting_i(sesskey, "BCE", conf_get_int(conf, CONF_bce));
    write_setting_i(sesskey, "BlinkText", conf_get_int(conf, CONF_blinktext));
    write_setting_i(sesskey, "X11Forward", conf_get_int(conf, CONF_x11_forward));
    write_setting_s(sesskey, "X11Display", conf_get_str(conf, CONF_x11_display));
    write_setting_i(sesskey, "X11AuthType", conf_get_int(conf, CONF_x11_auth));
    write_setting_filename(sesskey, "X11AuthFile", conf_get_filename(conf, CONF_xauthfile));
    write_setting_i(sesskey, "LocalPortAcceptAll", conf_get_int(conf, CONF_lport_acceptall));
    write_setting_i(sesskey, "RemotePortAcceptAll", conf_get_int(conf, CONF_rport_acceptall));
    wmap(sesskey, "PortForwardings", conf, CONF_portfwd, TRUE);
    write_setting_i(sesskey, "BugIgnore1", 2-conf_get_int(conf, CONF_sshbug_ignore1));
    write_setting_i(sesskey, "BugPlainPW1", 2-conf_get_int(conf, CONF_sshbug_plainpw1));
    write_setting_i(sesskey, "BugRSA1", 2-conf_get_int(conf, CONF_sshbug_rsa1));
    write_setting_i(sesskey, "BugIgnore2", 2-conf_get_int(conf, CONF_sshbug_ignore2));
    write_setting_i(sesskey, "BugHMAC2", 2-conf_get_int(conf, CONF_sshbug_hmac2));
    write_setting_i(sesskey, "BugDeriveKey2", 2-conf_get_int(conf, CONF_sshbug_derivekey2));
    write_setting_i(sesskey, "BugRSAPad2", 2-conf_get_int(conf, CONF_sshbug_rsapad2));
    write_setting_i(sesskey, "BugPKSessID2", 2-conf_get_int(conf, CONF_sshbug_pksessid2));
    write_setting_i(sesskey, "BugRekey2", 2-conf_get_int(conf, CONF_sshbug_rekey2));
    write_setting_i(sesskey, "BugMaxPkt2", 2-conf_get_int(conf, CONF_sshbug_maxpkt2));
    write_setting_i(sesskey, "BugOldGex2", 2-conf_get_int(conf, CONF_sshbug_oldgex2));
    write_setting_i(sesskey, "BugWinadj", 2-conf_get_int(conf, CONF_sshbug_winadj));
    write_setting_i(sesskey, "BugChanReq", 2-conf_get_int(conf, CONF_sshbug_chanreq));
    write_setting_i(sesskey, "StampUtmp", conf_get_int(conf, CONF_stamp_utmp));
    write_setting_i(sesskey, "LoginShell", conf_get_int(conf, CONF_login_shell));
    write_setting_i(sesskey, "ScrollbarOnLeft", conf_get_int(conf, CONF_scrollbar_on_left));
    write_setting_fontspec(sesskey, "BoldFont", conf_get_fontspec(conf, CONF_boldfont));
    write_setting_fontspec(sesskey, "WideFont", conf_get_fontspec(conf, CONF_widefont));
    write_setting_fontspec(sesskey, "WideBoldFont", conf_get_fontspec(conf, CONF_wideboldfont));
    write_setting_i(sesskey, "ShadowBold", conf_get_int(conf, CONF_shadowbold));
    write_setting_i(sesskey, "ShadowBoldOffset", conf_get_int(conf, CONF_shadowboldoffset));
    write_setting_s(sesskey, "SerialLine", conf_get_str(conf, CONF_serline));
    write_setting_i(sesskey, "SerialSpeed", conf_get_int(conf, CONF_serspeed));
    write_setting_i(sesskey, "SerialDataBits", conf_get_int(conf, CONF_serdatabits));
    write_setting_i(sesskey, "SerialStopHalfbits", conf_get_int(conf, CONF_serstopbits));
    write_setting_i(sesskey, "SerialParity", conf_get_int(conf, CONF_serparity));
    write_setting_i(sesskey, "SerialFlowControl", conf_get_int(conf, CONF_serflow));
    write_setting_s(sesskey, "WindowClass", conf_get_str(conf, CONF_winclass));
    write_setting_i(sesskey, "ConnectionSharing", conf_get_int(conf, CONF_ssh_connection_sharing));
    write_setting_i(sesskey, "ConnectionSharingUpstream", conf_get_int(conf, CONF_ssh_connection_sharing_upstream));
    write_setting_i(sesskey, "ConnectionSharingDownstream", conf_get_int(conf, CONF_ssh_connection_sharing_downstream));
    wmap(sesskey, "SSHManualHostKeys", conf, CONF_ssh_manual_hostkeys, FALSE);
}
/*
 * Called to set up the rlogin connection.
 * 
 * Returns an error message, or NULL on success.
 *
 * Also places the canonical host name into `realhost'. It must be
 * freed by the caller.
 */
static const char *rlogin_init(void *frontend_handle, void **backend_handle,
			       Conf *conf,
			       char *host, int port, char **realhost,
			       int nodelay, int keepalive)
{
    static const struct plug_function_table fn_table = {
	rlogin_log,
	rlogin_closing,
	rlogin_receive,
	rlogin_sent
    };
    SockAddr addr;
    const char *err;
    Rlogin rlogin;
    char *ruser;
    int addressfamily;
    char *loghost;

    rlogin = snew(struct rlogin_tag);
    rlogin->fn = &fn_table;
    rlogin->s = NULL;
    rlogin->closed_on_socket_error = FALSE;
    rlogin->frontend = frontend_handle;
    rlogin->term_width = conf_get_int(conf, CONF_width);
    rlogin->term_height = conf_get_int(conf, CONF_height);
    rlogin->firstbyte = 1;
    rlogin->cansize = 0;
    rlogin->prompt = NULL;
    rlogin->conf = conf_copy(conf);
    *backend_handle = rlogin;

    addressfamily = conf_get_int(conf, CONF_addressfamily);
    /*
     * Try to find host.
     */
    {
	char *buf;
	buf = dupprintf("Looking up host \"%s\"%s", host,
			(addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
			 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" :
			  "")));
	logevent(rlogin->frontend, buf);
	sfree(buf);
    }
    addr = name_lookup(host, port, realhost, conf, addressfamily);
    if ((err = sk_addr_error(addr)) != NULL) {
	sk_addr_free(addr);
	return err;
    }

    if (port < 0)
	port = 513;		       /* default rlogin port */

    /*
     * Open socket.
     */
    rlogin->s = new_connection(addr, *realhost, port, 1, 0,
			       nodelay, keepalive, (Plug) rlogin, conf);
    if ((err = sk_socket_error(rlogin->s)) != NULL)
	return err;

    loghost = conf_get_str(conf, CONF_loghost);
    if (*loghost) {
	char *colon;

	sfree(*realhost);
	*realhost = dupstr(loghost);

	colon = host_strrchr(*realhost, ':');
	if (colon)
	    *colon++ = '\0';
    }

    /*
     * Send local username, remote username, terminal type and
     * terminal speed - unless we don't have the remote username yet,
     * in which case we prompt for it and may end up deferring doing
     * anything else until the local prompt mechanism returns.
     */
    if ((ruser = get_remote_username(conf)) != NULL) {
        rlogin_startup(rlogin, ruser);
        sfree(ruser);
    } else {
        int ret;

        rlogin->prompt = new_prompts(rlogin->frontend);
        rlogin->prompt->to_server = TRUE;
        rlogin->prompt->name = dupstr("Rlogin login name");
        add_prompt(rlogin->prompt, dupstr("rlogin username: "), TRUE); 
        ret = get_userpass_input(rlogin->prompt, NULL, 0);
        if (ret >= 0) {
            rlogin_startup(rlogin, rlogin->prompt->prompts[0]->result);
        }
    }

    return NULL;
}
Example #30
0
static
int
custom_get_autosync(void)
{
  return conf_get_int(CONF_AUTOSYNC) != 0;
}