Example #1
0
//top main
int main(int argc, char **argv){
	int i;
	struct argop options;
	int s = -1;
	struct hostent *serverhost = NULL;
	struct sockaddr_in server;
	char send_buf[BUF_LEN];
	char *get_buf;
	char hostname[STR_LEN];
	char path[LONG_STR_LEN];
	int port = 0;
	int read_size = 0;
	int opt_stat = 0;
	int send_buf_end = 0;

	get_buf = c_calloc_vec(LONG_BUF_LEN);
	init_options(&options);
	if(argc == 1){
		print_help();
		exit(0);
	}else if(argc >= 2){
		opt_stat = get_options(1,argc,argv,&options);
		strcpy(hostname,options.host);
		strcpy(path,options.path);
		port = options.port;
		if((serverhost = gethostbyname(hostname)) == NULL){
			printf("failed : gethostbyname().\n");
			exit(1);
		}
		bzero((char *)&server,sizeof(server));
		server.sin_family = AF_INET;
		bcopy(serverhost->h_addr,(char *)&server.sin_addr,serverhost->h_length);
		server.sin_port = htons(port);
		if((s = socket(AF_INET,SOCK_STREAM,0)) < 0){
			printf("failed : socket().\n");
			exit(1);
		}
		if(connect(s,(struct sockaddr *)&server,sizeof(server)) == -1){
			printf("failed : connect.\n");
			exit(1);
		}

		//get greeting - check "Ready."
		for(i=0;i<BUF_LEN;i++){
			get_buf[i] = '\0';
		}
		read_size = read(s,get_buf,BUF_LEN);
		printf("%s",get_buf);
		fprintf(stderr,"size:%d:",read_size);
		//read_size = read(s,get_buf,BUF_LEN);

		//send command
		sprintf(send_buf,"Test");
		send_buf_end = strlen(send_buf);
		send_buf[send_buf_end] = 0x04;
		send_buf[send_buf_end+1] = '\0';
		write(s,send_buf,strlen(send_buf));
		fprintf(stderr,"enter while...\n");

		//mode set
		//SetBlock(s,0); // non-block
		SetBlock(s,1); // block

		while(1){
			read_size = read(s,get_buf,BUF_LEN);
			if(read_size > 0){
				write(1,get_buf,read_size);
				close(s);
				exit(0);
			}else{
				break;
			}
			fprintf(stderr,"in while...\n");
		}
		fprintf(stderr,"exit while...\n");
		sprintf(send_buf,"end");
		send_buf_end = strlen(send_buf);
		send_buf[send_buf_end] = 0x04;
		send_buf[send_buf_end+1] = '\0';
		fprintf(stderr,"sending...\n");
		write(s,send_buf,strlen(send_buf));
		fprintf(stderr,"send.\n");
		read(s,get_buf,BUF_LEN);
		close(s);
		exit(0);
	}
	return(0);
}
Example #2
0
int main(int argc, char** argv) {
    int i;
    int rv;
    double time0, time1;

    int c, opt_i;
    int nloops = 0;
    char* gt = "";
    char* fname = "";

    static struct option long_opts[] = {
        {"help",   no_argument,       0, 0},
        {"type",   required_argument, 0, 0},
        {"nloops", required_argument, 0, 0},
        {"file",   required_argument, 0, 0}
    };

    /* Parse command-line arguments */
    while (1) {
        c = getopt_long(argc, argv, "", 
                long_opts, &opt_i);

        if (c == -1) {
            break;
        }

        if (c == 0) {
            switch (opt_i) {
                case 0:
                    print_help();
                    exit(0);
                case 1:
                    gt = optarg;
                    break;
                case 2:
                    nloops = atoi(optarg);
                    break;
                case 3:
                    fname = optarg;
                    break;
            }
        } else {
            print_help();
            exit(0);
        }
    }

    /* check for errors */
    if (gt == NULL || nloops < 1) {
        print_help();
        exit(0);
    }


    // initialize data structures
    rv = graph_init(gt, fname);
    if (rv < 0) {
        printf("Error creating graph. \n");
        exit(0);
    }

    // initialize data structures
    data_init();
    edge_data_init();

    // loop
    time0 = timer();
    for (i = 0; i < nloops; i++) {
        edge_gather(NEDGES, &gr, pt_data, edge_data);
        edge_compute(NEDGES, &gr);
        edge_scatter(NEDGES, &gr, pt_data);
    }
    time1 = timer();


    // print results
    for (i = 0; i < 10; i++) {
        printf("%i : %f %f %f \n", i, pt_data[i][0], pt_data[i][1], pt_data[i][2]);
    }

    printf("Time: %f s \n", (time1 - time0) / ((float) nloops));

    return 0;
}
Example #3
0
/**
 * \brief Main function of verse_client program.
 *
 * \details This program requires one argument (address of Verse server).
 * This function set up handling of signals (SIGINIT). This function register
 * all necessary callback functions and then send connect request to the
 * server. Then callback update function is called 30 times per
 * seconds (30 FPS).
 *
 * \param	argc	number of arguments
 * \param	argv	array of arguments
 *
 * \return	Returns 0, when client is finished successfully and non-zero value,
 * when it is finished with some error.
 */
int main(int argc, char *argv[])
{
	int error_num, opt, ret, flags = VRS_SEC_DATA_NONE;

	/* When client was started with some arguments */
	if(argc>1) {
		/* Parse all options */
		while( (opt = getopt(argc, argv, "hu:p:s:t:d:")) != -1) {
			switch(opt) {
				case 's':
					if(strcmp(optarg, "none") == 0) {
						flags |= VRS_SEC_DATA_NONE;
						flags &= ~VRS_SEC_DATA_TLS;
					} else if(strcmp(optarg, "tls") == 0) {
						flags &= ~VRS_SEC_DATA_NONE;
						flags |= VRS_SEC_DATA_TLS;
					} else {
						printf("ERROR: unsupported security\n\n");
						print_help(argv[0]);
						exit(EXIT_FAILURE);
					}
					break;
				case 't':
					if(strcmp(optarg, "udp") == 0) {
						flags |= VRS_TP_UDP;
						flags &= ~VRS_TP_TCP;
					} else if(strcmp(optarg, "tcp") == 0) {
						flags &= ~VRS_TP_UDP;
						flags |= VRS_TP_TCP;
					} else {
						printf("ERROR: unsupported transport protocol\n\n");
						print_help(argv[0]);
						exit(EXIT_FAILURE);
					}
					break;
				case 'u':
					my_username = optarg;
					break;
				case 'p':
					my_password = optarg;
					break;
				case 'c':
					if(strcmp(optarg, "none") == 0) {
						flags |= VRS_CMD_CMPR_NONE;
						flags &= ~VRS_CMD_CMPR_ADDR_SHARE;
					} else if(strcmp(optarg, "addrshare") == 0) {
						flags &= ~VRS_CMD_CMPR_NONE;
						flags |= VRS_CMD_CMPR_ADDR_SHARE;
					} else {
						printf("ERROR: unsupported command compression\n\n");
						print_help(argv[0]);
						exit(EXIT_FAILURE);
					}
					break;
				case 'd':
					ret = set_debug_level(optarg);
					if(ret != VRS_SUCCESS) {
						print_help(argv[0]);
						exit(EXIT_FAILURE);
					}
					break;
				case 'h':
					print_help(argv[0]);
					exit(EXIT_SUCCESS);
				case ':':
					exit(EXIT_FAILURE);
				case '?':
					exit(EXIT_FAILURE);
			}
		}

		/* The last argument has to be server name, not option */
		if(optind+1 != argc) {
			printf("Error: last argument has to be server name\n\n");
			print_help(argv[0]);
			exit(EXIT_FAILURE);
		}
	} else {
		printf("Error: no server specified\n\n");
		print_help(argv[0]);
		return EXIT_FAILURE;
	}

	/* Handle SIGINT signal. The handle_signal function will try to terminate
	 * connection. */
	signal(SIGINT, handle_signal);

	/* Register callback functions */
	vrs_register_receive_user_authenticate(cb_receive_user_authenticate);
	vrs_register_receive_connect_accept(cb_receive_connect_accept);
	vrs_register_receive_connect_terminate(cb_receive_connect_terminate);

	vrs_register_receive_node_create(cb_receive_node_create);
	vrs_register_receive_node_destroy(cb_receive_node_destroy);

	vrs_register_receive_node_owner(cb_receive_node_owner);
	vrs_register_receive_node_perm(cb_receive_node_perm);

	vrs_register_receive_node_lock(cb_receive_node_lock);
	vrs_register_receive_node_unlock(cb_receive_node_unlock);

	vrs_register_receive_node_link(cb_receive_node_link);

	vrs_register_receive_taggroup_create(cb_receive_taggroup_create);
	vrs_register_receive_taggroup_destroy(cb_receive_taggroup_destroy);

	vrs_register_receive_tag_create(cb_receive_tag_create);
	vrs_register_receive_tag_destroy(cb_receive_tag_destroy);

	vrs_register_receive_tag_set_value(cb_receive_tag_set_value);

	vrs_register_receive_layer_create(cb_receive_layer_create);
	vrs_register_receive_layer_destroy(cb_receive_layer_destroy);

	vrs_register_receive_layer_set_value(cb_receive_layer_set_value);
	vrs_register_receive_layer_unset_value(cb_receive_layer_unset_value);

	/* Set client name and version */
	vrs_set_client_info("Example Verse Client", "0.1");

	/* Send connect request to the server (it will also create independent thread for connection) */
#ifdef WITH_OPENSSL
	/* 12345 is secured port */
	error_num = vrs_send_connect_request(argv[optind], "12345", flags, &session_id);
#else
	/* 12344 is unsecured port */
	error_num = vrs_send_connect_request(argv[optind], "12344", flags, &session_id);
#endif

	if(error_num != VRS_SUCCESS) {
		printf("ERROR: %s\n", vrs_strerror(error_num));
		return EXIT_FAILURE;
	}

	/* Never ending loop */
	while(1) {
		vrs_callback_update(session_id);
		usleep(1000000/FPS);
	}

	return EXIT_SUCCESS;
}
Example #4
0
int
main (int argc, char *argv[]) {
#if PORTABLE
    strcpy (dbinstalldir, argv[0]);
    char *e = dbinstalldir + strlen (dbinstalldir);
    while (e >= dbinstalldir && *e != '/') {
        e--;
    }
    *e = 0;
#else
    strcpy (dbinstalldir, PREFIX);
#endif

#ifdef __linux__
    signal (SIGSEGV, sigsegv_handler);
#endif
    setlocale (LC_ALL, "");
    setlocale (LC_NUMERIC, "C");
#ifdef ENABLE_NLS
//    fprintf (stderr, "enabling gettext support: package=" PACKAGE ", dir=" LOCALEDIR "...\n");
#if PORTABLE
    char localedir[PATH_MAX];
    snprintf (localedir, sizeof (localedir), "%s/locale", dbinstalldir);
	bindtextdomain (PACKAGE, localedir);
#else
	bindtextdomain (PACKAGE, LOCALEDIR);
#endif
	bind_textdomain_codeset (PACKAGE, "UTF-8");
	textdomain (PACKAGE);
#endif

    int staticlink = 0;
    int portable = 0;
#if STATICLINK
    staticlink = 1;
#endif
#if PORTABLE
    portable = 1;
#endif

    fprintf (stderr, "starting deadbeef " VERSION "%s%s\n", staticlink ? " [static]" : "", portable ? " [portable]" : "");
    srand (time (NULL));
#ifdef __linux__
    prctl (PR_SET_NAME, "deadbeef-main", 0, 0, 0, 0);
#endif

#if PORTABLE_FULL
    if (snprintf (confdir, sizeof (confdir), "%s/config", dbinstalldir) > sizeof (confdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }

    strcpy (dbconfdir, confdir);
#else
    char *homedir = getenv ("HOME");
    if (!homedir) {
        fprintf (stderr, "unable to find home directory. stopping.\n");
        return -1;
    }

    char *xdg_conf_dir = getenv ("XDG_CONFIG_HOME");
    if (xdg_conf_dir) {
        if (snprintf (confdir, sizeof (confdir), "%s", xdg_conf_dir) > sizeof (confdir)) {
            fprintf (stderr, "fatal: XDG_CONFIG_HOME value is too long: %s\n", xdg_conf_dir);
            return -1;
        }
    }
    else {
        if (snprintf (confdir, sizeof (confdir), "%s/.config", homedir) > sizeof (confdir)) {
            fprintf (stderr, "fatal: HOME value is too long: %s\n", homedir);
            return -1;
        }
    }
    if (snprintf (dbconfdir, sizeof (dbconfdir), "%s/deadbeef", confdir) > sizeof (dbconfdir)) {
        fprintf (stderr, "fatal: out of memory while configuring\n");
        return -1;
    }
    mkdir (confdir, 0755);
#endif


#if PORTABLE
    if (snprintf (dbdocdir, sizeof (dbdocdir), "%s/doc", dbinstalldir) > sizeof (dbdocdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    if (snprintf (dbplugindir, sizeof (dbplugindir), "%s/plugins", dbinstalldir) > sizeof (dbplugindir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    if (snprintf (dbpixmapdir, sizeof (dbpixmapdir), "%s/pixmaps", dbinstalldir) > sizeof (dbpixmapdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    mkdir (dbplugindir, 0755);
#else
    if (snprintf (dbdocdir, sizeof (dbdocdir), "%s", DOCDIR) > sizeof (dbdocdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    if (snprintf (dbplugindir, sizeof (dbplugindir), "%s/deadbeef", LIBDIR) > sizeof (dbplugindir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    if (snprintf (dbpixmapdir, sizeof (dbpixmapdir), "%s/share/deadbeef/pixmaps", PREFIX) > sizeof (dbpixmapdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
#endif

    for (int i = 1; i < argc; i++) {
        // help, version and nowplaying are executed with any filter
        if (!strcmp (argv[i], "--help") || !strcmp (argv[i], "-h")) {
            print_help ();
            return 0;
        }
        else if (!strcmp (argv[i], "--version")) {
            fprintf (stdout, "DeaDBeeF " VERSION " Copyright © 2009-2011 Alexey Yakovenko\n");
            return 0;
        }
        else if (!strcmp (argv[i], "--gui")) {
            strncpy (use_gui_plugin, argv[i], sizeof(use_gui_plugin) - 1);
            use_gui_plugin[sizeof(use_gui_plugin) - 1] = 0;
        }
    }

    trace ("installdir: %s\n", dbinstalldir);
    trace ("confdir: %s\n", confdir);
    trace ("docdir: %s\n", dbdocdir);
    trace ("plugindir: %s\n", dbplugindir);
    trace ("pixmapdir: %s\n", dbpixmapdir);

    mkdir (dbconfdir, 0755);

    int size = 0;
    char *cmdline = prepare_command_line (argc, argv, &size);

    // try to connect to remote player
    int s, len;
    struct sockaddr_un remote;

    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    memset (&remote, 0, sizeof (remote));
    remote.sun_family = AF_UNIX;
#if USE_ABSTRACT_NAME
    memcpy (remote.sun_path, server_id, sizeof (server_id));
    len = offsetof(struct sockaddr_un, sun_path) + sizeof (server_id)-1;
#else
    char *socketdirenv = getenv ("DDB_SOCKET_DIR");
    snprintf (remote.sun_path, sizeof (remote.sun_path), "%s/socket", socketdirenv ? socketdirenv : dbconfdir);
    len = offsetof(struct sockaddr_un, sun_path) + strlen (remote.sun_path);
#endif
    if (connect(s, (struct sockaddr *)&remote, len) == 0) {
        // pass args to remote and exit
        if (send(s, cmdline, size, 0) == -1) {
            perror ("send");
            exit (-1);
        }
        // end of message
        shutdown(s, SHUT_WR);

        int sz = -1;
        char *out = read_entire_message(s, &sz);
        if (sz == -1) {
            fprintf (stderr, "failed to pass args to remote!\n");
            exit (-1);
        }
        else {
            // check if that's nowplaying response
            const char np[] = "nowplaying ";
            const char err[] = "error ";
            if (!strncmp (out, np, sizeof (np)-1)) {
                const char *prn = &out[sizeof (np)-1];
                fwrite (prn, 1, strlen (prn), stdout);
            }
            else if (!strncmp (out, err, sizeof (err)-1)) {
                const char *prn = &out[sizeof (err)-1];
                fwrite (prn, 1, strlen (prn), stderr);
            }
            else if (sz > 0 && out[0]) {
                fprintf (stderr, "%s\n", out);
            }
        }
        close (s);
        exit (0);
    }
//    else {
//        perror ("INFO: failed to connect to existing session:");
//    }
    close(s);

    // become a server
    if (server_start () < 0) {
        exit (-1);
    }

    // hack: report nowplaying
    if (!strcmp (cmdline, "--nowplaying")) {
        char nothing[] = "nothing";
        fwrite (nothing, 1, sizeof (nothing)-1, stdout);
        return 0;
    }

    pl_init ();
    conf_init ();
    conf_load (); // required by some plugins at startup

    if (use_gui_plugin[0]) {
        conf_set_str ("gui_plugin", use_gui_plugin);
    }

    conf_set_str ("deadbeef_version", VERSION);

    volume_set_db (conf_get_float ("playback.volume", 0)); // volume need to be initialized before plugins start
    messagepump_init (); // required to push messages while handling commandline
    if (plug_load_all ()) { // required to add files to playlist from commandline
        exit (-1);
    }
    pl_load_all ();
    plt_set_curr_idx (conf_get_int ("playlist.current", 0));

    // execute server commands in local context
    int noloadpl = 0;
    if (argc > 1) {
        int res = server_exec_command_line (cmdline, size, NULL, 0);
        // some of the server commands ran on 1st instance should terminate it
        if (res == 2) {
            noloadpl = 1;
        }
        else if (res > 0) {
            exit (0);
        }
        else if (res < 0) {
            exit (-1);
        }
    }

    free (cmdline);

#if 0
    signal (SIGTERM, sigterm_handler);
    atexit (atexit_handler); // helps to save in simple cases
#endif

    // start all subsystems
    messagepump_push (DB_EV_PLAYLISTCHANGED, 0, 0, 0);

    streamer_init ();

    plug_connect_all ();

    if (!noloadpl) {
        restore_resume_state ();
    }

    server_tid = thread_start (server_loop, NULL);
    // this runs in main thread (blocks right here)
    player_mainloop ();

    // terminate server and wait for completion
    if (server_tid) {
        server_terminate = 1;
        thread_join (server_tid);
        server_tid = 0;
    }

    // save config
    pl_save_all ();
    conf_save ();

    // delete legacy session file
    {
        char sessfile[1024]; // $HOME/.config/deadbeef/session
        if (snprintf (sessfile, sizeof (sessfile), "%s/deadbeef/session", confdir) < sizeof (sessfile)) {
            unlink (sessfile);
        }
    }

    // stop receiving messages from outside
    server_close ();

    // plugins might still hood references to playitems,
    // and query configuration in background
    // so unload everything 1st before final cleanup
    plug_disconnect_all ();
    plug_unload_all ();

    // at this point we can simply do exit(0), but let's clean up for debugging
    pl_free (); // may access conf_*
    conf_free ();
    messagepump_free ();
    plug_cleanup ();

    fprintf (stderr, "hej-hej!\n");
    return 0;
}
Example #5
0
int main(int argc, char * const argv[])
{
	u8 *buf;
	int found = 0;
	unsigned int fp;

	if (sizeof(u8) != 1)
	{
		fprintf(stderr, "%s: compiler incompatibility\n", argv[0]);
		exit(255);
	}

	/* Set default option values */
	opt.devmem = DEFAULT_MEM_DEV;
	opt.flags = 0;

	if (parse_command_line(argc, argv)<0)
		exit(2);

	if (opt.flags & FLAG_HELP)
	{
		print_help();
		return 0;
	}

	if (opt.flags & FLAG_VERSION)
	{
		printf("%s\n", VERSION);
		return 0;
	}

	if (!(opt.flags & FLAG_QUIET))
		printf("# vpddecode %s\n", VERSION);

	if ((buf = mem_chunk(0xF0000, 0x10000, opt.devmem)) == NULL)
		exit(1);

	for (fp = 0; fp <= 0xFFF0; fp += 4)
	{
		u8 *p = buf + fp;

		if (memcmp((char *)p, "\252\125VPD", 5) == 0
		 && fp + p[5] - 1 <= 0xFFFF)
		{
			if (fp % 16 && !(opt.flags & FLAG_QUIET))
				printf("# Unaligned address (%#x)\n",
				       0xf0000 + fp);
			if (opt.flags & FLAG_DUMP)
			{
				dump(p, p[5]);
				found++;
			}
			else
			{
				if (decode(p))
					found++;
			}
		}
	}

	free(buf);

	if (!found && !(opt.flags & FLAG_QUIET))
		printf("# No VPD structure found, sorry.\n");

	return 0;
}
Example #6
0
int main(int argc, char *argv[])
{
	struct iscsi_context *iscsi;
	const char *url = NULL;
	struct iscsi_url *iscsi_url = NULL;
	int evpd = 0, pagecode = 0;
	int show_help = 0, show_usage = 0, debug = 0;
	int c;

	static struct option long_options[] = {
		{"help",           no_argument,          NULL,        'h'},
		{"usage",          no_argument,          NULL,        'u'},
		{"debug",          no_argument,          NULL,        'd'},
		{"initiator_name", required_argument,    NULL,        'i'},
		{"evpd",           required_argument,    NULL,        'e'},
		{"pagecode",       required_argument,    NULL,        'c'},
		{0, 0, 0, 0}
	};
	int option_index;

	while ((c = getopt_long(argc, argv, "h?udi:e:c:", long_options,
			&option_index)) != -1) {
		switch (c) {
		case 'h':
		case '?':
			show_help = 1;
			break;
		case 'u':
			show_usage = 1;
			break;
		case 'd':
			debug = 1;
			break;
		case 'i':
			initiator = optarg;
			break;
		case 'e':
			evpd = atoi(optarg);
			break;
		case 'c':
			pagecode = atoi(optarg);
			break;
		default:
			fprintf(stderr, "Unrecognized option '%c'\n\n", c);
			print_help();
			exit(0);
		}
	}

	if (show_help != 0) {
		print_help();
		exit(0);
	}

	if (show_usage != 0) {
		print_usage();
		exit(0);
	}

	iscsi = iscsi_create_context(initiator);
	if (iscsi == NULL) {
		fprintf(stderr, "Failed to create context\n");
		exit(10);
	}

	if (debug > 0) {
		iscsi_set_log_level(iscsi, debug);
		iscsi_set_log_fn(iscsi, iscsi_log_to_stderr);
	}

	if (argv[optind] != NULL) {
		url = strdup(argv[optind]);
	}
	if (url == NULL) {
		fprintf(stderr, "You must specify the URL\n");
		print_usage();
		exit(10);
	}
	iscsi_url = iscsi_parse_full_url(iscsi, url);
	
	if (url) {
		free(discard_const(url));
	}

	if (iscsi_url == NULL) {
		fprintf(stderr, "Failed to parse URL: %s\n", 
			iscsi_get_error(iscsi));
		exit(10);
	}

	iscsi_set_targetname(iscsi, iscsi_url->target);
	iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL);
	iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);

	if (iscsi_url->user[0]) {
		if (iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user, iscsi_url->passwd) != 0) {
			fprintf(stderr, "Failed to set initiator username and password\n");
			exit(10);
		}
	}

	if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
		fprintf(stderr, "Login Failed. %s\n", iscsi_get_error(iscsi));
		iscsi_destroy_url(iscsi_url);
		iscsi_destroy_context(iscsi);
		exit(10);
	}

	do_inquiry(iscsi, iscsi_url->lun, evpd, pagecode);
	iscsi_destroy_url(iscsi_url);

	iscsi_logout_sync(iscsi);
	iscsi_destroy_context(iscsi);
	return 0;
}
Example #7
0
File: main.c Project: BeQ/webserver
int
main (int argc, char **argv)
{
	int                    re;
	ret_t                  ret;
	cint_t                 val;
	cint_t                 param_num;
	cint_t                 long_index;
	cherokee_downloader_t *downloader;
	cherokee_buffer_t      proxy       = CHEROKEE_BUF_INIT;
	cuint_t                proxy_port;

	struct option long_options[] = {
		/* Options without arguments */
		{"help",          no_argument,       NULL, 'h'},
		{"version",       no_argument,       NULL, 'V'},
		{"quiet",         no_argument,       NULL, 'q'},
		{"save-headers",  no_argument,       NULL, 's'},
		{"header",        required_argument, NULL,  0 },
		{NULL, 0, NULL, 0}
	};

	/* Parse known parameters
	 */
	while ((val = getopt_long (argc, argv, "VshqO:", long_options, &long_index)) != -1) {
		switch (val) {
		case 'V':
			printf ("Cherokee Downloader %s\n"
				"Written by Alvaro Lopez Ortega <[email protected]>\n\n"
				"Copyright (C) 2001-2013 Alvaro Lopez Ortega.\n"
				"This is free software; see the source for copying conditions.  There is NO\n"
				"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
				PACKAGE_VERSION);
			return EXIT_OK;

		case 'O':
			if (global_fd != UNSET_FD) {
				close (global_fd);
			}

			if ((strlen(optarg) == 1) && (optarg[0] == '-')) {
				global_fd = fileno(stdout);
			} else {
				global_fd = open (optarg, O_WRONLY | O_CREAT, 0644);
			}

			if (global_fd < 0) {
				PRINT_MSG ("ERROR: Can not open %s\n", optarg);
				return EXIT_ERROR;
			}
			break;

		case 0:
			break;

		case 'q':
			quiet = true;
			break;

		case 's':
			save_headers = true;
			break;

		case 'h':
		case '?':
		default:
			print_help();
			return EXIT_OK;
		}
	}

	/* The rest..
	 */
	param_num = argc - optind;

	if (param_num <= 0) {
		print_usage();
		return EXIT_OK;
	}

	/* Tracing and proxy discovering..
	 */
	cherokee_init();
	cget_find_proxy (&proxy, &proxy_port);

	for (val=optind; val<optind+param_num; val++) {
		cherokee_buffer_t url = CHEROKEE_BUF_INIT;

		/* Build the url buffer
		 */
		ret = cherokee_buffer_add_va (&url, "%s", argv[val]);
		if (ret != ret_ok)
			exit (EXIT_ERROR);

		/* Create the downloader object..
		 */
		ret = cherokee_downloader_new (&downloader);
		if (ret != ret_ok)
			exit (EXIT_ERROR);

		ret = cherokee_downloader_init(downloader);
		if (ret != ret_ok)
			exit (EXIT_ERROR);

		if (! cherokee_buffer_is_empty (&proxy)) {
			ret = cherokee_downloader_set_proxy (downloader, &proxy, proxy_port);
			if (ret != ret_ok)
				exit (EXIT_ERROR);
		}

		ret = cherokee_downloader_set_url (downloader, &url);
		if (ret != ret_ok)
			exit (EXIT_ERROR);

		ret = cherokee_downloader_connect (downloader);
		if (ret != ret_ok)
			exit (EXIT_ERROR);

		/* Download it!
		 */
		ret = do_download (downloader);
		if ((ret != ret_ok) && (ret != ret_eof)) {
			exit (EXIT_ERROR);
		}

		/* Free the objects..
		 */
		cherokee_buffer_mrproper (&url);
		cherokee_downloader_free (downloader);
	}

	/* Close the output file
	 */
	re = close (output_fd);
	if (re != 0)
		exit (EXIT_ERROR);

	cherokee_mrproper();
	return EXIT_OK;
}
Example #8
0
void CommandLine::parse_and_exec(){
  try{
    if(vm->count("help")){
      print_help();
      return;
    }
    else if(vm->count("interactive")){
      InteractiveMode * im = new InteractiveMode();
      im->start();
      return;
    }
    if(vm->count("file") + vm->count("max") + vm->count("random") != 1){
      std::cerr << "Need to provide exactly one of 'file', 'max' or 'random' options when not using interactive mode." << std::endl;
      return;
    }

    CNFFormula f;

    if(vm->count("file")){
      parse_file_options(f);
    }
    if(vm->count("random")){
      parse_random(f);
    }
    if(vm->count("max")){
      parse_max(f);
    }

    if(vm->count("minimalize")){
      f.minimalize();
    }
  
    if(vm->count("bruteforce")){
      SolvedCNF * solf = new SolvedCNF(f);
      std::cout << *solf << std::endl;
      delete solf;
    }

    if(vm->count("ppzfull")){
      Ppz * ppz = new Ppz(f);
      PpzRunStats stats;
      ppz->full_solve_ppz(stats);
      std::cout << stats << std::endl;
      delete ppz;
    }

    if(vm->count("ppzfulloracle")){
      Ppz * ppz = new Ppz(f);
      PpzRunStats stats;
      ppz->full_solve_ppz(stats,true);
      std::cout << stats << std::endl;
      delete ppz;
    }

    if(vm->count("ppzrandom")){
      Ppz * ppz = new Ppz(f);
      double limit = pow(2, f.get_n()-1.0/f.get_k());
      ppz->random_solve_ppz(limit);
    }

    std::string savefilename = "formula.cnf";
    if(vm->count("save")){
      savefilename = (*vm)["save"].as<std::string>();
      f.save(savefilename);
    }
  }

  catch(std::exception & e){
    std::cerr << e.what() << std::endl;
  }
}
Example #9
0
int main(int argc, char** argv)
{
	// get a configuration object
	Configuration &conf = Configuration::getInstance();

	int opt = 0;
	std::string p_hostname = conf.getHostname();
	std::string p_iface = "lo";
	std::string p_ntpserver = "127.0.0.1";
	bool p_gps = false;
	unsigned int _p_disco_port = 3232;
	unsigned int _p_port = 3486;

	while((opt = ::getopt(argc, argv, "hd:vgp:n:i:t:")) != -1)
	{
		switch (opt)
		{
		case 'h':
			print_help();
			return 0;

		case 'd':
			_p_disco_port = ::atoi(optarg);
			break;

		case 'p':
			_p_port = atoi(optarg);
			break;

		case 'g':
			p_gps = true;
			break;

		case 'n':
			p_hostname = optarg;
			break;

		case 'i':
			p_iface = optarg;
			break;

		case 't':
			p_ntpserver = optarg;
			break;

		default:
			std::cout << "unknown command" << std::endl;
			return -1;
		}
	}

	// some output for the user
	std::cout << "startup of hydra node daemon" << std::endl;
	std::cout << "hostname: " << p_hostname << std::endl;

	// listen on interface
	const ibrcommon::vinterface iface(p_iface);
	conf.setInterface(iface);

	// create a fake gps
	FakeGPS &gps = FakeGPS::getInstance();
	if (!p_gps) gps.disable();

	// create clock monitor instance
	ClockMonitor &cm = ClockMonitor::getInstance();
	cm.setReference(p_ntpserver);
	cm.start();

	// listen on incoming tcp connections
	CommandServer srv(_p_port);
	srv.start();

	while (true)
	{
		try {
			// run discovery module
			DiscoverComponent disco(p_hostname, _p_disco_port, iface);
			disco.run();
		} catch (const std::exception&) {
			// error retry in 2 seconds
			std::cout << "can not listen on multicast socket" << std::endl;
			ibrcommon::Thread::sleep(2000);
		}
	}
}
/* We use exec_style instead of #ifdef's because ebtables.so is a shared object. */
int do_command(int argc, char *argv[], int exec_style,
               struct ebt_u_replace *replace_)
{
	char *buffer;
	int c, i;
	int zerochain = -1; /* Needed for the -Z option (we can have -Z <this> -L <that>) */
	int chcounter; /* Needed for -C */
	int policy = 0;
	int rule_nr = 0;
	int rule_nr_end = 0;
	struct ebt_u_target *t;
	struct ebt_u_match *m;
	struct ebt_u_watcher *w;
	struct ebt_u_match_list *m_l;
	struct ebt_u_watcher_list *w_l;
	struct ebt_u_entries *entries;

	opterr = 0;
	ebt_modprobe = NULL;

	replace = replace_;

	/* The daemon doesn't use the environment variable */
	if (exec_style == EXEC_STYLE_PRG) {
		buffer = getenv(ATOMIC_ENV_VARIABLE);
		if (buffer) {
			replace->filename = malloc(strlen(buffer) + 1);
			if (!replace->filename)
				ebt_print_memory();
			strcpy(replace->filename, buffer);
			buffer = NULL;
		}
	}

	replace->flags &= OPT_KERNELDATA; /* ebtablesd needs OPT_KERNELDATA */
	replace->selected_chain = -1;
	replace->command = 'h';

	if (!new_entry) {
		new_entry = (struct ebt_u_entry *)malloc(sizeof(struct ebt_u_entry));
		if (!new_entry)
			ebt_print_memory();
	}
	/* Put some sane values in our new entry */
	ebt_initialize_entry(new_entry);
	new_entry->replace = replace;

	/* The scenario induced by this loop makes that:
	 * '-t'  ,'-M' and --atomic (if specified) have to come
	 * before '-A' and the like */

	/* Getopt saves the day */
	while ((c = getopt_long(argc, argv,
	   "-A:D:C:I:N:E:X::L::Z::F::P:Vhi:o:j:c:p:s:d:t:M:", ebt_options, NULL)) != -1) {
		switch (c) {

		case 'A': /* Add a rule */
		case 'D': /* Delete a rule */
		case 'C': /* Change counters */
		case 'P': /* Define policy */
		case 'I': /* Insert a rule */
		case 'N': /* Make a user defined chain */
		case 'E': /* Rename chain */
		case 'X': /* Delete chain */
			/* We allow -N chainname -P policy */
			if (replace->command == 'N' && c == 'P') {
				replace->command = c;
				optind--; /* No table specified */
				goto handle_P;
			}
			if (OPT_COMMANDS)
				ebt_print_error2("Multiple commands are not allowed");

			replace->command = c;
			replace->flags |= OPT_COMMAND;
			if (!(replace->flags & OPT_KERNELDATA))
				ebt_get_kernel_table(replace, 0);
			if (optarg && (optarg[0] == '-' || !strcmp(optarg, "!")))
				ebt_print_error2("No chain name specified");
			if (c == 'N') {
				if (ebt_get_chainnr(replace, optarg) != -1)
					ebt_print_error2("Chain %s already exists", optarg);
				else if (ebt_find_target(optarg))
					ebt_print_error2("Target with name %s exists", optarg);
				else if (strlen(optarg) >= EBT_CHAIN_MAXNAMELEN)
					ebt_print_error2("Chain name length can't exceed %d",
							EBT_CHAIN_MAXNAMELEN - 1);
				else if (strchr(optarg, ' ') != NULL)
					ebt_print_error2("Use of ' ' not allowed in chain names");
				ebt_new_chain(replace, optarg, EBT_ACCEPT);
				/* This is needed to get -N x -P y working */
				replace->selected_chain = ebt_get_chainnr(replace, optarg);
				break;
			} else if (c == 'X') {
				if (optind >= argc) {
					replace->selected_chain = -1;
					ebt_delete_chain(replace);
					break;
				}

				if (optind < argc - 1)
					ebt_print_error2("No extra options allowed with -X");

				if ((replace->selected_chain = ebt_get_chainnr(replace, argv[optind])) == -1)
					ebt_print_error2("Chain '%s' doesn't exist", argv[optind]);
				ebt_delete_chain(replace);
				if (ebt_errormsg[0] != '\0')
					return -1;
				optind++;
				break;
			}

			if ((replace->selected_chain = ebt_get_chainnr(replace, optarg)) == -1)
				ebt_print_error2("Chain '%s' doesn't exist", optarg);
			if (c == 'E') {
				if (optind >= argc)
					ebt_print_error2("No new chain name specified");
				else if (optind < argc - 1)
					ebt_print_error2("No extra options allowed with -E");
				else if (strlen(argv[optind]) >= EBT_CHAIN_MAXNAMELEN)
					ebt_print_error2("Chain name length can't exceed %d characters", EBT_CHAIN_MAXNAMELEN - 1);
				else if (ebt_get_chainnr(replace, argv[optind]) != -1)
					ebt_print_error2("Chain '%s' already exists", argv[optind]);
				else if (ebt_find_target(argv[optind]))
					ebt_print_error2("Target with name '%s' exists", argv[optind]);
				else if (strchr(argv[optind], ' ') != NULL)
					ebt_print_error2("Use of ' ' not allowed in chain names");
				ebt_rename_chain(replace, argv[optind]);
				optind++;
				break;
			} else if (c == 'D' && optind < argc && (argv[optind][0] != '-' || (argv[optind][1] >= '0' && argv[optind][1] <= '9'))) {
				if (optind != argc - 1)
					ebt_print_error2("No extra options allowed with -D start_nr[:end_nr]");
				if (parse_rule_range(argv[optind], &rule_nr, &rule_nr_end))
					ebt_print_error2("Problem with the specified rule number(s) '%s'", argv[optind]);
				optind++;
			} else if (c == 'C') {
				if ((chcounter = parse_change_counters_rule(argc, argv, &rule_nr, &rule_nr_end, exec_style)) == -1)
					return -1;
			} else if (c == 'I') {
				if (optind >= argc || (argv[optind][0] == '-' && (argv[optind][1] < '0' || argv[optind][1] > '9')))
					rule_nr = 1;
				else {
					rule_nr = strtol(argv[optind], &buffer, 10);
					if (*buffer != '\0')
						ebt_print_error2("Problem with the specified rule number '%s'", argv[optind]);
					optind++;
				}
			} else if (c == 'P') {
handle_P:
				if (optind >= argc)
					ebt_print_error2("No policy specified");
				for (i = 0; i < NUM_STANDARD_TARGETS; i++)
					if (!strcmp(argv[optind], ebt_standard_targets[i])) {
						policy = -i -1;
						if (policy == EBT_CONTINUE)
							ebt_print_error2("Wrong policy '%s'", argv[optind]);
						break;
					}
				if (i == NUM_STANDARD_TARGETS)
					ebt_print_error2("Unknown policy '%s'", argv[optind]);
				optind++;
			}
			break;
		case 'L': /* List */
		case 'F': /* Flush */
		case 'Z': /* Zero counters */
			if (c == 'Z') {
				if ((replace->flags & OPT_ZERO) || (replace->flags & OPT_COMMAND && replace->command != 'L'))
print_zero:
					ebt_print_error2("Command -Z only allowed together with command -L");
				replace->flags |= OPT_ZERO;
			} else {
				if (replace->flags & OPT_COMMAND)
					ebt_print_error2("Multiple commands are not allowed");
				replace->command = c;
				replace->flags |= OPT_COMMAND;
				if (replace->flags & OPT_ZERO && c != 'L')
					goto print_zero;
			}

#ifdef SILENT_DAEMON
			if (c== 'L' && exec_style == EXEC_STYLE_DAEMON)
				ebt_print_error2("-L not supported in daemon mode");
#endif

			if (!(replace->flags & OPT_KERNELDATA))
				ebt_get_kernel_table(replace, 0);
			i = -1;
			if (optind < argc && argv[optind][0] != '-') {
				if ((i = ebt_get_chainnr(replace, argv[optind])) == -1)
					ebt_print_error2("Chain '%s' doesn't exist", argv[optind]);
				optind++;
			}
			if (i != -1) {
				if (c == 'Z')
					zerochain = i;
				else
					replace->selected_chain = i;
			}
			break;
		case 'V': /* Version */
			if (OPT_COMMANDS)
				ebt_print_error2("Multiple commands are not allowed");
			replace->command = 'V';
			if (exec_style == EXEC_STYLE_DAEMON)
				ebt_print_error2(PROGNAME" v"PROGVERSION" ("PROGDATE")\n");
			PRINT_VERSION;
			exit(0);
		case 'M': /* Modprobe */
			if (OPT_COMMANDS)
				ebt_print_error2("Please put the -M option earlier");
			free(ebt_modprobe);
			ebt_modprobe = optarg;
			break;
		case 'h': /* Help */
#ifdef SILENT_DAEMON
			if (exec_style == EXEC_STYLE_DAEMON)
				ebt_print_error2("-h not supported in daemon mode");
#endif
			if (OPT_COMMANDS)
				ebt_print_error2("Multiple commands are not allowed");
			replace->command = 'h';

			/* All other arguments should be extension names */
			while (optind < argc) {
				struct ebt_u_match *m;
				struct ebt_u_watcher *w;

				if (!strcasecmp("list_extensions", argv[optind])) {
					ebt_list_extensions();
					exit(0);
				}
				if ((m = ebt_find_match(argv[optind])))
					ebt_add_match(new_entry, m);
				else if ((w = ebt_find_watcher(argv[optind])))
					ebt_add_watcher(new_entry, w);
				else {
					if (!(t = ebt_find_target(argv[optind])))
						ebt_print_error2("Extension '%s' not found", argv[optind]);
					if (replace->flags & OPT_JUMP)
						ebt_print_error2("Sorry, you can only see help for one target extension at a time");
					replace->flags |= OPT_JUMP;
					new_entry->t = (struct ebt_entry_target *)t;
				}
				optind++;
			}
			break;
		case 't': /* Table */
			if (OPT_COMMANDS)
				ebt_print_error2("Please put the -t option first");
			ebt_check_option2(&(replace->flags), OPT_TABLE);
			if (strlen(optarg) > EBT_TABLE_MAXNAMELEN - 1)
				ebt_print_error2("Table name length cannot exceed %d characters", EBT_TABLE_MAXNAMELEN - 1);
			strcpy(replace->name, optarg);
			break;
		case 'i': /* Input interface */
		case 2  : /* Logical input interface */
		case 'o': /* Output interface */
		case 3  : /* Logical output interface */
		case 'j': /* Target */
		case 'p': /* Net family protocol */
		case 's': /* Source mac */
		case 'd': /* Destination mac */
		case 'c': /* Set counters */
			if (!OPT_COMMANDS)
				ebt_print_error2("No command specified");
			if (replace->command != 'A' && replace->command != 'D' && replace->command != 'I' && replace->command != 'C')
				ebt_print_error2("Command and option do not match");
			if (c == 'i') {
				ebt_check_option2(&(replace->flags), OPT_IN);
				if (replace->selected_chain > 2 && replace->selected_chain < NF_BR_BROUTING)
					ebt_print_error2("Use -i only in INPUT, FORWARD, PREROUTING and BROUTING chains");
				if (ebt_check_inverse2(optarg))
					new_entry->invflags |= EBT_IIN;

				if (strlen(optarg) >= IFNAMSIZ)
big_iface_length:
					ebt_print_error2("Interface name length cannot exceed %d characters", IFNAMSIZ - 1);
				strcpy(new_entry->in, optarg);
				if (parse_iface(new_entry->in, "-i"))
					return -1;
				break;
			} else if (c == 2) {
				ebt_check_option2(&(replace->flags), OPT_LOGICALIN);
				if (replace->selected_chain > 2 && replace->selected_chain < NF_BR_BROUTING)
					ebt_print_error2("Use --logical-in only in INPUT, FORWARD, PREROUTING and BROUTING chains");
				if (ebt_check_inverse2(optarg))
					new_entry->invflags |= EBT_ILOGICALIN;

				if (strlen(optarg) >= IFNAMSIZ)
					goto big_iface_length;
				strcpy(new_entry->logical_in, optarg);
				if (parse_iface(new_entry->logical_in, "--logical-in"))
					return -1;
				break;
			} else if (c == 'o') {
				ebt_check_option2(&(replace->flags), OPT_OUT);
				if (replace->selected_chain < 2 )//|| replace->selected_chain == NF_BR_BROUTING)
					ebt_print_error2("Use -o only in OUTPUT, FORWARD and POSTROUTING chains");
				if (ebt_check_inverse2(optarg))
					new_entry->invflags |= EBT_IOUT;

				if (strlen(optarg) >= IFNAMSIZ)
					goto big_iface_length;
				strcpy(new_entry->out, optarg);
				if (parse_iface(new_entry->out, "-o"))
					return -1;
				break;
			} else if (c == 3) {
				ebt_check_option2(&(replace->flags), OPT_LOGICALOUT);
				if (replace->selected_chain < 2 || replace->selected_chain == NF_BR_BROUTING)
					ebt_print_error2("Use --logical-out only in OUTPUT, FORWARD and POSTROUTING chains");
				if (ebt_check_inverse2(optarg))
					new_entry->invflags |= EBT_ILOGICALOUT;

				if (strlen(optarg) >= IFNAMSIZ)
					goto big_iface_length;
				strcpy(new_entry->logical_out, optarg);
				if (parse_iface(new_entry->logical_out, "--logical-out"))
					return -1;    
				break;
			} else if (c == 'j') {
				ebt_check_option2(&(replace->flags), OPT_JUMP);
				for (i = 0; i < NUM_STANDARD_TARGETS; i++)
					if (!strcmp(optarg, ebt_standard_targets[i])) {
						t = ebt_find_target(EBT_STANDARD_TARGET);
						((struct ebt_standard_target *) t->t)->verdict = -i - 1;
						break;
					}
				if (-i - 1 == EBT_RETURN && replace->selected_chain < NF_BR_NUMHOOKS) {
					ebt_print_error2("Return target only for user defined chains");
				} else if (i != NUM_STANDARD_TARGETS)
					break;

				if ((i = ebt_get_chainnr(replace, optarg)) != -1) {
					if (i < NF_BR_NUMHOOKS)
						ebt_print_error2("Don't jump to a standard chain");
					t = ebt_find_target(EBT_STANDARD_TARGET);
					((struct ebt_standard_target *) t->t)->verdict = i - NF_BR_NUMHOOKS;
					break;
				} else {
					/* Must be an extension then */
					struct ebt_u_target *t;

					t = ebt_find_target(optarg);
					/* -j standard not allowed either */
					if (!t || t == (struct ebt_u_target *)new_entry->t)
						ebt_print_error2("Illegal target name '%s'", optarg);
					new_entry->t = (struct ebt_entry_target *)t;
					ebt_find_target(EBT_STANDARD_TARGET)->used = 0;
					t->used = 1;
				}
				break;
			} else if (c == 's') {
				ebt_check_option2(&(replace->flags), OPT_SOURCE);
				if (ebt_check_inverse2(optarg))
					new_entry->invflags |= EBT_ISOURCE;

				if (ebt_get_mac_and_mask(optarg, new_entry->sourcemac, new_entry->sourcemsk))
					ebt_print_error2("Problem with specified source mac '%s'", optarg);
				new_entry->bitmask |= EBT_SOURCEMAC;
				break;
			} else if (c == 'd') {
				ebt_check_option2(&(replace->flags), OPT_DEST);
				if (ebt_check_inverse2(optarg))
					new_entry->invflags |= EBT_IDEST;

				if (ebt_get_mac_and_mask(optarg, new_entry->destmac, new_entry->destmsk))
					ebt_print_error2("Problem with specified destination mac '%s'", optarg);
				new_entry->bitmask |= EBT_DESTMAC;
				break;
			} else if (c == 'c') {
				ebt_check_option2(&(replace->flags), OPT_COUNT);
				if (ebt_check_inverse2(optarg))
					ebt_print_error2("Unexpected '!' after -c");
				if (optind >= argc || optarg[0] == '-' || argv[optind][0] == '-')
					ebt_print_error2("Option -c needs 2 arguments");

				new_entry->cnt.pcnt = strtoull(optarg, &buffer, 10);
				if (*buffer != '\0')
					ebt_print_error2("Packet counter '%s' invalid", optarg);
				new_entry->cnt.bcnt = strtoull(argv[optind], &buffer, 10);
				if (*buffer != '\0')
					ebt_print_error2("Packet counter '%s' invalid", argv[optind]);
				optind++;
				break;
			}
			ebt_check_option2(&(replace->flags), OPT_PROTOCOL);
			if (ebt_check_inverse2(optarg))
				new_entry->invflags |= EBT_IPROTO;

			new_entry->bitmask &= ~((unsigned int)EBT_NOPROTO);
			i = strtol(optarg, &buffer, 16);
			if (*buffer == '\0' && (i < 0 || i > 0xFFFF))
				ebt_print_error2("Problem with the specified protocol");
			if (*buffer != '\0') {
				struct ethertypeent *ent;

				if (!strcasecmp(optarg, "LENGTH")) {
					new_entry->bitmask |= EBT_802_3;
					break;
				}
				ent = getethertypebyname(optarg);
				if (!ent)
					ebt_print_error2("Problem with the specified Ethernet protocol '%s', perhaps "_PATH_ETHERTYPES " is missing", optarg);
				new_entry->ethproto = ent->e_ethertype;
			} else
				new_entry->ethproto = i;

			if (new_entry->ethproto < 0x0600)
				ebt_print_error2("Sorry, protocols have values above or equal to 0x0600");
			break;
		case 4  : /* Lc */
#ifdef SILENT_DAEMON
			if (exec_style == EXEC_STYLE_DAEMON)
				ebt_print_error2("--Lc is not supported in daemon mode");
#endif
			ebt_check_option2(&(replace->flags), LIST_C);
			if (replace->command != 'L')
				ebt_print_error("Use --Lc with -L");
			replace->flags |= LIST_C;
			break;
		case 5  : /* Ln */
#ifdef SILENT_DAEMON
			if (exec_style == EXEC_STYLE_DAEMON)
				ebt_print_error2("--Ln is not supported in daemon mode");
#endif
			ebt_check_option2(&(replace->flags), LIST_N);
			if (replace->command != 'L')
				ebt_print_error2("Use --Ln with -L");
			if (replace->flags & LIST_X)
				ebt_print_error2("--Lx is not compatible with --Ln");
			replace->flags |= LIST_N;
			break;
		case 6  : /* Lx */
#ifdef SILENT_DAEMON
			if (exec_style == EXEC_STYLE_DAEMON)
				ebt_print_error2("--Lx is not supported in daemon mode");
#endif
			ebt_check_option2(&(replace->flags), LIST_X);
			if (replace->command != 'L')
				ebt_print_error2("Use --Lx with -L");
			if (replace->flags & LIST_N)
				ebt_print_error2("--Lx is not compatible with --Ln");
			replace->flags |= LIST_X;
			break;
		case 12 : /* Lmac2 */
#ifdef SILENT_DAEMON
			if (exec_style == EXEC_STYLE_DAEMON)
				ebt_print_error("--Lmac2 is not supported in daemon mode");
#endif
			ebt_check_option2(&(replace->flags), LIST_MAC2);
			if (replace->command != 'L')
				ebt_print_error2("Use --Lmac2 with -L");
			replace->flags |= LIST_MAC2;
			break;
		case 8 : /* atomic-commit */
			if (exec_style == EXEC_STYLE_DAEMON)
				ebt_print_error2("--atomic-commit is not supported in daemon mode");
			replace->command = c;
			if (OPT_COMMANDS)
				ebt_print_error2("Multiple commands are not allowed");
			replace->flags |= OPT_COMMAND;
			if (!replace->filename)
				ebt_print_error2("No atomic file specified");
			/* Get the information from the file */
			ebt_get_table(replace, 0);
			/* We don't want the kernel giving us its counters,
			 * they would overwrite the counters extracted from
			 * the file */
			replace->num_counters = 0;
			/* Make sure the table will be written to the kernel */
			free(replace->filename);
			replace->filename = NULL;
			break;
		case 7 : /* atomic-init */
		case 10: /* atomic-save */
		case 11: /* init-table */
			if (exec_style == EXEC_STYLE_DAEMON) {
				if (c == 7) {
					ebt_print_error2("--atomic-init is not supported in daemon mode");
				} else if (c == 10)
					ebt_print_error2("--atomic-save is not supported in daemon mode");
				ebt_print_error2("--init-table is not supported in daemon mode");
			}
			replace->command = c;
			if (OPT_COMMANDS)
				ebt_print_error2("Multiple commands are not allowed");
			if (c != 11 && !replace->filename)
				ebt_print_error2("No atomic file specified");
			replace->flags |= OPT_COMMAND;
			{
				char *tmp = replace->filename;

				/* Get the kernel table */
				replace->filename = NULL;
				ebt_get_kernel_table(replace, c == 10 ? 0 : 1);
				replace->filename = tmp;
			}
			break;
		case 9 : /* atomic */
			if (exec_style == EXEC_STYLE_DAEMON)
				ebt_print_error2("--atomic is not supported in daemon mode");
			if (OPT_COMMANDS)
				ebt_print_error2("--atomic has to come before the command");
			/* A possible memory leak here, but this is not
			 * executed in daemon mode */
			replace->filename = (char *)malloc(strlen(optarg) + 1);
			strcpy(replace->filename, optarg);
			break;
		case 13 : /* concurrent */
			signal(SIGINT, sighandler);
			signal(SIGTERM, sighandler);
			use_lockfd = 1;
			break;
		case 1 :
			if (!strcmp(optarg, "!"))
				ebt_check_inverse2(optarg);
			else
				ebt_print_error2("Bad argument : '%s'", optarg);
			/* ebt_check_inverse() did optind++ */
			optind--;
			continue;
		default:
			/* Is it a target option? */
			t = (struct ebt_u_target *)new_entry->t;
			if ((t->parse(c - t->option_offset, argv, argc, new_entry, &t->flags, &t->t))) {
				if (ebt_errormsg[0] != '\0')
					return -1;
				goto check_extension;
			}

			/* Is it a match_option? */
			for (m = ebt_matches; m; m = m->next)
				if (m->parse(c - m->option_offset, argv, argc, new_entry, &m->flags, &m->m))
					break;

			if (m != NULL) {
				if (ebt_errormsg[0] != '\0')
					return -1;
				if (m->used == 0) {
					ebt_add_match(new_entry, m);
					m->used = 1;
				}
				goto check_extension;
			}

			/* Is it a watcher option? */
			for (w = ebt_watchers; w; w = w->next)
				if (w->parse(c - w->option_offset, argv, argc, new_entry, &w->flags, &w->w))
					break;

			if (w == NULL && c == '?')
				ebt_print_error2("Unknown argument: '%s'", argv[optind - 1], (char)optopt, (char)c);
			else if (w == NULL) {
				if (!strcmp(t->name, "standard"))
					ebt_print_error2("Unknown argument: don't forget the -t option");
				else
					ebt_print_error2("Target-specific option does not correspond with specified target");
			}
			if (ebt_errormsg[0] != '\0')
				return -1;
			if (w->used == 0) {
				ebt_add_watcher(new_entry, w);
				w->used = 1;
			}
check_extension:
			if (replace->command != 'A' && replace->command != 'I' &&
			    replace->command != 'D' && replace->command != 'C')
				ebt_print_error2("Extensions only for -A, -I, -D and -C");
		}
		ebt_invert = 0;
	}

	/* Just in case we didn't catch an error */
	if (ebt_errormsg[0] != '\0')
		return -1;

	if (!(table = ebt_find_table(replace->name)))
		ebt_print_error2("Bad table name");

	if (replace->command == 'h' && !(replace->flags & OPT_ZERO)) {
		print_help();
		if (exec_style == EXEC_STYLE_PRG)
			exit(0);
	}

	/* Do the final checks */
	if (replace->command == 'A' || replace->command == 'I' ||
	   replace->command == 'D' || replace->command == 'C') {
		/* This will put the hook_mask right for the chains */
		ebt_check_for_loops(replace);
		if (ebt_errormsg[0] != '\0')
			return -1;
		entries = ebt_to_chain(replace);
		m_l = new_entry->m_list;
		w_l = new_entry->w_list;
		t = (struct ebt_u_target *)new_entry->t;
		while (m_l) {
			m = (struct ebt_u_match *)(m_l->m);
			m->final_check(new_entry, m->m, replace->name,
			   entries->hook_mask, 0);
			if (ebt_errormsg[0] != '\0')
				return -1;
			m_l = m_l->next;
		}
		while (w_l) {
			w = (struct ebt_u_watcher *)(w_l->w);
			w->final_check(new_entry, w->w, replace->name,
			   entries->hook_mask, 0);
			if (ebt_errormsg[0] != '\0')
				return -1;
			w_l = w_l->next;
		}
		t->final_check(new_entry, t->t, replace->name,
		   entries->hook_mask, 0);
		if (ebt_errormsg[0] != '\0')
			return -1;
	}
	/* So, the extensions can work with the host endian.
	 * The kernel does not have to do this of course */
	new_entry->ethproto = htons(new_entry->ethproto);

	if (replace->command == 'P') {
		if (replace->selected_chain < NF_BR_NUMHOOKS && policy == EBT_RETURN)
			ebt_print_error2("Policy RETURN only allowed for user defined chains");
		ebt_change_policy(replace, policy);
		if (ebt_errormsg[0] != '\0')
			return -1;
	} else if (replace->command == 'L') {
		list_rules();
		if (!(replace->flags & OPT_ZERO) && exec_style == EXEC_STYLE_PRG)
			exit(0);
	}
	if (replace->flags & OPT_ZERO) {
		replace->selected_chain = zerochain;
		ebt_zero_counters(replace);
	} else if (replace->command == 'F') {
		ebt_flush_chains(replace);
	} else if (replace->command == 'A' || replace->command == 'I') {
		ebt_add_rule(replace, new_entry, rule_nr);
		if (ebt_errormsg[0] != '\0')
			return -1;
		/* Makes undoing the add easier (jumps to delete_the_rule) */
		if (rule_nr <= 0)
			rule_nr--;
		rule_nr_end = rule_nr;

		/* a jump to a udc requires checking for loops */
		if (!strcmp(new_entry->t->u.name, EBT_STANDARD_TARGET) &&
		((struct ebt_standard_target *)(new_entry->t))->verdict >= 0) {
			/* FIXME: this can be done faster */
			ebt_check_for_loops(replace);
			if (ebt_errormsg[0] != '\0')
				goto delete_the_rule;
		}

		/* Do the final_check(), for all entries.
		 * This is needed when adding a rule that has a chain target */
		i = -1;
		while (++i != replace->num_chains) {
			struct ebt_u_entry *e;

			entries = replace->chains[i];
			if (!entries) {
				if (i < NF_BR_NUMHOOKS)
					continue;
				else
					ebt_print_bug("whoops\n");
			}
			e = entries->entries->next;
			while (e != entries->entries) {
				/* Userspace extensions use host endian */
				e->ethproto = ntohs(e->ethproto);
				ebt_do_final_checks(replace, e, entries);
				if (ebt_errormsg[0] != '\0')
					goto delete_the_rule;
				e->ethproto = htons(e->ethproto);
				e = e->next;
			}
		}
		/* Don't reuse the added rule */
		new_entry = NULL;
	} else if (replace->command == 'D') {
delete_the_rule:
		ebt_delete_rule(replace, new_entry, rule_nr, rule_nr_end);
		if (ebt_errormsg[0] != '\0')
			return -1;
	} else if (replace->command == 'C') {
		ebt_change_counters(replace, new_entry, rule_nr, rule_nr_end, &(new_entry->cnt_surplus), chcounter);
		if (ebt_errormsg[0] != '\0')
			return -1;
	}
	/* Commands -N, -E, -X, --atomic-commit, --atomic-commit, --atomic-save,
	 * --init-table fall through */

	if (ebt_errormsg[0] != '\0')
		return -1;
	if (table->check)
		table->check(replace);

	if (exec_style == EXEC_STYLE_PRG) {/* Implies ebt_errormsg[0] == '\0' */
		ebt_deliver_table(replace);

		if (replace->nentries)
			ebt_deliver_counters(replace);
	}
	return 0;
}
Example #11
0
int main(int argc,char*argv[])
{
	int incode,outcode,dist;
	char buff[MAX_BUFFER*3];
	char *pbuf;
	char *ps;
	int need_judge=1;


	int count;

	incode = 0;

	pbuf=&buff[2];

	if( strstr(argv[0],"autogb") != '\0' ){
		outcode=GB_CODE;
	}else if(strstr(argv[0],"autob5") != '\0'){
	
		outcode=BIG5_CODE;
	}
	/* We need one option for encoding at least*/
	if (argc >= 2){ 
	
		/*
		if(argv[1][0] != '-')
			print_help(argv[0]);

		for ( i = 1; i < strlen(argv[1]); i++)
			argv[1][i] = tolower(argv[1][i]);
		
		*/
		/* Get options here. */
		while(1){
			int c;
			int option_index ;
			static struct option long_options[] = 
			{
				{"input", 1, 0, 'i'},
				{"output", 1, 0, 'o'},
				{0, 0, 0, 0},
			};
//			c = getopt_long_only(argc, argv, "io", long_options,
//				&option_index);
			c = getopt_long(argc, argv, "i:o:", long_options,
				&option_index);

			/* No more option, break 'while' loop */
			if ( c == -1 ){
				break; /* While loop */
			}

			switch( c ){
				case 'i':
					need_judge=0;
					if(optarg){
						if((incode=conv_str(optarg))==OTHER_CODE) print_help(argv[0]);
					}else{
						print_help(argv[0]);
					}
					break;

				case 'o':
					if(optarg){
						if((outcode=conv_str(optarg))==OTHER_CODE) print_help(argv[0]);
					}else{
						print_help(argv[0]);
					}
					break;
				case '?':
				default:
					print_help(argv[0]);
					break;
			} /* End switch */

		} /* End while */
	} /* End else if */

	if((count=read(0,pbuf,MAX_BUFFER))< 0){
		fprintf(stderr,"Can't read stdin\n");
	}
	
	/* If incode is set in command line, don't judge. */
	if (need_judge==1)
		incode=j_code(pbuf,count);

	if (incode != outcode){
		hz_setup();
		if((dist=hz_search(incode,outcode,8))==0){
			printf("I couldn't do this conversion\n");
			exit(0);
		}
	}

	do{
		if(incode==outcode){
			write(1,pbuf,count);
		}else{
			ps=hz_convert(pbuf,&count,0);
			write(1,ps,count);
		}
		pbuf=&buff[2];
	}while((count=read(0,pbuf,MAX_BUFFER))>0);
	fflush(0);
}
Example #12
0
int
main(int argc, char *argv[])
{
  PBASIS p;
  OBSERVATION	futobs;
  struct date_time dt;
  char	inbuff[256],rastring[20],decstring[20];
  double **covar,**sigxy,a,b,PA,**derivs;
  double lat,lon,**covecl;
  double ra,dec, **coveq;
  double yr,mo,day,hr,mn,ss;
  double xx,yy,xy,bovasqrd,det;
  int i,nfields;

  int iarg=1;
  if (argc>1 && *argv[1]=='^') print_help();
  if (read_options(&iarg, argc, argv)) print_help();
  if (iarg>=argc) print_help();

  /* echo the command line to output */
  printf("#");
  for (i=0; i<argc; i++) printf(" %s",argv[i]);
  {
#include <time.h>
    time_t timettt;
    time(&timettt);
    /* note that ctime returns string with newline at end */
    printf("\n#---%s",ctime(&timettt));
  }

  sigxy = dmatrix(1,2,1,2);
  derivs = dmatrix(1,2,1,2);
  covar = dmatrix(1,6,1,6);
  covecl = dmatrix(1,2,1,2);
  coveq = dmatrix(1,2,1,2);

  if (read_abg(argv[iarg],&p,covar)) {
    fprintf(stderr, "Error input alpha/beta/gamma file %s\n",argv[iarg]);
    exit(1);
  }

  /* get observatory code */
  fprintf (stderr,"Enter observatory code:\n");
  if (fgets_nocomment(inbuff,255,stdin,NULL)==NULL
      || sscanf(inbuff,"%d",&futobs.obscode)!=1) {
    fprintf(stderr,"Error reading observatory code\n");
    exit(1);
  }
  printf("# For observations at site %d\n"
	 "#                 x/RA           y/DEC          "
	 "err_a    err_b  err_pa\n",futobs.obscode);

  fprintf (stderr,"Enter JD's or Y M D ... of observations, -1 to quit:\n");
  while ( fgets_nocomment(inbuff,255,stdin,NULL)!=NULL) {
    nfields=sscanf(inbuff,"%lf %lf %lf %lf %lf %lf",
		   &yr,&mo,&day,&hr,&mn,&ss);
    if (nfields==0 ) {
      fprintf(stderr,"Error on time spec:\n->%s\n",inbuff);
      exit(1);
    } else if (yr<0.) {
      /*done*/
      exit(0);
    } else if (nfields==1 || nfields==2) {
      /* Got a JD. (probably...)*/
      futobs.obstime = (yr-jd0)*DAY;
    } else {
      dt.y = yr;
      dt.mo = mo;
      dt.d = day;
      if (nfields>=4) dt.h = hr;  else dt.h=0.;
      if (nfields>=5) dt.mn = mn; else dt.mn=0.;
      if (nfields>=6) dt.s = ss;  else dt.s=0.;
      futobs.obstime = (date_to_jd(dt)-jd0)*DAY;
    }

    futobs.xe = -999.;		/* Force evaluation of earth3d */

    printf("At time= %s",inbuff);

    predict_posn(&p,covar,&futobs,sigxy);

    printf("# Solar Elongation = %.2f Opp angle = %.2f\n",
	   elongation(&futobs)/DTOR,opposition_angle(&futobs)/DTOR);

    /* Compute a, b, theta of error ellipse for output */
    xx = sigxy[1][1];
    yy = sigxy[2][2];
    xy = sigxy[1][2];
    PA = 0.5 * atan2(2.*xy,(xx-yy)) * 180./PI;	/*go right to degrees*/
    /* Adjust for PA to be N through E, */
    PA = PA-90;
    if (PA<-90.) PA += 180.;
    bovasqrd  = (xx+yy-sqrt(pow(xx-yy,2.)+pow(2.*xy,2.))) 
      / (xx+yy+sqrt(pow(xx-yy,2.)+pow(2.*xy,2.))) ;
    det = xx*yy-xy*xy;
    b = pow(det*bovasqrd,0.25);
    a = pow(det/bovasqrd,0.25);

    printf("Cum. ecliptic posn: %10.4f %10.4f   %8.2f %8.2f %7.2f\n",
	   futobs.thetax/ARCSEC, futobs.thetay/ARCSEC,
	   a/ARCSEC,b/ARCSEC,PA); 

    /* Now transform to RA/DEC, via ecliptic*/
    proj_to_ec(futobs.thetax,futobs.thetay,
	       &lat, &lon,
	       lat0, lon0, derivs);
    /* map the covariance */
    covar_map(sigxy, derivs, covecl, 2, 2);

    /* Now to ICRS: */
    ec_to_eq(lat, lon, &ra, &dec, derivs);
    /* map the covariance */
    covar_map(covecl, derivs, coveq, 2, 2);

    /* Compute a, b, theta of error ellipse for output */
    xx = coveq[1][1]*cos(dec)*cos(dec);
    xy = coveq[1][2]*cos(dec);
    yy = coveq[2][2];
    PA = 0.5 * atan2(2.*xy,(xx-yy)) * 180./PI;	/*go right to degrees*/
    /* Put PA N through E */
    PA = 90.-PA;
    bovasqrd  = (xx+yy-sqrt(pow(xx-yy,2.)+pow(2.*xy,2.))) 
      / (xx+yy+sqrt(pow(xx-yy,2.)+pow(2.*xy,2.))) ;
    det = xx*yy-xy*xy;
    b = pow(det*bovasqrd,0.25);
    a = pow(det/bovasqrd,0.25);

    ra /= DTOR;
    if (ra<0.) ra+= 360.;
    dec /= DTOR;
    deghms(ra,rastring);
    degdms(dec,decstring);
    printf("ICRS position: %s %s %10.4f %10.4f %7.2f\n",
	   rastring,decstring,a/ARCSEC,b/ARCSEC,PA); 
  }
  exit(0);
}
Example #13
0
void handle_command_line_arguments(int argc, char *argv[], char **cfg_file_path, LOG_BACKEND *log_backend,
                                   bool *run_in_foreground)
{
    if (argc < 2) {
        log_write(LOG_LEVEL_ERROR, "Error: No arguments provided.\n\n");
        print_help();
        exit(1);
    }

    opterr = 0;

    static struct option long_options[] = {
        {"config",      required_argument, 0, 'c'}, // required option
        {"foreground",  no_argument,       0, 'f'},
        {"help",        no_argument,       0, 'h'},
        {"log-backend", required_argument, 0, 'l'}, // optional, defaults to syslog
        {"version",     no_argument,       0, 'v'},
        {0,             0,                 0,  0 }
    };

    bool cfg_file_path_set = false;
    bool log_backend_set   = false;

    *run_in_foreground = false;

    int opt;

    while ((opt = getopt_long(argc, argv, ":", long_options, nullptr)) != -1) {

        switch (opt) {

            case 'c':
                *cfg_file_path = optarg;
                cfg_file_path_set = true;
                break;

            case 'f':
                *run_in_foreground = true;
                break;

            case 'h':
                print_help();
                exit(0);

            case 'l':
                if (strcmp(optarg, "syslog") == 0) {
                    *log_backend = LOG_BACKEND_SYSLOG;
                    log_backend_set = true;
                } else if (strcmp(optarg, "stdout") == 0) {
                    *log_backend = LOG_BACKEND_STDOUT;
                    log_backend_set = true;
                } else {
                    log_write(LOG_LEVEL_ERROR, "Error: Invalid BACKEND value for --log-backend option passed: %s\n\n", optarg);
                    print_help();
                    exit(1);
                }

                break;

            case 'v':
                log_write(LOG_LEVEL_INFO, "Version: %lu\n", DAEMON_VERSION_NUMBER);
                exit(0);

            case '?':
                log_write(LOG_LEVEL_ERROR, "Error: Unrecognized option %s\n\n", argv[optind - 1]);
                print_help();
                exit(1);

            case ':':
                log_write(LOG_LEVEL_ERROR, "Error: No argument provided for option %s\n\n", argv[optind - 1]);
                print_help();
                exit(1);
        }
    }

    if (!log_backend_set) {
        *log_backend = LOG_BACKEND_SYSLOG;
    }

    if (!cfg_file_path_set) {
        log_write(LOG_LEVEL_ERROR, "Error: The required --config option wasn't specified\n\n");
        print_help();
        exit(1);
    }
}
Example #14
0
int main(int argc, char *argv[])
{
	int get_tmp = 1, get_cmd;

	if(argc < 3) {
		print_help(argv[0]);
		exit(2);
	}

	int option_index = 0;
	static struct option long_options[] = {
		{ "mac", required_argument, 0, 'm' },
		{ "interface", required_argument, 0, 'i' },
		{ "vlan", required_argument, 0, 'v' },
		{ "dhcp_xid", required_argument, 0, 'x' },
		{ "tos", required_argument, 0, 't' },
		{ "option51-lease_time", required_argument, 0, 'L' },
		{ "option50-ip", required_argument, 0, 'I' },
		{ "option60-vci", required_argument, 0, 'o' },
		{ "option12-hostname", required_argument, 0, 'h' },
		{ "timeout", required_argument, 0, 'T' },
		{ "bind-ip", no_argument, 0, 'b' },
		{ "bind-timeout", required_argument, 0, 'k' },
		{ "bcast_flag", no_argument, 0, 'f'},
		{ "verbose", no_argument, 0, 'V'},
		{ "fqdn-server-not-update", no_argument, 0, 'n'},
		{ "fqdn-server-update-a", no_argument, 0, 's'},
		{ "fqdn-domain-name", required_argument, 0, 'd'},
		{ "padding", no_argument, 0, 'p'},
		{ "port", required_argument, 0, 'P'},
		{ "giaddr", required_argument, 0, 'g'},
		{ "unicast", optional_argument, 0, 'u'},
		{ "nagios", no_argument, 0, 'a'},
		{ "server", required_argument, 0, 'S'},
		{ "release", no_argument, 0, 'r'},
		{ 0, 0, 0, 0 }
	};

	/*getopt routine to get command line arguments*/
	while(get_tmp < argc) {
		get_cmd  = getopt_long(argc, argv, "m:i:v:t:bfVrpansu::T:P:g:S:I:o:k:L:h:d:",\
				long_options, &option_index);
		if(get_cmd == -1 ) {
			break;
		}
		switch(get_cmd) {
			case 'm':
				{
					u_char aux_dhmac[ETHER_ADDR_LEN + 1];

					if(strlen(optarg) > 18) {
						fprintf(stdout, "Invalid mac address\n");
						exit(2);
					}
					strcpy(dhmac_fname, optarg);
					sscanf((char *)optarg, "%2X:%2X:%2X:%2X:%2X:%2X",
							(u_int32_t *) &aux_dhmac[0], (u_int32_t *) &aux_dhmac[1],
							(u_int32_t *) &aux_dhmac[2], (u_int32_t *) &aux_dhmac[3],
							(u_int32_t *) &aux_dhmac[4], (u_int32_t *) &aux_dhmac[5]);
					memcpy(dhmac, aux_dhmac, sizeof(dhmac));
					dhmac_flag = 1;
				}
				break;

			case 'i':
				iface = if_nametoindex(optarg);
				if(iface == 0) {
					fprintf(stdout, "Interface doesnot exist\n");
					exit(2);
				}
				strncpy(iface_name, optarg, 29);
				break;

			case 'v':
				if(atoi(optarg) < 1 || atoi(optarg) > 4095)
				{
					fprintf(stdout, "VLAN ID is not valid. Range 1 to 4095\n");
					exit(2);
				}
				vlan = atoi(optarg);
				l2_hdr_size = 18;
				break;

			case 'r':
				dhcp_release_flag = 1;
				break;

			case 'b':
				ip_listen_flag = 1;
				break;

			case 'k':
				listen_timeout = atoi(optarg);
				tval_listen.tv_sec = listen_timeout;
				break;

			case 'x':
				{
					u_int32_t aux_dhcp_xid[2];
					aux_dhcp_xid[0] = 0;
					sscanf((char *)optarg, "%X", &aux_dhcp_xid[0]);
					dhcp_xid = aux_dhcp_xid[0];
				}
				break;

			case 't':
				if(atoi(optarg) >= 256 || atoi(optarg) < 0) {
					fprintf(stdout, "Invalid TOS value\n");
					exit(2);
				}
				l3_tos = atoi(optarg);
				break;

			case 'L':
				option51_lease_time = atoi(optarg);
				break;

			case 'I':
				option50_ip = inet_addr(optarg);
				break;

			case 'o':
				if(strlen(optarg) > 256) {
					fprintf(stdout, "VCI string size should be less than 256\n");
					exit(2);
				}
				vci_flag = 1;
				memcpy(vci_buff, optarg, sizeof(vci_buff));
				break;

			case 'h':
				if(strlen(optarg) > 256) {
					fprintf(stdout, "Hostname string size should be less than 256\n");
					exit(2);
				}
				hostname_flag = 1;
				memcpy(hostname_buff, optarg, sizeof(hostname_buff));
				break;

			case 'd':
				if(strlen(optarg) > 256) {
					fprintf(stdout, "FQDN domain name string size should be less than 256\n");
					exit(2);
				}
				fqdn_flag = 1;
				memcpy(fqdn_buff, optarg, sizeof(fqdn_buff));
				break;

			case 'n':
				fqdn_n = 1;
				break;

			case 's':
				fqdn_s = 1;
				break;

			case 'T':
				if(atoi(optarg) < 5 || atoi(optarg) > 3600) {
					fprintf(stdout, "Invalid timout value. Range 5 to 3600\n");
					exit(2);
				}
				timeout = atoi(optarg);
				break;

			case 'P':
				if(atoi(optarg) <=0 || atoi(optarg) > 65535) {
					fprintf(stdout, "Invalid portt value. Range 1 to 65535\n");
					exit(2);
				}
				port = atoi(optarg);
				break;

			case 'g':
				giaddr = optarg;
				break;

			case 'S':
				server_addr = optarg;
				break;

			case 'p':
				padding_flag = 1;
				break;

			case 'f':
				bcast_flag = htons(0x8000);
				break;

			case 'V':
				verbose = 1;
				break;

			case 'u':
				if (optarg) {
					struct in_addr out;

					if (!inet_aton(optarg, &out)) {
						fprintf(stdout, "Invalid unicast IP address.");
						exit(2);
					}
					unicast_ip_address = out.s_addr;
				}
				unicast_flag = 1;
				break;

			case 'a':
				nagios_flag = 1;
				break;

			default:
				exit(2);
		}
		get_tmp++;
	}	

	if(!dhmac_flag) {
		print_help(argv[0]);
		exit(2);
	}
	/* Opens the PF_PACKET socket */
	if(open_socket() < 0) {
		if (nagios_flag)
			fprintf(stdout, "CRITICAL: Socket error.");
		else
			fprintf(stdout, "Socket error\n");
		exit(2);
	}

	/* Sets the promiscuous mode */
	set_promisc();

	if (unicast_flag && !unicast_ip_address) {
		unicast_ip_address = get_interface_address();
	}

	/* Sets a random DHCP xid */
	set_rand_dhcp_xid(); 

	/*
	 * If DHCP release flag is set, send DHCP release packet
	 * and exit. get_dhinfo parses the DHCP info from log file
	 * and unlinks it from the system
	 */
	if(dhcp_release_flag) {
		if(get_dhinfo() == ERR_FILE_OPEN) {
			if (nagios_flag) {
				fprintf(stdout, "CRITICAL: Error on opening DHCP info file.");
			} else {
				fprintf(stdout, "Error on opening DHCP info file\n");
				fprintf(stdout, "Release the DHCP IP after acquiring\n");
			}
			exit(2);
		}
		build_option53(DHCP_MSGRELEASE); /* Option53 DHCP release */
		if(hostname_flag) {
			build_option12_hostname();
		}
		if(fqdn_flag) {
			build_option81_fqdn();
		}
		build_option54();		 /* Server id */
		build_optioneof();		 /* End of option */
		build_dhpacket(DHCP_MSGRELEASE); /* Build DHCP release packet */
		send_packet(DHCP_MSGRELEASE);	 /* Send DHCP release packet */
		clear_promisc();		 /* Clear the promiscuous mode */
		close_socket();
		return 0; 
	}
	if(timeout) {
		time_last = time(NULL);
	}
	build_option53(DHCP_MSGDISCOVER);	/* Option53 for DHCP discover */
	if(hostname_flag) {
		build_option12_hostname();
	}
	if(fqdn_flag) {
		build_option81_fqdn();
	}
	if(option50_ip) {
		build_option50();		/* Option50 - req. IP  */
	}
	if(option51_lease_time) {
		build_option51();               /* Option51 - DHCP lease time requested */
	}

	if(vci_flag == 1) {
		build_option60_vci(); 		/* Option60 - VCI  */
	}
	build_optioneof();			/* End of option */
	build_dhpacket(DHCP_MSGDISCOVER);	/* Build DHCP discover packet */

	int dhcp_offer_state = 0;
	while(dhcp_offer_state != DHCP_OFFR_RCVD) {

		/* Sends DHCP discover packet */
		send_packet(DHCP_MSGDISCOVER);
		/*
		 * recv_packet functions returns when the specified 
		 * packet is received
		 */
		dhcp_offer_state = recv_packet(DHCP_MSGOFFER); 

		if(timeout) {
			time_now = time(NULL);
			if((time_now - time_last) > timeout) {
				if (nagios_flag)
					fprintf(stdout, "CRITICAL: Timeout reached: DISCOVER.");
				close_socket();
				exit(2);
			}
		}
		if(dhcp_offer_state == DHCP_OFFR_RCVD) {
			if (!nagios_flag)
				fprintf(stdout, "DHCP offer received\t - ");
			set_serv_id_opt50();
			if (!nagios_flag)
  				fprintf(stdout, "Offered IP : %s\n", get_ip_str(dhcph_g->dhcp_yip));
			if(!nagios_flag && verbose) { 
				print_dhinfo(DHCP_MSGOFFER);
			}
		}
	}
	/* Reset the dhopt buffer to build DHCP request options  */
	reset_dhopt_size();
	build_option53(DHCP_MSGREQUEST); 
	build_option50();
	build_option54();
	if(hostname_flag) {
		build_option12_hostname();
	}
	if(fqdn_flag) {
		build_option81_fqdn();
	}
	if(vci_flag == 1) {
		build_option60_vci();  
	}
	if(option51_lease_time) {
		build_option51();                       /* Option51 - DHCP lease time requested */
	}
	build_option55();
	build_optioneof();
	build_dhpacket(DHCP_MSGREQUEST); 		/* Builds specified packet */
	int dhcp_ack_state = 1;
	while(dhcp_ack_state != DHCP_ACK_RCVD) { 

		send_packet(DHCP_MSGREQUEST);
		dhcp_ack_state = recv_packet(DHCP_MSGACK); 

		if(timeout) {
			time_now = time(NULL);
			if((time_now - time_last) > timeout) {
				if (nagios_flag)
					fprintf(stdout, "CRITICAL: Timeout reached: REQUEST.");
				else
					fprintf(stdout, "Timeout reached. Exiting\n");
				close_socket();
				exit(1);
			}
		}

		if(dhcp_ack_state == DHCP_ACK_RCVD) {
			if (nagios_flag) {
				fprintf(stdout, "OK: Acquired IP: %s", get_ip_str(dhcph_g->dhcp_yip));
			} else {
				fprintf(stdout, "DHCP ack received\t - ");
				fprintf(stdout, "Acquired IP: %s\n", get_ip_str(dhcph_g->dhcp_yip));
			}

			/* Logs DHCP IP details to log file. This file is used for DHCP release */
			log_dhinfo(); 
			if(!nagios_flag && verbose) {
				print_dhinfo(DHCP_MSGACK);
			}
		} else if (dhcp_ack_state == DHCP_NAK_RCVD) {
			if (!nagios_flag) {
				fprintf(stdout, "DHCP nack received\t - ");
				fprintf(stdout, "Client MAC : %02x:%02x:%02x:%02x:%02x:%02x\n", \
					dhmac[0], dhmac[1], dhmac[2], dhmac[3], dhmac[4], dhmac[5]); 
			}
		}
	}
	/* If IP listen flag is enabled, Listen on obtained for ARP, ICMP protocols  */
	if(!nagios_flag && ip_listen_flag) {
		fprintf(stdout, "\nListening on %s for ARP and ICMP protocols\n", iface_name);
		fprintf(stdout, "IP address: %s, Listen timeout: %d seconds\n", get_ip_str(htonl(ip_address)), listen_timeout);
		int arp_icmp_rcv_state = 0;
		while(arp_icmp_rcv_state != LISTEN_TIMOUET) { 
			arp_icmp_rcv_state = recv_packet(ARP_ICMP_RCV);
			/* Send ARP reply if ARP request received */
			if(arp_icmp_rcv_state == ARP_RCVD) {
				/*if(verbose) {
				  fprintf(stdout, "ARP request received\n");
				  fprintf(stdout, "Sending ARP reply\n");
				  }*/
				build_packet(ARP_SEND);
				send_packet(ARP_SEND);
			} else if(arp_icmp_rcv_state == ICMP_RCVD) {
				/* Send ICMP reply if ICMP echo request received */
				/*if(verbose) {
				  fprintf(stdout, "ICMP request received\n");
				  fprintf(stdout, "Sending ICMP reply\n");
				  }*/
				build_packet(ICMP_SEND);
				send_packet(ICMP_SEND);  
			} 
		}
		fprintf(stdout, "Listen timout reached\n");
	}
	/* Clear the promiscuous mode */
	clear_promisc();
	/* Close the socket */
	close_socket();
	return 0;
}
Example #15
0
/**
 *	@brief	Checks whether the given arguments are valid.
 *
 *	This consists in verifying that:
 *	- All the requested categories for the "dump" command exist
 *	- All the requested plugins exist
 *	- All the input files exist
 *	- The requested output formatter exists
 *
 *	If an error is detected, the help message is displayed.
 *
 *	@param	po::variables_map& vm The parsed arguments.
 *	@param	po::options_description& desc The description of the arguments (only so it can be
 *			passed to print_help if needed).
 *	@param	char** argv The raw arguments (only so it can be passed to print_help if needed).
 *
 *	@return	True if the arguments are all valid, false otherwise.
 */
bool validate_args(po::variables_map& vm, po::options_description& desc, char** argv)
{
	// Verify that the requested categories exist
	if (vm.count("dump"))
	{
		std::vector<std::string> selected_categories = tokenize_args(vm["dump"].as<std::vector<std::string> >());
		const std::vector<std::string> categories = boost::assign::list_of("all")("summary")("dos")("pe")("opt")("sections")
			("imports")("exports")("resources")("version")("debug")("tls")("config");
		for (auto it = selected_categories.begin() ; it != selected_categories.end() ; ++it)
		{
			std::vector<std::string>::const_iterator found = std::find(categories.begin(), categories.end(), *it);
			if (found == categories.end())
			{
				print_help(desc, argv[0]);
				std::cout << std::endl;
				PRINT_ERROR << "category " << *it << " does not exist!" << std::endl;
				return false;
			}
		}
	}

	// Verify that the requested plugins exist
	if (vm.count("plugins"))
	{
		std::vector<std::string> selected_plugins = tokenize_args(vm["plugins"].as<std::vector<std::string> >());
		std::vector<plugin::pIPlugin> plugins = plugin::PluginManager::get_instance().get_plugins();
		for (auto it = selected_plugins.begin() ; it != selected_plugins.end() ; ++it)
		{
			if (*it == "all") {
				continue;
			}

			auto found = std::find_if(plugins.begin(), plugins.end(), boost::bind(&plugin::name_matches, *it, _1));
			if (found == plugins.end())
			{
				print_help(desc, argv[0]);
				std::cout << std::endl;
				PRINT_ERROR << "plugin " << *it << " does not exist!" << std::endl;
				return false;
			}
		}
	}

	// Verify that all the input files exist.
	std::vector<std::string> input_files = vm["pe"].as<std::vector<std::string> >();
	for (auto it = input_files.begin() ; it != input_files.end() ; ++it)
	{
		if (!bfs::exists(*it))
		{
			PRINT_ERROR << *it << " not found!" << std::endl;
			return false;
		}
	}

	// Verify that the requested output formatter exists
	if (vm.count("output"))
	{
		auto formatters = boost::assign::list_of("raw")("json");
		auto found = std::find(formatters.begin(), formatters.end(), vm["output"].as<std::string>());
		if (found == formatters.end())
		{
			print_help(desc, argv[0]);
			std::cout << std::endl;
			PRINT_ERROR << "output formatter " << vm["output"].as<std::string>() << " does not exist!" << std::endl;
			return false;
		}
	}

	return true;
}
Example #16
0
/*-----------------------------------------------------------*/
static int parse_commandline(int argc, char **argv) {
  int  nargc , nargsused;
  char **pargv, *option ;

  if (argc < 1) usage_exit();

  nargc   = argc;
  pargv = argv;
  while (nargc > 0) {

    option = pargv[0];
    if (debug) printf("%d %s\n",nargc,option);
    nargc -= 1;
    pargv += 1;

    nargsused = 0;

    if (!strcasecmp(option, "--help"))  print_help() ;
    else if (!strcasecmp(option, "--version")) print_version() ;
    else if (!strcasecmp(option, "--debug"))   debug = 1;
    else if (!strcasecmp(option, "--checkopts"))   checkoptsonly = 1;
    else if (!strcasecmp(option, "--nocheckopts")) checkoptsonly = 0;
    else if (!strcasecmp(option, "--single")) single_path = 1;
    else if (!strcasecmp(option, "--label2path")) label_to_path = 1;
    else if (!strcasecmp(option, "--path2label")) path_to_label = 1;

    else if (!strcasecmp(option, "--connect")){
      if(nargc < 2) CMDargNErr(option,2);
      connect = 1;
      subject = pargv[0];
      hemi    = pargv[1];
      nargsused = 2;
    } 
    else if (!strcasecmp(option, "--fill")){
      if(nargc < 3) CMDargNErr(option,3);
      fill = 1;
      subject = pargv[0];
      hemi    = pargv[1];
      sscanf(pargv[2],"%d",&fillseed);
      nargsused = 3;
    } 
    else if (!strcasecmp(option, "--confillx")){
      if(nargc < 2) CMDargNErr(option,3);
      con_and_fillx = 1;
      surfacefname = pargv[0];
      sscanf(pargv[1],"%d",&fillseed);
      nargsused = 2;
    } 
    else if (!strcasecmp(option, "--confillxfn")){
      if(nargc < 2) CMDargNErr(option,3);
      con_and_fillx = 1;
      surfacefname = pargv[0];
      con_and_fillx_fname = pargv[1];
      path_to_label = 1;
      nargsused = 2;
    } 
    else if (!strcasecmp(option, "--confill")){
      if(nargc < 3) CMDargNErr(option,3);
      con_and_fill = 1;
      subject = pargv[0];
      hemi    = pargv[1];
      sscanf(pargv[2],"%d",&fillseed);
      nargsused = 3;
    } 
    else if (!strcasecmp(option, "--i")){
      if(nargc < 1) CMDargNErr(option,1);
      source_file = pargv[0];
      nargsused = 1;
    } 
    else if (!strcasecmp(option, "--o")){
      if(nargc < 1) CMDargNErr(option,1);
      dest_file = pargv[0];
      nargsused = 1;
    } 
    else {
      if(source_file == NULL) source_file = option;
      else if(dest_file == NULL) dest_file = option;
      else {
	fprintf(stderr,"ERROR: Option %s unknown\n",option);
	if(CMDsingleDash(option))
	  fprintf(stderr,"       Did you really mean -%s ?\n",option);
	exit(-1);
      }
    }
    nargc -= nargsused;
    pargv += nargsused;
  }
  return(0);
}
Example #17
0
int
main (int argc, char **argv)
{
  int last_argc = -1;
  int debug = 0;

  if (argc)
    {
      argc--;
      argv++;
    }

  /* We skip this test if we are running under the test suite (no args
     and srcdir defined) and GCRYPT_NO_BENCHMARKS is set.  */
  if (!argc && getenv ("srcdir") && getenv ("GCRYPT_NO_BENCHMARKS"))
    exit (77);

  if (getenv ("GCRYPT_IN_REGRESSION_TEST"))
    {
      in_regression_test = 1;
      num_measurement_repetitions = 2;
    }
  else
    num_measurement_repetitions = NUM_MEASUREMENT_REPETITIONS;

  while (argc && last_argc != argc)
    {
      last_argc = argc;

      if (!strcmp (*argv, "--"))
	{
	  argc--;
	  argv++;
	  break;
	}
      else if (!strcmp (*argv, "--help"))
	{
	  print_help ();
	  exit (0);
	}
      else if (!strcmp (*argv, "--verbose"))
	{
	  verbose++;
	  argc--;
	  argv++;
	}
      else if (!strcmp (*argv, "--debug"))
	{
	  verbose += 2;
	  debug++;
	  argc--;
	  argv++;
	}
      else if (!strcmp (*argv, "--csv"))
	{
	  csv_mode = 1;
	  argc--;
	  argv++;
	}
      else if (!strcmp (*argv, "--disable-hwf"))
	{
	  argc--;
	  argv++;
	  if (argc)
	    {
	      if (gcry_control (GCRYCTL_DISABLE_HWF, *argv, NULL))
		fprintf (stderr,
			 PGM
			 ": unknown hardware feature `%s' - option ignored\n",
			 *argv);
	      argc--;
	      argv++;
	    }
	}
      else if (!strcmp (*argv, "--cpu-mhz"))
	{
	  argc--;
	  argv++;
	  if (argc)
	    {
	      cpu_ghz = atof (*argv);
	      cpu_ghz /= 1000;	/* Mhz => Ghz */

	      argc--;
	      argv++;
	    }
	}
      else if (!strcmp (*argv, "--repetitions"))
	{
	  argc--;
	  argv++;
	  if (argc)
	    {
	      num_measurement_repetitions = atof (*argv);
              if (num_measurement_repetitions < 2)
                {
                  fprintf (stderr,
                           PGM
                           ": value for --repetitions too small - using %d\n",
                           NUM_MEASUREMENT_REPETITIONS);
                  num_measurement_repetitions = NUM_MEASUREMENT_REPETITIONS;
                }
	      argc--;
	      argv++;
	    }
	}
    }

  gcry_control (GCRYCTL_SET_VERBOSITY, (int) verbose);

  if (!gcry_check_version (GCRYPT_VERSION))
    {
      fprintf (stderr, PGM ": version mismatch; pgm=%s, library=%s\n",
	       GCRYPT_VERSION, gcry_check_version (NULL));
      exit (1);
    }

  if (debug)
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);

  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);

  if (in_regression_test)
    fputs ("Note: " PGM " running in quick regression test mode.\n", stdout);

  if (!argc)
    {
      warm_up_cpu ();
      hash_bench (NULL, 0);
      mac_bench (NULL, 0);
      cipher_bench (NULL, 0);
    }
  else if (!strcmp (*argv, "hash"))
    {
      argc--;
      argv++;

      warm_up_cpu ();
      hash_bench ((argc == 0) ? NULL : argv, argc);
    }
  else if (!strcmp (*argv, "mac"))
    {
      argc--;
      argv++;

      warm_up_cpu ();
      mac_bench ((argc == 0) ? NULL : argv, argc);
    }
  else if (!strcmp (*argv, "cipher"))
    {
      argc--;
      argv++;

      warm_up_cpu ();
      cipher_bench ((argc == 0) ? NULL : argv, argc);
    }
  else
    {
      fprintf (stderr, PGM ": unknown argument: %s\n", *argv);
      print_help ();
    }

  return 0;
}
Example #18
0
void print_help_and_exit() {
    print_help();
    exit( EXIT_FAILURE );
}
Example #19
0
/* process command-line arguments */
static int
process_arguments (int argc, char **argv)
{
	int c;
	int escape = 0;
	char *temp;

	int option = 0;
	static struct option longopts[] = {
		{"hostname", required_argument, 0, 'H'},
		{"critical", required_argument, 0, 'c'},
		{"warning", required_argument, 0, 'w'},
		{"critical-codes", required_argument, 0, 'C'},
		{"warning-codes", required_argument, 0, 'W'},
		{"timeout", required_argument, 0, 't'},
		{"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */
		{"port", required_argument, 0, 'p'},
		{"escape", no_argument, 0, 'E'},
		{"all", no_argument, 0, 'A'},
		{"send", required_argument, 0, 's'},
		{"expect", required_argument, 0, 'e'},
		{"maxbytes", required_argument, 0, 'm'},
		{"quit", required_argument, 0, 'q'},
		{"jail", no_argument, 0, 'j'},
		{"delay", required_argument, 0, 'd'},
		{"refuse", required_argument, 0, 'r'},
		{"mismatch", required_argument, 0, 'M'},
		{"use-ipv4", no_argument, 0, '4'},
		{"use-ipv6", no_argument, 0, '6'},
		{"verbose", no_argument, 0, 'v'},
		{"version", no_argument, 0, 'V'},
		{"help", no_argument, 0, 'h'},
		{"ssl", no_argument, 0, 'S'},
		{"certificate", required_argument, 0, 'D'},
		{0, 0, 0, 0}
	};

	if (argc < 2)
		usage4 (_("No arguments found"));

	/* backwards compatibility */
	for (c = 1; c < argc; c++) {
		if (strcmp ("-to", argv[c]) == 0)
			strcpy (argv[c], "-t");
		else if (strcmp ("-wt", argv[c]) == 0)
			strcpy (argv[c], "-w");
		else if (strcmp ("-ct", argv[c]) == 0)
			strcpy (argv[c], "-c");
	}

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

	while (1) {
		c = getopt_long (argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
		                 longopts, &option);

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

		switch (c) {
		case '?':                 /* print short usage statement if args not parsable */
			usage5 ();
		case 'h':                 /* help */
			print_help ();
			exit (STATE_OK);
		case 'V':                 /* version */
			print_revision (progname, NP_VERSION);
			exit (STATE_OK);
		case 'v':                 /* verbose mode */
			flags |= FLAG_VERBOSE;
			break;
		case '4':
			address_family = AF_INET;
			break;
		case '6':
#ifdef USE_IPV6
			address_family = AF_INET6;
#else
			usage4 (_("IPv6 support not available"));
#endif
			break;
		case 'H':                 /* hostname */
			server_address = optarg;
			break;
		case 'c':                 /* critical */
			critical_time = strtod (optarg, NULL);
			flags |= FLAG_TIME_CRIT;
			break;
		case 'j':		  /* hide output */
			flags |= FLAG_HIDE_OUTPUT;
			break;
		case 'w':                 /* warning */
			warning_time = strtod (optarg, NULL);
			flags |= FLAG_TIME_WARN;
			break;
		case 'C':
			crit_codes = realloc (crit_codes, ++crit_codes_count);
			crit_codes[crit_codes_count - 1] = optarg;
			break;
		case 'W':
			warn_codes = realloc (warn_codes, ++warn_codes_count);
			warn_codes[warn_codes_count - 1] = optarg;
			break;
		case 't':                 /* timeout */
			if (!is_intpos (optarg))
				usage4 (_("Timeout interval must be a positive integer"));
			else
				socket_timeout = atoi (optarg);
			break;
		case 'p':                 /* port */
			if (!is_intpos (optarg))
				usage4 (_("Port must be a positive integer"));
			else
				server_port = atoi (optarg);
			break;
		case 'E':
			escape = 1;
			break;
		case 's':
			if (escape)
				server_send = np_escaped_string(optarg);
			else
				xasprintf(&server_send, "%s", optarg);
			break;
		case 'e': /* expect string (may be repeated) */
			flags &= ~FLAG_EXACT_MATCH;
			if (server_expect_count == 0)
				server_expect = malloc (sizeof (char *) * (++server_expect_count));
			else
				server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
			server_expect[server_expect_count - 1] = optarg;
			break;
		case 'm':
			if (!is_intpos (optarg))
				usage4 (_("Maxbytes must be a positive integer"));
			else
				maxbytes = strtol (optarg, NULL, 0);
			break;
		case 'q':
			if (escape)
				server_quit = np_escaped_string(optarg);
			else
				xasprintf(&server_quit, "%s\r\n", optarg);
			break;
		case 'r':
			if (!strncmp(optarg,"ok",2))
				econn_refuse_state = STATE_OK;
			else if (!strncmp(optarg,"warn",4))
				econn_refuse_state = STATE_WARNING;
			else if (!strncmp(optarg,"crit",4))
				econn_refuse_state = STATE_CRITICAL;
			else
				usage4 (_("Refuse must be one of ok, warn, crit"));
			break;
		case 'M':
			if (!strncmp(optarg,"ok",2))
				expect_mismatch_state = STATE_OK;
			else if (!strncmp(optarg,"warn",4))
				expect_mismatch_state = STATE_WARNING;
			else if (!strncmp(optarg,"crit",4))
				expect_mismatch_state = STATE_CRITICAL;
			else
				usage4 (_("Mismatch must be one of ok, warn, crit"));
			break;
		case 'd':
			if (is_intpos (optarg))
				delay = atoi (optarg);
			else
				usage4 (_("Delay must be a positive integer"));
			break;
		case 'D': /* Check SSL cert validity - days 'til certificate expiration */
#ifdef HAVE_SSL
#  ifdef USE_OPENSSL /* XXX */
			if ((temp=strchr(optarg,','))!=NULL) {
			    *temp='\0';
			    if (!is_intnonneg (optarg))
                               usage2 (_("Invalid certificate expiration period"), optarg);				 days_till_exp_warn = atoi(optarg);
			    *temp=',';
			    temp++;
			    if (!is_intnonneg (temp))
				usage2 (_("Invalid certificate expiration period"), temp);
			    days_till_exp_crit = atoi (temp);
			}
			else {
			    days_till_exp_crit=0;
			    if (!is_intnonneg (optarg))
				usage2 (_("Invalid certificate expiration period"), optarg);
			    days_till_exp_warn = atoi (optarg);
			}
			check_cert = TRUE;
			flags |= FLAG_SSL;
			break;
#  endif /* USE_OPENSSL */
#endif
			/* fallthrough if we don't have ssl */
		case 'S':
#ifdef HAVE_SSL
			flags |= FLAG_SSL;
#else
			die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
#endif
			break;
		case 'A':
			flags |= FLAG_MATCH_ALL;
			break;
		}
	}

	if (server_address == NULL)
		usage4 (_("You must provide a server address"));
	else if (server_address[0] != '/' && is_host (server_address) == FALSE)
		die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address);

	return TRUE;
}
Example #20
0
int main(int argc, char **argv){
	if (argc==1)
		print_help(argv[0]);
	int i;
	char *outfile=NULL;
	char *assetfile="assets.h";
	// First pass cancel out the options, let only the files
	for (i=1;i<argc;i++){
		if (strcmp(argv[i],"--help")==0)
			print_help();
		else if (strcmp(argv[i],"-o")==0){
			if (i>=argc-1){
				fprintf(stderr,"ERROR: Need an argument for -o");
				exit(2);
			}
			outfile=argv[i+1];
			argv[i]=NULL; // cancel them out.
			argv[i+1]=NULL; 
			i++;
		}
		else if (strcmp(argv[i],"-a")==0){
			if (i>=argc-1){
				fprintf(stderr,"ERROR: Need an argument for -a");
				exit(2);
			}
			assetfile=argv[i+1];
			argv[i]=NULL; // cancel them out.
			argv[i+1]=NULL; 
			i++;
		}
	}
	
	FILE *outfd=stdout;
	if (outfile){
		outfd=fopen(outfile,"w");
		if (!outfd){
			perror("ERROR: Could not open output file");
			exit(2);
		}
	}
	onion_assets_file *assets=onion_assets_file_new(assetfile);
	
	// Some header...
	fprintf(outfd,"/** File autogenerated by opack **/\n\n");
  fprintf(outfd,"#include <onion/request.h>\n\n");
	fprintf(outfd,"#include <onion/response.h>\n\n");
  fprintf(outfd,"#include <string.h>\n\n");
	
	for (i=1;i<argc;i++){
		if (argv[i]){
      struct stat st;
      stat(argv[i], &st);
      if (S_ISDIR(st.st_mode)){
        parse_directory(basename(argv[1]), argv[i], outfd, assets);
      }
      else{
        parse_file("", argv[i], outfd, assets);
      }
		}
	}
	
	if (outfile){
		fclose(outfd);
	}
	onion_assets_file_free(assets);
	
	return 0;
}
Example #21
0
int main(int argc, char **argv)
{
	std::string LocSocket = "/tmp/ipdupdetect";
	std::unique_ptr<PIDFile> PidFile;
	std::string LocPidFile = "";
	const char *opts = "hdp:";
	int longindex = 0;
	int c = 0;
	int debug = 0;
	struct option loptions[]
	{
		{"help", 0, 0, 'h'},
		{"pid", 1, 0, 'p'},
		{"debug", 0, 0, 'd'},
		{0, 0, 0, 0}
	};
	
	while( (c = getopt_long(argc, argv, opts, loptions, &longindex)) >= 0)
	{
		switch(c)
		{
			case 'd':
				debug = 1;
				break;
			case 'h':
				print_help(stdout, argv[0]);
				exit(EXIT_SUCCESS);
				break;
			case 'p':
				LocPidFile = optarg;
				break;
			default:
				break;
		}
	}
	
	//Add Logging
	if (isatty(fileno(stdout)) == 1)
	{
		std::shared_ptr<ILogger> tmp = std::make_shared<LogStdoutColor>();
		LogManager::Add(tmp);
	} else {
		std::shared_ptr<ILogger> tmp = std::make_shared<LogStdout>();
		LogManager::Add(tmp);
	}

	if (debug)
	{
		LogManager::SetLevel(LOGGER_DEBUG);
	}
	else
	{
		LogManager::SetLevel(LOGGER_INFO);
	}
	
	if (LocPidFile != "")
	{
		PidFile.reset(new PIDFile(LocPidFile));
		if (PidFile->Create() == false)
		{
			LogCritical("Cannot Create PID file '%s'", LocPidFile.c_str());
			exit(EXIT_FAILURE);
		}
		LogInfo("Created PID file '%s'", LocPidFile.c_str());
	}

	SigHandler SHandler;
	SignalHandler Signals = SignalHandler(&SHandler);
	Signals.Block();

	do
	{
		ServerManager *SrvManager = NULL;
		MonitorManager MManager;
		Service *Srv = new Service(&MManager); //Bind instance of MonitorManager to the ServiceProxy
		struct timespec timeout = {60, 0}; //Timeout to reprocess interface list
		ScopedLock lock(&ExitLock);
		SHandler.SetMonitorManager(&MManager); //Bind MonitorManager to signal handler proxy

		
		ServerUnixPolled Unix(LocSocket); //Create a suitable socket
		SrvManager = new ServerManager(Srv); //Create a new server instance
		SrvManager->ServerAdd(&Unix); //Bind our Service proxy to the socket instance

		Signals.UnBlock();
		while(DoExit == false)
		{
			MManager.Scan();
			MManager.Purge();
			ExitLock.Wait(&timeout);
		}
		lock.Unlock(); //Required to prevent hang in signals
		
		SrvManager->ServerRemove(&Unix);
		delete Srv;
		delete SrvManager;
		
		Signals.Block();
		SHandler.SetMonitorManager(NULL);
		Signals.UnBlock();
		
	} while(0);


	return 0;
}
Example #22
0
Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phase) {

    RID_OwnerBase::init_rid();

    OS::get_singleton()->initialize_core();
    ObjectTypeDB::init();

    MAIN_PRINT("Main: Initialize CORE");

    register_core_types();
    register_core_driver_types();

    MAIN_PRINT("Main: Initialize Globals");


    Thread::_main_thread_id = Thread::get_caller_ID();

    globals = memnew( Globals );
    input_map = memnew( InputMap );


    path_remap = memnew( PathRemap );
    translation_server = memnew( TranslationServer );
    performance = memnew( Performance );
    globals->add_singleton(Globals::Singleton("Performance",performance));

    MAIN_PRINT("Main: Parse CMDLine");

    /* argument parsing and main creation */
    List<String> args;
    List<String> main_args;

    for(int i=0; i<argc; i++) {

        args.push_back(String::utf8(argv[i]));
    }

    List<String>::Element *I=args.front();

    I=args.front();

    while (I) {

        I->get()=unescape_cmdline(I->get().strip_escapes());
//		print_line("CMD: "+I->get());
        I=I->next();
    }

    I=args.front();

    video_mode = OS::get_singleton()->get_default_video_mode();

    String video_driver="";
    String audio_driver="";
    String game_path=".";
    String debug_mode;
    String debug_host;
    String main_pack;
    bool quiet_stdout=false;
    int rtm=-1;

    String remotefs;
    String remotefs_pass;

    String screen = "";

    List<String> pack_list;
    Vector<String> breakpoints;
    bool use_custom_res=true;
    bool force_res=false;

    I=args.front();

    packed_data = PackedData::get_singleton();
    if (!packed_data)
        packed_data = memnew(PackedData);

#ifdef MINIZIP_ENABLED
    packed_data->add_pack_source(ZipArchive::get_singleton());
#endif

    bool editor=false;

    while(I) {

        List<String>::Element *N=I->next();

        if (I->get() == "-noop") {

            // no op
        } else if (I->get()=="-h" || I->get()=="--help" || I->get()=="/?") { // resolution

            goto error;


        } else if (I->get()=="-r") { // resolution

            if (I->next()) {

                String vm=I->next()->get();

                if (vm.find("x")==-1) { // invalid parameter format

                    goto error;


                }

                int w=vm.get_slice("x",0).to_int();
                int h=vm.get_slice("x",1).to_int();

                if (w==0 || h==0) {

                    goto error;

                }

                video_mode.width=w;
                video_mode.height=h;
                force_res=true;

                N=I->next()->next();
            } else {
                goto error;


            }

        } else if (I->get()=="-vd") { // video driver

            if (I->next()) {

                video_driver=I->next()->get();
                N=I->next()->next();
            } else {
                goto error;

            }
        } else if (I->get()=="-lang") { // language

            if (I->next()) {

                locale=I->next()->get();
                N=I->next()->next();
            } else {
                goto error;

            }
        } else if (I->get()=="-rfs") { // language

            if (I->next()) {

                remotefs=I->next()->get();
                N=I->next()->next();
            } else {
                goto error;

            }
        } else if (I->get()=="-rfs_pass") { // language

            if (I->next()) {

                remotefs_pass=I->next()->get();
                N=I->next()->next();
            } else {
                goto error;

            }
        } else if (I->get()=="-rthread") { // language

            if (I->next()) {

                if (I->next()->get()=="safe")
                    rtm=OS::RENDER_THREAD_SAFE;
                else if (I->next()->get()=="unsafe")
                    rtm=OS::RENDER_THREAD_UNSAFE;
                else if (I->next()->get()=="separate")
                    rtm=OS::RENDER_SEPARATE_THREAD;


                N=I->next()->next();
            } else {
                goto error;

            }

        } else if (I->get()=="-ad") { // video driver

            if (I->next()) {

                audio_driver=I->next()->get();
                N=I->next()->next();
            } else {
                goto error;

            }

        } else if (I->get()=="-f") { // fullscreen

            video_mode.fullscreen=true;
        } else if (I->get()=="-e" || I->get()=="-editor") { // fonud editor

            editor=true;

        } else if (I->get()=="-nowindow") { // fullscreen

            OS::get_singleton()->set_no_window_mode(true);
        } else if (I->get()=="-quiet") { // fullscreen

            quiet_stdout=true;
        } else if (I->get()=="-v") { // fullscreen
            OS::get_singleton()->_verbose_stdout=true;
        } else if (I->get()=="-path") { // resolution

            if (I->next()) {

                String p = I->next()->get();
                if (OS::get_singleton()->set_cwd(p)==OK) {
                    //nothing
                } else {
                    game_path=I->next()->get(); //use game_path instead
                }

                N=I->next()->next();
            } else {
                goto error;

            }
        } else if (I->get()=="-bp") { // /breakpoints

            if (I->next()) {

                String bplist = I->next()->get();
                breakpoints= bplist.split(",");
                N=I->next()->next();
            } else {
                goto error;

            }


        } else if (I->get()=="-fdelay") { // resolution

            if (I->next()) {

                OS::get_singleton()->set_frame_delay(I->next()->get().to_int());
                N=I->next()->next();
            } else {
                goto error;

            }

        } else if (I->get()=="-timescale") { // resolution

            if (I->next()) {

                OS::get_singleton()->set_time_scale(I->next()->get().to_double());
                N=I->next()->next();
            } else {
                goto error;

            }


        } else if (I->get() == "-pack") {

            if (I->next()) {

                pack_list.push_back(I->next()->get());
                N = I->next()->next();
            } else {

                goto error;
            };

        } else if (I->get() == "-main_pack") {

            if (I->next()) {

                main_pack=I->next()->get();
                N = I->next()->next();
            } else {

                goto error;
            };

        } else if (I->get()=="-debug" || I->get()=="-d") {
            debug_mode="local";
        } else if (I->get()=="-editor_scene") {

            if (I->next()) {

                Globals::get_singleton()->set("editor_scene",game_path=I->next()->get());
            } else {
                goto error;

            }

        } else if (I->get()=="-rdebug") {
            if (I->next()) {

                debug_mode="remote";
                debug_host=I->next()->get();
                if (debug_host.find(":")==-1) //wrong host
                    goto error;
                N=I->next()->next();
            } else {
                goto error;

            }
        } else {

            //test for game path
            bool gpfound=false;

            if (!I->get().begins_with("-") && game_path=="") {
                DirAccess* da = DirAccess::open(I->get());
                if (da!=NULL) {
                    game_path=I->get();
                    gpfound=true;
                    memdelete(da);
                }

            }

            if (!gpfound) {
                main_args.push_back(I->get());
            }
        }

        I=N;
    }



    if (debug_mode == "remote") {

        ScriptDebuggerRemote *sdr = memnew( ScriptDebuggerRemote );
        uint16_t debug_port = GLOBAL_DEF("debug/remote_port",6007);
        if (debug_host.find(":")!=-1) {
            debug_port=debug_host.get_slice(":",1).to_int();
            debug_host=debug_host.get_slice(":",0);
        }
        Error derr = sdr->connect_to_host(debug_host,debug_port);

        if (derr!=OK) {
            memdelete(sdr);
        } else {
            script_debugger=sdr;

        }
    } else if (debug_mode=="local") {

        script_debugger = memnew( ScriptDebuggerLocal );
    }


    if (remotefs!="") {

        file_access_network_client=memnew(FileAccessNetworkClient);
        int port;
        if (remotefs.find(":")!=-1) {
            port=remotefs.get_slice(":",1).to_int();
            remotefs=remotefs.get_slice(":",0);
        } else {
            port=6010;
        }

        Error err = file_access_network_client->connect(remotefs,port,remotefs_pass);
        if (err) {
            OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i\n",remotefs.utf8().get_data(),port);
            goto error;
        }

        FileAccess::make_default<FileAccessNetwork>(FileAccess::ACCESS_RESOURCES);
    }
    if (script_debugger) {
        //there is a debugger, parse breakpoints

        for(int i=0; i<breakpoints.size(); i++) {

            String bp = breakpoints[i];
            int sp=bp.find_last(":");
            if (sp==-1) {
                ERR_EXPLAIN("Invalid breakpoint: '"+bp+"', expected file:line format.");
                ERR_CONTINUE(sp==-1);
            }

            script_debugger->insert_breakpoint(bp.substr(sp+1,bp.length()).to_int(),bp.substr(0,sp));
        }
    }


#ifdef TOOLS_ENABLED
    if (editor) {
        packed_data->set_disabled(true);
        globals->set_disable_platform_override(true);
    }

#endif


    if (globals->setup(game_path,main_pack)!=OK) {

#ifdef TOOLS_ENABLED
        editor=false;
#else
        OS::get_singleton()->print("error: Couldn't load game path '%s'\n",game_path.ascii().get_data());

        goto error;
#endif
    }

    if (editor) {
        main_args.push_back("-editor");
        use_custom_res=false;
    }

    if (bool(Globals::get_singleton()->get("application/disable_stdout"))) {
        quiet_stdout=true;
    }

    if (quiet_stdout)
        _print_line_enabled=false;

    OS::get_singleton()->set_cmdline(execpath, main_args);

#ifdef TOOLS_ENABLED

    if (main_args.size()==0 && (!Globals::get_singleton()->has("application/main_loop_type")) && (!Globals::get_singleton()->has("application/main_scene") || String(Globals::get_singleton()->get("application/main_scene"))==""))
        use_custom_res=false; //project manager (run without arguments)

#endif

    input_map->load_from_globals();

    if (video_driver=="") // specified in engine.cfg
        video_driver=_GLOBAL_DEF("display/driver",Variant((const char*)OS::get_singleton()->get_video_driver_name(0)));

    if (!force_res && use_custom_res && globals->has("display/width"))
        video_mode.width=globals->get("display/width");
    if (!force_res &&use_custom_res && globals->has("display/height"))
        video_mode.height=globals->get("display/height");
    if (use_custom_res && globals->has("display/fullscreen"))
        video_mode.fullscreen=globals->get("display/fullscreen");
    if (use_custom_res && globals->has("display/resizable"))
        video_mode.resizable=globals->get("display/resizable");

    if (!force_res && use_custom_res && globals->has("display/test_width") && globals->has("display/test_height")) {
        int tw = globals->get("display/test_width");
        int th = globals->get("display/test_height");
        if (tw>0 && th>0) {
            video_mode.width=tw;
            video_mode.height=th;
        }
    }


    GLOBAL_DEF("display/width",video_mode.width);
    GLOBAL_DEF("display/height",video_mode.height);
    GLOBAL_DEF("display/fullscreen",video_mode.fullscreen);
    GLOBAL_DEF("display/resizable",video_mode.resizable);
    GLOBAL_DEF("display/test_width",0);
    GLOBAL_DEF("display/test_height",0);
    if (rtm==-1) {
        rtm=GLOBAL_DEF("render/thread_model",OS::RENDER_THREAD_SAFE);
    }

    if (rtm>=0 && rtm<3)
        OS::get_singleton()->_render_thread_mode=OS::RenderThreadMode(rtm);



    /* Determine Video Driver */

    if (audio_driver=="") // specified in engine.cfg
        audio_driver=GLOBAL_DEF("audio/driver",OS::get_singleton()->get_audio_driver_name(0));


    for (int i=0; i<OS::get_singleton()->get_video_driver_count(); i++) {

        if (video_driver==OS::get_singleton()->get_video_driver_name(i)) {

            video_driver_idx=i;
            break;
        }
    }

    if (video_driver_idx<0) {

        OS::get_singleton()->alert( "Invalid Video Driver: "+video_driver );
        video_driver_idx = 0;
        //goto error;
    }

    for (int i=0; i<OS::get_singleton()->get_audio_driver_count(); i++) {

        if (audio_driver==OS::get_singleton()->get_audio_driver_name(i)) {

            audio_driver_idx=i;
            break;
        }
    }

    if (audio_driver_idx<0) {

        OS::get_singleton()->alert( "Invalid Audio Driver: "+audio_driver );
        goto error;
    }

    {
        String orientation = GLOBAL_DEF("display/orientation","landscape");

        if (orientation=="portrait")
            OS::get_singleton()->set_screen_orientation(OS::SCREEN_PORTRAIT);
        else if (orientation=="reverse_landscape")
            OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_LANDSCAPE);
        else if (orientation=="reverse_portrait")
            OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_PORTRAIT);
        else if (orientation=="sensor_landscape")
            OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_LANDSCAPE);
        else if (orientation=="sensor_portrait")
            OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_PORTRAIT);
        else if (orientation=="sensor")
            OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR);
        else
            OS::get_singleton()->set_screen_orientation(OS::SCREEN_LANDSCAPE);
    }

    OS::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/fixed_fps",60));
    OS::get_singleton()->set_target_fps(GLOBAL_DEF("application/target_fps",0));

    if (!OS::get_singleton()->_verbose_stdout) //overrided
        OS::get_singleton()->_verbose_stdout=GLOBAL_DEF("debug/verbose_stdout",false);

    message_queue = memnew( MessageQueue );

    Globals::get_singleton()->register_global_defaults();

    if (p_second_phase)
        return setup2();

    return OK;

error:

    video_driver="";
    audio_driver="";
    game_path="";

    args.clear();
    main_args.clear();

    print_help(execpath);


    if (performance)
        memdelete(performance);
    if (input_map)
        memdelete(input_map);
    if (translation_server)
        memdelete( translation_server );
    if (globals)
        memdelete(globals);
    if (script_debugger)
        memdelete(script_debugger);
    if (packed_data)
        memdelete(packed_data);
    if (file_access_network_client)
        memdelete(file_access_network_client);
    unregister_core_types();

    OS::get_singleton()->_cmdline.clear();

    if (message_queue)
        memdelete( message_queue);
    OS::get_singleton()->finalize_core();
    locale=String();

    return ERR_INVALID_PARAMETER;
}
Example #23
0
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
  int c;
  char *warning = NULL;
  char *critical = NULL;

  int opt_index = 0;
  static struct option long_opts[] = {
    {"help", no_argument, 0, 'h'},
    {"version", no_argument, 0, 'V'},
    {"verbose", no_argument, 0, 'v'},
    {"timeout", required_argument, 0, 't'},
    {"hostname", required_argument, 0, 'H'},
    {"server", required_argument, 0, 's'},
    {"reverse-server", required_argument, 0, 'r'},
    {"expected-address", required_argument, 0, 'a'},
    {"expect-authority", no_argument, 0, 'A'},
    {"warning", required_argument, 0, 'w'},
    {"critical", required_argument, 0, 'c'},
    {0, 0, 0, 0}
  };

  if (argc < 2)
    return ERROR;

  for (c = 1; c < argc; c++)
    if (strcmp ("-to", argv[c]) == 0)
      strcpy (argv[c], "-t");

  while (1) {
    c = getopt_long (argc, argv, "hVvAt:H:s:r:a:w:c:", long_opts, &opt_index);

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

    switch (c) {
    case 'h': /* help */
      print_help ();
      exit (STATE_UNKNOWN);
    case 'V': /* version */
      print_revision (progname, NP_VERSION);
      exit (STATE_UNKNOWN);
    case 'v': /* version */
      verbose = TRUE;
      break;
    case 't': /* timeout period */
      timeout_interval = atoi (optarg);
      break;
    case 'H': /* hostname */
      if (strlen (optarg) >= ADDRESS_LENGTH)
        die (STATE_UNKNOWN, _("Input buffer overflow\n"));
      strcpy (query_address, optarg);
      break;
    case 's': /* server name */
      /* TODO: this host_or_die check is probably unnecessary.
       * Better to confirm nslookup response matches */
      host_or_die(optarg);
      if (strlen (optarg) >= ADDRESS_LENGTH)
        die (STATE_UNKNOWN, _("Input buffer overflow\n"));
      strcpy (dns_server, optarg);
      break;
    case 'r': /* reverse server name */
      /* TODO: Is this host_or_die necessary? */
      host_or_die(optarg);
      if (strlen (optarg) >= ADDRESS_LENGTH)
        die (STATE_UNKNOWN, _("Input buffer overflow\n"));
      strcpy (ptr_server, optarg);
      break;
    case 'a': /* expected address */
      if (strlen (optarg) >= ADDRESS_LENGTH)
        die (STATE_UNKNOWN, _("Input buffer overflow\n"));
      expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**));
      expected_address[expected_address_cnt] = strdup(optarg);
      expected_address_cnt++;
      break;
    case 'A': /* expect authority */
      expect_authority = TRUE;
      break;
    case 'w':
      warning = optarg;
      break;
    case 'c':
      critical = optarg;
      break;
    default: /* args not parsable */
      usage5();
    }
  }

  c = optind;
  if (strlen(query_address)==0 && c<argc) {
    if (strlen(argv[c])>=ADDRESS_LENGTH)
      die (STATE_UNKNOWN, _("Input buffer overflow\n"));
    strcpy (query_address, argv[c++]);
  }

  if (strlen(dns_server)==0 && c<argc) {
    /* TODO: See -s option */
    host_or_die(argv[c]);
    if (strlen(argv[c]) >= ADDRESS_LENGTH)
      die (STATE_UNKNOWN, _("Input buffer overflow\n"));
    strcpy (dns_server, argv[c++]);
  }

  set_thresholds(&time_thresholds, warning, critical);

  return validate_arguments ();
}
Example #24
0
int main(int argc, char *argv[]) {
	unsigned long long num_nodes, ram_size;
	unsigned long num_forks = 1;
	struct sysinfo info;
	void *shm;
	int *cond;
	struct sigaction zig;
	int c, add_wait = -1, is_parent = 1;
#ifdef __cpu_set_t_defined
	int affinity = 0;
	cpu_set_t my_cpu_mask;
#endif

	/* By default we'll use 1/16th of total RAM, rounded
	 * down to the nearest page. */
	if (sysinfo(&info) != 0) {
		perror("sysinfo");
		return 1;
	}

	ram_size = info.totalram / 16;
	ram_size = ram_size & ~(getpagesize() - 1);
	num_nodes = ram_size / sizeof(void *);

	/* Parse command line args */
	while ( (c = getopt(argc, argv, "a:p:n:d:s:t")) != -1) {
		switch (c) {
			case 'p':
				num_forks = atoi(optarg);
				break;
			case 'd':
				ram_size = info.totalram / atoi(optarg);
				ram_size = ram_size & ~(getpagesize() - 1);
				num_nodes = ram_size / sizeof(void *);
				break;
			case 'n':
				num_nodes = atoi(optarg);
				ram_size = num_nodes * sizeof(void *);
				break;
			case 's':
				report_interval = atoi(optarg);
				break;
			case 'a':
				add_wait = atoi(optarg);
				break;
#ifdef __cpu_set_t_defined
			case 't':
				affinity = 1;
				break;
#endif
			default:
				print_help(argv[0]);
				return 0;
		}
	}

	/* Will we exceed half the address space size?  Use 1/4 of it at most.  */
	if (ram_size > ((unsigned long long)1 << ((sizeof(void *) * 8) - 1))) {
		printf("Was going to use %lluKB (%llu nodes) but that's too big.\n",
			ram_size / 1024, num_nodes);
		ram_size = ((unsigned long long)1 << (sizeof(void *) * 8));
		ram_size /= 4;
		num_nodes = ram_size / sizeof(void *);
		printf("Clamping to %lluKB (%llu nodes) instead.\n",
			ram_size / 1024, num_nodes);
	}

	/* Talk about what we're going to do. */
	printf("Going to use %lluKB (%llu nodes).\n", ram_size / 1024,
		num_nodes);
	
	/* Make a shared anonymous map of the RAM */
	shm = mmap(NULL, ram_size, PROT_READ | PROT_WRITE,
		MAP_SHARED | MAP_ANONYMOUS, 0, 0);
	if (shm == MAP_FAILED) {
		perror("mmap");
		return 2;
	}
	printf("mmap region: %p (%llu nodes)\n", shm, num_nodes);

	/* Create an SHM condition variable.  Bogus, I know... */
	cond = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE,
		MAP_SHARED | MAP_ANONYMOUS, 0, 0);
	if (cond == MAP_FAILED) {
		perror("mmap");
		return 4;
	}
	*cond = 1;

	/* Create a "graph" by populating it with random pointers. */
	printf("Populating nodes...");
	fflush(stdout);
	populate_graph(shm, num_nodes);
	printf("done.\n");

	printf("Creating %lu processes with reports every %lu seconds \
and %d seconds between adding children.\n",
		num_forks, report_interval, add_wait);

	/* Fork off separate processes.  The shared region is shared
	 * across all children.  If we only wanted one thread, we shouldn't
	 * fork anything.  Note that the "cond" mmap is a really crappy
	 * condition variable kludge that works well enough for HERE ONLY. */
	for (c = (add_wait >= 0 ? 0 : 1); c < num_forks; c++) {
		/* Child should wait for the condition and then break. */
		if (!fork()) {
#ifdef __cpu_set_t_defined
			if (affinity) {
				CPU_ZERO(&my_cpu_mask);
				CPU_SET(c, &my_cpu_mask);
				if (0 != sched_setaffinity(0,sizeof(cpu_set_t), &my_cpu_mask)) {
					perror("sched_setaffinity");
				}
			}
#endif

			is_parent = 0;
			while (*cond) {
				usleep(10000);
			}
			break;
		}
	}
	if (is_parent) {
#ifdef __cpu_set_t_defined
		if (affinity) {
			CPU_ZERO(&my_cpu_mask);
			CPU_SET(0, &my_cpu_mask);
			if (0 != sched_setaffinity(0,sizeof(cpu_set_t), &my_cpu_mask)) {
				perror("sched_setaffinity");
			}
		}
#endif
		printf("All threads created.  Launching!\n");
		*cond = 0;
	}

	/* now start the work */
	if (!is_parent) {
start_thread:
		/* Set up the alarm handler to print speed info. */
		memset(&zig, 0x00, sizeof(zig));
		zig.sa_handler = alarm_func;
		sigaction(SIGALRM, &zig, NULL);
		gettimeofday(&last, NULL);
		alarm(report_interval);

		/* Walk the graph. */
		walk_graph(shm);

		/* This function never returns */
	} else {
		/* Start the ramp-up.  The children will never die,
		 * so we don't need to wait() for 'em.
		 */
		while (add_wait != -1) {
			sleep(add_wait);
			if (fork() == 0) {
				/* goto is cheesy, but works. */
				goto start_thread;
			} else {
				printf("Added thread.\n");
			}
		}
		goto start_thread;
	}
	
	return 0;
}
Example #25
0
int main_cow (int argc, char **argv)
{
	int    r;
	char   **optarg;
	disk_t *out;

	out = NULL;

	while (1) {
		r = pce_getopt (argc, argv, &optarg, opts_create);

		if (r == GETOPT_DONE) {
			break;
		}

		if (r < 0) {
			return (1);
		}

		switch (r) {
		case '?':
			print_help();
			return (0);

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

		case 'c':
			pce_set_c (optarg[0]);
			break;

		case 'C':
			pce_set_min_cluster_size (optarg[0]);
			break;

		case 'f':
			pce_set_ofs (optarg[0]);
			break;

		case 'g':
			pce_set_c (optarg[0]);
			pce_set_h (optarg[1]);
			pce_set_s (optarg[2]);
			break;

		case 'h':
			pce_set_h (optarg[0]);
			break;

		case 'm':
			pce_set_n (optarg[0], 2048);
			break;

		case 'n':
			pce_set_n (optarg[0], 1);
			break;

		case 'o':
			if ((out = dsk_open_out (optarg[0], out, 0)) == NULL) {
				return (1);
			}
			break;

		case 'q':
			pce_set_quiet (1);
			break;

		case 's':
			pce_set_s (optarg[0]);
			break;

		case 'w':
			remove (optarg[0]);

			if ((out = dsk_cow (optarg[0], out)) == NULL) {
				return (1);
			}
			break;

		case 0:
			if ((out = dsk_open_out (optarg[0], out, 0)) == NULL) {
				return (1);
			}
			break;

		default:
			return (1);
		}
	}

	if (out != NULL) {
		dsk_del (out);
	}

	return (1);
}
Example #26
0
int parse_args(int argc, char **argv) {

    int arg_help = 0;
    int arg_verbosity = 0;

    int count;

    if (argc > 1) {
        for (count = 1; count < argc; count++) {
            char *argument = argv[count];
            size_t lenght = strlen(argv[count]);

            if (lenght < 2 || argument[0] != '-') {
                fprintf(stderr, "Unknown argument \"%s\"\n\n", argument);
                print_help();
                exit(EXIT_FAILURE);
            }

            for (int i = 1; i < lenght; ++i) {
                if (argument[i] == 'h') {
                    arg_help = 1;
                } else if (argument[i] == 'v') {
                    arg_verbosity++;
                } else if (argument[i] == 'i') {
                    count++;
                    strncpy(arg_inverter_mac, argv[count], 19);
                }
                else {
                    fprintf(stderr, "Unknown argument \"%c\"\n\n", argument[i]);
                    print_help();
                    exit(EXIT_FAILURE);
                }
            }
        }

        if (arg_help == 1) {
            print_help();
            exit(EXIT_SUCCESS);
        }

        if (arg_verbosity == 1) {
            logging_set_loglevel(logger, ll_verbose);
        } else if (arg_verbosity == 2) {
            logging_set_loglevel(logger, ll_debug);
        } else if (arg_verbosity > 2) {
            logging_set_loglevel(logger, ll_trace);
        }

        if (strlen(arg_inverter_mac) != 17) {
            fprintf(stderr, "Invalid invertor mac %s!\n\n", arg_inverter_mac);
            print_help();
            exit(EXIT_FAILURE);
        }

    } else {
        print_help();
        exit(EXIT_FAILURE);
    }

    return 0;
}
Example #27
0
File: shell.c Project: JMR-b/RIOT
static void handle_input_line(const shell_command_t *command_list, char *line)
{
    static const char *INCORRECT_QUOTING = "shell: incorrect quoting";

    /* first we need to calculate the number of arguments */
    unsigned argc = 0;
    char *pos = line;
    int contains_esc_seq = 0;
    while (1) {
        if ((unsigned char) *pos > ' ') {
            /* found an argument */
            if (*pos == '"' || *pos == '\'') {
                /* it's a quoted argument */
                const char quote_char = *pos;
                do {
                    ++pos;
                    if (!*pos) {
                        puts(INCORRECT_QUOTING);
                        return;
                    }
                    else if (*pos == '\\') {
                        /* skip over the next character */
                        ++contains_esc_seq;
                        ++pos;
                        if (!*pos) {
                            puts(INCORRECT_QUOTING);
                            return;
                        }
                        continue;
                    }
                } while (*pos != quote_char);
                if ((unsigned char) pos[1] > ' ') {
                    puts(INCORRECT_QUOTING);
                    return;
                }
            }
            else {
                /* it's an unquoted argument */
                do {
                    if (*pos == '\\') {
                        /* skip over the next character */
                        ++contains_esc_seq;
                        ++pos;
                        if (!*pos) {
                            puts(INCORRECT_QUOTING);
                            return;
                        }
                    }
                    ++pos;
                    if (*pos == '"') {
                        puts(INCORRECT_QUOTING);
                        return;
                    }
                } while ((unsigned char) *pos > ' ');
            }

            /* count the number of arguments we got */
            ++argc;
        }

        /* zero out the current position (space or quotation mark) and advance */
        if (*pos > 0) {
            *pos = 0;
            ++pos;
        }
        else {
            break;
        }
    }
    if (!argc) {
        return;
    }

    /* then we fill the argv array */
    char *argv[argc + 1];
    argv[argc] = NULL;
    pos = line;
    for (unsigned i = 0; i < argc; ++i) {
        while (!*pos) {
            ++pos;
        }
        if (*pos == '"' || *pos == '\'') {
            ++pos;
        }
        argv[i] = pos;
        while (*pos) {
            ++pos;
        }
    }
    for (char **arg = argv; contains_esc_seq && *arg; ++arg) {
        for (char *c = *arg; *c; ++c) {
            if (*c != '\\') {
                continue;
            }
            for (char *d = c; *d; ++d) {
                *d = d[1];
            }
            if (--contains_esc_seq == 0) {
                break;
            }
        }
    }

    /* then we call the appropriate handler */
    shell_command_handler_t handler = find_handler(command_list, argv[0]);
    if (handler != NULL) {
        handler(argc, argv);
    }
    else {
        if (strcmp("help", argv[0]) == 0) {
            print_help(command_list);
        }
        else {
            printf("shell: command not found: %s\n", argv[0]);
        }
    }
}
Example #28
0
int main(int argc, char** argv)
{
	int len;
	int lenc;
	char opt;
	int TC=120;
	int As=60;
	int GT=30;    // NT = pow(2, GT-1)
	int Namps=8;  // killgem in tower
	int output_options=0;
	char filename[256]="";		// it should be enough
	char filenamec[256]="";		// it should be enough
	char filenameA[256]="";		// it should be enough

	while ((opt=getopt(argc,argv,"hptecdqurf:T:A:N:G:"))!=-1) {
		switch(opt) {
			case 'h':
				print_help("hptecdqurf:T:A:N:G:");
				return 0;
			PTECIDQUR_OPTIONS_BLOCK
			case 'f':		// can be "filename,filenamec,filenameA", if missing default is used
				table_selection3(optarg, filename, filenamec, filenameA);
				break;
			TAN_OPTIONS_BLOCK
			case 'G':
				GT=atoi(optarg);
				break;
			case '?':
				return 1;
			default:
				break;
		}
	}
	if (optind==argc) {
		printf("No length specified\n");
		return 1;
	}
	if (optind+1==argc) {
		len = atoi(argv[optind]);
		lenc= 16;		// 16c as default combine
	}
	else if (optind+2==argc) {
		len = atoi(argv[optind]);
		lenc= atoi(argv[optind+1]);
	}
	else {
		printf("Too many arguments:\n");
		while (argv[optind]!=NULL) {
			printf("%s ", argv[optind]);
			optind++;
		}
		printf("\n");
		return 1;
	}
	if (len<1 || lenc<1) {
		printf("Improper gem number\n");
		return 1;
	}
	file_selection(filename, "table_kgspec");
	file_selection(filenamec, "table_kgcomb");
	file_selection(filenameA, "table_crit");
	worker(len, lenc, output_options, filename, filenamec, filenameA, TC, As, GT, Namps);
	return 0;
}
Example #29
0
/* --------------------------------------------- */
static int parse_commandline(int argc, char **argv) {
    int  nargc , nargsused;
    char **pargv, *option ;

    if (argc < 1) usage_exit();

    nargc   = argc;
    pargv = argv;
    while (nargc > 0) {

        option = pargv[0];
        if (debug) printf("%d %s\n",nargc,option);
        nargc -= 1;
        pargv += 1;

        nargsused = 0;

        if (!strcasecmp(option, "--help"))  print_help() ;
        else if (!strcasecmp(option, "--version")) print_version() ;
        else if (!strcasecmp(option, "--debug"))   debug = 1;
        else if (!strcasecmp(option, "--checkopts"))   checkoptsonly = 1;
        else if (!strcasecmp(option, "--nocheckopts")) checkoptsonly = 0;
        else if (!strcasecmp(option, "--no-log10")) log10flag = 0;
        else if (!strcasecmp(option, "--no-strip4")) DoStrip4 = 0;

        else if (!strcasecmp(option, "--stat")) {
            if (nargc < 1) CMDargNErr(option,1);
            statfile = pargv[0];
            DoDavid = 1;
            nargsused = 1;
        } else if (!strcasecmp(option, "--sue")) {
            if (nargc < 2) CMDargNErr(option,2);
            statfile = pargv[0];
            sscanf(pargv[1],"%d",&datcol1);
            log10flag = 1;
            DoSue = 1;
            nargsused = 2;
        } else if (!strcasecmp(option, "--seg")) {
            if (nargc < 1) CMDargNErr(option,1);
            segfile = pargv[0];
            nargsused = 1;
        } else if (!strcasecmp(option, "--annot")) {
            if (nargc < 3) CMDargNErr(option,3);
            annot   = pargv[0];
            subject = pargv[1];
            hemi    = pargv[2];
            nargsused = 3;
        } else if (!strcasecmp(option, "--o")) {
            if (nargc < 1) CMDargNErr(option,1);
            outfile = pargv[0];
            nargsused = 1;
        } else {
            fprintf(stderr,"ERROR: Option %s unknown\n",option);
            if (CMDsingleDash(option))
                fprintf(stderr,"       Did you really mean -%s ?\n",option);
            exit(-1);
        }
        nargc -= nargsused;
        pargv += nargsused;
    }
    return(0);
}
Example #30
0
int main(int argc,char **argv)
{

	server *srv=NULL;
	
	//step 1 : initialize server
	if( (srv= server_init()) ==NULL){
		fprintf(stderr,"failed to initialize server in [%s|%d|%s]\n",__FILE__,__LINE__,__FUNCTION__);
		return -1;		
	}	
	//step 2 : parameter parse
	char opt_chr;
	while(  (opt_chr=getopt(argc,argv,"f:hvD"))!=-1 ){
		switch(opt_chr){
			/*configuration file path */
		    case 'f':{
				        buffer_copy_string(srv->config->minihttpd_global_config_filepath,optarg);
				        break;
			}
		   /* show help */
		   case 'h':{
			            print_help();
						server_free(srv);
						return 0;
		   }
		  case 'v':{
			       fprintf(stdout,"%s-%s",srv->config->service_name->ptr,srv->config->version_info->ptr);
				   server_free(srv);
			       return 0;
		   }
		  case 'D':{
			         srv->dont_daemonize=1;
			         break;			
		  }
		  default:{
			        print_help();
			        server_free(srv);
					return -1;
		  }				
		}		
 	}

    //step 3 :check if all configuraiton is legal
	if(buffer_is_empty(srv->config->service_root_dir)){
		fprintf(stderr,"[%s|%d|%s]:please specify minihttp root dir in configuration file\n",
				 __FILE__,__LINE__,__FUNCTION__);
		server_free(srv);
		return -1;		
	}	
    /*parse the mime configuration file */
	if(buffer_is_empty(srv->config->mimetype_filepath)
	   ||   (srv->config->table= mime_table_initialize( (const char*)srv->config->mimetype_filepath->ptr) )==NULL){
        fprintf(stderr,"invalid mime configuration file is specified,pls check it..\n");
		server_free(srv);
		return -1;
	}

	//step4 :server started
    srv->uid=getuid();
	srv->gid=getgid();
	if(srv->uid==0) {  //we are root 
		struct rlimit res_limit;
		if(getrlimit(RLIMIT_NOFILE,&res_limit)!=0){
            fprintf(stderr,"[%s|%d|%s]: failed to get file descriptor max number for current process!\n",
					__FILE__,__LINE__,__FUNCTION__);
			server_free(srv);
			return -1;			
		}

		res_limit.rlim_cur=srv->config->max_fd;
		res_limit.rlim_max=srv->config->max_fd;
		
		if(setrlimit(RLIMIT_NOFILE,&res_limit)!=0){
			fprintf(stderr,"[%s|%d|%s]: failed call setrlimit(RLIMIT_NOFILE,) for current process!\n",
					__FILE__,__LINE__,__FUNCTION__);
			server_free(srv);
			return -1;			
		}     		
	}else{
		struct rlimit res_limit;
		if(getrlimit(RLIMIT_NOFILE,&res_limit)!=0){

			fprintf(stderr,"[%s|%d|%s]: failed to get file descriptor max number for current process!\n",
					__FILE__,__LINE__,__FUNCTION__);
			server_free(srv);
			return -1;				
		}

		if(srv->config->max_fd< res_limit.rlim_cur)
			res_limit.rlim_cur=srv->config->max_fd;
		else if(srv->config->max_fd<=res_limit.rlim_max)
			res_limit.rlim_cur=srv->config->max_fd;

		if(setrlimit(RLIMIT_NOFILE,&res_limit)!=0){
            fprintf(stderr,"[%s|%d|%s]: failed call setrlimit(RLIMIT_NOFILE,) for current process!\n",
				__FILE__,__LINE__,__FUNCTION__);
			server_free(srv);
			return -1;			 
		}
	}

	//step 5:  become a daemon process if dont_daemonize=0;
	if(!srv->dont_daemonize){
        daemonize((const char*)srv->config->service_name->ptr); 		 
	}
	//step 6: open log file for error log, by default we use syslog.
	// if the minihttpd log filepath is specified manually or server dont_daemonize=1,
	// we set mode = LOG_MODE_FILE;
	
	if(!buffer_is_empty(srv->config->log_filename) || srv->dont_daemonize ){
		if(buffer_is_empty(srv->config->log_filename))
			buffer_copy_string(srv->config->log_filename,MINIHTTPD_DEFAULT_LOG_FILEPATH);
		
		srv->log_fd= open((const char*)srv->config->log_filename->ptr,O_WRONLY|O_CREAT|O_TRUNC,
						  S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
		if(srv->log_fd<0){
			server_free(srv);
			return -1;
		}
		fd_close_on_exec(srv->log_fd);
        srv->mode=server::LOG_MODE_FILE;			
	}
	log_to_backend(srv,MINIHTTPD_LOG_LEVEL_INFO,"%s is start now...",(const char*)srv->config->service_name->ptr);
	
	//step 7 : create listening tcp socket(we only support ipv4 now)
    struct sockaddr_in * addr= (struct sockaddr_in*)&srv->server_addr;
	memset(addr,0,sizeof(*addr));
	addr->sin_family=AF_INET;
	addr->sin_addr.s_addr=htonl(INADDR_ANY);
	addr->sin_port=htons(srv->config->listenint_port);
	srv->listening_socket_fd= create_tcp_socket((struct sockaddr*)addr,srv->config->max_listening_number);
	if(srv->listening_socket_fd<0){
        log_to_backend(srv, MINIHTTPD_LOG_LEVEL_ERROR,"failed to create listening tcp socket on port:%d",
							 srv->config->listenint_port);
		server_free(srv);
		return -1;
	}

	 /*
	    step 8:  setup signal  handler
		signo: SIGCHLD
		signo: SIGPIPE: unix domain socket pipe is broken
		signo: SIGINT:  user intend to shutdown the minihttpd server
		                if SIGINT is kill to the server proces for twice, the minihtpd server is going to shutdown
		signo: SIGTERM: exit minihttpd service now 				
	 */
	struct sigaction act;
	sigemptyset(&act.sa_mask);
	act.sa_flags=0;
	act.sa_handler=signal_handler;
	sigaction(SIGPIPE,&act,NULL);
	sigaction(SIGCHLD,&act,NULL);
    sigaction(SIGINT,&act,NULL);
	sigaction(SIGTERM,&act,NULL);
	
	/*
	     step 9: fork worker child process  and transfter accept socket file descriptor to worker process
		 the only tasks for main processis :
		        1) to call accept to wait for connection and pick one worker process to handle the connection  
				2) wait all worker  process to finish before exit.
   */
    
	for(uint32_t worker_process_id=0;worker_process_id< srv->worker_number ;worker_process_id++) {
		server_child * child= &srv->child[worker_process_id];
		
		//create unix domain socket 
		if(socketpair(AF_UNIX,SOCK_STREAM,0,child->unix_domain_socket_fd)<0){
			log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"failed to create unix domain socket for worker%d",
						  worker_process_id);
			close(srv->listening_socket_fd);
			server_free(srv);
			return -1;			
		}
        child->sent_connection_number=0;
		int unix_domain_socket_child_fd=child->unix_domain_socket_fd[1];
		fd_set_nonblocking(unix_domain_socket_child_fd);
		child->pid=fork();
		
		if(child->pid <0){   //we can not fork worker process, this should not be happened
			close(srv->listening_socket_fd);
			server_free(srv) ;
			return -1;
		}
		else if(child->pid ==0) {   /*  worker process */ 
            /*we should use p_worker only in the child worker process */
#if 0
			minihttpd_running_log(srv->log_fd,MINIHTTPD_LOG_LEVEL_INFO,__FILE__,__LINE__,__FUNCTION__,
								  "worker(pid=%d) is starting.....",getpid());
#endif 	
			worker * server_worker =  (worker*)malloc(sizeof(worker));
			memset(server_worker,0,sizeof(worker));
            server_worker->worker_id= worker_process_id;
			server_worker->unix_domain_socekt_fd=unix_domain_socket_child_fd;
			server_worker->log_filepath=buffer_init();
			server_worker->global_config= srv->config;
			/*step1 : get current file descriptor max number (it should be same as parent process
			                               which we have set the resouces)*/
		    struct rlimit limit;
			if(getrlimit(RLIMIT_NOFILE,&limit)<0){
				exit(-1);  // terminated the worker   				
			}
			//close unnecessary file descriptor
			for(uint32_t file_descriptor_index=0;file_descriptor_index< limit.rlim_cur;file_descriptor_index++){
				if(file_descriptor_index> STDERR_FILENO && file_descriptor_index != unix_domain_socket_child_fd){
					close(file_descriptor_index);					
				}
			}
			
			//step 2: set event handler
			server_worker->ev= fdevent_initialize(limit.rlim_cur);
            /*support max connection number */
			uint32_t worker_support_max_connections=limit.rlim_cur/2;
			worker_connection_initialize(server_worker, worker_support_max_connections);
			
			//step 3 : register unix domain socket event
			fdevents_register_fd(server_worker->ev,server_worker->unix_domain_socekt_fd,
								 unix_domain_socket_handle,server_worker);
			//EPOLLHUP |EPOLLERR events is set by default
			fdevents_set_events(server_worker->ev,server_worker->unix_domain_socekt_fd,EPOLLIN); 

			//step 4 : open log file for worker to log debug/info/warning/error
            if(buffer_is_empty(server_worker->log_filepath)){
				char  worker_log_filepath[255];
				snprintf(worker_log_filepath,sizeof(worker_log_filepath),
						            MINIHTTPD_WORKER_CONFIG_PATH"%u.log", server_worker->worker_id );
				buffer_append_string(server_worker->log_filepath,worker_log_filepath);			   				
			}
			server_worker->log_fd= open((const char*)server_worker->log_filepath->ptr, O_WRONLY|O_CREAT|O_TRUNC,
				 S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
			if(server_worker->log_fd<0){
				exit(-2); 
			}
			//step 5 : setup timer and expect timer will expire with internal 1 seconds
			time(&server_worker->cur_ts);
			int timer_fd=timerfd_create(CLOCK_REALTIME,TFD_NONBLOCK);
			struct itimerspec timer_spec;
			timer_spec.it_value.tv_sec=1;
			timer_spec.it_value.tv_nsec=0;
			timer_spec.it_interval.tv_sec=1;
			timer_spec.it_interval.tv_nsec=0;
			timerfd_settime(timer_fd,0,&timer_spec,NULL);
			// setup timer experation events handler
			fdevents_register_fd(server_worker->ev, timer_fd,worker_timer_expire_handler,
				server_worker);
			fdevents_set_events(server_worker->ev,timer_fd,EPOLLIN);
			
			/* main loop for worker: epoll event loop for unix domain socket and connections */
			while(server_shutdown==0 || server_worker->cur_connection_number >0 ) {
				int n=epoll_wait(server_worker->ev->epoll_fd, server_worker->ev->epoll_events,
								 server_worker->ev->max_epoll_events,-1);
				if(n<0 ){
					if(errno!=EINTR){
						minihttpd_running_log(server_worker->log_fd,MINIHTTPD_LOG_LEVEL_ERROR
											  ,__FILE__,__LINE__,__FUNCTION__,
											  "failed to call epoll with errno=%d",errno);						
					}
					continue;
				}
				else if(n==0){
					//we should not get to here
					continue;					
				}else {

					for(uint32_t event_index=0;event_index<n;event_index++){
                        struct epoll_event * event= &server_worker->ev->epoll_events[event_index];
						assert(event!=NULL);
						int connection_socket_fd= event->data.fd;
						event_handle handler=fdevents_get_handle(server_worker->ev,connection_socket_fd);
						void * event_ctx=fdevents_get_context(server_worker->ev, connection_socket_fd);
						assert(handler!=NULL);
						int handle_status= handler(connection_socket_fd,event_ctx,event->events);
					    minihttpd_running_log(server_worker->log_fd,handle_status==0?
											  MINIHTTPD_LOG_LEVEL_INFO:MINIHTTPD_LOG_LEVEL_ERROR,
											  __FILE__,__LINE__,__FUNCTION__,"the epoll event is already handled!");
						

					}										
				}				
			}
			
			minihttpd_running_log(server_worker->log_fd,MINIHTTPD_LOG_LEVEL_INFO,
							  __FILE__,__LINE__,__FUNCTION__,"child worker process has finished all client requests!\n");

			/*free all connections */
			worker_free_connectons(server_worker);

			/* unregister timer file descriptor */
			fdevents_unset_event(server_worker->ev,timer_fd);
			fdevents_unregister_fd(server_worker->ev,timer_fd);
		    close(timer_fd);
            /* unregister unix domain socket hanlde events and handler context */
			fdevents_unset_event(server_worker->ev,server_worker->unix_domain_socekt_fd);
			fdevents_unregister_fd(server_worker->ev,server_worker->unix_domain_socekt_fd);
			close(server_worker->unix_domain_socekt_fd);
			
			/* free fevents resources  */
            close(server_worker->ev->epoll_fd);			
			fdevent_free(server_worker->ev);

			//close the log file
			close(server_worker->log_fd);
			buffer_free(server_worker->log_filepath);

			/* free worker */
			free( (void*) server_worker);
			exit(0);   //termianted the worker 
		}
		//close the unix domain socket worker file descriptor;
		close(child->unix_domain_socket_fd[1]);

		// child worker is running 
		child->worker_running=1;
		//parent process
		log_to_backend(srv,MINIHTTPD_LOG_LEVEL_INFO,"worker process %d is already created!",worker_process_id);
	}

    //main loop to accept client connection and re-transfter to worker process 
	while(!server_shutdown) {

         /*
             log signal events after signal si handled by signal handler   

		 */
		if(signal_pipe_handled){
            /* if unix domain socket pipe is broken and we still write data to the pipe  */
		    	
		}
		
		
		if(signal_child_handled){
			/*a child worker process has terminated */
			int worker_exit_status;
			pid_t exit_worker_pid;

			
			while( (exit_worker_pid= waitpid(-1,&worker_exit_status,WNOHANG))>0){

			  if(WIFEXITED(worker_exit_status)){	  
			    log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"worker child process(pid=%d) has exited normally with exit"  \
							  "status=%d",exit_worker_pid,WEXITSTATUS(worker_exit_status));
			  }	  
			  else if(WIFSIGNALED(worker_exit_status)){
				  log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"worker child process(pid=%d) is killed by signal(%d)",
								 exit_worker_pid,WTERMSIG(worker_exit_status))  
			  }
              else{
            		 log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"worker child process(pid=%d) has exited unexpected",                                      exit_worker_pid);
			  }

               //remove the worker from available worker list and do not send socket file descriptor to it
			  for(uint32_t child_worker_id=0;child_worker_id< srv->worker_number;child_worker_id++){
				  if(srv->child[child_worker_id].pid==exit_worker_pid)
					  srv->child[child_worker_id].worker_running=0;				  
			  }			 			 
		    }

		    signal_child_handled=0;
		}		
		//we block here to wait connection(only IPV4 is supported now ) 
		struct sockaddr_in client_addr;
		socklen_t client_addr_length=sizeof(client_addr);
		int connection_fd =accept(srv->listening_socket_fd,(struct sockaddr*)&client_addr,(socklen_t*)& client_addr_length);
		if(connection_fd<0){
			switch(errno){
			   case  EINTR:
				// the connection is reset by client
			   case ECONNABORTED:   
				                 continue;				   		  				
			   case  EMFILE:  //file descriptor is all used now, need to send file descriptor to worker soon
				             break;
			   default:  {
				   log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"failed to call accept() with errno=%d\n",errno);				 
				   break;				
			   }				
			}			
		}
		else{

          /*
		     pick up a worker process and send the @conneciton_fd to it
             the pick algorithm is round-robin,;
			 but for the draft version, we just pick a worker that we has sent the min connections  

		  */
 		 log_to_backend(srv,MINIHTTPD_LOG_LEVEL_INFO,"client connection is accepted,pick a worker to handle it.");
			
		 uint32_t  pick_worker_index= srv->worker_number;
		 uint32_t  min_sent_connections=0xFFFFFFFF;

         for(uint32_t worker_process_id=0; worker_process_id<srv->worker_number;worker_process_id++){
            if(srv->child[worker_process_id].sent_connection_number < min_sent_connections
			   &&  srv->child[worker_process_id].worker_running) {
				min_sent_connections= srv->child[worker_process_id].sent_connection_number;
				pick_worker_index= worker_process_id;
			}			
		 }
		 
		 if(pick_worker_index>= srv->worker_number){
			  /* we can not handle it as all child worker has exited...*/
			 close(connection_fd);
			 continue;
		 }
		 
		 /*set file descriptor to nonblocking and set close_on_exec flag*/
		 fd_set_nonblocking(connection_fd);
		 fd_close_on_exec(connection_fd);

		 if(unix_domain_socket_sendfd(srv->child[pick_worker_index].unix_domain_socket_fd[0],
									 connection_fd)<0){
			 log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"failed to send the connection file descriptor to worker!");
			 close(connection_fd);  //just close it to tell the client,we can not handle it now.
			 continue;			
		 }
		 srv->child[pick_worker_index].sent_connection_number++;
		 //close the file descriptor as it is already marked in flight
		 close(connection_fd);
	   }
	}