Exemplo n.º 1
0
int main(int argc, char **argv)
{
    int i;
    cfg_t *cfg = parse_conf(argc > 1 ? argv[1] : "ftp.conf");

    /* print the parsed configuration options */
    if(cfg)
    {
        printf("reverse-dns = %s\n", cfg_getbool(cfg, "reverse-dns") ? "true" : "false");
        printf("passive-mode = %s\n", cfg_getbool(cfg, "passive-mode") ? "true" : "false");
        printf("remote-completion = %s\n", cfg_getbool(cfg, "remote-completion") ? "true" : "false");

        printf("number of bookmarks: %d\n", cfg_size(cfg, "bookmark"));
        for(i = 0; i < cfg_size(cfg, "bookmark"); i++)
        {
            cfg_t *bookmark = cfg_getnsec(cfg, "bookmark", i);
            printf("  bookmark #%d: %s:%s@%s:%ld%s\n", i+1,
                    cfg_getstr(bookmark, "login"),
                    cfg_getstr(bookmark, "password"),
                    cfg_getstr(bookmark, "host"),
                    cfg_getint(bookmark, "port"),
                    cfg_getstr(bookmark, "directory"));
        }

        for(i = 0; i < cfg_size(cfg, "xterm-terminals"); i++)
            printf("xterm-terminal #%d: %s\n", i+1, cfg_getnstr(cfg, "xterm-terminals", i));

        printf("auto-create-bookmark = %ld\n", cfg_getint(cfg, "auto-create-bookmark"));
        cfg_free(cfg);
    }

    return 0;
}
Exemplo n.º 2
0
int read_config_file()
{
	char buf[1024];
	char name[64];
	char value[512];
	int i;
	FILE *fp=tr_fopen("tr.conf","r");
	if(fp==NULL)
	{
		tr_log(ERROR,"open file:tr.conf fail!");
		return -1;
	}
	while(fgets(buf,sizeof(buf),fp))
	{
		if(parse_conf(buf,name,value)<0)
			continue;
		for(i=0;i<sizeof(cps)/sizeof(cps[0]);i++)
		{
			if(strcasecmp(name,cps[i].config_name)==0)
			{
				cps[i].p_func(name,value);
				break;
			}
		}
	}
	return 0;
}
Exemplo n.º 3
0
int main(int argc, char **argv)
{
    int     shmid;
    skbstat_t    *skbstat;
    int core_num;
    parse_conf();
    if (high_water_mark == 0 || hash_level_water_mark == 0) {
        printf("Please set high water mark in config file\n");
        exit(1);
    }
    if ( (shmid = shmget(STAT_SHM_KEY, SHM_SIZE, SHM_MODE)) < 0)
        perror("shmget");

    if ( ( skbstat = (skbstat_t *)shmat(shmid, NULL, 0)) == (void *) -1)
        perror("shmat");
    core_num = 8; 
    skbstat->hash_level_water_mark = hash_level_water_mark;
    int output_flag = 0;
    if (argc >1) {
        output_flag = atoi(argv[1]);
    }
    time_t timep;
    char buf[400];
    printf("core_num=%d\n",core_num);
    while (1) {
        int i;
        //system("clear");
        for (i = 0; i < core_num; ) {
            if (skbstat->total_tsc[i] && skbstat->total_num[i]) {
                if (skbstat->max_arg_diff_tsc[i] < (skbstat->total_tsc[i]) /(skbstat->total_num[i])) {
                    skbstat->max_arg_diff_tsc[i] = (skbstat->total_tsc[i])/(skbstat->total_num[i]);
                }
                if (skbstat->total_tsc[i] /(2 * 5) > high_water_mark) {
                   skbstat->exceed_high_water_mark_count ++; 
                }
                if (output_flag) {
                    time (&timep);
                printf("%score_%u avg-time: %6u ns, max-time: %6uns, pkg(s) :%8u  time(s):%10u high-water(%u) %5u, free-skb %10u, htimes:%5u, high-hwater:%5u, num-FIP:%5u,rte-timer(s):%10u,send-pkt(s):%10u,web-msg:%5d, cache-pkg:%5u, fail-recv-pkg:%5u, study-cnt:%5u,dynamic-cnt:%5u,dns-cnt:%u, exceed-ac-state:%u\n", 
                        asctime(gmtime(&timep)), i, skbstat->total_tsc[i]/(2*(skbstat->total_num[i])), skbstat->max_arg_diff_tsc[i]/2,
                         skbstat->total_num[i]/5, skbstat->total_tsc[i]/(5*2), high_water_mark, skbstat->exceed_high_water_mark_count, skbstat->fail_skb,
                         skbstat->max_hash_level, skbstat->exceed_hash_level_count, skbstat->nums_sft_fip_entry,skbstat->rte_timer_tsc_per_sec[i] / 2, skbstat->send_pkt_tsc_per_sec[i]/2, skbstat->web_mesg_flag, skbstat->cache_pkg_num, skbstat->failed_recv_pkg[i], skbstat->study_hash_count, skbstat->dynamic_hash_count,skbstat->dns_hash_count, skbstat->exceed_ac_state[i]);
                } else {
                sprintf(buf, "core_%u avg-time: %6u ns, max-time: %6uns, pkg(s) :%8u  time(s):%10u high-water(%u) %5u, free-skb %10u, htimes:%5u, high-hwater:%5u, num-FIP:%5u,rte-timer(s):%10u,send-pkt(s):%10u,web-msg:%5d, cache-pkg:%5u, fail-recv-pkg:%5u,study-cnt:%5u,dynamic-cnt:%5u,dns-cnt:%u,exceed-ac-state:%u\n", 
                         i, skbstat->total_tsc[i]/(2*(skbstat->total_num[i])), skbstat->max_arg_diff_tsc[i]/2, 
                        skbstat->total_num[i]/5, skbstat->total_tsc[i]/(5*2), high_water_mark, skbstat->exceed_high_water_mark_count, skbstat->fail_skb, 
                        skbstat->max_hash_level, skbstat->exceed_hash_level_count, skbstat->nums_sft_fip_entry,skbstat->rte_timer_tsc_per_sec[i] / 2, skbstat->send_pkt_tsc_per_sec[i]/2, skbstat->web_mesg_flag, skbstat->cache_pkg_num, skbstat->failed_recv_pkg[i], skbstat->dynamic_hash_count,skbstat->dns_hash_count,skbstat->exceed_ac_state[i]);
                    write_log(buf);
                }
            }
            i++;
        }

        sleep(3);

    }
    exit(0);
}
Exemplo n.º 4
0
int main()
{
  int i;
  parse_conf();
  printf("alarm_interval : %d\n", alarm_interval );
  printf("max_tries : %d\n", max_tries );
  printf("max_tries_if_coredumped : %d\n", max_tries_if_coredumped );
  printf("gsm_list_len : %d\n", gsm_list_len );
  printf("alarm_mail : %s\n", alarm_mail );
  for ( i = 0; i < gsm_list_len; i++ )
    printf("alarm_gsm[%d] : %s\n", i, alarm_gsm[ i ] );
  return 0;
}
Exemplo n.º 5
0
int
main(int argc, char **argv)
{

   int                 prio;

   prio = getpriority(PRIO_PROCESS, getpid());
   setpriority(PRIO_PROCESS, getpid(), prio + 10);
   atexit(Epplet_cleanup);
   Epplet_Init("E-Bandwidth", "0.2", "Enlightenment Network I/O Monitor Epplet",
	       3, 3, argc, argv, 0);
   Epplet_load_config();
   parse_conf();

   title = Epplet_create_label(3, 3, "Net I/O", 1);
   if (show_title)
     {
	/* New arrangement */
	in_label = Epplet_create_label(3, 13, "I: 0 b/s", 1);
	out_label = Epplet_create_label(3, 30, "O: 0 b/s", 1);
	in_bar = Epplet_create_hbar(3, 22, 42, 7, 0, &in_val);
	out_bar = Epplet_create_hbar(3, 39, 42, 7, 0, &out_val);
	Epplet_gadget_show(title);
     }
   else
     {
	/* Old arrangement */
	in_label = Epplet_create_label(4, 4, "I: 0 b/s", 1);
	out_label = Epplet_create_label(4, 24, "O: 0 b/s", 1);
	in_bar = Epplet_create_hbar(4, 14, 40, 8, 0, &in_val);
	out_bar = Epplet_create_hbar(4, 36, 40, 8, 0, &out_val);
     }
   close_button =
      Epplet_create_button(NULL, NULL, 2, 2, 0, 0, "CLOSE", 0, NULL, close_cb,
			   NULL);
   cfg_button =
      Epplet_create_button(NULL, NULL, 33, 2, 0, 0, "CONFIGURE", 0, NULL,
			   config_cb, NULL);
   Epplet_gadget_show(in_label);
   Epplet_gadget_show(in_bar);
   Epplet_gadget_show(out_label);
   Epplet_gadget_show(out_bar);
   Epplet_show();

   Epplet_register_focus_in_handler(in_cb, NULL);
   Epplet_register_focus_out_handler(out_cb, NULL);
   timer_cb(NULL);		/* Set everything up */
   Epplet_Loop();

   return 0;
}
Exemplo n.º 6
0
static int signal_pipe_dispatch(void) {
    int sig, err;

    s_log(LOG_DEBUG, "Dispatching signals from the signal pipe");
    while(readsocket(signal_pipe[0], (char *)&sig, sizeof sig)==sizeof sig) {
        switch(sig) {
#ifndef USE_WIN32
        case SIGCHLD:
            s_log(LOG_DEBUG, "Processing SIGCHLD");
#ifdef USE_FORK
            client_status(); /* report status of client process */
#else /* USE_UCONTEXT || USE_PTHREAD */
            child_status();  /* report status of libwrap or 'exec' process */
#endif /* defined USE_FORK */
            break;
#endif /* !defind USE_WIN32 */
        case SIGNAL_RELOAD_CONFIG:
            s_log(LOG_DEBUG, "Processing SIGNAL_RELOAD_CONFIG");
            err=parse_conf(NULL, CONF_RELOAD);
            if(err) {
                s_log(LOG_ERR, "Failed to reload the configuration file");
            } else {
                unbind_ports();
                log_close();
                apply_conf();
                log_open();
                if(bind_ports()) {
                    /* FIXME: handle the error */
                }
            }
            break;
        case SIGNAL_REOPEN_LOG:
            s_log(LOG_DEBUG, "Processing SIGNAL_REOPEN_LOG");
            log_close();
            log_open();
            s_log(LOG_NOTICE, "Log file reopened");
            break;
        case SIGNAL_TERMINATE:
            s_log(LOG_DEBUG, "Processing SIGNAL_TERMINATE");
            s_log(LOG_NOTICE, "Terminated");
            return 2;
        default:
            s_log(LOG_ERR, "Received signal %d; terminating", sig);
            return 1;
        }
    }
    s_log(LOG_DEBUG, "Signal pipe is empty");
    return 0;
}
Exemplo n.º 7
0
int
setup(struct config_t *config, int argc, char **argv)
{
	char *home, *cfgfile = NULL;
	
	config_init(config);
	
	/* parse arguments */
	if (parse_args(config, argc, argv) != 0)
		return SETUP_ERROR;
	
	/* if the user did not supply an alternate config file,
	 * check if the default config file exists */
	if (!config->filename) {
		if ((home = getenv("HOME"))) {
			cfgfile = malloc(strlen(home) + sizeof(CONFIG_FILE) + 2);
			if (!cfgfile) {
				warn("malloc failed for $HOME + " CONFIG_FILE);
				return SETUP_ERROR;
			}
			stpcpy(stpcpy(stpcpy(cfgfile, home), "/"), CONFIG_FILE);
			if (access(cfgfile, F_OK) == 0) {
				/* file exists - keep malloc'ed data */
				config->filename = cfgfile;
			} else {
				/* file does not exist - free data */
				errno = 0;
				free(cfgfile);
				cfgfile = NULL;
			}
		}
	}
	
	/* parse config file - if provided or default exists */
	if (config->filename && parse_conf(config, config->filename) != 0)
		return SETUP_ERROR;
	
	/* put defaults for each undefined variable */
	config_finalize(config);
	
	/* check mandatory/conflicting settings */
	if (config_validate(config) != 0)
		return SETUP_ERROR;
	
	return SETUP_OK;
}
Exemplo n.º 8
0
/*
    load config from file. support load from multi file, all config will insert
    into g_conf
*/
void load_conf(const char *filename)
{
    FILE *fp;
    char buff[512];
    struct conf *head = NULL;
    struct conf *c;

    fp = fopen(filename, "r");
    if (NULL == fp)
    {
        printf("%s :%s\n", filename, strerror(errno));
        exit(0);
    }

    while (fgets(buff, sizeof(buff), fp))
    {
        str_t key, value;
        if (parse_conf((unsigned char *)buff, &key, &value))
            continue;

        c = (struct conf *)malloc(sizeof(struct conf));
        if (!c)
        {
            printf("Failed to alloc mem for conf\n");
            exit(0);
        }

        memcpy(c->key, key.p, key.len);
        c->key[key.len] = 0;
        memcpy(c->value, value.p, value.len);
        c->value[value.len] = 0;

        if (head)
            c->next = head;
        else
            c->next = NULL;
        head = c;
    }

    free_old_conf(g_conf);
    g_conf = head;
    fclose(fp);
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
    hash_t = hashtable_create();

    array_a = arraylist_create();
    hashtable_set(hash_t, "application name", "Test Application");

    arraylist_add(array_a, "abcd");
    LOG.debug = 1;
    //LOG.error_log_path = "error.log";
    log_init();
    log_debug("Starting server now...\n");
    config_init();
    parse_conf();
    read_logfile("./test.log");
    hashtable_destroy(hash_t);
    arraylist_destroy(array_a);
    return 0;
}
Exemplo n.º 10
0
int main(int argc, char* argv[]) {
    if (argc != 3) {
        printf("%s config-file node_id\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    Config *conf = parse_conf(argv[1]);
    struct application *app = malloc(sizeof(struct application));
    app->server_id = atoi(argv[2]);
    app->sock = create_socket();
    app->conf = conf;
    LearnerCtx *learner_ctx = make_learner(conf);
    set_app_ctx(learner_ctx, app);
    register_deliver_cb(learner_ctx, deliver);
    event_base_dispatch(learner_ctx->base);
    free_learner(learner_ctx);
    free(conf);
    free(app);
    return (EXIT_SUCCESS);
}
Exemplo n.º 11
0
int conf_parse_config(void)
{
	int result;

	username = strdup(DEFUSER);
	hostname = strdup(DEFHOST);

	result = parse_conf(FINIT_CONF);
	if (!tty_num()) {
		char *fallback = FALLBACK_SHELL;

		if (console)
			fallback = console;

		tty_register(fallback);
	}

	return result;
}
Exemplo n.º 12
0
void init()
{
    // read config, and init pid, if any process is not up, start it.
    int i = 0;

    cfg_t *cfg = parse_conf("config.conf");
    if (cfg == NULL)
    {
        return;
    }

    g_frequency = cfg_getint(cfg, "frequency");

    g_tree_ps = make_node(NULL, NULL); 

    for (i=0; i<cfg_size(cfg, "process"); i++)
    {
        tree_node_t *node = NULL; 
        cfg_t *ps_opt = cfg_getnsec(cfg, "process", i);
        ps_conf_t *ps_conf = (ps_conf_t*)malloc(sizeof(ps_conf_t));
        ps_conf->comm = strdup(cfg_getstr(ps_opt, "comm"));
        ps_conf->args = strdup(cfg_getstr(ps_opt, "args"));
        ps_t *ps = (ps_t*)malloc(sizeof(ps_t));
        ps->pid = PID_UNDEFINED;
        ps->ps_conf = ps_conf;
        node = find_node(g_tree_ps, ps_opt->title);
        if (node != NULL)
        {
            node->data = ps;
            // re-layout
            adjust_node(node, strdup(cfg_getstr(ps_opt, "pre"))); 
        }
        else
        {
            char *pre = cfg_getstr(ps_opt, "pre");
            node = make_node(ps, ps_opt->title==NULL?NULL:strdup(ps_opt->title));
            insert_node(node, pre!=NULL ? strdup(pre) : NULL );
        }
     }

    cfg_free(cfg);
}
Exemplo n.º 13
0
int main (int argc, char *argv[])
{
	cfg_t *cfg;

	cfg = parse_conf(argc > 1 ? argv[1] : "/etc/example.conf");
	if (!cfg)
		return 1;

	print_bool   (cfg, "syslog");
	print_integer(cfg, "period");
	print_integer(cfg, "startup-delay");
	print_integer(cfg, "forced-update");
	print_bool   (cfg, "wildcard");
	print_string (cfg, "bind", 0);
	print_systems(cfg);

	cfg_free(cfg);

	return 0;
}
Exemplo n.º 14
0
idn_result_t
idn_resconf_loadfile(idn_resconf_t ctx, const char *file) {
	FILE *fp = NULL;
	idn_result_t r;

	assert(ctx != NULL);

	TRACE(("idn_resconf_loadfile(file=%s)\n",
	      file == NULL ? "<null>" : file));

	resetconf(ctx);
	r = idn_delimitermap_create(&ctx->delimiter_mapper);
	if (r != idn_success) {
		goto ret;
	}

	if (file == NULL) {
		r = open_defaultfile(&fp);
		if (r == idn_nofile || r == idn_notfound) {
			r = setdefaults_body(ctx, 0);
			goto ret;
		} else if (r != idn_success) {
			goto ret;
		}
	} else {
		fp = fopen(file, "r");
		if (fp == NULL) {
			TRACE(("idn_resconf_loadfile: cannot open %-.40s\n",
			       file));
			r = idn_nofile;
			goto ret;
		}
	}

	r = parse_conf(ctx, fp);
	fclose(fp);

ret:
	TRACE(("idn_resconf_loadfile(): %s\n", idn_result_tostring(r)));
	return (r);
}
Exemplo n.º 15
0
int main(int argc, char* argv[])
{
    int ret;
    if(argc != 2){
        printf("usage: ./parse_conf <conf_path>\n");
        return 1;
    }
    ret = parse_conf(argv[1]);
    if (ret) {
		int i;
		printf("\nlog:\n");
		printf("\nbaby : %s\n",BABY);
		printf("\nmain : %s\n",MAIN);
		printf("\nbook : %s\n",BOOK);
		printf("\nnba:\n");
		printf("\njodan : %s\n",JODAN);
		printf("\nkobe : %s\n",KOBE);
		printf("\nyao : %s\n",YAO);
		}
    return 0;
}
Exemplo n.º 16
0
int		main(int ac, char **av)
{
  t_serv	serv;
  int		fd;
  char		**conf;
  char		*conf_line;

  conf = NULL;
  conf_line = xmalloc(sizeof(char) * 1024);
  if (ac != 2)
    {
      printf("Uage : %s <Port>\n", av[0]);
      return (EXIT_FAILURE);
    }
  if (init_serv(&serv, av[1]) != -1)
    {
      if ((fd = open("utils/conf/conf.xml", O_RDONLY)) == -1)
        serv.tag = create_tag("#default");
      else
        serv.tag = parse_conf(fd, conf, conf_line);
      serv_loop(&serv);
    }
  return (EXIT_SUCCESS);
}
Exemplo n.º 17
0
// .c file
void main(void)
{
	dict *inif[HASHSIZE] = {}; // initialized to NULL 	
	dict *dirs;
	char *dir = str_init(), *d_cpy = str_init();
	char *files[256] = {};
	
	parse_conf(inif, INIFILE);
	dirs = lookup(inif, DIRECT);		
	dir = strtok(dirs->defn, DELIM);
	
	while (dir != NULL) {
		strcpy(d_cpy, dir);
		strcat(d_cpy, BUILD_PATH);
		str_strip(d_cpy);
		ls_dir(files, d_cpy);	   // List files
		
		/*
			do parse here
		*/
		
		dir = strtok(NULL, DELIM); // for each until no more delimiters
	}
}
Exemplo n.º 18
0
int		main(int ac, char **av)
{
    t_glob	*glob;

    glob = cx_malloc(1 * sizeof(*glob));
    glob->graph = cx_malloc(1 * sizeof(t_graph));
    glob->universe = cx_malloc(1 * sizeof(t_uni));
    glob->option = cx_malloc(1 * sizeof(t_option));
    if (ac < 2)
    {
        fprintf(stderr, "Usage: ./%s [file.xml] [flags]\n", av[0]);
        put_error(USAGE_FLAG, 1);
    }
    parse_conf(av[1], glob);
    get_args(glob, ac, av);
    check_parse(glob);
    init_methodes(glob);
    init(glob);
    tracemyray(glob);
    mlx_expose_hook(glob->graph->win_ptr, &expose, glob);
    mlx_key_hook(glob->graph->win_ptr, &key_hook, glob);
    mlx_loop(glob->graph->mlx_ptr);
    return (EXIT_SUCCESS);
}
Exemplo n.º 19
0
Arquivo: zginx.c Projeto: johnzz/zginx
int main(int argc, char *argv[])
{
	char			*conf_path;
	struct passwd	*pwd;
	FILE			*pidfd;
	zgx_listening_t	*listen;
	uid_t			uid;
	gid_t			gid;
	char			c;
	int				ret;
	int				i;

	while ((c = getopt(argc,argv,"c:")) != -1 ) {
		switch (c) {
		case 'c':
			conf_path = optarg;
			break;
		default:
			fprintf(stderr,"Usage:%s -c ConfigFile\r\n",argv[0]);
			return -1;
		}
	}

    fprintf(stderr,"conf path %s\n",conf_path);
	if ( (ret = parse_conf(conf_path)) < 0) {
		return -1;
	}

	cycle_init();
	zgx_shmtx_init();

	/* If we're root and we're going to become another user, get the uid/gid
    ** now.
    */
	
	if (getuid() == 0) {
		pwd = getpwnam("www");
		if (!pwd) {
			fprintf(stderr,"unkown user:%s\n",conf.user);
			return -1;
		}
		
		uid = pwd->pw_uid;
		gid = pwd->pw_gid;
	}
	/*logfile
	*/
	if (conf.log[0] != '/') {
		fprintf(stderr,"pls set log abs path!\n");
		return -1;
	}
	
	cycle.logfp = fopen(conf.log,"a");
	if (!cycle.logfp){
		fprintf(stderr,"open the log [%s] error!\n",conf.log);
		return -1;
	}

	if (getuid() == 0) {
		if ( fchown(fileno(cycle.logfp),uid,gid) < 0) {
			fprintf(stderr,"fchown logfile - error!\n");
			return -1 ;
		}
	}
	
	/*daemonize
	*/
	if ( (ret = make_deamon()) < 0 ) {
		fprintf(stderr,"make daemon error!\n");
		return -1;
	}

	if (conf.pidfile[0] != '/') {
		fprintf(stderr,"it's not a abs path!\n");
	}
	
	pidfd = fopen(conf.pidfile,"w");
	if (!pidfd){
		fprintf(stderr, "can't open [%s] pid file!\n",conf.pidfile);
		return -1;
	}

	fprintf(pidfd,"%d\n",(int)getpid());
	fclose(pidfd);

    zgx_log(ERROR,"begin to listen!");
	if ( init_listening_socket(listen) < 0 ) {
        return -1;
	}
	
	for (i=0;i<conf.process_num;i++) {
		zgx_start_worker_process((void *)(int) i, zgx_worker_process_cycle);
	}
	
	
}
Exemplo n.º 20
0
int main(int argc, char * const argv[])
{
	struct sdp_dev *p_id;
	struct mach_id *mach;
	libusb_device **devs;
	libusb_device *dev;
	int r;
	int err;
	ssize_t cnt;
	libusb_device_handle *h = NULL;
	int config = 0;
	int verify = 0;
	struct sdp_work *curr;
	struct sdp_work *cmd_head = NULL;
	char const *conf;
	char const *base_path = get_base_path(argv[0]);
	char const *conf_path = "/etc/imx-loader.d/";

	err = parse_opts(argc, argv, &conf_path, &verify, &cmd_head);
	if (err < 0)
		return -1;

	// Get list of machines...
	conf = conf_file_name("imx_usb.conf", base_path, conf_path);
	if (conf == NULL)
		return -1;

	struct mach_id *list = parse_imx_conf(conf);
	if (!list)
		return -1;

	r = libusb_init(NULL);
	if (r < 0)
		goto out;

	cnt = libusb_get_device_list(NULL, &devs);
	if (cnt < 0)
		goto out;

//	print_devs(devs);
	dev = find_imx_dev(devs, &mach, list);
	if (dev) {
		err = libusb_open(dev, &h);
		if (err)
			printf("%s:Could not open device vid=0x%x pid=0x%x err=%d\n", __func__, mach->vid, mach->pid, err);
	}
	libusb_free_device_list(devs, 1);

	if (!h)
		goto out;

	// Get machine specific configuration file..
	conf = conf_file_name(mach->file_name, base_path, conf_path);
	if (conf == NULL)
		goto out;

	p_id = parse_conf(conf);
	if (!p_id)
		goto out;

	if (p_id->mode == MODE_HID)
		p_id->transfer = &transfer_hid;
	if (p_id->mode == MODE_BULK)
		p_id->transfer = &transfer_bulk;

	// USB private pointer is libusb device handle...
	p_id->priv = h;

	libusb_get_configuration(h, &config);
	printf("%04x:%04x(%s) bConfigurationValue =%x\n",
			mach->vid, mach->pid, p_id->name, config);

	if (libusb_kernel_driver_active(h, 0))
		 libusb_detach_kernel_driver(h, 0);

	err = libusb_claim_interface(h, 0);
	if (err) {
		printf("Claim failed\n");
		goto out;
	}
	printf("Interface 0 claimed\n");
	err = do_status(p_id);
	if (err) {
		printf("status failed\n");
		goto out;
	}

	// By default, use work from config file...
	curr = p_id->work;

	if (cmd_head != NULL)
		curr = cmd_head;

	if (curr == NULL) {
		printf("no job found\n"); 
		goto out;
	}

	while (curr) {
		if (curr->mem)
			perform_mem_work(p_id, curr->mem);
//		printf("jump_mode %x\n", curr->jump_mode);
		if (curr->filename[0]) {
			err = DoIRomDownload(p_id, curr, verify);
		}
		if (err) {
			err = do_status(p_id);
			break;
		}
		if (!curr->next && (!curr->plug || curr != cmd_head))
			break;
		err = do_status(p_id);
		printf("jump_mode %x plug=%i err=%i\n", curr->jump_mode, curr->plug, err);
		if (err) {
			int retry;
			/* Rediscovers device */
			libusb_release_interface(h, 0);
			libusb_close(h);
			libusb_exit(NULL);
			for (retry = 0; retry < 10; retry++) {
				printf("sleeping\n");
				sleep(3);
				printf("done sleeping\n");
				h = open_vid_pid(mach, p_id);
				if (h)
					break;
			}
			if (!h)
				goto out;
		}
		if (curr == cmd_head && curr->plug) {
			curr->plug = 0;
			continue;
		}
		curr = curr->next;
	}

exit:
	libusb_release_interface(h, 0);
out:
	if (h)
		libusb_close(h);
	libusb_exit(NULL);
	return 0;
}
Exemplo n.º 21
0
int main(int argc, char *argv[]) {
        static struct list_sample_data *sampledata;
        _cleanup_closedir_ DIR *proc = NULL;
        _cleanup_free_ char *build = NULL;
        _cleanup_fclose_ FILE *of = NULL;
        _cleanup_close_ int sysfd = -1;
        int schfd;
        struct ps_struct *ps_first;
        double graph_start;
        double log_start;
        double interval;
        char output_file[PATH_MAX];
        char datestr[200];
        int pscount = 0;
        int n_cpus = 0;
        int overrun = 0;
        time_t t = 0;
        int r, samples;
        struct ps_struct *ps;
        struct rlimit rlim;
        struct list_sample_data *head;
        struct sigaction sig = {
                .sa_handler = signal_handler,
        };

        parse_conf();

        r = parse_argv(argc, argv);
        if (r < 0)
                return EXIT_FAILURE;

        if (r == 0)
                return EXIT_SUCCESS;

        /*
         * If the kernel executed us through init=/usr/lib/systemd/systemd-bootchart, then
         * fork:
         * - parent execs executable specified via init_path[] (/usr/lib/systemd/systemd by default) as pid=1
         * - child logs data
         */
        if (getpid() == 1) {
                if (fork())
                        /* parent */
                        execl(arg_init_path, arg_init_path, NULL);
        }
        argv[0][0] = '@';

        rlim.rlim_cur = 4096;
        rlim.rlim_max = 4096;
        (void) setrlimit(RLIMIT_NOFILE, &rlim);

        schfd = open("/proc/sys/kernel/sched_schedstats", O_WRONLY);
        if (schfd >= 0) {
                write(schfd, "1\n", 2);
                close(schfd);
        }

        /* start with empty ps LL */
        ps_first = new0(struct ps_struct, 1);
        if (!ps_first) {
                log_oom();
                return EXIT_FAILURE;
        }

        /* handle TERM/INT nicely */
        sigaction(SIGHUP, &sig, NULL);

        interval = (1.0 / arg_hz) * 1000000000.0;

        if (arg_relative)
                graph_start = log_start = gettime_ns();
        else {
                struct timespec n;
                double uptime;

                clock_gettime(clock_boottime_or_monotonic(), &n);
                uptime = (n.tv_sec + (n.tv_nsec / (double) NSEC_PER_SEC));

                log_start = gettime_ns();
                graph_start = log_start - uptime;
        }

        if (graph_start < 0.0) {
                log_error("Failed to setup graph start time.\n\n"
                          "The system uptime probably includes time that the system was suspended. "
                          "Use --rel to bypass this issue.");
                return EXIT_FAILURE;
        }

        LIST_HEAD_INIT(head);

        /* main program loop */
        for (samples = 0; !exiting && samples < arg_samples_len; samples++) {
                int res;
                double sample_stop;
                double elapsed;
                double timeleft;

                sampledata = new0(struct list_sample_data, 1);
                if (sampledata == NULL) {
                        log_oom();
                        return EXIT_FAILURE;
                }

                sampledata->sampletime = gettime_ns();
                sampledata->counter = samples;

                if (sysfd < 0)
                        sysfd = open("/sys", O_RDONLY|O_CLOEXEC);

                if (!build) {
                        if (parse_env_file("/etc/os-release", NEWLINE, "PRETTY_NAME", &build, NULL) == -ENOENT)
                                parse_env_file("/usr/lib/os-release", NEWLINE, "PRETTY_NAME", &build, NULL);
                }

                if (proc)
                        rewinddir(proc);
                else
                        proc = opendir("/proc");

                /* wait for /proc to become available, discarding samples */
                if (proc) {
                        r = log_sample(proc, samples, ps_first, &sampledata, &pscount, &n_cpus);
                        if (r < 0)
                                return EXIT_FAILURE;
                }

                sample_stop = gettime_ns();

                elapsed = (sample_stop - sampledata->sampletime) * 1000000000.0;
                timeleft = interval - elapsed;

                /*
                 * check if we have not consumed our entire timeslice. If we
                 * do, don't sleep and take a new sample right away.
                 * we'll lose all the missed samples and overrun our total
                 * time
                 */
                if (timeleft > 0) {
                        struct timespec req;

                        req.tv_sec = (time_t)(timeleft / 1000000000.0);
                        req.tv_nsec = (long)(timeleft - (req.tv_sec * 1000000000.0));

                        res = nanosleep(&req, NULL);
                        if (res) {
                                if (errno == EINTR)
                                        /* caught signal, probably HUP! */
                                        break;
                                log_error_errno(errno, "nanosleep() failed: %m");
                                return EXIT_FAILURE;
                        }
                } else {
                        overrun++;
                        /* calculate how many samples we lost and scrap them */
                        arg_samples_len -= (int)(-timeleft / interval);
                }
                LIST_PREPEND(link, head, sampledata);
        }

        /* do some cleanup, close fd's */
        ps = ps_first;
        while (ps->next_ps) {
                ps = ps->next_ps;
                ps->schedstat = safe_close(ps->schedstat);
                ps->sched = safe_close(ps->sched);
                ps->smaps = safe_fclose(ps->smaps);
        }

        if (!of) {
                t = time(NULL);
                r = strftime(datestr, sizeof(datestr), "%Y%m%d-%H%M", localtime(&t));
                assert_se(r > 0);

                snprintf(output_file, PATH_MAX, "%s/bootchart-%s.svg", arg_output_path, datestr);
                of = fopen(output_file, "we");
        }

        if (!of) {
                log_error("Error opening output file '%s': %m\n", output_file);
                return EXIT_FAILURE;
        }

        r = svg_do(of, strna(build), head, ps_first,
                   samples, pscount, n_cpus, graph_start,
                   log_start, interval, overrun);

        if (r < 0) {
                log_error_errno(r, "Error generating svg file: %m");
                return EXIT_FAILURE;
        }

        log_info("systemd-bootchart wrote %s\n", output_file);

        r = do_journal_append(output_file);
        if (r < 0)
                return EXIT_FAILURE;

        /* nitpic cleanups */
        ps = ps_first->next_ps;
        while (ps->next_ps) {
                struct ps_struct *old;

                old = ps;
                old->sample = ps->first;
                ps = ps->next_ps;
                while (old->sample->next) {
                        struct ps_sched_struct *oldsample = old->sample;

                        old->sample = old->sample->next;
                        free(oldsample);
                }
                free(old->cgroup);
                free(old->sample);
                free(old);
        }

        free(ps->cgroup);
        free(ps->sample);
        free(ps);

        sampledata = head;
        while (sampledata->link_prev) {
                struct list_sample_data *old_sampledata = sampledata;
                sampledata = sampledata->link_prev;
                free(old_sampledata);
        }
        free(sampledata);

        /* don't complain when overrun once, happens most commonly on 1st sample */
        if (overrun > 1)
                log_warning("systemd-bootchart: sample time overrun %i times\n", overrun);

        return 0;
}
Exemplo n.º 22
0
int parse_cmd_line(struct watch_session *ws, int argc, char *const *argv)
{
    struct option long_options[] =
        {
            {"rsync",     required_argument, NULL, 'r'},
            {"help",      no_argument,       NULL, 'h'},
            {"depth",     required_argument, NULL, 'd'},
            {"exclude",   required_argument, NULL, 'e'},
            {"daemon",    no_argument,       NULL, 'D'},
            {"pid-file",  required_argument, NULL, 'p'},
            {"log-file",  required_argument, NULL, 'l'},
            {"conf-file", required_argument, NULL, 'c'},
            {NULL,       0,                  NULL, 0}
        };

    const char *short_options = "r:hd:e:Dp:l:c:";

    int add_args;  /* Remaining arguments. */
    int args;  /* Option indicator. */


    /* Loop through command line arguments
     * and interprete them. */
    while(1) {
        int option_index = 0;
        int c = -1;

        /* Retrieve next option */
        c = getopt_long(argc, argv, short_options,
                        long_options, &option_index);

        if(c == -1)
            break;

        switch(c) {
        case 0:
            break;
        case 'r':
        {
            int r = clone_str(&ws->rsync_path, optarg);

            /* Check that memory was successfully allocated. */
            assert(r == 0);
            break;
        }
        case 'p':
        {
            int r = clone_str(&ws->pid_file, optarg);

            /* Check that memory was successfully allocated. */
            assert(r == 0);
            break;
        }
        case 'l':
        {
            int r = clone_str(&ws->log_file, optarg);

            /* Check that memory was successfully allocated. */
            assert(r == 0);
            break;
        }
        case 'd':
            ws->depth = atoi(optarg);
            if(ws->depth == INT_MAX) {
                log_msg(WARN,
                        "error while parsing depth argument, "
                        "settings depth to -1");
                ws->depth = -1;
            }
            break;
        case 'e':
            watch_session_set_excl(ws, optarg, REG_EXTENDED);

            break;
        case 'D':
            ws->daemon = TRUE;
            break;
        case 'c':
        {
            if(strcmp(optarg, "-") == 0)
                parse_conf_fd(ws, 0, "<stdin>");
            else
                parse_conf(ws, optarg);

            break;
        }
        case '?':
            return -1;
        default:
            /* This case should be impossible to reach */
            printf("val: %d\n", c);
            abort();
        }
    }

    add_args = argc - optind;
    args = optind;

    /* Parse remaining arguments */
    if(add_args >= 1) {

        ws->src.len = strlen(argv[args]);
        ws->src.str = (char *)f_malloc(ws->src.len + 1);

        strncpy(ws->src.str, argv[args], ws->src.len + 1);

        if(--add_args >= 1) {
            if(clone_str(&ws->target, argv[++args]) < 0)
                return -1;
        }
    }

    return 0;
}
Exemplo n.º 23
0
int main(int argc, char *argv[]) {
        _cleanup_free_ char *build = NULL;
        struct sigaction sig = {
                .sa_handler = signal_handler,
        };
        struct ps_struct *ps;
        char output_file[PATH_MAX];
        char datestr[200];
        time_t t = 0;
        int r;
        struct rlimit rlim;

        parse_conf();

        r = parse_args(argc, argv);
        if (r < 0)
                return EXIT_FAILURE;

        /*
         * If the kernel executed us through init=/usr/lib/systemd/systemd-bootchart, then
         * fork:
         * - parent execs executable specified via init_path[] (/sbin/init by default) as pid=1
         * - child logs data
         */
        if (getpid() == 1) {
                if (fork()) {
                        /* parent */
                        execl(arg_init_path, arg_init_path, NULL);
                }
        }
        argv[0][0] = '@';

        rlim.rlim_cur = 4096;
        rlim.rlim_max = 4096;
        (void) setrlimit(RLIMIT_NOFILE, &rlim);

        /* start with empty ps LL */
        ps_first = calloc(1, sizeof(struct ps_struct));
        if (!ps_first) {
                perror("calloc(ps_struct)");
                exit(EXIT_FAILURE);
        }

        /* handle TERM/INT nicely */
        sigaction(SIGHUP, &sig, NULL);

        interval = (1.0 / arg_hz) * 1000000000.0;

        log_uptime();

        LIST_HEAD_INIT(struct list_sample_data, head);

        /* main program loop */
        for (samples = 0; !exiting && samples < arg_samples_len; samples++) {
                int res;
                double sample_stop;
                struct timespec req;
                time_t newint_s;
                long newint_ns;
                double elapsed;
                double timeleft;

                sampledata = new0(struct list_sample_data, 1);
                if (sampledata == NULL) {
                        log_error("Failed to allocate memory for a node: %m");
                        return -1;
                }

                sampledata->sampletime = gettime_ns();
                sampledata->counter = samples;

                if (!of && (access(arg_output_path, R_OK|W_OK|X_OK) == 0)) {
                        t = time(NULL);
                        strftime(datestr, sizeof(datestr), "%Y%m%d-%H%M", localtime(&t));
                        snprintf(output_file, PATH_MAX, "%s/bootchart-%s.svg", arg_output_path, datestr);
                        of = fopen(output_file, "w");
                }

                if (sysfd < 0)
                        sysfd = open("/sys", O_RDONLY);

                if (!build)
                        parse_env_file("/etc/os-release", NEWLINE,
                                       "PRETTY_NAME", &build,
                                       NULL);

                /* wait for /proc to become available, discarding samples */
                if (graph_start <= 0.0)
                        log_uptime();
                else
                        log_sample(samples, &sampledata);

                sample_stop = gettime_ns();

                elapsed = (sample_stop - sampledata->sampletime) * 1000000000.0;
                timeleft = interval - elapsed;

                newint_s = (time_t)(timeleft / 1000000000.0);
                newint_ns = (long)(timeleft - (newint_s * 1000000000.0));

                /*
                 * check if we have not consumed our entire timeslice. If we
                 * do, don't sleep and take a new sample right away.
                 * we'll lose all the missed samples and overrun our total
                 * time
                 */
                if (newint_ns > 0 || newint_s > 0) {
                        req.tv_sec = newint_s;
                        req.tv_nsec = newint_ns;

                        res = nanosleep(&req, NULL);
                        if (res) {
                                if (errno == EINTR) {
                                        /* caught signal, probably HUP! */
                                        break;
                                }
                                perror("nanosleep()");
                                exit (EXIT_FAILURE);
                        }
                } else {
                        overrun++;
                        /* calculate how many samples we lost and scrap them */
                        arg_samples_len -= (int)(newint_ns / interval);
                }
                LIST_PREPEND(struct list_sample_data, link, head, sampledata);
        }

        /* do some cleanup, close fd's */
        ps = ps_first;
        while (ps->next_ps) {
                ps = ps->next_ps;
                if (ps->schedstat)
                        close(ps->schedstat);
                if (ps->sched)
                        close(ps->sched);
                if (ps->smaps)
                        fclose(ps->smaps);
        }

        if (!of) {
                t = time(NULL);
                strftime(datestr, sizeof(datestr), "%Y%m%d-%H%M", localtime(&t));
                snprintf(output_file, PATH_MAX, "%s/bootchart-%s.svg", arg_output_path, datestr);
                of = fopen(output_file, "w");
        }

        if (!of) {
                fprintf(stderr, "opening output file '%s': %m\n", output_file);
                exit (EXIT_FAILURE);
        }

        svg_do(build);

        fprintf(stderr, "systemd-bootchart wrote %s\n", output_file);

        do_journal_append(output_file);

        if (of)
                fclose(of);

        closedir(proc);
        if (sysfd >= 0)
                close(sysfd);

        /* nitpic cleanups */
        ps = ps_first->next_ps;
        while (ps->next_ps) {
                struct ps_struct *old;

                old = ps;
                old->sample = ps->first;
                ps = ps->next_ps;
                while (old->sample->next) {
                        struct ps_sched_struct *oldsample = old->sample;

                        old->sample = old->sample->next;
                        free(oldsample);
                }
                free(old->sample);
                free(old);
        }
        free(ps->sample);
        free(ps);

        sampledata = head;
        while (sampledata->link_prev) {
                struct list_sample_data *old_sampledata = sampledata;
                sampledata = sampledata->link_prev;
                free(old_sampledata);
        }
        free(sampledata);
        /* don't complain when overrun once, happens most commonly on 1st sample */
        if (overrun > 1)
                fprintf(stderr, "systemd-boochart: Warning: sample time overrun %i times\n", overrun);

        return 0;
}
Exemplo n.º 24
0
int
main(int argc, char **argv)
{
	const char *conf = NULL;
	const char *dev = NULL;
	const char *table = NULL;
	int fd, fp, ch, n, val, i;
	size_t sz, sz1;
	int demon, ignore, dieearly;
	report_desc_t repd;
	char buf[100];
	char devnamebuf[PATH_MAX];
	struct command *cmd;
	int reportid = -1;

	demon = 1;
	ignore = 0;
	dieearly = 0;
	while ((ch = getopt(argc, argv, "c:def:ip:r:t:v")) != -1) {
		switch(ch) {
		case 'c':
			conf = optarg;
			break;
		case 'd':
			demon ^= 1;
			break;
		case 'e':
			dieearly = 1;
			break;
		case 'i':
			ignore++;
			break;
		case 'f':
			dev = optarg;
			break;
		case 'p':
			pidfile = optarg;
			break;
		case 'r':
			reportid = atoi(optarg);
			break;
		case 't':
			table = optarg;
			break;
		case 'v':
			demon = 0;
			verbose++;
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (conf == NULL || dev == NULL)
		usage();

	hid_init(table);

	if (dev[0] != '/') {
		snprintf(devnamebuf, sizeof(devnamebuf), "/dev/%s%s",
			 isdigit(dev[0]) ? "uhid" : "", dev);
		dev = devnamebuf;
	}

	fd = open(dev, O_RDWR);
	if (fd < 0)
		err(1, "%s", dev);
	repd = hid_get_report_desc(fd);
	if (repd == NULL)
		err(1, "hid_get_report_desc() failed");

	commands = parse_conf(conf, repd, reportid, ignore);

	sz = (size_t)hid_report_size(repd, hid_input, -1);

	if (verbose)
		printf("report size %zu\n", sz);
	if (sz > sizeof buf)
		errx(1, "report too large");

	(void)signal(SIGHUP, sighup);

	if (demon) {
		fp = open(pidfile, O_WRONLY|O_CREAT, S_IRUSR|S_IRGRP|S_IROTH);
		if (fp < 0)
			err(1, "%s", pidfile);
		if (daemon(0, 0) < 0)
			err(1, "daemon()");
		snprintf(buf, sizeof(buf), "%ld\n", (long)getpid());
		sz1 = strlen(buf);
		if (write(fp, buf, sz1) < 0)
			err(1, "%s", pidfile);
		close(fp);
		isdemon = 1;
	}

	for(;;) {
		n = read(fd, buf, sz);
		if (verbose > 2) {
			printf("read %d bytes:", n);
			for (i = 0; i < n; i++)
				printf(" %02x", buf[i]);
			printf("\n");
		}
		if (n < 0) {
			if (verbose)
				err(1, "read");
			else
				exit(1);
		}
#if 0
		if (n != sz) {
			err(2, "read size");
		}
#endif
		for (cmd = commands; cmd; cmd = cmd->next) {
			if (cmd->item.report_ID != 0 &&
			    buf[0] != cmd->item.report_ID)
				continue;
			if (cmd->item.flags & HIO_VARIABLE)
				val = hid_get_data(buf, &cmd->item);
			else {
				uint32_t pos = cmd->item.pos;
				for (i = 0; i < cmd->item.report_count; i++) {
					val = hid_get_data(buf, &cmd->item);
					if (val == cmd->value)
						break;
					cmd->item.pos += cmd->item.report_size;
				}
				cmd->item.pos = pos;
				val = (i < cmd->item.report_count) ?
				    cmd->value : -1;
			}
			if (cmd->value != val && cmd->anyvalue == 0)
				goto next;
			if ((cmd->debounce == 0) ||
			    ((cmd->debounce == 1) && ((cmd->lastseen == -1) ||
					       (cmd->lastseen != val)))) {
				docmd(cmd, val, dev, argc, argv);
				goto next;
			}
			if ((cmd->debounce > 1) &&
			    ((cmd->lastused == -1) ||
			     (abs(cmd->lastused - val) >= cmd->debounce))) {
				docmd(cmd, val, dev, argc, argv);
				cmd->lastused = val;
				goto next;
			}
next:
			cmd->lastseen = val;
		}

		if (dieearly)
			exit(0);

		if (reparse) {
			struct command *cmds =
			    parse_conf(conf, repd, reportid, ignore);
			if (cmds) {
				freecommands(commands);
				commands = cmds;
			}
			reparse = 0;
		}
	}

	exit(0);
}
Exemplo n.º 25
0
int main(int argc,char **argv)
{
	int opt,long_opt_index = 0,ret;
	struct netdev *vdev,dev;
	struct socket sk;
	u_char *ifconf;
	struct linger so_linger;
	u_int mtu=0;

	memset(&dev,0,sizeof(struct netdev));
	memset(&sk,0,sizeof(struct socket));
	ifconf = NULL;
	vdev = &dev;
	vdev->nd_ops = &nd_ops;
	vdev->sk = &sk;

	while( (opt =getopt_long(argc,argv,"hi:I:p:u:vm:H:K:d",long_opt,&long_opt_index)) != -1 ) {
		switch(opt) {
		case 'h':
			banner(argv[0]);
			break;
		case 'i':
			memcpy(&dev.nd_name,optarg,IFNAMSIZ-1);
			break;
		case 'I':
			ifconf = (u_char*)strdup(optarg);
			has_ifconf |=1;
			break;
		case 'p':
			sk.sk_port = atoi(optarg);
			break;
		case 'u':
			dev.nd_owner = (u_int8_t*)strdup(optarg);
			break;
		case 'v':
			verbose |= 1;
			break;
		case 'm':
			mtu = atoi(optarg);
			break;
		case 'K':
			shr_key = (unsigned char*)strdup(optarg);
			break;
		case 'H':
			hwaddr = (u_char *)strdup(optarg);
			break;
		case 'd':
			daemonize |=1;
			break;
		default:
			banner(argv[0]);
			break;
		}
	}
	
	/* device name is not required , 
	   the kernel will give us a random name  */
	dev.nd_flags = IFF_TAP | IFF_NO_PI;
	if(daemonize)
		if(daemon(0,0) == -1) {
			perrx("main():daemon()");
			return -1;
		}

	if(!has_ifconf ) {
		fprintf(stderr,"[!] Device configuration is not set \n");
	} else 
		parse_conf((char*)ifconf,&dev);

	if (!sk.sk_port) 
		sk.sk_port = DEFAULT_PORT;
	
	if(!mtu || mtu < 0 || mtu > 4096)
		vdev->nd_mtu = MTU;
	else
		vdev->nd_mtu = mtu;
	
	if(shr_key == NULL) {
		printf("[-] Shared key is not set\n");
		return -1;
	}
	sk.sk_fd = socket(AF_INET,SOCK_STREAM,0);
	if(sk.sk_fd < 0) {
		perror("main():socket()");
		return -1;
	}

	/* set linger socket option  */
	so_linger.l_onoff = 1;
	so_linger.l_linger = 0;
	
	ret = setsockopt(sk.sk_fd,SOL_SOCKET,SO_LINGER,&so_linger,sizeof(struct linger));
	if(ret == -1) {
		perror("main:setsockopt(SO_LINGER)");
		close(sk.sk_fd);
		return ret;
	}

	/* let's create a virtual device interface */
	if(vdev->nd_ops->init(&dev))
		return -1;
	
	int yes = 1;
	struct socket *sk_cli;
	
	sk.sk_serv.sin_family = AF_INET;
	sk.sk_serv.sin_port = htons(sk.sk_port);
	sk.sk_serv.sin_addr.s_addr = htonl(INADDR_ANY);
	
	/* enable socket address re-use */
	ret = setsockopt(sk.sk_fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes));
	if(ret == -1) {
		perror("main:setsockopt(SO_REUSEADDR)");
		close(sk.sk_fd);
		return ret;
	}
	ret = bind(sk.sk_fd,(struct sockaddr*)&sk.sk_serv,sizeof(struct sockaddr_in));
	if(ret == -1) {
		perror("main:bind()");
		close(sk.sk_fd);
		return ret;
	}
	ret = listen(sk.sk_fd,4);
	if(ret == -1) {
		perror("main:listen()");
		return -1;
	}
	if(verbose) 
		printf("[+] Listening on port : %d\n",sk.sk_port);
	
	for(;;) {
		sk_cli =sock_accept(&dev);
		if(!sk_cli)  
			return -1;
		vdev->nd_ops->xmit(vdev,sk_cli);
	}
		
	vdev->nd_ops->exit(vdev);
	return 0;
}
Exemplo n.º 26
0
int main(int argc, char* argv[]) {
    if (argc < 3) {
        printf("Usage: %s config output\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    Config *conf = parse_conf(argv[1]);
    struct client_state *state = client_state_new(conf);
    state->verbose = conf->verbose;
    struct sockaddr_in *proposer = malloc(sizeof (struct sockaddr_in));
    // socket to send Paxos messages to learners
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("cannot create socket");
        return EXIT_FAILURE;
    }

    state->sock = sock;

    struct hostent *server = gethostbyname(conf->proposer_addr);

    if (server == NULL) {
        fprintf(stderr, "ERROR, no such host as %s\n", conf->proposer_addr);
        return EXIT_FAILURE;
    }
    /* build the server's Internet address */
    bzero((char *) proposer, sizeof(struct sockaddr_in));
    proposer->sin_family = AF_INET;
    bcopy((char *)server->h_addr,
      (char *)&(proposer->sin_addr.s_addr), server->h_length);
    proposer->sin_port = htons(conf->proposer_port);

    state->proposer = proposer;

   int i;
    for (i = 0; i < state->vlen; i++) {
        state->iovecs[i].iov_base         = (void*)state->bufs[i];
        state->iovecs[i].iov_len          = BUFSIZE;
        state->msgs[i].msg_hdr.msg_iov    = &state->iovecs[i];
        state->msgs[i].msg_hdr.msg_iovlen = 1;

        state->out_iovecs[i].iov_base         = (void*)state->payload;
        state->out_iovecs[i].iov_len          = state->payload_sz;
        state->out_msgs[i].msg_hdr.msg_name    = (void *)state->proposer;
        state->out_msgs[i].msg_hdr.msg_namelen = sizeof(struct sockaddr_in);
        state->out_msgs[i].msg_hdr.msg_iov    = &state->out_iovecs[i];
        state->out_msgs[i].msg_hdr.msg_iovlen = 1;
    }

    state->fp = fopen(argv[2], "w+");

    send_message(state, state->vlen);

    struct timeval period = {1, 0};
    struct event *ev_recv;
    ev_recv = event_new(state->base, state->sock, EV_READ|EV_PERSIST, on_response, state);
    struct event *ev_monitor;
    ev_monitor = event_new(state->base, -1, EV_TIMEOUT|EV_PERSIST, monitor, state);
    struct event *ev_sigterm;
    ev_sigterm = evsignal_new(state->base, SIGTERM, signal_handler, state);
    struct event *ev_sigint;
    ev_sigint = evsignal_new(state->base, SIGINT, signal_handler, state);


    event_add(ev_sigint, NULL);
    event_add(ev_recv, &period);
    event_add(ev_monitor, &period);
    event_add(ev_sigterm, NULL);

    event_base_dispatch(state->base);
    free(conf);
    event_free(ev_recv);
    event_free(ev_monitor);
    event_free(ev_sigint);
    event_free(ev_sigterm);
    client_state_free(state);
    close(sock);
    return EXIT_SUCCESS;
}
Exemplo n.º 27
0
int mainLoop (char *confpath) {
	cfg_t *cfg;
	redisContext *c;
	redisReply *reply;
	char *respcpy, *ascval, *curtok;
	unsigned int chan, val, start;
	int iofd, retval=-1, maxchain, numchan;
	int outbpc[3];
	/* Localize messages & types according to environment, since v2.9 */
	setlocale(LC_MESSAGES, "");
	setlocale(LC_CTYPE, "");

	/* Read configuration and initialize to default state*/
	statestr=malloc(sizeof(DEFSTATE)+1);
	strcpy(statestr,DEFSTATE);

	cfg = parse_conf(confpath == NULL ? "/etc/bone-shiftreg.conf" : confpath);
	if (!cfg) {
		fprintf(stderr,"Error parsing configuration file!\n");
		retval=-2;
		goto cleanupnone;
	}
	outbpc[0] = cfg_getint(cfg,"ser0-num-channels");
	outbpc[1] = cfg_getint(cfg,"ser1-num-channels");
	outbpc[2] = cfg_getint(cfg,"ser2-num-channels");
	if(cfg_getbool(cfg,"debug")){
		debug = 1;
	} else {
		debug = 0;
	}
	start = cfg_getint(cfg,"start-address");
	numchan = summation(0,NUMPINS-1, outbpc);
	printf("This board has a total of %d channels\n", numchan);

	/* Open remoteproc device */
	if((iofd = io_init(cfg_getstr(cfg,"pru-remoteproc-file"))) < 0){
		fprintf(stderr,"Failed to open remoteproc device file! Firmware still booting?\n");
		retval = -1;
		goto cleanupconf;
	}
	/* Set output channel count */
	maxchain = imax(imax(outbpc[0],outbpc[1]),outbpc[2]);
	if(maxchain == 0){
		fprintf(stderr,"At least one output chain must have more then zero channels!\n");
		goto cleanupio;
	}

	if(io_set_nchannels(iofd, maxchain) < 0){
		fprintf(stderr,"Failed to set max chain length to %d!\n", maxchain);
		retval = -2;
		goto cleanupio;
	}
	/* Establish Redis connection */
	printf("Connecting to redis at %s, port %ld\n", cfg_getstr(cfg,"redis-host"), cfg_getint(cfg,"redis-port"));
	c = redisConnect(cfg_getstr(cfg,"redis-host"), cfg_getint(cfg,"redis-port"));
	/* Handle Redis connection errors */
	if (c == NULL || c->err) {
		if (c) {
			fprintf(stderr,"Error: %s\n", c->errstr);
			goto cleanupall;
		} else {
			fprintf(stderr,"Can't allocate redis context\n");
			goto cleanupio;
		}
	}
	/* Authenticate if needed */
	if(cfg_getbool(cfg,"redis-authrequired")){
		const char authpref[] = "AUTH ";
		char *authstr = malloc(sizeof(authpref) + strlen(cfg_getstr(cfg,"redis-password")) + 1);
		memcpy(authstr, authpref, sizeof(authpref));
		strcat(authstr, cfg_getstr(cfg,"redis-password"));
		reply = redisCommand(c, authstr);
		free(authstr);
		if(!reply || reply->type == REDIS_REPLY_ERROR){
			fprintf(stderr,"authentication failed\n");
			goto cleanupall;
		}
		if(reply)
			freeReplyObject(reply);
	}
	reply = redisCommand(c, "PING");
	if(!reply || reply->type == REDIS_REPLY_ERROR){
		fprintf(stderr,"Unable to execute Redis commands, are you authenticated if necessary?\n");
		if(reply)
			freeReplyObject(reply);
		goto cleanupall;
	} else { 
		freeReplyObject(reply);
	}
	/* If we have gotten here we have initialized successfully */
	/* Restore state */ 
	if(cfg_getbool(cfg,"persistent-state")){
		if(restoreState(c, iofd, start, start+numchan, outbpc, NUMPINS) == -2){
			retval = -2;
			goto cleanupall;
		}
	}
	retval=0;
	/* Message handling loop */
	if(debug)
		fprintf(stderr,"Subscribed...\n");
	reply = redisCommand(c, "SUBSCRIBE changes");
	freeReplyObject(reply);
	while(redisGetReply(c,(void *)&reply) == REDIS_OK) {
		if(debug)
			fprintf(stderr,"Begin message parsing\n");
		// consume message
		if (reply == NULL) 
			continue;
		if (reply->type == REDIS_REPLY_ARRAY) {
			if(reply->elements == 3) {
				if(reply->element[0]->type == REDIS_REPLY_STRING && reply->element[2]->type == REDIS_REPLY_STRING && strcmp("message", reply->element[0]->str) == 0){
					if(debug)  
						fprintf(stderr,"Processing incoming message %s\n", reply->element[2]->str);
					//Message parsing
					respcpy = malloc(strlen(reply->element[2]->str)+1);
					assert(respcpy != NULL);
					strcpy(respcpy, reply->element[2]->str);
					#ifdef ALLOWSHUTDOWN
					if(strstr(respcpy, "@")){
						free(respcpy);
						freeReplyObject(reply);
						retval = -3;
						goto cleanupall;
					}
					#endif
					if(strstr(respcpy, "!")){
						//Reload requested, cleanup and return 0 (which causes a reload)
						free(respcpy);
						freeReplyObject(reply);
						goto cleanupall;
					}
					curtok = strtok(respcpy,",");
					while(curtok != NULL){
						ascval = strsep(&curtok, ":");
						if(curtok != NULL){
							chan = atoi(ascval);
							val = atoi(curtok);
							//Does this channel belong to us? If so, update!
							if(setChannelIfOurs(iofd, chan, val, start, outbpc, NUMPINS) == -2){
								/* IO error, bail out! */
								fprintf(stderr, "IO error, bailing!\n");
								freeReplyObject(reply);
								free(respcpy);
								goto cleanupall;
							}
						} else {
							fprintf(stderr, "Malformed message published to channel!\n");
						}
						curtok = strtok(NULL,",");
					}
					free(respcpy);
				}
			} else {
				fprintf(stderr, "Invalid number of elements in reply array!\n");
			}
		}
		freeReplyObject(reply);
	}
	fprintf(stderr, "Lost connection to redis server!\n");
cleanupall:
	redisFree(c);
cleanupio:
	io_close(iofd);
cleanupconf:
	cfg_free(cfg);
cleanupnone:
	free(statestr);
	return retval;
}
Exemplo n.º 28
0
int main(int argc, char * const argv[])
{
	struct sdp_dev *p_id;
	int err = 0;
	int config = 0;
	int verify = 0;
	int usertscts = 1;
	int uart_fd;
	struct sdp_work *curr;
	char const *conf;
	char const *ttyfile;
	char const *conffilepath;
	char const *conffile;
	char const *basepath;
#ifndef WIN32
	struct termios orig;
#else
	DCB orig;
#endif

	curr=NULL;

	err = parse_opts(argc, argv, &ttyfile, &conffilepath, &verify, &usertscts, &curr);

	if (err < 0)
		return err;

	// Get machine specific configuration file..
	if ((conffile = strrchr(conffilepath, PATH_SEPARATOR)) == NULL) {
		// Only a file was given as configuration
		basepath = get_base_path(argv[0]);
		conffile = conffilepath;
	} else {
		// A whole path is given as configuration
		basepath = get_base_path(conffilepath);
		conffile++; // Filename starts after slash
	}

	conf = conf_file_name(conffile, basepath, SYSCONFDIR "/imx-loader.d/");
	if (conf == NULL)
		return -1;

	p_id = parse_conf(conf);
	if (!p_id)
		return -1;

	// Open UART and start associating phase...
	err = uart_connect(&uart_fd, ttyfile, usertscts, &orig);

	if (err < 0)
		goto out;

	p_id->transfer = &transfer_uart;

	// UART private pointer is TTY file descriptor...
	p_id->priv = &uart_fd;

	err = do_status(p_id);
	if (err) {
		printf("status failed\n");
		goto out;
	}

	// By default, use work from config file...
	if (curr == NULL)
		curr = p_id->work;

	while (curr) {
		if (curr->mem)
			perform_mem_work(p_id, curr->mem);
//		printf("jump_mode %x\n", curr->jump_mode);
		if (curr->filename[0]) {
			err = DoIRomDownload(p_id, curr, verify);
		}
		if (err) {
			err = do_status(p_id);
			break;
		}
		if (!curr->next && !curr->plug)
			break;
		err = do_status(p_id);
		printf("jump_mode %x plug=%i err=%i\n", curr->jump_mode, curr->plug, err);

		if (err)
			goto out;

		if (curr->plug) {
			curr->plug = 0;
			continue;
		}
		curr = curr->next;
	}

out:
	uart_close(&uart_fd, &orig);
	return err;
}
Exemplo n.º 29
0
static int
gcc_apt_build (int argc, char **argv)
{
  return gcc_real (parse_conf (argc, argv));
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{

    struct netcat_conf conf;
    int sd;
    struct sockaddr_in all = {};
    struct sockaddr_in tgt = {};
    size_t socksize = sizeof(struct sockaddr_in);
    struct pollfd pfd[2];
    int off = 0;

    if (parse_conf(&conf, argc, argv) < 0) {
        return 1;
    }

    sd = socket(AF_INET, conf.socktype, 0);
    if (sd < 0)
    {
        fprintf(stderr, "Cannot open socket!\n");
        exit(1);
    }

    if (conf.mode) {
        int ret;
        all.sin_family = AF_INET;
        all.sin_port = htons(conf.lport);

        ret = bind(sd, (struct sockaddr *)&all, sizeof(struct sockaddr_in));
        if (ret < 0) {
            fprintf(stderr, "Bind failed with %d - errno: %d (%s)\r\n", ret, errno, strerror(errno));
            exit(3);
        }

        if (conf.socktype == SOCK_STREAM) {
            int asd;
            if (listen(sd, 3) < 0) {
                perror("listen");
                exit(2);
            }
            asd = accept(sd, (struct sockaddr *)&tgt, &socksize);
            if (asd < 0) {
                perror("accept");
                exit(3);
            }
            close(sd);
            sd = asd;
            fprintf(stderr, "Accepted connection.\r\n");
        }
    } else {
        tgt.sin_family = AF_INET;
        tgt.sin_port = htons(conf.port);
        inet_aton(conf.host, &tgt.sin_addr); /* TODO: getaddrinfo */
        if (connect(sd, (struct sockaddr *)&tgt, sizeof(struct sockaddr_in)) < 0) {
            perror("connect");
            exit(3);
        }
        fprintf(stderr, "Connected to server.\r\n");
    }

    while(1) {
        int pollret;
        int r;
        char buf_in[100];
        char buf_sock[100];
        pfd[0].fd = STDIN_FILENO;
        pfd[1].fd = sd;
        pfd[0].events = POLLIN;
        pfd[1].events = POLLIN | POLLHUP | POLLERR;
        pollret = poll(pfd, 2, -1);
        if (pollret < 0) {
            fprintf(stderr, "nc: poll returned -1\r\n");
            break;
        }
        if ((pfd[1].revents & (POLLHUP | POLLERR)) != 0) {
            fprintf(stderr, "nc: remote peer has closed connection.\r\n");
            break;
        }
        if (pfd[1].revents & POLLIN) {
            r = read(sd, buf_sock, 100);
            if (r > 0) {
                if (buf_sock[r - 1] == '\n') {
                    r--;
                    write(STDOUT_FILENO, buf_sock, r);
                    printf("\r\n");
                } else {
                    write(STDOUT_FILENO, buf_sock, r);
                }
            }
        }
        if (pfd[0].revents & POLLIN) {
            r = read(pfd[0].fd, buf_in + off, 100 - off);
            if (r > 0) {
                write(STDOUT_FILENO, buf_in + off, r);
                off += r;
                if ((off == 100) || (buf_in[off - 1] == '\n') || (buf_in[off - 1] == '\r')) {
                    if (buf_in[off - 1] == '\r') {
                        buf_in[off - 1] = '\n';
                        printf("\n");
                    }
                    write(sd, buf_in, off);
                    off = 0;
                }
            }
        }
    }
    fprintf(stderr, "nc: interrupted\r\n");
    return 1;
}