示例#1
0
/*
 * opt_args() : set options via commandline args and getopt_long
 */
static void _opt_args(int argc, char **argv)
{
	int opt_char;
	int option_index;
	static struct option long_options[] = {
		{"account",	required_argument, 0, 'A'},
		{"batch",	no_argument,       0, 'b'},
		{"ctld",	no_argument,	   0, OPT_LONG_CTLD},
		{"help",        no_argument,       0, OPT_LONG_HELP},
		{"interactive", no_argument,       0, 'i'},
		{"cluster",     required_argument, 0, 'M'},
		{"clusters",    required_argument, 0, 'M'},
		{"name",        required_argument, 0, 'n'},
		{"nodelist",    required_argument, 0, 'w'},
		{"partition",   required_argument, 0, 'p'},
		{"qos",         required_argument, 0, 'q'},
		{"quiet",       no_argument,       0, 'Q'},
		{"reservation", required_argument, 0, 'R'},
		{"signal",      required_argument, 0, 's'},
		{"state",       required_argument, 0, 't'},
		{"usage",       no_argument,       0, OPT_LONG_USAGE},
		{"user",        required_argument, 0, 'u'},
		{"verbose",     no_argument,       0, 'v'},
		{"version",     no_argument,       0, 'V'},
		{"wckey",       required_argument, 0, OPT_LONG_WCKEY},
		{NULL,          0,                 0, 0}
	};

	while((opt_char = getopt_long(argc, argv, "A:biM:n:p:Qq:R:s:t:u:vVw:",
				      long_options, &option_index)) != -1) {
		switch (opt_char) {
		case (int)'?':
			fprintf(stderr,
				"Try \"scancel --help\" for more "
				"information\n");
			exit(1);
			break;
		case (int)'A':
			opt.account = xstrtolower(xstrdup(optarg));
			break;
		case (int)'b':
			opt.batch = true;
			break;
		case OPT_LONG_CTLD:
			opt.ctld = true;
			break;
		case (int)'i':
			opt.interactive = true;
			break;
		case (int)'M':
			opt.ctld = true;
			if (opt.clusters)
				list_destroy(opt.clusters);
			opt.clusters = slurmdb_get_info_cluster(optarg);
			if (!opt.clusters) {
				print_db_notok(optarg, 0);
				exit(1);
			}
			working_cluster_rec = list_peek(opt.clusters);
			break;
		case (int)'n':
			opt.job_name = xstrdup(optarg);
			break;
		case (int)'p':
			opt.partition = xstrdup(optarg);
			break;
		case (int)'Q':
			opt.verbose = -1;
			break;
		case (int)'q':
			opt.qos = xstrtolower(xstrdup(optarg));
			break;
		case (int)'R':
			opt.reservation = xstrdup(optarg);
			break;
		case (int)'s':
			opt.signal = _xlate_signal_name(optarg);
			break;
		case (int)'t':
			opt.state = _xlate_state_name(optarg, false);
			break;
		case (int)'u':
			opt.user_name = xstrdup(optarg);
			break;
		case (int)'v':
			opt.verbose++;
			break;
		case (int)'V':
			print_slurm_version ();
			exit(0);
		case (int)'w':
			opt.nodelist = xstrdup(optarg);
			break;
		case OPT_LONG_WCKEY:
			opt.wckey = xstrdup(optarg);
			break;
		case OPT_LONG_HELP:
			_help();
			exit(0);
		case OPT_LONG_USAGE:
			_usage();
			exit(0);
		}
	}

	if (optind < argc) {
		char **rest = argv + optind;
		opt.job_list = rest;
		_xlate_job_step_ids(rest);
	}

	if (!_opt_verify())
		exit(1);
}
示例#2
0
static int parse_args(int argc, char * argv[])
{
    int i, c;
    long n;

    while ((c = getopt_long(argc, argv, 
                    opt_string, long_options, &i)) != -1) {
        switch (c) {
        case 'v':
            verbose = 1;
            break;
        case 'p':
            report_progress = 1;
            break;
        case 'h':
            help = 1;
            break;
        case 'f':
            if (strlen(optarg) == 0) {
                printf("invalid root directory\n");
                return 1;
            }
            benchmark_root_dir = optarg;
            break;
        case 'c':
            n = atol(optarg);
            if (n <= 32) {
                printf("cachesize shouldn't be less than 32mb\n");
                return 1;
            }
            cachesize = n * 1024 * 1024L;
            break;
        case 'n':
            n = atol(optarg);
            if (n <= 0) {
                printf("need to operate on at least one file\n");
                return 1;
            }
            num_files = n;
            break;
        case 'd':
            n = atol(optarg);
            if (n <= 0) {
                printf("need at least one file per directory\n");
                return 1;
            }
            directory_max_children = n;
            break;
        case 'm':
            n = atol(optarg);
            if (n <= 0) {
                printf("need to use at least one thread\n");
                return 1;
            }
            num_threads = n;
            break;
        case 'b':
            n = atol(optarg);
            if (n <= 0) {
                printf("io size needs to be > 0\n");
                return 1;
            }
            iosize = n;
            break;
        case 'x':
            n = atol(optarg);
            if (n < 0) {
                printf("number of operations needs to be >= 0.\n"
                       "0 means only open and close files\n");
                return 1;
            }
            num_operations = n;
            break;
        case 0:
            break;
        case '?':
            printf("?\n");
        default:
            return 1;
        }
    }

    return 0;
}
示例#3
0
文件: helios.cpp 项目: torule/rss-glx
void hack_handle_opts (int argc, char **argv)
{
	dIons = 1500;
	dSize = 10;
	dEmitters = 3;
	dAttracters = 3;
	dSpeed = 10;
	dCameraspeed = 10;
	dSurface = 1;
	dWireframe = 0;
	dBlur = 10;

	while (1) {
		int c;

#ifdef HAVE_GETOPT_H
		static struct option long_options[] = {
			{"help", 0, 0, 'h'},
			DRIVER_OPTIONS_LONG {"ions", 1, 0, 'i'},
			{"size", 1, 0, 's'},
			{"emitters", 1, 0, 'e'},
			{"attracters", 1, 0, 'a'},
			{"speed", 1, 0, 'S'},
			{"cameraspeed", 1, 0, 'c'},
			{"surface", 0, 0, 'u'},
			{"no-surface", 0, 0, 'U'},
			{"blur", 1, 0, 'b'},
			{"wireframe", 0, 0, 'w'},
			{"no-wireframe", 0, 0, 'W'},
			{0, 0, 0, 0}
		};

		c = getopt_long (argc, argv, DRIVER_OPTIONS_SHORT "hi:s:e:a:S:c:uUb:wW", long_options, NULL);
#else
		c = getopt (argc, argv, DRIVER_OPTIONS_SHORT "hi:s:e:a:S:c:uUb:wW");
#endif
		if (c == -1)
			break;

		switch (c) {
			DRIVER_OPTIONS_CASES case 'h':printf ("%s:"
#ifndef HAVE_GETOPT_H
							      " Not built with GNU getopt.h, long options *NOT* enabled."
#endif
							      "\n" DRIVER_OPTIONS_HELP "\t--ions/-i <arg>\n" "\t--size/-s <arg>\n" "\t--emitters/-e <arg>\n"
							      "\t--attracters/-a <arg>\n" "\t--speed/-S <arg>\n" "\t--cameraspeed/-c <arg>\n" "\t--surface/-u\n"
							      "\t--no-surface/-U\n" "\t--blur/-b <arg>\n" "\t--wireframe/-w\n" "\t--no-wireframe/-W\n", argv[0]);
			exit (1);
		case 'i':
			dIons = strtol_minmaxdef (optarg, 10, 0, 30000, 1, 1500, "--ions: ");
			break;
		case 's':
			dSize = strtol_minmaxdef (optarg, 10, 1, 100, 1, 10, "--size: ");
			break;
		case 'e':
			dEmitters = strtol_minmaxdef (optarg, 10, 1, 10, 1, 3, "--emitters: ");
			break;
		case 'a':
			dAttracters = strtol_minmaxdef (optarg, 10, 1, 10, 1, 3, "--attracters: ");
			break;
		case 'S':
			dSpeed = strtol_minmaxdef (optarg, 10, 1, 100, 1, 10, "--speed: ");
			break;
		case 'c':
			dCameraspeed = strtol_minmaxdef (optarg, 10, 0, 100, 1, 10, "--cameraspeed: ");
			break;
		case 'u':
			dSurface = 1;
			break;
		case 'U':
			dSurface = 0;
			break;
		case 'b':
			dBlur = strtol_minmaxdef (optarg, 10, 0, 100, 1, 10, "--blur: ");
			break;
		case 'w':
			dWireframe = 1;
			break;
		case 'W':
			dWireframe = 0;
			break;
		}
	}
}
示例#4
0
int
main(int argc, char* argv[])
{
    bool add = false, create = false, destroy = false, erase = false, header = false;
    bool list = false, lvcreate = false, lvdestroy = false, lvlist = false, lvmodify = false, lvresize = false, lvsnap = false;
    bool modify = false, remove = false, spare = false, watch = false;
    char * setLevel = 0, * setName = 0; 

    /* options descriptor */
    static struct option longopts[] = {
	{ "add",	required_argument,	0,	'a' },
	{ "create",	no_argument,		0,	'c' },
	{ "destroy",	required_argument,	0,	'd' },
	{ "erase",	no_argument,		0,	'e' },
	{ "header",	no_argument,		0,	'h' },
	{ "list",	no_argument,		0,	'l' },
	{ "modify",	required_argument,	0,	'm' },
	{ "remove",	required_argument,	0,	'r' },
	{ "spare",	required_argument,	0,	's' },
	{ "watch",	no_argument,		0,	'w' },
	
	{ "lvcreate",	required_argument,	0,	'C' },
	{ "lvdestroy",	required_argument,	0,	'D' },
	{ "lvlist",	no_argument,		0,	'L' },
	{ "lvmodify",	required_argument,	0,	'M' },
	{ "lvresize",	required_argument,	0,	'R' },
	{ "lvsnap",	required_argument,	0,	'S' },
	
	{ "auto-rebuild",required_argument,	0,	'A' },
	{ "block-size", required_argument,	0,	'B' },
	{ "extents",	no_argument,		0,	'E' },
	{ "hint",	required_argument,	0,	'H' },
	{ "level",	required_argument,	0,	'V' },
	{ "name",	required_argument,	0,	'N' },
	{ "quick-rebuild",required_argument,	0,	'Q' },
	{ "size",	required_argument,	0,	'Z' },
	{ "timeout",	required_argument,	0,	'T' },

	{ "verbose",	no_argument,		0,	'v' },
	{ "help",	no_argument,		0,	'?' },
	{ 0,		0,			0,	0   }
    };

    int ch;
    while ((ch = getopt_long(argc, argv, "a:cd:ehlm:r:s:wC:D:LM:R:S:A:B:EH:V:N:Q:Z:T:v?", longopts, NULL)) != -1) {
	
	switch(ch) {

	case 'a':
	    add = true;
	    setName = strdup(optarg);
	    break;
	case 'c':
	    create = true;
	    break;
	case 'd':
	    destroy = true;
	    setName = strdup(optarg);
	    break;
	case 'e':
	    erase = true;
	    break;
	case 'h':
	    header = true;
	    break;
	case 'l':
	    list = true;
	    break;
	case 'm':
	    modify = true;
	    setName = strdup(optarg);
	    break;
	case 'r':
	    remove = true;
	    setName = strdup(optarg);
	    break;
	case 's':
	    spare = true;
	    setName = strdup(optarg);
	    break;
	case 'w':
	    watch = true;
	    break;

	    
	case 'C':
	    lvcreate = true;
	    setName = strdup(optarg);
	    break;
	case 'D':
	    lvdestroy = true;
	    setName = strdup(optarg);
	    break;
	case 'L':
	    lvlist = true;
	    break;
	case 'M':
	    lvmodify = true;
	    setName = strdup(optarg);
	    break;
	case 'R':
	    lvresize = true;
	    setName = strdup(optarg);
	    break;
	case 'S':
	    lvsnap = true;
	    setName = strdup(optarg);
	    break;


	case 'A':
	    autoRebuild = ((optarg[0] == 'Y') || (optarg[0] == 'y')) ? AUTO_YES : AUTO_NO;
	    break;
	case 'B':
	    sscanf(optarg, "%lli", &blockSize);
	    break;
	case 'E':
	    extents = true;
	    break;
	case 'H':
	    hint = strdup(optarg);
	    break;
	case 'V':
	    setLevel = strdup(optarg);
	    break;
	case 'N':
	    nickname = strdup(optarg);
	    break;
	case 'Q':
	    quickRebuild = ((optarg[0] == 'Y') || (optarg[0] == 'y')) ? AUTO_YES : AUTO_NO;
	    break;
	case 'Z':
	    sscanf(optarg, "%lli", &volSize);
	    break;
	case 'T':
	    sscanf(optarg, "%lli", &timeout);
	    break;


	case 'v':
	    verbose = true;
	    break;
	case 0:
	case '?':
	default:
	    usage();
	    exit(0);
	}
    }
    argc -= optind;
    argv += optind;

    if (!add && !create && !destroy && !erase && !header && !list && !modify && !remove && !spare && !watch &&
	!lvcreate && !lvdestroy && !lvlist && !lvmodify && !lvresize && !lvsnap) {
	usage();
	exit(0);
    }

    if (list) {
	listRAIDSets();
	exit(0);
    }

    if (lvlist) {
	listLogicalVolumes(NULL, argc, argv);
	exit(0);
    }

    if (geteuid()) {
	printf("ERROR: you must be super user for this operation.\n");
	exit(1);
    }
	
    if (erase) {
	erasePartition(argc, argv);
	exit(0);
    };

    if (header) {
	dumpHeader(argc, argv);
	exit(0);
    };

    if (watch) {

	CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
					NULL,					// const void *observer
					callBack,
					CFSTR(kAppleRAIDNotificationSetDiscovered),
					NULL,					// const void *object
					CFNotificationSuspensionBehaviorHold);

	CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
					NULL,					// const void *observer
					callBack,
					CFSTR(kAppleRAIDNotificationSetTerminated),
					NULL,					// const void *object
					CFNotificationSuspensionBehaviorHold);

	CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
					NULL,					// const void *observer
					callBack,
					CFSTR(kAppleRAIDNotificationSetChanged),
					NULL,					// const void *object
					CFNotificationSuspensionBehaviorHold);

	CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
					NULL,					// const void *observer
					callBack,
					CFSTR(kAppleLVMNotificationVolumeDiscovered),
					NULL,					// const void *object
					CFNotificationSuspensionBehaviorHold);

	CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
					NULL,					// const void *observer
					callBack,
					CFSTR(kAppleLVMNotificationVolumeTerminated),
					NULL,					// const void *object
					CFNotificationSuspensionBehaviorHold);

	CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
					NULL,					// const void *observer
					callBack,
					CFSTR(kAppleLVMNotificationVolumeChanged),
					NULL,					// const void *object
					CFNotificationSuspensionBehaviorHold);

	// this will not fail if there is no raid controller, ie, if AppleRAID class is not instantiated in the kernel

	AppleRAIDEnableNotifications();
    }


    if (add) addMember(setName, CFSTR(kAppleRAIDMembersKey), argc, argv);
    if (create) createSet(setLevel, nickname, argc, argv);
    if (destroy) destroySet(setName, argc, argv);
    if (modify) modifySet(setName, argc, argv);
    if (remove) removeMember(setName, argc, argv);
    if (spare) addMember(setName, CFSTR(kAppleRAIDSparesKey), argc, argv);

    
    if (lvcreate) createLogicalVolume(setName, setLevel, argc, argv);
    if (lvdestroy) destroyLogicalVolume(setName, argc, argv);
    if (lvmodify) modifyLogicalVolume(setName, argc, argv);
    if (lvresize) resizeLogicalVolume(setName, argc, argv);
    if (lvsnap) snapshotLogicalVolume(setName, setLevel, argc, argv);

    
    if (watch) {

	printf("watching...\n");

	// Set up a signal handler so we can clean up when we're interrupted from the command line
	// Otherwise we stay in our run loop forever.
	sig_t oldHandler = signal(SIGINT, signalHandler);
	if (oldHandler == SIG_ERR) {
	    printf("Could not establish new signal handler");
	    exit(1);
	}

	// Start the run loop. Now we'll receive notifications.
	//
	printf("Starting run loop.\n");
	CFRunLoopRun();
        
	printf("Unexpectedly back from CFRunLoopRun()!\n");
    }

    return 0;
}
示例#5
0
static void
parse_psql_options(int argc, char *argv[], struct adhoc_opts * options)
{
	static struct option long_options[] =
	{
		{"echo-all", no_argument, NULL, 'a'},
		{"no-align", no_argument, NULL, 'A'},
		{"command", required_argument, NULL, 'c'},
		{"dbname", required_argument, NULL, 'd'},
		{"echo-queries", no_argument, NULL, 'e'},
		{"echo-errors", no_argument, NULL, 'b'},
		{"echo-hidden", no_argument, NULL, 'E'},
		{"file", required_argument, NULL, 'f'},
		{"field-separator", required_argument, NULL, 'F'},
		{"field-separator-zero", no_argument, NULL, 'z'},
		{"host", required_argument, NULL, 'h'},
		{"html", no_argument, NULL, 'H'},
		{"list", no_argument, NULL, 'l'},
		{"log-file", required_argument, NULL, 'L'},
		{"no-readline", no_argument, NULL, 'n'},
		{"single-transaction", no_argument, NULL, '1'},
		{"output", required_argument, NULL, 'o'},
		{"port", required_argument, NULL, 'p'},
		{"pset", required_argument, NULL, 'P'},
		{"quiet", no_argument, NULL, 'q'},
		{"record-separator", required_argument, NULL, 'R'},
		{"record-separator-zero", no_argument, NULL, '0'},
		{"single-step", no_argument, NULL, 's'},
		{"single-line", no_argument, NULL, 'S'},
		{"tuples-only", no_argument, NULL, 't'},
		{"table-attr", required_argument, NULL, 'T'},
		{"username", required_argument, NULL, 'U'},
		{"set", required_argument, NULL, 'v'},
		{"variable", required_argument, NULL, 'v'},
		{"version", no_argument, NULL, 'V'},
		{"no-password", no_argument, NULL, 'w'},
		{"password", no_argument, NULL, 'W'},
		{"expanded", no_argument, NULL, 'x'},
		{"no-psqlrc", no_argument, NULL, 'X'},
		{"help", optional_argument, NULL, 1},
		{NULL, 0, NULL, 0}
	};

	int			optindex;
	int			c;

	memset(options, 0, sizeof *options);

	while ((c = getopt_long(argc, argv, "aAbc:d:eEf:F:h:HlL:no:p:P:qR:sStT:U:v:VwWxXz?01",
							long_options, &optindex)) != -1)
	{
		switch (c)
		{
			case 'a':
				SetVariable(pset.vars, "ECHO", "all");
				break;
			case 'A':
				pset.popt.topt.format = PRINT_UNALIGNED;
				break;
			case 'b':
				SetVariable(pset.vars, "ECHO", "errors");
				break;
			case 'c':
				if (optarg[0] == '\\')
					simple_action_list_append(&options->actions,
											  ACT_SINGLE_SLASH,
											  optarg + 1);
				else
					simple_action_list_append(&options->actions,
											  ACT_SINGLE_QUERY,
											  optarg);
				break;
			case 'd':
				options->dbname = pg_strdup(optarg);
				break;
			case 'e':
				SetVariable(pset.vars, "ECHO", "queries");
				break;
			case 'E':
				SetVariableBool(pset.vars, "ECHO_HIDDEN");
				break;
			case 'f':
				simple_action_list_append(&options->actions,
										  ACT_FILE,
										  optarg);
				break;
			case 'F':
				pset.popt.topt.fieldSep.separator = pg_strdup(optarg);
				pset.popt.topt.fieldSep.separator_zero = false;
				break;
			case 'h':
				options->host = pg_strdup(optarg);
				break;
			case 'H':
				pset.popt.topt.format = PRINT_HTML;
				break;
			case 'l':
				options->list_dbs = true;
				break;
			case 'L':
				options->logfilename = pg_strdup(optarg);
				break;
			case 'n':
				options->no_readline = true;
				break;
			case 'o':
				if (!setQFout(optarg))
					exit(EXIT_FAILURE);
				break;
			case 'p':
				options->port = pg_strdup(optarg);
				break;
			case 'P':
				{
					char	   *value;
					char	   *equal_loc;
					bool		result;

					value = pg_strdup(optarg);
					equal_loc = strchr(value, '=');
					if (!equal_loc)
						result = do_pset(value, NULL, &pset.popt, true);
					else
					{
						*equal_loc = '\0';
						result = do_pset(value, equal_loc + 1, &pset.popt, true);
					}

					if (!result)
					{
						fprintf(stderr, _("%s: could not set printing parameter \"%s\"\n"), pset.progname, value);
						exit(EXIT_FAILURE);
					}

					free(value);
					break;
				}
			case 'q':
				SetVariableBool(pset.vars, "QUIET");
				break;
			case 'R':
				pset.popt.topt.recordSep.separator = pg_strdup(optarg);
				pset.popt.topt.recordSep.separator_zero = false;
				break;
			case 's':
				SetVariableBool(pset.vars, "SINGLESTEP");
				break;
			case 'S':
				SetVariableBool(pset.vars, "SINGLELINE");
				break;
			case 't':
				pset.popt.topt.tuples_only = true;
				break;
			case 'T':
				pset.popt.topt.tableAttr = pg_strdup(optarg);
				break;
			case 'U':
				options->username = pg_strdup(optarg);
				break;
			case 'v':
				{
					char	   *value;
					char	   *equal_loc;

					value = pg_strdup(optarg);
					equal_loc = strchr(value, '=');
					if (!equal_loc)
					{
						if (!DeleteVariable(pset.vars, value))
						{
							fprintf(stderr, _("%s: could not delete variable \"%s\"\n"),
									pset.progname, value);
							exit(EXIT_FAILURE);
						}
					}
					else
					{
						*equal_loc = '\0';
						if (!SetVariable(pset.vars, value, equal_loc + 1))
						{
							fprintf(stderr, _("%s: could not set variable \"%s\"\n"),
									pset.progname, value);
							exit(EXIT_FAILURE);
						}
					}

					free(value);
					break;
				}
			case 'V':
				showVersion();
				exit(EXIT_SUCCESS);
			case 'w':
				pset.getPassword = TRI_NO;
				break;
			case 'W':
				pset.getPassword = TRI_YES;
				break;
			case 'x':
				pset.popt.topt.expanded = true;
				break;
			case 'X':
				options->no_psqlrc = true;
				break;
			case 'z':
				pset.popt.topt.fieldSep.separator_zero = true;
				break;
			case '0':
				pset.popt.topt.recordSep.separator_zero = true;
				break;
			case '1':
				options->single_txn = true;
				break;
			case '?':
				/* Actual help option given */
				if (strcmp(argv[optind - 1], "-?") == 0)
				{
					usage(NOPAGER);
					exit(EXIT_SUCCESS);
				}
				/* unknown option reported by getopt */
				else
					goto unknown_option;
				break;
			case 1:
				{
					if (!optarg || strcmp(optarg, "options") == 0)
						usage(NOPAGER);
					else if (optarg && strcmp(optarg, "commands") == 0)
						slashUsage(NOPAGER);
					else if (optarg && strcmp(optarg, "variables") == 0)
						helpVariables(NOPAGER);
					else
						goto unknown_option;

					exit(EXIT_SUCCESS);
				}
				break;
			default:
		unknown_option:
				fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
						pset.progname);
				exit(EXIT_FAILURE);
				break;
		}
	}

	/*
	 * if we still have arguments, use it as the database name and username
	 */
	while (argc - optind >= 1)
	{
		if (!options->dbname)
			options->dbname = argv[optind];
		else if (!options->username)
			options->username = argv[optind];
		else if (!pset.quiet)
			fprintf(stderr, _("%s: warning: extra command-line argument \"%s\" ignored\n"),
					pset.progname, argv[optind]);

		optind++;
	}
}
示例#6
0
int
main(int argc, char **argv)
{
	RestoreOptions *opts;
	int			c;
	int			exit_code;
	int			numWorkers = 1;
	Archive    *AH;
	char	   *inputFileSpec;
	static int	disable_triggers = 0;
	static int	enable_row_security = 0;
	static int	if_exists = 0;
	static int	no_data_for_failed_tables = 0;
	static int	outputNoTablespaces = 0;
	static int	use_setsessauth = 0;
	static int	no_security_labels = 0;

	struct option cmdopts[] = {
		{"clean", 0, NULL, 'c'},
		{"create", 0, NULL, 'C'},
		{"data-only", 0, NULL, 'a'},
		{"dbname", 1, NULL, 'd'},
		{"exit-on-error", 0, NULL, 'e'},
		{"file", 1, NULL, 'f'},
		{"format", 1, NULL, 'F'},
		{"function", 1, NULL, 'P'},
		{"host", 1, NULL, 'h'},
		{"index", 1, NULL, 'I'},
		{"jobs", 1, NULL, 'j'},
		{"list", 0, NULL, 'l'},
		{"no-privileges", 0, NULL, 'x'},
		{"no-acl", 0, NULL, 'x'},
		{"no-owner", 0, NULL, 'O'},
		{"no-reconnect", 0, NULL, 'R'},
		{"port", 1, NULL, 'p'},
		{"no-password", 0, NULL, 'w'},
		{"password", 0, NULL, 'W'},
		{"schema", 1, NULL, 'n'},
		{"schema-only", 0, NULL, 's'},
		{"superuser", 1, NULL, 'S'},
		{"table", 1, NULL, 't'},
		{"trigger", 1, NULL, 'T'},
		{"use-list", 1, NULL, 'L'},
		{"username", 1, NULL, 'U'},
		{"verbose", 0, NULL, 'v'},
		{"single-transaction", 0, NULL, '1'},

		/*
		 * the following options don't have an equivalent short option letter
		 */
		{"disable-triggers", no_argument, &disable_triggers, 1},
		{"enable-row-security", no_argument, &enable_row_security, 1},
		{"if-exists", no_argument, &if_exists, 1},
		{"no-data-for-failed-tables", no_argument, &no_data_for_failed_tables, 1},
		{"no-tablespaces", no_argument, &outputNoTablespaces, 1},
		{"role", required_argument, NULL, 2},
		{"section", required_argument, NULL, 3},
		{"use-set-session-authorization", no_argument, &use_setsessauth, 1},
		{"no-security-labels", no_argument, &no_security_labels, 1},

		{NULL, 0, NULL, 0}
	};

	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));

	init_parallel_dump_utils();

	opts = NewRestoreOptions();

	progname = get_progname(argv[0]);

	if (argc > 1)
	{
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
		{
			usage(progname);
			exit_nicely(0);
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
			puts("pg_restore (PostgreSQL) " PG_VERSION);
			exit_nicely(0);
		}
	}

	while ((c = getopt_long(argc, argv, "acCd:ef:F:h:I:j:lL:n:Op:P:RsS:t:T:U:vwWx1",
							cmdopts, NULL)) != -1)
	{
		switch (c)
		{
			case 'a':			/* Dump data only */
				opts->dataOnly = 1;
				break;
			case 'c':			/* clean (i.e., drop) schema prior to create */
				opts->dropSchema = 1;
				break;
			case 'C':
				opts->createDB = 1;
				break;
			case 'd':
				opts->dbname = pg_strdup(optarg);
				break;
			case 'e':
				opts->exit_on_error = true;
				break;
			case 'f':			/* output file name */
				opts->filename = pg_strdup(optarg);
				break;
			case 'F':
				if (strlen(optarg) != 0)
					opts->formatName = pg_strdup(optarg);
				break;
			case 'h':
				if (strlen(optarg) != 0)
					opts->pghost = pg_strdup(optarg);
				break;

			case 'j':			/* number of restore jobs */
				numWorkers = atoi(optarg);
				break;

			case 'l':			/* Dump the TOC summary */
				opts->tocSummary = 1;
				break;

			case 'L':			/* input TOC summary file name */
				opts->tocFile = pg_strdup(optarg);
				break;

			case 'n':			/* Dump data for this schema only */
				simple_string_list_append(&opts->schemaNames, optarg);
				break;

			case 'O':
				opts->noOwner = 1;
				break;

			case 'p':
				if (strlen(optarg) != 0)
					opts->pgport = pg_strdup(optarg);
				break;
			case 'R':
				/* no-op, still accepted for backwards compatibility */
				break;
			case 'P':			/* Function */
				opts->selTypes = 1;
				opts->selFunction = 1;
				simple_string_list_append(&opts->functionNames, optarg);
				break;
			case 'I':			/* Index */
				opts->selTypes = 1;
				opts->selIndex = 1;
				simple_string_list_append(&opts->indexNames, optarg);
				break;
			case 'T':			/* Trigger */
				opts->selTypes = 1;
				opts->selTrigger = 1;
				simple_string_list_append(&opts->triggerNames, optarg);
				break;
			case 's':			/* dump schema only */
				opts->schemaOnly = 1;
				break;
			case 'S':			/* Superuser username */
				if (strlen(optarg) != 0)
					opts->superuser = pg_strdup(optarg);
				break;
			case 't':			/* Dump data for this table only */
				opts->selTypes = 1;
				opts->selTable = 1;
				simple_string_list_append(&opts->tableNames, optarg);
				break;

			case 'U':
				opts->username = pg_strdup(optarg);
				break;

			case 'v':			/* verbose */
				opts->verbose = 1;
				break;

			case 'w':
				opts->promptPassword = TRI_NO;
				break;

			case 'W':
				opts->promptPassword = TRI_YES;
				break;

			case 'x':			/* skip ACL dump */
				opts->aclsSkip = 1;
				break;

			case '1':			/* Restore data in a single transaction */
				opts->single_txn = true;
				opts->exit_on_error = true;
				break;

			case 0:

				/*
				 * This covers the long options without a short equivalent.
				 */
				break;

			case 2:				/* SET ROLE */
				opts->use_role = pg_strdup(optarg);
				break;

			case 3:				/* section */
				set_dump_section(optarg, &(opts->dumpSections));
				break;

			default:
				fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
				exit_nicely(1);
		}
	}

	/* Get file name from command line */
	if (optind < argc)
		inputFileSpec = argv[optind++];
	else
		inputFileSpec = NULL;

	/* Complain if any arguments remain */
	if (optind < argc)
	{
		fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
				progname, argv[optind]);
		fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
				progname);
		exit_nicely(1);
	}

	/* Should get at most one of -d and -f, else user is confused */
	if (opts->dbname)
	{
		if (opts->filename)
		{
			fprintf(stderr, _("%s: options -d/--dbname and -f/--file cannot be used together\n"),
					progname);
			fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
					progname);
			exit_nicely(1);
		}
		opts->useDB = 1;
	}

	if (opts->dataOnly && opts->schemaOnly)
	{
		fprintf(stderr, _("%s: options -s/--schema-only and -a/--data-only cannot be used together\n"),
				progname);
		exit_nicely(1);
	}

	if (opts->dataOnly && opts->dropSchema)
	{
		fprintf(stderr, _("%s: options -c/--clean and -a/--data-only cannot be used together\n"),
				progname);
		exit_nicely(1);
	}

	/* Can't do single-txn mode with multiple connections */
	if (opts->single_txn && numWorkers > 1)
	{
		fprintf(stderr, _("%s: cannot specify both --single-transaction and multiple jobs\n"),
				progname);
		exit_nicely(1);
	}

	opts->disable_triggers = disable_triggers;
	opts->enable_row_security = enable_row_security;
	opts->noDataForFailedTables = no_data_for_failed_tables;
	opts->noTablespace = outputNoTablespaces;
	opts->use_setsessauth = use_setsessauth;
	opts->no_security_labels = no_security_labels;

	if (if_exists && !opts->dropSchema)
	{
		fprintf(stderr, _("%s: option --if-exists requires option -c/--clean\n"),
				progname);
		exit_nicely(1);
	}
	opts->if_exists = if_exists;

	if (opts->formatName)
	{
		switch (opts->formatName[0])
		{
			case 'c':
			case 'C':
				opts->format = archCustom;
				break;

			case 'd':
			case 'D':
				opts->format = archDirectory;
				break;

			case 't':
			case 'T':
				opts->format = archTar;
				break;

			default:
				write_msg(NULL, "unrecognized archive format \"%s\"; please specify \"c\", \"d\", or \"t\"\n",
						  opts->formatName);
				exit_nicely(1);
		}
	}

	AH = OpenArchive(inputFileSpec, opts->format);

	/*
	 * We don't have a connection yet but that doesn't matter. The connection
	 * is initialized to NULL and if we terminate through exit_nicely() while
	 * it's still NULL, the cleanup function will just be a no-op.
	 */
	on_exit_close_archive(AH);

	/* Let the archiver know how noisy to be */
	AH->verbose = opts->verbose;

	/*
	 * Whether to keep submitting sql commands as "pg_restore ... | psql ... "
	 */
	AH->exit_on_error = opts->exit_on_error;

	if (opts->tocFile)
		SortTocFromFile(AH, opts);

	/* See comments in pg_dump.c */
#ifdef WIN32
	if (numWorkers > MAXIMUM_WAIT_OBJECTS)
	{
		fprintf(stderr, _("%s: maximum number of parallel jobs is %d\n"),
				progname, MAXIMUM_WAIT_OBJECTS);
		exit(1);
	}
#endif

	AH->numWorkers = numWorkers;

	if (opts->tocSummary)
		PrintTOCSummary(AH, opts);
	else
	{
		SetArchiveRestoreOptions(AH, opts);
		RestoreArchive(AH);
	}

	/* done, print a summary of ignored errors */
	if (AH->n_errors)
		fprintf(stderr, _("WARNING: errors ignored on restore: %d\n"),
				AH->n_errors);

	/* AH may be freed in CloseArchive? */
	exit_code = AH->n_errors ? 1 : 0;

	CloseArchive(AH, NULL);

	return exit_code;
}
示例#7
0
int main (int argc, char *argv[])
{
	enum {
		OPT_SERVER,
		OPT_MUTLI_SERVER,
		OPT_DAEMON,
		OPT_VERBOSE,
		OPT_QUIET,
		OPT_SH,
		OPT_CSH,
		OPT_OPTIONS,
		OPT_NO_DETACH,
		OPT_LOG_FILE,
		OPT_VERSION,
		OPT_HELP
	};

	static struct option long_options[] = {
		{ "server", no_argument, NULL, OPT_SERVER },
		{ "multi-server", no_argument, NULL, OPT_MUTLI_SERVER },
		{ "daemon", no_argument, NULL, OPT_DAEMON },
		{ "verbose", no_argument, NULL, OPT_VERBOSE },
		{ "quiet", no_argument, NULL, OPT_QUIET },
		{ "sh", no_argument, NULL, OPT_SH },
		{ "csh", no_argument, NULL, OPT_CSH },
		{ "options", required_argument, NULL, OPT_OPTIONS },
		{ "no-detach", no_argument, NULL, OPT_NO_DETACH },
		{ "log-file", required_argument, NULL, OPT_LOG_FILE },
		{ "version", no_argument, NULL, OPT_VERSION },
		{ "help", no_argument, NULL, OPT_HELP },
		{ NULL, 0, NULL, 0 }
	};
	int long_options_ret;
	int base_argc = 1;

	int usage_ok = 1;
	enum {
		RUN_MODE_NONE,
		RUN_MODE_SERVER,
		RUN_MODE_MULTI_SERVER,
		RUN_MODE_DAEMON
	} run_mode = RUN_MODE_NONE;
	int env_is_csh = 0;
	int log_verbose = 0;
	int log_quiet = 0;
	int no_detach = 0;
	char *config_file = NULL;
	char *log_file = NULL;
	char *home_dir = NULL;
	int have_at_least_one_provider=0;
	FILE *fp_log = NULL;
	int i;
	CK_RV rv;

	dconfig_data_t config;

	const char * CONFIG_SUFFIX = ".conf";
	char *default_config_file = NULL;

#if !defined(HAVE_W32_SYSTEM)
	s_parent_pid = getpid ();
#endif

	if ((default_config_file = (char *)malloc (strlen (PACKAGE)+strlen (CONFIG_SUFFIX)+1)) == NULL) {
		common_log (LOG_FATAL, "malloc failed");
	}
	sprintf (default_config_file, "%s%s", PACKAGE, CONFIG_SUFFIX);

	common_set_log_stream (stderr);

	while ((long_options_ret = getopt_long (argc, argv, "vqsc", long_options, NULL)) != -1) {
		base_argc++;

		switch (long_options_ret) {
			case OPT_SERVER:
				run_mode = RUN_MODE_SERVER;
			break;
			case OPT_MUTLI_SERVER:
				run_mode = RUN_MODE_MULTI_SERVER;
			break;
			case OPT_DAEMON:
				run_mode = RUN_MODE_DAEMON;
			break;
			case OPT_VERBOSE:
			case 'v':
				log_verbose = 1;
			break;
			case OPT_QUIET:
			case 'q':
				log_quiet = 1;
			break;
			case OPT_SH:
			case 's':
			break;
			case OPT_CSH:
			case 'c':
				env_is_csh = 1;
			break;
			case OPT_OPTIONS:
				base_argc++;
				config_file = strdup (optarg);
			break;
			case OPT_NO_DETACH:
				no_detach = 1;
			break;
			case OPT_LOG_FILE:
				base_argc++;
				log_file = strdup (optarg);
			break;
			case OPT_VERSION:
				printf (
					"%s %s\n"
					"\n"
					"Copyright (c) 2006-2007 Zeljko Vrba <*****@*****.**>\n"
					"Copyright (c) 2006-2011 Alon Bar-Lev <*****@*****.**>\n"
					"\n"
					"This is free software; see the source for copying conditions.\n"
					"There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
					PACKAGE,
					PACKAGE_VERSION
				);
				exit (1);
			break;
			case OPT_HELP:
				usage_ok = 0;
			break;
			default:
				usage_ok = 0;
			break;
		}
	}

	if (base_argc < argc) {
		if (!strcmp (argv[base_argc], "--")) {
			base_argc++;
		}
	}

	if (!usage_ok) {
		usage (argv[0]);
	}

	if (run_mode == RUN_MODE_NONE) {
		common_log (LOG_FATAL, "please use the option `--daemon' to run the program in the background");
	}

#if defined(HAVE_W32_SYSTEM)
	if (run_mode == RUN_MODE_DAEMON) {
		common_log (LOG_FATAL, "daemon mode is not supported");
	}
#endif

	home_dir = get_home_dir ();

	if (config_file == NULL) {
		if ((config_file = (char *)malloc (strlen (home_dir) + strlen (default_config_file)+2)) == NULL) {
			common_log (LOG_FATAL, "malloc failed");
		}
		sprintf (config_file, "%s%c%s", home_dir, CONFIG_PATH_SEPARATOR, default_config_file);
	}

	if (
		!dconfig_read (config_file, &config) &&
		!dconfig_read (CONFIG_SYSTEM_CONFIG, &config)
	) {
		common_log (LOG_FATAL, "Cannot open configuration file");
	}

	if (log_file != NULL) {
		if (config.log_file != NULL) {
			free (config.log_file);
		}
		if ((config.log_file = strdup (log_file)) == NULL) {
			common_log (LOG_FATAL, "strdup failed");
		}
	}

	if (log_verbose) {
		config.verbose = 1;
	}

#if !defined(HAVE_W32_SYSTEM)
	signal (SIGPIPE, SIG_IGN);
	signal (SIGINT, on_signal);
	signal (SIGTERM, on_signal);
	signal (SIGABRT, on_signal);
	signal (SIGHUP, on_signal);
#endif

	if (log_file != NULL) {
		if (strcmp (log_file, "stderr")) {
			if ((fp_log = fopen (log_file, "a")) != NULL) {
				common_set_log_stream (fp_log);
			}
		}
	}
	else if (config.log_file != NULL) {
		if (strcmp (config.log_file, "stderr")) {
			if ((fp_log = fopen (config.log_file, "a")) != NULL) {
				common_set_log_stream (fp_log);
			}
		}
	}

	if (config.debug) {
		common_log (LOG_DEBUG, "version: %s", PACKAGE_VERSION);
		dconfig_print (&config);
		common_log (LOG_DEBUG, "run_mode: %d", run_mode);
		common_log (LOG_DEBUG, "crypto: %s",
#if defined(ENABLE_OPENSSL)
			"openssl"
#elif defined(ENABLE_GNUTLS)
			"gnutls"
#else
			"invalid"
#endif
		);
	}

#if !defined(HAVE_W32_SYSTEM)
	if (run_mode == RUN_MODE_DAEMON || run_mode == RUN_MODE_MULTI_SERVER) {
		server_socket_create_name ();
	}

	/*
	 * fork before doing PKCS#11 stuff
	 * some providers don't behave well
	 */
	if (run_mode == RUN_MODE_DAEMON) {
		pid_t pid;

		pid = fork ();

		if (pid == -1) {
			common_log (LOG_FATAL, "fork failed");
		}

		if (pid != 0) {
			static const char *key = "SCDAEMON_INFO";
			char env[1024];
			snprintf (env, sizeof (env), "%s:%lu:1", s_socket_name, (unsigned long)pid);

			if (argc - base_argc > 0) {
				setenv(key, env, 1);
				execvp (argv[base_argc], &(argv[base_argc]));
				kill (pid, SIGTERM);
				exit (1);
			}
			else {
				if (env_is_csh) {
					*strchr (env, '=') = ' ';
					printf ("setenv %s %s\n", key, env);
				}
				else {
					printf ("%s=%s; export %s\n", key, env, key);
				}
				exit (0);
			}
		}

		if (!no_detach) {
			int i;

			for (i=0;i<3;i++) {
				if (fileno (common_get_log_stream ()) != i) {
					close (i);
				}
			}

			if (setsid () == -1) {
				common_log (LOG_FATAL, "setsid failed");
			}
		}

		if (chdir ("/") == -1) {
			common_log (LOG_FATAL, "chdir failed");
		}

		if (argc - base_argc > 0) {
			struct sigaction sa;

			memset (&sa, 0, sizeof (sa));
			sigemptyset (&sa.sa_mask);
#if defined(SA_INTERRUPT)
			sa.sa_flags |= SA_INTERRUPT;
#endif
			sa.sa_handler = on_alarm;
			sigaction (SIGALRM, &sa, NULL);
			alarm (10);
		}
	}
#endif				/* HAVE_W32_SYSTEM */

	assuan_set_assuan_log_prefix (PACKAGE);
	assuan_set_assuan_log_stream (common_get_log_stream ());

#if defined(USE_GNUTLS)
	if (gnutls_global_init () != GNUTLS_E_SUCCESS) {
		common_log (LOG_FATAL, "Cannot initialize gnutls");
	}
#endif

	if ((rv = pkcs11h_initialize ()) != CKR_OK) {
		common_log (LOG_FATAL, "Cannot initialize PKCS#11: %s", pkcs11h_getMessage (rv));
	}

	pkcs11h_setLogLevel (config.verbose ? PKCS11H_LOG_DEBUG2 : PKCS11H_LOG_INFO);
	pkcs11h_setLogHook (pkcs11_log_hook, NULL);
	pkcs11h_setTokenPromptHook (pkcs11_token_prompt_hook, NULL);
	pkcs11h_setPINPromptHook (pkcs11_pin_prompt_hook, NULL);
	pkcs11h_setProtectedAuthentication (TRUE);

	for (i=0;i<DCONFIG_MAX_PROVIDERS;i++) {
		if (
			config.providers[i].name != NULL &&
			config.providers[i].library != NULL
		) {
			if (
				(rv = pkcs11h_addProvider (
					config.providers[i].name,
					config.providers[i].library,
					config.providers[i].allow_protected,
					config.providers[i].private_mask,
					PKCS11H_SLOTEVENT_METHOD_POLL,
					0,
					config.providers[i].cert_is_private
				)) != CKR_OK
			) {
				common_log (LOG_WARNING, "Cannot add PKCS#11 provider '%s': %ld-'%s'", config.providers[i].name, rv, pkcs11h_getMessage (rv));
			}
			else {
				have_at_least_one_provider = 1;
			}
		}
	}

	if (!have_at_least_one_provider) {
		common_log (LOG_FATAL, "Could not load any provider");
	}

#if defined(HAVE_W32_SYSTEM)
	command_handler (-1, &config);
#else
{
	pthread_t accept_thread = 0;
	int accept_socket = -1;

	if (run_mode == RUN_MODE_DAEMON || run_mode == RUN_MODE_MULTI_SERVER) {
		accept_socket = server_socket_create ();

		server_socket_accept (accept_socket, &accept_thread, &config);
	}

	if (run_mode == RUN_MODE_DAEMON) {
		/*
		 * Emulate assuan behavior
		 */
		int fds[2];
		char c;
		if (pipe (fds)==-1) {
			common_log (LOG_FATAL, "Could not create pipe");
		}
		close (0);
		dup2 (fds[0], 0);
		close (fds[0]);
		while (read (0, &c, 1) == -1 && errno == EINTR);
		close (fds[1]);
	}
	else {
		command_handler (-1, &config);
	}

	if (run_mode == RUN_MODE_DAEMON || run_mode == RUN_MODE_MULTI_SERVER) {
		server_socket_accept_terminate (accept_thread);
		server_socket_close (accept_socket);
	}
}
#endif

	pkcs11h_terminate ();

#if defined(USE_GNUTLS)
	gnutls_global_deinit ();
#endif

	dconfig_free (&config);

	if (log_file != NULL) {
		free (log_file);
		log_file = NULL;
	}

	if (config_file != NULL) {
		free (config_file);
		config_file = NULL;
	}

	if (default_config_file != NULL) {
		free (default_config_file);
		default_config_file = NULL;
	}

	if (home_dir != NULL) {
		free (home_dir);
		home_dir = NULL;
	}

	if (fp_log != NULL) {
		fclose (fp_log);
		fp_log = NULL;
	}

	return 0;
}
示例#8
0
static void
process_parameters (int argc, char **argv)
{
	ret_t              ret;
	int                c;
	cherokee_boolean_t error = false;

	struct option long_options[] = {
		{"help",            no_argument,       NULL, 'h'},
		{"version",         no_argument,       NULL, 'V'},
		{"debug",           no_argument,       NULL, 'x'},
		{"unsecure",        no_argument,       NULL, 'u'},
		{"internal-tcp",    no_argument,       NULL, 't'},
		{"disable-iocache", no_argument,       NULL, 'i'},
		{"bind",            optional_argument, NULL, 'b'},
		{"appdir",          required_argument, NULL, 'd'},
		{"port",            required_argument, NULL, 'p'},
		{"target",          required_argument, NULL, 'C'},
		{"threads",         required_argument, NULL, 'T'},
		{NULL, 0, NULL, 0}
	};

	while ((c = getopt_long(argc, argv, "hVxutib::d:p:C:T:", long_options, NULL)) != -1) {
		switch(c) {
		case 'b':
			free (bind_to);
			if (optarg) {
				bind_to = strdup(optarg);
			} else if (argv[optind] && argv[optind][0] != '-') {
				bind_to = strdup(argv[optind]);
				optind++;
			} else {
				bind_to = NULL;
			}
			break;
		case 'p':
			ret = cherokee_atoi (optarg, &port);
			if (ret != ret_ok) {
				error = true;
			}
			break;
		case 'T':
			ret = cherokee_atoi (optarg, &thread_num);
			if (ret != ret_ok) {
				error = true;
			}
			break;
		case 'd':
			free (document_root);
			document_root = strdup(optarg);
			break;
		case 'C':
			free (config_file);
			config_file = strdup(optarg);
			break;
		case 'x':
			debug   = 1;
			iocache = 0;
			break;
		case 'u':
			unsecure = 1;
			break;
		case 'i':
			iocache = 0;
			break;
		case 't':
			scgi_port = 0;
			break;
		case 'V':
			printf (APP_NAME " " PACKAGE_VERSION "\n" APP_COPY_NOTICE);
			exit(0);
		case 'h':
		case '?':
		default:
			error = true;
		}

		if (error) {
			print_help();
			exit (1);
		}
	}

	/* Check for trailing parameters
	 */
	for (c = optind; c < argc; c++) {
		if ((argv[c] != NULL) && (strlen(argv[c]) > 0)) {
			print_help();
			exit (1);
		}
	}
}
示例#9
0
文件: mythping.c 项目: cmyth/cmyth
int
main(int argc, char **argv)
{
	int c, opt_index;
	int verbose = 0;
	int opt_e = 0, opt_r = 0, opt_s = 0, opt_u = 0;
	char *server;

	while ((c=getopt_long(argc, argv, "hersuv", opts, &opt_index)) != -1) {
		switch (c) {
		case 'h':
			print_help(argv[0]);
			exit(0);
			break;
		case 'e':
			opt_e = 1;
			break;
		case 'r':
			opt_r = 1;
			break;
		case 's':
			opt_s = 1;
			break;
		case 'u':
			opt_u = 1;
			break;
		case 'v':
			verbose++;
			break;
		default:
			print_help(argv[0]);
			exit(1);
			break;
		}
	}

	if (optind == argc) {
		fprintf(stderr, "no server given!\n");
		return -1;
	}

	server = argv[optind];

	if (!is_alive(server)) {
		printf("%s is not responding.\n", server);
		return 1;
	}

	printf("%s is alive.\n", server);

	if (cmyth_conn_block_shutdown(control) < 0) {
		printf("Failed to block backend shutdown!\n");
	}

	if (verbose) {
		int version, count;
		cmyth_proglist_t list;
		long long total, used;

		printf("libcmyth version %s\n", cmyth_version());
		printf("librefmem version %s\n", ref_version());

		version = cmyth_conn_get_protocol_version(control);

		printf("\tprotocol version: %d\n", version);

		list = cmyth_proglist_get_all_recorded(control);
		count = cmyth_proglist_get_count(list);

		printf("\trecordings: %d\n", count);

		if (cmyth_conn_get_freespace(control, &total, &used) == 0) {
			printf("\ttotal space: %lld bytes\n", total);
			printf("\tused space:  %lld bytes\n", used);
		}

		get_event(server);

		ref_release(list);
	}

	if (opt_e) {
		get_recordings(verbose);
	}

	if (opt_r) {
		get_recorders(verbose);
	}

	if (opt_s) {
		get_scheduled(verbose);
	}

	if (opt_u) {
		get_upcoming(verbose);
	}

	if (cmyth_conn_allow_shutdown(control) < 0) {
		printf("Failed to allow backend shutdown!\n");
	}

	ref_release(control);

	if (verbose > 1) {
		unsigned int refs, bytes;

		ref_get_usage(&refs, &bytes);

		printf("Refmem: refs  %d\n", refs);
		printf("Refmem: bytes %d\n", bytes);

		if (refs > 0) {
			ref_alloc_show();
		}
	}

	return 0;
}
示例#10
0
文件: crass.cpp 项目: jrherr/crass
int processOptions(int argc, char *argv[], options *opts) 
{
    int c;
    int index;
    bool scalling = false;
    while( (c = getopt_long(argc, argv, "a:b:c:d:D:ef:gGhHk:K:l:Ln:o:rs:S:Vw:x:y:z", long_options, &index)) != -1 ) 
    {
        switch(c) 
        {
            case 'a':
#if RENDERING                
                if (strcmp(optarg, "dot") && strcmp(optarg, "neato") && strcmp(optarg, "fdp") && strcmp(optarg, "sfdp") && strcmp(optarg, "twopi") && strcmp(optarg, "circo")) {
                    std::cerr<<PACKAGE_NAME<<" [WARNING]: '"<<optarg<<"' is not a recognised layout algorithm. Please choose from the following:"<<std::endl;
#ifdef HAVE_NEATO
                    std::cerr<<"\tneato"<<std::endl;
#endif
#ifdef HAVE_DOT
                    std::cerr<<"\tdot"<<std::endl;
#endif
#ifdef HAVE_FDP
                    std::cerr<<"\tfdp"<<std::endl;
#endif
#ifdef HAVE_SFDP
                    std::cerr<<"\tsfdp"<<std::endl;
#endif
#ifdef HAVE_CIRCO
                    std::cerr<<"\tcirco"<<std::endl;
#endif
#ifdef HAVE_TWOPI
                    std::cerr<<"\ttwopi"<<std::endl;
#endif
                    
                } else {
                    opts->layoutAlgorithm = optarg;
                }
#else 
                std::cerr<<PACKAGE_NAME<<" [WARNING]: Not compiled with the correct options to allow rendering of graphs.\nEither use the --enable-rendering option during ./configure and make sure that the graphviz layout programs are in your PATH"<<std::endl;
#endif
                break;
            case 'b': 
                from_string<int>(opts->coverageBins, optarg, std::dec);
                if (opts->coverageBins < 1) 
                {
                    std::cerr<<PACKAGE_NAME<<" [ERROR]: The number of bins for coverage cannot be less than 1"<<std::endl;
                    usage();
                    exit(1);
                }
                break;
            case 'c': 
                if (strcmp(optarg, "red-blue") == 0) 
                {
                    opts->graphColourType = RED_BLUE;
                } 
                else if(strcmp(optarg, "read-blue-green") == 0)
                {
                    opts->graphColourType = RED_BLUE_GREEN;
                }
                else if(strcmp(optarg, "blue-red") == 0)
                {
                    opts->graphColourType = BLUE_RED; 
                }
                else if(strcmp(optarg, "green-blue-red") == 0)
                {
                    opts->graphColourType = GREEN_BLUE_RED;
                }
                else
                {
                    std::cerr<<PACKAGE_NAME<<" [WARNING]: Unknown graph colour type "<<optarg<<" changing to default colour type (red-blue)"<<std::endl;
                    opts->graphColourType = RED_BLUE;
                }
                break;
            case 'd': 
                from_string<unsigned int>(opts->lowDRsize, optarg, std::dec);
                if (opts->lowDRsize < 8) 
                {
                    std::cerr<<PACKAGE_NAME<<" [WARNING]: The lower bound for direct repeat sizes cannot be "<<opts->lowDRsize<<" changing to "<<CRASS_DEF_MIN_DR_SIZE<<std::endl;
                    opts->lowDRsize = CRASS_DEF_MIN_DR_SIZE;
                }
                break;
            case 'D': 
                from_string<unsigned int>(opts->highDRsize, optarg, std::dec);
                break;
            case 'e':
#ifdef DEBUG
                opts->noDebugGraph = true;
#endif
                break;
            case 'f':
                from_string<int>(opts->covCutoff, optarg, std::dec);
                break;
            case 'g':
                 opts->logToScreen = true;
                break;
            case 'G':
            	opts->showSingles= true;
                break;
            case 'h': 
                versionInfo(); 
                usage();
                exit(1); 
                break;
            case 'H':
                opts->removeHomopolymers = true;
                break;
            case 'k': 
                from_string<int>(opts->kmer_clust_size, optarg, std::dec);
                if (opts->kmer_clust_size < 4) 
                {
                    std::cerr<<PACKAGE_NAME<<" [WARNING]: Minimum value for kmer clustering size is: "<<4<<" changing to "<<CRASS_DEF_K_CLUST_MIN<<std::endl;
                    opts->kmer_clust_size = CRASS_DEF_K_CLUST_MIN;
                }
                break;
            case 'K': 
                from_string<int>(opts->cNodeKmerLength, optarg, std::dec);
                break;
            case 'l': 
                from_string<int>(opts->logLevel, optarg, std::dec);
                if(opts->logLevel > CRASS_DEF_MAX_LOGGING)
                {
                    std::cerr<<PACKAGE_NAME<<" [WARNING]: Specified log level higher than max. Changing log level to "<<CRASS_DEF_MAX_LOGGING<<" instead of "<<opts->logLevel<<std::endl;
                    opts->logLevel = CRASS_DEF_MAX_LOGGING;
                }
                break;
            case 'L':
                opts->longDescription = true;
                break;
            case 'n':
                from_string<unsigned int>(opts->minNumRepeats, optarg, std::dec);
                if (opts->minNumRepeats < 2) 
                {
                    std::cerr<<PACKAGE_NAME<<" [ERROR]: The mininum number of repeats cannot be less than 2"<<std::endl;
                    usage();
                    exit(1);
                }
                break;
            case 'o': 
                opts->output_fastq = optarg; 
                // just in case the user put '.' or '..' or '~' as the output directory
                if (opts->output_fastq[opts->output_fastq.length() - 1] != '/')
                {
                    opts->output_fastq += '/';
                }
                
                // check if our output folder exists
                struct stat file_stats;
                if (0 != stat(opts->output_fastq.c_str(),&file_stats)) 
                {
                    RecursiveMkdir(opts->output_fastq);
                }
                // check that the directory is writable
                else if(access(optarg, W_OK))
                {
                    std::cerr<<PACKAGE_NAME<<" [ERROR]: You do not have permission to write to "<<optarg<<std::endl;
                    exit(1);
                }
                break;
            case 'r': 
#ifdef RENDERING 
                opts->noRendering = true; 
#endif
                break;
            case 's': 
                from_string<unsigned int>(opts->lowSpacerSize, optarg, std::dec);
                if (opts->lowSpacerSize < 8) 
                {
                    std::cerr<<PACKAGE_NAME<<" [WARNING]: The lower bound for spacer sizes cannot be "<<opts->lowSpacerSize<<" changing to "<<CRASS_DEF_MIN_SPACER_SIZE<<std::endl;
                    opts->lowSpacerSize = CRASS_DEF_MIN_SPACER_SIZE;
                }
                break;
            case 'S': 
                from_string<unsigned int>(opts->highSpacerSize, optarg, std::dec);
                break;
            case 'V': 
                versionInfo(); 
                exit(1); 
                break;
            case 'w': 
                from_string<unsigned int>(opts->searchWindowLength, optarg, std::dec);
                if ((opts->searchWindowLength < CRASS_DEF_MIN_SEARCH_WINDOW_LENGTH) || (opts->searchWindowLength > CRASS_DEF_MAX_SEARCH_WINDOW_LENGTH))
                {
                    std::cerr<<PACKAGE_NAME<<" [WARNING]: Specified window length higher than max. Changing window length to " << CRASS_DEF_OPTIMAL_SEARCH_WINDOW_LENGTH << " instead of " << opts->searchWindowLength<<std::endl;
                    // Change window length
                    opts->searchWindowLength = CRASS_DEF_OPTIMAL_SEARCH_WINDOW_LENGTH;
                }
                break;        
            case 'x':
                from_string<double>(opts->averageSpacerScalling, optarg, std::dec);
                if (isNotDecimal(opts->averageSpacerScalling)) 
                {
                    std::cerr<<PACKAGE_NAME<<" [WARNING]: The average spacer scalling must be a decimal number. Changing to "<<CRASS_DEF_HOMOPOLYMER_SCALLING<<" instead of "<<opts->averageSpacerScalling<<std::endl;
                    opts->averageSpacerScalling = CRASS_DEF_HOMOPOLYMER_SCALLING;
                }
                scalling = true;
                break;
            case 'y':
                from_string<double>(opts->averageDrScalling, optarg, std::dec);
                if (isNotDecimal(opts->averageDrScalling)) 
                {
                    std::cerr<<PACKAGE_NAME<<" [WARNING]: The average spacer scalling must be a decimal number. Changing to "<<CRASS_DEF_HOMOPOLYMER_SCALLING<<" instead of "<<opts->averageDrScalling<<std::endl;
                    opts->averageDrScalling = CRASS_DEF_HOMOPOLYMER_SCALLING;
                }
                scalling = true;
                break;
            case 'z':
                opts->dontPerformScalling = true;
                break;
            case 0:
#ifdef SEARCH_SINGLETON
                if (strcmp("searchChecker", long_options[index].name) == 0) opts->searchChecker = optarg;
#endif
                break;
            default: 
                versionInfo(); 
                usage(); 
                exit(1); 
                break;
        }
    }
    // Sanity checks for the high and low dr size
    if (opts->lowDRsize >= opts->highDRsize) 
    {
        std::cerr<<PACKAGE_NAME<<" [ERROR]: The lower direct repeat bound is bigger than the higher bound ("<<opts->lowDRsize<<" >= "<<opts->highDRsize<<")"<<std::endl;
        usage();
        exit(1);
    }
    // Sanity checks for the high and low spacer size
    if (opts->lowSpacerSize >= opts->highSpacerSize) 
    {
        std::cerr<<PACKAGE_NAME<<" [ERROR]: The lower spacer bound is bigger than the higher bound ("<<opts->lowSpacerSize<<" >= "<<opts->highSpacerSize<<")"<<std::endl;
        usage();
        exit(1);
    }
    
    // sanity check so that the user doesn't specify scalling and no scalling simultaneously
    if (scalling & opts->dontPerformScalling) {
        std::cerr<<PACKAGE_NAME<<" [ERROR]: Cannot use scalling (-x -y) in conjunction with --noScalling"<<std::endl;
        usage();
        exit(1);
    }
    
    // warn them if they try to scale without specifying to remove homopolymers
    if (scalling && !opts->removeHomopolymers) 
    {
        std::cerr<<PACKAGE_NAME<<" [ERROR]: scalling (-x -y) can only be used in conjunction with --removeHomopolymers"<<std::endl;
        usage();
        exit(1);
    }
    
    // scale the direct repeat and spacer lengths if we should
    if (opts->removeHomopolymers && !opts->dontPerformScalling) 
    {
        opts->lowDRsize *= opts->averageDrScalling;
        opts->highDRsize *= opts->averageDrScalling;
        opts->lowSpacerSize *= opts->averageSpacerScalling;
        opts->highSpacerSize *= opts->averageSpacerScalling;
    }
    
    return optind;
}
示例#11
0
int main(int argc, char* argv[])
{
	int             opt_reader = -1;
	int             opt_wait = 0;
	const char     *opt_pin = NULL;
	int             opt_key = 0;
	int             opt_is_iv = 0;
	u8              opt_keytype = SC_RUTOKEN_OPTIONS_GOST_CRYPT_PZ;
	const char     *opt_input = NULL;
	const char     *opt_output = NULL;
	int             opt_operation = OP_NONE;
	int             opt_debug = 0;
	char IV[IV_SIZE];
	
	int err = 0;
	sc_context_t *ctx = NULL;
	sc_context_param_t ctx_param;
	sc_card_t *card = NULL;
	int c, long_optind, r, tries_left;
	
	while (1) {
		c = getopt_long(argc, argv, "r:wp:k:I:t:i:o:sgedmv",
				options, &long_optind);
		if (c == -1)
			break;
		switch (c) {
		case '?':
			util_print_usage_and_die(app_name, options, option_help);
		case 'r':
			opt_reader = atoi(optarg);
			break;
		case 'w':
			opt_wait = 1;
			break;
		case 'p':
			opt_pin = optarg;
			break;
		case 'k':
			opt_key = atoi(optarg);
			if (opt_key <= 0 || opt_key < SC_RUTOKEN_DO_ALL_MIN_ID
					|| opt_key > SC_RUTOKEN_DO_NOCHV_MAX_ID) {
				fprintf(stderr, "Error: Key ID is invalid"
						" (%d <= ID <= %d)\n",
						SC_RUTOKEN_DO_ALL_MIN_ID > 0 ?
						SC_RUTOKEN_DO_ALL_MIN_ID : 1,
						SC_RUTOKEN_DO_NOCHV_MAX_ID);
				return -1;
			}
			break;
		case 'I':
			opt_is_iv = 1;
			strncpy(IV, optarg, sizeof(IV));
			break;
		case 't':
			if (strcmp(optarg, "CFB") == 0)
				opt_keytype = SC_RUTOKEN_OPTIONS_GOST_CRYPT_GAMMOS;
			else if (strcmp(optarg, "SM") == 0)
				opt_keytype = SC_RUTOKEN_OPTIONS_GOST_CRYPT_GAMM;
			else if (strcmp(optarg, "ECB") != 0) {
				fprintf(stderr, "Error: Key type must be either"
						" ECB, SM or CFB\n");
				return -1;
			}
			break;
		case 'i':
			opt_input = optarg;
			break;
		case 'o':
			opt_output = optarg;
			break;
		case 's':
			opt_operation = OP_GET_INFO;
			break;
		case 'g':
			opt_operation = OP_GEN_KEY;
			break;
		case 'e':
			opt_operation = OP_ENCRYPT;
			break;
		case 'd':
			opt_operation = OP_DECRYPT;
			break;
		case 'm':
			opt_operation = OP_MAC;
			break;
		case 'v':
			opt_debug++;
			break;
		}
	}

	memset(&ctx_param, 0, sizeof(ctx_param));
	ctx_param.app_name = app_name;
	r = sc_context_create(&ctx, &ctx_param);
	if (r) {
		fprintf(stderr, "Error: Failed to establish context: %s\n",
			sc_strerror(r));
		return -1;
	}
		ctx->debug = opt_debug;

	if (util_connect_card(ctx, &card, opt_reader, 0, opt_wait, opt_debug) != 0)
		err = -1;
		
	if (err == 0  &&  opt_pin) {
		/*  verify  */
		r = sc_verify(card, SC_AC_CHV, SC_RUTOKEN_DEF_ID_GCHV_USER,
				(u8*)opt_pin, strlen(opt_pin), &tries_left);
		if (r) {
			fprintf(stderr, "Error: PIN verification failed: %s",
					sc_strerror(r));
			if (r == SC_ERROR_PIN_CODE_INCORRECT)
				fprintf(stderr, " (tries left %d)\n", tries_left);
			else
				putc('\n', stderr);
			err = 1;
		}
	}
	if (err == 0) {
		err = -1;
		switch (opt_operation) {
	case OP_GET_INFO:
			err = rutoken_info(card);
		break;
		case OP_DECRYPT:
		case OP_ENCRYPT:
		case OP_MAC:
			if (!opt_input) {
				fprintf(stderr, "Error: No input file specified\n");
			break;
		}
			if (opt_operation != OP_MAC  &&  !opt_output) {
				fprintf(stderr, "Error: No output file specified\n");
			break;
		}
		case OP_GEN_KEY:
			if (opt_key == 0) {
				fprintf(stderr, "Error: You must set key ID\n");
			break;
		}
			if (opt_operation == OP_GEN_KEY)
				err = generate_gostkey(card, (u8)opt_key, opt_keytype);
			else if (opt_operation == OP_MAC)
				err = gostmac(card, (u8)opt_key, opt_input);
			else
				err = gostchiper(card, (u8)opt_key, opt_input,opt_output,
						IV, opt_is_iv, opt_operation);
		break;
	default:
			fprintf(stderr, "Error: No operation specified\n");
		break;
	}
	}
	if (card) {
		/*  sc_lock  and  sc_connect_card  in  util_connect_card  */
		sc_unlock(card);
		sc_disconnect_card(card, 0);
	}
	if (ctx)
		sc_release_context(ctx);
	return err;
}
示例#12
0
static void parse_args(int argc, char **argv)
{
	while (1)
	{
		int c;
		/* getopt_long stores the option index here. */
		int option_index = 0;
		static struct option long_options[] =
		{
			{"verbose",		no_argument,		0, 'v'},
			{"quiet",		no_argument,		0, 'q'},
			{"daemonize",		no_argument,		0, 'd'},
			{"log-file",		required_argument,	0, 'l'},
			{"diode-off",		no_argument,		0, 'o'},
			{"detach-dvd",		no_argument,		0, 'f'},
			{"device",		required_argument,	0, 1},
			{"exact-device",	required_argument,	0, 2},
			{"version",		no_argument,		0, 'V'},
			{"ssid",		required_argument,	0, 3},
			{"event-script",	required_argument,	0, 'e'},
			{"help",		no_argument,		0, 'h'},
			{"debug",		no_argument,		0, 'D'},
			{0, 0, 0, 0}
		};

		c = getopt_long(argc, argv, "vqdl:ofVe:hD", long_options, &option_index);

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

		switch (c)
		{
			case 'D': {
					set_wmlog_level(2);
					break;
				}
			case 'v': {
					inc_wmlog_level();
					break;
				}
			case 'q': {
					set_wmlog_level(-1);
					break;
				}
			case 'd': {
					daemonize = 1;
					break;
				}
			case 'l': {
					logfile = fopen(optarg, "a");
					if (logfile == NULL) {
						fprintf(stderr, "Error opening log file '%s': ", optarg);
						perror(NULL);
						exit(1);
					}
					break;
				}
			case 'o': {
					diode_on = 0;
					break;
				}
			case 'f': {
					detach_dvd = 1;
					break;
				}
			case 'V': {
					version();
					exit(0);
					break;
				}
			case 'h': {
					usage(argv[0]);
					exit(0);
					break;
				}
			case 1: {
					char *delim = strchr(optarg, ':');

					if (delim != NULL) {
						unsigned long int vid, pid;
						char *c1, *c2;

						*delim = 0;

						vid = strtoul(optarg, &c1, 16);
						pid = strtoul(delim + 1, &c2, 16);
						if (!*c1 && !*c2 && vid < 0x10000 && pid < 0x10000) {
							match_method = MATCH_BY_VID_PID;
							match_params.vid = vid;
							match_params.pid = pid;
							break;
						}
					}

					fprintf(stderr, "Error parsing VID:PID combination.\n");
					exit(1);
					break;
				}
			case 2: {
					char *delim = strchr(optarg, '/');

					if (delim != NULL) {
						unsigned long int bus, dev;
						char *c1, *c2;

						*delim = 0;

						bus = strtoul(optarg, &c1, 10);
						dev = strtoul(delim + 1, &c2, 10);
						if (!*c1 && !*c2) {
							match_method = MATCH_BY_BUS_DEV;
							match_params.bus = bus;
							match_params.dev = dev;
							break;
						}
					}

					fprintf(stderr, "Error parsing BUS/DEV combination.\n");
					exit(1);
					break;
				}
			case 3: {
					ssid = optarg;
					break;
				}
			case 'e': {
					event_script = optarg;
					break;
				}
			case '?': {
					/* getopt_long already printed an error message. */
					usage(argv[0]);
					exit(1);
					break;
				}
			default: {
					exit(1);
				}
		}
	}
}
int main(int argc, char *argv[]) {
  FILE *prob_f;
  char c;
  int opt_idx, i, nlines = 0, ngaps = 0;
  unsigned idx;
  PbsCode *code;
  List *fields = lst_new_ptr(10);
  double error, tot_error = 0, prob;
  Vector *v;
  String *line = str_new(STR_MED_LEN);

  struct option long_opts[] = {
    {"discard-gaps", 0, 0, 'G'},
    {"help", 0, 0, 'h'},
    {0, 0, 0, 0}
  };

  /* variables for options, with defaults */
  int discard_gaps = FALSE;

  set_seed(-1);

  while ((c = (char)getopt_long(argc, argv, "Gh", long_opts, &opt_idx)) != -1) {
    switch (c) {
    case 'G':
      discard_gaps = TRUE;
      break;
    case 'h':
      printf("%s", HELP);
      exit(0);
    case '?':
      die("Bad argument.  Try 'pbsEncode -h'.\n");
    }
  }

  if (optind != argc - 2) 
    die("Two arguments required.  Try 'pbsEncode -h'.\n");
    
  prob_f = phast_fopen(argv[optind], "r");
  code = pbs_new_from_file(phast_fopen(argv[optind+1], "r"));
  v = vec_new(code->sg->d);
  
  while (str_readline(line, prob_f) != EOF) {

    if (line->length == 0 || line->chars[0] == '#') continue;

    str_split(line, NULL, fields);

    if (lst_size(fields) == 1 && str_equals_charstr(lst_get_ptr(fields, 0), "-")) {
      ngaps++;
      if (!discard_gaps)
	pbs_write_binary(code, code->gap_code, stdout);
    }
    else {			/* ordinary prob vector */
      if (lst_size(fields) != code->sg->d)
	die("ERROR: number of columns must equal dimension of code (%d).\n",
	    code->sg->d);
    
      for (i = 0; i < code->sg->d; i++) {
	if (str_as_dbl(lst_get_ptr(fields, i), &prob) != 0 || prob < 0 || prob > 1)
	  die("ERROR: bad value ('%s')\n", lst_get_ptr(fields, i));

	vec_set(v, i, prob);
      }

      idx = pbs_get_index(code, v, &error);
      tot_error += error;
      pbs_write_binary(code, idx, stdout);
      nlines++;
    }

    lst_free_strings(fields);
  }

  fprintf(stderr, "Dimensions: %d\n\
Rows per dimension: %d\n\
Code size: %d\n\
Bytes per vector: %d\n\
Vectors processed: %d\n\
Gaps: %d%s\n\
Average approximation error: %f bits\n", 
	  code->sg->d, code->sg->nrows, code->code_size, code->nbytes,  
	  nlines, ngaps, discard_gaps ? " (discarded)" : "", tot_error/nlines);

  return 0;
}
示例#14
0
static int adm_hwdb(struct udev *udev, int argc, char *argv[]) {
        static const struct option options[] = {
                { "update", no_argument, NULL, 'u' },
                { "root", required_argument, NULL, 'r' },
                { "test", required_argument, NULL, 't' },
                { "help", no_argument, NULL, 'h' },
                {}
        };
        const char *test = NULL;
        const char *root = "";
        bool update = false;
        struct trie *trie = NULL;
        int err;
        int rc = EXIT_SUCCESS;

        for (;;) {
                int option;

                option = getopt_long(argc, argv, "ut:r:h", options, NULL);
                if (option == -1)
                        break;

                switch (option) {
                case 'u':
                        update = true;
                        break;
                case 't':
                        test = optarg;
                        break;
                case 'r':
                        root = optarg;
                        break;
                case 'h':
                        help();
                        return EXIT_SUCCESS;
                }
        }

        if (!update && !test) {
                help();
                return EXIT_SUCCESS;
        }

        if (update) {
                char **files, **f;
                _cleanup_free_ char *hwdb_bin = NULL;

                trie = calloc(sizeof(struct trie), 1);
                if (!trie) {
                        rc = EXIT_FAILURE;
                        goto out;
                }

                /* string store */
                trie->strings = strbuf_new();
                if (!trie->strings) {
                        rc = EXIT_FAILURE;
                        goto out;
                }

                /* index */
                trie->root = calloc(sizeof(struct trie_node), 1);
                if (!trie->root) {
                        rc = EXIT_FAILURE;
                        goto out;
                }
                trie->nodes_count++;

                err = conf_files_list_strv(&files, ".hwdb", root, conf_file_dirs);
                if (err < 0) {
                        log_error("failed to enumerate hwdb files: %s\n", strerror(-err));
                        rc = EXIT_FAILURE;
                        goto out;
                }
                STRV_FOREACH(f, files) {
                        log_debug("reading file '%s'", *f);
                        import_file(udev, trie, *f);
                }
                strv_free(files);

                strbuf_complete(trie->strings);

                log_debug("=== trie in-memory ===\n");
                log_debug("nodes:            %8zu bytes (%8zu)\n",
                          trie->nodes_count * sizeof(struct trie_node), trie->nodes_count);
                log_debug("children arrays:  %8zu bytes (%8zu)\n",
                          trie->children_count * sizeof(struct trie_child_entry), trie->children_count);
                log_debug("values arrays:    %8zu bytes (%8zu)\n",
                          trie->values_count * sizeof(struct trie_value_entry), trie->values_count);
                log_debug("strings:          %8zu bytes\n",
                          trie->strings->len);
                log_debug("strings incoming: %8zu bytes (%8zu)\n",
                          trie->strings->in_len, trie->strings->in_count);
                log_debug("strings dedup'ed: %8zu bytes (%8zu)\n",
                          trie->strings->dedup_len, trie->strings->dedup_count);

                if (asprintf(&hwdb_bin, "%s/" UDEVLIBEXECDIR "/hwdb.bin", root) < 0) {
                        rc = EXIT_FAILURE;
                        goto out;
                }
                mkdir_parents(hwdb_bin, 0755);
                err = trie_store(trie, hwdb_bin);
                if (err < 0) {
                        log_error("Failure writing database %s: %s", hwdb_bin, strerror(-err));
                        rc = EXIT_FAILURE;
                }
        }
示例#15
0
文件: fc-match.c 项目: Ionic/nx-libs
int
main (int argc, char **argv)
{
    int		verbose = 0;
    int		sort = 0;
    int		i;
    FcFontSet	*fs;
    FcPattern   *pat;
    FcResult	result;
#if HAVE_GETOPT_LONG || HAVE_GETOPT
    int		c;

#if HAVE_GETOPT_LONG
    while ((c = getopt_long (argc, argv, "Vv?", longopts, NULL)) != -1)
#else
    while ((c = getopt (argc, argv, "sVv?")) != -1)
#endif
    {
	switch (c) {
	case 's':
	    sort = 1;
	    break;
	case 'V':
	    fprintf (stderr, "fontconfig version %d.%d.%d\n", 
		     FC_MAJOR, FC_MINOR, FC_REVISION);
	    exit (0);
	case 'v':
	    verbose = 1;
	    break;
	default:
	    usage (argv[0]);
	}
    }
    i = optind;
#else
    i = 1;
#endif

    if (!FcInit ())
    {
	fprintf (stderr, "Can't init font config library\n");
	return 1;
    }
    if (argv[i])
	pat = FcNameParse ((FcChar8 *) argv[i]);
    else
	pat = FcPatternCreate ();

    FcConfigSubstitute (0, pat, FcMatchPattern);
    FcDefaultSubstitute (pat);
    
    if (sort)
	fs = FcFontSort (0, pat, FcTrue, 0, &result);
    else
    {
	FcPattern   *match;
	fs = FcFontSetCreate ();
	match = FcFontMatch (0, pat, &result);
	if (match)
	    FcFontSetAdd (fs, match);
    }
    if (pat)
	FcPatternDestroy (pat);

    if (fs)
    {
	int	j;

	for (j = 0; j < fs->nfont; j++)
	{
	    if (verbose)
	    {
		FcPatternPrint (fs->fonts[j]);
	    }
	    else
	    {
		FcChar8	*family;
		FcChar8	*style;
		FcChar8	*file;

		if (FcPatternGetString (fs->fonts[j], FC_FILE, 0, &file) != FcResultMatch)
		    file = "<unknown filename>";
		else
		{
		    FcChar8 *slash = strrchr (file, '/');
		    if (slash)
			file = slash+1;
		}
		if (FcPatternGetString (fs->fonts[j], FC_FAMILY, 0, &family) != FcResultMatch)
		    family = "<unknown family>";
		if (FcPatternGetString (fs->fonts[j], FC_STYLE, 0, &style) != FcResultMatch)
		    file = "<unknown style>";

		printf ("%s: \"%s\" \"%s\"\n", file, family, style);
	    }
	}
	FcFontSetDestroy (fs);
    }
    return 0;
}
示例#16
0
int main(int argc, char *argv[])
{
	static const char short_options[] = "hVlp:";
	static const struct option long_options[] = {
		{"help", 0, NULL, 'h'},
		{"version", 0, NULL, 'V'},
		{"list", 0, NULL, 'l'},
		{"port", 1, NULL, 'p'},
		{ }
	};

	int do_list = 0;
	struct pollfd *pfds;
	int npfds;
	int c, err;

	init_seq();

	while ((c = getopt_long(argc, argv, short_options,
				long_options, NULL)) != -1) {
		switch (c) {
		case 'h':
			help(argv[0]);
			return 0;
		case 'V':
			version();
			return 0;
		case 'l':
			do_list = 1;
			break;
		case 'p':
			parse_ports(optarg);
			break;
		default:
			help(argv[0]);
			return 1;
		}
	}
	if (optind < argc) {
		help(argv[0]);
		return 1;
	}

	if (do_list) {
		list_ports();
		return 0;
	}

	create_port();
	connect_ports();

	err = snd_seq_nonblock(seq, 1);
	check_snd("set nonblock mode", err);
	
	if (port_count > 0)
		printf("Waiting for data.");
	else
		printf("Waiting for data at port %d:0.",
		       snd_seq_client_id(seq));
	printf(" Press Ctrl+C to end.\n");
	printf("Source  Event                  Ch  Data\n");
	
	signal(SIGINT, sighandler);
	signal(SIGTERM, sighandler);

	npfds = snd_seq_poll_descriptors_count(seq, POLLIN);
	pfds = alloca(sizeof(*pfds) * npfds);
	for (;;) {
		snd_seq_poll_descriptors(seq, pfds, npfds, POLLIN);
		if (poll(pfds, npfds, -1) < 0)
			break;
		do {
			snd_seq_event_t *event;
			err = snd_seq_event_input(seq, &event);
			if (err < 0)
				break;
			if (event)
				dump_event(event);
		} while (err > 0);
		fflush(stdout);
		if (stop)
			break;
	}

	snd_seq_close(seq);
	return 0;
}
示例#17
0
int main(int argc, char **argv)
{
	int permission = 0644;
	int opt;
	size_t size = 0;
	int nsems = 0;
	int ask_shm = 0, ask_msg = 0, ask_sem = 0;
	static const struct option longopts[] = {
		{"shmem", required_argument, NULL, 'M'},
		{"semaphore", required_argument, NULL, 'S'},
		{"queue", no_argument, NULL, 'Q'},
		{"mode", required_argument, NULL, 'p'},
		{"version", no_argument, NULL, 'V'},
		{"help", no_argument, NULL, 'h'},
		{NULL, 0, NULL, 0}
	};

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	while((opt = getopt_long(argc, argv, "hM:QS:p:Vh", longopts, NULL)) != -1) {
		switch(opt) {
		case 'M':
			size = strtou64_or_err(optarg, _("failed to parse size"));
			ask_shm = 1;
			break;
		case 'Q':
			ask_msg = 1;
			break;
		case 'S':
			nsems = strtos32_or_err(optarg, _("failed to parse elements"));
			ask_sem = 1;
			break;
		case 'p':
			permission = strtoul(optarg, NULL, 8);
			break;
		case 'h':
			usage(stdout);
			break;
		case 'V':
			printf(UTIL_LINUX_VERSION);
			return EXIT_SUCCESS;
		default:
			ask_shm = ask_msg = ask_sem = 0;
			break;
		}
	}

	if(!ask_shm && !ask_msg && !ask_sem)
		usage(stderr);

	if (ask_shm) {
		int shmid;
		if (-1 == (shmid = create_shm(size, permission)))
			err(EXIT_FAILURE, _("create share memory failed"));
		else
			printf(_("Shared memory id: %d\n"), shmid);
	}

	if (ask_msg) {
		int msgid;
		if (-1 == (msgid = create_msg(permission)))
			err(EXIT_FAILURE, _("create message queue failed"));
		else
			printf(_("Message queue id: %d\n"), msgid);
	}

	if (ask_sem) {
		int semid;
		if (-1 == (semid = create_sem(nsems, permission)))
			err(EXIT_FAILURE, _("create semaphore failed"));
		else
			printf(_("Semaphore id: %d\n"), semid);
	}

	return EXIT_SUCCESS;
}
示例#18
0
/*
 * @mrule   Rule structure.
 *
 * @return  -1: Error. 0: Output help. 1: Add rule. 2: Delete rule. 3: List
 * rules. 4: Flush rules.
 *
 */
int parse_args(int argc, char **argv, struct mer_rule *mrule)
{
	int opt, arg_index;

	/* Command-line options. */
	struct option mer_options[] = {
		{ "index", required_argument, NULL, 'x' },
		{ "delete", required_argument, NULL, 'd' },
		{ "action", required_argument, NULL, 'c' },
		{ "direction", required_argument, NULL, 'e' },
		{ "proto", required_argument, NULL, 'r' },
		{ "srcip", required_argument, NULL, 'i' },
		{ "dstip", required_argument, NULL, 'I' },
		{ "srcport", required_argument, NULL, 'p' },
		{ "dstport", required_argument, NULL, 'P' },
		{ "list", no_argument, NULL, 'l' },
		{ "flush", no_argument, NULL, 'f' },
		{ "help", no_argument, NULL, 'h' },
		{ 0, 0, 0, 0 }
	};

	if (!argv || !mrule || argc < 2)
		return -1;

	/* Parse arguments */
	opt = getopt_long(argc, argv, "lh", mer_options, &arg_index);
	while (opt != -1) {
		int port, index;
		__u32 ip;

		switch (opt) {

		/* --index */
		case 'x':
			index = atoi(optarg);
			if (index < 0)
				return -1;
			mrule->index = index;
			break;

		/* --direction */
		case 'e':
			if (!strcasecmp(optarg, DIRECTION_ALL_STR))
				mrule->direction = DIRECTION_ALL;
			else if (!strcasecmp(optarg, DIRECTION_IN_STR))
				mrule->direction = DIRECTION_IN;
			else if (!strcasecmp(optarg, DIRECTION_OUT_STR))
				mrule->direction = DIRECTION_OUT;
			else
				return -1;
			break;

		/* --proto */
		case 'r':
			if (!strcasecmp(optarg, PROTO_ALL_STR))
				mrule->proto = PROTO_ALL;
			else if (!strcasecmp(optarg, PROTO_TCP_STR))
				mrule->proto = PROTO_TCP;
			else if (!strcasecmp(optarg, PROTO_UDP_STR))
				mrule->proto = PROTO_UDP;
			else
				return -1;
			break;

		/* --srcip */
		case 'i':
			if (inet_pton(AF_INET, optarg, &ip) <= 0)
				return -1;
			mrule->srcip = ip;
			break;

		/* --dstip */
		case 'I':
			if (inet_pton(AF_INET, optarg, &ip) <= 0)
				return -1;
			mrule->dstip = ip;
			break;

		/* --srcport */
		case 'p':
			port = atoi(optarg);
			if (port < 0 || port > PORT_MAX)
				return -1;
			mrule->srcport = port;
			break;

		/* --dstport */
		case 'P':
			port = atoi(optarg);
			if (port < 0 || port > PORT_MAX)
				return -1;
			mrule->dstport = port;
			break;

		/* --action */
		case 'c':
			if (!strcasecmp(optarg, ACT_DROP_STR))
				mrule->action = ACT_DROP;
			else if (!strcasecmp(optarg, ACT_PASS_STR))
				mrule->action = ACT_PASS;
			else if (!strcasecmp(optarg, ACT_LOG_STR))
				mrule->action = ACT_LOG;
			else
				return -1;
			break;

		/* --delete */
		case 'd':
			index = atoi(optarg);
			if (index < 0)
				return -1;
			mrule->index = index;
			return 2;

		/* --list */
		case 'l':
			return 3;

		/* --flush */
		case 'f':
			return 4;

		/* --help */
		case 'h':
			return 0;

		/* Error */
		case '?':
		default:
			return -1;
		}
		opt = getopt_long(argc, argv, "lh", mer_options, &arg_index);
	}

	/* Default: Add rule */
	return 1;
}
示例#19
0
int main(int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;

    int server_num = 0;
    const char *server_host[MAX_REMOTE_NUM];
    const char *server_port = NULL;

    char * nameservers[MAX_DNS_NUM + 1];
    int nameserver_num = 0;

    int option_index = 0;
    static struct option long_options[] =
    {
        { "fast-open", no_argument,       0, 0 },
        { "acl",       required_argument, 0, 0 },
        { 0,           0,                 0, 0 }
    };

    opterr = 0;

    USE_TTY();

    while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:c:i:d:a:uv",
                            long_options, &option_index)) != -1) {
        switch (c) {
        case 0:
            if (option_index == 0) {
                fast_open = 1;
            } else if (option_index == 1) {
                LOGI("initialize acl...");
                acl = !init_acl(optarg);
            }
            break;
        case 's':
            if (server_num < MAX_REMOTE_NUM) {
                server_host[server_num++] = optarg;
            }
            break;
        case 'p':
            server_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'd':
            if (nameserver_num < MAX_DNS_NUM) {
                nameservers[nameserver_num++] = optarg;
            }
            break;
        case 'a':
            user = optarg;
            break;
        case 'u':
            udprelay = 1;
            break;
        case 'v':
            verbose = 1;
            break;
        }
    }

    if (opterr) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (argc == 1) {
        if (conf_path == NULL) {
            conf_path = DEFAULT_CONF_PATH;
        }
    }

    if (conf_path != NULL) {
        jconf_t *conf = read_jconf(conf_path);
        if (server_num == 0) {
            server_num = conf->remote_num;
            for (i = 0; i < server_num; i++) {
                server_host[i] = conf->remote_addr[i].host;
            }
        }
        if (server_port == NULL) {
            server_port = conf->remote_port;
        }
        if (password == NULL) {
            password = conf->password;
        }
        if (method == NULL) {
            method = conf->method;
        }
        if (timeout == NULL) {
            timeout = conf->timeout;
        }
#ifdef TCP_FASTOPEN
        if (fast_open == 0) {
            fast_open = conf->fast_open;
        }
#endif
#ifdef HAVE_SETRLIMIT
        if (nofile == 0) {
            nofile = conf->nofile;
        }
        /*
         * no need to check the return value here since we will show
         * the user an error message if setrlimit(2) fails
         */
        if (nofile) {
            if (verbose) {
                LOGI("setting NOFILE to %d", nofile);
            }
            set_nofile(nofile);
        }
#endif
        if (conf->nameserver != NULL) {
            nameservers[nameserver_num++] = conf->nameserver;
        }
    }

    if (server_num == 0) {
        server_host[server_num++] = NULL;
    }

    if (server_num == 0 || server_port == NULL || password == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (method == NULL) {
        method = "table";
    }

    if (timeout == NULL) {
        timeout = "60";
    }

    if (pid_flags) {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    if (fast_open == 1) {
#ifdef TCP_FASTOPEN
        LOGI("using tcp fast open");
#else
        LOGE("tcp fast open is not supported by this environment");
#endif
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    struct ev_signal sigint_watcher;
    struct ev_signal sigterm_watcher;
    ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
    ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
    ev_signal_start(EV_DEFAULT, &sigint_watcher);
    ev_signal_start(EV_DEFAULT, &sigterm_watcher);

    // setup keys
    LOGI("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // inilitialize ev loop
    struct ev_loop *loop = EV_DEFAULT;

    // setup udns
    if (nameserver_num == 0) {
#ifdef __MINGW32__
        nameservers[nameserver_num++] = "8.8.8.8";
        resolv_init(loop, nameservers, nameserver_num);
#else
        resolv_init(loop, NULL, 0);
#endif
    } else {
        resolv_init(loop, nameservers, nameserver_num);
    }

    for (int i = 0; i < nameserver_num; i++) {
        LOGI("using nameserver: %s", nameservers[i]);
    }

    // inilitialize listen context
    struct listen_ctx listen_ctx_list[server_num];

    // bind to each interface
    while (server_num > 0) {
        int index = --server_num;
        const char * host = server_host[index];

        // Bind to port
        int listenfd;
        listenfd = create_and_bind(host, server_port);
        if (listenfd < 0) {
            FATAL("bind() error");
        }
        if (listen(listenfd, SSMAXCONN) == -1) {
            FATAL("listen() error");
        }
        setnonblocking(listenfd);
        LOGI("listening at %s:%s", host ? host : "*", server_port);

        struct listen_ctx *listen_ctx = &listen_ctx_list[index];

        // Setup proxy context
        listen_ctx->timeout = atoi(timeout);
        listen_ctx->fd = listenfd;
        listen_ctx->method = m;
        listen_ctx->iface = iface;
        listen_ctx->loop = loop;

        ev_io_init(&listen_ctx->io, accept_cb, listenfd, EV_READ);
        ev_io_start(loop, &listen_ctx->io);

        // Setup UDP
        if (udprelay) {
            init_udprelay(server_host[index], server_port, m, atoi(timeout),
                          iface);
        }

    }

    if (udprelay) {
        LOGI("udprelay enabled");
    }

    // setuid
    if (user != NULL) {
        run_as(user);
    }

    // Init connections
    cork_dllist_init(&connections);

    // start ev loop
    ev_run(loop, 0);

    if (verbose) {
        LOGI("closed gracefully");
    }

    // Clean up
    for (int i = 0; i <= server_num; i++) {
        struct listen_ctx *listen_ctx = &listen_ctx_list[i];
        ev_io_stop(loop, &listen_ctx->io);
        close(listen_ctx->fd);
    }

    free_connections(loop);

    if (udprelay) {
        free_udprelay();
    }

    resolv_shutdown(loop);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    ev_signal_stop(EV_DEFAULT, &sigint_watcher);
    ev_signal_stop(EV_DEFAULT, &sigterm_watcher);

    return 0;
}
示例#20
0
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
  int c;
  char *rv[2];

  int option = 0;
  static struct option longopts[] = {
    {"hostname", required_argument, 0, 'H'},
    {"sourceip", required_argument, 0, 'S'},
    {"sourceif", required_argument, 0, 'I'},
    {"critical", required_argument, 0, 'c'},
    {"warning", required_argument, 0, 'w'},
    {"bytes", required_argument, 0, 'b'},
    {"number", required_argument, 0, 'n'},
    {"target-timeout", required_argument, 0, 'T'},
    {"interval", required_argument, 0, 'i'},
    {"verbose", no_argument, 0, 'v'},
    {"version", no_argument, 0, 'V'},
    {"help", no_argument, 0, 'h'},
    {"use-ipv4", no_argument, 0, '4'},
    {"use-ipv6", no_argument, 0, '6'},
    {0, 0, 0, 0}
  };

  rv[PL] = NULL;
  rv[RTA] = NULL;

  if (argc < 2)
    return ERROR;

  if (!is_option (argv[1])) {
    server_name = argv[1];
    argv[1] = argv[0];
    argv = &argv[1];
    argc--;
  }

  while (1) {
    c = getopt_long (argc, argv, "+hVvH:S:c:w:b:n:T:i:I:46", longopts, &option);

    if (c == -1 || c == EOF || c == 1)
      break;

    switch (c) {
    case '?':                 /* print short usage statement if args not parsable */
      usage5 ();
    case 'h':                 /* help */
      print_help ();
      exit (STATE_UNKNOWN);
    case 'V':                 /* version */
      print_revision (progname, NP_VERSION);
      exit (STATE_UNKNOWN);
    case 'v':                 /* verbose mode */
      verbose = TRUE;
      break;
    case 'H':                 /* hostname */
      if (is_host (optarg) == FALSE) {
        usage2 (_("Invalid hostname/address"), optarg);
      }
      server_name = strscpy (server_name, optarg);
      break;
    case 'S':                 /* sourceip */
      if (is_host (optarg) == FALSE) {
        usage2 (_("Invalid hostname/address"), optarg);
      }
      sourceip = strscpy (sourceip, optarg);
      break;
    case 'I':                 /* sourceip */
      sourceif = strscpy (sourceif, optarg);
    case '4':                 /* IPv4 only */
      address_family = AF_INET;
      break;
    case '6':                 /* IPv6 only */
#ifdef USE_IPV6
      address_family = AF_INET6;
#else
      usage (_("IPv6 support not available\n"));
#endif
      break;
    case 'c':
      get_threshold (optarg, rv);
      if (rv[RTA]) {
        crta = strtod (rv[RTA], NULL);
        crta_p = TRUE;
        rv[RTA] = NULL;
      }
      if (rv[PL]) {
        cpl = atoi (rv[PL]);
        cpl_p = TRUE;
        rv[PL] = NULL;
      }
      break;
    case 'w':
      get_threshold (optarg, rv);
      if (rv[RTA]) {
        wrta = strtod (rv[RTA], NULL);
        wrta_p = TRUE;
        rv[RTA] = NULL;
      }
      if (rv[PL]) {
        wpl = atoi (rv[PL]);
        wpl_p = TRUE;
        rv[PL] = NULL;
      }
      break;
    case 'b':                 /* bytes per packet */
      if (is_intpos (optarg))
        packet_size = atoi (optarg);
      else
        usage (_("Packet size must be a positive integer"));
      break;
    case 'n':                 /* number of packets */
      if (is_intpos (optarg))
        packet_count = atoi (optarg);
      else
        usage (_("Packet count must be a positive integer"));
      break;
    case 'T':                 /* timeout in msec */
      if (is_intpos (optarg))
        target_timeout = atoi (optarg);
      else
        usage (_("Target timeout must be a positive integer"));
      break;
    case 'i':                 /* interval in msec */
      if (is_intpos (optarg))
        packet_interval = atoi (optarg);
      else
        usage (_("Interval must be a positive integer"));
      break;
    }
  }

  if (server_name == NULL)
    usage4 (_("Hostname was not supplied"));

  return OK;
}
int
main (int argc, char **argv)
{
  int c, err;
  bool verbose = false;
  unsigned int tcp_flags = TCP_UNSET;
  char *critical = NULL, *warning = NULL;
  nagstatus status = STATE_OK;
  thresholds *my_threshold = NULL;

  struct proc_tcptable *tcptable = NULL;
  unsigned long tcp_established;
  unsigned long tcp_syn_sent;
  unsigned long tcp_syn_recv;
  unsigned long tcp_fin_wait1;
  unsigned long tcp_fin_wait2;
  unsigned long tcp_time_wait;
  unsigned long tcp_close;
  unsigned long tcp_close_wait;
  unsigned long tcp_last_ack;
  unsigned long tcp_listen;
  unsigned long tcp_closing;

  set_program_name (argv[0]);

  while ((c = getopt_long (argc, argv,
			   "t6c:w:v" GETOPT_HELP_VERSION_STRING,
			   longopts, NULL)) != -1)
    {
      switch (c)
	{
	default:
	  usage (stderr);
	case 't':
	  tcp_flags |= TCP_v4;
	  break;
	case '6':
	  tcp_flags |= TCP_v6;
	  break;
	case 'c':
	  critical = optarg;
	  break;
	case 'w':
	  warning = optarg;
	  break;
	case 'v':
	  verbose = true;
	  break;

	case_GETOPT_HELP_CHAR
	case_GETOPT_VERSION_CHAR

	}
    }

  if (tcp_flags == TCP_UNSET)
    tcp_flags = TCP_v4;

  if (verbose)
    tcp_flags |= TCP_VERBOSE;

  status = set_thresholds (&my_threshold, warning, critical);
  if (status == NP_RANGE_UNPARSEABLE)
    usage (stderr);

  err = proc_tcptable_new (&tcptable);
  if (err < 0)
    plugin_error (STATE_UNKNOWN, err, "memory exhausted");

  proc_tcptable_read (tcptable, tcp_flags);

  tcp_established = proc_tcp_get_tcp_established (tcptable);
  tcp_syn_sent    = proc_tcp_get_tcp_syn_sent (tcptable);
  tcp_syn_recv    = proc_tcp_get_tcp_syn_recv (tcptable);
  tcp_fin_wait1   = proc_tcp_get_tcp_fin_wait1 (tcptable);
  tcp_fin_wait2   = proc_tcp_get_tcp_fin_wait2 (tcptable);
  tcp_time_wait   = proc_tcp_get_tcp_time_wait (tcptable);
  tcp_close       = proc_tcp_get_tcp_close (tcptable);
  tcp_close_wait  = proc_tcp_get_tcp_close_wait (tcptable);
  tcp_last_ack    = proc_tcp_get_tcp_last_ack (tcptable);
  tcp_listen      = proc_tcp_get_tcp_listen (tcptable);
  tcp_closing     = proc_tcp_get_tcp_closing (tcptable);

  proc_tcptable_unref (tcptable);

  status = get_status (tcp_established, my_threshold);
  free (my_threshold);

  printf ("%s %s - %lu tcp established | "
	  "tcp_established=%lu tcp_syn_sent=%lu tcp_syn_recv=%lu "
	  "tcp_fin_wait1=%lu tcp_fin_wait2=%lu tcp_time_wait=%lu "
	  "tcp_close=%lu tcp_close_wait=%lu tcp_last_ack=%lu "
	  "tcp_listen=%lu tcp_closing=%lu\n",
	  program_name_short, state_text (status), tcp_established,
	  tcp_established, tcp_syn_sent, tcp_syn_recv,
	  tcp_fin_wait1, tcp_fin_wait2, tcp_time_wait,
	  tcp_close, tcp_close_wait, tcp_last_ack,
	  tcp_listen, tcp_closing);

  return status;
}
示例#22
0
文件: cibmon.c 项目: fghaas/pacemaker
int
main(int argc, char **argv)
{
    int argerr = 0;
    int flag;
    int attempts = 0;

#ifdef HAVE_GETOPT_H
    int option_index = 0;

    static struct option long_options[] = {
        /* Top-level Options */
        {"verbose", 0, 0, 'V'},
        {"help", 0, 0, '?'},
        {"log-diffs", 0, 0, 'd'},
        {"log-updates", 0, 0, 'u'},
        {"max-conn-fail", 1, 0, 'm'},
        {0, 0, 0, 0}
    };
#endif

    crm_log_init_quiet(NULL, LOG_INFO, FALSE, FALSE, argc, argv);

    crm_signal(SIGTERM, cibmon_shutdown);

    while (1) {
#ifdef HAVE_GETOPT_H
        flag = getopt_long(argc, argv, OPTARGS, long_options, &option_index);
#else
        flag = getopt(argc, argv, OPTARGS);
#endif
        if (flag == -1)
            break;

        switch (flag) {
        case 'V':
            crm_bump_log_level();
            break;
        case '?':
            usage(crm_system_name, LSB_EXIT_OK);
            break;
        case 'd':
            log_diffs = TRUE;
            break;
        case 'u':
            log_updates = TRUE;
            break;
        case 'm':
            max_failures = crm_parse_int(optarg, "30");
            break;
        default:
            printf("Argument code 0%o (%c)" " is not (?yet?) supported\n", flag, flag);
            ++argerr;
            break;
        }
    }

    if (optind < argc) {
        printf("non-option ARGV-elements: ");
        while (optind < argc)
            printf("%s ", argv[optind++]);
        printf("\n");
    }

    if (optind > argc) {
        ++argerr;
    }

    if (argerr) {
        usage(crm_system_name, LSB_EXIT_GENERIC);
    }

    cib = cib_new();

    do {
        sleep(1);
        exit_code = cib->cmds->signon(cib, crm_system_name, cib_query);

    } while (exit_code == cib_connection && attempts++ < max_failures);

    if (exit_code != cib_ok) {
        crm_err("Signon to CIB failed: %s", cib_error2string(exit_code));
    }

    if (exit_code == cib_ok) {
        crm_debug("Setting dnotify");
        exit_code = cib->cmds->set_connection_dnotify(cib, cib_connection_destroy);
    }

    crm_debug("Setting diff callback");
    exit_code = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, cibmon_diff);

    if (exit_code != cib_ok) {
        crm_err("Failed to set %s callback: %s", T_CIB_DIFF_NOTIFY, cib_error2string(exit_code));
    }

    if (exit_code != cib_ok) {
        crm_err("Setup failed, could not monitor CIB actions");
        return -exit_code;
    }

    mainloop = g_main_new(FALSE);
    crm_info("Starting mainloop");
    g_main_run(mainloop);
    crm_debug_3("%s exiting normally", crm_system_name);
    fflush(stderr);
    return -exit_code;
}
示例#23
0
int main(int argc, char **argv)
{
	int ch, longindex, nr;
	int is_daemon = 1, is_debug = 1;
	pid_t pid;
	struct pollfd *poll_array;

	while ((ch = getopt_long(argc, argv, "fd:vh", long_options, &longindex)) >= 0) {
		switch (ch) {
		case 'f':
			is_daemon = 0;
			break;
		case 'd':
			is_debug = atoi(optarg);
			break;
		case 'v':
			exit(0);
			break;
		case 'h':
			usage(0);
			break;
		default:
			usage(1);
			break;
		}
	}

	init(is_daemon, is_debug);

	if (is_daemon) {
		pid = fork();
		if (pid < 0)
			exit(-1);
		else if (pid)
			exit(0);

		chdir("/");

		close(0);
		open("/dev/null", O_RDWR);
		dup2(0, 1);
		dup2(0, 2);
		setsid();
	}

	nl_fd = nl_open();
	if (nl_fd < 0)
		exit(nl_fd);

	ipc_fd = ipc_open();
	if (ipc_fd < 0)
		exit(ipc_fd);

	dl_init();

	nr = MAX_DL_HANDLES;
	poll_array = poll_init(nr);

	dl_config_load();

	event_loop(nr, poll_array);

	return 0;
}
示例#24
0
int main( int argc, char **argv )
{
  int i, listenSocket[ MAX_PLAYERS ], v, longOpt;
  int fixedSeats, quiet;
  int seatFD[ MAX_PLAYERS ];
  FILE *file, *logFile, *transactionFile;
  ReadBuf *readBuf[ MAX_PLAYERS ];
  Game *game;
  rng_state_t rng;
  ErrorInfo errorInfo;
  struct sockaddr_in addr;
  socklen_t addrLen;
  char *seatName[ MAX_PLAYERS ];

  int useLogFile, useTransactionFile;
  uint64_t maxResponseMicros, maxUsedHandMicros, maxUsedPerHandMicros;
  uint32_t numHands, seed, maxInvalidActions;
  uint16_t listenPort[ MAX_PLAYERS ];

  char name[ MAX_LINE_LEN ];
  static struct option longOptions[] = {
    { "t_response", 1, 0, 0 },
    { "t_hand", 1, 0, 0 },
    { "t_per_hand", 1, 0, 0 },
    { 0, 0, 0, 0 }
  };

  /* set defaults */

  /* game error conditions */
  maxInvalidActions = DEFAULT_MAX_INVALID_ACTIONS;
  maxResponseMicros = DEFAULT_MAX_RESPONSE_MICROS;
  maxUsedHandMicros = DEFAULT_MAX_USED_HAND_MICROS;
  maxUsedPerHandMicros = DEFAULT_MAX_USED_PER_HAND_MICROS;

  /* use random ports */
  for( i = 0; i < MAX_PLAYERS; ++i ) {

    listenPort[ i ] = 0;
  }

  /* use log file, don't use transaction file */
  useLogFile = 1;
  useTransactionFile = 0;

  /* print all messages */
  quiet = 0;

  /* players rotate around the table */
  fixedSeats = 0;

  /* parse options */
  while( 1 ) {

    i = getopt_long( argc, argv, "flLp:qtT", longOptions, &longOpt );
    if( i < 0 ) {

      break;
    }

    switch( i ) {
    case 0:
      /* long option longOpt */

      switch( longOpt ) {
      case 0:
	/* t_response */

	if( sscanf( optarg, "%"SCNu64, &maxResponseMicros ) < 1 ) {

	  fprintf( stderr, "ERROR: could not get response timeout from %s\n",
		   optarg );
	  exit( EXIT_FAILURE );
	}

	/* convert from milliseconds to microseconds */
	maxResponseMicros *= 1000;
	break;

      case 1:
	/* t_hand */

	if( sscanf( optarg, "%"SCNu64, &maxUsedHandMicros ) < 1 ) {

	  fprintf( stderr,
		   "ERROR: could not get player hand timeout from %s\n",
		   optarg );
	  exit( EXIT_FAILURE );
	}

	/* convert from milliseconds to microseconds */
	maxUsedHandMicros *= 1000;
	break;

      case 2:
	/* t_per_hand */

	if( sscanf( optarg, "%"SCNu64, &maxUsedPerHandMicros ) < 1 ) {

	  fprintf( stderr, "ERROR: could not get average player hand timeout from %s\n", optarg );
	  exit( EXIT_FAILURE );
	}

	/* convert from milliseconds to microseconds */
	maxUsedPerHandMicros *= 1000;
	break;

      }
      break;

    case 'f':
      /* fix the player seats */;

      fixedSeats = 1;
      break;

    case 'l':
      /* no transactionFile */;

      useLogFile = 0;
      break;

    case 'L':
      /* use transactionFile */;

      useLogFile = 1;
      break;

    case 'p':
      /* port specification */

      if( scanPortString( optarg, listenPort ) < 0 ) {

	fprintf( stderr, "ERROR: bad port string %s\n", optarg );
	exit( EXIT_FAILURE );
      }

      break;

    case 'q':

      quiet = 1;
      break;

    case 't':
      /* no transactionFile */

      useTransactionFile = 0;
      break;

    case 'T':
      /* use transactionFile */

      useTransactionFile = 1;
      break;

    default:

      fprintf( stderr, "ERROR: unknown option %c\n", i );
      exit( EXIT_FAILURE );
    }
  }

  if( optind + 4 > argc ) {

    printUsage( stdout, 0 );
    exit( EXIT_FAILURE );
  }

  /* get the game definition */
  file = fopen( argv[ optind + 1 ], "r" );
  if( file == NULL ) {

    fprintf( stderr, "ERROR: could not open game definition %s\n",
	     argv[ optind + 1 ] );
    exit( EXIT_FAILURE );
  }
  game = readGame( file );
  if( game == NULL ) {

    fprintf( stderr, "ERROR: could not read game %s\n", argv[ optind + 1 ] );
    exit( EXIT_FAILURE );
  }
  fclose( file );

  /* save the seat names */
  if( optind + 4 + game->numPlayers > argc ) {

    printUsage( stdout, 0 );
    exit( EXIT_FAILURE );
  }
  for( i = 0; i < game->numPlayers; ++i ) {

    seatName[ i ] = argv[ optind + 4 + i ];
  }

  /* get number of hands */
  if( sscanf( argv[ optind + 2 ], "%"SCNu32, &numHands ) < 1
      || numHands == 0 ) {

    fprintf( stderr, "ERROR: invalid number of hands %s\n",
	     argv[ optind + 2 ] );
    exit( EXIT_FAILURE );
  }

  /* get random number seed */
  if( sscanf( argv[ optind + 3 ], "%"SCNu32, &seed ) < 1 ) {

    fprintf( stderr, "ERROR: invalid random number seed %s\n",
	     argv[ optind + 3 ] );
    exit( EXIT_FAILURE );
  }
  init_genrand( &rng, seed );
  srandom( seed ); /* used for random port selection */

  if( useLogFile ) {
    /* create/open the log */
    if( snprintf( name, MAX_LINE_LEN, "%s.log", argv[ optind ] ) < 0 ) {

      fprintf( stderr, "ERROR: match file name too long %s\n", argv[ optind ] );
      exit( EXIT_FAILURE );
    }
    logFile = fopen( name, "a+" );
    if( logFile == NULL ) {

      fprintf( stderr, "ERROR: could not open log file %s\n", name );
      exit( EXIT_FAILURE );
    }
  } else {
    /* no log file */

    logFile = NULL;
  }

  if( useTransactionFile ) {
    /* create/open the transaction log */

    if( snprintf( name, MAX_LINE_LEN, "%s.tlog", argv[ optind ] ) < 0 ) {

      fprintf( stderr, "ERROR: match file name too long %s\n", argv[ optind ] );
      exit( EXIT_FAILURE );
    }
    transactionFile = fopen( name, "a+" );
    if( transactionFile == NULL ) {

      fprintf( stderr, "ERROR: could not open transaction file %s\n", name );
      exit( EXIT_FAILURE );
    }
  } else { 
    /* no transaction file */

    transactionFile = NULL;
  }

  /* set up the error info */
  initErrorInfo( maxInvalidActions, maxResponseMicros, maxUsedHandMicros,
		 maxUsedPerHandMicros * numHands, &errorInfo );

  /* open sockets for players to connect to */
  for( i = 0; i < game->numPlayers; ++i ) {

    listenSocket[ i ] = getListenSocket( &listenPort[ i ] );
    if( listenSocket[ i ] < 0 ) {

      fprintf( stderr, "ERROR: could not create listen socket for player %d\n",
	       i + 1 );
      exit( EXIT_FAILURE );
    }
  }

  /* print out the final port assignments */
  for( i = 0; i < game->numPlayers; ++i ) {
    printf( i ? " %"PRIu16 : "%"PRIu16, listenPort[ i ] );
  }
  printf( "\n" );
  fflush( stdout );

  /* print out usage information */
  printInitialMessage( argv[ optind ], argv[ optind + 1 ],
		       numHands, seed, &errorInfo, logFile );

  /* wait for each player to connect */
  for( i = 0; i < game->numPlayers; ++i ) {

    addrLen = sizeof( addr );
    seatFD[ i ] = accept( listenSocket[ i ],
			  (struct sockaddr *)&addr, &addrLen );
    if( seatFD[ i ] < 0 ) {

      fprintf( stderr, "ERROR: seat %d could not connect\n", i + 1 );
      exit( EXIT_FAILURE );
    }
    close( listenSocket[ i ] );

    v = 1;
    setsockopt( seatFD[ i ], IPPROTO_TCP, TCP_NODELAY,
		(char *)&v, sizeof(int) );

    readBuf[ i ] = createReadBuf();
  }

  /* play the match */
  if( gameLoop( game, seatName, numHands, quiet, fixedSeats, &rng, &errorInfo,
		seatFD, readBuf, logFile, transactionFile ) < 0 ) {
    /* should have already printed an error message */

    exit( EXIT_FAILURE );
  }

  fflush( stderr );
  fflush( stdout );
  if( transactionFile != NULL ) {
    fclose( transactionFile );
  }
  if( logFile != NULL ) {
    fclose( logFile );
  }
  free( game );

  return EXIT_SUCCESS;
}
示例#25
0
int main (int argc, char* argv[])
{
	bool argVerbose = false;
	bool argNoHeaders = false;
	bool argPrintHelp = false;
	const char* argBinaryDumpFile = 0;
	const char* argParseBinary  = 0;

	while (true)
	{
		int option_index = 0;
		static struct option long_options[] = {
				{"dumpbinary",  required_argument, 0, 'd' },
				{"parsebinary", required_argument, 0, 'p' },
				{"verbose",     no_argument, 0, 'v' },
				{"noheader",    no_argument, 0, 'n' },
				{"help",        no_argument, 0, 'h' },
				{0, 0, 0, 0 }
		};

		int c = getopt_long(argc, argv, "l:d:p:vnh", long_options, &option_index);
		if (c == -1)
			break;

		switch (c)
		{
		case 'd':
			argBinaryDumpFile = optarg;
			break;

		case 'p':
			argParseBinary = optarg;
			break;

		case 'v':
			argVerbose = true;
			break;

		case 'n':
			argNoHeaders = true;
			break;

		case 'h':
			argPrintHelp = true;
			break;

		case '?':
			std::cerr << "ERROR: error occurred while parsing command line options.\n\n";
			printHelp();
			return 1;
			break;

		default:
			std::cerr << "ERROR: getopt returned unhandled character code " << int(c) << "\n\n";
			printHelp();
			return 1;
		}
	}
	if (optind < argc)
	{
		std::cerr << "ERROR: non-option arguments provided: ";
		while (optind < argc)
		{
			std::cerr << "\"" << argv[optind++] << "\" ";
		}
		std::cerr << "\n\n";
		printHelp();
		return 1;
	}

	if (argPrintHelp)
	{
		printHelp();
		return 0;
	}

	if (argParseBinary)
	{
		processFile(argParseBinary, !argNoHeaders, argVerbose);
		return 0;
	}
	else
	{
		return processUSB(!argNoHeaders, argVerbose, argBinaryDumpFile);
	}

	
	return 1;
}
示例#26
0
/* Process the command line options and arguments. */
static lists_t_strs *process_command_line (int argc, char *argv[],
                                           struct parameters *params,
                                           lists_t_strs *deferred)
{
	int ret, opt_index = 0;
	const char *jump_type;
	lists_t_strs *result;

	struct option long_options[] = {
		{ "version",		0, NULL, 'V' },
		{ "help",		0, NULL, 'h' },
#ifndef NDEBUG
		{ "debug",		0, NULL, 'D' },
#endif
		{ "server",		0, NULL, 'S' },
		{ "foreground",		0, NULL, 'F' },
		{ "sound-driver",	1, NULL, 'R' },
		{ "music-dir",		0, NULL, 'm' },
		{ "append",		0, NULL, 'a' },
		{ "enqueue",		0, NULL, 'q' },
		{ "clear", 		0, NULL, 'c' },
		{ "play", 		0, NULL, 'p' },
		{ "playit",		0, NULL, 'l' },
		{ "stop",		0, NULL, 's' },
		{ "next",		0, NULL, 'f' },
		{ "previous",		0, NULL, 'r' },
		{ "exit",		0, NULL, 'x' },
		{ "theme",		1, NULL, 'T' },
		{ "config",		1, NULL, 'C' },
		{ "set-option",		1, NULL, 'O' },
		{ "moc-dir",		1, NULL, 'M' },
		{ "pause",		0, NULL, 'P' },
		{ "unpause",		0, NULL, 'U' },
		{ "toggle-pause",	0, NULL, 'G' },
		{ "sync",		0, NULL, 'y' },
		{ "nosync",		0, NULL, 'n' },
		{ "ascii",		0, NULL, 'A' },
		{ "info",		0, NULL, 'i' },
		{ "recursively",	0, NULL, 'e' },
		{ "seek",		1, NULL, 'k' },
		{ "jump",		1, NULL, 'j' },
		{ "format",		1, NULL, 'Q' },
		{ "volume",		1, NULL, 'v' },
		{ "toggle",		1, NULL, 't' },
		{ "on",			1, NULL, 'o' },
		{ "off",		1, NULL, 'u' },
		{ 0, 0, 0, 0 }
	};

	assert (argc >= 0);
	assert (argv != NULL);
	assert (argv[argc] == NULL);
	assert (params != NULL);
	assert (deferred != NULL);

	while ((ret = getopt_long(argc, argv,
					"VhDSFR:macpsxT:C:O:M:PUynArfiGelk:j:v:t:o:u:Q:q",
					long_options, &opt_index)) != -1) {
		switch (ret) {
			case 'V':
				show_version ();
				exit (0);
			case 'h':
				show_usage (argv[0]);
				exit (0);
#ifndef NDEBUG
			case 'D':
				params->debug = 1;
				break;
#endif
			case 'S':
				params->only_server = 1;
				break;
			case 'F':
				params->foreground = 1;
				params->only_server = 1;
				break;
			case 'R':
				if (!options_check_list ("SoundDriver", optarg))
					fatal ("No such sound driver: %s", optarg);
				options_set_list ("SoundDriver", optarg, false);
				options_ignore_config ("SoundDriver");
				break;
			case 'm':
				options_set_int ("StartInMusicDir", 1);
				options_ignore_config ("StartInMusicDir");
				break;
			case 'a':
			case 'e':
				params->append = 1;
				params->dont_run_iface = 1;
				break;
			case 'q':
				params->enqueue = 1;
				params->dont_run_iface = 1;
				break;
			case 'c':
				params->clear = 1;
				params->dont_run_iface = 1;
				break;
			case 'i':
				params->get_file_info = 1;
				params->dont_run_iface = 1;
				break;
			case 'p':
				params->play = 1;
				params->dont_run_iface = 1;
				break;
			case 'l':
				params->playit = 1;
				params->dont_run_iface = 1;
				break;
			case 's':
				params->stop = 1;
				params->dont_run_iface = 1;
				break;
			case 'f':
				params->next = 1;
				params->dont_run_iface = 1;
				break;
			case 'r':
				params->previous = 1;
				params->dont_run_iface = 1;
				break;
			case 'x':
				params->exit = 1;
				params->dont_run_iface = 1;
				break;
			case 'P':
				params->pause = 1;
				params->dont_run_iface = 1;
				break;
			case 'U':
				params->unpause = 1;
				params->dont_run_iface = 1;
				break;
			case 'T':
				options_set_str ("ForceTheme", optarg);
				break;
			case 'C':
				params->config_file = xstrdup (optarg);
				break;
			case 'O':
				override_config_option (optarg, deferred);
				break;
			case 'M':
				options_set_str ("MOCDir", optarg);
				options_ignore_config ("MOCDir");
				break;
			case 'y':
				options_set_int ("SyncPlaylist", 1);
				options_ignore_config ("SyncPlaylist");
				break;
			case 'n':
				options_set_int ("SyncPlaylist", 0);
				options_ignore_config ("SyncPlaylist");
				break;
			case 'A':
				options_set_int ("ASCIILines", 1);
				options_ignore_config ("ASCIILines");
				break;
			case 'G':
				params->toggle_pause = 1;
				params->dont_run_iface = 1;
				break;
			case 'k':
				params->seek_by = get_num_param (optarg, NULL);
				params->dont_run_iface = 1;
				break;
			case 'j':
				params->jump_to = get_num_param (optarg, &jump_type);
				if (*jump_type)
					if (!jump_type[1])
						if (*jump_type == '%' || tolower (*jump_type) == 's') {
							params->jump_type = tolower (*jump_type);
							params->dont_run_iface = 1;
							break;
						}
				//TODO: Add message explaining the error
				show_usage (argv[0]);
				exit (1);
			case 'v' :
				params->adj_volume = optarg;
				params->dont_run_iface = 1;
				break;
			case 't' :
				params->toggle = optarg;
				params->dont_run_iface = 1;
				break;
			case 'o' :
				params->on = optarg;
				params->dont_run_iface = 1;
				break;
			case 'u' :
				params->off = optarg;
				params->dont_run_iface = 1;
				break;
			case 'Q':
				params->formatted_into_param = optarg;
				params->get_formatted_info = 1;
				params->dont_run_iface = 1;
				break;
			default:
				show_usage (argv[0]);
				exit (1);
		}
	}

	result = lists_strs_new (argc - optind);
	lists_strs_load (result, argv + optind);

	return result;
}
示例#27
0
/* Parse command line options */
void patch_options_parse(int argc, char **argv) {
  int opt;

  const struct option opts[] = {
    {"address",       required_argument, NULL, 'a'},
    {"bytes",         required_argument, NULL, 'b'},
    {"filename",      required_argument, NULL, 'f'},
    {"help",          no_argument,       NULL, 'h'},
    {"offset",        required_argument, NULL, 'o'},
    {"output",        required_argument, NULL, 'O'},
    {"raw",           no_argument,       NULL, 'r'},
    {NULL,            0,                 NULL, 0  }
  };

  while((opt = getopt_long(argc, argv, "a:b:f:ho:O:r", opts, NULL)) != -1) {
    switch(opt) {

    case 'a':
      patch_options_address = strtoull(optarg, NULL, 0);
      break;

    case 'b':
      patch_options_bytes = r_utils_bytes_unhexlify(optarg);
      break;

    case 'f':
      patch_options_filename = optarg;
      break;

    case 'h':
      patch_help();
      exit(EXIT_FAILURE);
      break;

    case 'o':
      patch_options_offset = strtoull(optarg, NULL, 0);
      break;

    case 'O':
      patch_options_output = optarg;
      break;

    case 'r':
      patch_options_arch = R_BINFMT_ARCH_X86;
      break;

    default:
      patch_help();
      exit(EXIT_FAILURE);
    }
  }

  if(optind < argc) {
    patch_options_filename = argv[optind];
  }

  if(patch_options_address == R_BINFMT_BAD_ADDR && patch_options_offset == R_BINFMT_BAD_ADDR)
    R_UTILS_ERR("Where I patch ? Random location ?! Use --offset or --address options !");
  if(patch_options_address != R_BINFMT_BAD_ADDR && patch_options_offset != R_BINFMT_BAD_ADDR)
    R_UTILS_ERR("I need an offset OR an address, not twice !");
  if(patch_options_bytes == NULL)
    R_UTILS_ERR("I patch what ? use --bytes option !");
}
示例#28
0
// Takes the command line options and turns them into something we can understand
static parsed_opts_t* parse_args(int argc, char** argv)
{
    if (argc == 1) { usage(pysam_stdout); return NULL; }

    const char* optstring = "vf:u:";
    char* delim;

    static const struct option lopts[] = {
        SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0),
        { NULL, 0, NULL, 0 }
    };

    parsed_opts_t* retval = calloc(sizeof(parsed_opts_t), 1);
    if (! retval ) { perror("cannot allocate option parsing memory"); return NULL; }

    sam_global_args_init(&retval->ga);

    int opt;
    while ((opt = getopt_long(argc, argv, optstring, lopts, NULL)) != -1) {
        switch (opt) {
        case 'f':
            retval->output_format_string = strdup(optarg);
            if (! retval->output_format_string ) { perror("cannot allocate output format string memory"); return NULL; }
            break;
        case 'v':
            retval->verbose = true;
            break;
        case 'u':
            retval->unaccounted_name = strdup(optarg);
            if (! retval->unaccounted_name ) { perror("cannot allocate string memory"); return NULL; }
            if ((delim = strchr(retval->unaccounted_name, ':')) != NULL) {
                *delim = '\0';
                retval->unaccounted_header_name = strdup(delim+1);
                if (! retval->unaccounted_header_name ) { perror("cannot allocate string memory"); return NULL; }
            }
            break;
        default:
            if (parse_sam_global_opt(opt, optarg, lopts, &retval->ga) == 0) break;
            /* else fall-through */
        case '?':
            usage(pysam_stdout);
            free(retval);
            return NULL;
        }
    }

    if (retval->output_format_string == NULL) retval->output_format_string = strdup("%*_%#.%.");

    argc -= optind;
    argv += optind;

    if (argc != 1) {
        fprintf(pysam_stderr, "Invalid number of arguments: %d\n", argc);
        usage(pysam_stderr);
        free(retval);
        return NULL;
    }

    retval->merged_input_name = strdup(argv[0]);
    if (! retval->merged_input_name ) { perror("cannot allocate string memory"); return NULL; }

    return retval;
}
示例#29
0
static int ParseCommandLine(int argc, char *argv[])
{
    int c;
    int option_index = 0;
    static struct option long_options[] =
    {
        {"name",  1, NULL, 'n'},
        {"path",  1, NULL, 'p'},
        {"help",  0, NULL, 0},
        {NULL,    0, NULL, 0}
    };

    memset(&config, 0, sizeof(config));
    while((c = getopt_long(argc, argv, "n:p:", long_options,
                    &option_index)) != -1)
    {
        switch(c)
        {
            case 0:
                if(strcasecmp("help", long_options[option_index].name) == 0)
                {
                    usage(argv[0]);
                    exit(0);
                }
                else
                {
                    fprintf(stderr, "Unknown command line option: %s",
                            long_options[option_index].name);
                    return SF_EINVAL;
                }
                break;

            case 'n':
                config.name = malloc(strlen(optarg)+2);
                if(!(config.name))
                {
                    fprintf(stderr, "Out of memory processing command line");
                    return SF_ENOMEM;
                }
                strcpy(config.name, optarg);
                strcat(config.name,".");
                break;

            case 'p':
                if(!(config.path = strdup(optarg)))
                {
                    fprintf(stderr, "Out of memory processing command line");
                    return SF_ENOMEM;
                }
                break;

            default:
                return SF_EINVAL;
        }
    }
    if (!config.name || !config.path)
    {
        usage(argv[0]);
        exit(-1);
    }
    config.priority = (LOG_INFO | LOG_INFO);
    return 0;
}
示例#30
0
文件: rpcinfo.c 项目: AubrCool/glibc
int
main (int argc, char **argv)
{
  register int c;
  int errflg;
  int function;
  u_short portnum;
  static const struct option long_options[] = {
    { "help", no_argument, NULL, 'H' },
    { "version", no_argument, NULL, 'V' },
    { NULL, 0, NULL, 0 }
  };

  setlocale (LC_ALL, "");
  textdomain (_libc_intl_domainname);

  function = NONE;
  portnum = 0;
  errflg = 0;
  while ((c = getopt_long (argc, argv, "ptubdn:", long_options, NULL)) != -1)
    {
      switch (c)
	{

	case 'p':
	  if (function != NONE)
	    errflg = 1;
	  else
	    function = PMAPDUMP;
	  break;

	case 't':
	  if (function != NONE)
	    errflg = 1;
	  else
	    function = TCPPING;
	  break;

	case 'u':
	  if (function != NONE)
	    errflg = 1;
	  else
	    function = UDPPING;
	  break;

	case 'b':
	  if (function != NONE)
	    errflg = 1;
	  else
	    function = BRDCST;
	  break;

	case 'n':
	  portnum = (u_short) atoi (optarg);	/* hope we don't get bogus # */
	  break;

	case 'd':
	  if (function != NONE)
	    errflg = 1;
	  else
	    function = DELETES;
	  break;

	case 'H':
	  usage (stdout);
	  return 0;

	case 'V':
	  print_version ();
	  return 0;

	case '?':
	  errflg = 1;
	}
    }

  if (errflg || function == NONE)
    {
      usage (stderr);
      return 1;
    }

  switch (function)
    {

    case PMAPDUMP:
      if (portnum != 0)
	{
	  usage (stderr);
	  return 1;
	}
      pmapdump (argc - optind, argv + optind);
      break;

    case UDPPING:
      udpping (portnum, argc - optind, argv + optind);
      break;

    case TCPPING:
      tcpping (portnum, argc - optind, argv + optind);
      break;

    case BRDCST:
      if (portnum != 0)
	{
	  usage (stderr);
	  return 1;
	}
      brdcst (argc - optind, argv + optind);
      break;

    case DELETES:
      deletereg (argc - optind, argv + optind);
      break;
    }

  return 0;
}