Пример #1
0
int
main (int argc, char **argv)
{
  ARGPARSE_ARGS pargs;
  int cmd = 0;
  const char *keygrip = NULL;

  set_strusage (my_strusage);
  log_set_prefix ("gpg-preset-passphrase", 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init ();
  init_common_subsystems (&argc, &argv);

  opt_homedir = default_homedir ();

  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags=  1;  /* (do not remove the args) */
  while (arg_parse (&pargs, opts) )
    {
      switch (pargs.r_opt)
        {
        case oVerbose: opt.verbose++; break;
        case oHomedir: opt_homedir = pargs.r.ret_str; break;

        case oPreset: cmd = oPreset; break;
        case oForget: cmd = oForget; break;
        case oPassphrase: opt_passphrase = pargs.r.ret_str; break;

        default : pargs.err = 2; break;
	}
    }
  if (log_get_errorcount(0))
    exit(2);

  if (argc == 1)
    keygrip = *argv;
  else
    usage (1);

  /* Tell simple-pwquery about the the standard socket name.  */
  {
    char *tmp = make_filename (opt_homedir, GPG_AGENT_SOCK_NAME, NULL);
    simple_pw_set_socket (tmp);
    xfree (tmp);
  }

  if (cmd == oPreset)
    preset_passphrase (keygrip);
  else if (cmd == oForget)
    forget_passphrase (keygrip);
  else
    log_error ("one of the options --preset or --forget must be given\n");

  agent_exit (0);
  return 8; /*NOTREACHED*/
}
Пример #2
0
/* Check whether gpgconf is installed and if so read the gpgconf.ctl
   file. */
static void
check_portable_app (const char *dir)
{
  char *fname;

  fname = xstrconcat (dir, DIRSEP_S "gpgconf.exe", NULL);
  if (!access (fname, F_OK))
    {
      strcpy (fname + strlen (fname) - 3, "ctl");
      if (!access (fname, F_OK))
        {
          /* gpgconf.ctl file found.  Record this fact.  */
          w32_portable_app = 1;
          {
            unsigned int flags;
            log_get_prefix (&flags);
            log_set_prefix (NULL, (flags | GPGRT_LOG_NO_REGISTRY));
          }
          /* FIXME: We should read the file to detect special flags
             and print a warning if we don't understand them  */
        }
    }
  xfree (fname);
}
Пример #3
0
/* gpgtar main. */
int
main (int argc, char **argv)
{
  ARGPARSE_ARGS pargs;
  const char *fname;
  int no_more_options = 0;
  enum cmd_and_opt_values cmd = 0;
  int skip_crypto = 0;
  const char *files_from = NULL;
  int null_names = 0;

  assert (sizeof (struct ustar_raw_header) == 512);

  gnupg_reopen_std ("gpgtar");
  set_strusage (my_strusage);
  log_set_prefix ("gpgtar", 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init();
  init_common_subsystems ();

  /* Parse the command line. */
  pargs.argc  = &argc;
  pargs.argv  = &argv;
  pargs.flags = ARGPARSE_FLAG_KEEP;
  while (!no_more_options && optfile_parse (NULL, NULL, NULL, &pargs, opts))
    {
      switch (pargs.r_opt)
        {
        case oOutput:    opt.outfile = pargs.r.ret_str; break;
        case oSetFilename: opt.filename = pargs.r.ret_str; break;
	case oQuiet:     opt.quiet = 1; break;
        case oVerbose:   opt.verbose++; break;
        case oNoVerbose: opt.verbose = 0; break;
        case oFilesFrom: files_from = pargs.r.ret_str; break;
        case oNull: null_names = 1; break;
          
	case aList:
        case aDecrypt:
        case aEncrypt:
        case aSign:
          set_cmd (&cmd, pargs.r_opt);
	  break;

        case oSymmetric:
          set_cmd (&cmd, aEncrypt);
          opt.symmetric = 1;
          break;

        case oSkipCrypto:
          skip_crypto = 1;
          break;

        case oOpenPGP: /* Dummy option for now.  */ break;
        case oCMS:     /* Dummy option for now.  */ break;

        default: pargs.err = 2; break;
	}
    }
  
  if ((files_from && !null_names) || (!files_from && null_names))
    log_error ("--files-from and --null may only be used in conjunction\n");
  if (files_from && strcmp (files_from, "-"))
    log_error ("--files-from only supports argument \"-\"\n");

  if (log_get_errorcount (0))
    exit (2);

  switch (cmd)
    {
    case aList:
      if (argc > 1)
        usage (1);
      fname = argc ? *argv : NULL;
      if (opt.filename)
        log_info ("note: ignoring option --set-filename\n");
      if (files_from)
        log_info ("note: ignoring option --files-from\n");
      if (skip_crypto)
        gpgtar_list (fname);
      else
        decrypt_and_list (fname);
      break;

    case aEncrypt:
      if ((!argc && !null_names)
          || (argc && null_names))
        usage (1);
      if (opt.filename)
        log_info ("note: ignoring option --set-filename\n");
      if (skip_crypto)
        gpgtar_create (null_names? NULL :argv);
      else
        tar_and_encrypt (null_names? NULL : argv);
      break;

    case aDecrypt:
      if (argc != 1)
        usage (1);
      if (opt.outfile)
        log_info ("note: ignoring option --output\n");
      if (files_from)
        log_info ("note: ignoring option --files-from\n");
      fname = argc ? *argv : NULL;
      if (skip_crypto)
        gpgtar_extract (fname);
      else
        decrypt_and_untar (fname);
      break;

    default:
      log_error (_("invalid command (there is no implicit command)\n"));
      break;
    }

  return log_get_errorcount (0)? 1:0;
}
Пример #4
0
int
main( int argc, char **argv )
{
    ARGPARSE_ARGS pargs;
    enum cmd_and_opt_values cmd = 0;
    unsigned long from = 0, to = ULONG_MAX;
    int dry_run = 0;

    early_system_init ();
    set_strusage( my_strusage );
    gcry_control (GCRYCTL_DISABLE_SECMEM);
    log_set_prefix ("kbxutil", 1);

    /* Make sure that our subsystems are ready.  */
    i18n_init ();
    init_common_subsystems (&argc, &argv);

    /* Check that the libraries are suitable.  Do it here because
       the option parsing may need services of the library.  */
    if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
    {
        log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
                   NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
    }

    gcry_set_log_handler (my_gcry_logger, NULL);

    /*create_dotlock(NULL); register locking cleanup */

    /* We need to use the gcry malloc function because jnlib uses them.  */
    keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
    ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );


    pargs.argc = &argc;
    pargs.argv = &argv;
    pargs.flags=  1;  /* do not remove the args */
    while (arg_parse( &pargs, opts) )
    {
        switch (pargs.r_opt)
        {
        case oVerbose:
            /*opt.verbose++;*/
            /*gcry_control( GCRYCTL_SET_VERBOSITY, (int)opt.verbose );*/
            break;
        case oDebug:
            /*opt.debug |= pargs.r.ret_ulong; */
            break;
        case oDebugAll:
            /*opt.debug = ~0;*/
            break;

        case aFindByFpr:
        case aFindByKid:
        case aFindByUid:
        case aStats:
        case aImportOpenPGP:
        case aFindDups:
        case aCut:
            cmd = pargs.r_opt;
            break;

        case oFrom:
            from = pargs.r.ret_ulong;
            break;
        case oTo:
            to = pargs.r.ret_ulong;
            break;

        case oDryRun:
            dry_run = 1;
            break;

        default:
            pargs.err = 2;
            break;
        }
    }

    if (to < from)
        log_error ("record number of \"--to\" is lower than \"--from\" one\n");


    if (log_get_errorcount(0) )
        myexit(2);

    if (!cmd)
    {   /* Default is to list a KBX file */
        if (!argc)
            _keybox_dump_file (NULL, 0, stdout);
        else
        {
            for (; argc; argc--, argv++)
                _keybox_dump_file (*argv, 0, stdout);
        }
    }
    else if (cmd == aStats )
    {
        if (!argc)
            _keybox_dump_file (NULL, 1, stdout);
        else
        {
            for (; argc; argc--, argv++)
                _keybox_dump_file (*argv, 1, stdout);
        }
    }
    else if (cmd == aFindDups )
    {
        if (!argc)
            _keybox_dump_find_dups (NULL, 0, stdout);
        else
        {
            for (; argc; argc--, argv++)
                _keybox_dump_find_dups (*argv, 0, stdout);
        }
    }
    else if (cmd == aCut )
    {
        if (!argc)
            _keybox_dump_cut_records (NULL, from, to, stdout);
        else
        {
            for (; argc; argc--, argv++)
                _keybox_dump_cut_records (*argv, from, to, stdout);
        }
    }
    else if (cmd == aImportOpenPGP)
    {
        if (!argc)
            import_openpgp ("-", dry_run);
        else
        {
            for (; argc; argc--, argv++)
                import_openpgp (*argv, dry_run);
        }
    }
#if 0
    else if ( cmd == aFindByFpr )
    {
        char *fpr;
        if ( argc != 2 )
            wrong_args ("kbxfile foingerprint");
        fpr = format_fingerprint ( argv[1] );
        if ( !fpr )
            log_error ("invalid formatted fingerprint\n");
        else
        {
            kbxfile_search_by_fpr ( argv[0], fpr );
            gcry_free ( fpr );
        }
    }
    else if ( cmd == aFindByKid )
    {
        u32 kid[2];
        int mode;

        if ( argc != 2 )
            wrong_args ("kbxfile short-or-long-keyid");
        mode = format_keyid ( argv[1], kid );
        if ( !mode )
            log_error ("invalid formatted keyID\n");
        else
        {
            kbxfile_search_by_kid ( argv[0], kid, mode );
        }
    }
    else if ( cmd == aFindByUid )
    {
        if ( argc != 2 )
            wrong_args ("kbxfile userID");
        kbxfile_search_by_uid ( argv[0], argv[1] );
    }
#endif
    else
        log_error ("unsupported action\n");

    myexit(0);
    return 8; /*NEVER REACHED*/
}
Пример #5
0
int storage_func_init(const char *filename, \
		char *bind_addr, const int addr_size)
{
	char *pBindAddr;
	char *pGroupName;
	char *pRunByGroup;
	char *pRunByUser;
	char *pFsyncAfterWrittenBytes;
	char *pThreadStackSize;
	char *pBuffSize;
	char *pIfAliasPrefix;
	char *pHttpDomain;
	IniContext iniContext;
	int result;
	int64_t fsync_after_written_bytes;
	int64_t thread_stack_size;
	int64_t buff_size;
	TrackerServerInfo *pServer;
	TrackerServerInfo *pEnd;

	/*
	while (nThreadCount > 0)
	{
		sleep(1);
	}
	*/

	if ((result=iniLoadFromFile(filename, &iniContext)) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"load conf file \"%s\" fail, ret code: %d", \
			__LINE__, filename, result);
		return result;
	}

	do
	{
		if (iniGetBoolValue(NULL, "disabled", &iniContext, false))
		{
			logError("file: "__FILE__", line: %d, " \
				"conf file \"%s\" disabled=true, exit", \
				__LINE__, filename);
			result = ECANCELED;
			break;
		}

		g_subdir_count_per_path=iniGetIntValue(NULL, \
				"subdir_count_per_path", &iniContext, \
				DEFAULT_DATA_DIR_COUNT_PER_PATH);
		if (g_subdir_count_per_path <= 0 || \
		    g_subdir_count_per_path > 256)
		{
			logError("file: "__FILE__", line: %d, " \
				"conf file \"%s\", invalid subdir_count: %d", \
				__LINE__, filename, g_subdir_count_per_path);
			result = EINVAL;
			break;
		}

		if ((result=storage_load_paths(&iniContext)) != 0)
		{
			break;
		}

		load_log_level(&iniContext);
		if ((result=log_set_prefix(g_fdfs_base_path, \
				STORAGE_ERROR_LOG_FILENAME)) != 0)
		{
			break;
		}

		g_fdfs_connect_timeout = iniGetIntValue(NULL, "connect_timeout", \
				&iniContext, DEFAULT_CONNECT_TIMEOUT);
		if (g_fdfs_connect_timeout <= 0)
		{
			g_fdfs_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
		}

		g_fdfs_network_timeout = iniGetIntValue(NULL, "network_timeout", \
				&iniContext, DEFAULT_NETWORK_TIMEOUT);
		if (g_fdfs_network_timeout <= 0)
		{
			g_fdfs_network_timeout = DEFAULT_NETWORK_TIMEOUT;
		}
		g_network_tv.tv_sec = g_fdfs_network_timeout;

		g_server_port = iniGetIntValue(NULL, "port", &iniContext, \
					FDFS_STORAGE_SERVER_DEF_PORT);
		if (g_server_port <= 0)
		{
			g_server_port = FDFS_STORAGE_SERVER_DEF_PORT;
		}

		g_heart_beat_interval = iniGetIntValue(NULL, \
				"heart_beat_interval", &iniContext, \
				STORAGE_BEAT_DEF_INTERVAL);
		if (g_heart_beat_interval <= 0)
		{
			g_heart_beat_interval = STORAGE_BEAT_DEF_INTERVAL;
		}

		g_stat_report_interval = iniGetIntValue(NULL, \
				"stat_report_interval", &iniContext, \
				STORAGE_REPORT_DEF_INTERVAL);
		if (g_stat_report_interval <= 0)
		{
			g_stat_report_interval = STORAGE_REPORT_DEF_INTERVAL;
		}

		pBindAddr = iniGetStrValue(NULL, "bind_addr", &iniContext);
		if (pBindAddr == NULL)
		{
			*bind_addr = '\0';
		}
		else
		{
			snprintf(bind_addr, addr_size, "%s", pBindAddr);
		}

		g_client_bind_addr = iniGetBoolValue(NULL, "client_bind", \
					&iniContext, true);

		pGroupName = iniGetStrValue(NULL, "group_name", &iniContext);
		if (pGroupName == NULL)
		{
			logError("file: "__FILE__", line: %d, " \
				"conf file \"%s\" must have item " \
				"\"group_name\"!", \
				__LINE__, filename);
			result = ENOENT;
			break;
		}
		if (pGroupName[0] == '\0')
		{
			logError("file: "__FILE__", line: %d, " \
				"conf file \"%s\", " \
				"group_name is empty!", \
				__LINE__, filename);
			result = EINVAL;
			break;
		}

		snprintf(g_group_name, sizeof(g_group_name), "%s", pGroupName);
		if ((result=fdfs_validate_group_name(g_group_name)) != 0) \
		{
			logError("file: "__FILE__", line: %d, " \
				"conf file \"%s\", " \
				"the group name \"%s\" is invalid!", \
				__LINE__, filename, g_group_name);
			result = EINVAL;
			break;
		}

		result = fdfs_load_tracker_group_ex(&g_tracker_group, \
				filename, &iniContext);
		if (result != 0)
		{
			break;
		}

		pEnd = g_tracker_group.servers + g_tracker_group.server_count;
		for (pServer=g_tracker_group.servers; pServer<pEnd; pServer++)
		{
			//printf("server=%s:%d\n", pServer->ip_addr, pServer->port);
			if (strcmp(pServer->ip_addr, "127.0.0.1") == 0)
			{
				logError("file: "__FILE__", line: %d, " \
					"conf file \"%s\", " \
					"tracker: \"%s:%d\" is invalid, " \
					"tracker server ip can't be 127.0.0.1",\
					__LINE__, filename, pServer->ip_addr, \
					pServer->port);
				result = EINVAL;
				break;
			}
		}
		if (result != 0)
		{
			break;
		}

		g_sync_wait_usec = iniGetIntValue(NULL, "sync_wait_msec",\
			 &iniContext, STORAGE_DEF_SYNC_WAIT_MSEC);
		if (g_sync_wait_usec <= 0)
		{
			g_sync_wait_usec = STORAGE_DEF_SYNC_WAIT_MSEC;
		}
		g_sync_wait_usec *= 1000;

		g_sync_interval = iniGetIntValue(NULL, "sync_interval",\
			 &iniContext, 0);
		if (g_sync_interval < 0)
		{
			g_sync_interval = 0;
		}
		g_sync_interval *= 1000;

		if ((result=get_time_item_from_conf(&iniContext, \
			"sync_start_time", &g_sync_start_time, 0, 0)) != 0)
		{
			break;
		}
		if ((result=get_time_item_from_conf(&iniContext, \
			"sync_end_time", &g_sync_end_time, 23, 59)) != 0)
		{
			break;
		}

		g_sync_part_time = !((g_sync_start_time.hour == 0 && \
				g_sync_start_time.minute == 0) && \
				(g_sync_end_time.hour == 23 && \
				g_sync_end_time.minute == 59));

		g_max_connections = iniGetIntValue(NULL, "max_connections", \
				&iniContext, DEFAULT_MAX_CONNECTONS);
		if (g_max_connections <= 0)
		{
			g_max_connections = DEFAULT_MAX_CONNECTONS;
		}
		if ((result=set_rlimit(RLIMIT_NOFILE, g_max_connections)) != 0)
		{
			break;
		}

		g_work_threads = iniGetIntValue(NULL, "work_threads", \
				&iniContext, DEFAULT_WORK_THREADS);
		if (g_work_threads <= 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"work_threads\" is invalid, " \
				"value: %d <= 0!", __LINE__, g_work_threads);
			result = EINVAL;
                        break;
		}

		pBuffSize = iniGetStrValue(NULL, \
			"buff_size", &iniContext);
		if (pBuffSize == NULL)
		{
			buff_size = STORAGE_DEFAULT_BUFF_SIZE;
		}
		else if ((result=parse_bytes(pBuffSize, 1, &buff_size)) != 0)
		{
			return result;
		}
		g_buff_size = buff_size;
		if (g_buff_size < 4 * 1024 || \
			g_buff_size < sizeof(TrackerHeader) + \
					TRUNK_BINLOG_BUFFER_SIZE)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"buff_size\" is too small, " \
				"value: %d < %d or < %d!", __LINE__, \
				g_buff_size, 4 * 1024, \
				(int)sizeof(TrackerHeader) + \
				TRUNK_BINLOG_BUFFER_SIZE);
			result = EINVAL;
                        break;
		}

		g_disk_rw_separated = iniGetBoolValue(NULL, \
				"disk_rw_separated", &iniContext, true);

		g_disk_reader_threads = iniGetIntValue(NULL, \
				"disk_reader_threads", \
				&iniContext, DEFAULT_DISK_READER_THREADS);
		if (g_disk_reader_threads < 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"disk_reader_threads\" is invalid, " \
				"value: %d < 0!", __LINE__, \
				g_disk_reader_threads);
			result = EINVAL;
                        break;
		}

		g_disk_writer_threads = iniGetIntValue(NULL, \
				"disk_writer_threads", \
				&iniContext, DEFAULT_DISK_WRITER_THREADS);
		if (g_disk_writer_threads < 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"disk_writer_threads\" is invalid, " \
				"value: %d < 0!", __LINE__, \
				g_disk_writer_threads);
			result = EINVAL;
                        break;
		}

		if (g_disk_rw_separated)
		{
			if (g_disk_reader_threads == 0)
			{
				logError("file: "__FILE__", line: %d, " \
					"item \"disk_reader_threads\" is " \
					"invalid, value = 0!", __LINE__);
				result = EINVAL;
				break;
			}

			if (g_disk_writer_threads == 0)
			{
				logError("file: "__FILE__", line: %d, " \
					"item \"disk_writer_threads\" is " \
					"invalid, value = 0!", __LINE__);
				result = EINVAL;
				break;
			}
		}
		else if (g_disk_reader_threads + g_disk_writer_threads == 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"disk_reader_threads\" and " \
				"\"disk_writer_threads\" are " \
				"invalid, both value = 0!", __LINE__);
			result = EINVAL;
			break;
		}

		/*
		g_disk_rw_direct = iniGetBoolValue(NULL, \
				"disk_rw_direct", &iniContext, false);
		*/

		pRunByGroup = iniGetStrValue(NULL, "run_by_group", &iniContext);
		pRunByUser = iniGetStrValue(NULL, "run_by_user", &iniContext);
		if (pRunByGroup == NULL)
		{
			*g_run_by_group = '\0';
		}
		else
		{
			snprintf(g_run_by_group, sizeof(g_run_by_group), \
				"%s", pRunByGroup);
		}
		if (*g_run_by_group == '\0')
		{
			g_run_by_gid = getegid();
		}
		else
		{
			struct group *pGroup;

     			pGroup = getgrnam(g_run_by_group);
			if (pGroup == NULL)
			{
				result = errno != 0 ? errno : ENOENT;
				logError("file: "__FILE__", line: %d, " \
					"getgrnam fail, errno: %d, " \
					"error info: %s", __LINE__, \
					result, STRERROR(result));
				return result;
			}

			g_run_by_gid = pGroup->gr_gid;
		}

		if (pRunByUser == NULL)
		{
			*g_run_by_user = '******';
		}
		else
		{
			snprintf(g_run_by_user, sizeof(g_run_by_user), \
				"%s", pRunByUser);
		}
		if (*g_run_by_user == '\0')
		{
			g_run_by_uid = geteuid();
		}
		else
		{
			struct passwd *pUser;

     			pUser = getpwnam(g_run_by_user);
			if (pUser == NULL)
			{
				result = errno != 0 ? errno : ENOENT;
				logError("file: "__FILE__", line: %d, " \
					"getpwnam fail, errno: %d, " \
					"error info: %s", __LINE__, \
					result, STRERROR(result));
				return result;
			}

			g_run_by_uid = pUser->pw_uid;
		}

		if ((result=load_allow_hosts(&iniContext, \
                	 &g_allow_ip_addrs, &g_allow_ip_count)) != 0)
		{
			return result;
		}

		g_file_distribute_path_mode = iniGetIntValue(NULL, \
			"file_distribute_path_mode", &iniContext, \
			FDFS_FILE_DIST_PATH_ROUND_ROBIN);
		g_file_distribute_rotate_count = iniGetIntValue(NULL, \
			"file_distribute_rotate_count", &iniContext, \
			FDFS_FILE_DIST_DEFAULT_ROTATE_COUNT);
		if (g_file_distribute_rotate_count <= 0)
		{
			g_file_distribute_rotate_count = \
				FDFS_FILE_DIST_DEFAULT_ROTATE_COUNT;
		}

		pFsyncAfterWrittenBytes = iniGetStrValue(NULL, \
			"fsync_after_written_bytes", &iniContext);
		if (pFsyncAfterWrittenBytes == NULL)
		{
			fsync_after_written_bytes = 0;
		}
		else if ((result=parse_bytes(pFsyncAfterWrittenBytes, 1, \
				&fsync_after_written_bytes)) != 0)
		{
			return result;
		}
		g_fsync_after_written_bytes = fsync_after_written_bytes;

		g_sync_log_buff_interval = iniGetIntValue(NULL, \
				"sync_log_buff_interval", &iniContext, \
				SYNC_LOG_BUFF_DEF_INTERVAL);
		if (g_sync_log_buff_interval <= 0)
		{
			g_sync_log_buff_interval = SYNC_LOG_BUFF_DEF_INTERVAL;
		}

		g_sync_binlog_buff_interval = iniGetIntValue(NULL, \
				"sync_binlog_buff_interval", &iniContext,\
				SYNC_BINLOG_BUFF_DEF_INTERVAL);
		if (g_sync_binlog_buff_interval <= 0)
		{
			g_sync_binlog_buff_interval=SYNC_BINLOG_BUFF_DEF_INTERVAL;
		}

		g_write_mark_file_freq = iniGetIntValue(NULL, \
				"write_mark_file_freq", &iniContext, \
				FDFS_DEFAULT_SYNC_MARK_FILE_FREQ);
		if (g_write_mark_file_freq <= 0)
		{
			g_write_mark_file_freq = FDFS_DEFAULT_SYNC_MARK_FILE_FREQ;
		}


		g_sync_stat_file_interval = iniGetIntValue(NULL, \
				"sync_stat_file_interval", &iniContext, \
				DEFAULT_SYNC_STAT_FILE_INTERVAL);
		if (g_sync_stat_file_interval <= 0)
		{
			g_sync_stat_file_interval=DEFAULT_SYNC_STAT_FILE_INTERVAL;
		}

		pThreadStackSize = iniGetStrValue(NULL, \
			"thread_stack_size", &iniContext);
		if (pThreadStackSize == NULL)
		{
			thread_stack_size = 512 * 1024;
		}
		else if ((result=parse_bytes(pThreadStackSize, 1, \
				&thread_stack_size)) != 0)
		{
			return result;
		}
		g_thread_stack_size = (int)thread_stack_size;

		if (g_thread_stack_size < 64 * 1024)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"thread_stack_size\" %d is invalid, " \
				"which < %d", __LINE__, g_thread_stack_size, \
				64 * 1024);
			result = EINVAL;
			break;
		}

		g_upload_priority = iniGetIntValue(NULL, \
				"upload_priority", &iniContext, \
				DEFAULT_UPLOAD_PRIORITY);

		pIfAliasPrefix = iniGetStrValue(NULL, \
			"if_alias_prefix", &iniContext);
		if (pIfAliasPrefix == NULL)
		{
			*g_if_alias_prefix = '\0';
		}
		else
		{
			snprintf(g_if_alias_prefix, sizeof(g_if_alias_prefix), 
				"%s", pIfAliasPrefix);
		}

		g_check_file_duplicate = iniGetBoolValue(NULL, \
				"check_file_duplicate", &iniContext, false);
		if (g_check_file_duplicate)
		{
			char *pKeyNamespace;

			strcpy(g_fdht_base_path, g_fdfs_base_path);
			g_fdht_connect_timeout = g_fdfs_connect_timeout;
			g_fdht_network_timeout = g_fdfs_network_timeout;

			pKeyNamespace = iniGetStrValue(NULL, \
				"key_namespace", &iniContext);
			if (pKeyNamespace == NULL || *pKeyNamespace == '\0')
			{
				logError("file: "__FILE__", line: %d, " \
					"item \"key_namespace\" does not " \
					"exist or is empty", __LINE__);
				result = EINVAL;
				break;
			}

			g_namespace_len = strlen(pKeyNamespace);
			if (g_namespace_len >= sizeof(g_key_namespace))
			{
				g_namespace_len = sizeof(g_key_namespace) - 1;
			}
			memcpy(g_key_namespace, pKeyNamespace, g_namespace_len);
			*(g_key_namespace + g_namespace_len) = '\0';

			if ((result=fdht_load_groups(&iniContext, \
					&g_group_array)) != 0)
			{
				break;
			}

			g_keep_alive = iniGetBoolValue(NULL, "keep_alive", \
					&iniContext, false);
		}

		g_http_port = iniGetIntValue(NULL, "http.server_port", \
                                        &iniContext, 80);
		if (g_http_port <= 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"invalid param \"http.server_port\": %d", \
				__LINE__, g_http_port);
			return EINVAL;
		}
 
		pHttpDomain = iniGetStrValue(NULL, \
			"http.domain_name", &iniContext);
		if (pHttpDomain == NULL)
		{
			*g_http_domain = '\0';
		}
		else
		{
			snprintf(g_http_domain, sizeof(g_http_domain), \
				"%s", pHttpDomain);
		}

#ifdef WITH_HTTPD
		{
		char *pHttpTrunkSize;
		int64_t http_trunk_size;

		if ((result=fdfs_http_params_load(&iniContext, \
				filename, &g_http_params)) != 0)
		{
			break;
		}

		pHttpTrunkSize = iniGetStrValue(NULL, \
			"http.trunk_size", &iniContext);
		if (pHttpTrunkSize == NULL)
		{
			http_trunk_size = 64 * 1024;
		}
		else if ((result=parse_bytes(pHttpTrunkSize, 1, \
				&http_trunk_size)) != 0)
		{
			break;
		}

		g_http_trunk_size = (int)http_trunk_size;
		}
#endif

		logInfo("FastDFS v%d.%02d, base_path=%s, store_path_count=%d, " \
			"subdir_count_per_path=%d, group_name=%s, " \
			"run_by_group=%s, run_by_user=%s, " \
			"connect_timeout=%ds, network_timeout=%ds, "\
			"port=%d, bind_addr=%s, client_bind=%d, " \
			"max_connections=%d, work_threads=%d, "    \
			"disk_rw_separated=%d, disk_reader_threads=%d, " \
			"disk_writer_threads=%d, " \
			"buff_size=%dKB, heart_beat_interval=%ds, " \
			"stat_report_interval=%ds, tracker_server_count=%d, " \
			"sync_wait_msec=%dms, sync_interval=%dms, " \
			"sync_start_time=%02d:%02d, sync_end_time=%02d:%02d, "\
			"write_mark_file_freq=%d, " \
			"allow_ip_count=%d, " \
			"file_distribute_path_mode=%d, " \
			"file_distribute_rotate_count=%d, " \
			"fsync_after_written_bytes=%d, " \
			"sync_log_buff_interval=%ds, " \
			"sync_binlog_buff_interval=%ds, " \
			"sync_stat_file_interval=%ds, " \
			"thread_stack_size=%d KB, upload_priority=%d, " \
			"if_alias_prefix=%s, " \
			"check_file_duplicate=%d, FDHT group count=%d, " \
			"FDHT server count=%d, FDHT key_namespace=%s, " \
			"FDHT keep_alive=%d, HTTP server port=%d, " \
			"domain name=%s", \
			g_fdfs_version.major, g_fdfs_version.minor, \
			g_fdfs_base_path, g_fdfs_path_count, g_subdir_count_per_path,\
			g_group_name, g_run_by_group, g_run_by_user, \
			g_fdfs_connect_timeout, \
			g_fdfs_network_timeout, g_server_port, bind_addr, \
			g_client_bind_addr, g_max_connections, \
			g_work_threads, g_disk_rw_separated, \
			g_disk_reader_threads, g_disk_writer_threads, \
			g_buff_size / 1024, \
			g_heart_beat_interval, g_stat_report_interval, \
			g_tracker_group.server_count, g_sync_wait_usec / 1000, \
			g_sync_interval / 1000, \
			g_sync_start_time.hour, g_sync_start_time.minute, \
			g_sync_end_time.hour, g_sync_end_time.minute, \
			g_write_mark_file_freq, \
			g_allow_ip_count, g_file_distribute_path_mode, \
			g_file_distribute_rotate_count, \
			g_fsync_after_written_bytes, g_sync_log_buff_interval, \
			g_sync_binlog_buff_interval, g_sync_stat_file_interval, \
			g_thread_stack_size/1024, g_upload_priority, \
			g_if_alias_prefix, g_check_file_duplicate, \
			g_group_array.group_count, g_group_array.server_count, \
			g_key_namespace, g_keep_alive, \
			g_http_port, g_http_domain);

#ifdef WITH_HTTPD
		if (!g_http_params.disabled)
		{
			logInfo("HTTP supported: " \
				"server_port=%d, " \
				"http_trunk_size=%d, " \
				"default_content_type=%s, " \
				"anti_steal_token=%d, " \
				"token_ttl=%ds, " \
				"anti_steal_secret_key length=%d, "  \
				"token_check_fail content_type=%s, " \
				"token_check_fail buff length=%d",  \
				g_http_params.server_port, \
				g_http_trunk_size, \
				g_http_params.default_content_type, \
				g_http_params.anti_steal_token, \
				g_http_params.token_ttl, \
				g_http_params.anti_steal_secret_key.length, \
				g_http_params.token_check_fail_content_type, \
				g_http_params.token_check_fail_buff.length);
		}
#endif

	} while (0);

	iniFreeContext(&iniContext);

	if (result != 0)
	{
		return result;
	}

	if ((result=storage_get_my_tracker_client_ip()) != 0)
	{
		return result;
	}

	if ((result=storage_check_and_make_data_dirs()) != 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"storage_check_and_make_data_dirs fail, " \
			"program exit!", __LINE__);
		return result;
	}

	if ((result=storage_get_params_from_tracker()) != 0)
	{
		return result;
	}

	if ((result=storage_check_ip_changed()) != 0)
	{
		return result;
	}

	if ((result=init_pthread_lock(&sync_stat_file_lock)) != 0)
	{
		return result;
	}

	return storage_open_stat_file();
}
Пример #6
0
int
main (int argc, char **argv)
{
  int last_argc = -1;
  gpg_error_t err;
  int rc;  parsed_uri_t uri;
  uri_tuple_t r;
  http_t hd;
  int c;
  unsigned int my_http_flags = 0;
  int no_out = 0;
  int tls_dbg = 0;
  int no_crl = 0;
  const char *cafile = NULL;
  http_session_t session = NULL;
  unsigned int timeout = 0;

  gpgrt_init ();
  log_set_prefix (PGM, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
  if (argc)
    { argc--; argv++; }
  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          fputs ("usage: " PGM " URL\n"
                 "Options:\n"
                 "  --verbose         print timings etc.\n"
                 "  --debug           flyswatter\n"
                 "  --tls-debug N     use TLS debug level N\n"
                 "  --cacert FNAME    expect CA certificate in file FNAME\n"
                 "  --timeout MS      timeout for connect in MS\n"
                 "  --no-verify       do not verify the certificate\n"
                 "  --force-tls       use HTTP_FLAG_FORCE_TLS\n"
                 "  --force-tor       use HTTP_FLAG_FORCE_TOR\n"
                 "  --no-out          do not print the content\n"
                 "  --no-crl          do not consuilt a CRL\n",
                 stdout);
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          verbose += 2;
          debug++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--tls-debug"))
        {
          argc--; argv++;
          if (argc)
            {
              tls_dbg = atoi (*argv);
              argc--; argv++;
            }
        }
      else if (!strcmp (*argv, "--cacert"))
        {
          argc--; argv++;
          if (argc)
            {
              cafile = *argv;
              argc--; argv++;
            }
        }
      else if (!strcmp (*argv, "--timeout"))
        {
          argc--; argv++;
          if (argc)
            {
              timeout = strtoul (*argv, NULL, 10);
              argc--; argv++;
            }
        }
      else if (!strcmp (*argv, "--no-verify"))
        {
          no_verify = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--force-tls"))
        {
          my_http_flags |= HTTP_FLAG_FORCE_TLS;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--force-tor"))
        {
          my_http_flags |= HTTP_FLAG_FORCE_TOR;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--no-out"))
        {
          no_out = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--no-crl"))
        {
          no_crl = 1;
          argc--; argv++;
        }
      else if (!strncmp (*argv, "--", 2))
        {
          fprintf (stderr, PGM ": unknown option '%s'\n", *argv);
          exit (1);
        }
    }
  if (argc != 1)
    {
      fprintf (stderr, PGM ": no or too many URLS given\n");
      exit (1);
    }

  if (!cafile)
    cafile = prepend_srcdir ("tls-ca.pem");

  if (verbose)
    my_http_flags |= HTTP_FLAG_LOG_RESP;

  if (verbose || debug)
    http_set_verbose (verbose, debug);

  /* http.c makes use of the assuan socket wrapper.  */
  assuan_sock_init ();

  if ((my_http_flags & HTTP_FLAG_FORCE_TOR))
    {
      enable_dns_tormode (1);
      if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
        {
          log_error ("error enabling Tor mode: %s\n", strerror (errno));
          log_info ("(is your Libassuan recent enough?)\n");
        }
    }

#if HTTP_USE_NTBTLS
  log_info ("new session.\n");
  err = http_session_new (&session, NULL,
                          ((no_crl? HTTP_FLAG_NO_CRL : 0)
                           | HTTP_FLAG_TRUST_DEF),
                          my_http_tls_verify_cb, NULL);
  if (err)
    log_error ("http_session_new failed: %s\n", gpg_strerror (err));
  ntbtls_set_debug (tls_dbg, NULL, NULL);

#elif HTTP_USE_GNUTLS

  rc = gnutls_global_init ();
  if (rc)
    log_error ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));

  http_register_tls_callback (verify_callback);
  http_register_tls_ca (cafile);

  err = http_session_new (&session, NULL,
                          ((no_crl? HTTP_FLAG_NO_CRL : 0)
                           | HTTP_FLAG_TRUST_DEF),
                          NULL, NULL);
  if (err)
    log_error ("http_session_new failed: %s\n", gpg_strerror (err));

  /* rc = gnutls_dh_params_init(&dh_params); */
  /* if (rc) */
  /*   log_error ("gnutls_dh_params_init failed: %s\n", gnutls_strerror (rc)); */
  /* read_dh_params ("dh_param.pem"); */

  /* rc = gnutls_certificate_set_x509_trust_file */
  /*   (certcred, "ca.pem", GNUTLS_X509_FMT_PEM); */
  /* if (rc) */
  /*   log_error ("gnutls_certificate_set_x509_trust_file failed: %s\n", */
  /*              gnutls_strerror (rc)); */

  /* gnutls_certificate_set_dh_params (certcred, dh_params); */

  gnutls_global_set_log_function (my_gnutls_log);
  if (tls_dbg)
    gnutls_global_set_log_level (tls_dbg);

#else
  (void)err;
  (void)tls_dbg;
  (void)no_crl;
#endif /*HTTP_USE_GNUTLS*/

  rc = http_parse_uri (&uri, *argv, 1);
  if (rc)
    {
      log_error ("'%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }

  printf ("Scheme: %s\n", uri->scheme);
  if (uri->opaque)
    printf ("Value : %s\n", uri->path);
  else
    {
      printf ("Auth  : %s\n", uri->auth? uri->auth:"[none]");
      printf ("Host  : %s\n", uri->host);
      printf ("Port  : %u\n", uri->port);
      printf ("Path  : %s\n", uri->path);
      for (r = uri->params; r; r = r->next)
        {
          printf ("Params: %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
      for (r = uri->query; r; r = r->next)
        {
          printf ("Query : %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
      printf ("Flags :%s%s%s%s\n",
              uri->is_http? " http":"",
              uri->opaque?  " opaque":"",
              uri->v6lit?   " v6lit":"",
              uri->onion?   " onion":"");
      printf ("TLS   : %s\n",
              uri->use_tls? "yes":
              (my_http_flags&HTTP_FLAG_FORCE_TLS)? "forced" : "no");
      printf ("Tor   : %s\n",
              (my_http_flags&HTTP_FLAG_FORCE_TOR)? "yes" : "no");

    }
  fflush (stdout);
  http_release_parsed_uri (uri);
  uri = NULL;

  if (session)
    http_session_set_timeout (session, timeout);

  rc = http_open_document (NULL, &hd, *argv, NULL, my_http_flags,
                           NULL, session, NULL, NULL);
  if (rc)
    {
      log_error ("can't get '%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }
  log_info ("open_http_document succeeded; status=%u\n",
            http_get_status_code (hd));

  {
    const char **names;
    int i;

    names = http_get_header_names (hd);
    if (!names)
      log_fatal ("http_get_header_names failed: %s\n",
                 gpg_strerror (gpg_error_from_syserror ()));
    for (i = 0; names[i]; i++)
      printf ("HDR: %s: %s\n", names[i], http_get_header (hd, names[i]));
    xfree (names);
  }
  fflush (stdout);

  switch (http_get_status_code (hd))
    {
    case 200:
    case 400:
    case 401:
    case 403:
    case 404:
      {
        unsigned long count = 0;
        while ((c = es_getc (http_get_read_ptr (hd))) != EOF)
          {
            count++;
            if (!no_out)
              putchar (c);
          }
        log_info ("Received bytes: %lu\n", count);
      }
      break;
    case 301:
    case 302:
    case 307:
      log_info ("Redirected to: %s\n", http_get_header (hd, "Location"));
      break;
    }
  http_close (hd, 0);

  http_session_release (session);
#ifdef HTTP_USE_GNUTLS
  gnutls_global_deinit ();
#endif /*HTTP_USE_GNUTLS*/

  return 0;
}
Пример #7
0
/* 
 
     M A I N

*/
int 
main (int argc, char **argv)
{
  int last_argc = -1;
  assuan_context_t ctx;
  gpg_error_t err;
  int no_close_fds[2];
  const char *arglist[10];
  int is_server = 0;
  int with_exec = 0;
  char *fname = prepend_srcdir ("motd");

  if (argc)
    {
      log_set_prefix (*argv);
      argc--; argv++;
    }
  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--help"))
        {
          puts (
"usage: ./fdpassing [options]\n"
"\n"
"Options:\n"
"  --verbose      Show what is going on\n"
"  --with-exec    Exec the child.  Default is just a fork\n"
);
          exit (0);
        }
      if (!strcmp (*argv, "--verbose"))
        {
          verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          verbose = debug = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--server"))
        {
          is_server = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--with-exec"))
        {
          with_exec = 1;
          argc--; argv++;
        }
    }


  assuan_set_assuan_log_prefix (log_prefix);

  if (is_server)
    {
      server ();
      log_info ("server finished\n");
    }
  else
    {
      const char *loc;

      no_close_fds[0] = 2;
      no_close_fds[1] = -1;
      if (with_exec)
        {
          arglist[0] = "fdpassing";
          arglist[1] = "--server";
          arglist[2] = verbose? "--verbose":NULL;
          arglist[3] = NULL;
        }

      err = assuan_new (&ctx);
      if (err)
	log_fatal ("assuan_new failed: %s\n", gpg_strerror (err));

      err = assuan_pipe_connect (ctx, with_exec? "./fdpassing":NULL,
				 with_exec ? arglist : &loc,
				 no_close_fds, NULL, NULL, 1);
      if (err)
        {
          log_error ("assuan_pipe_connect failed: %s\n", gpg_strerror (err));
          return 1;
        }
      
      if (!with_exec && loc[0] == 's')
        {
          server ();
          log_info ("server finished\n");
        }
      else
        {
          if (client (ctx, fname)) 
            {
              log_info ("waiting for server to terminate...\n");
              assuan_release (ctx);
            }
          log_info ("client finished\n");
        }
    }

  return errorcount ? 1 : 0;
}
Пример #8
0
int
main (int argc, char **argv )
{
  ARGPARSE_ARGS pargs;
  char *raw_pattern;
  size_t raw_pattern_length;
  pattern_t *patternarray;

  set_strusage (my_strusage);
  gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
  log_set_prefix ("gpg-check-pattern", 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init ();
  init_common_subsystems (&argc, &argv);

  /* We need Libgcrypt for hashing.  */
  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
    {
      log_fatal ( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
                  NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
    }

  setup_libgcrypt_logging ();
  gcry_control (GCRYCTL_INIT_SECMEM, 4096, 0);

  opt.homedir = default_homedir ();

  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags=  1;  /* (do not remove the args) */
  while (arg_parse (&pargs, opts) )
    {
      switch (pargs.r_opt)
        {
        case oVerbose: opt.verbose++; break;
        case oHomedir: opt.homedir = pargs.r.ret_str; break;
        case oCheck: opt.checkonly = 1; break;
        case oNull: opt.null = 1; break;

        default : pargs.err = 2; break;
	}
    }
  if (log_get_errorcount(0))
    exit (2);

  if (argc != 1)
    usage (1);

  /* We read the entire pattern file into our memory and parse it
     using a separate function.  This allows us to eventual do the
     reading while running setuid so that the pattern file can be
     hidden from regular users.  I am not sure whether this makes
     sense, but lets be prepared for it.  */
  raw_pattern = read_file (*argv, &raw_pattern_length);
  if (!raw_pattern)
    exit (2);

  patternarray = parse_pattern_file (raw_pattern, raw_pattern_length);
  if (!patternarray)
    exit (1);
  if (opt.checkonly)
    return 0;

#ifdef HAVE_DOSISH_SYSTEM
  setmode (fileno (stdin) , O_BINARY );
#endif
  process (stdin, patternarray);

  return log_get_errorcount(0)? 1 : 0;
}
Пример #9
0
int
main( int argc, char **argv )
{
  ARGPARSE_ARGS pargs;
  int rc=0;
  strlist_t sl;
  strlist_t nrings=NULL;
  unsigned configlineno;
  
  set_strusage (my_strusage);
  log_set_prefix ("gpgv", 1);
  
  /* Make sure that our subsystems are ready.  */
  i18n_init();
  init_common_subsystems ();
  
  gnupg_init_signals (0, NULL);

  opt.command_fd = -1; /* no command fd */
  opt.pgp2_workarounds = 1;
  opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
  opt.trust_model = TM_ALWAYS;
  opt.batch = 1;

  opt.homedir = default_homedir ();

  tty_no_terminal(1);
  tty_batchmode(1);
  disable_dotlock();
  
  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags=  1;  /* do not remove the args */
  while (optfile_parse( NULL, NULL, &configlineno, &pargs, opts))
    {
      switch (pargs.r_opt)
        {
        case oQuiet: opt.quiet = 1; break;
        case oVerbose: 
          opt.verbose++; 
          opt.list_sigs=1;
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
          break;
        case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
        case oStatusFD: set_status_fd( pargs.r.ret_int ); break;
        case oLoggerFD: 
          log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
          break;
        case oHomedir: opt.homedir = pargs.r.ret_str; break;
        case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
        default : pargs.err = ARGPARSE_PRINT_ERROR; break;
	}
    }
  
  if (log_get_errorcount (0))
    g10_exit(2);

  if (opt.verbose > 1)
    set_packet_list_mode(1);

  /* Note: We open all keyrings in read-only mode (flag value: 8).  */
  if (!nrings)  /* No keyring given: use default one. */
    keydb_add_resource ("trustedkeys" EXTSEP_S "gpg", 8, 0);
  for (sl = nrings; sl; sl = sl->next)
    keydb_add_resource (sl->d, 8, 0 );
   
  FREE_STRLIST (nrings);
    
  if ( (rc = verify_signatures( argc, argv ) ))
    log_error("verify signatures failed: %s\n", g10_errstr(rc) );
  
  /* cleanup */
  g10_exit (0);
  return 8; /*NOTREACHED*/
}
Пример #10
0
int
main (int argc, char **argv )
{
  ARGPARSE_ARGS pargs;
  int orig_argc;
  gpg_error_t err;
  int may_coredump;
  char **orig_argv;
  FILE *configfp = NULL;
  char *configname = NULL;
  const char *shell;
  unsigned int configlineno;
  int parse_debug = 0;
  const char *debug_level = NULL;
  int default_config =1;
  int greeting = 0;
  int nogreeting = 0;
  int multi_server = 0;
  int is_daemon = 0;
  int nodetach = 0;
  int csh_style = 0;
  char *logfile = NULL;
  int debug_wait = 0;
  int gpgconf_list = 0;
  const char *config_filename = NULL;
  int allow_coredump = 0;
  int standard_socket = 0;
  struct assuan_malloc_hooks malloc_hooks;

  set_strusage (my_strusage);
  gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
  /* Please note that we may running SUID(ROOT), so be very CAREFUL
     when adding any stuff between here and the call to INIT_SECMEM()
     somewhere after the option parsing */
  log_set_prefix ("scdaemon", 1|4);

  /* Make sure that our subsystems are ready.  */
  i18n_init ();
  init_common_subsystems (&argc, &argv);


  /* Libgcrypt requires us to register the threading model first.
     Note that this will also do the pth_init. */
  gcry_threads_pth.init = fixed_gcry_pth_init;
  err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
  if (err)
    {
      log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
                 gpg_strerror (err));
    }

  /* Check that the libraries are suitable.  Do it here because
     the option parsing may need services of the library */
  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
    {
      log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
                 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
    }

  ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);

  malloc_hooks.malloc = gcry_malloc;
  malloc_hooks.realloc = gcry_realloc;
  malloc_hooks.free = gcry_free;
  assuan_set_malloc_hooks (&malloc_hooks);
  assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
  assuan_set_system_hooks (ASSUAN_SYSTEM_PTH);
  assuan_sock_init ();
  setup_libassuan_logging (&opt.debug);

  setup_libgcrypt_logging ();
  gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);

  may_coredump = disable_core_dumps ();

  /* Set default options. */
  opt.allow_admin = 1;
  opt.pcsc_driver = DEFAULT_PCSC_DRIVER;

#ifdef HAVE_W32_SYSTEM
  standard_socket = 1;  /* Under Windows we always use a standard
                           socket.  */
#endif


  shell = getenv ("SHELL");
  if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
    csh_style = 1;

  opt.homedir = default_homedir ();

  /* Check whether we have a config file on the commandline */
  orig_argc = argc;
  orig_argv = argv;
  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
  while (arg_parse( &pargs, opts))
    {
      if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
        parse_debug++;
      else if (pargs.r_opt == oOptions)
        { /* yes there is one, so we do not try the default one, but
	     read the option file when it is encountered at the
	     commandline */
          default_config = 0;
	}
	else if (pargs.r_opt == oNoOptions)
          default_config = 0; /* --no-options */
	else if (pargs.r_opt == oHomedir)
          opt.homedir = pargs.r.ret_str;
    }

  /* initialize the secure memory. */
  gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
  maybe_setuid = 0;

  /*
     Now we are working under our real uid
  */


  if (default_config)
    configname = make_filename (opt.homedir, "scdaemon.conf", NULL );


  argc = orig_argc;
  argv = orig_argv;
  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags=  1;  /* do not remove the args */
 next_pass:
  if (configname)
    {
      configlineno = 0;
      configfp = fopen (configname, "r");
      if (!configfp)
        {
          if (default_config)
            {
              if( parse_debug )
                log_info (_("NOTE: no default option file `%s'\n"),
                          configname );
	    }
          else
            {
              log_error (_("option file `%s': %s\n"),
                         configname, strerror(errno) );
              exit(2);
	    }
          xfree (configname);
          configname = NULL;
	}
      if (parse_debug && configname )
        log_info (_("reading options from `%s'\n"), configname );
      default_config = 0;
    }

  while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
    {
      switch (pargs.r_opt)
        {
        case aGPGConfList: gpgconf_list = 1; break;
        case aGPGConfTest: gpgconf_list = 2; break;
        case oQuiet: opt.quiet = 1; break;
        case oVerbose: opt.verbose++; break;
        case oBatch: opt.batch=1; break;

        case oDebug: opt.debug |= pargs.r.ret_ulong; break;
        case oDebugAll: opt.debug = ~0; break;
        case oDebugLevel: debug_level = pargs.r.ret_str; break;
        case oDebugWait: debug_wait = pargs.r.ret_int; break;
        case oDebugAllowCoreDump:
          enable_core_dumps ();
          allow_coredump = 1;
          break;
        case oDebugCCIDDriver:
#ifdef HAVE_LIBUSB
          ccid_set_debug_level (ccid_set_debug_level (-1)+1);
#endif /*HAVE_LIBUSB*/
          break;
        case oDebugDisableTicker: ticker_disabled = 1; break;
        case oDebugLogTid:
          log_set_pid_suffix_cb (tid_log_callback);
          break;

        case oOptions:
          /* config files may not be nested (silently ignore them) */
          if (!configfp)
            {
		xfree(configname);
		configname = xstrdup(pargs.r.ret_str);
		goto next_pass;
	    }
          break;
        case oNoGreeting: nogreeting = 1; break;
        case oNoVerbose: opt.verbose = 0; break;
        case oNoOptions: break; /* no-options */
        case oHomedir: opt.homedir = pargs.r.ret_str; break;
        case oNoDetach: nodetach = 1; break;
        case oLogFile: logfile = pargs.r.ret_str; break;
        case oCsh: csh_style = 1; break;
        case oSh: csh_style = 0; break;
        case oServer: pipe_server = 1; break;
        case oMultiServer: pipe_server = 1; multi_server = 1; break;
        case oDaemon: is_daemon = 1; break;

        case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
        case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
        case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
        case oDisableCCID: opt.disable_ccid = 1; break;
        case oDisableOpenSC: break;

        case oDisableKeypad: opt.disable_keypad = 1; break;

        case oAllowAdmin: /* Dummy because allow is now the default.  */
          break;
        case oDenyAdmin: opt.allow_admin = 0; break;

        case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;

        case oDisableApplication:
          add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
          break;

        default:
          pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
          break;
	}
    }
  if (configfp)
    {
      fclose( configfp );
      configfp = NULL;
      /* Keep a copy of the config name for use by --gpgconf-list. */
      config_filename = configname;
      configname = NULL;
      goto next_pass;
    }
  xfree (configname);
  configname = NULL;
  if (log_get_errorcount(0))
    exit(2);
  if (nogreeting )
    greeting = 0;

  if (greeting)
    {
      es_fprintf (es_stderr, "%s %s; %s\n",
                  strusage(11), strusage(13), strusage(14) );
      es_fprintf (es_stderr, "%s\n", strusage(15) );
    }
#ifdef IS_DEVELOPMENT_VERSION
  log_info ("NOTE: this is a development version!\n");
#endif


  if (atexit (cleanup))
    {
      log_error ("atexit failed\n");
      cleanup ();
      exit (1);
    }

  set_debug (debug_level);

  initialize_module_command ();

  if (gpgconf_list == 2)
    scd_exit (0);
  if (gpgconf_list)
    {
      /* List options and default values in the GPG Conf format.  */
      char *filename = NULL;
      char *filename_esc;

      if (config_filename)
	filename = xstrdup (config_filename);
      else
        filename = make_filename (opt.homedir, "scdaemon.conf", NULL);
      filename_esc = percent_escape (filename, NULL);

      es_printf ("gpgconf-scdaemon.conf:%lu:\"%s\n",
                 GC_OPT_FLAG_DEFAULT, filename_esc);
      xfree (filename_esc);
      xfree (filename);

      es_printf ("verbose:%lu:\n"
                 "quiet:%lu:\n"
                 "debug-level:%lu:\"none:\n"
                 "log-file:%lu:\n",
                 GC_OPT_FLAG_NONE,
                 GC_OPT_FLAG_NONE,
                 GC_OPT_FLAG_DEFAULT,
                 GC_OPT_FLAG_NONE );

      es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
      es_printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
      es_printf ("pcsc-driver:%lu:\"%s:\n",
              GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
#ifdef HAVE_LIBUSB
      es_printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
#endif
      es_printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE );
      es_printf ("disable-keypad:%lu:\n", GC_OPT_FLAG_NONE );
      es_printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);

      scd_exit (0);
    }

  /* Now start with logging to a file if this is desired.  */
  if (logfile)
    {
      log_set_file (logfile);
      log_set_prefix (NULL, 1|2|4);
    }

  if (debug_wait && pipe_server)
    {
      log_debug ("waiting for debugger - my pid is %u .....\n",
                 (unsigned int)getpid());
      gnupg_sleep (debug_wait);
      log_debug ("... okay\n");
    }

  if (pipe_server)
    {
      /* This is the simple pipe based server */
      ctrl_t ctrl;
      pth_attr_t tattr;
      int fd = -1;

#ifndef HAVE_W32_SYSTEM
      {
        struct sigaction sa;

        sa.sa_handler = SIG_IGN;
        sigemptyset (&sa.sa_mask);
        sa.sa_flags = 0;
        sigaction (SIGPIPE, &sa, NULL);
      }
#endif

      /* If --debug-allow-core-dump has been given we also need to
         switch the working directory to a place where we can actually
         write. */
      if (allow_coredump)
        {
          if (chdir("/tmp"))
            log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno));
          else
            log_debug ("changed working directory to `/tmp'\n");
        }

      /* In multi server mode we need to listen on an additional
         socket.  Create that socket now before starting the handler
         for the pipe connection.  This allows that handler to send
         back the name of that socket. */
      if (multi_server)
        {
          socket_name = create_socket_name (standard_socket,
                                            "S.scdaemon",
                                            "gpg-XXXXXX/S.scdaemon");

          fd = FD2INT(create_server_socket (standard_socket,
                                            socket_name, &socket_nonce));
        }

      tattr = pth_attr_new();
      pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
      pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
      pth_attr_set (tattr, PTH_ATTR_NAME, "pipe-connection");

      ctrl = xtrycalloc (1, sizeof *ctrl);
      if ( !ctrl )
        {
          log_error ("error allocating connection control data: %s\n",
                     strerror (errno) );
          scd_exit (2);
        }
      ctrl->thread_startup.fd = GNUPG_INVALID_FD;
      if ( !pth_spawn (tattr, start_connection_thread, ctrl) )
        {
          log_error ("error spawning pipe connection handler: %s\n",
                     strerror (errno) );
          xfree (ctrl);
          scd_exit (2);
        }

      /* We run handle_connection to wait for the shutdown signal and
         to run the ticker stuff.  */
      handle_connections (fd);
      if (fd != -1)
        close (fd);
    }
  else if (!is_daemon)
    {
      log_info (_("please use the option `--daemon'"
                  " to run the program in the background\n"));
    }
  else
    { /* Regular server mode */
      int fd;
#ifndef HAVE_W32_SYSTEM
      pid_t pid;
      int i;
#endif

      /* Create the socket.  */
      socket_name = create_socket_name (standard_socket,
                                        "S.scdaemon",
                                        "gpg-XXXXXX/S.scdaemon");

      fd = FD2INT (create_server_socket (standard_socket,
                                         socket_name, &socket_nonce));


      fflush (NULL);
#ifndef HAVE_W32_SYSTEM
      pid = fork ();
      if (pid == (pid_t)-1)
        {
          log_fatal ("fork failed: %s\n", strerror (errno) );
          exit (1);
        }
      else if (pid)
        { /* we are the parent */
          char *infostr;

          close (fd);

          /* create the info string: <name>:<pid>:<protocol_version> */
          if (estream_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
				socket_name, (ulong) pid) < 0)
            {
              log_error ("out of core\n");
              kill (pid, SIGTERM);
              exit (1);
            }
          *socket_name = 0; /* don't let cleanup() remove the socket -
                               the child should do this from now on */
          if (argc)
            { /* run the program given on the commandline */
              if (putenv (infostr))
                {
                  log_error ("failed to set environment: %s\n",
                             strerror (errno) );
                  kill (pid, SIGTERM );
                  exit (1);
                }
              execvp (argv[0], argv);
              log_error ("failed to run the command: %s\n", strerror (errno));
              kill (pid, SIGTERM);
              exit (1);
            }
          else
            {
              /* Print the environment string, so that the caller can use
                 shell's eval to set it */
              if (csh_style)
                {
                  *strchr (infostr, '=') = ' ';
                  es_printf ( "setenv %s\n", infostr);
                }
              else
                {
                  es_printf ( "%s; export SCDAEMON_INFO;\n", infostr);
                }
              xfree (infostr);
              exit (0);
            }
          /* NOTREACHED */
        } /* end parent */

      /* This is the child. */

      /* Detach from tty and put process into a new session. */
      if (!nodetach )
        {
          /* Close stdin, stdout and stderr unless it is the log stream. */
          for (i=0; i <= 2; i++)
            {
              if ( log_test_fd (i) && i != fd)
                close (i);
            }
          if (setsid() == -1)
            {
              log_error ("setsid() failed: %s\n", strerror(errno) );
              cleanup ();
              exit (1);
            }
        }

      {
        struct sigaction sa;

        sa.sa_handler = SIG_IGN;
        sigemptyset (&sa.sa_mask);
        sa.sa_flags = 0;
        sigaction (SIGPIPE, &sa, NULL);
      }

      if (chdir("/"))
        {
          log_error ("chdir to / failed: %s\n", strerror (errno));
          exit (1);
        }

#endif /*!HAVE_W32_SYSTEM*/

      handle_connections (fd);

      close (fd);
    }

  return 0;
}
Пример #11
0
int tracker_load_from_conf_file(const char *filename, \
		char *bind_addr, const int addr_size)
{
	char *pBasePath;
	char *pBindAddr;
	char *pRunByGroup;
	char *pRunByUser;
	char *pThreadStackSize;
	char *pSlotMinSize;
	char *pSlotMaxSize;
	char *pSpaceThreshold;
	char *pTrunkFileSize;
	char *pRotateErrorLogSize;
    char *pMinBuffSize;
    char *pMaxBuffSize;
#ifdef WITH_HTTPD
	char *pHttpCheckUri;
	char *pHttpCheckType;
#endif
	IniContext iniContext;
	int result;
	int64_t thread_stack_size;
	int64_t trunk_file_size;
	int64_t slot_min_size;
	int64_t slot_max_size;
	int64_t rotate_error_log_size;
    int64_t min_buff_size;
    int64_t max_buff_size;
    char sz_min_buff_size[32];
    char sz_max_buff_size[32];
	char reserved_space_str[32];

	memset(&g_groups, 0, sizeof(FDFSGroups));
	memset(&iniContext, 0, sizeof(IniContext));
	if ((result=iniLoadFromFile(filename, &iniContext)) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"load conf file \"%s\" fail, ret code: %d", \
			__LINE__, filename, result);
		return result;
	}

	//iniPrintItems(&iniContext);

	do
	{
		if (iniGetBoolValue(NULL, "disabled", &iniContext, false))
		{
			logError("file: "__FILE__", line: %d, " \
				"conf file \"%s\" disabled=true, exit", \
				__LINE__, filename);
			result = ECANCELED;
			break;
		}

		pBasePath = iniGetStrValue(NULL, "base_path", &iniContext);
		if (pBasePath == NULL)
		{
			logError("file: "__FILE__", line: %d, " \
				"conf file \"%s\" must have item " \
				"\"base_path\"!", __LINE__, filename);
			result = ENOENT;
			break;
		}

		snprintf(g_fdfs_base_path, sizeof(g_fdfs_base_path), "%s", pBasePath);
		chopPath(g_fdfs_base_path);
		if (!fileExists(g_fdfs_base_path))
		{
			logError("file: "__FILE__", line: %d, " \
				"\"%s\" can't be accessed, error info: %s", \
				__LINE__, g_fdfs_base_path, STRERROR(errno));
			result = errno != 0 ? errno : ENOENT;
			break;
		}
		if (!isDir(g_fdfs_base_path))
		{
			logError("file: "__FILE__", line: %d, " \
				"\"%s\" is not a directory!", \
				__LINE__, g_fdfs_base_path);
			result = ENOTDIR;
			break;
		}

		load_log_level(&iniContext);
		if ((result=log_set_prefix(g_fdfs_base_path, \
				TRACKER_ERROR_LOG_FILENAME)) != 0)
		{
			break;
		}

		g_fdfs_connect_timeout = iniGetIntValue(NULL, "connect_timeout", \
				&iniContext, DEFAULT_CONNECT_TIMEOUT);
		if (g_fdfs_connect_timeout <= 0)
		{
			g_fdfs_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
		}

		g_fdfs_network_timeout = iniGetIntValue(NULL, "network_timeout", \
				&iniContext, DEFAULT_NETWORK_TIMEOUT);
		if (g_fdfs_network_timeout <= 0)
		{
			g_fdfs_network_timeout = DEFAULT_NETWORK_TIMEOUT;
		}

		g_server_port = iniGetIntValue(NULL, "port", &iniContext, \
				FDFS_TRACKER_SERVER_DEF_PORT);
		if (g_server_port <= 0)
		{
			g_server_port = FDFS_TRACKER_SERVER_DEF_PORT;
		}

		pBindAddr = iniGetStrValue(NULL, "bind_addr", &iniContext);
		if (pBindAddr == NULL)
		{
			bind_addr[0] = '\0';
		}
		else
		{
			snprintf(bind_addr, addr_size, "%s", pBindAddr);
		}

		if ((result=tracker_load_store_lookup(filename, \
			&iniContext)) != 0)
		{
			break;
		}

		g_groups.store_server = (byte)iniGetIntValue(NULL, \
				"store_server",  &iniContext, \
				FDFS_STORE_SERVER_ROUND_ROBIN);
		if (!(g_groups.store_server == FDFS_STORE_SERVER_FIRST_BY_IP ||\
			g_groups.store_server == FDFS_STORE_SERVER_FIRST_BY_PRI||
			g_groups.store_server == FDFS_STORE_SERVER_ROUND_ROBIN))
		{
			logWarning("file: "__FILE__", line: %d, " \
				"store_server 's value %d is invalid, " \
				"set to %d (round robin)!", \
				__LINE__, g_groups.store_server, \
				FDFS_STORE_SERVER_ROUND_ROBIN);

			g_groups.store_server = FDFS_STORE_SERVER_ROUND_ROBIN;
		}

		g_groups.download_server = (byte)iniGetIntValue(NULL, \
			"download_server", &iniContext, \
			FDFS_DOWNLOAD_SERVER_ROUND_ROBIN);
		if (!(g_groups.download_server==FDFS_DOWNLOAD_SERVER_ROUND_ROBIN
			|| g_groups.download_server == 
				FDFS_DOWNLOAD_SERVER_SOURCE_FIRST))
		{
			logWarning("file: "__FILE__", line: %d, " \
				"download_server 's value %d is invalid, " \
				"set to %d (round robin)!", \
				__LINE__, g_groups.download_server, \
				FDFS_DOWNLOAD_SERVER_ROUND_ROBIN);

			g_groups.download_server = \
				FDFS_DOWNLOAD_SERVER_ROUND_ROBIN;
		}

		g_groups.store_path = (byte)iniGetIntValue(NULL, "store_path", \
			&iniContext, FDFS_STORE_PATH_ROUND_ROBIN);
		if (!(g_groups.store_path == FDFS_STORE_PATH_ROUND_ROBIN || \
			g_groups.store_path == FDFS_STORE_PATH_LOAD_BALANCE))
		{
			logWarning("file: "__FILE__", line: %d, " \
				"store_path 's value %d is invalid, " \
				"set to %d (round robin)!", \
				__LINE__, g_groups.store_path , \
				FDFS_STORE_PATH_ROUND_ROBIN);
			g_groups.store_path = FDFS_STORE_PATH_ROUND_ROBIN;
		}

		if ((result=fdfs_parse_storage_reserved_space(&iniContext, \
				&g_storage_reserved_space)) != 0)
		{
			break;
		}

		g_max_connections = iniGetIntValue(NULL, "max_connections", \
				&iniContext, DEFAULT_MAX_CONNECTONS);
		if (g_max_connections <= 0)
		{
			g_max_connections = DEFAULT_MAX_CONNECTONS;
		}
	
		g_accept_threads = iniGetIntValue(NULL, "accept_threads", \
				&iniContext, 1);
		if (g_accept_threads <= 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"accept_threads\" is invalid, " \
				"value: %d <= 0!", __LINE__, g_accept_threads);
			result = EINVAL;
                        break;
		}

		g_work_threads = iniGetIntValue(NULL, "work_threads", \
				&iniContext, DEFAULT_WORK_THREADS);
		if (g_work_threads <= 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"work_threads\" is invalid, " \
				"value: %d <= 0!", __LINE__, g_work_threads);
			result = EINVAL;
                        break;
		}

		if ((result=set_rlimit(RLIMIT_NOFILE, g_max_connections)) != 0)
		{
			break;
		}
	
		pRunByGroup = iniGetStrValue(NULL, "run_by_group", &iniContext);
		pRunByUser = iniGetStrValue(NULL, "run_by_user", &iniContext);
		if (pRunByGroup == NULL)
		{
			*g_run_by_group = '\0';
		}
		else
		{
			snprintf(g_run_by_group, sizeof(g_run_by_group), \
				"%s", pRunByGroup);
		}
		if (*g_run_by_group == '\0')
		{
			g_run_by_gid = getegid();
		}
		else
		{
			struct group *pGroup;

     			pGroup = getgrnam(g_run_by_group);
			if (pGroup == NULL)
			{
				result = errno != 0 ? errno : ENOENT;
				logError("file: "__FILE__", line: %d, " \
					"getgrnam fail, errno: %d, " \
					"error info: %s", __LINE__, \
					result, STRERROR(result));
				return result;
			}

			g_run_by_gid = pGroup->gr_gid;
		}


		if (pRunByUser == NULL)
		{
			*g_run_by_user = '******';
		}
		else
		{
			snprintf(g_run_by_user, sizeof(g_run_by_user), \
				"%s", pRunByUser);
		}
		if (*g_run_by_user == '\0')
		{
			g_run_by_uid = geteuid();
		}
		else
		{
			struct passwd *pUser;

     			pUser = getpwnam(g_run_by_user);
			if (pUser == NULL)
			{
				result = errno != 0 ? errno : ENOENT;
				logError("file: "__FILE__", line: %d, " \
					"getpwnam fail, errno: %d, " \
					"error info: %s", __LINE__, \
					result, STRERROR(result));
				return result;
			}

			g_run_by_uid = pUser->pw_uid;
		}

		if ((result=load_allow_hosts(&iniContext, \
                	 &g_allow_ip_addrs, &g_allow_ip_count)) != 0)
		{
			return result;
		}

		g_sync_log_buff_interval = iniGetIntValue(NULL, \
				"sync_log_buff_interval", &iniContext, \
				SYNC_LOG_BUFF_DEF_INTERVAL);
		if (g_sync_log_buff_interval <= 0)
		{
			g_sync_log_buff_interval = SYNC_LOG_BUFF_DEF_INTERVAL;
		}

		g_check_active_interval = iniGetIntValue(NULL, \
				"check_active_interval", &iniContext, \
				CHECK_ACTIVE_DEF_INTERVAL);
		if (g_check_active_interval <= 0)
		{
			g_check_active_interval = CHECK_ACTIVE_DEF_INTERVAL;
		}

		pThreadStackSize = iniGetStrValue(NULL, \
			"thread_stack_size", &iniContext);
		if (pThreadStackSize == NULL)
		{
			thread_stack_size = 64 * 1024;
		}
		else if ((result=parse_bytes(pThreadStackSize, 1, \
				&thread_stack_size)) != 0)
		{
			return result;
		}
		g_thread_stack_size = (int)thread_stack_size;

		g_storage_ip_changed_auto_adjust = iniGetBoolValue(NULL, \
				"storage_ip_changed_auto_adjust", \
				&iniContext, true);

		g_storage_sync_file_max_delay = iniGetIntValue(NULL, \
				"storage_sync_file_max_delay", &iniContext, \
				DEFAULT_STORAGE_SYNC_FILE_MAX_DELAY);
		if (g_storage_sync_file_max_delay <= 0)
		{
			g_storage_sync_file_max_delay = \
					DEFAULT_STORAGE_SYNC_FILE_MAX_DELAY;
		}

		g_storage_sync_file_max_time = iniGetIntValue(NULL, \
				"storage_sync_file_max_time", &iniContext, \
				DEFAULT_STORAGE_SYNC_FILE_MAX_TIME);
		if (g_storage_sync_file_max_time <= 0)
		{
			g_storage_sync_file_max_time = \
				DEFAULT_STORAGE_SYNC_FILE_MAX_TIME;
		}

		g_if_use_trunk_file = iniGetBoolValue(NULL, \
			"use_trunk_file", &iniContext, false);

		pSlotMinSize = iniGetStrValue(NULL, \
			"slot_min_size", &iniContext);
		if (pSlotMinSize == NULL)
		{
			slot_min_size = 256;
		}
		else if ((result=parse_bytes(pSlotMinSize, 1, \
				&slot_min_size)) != 0)
		{
			return result;
		}
		g_slot_min_size = (int)slot_min_size;
		if (g_slot_min_size <= 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"slot_min_size\" %d is invalid, " \
				"which <= 0", __LINE__, g_slot_min_size);
			result = EINVAL;
			break;
		}
		if (g_slot_min_size > 64 * 1024)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"item \"slot_min_size\" %d is too large, " \
				"change to 64KB", __LINE__, g_slot_min_size);
			g_slot_min_size = 64 * 1024;
		}

		pTrunkFileSize = iniGetStrValue(NULL, \
			"trunk_file_size", &iniContext);
		if (pTrunkFileSize == NULL)
		{
			trunk_file_size = 64 * 1024 * 1024;
		}
		else if ((result=parse_bytes(pTrunkFileSize, 1, \
				&trunk_file_size)) != 0)
		{
			return result;
		}
		g_trunk_file_size = (int)trunk_file_size;
		if (g_trunk_file_size < 4 * 1024 * 1024)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"item \"trunk_file_size\" %d is too small, " \
				"change to 4MB", __LINE__, g_trunk_file_size);
			g_trunk_file_size = 4 * 1024 * 1024;
		}

		pSlotMaxSize = iniGetStrValue(NULL, \
			"slot_max_size", &iniContext);
		if (pSlotMaxSize == NULL)
		{
			slot_max_size = g_trunk_file_size / 2;
		}
		else if ((result=parse_bytes(pSlotMaxSize, 1, \
				&slot_max_size)) != 0)
		{
			return result;
		}
		g_slot_max_size = (int)slot_max_size;
		if (g_slot_max_size <= g_slot_min_size)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"slot_max_size\" %d is invalid, " \
				"which <= slot_min_size: %d", \
				__LINE__, g_slot_max_size, g_slot_min_size);
			result = EINVAL;
			break;
		}
		if (g_slot_max_size > g_trunk_file_size / 2)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"item \"slot_max_size\": %d is too large, " \
				"change to %d", __LINE__, g_slot_max_size, \
				g_trunk_file_size / 2);
			g_slot_max_size = g_trunk_file_size / 2;
		}

		g_trunk_create_file_advance = iniGetBoolValue(NULL, \
			"trunk_create_file_advance", &iniContext, false);
		if ((result=get_time_item_from_conf(&iniContext, \
                	"trunk_create_file_time_base", \
			&g_trunk_create_file_time_base, 2, 0)) != 0)
		{
			return result;
		}

		g_trunk_create_file_interval = iniGetIntValue(NULL, \
				"trunk_create_file_interval", &iniContext, \
				86400);
		pSpaceThreshold = iniGetStrValue(NULL, \
			"trunk_create_file_space_threshold", &iniContext);
		if (pSpaceThreshold == NULL)
		{
			g_trunk_create_file_space_threshold = 0;
		}
		else if ((result=parse_bytes(pSpaceThreshold, 1, \
				&g_trunk_create_file_space_threshold)) != 0)
		{
			return result;
		}
		g_trunk_compress_binlog_min_interval = iniGetIntValue(NULL, \
				"trunk_compress_binlog_min_interval", \
				&iniContext, 0);

		g_trunk_init_check_occupying = iniGetBoolValue(NULL, \
			"trunk_init_check_occupying", &iniContext, false);

		g_trunk_init_reload_from_binlog = iniGetBoolValue(NULL, \
			"trunk_init_reload_from_binlog", &iniContext, false);

		if ((result=tracker_load_storage_id_info( \
				filename, &iniContext)) != 0)
		{
			return result;
		}

		g_rotate_error_log = iniGetBoolValue(NULL, "rotate_error_log",\
					&iniContext, false);
		if ((result=get_time_item_from_conf(&iniContext, \
			"error_log_rotate_time", &g_error_log_rotate_time, \
			0, 0)) != 0)
		{
			break;
		}

		pRotateErrorLogSize = iniGetStrValue(NULL, \
			"rotate_error_log_size", &iniContext);
		if (pRotateErrorLogSize == NULL)
		{
			rotate_error_log_size = 0;
		}
		else if ((result=parse_bytes(pRotateErrorLogSize, 1, \
				&rotate_error_log_size)) != 0)
		{
			break;
		}
		if (rotate_error_log_size > 0 && \
			rotate_error_log_size < FDFS_ONE_MB)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"item \"rotate_error_log_size\": " \
				"%"PRId64" is too small, " \
				"change to 1 MB", __LINE__, \
				rotate_error_log_size);
			rotate_error_log_size = FDFS_ONE_MB;
		}
		fdfs_set_log_rotate_size(&g_log_context, rotate_error_log_size);

		g_log_file_keep_days = iniGetIntValue(NULL, \
				"log_file_keep_days", &iniContext, 0);

		g_store_slave_file_use_link = iniGetBoolValue(NULL, \
			"store_slave_file_use_link", &iniContext, false);

		if ((result=fdfs_connection_pool_init(filename, &iniContext)) != 0)
		{
			break;
		}


        pMinBuffSize = iniGetStrValue(NULL,
                "min_buff_size", &iniContext);
        if (pMinBuffSize == NULL) {
            min_buff_size = TRACKER_MAX_PACKAGE_SIZE;
        }
        else if ((result=parse_bytes(pMinBuffSize, 1,
                        &min_buff_size)) != 0)
        {
            return result;
        }
        g_min_buff_size = (int)min_buff_size;

        pMaxBuffSize = iniGetStrValue(NULL,
                "max_buff_size", &iniContext);
        if (pMaxBuffSize == NULL) {
            max_buff_size = 16 * TRACKER_MAX_PACKAGE_SIZE;
        }
        else if ((result=parse_bytes(pMaxBuffSize, 1,
                        &max_buff_size)) != 0)
        {
            return result;
        }
        g_max_buff_size = (int)max_buff_size;

        if (g_min_buff_size < TRACKER_MAX_PACKAGE_SIZE) {
            g_min_buff_size = TRACKER_MAX_PACKAGE_SIZE;
        }
        if (g_max_buff_size < g_min_buff_size) {
            g_max_buff_size = g_min_buff_size;
        }

#ifdef WITH_HTTPD
		if ((result=fdfs_http_params_load(&iniContext, \
				filename, &g_http_params)) != 0)
		{
			return result;
		}

		g_http_check_interval = iniGetIntValue(NULL, \
			"http.check_alive_interval", &iniContext, 30);

		pHttpCheckType = iniGetStrValue(NULL, \
			"http.check_alive_type", &iniContext);
		if (pHttpCheckType != NULL && \
			strcasecmp(pHttpCheckType, "http") == 0)
		{
			g_http_check_type = FDFS_HTTP_CHECK_ALIVE_TYPE_HTTP;
		}
		else
		{
			g_http_check_type = FDFS_HTTP_CHECK_ALIVE_TYPE_TCP;
		}

		pHttpCheckUri = iniGetStrValue(NULL, \
			"http.check_alive_uri", &iniContext);
		if (pHttpCheckUri == NULL)
		{
			*g_http_check_uri = '/';
			*(g_http_check_uri+1) = '\0';
		}
		else if (*pHttpCheckUri == '/')
		{
			snprintf(g_http_check_uri, sizeof(g_http_check_uri), \
				"%s", pHttpCheckUri);
		}
		else
		{
			snprintf(g_http_check_uri, sizeof(g_http_check_uri), \
				"/%s", pHttpCheckUri);
		}


#endif

        if (g_if_use_trunk_file && g_groups.store_server == FDFS_STORE_SERVER_ROUND_ROBIN)
        {
            logInfo("file: "__FILE__", line: %d, "
                    "set store_server to %d because use_trunk_file is true",
                    __LINE__, FDFS_STORE_SERVER_FIRST_BY_IP);
            g_groups.store_server = FDFS_STORE_SERVER_FIRST_BY_IP;
        }

        int_to_comma_str(g_min_buff_size, sz_min_buff_size);
        int_to_comma_str(g_max_buff_size, sz_max_buff_size);

		logInfo("FastDFS v%d.%02d, base_path=%s, " \
			"run_by_group=%s, run_by_user=%s, " \
			"connect_timeout=%ds, "    \
			"network_timeout=%ds, "    \
			"port=%d, bind_addr=%s, " \
			"max_connections=%d, "    \
			"accept_threads=%d, "    \
			"work_threads=%d, "    \
            "min_buff_size=%s, " \
            "max_buff_size=%s, " \
			"store_lookup=%d, store_group=%s, " \
			"store_server=%d, store_path=%d, " \
			"reserved_storage_space=%s, " \
			"download_server=%d, " \
			"allow_ip_count=%d, sync_log_buff_interval=%ds, " \
			"check_active_interval=%ds, " \
			"thread_stack_size=%d KB, " \
			"storage_ip_changed_auto_adjust=%d, "  \
			"storage_sync_file_max_delay=%ds, " \
			"storage_sync_file_max_time=%ds, "  \
			"use_trunk_file=%d, " \
			"slot_min_size=%d, " \
			"slot_max_size=%d MB, " \
			"trunk_file_size=%d MB, " \
			"trunk_create_file_advance=%d, " \
			"trunk_create_file_time_base=%02d:%02d, " \
			"trunk_create_file_interval=%d, " \
			"trunk_create_file_space_threshold=%d GB, " \
			"trunk_init_check_occupying=%d, " \
			"trunk_init_reload_from_binlog=%d, " \
			"trunk_compress_binlog_min_interval=%d, " \
			"use_storage_id=%d, " \
			"id_type_in_filename=%s, " \
			"storage_id_count=%d, " \
			"rotate_error_log=%d, " \
			"error_log_rotate_time=%02d:%02d, " \
			"rotate_error_log_size=%"PRId64", " \
			"log_file_keep_days=%d, " \
			"store_slave_file_use_link=%d, " \
			"use_connection_pool=%d, " \
			"g_connection_pool_max_idle_time=%ds", \
			g_fdfs_version.major, g_fdfs_version.minor,  \
			g_fdfs_base_path, g_run_by_group, g_run_by_user, \
			g_fdfs_connect_timeout, \
			g_fdfs_network_timeout, g_server_port, bind_addr, \
			g_max_connections, g_accept_threads, g_work_threads, \
            sz_min_buff_size, sz_max_buff_size, \
			g_groups.store_lookup, g_groups.store_group, \
			g_groups.store_server, g_groups.store_path, \
			fdfs_storage_reserved_space_to_string( \
			    &g_storage_reserved_space, reserved_space_str), \
			g_groups.download_server, \
			g_allow_ip_count, g_sync_log_buff_interval, \
			g_check_active_interval, g_thread_stack_size / 1024, \
			g_storage_ip_changed_auto_adjust, \
			g_storage_sync_file_max_delay, \
			g_storage_sync_file_max_time, \
			g_if_use_trunk_file, g_slot_min_size, \
			g_slot_max_size / FDFS_ONE_MB, \
			g_trunk_file_size / FDFS_ONE_MB, \
			g_trunk_create_file_advance, \
			g_trunk_create_file_time_base.hour, \
			g_trunk_create_file_time_base.minute, \
			g_trunk_create_file_interval, \
			(int)(g_trunk_create_file_space_threshold / \
			(FDFS_ONE_MB * 1024)), g_trunk_init_check_occupying, \
			g_trunk_init_reload_from_binlog, \
			g_trunk_compress_binlog_min_interval, \
			g_use_storage_id, g_id_type_in_filename == \
			FDFS_ID_TYPE_SERVER_ID ? "id" : "ip", g_storage_id_count, \
			g_rotate_error_log, g_error_log_rotate_time.hour, \
			g_error_log_rotate_time.minute, \
			g_log_context.rotate_size, g_log_file_keep_days,
			g_store_slave_file_use_link, \
			g_use_connection_pool, g_connection_pool_max_idle_time);

#ifdef WITH_HTTPD
		if (!g_http_params.disabled)
		{
			logInfo("HTTP supported: " \
				"server_port=%d, " \
				"default_content_type=%s, " \
				"anti_steal_token=%d, " \
				"token_ttl=%ds, " \
				"anti_steal_secret_key length=%d, "  \
				"token_check_fail content_type=%s, " \
				"token_check_fail buff length=%d, "  \
				"check_active_interval=%d, " \
				"check_active_type=%s, " \
				"check_active_uri=%s",  \
				g_http_params.server_port, \
				g_http_params.default_content_type, \
				g_http_params.anti_steal_token, \
				g_http_params.token_ttl, \
				g_http_params.anti_steal_secret_key.length, \
				g_http_params.token_check_fail_content_type, \
				g_http_params.token_check_fail_buff.length, \
				g_http_check_interval, g_http_check_type == \
				FDFS_HTTP_CHECK_ALIVE_TYPE_TCP ? "tcp":"http",\
				g_http_check_uri);
		}
#endif

	} while (0);

	iniFreeContext(&iniContext);

	load_local_host_ip_addrs();

	return result;
}
Пример #12
0
int
main (int argc, char **argv )
{
  ARGPARSE_ARGS pargs;
  int slot, rc;
  const char *reader_port = NULL;
  struct app_ctx_s appbuf;

  memset (&appbuf, 0, sizeof appbuf);

  set_strusage (my_strusage);
  gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
  log_set_prefix ("sc-copykeys", 1);

  /* check that the libraries are suitable.  Do it here because
     the option parsing may need services of the library */
  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
    {
      log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
                 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
    }

  setup_libgcrypt_logging ();
  gcry_control (GCRYCTL_DISABLE_SECMEM, 0); /* FIXME - we want to use it */
  /* FIXME? gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);*/

  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags=  1;  /* do not remove the args */
  while (arg_parse (&pargs, opts) )
    {
      switch (pargs.r_opt)
        {
        case oVerbose: opt.verbose++; break;
        case oDebug: opt.debug |= pargs.r.ret_ulong; break;
        case oDebugAll: opt.debug = ~0; break;
        case oReaderPort: reader_port = pargs.r.ret_str; break;
        case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
        default : pargs.err = 2; break;
	}
    }
  if (log_get_errorcount(0))
    exit(2);

  if (argc != 1)
    usage (1);

  slot = apdu_open_reader (reader_port, NULL);
  if (slot == -1)
    exit (1);
  if (apdu_connect (slot))
    exit (1);

  /* FIXME: Use select_application. */
  appbuf.slot = slot;
  rc = app_select_openpgp (&appbuf);
  if (rc)
    {
      log_error ("selecting openpgp failed: %s\n", gpg_strerror (rc));
      exit (1);
    }
  appbuf.initialized = 1;
  log_info ("openpgp application selected\n");

  copykeys (&appbuf, *argv);


  return 0;
}
Пример #13
0
int main(int argc, char *argv[])
{
	char *conf_filename;
	int result;
	int success_count;
	int fail_count;
	int expires;
	FDHTKeyInfo key_info;
	char szValue[101];
	char *pValue;
	int value_len;
	struct sigaction act;
	int i;

	printf("This is FastDHT client test program v%d.%02d\n" \
"\nCopyright (C) 2008, Happy Fish / YuQing\n" \
"\nFastDHT may be copied only under the terms of the GNU General\n" \
"Public License V3, which may be found in the FastDHT source kit.\n" \
"Please visit the FastDHT Home Page http://www.csource.org/ \n" \
"for more detail.\n\n" \
, g_fdht_version.major, g_fdht_version.minor);

	if (argc < 2)
	{
		printf("Usage: %s <config_file>\n", argv[0]);
		return 1;
	}

	log_init();
	conf_filename = argv[1];

	g_log_context.log_level = LOG_DEBUG;
	if ((result=fdht_client_init(conf_filename)) != 0)
	{
		return result;
	}

	log_set_prefix(g_fdht_base_path, "fdht_test_get");
	log_set_cache(false);

	memset(&act, 0, sizeof(act));
	sigemptyset(&act.sa_mask);
	act.sa_handler = SIG_IGN;
	if(sigaction(SIGPIPE, &act, NULL) < 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"call sigaction fail, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		return errno;
	}

	srand(time(NULL));

	expires = 0;
	memset(&key_info, 0, sizeof(key_info));

	value_len = sizeof(szValue) - 1;
	for (i=0; i<value_len; i++)
	{
		szValue[i] = (char)rand();
	}

	g_keep_alive = true;
	if (g_keep_alive)
	{
		if ((result=fdht_connect_all_servers(&g_group_array, true, \
			&success_count, &fail_count)) != 0)
		{
			printf("fdht_connect_all_servers fail, " \
				"error code: %d, error info: %s\n", \
				result, STRERROR(result));
			return result;
		}
	}

	key_info.key_len = sprintf(key_info.szKey, "k%015d", rand());
	if ((result=fdht_set(&key_info, expires, szValue, value_len)) != 0)
	{
		return result;
	}

	pValue = szValue;
	success_count = 0;
	fail_count = 0;
	for (i=1; i<=100000; i++)
	{
		if (i % 10000 == 0)
		{
			printf("current: %d\n", i);
			fflush(stdout);
		}

		value_len = sizeof(szValue);
		if ((result=fdht_get(&key_info, &pValue, &value_len)) != 0)
		{
			logError("fdht_get return %d", result);
			fail_count++;
		}
		else
		{
			success_count++;
		}
	}

	if (g_keep_alive)
	{
		fdht_disconnect_all_servers(&g_group_array);
	}

	fdht_client_destroy();

	printf("success count=%d, fail count=%d\n", success_count, fail_count);

	return result;
}
Пример #14
0
/* Uaaahahahh, ich will dir einloggen!  PAM authentication entry
   point.  */
PAM_EXTERN int
pam_sm_authenticate (pam_handle_t *pam_handle,
		     int flags, int argc, const char **argv)
{
  const void *conv_void;
  gpg_error_t err; 
  poldi_ctx_t ctx;
  conv_t conv;
  scd_context_t scd_ctx;
  int ret;
  const char *pam_username;
  struct auth_method_parse_cookie method_parse_cookie = { NULL, NULL };
  simpleparse_handle_t method_parse;
  struct getpin_cb_data getpin_cb_data;

  pam_username = NULL;
  scd_ctx = NULL;
  conv = NULL;
  ctx = NULL;
  method_parse = NULL;
  err = 0;

  /*** Basic initialization. ***/

  bindtextdomain (PACKAGE, LOCALEDIR);

  /* Initialize Libgcrypt.  Disable secure memory for now; because of
     the implicit priviledge dropping, having secure memory enabled
     causes the following error:

     su: Authentication service cannot retrieve authentication
     info. */
  gcry_control (GCRYCTL_DISABLE_SECMEM);

  /*** Setup main context.  ***/

  err = create_context (&ctx, pam_handle);
  if (err)
    goto out;

  /* Setup logging prefix.  */
  log_set_flags (ctx->loghandle,
		 LOG_FLAG_WITH_PREFIX | LOG_FLAG_WITH_TIME | LOG_FLAG_WITH_PID);
  log_set_prefix (ctx->loghandle, "Poldi");
  log_set_backend_syslog (ctx->loghandle);

  /*** Parse auth-method independent options.  ***/

  /* ... from configuration file:  */
  err = simpleparse_parse_file (ctx->parsehandle, 0, POLDI_CONF_FILE);
  if (err)
    {
      log_msg_error (ctx->loghandle,
		     _("failed to parse configuration file '%s': %s"),
		     POLDI_CONF_FILE,
		     gpg_strerror (err));
      goto out;
    }

  /* ... and from argument vector provided by PAM: */
  if (argc)
    {
      err = simpleparse_parse (ctx->parsehandle, 0, argc, argv, NULL);
      if (err)
	{
	  log_msg_error (ctx->loghandle,
			 _("failed to parse PAM argument vector: %s"),
			 gpg_strerror (err));
	  goto out;
	}
    }

  /*** Initialize logging. ***/

  /* In case `logfile' has been set in the configuration file,
     initialize jnlib-logging the traditional file, loggin to the file
     (or socket special file) specified in the configuration file; in
     case `logfile' has NOT been set in the configuration file, log
     through Syslog.  */
  if (ctx->logfile)
    {
      gpg_error_t rc;

      rc = log_set_backend_file (ctx->loghandle, ctx->logfile);
      if (rc != 0)
	/* Last try...  */
	log_set_backend_syslog (ctx->loghandle);
    }

  /*** Sanity checks. ***/

  /* Authentication method to use must be specified.  */
  if (ctx->auth_method < 0)
    {
      log_msg_error (ctx->loghandle,
		     _("no authentication method specified"));
      err = GPG_ERR_CONFIGURATION;
      goto out;
    }

  /* Authentication methods must provide a parser callback in case
     they have specific a configuration file.  */
  assert ((!auth_methods[ctx->auth_method].method->config)
	  || (auth_methods[ctx->auth_method].method->parsecb
	      && auth_methods[ctx->auth_method].method->opt_specs));

  if (ctx->debug)
    {
      log_msg_debug (ctx->loghandle,
		     _("using authentication method `%s'"),
		     auth_methods[ctx->auth_method].name);
    }

  /*** Init authentication method.  ***/
  
  if (auth_methods[ctx->auth_method].method->func_init)
    {
      err = (*auth_methods[ctx->auth_method].method->func_init) (&ctx->cookie);
      if (err)
	{
	  log_msg_error (ctx->loghandle,
			 _("failed to initialize authentication method %i: %s"),
			 -1, gpg_strerror (err));
	  goto out;
	}
    }

  if (auth_methods[ctx->auth_method].method->config)
    {
      /* Do auth-method specific parsing. */

      err = simpleparse_create (&method_parse);
      if (err)
	{
	  log_msg_error (ctx->loghandle,
			 _("failed to initialize parsing of configuration file for authentication method %s: %s"),
			 auth_methods[ctx->auth_method].name, gpg_strerror (err));
	  goto out_parsing;
	}

      method_parse_cookie.poldi_ctx = ctx;
      method_parse_cookie.method_ctx = ctx->cookie;

      simpleparse_set_loghandle (method_parse, ctx->loghandle);
      simpleparse_set_parse_cb (method_parse,
				auth_methods[ctx->auth_method].method->parsecb,
				&method_parse_cookie);
      simpleparse_set_i18n_cb (method_parse, i18n_cb, NULL);
      simpleparse_set_specs (method_parse,
			     auth_methods[ctx->auth_method].method->opt_specs);

      err = simpleparse_parse_file (method_parse, 0, 
				    auth_methods[ctx->auth_method].method->config);
      if (err)
	{
	  log_msg_error (ctx->loghandle,
			 _("failed to parse configuration for authentication method %i: %s"),
			 auth_methods[ctx->auth_method].name, gpg_strerror (err));
	  goto out_parsing;
	}

    out_parsing:

      simpleparse_destroy (method_parse);
      if (err)
	goto out;
    }

  /*** Prepare PAM interaction.  ***/

  /* Ask PAM for conv structure.  */
  ret = pam_get_item (ctx->pam_handle, PAM_CONV, &conv_void);
  if (ret != PAM_SUCCESS)
    {
      log_msg_error (ctx->loghandle,
		     _("failed to retrieve PAM conversation structure"));
      err = GPG_ERR_INTERNAL;
      goto out;
    }

  /* Init conv subsystem by creating a conv_t object.  */
  err = conv_create (&conv, conv_void);
  if (err)
    goto out;

  ctx->conv = conv;

  /*** Retrieve username from PAM.  ***/

  err = retrieve_username_from_pam (ctx->pam_handle, &pam_username);
  if (err)
    {
      log_msg_error (ctx->loghandle,
		     _("failed to retrieve username from PAM: %s"),
		     gpg_strerror (err));
    }

  /*** Connect to Scdaemon. ***/

  err = scd_connect (&scd_ctx,
		     NULL, getenv ("GPG_AGENT_INFO"),
		     ctx->scdaemon_program, ctx->scdaemon_options,
		     0, ctx->loghandle);
  if (err)
    goto out;

  ctx->scd = scd_ctx;

  /* Install PIN retrival callback. */
  getpin_cb_data.poldi_ctx = ctx;
  scd_set_pincb (ctx->scd, getpin_cb, &getpin_cb_data);

  /*** Wait for card insertion.  ***/

  if (pam_username)
    {
      if (ctx->debug)
	log_msg_debug (ctx->loghandle, _("Waiting for card for user `%s'..."), pam_username);
      if (!ctx->quiet)
	conv_tell (ctx->conv, _("Insert authentication card for user `%s'"), pam_username);
    }
  else
    {
      if (ctx->debug)
	log_msg_debug (ctx->loghandle, _("Waiting for card..."));
      if (!ctx->quiet)
	conv_tell (ctx->conv, _("Insert authentication card"));
    }

  err = wait_for_card (ctx->scd, 0);
  if (err)
    {
      log_msg_error (ctx->loghandle,
		     _("failed to wait for card insertion: %s"),
		     gpg_strerror (err));
      goto out;
    }

  /*** Receive card info. ***/

  err = scd_learn (ctx->scd, &ctx->cardinfo);
  if (err)
    goto out;

  if (ctx->debug)
    log_msg_debug (ctx->loghandle,
		   _("connected to card; serial number is: %s"),
		   ctx->cardinfo.serialno);

  /*** Authenticate.  ***/

  if (pam_username)
    {
      /* Try to authenticate user as PAM_USERNAME.  */

      if (!(*auth_methods[ctx->auth_method].method->func_auth_as) (ctx, ctx->cookie,
								   pam_username))
	/* Authentication failed.  */
	err = GPG_ERR_GENERAL;
    }
  else
    {
      /* Try to authenticate user, choosing an identity is up to the
	 user.  */

      char *username_authenticated = NULL;

      if (!(*auth_methods[ctx->auth_method].method->func_auth) (ctx, ctx->cookie,
								&username_authenticated))
	/* Authentication failed.  */
	err = GPG_ERR_GENERAL;
      else
	{
	  /* Send username received during authentication process back
	     to PAM.  */
	  err = send_username_to_pam (ctx->pam_handle, username_authenticated);
	  xfree (username_authenticated);
	}
    }

 out:

  /* Log result.  */
  if (err)
    log_msg_error (ctx->loghandle, _("authentication failed: %s"), gpg_strerror (err));
  else
    {
      if (ctx->debug)
	log_msg_debug (ctx->loghandle, _("authentication succeeded"));
      if (ctx->modify_environment)
	modify_environment (pam_handle, ctx);
    }

  /* Call authentication method's deinit callback. */
  if ((ctx->auth_method >= 0)
      && auth_methods[ctx->auth_method].method->func_deinit)
    (*auth_methods[ctx->auth_method].method->func_deinit) (ctx->cookie);

  /* FIXME, cosmetics? */
  conv_destroy (conv);
  destroy_context (ctx);

  /* Return to PAM.  */

  return err ? PAM_AUTH_ERR : PAM_SUCCESS;
}
Пример #15
0
int
main (int argc, char **argv )
{
  ARGPARSE_ARGS pargs;
  assuan_context_t ctx;
  gpg_error_t err;
  unsigned char *certbuf;
  size_t certbuflen = 0;
  int cmd_ping = 0;
  int cmd_cache_cert = 0;
  int cmd_validate = 0;
  int cmd_lookup = 0;
  int cmd_loadcrl = 0;
  int cmd_squid_mode = 0;

  set_strusage (my_strusage);
  log_set_prefix ("dirmngr-client",
                  JNLIB_LOG_WITH_PREFIX);

  /* For W32 we need to initialize the socket subsystem.  Becuase we
     don't use Pth we need to do this explicit. */
#ifdef HAVE_W32_SYSTEM
 {
   WSADATA wsadat;

   WSAStartup (0x202, &wsadat);
 }
#endif /*HAVE_W32_SYSTEM*/

  /* Init Assuan.  */
  assuan_set_assuan_log_prefix (log_get_prefix (NULL));
  assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);

  /* Setup I18N. */
  i18n_init();

  /* Parse the command line.  */
  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags= 1;  /* Do not remove the args. */
  while (arg_parse (&pargs, opts) )
    {
      switch (pargs.r_opt)
        {
        case oVerbose: opt.verbose++; break;
        case oQuiet: opt.quiet++; break;

        case oOCSP: opt.use_ocsp++; break;
        case oPing: cmd_ping = 1; break;
        case oCacheCert: cmd_cache_cert = 1; break;
        case oValidate: cmd_validate = 1; break;
        case oLookup: cmd_lookup = 1; break;
        case oUrl: opt.url = 1; break;
        case oLocal: opt.local = 1; break;
        case oLoadCRL: cmd_loadcrl = 1; break;
        case oPEM: opt.pem = 1; break;
        case oSquidMode:
          opt.pem = 1;
          opt.escaped_pem = 1;
          cmd_squid_mode = 1;
          break;
        case oForceDefaultResponder: opt.force_default_responder = 1; break;

        default : pargs.err = 2; break;
	}
    }
  if (log_get_errorcount (0))
    exit (2);

  /* Build the helptable for radix64 to bin conversion. */
  if (opt.pem)
    {
      int i;
      unsigned char *s;

      for (i=0; i < 256; i++ )
        asctobin[i] = 255; /* Used to detect invalid characters. */
      for (s=bintoasc, i=0; *s; s++, i++)
        asctobin[*s] = i;
    }


  if (cmd_ping)
    err = 0;
  else if (cmd_lookup || cmd_loadcrl)
    {
      if (!argc)
        usage (1);
      err = 0;
    }
  else if (cmd_squid_mode)
    {
      err = 0;
      if (argc)
        usage (1);
    }
  else if (!argc)
    {
      err = read_certificate (NULL, &certbuf, &certbuflen);
      if (err)
        log_error (_("error reading certificate from stdin: %s\n"),
                   gpg_strerror (err));
    }
  else if (argc == 1)
    {
      err = read_certificate (*argv, &certbuf, &certbuflen);
      if (err)
        log_error (_("error reading certificate from '%s': %s\n"),
                   *argv, gpg_strerror (err));
    }
  else
    {
      err = 0;
      usage (1);
    }

  if (log_get_errorcount (0))
    exit (2);

  if (certbuflen > 20000)
    {
      log_error (_("certificate too large to make any sense\n"));
      exit (2);
    }

  ctx = start_dirmngr (1);
  if (!ctx)
    exit (2);

  if (cmd_ping)
    ;
  else if (cmd_squid_mode)
    {
      while (!(err = squid_loop_body (ctx)))
        ;
      if (gpg_err_code (err) == GPG_ERR_EOF)
        err = 0;
    }
  else if (cmd_lookup)
    {
      int last_err = 0;

      for (; argc; argc--, argv++)
        {
          err = do_lookup (ctx, *argv);
          if (err)
            {
              log_error (_("lookup failed: %s\n"), gpg_strerror (err));
              last_err = err;
            }
        }
      err = last_err;
    }
  else if (cmd_loadcrl)
    {
      int last_err = 0;

      for (; argc; argc--, argv++)
        {
          err = do_loadcrl (ctx, *argv);
          if (err)
            {
              log_error (_("loading CRL '%s' failed: %s\n"),
                         *argv, gpg_strerror (err));
              last_err = err;
            }
        }
      err = last_err;
    }
  else if (cmd_cache_cert)
    {
      err = do_cache (ctx, certbuf, certbuflen);
      xfree (certbuf);
    }
  else if (cmd_validate)
    {
      err = do_validate (ctx, certbuf, certbuflen);
      xfree (certbuf);
    }
  else
    {
      err = do_check (ctx, certbuf, certbuflen);
      xfree (certbuf);
    }

  assuan_release (ctx);

  if (cmd_ping)
    {
      if (!opt.quiet)
        log_info (_("a dirmngr daemon is up and running\n"));
      return 0;
    }
  else if (cmd_lookup|| cmd_loadcrl || cmd_squid_mode)
    return err? 1:0;
  else if (cmd_cache_cert)
    {
      if (err && gpg_err_code (err) == GPG_ERR_DUP_VALUE )
        {
          if (!opt.quiet)
            log_info (_("certificate already cached\n"));
        }
      else if (err)
        {
          log_error (_("error caching certificate: %s\n"),
                     gpg_strerror (err));
          return 1;
        }
      return 0;
    }
  else if (cmd_validate && err)
    {
      log_error (_("validation of certificate failed: %s\n"),
                 gpg_strerror (err));
      return 1;
    }
  else if (!err)
    {
      if (!opt.quiet)
        log_info (_("certificate is valid\n"));
      return 0;
    }
  else if (gpg_err_code (err) == GPG_ERR_CERT_REVOKED )
    {
      if (!opt.quiet)
        log_info (_("certificate has been revoked\n"));
      return 1;
    }
  else
    {
      log_error (_("certificate check failed: %s\n"), gpg_strerror (err));
      return 2;
    }
}
Пример #16
0
/* gpgconf main. */
int
main (int argc, char **argv)
{
  ARGPARSE_ARGS pargs;
  const char *fname;
  int no_more_options = 0;
  enum cmd_and_opt_values cmd = 0;
  FILE *outfp = NULL;

  gnupg_reopen_std ("gpgconf");
  set_strusage (my_strusage);
  log_set_prefix ("gpgconf", 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init();
  init_common_subsystems ();

  /* Parse the command line. */
  pargs.argc  = &argc;
  pargs.argv  = &argv;
  pargs.flags =  1;  /* Do not remove the args.  */
  while (!no_more_options && optfile_parse (NULL, NULL, NULL, &pargs, opts))
    {
      switch (pargs.r_opt)
        {
        case oOutput:    opt.outfile = pargs.r.ret_str; break;
	case oQuiet:     opt.quiet = 1; break;
        case oDryRun:    opt.dry_run = 1; break;
        case oRuntime:
	  opt.runtime = 1;
	  break;
        case oVerbose:   opt.verbose++; break;
        case oNoVerbose: opt.verbose = 0; break;

	case aListDirs:
        case aListComponents:
        case aCheckPrograms:
        case aListOptions:
        case aChangeOptions:
        case aCheckOptions:
        case aApplyDefaults:
        case aListConfig:
        case aCheckConfig:
        case aReload:
	  cmd = pargs.r_opt;
	  break;

        default: pargs.err = 2; break;
	}
    }

  if (log_get_errorcount (0))
    exit (2);
  
  fname = argc ? *argv : NULL;
  
  switch (cmd)
    {
    case aListComponents:
    default:
      /* List all components. */
      gc_component_list_components (get_outfp (&outfp));
      break;

    case aCheckPrograms:
      /* Check all programs. */
      gc_check_programs (get_outfp (&outfp));
      break;

    case aListOptions:
    case aChangeOptions:
    case aCheckOptions:
      if (!fname)
	{
	  fputs (_("usage: gpgconf [options] "), stderr);
	  putc ('\n',stderr);
	  fputs (_("Need one component argument"), stderr);
	  putc ('\n',stderr);
	  exit (2);
	}
      else
	{
	  int idx = gc_component_find (fname);
	  if (idx < 0)
	    {
	      fputs (_("Component not found"), stderr);
	      putc ('\n', stderr);
	      exit (1);
	    }
	  if (cmd == aCheckOptions)
	    gc_component_check_options (idx, get_outfp (&outfp), NULL);
          else
            {
              gc_component_retrieve_options (idx);
              if (gc_process_gpgconf_conf (NULL, 1, 0, NULL))
                exit (1);
              if (cmd == aListOptions)
                gc_component_list_options (idx, get_outfp (&outfp));
              else if (cmd == aChangeOptions)
                gc_component_change_options (idx, stdin, get_outfp (&outfp));
            }
	}
      break;

    case aReload:
      if (!fname)
	{
          /* Reload all.  */
          gc_component_reload (-1);
	}
      else
        {
          /* Reload given component.  */
          int idx;

          idx = gc_component_find (fname);
          if (idx < 0)
            {
              fputs (_("Component not found"), stderr);
              putc ('\n', stderr);
              exit (1);
            }
          else
            {
              gc_component_reload (idx);
            }
        }
      break;

    case aListConfig:
      if (gc_process_gpgconf_conf (fname, 0, 0, get_outfp (&outfp)))
        exit (1);
      break;

    case aCheckConfig:
      if (gc_process_gpgconf_conf (fname, 0, 0, NULL))
        exit (1);
      break;

    case aApplyDefaults:
      if (fname)
	{
	  fputs (_("usage: gpgconf [options] "), stderr);
	  putc ('\n',stderr);
	  fputs (_("No argument allowed"), stderr);
	  putc ('\n',stderr);
	  exit (2);
	}
      gc_component_retrieve_options (-1);
      if (gc_process_gpgconf_conf (NULL, 1, 1, NULL))
        exit (1);
      break;
      
    case aListDirs:
      /* Show the system configuration directories for gpgconf.  */
      get_outfp (&outfp);
      fprintf (outfp, "sysconfdir:%s\n",
	       gc_percent_escape (gnupg_sysconfdir ()));
      fprintf (outfp, "bindir:%s\n",
	       gc_percent_escape (gnupg_bindir ()));
      fprintf (outfp, "libexecdir:%s\n",
	       gc_percent_escape (gnupg_libexecdir ()));
      fprintf (outfp, "libdir:%s\n",
	       gc_percent_escape (gnupg_libdir ()));
      fprintf (outfp, "datadir:%s\n",
	       gc_percent_escape (gnupg_datadir ()));
      fprintf (outfp, "localedir:%s\n",
	       gc_percent_escape (gnupg_localedir ()));
      fprintf (outfp, "dirmngr-socket:%s\n",
	       gc_percent_escape (dirmngr_socket_name ()));
      {
        char *infostr = getenv ("GPG_AGENT_INFO");

        if (!infostr || !*infostr)
          infostr = make_filename (default_homedir (), "S.gpg-agent", NULL);
        else
          {
            char *tmp;

            infostr = xstrdup (infostr);
            tmp = strchr (infostr, PATHSEP_C);
            if (!tmp || tmp == infostr)
              {
                xfree (infostr);
                infostr = NULL;
              }
            else
              *tmp = 0;
          }
        fprintf (outfp, "agent-socket:%s\n",
                 infostr? gc_percent_escape (infostr) : "");
        xfree (infostr);
      }
      {
        /* We need to use make_filename to expand a possible "~/".  */
        char *tmp = make_filename (default_homedir (), NULL);
        fprintf (outfp, "homedir:%s\n", gc_percent_escape (tmp));
        xfree (tmp);
      }
      break;
    }

  if (outfp && outfp != stdout)
    if (fclose (outfp))
      gc_error (1, errno, "error closing `%s'", opt.outfile);

  return 0; 
}
Пример #17
0
int
tnt_fork(int imsg_fds[2]) {
    pid_t pid;
    struct imsgbuf ibuf;
    struct imsg_data data;
    struct passwd *pw;
    struct event_base *evbase = NULL;
    struct event *sigterm = NULL;
    struct event *sigint = NULL;
    struct event *imsg_event = NULL;
    struct server server;
    struct event_config *evcfg;

    switch ((pid = fork())) {
        case -1:
            log_err(TNT_OSERR, "fork");
            break;
        case 0:
            tnt_setproctitle("[unpriv]");
            log_set_prefix("unpriv");
            break;
        default:
            tnt_setproctitle("[priv]");
            log_set_prefix("priv");
            return pid;
    }

    if ((pw = getpwnam(TNETACLE_USER)) == NULL) {
        log_errx(1, "unknown user " TNETACLE_USER);
        return TNT_NOUSER;
    }

    /*Allocate the event config*/
    evcfg = event_config_new();

    /* Initialize the OpenSSL library */
    SSL_library_init();
    SSL_load_error_strings();
    /* We MUST have entropy, or else there's no point to crypto. */
    if (!RAND_poll())
    {
        log_errx(TNT_SOFTWARE, "[INIT] failed to find an entropy source");
        /* never returns */
    }

    if (serv_opts.encryption)
        server.server_ctx = evssl_init();
    else
        server.server_ctx = NULL;

    tnt_priv_drop(pw);

#if defined(Darwin)
    /* It's sad isn't it ?*/
    event_config_avoid_method(evcfg, "kqueue");
    event_config_avoid_method(evcfg, "poll");
    event_config_avoid_method(evcfg, "devpoll");
    if ((evbase = event_base_new_with_config(evcfg)) == NULL) {
        log_err(1, "libevent");
    }
#else
    if ((evbase = event_base_new_with_config(evcfg)) == NULL) {
        log_err(1, "libevent");
    }
#endif

    sigterm = event_new(evbase, SIGTERM, EV_SIGNAL, &chld_sighdlr, evbase);
    sigint = event_new(evbase, SIGINT, EV_SIGNAL, &chld_sighdlr, evbase);

    signal(SIGPIPE, SIG_IGN);
    signal(SIGHUP, SIG_IGN);
    signal(SIGCHLD, SIG_DFL);

    if (server_init(&server, evbase) == -1)
        log_errx(1, "failed to init the server socket");

    data.ibuf = &ibuf;
    data.evbase = evbase;
    data.server = &server;
    imsg_event = init_pipe_endpoint(imsg_fds, &data);

    event_add(sigterm, NULL);
    event_add(sigint, NULL);
    event_add(imsg_event, NULL);

    log_info("tnetacle ready");

    /* Immediately request the creation of a tun interface */
    imsg_compose(&ibuf, IMSG_CREATE_DEV, 0, 0, -1, NULL, 0);

    log_info("starting event loop");
    event_base_dispatch(evbase);

    /* cleanely exit */
    msgbuf_write(&ibuf.w);
    msgbuf_clear(&ibuf.w);

    /* Shutdown the server */
    server_delete(&server);

    /*
     * It may look like we freed this one twice,
     * once here and once in tnetacled.c but this is not the case.
     * Please don't erase this !
     */

    event_free(sigterm);
    event_free(sigint);
    close(event_get_fd(imsg_event));
    event_free(imsg_event);
    event_base_free(evbase);
    event_config_free(evcfg);

    log_info("tnetacle exiting");
    exit(TNT_OK);
}
Пример #18
0
int
main ( int argc, char **argv)
{
  ARGPARSE_ARGS pargs;
  int orig_argc;
  char **orig_argv;
  gpg_error_t err = 0;
  /* const char *fname; */
  int may_coredump;
  FILE *configfp = NULL;
  char *configname = NULL;
  unsigned configlineno;
  int parse_debug = 0;
  int no_more_options = 0;
  int default_config =1;
  char *logfile = NULL;
  /* int debug_wait = 0; */
  int use_random_seed = 1;
  /* int nodetach = 0; */
  /* int nokeysetup = 0; */
  struct server_control_s ctrl;

  /*mtrace();*/

  early_system_init ();
  gnupg_reopen_std (G13_NAME "-syshelp");
  set_strusage (my_strusage);
  gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);

  log_set_prefix (G13_NAME "-syshelp", 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init ();
  init_common_subsystems (&argc, &argv);

  /* Check that the Libgcrypt is suitable.  */
  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
    log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
               NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );

  /* Take extra care of the random pool.  */
  gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);

  may_coredump = disable_core_dumps ();

  g13_init_signals ();

  dotlock_create (NULL, 0); /* Register locking cleanup.  */

  opt.session_env = session_env_new ();
  if (!opt.session_env)
    log_fatal ("error allocating session environment block: %s\n",
               strerror (errno));

  opt.homedir = default_homedir ();
  /* Fixme: We enable verbose mode here because there is currently no
     way to do this when starting g13-syshelp.  To fix that we should
     add a g13-syshelp.conf file in /etc/gnupg.  */
  opt.verbose = 1;

  /* First check whether we have a debug option on the commandline.  */
  orig_argc = argc;
  orig_argv = argv;
  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
  while (arg_parse( &pargs, opts))
    {
      if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
        parse_debug++;
    }

  /* Initialize the secure memory. */
  gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
  maybe_setuid = 0;

  /*
     Now we are now working under our real uid
  */

  /* Setup malloc hooks. */
  {
    struct assuan_malloc_hooks malloc_hooks;

    malloc_hooks.malloc = gcry_malloc;
    malloc_hooks.realloc = gcry_realloc;
    malloc_hooks.free = gcry_free;
    assuan_set_malloc_hooks (&malloc_hooks);
  }

  /* Prepare libassuan.  */
  assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
  /*assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);*/
  setup_libassuan_logging (&opt.debug);

  /* Setup a default control structure for command line mode.  */
  memset (&ctrl, 0, sizeof ctrl);
  g13_syshelp_init_default_ctrl (&ctrl);
  ctrl.no_server = 1;
  ctrl.status_fd = -1; /* No status output. */

  if (default_config )
    configname = make_filename (gnupg_sysconfdir (),
                                G13_NAME"-syshelp.conf", NULL);

  argc        = orig_argc;
  argv        = orig_argv;
  pargs.argc  = &argc;
  pargs.argv  = &argv;
  pargs.flags =  1;  /* Do not remove the args.  */

 next_pass:
  if (configname)
    {
      configlineno = 0;
      configfp = fopen (configname, "r");
      if (!configfp)
        {
          if (default_config)
            {
              if (parse_debug)
                log_info (_("NOTE: no default option file '%s'\n"), configname);
            }
          else
            {
              log_error (_("option file '%s': %s\n"),
                         configname, strerror(errno));
              g13_exit(2);
            }
          xfree (configname);
          configname = NULL;
        }
      if (parse_debug && configname)
        log_info (_("reading options from '%s'\n"), configname);
      default_config = 0;
    }

  while (!no_more_options
         && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
    {
      switch (pargs.r_opt)
        {
        case oQuiet: opt.quiet = 1; break;

        case oDryRun: opt.dry_run = 1; break;

        case oVerbose:
          opt.verbose++;
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
          break;
        case oNoVerbose:
          opt.verbose = 0;
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
          break;

        case oLogFile: logfile = pargs.r.ret_str; break;
        case oNoLogFile: logfile = NULL; break;

        case oNoDetach: /*nodetach = 1; */break;

        case oDebug:
          if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
            {
              pargs.r_opt = ARGPARSE_INVALID_ARG;
              pargs.err = ARGPARSE_PRINT_ERROR;
            }
            break;
        case oDebugAll: debug_value = ~0; break;
        case oDebugNone: debug_value = 0; break;
        case oDebugLevel: debug_level = pargs.r.ret_str; break;
        case oDebugWait: /*debug_wait = pargs.r.ret_int; */break;
        case oDebugAllowCoreDump:
          may_coredump = enable_core_dumps ();
          break;

        case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
        case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;

        case oHomedir: opt.homedir = pargs.r.ret_str; break;

        case oFakedSystemTime:
          {
            time_t faked_time = isotime2epoch (pargs.r.ret_str);
            if (faked_time == (time_t)(-1))
              faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
            gnupg_set_time (faked_time, 0);
          }
          break;

        case oNoSecmemWarn: gcry_control (GCRYCTL_DISABLE_SECMEM_WARN); break;

        case oNoRandomSeedFile: use_random_seed = 0; break;

        default:
          pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
          break;
	}
    }

  if (configfp)
    {
      fclose (configfp);
      configfp = NULL;
      /* Keep a copy of the config filename. */
      opt.config_filename = configname;
      configname = NULL;
      goto next_pass;
    }
  xfree (configname);
  configname = NULL;

  if (!opt.config_filename)
    opt.config_filename = make_filename (opt.homedir, G13_NAME".conf", NULL);

  if (log_get_errorcount(0))
    g13_exit(2);

  /* Now that we have the options parsed we need to update the default
     control structure.  */
  g13_syshelp_init_default_ctrl (&ctrl);

  if (may_coredump && !opt.quiet)
    log_info (_("WARNING: program may create a core file!\n"));

  if (logfile)
    {
      log_set_file (logfile);
      log_set_prefix (NULL, 1|2|4);
    }

  if (gnupg_faked_time_p ())
    {
      gnupg_isotime_t tbuf;

      log_info (_("WARNING: running with faked system time: "));
      gnupg_get_isotime (tbuf);
      dump_isotime (tbuf);
      log_printf ("\n");
    }

  /* Print any pending secure memory warnings.  */
  gcry_control (GCRYCTL_RESUME_SECMEM_WARN);

  /* Setup the debug flags for all subsystems.  */
  set_debug ();

  /* Install a regular exit handler to make real sure that the secure
     memory gets wiped out.  */
  g13_install_emergency_cleanup ();

  /* Terminate if we found any error until now.  */
  if (log_get_errorcount(0))
    g13_exit (2);

  /* Set the standard GnuPG random seed file.  */
  if (use_random_seed)
    {
      char *p = make_filename (opt.homedir, "random_seed", NULL);
      gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
      xfree(p);
    }

  /* Get the UID of the caller.  */
#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
  {
    const char *uidstr;
    struct passwd *pwd = NULL;

    uidstr = getenv ("USERV_UID");

    /* Print a quick note if we are not started via userv.  */
    if (!uidstr)
      {
        if (getuid ())
          {
            log_info ("WARNING: Not started via userv\n");
            ctrl.fail_all_cmds = 1;
          }
        ctrl.client.uid = getuid ();
      }
    else
      {
        unsigned long myuid;

        errno = 0;
        myuid = strtoul (uidstr, NULL, 10);
        if (myuid == ULONG_MAX && errno)
          {
            log_info ("WARNING: Started via broken userv: %s\n",
                      strerror (errno));
            ctrl.fail_all_cmds = 1;
            ctrl.client.uid = getuid ();
          }
        else
          ctrl.client.uid = (uid_t)myuid;
      }

    pwd = getpwuid (ctrl.client.uid);
    if (!pwd || !*pwd->pw_name)
      {
        log_info ("WARNING: Name for UID not found: %s\n", strerror (errno));
        ctrl.fail_all_cmds = 1;
        ctrl.client.uname = xstrdup ("?");
      }
    else
      ctrl.client.uname = xstrdup (pwd->pw_name);

    /* Check that the user name does not contain a directory
       separator. */
    if (strchr (ctrl.client.uname, '/'))
      {
        log_info ("WARNING: Invalid user name passed\n");
        ctrl.fail_all_cmds = 1;
      }
  }
#else /*!HAVE_PWD_H || !HAVE_GETPWUID*/
  log_info ("WARNING: System does not support required syscalls\n");
  ctrl.fail_all_cmds = 1;
  ctrl.client.uid = getuid ();
  ctrl.client.uname = xstrdup ("?");
#endif /*!HAVE_PWD_H || !HAVE_GETPWUID*/

  /* Read the table entries for this user.  */
  if (!ctrl.fail_all_cmds
      && !(ctrl.client.tab = parse_g13tab (ctrl.client.uname)))
    ctrl.fail_all_cmds = 1;

  /* Start the server.  */
  err = syshelp_server (&ctrl);
  if (err)
    log_error ("server exited with error: %s <%s>\n",
               gpg_strerror (err), gpg_strsource (err));

  /* Cleanup.  */
  g13_syshelp_deinit_default_ctrl (&ctrl);
  g13_exit (0);
  return 8; /*NOTREACHED*/
}
Пример #19
0
/* gpgconf main. */
int
main (int argc, char **argv)
{
  ARGPARSE_ARGS pargs;
  const char *fname;
  int no_more_options = 0;
  enum cmd_and_opt_values cmd = 0;
  estream_t outfp = NULL;

  early_system_init ();
  gnupg_reopen_std (GPGCONF_NAME);
  set_strusage (my_strusage);
  log_set_prefix (GPGCONF_NAME, 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init();
  init_common_subsystems (&argc, &argv);

  /* Parse the command line. */
  pargs.argc  = &argc;
  pargs.argv  = &argv;
  pargs.flags =  1;  /* Do not remove the args.  */
  while (!no_more_options && optfile_parse (NULL, NULL, NULL, &pargs, opts))
    {
      switch (pargs.r_opt)
        {
        case oOutput:    opt.outfile = pargs.r.ret_str; break;
	case oQuiet:     opt.quiet = 1; break;
        case oDryRun:    opt.dry_run = 1; break;
        case oRuntime:
	  opt.runtime = 1;
	  break;
        case oVerbose:   opt.verbose++; break;
        case oNoVerbose: opt.verbose = 0; break;

	case aListDirs:
        case aListComponents:
        case aCheckPrograms:
        case aListOptions:
        case aChangeOptions:
        case aCheckOptions:
        case aApplyDefaults:
        case aListConfig:
        case aCheckConfig:
        case aReload:
        case aLaunch:
        case aKill:
	  cmd = pargs.r_opt;
	  break;

        default: pargs.err = 2; break;
	}
    }

  if (log_get_errorcount (0))
    exit (2);

  /* Print a warning if an argument looks like an option.  */
  if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
    {
      int i;

      for (i=0; i < argc; i++)
        if (argv[i][0] == '-' && argv[i][1] == '-')
          log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
    }

  fname = argc ? *argv : NULL;

  switch (cmd)
    {
    case aListComponents:
    default:
      /* List all components. */
      gc_component_list_components (get_outfp (&outfp));
      break;

    case aCheckPrograms:
      /* Check all programs. */
      gc_check_programs (get_outfp (&outfp));
      break;

    case aListOptions:
    case aChangeOptions:
    case aCheckOptions:
      if (!fname)
	{
	  es_fprintf (es_stderr, _("usage: %s [options] "), GPGCONF_NAME);
	  es_putc ('\n', es_stderr);
	  es_fputs (_("Need one component argument"), es_stderr);
	  es_putc ('\n', es_stderr);
	  exit (2);
	}
      else
	{
	  int idx = gc_component_find (fname);
	  if (idx < 0)
	    {
	      es_fputs (_("Component not found"), es_stderr);
	      es_putc ('\n', es_stderr);
	      exit (1);
	    }
          if (cmd == aCheckOptions)
	    gc_component_check_options (idx, get_outfp (&outfp), NULL);
          else
            {
              gc_component_retrieve_options (idx);
              if (gc_process_gpgconf_conf (NULL, 1, 0, NULL))
                exit (1);
              if (cmd == aListOptions)
                gc_component_list_options (idx, get_outfp (&outfp));
              else if (cmd == aChangeOptions)
                gc_component_change_options (idx, es_stdin, get_outfp (&outfp));
            }
	}
      break;

    case aLaunch:
    case aKill:
      if (!fname)
	{
	  es_fprintf (es_stderr, _("usage: %s [options] "), GPGCONF_NAME);
	  es_putc ('\n', es_stderr);
	  es_fputs (_("Need one component argument"), es_stderr);
	  es_putc ('\n', es_stderr);
	  exit (2);
	}
      else
        {
          /* Launch/Kill a given component.  */
          int idx;

          idx = gc_component_find (fname);
          if (idx < 0)
            {
              es_fputs (_("Component not found"), es_stderr);
              es_putc ('\n', es_stderr);
              exit (1);
            }
          else if (cmd == aLaunch)
            {
              if (gc_component_launch (idx))
                exit (1);
            }
          else
            {
              /* We don't error out if the kill failed because this
                 command should do nothing if the component is not
                 running.  */
              gc_component_kill (idx);
            }
        }
      break;

    case aReload:
      if (!fname)
	{
          /* Reload all.  */
          gc_component_reload (-1);
	}
      else
        {
          /* Reload given component.  */
          int idx;

          idx = gc_component_find (fname);
          if (idx < 0)
            {
              es_fputs (_("Component not found"), es_stderr);
              es_putc ('\n', es_stderr);
              exit (1);
            }
          else
            {
              gc_component_reload (idx);
            }
        }
      break;

    case aListConfig:
      if (gc_process_gpgconf_conf (fname, 0, 0, get_outfp (&outfp)))
        exit (1);
      break;

    case aCheckConfig:
      if (gc_process_gpgconf_conf (fname, 0, 0, NULL))
        exit (1);
      break;

    case aApplyDefaults:
      if (fname)
	{
	  es_fprintf (es_stderr, _("usage: %s [options] "), GPGCONF_NAME);
	  es_putc ('\n', es_stderr);
	  es_fputs (_("No argument allowed"), es_stderr);
	  es_putc ('\n', es_stderr);
	  exit (2);
	}
      gc_component_retrieve_options (-1);
      if (gc_process_gpgconf_conf (NULL, 1, 1, NULL))
        exit (1);
      break;

    case aListDirs:
      /* Show the system configuration directories for gpgconf.  */
      get_outfp (&outfp);
      es_fprintf (outfp, "sysconfdir:%s\n",
                  gc_percent_escape (gnupg_sysconfdir ()));
      es_fprintf (outfp, "bindir:%s\n",
                  gc_percent_escape (gnupg_bindir ()));
      es_fprintf (outfp, "libexecdir:%s\n",
                  gc_percent_escape (gnupg_libexecdir ()));
      es_fprintf (outfp, "libdir:%s\n",
                  gc_percent_escape (gnupg_libdir ()));
      es_fprintf (outfp, "datadir:%s\n",
                  gc_percent_escape (gnupg_datadir ()));
      es_fprintf (outfp, "localedir:%s\n",
                  gc_percent_escape (gnupg_localedir ()));

      if (dirmngr_user_socket_name ())
        {
          es_fprintf (outfp, "dirmngr-socket:%s\n",
                      gc_percent_escape (dirmngr_user_socket_name ()));
          es_fprintf (outfp, "dirmngr-sys-socket:%s\n",
                      gc_percent_escape (dirmngr_sys_socket_name ()));
        }
      else
        {
          es_fprintf (outfp, "dirmngr-socket:%s\n",
                      gc_percent_escape (dirmngr_sys_socket_name ()));
        }

      {
        char *tmp = make_filename (default_homedir (),
                                   GPG_AGENT_SOCK_NAME, NULL);
        es_fprintf (outfp, "agent-socket:%s\n", gc_percent_escape (tmp));
        xfree (tmp);
      }
      {
        /* We need to use make_filename to expand a possible "~/".  */
        char *tmp = make_filename (default_homedir (), NULL);
        es_fprintf (outfp, "homedir:%s\n", gc_percent_escape (tmp));
        xfree (tmp);
      }
      break;
    }

  if (outfp != es_stdout)
    if (es_fclose (outfp))
      gc_error (1, errno, "error closing '%s'", opt.outfile);

  return 0;
}
Пример #20
0
Файл: gpgtar.c Проект: gpg/gnupg
/* gpgtar main. */
int
main (int argc, char **argv)
{
    gpg_error_t err;
    const char *fname;
    ARGPARSE_ARGS pargs;

    assert (sizeof (struct ustar_raw_header) == 512);

    gnupg_reopen_std (GPGTAR_NAME);
    set_strusage (my_strusage);
    log_set_prefix (GPGTAR_NAME, 1);

    /* Make sure that our subsystems are ready.  */
    i18n_init();
    init_common_subsystems (&argc, &argv);

    /* Parse the command line. */
    pargs.argc  = &argc;
    pargs.argv  = &argv;
    pargs.flags = ARGPARSE_FLAG_KEEP;
    parse_arguments (&pargs, opts);

    if ((files_from && !null_names) || (!files_from && null_names))
        log_error ("--files-from and --null may only be used in conjunction\n");
    if (files_from && strcmp (files_from, "-"))
        log_error ("--files-from only supports argument \"-\"\n");

    if (log_get_errorcount (0))
        exit (2);

    /* Print a warning if an argument looks like an option.  */
    if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
    {
        int i;

        for (i=0; i < argc; i++)
            if (argv[i][0] == '-' && argv[i][1] == '-')
                log_info (_("NOTE: '%s' is not considered an option\n"), argv[i]);
    }

    if (! opt.gpg_program)
        opt.gpg_program = gnupg_module_name (GNUPG_MODULE_NAME_GPG);

    if (opt.verbose > 1)
        opt.debug_level = 1024;

    switch (cmd)
    {
    case aList:
        if (argc > 1)
            usage (1);
        fname = argc ? *argv : NULL;
        if (opt.filename)
            log_info ("note: ignoring option --set-filename\n");
        if (files_from)
            log_info ("note: ignoring option --files-from\n");
        err = gpgtar_list (fname, !skip_crypto);
        if (err && log_get_errorcount (0) == 0)
            log_error ("listing archive failed: %s\n", gpg_strerror (err));
        break;

    case aEncrypt:
    case aSign:
    case aSignEncrypt:
        if ((!argc && !null_names)
                || (argc && null_names))
            usage (1);
        if (opt.filename)
            log_info ("note: ignoring option --set-filename\n");
        err = gpgtar_create (null_names? NULL :argv,
                             !skip_crypto
                             && (cmd == aEncrypt || cmd == aSignEncrypt),
                             cmd == aSign || cmd == aSignEncrypt);
        if (err && log_get_errorcount (0) == 0)
            log_error ("creating archive failed: %s\n", gpg_strerror (err));
        break;

    case aDecrypt:
        if (argc != 1)
            usage (1);
        if (opt.outfile)
            log_info ("note: ignoring option --output\n");
        if (files_from)
            log_info ("note: ignoring option --files-from\n");
        fname = argc ? *argv : NULL;
        err = gpgtar_extract (fname, !skip_crypto);
        if (err && log_get_errorcount (0) == 0)
            log_error ("extracting archive failed: %s\n", gpg_strerror (err));
        break;

    default:
        log_error (_("invalid command (there is no implicit command)\n"));
        break;
    }

    return log_get_errorcount (0)? 1:0;
}
Пример #21
0
Файл: gpgv.c Проект: gpg/gnupg
int
main( int argc, char **argv )
{
  ARGPARSE_ARGS pargs;
  int rc=0;
  strlist_t sl;
  strlist_t nrings = NULL;
  unsigned configlineno;
  ctrl_t ctrl;

  early_system_init ();
  set_strusage (my_strusage);
  log_set_prefix ("gpgv", 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init();
  init_common_subsystems (&argc, &argv);

  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
    {
      log_fatal ( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
                  NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
    }
  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);

  gnupg_init_signals (0, NULL);

  opt.command_fd = -1; /* no command fd */
  opt.keyserver_options.options |= KEYSERVER_AUTO_KEY_RETRIEVE;
  opt.trust_model = TM_ALWAYS;
  opt.batch = 1;

  opt.weak_digests = NULL;

  tty_no_terminal(1);
  tty_batchmode(1);
  dotlock_disable ();
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  additional_weak_digest("MD5");

  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags=  1;  /* do not remove the args */
  while (optfile_parse( NULL, NULL, &configlineno, &pargs, opts))
    {
      switch (pargs.r_opt)
        {
        case oQuiet: opt.quiet = 1; break;
        case oVerbose:
          opt.verbose++;
          opt.list_sigs=1;
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
          break;
        case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
        case oStatusFD: set_status_fd( pargs.r.ret_int ); break;
        case oLoggerFD:
          log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
          break;
        case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
        case oWeakDigest:
          additional_weak_digest(pargs.r.ret_str);
          break;
        case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
        default : pargs.err = ARGPARSE_PRINT_ERROR; break;
	}
    }

  if (log_get_errorcount (0))
    g10_exit(2);

  if (opt.verbose > 1)
    set_packet_list_mode(1);

  /* Note: We open all keyrings in read-only mode.  */
  if (!nrings)  /* No keyring given: use default one. */
    keydb_add_resource ("trustedkeys" EXTSEP_S "kbx",
                        (KEYDB_RESOURCE_FLAG_READONLY
                         |KEYDB_RESOURCE_FLAG_GPGVDEF));
  for (sl = nrings; sl; sl = sl->next)
    keydb_add_resource (sl->d, KEYDB_RESOURCE_FLAG_READONLY);

  FREE_STRLIST (nrings);

  ctrl = xcalloc (1, sizeof *ctrl);

  if ((rc = verify_signatures (ctrl, argc, argv)))
    log_error("verify signatures failed: %s\n", gpg_strerror (rc) );

  xfree (ctrl);

  /* cleanup */
  g10_exit (0);
  return 8; /*NOTREACHED*/
}
Пример #22
0
int
main (int argc, char **argv)
{
  int last_argc = -1;
  gpg_error_t err;
  int rc;
  parsed_uri_t uri;
  uri_tuple_t r;
  http_t hd;
  int c;
  unsigned int my_http_flags = 0;
  int no_out = 0;
  int tls_dbg = 0;
  const char *cafile = NULL;
  http_session_t session = NULL;

  gpgrt_init ();
  log_set_prefix (PGM, 1 | 4);
  if (argc)
    { argc--; argv++; }
  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          fputs ("usage: " PGM " URL\n"
                 "Options:\n"
                 "  --verbose         print timings etc.\n"
                 "  --debug           flyswatter\n"
                 "  --gnutls-debug N  use GNUTLS debug level N\n"
                 "  --cacert FNAME    expect CA certificate in file FNAME\n"
                 "  --no-verify       do not verify the certificate\n"
                 "  --force-tls       use HTTP_FLAG_FORCE_TLS\n"
                 "  --no-out          do not print the content\n",
                 stdout);
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          verbose += 2;
          debug++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--gnutls-debug"))
        {
          argc--; argv++;
          if (argc)
            {
              tls_dbg = atoi (*argv);
              argc--; argv++;
            }
        }
      else if (!strcmp (*argv, "--cacert"))
        {
          argc--; argv++;
          if (argc)
            {
              cafile = *argv;
              argc--; argv++;
            }
        }
      else if (!strcmp (*argv, "--no-verify"))
        {
          no_verify = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--force-tls"))
        {
          my_http_flags |= HTTP_FLAG_FORCE_TLS;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--no-out"))
        {
          no_out = 1;
          argc--; argv++;
        }
      else if (!strncmp (*argv, "--", 2))
        {
          fprintf (stderr, PGM ": unknown option '%s'\n", *argv);
          exit (1);
        }
    }
  if (argc != 1)
    {
      fprintf (stderr, PGM ": no or too many URLS given\n");
      exit (1);
    }

  if (!cafile)
    cafile = prepend_srcdir ("tls-ca.pem");

#if HTTP_USE_NTBTLS

  (void)err;

  ntbtls_set_debug (tls_dbg, NULL, NULL);

#elif HTTP_USE_GNUTLS

  rc = gnutls_global_init ();
  if (rc)
    log_error ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));

  http_register_tls_callback (verify_callback);
  http_register_tls_ca (cafile);

  err = http_session_new (&session, NULL);
  if (err)
    log_error ("http_session_new failed: %s\n", gpg_strerror (err));

  /* rc = gnutls_dh_params_init(&dh_params); */
  /* if (rc) */
  /*   log_error ("gnutls_dh_params_init failed: %s\n", gnutls_strerror (rc)); */
  /* read_dh_params ("dh_param.pem"); */

  /* rc = gnutls_certificate_set_x509_trust_file */
  /*   (certcred, "ca.pem", GNUTLS_X509_FMT_PEM); */
  /* if (rc) */
  /*   log_error ("gnutls_certificate_set_x509_trust_file failed: %s\n", */
  /*              gnutls_strerror (rc)); */

  /* gnutls_certificate_set_dh_params (certcred, dh_params); */

  gnutls_global_set_log_function (my_gnutls_log);
  if (tls_dbg)
    gnutls_global_set_log_level (tls_dbg);

#endif /*HTTP_USE_GNUTLS*/

  rc = http_parse_uri (&uri, *argv, 1);
  if (rc)
    {
      log_error ("'%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }

  printf ("Scheme: %s\n", uri->scheme);
  if (uri->opaque)
    printf ("Value : %s\n", uri->path);
  else
    {
      printf ("Auth  : %s\n", uri->auth? uri->auth:"[none]");
      printf ("Host  : %s\n", uri->host);
      printf ("Port  : %u\n", uri->port);
      printf ("Path  : %s\n", uri->path);
      for (r = uri->params; r; r = r->next)
        {
          printf ("Params: %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
      for (r = uri->query; r; r = r->next)
        {
          printf ("Query : %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
      printf ("TLS   : %s\n",
              uri->use_tls? "yes":
              (my_http_flags&HTTP_FLAG_FORCE_TLS)? "forced" : "no");

    }
  fflush (stdout);
  http_release_parsed_uri (uri);
  uri = NULL;

  rc = http_open_document (&hd, *argv, NULL, my_http_flags,
                           NULL, session, NULL, NULL);
  if (rc)
    {
      log_error ("can't get '%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }
  log_info ("open_http_document succeeded; status=%u\n",
            http_get_status_code (hd));

  {
    const char **names;
    int i;

    names = http_get_header_names (hd);
    if (!names)
      log_fatal ("http_get_header_names failed: %s\n",
                 gpg_strerror (gpg_error_from_syserror ()));
    for (i = 0; names[i]; i++)
      printf ("HDR: %s: %s\n", names[i], http_get_header (hd, names[i]));
    xfree (names);
  }
  fflush (stdout);

  switch (http_get_status_code (hd))
    {
    case 200:
    case 400:
    case 401:
    case 403:
    case 404:
      {
        unsigned long count = 0;
        while ((c = es_getc (http_get_read_ptr (hd))) != EOF)
          {
            count++;
            if (!no_out)
              putchar (c);
          }
        log_info ("Received bytes: %lu\n", count);
      }
      break;
    case 301:
    case 302:
    case 307:
      log_info ("Redirected to: %s\n", http_get_header (hd, "Location"));
      break;
    }
  http_close (hd, 0);

  http_session_release (session);
#ifdef HTTP_USE_GNUTLS
  gnutls_global_deinit ();
#endif /*HTTP_USE_GNUTLS*/

  return 0;
}
Пример #23
0
int
main (int argc, char **argv)
{
  gpg_error_t err;
  int rc;
  parsed_uri_t uri;
  uri_tuple_t r;
  http_t hd;
  int c;
  http_session_t session = NULL;

  gpgrt_init ();
  log_set_prefix ("t-http", 1 | 4);
  if (argc != 2)
    {
      fprintf (stderr, "usage: t-http uri\n");
      return 1;
    }
  argc--;
  argv++;

#ifdef HTTP_USE_GNUTLS
  rc = gnutls_global_init ();
  if (rc)
    log_error ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));

  http_register_tls_callback (verify_callback);
  http_register_tls_ca ("tls-ca.pem");

  err = http_session_new (&session, NULL);
  if (err)
    log_error ("http_session_new failed: %s\n", gpg_strerror (err));

  /* rc = gnutls_dh_params_init(&dh_params); */
  /* if (rc) */
  /*   log_error ("gnutls_dh_params_init failed: %s\n", gnutls_strerror (rc)); */
  /* read_dh_params ("dh_param.pem"); */

  /* rc = gnutls_certificate_set_x509_trust_file */
  /*   (certcred, "ca.pem", GNUTLS_X509_FMT_PEM); */
  /* if (rc) */
  /*   log_error ("gnutls_certificate_set_x509_trust_file failed: %s\n", */
  /*              gnutls_strerror (rc)); */

  /* gnutls_certificate_set_dh_params (certcred, dh_params); */

  gnutls_global_set_log_function (my_gnutls_log);
  /* gnutls_global_set_log_level (2); */

#endif /*HTTP_USE_GNUTLS*/

  rc = http_parse_uri (&uri, *argv, 1);
  if (rc)
    {
      log_error ("'%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }

  printf ("Scheme: %s\n", uri->scheme);
  if (uri->opaque)
    printf ("Value : %s\n", uri->path);
  else
    {
      printf ("Auth  : %s\n", uri->auth? uri->auth:"[none]");
      printf ("Host  : %s\n", uri->host);
      printf ("Port  : %u\n", uri->port);
      printf ("Path  : %s\n", uri->path);
      for (r = uri->params; r; r = r->next)
        {
          printf ("Params: %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
      for (r = uri->query; r; r = r->next)
        {
          printf ("Query : %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
    }
  http_release_parsed_uri (uri);
  uri = NULL;

  rc = http_open_document (&hd, *argv, NULL, 0, NULL, session, NULL, NULL);
  if (rc)
    {
      log_error ("can't get '%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }
  log_info ("open_http_document succeeded; status=%u\n",
            http_get_status_code (hd));

  {
    const char **names;
    int i;

    names = http_get_header_names (hd);
    if (!names)
      log_fatal ("http_get_header_names failed: %s\n",
                 gpg_strerror (gpg_error_from_syserror ()));
    for (i = 0; names[i]; i++)
      printf ("HDR: %s: %s\n", names[i], http_get_header (hd, names[i]));
    xfree (names);
  }

  switch (http_get_status_code (hd))
    {
    case 200:
    case 400:
    case 401:
    case 403:
    case 404:
      while ((c = es_getc (http_get_read_ptr (hd))) != EOF)
        putchar (c);
      break;
    case 301:
    case 302:
      printf ("Redirected to '%s'\n", http_get_header (hd, "Location"));
      break;
    }
  http_close (hd, 0);

  http_session_release (session);
#ifdef HTTP_USE_GNUTLS
  gnutls_global_deinit ();
#endif /*HTTP_USE_GNUTLS*/

  return 0;
}