Exemplo n.º 1
0
int main(int argc, char **argv)
{
	int opt;
	poptContext pc;
	char *outputfile = NULL;
	struct registry_context *h1 = NULL, *h2 = NULL;
	int from_null = 0;
	WERROR error;
	struct reg_diff *diff;
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"output", 'o', POPT_ARG_STRING, &outputfile, 'o', "output file to use", NULL },
		{"null", 'n', POPT_ARG_NONE, &from_null, 'n', "Diff from NULL", NULL },
		{"remote", 'R', POPT_ARG_STRING, NULL, 0, "Connect to remote server" , NULL },
		{"local", 'L', POPT_ARG_NONE, NULL, 0, "Open local registry", NULL },
		POPT_COMMON_SAMBA
		POPT_COMMON_CREDENTIALS
		POPT_COMMON_VERSION
		{ NULL }
	};

	registry_init();

	pc = poptGetContext(argv[0], argc, (const char **) argv, long_options,0);

	while((opt = poptGetNextOpt(pc)) != -1) {
		error = WERR_OK;
		switch(opt)	{
		case 'L':
			if (!h1 && !from_null) error = reg_open_local(NULL, &h1, NULL, cmdline_credentials);
			else if (!h2) error = reg_open_local(NULL, &h2, NULL, cmdline_credentials);
			break;
		case 'R':
			if (!h1 && !from_null) 
				error = reg_open_remote(&h1, NULL, cmdline_credentials, 
							poptGetOptArg(pc), NULL);
			else if (!h2) error = reg_open_remote(&h2, NULL, cmdline_credentials, 
							      poptGetOptArg(pc), NULL);
			break;
		}

		if (!W_ERROR_IS_OK(error)) {
			fprintf(stderr, "Error: %s\n", win_errstr(error));
			return 1;
		}
	}

	poptFreeContext(pc);

	diff = reg_generate_diff(NULL, h1, h2);
	if (!diff) {
		fprintf(stderr, "Unable to generate diff between keys\n");
		return -1;
	}

	reg_diff_save(diff, outputfile);

	return 0;
}
Exemplo n.º 2
0
void InitOption(int argc, char* argv[])
{
	static struct poptOption option_table[] =
	{
		{NULL,             's', POPT_ARG_STRING,  NULL,  UI_OPT_SOCKET },
		{"model",           0,  POPT_ARG_STRING,  NULL,  UI_OPT_MODEL  },
		{"cups",            0,  0,                NULL,  UI_OPT_CUPS   },
		{"internalversion", 0,  POPT_ARG_NONE,    NULL,  UI_OPT_INTVER },	/* Ver.2.70 */
		{"bidi",            0,  POPT_ARG_NONE,    NULL,  UI_OPT_BIDI   },	/* Ver.3.20 */
		{NULL,              0,  0,                NULL,  0             }
	};

	poptContext context
		 = poptGetContext("printui", argc, (const char**)argv, option_table, 0);
	int rc;

	g_model_name = NULL;
	g_cups_mode = FALSE;
	g_bidi_mode = FALSE;		/* Ver.3.20 */

	while( (rc = poptGetNextOpt(context)) > 0 )
	{
		switch( rc )
		{
		case UI_OPT_SOCKET:
			g_socketname = g_strdup(poptGetOptArg(context));
			break;

		case UI_OPT_MODEL:
			g_model_name = g_strdup(poptGetOptArg(context));
			break;

		case UI_OPT_CUPS:
			g_cups_mode = TRUE;
			break;

		case UI_OPT_INTVER:
			g_message( "Internal Version : %s\n" ,INTERNAL_VERSION_STR );
			break;

		case UI_OPT_BIDI:		/* Ver.3.20 */
			g_bidi_mode = TRUE;
			break;

		default:
			break;
		}
	}
	
	if( rc < -1 )
		g_warning("Unknown switch, %s\n",
			 poptBadOption(context, POPT_BADOPTION_NOALIAS));
}
Exemplo n.º 3
0
void InitOption(int argc, char* argv[])
{
	static struct poptOption option_table[] =
	{
		{NULL,   's', POPT_ARG_STRING,  NULL, UI_OPT_SOCKET },
		{"model",  0, POPT_ARG_STRING,  NULL, UI_OPT_MODEL  },
		{"cups",   0,               0,  NULL, UI_OPT_CUPS   },
		{NULL,     0,               0,  NULL, 0}
	};

	poptContext context
		 = poptGetContext("printui", argc, (const char**)argv, option_table, 0);
	int rc;

	g_model_name = NULL;
	g_cups_mode = FALSE;

	while( (rc = poptGetNextOpt(context)) > 0 )
	{
		switch( rc )
		{
		case UI_OPT_SOCKET:
			g_socketname = g_strdup(poptGetOptArg(context));
			break;

		case UI_OPT_MODEL:
			g_model_name = g_strdup(poptGetOptArg(context));
			break;

		case UI_OPT_CUPS:
			g_cups_mode = TRUE;
			break;

		default:
			break;
		}
	}
	
	if( rc < -1 )
		g_warning("Unknown switch, %s\n",
			 poptBadOption(context, POPT_BADOPTION_NOALIAS));
}
Exemplo n.º 4
0
static void rdiff_options(poptContext opcon)
{
    int             c;
    char const      *a;
    
    while ((c = poptGetNextOpt(opcon)) != -1) {
        switch (c) {
        case 'h':
            help();
            exit(RS_DONE);
        case 'V':
            rdiff_show_version();
            exit(RS_DONE);
        case 'v':
            if (!rs_supports_trace()) {
                rs_error("library does not support trace");
            }
            rs_trace_set_level(RS_LOG_DEBUG);
            break;
            
        case OPT_GZIP:
        case OPT_BZIP2:
            if ((a = poptGetOptArg(opcon))) {
                int l = atoi(a);
                if (c == OPT_GZIP)
                    gzip_level = l;
                else
                    bzip2_level = l;
            } else {
                if (c == OPT_GZIP)
                    gzip_level = -1;      /* library default */
                else
                    bzip2_level = 9;      /* demand the best */
            }
            rs_error("sorry, compression is not really implemented yet");
            exit(RS_UNIMPLEMENTED);
            
        default:
            bad_option(opcon, c);
        }
    }
}
Exemplo n.º 5
0
static int get_fields_args(poptContext *pc)
{
	char *str, *strlist, *strctx;
	int ret = 0;

	strlist = (char *) poptGetOptArg(*pc);
	if (!strlist) {
		return -EINVAL;
	}
	str = strtok_r(strlist, ",", &strctx);
	do {
		opt_trace_default_fields = 0;
		if (!strcmp(str, "all"))
			opt_all_fields = 1;
		else if (!strcmp(str, "trace"))
			opt_trace_field = 1;
		else if (!strcmp(str, "trace:hostname"))
			opt_trace_hostname_field = 1;
		else if (!strcmp(str, "trace:domain"))
			opt_trace_domain_field = 1;
		else if (!strcmp(str, "trace:procname"))
			opt_trace_procname_field = 1;
		else if (!strcmp(str, "trace:vpid"))
			opt_trace_vpid_field = 1;
		else if (!strcmp(str, "loglevel"))
			opt_loglevel_field = 1;
		else if (!strcmp(str, "emf"))
			opt_emf_field = 1;
		else if (!strcmp(str, "callsite"))
			opt_callsite_field = 1;
		else {
			fprintf(stderr, "[error] unknown field type %s\n", str);
			ret = -EINVAL;
			goto end;
		}
	} while ((str = strtok_r(NULL, ",", &strctx)));
end:
	free(strlist);
	return ret;
}
Exemplo n.º 6
0
static int get_names_args(poptContext *pc)
{
	char *str, *strlist, *strctx;
	int ret = 0;

	opt_payload_field_names = 0;
	opt_context_field_names = 0;
	strlist = (char *) poptGetOptArg(*pc);
	if (!strlist) {
		return -EINVAL;
	}
	str = strtok_r(strlist, ",", &strctx);
	do {
		if (!strcmp(str, "all"))
			opt_all_field_names = 1;
		else if (!strcmp(str, "scope"))
			opt_scope_field_names = 1;
		else if (!strcmp(str, "context") || !strcmp(str, "ctx"))
			opt_context_field_names = 1;
		else if (!strcmp(str, "header"))
			opt_header_field_names = 1;
		else if (!strcmp(str, "payload") || !strcmp(str, "args") || !strcmp(str, "arg"))
			opt_payload_field_names = 1;
		else if (!strcmp(str, "none")) {
			opt_all_field_names = 0;
			opt_scope_field_names = 0;
			opt_context_field_names = 0;
			opt_header_field_names = 0;
			opt_payload_field_names = 0;
		} else {
			fprintf(stderr, "[error] unknown field name type %s\n", str);
			ret = -EINVAL;
			goto end;
		}
	} while ((str = strtok_r(NULL, ",", &strctx)));
end:
	free(strlist);
	return ret;
}
Exemplo n.º 7
0
int main(int argc, const char **argv)
{
    uid_t pc_uid = 0;
    const char *pc_gecos = NULL;
    const char *pc_home = NULL;
    char *pc_shell = NULL;
    int pc_debug = SSSDBG_DEFAULT;
    int pc_create_home = 0;
    const char *pc_username = NULL;
    const char *pc_skeldir = NULL;
    const char *pc_selinux_user = NULL;
    struct poptOption long_options[] = {
        POPT_AUTOHELP
        { "debug", '\0', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_debug, 0, _("The debug level to run with"), NULL },
        { "uid",   'u', POPT_ARG_INT, &pc_uid, 0, _("The UID of the user"), NULL },
        { "gecos", 'c', POPT_ARG_STRING, &pc_gecos, 0, _("The comment string"), NULL },
        { "home",  'h', POPT_ARG_STRING, &pc_home, 0, _("Home directory"), NULL },
        { "shell", 's', POPT_ARG_STRING, &pc_shell, 0, _("Login shell"), NULL },
        { "groups", 'G', POPT_ARG_STRING, NULL, 'G', _("Groups"), NULL },
        { "create-home", 'm', POPT_ARG_NONE, NULL, 'm', _("Create user's directory if it does not exist"), NULL },
        { "no-create-home", 'M', POPT_ARG_NONE, NULL, 'M', _("Never create user's directory, overrides config"), NULL },
        { "skel", 'k', POPT_ARG_STRING, &pc_skeldir, 0, _("Specify an alternative skeleton directory"), NULL },
        { "selinux-user", 'Z', POPT_ARG_STRING, &pc_selinux_user, 0, _("The SELinux user for user's login"), NULL },
        POPT_TABLEEND
    };
    poptContext pc = NULL;
    struct tools_ctx *tctx = NULL;
    char *groups = NULL;
    char *badgroup = NULL;
    int ret;
    errno_t sret;
    bool in_transaction = false;

    debug_prg_name = argv[0];

    ret = set_locale();
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE,
              "set_locale failed (%d): %s\n", ret, strerror(ret));
        ERROR("Error setting the locale\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* parse parameters */
    pc = poptGetContext(NULL, argc, argv, long_options, 0);
    poptSetOtherOptionHelp(pc, "USERNAME");
    while ((ret = poptGetNextOpt(pc)) > 0) {
        switch (ret) {
            case 'G':
                groups = poptGetOptArg(pc);
                if (!groups) {
                    BAD_POPT_PARAMS(pc, _("Specify group to add to\n"),
                                    ret, fini);
                }
                break;

            case 'm':
                pc_create_home = DO_CREATE_HOME;
                break;

            case 'M':
                pc_create_home = DO_NOT_CREATE_HOME;
                break;
        }
    }

    DEBUG_CLI_INIT(pc_debug);

    if (ret != -1) {
        BAD_POPT_PARAMS(pc, poptStrerror(ret), ret, fini);
    }

    /* username is an argument without --option */
    pc_username = poptGetArg(pc);
    if (pc_username == NULL) {
        BAD_POPT_PARAMS(pc, _("Specify user to add\n"), ret, fini);
    }

    CHECK_ROOT(ret, debug_prg_name);

    ret = init_sss_tools(&tctx);
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE,
              "init_sss_tools failed (%d): %s\n", ret, strerror(ret));
        if (ret == ENOENT) {
            ERROR("Error initializing the tools - no local domain\n");
        } else {
            ERROR("Error initializing the tools\n");
        }
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* if the domain was not given as part of FQDN, default to local domain */
    ret = parse_name_domain(tctx, pc_username);
    if (ret != EOK) {
        ERROR("Invalid domain specified in FQDN\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    if (groups) {
        ret = parse_groups(tctx, groups, &tctx->octx->addgroups);
        if (ret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE,
                  "Cannot parse groups to add the user to\n");
            ERROR("Internal error while parsing parameters\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        ret = parse_group_name_domain(tctx, tctx->octx->addgroups);
        if (ret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE,
                  "Cannot parse FQDN groups to add the user to\n");
            ERROR("Groups must be in the same domain as user\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        /* Check group names in the LOCAL domain */
        ret = check_group_names(tctx, tctx->octx->addgroups, &badgroup);
        if (ret != EOK) {
            ERROR("Cannot find group %1$s in local domain\n", badgroup);
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

    tctx->octx->uid = pc_uid;

    /*
     * Fills in defaults for ops_ctx user did not specify.
     */
    ret = useradd_defaults(tctx, tctx->confdb, tctx->octx,
                           pc_gecos, pc_home, pc_shell,
                           pc_create_home, pc_skeldir);
    if (ret != EOK) {
        ERROR("Cannot set default values\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* arguments processed, go on to actual work */
    if (id_in_range(tctx->octx->uid, tctx->octx->domain) != EOK) {
        ERROR("The selected UID is outside the allowed range\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    tctx->error = sysdb_transaction_start(tctx->sysdb);
    if (tctx->error != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Failed to start transaction\n");
        goto done;
    }
    in_transaction = true;

    /* useradd */
    tctx->error = useradd(tctx, tctx->octx);
    if (tctx->error) {
        goto done;
    }

    tctx->error = sysdb_transaction_commit(tctx->sysdb);
    if (tctx->error) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Failed to commit transaction\n");
        goto done;
    }
    in_transaction = false;

    /* Set SELinux login context - must be done after transaction is done
     * b/c libselinux calls getpwnam */
    ret = set_seuser(tctx->octx->name, pc_selinux_user, NULL);
    if (ret != EOK) {
        ERROR("Cannot set SELinux login context\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* Create user's home directory and/or mail spool */
    if (tctx->octx->create_homedir) {
        /* We need to know the UID of the user, if
         * sysdb did assign it automatically, do a lookup */
        if (tctx->octx->uid == 0) {
            ret = sysdb_getpwnam_sync(tctx,
                                      tctx->octx->name,
                                      tctx->octx);
            if (ret != EOK) {
                ERROR("Cannot get info about the user\n");
                ret = EXIT_FAILURE;
                goto fini;
            }
        }

        ret = create_homedir(tctx->octx->skeldir,
                             tctx->octx->home,
                             tctx->octx->uid,
                             tctx->octx->gid,
                             tctx->octx->umask);
        if (ret == EEXIST) {
            ERROR("User's home directory already exists, not copying "
                  "data from skeldir\n");
        } else if (ret != EOK) {
            ERROR("Cannot create user's home directory: %1$s\n", strerror(ret));
            ret = EXIT_FAILURE;
            goto fini;
        }

        ret = create_mail_spool(tctx,
                                tctx->octx->name,
                                tctx->octx->maildir,
                                tctx->octx->uid,
                                tctx->octx->gid);
        if (ret != EOK) {
            ERROR("Cannot create user's mail spool: %1$s\n", strerror(ret));
            DEBUG(SSSDBG_CRIT_FAILURE,
                  "Cannot create user's mail spool: [%d][%s].\n",
                        ret, strerror(ret));
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

done:
    if (in_transaction) {
        sret = sysdb_transaction_cancel(tctx->sysdb);
        if (sret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE, "Failed to cancel transaction\n");
        }
    }

    if (tctx->error) {
        switch (tctx->error) {
            case ERANGE:
                ERROR("Could not allocate ID for the user - domain full?\n");
                break;

            case EEXIST:
                ERROR("A user or group with the same name or ID already exists\n");
                break;

            default:
                DEBUG(SSSDBG_CRIT_FAILURE, "sysdb operation failed (%d)[%s]\n",
                          tctx->error, strerror(tctx->error));
                ERROR("Transaction error. Could not add user.\n");
                break;
        }
        ret = EXIT_FAILURE;
        goto fini;
    }

    ret = EXIT_SUCCESS;

fini:
    poptFreeContext(pc);
    talloc_free(tctx);
    free(groups);
    exit(ret);
}
Exemplo n.º 8
0
/****************************************************************************
  main program
****************************************************************************/
int main(int argc, const char *argv[])
{
	int opt;
	unsigned int lookup_type = 0x0;
	fstring lookup;
	static bool find_master=False;
	static bool lookup_by_ip = False;
	poptContext pc = NULL;
	TALLOC_CTX *frame = talloc_stackframe();
	int rc = 0;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{ "broadcast", 'B', POPT_ARG_STRING, NULL, 'B', "Specify address to use for broadcasts", "BROADCAST-ADDRESS" },
		{ "flags", 'f', POPT_ARG_NONE, NULL, 'f', "List the NMB flags returned" },
		{ "unicast", 'U', POPT_ARG_STRING, NULL, 'U', "Specify address to use for unicast" },
		{ "master-browser", 'M', POPT_ARG_NONE, NULL, 'M', "Search for a master browser" },
		{ "recursion", 'R', POPT_ARG_NONE, NULL, 'R', "Set recursion desired in package" },
		{ "status", 'S', POPT_ARG_NONE, NULL, 'S', "Lookup node status as well" },
		{ "translate", 'T', POPT_ARG_NONE, NULL, 'T', "Translate IP addresses into names" },
		{ "root-port", 'r', POPT_ARG_NONE, NULL, 'r', "Use root port 137 (Win95 only replies to this)" },
		{ "lookup-by-ip", 'A', POPT_ARG_NONE, NULL, 'A', "Do a node status on <name> as an IP Address" },
		POPT_COMMON_SAMBA
		POPT_COMMON_CONNECTION
		{ 0, 0, 0, 0 }
	};

	*lookup = 0;

	load_case_tables();

	setup_logging(argv[0], DEBUG_STDOUT);

	pc = poptGetContext("nmblookup", argc, argv,
			long_options, POPT_CONTEXT_KEEP_FIRST);

	poptSetOtherOptionHelp(pc, "<NODE> ...");

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case 'f':
			give_flags = true;
			break;
		case 'M':
			find_master = true;
			break;
		case 'R':
			recursion_desired = true;
			break;
		case 'S':
			find_status = true;
			break;
		case 'r':
			RootPort = true;
			break;
		case 'A':
			lookup_by_ip = true;
			break;
		case 'B':
			if (interpret_string_addr(&bcast_addr,
					poptGetOptArg(pc),
					NI_NUMERICHOST)) {
				got_bcast = True;
				use_bcast = True;
			}
			break;
		case 'U':
			if (interpret_string_addr(&bcast_addr,
					poptGetOptArg(pc),
					0)) {
				got_bcast = True;
				use_bcast = False;
			}
			break;
		case 'T':
			translate_addresses = !translate_addresses;
			break;
		}
	}

	poptGetArg(pc); /* Remove argv[0] */

	if(!poptPeekArg(pc)) {
		poptPrintUsage(pc, stderr, 0);
		rc = 1;
		goto out;
	}

	if (!lp_load_global(get_dyn_CONFIGFILE())) {
		fprintf(stderr, "Can't load %s - run testparm to debug it\n",
				get_dyn_CONFIGFILE());
	}

	load_interfaces();
	if (!open_sockets()) {
		rc = 1;
		goto out;
	}

	while(poptPeekArg(pc)) {
		char *p;
		struct in_addr ip;

		fstrcpy(lookup,poptGetArg(pc));

		if(lookup_by_ip) {
			struct sockaddr_storage ss;
			ip = interpret_addr2(lookup);
			in_addr_to_sockaddr_storage(&ss, ip);
			fstrcpy(lookup,"*");
			if (!do_node_status(lookup, lookup_type, &ss)) {
				rc = 1;
			}
			continue;
		}

		if (find_master) {
			if (*lookup == '-') {
				fstrcpy(lookup,"\01\02__MSBROWSE__\02");
				lookup_type = 1;
			} else {
				lookup_type = 0x1d;
			}
		}

		p = strchr_m(lookup,'#');
		if (p) {
			*p = '\0';
			sscanf(++p,"%x",&lookup_type);
		}

		if (!query_one(lookup, lookup_type)) {
			rc = 1;
			d_printf( "name_query failed to find name %s", lookup );
			if( 0 != lookup_type ) {
				d_printf( "#%02x", lookup_type );
			}
			d_printf( "\n" );
		}
	}

out:
	poptFreeContext(pc);
	TALLOC_FREE(frame);
	return rc;
}
Exemplo n.º 9
0
int main(int argc, const char **argv)
{
	int c = 0;
	const char *file = NULL;
	char *rcfile = NULL;
	bool smb_encrypt = false;
	int resume = 0, recursive = 0;
	TALLOC_CTX *frame = talloc_stackframe();
	struct poptOption long_options[] = {
		{"guest", 'a', POPT_ARG_NONE, NULL, 'a', "Work as user guest" },	
		{"encrypt", 'e', POPT_ARG_NONE, NULL, 'e', "Encrypt SMB transport (UNIX extended servers only)" },	
		{"resume", 'r', POPT_ARG_NONE, &resume, 0, "Automatically resume aborted files" },
		{"update", 'U',  POPT_ARG_NONE, &update, 0, "Download only when remote file is newer than local file or local file is missing"},
		{"recursive", 'R',  POPT_ARG_NONE, &recursive, 0, "Recursively download files" },
		{"username", 'u', POPT_ARG_STRING, &username, 'u', "Username to use" },
		{"password", 'p', POPT_ARG_STRING, &password, 'p', "Password to use" },
		{"workgroup", 'w', POPT_ARG_STRING, &workgroup, 'w', "Workgroup to use (optional)" },
		{"nonprompt", 'n', POPT_ARG_NONE, &nonprompt, 'n', "Don't ask anything (non-interactive)" },
		{"debuglevel", 'd', POPT_ARG_INT, &debuglevel, 'd', "Debuglevel to use" },
		{"outputfile", 'o', POPT_ARG_STRING, &outputfile, 'o', "Write downloaded data to specified file" },
		{"stdout", 'O', POPT_ARG_NONE, &send_stdout, 'O', "Write data to stdout" },
		{"dots", 'D', POPT_ARG_NONE, &dots, 'D', "Show dots as progress indication" },
		{"quiet", 'q', POPT_ARG_NONE, &quiet, 'q', "Be quiet" },
		{"verbose", 'v', POPT_ARG_NONE, &verbose, 'v', "Be verbose" },
		{"keep-permissions", 'P', POPT_ARG_NONE, &keep_permissions, 'P', "Keep permissions" },
		{"blocksize", 'b', POPT_ARG_INT, &blocksize, 'b', "Change number of bytes in a block"},
		{"rcfile", 'f', POPT_ARG_STRING, NULL, 'f', "Use specified rc file"},
		POPT_AUTOHELP
		POPT_TABLEEND
	};
	poptContext pc;

	load_case_tables();

	/* only read rcfile if it exists */
	if (asprintf(&rcfile, "%s/.smbgetrc", getenv("HOME")) == -1) {
		return 1;
	}
	if(access(rcfile, F_OK) == 0) 
		readrcfile(rcfile, long_options);
	free(rcfile);

#ifdef SIGWINCH
	signal(SIGWINCH, change_columns);
#endif
	signal(SIGINT, signal_quit);
	signal(SIGTERM, signal_quit);

	pc = poptGetContext(argv[0], argc, argv, long_options, 0);

	while((c = poptGetNextOpt(pc)) >= 0) {
		switch(c) {
		case 'f':
			readrcfile(poptGetOptArg(pc), long_options);
			break;
		case 'a':
			username = ""; password = "";
			break;
		case 'e':
			smb_encrypt = true;
			break;
		}
	}

	if((send_stdout || resume || outputfile) && update) {
		fprintf(stderr, "The -o, -R or -O and -U options can not be used together.\n");
		return 1;
	}
	if((send_stdout || outputfile) && recursive) {
		fprintf(stderr, "The -o or -O and -R options can not be used together.\n");
		return 1;
	}

	if(outputfile && send_stdout) {
		fprintf(stderr, "The -o and -O options cannot be used together.\n");
		return 1;
	}

	if(smbc_init(get_auth_data, debuglevel) < 0) {
		fprintf(stderr, "Unable to initialize libsmbclient\n");
		return 1;
	}

	if (smb_encrypt) {
		SMBCCTX *smb_ctx = smbc_set_context(NULL);
		smbc_option_set(smb_ctx,
			CONST_DISCARD(char *, "smb_encrypt_level"),
			"require");
	}
	
	columns = get_num_cols();

	total_start_time = time(NULL);

	while ( (file = poptGetArg(pc)) ) {
		if (!recursive) 
			return smb_download_file(file, "", recursive, resume, outputfile);
		else 
			return smb_download_dir(file, "", resume);
	}

	clean_exit();
	TALLOC_FREE(frame);
	return 0;
}
Exemplo n.º 10
0
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc, const char **argv)
{
	int opt,i;
	char *p;
	int rc = 0;
	int argc_new = 0;
	const char ** argv_new;
	poptContext pc;
	TALLOC_CTX *frame = talloc_stackframe();
	struct net_context *c = talloc_zero(frame, struct net_context);

	struct poptOption long_options[] = {
		{"help",	'h', POPT_ARG_NONE,   0, 'h'},
		{"workgroup",	'w', POPT_ARG_STRING, &c->opt_target_workgroup},
		{"user",	'U', POPT_ARG_STRING, &c->opt_user_name, 'U'},
		{"ipaddress",	'I', POPT_ARG_STRING, 0,'I'},
		{"port",	'p', POPT_ARG_INT,    &c->opt_port},
		{"myname",	'n', POPT_ARG_STRING, &c->opt_requester_name},
		{"server",	'S', POPT_ARG_STRING, &c->opt_host},
		{"encrypt",	'e', POPT_ARG_NONE,   NULL, 'e', N_("Encrypt SMB transport (UNIX extended servers only)") },
		{"container",	'c', POPT_ARG_STRING, &c->opt_container},
		{"comment",	'C', POPT_ARG_STRING, &c->opt_comment},
		{"maxusers",	'M', POPT_ARG_INT,    &c->opt_maxusers},
		{"flags",	'F', POPT_ARG_INT,    &c->opt_flags},
		{"long",	'l', POPT_ARG_NONE,   &c->opt_long_list_entries},
		{"reboot",	'r', POPT_ARG_NONE,   &c->opt_reboot},
		{"force",	'f', POPT_ARG_NONE,   &c->opt_force},
		{"stdin",	'i', POPT_ARG_NONE,   &c->opt_stdin},
		{"timeout",	't', POPT_ARG_INT,    &c->opt_timeout},
		{"request-timeout",0,POPT_ARG_INT,    &c->opt_request_timeout},
		{"machine-pass",'P', POPT_ARG_NONE,   &c->opt_machine_pass},
		{"kerberos",    'k', POPT_ARG_NONE,   &c->opt_kerberos},
		{"myworkgroup", 'W', POPT_ARG_STRING, &c->opt_workgroup},
		{"use-ccache",    0, POPT_ARG_NONE,   &c->opt_ccache},
		{"verbose",	'v', POPT_ARG_NONE,   &c->opt_verbose},
		{"test",	'T', POPT_ARG_NONE,   &c->opt_testmode},
		/* Options for 'net groupmap set' */
		{"local",       'L', POPT_ARG_NONE,   &c->opt_localgroup},
		{"domain",      'D', POPT_ARG_NONE,   &c->opt_domaingroup},
		{"ntname",      'N', POPT_ARG_STRING, &c->opt_newntname},
		{"rid",         'R', POPT_ARG_INT,    &c->opt_rid},
		/* Options for 'net rpc share migrate' */
		{"acls",	0, POPT_ARG_NONE,     &c->opt_acls},
		{"attrs",	0, POPT_ARG_NONE,     &c->opt_attrs},
		{"timestamps",	0, POPT_ARG_NONE,     &c->opt_timestamps},
		{"exclude",	'X', POPT_ARG_STRING, &c->opt_exclude},
		{"destination",	0, POPT_ARG_STRING,   &c->opt_destination},
		{"tallocreport", 0, POPT_ARG_NONE,    &c->do_talloc_report},
		/* Options for 'net rpc vampire (keytab)' */
		{"force-full-repl", 0, POPT_ARG_NONE, &c->opt_force_full_repl},
		{"single-obj-repl", 0, POPT_ARG_NONE, &c->opt_single_obj_repl},
		{"clean-old-entries", 0, POPT_ARG_NONE, &c->opt_clean_old_entries},
		/* Options for 'net idmap'*/
		{"db", 0, POPT_ARG_STRING, &c->opt_db},
		{"lock", 0, POPT_ARG_NONE,   &c->opt_lock},
		{"auto", 'a', POPT_ARG_NONE,   &c->opt_auto},
		{"repair", 0, POPT_ARG_NONE,   &c->opt_repair},
		/* Options for 'net registry check'*/
		{"reg-version", 0, POPT_ARG_INT, &c->opt_reg_version},
		{"output", 'o', POPT_ARG_STRING, &c->opt_output},
		{"wipe", 0, POPT_ARG_NONE, &c->opt_wipe},
		POPT_COMMON_SAMBA
		{ 0, 0, 0, 0}
	};

	zero_sockaddr(&c->opt_dest_ip);

	setup_logging(argv[0], DEBUG_STDERR);

	load_case_tables();

	setlocale(LC_ALL, "");
#if defined(HAVE_BINDTEXTDOMAIN)
	bindtextdomain(MODULE_NAME, get_dyn_LOCALEDIR());
#endif
#if defined(HAVE_TEXTDOMAIN)
	textdomain(MODULE_NAME);
#endif

	/* set default debug level to 0 regardless of what smb.conf sets */
	lp_set_cmdline("log level", "0");
	c->private_data = net_func;

	pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
			    POPT_CONTEXT_KEEP_FIRST);

	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case 'h':
			c->display_usage = true;
			break;
		case 'e':
			c->smb_encrypt = true;
			break;
		case 'I':
			if (!interpret_string_addr(&c->opt_dest_ip,
						poptGetOptArg(pc), 0)) {
				d_fprintf(stderr, _("\nInvalid ip address specified\n"));
			} else {
				c->opt_have_ip = true;
			}
			break;
		case 'U':
			c->opt_user_specified = true;
			c->opt_user_name = SMB_STRDUP(c->opt_user_name);
			p = strchr(c->opt_user_name,'%');
			if (p) {
				*p = 0;
				c->opt_password = p+1;
			}
			break;
		default:
			d_fprintf(stderr, _("\nInvalid option %s: %s\n"),
				 poptBadOption(pc, 0), poptStrerror(opt));
			net_help(c, argc, argv);
			exit(1);
		}
	}

	lp_load_global(get_dyn_CONFIGFILE());

#if defined(HAVE_BIND_TEXTDOMAIN_CODESET)
	/* Bind our gettext results to 'unix charset'
	   
	   This ensures that the translations and any embedded strings are in the
	   same charset.  It won't be the one from the user's locale (we no
	   longer auto-detect that), but it will be self-consistent.
	*/
	bind_textdomain_codeset(MODULE_NAME, lp_unix_charset());
#endif

 	argv_new = (const char **)poptGetArgs(pc);

	argc_new = argc;
	for (i=0; i<argc; i++) {
		if (argv_new[i] == NULL) {
			argc_new = i;
			break;
		}
	}

	if (c->do_talloc_report) {
		talloc_enable_leak_report();
	}

	if (c->opt_requester_name) {
		lp_set_cmdline("netbios name", c->opt_requester_name);
	}

	if (!c->opt_user_name && getenv("LOGNAME")) {
		c->opt_user_name = getenv("LOGNAME");
	}

	if (!c->opt_workgroup) {
		c->opt_workgroup = smb_xstrdup(lp_workgroup());
	}

	if (!c->opt_target_workgroup) {
		c->opt_target_workgroup = smb_xstrdup(lp_workgroup());
	}

	if (!init_names())
		exit(1);

	load_interfaces();

	/* this makes sure that when we do things like call scripts,
	   that it won't assert because we are not root */
	sec_init();

	if (c->opt_machine_pass) {
		/* it is very useful to be able to make ads queries as the
		   machine account for testing purposes and for domain leave */

		net_use_krb_machine_account(c);
	}

	if (!c->opt_password) {
		c->opt_password = getenv("PASSWD");
	}

	/* Failing to init the msg_ctx isn't a fatal error. Only
	   root-level things (joining/leaving domains etc.) will be denied. */

	c->msg_ctx = messaging_init(c, procid_self(),
				    event_context_init(c));

	rc = net_run_function(c, argc_new-1, argv_new+1, "net", net_func);

	DEBUG(2,("return code = %d\n", rc));

	gencache_stabilize();

	libnetapi_free(c->netapi_ctx);

	poptFreeContext(pc);

	TALLOC_FREE(frame);
	return rc;
}
Exemplo n.º 11
0
 int main(int argc, char *argv[])
{
	int c;
	int profile_only = 0;
	bool show_processes, show_locks, show_shares;
	poptContext pc;
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"processes",	'p', POPT_ARG_NONE,	NULL, 'p', "Show processes only" },
		{"verbose",	'v', POPT_ARG_NONE, 	NULL, 'v', "Be verbose" },
		{"locks",	'L', POPT_ARG_NONE,	NULL, 'L', "Show locks only" },
		{"shares",	'S', POPT_ARG_NONE,	NULL, 'S', "Show shares only" },
		{"user", 	'u', POPT_ARG_STRING,	&username, 'u', "Switch to user" },
		{"brief",	'b', POPT_ARG_NONE, 	NULL, 'b', "Be brief" },
		{"profile",     'P', POPT_ARG_NONE, NULL, 'P', "Do profiling" },
		{"profile-rates", 'R', POPT_ARG_NONE, NULL, 'R', "Show call rates" },
		{"byterange",	'B', POPT_ARG_NONE,	NULL, 'B', "Include byte range locks"},
		{"numeric",	'n', POPT_ARG_NONE,	NULL, 'n', "Numeric uid/gid"},
		POPT_COMMON_SAMBA
		POPT_TABLEEND
	};
	TALLOC_CTX *frame = talloc_stackframe();
	int ret = 0;
	struct messaging_context *msg_ctx;

	sec_init();
	load_case_tables();

	setup_logging(argv[0], DEBUG_STDERR);

	if (getuid() != geteuid()) {
		d_printf("smbstatus should not be run setuid\n");
		ret = 1;
		goto done;
	}

	pc = poptGetContext(NULL, argc, (const char **) argv, long_options, 
			    POPT_CONTEXT_KEEP_FIRST);

	while ((c = poptGetNextOpt(pc)) != -1) {
		switch (c) {
		case 'p':
			processes_only = true;
			break;
		case 'v':
			verbose = true;
			break;
		case 'L':
			locks_only = true;
			break;
		case 'S':
			shares_only = true;
			break;
		case 'b':
			brief = true;
			break;
		case 'u':
			Ucrit_addUid(nametouid(poptGetOptArg(pc)));
			break;
		case 'P':
		case 'R':
			profile_only = c;
			break;
		case 'B':
			show_brl = true;
			break;
		case 'n':
			numeric_only = true;
			break;
		}
	}

	/* setup the flags based on the possible combincations */

	show_processes = !(shares_only || locks_only || profile_only) || processes_only;
	show_locks     = !(shares_only || processes_only || profile_only) || locks_only;
	show_shares    = !(processes_only || locks_only || profile_only) || shares_only;

	if ( username )
		Ucrit_addUid( nametouid(username) );

	if (verbose) {
		d_printf("using configfile = %s\n", get_dyn_CONFIGFILE());
	}

	if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
		fprintf(stderr, "Can't load %s - run testparm to debug it\n",
			get_dyn_CONFIGFILE());
		ret = -1;
		goto done;
	}


	if (lp_clustering()) {
		/*
		 * This implicitly initializes the global ctdbd
		 * connection, usable by the db_open() calls further
		 * down.
		 */
		msg_ctx = messaging_init(NULL, event_context_init(NULL));
		if (msg_ctx == NULL) {
			fprintf(stderr, "messaging_init failed\n");
			ret = -1;
			goto done;
		}
	}

	if (!lp_load_global(get_dyn_CONFIGFILE())) {
		fprintf(stderr, "Can't load %s - run testparm to debug it\n",
			get_dyn_CONFIGFILE());
		ret = -1;
		goto done;
	}

	switch (profile_only) {
		case 'P':
			/* Dump profile data */
			return status_profile_dump(verbose);
		case 'R':
			/* Continuously display rate-converted data */
			return status_profile_rates(verbose);
		default:
			break;
	}

	if ( show_processes ) {
		d_printf("\nSamba version %s\n",samba_version_string());
		d_printf("PID     Username      Group         Machine                        \n");
		d_printf("-------------------------------------------------------------------\n");
		if (lp_security() == SEC_SHARE) {
			d_printf(" <processes do not show up in "
				 "anonymous mode>\n");
		}

		sessionid_traverse_read(traverse_sessionid, NULL);

		if (processes_only) {
			goto done;
		}
	}

	if ( show_shares ) {
		if (verbose) {
			d_printf("Opened %s\n", lock_path("connections.tdb"));
		}

		if (brief) {
			goto done;
		}

		d_printf("\nService      pid     machine       Connected at\n");
		d_printf("-------------------------------------------------------\n");

		connections_forall_read(traverse_fn1, NULL);

		d_printf("\n");

		if ( shares_only ) {
			goto done;
		}
	}

	if ( show_locks ) {
		int result;
		struct db_context *db;
		db = db_open(NULL, lock_path("locking.tdb"), 0,
			     TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, O_RDONLY, 0,
			     DBWRAP_LOCK_ORDER_1);

		if (!db) {
			d_printf("%s not initialised\n",
				 lock_path("locking.tdb"));
			d_printf("This is normal if an SMB client has never "
				 "connected to your server.\n");
			exit(0);
		} else {
			TALLOC_FREE(db);
		}

		if (!locking_init_readonly()) {
			d_printf("Can't initialise locking module - exiting\n");
			ret = 1;
			goto done;
		}

		result = share_mode_forall(print_share_mode, NULL);

		if (result == 0) {
			d_printf("No locked files\n");
		} else if (result < 0) {
			d_printf("locked file list truncated\n");
		}

		d_printf("\n");

		if (show_brl) {
			brl_forall(print_brl, NULL);
		}

		locking_end();
	}

done:
	TALLOC_FREE(frame);
	return ret;
}
Exemplo n.º 12
0
/**
 * Second half of command line parsing. See ParseCommandLineEarly() for
 * the first half. Note that render mode must come before resolution flag.
 * \param argc number of arguments given
 * \param argv string array of the arguments
 * \return Returns true on success, false on error */
bool ParseCommandLine(int argc, const char **argv)
{
	poptContext poptCon = poptGetContext(NULL, argc, argv, getOptionsTable(), 0);
	int iOption;

	/* loop through command line */
	while ((iOption = poptGetNextOpt(poptCon)) > 0)
	{
		const char *token;
		CLI_OPTIONS option = (CLI_OPTIONS)iOption;

		switch (option)
		{
		case CLI_DEBUG:
		case CLI_DEBUGFILE:
		case CLI_FLUSHDEBUGSTDERR:
		case CLI_CONFIGDIR:
		case CLI_HELP:
		case CLI_VERSION:
			// These options are parsed in ParseCommandLineEarly() already, so ignore them
			break;

		case CLI_NOASSERT:
			kf_NoAssert();
			break;

		// NOTE: The sole purpose of this is to test the crash handler.
		case CLI_CRASH:
			CauseCrash = true;
			NetPlay.bComms = false;
			sstrcpy(aLevelName, "CAM_3A");
			SetGameMode(GS_NORMAL);
			break;

		case CLI_DATADIR:
			// retrieve the quoted path name
			token = poptGetOptArg(poptCon);
			if (token == NULL)
			{
				qFatal("Unrecognised datadir");
			}
			sstrcpy(datadir, token);
			break;

		case CLI_FULLSCREEN:
			war_setFullscreen(true);
			break;
		case CLI_CONNECTTOIP:
			//get the ip we want to connect with, and go directly to join screen.
			token = poptGetOptArg(poptCon);
			if (token == NULL)
			{
				qFatal("No IP/hostname given");
			}
			sstrcpy(iptoconnect, token);
			break;
		case CLI_HOSTLAUNCH:
			// go directly to host screen, bypass all others.
			hostlaunch = true;
			break;
		case CLI_GAME:
			// retrieve the game name
			token = poptGetOptArg(poptCon);
			if (token == NULL
			    || (strcmp(token, "CAM_1A") && strcmp(token, "CAM_2A") && strcmp(token, "CAM_3A")
			        && strcmp(token, "TUTORIAL3") && strcmp(token, "FASTPLAY")))
			{
				qFatal("The game parameter requires one of the following keywords:"
				       "CAM_1A, CAM_2A, CAM_3A, TUTORIAL3, or FASTPLAY.");
			}
			NetPlay.bComms = false;
			bMultiPlayer = false;
			bMultiMessages = false;
			NetPlay.players[0].allocated = true;
			if (!strcmp(token, "CAM_1A") || !strcmp(token, "CAM_2A") || !strcmp(token, "CAM_3A"))
			{
				game.type = CAMPAIGN;
			}
			else
			{
				game.type = SKIRMISH; // tutorial is skirmish for some reason
			}
			sstrcpy(aLevelName, token);
			SetGameMode(GS_NORMAL);
			break;
		case CLI_MOD_GLOB:
			{
				unsigned int i;

				// retrieve the file name
				token = poptGetOptArg(poptCon);
				if (token == NULL)
				{
					qFatal("Missing mod name?");
				}

				// Find an empty place in the global_mods list
				for (i = 0; i < 100 && global_mods[i] != NULL; ++i) {}
				if (i >= 100 || global_mods[i] != NULL)
				{
					qFatal("Too many mods registered! Aborting!");
				}
				global_mods[i] = strdup(token);
				break;
			}
		case CLI_MOD_CA:
			{
				unsigned int i;

				// retrieve the file name
				token = poptGetOptArg(poptCon);
				if (token == NULL)
				{
					qFatal("Missing mod name?");
				}

				// Find an empty place in the campaign_mods list
				for (i = 0; i < 100 && campaign_mods[i] != NULL; ++i) {}
				if (i >= 100 || campaign_mods[i] != NULL)
				{
					qFatal("Too many mods registered! Aborting!");
				}
				campaign_mods[i] = strdup(token);
				break;
			}
		case CLI_MOD_MP:
			{
				unsigned int i;

				// retrieve the file name
				token = poptGetOptArg(poptCon);
				if (token == NULL)
				{
					qFatal("Missing mod name?");
				}

				for (i = 0; i < 100 && multiplay_mods[i] != NULL; ++i) {}
				if (i >= 100 || multiplay_mods[i] != NULL)
				{
					qFatal("Too many mods registered! Aborting!");
				}
				multiplay_mods[i] = strdup(token);
				break;
			}
		case CLI_RESOLUTION:
			{
				unsigned int width, height;

				token = poptGetOptArg(poptCon);
				if (sscanf(token, "%ix%i", &width, &height) != 2)
				{
					qFatal("Invalid parameter specified (format is WIDTHxHEIGHT, e.g. 800x600)");
				}
				if (width < 640)
				{
					debug(LOG_ERROR, "Screen width < 640 unsupported, using 640");
					width = 640;
				}
				if (height < 480)
				{
					debug(LOG_ERROR, "Screen height < 480 unsupported, using 480");
					height = 480;
				}
				// tell the display system of the desired resolution
				pie_SetVideoBufferWidth(width);
				pie_SetVideoBufferHeight(height);
				// and update the configuration
				war_SetWidth(width);
				war_SetHeight(height);
				break;
			}
		case CLI_SAVEGAME:
			// retrieve the game name
			token = poptGetOptArg(poptCon);
			if (token == NULL)
			{
				qFatal("Unrecognised savegame name");
			}
			snprintf(saveGameName, sizeof(saveGameName), "%s/%s", SaveGamePath, token);
			SetGameMode(GS_SAVEGAMELOAD);
			break;

		case CLI_WINDOW:
			war_setFullscreen(false);
			break;

		case CLI_SHADOWS:
			setDrawShadows(true);
			break;

		case CLI_NOSHADOWS:
			setDrawShadows(false);
			break;

		case CLI_SOUND:
			war_setSoundEnabled(true);
			break;

		case CLI_NOSOUND:
			war_setSoundEnabled(false);
			break;

		case CLI_TEXTURECOMPRESSION:
			wz_texture_compression = GL_COMPRESSED_RGBA_ARB;
			break;

		case CLI_NOTEXTURECOMPRESSION:
			wz_texture_compression = GL_RGBA;
			break;
		};
	}

	return true;
}
Exemplo n.º 13
0
int
main(int argc, char **argv)
{
    char buf[2048], *s, *string[2], *end[2];
    const char *arg;
    FILE *fp;
    int opt, line, i, flag[2];
    poptContext pc = poptGetContext("wildtest", argc, (const char**)argv,
				    long_options, 0);

    while ((opt = poptGetNextOpt(pc)) != -1) {
	switch (opt) {
	  case 'e':
	    arg = poptGetOptArg(pc);
	    empties_mod = atoi(arg);
	    if (strchr(arg, 's'))
		empty_at_start = 1;
	    if (strchr(arg, 'e'))
		empty_at_end = 1;
	    if (!explode_mod)
		explode_mod = 1024;
	    break;
	  default:
	    fprintf(stderr, "%s: %s\n",
		    poptBadOption(pc, POPT_BADOPTION_NOALIAS),
		    poptStrerror(opt));
	    exit(1);
	}
    }

    if (explode_mod && !empties_mod)
	empties_mod = 1024;

    argv = (char**)poptGetArgs(pc);
    if (!argv || argv[1]) {
	fprintf(stderr, "Usage: wildtest [OPTIONS] TESTFILE\n");
	exit(1);
    }

    if ((fp = fopen(*argv, "r")) == NULL) {
	fprintf(stderr, "Unable to open %s\n", *argv);
	exit(1);
    }

    line = 0;
    while (fgets(buf, sizeof buf, fp)) {
	line++;
	if (*buf == '#' || *buf == '\n')
	    continue;
	for (s = buf, i = 0; i <= 1; i++) {
	    if (*s == '1')
		flag[i] = 1;
	    else if (*s == '0')
		flag[i] = 0;
	    else
		flag[i] = -1;
	    if (*++s != ' ' && *s != '\t')
		flag[i] = -1;
	    if (flag[i] < 0) {
		fprintf(stderr, "Invalid flag syntax on line %d of %s:\n%s",
			line, *argv, buf);
		exit(1);
	    }
	    while (*++s == ' ' || *s == '\t') {}
	}
	for (i = 0; i <= 1; i++) {
	    if (*s == '\'' || *s == '"' || *s == '`') {
		char quote = *s++;
		string[i] = s;
		while (*s && *s != quote) s++;
		if (!*s) {
		    fprintf(stderr, "Unmatched quote on line %d of %s:\n%s",
			    line, *argv, buf);
		    exit(1);
		}
		end[i] = s;
	    }
	    else {
		if (!*s || *s == '\n') {
		    fprintf(stderr, "Not enough strings on line %d of %s:\n%s",
			    line, *argv, buf);
		    exit(1);
		}
		string[i] = s;
		while (*++s && *s != ' ' && *s != '\t' && *s != '\n') {}
		end[i] = s;
	    }
	    while (*++s == ' ' || *s == '\t') {}
	}
	*end[0] = *end[1] = '\0';
	run_test(line, flag[0], flag[1], string[0], string[1]);
    }

    if (!wildmatch_errors)
	fputs("No", stdout);
    else
	printf("%d", wildmatch_errors);
    printf(" wildmatch error%s found.\n", wildmatch_errors == 1? "" : "s");

#ifdef COMPARE_WITH_FNMATCH
    if (!fnmatch_errors)
	fputs("No", stdout);
    else
	printf("%d", fnmatch_errors);
    printf(" fnmatch error%s found.\n", fnmatch_errors == 1? "" : "s");

#endif

    return 0;
}
Exemplo n.º 14
0
int main(int argc, const char **argv)
{
	int resume = 0, recursive = 0;
	int c = 0;
	int debuglevel = 0;
	const char *file = NULL;
	char *rcfile = NULL;
	char *outputfile = NULL;
	struct poptOption long_options[] = {
		{"guest", 'a', POPT_ARG_NONE, NULL, 'a', "Work as user guest" },	
		{"resume", 'r', POPT_ARG_NONE, &resume, 0, "Automatically resume aborted files" },
		{"recursive", 'R',  POPT_ARG_NONE, &recursive, 0, "Recursively download files" },
		{"username", 'u', POPT_ARG_STRING, &username, 'u', "Username to use" },
		{"password", 'p', POPT_ARG_STRING, &password, 'p', "Password to use" },
		{"workgroup", 'w', POPT_ARG_STRING, &workgroup, 'w', "Workgroup to use (optional)" },
		{"nonprompt", 'n', POPT_ARG_NONE, &nonprompt, 'n', "Don't ask anything (non-interactive)" },
		{"debuglevel", 'd', POPT_ARG_INT, &debuglevel, 'd', "Debuglevel to use" },
		{"outputfile", 'o', POPT_ARG_STRING, &outputfile, 'o', "Write downloaded data to specified file" },
		{"dots", 'D', POPT_ARG_NONE, &dots, 'D', "Show dots as progress indication" },
		{"quiet", 'q', POPT_ARG_NONE, &quiet, 'q', "Be quiet" },
		{"verbose", 'v', POPT_ARG_NONE, &verbose, 'v', "Be verbose" },
		{"keep-permissions", 'P', POPT_ARG_NONE, &keep_permissions, 'P', "Keep permissions" },
		{"blocksize", 'b', POPT_ARG_INT, &blocksize, 'b', "Change number of bytes in a block"},
		{"rcfile", 'f', POPT_ARG_STRING, NULL, 0, "Use specified rc file"},
		POPT_AUTOHELP
		POPT_TABLEEND
	};
	poptContext pc;

	/* only read rcfile if it exists */
	asprintf(&rcfile, "%s/.smbgetrc", getenv("HOME"));
	if(access(rcfile, F_OK) == 0) readrcfile(rcfile, long_options);
	free(rcfile);

#ifdef SIGWINCH
	signal(SIGWINCH, change_columns);
#endif
	signal(SIGINT, signal_quit);
	signal(SIGTERM, signal_quit);

	pc = poptGetContext(argv[0], argc, argv, long_options, 0);

	while((c = poptGetNextOpt(pc)) >= 0) {
		switch(c) {
		case 'f':
			readrcfile(poptGetOptArg(pc), long_options);
			break;
		case 'a':
			username = ""; password = "";
			break;
		}
	}

	if(outputfile && recursive) {
		fprintf(stderr, "The -o and -R options can not be used together.\n");
		return 1;
	}

	if(smbc_init(get_auth_data, debuglevel) < 0) {
		fprintf(stderr, "Unable to initialize libsmbclient\n");
		return 1;
	}

	columns = get_num_cols();

	total_start_time = time(NULL);

	while((file = poptGetArg(pc))) {
		if(!recursive) return smb_download_file(file, "", recursive, resume, outputfile);
		else return smb_download_dir(file, "", resume);
	}

	clean_exit();

	return 0;
}
Exemplo n.º 15
0
int main( int argc, char *argv[] )
{
	TALLOC_CTX *frame = talloc_stackframe();
	int opt;
	REGF_FILE *infile, *outfile;
	REGF_NK_REC *nk;
	char *orig_filename, *new_filename;
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{ "change-sid", 'c', POPT_ARG_STRING, NULL, 'c', "Provides SID to change" },
		{ "new-sid", 'n', POPT_ARG_STRING, NULL, 'n', "Provides SID to change to" },
		{ "verbose", 'v', POPT_ARG_NONE, &opt_verbose, 'v', "Verbose output" },
		POPT_COMMON_SAMBA
		POPT_COMMON_VERSION
		POPT_TABLEEND
	};
	poptContext pc;

	load_case_tables();

	/* setup logging options */

	setup_logging( "profiles", DEBUG_STDERR);

	pc = poptGetContext("profiles", argc, (const char **)argv, long_options,
		POPT_CONTEXT_KEEP_FIRST);

	poptSetOtherOptionHelp(pc, "<profilefile>");

	/* Now, process the arguments */

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case 'c':
			change = 1;
			if (!string_to_sid(&old_sid, poptGetOptArg(pc))) {
				fprintf(stderr, "Argument to -c should be a SID in form of S-1-5-...\n");
				poptPrintUsage(pc, stderr, 0);
				exit(254);
			}
			break;

		case 'n':
			new_val = 1;
			if (!string_to_sid(&new_sid, poptGetOptArg(pc))) {
				fprintf(stderr, "Argument to -n should be a SID in form of S-1-5-...\n");
				poptPrintUsage(pc, stderr, 0);
				exit(253);
			}
			break;

		}
	}

	poptGetArg(pc);

	if (!poptPeekArg(pc)) {
		poptPrintUsage(pc, stderr, 0);
		exit(1);
	}

	if ((!change && new_val) || (change && !new_val)) {
		fprintf(stderr, "You must specify both -c and -n if one or the other is set!\n");
		poptPrintUsage(pc, stderr, 0);
		exit(252);
	}

	orig_filename = talloc_strdup(frame, poptPeekArg(pc));
	if (!orig_filename) {
		exit(ENOMEM);
	}
	new_filename = talloc_asprintf(frame,
					"%s.new",
					orig_filename);
	if (!new_filename) {
		exit(ENOMEM);
	}

	if (!(infile = regfio_open( orig_filename, O_RDONLY, 0))) {
		fprintf( stderr, "Failed to open %s!\n", orig_filename );
		fprintf( stderr, "Error was (%s)\n", strerror(errno) );
		exit (1);
	}

	if ( !(outfile = regfio_open( new_filename, (O_RDWR|O_CREAT|O_TRUNC),
				      (S_IRUSR|S_IWUSR) )) ) {
		fprintf( stderr, "Failed to open new file %s!\n", new_filename );
		fprintf( stderr, "Error was (%s)\n", strerror(errno) );
		exit (1);
	}

	/* actually do the update now */

	if ((nk = regfio_rootkey( infile )) == NULL) {
		fprintf(stderr, "Could not get rootkey\n");
		exit(3);
	}

	if (!copy_registry_tree( infile, nk, NULL, outfile, "")) {
		fprintf(stderr, "Failed to write updated registry file!\n");
		exit(2);
	}

	/* cleanup */

	regfio_close(infile);
	regfio_close(outfile);

	poptFreeContext(pc);

	TALLOC_FREE(frame);
	return 0;
}
Exemplo n.º 16
0
/*
 * Add event to trace session
 */
int cmd_enable_events(int argc, const char **argv)
{
	int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
	static poptContext pc;
	char *session_name = NULL;
	const char *leftover = NULL;
	int event_type = -1;

	pc = poptGetContext(NULL, argc, argv, long_options, 0);
	poptReadDefaultConfig(pc, 0);

	/* Default event type */
	opt_event_type = LTTNG_EVENT_ALL;

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_HELP:
			SHOW_HELP();
			goto end;
		case OPT_TRACEPOINT:
			opt_event_type = LTTNG_EVENT_TRACEPOINT;
			break;
		case OPT_PROBE:
			opt_event_type = LTTNG_EVENT_PROBE;
			break;
		case OPT_USERSPACE_PROBE:
			opt_event_type = LTTNG_EVENT_USERSPACE_PROBE;
			break;
		case OPT_FUNCTION:
			opt_event_type = LTTNG_EVENT_FUNCTION;
			break;
		case OPT_SYSCALL:
			opt_event_type = LTTNG_EVENT_SYSCALL;
			break;
		case OPT_USERSPACE:
			opt_userspace = 1;
			break;
		case OPT_LOGLEVEL:
			opt_loglevel_type = LTTNG_EVENT_LOGLEVEL_RANGE;
			opt_loglevel = poptGetOptArg(pc);
			break;
		case OPT_LOGLEVEL_ONLY:
			opt_loglevel_type = LTTNG_EVENT_LOGLEVEL_SINGLE;
			opt_loglevel = poptGetOptArg(pc);
			break;
		case OPT_LIST_OPTIONS:
			list_cmd_options(stdout, long_options);
			goto end;
		case OPT_FILTER:
			break;
		case OPT_EXCLUDE:
			break;
		default:
			ret = CMD_UNDEFINED;
			goto end;
		}

		/* Validate event type. Multiple event type are not supported. */
		if (event_type == -1) {
			event_type = opt_event_type;
		} else {
			if (event_type != opt_event_type) {
				ERR("Multiple event type not supported.");
				ret = CMD_ERROR;
				goto end;
			}
		}
	}

	ret = print_missing_or_multiple_domains(
		opt_kernel + opt_userspace + opt_jul + opt_log4j + opt_python);
	if (ret) {
		ret = CMD_ERROR;
		goto end;
	}

	/* Mi check */
	if (lttng_opt_mi) {
		writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
		if (!writer) {
			ret = -LTTNG_ERR_NOMEM;
			goto end;
		}

		/* Open command element */
		ret = mi_lttng_writer_command_open(writer,
				mi_lttng_element_command_enable_event);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Open output element */
		ret = mi_lttng_writer_open_element(writer,
				mi_lttng_element_command_output);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}
	}

	opt_event_list = (char*) poptGetArg(pc);
	if (opt_event_list == NULL && opt_enable_all == 0) {
		ERR("Missing event name(s).\n");
		ret = CMD_ERROR;
		goto end;
	}

	leftover = poptGetArg(pc);
	if (leftover) {
		ERR("Unknown argument: %s", leftover);
		ret = CMD_ERROR;
		goto end;
	}

	if (!opt_session_name) {
		session_name = get_session_name();
		if (session_name == NULL) {
			command_ret = CMD_ERROR;
			success = 0;
			goto mi_closing;
		}
	} else {
		session_name = opt_session_name;
	}

	command_ret = enable_events(session_name);
	if (command_ret) {
		success = 0;
		goto mi_closing;
	}

mi_closing:
	/* Mi closing */
	if (lttng_opt_mi) {
		/* Close  output element */
		ret = mi_lttng_writer_close_element(writer);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		ret = mi_lttng_writer_write_element_bool(writer,
				mi_lttng_element_command_success, success);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Command element close */
		ret = mi_lttng_writer_command_close(writer);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}
	}

end:
	/* Mi clean-up */
	if (writer && mi_lttng_writer_destroy(writer)) {
		/* Preserve original error code */
		ret = ret ? ret : LTTNG_ERR_MI_IO_FAIL;
	}

	if (opt_session_name == NULL) {
		free(session_name);
	}

	/* Overwrite ret if an error occurred in enable_events */
	ret = command_ret ? command_ret : ret;

	poptFreeContext(pc);
	return ret;
}
Exemplo n.º 17
0
/**
  process command line options
*/
struct ldb_cmdline *ldb_cmdline_process(struct ldb_context *ldb, 
					int argc, const char **argv,
					void (*usage)(struct ldb_context *))
{
	struct ldb_cmdline *ret=NULL;
	poptContext pc;
	int num_options = 0;
	int opt;
	unsigned int flags = 0;
	int rc;
	struct poptOption **popt_options;

	/* make the ldb utilities line buffered */
	setlinebuf(stdout);

	ret = talloc_zero(ldb, struct ldb_cmdline);
	if (ret == NULL) {
		fprintf(stderr, "Out of memory!\n");
		goto failed;
	}

	options = *ret;
	
	/* pull in URL */
	options.url = getenv("LDB_URL");

	/* and editor (used by ldbedit) */
	options.editor = getenv("VISUAL");
	if (!options.editor) {
		options.editor = getenv("EDITOR");
	}
	if (!options.editor) {
		options.editor = "vi";
	}

	options.scope = LDB_SCOPE_DEFAULT;

	popt_options = ldb_module_popt_options(ldb);
	(*popt_options) = builtin_popt_options;

	rc = ldb_modules_hook(ldb, LDB_MODULE_HOOK_CMDLINE_OPTIONS);
	if (rc != LDB_SUCCESS) {
		fprintf(stderr, "ldb: failed to run command line hooks : %s\n", ldb_strerror(rc));
		goto failed;
	}

	pc = poptGetContext(argv[0], argc, argv, *popt_options,
			    POPT_CONTEXT_KEEP_FIRST);

	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case 's': {
			const char *arg = poptGetOptArg(pc);
			if (strcmp(arg, "base") == 0) {
				options.scope = LDB_SCOPE_BASE;
			} else if (strcmp(arg, "sub") == 0) {
				options.scope = LDB_SCOPE_SUBTREE;
			} else if (strcmp(arg, "one") == 0) {
				options.scope = LDB_SCOPE_ONELEVEL;
			} else {
				fprintf(stderr, "Invalid scope '%s'\n", arg);
				goto failed;
			}
			break;
		}

		case 'v':
			options.verbose++;
			break;

		case 'o':
			options.options = talloc_realloc(ret, options.options, 
							 const char *, num_options+3);
			if (options.options == NULL) {
				fprintf(stderr, "Out of memory!\n");
				goto failed;
			}
			options.options[num_options] = poptGetOptArg(pc);
			options.options[num_options+1] = NULL;
			num_options++;
			break;

		case 'c': {
			const char *cs = poptGetOptArg(pc);
			const char *p;

			for (p = cs; p != NULL; ) {
				const char *t, *c;

				t = strchr(p, ',');
				if (t == NULL) {
					c = talloc_strdup(options.controls, p);
					p = NULL;
				} else {
					c = talloc_strndup(options.controls, p, t-p);
			        	p = t + 1;
				}
				if (c == NULL || !add_control(ret, c)) {
					fprintf(stderr, __location__ ": out of memory\n");
					goto failed;
				}
			}

			break;	  
		}
		case 'P':
			if (!add_control(ret, "paged_results:1:1024")) {
				fprintf(stderr, __location__ ": out of memory\n");
				goto failed;
			}
			break;
		case 'D':
			if (!add_control(ret, "show_deleted:1")) {
				fprintf(stderr, __location__ ": out of memory\n");
				goto failed;
			}
			break;
		case 'R':
			if (!add_control(ret, "show_recycled:0")) {
				fprintf(stderr, __location__ ": out of memory\n");
				goto failed;
			}
			break;
		case 'd':
			if (!add_control(ret, "show_deactivated_link:0")) {
				fprintf(stderr, __location__ ": out of memory\n");
				goto failed;
			}
			break;
		case 'r':
			if (!add_control(ret, "reveal_internals:0")) {
				fprintf(stderr, __location__ ": out of memory\n");
				goto failed;
			}
			break;
		case CMDLINE_RELAX:
			if (!add_control(ret, "relax:0")) {
				fprintf(stderr, __location__ ": out of memory\n");
				goto failed;
			}
			break;
		case 'N':
			if (!add_control(ret, "search_options:1:2")) {
				fprintf(stderr, __location__ ": out of memory\n");
				goto failed;
			}
			break;
		case 'E':
			if (!add_control(ret, "extended_dn:1:1")) {
				fprintf(stderr, __location__ ": out of memory\n");
				goto failed;
			}
			break;
		default:
			fprintf(stderr, "Invalid option %s: %s\n", 
				poptBadOption(pc, 0), poptStrerror(opt));
			if (usage) usage(ldb);
			goto failed;
		}
	}

	/* setup the remaining options for the main program to use */
	options.argv = poptGetArgs(pc);
	if (options.argv) {
		options.argv++;
		while (options.argv[options.argc]) options.argc++;
	}

	*ret = options;

	/* all utils need some option */
	if (ret->url == NULL) {
		fprintf(stderr, "You must supply a url with -H or with $LDB_URL\n");
		if (usage) usage(ldb);
		goto failed;
	}

	if (strcmp(ret->url, "NONE") == 0) {
		return ret;
	}

	if (options.nosync) {
		flags |= LDB_FLG_NOSYNC;
	}

	if (options.show_binary) {
		flags |= LDB_FLG_SHOW_BINARY;
	}

	if (options.tracing) {
		flags |= LDB_FLG_ENABLE_TRACING;
	}

	if (options.modules_path != NULL) {
		ldb_set_modules_dir(ldb, options.modules_path);
	}

	rc = ldb_modules_hook(ldb, LDB_MODULE_HOOK_CMDLINE_PRECONNECT);
	if (rc != LDB_SUCCESS) {
		fprintf(stderr, "ldb: failed to run preconnect hooks : %s\n", ldb_strerror(rc));
		goto failed;
	}

	/* now connect to the ldb */
	if (ldb_connect(ldb, ret->url, flags, ret->options) != LDB_SUCCESS) {
		fprintf(stderr, "Failed to connect to %s - %s\n", 
			ret->url, ldb_errstring(ldb));
		goto failed;
	}

	rc = ldb_modules_hook(ldb, LDB_MODULE_HOOK_CMDLINE_POSTCONNECT);
	if (rc != LDB_SUCCESS) {
		fprintf(stderr, "ldb: failed to run post connect hooks : %s\n", ldb_strerror(rc));
		goto failed;
	}

	return ret;

failed:
	talloc_free(ret);
	exit(LDB_ERR_OPERATIONS_ERROR);
	return NULL;
}
Exemplo n.º 18
0
Arquivo: net.c Projeto: AllardJ/Tomato
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc, const char **argv)
{
	int opt,i;
	char *p;
	int rc = 0;
	int argc_new = 0;
	const char ** argv_new;
	poptContext pc;

	struct poptOption long_options[] = {
		{"help",	'h', POPT_ARG_NONE,   0, 'h'},
		{"workgroup",	'w', POPT_ARG_STRING, &opt_target_workgroup},
		{"user",	'U', POPT_ARG_STRING, &opt_user_name, 'U'},
		{"ipaddress",	'I', POPT_ARG_STRING, 0,'I'},
		{"port",	'p', POPT_ARG_INT,    &opt_port},
		{"myname",	'n', POPT_ARG_STRING, &opt_requester_name},
		{"server",	'S', POPT_ARG_STRING, &opt_host},
		{"container",	'c', POPT_ARG_STRING, &opt_container},
		{"comment",	'C', POPT_ARG_STRING, &opt_comment},
		{"maxusers",	'M', POPT_ARG_INT,    &opt_maxusers},
		{"flags",	'F', POPT_ARG_INT,    &opt_flags},
		{"long",	'l', POPT_ARG_NONE,   &opt_long_list_entries},
		{"reboot",	'r', POPT_ARG_NONE,   &opt_reboot},
		{"force",	'f', POPT_ARG_NONE,   &opt_force},
		{"stdin",	'i', POPT_ARG_NONE,   &opt_stdin},
		{"timeout",	't', POPT_ARG_INT,    &opt_timeout},
		{"machine-pass",'P', POPT_ARG_NONE,   &opt_machine_pass},
		{"myworkgroup", 'W', POPT_ARG_STRING, &opt_workgroup},
		{"verbose",	'v', POPT_ARG_NONE,   &opt_verbose},
		/* Options for 'net groupmap set' */
		{"local",       'L', POPT_ARG_NONE,   &opt_localgroup},
		{"domain",      'D', POPT_ARG_NONE,   &opt_domaingroup},
		{"ntname",      'N', POPT_ARG_STRING, &opt_newntname},
		{"rid",         'R', POPT_ARG_INT,    &opt_rid},
		/* Options for 'net rpc share migrate' */
		{"acls",	0, POPT_ARG_NONE,     &opt_acls},
		{"attrs",	0, POPT_ARG_NONE,     &opt_attrs},
		{"timestamps",	0, POPT_ARG_NONE,     &opt_timestamps},
		{"exclude",	'e', POPT_ARG_STRING, &opt_exclude},
		{"destination",	0, POPT_ARG_STRING,   &opt_destination},
		{"tallocreport", 0, POPT_ARG_NONE, &do_talloc_report},

		POPT_COMMON_SAMBA
		{ 0, 0, 0, 0}
	};

	zero_ip(&opt_dest_ip);

	load_case_tables();

	/* set default debug level to 0 regardless of what smb.conf sets */
	DEBUGLEVEL_CLASS[DBGC_ALL] = 0;
	dbf = x_stderr;
	
	pc = poptGetContext(NULL, argc, (const char **) argv, long_options, 
			    POPT_CONTEXT_KEEP_FIRST);
	
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case 'h':
			net_help(argc, argv);
			exit(0);
			break;
		case 'I':
			opt_dest_ip = *interpret_addr2(poptGetOptArg(pc));
			if (is_zero_ip(opt_dest_ip))
				d_fprintf(stderr, "\nInvalid ip address specified\n");
			else
				opt_have_ip = True;
			break;
		case 'U':
			opt_user_specified = True;
			opt_user_name = SMB_STRDUP(opt_user_name);
			p = strchr(opt_user_name,'%');
			if (p) {
				*p = 0;
				opt_password = p+1;
			}
			break;
		default:
			d_fprintf(stderr, "\nInvalid option %s: %s\n", 
				 poptBadOption(pc, 0), poptStrerror(opt));
			net_help(argc, argv);
			exit(1);
		}
	}
	
	/*
	 * Don't load debug level from smb.conf. It should be
	 * set by cmdline arg or remain default (0)
	 */
	AllowDebugChange = False;
	lp_load(dyn_CONFIGFILE,True,False,False,True);
	
 	argv_new = (const char **)poptGetArgs(pc);

	argc_new = argc;
	for (i=0; i<argc; i++) {
		if (argv_new[i] == NULL) {
			argc_new = i;
			break;
		}
	}

	if (do_talloc_report) {
		talloc_enable_leak_report();
	}

	if (opt_requester_name) {
		set_global_myname(opt_requester_name);
	}

	if (!opt_user_name && getenv("LOGNAME")) {
		opt_user_name = getenv("LOGNAME");
	}

	if (!opt_user_name) {
		opt_user_name = "";
	}

	if (!opt_workgroup) {
		opt_workgroup = smb_xstrdup(lp_workgroup());
	}
	
	if (!opt_target_workgroup) {
		opt_target_workgroup = smb_xstrdup(lp_workgroup());
	}
	
	if (!init_names())
		exit(1);

	load_interfaces();
	
	/* this makes sure that when we do things like call scripts, 
	   that it won't assert becouse we are not root */
	sec_init();

	if (opt_machine_pass) {
		/* it is very useful to be able to make ads queries as the
		   machine account for testing purposes and for domain leave */

		net_use_krb_machine_account();
	}

	if (!opt_password) {
		opt_password = getenv("PASSWD");
	}
  	 
	rc = net_run_function(argc_new-1, argv_new+1, net_func, net_help);
	
	DEBUG(2,("return code = %d\n", rc));
	return rc;
}
Exemplo n.º 19
0
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc,char *argv[])
{
	char *share[NSERVERS];
	int opt;
	int seed, server;
	int username_count=0;
	struct tevent_context *ev;
	struct loadparm_context *lp_ctx;
	poptContext pc;
	int argc_new, i;
	char **argv_new;
	enum {OPT_UNCLIST=1000};
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"seed",	  0, POPT_ARG_INT,  &seed, 	0,	"Seed to use for randomizer", 	NULL},
		{"num-ops",	  0, POPT_ARG_INT,  &numops, 	0, 	"num ops",	NULL},
		{"lockrange",     0, POPT_ARG_INT,  &lock_range,0,      "locking range", NULL},
		{"lockbase",      0, POPT_ARG_INT,  &lock_base, 0,      "locking base", NULL},
		{"minlength",     0, POPT_ARG_INT,  &min_length,0,      "min lock length", NULL},
		{"hidefails",     0, POPT_ARG_NONE, &hide_unlock_fails,0,"hide unlock fails", NULL},
		{"oplocks",       0, POPT_ARG_NONE, &use_oplocks,0,      "use oplocks", NULL},
		{"showall",       0, POPT_ARG_NONE, &showall,    0,      "display all operations", NULL},
		{"analyse",       0, POPT_ARG_NONE, &analyze,    0,      "do backtrack analysis", NULL},
		{"zerozero",      0, POPT_ARG_NONE, &zero_zero,    0,      "do zero/zero lock", NULL},
		{"exacterrors",   0, POPT_ARG_NONE, &exact_error_codes,0,"use exact error codes", NULL},
		{"unclist",	  0, POPT_ARG_STRING,	NULL, 	OPT_UNCLIST,	"unclist", 	NULL},
		{ "user", 'U',       POPT_ARG_STRING, NULL, 'U', "Set the network username", "[DOMAIN/]USERNAME[%PASSWORD]" },
		POPT_COMMON_SAMBA
		POPT_COMMON_CONNECTION
		POPT_COMMON_CREDENTIALS
		POPT_COMMON_VERSION
		{ NULL }
	};

	setlinebuf(stdout);
	seed = time(NULL);

	pc = poptGetContext("locktest", argc, (const char **) argv, long_options, 
			    POPT_CONTEXT_KEEP_FIRST);

	poptSetOtherOptionHelp(pc, "<unc1> <unc2>");

	lp_ctx = cmdline_lp_ctx;
	servers[0] = cli_credentials_init(talloc_autofree_context());
	servers[1] = cli_credentials_init(talloc_autofree_context());
	cli_credentials_guess(servers[0], lp_ctx);
	cli_credentials_guess(servers[1], lp_ctx);

	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_UNCLIST:
			lp_set_cmdline(cmdline_lp_ctx, "torture:unclist", poptGetOptArg(pc));
			break;
		case 'U':
			if (username_count == 2) {
				usage(pc);
				exit(1);
			}
			cli_credentials_parse_string(servers[username_count], poptGetOptArg(pc), CRED_SPECIFIED);
			username_count++;
			break;
		}
	}

	argv_new = discard_const_p(char *, poptGetArgs(pc));
	argc_new = argc;
	for (i=0; i<argc; i++) {
		if (argv_new[i] == NULL) {
			argc_new = i;
			break;
		}
	}

	if (!(argc_new >= 3)) {
		usage(pc);
		exit(1);
	}

	setup_logging("locktest", DEBUG_STDOUT);

	for (server=0;server<NSERVERS;server++) {
		share[server] = argv_new[1+server];
		all_string_sub(share[server],"/","\\",0);
	}

	lp_ctx = cmdline_lp_ctx;

	if (username_count == 0) {
		usage(pc);
		return -1;
	}
	if (username_count == 1) {
		servers[1] = servers[0];
	}

	ev = s4_event_context_init(talloc_autofree_context());

	gensec_init(lp_ctx);

	DEBUG(0,("seed=%u base=%d range=%d min_length=%d\n", 
		 seed, lock_base, lock_range, min_length));
	srandom(seed);

	return test_locks(ev, lp_ctx, NULL, share);
}
Exemplo n.º 20
0
/*
 * Add channel to trace session
 */
int cmd_enable_channels(int argc, const char **argv)
{
	int opt, ret = CMD_SUCCESS;
	static poptContext pc;
	char *session_name = NULL;
	char *opt_arg = NULL;

	init_channel_config();

	pc = poptGetContext(NULL, argc, argv, long_options, 0);
	poptReadDefaultConfig(pc, 0);

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_HELP:
			usage(stdout);
			goto end;
		case OPT_DISCARD:
			chan.attr.overwrite = 0;
			DBG("Channel set to discard");
			break;
		case OPT_OVERWRITE:
			chan.attr.overwrite = 1;
			DBG("Channel set to overwrite");
			break;
		case OPT_SUBBUF_SIZE:
		{
			uint64_t rounded_size;
			int order;

			/* Parse the size */
			opt_arg = poptGetOptArg(pc);
			if (utils_parse_size_suffix(opt_arg, &chan.attr.subbuf_size) < 0 || !chan.attr.subbuf_size) {
				ERR("Wrong value in --subbuf-size parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}

			order = get_count_order_u64(chan.attr.subbuf_size);
			assert(order >= 0);
			rounded_size = 1ULL << order;
			if (rounded_size != chan.attr.subbuf_size) {
				WARN("The subbuf size (%" PRIu64 ") is rounded to the next power of 2 (%" PRIu64 ")",
						chan.attr.subbuf_size, rounded_size);
				chan.attr.subbuf_size = rounded_size;
			}

			/* Should now be power of 2 */
			assert(!((chan.attr.subbuf_size - 1) & chan.attr.subbuf_size));

			DBG("Channel subbuf size set to %" PRIu64, chan.attr.subbuf_size);
			break;
		}
		case OPT_NUM_SUBBUF:
		{
			uint64_t rounded_size;
			int order;

			errno = 0;
			opt_arg = poptGetOptArg(pc);
			chan.attr.num_subbuf = strtoull(opt_arg, NULL, 0);
			if (errno != 0 || !chan.attr.num_subbuf || !isdigit(opt_arg[0])) {
				ERR("Wrong value in --num-subbuf parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}

			order = get_count_order_u64(chan.attr.num_subbuf);
			assert(order >= 0);
			rounded_size = 1ULL << order;
			if (rounded_size != chan.attr.num_subbuf) {
				WARN("The number of subbuffers (%" PRIu64 ") is rounded to the next power of 2 (%" PRIu64 ")",
						chan.attr.num_subbuf, rounded_size);
				chan.attr.num_subbuf = rounded_size;
			}

			/* Should now be power of 2 */
			assert(!((chan.attr.num_subbuf - 1) & chan.attr.num_subbuf));

			DBG("Channel subbuf num set to %" PRIu64, chan.attr.num_subbuf);
			break;
		}
		case OPT_SWITCH_TIMER:
		{
			unsigned long v;

			errno = 0;
			opt_arg = poptGetOptArg(pc);
			v = strtoul(opt_arg, NULL, 0);
			if (errno != 0 || !isdigit(opt_arg[0])) {
				ERR("Wrong value in --switch-timer parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			if (v != (uint32_t) v) {
				ERR("32-bit overflow in --switch-timer parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			chan.attr.switch_timer_interval = (uint32_t) v;
			DBG("Channel switch timer interval set to %d", chan.attr.switch_timer_interval);
			break;
		}
		case OPT_READ_TIMER:
		{
			unsigned long v;

			errno = 0;
			opt_arg = poptGetOptArg(pc);
			v = strtoul(opt_arg, NULL, 0);
			if (errno != 0 || !isdigit(opt_arg[0])) {
				ERR("Wrong value in --read-timer parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			if (v != (uint32_t) v) {
				ERR("32-bit overflow in --read-timer parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			chan.attr.read_timer_interval = (uint32_t) v;
			DBG("Channel read timer interval set to %d", chan.attr.read_timer_interval);
			break;
		}
		case OPT_USERSPACE:
			opt_userspace = 1;
			break;
		case OPT_TRACEFILE_SIZE:
			opt_arg = poptGetOptArg(pc);
			if (utils_parse_size_suffix(opt_arg, &chan.attr.tracefile_size) < 0) {
				ERR("Wrong value in --tracefile-size parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			DBG("Maximum tracefile size set to %" PRIu64,
					chan.attr.tracefile_size);
			break;
		case OPT_TRACEFILE_COUNT:
		{
			unsigned long v;

			errno = 0;
			opt_arg = poptGetOptArg(pc);
			v = strtoul(opt_arg, NULL, 0);
			if (errno != 0 || !isdigit(opt_arg[0])) {
				ERR("Wrong value in --tracefile-count parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			if (v != (uint32_t) v) {
				ERR("32-bit overflow in --tracefile-count parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			chan.attr.tracefile_count = (uint32_t) v;
			DBG("Maximum tracefile count set to %" PRIu64,
					chan.attr.tracefile_count);
			break;
		}
		case OPT_LIST_OPTIONS:
			list_cmd_options(stdout, long_options);
			goto end;
		default:
			usage(stderr);
			ret = CMD_UNDEFINED;
			goto end;
		}
	}

	opt_channels = (char*) poptGetArg(pc);
	if (opt_channels == NULL) {
		ERR("Missing channel name.\n");
		usage(stderr);
		ret = CMD_ERROR;
		goto end;
	}

	if (!opt_session_name) {
		session_name = get_session_name();
		if (session_name == NULL) {
			ret = CMD_ERROR;
			goto end;
		}
	} else {
		session_name = opt_session_name;
	}

	ret = enable_channel(session_name);

end:
	if (!opt_session_name && session_name) {
		free(session_name);
	}
	poptFreeContext(pc);
	return ret;
}
Exemplo n.º 21
0
int main(int argc, const char *argv[])
{
	TALLOC_CTX				*mem_ctx = NULL;
	const struct ndr_interface_table	*p = NULL;
	const struct ndr_interface_call		*f;
	struct SPropTagArray			*s;
	const char				*opt_reqfile = NULL;
	const char				*opt_replfile = NULL;
	poptContext				pc;
	int					opt;
	int					index = -1;
	int					ret = -1;
	uint8_t					opnum = 0;

	enum {OPT_REQ=1000, OPT_REPL};
	struct poptOption	long_options[] = {
		POPT_AUTOHELP
		{ "request",  'i', POPT_ARG_STRING, NULL, OPT_REQ,  "MAPI Request", NULL },
		{ "response", 'o', POPT_ARG_STRING, NULL, OPT_REPL, "MAPI Response", NULL },
		{ NULL }
	};

	pc = poptGetContext("mapipropsdump", argc, argv, long_options, 0);

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_REQ:
			opt_reqfile = poptGetOptArg(pc);
			break;
		case OPT_REPL:
			opt_replfile = poptGetOptArg(pc);
			break;
		}
	}

	/* Sanity checks on options */
	if (!opt_reqfile || !opt_replfile) {
		DEBUG(0, ("Request and Response files required\n"));
		exit (1);
	}

	p = load_exchange_emsmdb_dso(PLUGIN);
	if (!p) {
		exit (1);
	}

	f = &p->calls[FUNCTION];
	mem_ctx = talloc_init("mapipropsdump");

	/* Load the request */
	s = process_request(mem_ctx, f, opt_reqfile, &opnum, &index);
	if (!s) {
		talloc_free(mem_ctx);
		exit (1);
	}

	/* Load the response */
	ret = process_response(mem_ctx, f, opt_replfile, s, opnum, index);
	if (ret == -1) {
		talloc_free(mem_ctx);
		exit (1);
	}

	talloc_free(mem_ctx);
	return (0);
}
Exemplo n.º 22
0
/*
 * Add channel to trace session
 */
int cmd_enable_channels(int argc, const char **argv)
{
	int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
	static poptContext pc;
	char *session_name = NULL;
	char *opt_arg = NULL;

	init_channel_config();

	pc = poptGetContext(NULL, argc, argv, long_options, 0);
	poptReadDefaultConfig(pc, 0);

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_HELP:
			usage(stdout);
			goto end;
		case OPT_DISCARD:
			chan.attr.overwrite = 0;
			DBG("Channel set to discard");
			break;
		case OPT_OVERWRITE:
			chan.attr.overwrite = 1;
			DBG("Channel set to overwrite");
			break;
		case OPT_SUBBUF_SIZE:
		{
			uint64_t rounded_size;
			int order;

			/* Parse the size */
			opt_arg = poptGetOptArg(pc);
			if (utils_parse_size_suffix(opt_arg, &chan.attr.subbuf_size) < 0 || !chan.attr.subbuf_size) {
				ERR("Wrong value in --subbuf-size parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}

			order = get_count_order_u64(chan.attr.subbuf_size);
			assert(order >= 0);
			rounded_size = 1ULL << order;
			if (rounded_size < chan.attr.subbuf_size) {
				ERR("The subbuf size (%" PRIu64 ") is rounded and overflows!",
						chan.attr.subbuf_size);
				ret = CMD_ERROR;
				goto end;
			}

			if (rounded_size != chan.attr.subbuf_size) {
				WARN("The subbuf size (%" PRIu64 ") is rounded to the next power of 2 (%" PRIu64 ")",
						chan.attr.subbuf_size, rounded_size);
				chan.attr.subbuf_size = rounded_size;
			}

			/* Should now be power of 2 */
			assert(!((chan.attr.subbuf_size - 1) & chan.attr.subbuf_size));

			DBG("Channel subbuf size set to %" PRIu64, chan.attr.subbuf_size);
			break;
		}
		case OPT_NUM_SUBBUF:
		{
			uint64_t rounded_size;
			int order;

			errno = 0;
			opt_arg = poptGetOptArg(pc);
			chan.attr.num_subbuf = strtoull(opt_arg, NULL, 0);
			if (errno != 0 || !chan.attr.num_subbuf || !isdigit(opt_arg[0])) {
				ERR("Wrong value in --num-subbuf parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}

			order = get_count_order_u64(chan.attr.num_subbuf);
			assert(order >= 0);
			rounded_size = 1ULL << order;
			if (rounded_size < chan.attr.num_subbuf) {
				ERR("The number of subbuffers (%" PRIu64 ") is rounded and overflows!",
						chan.attr.num_subbuf);
				ret = CMD_ERROR;
				goto end;
			}

			if (rounded_size != chan.attr.num_subbuf) {
				WARN("The number of subbuffers (%" PRIu64 ") is rounded to the next power of 2 (%" PRIu64 ")",
						chan.attr.num_subbuf, rounded_size);
				chan.attr.num_subbuf = rounded_size;
			}

			/* Should now be power of 2 */
			assert(!((chan.attr.num_subbuf - 1) & chan.attr.num_subbuf));

			DBG("Channel subbuf num set to %" PRIu64, chan.attr.num_subbuf);
			break;
		}
		case OPT_SWITCH_TIMER:
		{
			unsigned long v;

			errno = 0;
			opt_arg = poptGetOptArg(pc);
			v = strtoul(opt_arg, NULL, 0);
			if (errno != 0 || !isdigit(opt_arg[0])) {
				ERR("Wrong value in --switch-timer parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			if (v != (uint32_t) v) {
				ERR("32-bit overflow in --switch-timer parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			chan.attr.switch_timer_interval = (uint32_t) v;
			DBG("Channel switch timer interval set to %d", chan.attr.switch_timer_interval);
			break;
		}
		case OPT_READ_TIMER:
		{
			unsigned long v;

			errno = 0;
			opt_arg = poptGetOptArg(pc);
			v = strtoul(opt_arg, NULL, 0);
			if (errno != 0 || !isdigit(opt_arg[0])) {
				ERR("Wrong value in --read-timer parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			if (v != (uint32_t) v) {
				ERR("32-bit overflow in --read-timer parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			chan.attr.read_timer_interval = (uint32_t) v;
			DBG("Channel read timer interval set to %d", chan.attr.read_timer_interval);
			break;
		}
		case OPT_USERSPACE:
			opt_userspace = 1;
			break;
		case OPT_TRACEFILE_SIZE:
			opt_arg = poptGetOptArg(pc);
			if (utils_parse_size_suffix(opt_arg, &chan.attr.tracefile_size) < 0) {
				ERR("Wrong value in --tracefile-size parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			DBG("Maximum tracefile size set to %" PRIu64,
					chan.attr.tracefile_size);
			break;
		case OPT_TRACEFILE_COUNT:
		{
			unsigned long v;

			errno = 0;
			opt_arg = poptGetOptArg(pc);
			v = strtoul(opt_arg, NULL, 0);
			if (errno != 0 || !isdigit(opt_arg[0])) {
				ERR("Wrong value in --tracefile-count parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			if (v != (uint32_t) v) {
				ERR("32-bit overflow in --tracefile-count parameter: %s", opt_arg);
				ret = CMD_ERROR;
				goto end;
			}
			chan.attr.tracefile_count = (uint32_t) v;
			DBG("Maximum tracefile count set to %" PRIu64,
					chan.attr.tracefile_count);
			break;
		}
		case OPT_LIST_OPTIONS:
			list_cmd_options(stdout, long_options);
			goto end;
		default:
			usage(stderr);
			ret = CMD_UNDEFINED;
			goto end;
		}
	}

	/* Mi check */
	if (lttng_opt_mi) {
		writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
		if (!writer) {
			ret = -LTTNG_ERR_NOMEM;
			goto end;
		}

		/* Open command element */
		ret = mi_lttng_writer_command_open(writer,
				mi_lttng_element_command_enable_channels);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Open output element */
		ret = mi_lttng_writer_open_element(writer,
				mi_lttng_element_command_output);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}
	}

	opt_channels = (char*) poptGetArg(pc);
	if (opt_channels == NULL) {
		ERR("Missing channel name.\n");
		usage(stderr);
		ret = CMD_ERROR;
		success = 0;
		goto mi_closing;
	}

	if (!opt_session_name) {
		session_name = get_session_name();
		if (session_name == NULL) {
			command_ret = CMD_ERROR;
			success = 0;
			goto mi_closing;
		}
	} else {
		session_name = opt_session_name;
	}

	command_ret = enable_channel(session_name);
	if (command_ret) {
		success = 0;
	}

mi_closing:
	/* Mi closing */
	if (lttng_opt_mi) {
		/* Close  output element */
		ret = mi_lttng_writer_close_element(writer);
		if (ret) {
			goto end;
		}

		/* Success ? */
		ret = mi_lttng_writer_write_element_bool(writer,
				mi_lttng_element_command_success, success);
		if (ret) {
			goto end;
		}

		/* Command element close */
		ret = mi_lttng_writer_command_close(writer);
		if (ret) {
			goto end;
		}
	}

end:
	/* Mi clean-up */
	if (writer && mi_lttng_writer_destroy(writer)) {
		/* Preserve original error code */
		ret = ret ? ret : LTTNG_ERR_MI_IO_FAIL;
	}

	if (!opt_session_name && session_name) {
		free(session_name);
	}

	/* Overwrite ret if an error occurred when enable_channel */
	ret = command_ret ? command_ret : ret;
	poptFreeContext(pc);
	return ret;
}
Exemplo n.º 23
0
/**
 * First half of the command line parsing. Also see ParseCommandLine()
 * below. The parameters here are needed early in the boot process,
 * while the ones in ParseCommandLine can benefit from debugging being
 * set up first.
 * \param argc number of arguments given
 * \param argv string array of the arguments
 * \return Returns true on success, false on error */
bool ParseCommandLineEarly(int argc, const char **argv)
{
	poptContext poptCon = poptGetContext(NULL, argc, argv, getOptionsTable(), 0);
	int iOption;

#if defined(WZ_OS_MAC) && defined(DEBUG)
	debug_enable_switch("all");
#endif /* WZ_OS_MAC && DEBUG */

	/* loop through command line */
	while ((iOption = poptGetNextOpt(poptCon)) > 0 || iOption == POPT_ERROR_BADOPT)
	{
		CLI_OPTIONS option = (CLI_OPTIONS)iOption;
		const char *token;

		if (iOption == POPT_ERROR_BADOPT)
		{
			qFatal("Unrecognized option: %s", poptBadOption(poptCon, 0));
		}

		switch (option)
		{
		case CLI_DEBUG:
			// retrieve the debug section name
			token = poptGetOptArg(poptCon);
			if (token == NULL)
			{
				qFatal("Usage: --debug=<flag>");
			}

			// Attempt to enable the given debug section
			if (!debug_enable_switch(token))
			{
				qFatal("Debug flag \"%s\" not found!", token);
			}
			break;

		case CLI_DEBUGFILE:
			// find the file name
			token = poptGetOptArg(poptCon);
			if (token == NULL)
			{
				qFatal("Missing debugfile filename?");
			}
			debug_register_callback(debug_callback_file, debug_callback_file_init, debug_callback_file_exit, (void *)token);
			customDebugfile = true;
			break;

		case CLI_FLUSHDEBUGSTDERR:
			// Tell the debug stderr output callback to always flush its output
			debugFlushStderr();
			break;

		case CLI_CONFIGDIR:
			// retrieve the configuration directory
			token = poptGetOptArg(poptCon);
			if (token == NULL)
			{
				qFatal("Unrecognised configuration directory");
			}
			sstrcpy(configdir, token);
			break;

		case CLI_HELP:
			poptPrintHelp(poptCon, stdout, 0);
			return false;

		case CLI_VERSION:
			printf("Warzone 2100 - %s\n", version_getFormattedVersionString());
			return false;

		default:
			break;
		};
	}

	return true;
}
Exemplo n.º 24
0
/*
  main program
*/
int main(int argc, const char *argv[])
{
	bool ret = true;
	struct interface *ifaces;
	struct tevent_context *ev;
	poptContext pc;
	int opt;
	enum {
		OPT_BROADCAST_ADDRESS	= 1000,
		OPT_UNICAST_ADDRESS,
		OPT_FIND_MASTER,
		OPT_WINS_LOOKUP,
		OPT_NODE_STATUS,
		OPT_ROOT_PORT,
		OPT_LOOKUP_BY_IP,
		OPT_CASE_SENSITIVE
	};
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{ "broadcast", 'B', POPT_ARG_STRING, NULL, OPT_BROADCAST_ADDRESS,
		  "Specify address to use for broadcasts", "BROADCAST-ADDRESS" },

		{ "unicast", 'U', POPT_ARG_STRING, NULL, OPT_UNICAST_ADDRESS,
		  "Specify address to use for unicast", NULL },

		{ "master-browser", 'M', POPT_ARG_NONE, NULL, OPT_FIND_MASTER,
		  "Search for a master browser", NULL },

		{ "wins", 'W', POPT_ARG_NONE, NULL, OPT_WINS_LOOKUP,
		  "Do a WINS lookup", NULL },

		{ "status", 'S', POPT_ARG_NONE, NULL, OPT_NODE_STATUS, 
		  "Lookup node status as well", NULL },

		{ "root-port", 'r', POPT_ARG_NONE, NULL, OPT_ROOT_PORT, 
		  "Use root port 137 (Win95 only replies to this)", NULL },

		{ "lookup-by-ip", 'A', POPT_ARG_NONE, NULL, OPT_LOOKUP_BY_IP, 
		  "Do a node status on <name> as an IP Address", NULL },

		{ "case-sensitive", 0, POPT_ARG_NONE, NULL, OPT_CASE_SENSITIVE, 
		  "Don't uppercase the name before sending", NULL },

		POPT_COMMON_SAMBA
		{ 0, 0, 0, 0 }
	};
	
	pc = poptGetContext("nmblookup", argc, argv, long_options, 
			    POPT_CONTEXT_KEEP_FIRST);

	poptSetOtherOptionHelp(pc, "<NODE> ...");

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch(opt) {
		case OPT_BROADCAST_ADDRESS:
			options.broadcast_address = poptGetOptArg(pc);
			break;
		case OPT_UNICAST_ADDRESS:
			options.unicast_address = poptGetOptArg(pc);
			break;
		case OPT_FIND_MASTER:
			options.find_master = true;
			break;
		case OPT_WINS_LOOKUP:
			options.wins_lookup = true;
			break;
		case OPT_NODE_STATUS:
			options.node_status = true;
			break;
		case OPT_ROOT_PORT:
			options.root_port = true;
			break;
		case OPT_LOOKUP_BY_IP:
			options.lookup_by_ip = true;
			break;
		case OPT_CASE_SENSITIVE:
			options.case_sensitive = true;
			break;
		}
	}

	/* swallow argv[0] */
	poptGetArg(pc);

	if(!poptPeekArg(pc)) { 
		poptPrintUsage(pc, stderr, 0);
		exit(1);
	}

	load_interfaces(NULL, lp_interfaces(cmdline_lp_ctx), &ifaces);

	ev = s4_event_context_init(talloc_autofree_context());

	while (poptPeekArg(pc)) {
		const char *name = poptGetArg(pc);

		ret &= process_one(cmdline_lp_ctx, ev, ifaces, name, lp_nbt_port(cmdline_lp_ctx));
	}

	talloc_free(ev);

	talloc_free(ifaces);

	poptFreeContext(pc);

	if (!ret) {
		return 1;
	}

	return 0;
}
Exemplo n.º 25
0
int main(int argc, const char **argv)
{
	poptContext pc;
	int opt;

	static struct poptOption wbinfo_options[] = {
		{ "timeout", 't', POPT_ARG_INT, &timeout, 't', 
		  "Set timeout value in seconds", "TIMEOUT" },

		{ "configfile", 's', POPT_ARG_STRING, NULL, 's', 
		  "Use alternative configuration file", "CONFIGFILE" },

		POPT_TABLEEND
	};

	struct poptOption options[] = {
		{ NULL, 0, POPT_ARG_INCLUDE_TABLE, wbinfo_options, 0, 
		  "Options" },

		POPT_AUTOHELP
		POPT_COMMON_VERSION
		POPT_TABLEEND
	};

	setup_logging(argv[0],True);
	
	/* Parse command line arguments using popt */

	pc = poptGetContext(
		"smbcontrol", argc, (const char **)argv, options, 0);

	poptSetOtherOptionHelp(pc, "[OPTION...] <destination> <message-type> "
			       "<parameters>");

	if (argc == 1)
		usage(&pc);

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch(opt) {
		case 't':	/* --timeout */
			argc -= 2;
			break;
		case 's':	/* --configfile */
			pstrcpy(dyn_CONFIGFILE, poptGetOptArg(pc));
			argc -= 2;
			break;
		default:
			fprintf(stderr, "Invalid option\n");
			poptPrintHelp(pc, stderr, 0);
			break;
		}
	}

	/* We should now have the remaining command line arguments in
           argv.  The argc parameter should have been decremented to the
           correct value in the above switch statement. */

	argv = (const char **)poptGetArgs(pc);
	argc--;			/* Don't forget about argv[0] */

	if (argc == 1)
		usage(&pc);

	lp_load(dyn_CONFIGFILE,False,False,False);

	/* Need to invert sense of return code -- samba
         * routines mostly return True==1 for success, but
         * shell needs 0. */ 
	
	return !do_command(argc, argv);
}
Exemplo n.º 26
0
/**
 * Program entry point
 *
 *	@param argc Number of argv elements
 *	@param argv Program name and arguments
 *	@param envp Program environment
 *	@return <i>0</i> Success
 *	@return <br><i>254</i> Initialization failed
 */
int
main(int argc, char **argv, char **envp)
{
  bk_s B = NULL;				/* Baka general structure */
  BK_ENTRY_MAIN(B, __FUNCTION__, __FILE__, "bttcp");
  int c;
  int getopterr=0;
  extern char *optarg;
  extern int optind;
  struct program_config Pconfig, *pc=NULL;
  poptContext optCon=NULL;
  struct timeval tmstart, tmend;
  struct poptOption optionsTable[] =
  {
    {"debug", 'd', POPT_ARG_NONE, NULL, 'd', "Turn on debugging", NULL },
    {"verbose", 'v', POPT_ARG_NONE, NULL, 'v', "Turn on verbose message", NULL },
    {"no-seatbelts", 0, POPT_ARG_NONE, NULL, 0x1000, "Sealtbelts off & speed up", NULL },
    {"buffersize", 0, POPT_ARG_INT, NULL, 8, "Size of I/O queues", "buffer size" },
    {"length", 'l', POPT_ARG_INT, NULL, 9, "Default I/O chunk size", "default length" },
    POPT_AUTOHELP
    POPT_TABLEEND
  };

  if (!(B=bk_general_init(argc, &argv, &envp, BK_ENV_GWD(B, "BK_ENV_CONF_APP", BK_APP_CONF), NULL, ERRORQUEUE_DEPTH, LOG_LOCAL0, 0)))
  {
    fprintf(stderr,"Could not perform basic initialization\n");
    exit(254);
  }
  bk_fun_reentry(B);

  pc = &Pconfig;
  memset(pc,0,sizeof(*pc));

  if (!(optCon = poptGetContext(NULL, argc, (const char **)argv, optionsTable, 0)))
  {
    bk_error_printf(B, BK_ERR_ERR, "Could not initialize options processing\n");
    bk_exit(B,254);
  }

  while ((c = poptGetNextOpt(optCon)) >= 0)
  {
    switch (c)
    {
    case 'd':					// debug
      bk_error_config(B, BK_GENERAL_ERROR(B), 0, stderr, 0, 0, BK_ERROR_CONFIG_FH);	// Enable output of all error logs
      bk_general_debug_config(B, stderr, BK_ERR_NONE, 0);				// Set up debugging, from config file
      bk_debug_printf(B, "Debugging on\n");
      break;
    case 'v':					// verbose
      BK_FLAG_SET(pc->pc_flags, PC_VERBOSE);
      bk_error_config(B, BK_GENERAL_ERROR(B), ERRORQUEUE_DEPTH, stderr, BK_ERR_NONE, BK_ERR_ERR, 0);
      break;
    case 0x1000:				// no-seatbelts
      BK_FLAG_CLEAR(BK_GENERAL_FLAGS(B), BK_BGFLAGS_FUNON);
      break;
    default:
      getopterr++;
      break;

    case 8:					// Buffer size
      pc->pc_buffer = atoi(poptGetOptArg(optCon));
      break;

    case 9:					// Default I/O chunks
      pc->pc_len = atoi(poptGetOptArg(optCon));
      break;

    }
  }

  if (c < -1 || getopterr)
  {
    if (c < -1)
    {
      fprintf(stderr, "%s\n", poptStrerror(c));
    }
    poptPrintUsage(optCon, stderr, 0);
    bk_exit(B, 254);
  }

  if (proginit(B, pc) < 0)
  {
    bk_die(B, 254, stderr, "Could not perform program initialization\n", BK_FLAG_ISSET(pc->pc_flags, PC_VERBOSE)?BK_WARNDIE_WANTDETAILS:0);
  }

  gettimeofday(&tmstart, NULL);

  if (bk_run_run(B,pc->pc_run, 0)<0)
  {
    bk_die(B, 1, stderr, "Failure during run_run\n", BK_FLAG_ISSET(pc->pc_flags, PC_VERBOSE)?BK_WARNDIE_WANTDETAILS:0);
  }

  gettimeofday(&tmend, NULL);

  BK_TV_SUB(&tmend, &tmend, &tmstart);
  fprintf(stderr,"%d.%06d\n",(int)tmend.tv_sec, (int)tmend.tv_usec);

  bk_exit(B, 0);
  return(255);
}
Exemplo n.º 27
0
/**
 * Program entry point
 *
 *	@param argc Number of argv elements
 *	@param argv Program name and arguments
 *	@param envp Program environment
 *	@return <i>0</i> Success
 *	@return <br><i>254</i> Initialization failed
 */
int
main(int argc, char **argv, char **envp)
{
  bk_s B = NULL;				/* Baka general structure */
  BK_ENTRY_MAIN(B, __FUNCTION__, __FILE__, "SIMPLE");
  int c;
  int getopterr = 0;
  int debug_level = 0;
  char i18n_localepath[_POSIX_PATH_MAX];
  char *i18n_locale;
  struct program_config Pconfig, *pc = NULL;
  poptContext optCon = NULL;
  struct poptOption optionsTable[] =
  {
    {"debug", 'd', POPT_ARG_NONE, NULL, 'd', N_("Turn on debugging"), NULL },
    {"verbose", 'v', POPT_ARG_NONE, NULL, 'v', N_("Turn on verbose message"), NULL },
    {"no-seatbelts", 0, POPT_ARG_NONE, NULL, 0x1000, N_("Sealtbelts off & speed up"), NULL },
    {"seatbelts", 0, POPT_ARG_NONE, NULL, 0x1001, N_("Enable function tracing"), NULL },
    {"profiling", 0, POPT_ARG_STRING, NULL, 0x1002, N_("Enable and write profiling data"), N_("filename") },

    // XXX - customize here
    {"person", 'p', POPT_ARG_STRING, NULL, 'p', N_("Set the person to greet"), N_("person") },
    {"long-arg-only", 0, POPT_ARG_NONE, NULL, 1, N_("An example of a long argument without a shortcut"), NULL },
    {NULL, 's', POPT_ARG_NONE, NULL, 2, N_("An example of a short argument without a longcut"), NULL },
    POPT_AUTOHELP
    POPT_TABLEEND
  };

  if (!(B=bk_general_init(argc, &argv, &envp, BK_ENV_GWD(NULL, "BK_ENV_CONF_APP", BK_APP_CONF), NULL, ERRORQUEUE_DEPTH, LOG_LOCAL0, 0)))
  {
    fprintf(stderr,"Could not perform basic initialization\n");
    exit(254);
  }
  bk_fun_reentry(B);

  // i18n stuff
  setlocale(LC_ALL, "");
  if (!(i18n_locale = BK_GWD(B, STD_LOCALEDIR_KEY, NULL)))
  {
    i18n_locale = i18n_localepath;
    snprintf(i18n_localepath, sizeof(i18n_localepath), "%s/%s", BK_ENV_GWD(B, STD_LOCALEDIR_ENV,STD_LOCALEDIR_DEF), STD_LOCALEDIR_SUB);
  }
  bindtextdomain(BK_GENERAL_PROGRAM(B), i18n_locale);
  textdomain(BK_GENERAL_PROGRAM(B));
  for (c = 0; optionsTable[c].longName || optionsTable[c].shortName; c++)
  {
    if (optionsTable[c].descrip) (*((char **)&(optionsTable[c].descrip)))=_(optionsTable[c].descrip);
    if (optionsTable[c].argDescrip) (*((char **)&(optionsTable[c].argDescrip)))=_(optionsTable[c].argDescrip);
  }

  pc = &Pconfig;
  memset(pc, 0, sizeof(*pc));
  // XXX - customize here

  if (!(optCon = poptGetContext(NULL, argc, (const char **)argv, optionsTable, 0)))
  {
    bk_error_printf(B, BK_ERR_ERR, "Could not initialize options processing\n");
    bk_exit(B, 254);
  }
  // XXX - customize here
  poptSetOtherOptionHelp(optCon, _("[NON-FLAG ARGUMENTS]"));

  while ((c = poptGetNextOpt(optCon)) >= 0)
  {
    switch (c)
    {
    case 'd':					// debug
      if (!debug_level)
      {
	// Set up debugging, from config file
	bk_general_debug_config(B, stderr, BK_ERR_NONE, 0);
	bk_debug_printf(B, "Debugging on\n");
	debug_level++;
      }
      else if (debug_level == 1)
      {
	/*
	 * Enable output of error and higher error logs (this can be
	 * annoying so require -dd)
	 */
	bk_error_config(B, BK_GENERAL_ERROR(B), 0, stderr, BK_ERR_NONE, BK_ERR_ERR, BK_ERROR_CONFIG_FH | BK_ERROR_CONFIG_HILO_PIVOT | BK_ERROR_CONFIG_SYSLOGTHRESHOLD);
	bk_debug_printf(B, "Extra debugging on\n");
	debug_level++;
      }
      else if (debug_level == 2)
      {
	/*
	 * Enable output of all levels of bk_error logs (this can be
	 * very annoying so require -ddd)
	 */
	bk_error_config(B, BK_GENERAL_ERROR(B), 0, stderr, BK_ERR_NONE, BK_ERR_DEBUG, BK_ERROR_CONFIG_FH | BK_ERROR_CONFIG_HILO_PIVOT | BK_ERROR_CONFIG_SYSLOGTHRESHOLD);
	bk_debug_printf(B, "Super-extra debugging on\n");
	debug_level++;
      }
      break;
    case 'v':					// verbose
      BK_FLAG_SET(pc->pc_flags, PC_VERBOSE);
      bk_error_config(B, BK_GENERAL_ERROR(B), ERRORQUEUE_DEPTH, stderr, BK_ERR_NONE, BK_ERR_ERR, 0);
      break;
    case 0x1000:				// no-seatbelts
      BK_FLAG_CLEAR(BK_GENERAL_FLAGS(B), BK_BGFLAGS_FUNON);
      break;
    case 0x1001:				// seatbelts
      BK_FLAG_SET(BK_GENERAL_FLAGS(B), BK_BGFLAGS_FUNON);
      break;
    case 0x1002:				// profiling
      bk_general_funstat_init(B, (char *)poptGetOptArg(optCon), 0);
      break;
    default:
      getopterr++;
      break;

    // XXX - customize here
    case 'p':					// person
      pc->pc_person = poptGetOptArg(optCon);
      break;
    case 1:					// long-arg-only
      printf("You specificed the long-arg-only option\n");
      break;
    case 2:					// s
      printf("You specificed the short only option\n");
      break;
    }
  }

  /*
   * Reprocess so that argc and argv contain the remaining command
   * line arguments (note argv[0] is an argument, not the program
   * name).  argc remains the number of elements in the argv array.
   */
  argv = (char **)poptGetArgs(optCon);
  argc = 0;
  if (argv)
    for (; argv[argc]; argc++)
      ; // Void

  // XXX - customize here (argv test)
  if (c < -1 || getopterr)
  {
    if (c < -1)
    {
      fprintf(stderr, "%s\n", poptStrerror(c));
    }
    poptPrintUsage(optCon, stderr, 0);
    bk_exit(B, 254);
  }

  if (proginit(B, pc) < 0)
  {
    bk_die(B, 254, stderr, _("Could not perform program initialization\n"), BK_FLAG_ISSET(pc->pc_flags, PC_VERBOSE)?BK_WARNDIE_WANTDETAILS:0);
  }

  progrun(B, pc);

  poptFreeContext(optCon);
  bk_exit(B, 0);
  return(255);					// Stupid INSIGHT stuff.
}
Exemplo n.º 28
0
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc, const char **argv)
{
	int opt,i;
	char *p;
	int rc = 0;
	int argc_new = 0;
	const char ** argv_new;
	poptContext pc;
	TALLOC_CTX *frame = talloc_stackframe();
	struct net_context *c = talloc_zero(frame, struct net_context);

	struct poptOption long_options[] = {
		{"help",	'h', POPT_ARG_NONE,   0, 'h'},
		{"workgroup",	'w', POPT_ARG_STRING, &c->opt_target_workgroup},
		{"user",	'U', POPT_ARG_STRING, &c->opt_user_name, 'U'},
		{"ipaddress",	'I', POPT_ARG_STRING, 0,'I'},
		{"port",	'p', POPT_ARG_INT,    &c->opt_port},
		{"myname",	'n', POPT_ARG_STRING, &c->opt_requester_name},
		{"server",	'S', POPT_ARG_STRING, &c->opt_host},
		{"encrypt",	'e', POPT_ARG_NONE,   NULL, 'e', "Encrypt SMB transport (UNIX extended servers only)" },
		{"container",	'c', POPT_ARG_STRING, &c->opt_container},
		{"comment",	'C', POPT_ARG_STRING, &c->opt_comment},
		{"maxusers",	'M', POPT_ARG_INT,    &c->opt_maxusers},
		{"flags",	'F', POPT_ARG_INT,    &c->opt_flags},
		{"long",	'l', POPT_ARG_NONE,   &c->opt_long_list_entries},
		{"reboot",	'r', POPT_ARG_NONE,   &c->opt_reboot},
		{"force",	'f', POPT_ARG_NONE,   &c->opt_force},
		{"stdin",	'i', POPT_ARG_NONE,   &c->opt_stdin},
		{"timeout",	't', POPT_ARG_INT,    &c->opt_timeout},
		{"request-timeout",0,POPT_ARG_INT,    &c->opt_request_timeout},
		{"machine-pass",'P', POPT_ARG_NONE,   &c->opt_machine_pass},
		{"kerberos",    'k', POPT_ARG_NONE,   &c->opt_kerberos},
		{"myworkgroup", 'W', POPT_ARG_STRING, &c->opt_workgroup},
		{"verbose",	'v', POPT_ARG_NONE,   &c->opt_verbose},
		{"test",	'T', POPT_ARG_NONE,   &c->opt_testmode},
		/* Options for 'net groupmap set' */
		{"local",       'L', POPT_ARG_NONE,   &c->opt_localgroup},
		{"domain",      'D', POPT_ARG_NONE,   &c->opt_domaingroup},
		{"ntname",      'N', POPT_ARG_STRING, &c->opt_newntname},
		{"rid",         'R', POPT_ARG_INT,    &c->opt_rid},
		/* Options for 'net rpc share migrate' */
		{"acls",	0, POPT_ARG_NONE,     &c->opt_acls},
		{"attrs",	0, POPT_ARG_NONE,     &c->opt_attrs},
		{"timestamps",	0, POPT_ARG_NONE,     &c->opt_timestamps},
		{"exclude",	'X', POPT_ARG_STRING, &c->opt_exclude},
		{"destination",	0, POPT_ARG_STRING,   &c->opt_destination},
		{"tallocreport", 0, POPT_ARG_NONE,    &c->do_talloc_report},
		/* Options for 'net rpc vampire (keytab)' */
		{"force-full-repl", 0, POPT_ARG_NONE, &c->opt_force_full_repl},
		{"single-obj-repl", 0, POPT_ARG_NONE, &c->opt_single_obj_repl},
		{"clean-old-entries", 0, POPT_ARG_NONE, &c->opt_clean_old_entries},

		POPT_COMMON_SAMBA
		{ 0, 0, 0, 0}
	};


	zero_sockaddr(&c->opt_dest_ip);

	load_case_tables();

	/* set default debug level to 0 regardless of what smb.conf sets */
	DEBUGLEVEL_CLASS[DBGC_ALL] = 0;
	dbf = x_stderr;
	c->private_data = net_func;

	pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
			    POPT_CONTEXT_KEEP_FIRST);

	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case 'h':
			c->display_usage = true;
			break;
		case 'e':
			c->smb_encrypt = true;
			break;
		case 'I':
			if (!interpret_string_addr(&c->opt_dest_ip,
						poptGetOptArg(pc), 0)) {
				d_fprintf(stderr, "\nInvalid ip address specified\n");
			} else {
				c->opt_have_ip = true;
			}
			break;
		case 'U':
			c->opt_user_specified = true;
			c->opt_user_name = SMB_STRDUP(c->opt_user_name);
			p = strchr(c->opt_user_name,'%');
			if (p) {
				*p = 0;
				c->opt_password = p+1;
			}
			break;
		default:
			d_fprintf(stderr, "\nInvalid option %s: %s\n",
				 poptBadOption(pc, 0), poptStrerror(opt));
			net_help(c, argc, argv);
			exit(1);
		}
	}

	/*
	 * Don't load debug level from smb.conf. It should be
	 * set by cmdline arg or remain default (0)
	 */
	AllowDebugChange = false;
	lp_load(get_dyn_CONFIGFILE(), true, false, false, true);

 	argv_new = (const char **)poptGetArgs(pc);

	argc_new = argc;
	for (i=0; i<argc; i++) {
		if (argv_new[i] == NULL) {
			argc_new = i;
			break;
		}
	}

	if (c->do_talloc_report) {
		talloc_enable_leak_report();
	}

	if (c->opt_requester_name) {
		set_global_myname(c->opt_requester_name);
	}

	if (!c->opt_user_name && getenv("LOGNAME")) {
		c->opt_user_name = getenv("LOGNAME");
	}

	if (!c->opt_workgroup) {
		c->opt_workgroup = smb_xstrdup(lp_workgroup());
	}

	if (!c->opt_target_workgroup) {
		c->opt_target_workgroup = smb_xstrdup(lp_workgroup());
	}

	if (!init_names())
		exit(1);

	load_interfaces();

	/* this makes sure that when we do things like call scripts,
	   that it won't assert becouse we are not root */
	sec_init();

	if (c->opt_machine_pass) {
		/* it is very useful to be able to make ads queries as the
		   machine account for testing purposes and for domain leave */

		net_use_krb_machine_account(c);
	}

	if (!c->opt_password) {
		c->opt_password = getenv("PASSWD");
	}

	rc = net_run_function(c, argc_new-1, argv_new+1, "net", net_func);

	DEBUG(2,("return code = %d\n", rc));

	libnetapi_free(c->netapi_ctx);

	poptFreeContext(pc);

	TALLOC_FREE(frame);
	return rc;
}
Exemplo n.º 29
0
/*
 * The 'snapshot <cmd> <options>' first level command
 */
int cmd_snapshot(int argc, const char **argv)
{
	int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
	char *session_name = NULL;
	static poptContext pc;

	pc = poptGetContext(NULL, argc, argv, snapshot_opts, 0);
	poptReadDefaultConfig(pc, 0);

	/* Mi check */
	if (lttng_opt_mi) {
		writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
		if (!writer) {
			ret = -LTTNG_ERR_NOMEM;
			goto end;
		}

		/* Open command element */
		ret = mi_lttng_writer_command_open(writer,
				mi_lttng_element_command_snapshot);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Open output element */
		ret = mi_lttng_writer_open_element(writer,
				mi_lttng_element_command_output);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}
	}

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_HELP:
			usage(stdout);
			goto end;
		case OPT_LIST_OPTIONS:
			list_cmd_options(stdout, snapshot_opts);
			goto end;
		case OPT_LIST_COMMANDS:
			list_commands(actions, stdout);
			goto end;
		case OPT_MAX_SIZE:
		{
			uint64_t val;
			const char *opt = poptGetOptArg(pc);

			if (utils_parse_size_suffix((char *) opt, &val) < 0) {
				ERR("Unable to handle max-size value %s", opt);
				ret = CMD_ERROR;
				goto end;
			}

			opt_max_size = val;

			break;
		}
		default:
			usage(stderr);
			ret = CMD_UNDEFINED;
			goto end;
		}
	}

	if (!opt_session_name) {
		session_name = get_session_name();
		if (session_name == NULL) {
			ret = CMD_ERROR;
			goto end;
		}
		current_session_name = session_name;
	} else {
		current_session_name = opt_session_name;
	}

	command_ret = handle_command(poptGetArgs(pc));
	if (command_ret) {
		switch (-command_ret) {
		case LTTNG_ERR_EPERM:
			ERR("The session needs to be set in no output mode (--no-output)");
			break;
		case LTTNG_ERR_SNAPSHOT_NODATA:
			WARN("%s", lttng_strerror(command_ret));
			break;
		default:
			ERR("%s", lttng_strerror(command_ret));
			break;
		}
		success = 0;
	}

	if (lttng_opt_mi) {
		/* Close output element */
		ret = mi_lttng_writer_close_element(writer);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Success ? */
		ret = mi_lttng_writer_write_element_bool(writer,
				mi_lttng_element_command_success, success);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Command element close */
		ret = mi_lttng_writer_command_close(writer);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}
	}

end:
	/* Mi clean-up */
	if (writer && mi_lttng_writer_destroy(writer)) {
		/* Preserve original error code */
		ret = ret ? ret : -LTTNG_ERR_MI_IO_FAIL;
	}

	if (!opt_session_name) {
		free(session_name);
	}

	/* Overwrite ret if an error occured during handle_command */
	ret = command_ret ? command_ret : ret;
	poptFreeContext(pc);
	return ret;
}
Exemplo n.º 30
0
boolean rmdParseArgs(int argc, char **argv, ProgArgs *arg_return) {
    poptContext popt_context = NULL;
    boolean no_cursor = FALSE;
    boolean quick_subsampling = FALSE;
    boolean compress_cache = FALSE;
    boolean success = TRUE;
    int arg_id = 0;

    // Setup the option tables
    struct poptOption generic_options[] = {
        { NULL, '\0',
          POPT_ARG_CALLBACK, (void *)rmdPrintAndExit, 0,
          NULL, NULL },

        { "help", 'h',
          POPT_ARG_NONE, NULL, 0,
          "Print this help and exit.",
          NULL },

        { "version", '\0',
          POPT_ARG_NONE, NULL, 0,
          "Print program version and exit.",
          NULL },

        { "print-config", '\0',
          POPT_ARG_NONE, NULL, 0,
          "Print info about options selected during compilation and exit.",
          NULL },

        POPT_TABLEEND };

    struct poptOption image_options[] = {
        { "windowid", '\0',
          POPT_ARG_INT, &arg_return->windowid, 0,
          "id of window to be recorded.",
          "id_of_window" },

        { "display", '\0',
          POPT_ARG_STRING, &arg_return->display, 0,
          "Display to connect to.",
          "DISPLAY" },

        { "x", 'x',
          POPT_ARG_INT, &arg_return->x, 0,
          "Offset in x direction.",
          "N>=0" },

        { "y", 'y',
          POPT_ARG_INT, &arg_return->y, 0,
          "Offset in y direction.",
          "N>=0" },

        { "width", '\0',
          POPT_ARG_INT, &arg_return->width, 0,
          "Width of recorded window.",
          "N>0" },

        { "height", '\0',
          POPT_ARG_INT, &arg_return->height, 0,
          "Height of recorded window.",
          "N>0" },

        { "dummy-cursor", '\0',
          POPT_ARG_STRING, NULL, RMD_ARG_DUMMY_CURSOR,
          "Color of the dummy cursor [black|white]",
          "color" },

        { "no-cursor", '\0',
          POPT_ARG_NONE, &no_cursor, 0,
          "Disable drawing of the cursor.",
          NULL },

        { "no-shared", '\0',
          POPT_ARG_NONE, &arg_return->noshared, 0,
          "Disable usage of MIT-shared memory extension(Not Recommended!).",
          NULL },

        { "full-shots", '\0',
          POPT_ARG_NONE, &arg_return->full_shots, 0,
          "Take full screenshot at every frame(Not recomended!).",
          NULL },

        { "follow-mouse", '\0',
          POPT_ARG_NONE, &arg_return->follow_mouse, 0,
          "Makes the capture area follow the mouse cursor. Autoenables --full-shots.",
          NULL },

        { "quick-subsampling", '\0',
          POPT_ARG_NONE, &quick_subsampling, 0,
          "Do subsampling of the chroma planes by discarding, not averaging.",
          NULL },

        { "fps", '\0',
          POPT_ARG_FLOAT, &arg_return->fps, 0,
          "A positive number denoting desired framerate.",
          "N(number>0.0)" },

        POPT_TABLEEND };

    struct poptOption sound_options[] = {
        { "channels", '\0',
          POPT_ARG_INT, &arg_return->channels, 0,
          "A positive number denoting desired sound channels in recording.",
          "N" },

        { "freq", '\0',
          POPT_ARG_INT, &arg_return->frequency, 0,
          "A positive number denoting desired sound frequency.",
          "N" },

        { "buffer-size", '\0',
          POPT_ARG_INT, &arg_return->buffsize, 0,
          "A positive number denoting the desired sound buffer size (in frames,when using ALSA or OSS)",
          "N" },

        { "ring-buffer-size", '\0',
          POPT_ARG_FLOAT, &arg_return->jack_ringbuffer_secs, 0,
          "A float number denoting the desired ring buffer size (in seconds,when using JACK only).",
          "N" },

        { "device", '\0',
          POPT_ARG_STRING, &arg_return->device, 0,
          "Sound device(default " DEFAULT_AUDIO_DEVICE ").",
          "SOUND_DEVICE" },

        { "use-jack", '\0',
          POPT_ARG_STRING | RMD_USE_JACK_EXTRA_FLAG, NULL, RMD_ARG_USE_JACK,
          "Record audio from the specified list of space-separated jack ports.",
          "port1 port2... portn" },

        { "no-sound", '\0',
          POPT_ARG_NONE, &arg_return->nosound, 0,
          "Do not record sound.",
          NULL },

        POPT_TABLEEND };

    struct poptOption encoding_options[] = {
        { "on-the-fly-encoding", '\0',
          POPT_ARG_NONE, &arg_return->encOnTheFly, 0,
          "Encode the audio-video data, while recording.",
          NULL },

        { "v_quality", '\0',
          POPT_ARG_INT, &arg_return->v_quality, 0,
          "A number from 0 to 63 for desired encoded video quality(default 63).",
          "n" },

        { "v_bitrate", '\0',
          POPT_ARG_INT, &arg_return->v_bitrate, 0,
          "A number from 45000 to 2000000 for desired encoded video bitrate(default 45000).",
          "n" },

        { "s_quality", '\0',
          POPT_ARG_INT, &arg_return->s_quality, 0,
          "Desired audio quality(-1 to 10).",
          "n" },

        POPT_TABLEEND };

    struct poptOption misc_options[] = {
        { "rescue", '\0',
          POPT_ARG_STRING, &arg_return->rescue_path, 0,
          "Encode data from a previous, crashed, session.",
          "path_to_data" },

        { "no-encode", '\0',
          POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN, &arg_return->no_encode, 0,
          "Do not encode any data after recording is complete. This is instead done manually afterwards with --rescue.",
          NULL },

        { "no-wm-check", '\0',
          POPT_ARG_NONE, &arg_return->nowmcheck, 0,
          "Do not try to detect the window manager(and set options according to it)",
          NULL },

        { "no-frame", '\0',
          POPT_ARG_NONE, &arg_return->noframe, 0,
          "Don not show the frame that visualizes the recorded area.",
          NULL },

        { "pause-shortcut", '\0',
          POPT_ARG_STRING, &arg_return->pause_shortcut, 0,
          "Shortcut that will be used for (un)pausing (default Control+Mod1+p).",
          "MOD+KEY" },

        { "stop-shortcut", '\0',
          POPT_ARG_STRING, &arg_return->stop_shortcut, 0,
          "Shortcut that will be used to stop the recording (default Control+Mod1+s).",
          "MOD+KEY" },

        { "compress-cache", '\0',
          POPT_ARG_NONE, &compress_cache, 0,
          "Image data are cached with light compression.",
          NULL },

        { "workdir", '\0',
          POPT_ARG_STRING, &arg_return->workdir, 0,
          "Location where a temporary directory will be created to hold project files(default $HOME).",
          "DIR" },

        { "delay", '\0',
          POPT_ARG_STRING, &arg_return->delay, RMD_ARG_DELAY,
          "Number of secs(default),minutes or hours before capture starts(number can be float)",
          "n[H|h|M|m]" },

        { "overwrite", '\0',
          POPT_ARG_NONE, &arg_return->overwrite, 0,
          "If there is already a file with the same name, delete it (default is to add a number postfix to the new one).",
          NULL },

        { "output", 'o',
          POPT_ARG_STRING, &arg_return->filename, 0,
          "Name of recorded video(default out.ogv).",
          "filename" },

        POPT_TABLEEND };

    struct poptOption rmd_args[] = {
        RMD_OPTION_TABLE("Generic Options", generic_options),
        RMD_OPTION_TABLE("Image Options", image_options),
        RMD_OPTION_TABLE("Sound Options", sound_options),
        RMD_OPTION_TABLE("Encoding Options", encoding_options),
        RMD_OPTION_TABLE("Misc Options", misc_options),
        POPT_TABLEEND };


    // Some trivial setup
    popt_context = poptGetContext(NULL, argc, (const char **)argv, rmd_args, 0);
    poptSetOtherOptionHelp(popt_context, "[OPTIONS]^filename");


    // Parse the arguments
    while ((arg_id = poptGetNextOpt(popt_context)) > 0) {
        char *arg = poptGetOptArg(popt_context);

        // Most arguments are handled completely by libpopt but we
        // handle some by ourself, namely those in this switch case
        switch (arg_id) {
            case RMD_ARG_DELAY:
            {
                float num = atof(arg);

                if (num > 0.0) {
                    int k;
                    for (k = 0; k < strlen(arg); k++) {
                        if ((arg[k] == 'M') || (arg[k] == 'm')) {
                            num *= 60.0;
                            break;
                        }
                        else if ((arg[k] == 'H') || (arg[k] == 'h')) {
                            num *= 3600.0;
                            break;
                        }
                    }
                    arg_return->delay = (int) num;
                }
                else {
                    fprintf(stderr,
                            "Argument Usage: --delay n[H|h|M|m]\n"
                            "where n is a float number\n");
                    success = FALSE;
                }
            }
            break;

            case RMD_ARG_DUMMY_CURSOR:
            {
                if (!strcmp(arg, "white"))
                    arg_return->cursor_color = 0;
                else if (!strcmp(arg, "black"))
                    arg_return->cursor_color = 1;
                else {
                    fprintf(stderr,
                            "Argument Usage:\n"
                            " --dummy-cursor [black|white]\n");
                    success = FALSE;
                }
                arg_return->have_dummy_cursor = TRUE;
                arg_return->xfixes_cursor = FALSE;
            }
            break;

            case RMD_ARG_USE_JACK:
            {
                arg_return->jack_nports = 0;

                while (arg) {

                    arg_return->jack_nports++;

                    arg_return->jack_port_names[arg_return->jack_nports - 1] = malloc(strlen(arg) + 1);
                    strcpy(arg_return->jack_port_names[arg_return->jack_nports - 1], arg);

                    arg = poptGetOptArg(popt_context);
                }

                if (arg_return->jack_nports > 0) {
                    arg_return->use_jack = 1;
                }
                else {
                    fprintf(stderr,
                            "Argument Usage: --use-jack port1 port2... portn\n");
                    success = FALSE;
                }

                if (RMD_USE_JACK_EXTRA_FLAG == POPT_ARGFLAG_DOC_HIDDEN) {
                    fprintf(stderr,
                            "Warning, will ignore --use-jack flags, no libjack support in build.\n");
                }
            }                

            default:
                break;
        }
    }

    if (arg_id == -1) {
        // Parsing is complete, perform final adjustments
        if (no_cursor)
            arg_return->xfixes_cursor = FALSE;

        if (quick_subsampling)
            arg_return->no_quick_subsample = FALSE;

        if (compress_cache)
            arg_return->zerocompression = FALSE;

        if (arg_return->follow_mouse)
            arg_return->full_shots = TRUE;

        if (!arg_return->filename)
            arg_return->filename = strdup(poptGetArg(popt_context));
    }
    else {
        // Parsing error, say what went wrong
        const char *str = poptBadOption(popt_context, 0);

        success = FALSE;

        fprintf(stderr,
                "Error when parsing `%s': ", str);

        switch (arg_id) {
            case POPT_ERROR_NOARG:
                fprintf(stderr, "Missing argument\n");
                break;
                        
            case POPT_ERROR_BADNUMBER:
                fprintf(stderr, "Bad number\n");
                break;
                        
            default:
                fprintf(stderr, "libpopt error: %d\n", arg_id);
                break;
        }
    }
    
    // Make sure argument ranges are valid
    success = success && rmdValidateArguments(arg_return);

    // Clean up
    poptFreeContext(popt_context);
    
    return success;
}