예제 #1
0
파일: common.c 프로젝트: AgentT/iodine
END_TEST

START_TEST(test_topdomain_length)
{
	char *error;

	/* Test empty and too short */
	fail_unless(check_topdomain("", &error));
	fail_if(strcmp("Too short (< 3)", error));
	fail_unless(check_topdomain("a", &error));
	fail_if(strcmp("Too short (< 3)", error));
	fail_unless(check_topdomain(".a", &error));
	fail_if(strcmp("Too short (< 3)", error));
	fail_unless(check_topdomain("a.", &error));
	fail_if(strcmp("Too short (< 3)", error));
	fail_unless(check_topdomain("ab", &error));
	fail_if(strcmp("Too short (< 3)", error));
	fail_if(check_topdomain("a.b", &error));
	fail_if(strcmp("Too short (< 3)", error));

	/* Test too long (over 128, need rest of space for data) */
	fail_unless(check_topdomain(
		"abcd12345.abcd12345.abcd12345.abcd12345.abcd12345."
		"abcd12345.abcd12345.abcd12345.abcd12345.abcd12345."
		"abcd12345.abcd12345.foo129xxx", &error));
	fail_if(strcmp("Too long (> 128)", error));
	fail_if(check_topdomain(
		"abcd12345.abcd12345.abcd12345.abcd12345.abcd12345."
		"abcd12345.abcd12345.abcd12345.abcd12345.abcd12345."
		"abcd12345.abcd12345.foo128xx", &error));
}
예제 #2
0
파일: common.c 프로젝트: AgentT/iodine
END_TEST

START_TEST(test_topdomain_chunks)
{
	char *error;

	/* Must have at least one dot */
	fail_if(check_topdomain("abcde.gh", &error));
	fail_unless(check_topdomain("abcdefgh", &error));
	fail_if(strcmp("No dots", error));

	/* Not two consecutive dots */
	fail_unless(check_topdomain("abc..defgh", &error));
	fail_if(strcmp("Consecutive dots", error));

	/* Not end with a dots */
	fail_unless(check_topdomain("abc.defgh.", &error));
	fail_if(strcmp("Ends with a dot", error));

	/* No chunk longer than 63 chars */
	fail_if(check_topdomain("123456789012345678901234567890"
		"123456789012345678901234567890333.com", &error));
	fail_unless(check_topdomain("123456789012345678901234567890"
		"1234567890123456789012345678904444.com", &error));
	fail_if(strcmp("Too long domain part (> 63)", error));

	fail_if(check_topdomain("abc.123456789012345678901234567890"
		"123456789012345678901234567890333.com", &error));
	fail_unless(check_topdomain("abc.123456789012345678901234567890"
		"1234567890123456789012345678904444.com", &error));
	fail_if(strcmp("Too long domain part (> 63)", error));

	fail_if(check_topdomain("abc.123456789012345678901234567890"
		"123456789012345678901234567890333", &error));
	fail_unless(check_topdomain("abc.123456789012345678901234567890"
		"1234567890123456789012345678904444", &error));
	fail_if(strcmp("Too long domain part (> 63)", error));
}
예제 #3
0
파일: iodine.c 프로젝트: nbraud/iodine
int
main(int argc, char **argv)
{
	char *nameserv_host;
	char *topdomain;
	char *errormsg;
#ifndef WINDOWS32
	struct passwd *pw;
#endif
	char *username;
	char password[33];
	int foreground;
	char *newroot;
	char *context;
	char *device;
	char *pidfile;
	int choice;
	int tun_fd;
	int dns_fd;
	int max_downstream_frag_size;
	int autodetect_frag_size;
	int retval;
	int raw_mode;
	int lazymode;
	int selecttimeout;
	int hostname_maxlen;
#ifdef OPENBSD
	int rtable = 0;
#endif
	struct sockaddr_storage nameservaddr;
	int nameservaddr_len;
	int nameserv_family;

	nameserv_host = NULL;
	topdomain = NULL;
	errormsg = NULL;
#ifndef WINDOWS32
	pw = NULL;
#endif
	username = NULL;
	memset(password, 0, 33);
	srand(time(NULL));
	foreground = 0;
	newroot = NULL;
	context = NULL;
	device = NULL;
	pidfile = NULL;

	autodetect_frag_size = 1;
	max_downstream_frag_size = 3072;
	retval = 0;
	raw_mode = 1;
	lazymode = 1;
	selecttimeout = 4;
	hostname_maxlen = 0xFF;
	nameserv_family = AF_UNSPEC;

#ifdef WINDOWS32
	WSAStartup(req_version, &wsa_data);
#endif

	srand((unsigned) time(NULL));
	client_init();

#if !defined(BSD) && !defined(__GLIBC__)
	__progname = strrchr(argv[0], '/');
	if (__progname == NULL)
		__progname = argv[0];
	else
		__progname++;
#endif

	while ((choice = getopt(argc, argv, "46vfhru:t:d:R:P:m:M:F:T:O:L:I:")) != -1) {
		switch(choice) {
		case '4':
			nameserv_family = AF_INET;
			break;
		case '6':
			nameserv_family = AF_INET6;
			break;
		case 'v':
			version();
			/* NOTREACHED */
			break;
		case 'f':
			foreground = 1;
			break;
		case 'h':
			help();
			/* NOTREACHED */
			break;
		case 'r':
			raw_mode = 0;
			break;
		case 'u':
			username = optarg;
			break;
		case 't':
			newroot = optarg;
			break;
		case 'd':
			device = optarg;
			break;
#ifdef OPENBSD
		case 'R':
			rtable = atoi(optarg);
			break;
#endif
		case 'P':
			strncpy(password, optarg, sizeof(password));
			password[sizeof(password)-1] = 0;

			/* XXX: find better way of cleaning up ps(1) */
			memset(optarg, 0, strlen(optarg));
			break;
		case 'm':
			autodetect_frag_size = 0;
			max_downstream_frag_size = atoi(optarg);
			break;
		case 'M':
			hostname_maxlen = atoi(optarg);
			if (hostname_maxlen > 255)
				hostname_maxlen = 255;
			if (hostname_maxlen < 10)
				hostname_maxlen = 10;
			break;
		case 'z':
			context = optarg;
			break;
		case 'F':
			pidfile = optarg;
			break;
		case 'T':
			if (client_set_qtype(optarg))
				errx(5, "Invalid query type '%s'", optarg);
			break;
		case 'O':       /* not -D, is Debug in server */
			client_set_downenc(optarg);
			break;
		case 'L':
			lazymode = atoi(optarg);
			if (lazymode > 1)
				lazymode = 1;
			if (lazymode < 0)
				lazymode = 0;
			if (!lazymode)
				selecttimeout = 1;
			break;
		case 'I':
			selecttimeout = atoi(optarg);
			if (selecttimeout < 1)
				selecttimeout = 1;
			break;
		default:
			usage();
			/* NOTREACHED */
		}
	}

	check_superuser(usage);

	argc -= optind;
	argv += optind;

	switch (argc) {
	case 1:
		nameserv_host = get_resolvconf_addr();
		topdomain = strdup(argv[0]);
		break;
	case 2:
		nameserv_host = argv[0];
		topdomain = strdup(argv[1]);
		break;
	default:
		usage();
		/* NOTREACHED */
	}

	if (max_downstream_frag_size < 1 || max_downstream_frag_size > 0xffff) {
		warnx("Use a max frag size between 1 and 65535 bytes.\n");
		usage();
		/* NOTREACHED */
	}

	if (nameserv_host) {
		nameservaddr_len = get_addr(nameserv_host, DNS_PORT, nameserv_family, 0, &nameservaddr);
		if (nameservaddr_len < 0) {
			errx(1, "Cannot lookup nameserver '%s': %s ",
				nameserv_host, gai_strerror(nameservaddr_len));
		}
		client_set_nameserver(&nameservaddr, nameservaddr_len);
	} else {
		warnx("No nameserver found - not connected to any network?\n");
		usage();
		/* NOTREACHED */
	}

	if(check_topdomain(topdomain, &errormsg)) {
		warnx("Invalid topdomain: %s", errormsg);
		usage();
		/* NOTREACHED */
	}

	client_set_selecttimeout(selecttimeout);
	client_set_lazymode(lazymode);
	client_set_topdomain(topdomain);
	client_set_hostname_maxlen(hostname_maxlen);

	if (username != NULL) {
#ifndef WINDOWS32
		if ((pw = getpwnam(username)) == NULL) {
			warnx("User %s does not exist!\n", username);
			usage();
			/* NOTREACHED */
		}
#endif
	}

	if (strlen(password) == 0) {
		if (NULL != getenv(PASSWORD_ENV_VAR))
			snprintf(password, sizeof(password), "%s", getenv(PASSWORD_ENV_VAR));
		else
			read_password(password, sizeof(password));
	}

	client_set_password(password);

	if ((tun_fd = open_tun(device)) == -1) {
		retval = 1;
		goto cleanup1;
	}
	if ((dns_fd = open_dns_from_host(NULL, 0, nameservaddr.ss_family, AI_PASSIVE)) < 0) {
		retval = 1;
		goto cleanup2;
	}
#ifdef OPENBSD
	if (rtable > 0)
		socket_setrtable(dns_fd, rtable);
#endif

	signal(SIGINT, sighandler);
	signal(SIGTERM, sighandler);

	fprintf(stderr, "Sending DNS queries for %s to %s\n",
		topdomain, format_addr(&nameservaddr, nameservaddr_len));

	if (client_handshake(dns_fd, raw_mode, autodetect_frag_size, max_downstream_frag_size)) {
		retval = 1;
		goto cleanup2;
	}

	if (client_get_conn() == CONN_RAW_UDP) {
		fprintf(stderr, "Sending raw traffic directly to %s\n", client_get_raw_addr());
	}

	fprintf(stderr, "Connection setup complete, transmitting data.\n");

	if (foreground == 0)
		do_detach();

	if (pidfile != NULL)
		do_pidfile(pidfile);

	if (newroot != NULL)
		do_chroot(newroot);

	if (username != NULL) {
#ifndef WINDOWS32
		gid_t gids[1];
		gids[0] = pw->pw_gid;
		if (setgroups(1, gids) < 0 || setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
			warnx("Could not switch to user %s!\n", username);
			usage();
			/* NOTREACHED */
		}
#endif
	}

	if (context != NULL)
		do_setcon(context);

	client_tunnel(tun_fd, dns_fd);

cleanup2:
	close_dns(dns_fd);
	close_tun(tun_fd);
cleanup1:

	return retval;
}
예제 #4
0
int
main(int argc, char **argv)
{
	extern char *__progname;
	char *listen_ip4;
	char *listen_ip6;
	char *errormsg;
#ifndef WINDOWS32
	struct passwd *pw = NULL;
#endif
	int foreground;
	char *username;
	char *newroot;
	char *context;
	char *device;
	char *pidfile;

	int choice;

	int skipipconfig;
	char *netsize;
	int ns_get_externalip;
	int retval;

#ifdef HAVE_SYSTEMD
	int nb_fds;
#endif

	errormsg = NULL;
	username = NULL;
	newroot = NULL;
	context = NULL;
	device = NULL;
	foreground = 0;
	listen_ip4 = NULL;
	listen_ip6 = NULL;

	ns_get_externalip = 0;
	skipipconfig = 0;
	pidfile = NULL;
	srand(time(NULL));

	retval = 0;

#ifdef WINDOWS32
	WSAStartup(req_version, &wsa_data);
#endif

#if !defined(BSD) && !defined(__GLIBC__)
	__progname = strrchr(argv[0], '/');
	if (__progname == NULL)
		__progname = argv[0];
	else
		__progname++;
#endif

	// Load default values from preset
	memcpy(&server, &preset_default, sizeof(struct server_instance));

	/* each option has format:
	   char *name, int has_arg, int *flag, int val */
	static struct option iodined_args[] = {
		{"version", no_argument, 0, 'v'},
		{"noipcheck", no_argument, 0, 'c'},
		{"notun", no_argument, 0, 's'},
		{"user", required_argument, 0, 'u'},
		{"listen4", required_argument, 0, 'l'},
		{"listen6", required_argument, 0, 'L'},
		{"nsip", required_argument, 0, 'n'},
		{"mtu", required_argument, 0, 'm'},
		{"idlequit", required_argument, 0, 'i'},
		{"forwardto", required_argument, 0, 'b'},
		{"localforward", no_argument, 0, 'A'},
		{"remoteforward", no_argument, 0, 'R'},
		{"help", no_argument, 0, 'h'},
		{"context", required_argument, 0, 'z'},
		{"chrootdir", required_argument, 0, 't'},
		{"pidfile", required_argument, 0, 'F'},
		{NULL, 0, 0, 0}
	};

	static char *iodined_args_short = "46vcsfhDARu:t:d:m:l:L:p:n:b:P:z:F:i:";

	server.running = 1;

	while ((choice = getopt_long(argc, argv, iodined_args_short, iodined_args, NULL)) != -1) {
		switch(choice) {
		case '4':
			server.addrfamily = AF_INET;
			break;
		case '6':
			server.addrfamily = AF_INET6;
			break;
		case 'v':
			version();
			break;
		case 'c':
			server.check_ip = 0;
			break;
		case 's':
			skipipconfig = 1;
			break;
		case 'f':
			foreground = 1;
			break;
		case 'h':
			help();
			break;
		case 'D':
			server.debug++;
			break;
		case 'u':
			username = optarg;
			break;
		case 't':
			newroot = optarg;
			break;
		case 'd':
			device = optarg;
			break;
		case 'm':
			server.mtu = atoi(optarg);
			break;
		case 'l':
			listen_ip4 = optarg;
			break;
		case 'L':
			listen_ip6 = optarg;
			break;
		case 'p':
			server.port = atoi(optarg);
			break;
		case 'n':
			if (optarg && strcmp("auto", optarg) == 0) {
				ns_get_externalip = 1;
			} else {
				server.ns_ip = inet_addr(optarg);
			}
			break;
		case 'b':
			server.bind_enable = 1;
			server.bind_port = atoi(optarg);
			break;
		case 'A':
			server.allow_forward_local_port = 1;
			break;
		case 'R':
			server.allow_forward_local_port = 1;
			server.allow_forward_remote = 1;
			break;
		case 'F':
			pidfile = optarg;
			break;
		case 'i':
			server.max_idle_time = atoi(optarg);
			break;
		case 'P':
			strncpy(server.password, optarg, sizeof(server.password));
			server.password[sizeof(server.password)-1] = 0;

			/* XXX: find better way of cleaning up ps(1) */
			memset(optarg, 0, strlen(optarg));
			break;
		case 'z':
			context = optarg;
			break;
		default:
			usage();
			break;
		}
	}

	argc -= optind;
	argv += optind;

	check_superuser(usage);

	if (argc != 2)
		usage();

	netsize = strchr(argv[0], '/');
	if (netsize) {
		*netsize = 0;
		netsize++;
		server.netmask = atoi(netsize);
	}

	server.my_ip = inet_addr(argv[0]);

	if (server.my_ip == INADDR_NONE) {
		warnx("Bad IP address to use inside tunnel.");
		usage();
	}

	server.topdomain = strdup(argv[1]);
	if(check_topdomain(server.topdomain, &errormsg)) {
		warnx("Invalid topdomain: %s", errormsg);
		usage();
		/* NOTREACHED */
	}

	if (username != NULL) {
#ifndef WINDOWS32
		if ((pw = getpwnam(username)) == NULL) {
			warnx("User %s does not exist!", username);
			usage();
		}
#endif
	}

	if (server.mtu <= 0) {
		warnx("Bad MTU given.");
		usage();
	}

	if(server.port < 1 || server.port > 65535) {
		warnx("Bad port number given.");
		usage();
	}

	if (server.port != 53) {
		fprintf(stderr, "ALERT! Other dns servers expect you to run on port 53.\n");
		fprintf(stderr, "You must manually forward port 53 to port %d for things to work.\n", server.port);
	}

	if (server.debug) {
		fprintf(stderr, "Debug level %d enabled, will stay in foreground.\n", server.debug);
		fprintf(stderr, "Add more -D switches to set higher debug level.\n");
		foreground = 1;
	}

	if (server.addrfamily == AF_UNSPEC || server.addrfamily == AF_INET) {
		server.dns4addr_len = get_addr(listen_ip4, server.port, AF_INET,
									   AI_PASSIVE | AI_NUMERICHOST, &server.dns4addr);
		if (server.dns4addr_len < 0) {
			warnx("Bad IPv4 address to listen on.");
			usage();
		}
	}
	if (server.addrfamily == AF_UNSPEC || server.addrfamily == AF_INET6) {
		server.dns6addr_len = get_addr(listen_ip6, server.port, AF_INET6,
									   AI_PASSIVE | AI_NUMERICHOST, &server.dns6addr);
		if (server.dns6addr_len < 0) {
			warnx("Bad IPv6 address to listen on.");
			usage();
		}
	}
	if (server.bind_enable) {
		in_addr_t dns_ip = ((struct sockaddr_in *) &server.dns4addr)->sin_addr.s_addr;
		if (server.bind_port < 1 || server.bind_port > 65535) {
			warnx("Bad DNS server port number given.");
			usage();
			/* NOTREACHED */
		}
		/* Avoid forwarding loops */
		if (server.bind_port == server.port && (dns_ip == INADDR_ANY || dns_ip == INADDR_LOOPBACK)) {
			warnx("Forward port is same as listen port (%d), will create a loop!", server.bind_port);
			fprintf(stderr, "Use -l to set listen ip to avoid this.\n");
			usage();
			/* NOTREACHED */
		}
		fprintf(stderr, "Requests for domains outside of %s will be forwarded to port %d\n",
				server.topdomain, server.bind_port);
	}

	if (ns_get_externalip) {
		struct in_addr extip;
		int res = get_external_ip(&extip);
		if (res) {
			fprintf(stderr, "Failed to get external IP via web service.\n");
			exit(3);
		}
		server.ns_ip = extip.s_addr;
		fprintf(stderr, "Using %s as external IP.\n", inet_ntoa(extip));
	}

	if (server.ns_ip == INADDR_NONE) {
		warnx("Bad IP address to return as nameserver.");
		usage();
	}
	if (server.netmask > 30 || server.netmask < 8) {
		warnx("Bad netmask (%d bits). Use 8-30 bits.", server.netmask);
		usage();
	}

	if (strlen(server.password) == 0) {
		if (NULL != getenv(PASSWORD_ENV_VAR))
			snprintf(server.password, sizeof(server.password), "%s", getenv(PASSWORD_ENV_VAR));
		else
			read_password(server.password, sizeof(server.password));
	}

	created_users = init_users(server.my_ip, server.netmask);

	if ((server.tun_fd = open_tun(device)) == -1) {
		/* nothing to clean up, just return */
		return 1;
	}
	if (!skipipconfig) {
		const char *other_ip = users_get_first_ip();
		if (tun_setip(argv[0], other_ip, server.netmask) != 0 || tun_setmtu(server.mtu) != 0) {
			retval = 1;
			free((void*) other_ip);
			goto cleanup;
		}
		free((void*) other_ip);
	}

#ifdef HAVE_SYSTEMD
	nb_fds = sd_listen_fds(0);
	if (nb_fds > 1) {
		retval = 1;
		warnx("Too many file descriptors received!\n");
		goto cleanup;
	} else if (nb_fds == 1) {
		/* XXX: assume we get IPv4 socket */
		server.dns_fds.v4fd = SD_LISTEN_FDS_START;
	} else {
#endif
		if ((server.addrfamily == AF_UNSPEC || server.addrfamily == AF_INET) &&
			(server.dns_fds.v4fd = open_dns(&server.dns4addr, server.dns4addr_len)) < 0) {

			retval = 1;
			goto cleanup;
		}
		if ((server.addrfamily == AF_UNSPEC || server.addrfamily == AF_INET6) &&
			/* Set IPv6 socket to V6ONLY */
			(server.dns_fds.v6fd = open_dns_opt(&server.dns6addr, server.dns6addr_len, 1)) < 0) {

			retval = 1;
			goto cleanup;
		}
#ifdef HAVE_SYSTEMD
	}
#endif

	/* Setup dns file descriptors to get destination IP address */
	if (server.dns_fds.v4fd >= 0)
		prepare_dns_fd(server.dns_fds.v4fd);
	if (server.dns_fds.v6fd >= 0)
		prepare_dns_fd(server.dns_fds.v6fd);

	if (server.bind_enable) {
		if ((server.bind_fd = open_dns_from_host(NULL, 0, AF_INET, 0)) < 0) {
			retval = 1;
			goto cleanup;
		}
	}

	if (created_users < USERS) {
		fprintf(stderr, "Limiting to %d simultaneous users because of netmask /%d\n",
			created_users, server.netmask);
	}
	fprintf(stderr, "Listening to dns for domain %s\n", server.topdomain);

	if (foreground == 0)
		do_detach();

	if (pidfile != NULL)
		do_pidfile(pidfile);

#ifdef FREEBSD
	tzsetwall();
#endif
#ifndef WINDOWS32
	openlog( __progname, LOG_NDELAY, LOG_DAEMON );
#endif

	if (newroot != NULL)
		do_chroot(newroot);

	signal(SIGINT, sigint);
	if (username != NULL) {
#ifndef WINDOWS32
		gid_t gids[1];
		gids[0] = pw->pw_gid;
		if (setgroups(1, gids) < 0 || setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
			warnx("Could not switch to user %s!\n", username);
			usage();
		}
#endif
	}

	if (context != NULL)
		do_setcon(context);

	syslog(LOG_INFO, "started, listening on port %d", server.port);

	server_tunnel();

	syslog(LOG_INFO, "stopping");
	close_socket(server.bind_fd);
cleanup:
	close_socket(server.dns_fds.v6fd);
	close_socket(server.dns_fds.v4fd);
	close_socket(server.tun_fd);
#ifdef WINDOWS32
	WSACleanup();
#endif
	/* TODO close user TCP forward sockets */

	return retval;
}
예제 #5
0
int
main(int argc, char **argv)
{
	char *errormsg = NULL;
#ifndef WINDOWS32
	struct passwd *pw = NULL;
#endif
	int choice = -1;
	int retval = 0;

	char *username = NULL;
	char *newroot = NULL;
	char *context = NULL;
	char *device = NULL;
	char *pidfile = NULL;

	int remote_forward_port = 0;

	char *nameserv_host = NULL;
	struct sockaddr_storage nameservaddr;
	int nameservaddr_len = 0;
	int nameserv_family = AF_UNSPEC;

#ifdef WINDOWS32
	WSAStartup(req_version, &wsa_data);
#endif

#if !defined(BSD) && !defined(__GLIBC__)
	__progname = strrchr(argv[0], '/');
	if (__progname == NULL)
		__progname = argv[0];
	else
		__progname++;
#endif

#define OPT_RDOMAIN 0x80
#define OPT_NODROP 0x81

	/* each option has format:
	 * char *name, int has_arg, int *flag, int val */
	static struct option iodine_args[] = {
		{"version", no_argument, 0, 'v'},
		{"help", no_argument, 0, 'h'},
		{"stats", optional_argument, 0, 'V'},
		{"context", required_argument, 0, 'z'},
		{"rdomain", required_argument, 0, OPT_RDOMAIN},
		{"chrootdir", required_argument, 0, 't'},
		{"preset", required_argument, 0, 'Y'},
		{"proxycommand", no_argument, 0, 'R'},
//		{"nodrop", no_argument, 0, OPT_NODROP},
		{"remote", required_argument, 0, 'R'},
		{NULL, 0, 0, 0}
	};

	/* Pre-parse command line to get preset
	 * This is so that all options override preset values regardless of order in command line */
	int optind_orig = optind, preset_id = -1;

	static char *iodine_args_short = "46vfDhrY:s:V:c:C:i:j:u:t:d:R:P:w:W:m:M:F:T:O:L:I:";

	while ((choice = getopt_long(argc, argv, iodine_args_short, iodine_args, NULL))) {
		/* Check if preset has been found yet so we don't process any other options */
		if (preset_id < 0) {
			if (choice == -1) {
				/* reached end of command line and no preset specified - use default */
				preset_id = 0;
			} else if (choice == 'Y') {
				/* find index of preset */
				if (optarg) {
					for (int i = 0; i < NUM_CLIENT_PRESETS; i++) {
						if (toupper(optarg[0]) == client_presets[i].short_name) {
							preset_id = i;
							break;
						}
					}
				}
			} else if (choice == '?') {
				usage();
				/* Not reached */
			} else {
				/* skip all other options until we find preset */
				continue;
			}

			if (preset_id < 0) {
				/* invalid preset or none specified */
				fprintf(stderr, "Invalid preset or none specified with -Y or --preset!\n");
				print_presets(2);
				usage();
				/* not reached */
			}

			memcpy(&this, client_presets[preset_id].preset_data, sizeof(struct client_instance));

			/* Reset optind to reparse command line */
			optind = optind_orig;
			continue;
		} else if (choice == -1) {
			break;
		}

		/* Once a preset is used, it is copied into memory. This way other
		 * options can override preset values regardless of order in command line */

		switch (choice) {
		case '4':
			nameserv_family = AF_INET;
			break;
		case '6':
			nameserv_family = AF_INET6;
			break;
		case 'v':
			version();
			/* NOTREACHED */
			break;
		case 'V':
			this.stats = atoi(optarg);
			if (this.stats < 0)
				this.stats = 0;
			break;
		case 'f':
			this.foreground = 1;
			break;
		case 'D':
			this.debug++;
			break;
		case 'h':
			help();
			/* NOTREACHED */
			break;
		case 'r':
			this.raw_mode = 0;
			break;
		case 'u':
			username = optarg;
			break;
		case 't':
			newroot = optarg;
			break;
		case 'd':
			device = optarg;
			break;
#ifdef OPENBSD
		case OPT_RDOMAIN:
			rtable = atoi(optarg);
			break;
#endif
		case 'R':
			/* Argument format: [host:]port */
			if (!optarg) break;
			this.use_remote_forward = 1;
			remote_forward_port = parse_tcp_forward_option(optarg);
			break;
		case OPT_NODROP:
			// TODO implement TCP-over-tun optimisations
			break;
		case 'P':
			strncpy(this.password, optarg, sizeof(this.password));
			this.password[sizeof(this.password)-1] = 0;

			/* XXX: find better way of cleaning up ps(1) */
			memset(optarg, 0, strlen(optarg));
			break;
		case 'm':
			this.autodetect_frag_size = 0;
			this.max_downstream_frag_size = atoi(optarg);
			break;
		case 'M':
			this.hostname_maxlen = atoi(optarg);
			if (this.hostname_maxlen > 255)
				this.hostname_maxlen = 255;
			if (this.hostname_maxlen < 10)
				this.hostname_maxlen = 10;
			break;
		case 'z':
			context = optarg;
			break;
		case 'F':
			pidfile = optarg;
			break;
		case 'T':
			if (client_set_qtype(optarg))
				errx(5, "Invalid query type '%s'", optarg);
			break;
		case 'O':
			if ((this.downenc = parse_encoding(optarg)) == 0)
				errx(6, "Invalid encoding type '%s'", optarg);
			break;
		case 'L':
			this.lazymode = atoi(optarg);
			if (this.lazymode > 1)
				this.lazymode = 1;
			if (this.lazymode < 0)
				this.lazymode = 0;
			break;
		case 'I':
			this.max_timeout_ms = strtod(optarg, NULL) * 1000;
			if (this.autodetect_server_timeout) {
				this.server_timeout_ms = this.max_timeout_ms / 2;
			}
			break;
		case 'i':
			this.server_timeout_ms = strtod(optarg, NULL) * 1000;
			this.autodetect_server_timeout = 0;
			break;
		case 'j':
			this.downstream_timeout_ms = strtod(optarg, NULL) * 1000;
			if (this.autodetect_server_timeout) {
				this.autodetect_server_timeout = 0;
				this.server_timeout_ms = 4000;
			}
			break;
		case 's':
			this.send_interval_ms = atoi(optarg);
			if (this.send_interval_ms < 0)
				this.send_interval_ms = 0;
		case 'w':
			this.windowsize_down = atoi(optarg);
			break;
		case 'W':
			this.windowsize_up = atoi(optarg);
			break;
		case 'c':
			this.compression_down = atoi(optarg) & 1;
			break;
		case 'C':
			this.compression_up = atoi(optarg) & 1;
			break;
		case 'Y':
			/* Already processed preset: ignore */
			continue;
		default:
			usage();
			/* NOTREACHED */
		}
	}

	srand((unsigned) time(NULL));
	this.rand_seed = (uint16_t) rand();
	this.chunkid = (uint16_t) rand();
	this.running = 1;

	check_superuser(usage);

	argc -= optind;
	argv += optind;

	if (this.debug) {
		fprintf(stderr, "Debug level %d enabled, will stay in foreground.\n", this.debug);
		fprintf(stderr, "Add more -D switches to set higher debug level.\n");
		this.foreground = 1;
	}



	this.nameserv_hosts_len = argc - 1;
	if (this.nameserv_hosts_len <= 0)
		/* if no hosts specified, use resolv.conf */
		this.nameserv_hosts_len = 1;

	// Preallocate memory with expected number of hosts
	this.nameserv_hosts = malloc(sizeof(char *) * this.nameserv_hosts_len);
	this.nameserv_addrs = malloc(sizeof(struct sockaddr_storage) * this.nameserv_hosts_len);

	if (argc == 0) {
		usage();
		/* NOT REACHED */
	} else if (argc == 1) {
		this.nameserv_hosts[0] = get_resolvconf_addr();
	} else if (argc > 1)
		for (int h = 0; h < this.nameserv_hosts_len; h++)
			this.nameserv_hosts[h] = strdup(argv[h + 1]);
	this.topdomain = strdup(argv[0]);

	for (int n = 0; n < this.nameserv_hosts_len; n++) {
		nameserv_host = this.nameserv_hosts[n];
		if (!nameserv_host) {
			errx(1, "Error processing nameserver hostnames!");
		}
		nameservaddr_len = get_addr(nameserv_host, DNS_PORT, nameserv_family, 0, &nameservaddr);
		if (nameservaddr_len < 0) {
			errx(1, "Cannot lookup nameserver '%s': %s ",
					nameserv_host, gai_strerror(nameservaddr_len));
		}
		memcpy(&this.nameserv_addrs[n], &nameservaddr, sizeof(struct sockaddr_storage));
		this.nameserv_addrs_len ++;
		nameserv_host = NULL;
	}

	if (this.nameserv_addrs_len <= 0 || !this.nameserv_hosts[0]) {
		warnx("No nameservers found - not connected to any network?");
		usage();
	}

	if (this.max_downstream_frag_size < 10 || this.max_downstream_frag_size > MAX_FRAGSIZE) {
		warnx("Use a max frag size between 10 and %d bytes.", MAX_FRAGSIZE);
		usage();
		/* NOTREACHED */
	}

	if(check_topdomain(this.topdomain, &errormsg)) {
		warnx("Invalid topdomain: %s", errormsg);
		usage();
		/* NOTREACHED */
	}

	int max_ws = MAX_SEQ_ID / 2;
	if (this.windowsize_up < 1 || this.windowsize_down < 1 ||
		this.windowsize_up > max_ws || this.windowsize_down > max_ws) {
		warnx("Window sizes (-w or -W) must be between 0 and %d!", max_ws);
		usage();
	}

	if (this.max_timeout_ms < 100) {
		warnx("Target interval (-I) must be greater than 0.1 seconds!");
		usage();
	}

	if ((this.server_timeout_ms < 100 || this.server_timeout_ms >= this.max_timeout_ms)
		&& !this.autodetect_server_timeout) {
		warnx("Server timeout (-i) must be greater than 0.1 sec and less than target interval!");
		usage();
	}

	if (this.downstream_timeout_ms < 100) {
		warnx("Downstream fragment timeout must be more than 0.1 sec to prevent excessive retransmits.");
		usage();
	}

	if (!this.lazymode && this.max_timeout_ms > 1000) {
		fprintf(stderr, "Warning: Target interval of >1 second in immediate mode will cause high latency.\n");
	}

	if (username != NULL) {
#ifndef WINDOWS32
		if ((pw = getpwnam(username)) == NULL) {
			warnx("User %s does not exist!", username);
			usage();
			/* NOTREACHED */
		}
#else
		warnx("Warning: Cannot switch user on Windows systems.");
#endif
	}

	if (strlen(this.password) == 0) {
		if (NULL != getenv(PASSWORD_ENV_VAR))
			snprintf(this.password, sizeof(this.password), "%s", getenv(PASSWORD_ENV_VAR));
		else
			read_password(this.password, sizeof(this.password));
	}

	if (!this.use_remote_forward) {
		if ((this.tun_fd = open_tun(device)) == -1) {
			retval = 1;
			goto cleanup;
		}
	}

	if ((this.dns_fd = open_dns_from_host(NULL, 0, nameservaddr.ss_family, AI_PASSIVE)) < 0) {
		retval = 1;
		goto cleanup;
	}
#ifdef OPENBSD
	if (rtable > 0)
		socket_setrtable(dns_fd, rtable);
#endif

	signal(SIGINT, sighandler);
	signal(SIGTERM, sighandler);

	fprintf(stderr, "Sending DNS queries for %s to ", this.topdomain);
	for (int a = 0; a < this.nameserv_addrs_len; a++)
		fprintf(stderr, "%s%s", format_addr(&this.nameserv_addrs[a], sizeof(struct sockaddr_storage)),
				(a != this.nameserv_addrs_len - 1) ?  ", " : "");
	fprintf(stderr, "\n");

	if (this.remote_forward_addr.ss_family != AF_UNSPEC)
		fprintf(stderr, "Requesting TCP data forwarding from server to %s:%d\n",
				format_addr(&this.remote_forward_addr, sizeof(struct sockaddr_storage)), remote_forward_port);

	if (client_handshake()) {
		retval = 1;
		goto cleanup;
	}

	if (this.conn == CONN_RAW_UDP) {
		fprintf(stderr, "Sending raw UDP traffic directly to %s\n", client_get_raw_addr());
	}

	fprintf(stderr, "Connection setup complete, transmitting data.\n");

	if (this.foreground == 0)
		do_detach();

	if (pidfile != NULL)
		do_pidfile(pidfile);

	if (newroot != NULL)
		do_chroot(newroot);

	if (username != NULL) {
#ifndef WINDOWS32
		gid_t gids[1];
		gids[0] = pw->pw_gid;
		if (setgroups(1, gids) < 0 || setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
			warnx("Could not switch to user %s!\n", username);
			usage();
			/* NOTREACHED */
		}
#endif
	}

	if (context != NULL)
		do_setcon(context);

	client_tunnel();

cleanup:
	if (this.use_remote_forward)
		close(STDOUT_FILENO);
	close_socket(this.dns_fd);
	close_socket(this.tun_fd);
#ifdef WINDOWS32
	WSACleanup();
#endif

	return retval;
}