コード例 #1
0
ファイル: threader.c プロジェクト: jeremija/threader
/*
 * read fro mconfig file and set it up
 */
void config_file_actions(const char* home_dir) {
  /*
   * path of config file, default: /home/$USER/.threader/config
   */
  char* config_location;
  if (use_custom_config_file) {
    config_location = print_to_string("%s", custom_config_file_location);
  } else {
    config_location = print_to_string("%s%s%s%s", home_dir, "/.", APP_NAME, "/config");
  }
  LOG(INFO, "config_location=%s", config_location);
  /*
   * read config file
   */
  config = read_conf_file(config_location);
  free(config_location);
  LOG(INFO, "command='%s', threads=%d, old_ext='%s', new_ext='%s', run_script_on_finish=%d, "
      "script_path=%s",
      config.command, config.threads, config.old_ext, config.new_ext, config.run_script_on_finish, config.script_path);
  
  /* CONFIG FILE OVERRIDES */
  
  /*
   * override thread number set in config file if -n option was passed
   */
  if (override_config_threads_num != 0) {
    LOG(INFO, "Overriding thread number from config file from %d to %d (-n option was passed)", 
        config.threads, override_config_threads_num);
    set_config_threads(&config, override_config_threads_num);
  }
}
コード例 #2
0
ファイル: ztest.c プロジェクト: 2010fares/PMB
bend_initresult *bend_init(bend_initrequest *q)
{
    bend_initresult *r = (bend_initresult *)
        odr_malloc (q->stream, sizeof(*r));
    int *counter = (int *) xmalloc (sizeof(int));

    *counter = 0;
    r->errcode = 0;
    r->errstring = 0;
    r->handle = counter;         /* user handle, in this case a simple int */
    q->bend_sort = ztest_sort;              /* register sort handler */
    q->bend_search = ztest_search;          /* register search handler */
    q->bend_present = ztest_present;        /* register present handle */
    q->bend_esrequest = ztest_esrequest;
    q->bend_delete = ztest_delete;
    q->bend_fetch = ztest_fetch;
    q->bend_scan = ztest_scan;
    q->bend_explain = ztest_explain;
    
    if (read_conf_file()) {
    	yaz_log(LOG_LOG,"Can't handle configuration file");
    	r->errcode = 2;
    }
     return r;
}
コード例 #3
0
ファイル: splashd.c プロジェクト: arjan/NoCatSplash
int main (int argc, char **argv) {
    GMainLoop  *loop;
    GIOChannel *sock;

    /* Initialize signal handlers */
    signal(SIGPIPE, SIG_IGN);
    signal(SIGINT,  handle_sigint);

    /* read nocat.conf */
    read_conf_file( NC_CONF_PATH "/nocat.conf" );

    initialize_driver();

    /* initialize the firewall */
    fw_init( nocat_conf );

    /* initialize the peer table */
    peer_tab = g_hash_new();

    /* initialize the listen socket */
    sock = http_bind_socket( 
	    CONF("GatewayAddr"), CONFd("GatewayPort"), CONFd("ListenQueue") );

    /* initialize the main loop and handlers */
    loop = g_main_new(FALSE);
    g_io_add_watch( sock, G_IO_IN,  (GIOFunc) handle_accept, NULL );
    g_timeout_add( 30000, (GSourceFunc) check_peers, NULL );
    g_timeout_add( 1000, (GSourceFunc) check_sigint, loop );
    
    /* Go! */
    g_message("starting main loop");
    g_main_run( loop );
    g_message("exiting main loop");
    return 0;
}
コード例 #4
0
ファイル: bank.c プロジェクト: hnkien/bank
int main(int argc, char *argv[]) {
	if (pthread_mutex_init(&sending_lock, NULL ) != 0) {
		printf("Fail to initialize sending_lock.\n");
		exit(1);
	}
	const char *conf_file = DEFAULT_CONF_FILE;
	if (argc >= 3 && strcmp(argv[1], "-c") == 0) {
		conf_file = argv[2];
	}
	Node *conf = read_conf_file(conf_file);
	if (conf == NULL ) {
		printf("Fail to read conf file %s\n", conf_file);
		exit(1);
	}
	BankConfig config = get_bank_config(conf);
	if (gen_pid_file(config.bank_pid_file) != 0) {
		printf("Fail to generate pid file.\n");
		exit(1);
	}
	if (log_init(config.logging_error_log, config.logging_log_level) != 1) {
		printf("Fail to initialize logger.\n");
		exit(1);
	}
	run_bank(config);
	return 0;
}
コード例 #5
0
int main (int argc, char * argv[])
{
	int i, status, lsockfd, csockfd;  /* local/connection socket file descriptor */
	struct sockaddr_in raddr;      /* remote address object */
	socklen_t raddr_len = sizeof (struct sockaddr_in);
	pthread_t connThread;   /* thread identifier */
	User_Settings * o_stngs; /* user suplied settings struct (stores user settings)*/

	/* set global variables */
	server = "simpleText";
	version = 1.0f;

	/* allocate user suplied settings struct */
	o_stngs = malloc(sizeof(User_Settings));

	/* read configuration file */
	read_conf_file (o_stngs);

	/* parse and set cli options */
	parse_cli_opts (argc, (char **) &argv[0], o_stngs);

	/* make daemon and start logging */
	status = init_daemon (server, o_stngs);
	if (status == 0)
		return EXIT_SUCCESS; /* parent returns success */
	else if (status == 1)
		return EXIT_FAILURE; /* parent returns failure */

	syslog (LOG_NOTICE, "[PID: %u, SID: %u] > %s started..",
					getpid (), getsid (getpid ()), server);

	/* Read Hosts File */
	host_cnt = read_host_file (NULL, 1);
	for (i = 0; i < host_cnt; i++)
		read_host_file (&o_vhost[i], 0);

	/* start listening for TCP connections */
	lsockfd = start_listen (o_stngs->port);
	free(o_stngs);

	/* loop through accepting and handling connections */
	while (1)
	{
		/* accept connection or skip to next conection if accept fails */
		csockfd = accept (lsockfd, (struct sockaddr *) &raddr, &raddr_len);
		if (csockfd == -1) /* if connection fails ignore it and continue */
			continue;

		Connect_Args * o_args = malloc(sizeof(Connect_Args *));
		o_args->socket = csockfd;
		strcpy (o_args->client_addr, inet_ntoa (raddr.sin_addr));

		/* create thread to handle connection */
		pthread_create(&connThread, NULL, (void *) &attent_connection, o_args);

		/* wait for one second before accepting next connection */
		sleep (1);
	}
}
コード例 #6
0
ファイル: softp11.c プロジェクト: heimdal/heimdal
CK_RV CK_SPEC
C_Initialize(CK_VOID_PTR a)
{
    CK_C_INITIALIZE_ARGS_PTR args = a;
    CK_RV ret;
    size_t i;

    st_logf("Initialize\n");

    INIT_CONTEXT();

    OpenSSL_add_all_algorithms();

    srandom(getpid() ^ (int) time(NULL));

    for (i = 0; i < MAX_NUM_SESSION; i++) {
	soft_token.state[i].session_handle = CK_INVALID_HANDLE;
	soft_token.state[i].find.attributes = NULL;
	soft_token.state[i].find.num_attributes = 0;
	soft_token.state[i].find.next_object = -1;
	reset_crypto_state(&soft_token.state[i]);
    }

    soft_token.flags.hardware_slot = 1;
    soft_token.flags.app_error_fatal = 0;
    soft_token.flags.login_done = 0;

    soft_token.object.objs = NULL;
    soft_token.object.num_objs = 0;

    soft_token.logfile = NULL;
#if 0
    soft_token.logfile = stdout;
#endif
#if 0
    soft_token.logfile = fopen("/tmp/log-pkcs11.txt", "a");
#endif

    if (a != NULL_PTR) {
	st_logf("\tCreateMutex:\t%p\n", args->CreateMutex);
	st_logf("\tDestroyMutext\t%p\n", args->DestroyMutex);
	st_logf("\tLockMutext\t%p\n", args->LockMutex);
	st_logf("\tUnlockMutext\t%p\n", args->UnlockMutex);
	st_logf("\tFlags\t%04x\n", (unsigned int)args->flags);
    }

    soft_token.config_file = get_config_file_for_user();

    /*
     * This operations doesn't return CKR_OK if any of the
     * certificates failes to be unparsed (ie password protected).
     */
    ret = read_conf_file(soft_token.config_file, CKU_USER, NULL);
    if (ret == CKR_OK)
	soft_token.flags.login_done = 1;

    return CKR_OK;
}
コード例 #7
0
ファイル: hip_dht.c プロジェクト: carriercomm/openhip
int main(int argc, char **argv)
{
  int err, publish;
  hip_hit hit;
  struct sockaddr_storage addr;
  struct sockaddr_in *addr4 = (struct sockaddr_in*)&addr;

  /*
   * Load hip.conf configuration file
   * user may have provided path using command line, or search defaults
   */
  memset(HCNF, 0, sizeof(HCNF));
  if ((locate_config_file(HCNF.conf_filename, sizeof(HCNF.conf_filename),
                          HIP_CONF_FILENAME) < 0) ||
      (read_conf_file(HCNF.conf_filename) < 0))
    {
      log_(ERR, "Problem with configuration file, using defaults.\n");
    }
  else
    {
      log_(NORM, "Using configuration file:\t%s\n",
           HCNF.conf_filename);
    }


  memset(&addr, 0, sizeof(addr));
  addr4->sin_family = AF_INET;
  addr4->sin_addr.s_addr = inet_addr("192.168.1.2");
  hex_to_bin("7BE901B3AF2679C8C580619535641713", hit, HIT_SIZE);

  printf("Doing XML RPC put 1...\n");
  err = hip_dht_publish(&hit, (struct sockaddr*)&addr);
  printf("return value = %d\n", err);

  addr4->sin_addr.s_addr = inet_addr("192.168.2.7");

  printf("Doing XML RPC put 2...\n");
  err = hip_dht_publish(&hit, (struct sockaddr*)&addr);
  printf("return value = %d\n", err);

  memset(&addr, 0, sizeof(addr));
  addr4->sin_family = AF_INET;

  printf("addr is at: %p\n", &addr);
  printf("Doing XML RPC get...\n");
  err = hip_dht_lookup_address(&hit, (struct sockaddr*)&addr);
  printf("return value = %d\n", err);
  printf("Address = %s\n", logaddr((struct sockaddr*)&addr));
  return(0);
}
コード例 #8
0
ファイル: smcroute.c プロジェクト: swegener/smcroute
/*
 * Signal handler.  Take note of the fact that the signal arrived
 * so that the main loop can take care of it.
 */
static void handler(int sig)
{
	switch (sig) {
	case SIGINT:
	case SIGTERM:
		running = 0;
		break;

	case SIGHUP:
		smclog(LOG_NOTICE, 0, "Got SIGHUP, reloading %s ...", conf_file);
		restart();
		read_conf_file(conf_file);
		break;
	}
}
コード例 #9
0
int
check_include(char *buf)
{
	char *str;
	vector_t *strvec;
	char *path;
	int ret;

	strvec = alloc_strvec(buf);

	if (!strvec){
		return 0;
	}
	str = vector_slot(strvec, 0);
	
	if (!strcmp(str, EOB)) {
		free_strvec(strvec);
		return 0;
	}

	if(!strcmp("include", str) && vector_size(strvec) == 2){
		char *conf_file = vector_slot(strvec, 1);

		FILE *prev_stream = current_stream;
		char *prev_conf_file = current_conf_file;
		char prev_path[MAXBUF];
		path = getcwd(prev_path, MAXBUF);
		if (!path) {
			log_message(LOG_INFO, "getcwd(%s) error (%s)\n"
					    , prev_path, strerror(errno));
		}

		read_conf_file(conf_file);
		current_stream = prev_stream;
		current_conf_file = prev_conf_file;
		ret = chdir(prev_path);
		if (ret < 0) {
			log_message(LOG_INFO, "chdir(%s) error (%s)\n"
					    , prev_path, strerror(errno));
		}
		free_strvec(strvec);
		return 1;
	}
	free_strvec(strvec);
	return 0;
}
コード例 #10
0
/* Data initialization */
void
init_data(char *conf_file, vector_t * (*init_keywords) (void))
{
	/* Init Keywords structure */
	keywords = vector_alloc();
	(*init_keywords) ();

#if 0
	/* Dump configuration */
	vector_dump(keywords);
	dump_keywords(keywords, 0);
#endif

	/* Stream handling */
	current_keywords = keywords;
	read_conf_file((conf_file) ? conf_file : CONF);
	free_keywords(keywords);
}
コード例 #11
0
ファイル: splashd.c プロジェクト: xunmengdeganjue/nocatsplash
int main (int argc, char **argv) {
    GMainLoop  *loop;
    GIOChannel *sock;

    /* read nocat.conf */
    read_conf_file( NC_CONF_PATH "/nocat.conf" );

    if (argc < 2 || strncmp(argv[1], "-D", 2) != 0)
        daemonize();

    /* initalize the log */
    initialize_log();

    /* set network parameters */
    set_network_defaults( nocat_conf );

    /* initialize the gateway type driver */
    initialize_driver();

    /* initialize the firewall */
    fw_init( nocat_conf );

    /* initialize the peer table */
    peer_tab = g_hash_new();

    /* initialize the listen socket */
    sock = http_bind_socket(
               CONF("GatewayAddr"), CONFd("GatewayPort"), CONFd("ListenQueue") );

    /* initialize the main loop and handlers */
    loop = g_main_new(FALSE);
    g_io_add_watch( sock, G_IO_IN,  (GIOFunc) handle_accept, NULL );
    g_timeout_add( 30000, (GSourceFunc) check_peers, NULL );
    g_timeout_add( 1000, (GSourceFunc) check_exit_signal, loop );

    /* Go! */
    g_message("starting main loop");
    g_main_run( loop );
    g_message("exiting main loop");
    return 0;
}
コード例 #12
0
ファイル: smcroute.c プロジェクト: swegener/smcroute
/* Init everything before forking, so we can fail and return an
 * error code in the parent and the initscript will fail */
static void start_server(int background)
{
	int sd, api = 0;

	if (background && daemonize())
		return;

	smclog(LOG_NOTICE, 0, "%s", version_info);

	/* Build list of multicast-capable physical interfaces that
	 * are currently assigned an IP address. */
	iface_init();

	if (!mroute4_enable())
		api++;

	if (!mroute6_enable())
		api++;

	/* At least one API (IPv4 or IPv6) must have initialized successfully
	 * otherwise we abort the server initialization. */
	if (!api) {
		smclog(LOG_INIT, ENOPROTOOPT, "Kernel does not support multicast routing");
		exit(1);
	}

	sd = ipc_server_init();
	if (sd < 0)
		smclog(LOG_WARNING, errno, "Failed setting up IPC socket, client communication disabled");

	atexit(clean);
	signal_init();
	read_conf_file(conf_file);

	/* Everything setup, notify any clients by creating the pidfile */
	if (pidfile(NULL))
		smclog(LOG_WARNING, errno, "Failed creating pidfile");

	server_loop(sd);
}
コード例 #13
0
ファイル: config.c プロジェクト: Alkzndr/freebsd
static int
load_repositories(const char *repodir)
{
	struct dirent *ent;
	DIR *d;
	char *p;
	size_t n;
	char path[MAXPATHLEN];
	int ret;

	ret = 0;

	if ((d = opendir(repodir)) == NULL)
		return (1);

	while ((ent = readdir(d))) {
		/* Trim out 'repos'. */
		if ((n = strlen(ent->d_name)) <= 5)
			continue;
		p = &ent->d_name[n - 5];
		if (strcmp(p, ".conf") == 0) {
			snprintf(path, sizeof(path), "%s%s%s",
			    repodir,
			    repodir[strlen(repodir) - 1] == '/' ? "" : "/",
			    ent->d_name);
			if (access(path, F_OK) == 0 &&
			    read_conf_file(path, CONFFILE_REPO)) {
				ret = 1;
				goto cleanup;
			}
		}
	}

cleanup:
	closedir(d);

	return (ret);
}
コード例 #14
0
ファイル: parser.c プロジェクト: pqarmitage/keepalived
/* Data initialization */
void
init_data(const char *conf_file, vector_t * (*init_keywords) (void))
{
	/* Init Keywords structure */
	keywords = vector_alloc();

	(*init_keywords) ();

#if DUMP_KEYWORDS
	/* Dump configuration */
	dump_keywords(keywords, 0, NULL);
#endif

	/* Stream handling */
	current_keywords = keywords;

	register_null_strvec_handler(null_strvec);
	read_conf_file(conf_file);
	unregister_null_strvec_handler();

	free_keywords(keywords);
	clear_rt_names();
}
コード例 #15
0
ファイル: softp11.c プロジェクト: heimdal/heimdal
CK_RV
C_Login(CK_SESSION_HANDLE hSession,
	CK_USER_TYPE userType,
	CK_UTF8CHAR_PTR pPin,
	CK_ULONG ulPinLen)
{
    char *pin = NULL;
    CK_RV ret;
    INIT_CONTEXT();

    st_logf("Login\n");

    VERIFY_SESSION_HANDLE(hSession, NULL);

    if (pPin != NULL_PTR) {
	int aret;

	aret = asprintf(&pin, "%.*s", (int)ulPinLen, pPin);
	if (aret != -1 && pin)
		st_logf("type: %d password: %s\n", (int)userType, pin);
	else
		st_logf("memory error: asprintf failed\n");
    }

    /*
     * Login
     */

    ret = read_conf_file(soft_token.config_file, userType, pin);
    if (ret == CKR_OK)
	soft_token.flags.login_done = 1;

    free(pin);

    return soft_token.flags.login_done ? CKR_OK : CKR_PIN_INCORRECT;
}
コード例 #16
0
ファイル: parser.c プロジェクト: rohara/keepalived
static bool
check_include(char *buf)
{
	vector_t *strvec;
	bool ret = false;
	FILE *prev_stream;

	strvec = alloc_strvec(buf);

	if (!strvec)
		return false;

	if(!strcmp("include", vector_slot(strvec, 0)) && vector_size(strvec) == 2) {
		prev_stream = current_stream;

		read_conf_file(vector_slot(strvec, 1));

		current_stream = prev_stream;
		ret = true;
	}

	free_strvec(strvec);
	return ret;
}
コード例 #17
0
ファイル: main.c プロジェクト: leek2hu/wtcpcopy
static int
set_details()
{
    int            mtu_list[] = {576, 1492, 1500, 0};
    int            i, len, index, offset, rand_port;
    unsigned int   seed;
    unsigned char  value;
    struct timeval tp;

    for (i = tc_pagesize; i >>= 1; tc_pagesize_shift++) { /* void */ }

    /* generate a random port number for avoiding port conflicts */
    gettimeofday(&tp, NULL);\
    seed = tp.tv_usec;
#if (MINGW32)
    srand(seed);
    rand_port = (int) ((rand() / (RAND_MAX + 1.0)) * 512);
#else
    rand_port = (int) ((rand_r(&seed) / (RAND_MAX + 1.0)) * 512);
#endif
    clt_settings.rand_port_shifted = rand_port;

    if (clt_settings.sess_timeout < 0) {
        clt_settings.sess_timeout = DEFAULT_SESS_TIMEOUT;
    }
    tc_log_info(LOG_NOTICE, 0, "session timeout:%d",
            clt_settings.sess_timeout);

    if (clt_settings.sess_keepalive_timeout <= 0) {
        clt_settings.sess_keepalive_timeout = clt_settings.sess_timeout +
            SESS_KEEPLIVE_ADD;
    }
    tc_log_info(LOG_NOTICE, 0, "keepalive timeout:%d",
            clt_settings.sess_keepalive_timeout);

#if (!TC_UDP)
    if (clt_settings.s_pool_size == 0) {
        clt_settings.s_pool_size = TC_DEFAULT_UPOOL_SIZE;
    }
    tc_log_info(LOG_NOTICE, 0, "min sess pool size:%d", TC_MIN_SESS_POOL_SIZE);
    tc_log_info(LOG_NOTICE, 0, "sess pool size:%d", clt_settings.s_pool_size);

    if (clt_settings.s_pool_size < TC_MIN_SESS_POOL_SIZE) {
        tc_log_info(LOG_NOTICE, 0, "sess pool size is too small");
    }
#endif

    if (clt_settings.replica_num > 1) {
        tc_log_info(LOG_NOTICE, 0, "repl num:%d", clt_settings.replica_num);
    }

    if (clt_settings.gradully) {
        tc_log_info(LOG_NOTICE, 0, "gradully replay");
    }

    /* set the ip port pair mapping according to settings */
    if (retr_target_addrs(clt_settings.raw_tf, &clt_settings.transfer) == -1) {
        return -1;
    }

    if (clt_settings.raw_clt_tf_ip != NULL) {
        /* print out raw_clt_tf_ip */
        tc_log_info(LOG_NOTICE, 0, "raw_clt_tf_ip:%s",
                clt_settings.raw_clt_tf_ip);
        retrieve_clt_tf_ips();
    }

    if (clt_settings.percentage > 99) {
        clt_settings.percentage = 0;
    }

#if (!TC_UDP)
    if (sizeof(tc_sess_t) > TC_UPOOL_MAXV) {
        tc_log_info(LOG_NOTICE, 0, "TC_UPOOL_MAXV is too small");
    }
#endif

    if (clt_settings.par_conns <= 0) {
        clt_settings.par_conns = 1;
    } else if (clt_settings.par_conns > MAX_CONN_NUM) {
        clt_settings.par_conns = MAX_CONN_NUM;
    }
    tc_log_info(LOG_NOTICE, 0, "parallel connections per target:%d",
            clt_settings.par_conns);

    len = sizeof(mtu_list) / sizeof(int) - 1;
    for (i = 0; i < len; i++) {
        if (mtu_list[i] == clt_settings.mtu) {
            break;
        }
    }
    if (i == len) {
        mtu_list[len++] = clt_settings.mtu;
    }
    for (i = 0; i < len; i++) {
        index = mtu_list[i] >> 3;
        offset = mtu_list[i] - (index << 3);
        value = clt_settings.candidate_mtu[index];
        value = value | (1 << offset);
        clt_settings.candidate_mtu[index] = value;
    }

#if (TC_OFFLINE)
    if (clt_settings.pcap_file == NULL) {
        tc_log_info(LOG_ERR, 0, "it must have -i argument for offline");
        fprintf(stderr, "no -i argument\n");
        return -1;
    }

    if (clt_settings.accelerated_times < 1) {
        clt_settings.accelerated_times = 1;
    }

    tc_log_info(LOG_NOTICE, 0, "accelerated %d times,interval:%llu ms",
            clt_settings.accelerated_times, clt_settings.interval);

    if (clt_settings.interval > 0) {
        clt_settings.interval = clt_settings.interval * 1000;
    }
#endif

#if (TC_PCAP_SND)
    if (clt_settings.output_if_name != NULL) {
        tc_log_info(LOG_NOTICE, 0, "output device:%s",
                clt_settings.output_if_name);
    } else {
        tc_log_info(LOG_ERR, 0, "no -o argument");
        fprintf(stderr, "no -o argument\n");
        return -1;
    }
#endif

#if (TC_PCAP)
    if (clt_settings.raw_device != NULL) {
        tc_log_info(LOG_NOTICE, 0, "device:%s", clt_settings.raw_device);
        if (strcmp(clt_settings.raw_device, DEFAULT_DEVICE) == 0) {
            clt_settings.raw_device = NULL;
        } else {
            retrieve_devices(clt_settings.raw_device, &(clt_settings.devices));
        }
    }

    if (clt_settings.user_filter != NULL) {
        tc_log_info(LOG_NOTICE, 0, "user filter:%s", clt_settings.user_filter);
        len = strlen(clt_settings.user_filter);
        if (len >= MAX_FILTER_LENGH) {
            tc_log_info(LOG_ERR, 0, "user filter is too long");
            return -1;
        }
        memcpy(clt_settings.filter, clt_settings.user_filter, len);

    } else {
        extract_filter();
    }

    if (clt_settings.snaplen > PCAP_RCV_BUF_SIZE) {
        clt_settings.snaplen = PCAP_RCV_BUF_SIZE;
    }
#endif

    /* retrieve real server ip addresses  */
    if (clt_settings.raw_rs_list != NULL) {
        tc_log_info(LOG_NOTICE, 0, "s parameter:%s",
                clt_settings.raw_rs_list);
        retrieve_real_servers();
    } else {
        tc_log_info(LOG_WARN, 0, "no -s parameter(intercept addresses)");
        fprintf(stderr, "tcpcopy needs -s paramter(intercept addresses)\n");
        return -1;
    }

#if (TC_PLUGIN)
    /* support only one additional module*/
    clt_settings.plugin = tc_modules[0];
#endif

    if (read_conf_file() != TC_OK) {
        return -1;
    }


    if (clt_settings.do_daemonize) {
        /* ignore
        if (sigignore(SIGHUP) == -1) {
            tc_log_info(LOG_ERR, errno, "Failed to ignore SIGHUP");
        }
        if (daemonize() == -1) {
            fprintf(stderr, "failed to daemonize() in order to daemonize\n");
            return -1;
        }
        */
    }

    return 0;
}
コード例 #18
0
int main (int argc, char **argv) {
  std::string brokers = "localhost";
  std::string errstr;
  std::vector<std::string> topics;
  std::string conf_file;
  std::string mode = "P";
  int throughput = 0;
  int32_t partition = RdKafka::Topic::PARTITION_UA;
  bool do_conf_dump = false;
  MyHashPartitionerCb hash_partitioner;

  /*
   * Create configuration objects
   */
  RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
  RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);

  {
    char hostname[128];
    gethostname(hostname, sizeof(hostname)-1);
    conf->set("client.id", std::string("rdkafka@") + hostname, errstr);
  }

  conf->set("debug", "cgrp,topic", errstr);

  for (int i = 1 ; i < argc ; i++) {
    const char *name = argv[i];
    const char *val = i+1 < argc ? argv[i+1] : NULL;

    if (val && !strncmp(val, "--", 2))
      val = NULL;

    std::cout << now() << ": argument: " << name << " " <<
        (val?val:"") << std::endl;
    
    if (val) {
      if (!strcmp(name, "--topic"))
	topics.push_back(val);
      else if (!strcmp(name, "--broker-list"))
	brokers = val;
      else if (!strcmp(name, "--max-messages"))
	state.maxMessages = atoi(val);
      else if (!strcmp(name, "--throughput"))
	throughput = atoi(val);
      else if (!strcmp(name, "--producer.config") ||
	       !strcmp(name, "--consumer.config"))
	read_conf_file(val);
      else if (!strcmp(name, "--group-id"))
	conf->set("group.id", val, errstr);
      else if (!strcmp(name, "--session-timeout"))
	conf->set("session.timeout.ms", val, errstr);
      else if (!strcmp(name, "--reset-policy")) {
	if (tconf->set("auto.offset.reset", val, errstr)) {
	  std::cerr << now() << ": " << errstr << std::endl;
	  exit(1);
	}
      } else if (!strcmp(name, "--debug")) {
	conf->set("debug", val, errstr);
      } else {
	std::cerr << now() << ": Unknown option " << name << std::endl;
	exit(1);
      }

      i++;

    } else {
      if (!strcmp(name, "--consumer"))
	mode = "C";
      else if (!strcmp(name, "--producer"))
	mode = "P";
      else if (!strcmp(name, "--enable-autocommit")) {
	state.consumer.useAutoCommit = true;
	conf->set("enable.auto.commit", "true", errstr);
      } else {
	std::cerr << now() << ": Unknown option or missing argument to " << name << std::endl;
	exit(1);
      }
    }
  }

  if (topics.empty() || brokers.empty()) {
    std::cerr << now() << ": Missing --topic and --broker-list" << std::endl;
    exit(1);
  }


  /*
   * Set configuration properties
   */
  conf->set("metadata.broker.list", brokers, errstr);

  ExampleEventCb ex_event_cb;
  conf->set("event_cb", &ex_event_cb, errstr);

  if (do_conf_dump) {
    int pass;

    for (pass = 0 ; pass < 2 ; pass++) {
      std::list<std::string> *dump;
      if (pass == 0) {
        dump = conf->dump();
        std::cerr << now() << ": # Global config" << std::endl;
      } else {
        dump = tconf->dump();
        std::cerr << now() << ": # Topic config" << std::endl;
      }

      for (std::list<std::string>::iterator it = dump->begin();
           it != dump->end(); ) {
        std::cerr << *it << " = ";
        it++;
        std::cerr << *it << std::endl;
        it++;
      }
      std::cerr << std::endl;
    }
    exit(0);
  }

  signal(SIGINT, sigterm);
  signal(SIGTERM, sigterm);
  signal(SIGALRM,  sigwatchdog);


  if (mode == "P") {
    /*
     * Producer mode
     */

    ExampleDeliveryReportCb ex_dr_cb;

    /* Set delivery report callback */
    conf->set("dr_cb", &ex_dr_cb, errstr);

    /*
     * Create producer using accumulated global configuration.
     */
    RdKafka::Producer *producer = RdKafka::Producer::create(conf, errstr);
    if (!producer) {
      std::cerr << now() << ": Failed to create producer: " << errstr << std::endl;
      exit(1);
    }

    std::cerr << now() << ": % Created producer " << producer->name() << std::endl;

    /*
     * Create topic handle.
     */
    RdKafka::Topic *topic = RdKafka::Topic::create(producer, topics[0],
						   tconf, errstr);
    if (!topic) {
      std::cerr << now() << ": Failed to create topic: " << errstr << std::endl;
      exit(1);
    }

    static const int delay_us = throughput ? 1000000/throughput : 0;

    if (state.maxMessages == -1)
      state.maxMessages = 1000000; /* Avoid infinite produce */

    for (int i = 0 ; run && i < state.maxMessages ; i++) {
      /*
       * Produce message
       */
      std::ostringstream msg;
      msg << i;
      RdKafka::ErrorCode resp =
	producer->produce(topic, partition,
			  RdKafka::Producer::RK_MSG_COPY /* Copy payload */,
			  const_cast<char *>(msg.str().c_str()),
			  msg.str().size(), NULL, NULL);
      if (resp != RdKafka::ERR_NO_ERROR) {
	errorString("producer_send_error",
		    RdKafka::err2str(resp), topic->name(), NULL, msg.str());
	state.producer.numErr++;
      } else {
	std::cerr << now() << ": % Produced message (" <<
	  msg.str().size() << " bytes)" << std::endl;
	state.producer.numSent++;
      }

      producer->poll(delay_us / 1000);
      watchdog_kick();
    }
    run = true;

    while (run && producer->outq_len() > 0) {
      std::cerr << now() << ": Waiting for " << producer->outq_len() << std::endl;
      producer->poll(50);
      watchdog_kick();
    }

    std::cerr << now() << ": " << state.producer.numAcked << "/" <<
      state.producer.numSent << "/" << state.maxMessages <<
      " msgs acked/sent/max, " << state.producer.numErr <<
      " errored" << std::endl;

    delete topic;
    delete producer;


  } else if (mode == "C") {
    /*
     * Consumer mode
     */

    tconf->set("auto.offset.reset", "smallest", errstr);

    /* Set default topic config */
    conf->set("default_topic_conf", tconf, errstr);

    ExampleRebalanceCb ex_rebalance_cb;
    conf->set("rebalance_cb", &ex_rebalance_cb, errstr);

    ExampleOffsetCommitCb ex_offset_commit_cb;
    conf->set("offset_commit_cb", &ex_offset_commit_cb, errstr);


    /*
     * Create consumer using accumulated global configuration.
     */
    consumer = RdKafka::KafkaConsumer::create(conf, errstr);
    if (!consumer) {
      std::cerr << now() << ": Failed to create consumer: " <<
	errstr << std::endl;
      exit(1);
    }

    std::cerr << now() << ": % Created consumer " << consumer->name() <<
      std::endl;

    /*
     * Subscribe to topic(s)
     */
    RdKafka::ErrorCode resp = consumer->subscribe(topics);
    if (resp != RdKafka::ERR_NO_ERROR) {
      std::cerr << now() << ": Failed to subscribe to " << topics.size() << " topics: "
		<< RdKafka::err2str(resp) << std::endl;
      exit(1);
    }

    /*
     * Consume messages
     */
    while (run) {
      RdKafka::Message *msg = consumer->consume(500);
      msg_consume(consumer, msg, NULL);
      delete msg;
      watchdog_kick();
    }

    /* Final commit */
    do_commit(consumer, 1);

    /*
     * Stop consumer
     */
    consumer->close();

    delete consumer;
  }


  /*
   * Wait for RdKafka to decommission.
   * This is not strictly needed (when check outq_len() above), but
   * allows RdKafka to clean up all its resources before the application
   * exits so that memory profilers such as valgrind wont complain about
   * memory leaks.
   */
  RdKafka::wait_destroyed(5000);

  std::cerr << now() << ": EXITING WITH RETURN VALUE 0" << std::endl;
  return 0;
}
コード例 #19
0
ファイル: abw.c プロジェクト: helios66/loss_estimate
int main(int argc, char *argv[])
{ 
	configuration_t configuration;
	int i, j;
	struct timeval tm;
	struct timezone tz;
	measurement_t *measurement;
	struct timeval next, wait;
	int subject_id, flow_id;
	unsigned long long packets, bytes;
	double mbps;
	char command[MAX_COMMAND+1];
	char hostname_interface[MAX_HOSTNAME_INTERFACE+1];	/* DiMAPI connect string
															   as "hostname:interface,..." */

	struct timeval tv_start, tv_stop;	/* to measure how fast mapi_read_result()
														responds */
	int tv_diff_pkt, tv_diff_byte;		/* time used by mapi_read_results() */
	int tv_diff_threshold;		/* 1 if threshold was reached */
	mapi_results_t *pkt_counter_res;
	mapi_results_t *byte_counter_res;
	unsigned long long pkt_counter;
	unsigned long long byte_counter;
	int scope_size;
	double pkt_sec;	/* seconds from previous packet result */
	double byte_sec;	/* seconds from previous byte result */
   mapi_flow_info_t info;
   mapi_device_info_t dinfo;

	openlog("abw", LOG_PID, LOG_LOCAL0);
	syslog(LOG_DEBUG, "starting abw");

	memset((void *)&configuration, 0, (size_t)(sizeof(configuration)));

	/* Create global configuration */
	if ((configuration.global=malloc(sizeof(global_t)))==NULL) {
		fprintf(stderr, "%s: malloc() failed\n", __func__);
		return -1;
	}
	memset(configuration.global, 0, sizeof(global_t));

	/* Create first subject, scope, parameters and measurement so that they
      can be filled-in by command-line options */

	/* if ((configuration.subject=new_subject())==NULL) {
      fprintf(stderr, "%s: new_subject() failed\n", __func__);
      return -1;
	}
	if ((configuration.scope=new_scope())==NULL) {
      fprintf(stderr, "%s: new_subject() failed\n", __func__);
      return -1;
	}
	if ((configuration.parameters=new_parameters())==NULL) {
      fprintf(stderr, "%s: new_parameters() failed\n", __func__);
      return -1;
	}

	if ((configuration.measurement=new_measurement())==NULL) {
      fprintf(stderr, "%s: new_measurement() failed\n", __func__);
      return -1;
	} */

	/* Read command line */

	if (read_command_line(argc, argv, &configuration)<0) {
		fprintf(stderr, "%s: read_command_line() failed\n", __func__);
		return -1;
	}

	/* Read configuration file */

	if (configuration.global->conf_filename) {
		if (read_conf_file(&configuration)<0) {
			fprintf(stderr, "%s: read_conf_file() failed\n", __func__);
			return -1;
		}
	}

	/* Fill-in local hostname */

	if (get_local_hostname(&(configuration.global->hostname))<0) {
		fprintf(stderr, "%s: get_local_hostname() failed\n", __func__);
		return -1;
	}

	/* Check if specified values are within acceptable limits */

	if (check_conf(&configuration)<0) {
      fprintf(stderr, "%s: check_conf() failed\n", __func__);
      exit(-1);
	}

	/* Print configuration */

	if (debug)
		print_conf(&configuration);

	if (daemonize) {
		printf("Switching to daemon\n");
		if (continue_as_daemon()<0) {
			fprintf(stderr, "%s: continue_as_daemon() failed\n", __func__);
			return -1;
		}
		printf("Continuing as daemon\n");
	}

	/* 
	 * Create RRD files 
	 */

	/* Go over all measurements */

	measurement=configuration.measurement;
   while (measurement) {

		int parameters_id;
		char *filename;

		parameters_id = measurement->parameters_id;

		/* Go over all protocols */

		j=0;
		while (protocols[j].protocol) {
			if ((filename=
				abw_rrd_create_filename(measurement->scope, 
					parameters_id, protocols[j].protocol))==NULL) {
				fprintf(stderr, "%s: rrd_create_filename() failed\n", 
					__func__);
				return -1;
			}

			if (abw_rrd_create_file(filename)<0) {
				fprintf(stderr, "%s: abw_rrd_create_file() failed\n", __func__);
				return -1;
			}

			j++;
		} /* Go over all protocols */

		/* Go over all tracked protocols */

		j=0;
		while (tracked_protocols[j].protocol) {
			if ((filename=
				abw_rrd_create_filename(measurement->scope, 
					parameters_id, tracked_protocols[j].protocol))==NULL) {
				fprintf(stderr, "%s: rrd_create_filename() failed\n", 
					__func__);
				return -1;
			}

			if (abw_rrd_create_file(filename)<0) {
				fprintf(stderr, "%s: abw_rrd_create_file() failed\n", __func__);
				return -1;
			}

			j++;
		} /* Go over all tracked protocols */

		/* Create RRD file for "all" protocol (all traffic together) */

		if ((filename=
			abw_rrd_create_filename(measurement->scope, 
				parameters_id, "all"))==NULL) {
				fprintf(stderr, "%s: rrd_create_filename() failed\n", 
					__func__);
				return -1;
		}

		if (abw_rrd_create_file(filename)<0) {
			fprintf(stderr, "%s: abw_rrd_create_file() failed\n", __func__);
			return -1;
		}

		measurement=measurement->next;

   } /* while (measurement) */

	/* 
	 * Create MAPI flows 
	 */

	flow_id=0;

	/* Go over all measurements */

	measurement=configuration.measurement;
   while (measurement) {

		/* Go over all monitored protocols */

		i=0;
		while (measurement->protocols_array[i] && i<MAX_PROTOCOLS) {

			int parameters_id;
			char *protocol;

			/* Create data structure to maintain MAPI information */

			if (flow_id>=MAX_FLOWS) {
				fprintf(stderr, "%s: more than %d flows requested\n", __func__,
					MAX_FLOWS);
				return -1;
			}

			if ((flow[flow_id]=new_flow())==NULL) {
  				fprintf(stderr, "%s: new_flow() failed\n", __func__);
  				return -1;
  			}
			flow[flow_id]->measurement=measurement;
			flow[flow_id]->protocol=measurement->protocols_array[i];

			parameters_id = measurement->parameters_id;
			protocol = measurement->protocols_array[i];
				
			if ((flow[flow_id]->rrd_filename=
				abw_rrd_create_filename(measurement->scope, 
					parameters_id, protocol))==NULL) {
				fprintf(stderr, "%s: rrd_create_filename() failed\n", 
					__func__);
				return -1;
			}

			/* 
			 * If scope has only one subject and if hostname is "localhost" or
			 * equal to local hostname, then use MAPI connect string (not DiMAPI)
			 */

			if (!(measurement->scope->subject[1]) && 
				 (!strcmp(measurement->scope->subject[0]->hostname, "localhost") ||
				  !strcmp(measurement->scope->subject[0]->hostname, 
				  		configuration.global->hostname)))

				strcpy(hostname_interface, 
					measurement->scope->subject[0]->interface);

			/* 
			 * Prepare DiMAPI connect string as hostname:interface, ... 
			 */

			else {
				
				j=0; hostname_interface[0]='\0';
      		while (measurement->scope->subject[j] && j<MAX_SUBJECTS) {

					/* Append comma "," */

					if (hostname_interface[0]) {
						if (strlen(hostname_interface)+1>=MAX_HOSTNAME_INTERFACE) {
							fprintf(stderr, "%s: DiMAPI connect string is longer than %d characters\n", __func__, MAX_HOSTNAME_INTERFACE);
							return -1;
						}
						strcat(hostname_interface, ",");
					}

					/* Append next hostname:interface */
					if (strlen(hostname_interface) +
						 strlen(measurement->scope->subject[j]->hostname) +
				 		strlen(measurement->scope->subject[j]->interface) 
							>= MAX_HOSTNAME_INTERFACE) {
         			fprintf(stderr, "%s: DiMAPI connect string is longer than %d characters\n", __func__, MAX_HOSTNAME_INTERFACE);
            		return -1;
         		}
					sprintf(hostname_interface + strlen(hostname_interface), "%s:%s",
						measurement->scope->subject[j]->hostname,
						measurement->scope->subject[j]->interface);
			
					j++;
				} /* while (measurement->scope->subject[j] && j<MAX_SUBJECTS) */

			} /* Creating DiMAPI connect string */

			/* Create a new MAPI flow */

			if (debug)
				printf("%s: mapi_create_flow(%s)\n", __func__, hostname_interface);

  			if ((flow[flow_id]->fd=mapi_create_flow(hostname_interface))<0) {
				fprintf(stderr, "%s: mapi_create_flow(%s) failed\n", __func__,
					hostname_interface);
				fprintf(stderr, "%s: Do you run mapid daemon on the machine where you connect to?\n", __func__);
				fprintf(stderr, "%s: Do you run mapicommd daemon on the machine where you connect to? (if you are connecting to a non-local machine or to multiple machines)\n", __func__);
					return -1;
			}

         /* If this is a MAPI flow (not DiMAPI flow), then set MPLS and VLAN 
				flags according to mapi.conf. Otherwise the flags were set in
				abw.conf */

			if (!strchr(hostname_interface, ':')) {

				if (debug)
					printf("%s: MAPI flow on \"%s\", setting MPLS and VLAN flags from mapi.conf\n", __func__, hostname_interface);

         	if ((mapi_get_flow_info(flow[flow_id]->fd, &info)) < 0){
            	fprintf(stderr, "%s: mapi_get_flow_info() failed\n", __func__);
            	return -1;
         	}

         	if ((mapi_get_device_info(info.devid, &dinfo)) < 0) {
            	fprintf(stderr, "%s: mapi_get_device_info() failed\n", __func__);
            	return -1;
         	}

         	measurement->scope->mpls = dinfo.mpls;
         	measurement->scope->vlan = dinfo.vlan;

			}
			else
				if (debug)
               printf("%s: DiMAPI flow on \"%s\", setting MPLS and VLAN flags from abw.conf\n", __func__, hostname_interface);

			/* Prepare header filter for this protocol */

			if ((flow[flow_id]->tracked_protocol=
				protocol_filter(measurement->parameters->header_filter, 
					flow[flow_id]->protocol, measurement->scope->mpls, 
					measurement->scope->vlan,
					&(flow[flow_id]->header_filter)))<0) {
				fprintf(stderr, "%s: protocol_filter() failed\n", __func__);
				return -1;
			}

			if (debug)
				printf("measurement->parameters->header_filter: %s, flow[flow_id]->protocol: %s, flow[flow_id]->header_filter: %s, track_function: %s\n", (measurement->parameters->header_filter)?measurement->parameters->header_filter:"NULL", flow[flow_id]->protocol, (flow[flow_id]->header_filter)?flow[flow_id]->header_filter:"NULL", (flow[flow_id]->tracked_protocol)?tracked_protocols[flow[flow_id]->tracked_protocol-1].track_function:"none");

			/* Filter based on input port, we can use port number in the first 
				subject of the scope, because all subjects in a scope must have
				the same port number */

			if (measurement->scope->subject[0]->port >= 0) {
				if ((flow[flow_id]->interface_fid=mapi_apply_function(flow[flow_id]->fd, "INTERFACE", measurement->scope->subject[0]->port))<0) {
					fprintf(stderr, "%s: INTERFACE failed\n", __func__);
               return -1;
            }
			}

			/* Note that BPF_FILTER uses compiled header filter that
				selects packets of the given protocol */

			/* BPF_FILTER is applied if a) header_filter was specified in
				[parameters] section or b) protocol other than "all" and other than
				some that requires tracking was specified in [parameters] section or
				c) MPLS is used on links in this [scope] */

			if (flow[flow_id]->header_filter) {
				if (debug)
					printf("%s: mapi_apply_function(%d, BPF_FILTER, \"%s\")\n",
						__func__, flow[flow_id]->fd, flow[flow_id]->header_filter);
				if ((flow[flow_id]->bpf_filter_fid=
					mapi_apply_function(flow[flow_id]->fd, "BPF_FILTER", 
						flow[flow_id]->header_filter))<0) {
						fprintf(stderr, "%s: BPF_FILTER (\"%s\") failed\n", 
							__func__, flow[flow_id]->header_filter);
						return -1;
				}
			}

			/* Track application protocol, BPF_FILTER could have been applied 
				before */

			if (flow[flow_id]->tracked_protocol) {
				if (debug)
					printf("%s: mapi_apply_function(%d, %s)\n", __func__, 
						flow[flow_id]->fd,
						tracked_protocols[flow[flow_id]->tracked_protocol-1].
							track_function);
				if ((flow[flow_id]->track_function_fid=
					mapi_apply_function(flow[flow_id]->fd, 
						tracked_protocols[flow[flow_id]->tracked_protocol-1].
							track_function))<0) {
					fprintf(stderr, "%s: tracking (%s) failed\n", __func__, 
						tracked_protocols[flow[flow_id]->tracked_protocol-1].
							track_function);
					return -1;
				}
			}

			/* Sampling */

			if (measurement->parameters->sau_mode == 'd' && 
				 (unsigned int)(measurement->parameters->sau_threshold) != 1) {
				if ((flow[flow_id]->sample_fid=
					mapi_apply_function(flow[flow_id]->fd, "SAMPLE", 
						measurement->parameters->sau_threshold, PERIODIC))<0) {
					fprintf(stderr, "%s: SAMPLE (PERIODIC, %.02f) failed\n",
						__func__, measurement->parameters->sau_threshold);
					return -1;
				}
			}
			else if (measurement->parameters->sau_mode == 'p' && 
						(unsigned int)(measurement->parameters->sau_threshold) != 1) {
				if ((flow[flow_id]->sample_fid=
        			mapi_apply_function(flow[flow_id]->fd, "SAMPLE", 
						(measurement->parameters->sau_threshold)*100,
						PROBABILISTIC))<0) {
        			fprintf(stderr, "%s: SAMPLE (PROBABILISTIC, %.02f) failed\n", 
						__func__, (measurement->parameters->sau_threshold)*100);
        			return -1;
      		}
			}
	
			/* Payload searching */
	
			if (measurement->parameters->payload_strings[0]) {
				if ((flow[flow_id]->str_search_fid=
        			mapi_apply_function(flow[flow_id]->fd, "STR_SEARCH", 
					measurement->parameters->payload_strings[0], 0, 0))<0) {
           			fprintf(stderr, "%s: STR_SEARCH (%s) failed\n", 
						__func__, measurement->parameters->payload_strings[0]);
        	   		return -1;
       		}
			}

			/* Counting packets and bytes */

			if ((flow[flow_id]->pkt_counter_fid=
        		mapi_apply_function(flow[flow_id]->fd, "PKT_COUNTER"))<0) {
           		fprintf(stderr, "%s: PKT_COUNTER failed\n", __func__);
        		return -1;
  			}

			/* Simultaneous use of PKT_COUNTER and BYTE_COUNTER does not
				work with DAG4.3GE. Temporary hack: always use stflib version */

			if ((flow[flow_id]->byte_counter_fid=
        		mapi_apply_function(flow[flow_id]->fd, "stdflib:BYTE_COUNTER"))<0) {
           		fprintf(stderr, "%s: BYTE_COUNTER failed\n", 
				__func__);
        		return -1;
  			}

			/* Connect to flow */

			if (!configuration.global->no_measure) {
				if (mapi_connect(flow[flow_id]->fd)<0) {
					fprintf(stderr, "%s: mapi_connect() (%s) failed\n", 
						__func__, hostname_interface);
					return -1;
				}

				if ((scope_size=mapi_get_scope_size(flow[flow_id]->fd)) != 
					flow[flow_id]->measurement->scope->subject_no) {
					fprintf(stderr, "%s: mapi_get_scope_size() returned %d for %d subjects\n", __func__, scope_size, flow[flow_id]->measurement->scope->subject_no);
					return -1;
				}
			}

			i++;
			flow_id++;

		} /* while (measurement->protocols_array[i] && i<MAX_PROTOCOLS) */

		measurement=measurement->next;

	} /* while (measurement) */

	if (configuration.global->no_measure || !configuration.measurement)
		return 0;

	/* Periodically get results from MAPI flows */

	while (1) {
		if (gettimeofday(&tm, &tz)<0) {
			fprintf(stderr, "%s: gettimeofday() failed\n", __func__);
			return -1;
		}

		flow_id=0;
		while (flow[flow_id] && flow_id<MAX_FLOWS) {

			int scope_packets, scope_bytes;
	
			if (!configuration.global->no_stdout) {
				printf("%d %u.%u", flow[flow_id]->measurement->scope->id, 
					(unsigned int)(tm.tv_sec), 
					(unsigned int)(tm.tv_usec));
				if (!configuration.global->stdout_simple)
					printf(" %s\n", flow[flow_id]->protocol);
			}

			gettimeofday(&tv_start, NULL);
			if ((pkt_counter_res=mapi_read_results(flow[flow_id]->fd, 
				flow[flow_id]->pkt_counter_fid))==NULL) {
					fprintf(stderr, "%s: mapi_read_results() for flow %d failed\n",
						__func__, flow_id);
			 	return -1;
			}

			gettimeofday(&tv_stop, NULL);
			tv_diff_pkt=timestamp_diff(&tv_start, &tv_stop);

			gettimeofday(&tv_start, NULL);
			if ((byte_counter_res=mapi_read_results(flow[flow_id]->fd, 
				flow[flow_id]->byte_counter_fid))==NULL) {
        			fprintf(stderr, "%s: mapi_read_results() for flow %d failed\n",
             		__func__, flow_id);
          		return -1;
     		}
			gettimeofday(&tv_stop, NULL);
			tv_diff_byte=timestamp_diff(&tv_start, &tv_stop);

			if (tv_diff_pkt>=TV_DIFF_THRESHOLD ||
				 tv_diff_byte>=TV_DIFF_THRESHOLD)
				tv_diff_threshold=1;
			else
				tv_diff_threshold=0;

			if (tv_diff_pkt>=TV_DIFF_THRESHOLD)
				syslog(LOG_DEBUG, "mapi_read_result() for PKT_COUNTER takes %d us for measurement ID %d and protocol %s (threshold %d us reached)", tv_diff_pkt, flow[flow_id]->measurement->id, flow[flow_id]->protocol, TV_DIFF_THRESHOLD);
			if (tv_diff_byte>=TV_DIFF_THRESHOLD)
				syslog(LOG_DEBUG, "mapi_read_result() for BYTE_COUNTER takes %d us for measurement ID %d and protocol %s (threshold %d us reached)", tv_diff_byte, flow[flow_id]->measurement->id, flow[flow_id]->protocol, TV_DIFF_THRESHOLD);

			scope_size = flow[flow_id]->measurement->scope->subject_no;

			scope_packets=0;
			scope_bytes=0;

			for (subject_id=0; subject_id<scope_size; subject_id++) {
	
				pkt_counter=
					*((unsigned long long*)(pkt_counter_res[subject_id].res));
				byte_counter=
					*((unsigned long long*)(byte_counter_res[subject_id].res));

				packets=pkt_counter - flow[flow_id]->pkt_counter[subject_id];
				bytes=byte_counter - flow[flow_id]->byte_counter[subject_id];
				mbps=(double)bytes*8/1000000;

				flow[flow_id]->pkt_counter[subject_id]=pkt_counter;
				flow[flow_id]->byte_counter[subject_id]=byte_counter;

				/* Determine seconds from previous result */

				if (flow[flow_id]->pkt_ts[subject_id])
					pkt_sec=(double)(pkt_counter_res[subject_id].ts -
								flow[flow_id]->pkt_ts[subject_id])/1000000;
				else
					pkt_sec=
						flow[flow_id]->measurement->parameters->interval.tv_sec +
	               (double)(flow[flow_id]->measurement->parameters->interval.tv_usec)/1000000;
		
				if (flow[flow_id]->byte_ts[subject_id])
					byte_sec=(double)(byte_counter_res[subject_id].ts -
						flow[flow_id]->byte_ts[subject_id])/1000000;
				else
					byte_sec=
						flow[flow_id]->measurement->parameters->interval.tv_sec +
	               (double)(flow[flow_id]->measurement->parameters->interval.tv_usec)/1000000;

				scope_packets+=(packets/pkt_sec);
				scope_bytes+=(bytes/byte_sec);

				flow[flow_id]->pkt_ts[subject_id]=
					pkt_counter_res[subject_id].ts;
				flow[flow_id]->byte_ts[subject_id]=
					byte_counter_res[subject_id].ts;

				if (tv_diff_threshold) {
					syslog(LOG_DEBUG, "%s:%s: %.02f seconds from previous result",
						flow[flow_id]->measurement->scope->subject[subject_id]->hostname,
						flow[flow_id]->measurement->scope->subject[subject_id]->interface,
						byte_sec);
				}

				/* Print result */

				if (!configuration.global->no_stdout) {
					if (configuration.global->stdout_simple)
						printf(" %0.2f %0.2f %0.2f", packets/pkt_sec, 
							bytes/byte_sec, mbps/byte_sec);
					else
							printf(" %0.2f packets/s, %0.2f bytes/s, %0.2f Mb/s, time %uus/%uus, interval %0.2fs/%0.2fs\n", 
								packets/pkt_sec, bytes/byte_sec, mbps/byte_sec, 
								tv_diff_pkt, tv_diff_byte, pkt_sec, byte_sec);
				}

			} /* for (subject_id=0; subject_id++; subject_id<scope_size) */

			if (!configuration.global->no_stdout)
				printf("\n");

			/* If interval is at least 1 second, then store results 
			   to RRD file */
				
			if (flow[flow_id]->measurement->parameters->interval.tv_sec) {
				sprintf(command, "rrdtool update %s %u:%lu:%lu:%.6f", 
					 flow[flow_id]->rrd_filename, 
					 (unsigned int)(tm.tv_sec), 
					 (unsigned long)(scope_packets), 
					 (unsigned long)(scope_bytes), 
					 (double)scope_bytes*8/1000000);

				if (configuration.global->debug > 1)
					syslog(LOG_DEBUG, "system(%s)", command);

				if (tm.tv_sec == flow[flow_id]->rrd_ts)
					syslog(LOG_ERR, "duplicate RRD timestamp %u for scope %d\n", (unsigned int)(tm.tv_sec), flow[flow_id]->measurement->scope->id);
				else
					flow[flow_id]->rrd_ts=tm.tv_sec;

				if (debug)
					printf("%s: system(%s)\n", __func__, command);

				if (system(command)<0) {
					fprintf(stderr, "%s: command(%s) failed\n", __func__,
						command);
					return -1;
				}
			}

			flow_id++;

		} /* while (flow[flow_id] && flow_id<MAX_FLOWS) */

		abw_next_timestamp(&(configuration.measurement->parameters->interval), 
			&next, &wait);

		if (!configuration.global->no_stdout && 
			 !configuration.global->stdout_simple) {
     		printf("next.tv_sec: %d, next.tv_usec: %d, wait.tv_sec: %d, wait.tv_usec: %d\n", (int)(next.tv_sec), (int)(next.tv_usec), (int)(wait.tv_sec), (int)(wait.tv_usec));
			printf("===============================================================================\n");
		}

     	usleep(wait.tv_sec * 1000000 + wait.tv_usec);
		 
	} /* while (1) */

	return 0;
} /* main() */
コード例 #20
0
ファイル: tcsd_conf.c プロジェクト: ajinkya93/netbsd-src
TSS_RESULT
conf_file_init(struct tcsd_config *conf)
{
	FILE *f = NULL;
	struct stat stat_buf;
#ifndef SOLARIS
	struct group *grp;
	struct passwd *pw;
	mode_t mode = (S_IRUSR|S_IWUSR);
#endif /* SOLARIS */
	TSS_RESULT result;

	init_tcsd_config(conf);

#ifdef SOLARIS
       /*
	* Solaris runs as Rajiv Andrade <[email protected].:sys but with reduced privileges
	* so we don't need to create a new user/group and also so
	* we can have auditing support.  The permissions on
	* the tcsd configuration file are not checked on Solaris.
	*/
#endif
	/* look for a config file, create if it doesn't exist */
	if (stat(tcsd_config_file, &stat_buf) == -1) {
		if (errno == ENOENT) {
			/* no config file? use defaults */
			config_set_defaults(conf);
			LogInfo("Config file %s not found, using defaults.", tcsd_config_file);
			return TSS_SUCCESS;
		} else {
			LogError("stat(%s): %s", tcsd_config_file, strerror(errno));
			return TCSERR(TSS_E_INTERNAL_ERROR);
		}
	}

#ifndef SOLARIS
	/* find the gid that owns the conf file */
	errno = 0;
	grp = getgrnam(TSS_GROUP_NAME);
	if (grp == NULL) {
		if (errno == 0) {
			LogError("Group \"%s\" not found, please add this group"
					" manually.", TSS_GROUP_NAME);
		} else {
			LogError("getgrnam(%s): %s", TSS_GROUP_NAME, strerror(errno));
		}
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	errno = 0;
	pw = getpwnam(TSS_USER_NAME);
	if (pw == NULL) {
		if (errno == 0) {
			LogError("User \"%s\" not found, please add this user"
					" manually.", TSS_USER_NAME);
		} else {
			LogError("getpwnam(%s): %s", TSS_USER_NAME, strerror(errno));
		}
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	/* make sure user/group TSS owns the conf file */
	if (pw->pw_uid != stat_buf.st_uid || grp->gr_gid != stat_buf.st_gid) {
		LogError("TCSD config file (%s) must be user/group %s/%s", tcsd_config_file,
				TSS_USER_NAME, TSS_GROUP_NAME);
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	/* make sure only the tss user can manipulate the config file */
	if (((stat_buf.st_mode & 0777) ^ mode) != 0) {
		LogError("TCSD config file (%s) must be mode 0600", tcsd_config_file);
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}
#endif /* SOLARIS */

	if ((f = fopen(tcsd_config_file, "r")) == NULL) {
		LogError("fopen(%s): %s", tcsd_config_file, strerror(errno));
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	result = read_conf_file(f, conf);
	fclose(f);

	/* fill out any uninitialized options */
	config_set_defaults(conf);

#ifdef SOLARIS
	/*
	* The SMF value for "local_only" overrides the config file and
	* disables all remote operations.
	*/
if (get_smf_prop("local_only", B_TRUE)) {
		(void) memset(conf->remote_ops, 0, sizeof(conf->remote_ops));
		conf->unset |= TCSD_OPTION_REMOTE_OPS;
	
	}
#endif
	return result;
}
コード例 #21
0
ファイル: cli.c プロジェクト: aguynamedryan/fsqlf
void read_cli_options(int argc, char **argv,
                        struct kw_conf * (*kw)(const char *), FILE ** fin, FILE ** fout)
{
    int i;
    if (argc == 1) return; // use stdin and stdout

    if (argc == 2 && strcmp(argv[1], "--create-config-file") == 0) {
        if (create_conf_file(FSQLF_CONFFILE_NAME) != 0) {
            exit(1);
        } else {
            fprintf(stderr, "File '%s' (re)created.\n", FSQLF_CONFFILE_NAME);
            exit(0);
        }
    }

    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-') {
            if ((*fin) == stdin) {
                //try to openinig INPUT file
                (*fin) = fopen(argv[1], "r");
                if (!(*fin)) {
                    FAIL_WITH_ERROR(1, "Error opening input file: %s", argv[i]);
                }
            }
            else if ((*fout) == stdout) {   //try to openinig OUTPUT file (only if INPUT file is set)
                (*fout) = fopen(argv[2], "w+");
                if (!(*fout)) FAIL_WITH_ERROR(1, "Error opening output file: %s", argv[i]);
            }
        } else if (ARGV_MATCH(i, "-i")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            (*fin) = fopen(argv[i], "r");
            if (!(*fin)) FAIL_WITH_ERROR(1, "Error opening input file: %s", argv[i]);
        } else if (ARGV_MATCH(i, "-o")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            (*fout) = fopen(argv[i], "w+");
            if (!(*fout)) FAIL_WITH_ERROR(1, "Error opening output file: %s", argv[i]);
        } else if (ARGV_MATCH(i, "--config-file")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (read_conf_file(argv[i], kw) == READ_FAILED) {
                FAIL_WITH_ERROR(1, "Error reading configuration file: %s", argv[i]);
            }
        } else if (ARGV_MATCH(i, "--select-comma-newline")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (strcmp(argv[i], "after") == 0) {
                kw("kw_comma")->before.new_line = 0;
                kw("kw_comma")->after.new_line  = 1;
            } else if (strcmp(argv[i], "before") == 0) {
                kw("kw_comma")->before.new_line = 1;
                kw("kw_comma")->after.new_line  = 0;
            } else if (strcmp(argv[i], "none") == 0) {
                kw("kw_comma")->before.new_line = 0;
                kw("kw_comma")->after.new_line  = 0;
            }
        } else if (ARGV_MATCH(i, "--keyword-case")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (strcmp(argv[i], "none") == 0) {
                set_case(CASE_none);
            } else if (strcmp(argv[i], "upper") == 0) {
                set_case(CASE_UPPER);
            } else if (strcmp(argv[i], "lower") == 0) {
                set_case(CASE_lower);
            } else if (strcmp(argv[i], "initcap") == 0) {
                set_case(CASE_Initcap);
            }
        } else if (ARGV_MATCH(i, "--keyword-text")) {
            if (++i >= argc) FAIL_WITH_ERROR(1, "Missing value for option : %s", argv[i-1]);
            if (strcmp(argv[i], "original") == 0) {
                set_text_original(1);
            } else if (strcmp(argv[i], "default") == 0) {
                set_text_original(0);
            }
        } else if (ARGV_MATCH(i, "--select-newline-after")) {
            kw("kw_select")->after.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-or-before")) {
            kw("kw_or")->before.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-or-after")) {
            kw("kw_or")->after.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-and-before")) {
            kw("kw_and")->before.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-and-after")) {
            kw("kw_and")->after.new_line = get_int_arg(++i, argc, argv);
        } else if (ARGV_MATCH(i, "--newline-major-sections")) {
            int new_line_count = get_int_arg(++i, argc, argv);
            kw("kw_from")->before.new_line = new_line_count;
            kw("kw_where")->before.new_line = new_line_count;
            kw("kw_inner_join")->before.new_line = new_line_count;
            kw("kw_left_join")->before.new_line  = new_line_count;
            kw("kw_right_join")->before.new_line = new_line_count;
            kw("kw_full_join")->before.new_line  = new_line_count;
            kw("kw_cross_join")->before.new_line = new_line_count;
        } else if (ARGV_MATCH(i, "--debug")) {
            if (++i >= argc ) FAIL_WITH_ERROR(1, "Missing or invalid value for option : %s", argv[i-1]);
            if (ARGV_MATCH(i, "none")) debug_level |= DEBUGNONE;
            else if (ARGV_MATCH(i, "state")) debug_level |= DEBUGSTATES;
            else if (ARGV_MATCH(i, "match")) debug_level |= DEBUGMATCHES;
            else if (ARGV_MATCH(i, "parenthesis")) debug_level |= DEBUGPARCOUNTS;
            else FAIL_WITH_ERROR(1, "Missing or invalid value for option : %s", argv[i-1]);
        } else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
            usage_info(argc, argv);
            exit(0);
        } else FAIL_WITH_ERROR(1, "Option `%s' is not recognised or used incorrectly.\nTry `%s --help' for more information\n", argv[i], argv[0]);
    }
}
コード例 #22
0
ファイル: main.c プロジェクト: gcwnow/pwswd
int main(int argc, char **argv)
{
	const char *filename = NULL,
#ifdef BACKEND_VOLUME
		  *mixer = NULL, *dac = NULL,
#endif
		  *event = NULL, *uinput = NULL;
	int exitcode = EXIT_SUCCESS;
	size_t i;

	for (i = 1; i < argc; i++) {
		if (argc > i + 1) {
			if (!strcmp(argv[i], "-f"))
				filename = argv[i+1];
			else if (!strcmp(argv[i], "-e"))
				event = argv[i+1];
			else if (!strcmp(argv[i], "-u"))
				uinput = argv[i+1];
#ifdef BACKEND_VOLUME
			else if (!strcmp(argv[i], "-m"))
				mixer = argv[i+1];
			else if (!strcmp(argv[i], "-d"))
				dac = argv[i+1];
#endif
			else {
				printf(usage);
				return EXIT_FAILURE;
			}

			i++;
		} else {
			printf(usage);
			return EXIT_FAILURE;
		}
	}
	
	if (!filename) {
		struct stat st;
		filename = "/usr/local/etc/" PROGNAME ".conf";

		if (stat(filename, &st) == -1) {
			filename = "/etc/" PROGNAME ".conf";

			if (stat(filename, &st) == -1) {
				printf("pwswd: Unable to find a configuration file.\n");
				return EXIT_FAILURE;
			}
		}

		if (!S_ISREG(st.st_mode)) {
			printf("pwswd: The configuration file is not a regular file.\n");
			return EXIT_FAILURE;
		}
	}

	if (!event)
		event = EVENT_FILENAME;

	if (!uinput)
		uinput = UINPUT_FILENAME;

	if (read_conf_file(filename) < 0) {
		fprintf(stderr, "Unable to parse configuration file: aborting.\n");
		return EXIT_FAILURE;
	}

#ifdef BACKEND_VOLUME
	if (!mixer)
		mixer = DEFAULT_MIXER;

	if (vol_init(mixer, dac))
		fprintf(stderr, "Unable to init volume backend\n");
#endif

	if (do_listen(event, uinput))
		exitcode = EXIT_FAILURE;
	deinit();
	return exitcode;
}
コード例 #23
0
ファイル: parse-t.c プロジェクト: xunmengdeganjue/nocatsplash
int main (int argc, char **argv) {
    GHashTable *z = read_conf_file( "nocat.conf" );
    gchar *out = parse_template( argv[1], z );
    puts( out );
}
コード例 #24
0
ファイル: config.c プロジェクト: Alkzndr/freebsd
int
config_init(void)
{
	char *val;
	int i;
	const char *localbase;
	char *env_list_item;
	char confpath[MAXPATHLEN];
	struct config_value *cv;
	char abi[BUFSIZ];

	for (i = 0; i < CONFIG_SIZE; i++) {
		val = getenv(c[i].key);
		if (val != NULL) {
			c[i].envset = true;
			switch (c[i].type) {
			case PKG_CONFIG_LIST:
				/* Split up comma-separated items from env. */
				c[i].list = malloc(sizeof(*c[i].list));
				STAILQ_INIT(c[i].list);
				for (env_list_item = strtok(val, ",");
				    env_list_item != NULL;
				    env_list_item = strtok(NULL, ",")) {
					cv =
					    malloc(sizeof(struct config_value));
					cv->value =
					    strdup(env_list_item);
					STAILQ_INSERT_TAIL(c[i].list, cv,
					    next);
				}
				break;
			default:
				c[i].val = val;
				break;
			}
		}
	}

	/* Read LOCALBASE/etc/pkg.conf first. */
	localbase = getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE;
	snprintf(confpath, sizeof(confpath), "%s/etc/pkg.conf",
	    localbase);

	if (access(confpath, F_OK) == 0 && read_conf_file(confpath,
	    CONFFILE_PKG))
		goto finalize;

	/* Then read in all repos from REPOS_DIR list of directories. */
	if (c[REPOS_DIR].list == NULL) {
		c[REPOS_DIR].list = malloc(sizeof(*c[REPOS_DIR].list));
		STAILQ_INIT(c[REPOS_DIR].list);
		cv = malloc(sizeof(struct config_value));
		cv->value = strdup("/etc/pkg");
		STAILQ_INSERT_TAIL(c[REPOS_DIR].list, cv, next);
		cv = malloc(sizeof(struct config_value));
		if (asprintf(&cv->value, "%s/etc/pkg/repos", localbase) < 0)
			goto finalize;
		STAILQ_INSERT_TAIL(c[REPOS_DIR].list, cv, next);
	}

	STAILQ_FOREACH(cv, c[REPOS_DIR].list, next)
		if (load_repositories(cv->value))
			goto finalize;

finalize:
	if (c[ABI].val == NULL && c[ABI].value == NULL) {
		if (pkg_get_myabi(abi, BUFSIZ) != 0)
			errx(EXIT_FAILURE, "Failed to determine the system "
			    "ABI");
		c[ABI].val = abi;
	}

	subst_packagesite(c[ABI].value != NULL ? c[ABI].value : c[ABI].val);

	return (0);
}
コード例 #25
0
ファイル: main.c プロジェクト: 26597925/ucmq
int main(int argc, char *argv[])
{
    int     opt_char;
    int     ret_code;
    bool    daemon_flag = false;

    static const char *short_opts = "c:dhv";
    struct option long_opts[] = {
        {"help",   no_argument, 0, 'h'},
        {"version",no_argument, 0, 'v'},
        {"deamon", no_argument, 0, 'd'},
        {"config", required_argument, 0, 'c'},
        {0, 0, 0, 0}
    };

    while ((opt_char = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1)
    {
        switch (opt_char)
        {
            case 'c':
                SET_STR_OPT(g_mq_conf.conf_file);
                break;
            case 'd':
                daemon_flag = true;
                break;
            case 'v':
                print_version();
                return 0;
            case 'h':
            default :
                print_usage();
                return 0; 
        }
    }

    /* If arguments contain -c, the config file was already processed */
    if (!read_conf_file())
    {    
        fprintf(stderr, "ERROR: Read config fail, Please use the right conf\n");
        return 1;
    }    

    /* Init log */
    {
        log_config_t mq_log;

        log_init_config(&mq_log);
        strcpy(mq_log.log_path, g_mq_conf.output_log_path);
        strcpy(mq_log.log_file,"ucmq_log");
        if (strcmp(g_mq_conf.output_log_level, "TRACE") == 0)
        {
            mq_log.log_level = 0;
        }
        else if (strcmp(g_mq_conf.output_log_level, "DEBUG") == 0)
        {
            mq_log.log_level = 10;
        }
        else if (strcmp(g_mq_conf.output_log_level, "INFO") == 0)
        {
            mq_log.log_level = 100;
        }
        else if (strcmp(g_mq_conf.output_log_level, "WARN") == 0)
        {
            mq_log.log_level = 1000;
        }
        else if (strcmp(g_mq_conf.output_log_level, "ERROR") == 0)
        {
            mq_log.log_level = 10000;
        }
        else if (strcmp(g_mq_conf.output_log_level, "FATAL") == 0)
        {
            mq_log.log_level = 65535;
        }
        else
        {
            mq_log.log_level = 100;
        }
        log_init(&mq_log);
    }

    if (daemon_flag)
    {
        /* Set daemon */
        set_daemon();
        set_signal_handle();
        log_info("<%s> Startup ... Daemon mode %s", argv[0], "on");
        ret_code = main_entrance();
        log_info("<%s> ShutDown Ok", argv[0]);
    }
    else
    {
        set_signal_handle();
        log_info("<%s> Startup ... Daemon mode %s", argv[0], "off");
        ret_code = main_entrance();
        log_info("<%s> ShutDown Ok", argv[0]);
    }

    return ret_code;
}
コード例 #26
0
/*
 * open a windows driver and pass it to the kernel module.
 * returns 0: on success, -1 on error
 */
static int load_driver(int ioctl_device, char *driver_name,
		       char *conf_file_name)
{
	int i;
	struct dirent *dirent;
	struct load_driver *driver;
	int nr_sys_files, nr_bin_files;
	DIR *driver_dir;

	driver_dir = NULL;
	nr_sys_files = 0;
	nr_bin_files = 0;

	dbg("loading driver %s", driver_name);
	if (chdir(confdir) || chdir(driver_name)) {
		error("couldn't change to directory %s: %s",
		      driver_name, strerror(errno));
		return -EINVAL;
	}
	if ((driver_dir = opendir(".")) == NULL) {
		error("couldn't open driver directory %s: %s",
		      driver_name, strerror(errno));
		return -EINVAL;
	}
		
	if ((driver = malloc(sizeof(*driver))) == NULL) {
		error("couldn't allocate memory for driver %s", driver_name);
		goto err;
	}
	memset(driver, 0, sizeof(*driver));
	strncpy(driver->name, driver_name, MAX_DRIVER_NAME_LEN);

	if (read_conf_file(conf_file_name, driver) ||
	    driver->nr_settings == 0) {
		error("couldn't read conf file %s for driver %s",
		      conf_file_name, driver_name);
		goto err;
	}
	while ((dirent = readdir(driver_dir))) {
		int len;
		struct stat statbuf;

		if (strcmp(dirent->d_name, ".") == 0 ||
		    strcmp(dirent->d_name, "..") == 0)
			continue;

		if (stat(dirent->d_name, &statbuf) ||
		    !S_ISREG(statbuf.st_mode)) {
			error("%s in %s is not a valid file: %s",
			      dirent->d_name, driver_name, strerror(errno));
			continue;
		}

		len = strlen(dirent->d_name);
		if (len > 4 &&
		     strcmp(&dirent->d_name[len-4], ".inf") == 0)
			continue;
		if (len > 5 &&
		     strcmp(&dirent->d_name[len-5], ".conf") == 0)
			continue;

		if (len > 4 && strcmp(&dirent->d_name[len-4], ".sys") == 0) {
			if (load_file(dirent->d_name,
				      &driver->sys_files[nr_sys_files])) {
				error("couldn't load .sys file %s",
				      dirent->d_name);
				goto err;
			} else
				nr_sys_files++;
		} else if (len > 4 &&
			   strcmp(&dirent->d_name[len-4], ".bin") == 0) {
			if (load_file(dirent->d_name,
				      &driver->bin_files[nr_bin_files])) {
				error("coudln't load .bin file %s",
				      dirent->d_name);
				goto err;
			} else
				nr_bin_files++;
		} else
			error("file %s is ignored", dirent->d_name);

		if (nr_sys_files == MAX_PE_IMAGES) {
			error("too many .sys files for driver %s",
			      driver_name);
			goto err;
		}
		if (nr_bin_files == MAX_NDIS_BIN_FILES) {
			error("too many .bin files for driver %s",
			      driver_name);
			goto err;
		}
	}

	if (nr_sys_files == 0) {
		error("coudln't find valid drivers files for driver %s",
		      driver_name);
		goto err;
	}
	driver->nr_sys_files = nr_sys_files;
	driver->nr_bin_files = nr_bin_files;
	strncpy(driver->conf_file_name, conf_file_name,
		sizeof(driver->conf_file_name));

#ifndef DEBUG
	if (ioctl(ioctl_device, NDIS_LOAD_DRIVER, driver))
		goto err;
#endif

	closedir(driver_dir);
	dbg("driver %s loaded", driver_name);
	free(driver);
	return 0;

err:
	if (driver_dir)
		closedir(driver_dir);
	for (i = 0; i < nr_sys_files; i++)
		free(driver->sys_files[i].data);
	for (i = 0; i < nr_bin_files; i++)
		free(driver->bin_files[i].data);
	error("couldn't load driver %s", driver_name);
	free(driver);
	return -1;
}