Example #1
0
void reset_password(struct pwdb_passwd *p){
  // Unnecessary? Not sure about lab instructions.
  char password[PASSWORD_SIZE];
  char confirm[PASSWORD_SIZE];
  while (1){
    read_password(password);
    read_password(confirm);
    if (strcmp(password, confirm) == 0) break;
  }
  char *crypted = crypt(password, p->pw_passwd);
  p->pw_passwd=crypted;
  pwdb_update_user(p);
}
Example #2
0
int main(int argc, char **argv) {
  int i;
  FILE *password_file;
  int digits[16] = {0};
  char password[64];
  char new_password[64];
  char confirm_password[64];

  generate_hex_table();

  password_file = fopen(password_file_path, "r");
  if (password_file == NULL) {
    perror("fopen");
    return 1;
  }
  read_password(password_file, password, sizeof(password));
  fclose(password_file);

  printf("New password: "******"Invalid character: %c\n", new_password[i]);
      exit(1);
    }
    digits[index] = 1;
  }

  for (i = 0; i <= 16; ++i) {
    if (digits[i] == 0) {
      printf("Password is not complex enough: %d\n", i);
      return 1;
    }
  }

  printf("Confirm old password: "******"Old password is incorrect.\n");
    return 1;
  }

  change_password(new_password);
  printf("Password changed!\n");
  return 0;
}
Example #3
0
int main(int argc, char **argv) {
	char msg_usage_formatted[1024];

	snprintf(msg_usage_formatted, 1024, msg_usage, argv[0]);

	if (argc != 2 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)
		err_exit(msg_usage_formatted);
	
	int opt;

	while ((opt = getopt(argc, argv, "edl:")) != -1)
		switch (opt) {
		case 'e':
			operation = ENCRYPT;
			break;
		case 'd':
			operation = DECRYPT;
			break;
		default:
			err_exit(msg_usage_formatted);
		}	
	init();

	int pass_length = read_password();

	if (pass_length == -1)
		err_exit(msg_password_mismatch);
	
	term(scrypt());

	return EXIT_FAILURE;
}
Example #4
0
static int unlock(const struct agent_data_t *data, char *password)
{
    if (data->type != AGENT_GPG_AGENT)
        errx(EXIT_FAILURE, "only gpg-agent supports this operation");

    _cleanup_gpg_ struct gpg_t *agent = gpg_agent_connection(data->gpg, NULL);
    if (!agent)
        err(EXIT_FAILURE, "failed to connect to GPG_AUTH_SOCK");

    if (!password)
        read_password(&password);

    const struct fingerprint_t *fgpt = gpg_keyinfo(agent);
    for (; fgpt; fgpt = fgpt->next) {
        if (fgpt->flags & KEY_DISABLED)
            continue;

        if (gpg_preset_passphrase(agent, fgpt->fingerprint, -1, password) < 0) {
            warnx("failed to unlock key '%s'", fgpt->fingerprint);
            return 1;
        }
    }

    return 0;
}
Example #5
0
int keyring_unlock(char *keyring)
{
  GnomeKeyringInfo *info = NULL;
  char *password;

  gnome_keyring_get_info_sync(keyring, &info);

  if (gnome_keyring_info_get_is_locked(info))
  {
    password = try_secure_alloc(sizeof(char) * PASSWORD_MAX_SIZE);

    read_password(&password, "Enter the keyring password");
    GnomeKeyringResult res = gnome_keyring_unlock_sync(keyring, password);

    free_password(password);

    if (res != GNOME_KEYRING_RESULT_OK)
    {
      gnome_keyring_info_free(info);
      return keyring_handle_error(res);
    }
  }

  gnome_keyring_info_free(info);

  return GNOME_KEYRING_RESULT_OK;
}
Example #6
0
static BlockDriverState *bdrv_new_open(const char *filename,
                                       const char *fmt,
                                       int flags)
{
    BlockDriverState *bs;
    BlockDriver *drv;
    char password[256];

    bs = bdrv_new("");
    if (!bs)
        error("Not enough memory");
    if (fmt) {
        drv = bdrv_find_format(fmt);
        if (!drv)
            error("Unknown file format '%s'", fmt);
    } else {
        drv = NULL;
    }
    if (bdrv_open(bs, filename, flags, drv) < 0) {
        error("Could not open '%s'", filename);
    }
    if (bdrv_is_encrypted(bs)) {
        printf("Disk image '%s' is encrypted.\n", filename);
        if (read_password(password, sizeof(password)) < 0)
            error("No password given");
        if (bdrv_set_key(bs, password) < 0)
            error("invalid password");
    }
    return bs;
}
Example #7
0
/*
 * Ask the user for authentication details
 */
static int
query_auth(struct url *URL)
{
    int i, nopwd;

    fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
            URL->scheme, URL->host, URL->port);

    fprintf(stderr, "Login: "******"Password: ",  URL->pwd, sizeof(URL->pwd));

    if (nopwd)
        return (-1);
    for (i = strlen(URL->pwd); i >= 0; --i)
        if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
            URL->pwd[i] = '\0';

    return (0);
}
Example #8
0
void WifiCreds::connect(int indicator_pin) {
  if (!_is_eeprom_init){
    EEPROM.begin(512);
    _is_eeprom_init = true;
  }
  read_ssid(_ssid);
  read_password(_password);
  if (_verbose) {
    Serial.println("");
    Serial.print("Initializing connection to "); Serial.println(_ssid);
    Serial.println("Send \"ssid password\" to update credentials"); 
    Serial.println("");
  }
  
  WiFi.begin(_ssid, _password);
  
  while (_is_wifi_enabled && WiFi.status() != WL_CONNECTED) {
    if(indicator_pin >= 0) digitalWrite(indicator_pin, LOW);
    delay(5);
    if(indicator_pin >= 0) digitalWrite(indicator_pin, HIGH);
    if (Serial.available() > 0){
      read_from_serial(_ssid, WifiCreds::ssid_max_length);
      read_from_serial(_password, WifiCreds::password_max_length);
      if (_verbose) {
        Serial.println("");
        Serial.println("Got new wifi credentials.");
        Serial.print(" - SSID: "); Serial.println(_ssid);
        Serial.print(" - Password: "******".");
  }
  if (_verbose) {
    Serial.println(""); 
    if (_is_wifi_enabled) {
      Serial.println("WiFi connected");
      Serial.print("IP address: "); Serial.println(WiFi.localIP());
      WiFi.macAddress(mac);
      writeHex(mac[5], id, 1, 2);
      writeHex(mac[4], id, 4, 5);
      writeHex(mac[3], id, 7, 8);
      writeHex(mac[2], id, 10, 11);
      writeHex(mac[1], id, 13, 14);
      writeHex(mac[0], id, 16, 17);
      Serial.print("MAC address: "); Serial.println(id);
    } else {
      Serial.println("Skipping wifi setup");
    }
  }
  if (_is_wifi_enabled) _is_connected = true;;
}
Example #9
0
/***************************************************************************
  Function: cgiMain
  Description: 
  Input:  
  Output: 
  Return: 0 OK, other Error
  Others:  none
***************************************************************************/
int cgiMain()
{
    char account[FEATURE_GDGL_ACCOUNT_MAX_LEN + 1]; //16 + terminating null
	char password[FEATURE_GDGL_PASSWD_MAX_LEN + 1]; //16 + terminating null
	char gateway_id[FEATURE_GDGL_ID_LEN + 1]; //12 + terminating null
	char gateway_alias[FEATURE_GDGL_ACCOUNT_MAX_LEN + 1];
	char gateway_passwd[FEATURE_GDGL_PASSWD_MAX_LEN + 1];
	cgiFormResultType cgi_re;
	int res;

	cgiHeaderContentType("application/json"); //MIME

    // Read ID
    res = read_id(gateway_id);
	if (res != 0) {
		client_admin_response("noid", res, clientAdminResultStr[res]);
		return res;
	}
	
	// Read alias
	res = read_alias(gateway_alias);
	if (res != 0) {
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		return res;
	}

    // Read password
	res = read_password(gateway_passwd);
	if (res != 0) {
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		return res;
	}

    // Check account
    cgi_re = cgiFormString("account", account, FEATURE_GDGL_ACCOUNT_MAX_LEN + 1);
	res = check_account(cgi_re, account, gateway_id, gateway_alias);
	if (res != 0) {
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		return res;
	}

	// Check password
	cgi_re = cgiFormString("password", password, FEATURE_GDGL_PASSWD_MAX_LEN + 1);
	res = check_password(cgi_re, password, gateway_passwd);
	if (res != 0) {
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		return res;
	}

    // account & password all right	
    client_admin_response(gateway_id, clientAdminSuccess, clientAdminResultStr[clientAdminSuccess]);
	return 0;
}
Example #10
0
int main(int argc, char *argv[])
{
	char *password;
	int port = DEFAULT_LISTEN_PORT;
	parameters_t pars;
	struct sched_param sched_par;

	openlog("tcpconsole", LOG_CONS|LOG_NDELAY|LOG_NOWAIT|LOG_PID, LOG_DAEMON);

	if (getuid())
		error_exit("This program must be invoked with root-rights.");

	password = read_password("/etc/tcpconsole.pw");

	if (signal(SIGTERM, SIG_IGN) == SIG_ERR)
		error_exit("signal(SIGTERM) failed");

	if (signal(SIGHUP,  SIG_IGN) == SIG_ERR)
		error_exit("signal(SIGHUP) failed");

	pars.sysrq_fd = open_file("/proc/sysrq-trigger", O_WRONLY);
	pars.vcsa0_fd = open_file("/dev/vcsa", O_RDONLY);

	if (setpriority(PRIO_PROCESS, 0, -10) == -1)
		error_exit("Setpriority failed");

	if (nice(-20) == -1)
		error_exit("Failed to set nice-value to -20");

	if (mlockall(MCL_CURRENT) == -1 || mlockall(MCL_FUTURE) == -1)
		error_exit("Failed to lock program in core");

	memset(&sched_par, 0x00, sizeof(sched_par));
	sched_par.sched_priority = sched_get_priority_max(SCHED_RR);
	if (sched_setscheduler(0, SCHED_RR, &sched_par) == -1)
		error_exit("Failed to set scheduler properties for this process");

	syslog(LOG_INFO, "tcpconsole started");

	write_pidfile("/var/run/tcpconsole.pid");

	if ((pars.dmesg_buffer_size = klogctl(10, NULL, 0)) == -1)
		error_exit("klogctl(10) failed");
	pars.dmesg_buffer = (char *)malloc(pars.dmesg_buffer_size + 1);
	if (!pars.dmesg_buffer)
		error_exit("malloc failure");

	listen_on_socket(port, &pars, password);

	return 1;
}
Example #11
0
static BlockDriverState *bdrv_new_open(const char *filename,
                                       const char *fmt,
                                       int flags)
{
    BlockDriverState *bs;
    BlockDriver *drv;
    char password[256];
    int ret;

    bs = bdrv_new("image");

    if (fmt) {
        drv = bdrv_find_format(fmt);
        if (!drv) {
            error_report("Unknown file format '%s'", fmt);
            goto fail;
        }
    } else {
        drv = NULL;
    }

    ret = bdrv_open(bs, filename, flags, drv);
    if (ret < 0) {
        error_report("Could not open '%s': %s", filename, strerror(-ret));
        goto fail;
    }

    if (bdrv_is_encrypted(bs)) {
        printf("Disk image '%s' is encrypted.\n", filename);
        if (read_password(password, sizeof(password)) < 0) {
            error_report("No password given");
            goto fail;
        }
        if (bdrv_set_key(bs, password) < 0) {
            error_report("invalid password");
            goto fail;
        }
    }
    return bs;
fail:
    if (bs) {
        bdrv_delete(bs);
    }
    return NULL;
}
Example #12
0
int login(struct pwdb_passwd *info){
  char username[USERNAME_SIZE];
  char password[PASSWORD_SIZE];
  /*
   * Write "login: "******"Locked out!\n");
    return 1;
  }

  read_password(password);
  if (was_interrupted) return 1;
  char *crypted = crypt(password, info->pw_passwd);

  if (strncmp(info->pw_passwd, crypted, HASH_SIZE) == 0){
    login_success(info);
    printf("Logged in!\n");
    return 0;
  }
  else {
    login_failed(info);
    printf("No!\n");
    return 1;
  }
}
Example #13
0
int probe_main(probe_ctx *ctx, void *arg)
{
	SEXP_t *ent, *obj;
	oval_schema_version_t over;

	obj = probe_ctx_getobject(ctx);

	if (obj == NULL)
		return PROBE_ENOOBJ;

	over = probe_obj_get_platform_schema_version(obj);
        ent = probe_obj_getent(obj, "username", 1);

        if (ent == NULL) {
                return PROBE_ENOVAL;
        }

        // Now we check the file...
        read_password(ent, ctx, over);
        SEXP_free(ent);

        return 0;
}
Example #14
0
int wmain(int argc, wchar_t* argv[])
{
    int rc=0, passlen=0;
    FILE *infp = NULL;
    FILE *outfp = NULL;
    encryptmode_t mode=UNINIT;
    wchar_t *infile = NULL,
            pass[MAX_PASSWD_LEN+1];
    int file_count = 0;
    wchar_t outfile[1024];

    // Initialize the output filename
    outfile[0] = '\0';
    
    while ((rc = getopt(argc, argv, L"vhdep:o:")) != -1)
    {
        switch (rc)
        {
            case 'h':
                usage(argv[0]);
                return 0;
            case 'v':
                version(argv[0]);
                return 0;
            case 'd':
                if (mode != UNINIT)
                {
                    fprintf(stderr, "Error: only specify one of -d or -e\n");
                    cleanup(outfile);
                    return -1;
                }
                mode = DEC;
                break;
            case 'e':
                if (mode != UNINIT)
                {
                    fprintf(stderr, "Error: only specify one of -d or -e\n");
                    cleanup(outfile);
                    return -1;
                }
                mode = ENC;
                break;
            case 'p':
                if (optarg != 0)
                {
                    wcscpy(pass, optarg);
                    passlen = (int) wcslen(pass);
                    if (passlen < 0)
                    {
                        cleanup(outfile);
                        return -1;
                    }
                }
                break;
            case 'o':
                // outfile argument
                if (!wcsncmp(L"-", optarg, 2))
                {
                    // if '-' is outfile name then out to stdout
                    outfp = stdout;
                    _setmode(_fileno(stdout), _O_BINARY);
                }
                else if ((outfp = _wfopen(optarg, L"wb")) == NULL)
                {
                    fwprintf(stderr, L"Error opening output file %s:", optarg);
                    perror("");
                    cleanup(outfile);
                    return  -1;
                }
                wcsncpy(outfile, optarg, 1024);
                outfile[1023] = '\0';
                break;
            default:
                fwprintf(stderr, L"Error: Unknown option '%c'\n", rc);
        }
    }
    
    if (optind >= argc)
    {
        fprintf(stderr, "Error: No file argument specified\n");
        usage(argv[0]);
        cleanup(outfile);
        return -1;
    }

    if (mode == UNINIT)
    {
        fprintf(stderr, "Error: -e or -d not specified\n");
        usage(argv[0]);
        cleanup(outfile);
        return -1;
    }

    // Prompt for password if not provided on the command line
    if (passlen == 0)
    {
        passlen = read_password(pass, mode);

        switch (passlen)
        {
            case 0: //no password in input
                fprintf(stderr, "Error: No password supplied.\n");
                cleanup(outfile);
                return -1;
            case AESCRYPT_READPWD_GETWCHAR:
            case AESCRYPT_READPWD_TOOLONG:
                fwprintf(stderr, L"Error in read_password: %s.\n",
                        read_password_error(passlen));
                cleanup(outfile);
                return -1;
            case AESCRYPT_READPWD_NOMATCH:
                fprintf(stderr, "Error: Passwords don't match.\n");
                cleanup(outfile);
                return -1;
        }

        if (passlen < 0)
        {
            cleanup(outfile);
            // For security reasons, erase the password
            wmemset(pass, 0, passlen);
            return -1;
        }
    }

    file_count = argc - optind;
    if ((file_count > 1) && (outfp != NULL))
    {
        if (outfp != stdout)
        {
            fclose(outfp);
        }
        fprintf(stderr, "Error: A single output file may not be specified with multiple input files.\n");
        usage(argv[0]);
        cleanup(outfile);
        // For security reasons, erase the password
        wmemset(pass, 0, passlen);
        return -1;
    }

    while (optind < argc)
    {
        infile = argv[optind++];

        if(!wcsncmp(L"-", infile, 2))
        {
            if (file_count > 1)
            {
                if ((outfp != stdout) && (outfp != NULL))
                {
                    fclose(outfp);
                }
                fprintf(stderr, "Error: STDIN may not be specified with multiple input files.\n");
                usage(argv[0]);
                cleanup(outfile);
                // For security reasons, erase the password
                wmemset(pass, 0, passlen);
                return -1;
            }
            infp = stdin;
            _setmode(_fileno(stdin), _O_BINARY);
            if (outfp == NULL)
            {
                outfp = stdout;
                _setmode(_fileno(stdout), _O_BINARY);
            }
        }
        else if ((infp = _wfopen(infile, L"rb")) == NULL)
        {
            if ((outfp != stdout) && (outfp != NULL))
            {
                fclose(outfp);
            }
            fwprintf(stderr, L"Error opening input file %s : ", infile);
            perror("");
            cleanup(outfile);
            // For security reasons, erase the password
            wmemset(pass, 0, passlen);
            return  -1;
        }
        
        if (mode == ENC)
        {
            if (outfp == NULL)
            {
                _snwprintf(outfile, 1024, L"%s.aes", infile);
                if ((outfp = _wfopen(outfile, L"wb")) == NULL)
                {
                    if ((infp != stdin) && (infp != NULL))
                    {
                        fclose(infp);
                    }
                    fwprintf(stderr, L"Error opening output file %s : ", outfile);
                    perror("");
                    cleanup(outfile);
                    // For security reasons, erase the password
                    wmemset(pass, 0, passlen);
                    return  -1;
                }
            }
            
            rc = encrypt_stream(infp, outfp, pass, passlen);
        }
        else if (mode == DEC)
        {
            if (outfp == NULL)
            {
                // assume .aes extension
                wcsncpy(outfile, infile, wcslen(infile)-4);
                outfile[wcslen(infile)-4] = '\0';
                if ((outfp = _wfopen(outfile, L"wb")) == NULL)
                {
                    if ((infp != stdin) && (infp != NULL))
                    {
                        fclose(infp);
                    }
                    fwprintf(stderr, L"Error opening output file %s : ", outfile);
                    perror("");
                    cleanup(outfile);
                    // For security reasons, erase the password
                    wmemset(pass, 0, passlen);
                    return  -1;
                }
            }
            
            // should probably test against ascii, utf-16le, and utf-16be encodings
            rc = decrypt_stream(infp, outfp, pass, passlen);
        }
        
        if ((infp != stdin) && (infp != NULL))
        {
            fclose(infp);
        }
        if ((outfp != stdout) && (outfp != NULL))
        {
            fclose(outfp);
        }

        // If there was an error, remove the output file
        if (rc)
        {
            cleanup(outfile);
            // For security reasons, erase the password
            wmemset(pass, 0, passlen);
            return -1;
        }

        // Reset input/output file names and desriptors
        outfile[0] = '\0';
        infp = NULL;
        outfp = NULL;
    }

    // For security reasons, erase the password
    wmemset(pass, 0, passlen);
    
    return rc;
}
Example #15
0
int main(int argc, char *argv[], char *envp[])
{
	static const struct option options[] = {
		{ "debug", 0, NULL, 'd' },
		{ "verbose", 0, NULL, 'V' },
		{ "account", 1, NULL, 'a' },
		{ "password", 1, NULL, 'p' },
		{ "host", 1, NULL, 'H' },
		{ "proxy", 1, NULL, 'P' },
		{ "action", 1, NULL, 'A' },
		{ "user", 1, NULL, 'u' },
		{ "group", 1, NULL, 'G' },
		{ "logfile", 1, NULL, 'L' },
		{ "shrink-urls", 0, NULL, 's' },
		{ "help", 0, NULL, 'h' },
		{ "bash", 0, NULL, 'b' },
		{ "background", 0, NULL, 'B' },
		{ "dry-run", 0, NULL, 'n' },
		{ "page", 1, NULL, 'g' },
		{ "version", 0, NULL, 'v' },
		{ "config", 1, NULL, 'c' },
		{ "replyto", 1, NULL, 'r' },
		{ "retweet", 1, NULL, 'w' },
		{ }
	};
	struct session *session;
	pid_t child;
	char *tweet;
	static char password[80];
	int retval = 0;
	int option;
	char *http_proxy;
	time_t t;
	int page_nr;

	debug = 0;

	session = session_alloc();
	if (!session) {
		fprintf(stderr, "no more memory...\n");
		return -1;
	}

	/* get the current time so that we can log it later */
	time(&t);
	session->time = strdup(ctime(&t));
	session->time[strlen(session->time)-1] = 0x00;

	/* Get the home directory so we can try to find a config file */
	session->homedir = strdup(getenv("HOME"));

	/* set up a default config file location (traditionally ~/.bti) */
	session->configfile = zalloc(strlen(session->homedir) + 7);
	sprintf(session->configfile, "%s/.bti", session->homedir);

	/* Set environment variables first, before reading command line options
	 * or config file values. */
	http_proxy = getenv("http_proxy");
	if (http_proxy) {
		if (session->proxy)
			free(session->proxy);
		session->proxy = strdup(http_proxy);
		dbg("http_proxy = %s\n", session->proxy);
	}

	bti_parse_configfile(session);

	while (1) {
		option = getopt_long_only(argc, argv,
					  "dp:P:H:a:A:u:c:hg:G:sr:nVvw:",
					  options, NULL);
		if (option == -1)
			break;
		switch (option) {
		case 'd':
			debug = 1;
			break;
		case 'V':
			session->verbose = 1;
			break;
		case 'a':
			if (session->account)
				free(session->account);
			session->account = strdup(optarg);
			dbg("account = %s\n", session->account);
			break;
		case 'g':
			page_nr = atoi(optarg);
			dbg("page = %d\n", page_nr);
			session->page = page_nr;
			break;
		case 'r':
			session->replyto = strdup(optarg);
			dbg("in_reply_to_status_id = %s\n", session->replyto);
			break;
		case 'w':
			session->retweet = strdup(optarg);
			dbg("Retweet ID = %s\n", session->retweet);
			break;
		case 'p':
			if (session->password)
				free(session->password);
			session->password = strdup(optarg);
			dbg("password = %s\n", session->password);
			break;
		case 'P':
			if (session->proxy)
				free(session->proxy);
			session->proxy = strdup(optarg);
			dbg("proxy = %s\n", session->proxy);
			break;
		case 'A':
			if (strcasecmp(optarg, "update") == 0)
				session->action = ACTION_UPDATE;
			else if (strcasecmp(optarg, "friends") == 0)
				session->action = ACTION_FRIENDS;
			else if (strcasecmp(optarg, "user") == 0)
				session->action = ACTION_USER;
			else if (strcasecmp(optarg, "replies") == 0)
				session->action = ACTION_REPLIES;
			else if (strcasecmp(optarg, "public") == 0)
				session->action = ACTION_PUBLIC;
			else if (strcasecmp(optarg, "group") == 0)
				session->action = ACTION_GROUP;
			else if (strcasecmp(optarg, "retweet") == 0)
				session->action = ACTION_RETWEET;
			else
				session->action = ACTION_UNKNOWN;
			dbg("action = %d\n", session->action);
			break;
		case 'u':
			if (session->user)
				free(session->user);
			session->user = strdup(optarg);
			dbg("user = %s\n", session->user);
			break;

		case 'G':
			if (session->group)
				free(session->group);
			session->group = strdup(optarg);
			dbg("group = %s\n", session->group);
			break;
		case 'L':
			if (session->logfile)
				free(session->logfile);
			session->logfile = strdup(optarg);
			dbg("logfile = %s\n", session->logfile);
			break;
		case 's':
			session->shrink_urls = 1;
			break;
		case 'H':
			if (session->hosturl)
				free(session->hosturl);
			if (session->hostname)
				free(session->hostname);
			if (strcasecmp(optarg, "twitter") == 0) {
				session->host = HOST_TWITTER;
				session->hosturl = strdup(twitter_host);
				session->hostname = strdup(twitter_name);
			} else if (strcasecmp(optarg, "identica") == 0) {
				session->host = HOST_IDENTICA;
				session->hosturl = strdup(identica_host);
				session->hostname = strdup(identica_name);
			} else {
				session->host = HOST_CUSTOM;
				session->hosturl = strdup(optarg);
				session->hostname = strdup(optarg);
			}
			dbg("host = %d\n", session->host);
			break;
		case 'b':
			session->bash = 1;
			/* fall-through intended */
		case 'B':
			session->background = 1;
			break;
		case 'c':
			if (session->configfile)
				free(session->configfile);
			session->configfile = strdup(optarg);
			dbg("configfile = %s\n", session->configfile);

			/*
			 * read the config file now.  Yes, this could override
			 * previously set options from the command line, but
			 * the user asked for it...
			 */
			bti_parse_configfile(session);
			break;
		case 'h':
			display_help();
			goto exit;
		case 'n':
			session->dry_run = 1;
			break;
		case 'v':
			display_version();
			goto exit;
		default:
			display_help();
			goto exit;
		}
	}

	session_readline_init(session);
	/*
	 * Show the version to make it easier to determine what
	 * is going on here
	 */
	if (debug)
		display_version();

	if (session->host == HOST_TWITTER) {
		if (!session->consumer_key || !session->consumer_secret) {
			if (session->action == ACTION_USER ||
					session->action == ACTION_PUBLIC) {
				/*
				 * Some actions may still work without
				 * authentication
				 */
				session->guest = 1;
			} else {
				fprintf(stderr,
						"Twitter no longer supports HTTP basic authentication.\n"
						"Both consumer key, and consumer secret are required"
						" for bti in order to behave as an OAuth consumer.\n");
				goto exit;
			}
		}
		if (session->action == ACTION_GROUP) {
			fprintf(stderr, "Groups only work in Identi.ca.\n");
			goto exit;
		}
	} else {
		if (!session->consumer_key || !session->consumer_secret)
			session->no_oauth = 1;
	}

	if (session->no_oauth) {
		if (!session->account) {
			fprintf(stdout, "Enter account for %s: ",
				session->hostname);
			session->account = session->readline(NULL);
		}
		if (!session->password) {
			read_password(password, sizeof(password),
				      session->hostname);
			session->password = strdup(password);
		}
	} else if (!session->guest) {
		if (!session->access_token_key ||
		    !session->access_token_secret) {
			request_access_token(session);
			goto exit;
		}
	}

	if (session->action == ACTION_UNKNOWN) {
		fprintf(stderr, "Unknown action, valid actions are:\n"
			"'update', 'friends', 'public', 'replies', 'group' or 'user'.\n");
		goto exit;
	}

	if (session->action == ACTION_GROUP && !session->group) {
		fprintf(stdout, "Enter group name: ");
		session->group = session->readline(NULL);
	}

	if (session->action == ACTION_RETWEET) {
		if (!session->retweet) {
			char *rtid;

			fprintf(stdout, "Status ID to retweet: ");
			rtid = get_string_from_stdin();
			session->retweet = zalloc(strlen(rtid) + 10);
			sprintf(session->retweet, "%s", rtid);
			free(rtid);
		}

		if (!session->retweet || strlen(session->retweet) == 0) {
			dbg("no retweet?\n");
			return -1;
		}

		dbg("retweet ID = %s\n", session->retweet);
	}

	if (session->action == ACTION_UPDATE) {
		if (session->background || !session->interactive)
			tweet = get_string_from_stdin();
		else
			tweet = session->readline("tweet: ");
		if (!tweet || strlen(tweet) == 0) {
			dbg("no tweet?\n");
			return -1;
		}

		if (session->shrink_urls)
			tweet = shrink_urls(tweet);

		session->tweet = zalloc(strlen(tweet) + 10);
		if (session->bash)
			sprintf(session->tweet, "%c %s",
				getuid() ? '$' : '#', tweet);
		else
			sprintf(session->tweet, "%s", tweet);

		free(tweet);
		dbg("tweet = %s\n", session->tweet);
	}

	if (session->page == 0)
		session->page = 1;
	dbg("config file = %s\n", session->configfile);
	dbg("host = %d\n", session->host);
	dbg("action = %d\n", session->action);

	/* fork ourself so that the main shell can get on
	 * with it's life as we try to connect and handle everything
	 */
	if (session->background) {
		child = fork();
		if (child) {
			dbg("child is %d\n", child);
			exit(0);
		}
	}

	retval = send_request(session);
	if (retval && !session->background)
		fprintf(stderr, "operation failed\n");

	log_session(session, retval);
exit:
	session_readline_cleanup(session);
	session_free(session);
	return retval;;
}
Example #16
0
int main(int argc, char **argv)
{
	int ret = EXIT_FAILURE;
	struct vpn_config cfg;
	char *config_file = "/etc/openfortivpn/config";
	char *host, *username = NULL, *password = NULL;
	char *port_str;
	long int port;

	init_logging();

	// Set defaults
	init_vpn_config(&cfg);
	cfg.set_routes = 1;
	cfg.set_dns = 1;
	cfg.verify_cert = 1;
	cfg.insecure_ssl = 0;
	cfg.pppd_use_peerdns = 1;

	struct option long_options[] = {
		{"help",            no_argument,       0, 'h'},
		{"version",         no_argument,       0, 0},
		{"config",          required_argument, 0, 'c'},
		{"realm",           required_argument, 0, 0},
		{"username",        required_argument, 0, 'u'},
		{"password",        required_argument, 0, 'p'},
		{"no-routes",       no_argument, &cfg.set_routes, 0},
		{"no-dns",          no_argument, &cfg.set_dns, 0},
		{"pppd-no-peerdns", no_argument, &cfg.pppd_use_peerdns, 0},
		{"ca-file",         required_argument, 0, 0},
		{"user-cert",       required_argument, 0, 0},
		{"user-key",        required_argument, 0, 0},
		{"trusted-cert",    required_argument, 0, 0},
		{"insecure-ssl",    no_argument, &cfg.insecure_ssl, 1},
		{"cipher-list",     required_argument, 0, 0},
		{"pppd-log",        required_argument, 0, 0},
		{"pppd-plugin",     required_argument, 0, 0},
		{"plugin",          required_argument, 0, 0}, // deprecated
		{0, 0, 0, 0}
	};

	while (1) {
		/* getopt_long stores the option index here. */
		int c, option_index = 0;

		c = getopt_long(argc, argv, "hvqc:u:p:",
		                long_options, &option_index);

		/* Detect the end of the options. */
		if (c == -1)
			break;

		switch (c) {
		case 0:
			/* If this option set a flag, do nothing else now. */
			if (long_options[option_index].flag != 0)
				break;
			if (strcmp(long_options[option_index].name,
			           "version") == 0) {
				printf(VERSION "\n");
				ret = EXIT_SUCCESS;
				goto exit;
			}
			if (strcmp(long_options[option_index].name,
			           "pppd-log") == 0) {
				cfg.pppd_log = optarg;
				break;
			}
			if (strcmp(long_options[option_index].name,
			           "pppd-plugin") == 0) {
				cfg.pppd_plugin = optarg;
				break;
			}
			// --plugin is deprecated, --pppd-plugin should be used
			if (cfg.pppd_plugin == NULL &&
			    strcmp(long_options[option_index].name,
			           "plugin") == 0) {
				cfg.pppd_plugin = optarg;
				break;
			}
			if (strcmp(long_options[option_index].name,
			           "ca-file") == 0) {
				cfg.ca_file = strdup(optarg);
				break;
			}
			if (strcmp(long_options[option_index].name,
			           "user-cert") == 0) {
				cfg.user_cert = strdup(optarg);
				break;
			}
			if (strcmp(long_options[option_index].name,
			           "user-key") == 0) {
				cfg.user_key = strdup(optarg);
				break;
			}
			if (strcmp(long_options[option_index].name,
			           "realm") == 0) {
				strncpy(cfg.realm, optarg, FIELD_SIZE);
				cfg.realm[FIELD_SIZE] = '\0';
				break;
			}
			if (strcmp(long_options[option_index].name,
			           "trusted-cert") == 0) {
				if (add_trusted_cert(&cfg, optarg))
					log_warn("Could not add certificate "
					         "digest to whitelist.\n");
				break;
			}
			if (strcmp(long_options[option_index].name,
			           "cipher-list") == 0) {
				cfg.cipher_list = strdup(optarg);
				break;
			}
			goto user_error;
		case 'h':
			printf(HELP);
			ret = EXIT_SUCCESS;
			goto exit;
		case 'v':
			increase_verbosity();
			break;
		case 'q':
			decrease_verbosity();
			break;
		case 'c':
			config_file = optarg;
			break;
		case 'u':
			username = optarg;
			break;
		case 'p':
			password = optarg;
			break;
		default:
			goto user_error;
		}
	}

	if (optind < argc - 1 || optind > argc)
		goto user_error;

	if (password != NULL)
		log_warn("You should not pass the password on the command "
		         "line. Type it interactively or use a config file "
		         "instead.\n");

	// Load config file
	if (config_file[0] != '\0') {
		ret = load_config(&cfg, config_file);
		if (ret == 0)
			log_debug("Loaded config file \"%s\".\n", config_file);
		else
			log_warn("Could not load config file \"%s\" (%s).\n",
			         config_file, err_cfg_str(ret));
	}

	// Read host and port from the command line
	if (optind == argc - 1) {
		host = argv[optind++];
		port_str = strchr(host, ':');
		if (port_str == NULL) {
			log_error("Specify a valid host:port couple.\n");
			goto user_error;
		}
		port_str[0] = '\0';
		strncpy(cfg.gateway_host, host, FIELD_SIZE);
		cfg.gateway_host[FIELD_SIZE] = '\0';
		port_str++;
		port = strtol(port_str, NULL, 0);
		if (port <= 0 || port > 65535) {
			log_error("Specify a valid port.\n");
			goto user_error;
		}
		cfg.gateway_port = port;
	}
	// Read username and password from the command line
	if (username != NULL) {
		strncpy(cfg.username, username, FIELD_SIZE);
		cfg.username[FIELD_SIZE] = '\0';
	}
	if (password != NULL) {
		strncpy(cfg.password, password, FIELD_SIZE);
		cfg.password[FIELD_SIZE] = '\0';
	}

	// Check host and port
	if (cfg.gateway_host[0] == '\0' || cfg.gateway_port == 0) {
		log_error("Specify a valid host:port couple.\n");
		goto user_error;
	}
	// Check username
	if (cfg.username[0] == '\0') {
		log_error("Specify an username.\n");
		goto user_error;
	}
	// If no password given, interactively ask user
	if (cfg.password[0] == '\0')
		read_password("VPN account password: "******"Specify a password.\n");
		goto user_error;
	}

	log_debug("Config host = \"%s\"\n", cfg.gateway_host);
	log_debug("Config realm = \"%s\"\n", cfg.realm);
	log_debug("Config port = \"%d\"\n", cfg.gateway_port);
	log_debug("Config username = \"%s\"\n", cfg.username);
	log_debug("Config password = \"%s\"\n", "********");

	if (geteuid() != 0)
		log_warn("This process was not spawned with root "
		         "privileges, this will probably not work.\n");

	if (run_tunnel(&cfg) == 0)
		ret = EXIT_SUCCESS;
	goto exit;

user_error:
	fprintf(stderr, USAGE);
exit:
	destroy_vpn_config(&cfg);
	exit(ret);
}
Example #17
0
/* Client program */
int
main(int argc, char *argv[])
{
	char server[64];
	char fullhostname[64];
	char domain[16];
	char password[64];
	char shell[128];
	char directory[32];
	BOOL prompt_password, rdp_retval = False;
	struct passwd *pw;
	uint32 flags;
	char *p;
	int c;
	int username_option = 0;

	flags = RDP_LOGON_NORMAL;
	prompt_password = False;
	domain[0] = password[0] = shell[0] = directory[0] = 0;
	strcpy(keymapname, "en-us");

#ifdef RDP2VNC
#define VNCOPT "V:Q:"
#else
#define VNCOPT
#endif

	while ((c = getopt(argc, argv, VNCOPT "u:d:s:c:p:n:k:g:fbeEmCDKS:T:a:r:045h?")) != -1)
	{
		switch (c)
		{
#ifdef RDP2VNC
			case 'V':
				rfb_port = strtol(optarg, NULL, 10);
				if (rfb_port < 100)
					rfb_port += 5900;
				break;

			case 'Q':
				defer_time = strtol(optarg, NULL, 10);
				if (defer_time < 0)
					defer_time = 0;
				break;
#endif

			case 'u':
				STRNCPY(g_username, optarg, sizeof(g_username));
				username_option = 1;
				break;

			case 'd':
				STRNCPY(domain, optarg, sizeof(domain));
				break;

			case 's':
				STRNCPY(shell, optarg, sizeof(shell));
				break;

			case 'c':
				STRNCPY(directory, optarg, sizeof(directory));
				break;

			case 'p':
				if ((optarg[0] == '-') && (optarg[1] == 0))
				{
					prompt_password = True;
					break;
				}

				STRNCPY(password, optarg, sizeof(password));
				flags |= RDP_LOGON_AUTO;

				/* try to overwrite argument so it won't appear in ps */
				p = optarg;
				while (*p)
					*(p++) = 'X';
				break;

			case 'n':
				STRNCPY(hostname, optarg, sizeof(hostname));
				break;

			case 'k':
				STRNCPY(keymapname, optarg, sizeof(keymapname));
				break;

			case 'g':
				if (!strcmp(optarg, "workarea"))
				{
					g_width = g_height = 0;
					break;
				}

				g_width = strtol(optarg, &p, 10);
				if (g_width <= 0)
				{
					error("invalid geometry\n");
					return 1;
				}

				if (*p == 'x')
					g_height = strtol(p + 1, NULL, 10);

				if (g_height <= 0)
				{
					error("invalid geometry\n");
					return 1;
				}

				if (*p == '%')
					g_width = -g_width;

				break;

			case 'f':
				g_fullscreen = True;
				break;

			case 'b':
				g_orders = False;
				break;

			case 'e':
				g_encryption = False;
				break;
			case 'E':
				packet_encryption = False;
				break;
			case 'm':
				g_sendmotion = False;
				break;

			case 'C':
				g_owncolmap = True;
				break;

			case 'D':
				g_hide_decorations = True;
				break;

			case 'K':
				g_grab_keyboard = False;
				break;

			case 'S':
				if (!strcmp(optarg, "standard"))
				{
					g_win_button_size = 18;
					break;
				}

				g_win_button_size = strtol(optarg, &p, 10);

				if (*p)
				{
					error("invalid button size\n");
					return 1;
				}

				break;

			case 'T':
				STRNCPY(g_title, optarg, sizeof(g_title));
				break;

			case 'a':
				g_server_bpp = strtol(optarg, NULL, 10);
				if (g_server_bpp != 8 && g_server_bpp != 16 && g_server_bpp != 15
				    && g_server_bpp != 24)
				{
					error("invalid server bpp\n");
					return 1;
				}
				break;

			case 'r':
				if (!strcmp(optarg, "sound"))
#ifdef WITH_RDPSND
					g_rdpsnd = True;
#else
					warning("Not compiled with sound support");
#endif
				break;

			case '0':
				g_console_session = True;
				break;

			case '4':
				g_use_rdp5 = False;
				break;

			case '5':
				g_use_rdp5 = True;
				break;

			case 'h':
			case '?':
			default:
				usage(argv[0]);
				return 1;
		}
	}

	if (argc - optind < 1)
	{
		usage(argv[0]);
		return 1;
	}

	STRNCPY(server, argv[optind], sizeof(server));
	parse_server_and_port(server);

	if (!username_option)
	{
		pw = getpwuid(getuid());
		if ((pw == NULL) || (pw->pw_name == NULL))
		{
			error("could not determine username, use -u\n");
			return 1;
		}

		STRNCPY(g_username, pw->pw_name, sizeof(g_username));
	}

	if (hostname[0] == 0)
	{
		if (gethostname(fullhostname, sizeof(fullhostname)) == -1)
		{
			error("could not determine local hostname, use -n\n");
			return 1;
		}

		p = strchr(fullhostname, '.');
		if (p != NULL)
			*p = 0;

		STRNCPY(hostname, fullhostname, sizeof(hostname));
	}

	if (prompt_password && read_password(password, sizeof(password)))
		flags |= RDP_LOGON_AUTO;

	if (g_title[0] == 0)
	{
		strcpy(g_title, "rdesktop - ");
		strncat(g_title, server, sizeof(g_title) - sizeof("rdesktop - "));
	}

#ifdef RDP2VNC
	rdp2vnc_connect(server, flags, domain, password, shell, directory);
	return 0;
#else

	if (!ui_init())
		return 1;

#ifdef WITH_RDPSND
	if (g_rdpsnd)
		rdpsnd_init();
#endif
	/* rdpdr_init(); */

	if (!rdp_connect(server, flags, domain, password, shell, directory))
		return 1;

	/* By setting encryption to False here, we have an encrypted login 
	   packet but unencrypted transfer of other packets */
	if (!packet_encryption)
		g_encryption = False;


	DEBUG(("Connection successful.\n"));
	memset(password, 0, sizeof(password));

	if (ui_create_window())
	{
		rdp_retval = rdp_main_loop();
		ui_destroy_window();
	}

	DEBUG(("Disconnecting...\n"));
	rdp_disconnect();
	ui_deinit();

	if (True == rdp_retval)
		return 0;
	else
		return 2;

#endif

}
Example #18
0
int main(int argc, char *argv[])
{
    int rc=0, passlen=0;
    FILE *outfp = NULL;
    char outfile[1024];
    unsigned char pass_input[MAX_PASSWD_BUF],
                  pass[MAX_PASSWD_BUF];
    int file_count = 0;
    unsigned char bom[2];
    int password_acquired = 0;

    while ((rc = getopt(argc, argv, "vhg:p:o:")) != -1)
    {
        switch (rc)
        {
            case 'h':
                usage(argv[0]);
                return 0;
            case 'v':
                version(argv[0]);
                return 0;
            case 'g':
                if (password_acquired)
                {
                    fprintf(stderr, "Error: password supplied twice\n");
                    return -1;
                }
                if (optarg != 0)
                {
                    passlen = generate_password(atoi((char*) optarg),
                                                pass);
                    if (passlen < 0)
                    {
                        return -1;
                    }
                }
                password_acquired = 1;
                break;
            case 'p':
                if (password_acquired)
                {
                    fprintf(stderr, "Error: password supplied twice\n");
                    return -1;
                }
                if (optarg != 0)
                {
                    passlen = passwd_to_utf16(  (unsigned char*) optarg,
                                                strlen((char *)optarg),
                                                MAX_PASSWD_LEN,
                                                pass);
                    if (passlen < 0)
                    {
                        return -1;
                    }
                }
                password_acquired = 1;
                break;
            default:
                fprintf(stderr, "Error: Unknown option '%c'\n", rc);
        }
    }
    
    file_count = argc - optind;
    if (file_count != 1)
    {
        fprintf(stderr, "Error: A single output file must be specified.\n");
        usage(argv[0]);
        // For security reasons, erase the password
        memset(pass, 0, MAX_PASSWD_BUF);
        return -1;
    }
    else
    {
        /* What is the filename for the key file? */
        strncpy(outfile, argv[optind++], 1024);
        outfile[1023] = '\0';
    }

    // Prompt for password if not provided on the command line
    if (passlen == 0)
    {
        passlen = read_password(pass_input, ENC);

        switch (passlen)
        {
            case 0: //no password in input
                fprintf(stderr, "Error: No password supplied.\n");
                return -1;
            case AESCRYPT_READPWD_FOPEN:
            case AESCRYPT_READPWD_FILENO:
            case AESCRYPT_READPWD_TCGETATTR:
            case AESCRYPT_READPWD_TCSETATTR:
            case AESCRYPT_READPWD_FGETC:
            case AESCRYPT_READPWD_TOOLONG:
                fprintf(stderr, "Error in read_password: %s.\n",
                        read_password_error(passlen));
                return -1;
            case AESCRYPT_READPWD_NOMATCH:
                fprintf(stderr, "Error: Passwords don't match.\n");
                return -1;
        }

        passlen = passwd_to_utf16(  pass_input,
                                    strlen((char*) pass_input),
                                    MAX_PASSWD_LEN,
                                    pass);

        if (passlen < 0)
        {
            // For security reasons, erase the password
            memset(pass, 0, MAX_PASSWD_BUF);
            return -1;
        }
    }

    if(!strcmp("-", outfile))
    {
        outfp = stdout;
    }
    else if ((outfp = fopen(outfile, "w")) == NULL)
    {
        fprintf(stderr, "Error opening output file %s : ", outfile);
        perror("");
        // For security reasons, erase the password
        memset(pass, 0, MAX_PASSWD_BUF);
        return  -1;
    }

    /* Write the BOM.  AES Crypt uses UTF-16LE */
    bom[0] = 0xFF;
    bom[1] = 0xFE;
    if (fwrite(bom, 1, 2, outfp) != 2)
    {
        fprintf(stderr, "Error: Could not write BOM to password file.\n");
        if (strcmp("-",outfile))
        {
            fclose(outfp);
        }
        cleanup(outfile);
        return  -1;
    }
    
    if (fwrite(pass, 1, passlen, outfp) != passlen)
    {
        fprintf(stderr, "Error: Could not write password file.\n");
        if (strcmp("-",outfile))
        {
            fclose(outfp);
        }
        cleanup(outfile);
        return  -1;
    }

    /* Close the output file, so long as it is not stdout */
    if (strcmp("-",outfile))
    {
        fclose(outfp);
    }

    // For security reasons, erase the password
    memset(pass, 0, MAX_PASSWD_BUF);

    return rc;
}
Example #19
0
/* Client program */
int
main(int argc, char *argv[])
{
	char server[256];
	char fullhostname[64];
	char domain[256];
	char shell[256];
	char directory[256];
	RD_BOOL prompt_password, deactivated;
	struct passwd *pw;
	uint32 flags, ext_disc_reason = 0;
	char *p;
	int c;
	char *locale = NULL;
	int username_option = 0;
	RD_BOOL geometry_option = False;
#ifdef WITH_RDPSND
	char *rdpsnd_optarg = NULL;
#endif

#ifdef HAVE_LOCALE_H
	/* Set locale according to environment */
	locale = setlocale(LC_ALL, "");
	if (locale)
	{
		locale = xstrdup(locale);
	}

#endif

	/* Ignore SIGPIPE, since we are using popen() */
	struct sigaction act;
	memset(&act, 0, sizeof(act));
	act.sa_handler = SIG_IGN;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaction(SIGPIPE, &act, NULL);

	/* setup default flags for TS_INFO_PACKET */
	flags = RDP_INFO_MOUSE | RDP_INFO_DISABLECTRLALTDEL
		| RDP_INFO_UNICODE | RDP_INFO_MAXIMIZESHELL | RDP_INFO_ENABLEWINDOWSKEY;

	prompt_password = False;
	g_seamless_spawn_cmd[0] = domain[0] = g_password[0] = shell[0] = directory[0] = 0;
	g_embed_wnd = 0;

	g_num_devices = 0;

#ifdef RDP2VNC
#define VNCOPT "V:Q:"
#else
#define VNCOPT
#endif
	while ((c = getopt(argc, argv,
			   VNCOPT "A:u:L:d:s:c:p:n:k:g:o:fbBeEitmzCDKS:T:UNX:a:x:Pr:045h?")) != -1)
	{
		switch (c)
		{
#ifdef RDP2VNC
			case 'V':
				rfb_port = strtol(optarg, NULL, 10);
				if (rfb_port < 100)
					rfb_port += 5900;
				break;

			case 'Q':
				defer_time = strtol(optarg, NULL, 10);
				if (defer_time < 0)
					defer_time = 0;
				break;
#endif

			case 'A':
				g_seamless_rdp = True;
				STRNCPY(g_seamless_shell, optarg, sizeof(g_seamless_shell));
				break;

			case 'u':
				g_username = (char *) xmalloc(strlen(optarg) + 1);
				STRNCPY(g_username, optarg, strlen(optarg) + 1);
				username_option = 1;
				break;

			case 'L':
#ifdef HAVE_ICONV
				STRNCPY(g_codepage, optarg, sizeof(g_codepage));
#else
				error("iconv support not available\n");
#endif
				break;

			case 'd':
				STRNCPY(domain, optarg, sizeof(domain));
				break;

			case 's':
				STRNCPY(shell, optarg, sizeof(shell));
				g_seamless_persistent_mode = False;
				break;

			case 'c':
				STRNCPY(directory, optarg, sizeof(directory));
				break;

			case 'p':
				if ((optarg[0] == '-') && (optarg[1] == 0))
				{
					prompt_password = True;
					break;
				}

				STRNCPY(g_password, optarg, sizeof(g_password));
				flags |= RDP_INFO_AUTOLOGON;

				/* try to overwrite argument so it won't appear in ps */
				p = optarg;
				while (*p)
					*(p++) = 'X';
				break;
#ifdef WITH_SCARD
			case 'i':
				flags |= RDP_INFO_PASSWORD_IS_SC_PIN;
				g_use_password_as_pin = True;
				break;
#endif
			case 't':
				g_use_ctrl = False;
				break;

			case 'n':
				STRNCPY(g_hostname, optarg, sizeof(g_hostname));
				break;

			case 'k':
				STRNCPY(g_keymapname, optarg, sizeof(g_keymapname));
				break;

			case 'g':
				geometry_option = True;
				g_fullscreen = False;
				if (!strcmp(optarg, "workarea"))
				{
					g_sizeopt = 1;
					break;
				}

				g_width = strtol(optarg, &p, 10);
				if (g_width <= 0)
				{
					error("invalid geometry\n");
					return EX_USAGE;
				}

				if (*p == 'x')
					g_height = strtol(p + 1, &p, 10);

				if (g_height <= 0)
				{
					error("invalid geometry\n");
					return EX_USAGE;
				}

				if (*p == '%')
				{
					g_sizeopt = -g_width;
					g_width = 800;
					p++;
				}

				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 2 : 1;
					g_xpos = strtol(p, &p, 10);

				}
				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 4 : 1;
					g_ypos = strtol(p, NULL, 10);
				}

				break;

			case 'f':
				g_fullscreen = True;
				break;

			case 'b':
				g_bitmap_cache = False;
				break;

			case 'B':
				g_ownbackstore = False;
				break;

			case 'e':
				g_encryption_initial = g_encryption = False;
				break;
			case 'E':
				g_packet_encryption = False;
				break;
			case 'm':
				g_sendmotion = False;
				break;

			case 'C':
				g_owncolmap = True;
				break;

			case 'D':
				g_hide_decorations = True;
				break;

			case 'K':
				g_grab_keyboard = False;
				break;

			case 'U':
				g_ungrab_on_ctrlalt = True;
				break;

			case 'S':
				if (!strcmp(optarg, "standard"))
				{
					g_win_button_size = 18;
					break;
				}

				g_win_button_size = strtol(optarg, &p, 10);

				if (*p)
				{
					error("invalid button size\n");
					return EX_USAGE;
				}

				break;

			case 'T':
				STRNCPY(g_title, optarg, sizeof(g_title));
				break;

			case 'N':
				g_numlock_sync = True;
				break;

			case 'X':
				g_embed_wnd = strtol(optarg, NULL, 0);
				break;

			case 'a':
				g_server_depth = strtol(optarg, NULL, 10);
				if (g_server_depth != 8 &&
				    g_server_depth != 16 &&
				    g_server_depth != 15 && g_server_depth != 24
				    && g_server_depth != 32)
				{
					error("Invalid server colour depth.\n");
					return EX_USAGE;
				}
				break;

			case 'z':
				DEBUG(("rdp compression enabled\n"));
				flags |= (RDP_INFO_COMPRESSION | RDP_INFO_COMPRESSION2);
				break;

			case 'x':
				if (str_startswith(optarg, "m"))	/* modem */
				{
					g_rdp5_performanceflags = RDP5_NO_CURSOR_SHADOW |
						RDP5_NO_WALLPAPER | RDP5_NO_FULLWINDOWDRAG |
						RDP5_NO_MENUANIMATIONS | RDP5_NO_THEMING;
				}
				else if (str_startswith(optarg, "b"))	/* broadband */
				{
					g_rdp5_performanceflags =
						RDP5_NO_CURSOR_SHADOW | RDP5_NO_WALLPAPER;
				}
				else if (str_startswith(optarg, "l"))	/* lan */
				{
					g_rdp5_performanceflags =
						RDP5_NO_CURSOR_SHADOW | RDP5_DISABLE_NOTHING;
				}
				else
				{
					g_rdp5_performanceflags =
						RDP5_NO_CURSOR_SHADOW | strtol(optarg, NULL, 16);
				}
				break;

			case 'P':
				g_bitmap_cache_persist_enable = True;
				break;

			case 'r':

				if (str_startswith(optarg, "sound"))
				{
					optarg += 5;

					if (*optarg == ':')
					{
						optarg++;
						while ((p = next_arg(optarg, ',')))
						{
							if (str_startswith(optarg, "remote"))
								flags |= RDP_INFO_REMOTE_CONSOLE_AUDIO;

							if (str_startswith(optarg, "local"))
#ifdef WITH_RDPSND
							{
								rdpsnd_optarg =
									next_arg(optarg, ':');
								g_rdpsnd = True;
							}

#else
								warning("Not compiled with sound support\n");
#endif

							if (str_startswith(optarg, "off"))
#ifdef WITH_RDPSND
								g_rdpsnd = False;
#else
								warning("Not compiled with sound support\n");
#endif

							optarg = p;
						}
					}
					else
					{
#ifdef WITH_RDPSND
						g_rdpsnd = True;
#else
						warning("Not compiled with sound support\n");
#endif
					}
				}
				else if (str_startswith(optarg, "disk"))
				{
					/* -r disk:h:=/mnt/floppy */
					disk_enum_devices(&g_num_devices, optarg + 4);
				}
				else if (str_startswith(optarg, "comport"))
				{
					serial_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "lspci"))
				{
					g_lspci_enabled = True;
				}
				else if (str_startswith(optarg, "lptport"))
				{
					parallel_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "printer"))
				{
					printer_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "clientname"))
				{
					g_rdpdr_clientname = xmalloc(strlen(optarg + 11) + 1);
					strcpy(g_rdpdr_clientname, optarg + 11);
				}
				else if (str_startswith(optarg, "clipboard"))
				{
					optarg += 9;

					if (*optarg == ':')
					{
						optarg++;

						if (str_startswith(optarg, "off"))
							g_rdpclip = False;
						else
							cliprdr_set_mode(optarg);
					}
					else
						g_rdpclip = True;
				}
				else if (strncmp("scard", optarg, 5) == 0)
				{
#ifdef WITH_SCARD
					scard_enum_devices(&g_num_devices, optarg + 5);
#else
					warning("Not compiled with smartcard support\n");
#endif
				}
				else
				{
					warning("Unknown -r argument\n\n\tPossible arguments are: comport, disk, lptport, printer, sound, clipboard, scard\n");
				}
				break;

			case '0':
				g_console_session = True;
				break;

			case '4':
				g_rdp_version = RDP_V4;
				break;

			case '5':
				g_rdp_version = RDP_V5;
				break;
#if WITH_SCARD
			case 'o':
				{
					char *p = strchr(optarg, '=');
					if (p == NULL)
					{
						warning("Skipping option '%s' specified, lacks name=value format.\n");
						continue;
					}

					if (strncmp(optarg, "sc-csp-name", strlen("sc-scp-name")) ==
					    0)
						g_sc_csp_name = strdup(p + 1);
					else if (strncmp
						 (optarg, "sc-reader-name",
						  strlen("sc-reader-name")) == 0)
						g_sc_reader_name = strdup(p + 1);
					else if (strncmp
						 (optarg, "sc-card-name",
						  strlen("sc-card-name")) == 0)
						g_sc_card_name = strdup(p + 1);
					else if (strncmp
						 (optarg, "sc-container-name",
						  strlen("sc-container-name")) == 0)
						g_sc_container_name = strdup(p + 1);

				}
				break;
#endif
			case 'h':
			case '?':
			default:
				usage(argv[0]);
				return EX_USAGE;
		}
	}

	if (argc - optind != 1)
	{
		usage(argv[0]);
		return EX_USAGE;
	}

	STRNCPY(server, argv[optind], sizeof(server));
	parse_server_and_port(server);

	if (g_seamless_rdp)
	{
		if (shell[0])
			STRNCPY(g_seamless_spawn_cmd, shell, sizeof(g_seamless_spawn_cmd));

		STRNCPY(shell, g_seamless_shell, sizeof(shell));

		if (g_win_button_size)
		{
			error("You cannot use -S and -A at the same time\n");
			return EX_USAGE;
		}
		g_rdp5_performanceflags &= ~RDP5_NO_FULLWINDOWDRAG;
		if (geometry_option)
		{
			error("You cannot use -g and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_fullscreen)
		{
			error("You cannot use -f and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_hide_decorations)
		{
			error("You cannot use -D and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_embed_wnd)
		{
			error("You cannot use -X and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_rdp_version < RDP_V5)
		{
			error("You cannot use -4 and -A at the same time\n");
			return EX_USAGE;
		}
		g_sizeopt = -100;
		g_grab_keyboard = False;
	}

	if (!username_option)
	{
		pw = getpwuid(getuid());
		if ((pw == NULL) || (pw->pw_name == NULL))
		{
			error("could not determine username, use -u\n");
			return EX_OSERR;
		}
		/* +1 for trailing \0 */
		int pwlen = strlen(pw->pw_name) + 1;
		g_username = (char *) xmalloc(pwlen);
		STRNCPY(g_username, pw->pw_name, pwlen);
	}

#ifdef HAVE_ICONV
	if (g_codepage[0] == 0)
	{
		if (setlocale(LC_CTYPE, ""))
		{
			STRNCPY(g_codepage, nl_langinfo(CODESET), sizeof(g_codepage));
		}
		else
		{
			STRNCPY(g_codepage, DEFAULT_CODEPAGE, sizeof(g_codepage));
		}
	}
#endif

	if (g_hostname[0] == 0)
	{
		if (gethostname(fullhostname, sizeof(fullhostname)) == -1)
		{
			error("could not determine local hostname, use -n\n");
			return EX_OSERR;
		}

		p = strchr(fullhostname, '.');
		if (p != NULL)
			*p = 0;

		STRNCPY(g_hostname, fullhostname, sizeof(g_hostname));
	}

	if (g_keymapname[0] == 0)
	{
		if (locale && xkeymap_from_locale(locale))
		{
			fprintf(stderr, "Autoselected keyboard map %s\n", g_keymapname);
		}
		else
		{
			STRNCPY(g_keymapname, "en-us", sizeof(g_keymapname));
		}
	}
	if (locale)
		xfree(locale);


	if (prompt_password && read_password(g_password, sizeof(g_password)))
		flags |= RDP_INFO_AUTOLOGON;

	if (g_title[0] == 0)
	{
		strcpy(g_title, "rdesktop - ");
		strncat(g_title, server, sizeof(g_title) - sizeof("rdesktop - "));
	}

#ifdef RDP2VNC
	rdp2vnc_connect(server, flags, domain, g_password, shell, directory);
	return EX_OK;
#else

	/* Only startup ctrl functionality is seamless are used for now. */
	if (g_use_ctrl && g_seamless_rdp)
	{
		if (ctrl_init(server, domain, g_username) < 0)
		{
			error("Failed to initialize ctrl mode.");
			exit(1);
		}

		if (ctrl_is_slave())
		{
			fprintf(stdout,
				"rdesktop in slave mode sending command to master process.\n");

			if (g_seamless_spawn_cmd[0])
				return ctrl_send_command("seamless.spawn", g_seamless_spawn_cmd);

			fprintf(stdout, "No command specified to be spawn in seamless mode.\n");
			return EX_USAGE;
		}
	}

	if (!ui_init())
		return EX_OSERR;

#ifdef WITH_RDPSND
	if (!rdpsnd_init(rdpsnd_optarg))
		warning("Initializing sound-support failed!\n");
#endif

	if (g_lspci_enabled)
		lspci_init();

	rdpdr_init();
	g_reconnect_loop = False;
	while (1)
	{
		rdesktop_reset_state();

		if (g_redirect)
		{
			STRNCPY(domain, g_redirect_domain, sizeof(domain));
			xfree(g_username);
			g_username = (char *) xmalloc(strlen(g_redirect_username) + 1);
			STRNCPY(g_username, g_redirect_username, strlen(g_redirect_username) + 1);
			STRNCPY(server, g_redirect_server, sizeof(server));
			flags |= RDP_INFO_AUTOLOGON;

			fprintf(stderr, "Redirected to %s@%s session %d.\n",
				g_redirect_username, g_redirect_server, g_redirect_session_id);

			/* A redirect on SSL from a 2003 WTS will result in a 'connection reset by peer'
			   and therefor we just clear this error before we connect to redirected server.
			 */
			g_network_error = False;
			g_redirect = False;
		}

		ui_init_connection();
		if (!rdp_connect
		    (server, flags, domain, g_password, shell, directory, g_reconnect_loop))
		{

			g_network_error = False;

			if (g_reconnect_loop == False)
				return EX_PROTOCOL;

			/* check if auto reconnect cookie has timed out */
			if (time(NULL) - g_reconnect_random_ts > RECONNECT_TIMEOUT)
			{
				fprintf(stderr, "Tried to reconnect for %d minutes, giving up.\n",
					RECONNECT_TIMEOUT / 60);
				return EX_PROTOCOL;
			}

			sleep(4);
			continue;
		}

		if (g_redirect)
		{
			rdp_disconnect();
			continue;
		}

		/* By setting encryption to False here, we have an encrypted login 
		   packet but unencrypted transfer of other packets */
		if (!g_packet_encryption)
			g_encryption_initial = g_encryption = False;

		DEBUG(("Connection successful.\n"));

		rd_create_ui();
		tcp_run_ui(True);

		deactivated = False;
		g_reconnect_loop = False;
		rdp_main_loop(&deactivated, &ext_disc_reason);

		tcp_run_ui(False);

		DEBUG(("Disconnecting...\n"));
		rdp_disconnect();

		if (g_redirect)
			continue;

		/* handle network error and start autoreconnect */
		if (g_network_error && !deactivated)
		{
			fprintf(stderr,
				"Disconnected due to network error, retrying to reconnect for %d minutes.\n",
				RECONNECT_TIMEOUT / 60);
			g_network_error = False;
			g_reconnect_loop = True;
			continue;
		}

		ui_seamless_end();
		ui_destroy_window();

		/* Enter a reconnect loop if we have a pending resize request */
		if (g_pending_resize)
		{
			g_pending_resize = False;
			g_reconnect_loop = True;
			continue;
		}
		break;
	}

	cache_save_state();
	ui_deinit();

	if (g_user_quit)
		return EXRD_WINDOW_CLOSED;

	return handle_disconnect_reason(deactivated, ext_disc_reason);

#endif
	if (g_redirect_username)
		xfree(g_redirect_username);

	xfree(g_username);
}
Example #20
0
/***************************************************************************
  Function: cgiMain
  Description: 
  Input:  
  Output: 
  Return: 0 OK, other Error
  Others:  none
***************************************************************************/
int cgiMain()
{
    char id[FEATURE_GDGL_ID_LEN + 1]; //12 + terminating null
    char password[FEATURE_GDGL_PASSWD_MAX_LEN + 1]; //16 + terminating null
    char old_alias[FEATURE_GDGL_ACCOUNT_MAX_LEN + 1]; //16 + terminating null
    char new_alias[FEATURE_GDGL_ACCOUNT_MAX_LEN + 1]; //16 + terminating null
	char gateway_id[FEATURE_GDGL_ID_LEN + 1]; //12 + terminating null
	char gateway_passwd[FEATURE_GDGL_PASSWD_MAX_LEN + 1];
	cgiFormResultType cgi_re;
	int res;

	cgiHeaderContentType("application/json"); //MIME

    // Read ID
    res = read_id(gateway_id);
	if (res != 0) {
		client_admin_response("noid", res, clientAdminResultStr[res]);
		mAliasPushToCb(res);
		return res;
	}

	// Check ID
	cgi_re = cgiFormString("id", id, FEATURE_GDGL_ID_LEN + 1);
	res = check_id(cgi_re, id, gateway_id);
	if (res != 0) {
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		mAliasPushToCb(res);
		return res;
	}

	// Read password
	res = read_password(gateway_passwd);
	if (res != 0) {
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		mAliasPushToCb(res);
		return res;
	}

	// Check password
	cgi_re = cgiFormString("password", password, FEATURE_GDGL_PASSWD_MAX_LEN + 1);
	res = check_password(cgi_re, password, gateway_passwd);
	if (res != 0) {
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		mAliasPushToCb(res);
		return res;
	}

	// Check new alias
	cgi_re = cgiFormString("new_alias", new_alias, FEATURE_GDGL_ACCOUNT_MAX_LEN + 1);
	res = check_new_alias(cgi_re, new_alias);
	if (res != 0) {
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		mAliasPushToCb(res);
		return res;
	}

	// Modify alias, first check old, second push to cloud, third write new
	cgi_re = cgiFormString("old_alias", old_alias, FEATURE_GDGL_ACCOUNT_MAX_LEN + 1);
	res = modify_alias(cgi_re, old_alias, new_alias);
	if (res != 0) {
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		mAliasPushToCb(res);
		return res;
	}
	
	res = mAliasPushToCb(0);
	if(res !=0){
		client_admin_response(gateway_id, res, clientAdminResultStr[res]);
		return res;
	}

	//增解逻辑:kill模块gdgl_channel
	system("killall gdgl_channel");
    // all right	
    client_admin_response(gateway_id, clientAdminSuccess, clientAdminResultStr[clientAdminSuccess]);
	return 0;
}
Example #21
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;
}
Example #22
0
/* Client program */
int
main(int argc, char *argv[])
{
	char server[64];
	char fullhostname[64];
	char domain[16];
	char password[64];
	char shell[256];
	char directory[256];
	RD_BOOL prompt_password, deactivated;
	struct passwd *pw;
	uint32 flags, ext_disc_reason = 0;
	char *p;
	int c;
	char *locale = NULL;
	int username_option = 0;
	RD_BOOL geometry_option = False;
	int run_count = 0;	/* Session Directory support */
	RD_BOOL continue_connect = True;	/* Session Directory support */
#ifdef WITH_RDPSND
	char *rdpsnd_optarg = NULL;
#endif

#ifdef HAVE_LOCALE_H
	/* Set locale according to environment */
	locale = setlocale(LC_ALL, "");
	if (locale)
	{
		locale = xstrdup(locale);
	}

#endif
	flags = RDP_LOGON_NORMAL;
	prompt_password = False;
	domain[0] = password[0] = shell[0] = directory[0] = 0;
	g_embed_wnd = 0;

	g_num_devices = 0;

#ifdef RDP2VNC
#define VNCOPT "V:Q:"
#else
#define VNCOPT
#endif

	while ((c = getopt(argc, argv,
			   VNCOPT "Au:L:d:s:c:p:n:k:g:fbBeEmzCDKS:T:NX:a:x:Pr:045h?")) != -1)
	{
		switch (c)
		{
#ifdef RDP2VNC
			case 'V':
				rfb_port = strtol(optarg, NULL, 10);
				if (rfb_port < 100)
					rfb_port += 5900;
				break;

			case 'Q':
				defer_time = strtol(optarg, NULL, 10);
				if (defer_time < 0)
					defer_time = 0;
				break;
#endif

			case 'A':
				g_seamless_rdp = True;
				break;

			case 'u':
				STRNCPY(g_username, optarg, sizeof(g_username));
				username_option = 1;
				break;

			case 'L':
#ifdef HAVE_ICONV
				STRNCPY(g_codepage, optarg, sizeof(g_codepage));
#else
				error("iconv support not available\n");
#endif
				break;

			case 'd':
				STRNCPY(domain, optarg, sizeof(domain));
				break;

			case 's':
				STRNCPY(shell, optarg, sizeof(shell));
				break;

			case 'c':
				STRNCPY(directory, optarg, sizeof(directory));
				break;

			case 'p':
				if ((optarg[0] == '-') && (optarg[1] == 0))
				{
					prompt_password = True;
					break;
				}

				STRNCPY(password, optarg, sizeof(password));
				flags |= RDP_LOGON_AUTO;

				/* try to overwrite argument so it won't appear in ps */
				p = optarg;
				while (*p)
					*(p++) = 'X';
				break;

			case 'n':
				STRNCPY(g_hostname, optarg, sizeof(g_hostname));
				break;

			case 'k':
				STRNCPY(g_keymapname, optarg, sizeof(g_keymapname));
				break;

			case 'g':
				geometry_option = True;
				g_fullscreen = False;
				if (!strcmp(optarg, "workarea"))
				{
					g_width = g_height = 0;
					break;
				}

				g_width = strtol(optarg, &p, 10);
				if (g_width <= 0)
				{
					error("invalid geometry\n");
					return 1;
				}

				if (*p == 'x')
					g_height = strtol(p + 1, &p, 10);

				if (g_height <= 0)
				{
					error("invalid geometry\n");
					return 1;
				}

				if (*p == '%')
				{
					g_width = -g_width;
					p++;
				}

				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 2 : 1;
					g_xpos = strtol(p, &p, 10);

				}
				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 4 : 1;
					g_ypos = strtol(p, NULL, 10);
				}

				break;

			case 'f':
				g_fullscreen = True;
				break;

			case 'b':
				g_bitmap_cache = False;
				break;

			case 'B':
				g_ownbackstore = False;
				break;

			case 'e':
				g_encryption = False;
				break;
			case 'E':
				g_packet_encryption = False;
				break;
			case 'm':
				g_sendmotion = False;
				break;

			case 'C':
				g_owncolmap = True;
				break;

			case 'D':
				g_hide_decorations = True;
				break;

			case 'K':
				g_grab_keyboard = False;
				break;

			case 'S':
				if (!strcmp(optarg, "standard"))
				{
					g_win_button_size = 18;
					break;
				}

				g_win_button_size = strtol(optarg, &p, 10);

				if (*p)
				{
					error("invalid button size\n");
					return 1;
				}

				break;

			case 'T':
				STRNCPY(g_title, optarg, sizeof(g_title));
				break;

			case 'N':
				g_numlock_sync = True;
				break;

			case 'X':
				g_embed_wnd = strtol(optarg, NULL, 0);
				break;

			case 'a':
				g_server_depth = strtol(optarg, NULL, 10);
				if (g_server_depth != 8 &&
				    g_server_depth != 16 &&
				    g_server_depth != 15 && g_server_depth != 24
				    && g_server_depth != 32)
				{
					error("Invalid server colour depth.\n");
					return 1;
				}
				break;

			case 'z':
				DEBUG(("rdp compression enabled\n"));
				flags |= (RDP_LOGON_COMPRESSION | RDP_LOGON_COMPRESSION2);
				break;

			case 'x':
				if (str_startswith(optarg, "m"))	/* modem */
				{
					g_rdp5_performanceflags =
						RDP5_NO_WALLPAPER | RDP5_NO_FULLWINDOWDRAG |
						RDP5_NO_MENUANIMATIONS | RDP5_NO_THEMING;
				}
				else if (str_startswith(optarg, "b"))	/* broadband */
				{
					g_rdp5_performanceflags = RDP5_NO_WALLPAPER;
				}
				else if (str_startswith(optarg, "l"))	/* lan */
				{
					g_rdp5_performanceflags = RDP5_DISABLE_NOTHING;
				}
				else
				{
					g_rdp5_performanceflags = strtol(optarg, NULL, 16);
				}
				break;

			case 'P':
				g_bitmap_cache_persist_enable = True;
				break;

			case 'r':

				if (str_startswith(optarg, "sound"))
				{
					optarg += 5;

					if (*optarg == ':')
					{
						optarg++;
						while ((p = next_arg(optarg, ',')))
						{
							if (str_startswith(optarg, "remote"))
								flags |= RDP_LOGON_LEAVE_AUDIO;

							if (str_startswith(optarg, "local"))
#ifdef WITH_RDPSND
							{
								rdpsnd_optarg =
									next_arg(optarg, ':');
								g_rdpsnd = True;
							}

#else
								warning("Not compiled with sound support\n");
#endif

							if (str_startswith(optarg, "off"))
#ifdef WITH_RDPSND
								g_rdpsnd = False;
#else
								warning("Not compiled with sound support\n");
#endif

							optarg = p;
						}
					}
					else
					{
#ifdef WITH_RDPSND
						g_rdpsnd = True;
#else
						warning("Not compiled with sound support\n");
#endif
					}
				}
				else if (str_startswith(optarg, "disk"))
				{
					/* -r disk:h:=/mnt/floppy */
					disk_enum_devices(&g_num_devices, optarg + 4);
				}
				else if (str_startswith(optarg, "comport"))
				{
					serial_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "lspci"))
				{
					g_lspci_enabled = True;
				}
				else if (str_startswith(optarg, "lptport"))
				{
					parallel_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "printer"))
				{
					printer_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "clientname"))
				{
					g_rdpdr_clientname = xmalloc(strlen(optarg + 11) + 1);
					strcpy(g_rdpdr_clientname, optarg + 11);
				}
				else if (str_startswith(optarg, "clipboard"))
				{
					optarg += 9;

					if (*optarg == ':')
					{
						optarg++;

						if (str_startswith(optarg, "off"))
							g_rdpclip = False;
						else
							cliprdr_set_mode(optarg);
					}
					else
						g_rdpclip = True;
				}
				else if (strncmp("scard", optarg, 5) == 0)
				{
#ifdef WITH_SCARD
					scard_enum_devices(&g_num_devices, optarg + 5);
#else
					warning("Not compiled with smartcard support\n");
#endif
				}
				else
				{
					warning("Unknown -r argument\n\n\tPossible arguments are: comport, disk, lptport, printer, sound, clipboard, scard\n");
				}
				break;

			case '0':
				g_console_session = True;
				break;

			case '4':
				g_use_rdp5 = False;
				break;

			case '5':
				g_use_rdp5 = True;
				break;

			case 'h':
			case '?':
			default:
				usage(argv[0]);
				return 1;
		}
	}

	if (argc - optind != 1)
	{
		usage(argv[0]);
		return 1;
	}

	STRNCPY(server, argv[optind], sizeof(server));
	parse_server_and_port(server);

	if (g_seamless_rdp)
	{
		if (g_win_button_size)
		{
			error("You cannot use -S and -A at the same time\n");
			return 1;
		}
		g_rdp5_performanceflags &= ~RDP5_NO_FULLWINDOWDRAG;
		if (geometry_option)
		{
			error("You cannot use -g and -A at the same time\n");
			return 1;
		}
		if (g_fullscreen)
		{
			error("You cannot use -f and -A at the same time\n");
			return 1;
		}
		if (g_hide_decorations)
		{
			error("You cannot use -D and -A at the same time\n");
			return 1;
		}
		if (g_embed_wnd)
		{
			error("You cannot use -X and -A at the same time\n");
			return 1;
		}
		if (!g_use_rdp5)
		{
			error("You cannot use -4 and -A at the same time\n");
			return 1;
		}
		g_width = -100;
		g_grab_keyboard = False;
	}

	if (!username_option)
	{
		pw = getpwuid(getuid());
		if ((pw == NULL) || (pw->pw_name == NULL))
		{
			error("could not determine username, use -u\n");
			return 1;
		}

		STRNCPY(g_username, pw->pw_name, sizeof(g_username));
	}

#ifdef HAVE_ICONV
	if (g_codepage[0] == 0)
	{
		if (setlocale(LC_CTYPE, ""))
		{
			STRNCPY(g_codepage, nl_langinfo(CODESET), sizeof(g_codepage));
		}
		else
		{
			STRNCPY(g_codepage, DEFAULT_CODEPAGE, sizeof(g_codepage));
		}
	}
#endif

	if (g_hostname[0] == 0)
	{
		if (gethostname(fullhostname, sizeof(fullhostname)) == -1)
		{
			error("could not determine local hostname, use -n\n");
			return 1;
		}

		p = strchr(fullhostname, '.');
		if (p != NULL)
			*p = 0;

		STRNCPY(g_hostname, fullhostname, sizeof(g_hostname));
	}

	if (g_keymapname[0] == 0)
	{
		if (locale && xkeymap_from_locale(locale))
		{
			fprintf(stderr, "Autoselected keyboard map %s\n", g_keymapname);
		}
		else
		{
			STRNCPY(g_keymapname, "en-us", sizeof(g_keymapname));
		}
	}
	if (locale)
		xfree(locale);


	if (prompt_password && read_password(password, sizeof(password)))
		flags |= RDP_LOGON_AUTO;

	if (g_title[0] == 0)
	{
		strcpy(g_title, "rdesktop - ");
		strncat(g_title, server, sizeof(g_title) - sizeof("rdesktop - "));
	}

#ifdef RDP2VNC
	rdp2vnc_connect(server, flags, domain, password, shell, directory);
	return 0;
#else

	if (!ui_init())
		return 1;

#ifdef WITH_RDPSND
	if (g_rdpsnd)
	{
		if (!rdpsnd_init(rdpsnd_optarg))
		{
			warning("Initializing sound-support failed!\n");
		}
	}
#endif

	if (g_lspci_enabled)
		lspci_init();

	rdpdr_init();

	while (run_count < 2 && continue_connect)	/* add support for Session Directory; only reconnect once */
	{
		if (run_count == 0)
		{
			if (!rdp_connect(server, flags, domain, password, shell, directory))
				return 1;
		}
		else if (!rdp_reconnect
			 (server, flags, domain, password, shell, directory, g_redirect_cookie))
			return 1;

		/* By setting encryption to False here, we have an encrypted login 
		   packet but unencrypted transfer of other packets */
		if (!g_packet_encryption)
			g_encryption = False;


		DEBUG(("Connection successful.\n"));
		memset(password, 0, sizeof(password));

		if (run_count == 0)
			if (!ui_create_window())
				continue_connect = False;

		if (continue_connect)
			rdp_main_loop(&deactivated, &ext_disc_reason);

		DEBUG(("Disconnecting...\n"));
		rdp_disconnect();

		if ((g_redirect == True) && (run_count == 0))	/* Support for Session Directory */
		{
			/* reset state of major globals */
			rdesktop_reset_state();

			STRNCPY(domain, g_redirect_domain, sizeof(domain));
			STRNCPY(g_username, g_redirect_username, sizeof(g_username));
			STRNCPY(password, g_redirect_password, sizeof(password));
			STRNCPY(server, g_redirect_server, sizeof(server));
			flags |= RDP_LOGON_AUTO;

			g_redirect = False;
		}
		else
		{
			continue_connect = False;
			ui_destroy_window();
			break;
		}

		run_count++;
	}

	cache_save_state();
	ui_deinit();

	if (ext_disc_reason >= 2)
		print_disconnect_reason(ext_disc_reason);

	if (deactivated)
	{
		/* clean disconnect */
		return 0;
	}
	else
	{
		if (ext_disc_reason == exDiscReasonAPIInitiatedDisconnect
		    || ext_disc_reason == exDiscReasonAPIInitiatedLogoff)
		{
			/* not so clean disconnect, but nothing to worry about */
			return 0;
		}
		else
		{
			/* return error */
			return 2;
		}
	}

#endif

}
Example #23
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;
}
Example #24
0
/**
 * @brief
 *	The main function in C - entry point
 *
 * @param[in]  argc - argument count
 * @param[in]  argv - pointer to argument array
 *
 * @return  int
 * @retval  0 - success
 * @retval  !0 - error
 */
int
main(int argc, char *argv[])
{
	int i, rc;
	char passwd[MAX_PASSWORD_LEN + 1] = {'\0'};
	char passwd2[MAX_PASSWORD_LEN + 1];
	char *pquoted;
	char pwd_file[MAXPATHLEN + 1];
	char userid[LOGIN_NAME_MAX + 1];
	int fd, errflg = 0;
	int gen_pwd = 0;
	char sqlbuff[1024];
	int db_conn_error=0;
	char *db_errmsg = NULL;
	int pmode;
	int change_user = 0;
	char *olduser;
	int update_db = 0;
	char getopt_format[5];
	char prog[]="pbs_ds_password";
	char errmsg[PBS_MAX_DB_CONN_INIT_ERR + 1];

	conn = NULL;
	pwd_file_new[0]=0;

	/*test for real deal or just version and exit*/
	PRINT_VERSION_AND_EXIT(argc, argv);

	/* read configuration file */
	if (pbs_loadconf(0) == 0) {
		fprintf(stderr, "%s: Could not load pbs configuration\n", prog);
		return (-1);
	}

	/* backup old user name */
	if ((olduser = pbs_get_dataservice_usr(errmsg, PBS_MAX_DB_CONN_INIT_ERR)) == NULL) {
		fprintf(stderr, "%s: Could not retrieve current data service user\n", prog);
		if (strlen(errmsg) > 0)
			fprintf(stderr, "%s\n", errmsg);
		return (-1);
	}

	if (pbs_conf.pbs_data_service_host == NULL)
		update_db = 1;

	userid[0]=0; /* empty user id */

	strcpy(getopt_format, "rC:");

	while ((i = getopt(argc, argv, getopt_format)) != EOF) {
		switch (i) {
			case 'r':
				gen_pwd = 1;
				break;
			case 'C':
				strcpy(userid, optarg);
				break;
			case '?':
			default:
				errflg++;
		}
	}

	if (errflg) {
		fprintf(stderr, "\nusage:\t%s [-r] [-C username]\n", prog);
		fprintf(stderr, "      \t%s --version\n", prog);
		return (-1);
	}

    /* NOTE : This functionality is added just for the automation testing purpose.
     * Usage: pbs_ds_password <password>
     */
	if (argv[optind] != NULL) {
		gen_pwd = 0;
		strncpy(passwd, argv[optind], sizeof(passwd));
		passwd[sizeof(passwd) - 1] = '\0';
	}

	/* check admin privileges */
#ifdef WIN32
	if (!isAdminPrivilege(getlogin())) {
		fprintf(stderr, "pbs_ds_password: Must be run by Admin\n");
		return (1);
	}
#else
	if ((getuid() != 0) || (geteuid() != 0)) {
		fprintf(stderr, "%s: Must be run by root\n", prog);
		return (1);
	}
#endif	/* WIN32 */

	change_user = 0;
	/* if the -C option was specified read the user from pbs.conf */
	if (userid[0] != 0) {
		if (strcmp(olduser, userid) != 0) {
			change_user = 1;
		}
	}

	if (change_user == 1) {
		/* check that the supplied user-id exists (and is non-root on unix) */
		if (check_user(userid) != 0) {
#ifdef WIN32
			fprintf(stderr, "\n%s: User-id %s does not exist\n", prog, userid);
#else
			fprintf(stderr, "\n%s: User-id %s does not exist/is root user/home dir is not accessible\n", prog, userid);
#endif
			return (-1);
		}
	}

	atexit(cleanup);

	if (update_db == 1) {
		/* then connect to database */
		conn = pbs_db_init_connection(NULL, PBS_DB_CNT_TIMEOUT_NORMAL, 1, &db_conn_error, errmsg, PBS_MAX_DB_CONN_INIT_ERR);
		if (!conn) {
			get_db_errmsg(db_conn_error, &db_errmsg);
			fprintf(stderr, "%s: %s\n", prog, db_errmsg);
			if (strlen(errmsg) > 0)
				fprintf(stderr, "%s\n", errmsg);
			return -1;
		}
		db_conn_error = pbs_db_connect(conn);
		if (db_conn_error == PBS_DB_SUCCESS && change_user == 1) {
			/* able to connect ? Thats bad, PBS or dataservice is running */
			fprintf(stderr, "%s: PBS Services and/or PBS Data Service is running\n", prog);
			fprintf(stderr, "                 Stop PBS and Data Services before changing Data Service user\n");
			return (-1);
		}

		if (db_conn_error != PBS_DB_SUCCESS) {
			if (db_conn_error == PBS_DB_CONNREFUSED) {
				/* start db only if it was not already running */
				if (pbs_startup_db(&db_errmsg) != 0) {
					if (db_errmsg)
						fprintf(stderr, "%s: Failed to start PBS dataservice:[%s]\n", prog, db_errmsg);
					else
						fprintf(stderr, "%s: Failed to start PBS dataservice\n", prog);
					return (-1);
				}
				started_db = 1;
			}
			db_conn_error = pbs_db_connect(conn);
			if (db_conn_error != PBS_DB_SUCCESS) {
				get_db_errmsg(db_conn_error, &db_errmsg);
				if (conn->conn_db_err)
					fprintf(stderr, "%s: Could not connect to PBS data service:%s:[%s]\n", prog,
						db_errmsg, (char*)conn->conn_db_err);
				else
					fprintf(stderr, "%s: Could not connect to PBS data service:%s\n", prog, db_errmsg);
				return (-1);
			}
		}
	}

	if (gen_pwd == 0 && passwd[0] == '\0') {
		/* ask user to enter password twice */
		printf("Enter the password:"******"\nRe-enter the password:"******"\n\n");
		if (strcmp(passwd, passwd2) != 0) {
			fprintf(stderr, "Entered passwords do not match\n");
			return (-2);
		}
		if (strlen(passwd) == 0) {
			fprintf(stderr, "Blank password is not allowed\n");
			return (-2);
		}
	} else if (gen_pwd == 1) {
		gen_password(passwd, 16);
	}

	rc = pbs_encrypt_pwd(passwd, &cred_type, &cred_buf, &cred_len);
	if (rc != 0) {
		fprintf(stderr, "%s: Failed to encrypt password\n", prog);
		return (-1);
	}

	/* escape password to use in sql strings later */
	if ((pquoted = pbs_db_escape_str(conn, passwd)) == NULL) {
		fprintf(stderr, "%s: Out of memory\n", prog);
		return -1;
	}

#ifdef WIN32
	sprintf(pwd_file_new, "%s\\server_priv\\db_password.new", pbs_conf.pbs_home_path);
	sprintf(pwd_file, "%s\\server_priv\\db_password", pbs_conf.pbs_home_path);
#else
	sprintf(pwd_file_new, "%s/server_priv/db_password.new", pbs_conf.pbs_home_path);
	sprintf(pwd_file, "%s/server_priv/db_password", pbs_conf.pbs_home_path);
#endif

	/* write encrypted password to the password file */
#ifdef WIN32
	pmode = _S_IWRITE | _S_IREAD;
	fix_perms2(pwd_file_new, pwd_file);
	if ((fd = open(pwd_file_new, O_WRONLY | O_TRUNC | O_CREAT | O_Sync | O_BINARY,
		pmode)) == -1)
#else
	pmode = 0600;
	if ((fd = open(pwd_file_new, O_WRONLY | O_TRUNC | O_CREAT | O_Sync,
		pmode)) == -1)
#endif
	{
		perror("open/create failed");
		fprintf(stderr, "%s: Unable to create file %s\n", prog, pwd_file_new);
		return (-1);
	}

#ifdef WIN32
	secure_file(pwd_file_new, "Administrators",
		READS_MASK|WRITES_MASK|STANDARD_RIGHTS_REQUIRED);
	setmode(fd, O_BINARY);
#endif

	if (update_db == 1) {
		/* change password only if this config option is not set */

		if (pbs_db_begin_trx(conn, 0, 0) != 0) {
			fprintf(stderr, "%s: Could not start transaction\n", prog);
			unlink(pwd_file_new);
			return -1;
		}

		if (change_user == 1) {
			/* check whether user exists */
			snprintf(sqlbuff, sizeof(sqlbuff),
				"select usename from pg_user where usename = '%s'",
				userid);
			if (pbs_db_execute_str(conn, sqlbuff) == 1) {
				/* now attempt to create new user & set the database passwd to the un-encrypted password */
				snprintf(sqlbuff, sizeof(sqlbuff),
					"create user \"%s\" SUPERUSER ENCRYPTED PASSWORD '%s'",
					userid, pquoted);
			} else {
				/* attempt to alter new user & set the database passwd to the un-encrypted password */
				snprintf(sqlbuff, sizeof(sqlbuff),
					"alter user \"%s\" SUPERUSER ENCRYPTED PASSWORD '%s'",
					userid, pquoted);
			}
			memset(passwd, 0, sizeof(passwd));
			memset(passwd2, 0, sizeof(passwd2));
			memset(pquoted, 0, (sizeof(char) * strlen(pquoted)));
			if (pbs_db_execute_str(conn, sqlbuff) == -1) {
				fprintf(stderr, "%s: Failed to create/alter user id %s\n", prog, userid);
				(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
				return -1;
			}
		} else {
			/* now attempt to set the database passwd to the un-encrypted password */
			/* alter user ${user} SUPERUSER ENCRYPTED PASSWORD '${passwd}' */
			sprintf(sqlbuff, "alter user \"%s\" SUPERUSER ENCRYPTED PASSWORD '%s'",
				olduser, pquoted);
			memset(passwd, 0, sizeof(passwd));
			memset(passwd2, 0, sizeof(passwd2));
			memset(pquoted, 0, (sizeof(char) * strlen(pquoted)));
			if (pbs_db_execute_str(conn, sqlbuff) == -1) {
				fprintf(stderr, "%s: Failed to create/alter user id %s\n", prog, userid);
				(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
				return -1;
			}
		}
	}

	if (write(fd, cred_buf, cred_len) != cred_len) {
		perror("write failed");
		fprintf(stderr, "%s: Unable to write to file %s\n", prog, pwd_file_new);
		if (update_db == 1) {
			(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
		}
		return -1;
	}
	close(fd);
	free(cred_buf);

#ifdef WIN32
	if (MoveFileEx(pwd_file_new, pwd_file,
		MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) == 0) {
		errno = GetLastError();
		fprintf(stderr, "MoveFileEx(%s, %s) failed!",
			pwd_file_new, pwd_file);
		if (update_db == 1) {
			(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
		}
		return (-1);
	}
#else
	if (rename(pwd_file_new, pwd_file) != 0) {
		if (update_db == 1) {
			(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
		}
		return (-1);
	}
#endif

	if (update_db == 1) {
		/* commit  to database */
		(void) pbs_db_end_trx(conn, PBS_DB_COMMIT);
		cleanup(); /* cleanup will disconnect and delete tmp file too */
	}

	printf("---> Updated user password\n");
	if (update_db == 1 && change_user == 1) {
		printf("---> Updated user in datastore\n");
		printf("---> Stored user password in datastore\n");
	}

	if (change_user == 1) {
		char usr_file[MAXPATHLEN + 1];
#ifdef WIN32
		sprintf(usr_file, "%s\\server_priv\\db_user", pbs_conf.pbs_home_path);
#else
		sprintf(usr_file, "%s/server_priv/db_user", pbs_conf.pbs_home_path);
#endif
		/* update PBS_HOME/server_priv/db_user file with the new user name */
		if (update_db_usr(usr_file, userid) != 0) {
			fprintf(stderr, "Unable to update file %s\n", usr_file);
			return -1;
		}
		printf("---> Updated new user\n");
	}

	if (update_db == 1 && change_user == 1) {
		char datastore[MAXPATHLEN + 1];
#ifndef WIN32
		/* ownership is changed only for Unix users
		 * On windows, these files are allways owned by the user who installed the database
		 * and writable by administrators anyway
		 */
		sprintf(datastore, "%s/datastore", pbs_conf.pbs_home_path);
		/* change ownership of the datastore directories to the new user, so that db can be started again */
		if (change_ownership(datastore, userid) != 0) {
			fprintf(stderr, "%s: Failed to change ownership on path %s\n", prog, datastore);
			return -1;
		}
		printf("---> Changed ownership of %s to user %s\n", datastore, userid);
#endif

		/* reload configuration file */
		if (pbs_loadconf(1) == 0) {
			fprintf(stderr, "%s: Could not load pbs configuration\n", prog);
			return (-1);
		}

		if (pbs_startup_db(&db_errmsg) != 0) {
			if (db_errmsg)
				fprintf(stderr, "%s: Failed to start PBS dataservice as new user:[%s]\n", prog, db_errmsg);
			else
				fprintf(stderr, "%s: Failed to start PBS dataservice as new user\n", prog);
			return (-1);
		}
		started_db = 1;

		/* connect again to drop the old user */
		conn = pbs_db_init_connection(NULL, PBS_DB_CNT_TIMEOUT_NORMAL, 1, &db_conn_error, errmsg, PBS_MAX_DB_CONN_INIT_ERR);
		if (!conn) {
			get_db_errmsg(db_conn_error, &db_errmsg);
			fprintf(stderr, "%s: %s\n", prog, db_errmsg);
			if (strlen(errmsg) > 0)
				fprintf(stderr, "%s\n", errmsg);
			return -1;
		}
		db_conn_error = pbs_db_connect(conn);
		if (db_conn_error != PBS_DB_SUCCESS) {
			get_db_errmsg(db_conn_error, &db_errmsg);
			if (conn->conn_db_err)
				fprintf(stderr, "%s: Could not connect to PBS data service as new user:%s[%s]\n", prog,
					db_errmsg, (char*)conn->conn_db_err);
			else
				fprintf(stderr, "%s: Could not connect to PBS data service as new user:%s\n", prog, db_errmsg);
			return (-1);
		}
		/* delete the old user from the database */
		sprintf(sqlbuff, "drop user \"%s\"", olduser);
		pbs_db_execute_str(conn, sqlbuff);
	}
	printf("---> Success\n");

	return (0);
}
Example #25
0
int
main (int argc, char *argv[])
{
    /*
     * Collect information
     */

    bool f_flag = false;
    char *p;

    char ch;
    while ((ch = getopt (argc, argv, "f")) != -1) {
	switch (ch) {
	case 'f':
	    f_flag = true;
	    break;
	default:
	    usage (argv[0]);
	    exit (EXIT_FAILURE);
	    break;
	}
    }

    char issuer_address[BUFSIZ];
    fprintf (stderr, "Card issuer address: ");
    fgets (issuer_address, BUFSIZ, stdin);
    if ((p = strchr (issuer_address, '\n')))
	*p = '\0';

    char issuer_password[BUFSIZ];
    read_password ("Issuer password", issuer_password, BUFSIZ);
    fprintf (stderr, "\n");
    uint8_t issuer_password_data[16];
    ucard_derivate_password (issuer_password, strlen (issuer_password), 16, issuer_password_data);
    memset (issuer_password, '\0', strlen (issuer_password));
    MifareDESFireKey card_issuer_key = mifare_desfire_aes_key_new (issuer_password_data);

    char owner_full_name[BUFSIZ];
    fprintf (stderr, "Card owner full user name: ");
    fgets (owner_full_name, BUFSIZ, stdin);
    if ((p = strchr (owner_full_name, '\n')))
	*p = '\0';

    char user_password[BUFSIZ];
    read_password ("User password", user_password, BUFSIZ);
    fprintf (stderr, "\n");
    uint8_t user_key_data[16];
    ucard_derivate_password (user_password, strlen (user_password), 16, user_key_data);
    memset (user_password, '\0', strlen (user_password));
    MifareDESFireKey user_key = mifare_desfire_aes_key_new_with_version (user_key_data, UCARD_AES_KEY_VERSION);

    char admin_password[BUFSIZ];
    read_password ("Admin password", admin_password, BUFSIZ);
    fprintf (stderr, "\n");
    uint8_t admin_key_data[16];
    ucard_derivate_password (admin_password, strlen (admin_password), 16, admin_key_data);
    memset (admin_password, '\0', strlen (admin_password));

    MifareDESFireKey admin_key = mifare_desfire_aes_key_new_with_version (admin_key_data, UCARD_AES_KEY_VERSION);

    uint8_t null_key_data[16] = {
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    };
    MifareDESFireKey null_des_key = mifare_desfire_des_key_new (null_key_data);
    MifareDESFireKey null_aes_key = mifare_desfire_aes_key_new (null_key_data);

    nfc_connstring nfc_devices[8];
    size_t nfc_device_count;

    nfc_device_count = nfc_list_devices (NULL, nfc_devices, 8);

    for (size_t n = 0; n < nfc_device_count; n++) {
	nfc_device *nfc_device = nfc_open(NULL, nfc_devices[n]);

	MifareTag *tags = freefare_get_tags (nfc_device);
	for (int i = 0; tags[i]; i++) {
	    MifareTag tag = tags[i];
	    if (DESFIRE == freefare_get_tag_type (tag)) {

		/* Actually setup the card */

		printf ("Fond Mifare DESFire with UID: %s\n", freefare_get_tag_uid (tag));

		/*
		 * Master Application
		 *
		 * Key  0: Card owner 'user' private key
		 */

		MifareDESFireAID ucard_info_aid = mifare_desfire_aid_new (UCARD_INFO_AID);

		int res = mifare_desfire_connect (tag);
		if (f_flag) {
		    if (0 == res) res = mifare_desfire_authenticate_aes (tag, 0, user_key);
		    if (0 == res) res = mifare_desfire_format_picc (tag);
		} else {
		    if (0 == res) res = mifare_desfire_authenticate (tag, 0, null_des_key);
		    if (0 == res) res = mifare_desfire_change_key (tag, 0, user_key, NULL);
		    if (0 == res) res = mifare_desfire_authenticate_aes (tag, 0, user_key);
		}
		if (0 == res) res = mifare_desfire_create_application (tag, ucard_info_aid, 0x0F, 0x83);
		if (!f_flag) {
		    if (0 == res) res = mifare_desfire_change_key_settings (tag, 0x01);
		}

		/*
		 * Card information application
		 *
		 * Key  0: Card owner 'admin' private key
		 * Key  1: Card issuer private key
		 * Key  2: Anonymous access public key
		 *
		 * File  9: Card issuer information
		 * File 10: Card owner information
		 * File 11: Keyring
		 */

		if (0 == res) res = mifare_desfire_select_application (tag, ucard_info_aid);
		if (0 == res) res = mifare_desfire_authenticate_aes (tag, 0, null_aes_key);
		if (0 == res) res = mifare_desfire_change_key (tag, 0, admin_key, NULL);
		if (0 == res) res = mifare_desfire_authenticate_aes (tag, 0, admin_key);
		if (0 == res) res = mifare_desfire_change_key (tag, 1, card_issuer_key, NULL);

		if (0 == res) res = mifare_desfire_create_std_data_file (tag, 9, MDCM_ENCIPHERED, 0x0000, strlen (issuer_address));
		if (0 == res) res = mifare_desfire_write_data (tag, 9, 0, strlen (issuer_address), issuer_address);
		if (strlen (issuer_address) ==  (size_t) res) res = mifare_desfire_change_file_settings (tag, 9, MDCM_ENCIPHERED, 0x2F11);

		if (0 == res) res = mifare_desfire_create_std_data_file (tag, 10, MDCM_ENCIPHERED, 0x0000, strlen (owner_full_name));
		if (0 == res) res = mifare_desfire_write_data (tag, 10, 0, strlen (owner_full_name), owner_full_name);
		if (strlen (owner_full_name) == (size_t) res) res = mifare_desfire_change_file_settings (tag, 10, MDCM_ENCIPHERED, 0x0F11);

		if (0 == res) res = mifare_desfire_create_linear_record_file (tag, 11, MDCM_ENCIPHERED, 0xF20F, 3 + 16, 24);

		if (0 == res) res = mifare_desfire_change_key_settings (tag, 0x01);

		if (res < 0) {
		    fprintf (stderr, "Oops, something went wrong! (%s)\n", freefare_strerror (tag));
		}

		mifare_desfire_disconnect (tag);

		free (ucard_info_aid);
	    }
	}

	nfc_close (nfc_device);
    }

    mifare_desfire_key_free (admin_key);
    mifare_desfire_key_free (user_key);
    mifare_desfire_key_free (card_issuer_key);
    mifare_desfire_key_free (null_aes_key);
    mifare_desfire_key_free (null_des_key);

    exit(EXIT_SUCCESS);
}
Example #26
0
File: main.c Project: AnLingm/gpdb
int main (int argc, char *argv[])
{
	volatile int       errcode = 0;
	int                c;
	char              *procname = argv[0];
	int                forceprompt = false;
	int                needpass = false;
	char              *filename = NULL;
	char              *username = NULL;
	char              *database = NULL;
	char              *hostname = NULL;
	char              *port     = NULL;
	mapred_olist_t    *documents;
	mapred_olist_t    *doc_item;
	FILE              *file;

	/* The long_options structure */
	static struct option long_options[] = {
		{"help",     no_argument,       0, '?'},
		{"version",  no_argument,       0, 'V'},
		{"verbose",  no_argument,       0, 'v'},
		{"password", no_argument,       0, 'W'},
		{"explain",  no_argument,       0, 'x'},
		{"explain-analyze", no_argument, 0, 'X'},

		{"username", required_argument, 0, 'U'},
		{"host",     required_argument, 0, 'h'},
		{"port",     required_argument, 0, 'p'},
		{"file",     required_argument, 0, 'f'},
		{"key",      required_argument, 0, 'k'},
#ifdef INTERNAL_BUILD
		{"print",    no_argument,       0, 'P'},
		{"debug",    no_argument,       0, 'D'},
#endif
		{0, 0, 0, 0}
	};

#ifdef INTERNAL_BUILD
	static char* short_options = "VvWxXU:h:p:f:k:?PD";
#else
	static char* short_options = "VvWxXU:h:p:f:k:?";
#endif

	while (1)
	{
		int option_index = 0;
		c = getopt_long(argc, argv, short_options, long_options, 
						&option_index);
		if (c == -1)
			break; /* done processing options */
		switch (c)
		{
			case '?':  /* --help */
				
				/* Actual help option given */
				if (strcmp(argv[optind - 1], "-?") == 0 || 
					strcmp(argv[optind - 1], "--help") == 0)
				{
					usage(procname, true);
					exit(0);
				}
				
				/* unknown option reported by getopt */
				fprintf(stderr, "Try \"%s --help\" for usage information.\n",
						procname);
				exit(1);
				
			case 'V':  /* --version */
				showVersion(procname);
				exit(0);

			case 'v':  /* --verbose */
				global_verbose_flag = true;
				break;

			case 'x': /* --explain */
				global_explain_flag |= global_explain;
				break;

			case 'X': /* --explain-analyze */
				global_explain_flag |= global_explain | global_analyze;
				break;

#ifdef INTERNAL_BUILD
			case 'P':  /* --print (INTERNAL_BUILD only) */
				global_print_flag = 1;
				break;

			case 'D':  /* --debug (INTERNAL_BUILD only) */
				global_debug_flag = 1;
				break;
#endif

			case 'W':  /* --password */
				forceprompt = true;
				break;
     
			case 'U':  /* --username */
				username = optarg;
				break;
     
			case 'h':  /* --host */
				hostname = optarg;
				break;
     
			case 'p':  /* --port */
				port = optarg;
				break;

			case 'f':  /* --file */
				filename = optarg;
				break;
     
			case 'k':  /* --key */
			{
				mapred_plist_t *newitem;
				char *name = optarg;
				char *value = NULL;
				char *eq = strchr(name, '=');

				/* 
				 * either --key value      : sets parameter named "key"
				 * or     --key name=value : sets parameter named "name"
				 */
				if (eq)
				{
					eq[0] = '\0';
					value = eq+1;
					
					/* make sure parameter is a valid name */
					if (strspn(name, wordchars) != strlen(name))
					{
						fprintf(stderr, "bad parameter --key %s\n", name);
						exit(1);
					}
				}
				else
				{
					value = name;
					name = "key";
				}

				/* Add the parameter to the global parameter list */
				newitem = malloc(sizeof(mapred_plist_t));
				newitem->name  = name;
				newitem->type  = value;
				newitem->next  = global_plist;
				global_plist   = newitem;
			}
			break;

			default:  /* not feasible */
				fprintf(stderr, "Error processing options\n");
				exit(1);
		}
	}

	/* open the file */
	if (!filename)
	{
		usage(procname, false);
		exit(1);
	}

	file = fopen(filename, "rb");
	if (!file) 
	{
		fprintf(stderr, "Error: Could not open file '%s'\n", filename);
		exit(1);
	}

	/*
	 * Handle additional arguments as would psql:
	 *   - First argument is database
	 *   - Second argument is username, if not specified via -U
	 *   - All other arguments generate warnings
	 */
	if (optind < argc && !database)
		database = argv[optind++];
	if (optind < argc && !username)
		username = argv[optind++];
	while (optind < argc)
	{
		fprintf(stderr, "%s: warning: extra command-line argument \"%s\" ignored\n",
				procname, argv[optind++]);
	}

	if (global_verbose_flag)
	{
		mapred_plist_t *param = global_plist;
		while (param)
		{
			fprintf(stderr, "- Parameter: %s=%s\n", 
					param->name, param->type);
			param = param->next;
		}
		fprintf(stderr, "- Parsing '%s':\n", filename);
	}
	documents = NULL;
	XTRY
	{
		documents = mapred_parse_file(file);
	}
	XCATCH(ASSERTION_FAILURE)
	{
		fprintf(stderr, "Assertion failure at %s:%d\n",
				xframe.file, xframe.lineno);	
		exit(1);
	}
	XCATCH_ANY
	{
		if (global_verbose_flag)
			fprintf(stderr, "  - ");
		if (xframe.exception)
			fprintf(stderr, "Error: %s\n", (char *) xframe.exception);
		else
			fprintf(stderr, "Unknown Error (%d) at %s:%d\n", 
					xframe.errcode, xframe.file, xframe.lineno);
		exit(1);
	}
	XTRY_END;

	/* Do something interesting with documents */
	for (doc_item = documents; doc_item; doc_item = doc_item->next)
	{
		PGconn   *conn = NULL;
		char      pwdbuf[100];
		char      portbuf[11];  /* max int size should be 10 digits */
		char     *user, *db, *host, *pwd, *pqport, *options, *tty;

		XTRY
		{
			mapred_document_t *doc = &doc_item->object->u.document;

			if (global_verbose_flag)
			{
				fprintf(stderr, "- Executing Document %d:\n", doc->id);
			}

			if (port)
			{
				pqport = port;
			}
			else if (doc->port > 0)
			{
				snprintf(portbuf, sizeof(portbuf), "%d", doc->port);
				pqport = portbuf;
			}
			else
			{
				pqport = NULL;
			}
			if (database)
				db = database;
			else
				db = doc->database;
			if (username)
				user = username;
			else
				user = doc->user;
			if (hostname)
				host = hostname;
			else
				host = doc->host;

			options = NULL;
			tty     = NULL;
			pwd     = NULL;

			if (forceprompt)
			{
				read_password(pwdbuf, sizeof(pwdbuf));
				pwd = pwdbuf;
			}

			do {
				conn = PQsetdbLogin(host, pqport, options, tty, db, user, pwd);

				needpass = false;
				if (PQstatus(conn) == CONNECTION_BAD &&
					!strcmp(PQerrorMessage(conn), PQnoPasswordSupplied))
				{
					PQfinish(conn);

					read_password(pwdbuf, sizeof(pwdbuf));
					pwd = pwdbuf;
					needpass = true;
				}
			} while (needpass);

			if (PQstatus(conn) == CONNECTION_BAD)
			{
				XRAISE(CONNECTION_ERROR, PQerrorMessage(conn));
			}
			else
			{
				if (global_verbose_flag)
				{
					fprintf(stderr, "  - Connected Established:\n");
					fprintf(stderr, "    HOST: %s\n", 
							PQhost(conn) ? PQhost(conn) : "localhost");
					fprintf(stderr, "    PORT: %s\n", PQport(conn));
					fprintf(stderr, "    USER: %s/%s\n", PQuser(conn), PQdb(conn));
				}
				check_version(conn);
				
				/* Prepare to receive interupts */
				cancelConn = PQgetCancel(conn);

				if (signal(SIGINT, sigint_handler) == SIG_IGN)
					signal(SIGINT, SIG_IGN);
				if (signal(SIGHUP, sigint_handler) == SIG_IGN)
					signal(SIGHUP, SIG_IGN);
				if (signal(SIGTERM, sigint_handler) == SIG_IGN)
					signal(SIGTERM, SIG_IGN);

				mapred_run_document(conn, doc);

			}
		}
		XCATCH(ASSERTION_FAILURE)
		{
			fprintf(stderr, "Assertion failure at %s:%d\n",
					xframe.file, xframe.lineno);	
			errcode = 1;
		}
		XCATCH(USER_INTERUPT)
		{
			if (global_verbose_flag)
				fprintf(stderr, "  - ");			
			fprintf(stderr, "Job Cancelled: User Interrupt");
			exit(2); /* exit immediately */
		}
		XCATCH_ANY
		{
			if (global_verbose_flag)
				fprintf(stderr, "  - ");
			if (xframe.exception)
				fprintf(stderr, "Error: %s\n", (char *) xframe.exception);
			else
				fprintf(stderr, "Unknown Error (%d) at %s:%d\n", 
						xframe.errcode, xframe.file, xframe.lineno);
			errcode = 1;
		}
		XFINALLY
		{
			/* Ignore signals until we exit */
			signal(SIGINT, SIG_IGN);
			signal(SIGHUP, SIG_IGN);
			signal(SIGTERM, SIG_IGN);

			PQfreeCancel(cancelConn);
			cancelConn = NULL;
			PQfinish(conn);
		}
		XTRY_END;
	}
	
	/* Cleanup */
	mapred_destroy_olist(&documents);
	fclose(file);

	return errcode;
}
Example #27
0
/* Client program */
int
main(int argc, char *argv[])
{
	char server[64];
	char fullhostname[64];
	char domain[16];
	char password[16];
	char shell[128];
	char directory[32];
	BOOL prompt_password;
	struct passwd *pw;
	uint32 flags;
	char *p;
	int c;
	int username_option = 0;

	flags = RDP_LOGON_NORMAL;
	prompt_password = False;
	domain[0] = password[0] = shell[0] = directory[0] = 0;
	strcpy(keymapname, "en-us");

#ifdef RDP2VNC
#define VNCOPT "V:E:"
#else
#define VNCOPT
#endif

	while ((c = getopt(argc, argv, VNCOPT "u:d:s:S:c:p:n:k:g:a:fbemCKT:Dh?54")) != -1)
	{
		switch (c)
		{
#ifdef RDP2VNC
			case 'V':
				rfb_port = strtol(optarg, NULL, 10);
				if (rfb_port < 100)
					rfb_port += 5900;
				break;

			case 'E':
				defer_time = strtol(optarg, NULL, 10);
				if (defer_time < 0)
					defer_time = 0;
				break;
#endif

			case 'u':
				STRNCPY(username, optarg, sizeof(username));
				username_option = 1;
				break;

			case 'd':
				STRNCPY(domain, optarg, sizeof(domain));
				break;

			case 's':
				STRNCPY(shell, optarg, sizeof(shell));
				break;

			case 'S':
				if (!strcmp(optarg, "standard"))
				{
					win_button_size = 18;
					break;
				}

				win_button_size = strtol(optarg, &p, 10);

				if (*p)
				{
					error("invalid button size\n");
					return 1;
				}

				break;

			case 'c':
				STRNCPY(directory, optarg, sizeof(directory));
				break;

			case 'p':
				if ((optarg[0] == '-') && (optarg[1] == 0))
				{
					prompt_password = True;
					break;
				}

				STRNCPY(password, optarg, sizeof(password));
				flags |= RDP_LOGON_AUTO;

				/* try to overwrite argument so it won't appear in ps */
				p = optarg;
				while (*p)
					*(p++) = 'X';
				break;

			case 'n':
				STRNCPY(hostname, optarg, sizeof(hostname));
				break;

			case 'k':
				STRNCPY(keymapname, optarg, sizeof(keymapname));
				break;

			case 'g':
				if (!strcmp(optarg, "workarea"))
				{
					width = height = 0;
					break;
				}

				width = strtol(optarg, &p, 10);
				if (*p == 'x')
					height = strtol(p + 1, NULL, 10);

				if ((width == 0) || (height == 0))
				{
					error("invalid geometry\n");
					return 1;
				}
				break;

			case 'f':
				fullscreen = True;
				break;

			case 'b':
				orders = False;
				break;

			case 'e':
				encryption = False;
				break;

			case 'm':
				sendmotion = False;
				break;

			case 'C':
				owncolmap = True;
				break;

			case 'K':
				grab_keyboard = False;
				break;

			case 'T':
				STRNCPY(title, optarg, sizeof(title));
				break;

			case 'D':
				hide_decorations = True;
				break;

			case 'a':
				server_bpp = strtol(optarg, NULL, 10);
				if (server_bpp != 8 && server_bpp != 16 && server_bpp != 15
				    && server_bpp != 24)
				{
					error("invalid server bpp\n");
					return 1;
				}
				break;

			case '5':
				use_rdp5 = True;
				break;
			case 'h':
			case '?':
			default:
				usage(argv[0]);
				return 1;
		}
	}

	if (argc - optind < 1)
	{
		usage(argv[0]);
		return 1;
	}

	STRNCPY(server, argv[optind], sizeof(server));
	p = strchr(server, ':');
	if (p != NULL)
	{
		tcp_port_rdp = strtol(p + 1, NULL, 10);
		*p = 0;
	}

	if (!username_option)
	{
		pw = getpwuid(getuid());
		if ((pw == NULL) || (pw->pw_name == NULL))
		{
			error("could not determine username, use -u\n");
			return 1;
		}

		STRNCPY(username, pw->pw_name, sizeof(username));
	}

	if (hostname[0] == 0)
	{
		if (gethostname(fullhostname, sizeof(fullhostname)) == -1)
		{
			error("could not determine local hostname, use -n\n");
			return 1;
		}

		p = strchr(fullhostname, '.');
		if (p != NULL)
			*p = 0;

		STRNCPY(hostname, fullhostname, sizeof(hostname));
	}

	if (prompt_password && read_password(password, sizeof(password)))
		flags |= RDP_LOGON_AUTO;

	if (title[0] == 0)
	{
		strcpy(title, "rdesktop - ");
		strncat(title, server, sizeof(title) - sizeof("rdesktop - "));
	}

#ifdef RDP2VNC
	rdp2vnc_connect(server, flags, domain, password, shell, directory);
#else

	if (!ui_init())
		return 1;

	if (!rdp_connect(server, flags, domain, password, shell, directory))
		return 1;

	DEBUG(("Connection successful.\n"));
	memset(password, 0, sizeof(password));

	if (ui_create_window())
	{
		rdp_main_loop();
		ui_destroy_window();
	}

	DEBUG(("Disconnecting...\n"));
	rdp_disconnect();
	ui_deinit();

#endif

	return 0;
}
Example #28
0
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;
}