コード例 #1
0
ファイル: extoll_pp_velo.c プロジェクト: ParaStation/pscom
static
void parse_opt(int argc, char **argv)
{
	int c;
	poptContext optCon;
	const char *no_arg;

	struct poptOption optionsTable[] = {
		{ "loops"  , 'n', POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_INT,
		  &arg_loops , 0, "pp loops", "count" },
		{ "time"  , 't', POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_INT,
		  &arg_maxtime, 0, "max time", "ms" },
		{ "maxsize"  , 0, POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_INT,
		  &arg_maxmsize , 0, "maximal messagesize", "size" },

		{ "nokill" , 'k', POPT_ARGFLAG_OR | POPT_ARG_VAL,
		  &arg_nokill, 1, "Dont kill the server afterwards", NULL },

		{ "port" , 'p', POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_STRING,
		  &arg_port, 0, "server port to use", "port" },

		{ "verbose"	, 'v', POPT_ARG_NONE,
		  NULL		, 'v', "increase verbosity", NULL },
		POPT_AUTOHELP
		POPT_TABLEEND
	};

	optCon = poptGetContext(NULL, argc, (const char **) argv, optionsTable, 0);

	poptSetOtherOptionHelp(optCon, "[serveraddr]");

	while ((c = poptGetNextOpt(optCon)) >= 0) {
		switch (c) { // c = poptOption.val;
		case 'v': arg_verbose++; break;
		}
	}

	if (c < -1) { /* an error occurred during option processing */
		fprintf(stderr, "%s: %s\n",
			poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
			poptStrerror(c));
		poptPrintHelp(optCon, stderr, 0);
		exit(1);
	}

//	arg_1 = poptGetArg(optCon);
//	arg_2 = poptGetArg(optCon);
	arg_servername = poptGetArg(optCon);
	is_server = !arg_servername;

	no_arg = poptGetArg(optCon); // should return NULL
	if (no_arg) {
		fprintf(stderr, "%s: %s\n",
			no_arg, poptStrerror(POPT_ERROR_BADOPT));
		poptPrintHelp(optCon, stderr, 0);
		exit(1);
	}

	poptFreeContext(optCon);
}
コード例 #2
0
ファイル: dapl_pp.c プロジェクト: JonBau/pscom
static
void parse_opt(int argc, char **argv)
{
	int c;
	poptContext optCon;
	const char *no_arg;

	struct poptOption optionsTable[] = {
		{ "loops"  , 'n', POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_INT,
		  &arg_loops , 0, "pp loops", "count" },
		{ "time"  , 't', POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_INT,
		  &arg_maxtime, 0, "max time", "ms" },
		{ "maxsize"  , 0, POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_INT,
		  &arg_maxmsize , 0, "maximal messagesize", "size" },

		{ "once" , '1', POPT_ARGFLAG_OR | POPT_ARG_VAL,
		  &arg_run_once, 1, "stop after one client", NULL },

		{ "verbose"	, 'v', POPT_ARG_NONE,
		  NULL		, 'v', "increase verbosity", NULL },
		POPT_AUTOHELP
		POPT_TABLEEND
	};

	optCon = poptGetContext(NULL, argc, (const char **) argv, optionsTable, 0);

	poptSetOtherOptionHelp(optCon, "[serveraddr]");

	while ((c = poptGetNextOpt(optCon)) >= 0) {
		switch (c) { // c = poptOption.val;
		case 'v': arg_verbose++; break;
		//default: fprintf(stderr, "unhandled popt value %d\n", c); break;
		}
	}

	if (c < -1) { /* an error occurred during option processing */
		fprintf(stderr, "%s: %s\n",
			poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
			poptStrerror(c));
		poptPrintHelp(optCon, stderr, 0);
		exit(1);
	}

//	arg_1 = poptGetArg(optCon);
//	arg_2 = poptGetArg(optCon);
	/* if (arg_client)*/ {
		const char *server = poptGetArg(optCon);
		if (server) arg_server_addr = server;
	}

	no_arg = poptGetArg(optCon); // should return NULL
	if (no_arg) {
		fprintf(stderr, "%s: %s\n",
			no_arg, poptStrerror(POPT_ERROR_BADOPT));
		poptPrintHelp(optCon, stderr, 0);
		exit(1);
	}

	poptFreeContext(optCon);
}
コード例 #3
0
ファイル: pscom_ondemand.c プロジェクト: ParaStation/pscom
void parse_opt(int argc, char **argv)
{
	int c;
	poptContext optCon;
	const char *no_arg;

	struct poptOption optionsTable[] = {
		{ "send" , 's', POPT_ARGFLAG_OR | POPT_ARG_VAL,
		  &arg_send, 1, "first send", NULL },

		{ "lport"	, 'l', POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_INT,
		  &arg_listenport, 0, "listen on port", "port" },

		{ "lname"	, 'n', POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_STRING,
		  &arg_listenname, 0, "listen on name", "name" },

		{ "verbose"	, 'v', POPT_ARG_NONE,
		  NULL		, 'v', "increase verbosity", NULL },
		POPT_AUTOHELP
		POPT_TABLEEND
	};

	optCon = poptGetContext(NULL, argc, (const char **) argv, optionsTable, 0);

	poptSetOtherOptionHelp(optCon, "[peer address]");

	while ((c = poptGetNextOpt(optCon)) >= 0) {
		switch (c) { // c = poptOption.val;
		case 'v': arg_verbose++; break;
		//default: fprintf(stderr, "unhandled popt value %d\n", c); break;
		}
	}

	if (c < -1) { /* an error occurred during option processing */
		fprintf(stderr, "%s: %s\n",
			poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
			poptStrerror(c));
		poptPrintHelp(optCon, stderr, 0);
		exit(1);
	}

	{
		const char *s;
		s = poptGetArg(optCon);
		if (s) {
			arg_peer_str = s;
		}
	}

	no_arg = poptGetArg(optCon); // should return NULL
	if (no_arg) {
		fprintf(stderr, "%s: %s\n",
			no_arg, poptStrerror(POPT_ERROR_BADOPT));
		poptPrintHelp(optCon, stderr, 0);
		exit(1);
	}

	poptFreeContext(optCon);
}
コード例 #4
0
ファイル: oml2-proxy-server.c プロジェクト: stojadin/oml
int
main(int argc, const char *argv[])
{
  Socket* serverSock, *controlSock;
  int c;

  poptContext optCon = poptGetContext(NULL, argc, argv, options, 0);
  poptSetOtherOptionHelp(optCon, "configFile");

  while ((c = poptGetNextOpt(optCon)) >= 0) {
    switch (c) {
    case 'v':
      printf(V_STRING, VERSION);
      printf(COPYRIGHT);
      return 0;
    }
  }

  setup_logging (logfile_name, log_level);

  if (c < -1) {
    /* an error occurred during option processing */
    fprintf(stderr, "%s: %s\n",
      poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
      poptStrerror(c));
    return -1;
  }

  loginfo (V_STRING, VERSION);
  loginfo (COPYRIGHT);

  struct sigaction new_action, old_action;
  new_action.sa_handler = sigpipe_handler;
  sigemptyset (&new_action.sa_mask);
  new_action.sa_flags = 0;
  sigaction (SIGPIPE, NULL, &old_action);
  if (old_action.sa_handler != SIG_IGN)
    sigaction (SIGPIPE, &new_action, NULL);

  prepare_stdin(NULL);

  eventloop_init();
  session = (Session*) malloc(sizeof(Session));
  memset(session, 0, sizeof(Session));

  session->state = ProxyState_PAUSED;

  serverSock = socket_server_new("proxy_server", listen_port, on_connect, NULL);
  controlSock = socket_server_new("proxy_server_control", listen_port + 1, on_control_connect, NULL);

  eventloop_on_stdin(stdin_handler, session);
  eventloop_run();

  socket_free(serverSock);
  socket_free(controlSock);

  return(0);
}
コード例 #5
0
ファイル: getdc.c プロジェクト: ElijahLuk/samba
int main(int argc, const char **argv)
{
    NET_API_STATUS status;
    struct libnetapi_ctx *ctx = NULL;

    const char *hostname = NULL;
    const char *domain = NULL;
    uint8_t *buffer = NULL;

    poptContext pc;
    int opt;

    struct poptOption long_options[] = {
        POPT_AUTOHELP
        POPT_COMMON_LIBNETAPI_EXAMPLES
        POPT_TABLEEND
    };

    status = libnetapi_init(&ctx);
    if (status != 0) {
        return status;
    }

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

    poptSetOtherOptionHelp(pc, "hostname domainname");
    while((opt = poptGetNextOpt(pc)) != -1) {
    }

    if (!poptPeekArg(pc)) {
        poptPrintHelp(pc, stderr, 0);
        goto out;
    }
    hostname = poptGetArg(pc);

    if (!poptPeekArg(pc)) {
        poptPrintHelp(pc, stderr, 0);
        goto out;
    }
    domain = poptGetArg(pc);

    /* NetGetDCName */

    status = NetGetDCName(hostname, domain, &buffer);
    if (status != 0) {
        printf("GetDcName failed with: %s\n", libnetapi_errstr(status));
    } else {
        printf("%s\n", (char *)buffer);
    }

out:
    NetApiBufferFree(buffer);
    libnetapi_free(ctx);
    poptFreeContext(pc);

    return status;
}
コード例 #6
0
ファイル: share_del.c プロジェクト: 0x24bin/winexe-1
int main(int argc, const char **argv)
{
	NET_API_STATUS status;
	struct libnetapi_ctx *ctx = NULL;
	const char *hostname = NULL;
	const char *sharename = NULL;

	poptContext pc;
	int opt;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		POPT_COMMON_LIBNETAPI_EXAMPLES
		POPT_TABLEEND
	};

	status = libnetapi_init(&ctx);
	if (status != 0) {
		return status;
	}

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

	poptSetOtherOptionHelp(pc, "hostname sharename");
	while((opt = poptGetNextOpt(pc)) != -1) {
	}

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	hostname = poptGetArg(pc);

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	sharename = poptGetArg(pc);

	/* NetShareDel */

	status = NetShareDel(hostname,
			     sharename,
			     0);
	if (status != 0) {
		printf("NetShareDel failed with: %s\n",
			libnetapi_get_error_string(ctx, status));
		goto out;
	}

 out:
	libnetapi_free(ctx);
	poptFreeContext(pc);

	return status;
}
コード例 #7
0
ファイル: dump4mkd.c プロジェクト: junpei-yoshino/dump4mkd
int main(int argc, char *argv[]){
 char errbuf[PCAP_ERRBUF_SIZE], *device="any",*output_filename="/tmp/test.dump",*filter;
 const char *tmp;
 struct bpf_program fcode;
 int count=0;
 int timer=10;
 int c;
 poptContext context;
 struct poptOption optionsTable[] = {
  {"output",	'o',	POPT_ARG_STRING,	&output_filename,	'o'},
  {"count",	'c',	POPT_ARG_INT,		&count,			'c'},
  {"time",	't',	POPT_ARG_INT,		&timer,			't'},
  {NULL,0,0,NULL,0}
 };
 context = poptGetContext(NULL, argc, (const char **) argv, optionsTable, 0);
 poptSetOtherOptionHelp(context, "<tcpdump filter>");
 while (poptGetNextOpt(context) >= 0) {}
 filter = (char *)malloc(256);
 strcpy (filter,"");
 while ((tmp = poptGetArg(context))!=NULL) {
   if (strcmp(filter,"")) filter = strcat(filter," ");
   filter = strcat(filter,tmp);
 }
 if (strcmp(filter,"")==0) filter = "port 3306";
 poptFreeContext(context);

 printf("file=%s, count=%d, time=%d, filter=%s\n",output_filename,count,timer,filter);
 signal(SIGTERM, cleanup);
 signal(SIGALRM, cleanup);
 signal(SIGINT, cleanup);
 memset(errbuf,0,PCAP_ERRBUF_SIZE); 
 
descr = pcap_open_live(device,BUFSIZ,0,100,errbuf);
 if (descr == NULL) {
  fprintf(stderr, "Couldn't open device %s: %s\n", device, errbuf);
  return(2);
 }
 if (pcap_compile(descr, &fcode, filter, 0, 0) < 0){
  fprintf(stderr,"can not analyze filter:%s\n", filter);
  exit(1);
 }
 if (pcap_setfilter(descr,&fcode) == -1) {
  fprintf(stderr, "filter can not use: %s\n", filter);
  exit(1);
 }
 dumper = pcap_dump_open(descr,output_filename);
 alarm(timer);
 pcap_loop(descr,count,write_captured_packet,NULL);
 pcap_close(descr);
 pcap_dump_close(dumper);
 exit(0);
}
コード例 #8
0
ファイル: fsls.c プロジェクト: wgdavies/fs-utils
/** Process command line arguements and decide how to proceed.
 *  Includes explanatory text for inline help and self-documentation.
 */
int main( int argc, char *argv[] )
{
    int descend_flag = 0, hadoop_flag = 0, stats_flag = 0, verbose_flag = 0, json_flag = 0;
    int count = 0, ret_val = 0;
    g_dir_arg = "."; /// set the default directory argument to "here"
    poptContext pc;
    struct poptOption po[] = {
	{"descend", 'd', POPT_ARG_NONE, &descend_flag, 0, UNIMPL"Parallelise and descend into subdirectories.", NULL},
	{"stats",   's', POPT_ARG_NONE, &stats_flag,   0, "Print detailed statistics.", NULL},
	{"verbose", 'v', POPT_ARG_NONE, &verbose_flag, 0, UNIMPL"Expand statistics output for each subdirectory.", NULL},
	{"json",    'j', POPT_ARG_NONE, &json_flag,    0, UNIMPL"Write output in JSON format.", NULL},
	POPT_AUTOHELP
	POPT_TABLEEND
    };
    
    pc = poptGetContext(NULL, argc, (const char **)argv, po, 0);
    poptSetOtherOptionHelp(pc, "[directory]");
    
    while ( (count = poptGetNextOpt(pc) ) >= 0 ) {
	printf("poptGetNextOpt return val %d\n", count);
    }

    for ( count = 0 ; poptPeekArg(pc) != NULL ; ++count ) {
	asprintf(&g_dir_arg, (char*)poptGetArg(pc));
	
	if ( count > 0 ) {
	    poptPrintUsage(pc, stderr, 0);
	    goto EXITNOW;
	}
    }
    
    if ( descend_flag + hadoop_flag + stats_flag + verbose_flag + json_flag > 5 ) {
	poptPrintUsage(pc, stderr, 0);
	goto EXITNOW;
    } else {
	if ( descend_flag != POPT_ARG_NONE ) printf("%s: %s %s\n", PROGNAME, UNIMPL, "descend");
	else if ( stats_flag != POPT_ARG_NONE ) ret_val = getdirent(g_dir_arg);
	else if ( verbose_flag != POPT_ARG_NONE ) printf("%s: %s %s\n", PROGNAME, UNIMPL, "verbose");
	else if ( json_flag != POPT_ARG_NONE ) printf("%s: %s %s\n", PROGNAME, UNIMPL, "json");
	else ret_val = quickcount(g_dir_arg);
    }
    
    if ( ret_val == 0 ) { 
	exit(EXIT_SUCCESS);
    } else {
	goto EXITNOW;
    }

EXITNOW:
    exit(EXIT_FAILURE);
}
コード例 #9
0
ファイル: main.c プロジェクト: mir-ror/moc
/* Show program help. */
static void show_help (poptContext ctx)
{
	size_t ix;

	show_banner ();
	poptSetOtherOptionHelp (ctx, mocp_summary);
	poptPrintHelp (ctx, stdout, 0);

	printf ("\nEnvironment variables:\n\n");
	for (ix = 0; ix < ARRAY_SIZE(environment_variables); ix += 1)
		printf ("  %-34s%s\n", environment_variables[ix].name,
		                       environment_variables[ix].desc);
	printf ("\n");
}
コード例 #10
0
ファイル: split_tokens.c プロジェクト: 0x24bin/winexe-1
int main(int argc, const char *argv[])
{
	const char *config_file = get_dyn_CONFIGFILE();
	const char *sequence = "";
	poptContext pc;
	char *buff;
	TALLOC_CTX *ctx = talloc_stackframe();

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		POPT_COMMON_VERSION
		POPT_TABLEEND
	};

	load_case_tables();

	pc = poptGetContext(NULL, argc, argv, long_options,
			    POPT_CONTEXT_KEEP_FIRST);
	poptSetOtherOptionHelp(pc, "[OPTION...] <sequence-string>");

	while(poptGetNextOpt(pc) != -1);

	setup_logging(poptGetArg(pc), true);

	sequence = poptGetArg(pc);

	if (sequence == NULL) {
		fprintf(stderr, "ERROR: missing sequence string\n");
		return 1;
	}

	dbf = x_stderr;
	DEBUGLEVEL = 0;
	AllowDebugChange = false;

	if (!lp_load(config_file,false,true,false,true)) {
		fprintf(stderr,"Error loading services.\n");
		return 1;
	}

	while(next_token_talloc(ctx, &sequence, &buff, NULL)) {
		printf("[%s]\n", buff);
	}

	talloc_free(ctx);

	return 0;
}
コード例 #11
0
ファイル: pilot-wav.c プロジェクト: jichu4n/pilot-link
int main(int argc, const char *argv[])
{
        int 	c;

        char
	    	*fetch		= NULL,
	    	*convert	= NULL;

	poptContext pc;

	struct poptOption options[] = {
		USERLAND_RESERVED_OPTIONS
		{"fetch", 'f', POPT_ARG_STRING, &fetch, 0, "Fetch all wav files or specified wav file from the Palm", "[file|all]"},
		{"convert", 'c', POPT_ARG_STRING, &convert, 0, "Convert <file>.wav.pdb file to wav", "file"},
		POPT_TABLEEND
	};

	pc = poptGetContext("pilot-wav", argc, argv, options, 0);
	poptSetOtherOptionHelp(pc,"\n\n"
	"   Decodes Palm Voice Memo files to wav files you can read\n\n"
	"   Example arguments: \n"
	"      pilot-wav -p /dev/pilot -f MyVoiceMemo.wav.pdb\n"
	"      pilot-wav -c MyVoiceMemo.wav.pdb\n\n");

	if (argc < 2 ) {
		poptPrintUsage(pc,stderr,0);
		return 1;
	}


	while ((c = poptGetNextOpt(pc)) >= 0) {
		fprintf(stderr,"   ERROR: Unhandled option %d.\n",c);
		return 1;
        }

	if (c < -1) {
		plu_badoption(pc,c);
	}

	if(convert != NULL)
		pdb_to_wav(convert);

	if(fetch != NULL)
		do_fetch(fetch);

        return 0;
}
コード例 #12
0
void Popt::init(int argc, char *argv[], struct poptOption *optionsTable, const char *oh) {
	if(_optCon != NULL) {
		poptFreeContext(_optCon);
	}
	_optCon = poptGetContext(NULL, argc, const_cast<const char**>(argv), optionsTable, 0);
	assert(_optCon != NULL);
	poptSetOtherOptionHelp(_optCon, oh);
	const int opt = poptGetNextOpt(_optCon);
	if(opt != -1) {
		throw std::runtime_error("invalid command line");
	}
	_args.clear();
	const char *arg;
	while((arg = poptGetArg(_optCon)) != NULL) {
		_args.push_back(arg);
	}
}
コード例 #13
0
ファイル: airopt.c プロジェクト: aming2007/dpi-test-suite
AirOptionCtx *air_option_context_new(
    const char     *helpstr,
    int            *argc,
    char         ***argv,
    AirOptionEntry *entries)
{
    AirOptionCtx *aoctx;
#if USE_GOPTION
    GOptionContext  *octx = NULL;
#elif USE_POPT
    poptContext octx = NULL;
    int i    = 0;
#endif

    aoctx = g_new0(AirOptionCtx, 1);
#if USE_GOPTION
    octx = g_option_context_new(helpstr);
    if (entries) {
        g_option_context_add_main_entries(octx, entries, NULL);
    }
#elif USE_POPT

    aoctx->options = g_array_sized_new(TRUE, TRUE, sizeof(AirOptionEntry), 64);
    if (entries) {

        for (i=0; !AF_OPTION_EMPTY(entries[i]); i++) {
            g_array_append_val(aoctx->options, entries[i]);
        }
    }
    octx = poptGetContext(NULL, *argc,  (const char **) *argv,
                          (AirOptionEntry *) aoctx->options->data, 0);

    poptSetOtherOptionHelp(octx, helpstr);
#endif

    aoctx->argc = argc;
    aoctx->argv = argv;
    aoctx->octx = octx;

    return aoctx;
}
コード例 #14
0
ファイル: common.c プロジェクト: 7tomek/librabbitmqc
poptContext process_options(int argc, const char **argv,
                            struct poptOption *options,
                            const char *help)
{
  int c;
  poptContext opts = poptGetContext(NULL, argc, argv, options, 0);
  poptSetOtherOptionHelp(opts, help);

  while ((c = poptGetNextOpt(opts)) >= 0) {
    /* no options require explicit handling */
  }

  if (c < -1) {
    fprintf(stderr, "%s: %s\n",
            poptBadOption(opts, POPT_BADOPTION_NOALIAS),
            poptStrerror(c));
    poptPrintUsage(opts, stderr, 0);
    exit(1);
  }

  return opts;
}
コード例 #15
0
ファイル: Utils.cpp プロジェクト: Jesse-V/OnioNS-common
bool Utils::parse(const poptContext& pc)
{  // http://privatemisc.blogspot.com/2012/12/popt-basic-example.html
  poptSetOtherOptionHelp(pc, "[ARG...]");

  // process options and handle each val returned
  int val;
  while ((val = poptGetNextOpt(pc)) >= 0)
  {
  }

  // poptGetNextOpt returns -1 when the final argument has been parsed
  if (val != -1)
  {
    poptPrintUsage(pc, stderr, 0);

    // handle error
    switch (val)
    {
      case POPT_ERROR_NOARG:
        printf("Argument expected but missing for an option.\n");
        return false;
      case POPT_ERROR_BADOPT:
        printf("Failed to parse argument.\n");
        return false;
      case POPT_ERROR_BADNUMBER:
      case POPT_ERROR_OVERFLOW:
        printf("Option could not be converted to number\n");
        return false;
      default:
        printf("Unknown error in option processing\n");
        return false;
    }
  }

  poptFreeContext(pc);
  return true;
}
コード例 #16
0
ファイル: smbcontrol.c プロジェクト: srimalik/samba
int main(int argc, const char **argv)
{
	poptContext pc;
	int opt;
	struct tevent_context *evt_ctx;
	struct messaging_context *msg_ctx;

	static struct poptOption long_options[] = {
		/* POPT_AUTOHELP */
		{ NULL, '\0', POPT_ARG_INCLUDE_TABLE, help_options,
		                        0, "Help options:", NULL },
		{ "timeout", 't', POPT_ARG_INT, &timeout, 't', 
		  "Set timeout value in seconds", "TIMEOUT" },

		POPT_COMMON_SAMBA
		POPT_TABLEEND
	};
	TALLOC_CTX *frame = talloc_stackframe();
	int ret = 0;

	load_case_tables();

	setup_logging(argv[0], DEBUG_STDOUT);

	/* Parse command line arguments using popt */

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

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

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

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch(opt) {
		case 't':	/* --timeout */
			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 = 0;
	if (argv != NULL) {
		while (argv[argc] != NULL) {
			argc++;
		}
	}

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

	lp_load_global(get_dyn_CONFIGFILE());

	/* Need to invert sense of return code -- samba
         * routines mostly return True==1 for success, but
         * shell needs 0. */ 

	if (!(evt_ctx = tevent_context_init(NULL)) ||
	    !(msg_ctx = messaging_init(NULL, evt_ctx))) {
		fprintf(stderr, "could not init messaging context\n");
		TALLOC_FREE(frame);
		exit(1);
	}

	ret = !do_command(evt_ctx, msg_ctx, argc, argv);
	TALLOC_FREE(frame);
	return ret;
}
コード例 #17
0
ファイル: smbcontrol.c プロジェクト: hajuuk/R7000
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);
}
コード例 #18
0
ファイル: sss_userdel.c プロジェクト: nguay/SSSD
int main(int argc, const char **argv)
{
    int ret = EXIT_SUCCESS;
    struct tools_ctx *tctx = NULL;
    const char *pc_username = NULL;

    int pc_debug = SSSDBG_DEFAULT;
    int pc_remove = 0;
    int pc_force = 0;
    int pc_kick = 0;
    poptContext pc = 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 },
        { "remove", 'r', POPT_ARG_NONE, NULL, 'r',
                    _("Remove home directory and mail spool"), NULL },
        { "no-remove", 'R', POPT_ARG_NONE, NULL, 'R',
                    _("Do not remove home directory and mail spool"), NULL },
        { "force", 'f', POPT_ARG_NONE, NULL, 'f',
                    _("Force removal of files not owned by the user"), NULL },
        { "kick", 'k', POPT_ARG_NONE, NULL, 'k',
                    _("Kill users' processes before removing him"), NULL },
        POPT_TABLEEND
    };

    debug_prg_name = argv[0];

    ret = set_locale();
    if (ret != EOK) {
        DEBUG(1, ("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 'r':
                pc_remove = DO_REMOVE_HOME;
                break;

            case 'R':
                pc_remove = DO_NOT_REMOVE_HOME;
                break;

            case 'f':
                pc_force = DO_FORCE_REMOVAL;
                break;

            case 'k':
                pc_kick = 1;
                break;
        }
    }

    debug_level = debug_convert_old_level(pc_debug);

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

    pc_username = poptGetArg(pc);
    if (pc_username == NULL) {
        BAD_POPT_PARAMS(pc, _("Specify user to delete\n"), ret, fini);
    }

    CHECK_ROOT(ret, debug_prg_name);

    ret = init_sss_tools(&tctx);
    if (ret != EOK) {
        DEBUG(1, ("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;
    }

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

    ret = sysdb_getpwnam_sync(tctx,
                              tctx->sysdb,
                              tctx->octx->name,
                              tctx->octx);
    if (ret != EOK) {
        /* Error message will be printed in the switch */
        goto done;
    }

    if ((tctx->octx->uid < tctx->local->id_min) ||
        (tctx->local->id_max && tctx->octx->uid > tctx->local->id_max)) {
        ERROR("User %1$s is outside the defined ID range for domain\n",
              tctx->octx->name);
        ret = EXIT_FAILURE;
        goto fini;
    }

    if (pc_kick) {
        ret = kick_user(tctx);
        if (ret != EOK) {
            tctx->error = ret;

            goto done;
        }
    }

    /* userdel */
    ret = userdel(tctx, tctx->sysdb, tctx->octx);
    if (ret != EOK) {
        goto done;
    }

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

    if (!pc_kick) {
        ret = is_logged_in(tctx, tctx->octx->uid);
        switch(ret) {
            case ENOENT:
                break;

            case EOK:
                ERROR("WARNING: The user (uid %1$lu) was still logged in when "
                      "deleted.\n", (unsigned long) tctx->octx->uid);
                break;

            case ENOSYS:
                ERROR("Cannot determine if the user was logged in on this "
                      "platform");
                break;

            default:
                ERROR("Error while checking if the user was logged in\n");
                break;
        }
    }

    ret = run_userdel_cmd(tctx);
    if (ret != EOK) {
        ERROR("The post-delete command failed: %1$s\n", strerror(ret));
        goto fini;
    }

    if (tctx->octx->remove_homedir) {
        ret = remove_homedir(tctx,
                             tctx->octx->home,
                             tctx->octx->maildir,
                             tctx->octx->name,
                             tctx->octx->uid,
                             pc_force);
        if (ret == EPERM) {
            ERROR("Not removing home dir - not owned by user\n");
        } else if (ret != EOK) {
            ERROR("Cannot remove homedir: %1$s\n", strerror(ret));
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

done:
    if (ret) {
        DEBUG(1, ("sysdb operation failed (%d)[%s]\n", ret, strerror(ret)));
        switch (ret) {
            case ENOENT:
                ERROR("No such user in local domain. "
                      "Removing users only allowed in local domain.\n");
                break;

            default:
                ERROR("Internal error. Could not remove user.\n");
                break;
        }
        ret = EXIT_FAILURE;
        goto fini;
    }

    ret = EXIT_SUCCESS;

fini:
    talloc_free(tctx);
    poptFreeContext(pc);
    exit(ret);
}
コード例 #19
0
/* int segs2name (poptContext  *optCon, char **filename, int *seg_list); */
int main (int argc, char **argv)
{
    int i, ret;
    LorsExnode *exnode;
    char        *s;
    char        *output_filename = "-";
    char        *filename;
    int          same_name=0;
    int         v;
    int         file_cnt = 0;
    int         opts = LORS_MANAGE_CAP;
    XndRc       xndrc;

    poptContext optCon;   /* context for parsing command-line options */
    struct poptOption optionsTable[] = {
  { "samename",   'f', POPT_ARG_NONE,   0,                  SAME_OUTPUTNAME, 
        "Save the modified exNode to the original exNode filename.", NULL },
  { "outputfile", 'o', POPT_ARG_STRING, &output_filename,   OUTPUTNAME, 
        "Specify the name for the output exNode file.", NULL},
  { "read-cap",   'r', POPT_ARG_NONE,   0,                  LORS_READ_CAP, 
        "Delete the read capabilities from the exNode.", NULL},
  { "write-cap",  'w', POPT_ARG_NONE,   0,                  LORS_WRITE_CAP, 
        "Delete the write capabilities from the exNode.", NULL},
  { "manage-cap", 'm', POPT_ARG_NONE,   0,                  LORS_MANAGE_CAP, 
        "Delete the manage capabilities from the exNode.", NULL},
  { "version",    'v', POPT_ARG_NONE,   0,                  LORS_VERSION, 
        "Display Version information about this package.", NULL},
  { "verbose",    'V', POPT_ARG_INT,    &xndrc.verbose,        VERBOSE, 
        "Modify the level or mode of Verbosity in output messages.", "0"},
  /* { "demo",  'D', POPT_ARG_NONE, 0, LORS_ARG_DEMO, 
        "Add the messages understood by the LoRS View visualization.", NULL}, */
        POPT_AUTOHELP
        { NULL, 0, 0, NULL, 0 }
    };

    parse_xndrc_files(&xndrc);
    g_lors_demo = xndrc.demo;

    optCon = poptGetContext(NULL, argc, (const char **)argv, optionsTable, 0);
    poptSetOtherOptionHelp(optCon, "<filename>");

    if ( argc < 2 )
    {
        poptPrintUsage(optCon, stderr, 0);
        poptPrintHelp(optCon, stderr, 0);
                                 exit(EXIT_FAILURE);
    }
    while ( (v=poptGetNextOpt(optCon)) >= 0)
    {
        switch(v)
        {
            case LORS_READ_CAP:
            case LORS_WRITE_CAP:
            case LORS_MANAGE_CAP:
                opts |= v;
                break;
            case SAME_OUTPUTNAME:
                same_name = 1;
                break;
            case LORS_ARG_DEMO:
                g_lors_demo = (!g_lors_demo);
                break;
            case LORS_VERSION:
            {
                const char *package;
                double version;
                lorsGetLibraryVersion(&package, &version);
                fprintf(stderr, "Version: %s %f\n", package, version);
                exit(EXIT_FAILURE);
                break;
            }
            default:
                /*fprintf(stderr, "Unsupported option: %d\n", v);*/
                break;
        }

    }

    g_db_level = xndrc.verbose;
    if ( v < -1 )
    {
        fprintf(stderr, "error: %d\n", v);
        fprintf(stderr, "%s: %s\n",
                 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
                 poptStrerror(v));
    }
    while ( (filename = (char *)poptGetArg(optCon)) != NULL )
    {
        file_cnt++;
        /* output_filename= NULL;*/
	if (same_name == 1) output_filename = filename;
        ret = lorsModifyFile(filename, output_filename, opts);
        if ( ret != LORS_SUCCESS )
        {
            fprintf(stderr, "An error occured during modify: %d\n", ret);
        }
    }
    if ( file_cnt == 0 )
    {
        fprintf(stderr, "Error. You must also provide a filename on "
                "which lors_modify operates.\n");
        poptPrintHelp(optCon, stderr, 0);
        exit(EXIT_FAILURE);
    }
    free_xndrc(&xndrc);
    poptFreeContext(optCon);
    return 0;
}
コード例 #20
0
ファイル: share_enum.c プロジェクト: 0x24bin/winexe-1
int main(int argc, const char **argv)
{
	NET_API_STATUS status;
	struct libnetapi_ctx *ctx = NULL;
	const char *hostname = NULL;
	uint32_t level = 0;
	uint8_t *buffer = NULL;
	uint32_t entries_read = 0;
	uint32_t total_entries = 0;
	uint32_t resume_handle = 0;
	int i;

	struct SHARE_INFO_0 *i0 = NULL;
	struct SHARE_INFO_1 *i1 = NULL;
	struct SHARE_INFO_2 *i2 = NULL;

	poptContext pc;
	int opt;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		POPT_COMMON_LIBNETAPI_EXAMPLES
		POPT_TABLEEND
	};

	status = libnetapi_init(&ctx);
	if (status != 0) {
		return status;
	}

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

	poptSetOtherOptionHelp(pc, "hostname level");
	while((opt = poptGetNextOpt(pc)) != -1) {
	}

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	hostname = poptGetArg(pc);

	if (poptPeekArg(pc)) {
		level = atoi(poptGetArg(pc));
	}

	/* NetShareEnum */

	do {
		status = NetShareEnum(hostname,
				      level,
				      &buffer,
				      (uint32_t)-1,
				      &entries_read,
				      &total_entries,
				      &resume_handle);
		if (status == 0 || status == ERROR_MORE_DATA) {
			printf("total entries: %d\n", total_entries);
			switch (level) {
				case 0:
					i0 = (struct SHARE_INFO_0 *)buffer;
					break;
				case 1:
					i1 = (struct SHARE_INFO_1 *)buffer;
					break;
				case 2:
					i2 = (struct SHARE_INFO_2 *)buffer;
					break;
				default:
					break;
			}
			for (i=0; i<entries_read; i++) {
				switch (level) {
					case 0:
						printf("#%d netname: %s\n", i, i0->shi0_netname);
						i0++;
						break;
					case 1:
						printf("#%d netname: %s\n", i, i1->shi1_netname);
						printf("#%d type: %d\n", i, i1->shi1_type);
						printf("#%d remark: %s\n", i, i1->shi1_remark);
						i1++;
						break;
					case 2:
						printf("#%d netname: %s\n", i, i2->shi2_netname);
						printf("#%d type: %d\n", i, i2->shi2_type);
						printf("#%d remark: %s\n", i, i2->shi2_remark);
						printf("#%d permissions: %d\n", i, i2->shi2_permissions);
						printf("#%d max users: %d\n", i, i2->shi2_max_uses);
						printf("#%d current users: %d\n", i, i2->shi2_current_uses);
						printf("#%d path: %s\n", i, i2->shi2_path);
						printf("#%d password: %s\n", i, i2->shi2_passwd);
						i2++;
						break;
					default:
						break;
				}
			}
			NetApiBufferFree(buffer);
		}
	} while (status == ERROR_MORE_DATA);

	if (status != 0) {
		printf("NetShareEnum failed with: %s\n",
			libnetapi_get_error_string(ctx, status));
	}

 out:
	libnetapi_free(ctx);
	poptFreeContext(pc);

	return status;
}
コード例 #21
0
ファイル: share_setinfo.c プロジェクト: 0x24bin/winexe-1
int main(int argc, const char **argv)
{
	NET_API_STATUS status;
	struct libnetapi_ctx *ctx = NULL;
	const char *hostname = NULL;
	const char *sharename = NULL;
	const char *comment = "NetApi generated Share comment";
	uint32_t level = 1004;
	uint8_t *buffer = NULL;
	uint32_t parm_err = 0;

	struct SHARE_INFO_1004 i1004;

	poptContext pc;
	int opt;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		POPT_COMMON_LIBNETAPI_EXAMPLES
		POPT_TABLEEND
	};

	status = libnetapi_init(&ctx);
	if (status != 0) {
		return status;
	}

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

	poptSetOtherOptionHelp(pc, "hostname sharename comment");
	while((opt = poptGetNextOpt(pc)) != -1) {
	}

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	hostname = poptGetArg(pc);

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	sharename = poptGetArg(pc);

	if (poptPeekArg(pc)) {
		comment = poptGetArg(pc);
	}

	/* NetShareSetInfo */
	switch (level) {
		case 1004:
			i1004.shi1004_remark = comment;
			buffer = (uint8_t *)&i1004;
			break;
		default:
			break;
	}

	status = NetShareSetInfo(hostname,
				 sharename,
				 level,
				 buffer,
				 &parm_err);
	if (status != 0) {
		printf("NetShareSetInfo failed with: %s\n",
			libnetapi_get_error_string(ctx, status));
		goto out;
	}

 out:
	libnetapi_free(ctx);
	poptFreeContext(pc);

	return status;
}
コード例 #22
0
ファイル: nmblookup.c プロジェクト: javierag/samba
/****************************************************************************
  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;
}
コード例 #23
0
ファイル: sss_useradd.c プロジェクト: 3van/sssd
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);
}
コード例 #24
0
ファイル: CDC_discover.c プロジェクト: dfletcher/cdctool
int main(int argc, const char **argv) {

  int i;
  char c;
  int linestoread = 1;
  char *outpath = NULL;
  char *errpath = NULL;
  poptContext poptcxt;
  const char **addl = NULL;
  const char *regexp = NULL;
  const char *command = NULL;
  unsigned long numaddl = 0;
  CDCDiscoveryResults *discovery;

  // I/O defaults.
  in = stdin;
  out = stdout;
  err = stderr;

  struct poptOption options[] = {

    // --output,-o
    {
      "output", 'o', POPT_ARG_STRING, &outpath, 0,
      "output file (DEFAULT=stdout)", "path|-"
    },

    // --error,-e
    {
      "error", 'e', POPT_ARG_STRING, &errpath, 0,
      "error file (DEFAULT=stderr)", "path|-"
    },

    // --lines,-l
    {
      "lines", 'l', POPT_ARG_INT, &linestoread, 0,
      "Number of lines to read from the serial port before exiting. Zero is the same as -r. (DEFAULT=1)"
    },

    // --help,-?
    POPT_AUTOHELP

    // end
    { NULL, 0, 0, NULL, 0 }

  };

  // Process popt options.
  poptcxt = poptGetContext(NULL, argc, argv, options, 0);
  poptSetOtherOptionHelp(
    poptcxt, "[OPTIONS]* <command> <regexp> (additional port)+"
  );
  if (argc < 2) {
    usage(poptcxt, 0, 0, 0);
  }
  while ((c = poptGetNextOpt(poptcxt)) >= 0) { ; }
  if (c < -1) {
    // An error occurred during option processing.
    fprintf(
      stderr, "%s: %s\n",
      poptBadOption(poptcxt, POPT_BADOPTION_NOALIAS), poptStrerror(c)
    );
    return 1;
  }

  // Check error file.
  if (errpath && strcmp(errpath, "-") != 0) {
    err = fopen(errpath, "a");
    if (!err) {
      usage(poptcxt, 2, "Cannot open error file path", errpath);
    }
  }

  // Check output file.
  if (outpath && strcmp(outpath, "-") != 0) {
    out = fopen(outpath, "a");
    if (!out) {
      usage(poptcxt, 3, "Cannot open output file path", outpath);
    }
  }

  // Get the command and regular expression query.
  command = poptGetArg(poptcxt);
  regexp = poptGetArg(poptcxt);
  if ((command == NULL) || (regexp == NULL)) {
    usage(
      poptcxt, 1, "Please specify", "<command> <regex>"
    );
  }

  // Additional ports to check.
  while (poptPeekArg(poptcxt)) {
    addl = (const char**)realloc(addl, (++numaddl) * sizeof(char*));
    addl[numaddl] = poptGetArg(poptcxt);
  }

  // Discovery.
  discovery = cdc_discover(command, regexp, linestoread, numaddl, addl);
  for (i=0; i<discovery->matches; i++) {
    fprintf(out, "%s\n", discovery->match[i]);
  }
  cdc_discover_free_results(discovery);

  // Cleanup.
  if (numaddl) {
    free(addl);
  }
  poptFreeContext(poptcxt);

  return 0;
}
コード例 #25
0
ファイル: smsAnal.c プロジェクト: johnglover/libsms
int main (int argc, const char *argv[])
{
    FILE *pOutputSmsFile; 
    SMS_Data smsData;
    SMS_Header smsHeader;

    float pSoundData[SMS_MAX_WINDOW];
    SMS_SndHeader soundHeader;

    char *pChInputSoundFile = NULL, *pChOutputSmsFile = NULL;
    int verbose = 0;
    int iDoAnalysis = 1;
    int iFrame = 0;
    long iStatus = 0, iSample = 0, sizeNewData = 0;

    int optc;   /* switch */
    poptContext pc;

    SMS_AnalParams analParams;
    sms_initAnalParams(&analParams);    /* initialize arguments to defaults*/

    struct poptOption options[] =
    {
        {"verbose", 'v', POPT_ARG_NONE, &verbose, 0, 
            "verbose mode", 0},
        {"debug", 'd', POPT_ARG_INT, &analParams.iDebugMode, 0, 
            "debug mode (0)", "int"},
        {"format", 'f', POPT_ARG_INT, &analParams.iFormat, 0, 
            "analysis format (0, harmonic)", "int"},
        {"sound-type", 'q', POPT_ARG_INT, &analParams.iSoundType, 0, 
            "sound type (0, phrase)", "int"},
        {"direction", 'x', POPT_ARG_INT, &analParams.iAnalysisDirection, 0, 
            "analysis direction (0, forward)", "int"},
        /* STFT Parameters: */
        {"window-size", 's', POPT_ARG_FLOAT, &analParams.fSizeWindow, 0, 
            "size of the window in f0 periods (3.5)", "float"},
        {"window-type", 'i', POPT_ARG_INT, &analParams.iWindowType, 0, 
            "window type (1, blackman harris 70 dB)", "int"},
        {"frame-rate", 'r', POPT_ARG_INT, &analParams.iFrameRate, 0, 
            "frame rate in hertz (300)", "int"},
        /* Peak Detection Parameters */
        {"highest-freq", 'j', POPT_ARG_FLOAT, &analParams.fHighestFreq, 0, 
            "highest frequency to look for peaks (12000hz)", "float"},
        {"min-peak-mag", 'k', POPT_ARG_FLOAT, &analParams.fMinPeakMag, 0, 
            "minimum peak magnitude (0 normalized dB, which corresponds to -100dB)", "float"}, /*\todo check this doc*/
        /* Harmonic Detection Parameters */
        {"ref-harmonic", 'y', POPT_ARG_INT, &analParams.iRefHarmonic, 0, 
            "reference harmonic number in series (1)", "int"},
        {"min-ref-harm-mag", 'm', POPT_ARG_FLOAT, &analParams.fMinPeakMag, 0, 
            "minimum reference harmonic magnitude (30 normalized dB)", "float"}, /*\todo check this doc*/
        {"min-ref-harm-mag", 'z', POPT_ARG_FLOAT, &analParams.fRefHarmMagDiffFromMax, 0, 
            " maximum dB difference between the harmonic used for reference and the maximum peak (default 30)", "float"}, /*\todo check this doc*/
        {"default-fund", 'u', POPT_ARG_FLOAT, &analParams.fDefaultFundamental, 0, 
            "default fundamental frequency (hz), used to set initial window size, or window size for entire sound if inharmonic (default 100)", "float"}, 
        {"lowest-fund", 'l', POPT_ARG_FLOAT, &analParams.fDefaultFundamental, 0, 
            "lowest fundamental frequency(hz), or frequency in inharmonic analysis, to search for (default 50)", "float"}, 
        {"highest-fund", 'h', POPT_ARG_FLOAT, &analParams.fDefaultFundamental, 0, 
            "highest fundamental frequency to search for, has no effect on inharmonic analysis (default 1000)", "float"}, 
        /* Peak Continuation parameters */
        {"guides", 'n', POPT_ARG_INT, &analParams.nGuides, 0, 
            "number of guides to use in partial tracking (default 100)", "int"},
        {"tracks", 'p', POPT_ARG_INT, &analParams.nTracks, 0, 
            "number of output partial tracks (default 60)", "int"},
        {"freq-deviation", 'w', POPT_ARG_FLOAT, &analParams.fFreqDeviation, 0, 
            "maximum permitted frequency deviation from guide frequency (default .45)", "float"}, 
        {"peak-cont-guide", 't', POPT_ARG_FLOAT, &analParams.fPeakContToGuide, 0, 
            "contribution of the frequency of the previous peak of a given trajectory to the current guide frequency value (default .4).", "float"}, 
        {"fund-cont-guide", 'o', POPT_ARG_FLOAT, &analParams.fFundContToGuide, 0, 
            "contribution of the fundamental frequency of the previous peak of a given trajectory to the current guide frequency value (default .5).", "float"}, 
        /* Track Cleaning parameters:\n" */
        {"clean-track", 'g', POPT_ARG_INT, &analParams.iCleanTracks, 0, 
            "turn on/off track cleaning (default is on, 1)", "int"}, 
        {"min-track-length", 'a', POPT_ARG_FLOAT, &analParams.iMinTrackLength, 0, 
            "minimum track length in seconds (0.1)", "float"}, 
        {"max-sleeping-time", 'b', POPT_ARG_FLOAT, &analParams.iMaxSleepingTime, 0, 
            "maximum time a frame can sleep in seconds (0.1)", "float"},  /* this doc is horrible */
        /* Stochastic Analysis parameters */
        {"stochastic", 'e', POPT_ARG_INT, &analParams.iStochasticType, 0, 
            "turn on/off stochastic analysis (default is on, 1)", "int"}, 
        {"stoch-coeff", 'c', POPT_ARG_INT, &analParams.nStochasticCoeff, 0, 
            "number of stochastic coefficients in approximation (default 128)", "int"}, 
        /* spectral enveloping parameters */
        {"se",0, POPT_ARG_INT, &analParams.specEnvParams.iType, 0, 
            "spectral enveloping type (0, off)", "int"},
        {"co", 0, POPT_ARG_INT, &analParams.specEnvParams.iOrder, 0, 
            "discrete cepstrum order (25)", "int"},
        {"la", 0, POPT_ARG_FLOAT, &analParams.specEnvParams.fLambda, 0, 
            "lambda, regularizing coefficient (0.00001)", "float"}, 
        {"an", 0, POPT_ARG_NONE, &analParams.specEnvParams.iAnchor, 0, 
            "turn on anchoring of spectral envelope endpoints", 0}, 
        {"mef", 0, POPT_ARG_INT, &analParams.specEnvParams.iMaxFreq, 0, 
            "maximum envelope frequency (default is highest-freq", "int"}, 
        POPT_AUTOHELP
            POPT_TABLEEND
    };


    pc = poptGetContext("smsAnal", argc, argv, options, 0);
    poptSetOtherOptionHelp(pc, help_header_text);

    while ((optc = poptGetNextOpt(pc)) > 0) {
        switch (optc) {
            /* specific arguments are handled here */
            case 'v':
                verbose = 1;
            default:
                ;
        }
    }
    if (optc < -1) 
    {
        /* an error occurred during option processing */
        printf("%s: %s\n",
                poptBadOption(pc, POPT_BADOPTION_NOALIAS),
                poptStrerror(optc));
        return 1;
    }
    if (argc < 3)
    {
        poptPrintUsage(pc,stderr,0);
        return 1;
    }
    pChInputSoundFile = (char *) poptGetArg(pc);
    pChOutputSmsFile = (char *) poptGetArg(pc);
    /* parsing done */


    /* open input sound */
    if (sms_openSF(pChInputSoundFile, &soundHeader))
    {
        printf("error in sms_openSF: %s \n", sms_errorString());
        exit(EXIT_FAILURE);
    }       

    /* initialize everything */
    sms_init();
    /* TODO NExt: go from here through all the functions that need to look at specEnvParams */
    sms_initAnalysis (&analParams, &soundHeader);

    sms_fillHeader (&smsHeader, &analParams, "smsAnal");
    sms_writeHeader (pChOutputSmsFile, &smsHeader, &pOutputSmsFile);

    /* allocate output SMS record */
    sms_allocFrameH (&smsHeader, &smsData);

    /* perform analysis */
    if (analParams.iAnalysisDirection == SMS_DIR_REV)
        iSample = soundHeader.nSamples;

    if (analParams.iDebugMode == SMS_DBG_SYNC)
        sms_createDebugFile (&analParams);

    if(verbose)
    {
        printf("\n===sound file info===\n");
        printf("samples: %d, samplerate: %d, seconds: %f \n", soundHeader.nSamples, soundHeader.iSamplingRate, 
                soundHeader.nSamples / (float)soundHeader.iSamplingRate);
        printf("number of channels: %d, read channel: %d \n", soundHeader.channelCount, soundHeader.iReadChannel); 
        printf("\n===analysis parameters===\n");
        printf("sizeHop: %d, nFrames: %d \n", analParams.sizeHop, analParams.nFrames);
        /* \todo: print analysis window type (by name) here */
        if(analParams.specEnvParams.iType != SMS_ENV_NONE)
        {
            printf("\n===spectral envelope parameters===\n");
            if(analParams.specEnvParams.iType == SMS_ENV_CEP)
                printf("type: cepstral coefficients, ");
            else if(analParams.specEnvParams.iType == SMS_ENV_FBINS)
                printf("type: frequency bins, ");
            else
                printf("warning: unknown spectral envelope type! \n\n ");
            printf("order: %d, lambda: %f, max frequency: %d \n", analParams.specEnvParams.iOrder,
                    analParams.specEnvParams.fLambda, analParams.specEnvParams.iMaxFreq);
        }
        printf("\n===header info string===\n %s", smsHeader.pChTextCharacters);
        printf("\n\ndoing analysis now:\n");
    }

    while(iDoAnalysis > 0)
    {
        if (analParams.iAnalysisDirection == SMS_DIR_REV)
        {
            if ((iSample - analParams.sizeNextRead) >= 0)
                sizeNewData = analParams.sizeNextRead;
            else
                sizeNewData = iSample;
            iSample -= sizeNewData;
        }
        else
        {
            iSample += sizeNewData;
            if((iSample + analParams.sizeNextRead) < soundHeader.nSamples)
                sizeNewData = analParams.sizeNextRead;
            else
                sizeNewData = soundHeader.nSamples - iSample;
        }
        /* get one frame of sound */
        if (sms_getSound(&soundHeader, sizeNewData, pSoundData, iSample, &analParams))
        {
            printf("error: could not read sound frame %d\n", iFrame);
            printf("error message in sms_getSound: %s \n", sms_errorString());
            break;
        }
        /* perform analysis of one frame of sound */
        iStatus = sms_analyze (sizeNewData, pSoundData, &smsData,
                &analParams);

        /* if there is an output SMS record, write it */
        if (iStatus == 1)
        {
            sms_writeFrame (pOutputSmsFile, &smsHeader, &smsData);
            if(sms_errorCheck())
            {
                printf("error: could not write sms frame %d:\n", iFrame);
                printf("error message in sms_writeFrame: %s \n", sms_errorString());
                break;
            }
            if(verbose)
            {
                /*                                 if (iFrame % 10 == 0) */
                /*                                         printf ("frame: %d, %.2f \n", iFrame, iFrame / (float) smsHeader.iFrameRate); */
                if (iFrame % 10 == 0)
                    printf ("%.2f ", iFrame / (float) smsHeader.iFrameRate);

            }
            iFrame++;
        }
        else if (iStatus == -1) /* done */
        {
            iDoAnalysis = 0;
            smsHeader.nFrames = iFrame;
        }
    }


    smsHeader.fResidualPerc = analParams.fResidualAccumPerc / iFrame;
    if(verbose)
    {
        printf("\n");
        printf("residual percentage: %f \n", smsHeader.fResidualPerc);
    }                
    if(smsHeader.nFrames != analParams.nFrames && verbose)
        printf("warning: wrong number of analyzed frames: analParams: %d, smsHeader: %d \n", 
                analParams.nFrames, smsHeader.nFrames); 
    /* write an close output files */
    sms_writeFile (pOutputSmsFile, &smsHeader);
    if (analParams.iDebugMode == SMS_DBG_SYNC)
        sms_writeDebugFile ();

    printf("wrote %d analysis frames to %s\n", iFrame, pChOutputSmsFile);

    /* cleanup */
    sms_freeFrame(&smsData);
    sms_freeAnalysis(&analParams);
    sms_free();
    return 0;   
}
コード例 #26
0
ファイル: shairport.c プロジェクト: HugoChanD/shairport-sync
int parse_options(int argc, char **argv) {
  // there are potential memory leaks here -- it's called a second time, previously allocated strings will dangle.
  char *raw_service_name = NULL; /* Used to pick up the service name before possibly expanding it */
  char *stuffing = NULL; /* used for picking up the stuffing option */
  signed char c;      /* used for argument parsing */
  int i = 0;          /* used for tracking options */
  poptContext optCon; /* context for parsing command-line options */
  struct poptOption optionsTable[] = {
      {"verbose", 'v', POPT_ARG_NONE, NULL, 'v', NULL},
      {"disconnectFromOutput", 'D', POPT_ARG_NONE, NULL, 0, NULL},
      {"reconnectToOutput", 'R', POPT_ARG_NONE, NULL, 0, NULL},
      {"kill", 'k', POPT_ARG_NONE, NULL, 0, NULL},
      {"daemon", 'd', POPT_ARG_NONE, &config.daemonise, 0, NULL},
      {"configfile", 'c', POPT_ARG_STRING, &config.configfile, 0, NULL},
      {"statistics", 0, POPT_ARG_NONE, &config.statistics_requested, 0, NULL},
      {"version", 'V', POPT_ARG_NONE, NULL, 0, NULL},
      {"port", 'p', POPT_ARG_INT, &config.port, 0, NULL},
      {"name", 'a', POPT_ARG_STRING, &raw_service_name, 0, NULL},
      {"output", 'o', POPT_ARG_STRING, &config.output_name, 0, NULL},
      {"on-start", 'B', POPT_ARG_STRING, &config.cmd_start, 0, NULL},
      {"on-stop", 'E', POPT_ARG_STRING, &config.cmd_stop, 0, NULL},
      {"wait-cmd", 'w', POPT_ARG_NONE, &config.cmd_blocking, 0, NULL},
      {"mdns", 'm', POPT_ARG_STRING, &config.mdns_name, 0, NULL},
      {"latency", 'L', POPT_ARG_INT, &config.userSuppliedLatency, 0, NULL},
      {"AirPlayLatency", 'A', POPT_ARG_INT, &config.AirPlayLatency, 0, NULL},
      {"iTunesLatency", 'i', POPT_ARG_INT, &config.iTunesLatency, 0, NULL},
      {"forkedDaapdLatency", 0, POPT_ARG_INT, &config.ForkedDaapdLatency, 0, NULL},
      {"stuffing", 'S', POPT_ARG_STRING, &stuffing, 'S', NULL},
      {"resync", 'r', POPT_ARG_INT, &config.resyncthreshold, 0, NULL},
      {"timeout", 't', POPT_ARG_INT, &config.timeout, 't', NULL},
      {"password", 0, POPT_ARG_STRING, &config.password, 0, NULL},
      {"tolerance", 0, POPT_ARG_INT, &config.tolerance, 0, NULL},
#ifdef CONFIG_METADATA
      {"metadata-pipename", 'M', POPT_ARG_STRING, &config.metadata_pipename, 'M', NULL},
      {"get-coverart", 'g', POPT_ARG_NONE, &config.get_coverart, 'g', NULL},
#endif
      POPT_AUTOHELP
      {NULL, 0, 0, NULL, 0}};

// we have to parse the command line arguments to look for a config file
  int optind;
  optind = argc;
  int j;
  for (j = 0; j < argc; j++)
    if (strcmp(argv[j], "--") == 0)
      optind = j;

  optCon = poptGetContext(NULL, optind, (const char **)argv, optionsTable, 0);
  poptSetOtherOptionHelp(optCon, "[OPTIONS]* ");
  
   /* Now do options processing just to get a debug level */
  debuglev = 0;
  while ((c = poptGetNextOpt(optCon)) >= 0) {
    switch (c) {
    case 'v':
      debuglev++;
      break;
    }
  }
  if (c < -1) {
    die("%s: %s", poptBadOption(optCon, POPT_BADOPTION_NOALIAS), poptStrerror(c));
  }

  config_setting_t *setting;
  const char *str=0;
  int value=0;
  
  debug(1,"Looking for the configuration file \"%s\".",config.configfile);
  
  config_init(&config_file_stuff);
  
  char *config_file_real_path = realpath(config.configfile, NULL);
  if (config_file_real_path==NULL) {
    debug(2,"Can't resolve the configuration file \"%s\".",config.configfile);
  } else {
    debug(2, "Looking for configuration file at full path \"%s\"", config_file_real_path);
    /* Read the file. If there is an error, report it and exit. */
    if (config_read_file(&config_file_stuff, config_file_real_path)) {
      // make config.cfg point to it
      config.cfg = &config_file_stuff;
      /* Get the Service Name. */
      if (config_lookup_string(config.cfg, "general.name", &str)) {
        raw_service_name = (char *)str;
      }

      /* Get the Daemonize setting. */
      if (config_lookup_string(config.cfg, "general.daemonize", &str)) {
        if (strcasecmp(str, "no") == 0)
          config.daemonise = 0;
        else if (strcasecmp(str, "yes") == 0)
          config.daemonise = 1;
        else
          die("Invalid daemonize option choice \"%s\". It should be \"yes\" or \"no\"");
      }

      /* Get the mdns_backend setting. */
      if (config_lookup_string(config.cfg, "general.mdns_backend", &str))
        config.mdns_name = (char *)str;

      /* Get the output_backend setting. */
      if (config_lookup_string(config.cfg, "general.output_backend", &str))
        config.output_name = (char *)str;

      /* Get the port setting. */
      if (config_lookup_int(config.cfg, "general.port", &value)) {
        if ((value < 0) || (value > 65535))
          die("Invalid port number  \"%sd\". It should be between 0 and 65535, default is 5000",
              value);
        else
          config.port = value;
      }

      /* Get the udp port base setting. */
      if (config_lookup_int(config.cfg, "general.udp_port_base", &value)) {
        if ((value < 0) || (value > 65535))
          die("Invalid port number  \"%sd\". It should be between 0 and 65535, default is 6001",
              value);
        else
          config.udp_port_base = value;
      }

      /* Get the udp port range setting. This is number of ports that will be tried for free ports , starting at the port base. Only three ports are needed. */
      if (config_lookup_int(config.cfg, "general.udp_port_range", &value)) {
        if ((value < 0) || (value > 65535))
          die("Invalid port range  \"%sd\". It should be between 0 and 65535, default is 100",
              value);
        else
          config.udp_port_range = value;
      }

      /* Get the password setting. */
      if (config_lookup_string(config.cfg, "general.password", &str))
        config.password = (char *)str;

      if (config_lookup_string(config.cfg, "general.interpolation", &str)) {
        if (strcasecmp(str, "basic") == 0)
          config.packet_stuffing = ST_basic;
        else if (strcasecmp(str, "soxr") == 0)
          config.packet_stuffing = ST_soxr;
        else
          die("Invalid interpolation option choice \"%s\". It should be \"basic\" or \"soxr\"");
      }

      /* Get the statistics setting. */
      if (config_lookup_string(config.cfg, "general.statistics", &str)) {
        if (strcasecmp(str, "no") == 0)
          config.statistics_requested = 0;
        else if (strcasecmp(str, "yes") == 0)
          config.statistics_requested = 1;
        else
          die("Invalid statistics option choice \"%s\". It should be \"yes\" or \"no\"");
      }

      /* Get the drift tolerance setting. */
      if (config_lookup_int(config.cfg, "general.drift", &value))
        config.tolerance = value;

      /* Get the resync setting. */
      if (config_lookup_int(config.cfg, "general.resync_threshold", &value))
        config.resyncthreshold = value;

      /* Get the verbosity setting. */
      if (config_lookup_int(config.cfg, "general.log_verbosity", &value)) {
        if ((value >= 0) && (value <= 3))
          debuglev = value;
        else
          die("Invalid log verbosity setting option choice \"%d\". It should be between 0 and 3, "
              "inclusive.",
              value);
      }

      /* Get the ignore_volume_control setting. */
      if (config_lookup_string(config.cfg, "general.ignore_volume_control", &str)) {
        if (strcasecmp(str, "no") == 0)
          config.ignore_volume_control = 0;
        else if (strcasecmp(str, "yes") == 0)
          config.ignore_volume_control = 1;
        else
          die("Invalid ignore_volume_control option choice \"%s\". It should be \"yes\" or \"no\"");
      }

      /* Get the playback_mode setting */
       if (config_lookup_string(config.cfg, "general.playback_mode", &str)) {
        if (strcasecmp(str, "stereo") == 0)
          config.playback_mode = ST_stereo;
        else if (strcasecmp(str, "mono") == 0)
          config.playback_mode = ST_mono;
        else
          die("Invalid playback_mode choice \"%s\". It should be \"stereo\" (default) or \"mono\"");
      }

      /* Get the regtype -- the service type and protocol, separated by a dot. Default is "_raop._tcp" */
      if (config_lookup_string(config.cfg, "general.regtype", &str))
        config.regtype = strdup(str);
     

      /* Get the volume range, in dB, that should be used If not set, it means you just use the range set by the mixer. */
      if (config_lookup_int(config.cfg, "general.volume_range_db", &value)) {
        if ((value < 30) || (value > 150))
          die("Invalid volume range  \"%sd\". It should be between 30 and 150 dB. Zero means use the mixer's native range",
              value);
        else
          config.volume_range_db = value;
      }

/* Get the default latency. Deprecated! */
      if (config_lookup_int(config.cfg, "latencies.default", &value))
        config.userSuppliedLatency = value;

      /* Get the itunes latency. Deprecated! */
      if (config_lookup_int(config.cfg, "latencies.itunes", &value))
        config.iTunesLatency = value;

      /* Get the AirPlay latency. Deprecated! */
      if (config_lookup_int(config.cfg, "latencies.airplay", &value))
        config.AirPlayLatency = value;

      /* Get the forkedDaapd latency. Deprecated! */
      if (config_lookup_int(config.cfg, "latencies.forkedDaapd", &value))
        config.ForkedDaapdLatency = value;

  #ifdef CONFIG_METADATA
      /* Get the metadata setting. */
      if (config_lookup_string(config.cfg, "metadata.enabled", &str)) {
        if (strcasecmp(str, "no") == 0)
          config.metadata_enabled = 0;
        else if (strcasecmp(str, "yes") == 0)
          config.metadata_enabled = 1;
        else
          die("Invalid metadata enabled option choice \"%s\". It should be \"yes\" or \"no\"");
      }

      if (config_lookup_string(config.cfg, "metadata.include_cover_art", &str)) {
        if (strcasecmp(str, "no") == 0)
          config.get_coverart = 0;
        else if (strcasecmp(str, "yes") == 0)
          config.get_coverart = 1;
        else
          die("Invalid metadata include_cover_art option choice \"%s\". It should be \"yes\" or "
              "\"no\"");
      }

      if (config_lookup_string(config.cfg, "metadata.pipe_name", &str)) {
        config.metadata_pipename = (char *)str;
      }

      if (config_lookup_string(config.cfg, "metadata.socket_address", &str)) {
        config.metadata_sockaddr = (char *)str;
      }
      if (config_lookup_int(config.cfg, "metadata.socket_port", &value)) {
        config.metadata_sockport = value;
      }
      config.metadata_sockmsglength = 500;
      if (config_lookup_int(config.cfg, "metadata.socket_msglength", &value)) {
        config.metadata_sockmsglength = value < 500 ? 500 : value > 65000 ? 65000 : value;
      }
      if (config_lookup_int(config.cfg, "metadata.pipe_timeout", &value)) {
      
        if ((value < 1) || (value > 150000))
          die("Invalid timeout range  \"%sd\". It should be in the range 1 to 150,000 milliseconds.",
              value);
        else
          config.metadata_pipe_timeout = value;
      }

  #endif

      if (config_lookup_string(config.cfg, "sessioncontrol.run_this_before_play_begins", &str)) {
        config.cmd_start = (char *)str;
      }

      if (config_lookup_string(config.cfg, "sessioncontrol.run_this_after_play_ends", &str)) {
        config.cmd_stop = (char *)str;
      }

      if (config_lookup_string(config.cfg, "sessioncontrol.wait_for_completion", &str)) {
        if (strcasecmp(str, "no") == 0)
          config.cmd_blocking = 0;
        else if (strcasecmp(str, "yes") == 0)
          config.cmd_blocking = 1;
        else
          die("Invalid session control wait_for_completion option choice \"%s\". It should be "
              "\"yes\" or \"no\"");
      }

      if (config_lookup_string(config.cfg, "sessioncontrol.allow_session_interruption", &str)) {
        config.dont_check_timeout = 0; // this is for legacy -- only set by -t 0
        if (strcasecmp(str, "no") == 0)
          config.allow_session_interruption = 0;
        else if (strcasecmp(str, "yes") == 0)
          config.allow_session_interruption = 1;
        else
          die("Invalid session control allow_interruption option choice \"%s\". It should be \"yes\" "
              "or \"no\"");
      }

      if (config_lookup_int(config.cfg, "sessioncontrol.session_timeout", &value)) {
        config.timeout = value;
        config.dont_check_timeout = 0; // this is for legacy -- only set by -t 0
      }

    } else {
      if (config_error_type(&config_file_stuff) == CONFIG_ERR_FILE_IO)
        debug(1, "Error reading configuration file \"%s\": \"%s\".",
              config_error_file(&config_file_stuff), config_error_text(&config_file_stuff));
      else {
        die("Line %d of the configuration file \"%s\":\n%s", config_error_line(&config_file_stuff),
            config_error_file(&config_file_stuff), config_error_text(&config_file_stuff));
      }
    }
    free(config_file_real_path);
  }

// now, do the command line options again, but this time do them fully -- it's a unix convention that command line
// arguments have precedence over configuration file settings.

  optind = argc;
  for (j = 0; j < argc; j++)
    if (strcmp(argv[j], "--") == 0)
      optind = j;

  optCon = poptGetContext(NULL, optind, (const char **)argv, optionsTable, 0);
  poptSetOtherOptionHelp(optCon, "[OPTIONS]* ");

  /* Now do options processing, get portname */
  int tdebuglev = 0;
  while ((c = poptGetNextOpt(optCon)) >= 0) {
    switch (c) {
    case 'v':
      tdebuglev++;
      break;
    case 't':
      if (config.timeout == 0) {
        config.dont_check_timeout = 1;
        config.allow_session_interruption = 1;
      } else {
        config.dont_check_timeout = 0;
        config.allow_session_interruption = 0;
      }
      break;
#ifdef CONFIG_METADATA
    case 'M':
      config.metadata_enabled = 1;
      break;
    case 'g':
      if (config.metadata_enabled == 0)
        die("If you want to get cover art, you must also select the --metadata-pipename option.");
      break;
#endif
    case 'S':
      if (strcmp(stuffing, "basic") == 0)
        config.packet_stuffing = ST_basic;
      else if (strcmp(stuffing, "soxr") == 0)
#ifdef HAVE_LIBSOXR
        config.packet_stuffing = ST_soxr;
#else
        die("soxr option not available -- this version of shairport-sync was built without libsoxr "
            "support");
#endif
      else
        die("Illegal stuffing option \"%s\" -- must be \"basic\" or \"soxr\"", stuffing);
      break;
    }
  }
コード例 #27
0
ファイル: test_ringdir.c プロジェクト: SethRobertson/libbk
/**
 * 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.
}
コード例 #28
0
ファイル: profiles.c プロジェクト: rchicoli/samba
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;
}
コード例 #29
0
ファイル: sss_ssh_authorizedkeys.c プロジェクト: nguay/SSSD
int main(int argc, const char **argv)
{
    TALLOC_CTX *mem_ctx = NULL;
    int pc_debug = SSSDBG_DEFAULT;
    const char *pc_domain = NULL;
    const char *pc_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 },
        { "domain", 'd', POPT_ARG_STRING, &pc_domain, 0,
          _("The SSSD domain to use"), NULL },
        POPT_TABLEEND
    };
    poptContext pc = NULL;
    const char *user;
    struct sss_ssh_ent *ent;
    size_t i;
    char *repr;
    int ret;

    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;
    }

    mem_ctx = talloc_new(NULL);
    if (!mem_ctx) {
        ERROR("Not enough memory\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* parse parameters */
    pc = poptGetContext(NULL, argc, argv, long_options, 0);
    poptSetOtherOptionHelp(pc, "USER");
    while ((ret = poptGetNextOpt(pc)) > 0)
        ;

    debug_level = debug_convert_old_level(pc_debug);

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

    pc_user = poptGetArg(pc);
    if (pc_user == NULL) {
        BAD_POPT_PARAMS(pc, _("User not specified\n"), ret, fini);
    }

    /* append domain to username if domain is specified */
    if (pc_domain) {
        user = talloc_asprintf(mem_ctx, "%s@%s", pc_user, pc_domain);
        if (!user) {
            ERROR("Not enough memory\n");
            ret = EXIT_FAILURE;
            goto fini;
        }
    } else {
        user = pc_user;
    }

    /* look up public keys */
    ret = sss_ssh_get_ent(mem_ctx, SSS_SSH_GET_USER_PUBKEYS,
                          user, NULL, &ent);
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE,
              ("sss_ssh_get_ent() failed (%d): %s\n", ret, strerror(ret)));
        ERROR("Error looking up public keys\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* print results */
    for (i = 0; i < ent->num_pubkeys; i++) {
        repr = sss_ssh_format_pubkey(mem_ctx, ent, &ent->pubkeys[i],
                                     SSS_SSH_FORMAT_OPENSSH, NULL);
        if (!repr) {
            ERROR("Not enough memory\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        printf("%s\n", repr);
    }

    ret = EXIT_SUCCESS;

fini:
    poptFreeContext(pc);
    talloc_free(mem_ctx);

    return ret;
}
コード例 #30
0
ファイル: nmblookup.c プロジェクト: 0x24bin/winexe-1
/*
  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;
}