Esempio n. 1
0
static int ConfigDialogBoxProc (HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
    switch (message) {
    case MSG_INITDIALOG:
	init_config(hDlg);
	return 1;
        
    case MSG_COMMAND:
        switch (wParam) {
        case IDC_NETWORK_OK:
		ok(hDlg);
	case IDC_NETWORK_CANCEL:
        case IDCANCEL:
		EndDialog (hDlg, wParam);
		break;
        }
        break;
    }
    
    return DefaultDialogProc (hDlg, message, wParam, lParam);
}
Esempio n. 2
0
/**
 * \brief Initialize the application.
 * \param default_env Default workspace_environment.
 */
bool bf::animation_editor::do_init_app
( const workspace_environment& default_env )
{
  bool result = false;

  init_config();

  main_frame* frame = NULL;

  if (argc > 1)
    for (int i=1; i<argc; ++i)
      {
        std::string w =
          path_configuration::get_instance().search_workspace
          ( wx_to_std_string( argv[i] ) );
        
        workspace_environment env(w);

        if ( ! w.empty() )
          {
            frame = new main_frame(env);
            frame->load_animation( argv[i] );
            frame->Show();
            result = true;
          }
        else
          std::cout << "Error. No workspace is available for animation " 
                    << wx_to_std_string( argv[i] ) << std::endl;
      }
  else
    {
      frame = new main_frame( default_env );
      frame->SetSize( m_config.main_rect );
      frame->Show();
      result = true;
    }

  return result;
} // animation_editor::do_init_app()
Esempio n. 3
0
int main(int argc, char **argv) {
    int err;
    sigset_t oldmask;
    pthread_t tid;

    sigemptyset(&mask);
    sigaddset(&mask, SIGPIPE); //向信号集中添加SIGPIPE
    if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
        log_exit(err, "SIG_BLOCK error");
    err = pthread_create(&tid, NULL, sig_handler, 0);
    if (err != 0)
        log_exit(err, "Cannot create thread!");

    init_config();
    int listenfd = initserver();
    set_noblock(listenfd);
    threadpool_t *tp = threadpool_create(8);
    main_loop(tp, listenfd);

    threadpool_join(tp);
    exit(0);
}
Esempio n. 4
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    int ret;
    WSADATA wsaData;


    /* Starting Winsock -- for name resolution. */
    WSAStartup(MAKEWORD(2, 0), &wsaData);


    /* Initializing config */
    init_config();

    /* Initializing controls */
    InitCommonControls();

    /* Creating main dialogbox */
    DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN), NULL, DlgProc);


    /* Check if service is running and try to start it */
    if((strcmp(config_inst.key, FL_NOKEY) != 0)&&
            (strcmp(config_inst.server, FL_NOSERVER) != 0) &&
            !CheckServiceRunning() &&
            (config_inst.admin_access != 0))
    {
        ret = MessageBox(NULL, "OSSEC Agent not running. "
                "Do you wish to start it?",
                "Wish to start the agent?", MB_OKCANCEL);
        if(ret == IDOK)
        {
            /* Starting the service */
            os_start_service();
        }
    }

    return(0);
}
Esempio n. 5
0
/**
 * scout main
 */  
int 
main( int argc, char *argv[] )
{
  int x, result;                /* index, func. result*/
  struct sigaction  action;   
  CLIENT           *client;     /* defined in setup.h */  
 
  init_config();                /* defined in init.h */
  parse_cmdline(argc, argv);    /* defined above     */
  
  if( my.config ){
    /* see: init.h */  
    show_config( TRUE );    
  }

  memset( &action, 0, sizeof( action ));
  action.sa_handler = signal_handler;
  if( sigaction( SIGHUP, &action, NULL ))
    joe_error( "sigaction" );
  if( sigaction( SIGINT, &action, NULL))
    joe_error( "sigaction" );
  if( sigaction( SIGTERM, &action, NULL))
    joe_error( "sigaction" );

  /* cookie is an EXTERN, defined in setup */ 
  cookie = (COOKIE*)malloc( sizeof(COOKIE)); 
  if( !cookie ){ joe_fatal( "memory exhausted" ); }
  cookie->first = NULL;
  client = (CLIENT*)malloc(sizeof(CLIENT));
  if( !client ){ joe_fatal( "application memory exhausted" ); } 

  http_client( client );
  write_queue( my.showcodes );
  /**
   * exit program.
   */
  exit( EXIT_SUCCESS );	
} /* end of int main **/
Esempio n. 6
0
// read the xml file
int read_xml(){
	
	init_config();

	debug_printf ("Reading hardware element...\n");	

	// read the hardaware element
	if (read_hardware() != 0){
		return -1;	
	}
	debug_printf ("OK\n");	

	// read the kernel element	
	if (read_kernel() != 0){
		return -1;	
	}

	// read the ports element
	if (read_ports() != 0){
		return -1;	
	}

	// read the partitions element
	if (read_partitions() != 0){
		return -1;	
	}

	// check if every port has been assigned to a partition
	int i;
	for (i=0; i<nb_ports; i++){
		if (ports[i].partition_id == -1){
			printf("WARNING: port %d has not been assigned to any partition!\n",ports[i].user_port_id);
		}	
	}

	return 0;

} 
Esempio n. 7
0
char *find_config_section_with_string(char *name, char *str)
{
   CONFIG_ENTRY *p;
   CONFIG   *cfg;

   init_config(TRUE);

   cfg = config[0];

   if (cfg) {
      p = cfg->head;

      while (p) {
	 if (p->name) {
	    if ((p->name[0] == '[') && (p->name[strlen(p->name)-1] == ']')) {
	       /* change section */
	       strncpy(g_section, p->name+1, strlen(p->name)-2);
	       g_section[strlen(p->name)-2] = 0;
	    }
	    else
	    /* is this the one? */
	       if (stricmp(p->name, name) == 0)
	       {
		   if ((p->data) && (*p->data)) {
		        int i;
			i = stricmp(str, p->data);
			if (i == 0)
			    return g_section;
		   }
		}
	 }

	 p = p->next;
      }
   }

   return NULL;
}
Esempio n. 8
0
/* get_config_string:
 *  Reads a string from the configuration file.
 */
char *get_config_string(char *section, char *name, char *def)
{
   char section_name[256];
   CONFIG_HOOK *hook;
   CONFIG_ENTRY *p;

   init_config(TRUE);

   prettify_section_name(section, section_name);

   /* check for hooked sections */
   hook = config_hook;

   while (hook) {
      if (stricmp(section_name, hook->section) == 0) {
	 if (hook->stringgetter)
	    return hook->stringgetter(name, def);
	 else
	    return def;
      }
      hook = hook->next;
   }

   /* find the string */
   p = find_config_string(config_override, section_name, name, NULL);

   if (!p) {
      if ((name[0] == '#') || ((section_name[0] == '[') && (section_name[1] == '#')))
	 p = find_config_string(system_config, section_name, name, NULL);
      else
	 p = find_config_string(config[0], section_name, name, NULL);
   }

   if (p)
      return (p->data ? p->data : "");
   else
      return def;
}
void read_config(char* file)
{
    GKeyFile *config;
    char *cur = hciattach_options;
    const char *end = hciattach_options + sizeof(hciattach_options);

    /* set first default values and then load configured ones */
    init_config();
    config = load_config(file);
    parse_config(config);
    load_bd_add();

    /* set always configured options: use same configured baud-rate also for download, and ignore first 2 bytes (needed by bcm43341 and more recent brcm bt chip) */
    cur += snprintf(cur, end-cur, "%s", "--use_baudrate_for_download --no2bytes");

    /* concatenate configured options */
    if ((cur < end) && (main_opts.enable_fork)) {
        cur += snprintf(cur, end-cur," %s", "--enable_fork");
    }
    if ((cur < end) && (main_opts.enable_lpm)) {
        cur += snprintf(cur, end-cur," %s", "--enable_lpm");
    }
    if ((cur < end) && (main_opts.enable_hci)) {
        cur += snprintf(cur, end-cur," %s", "--enable_hci");
    }
    if ((cur < end) && (main_opts.set_baud_rate)) {
        cur += snprintf(cur, end-cur," --baudrate %d", main_opts.baud_rate);
    }
    if ((cur < end) && (main_opts.dl_patch)) {
        cur += snprintf(cur, end-cur," --patchram %s", main_opts.fw_patch);
    }
    if ((cur < end) && (main_opts.set_bd)) {
        cur += snprintf(cur, end-cur," --bd_addr %s", main_opts.bd_add);
    }
    if ((cur < end) && (main_opts.set_scopcm)) {
        cur += snprintf(cur, end-cur," --scopcm %s", main_opts.scopcm);
    }
}
Esempio n. 10
0
catalyzer_config * handle_user(int argc, char ** argv) {

	int c;

	catalyzer_config * config = init_config();
	opterr = 0;

	/* TODO: reject bad values, add more configurability */
	while ((c = getopt (argc, argv, "d:n:")) != -1)
	switch (c)
	{
		case 'd':
			config->downsample = atoi(optarg);
			break;
		case 'n':
			config->num_samples = atoi(optarg);
			break;
		default:
			abort();
	}

	return config;
}
Esempio n. 11
0
void
parse_INIfile ()
{
# if 0 //LUDO: TO_BE_DONE
  Log ("--[ PARSING INI FILE ]------------------------------\n");

#ifndef LINUX
  sprintf (config_file, "%shugo.ini", short_exe_name);
#else
  {

    char tmp_home[256];
    FILE *f;

    sprintf (tmp_home, "%shugo.ini", short_exe_name);

    f = fopen (tmp_home, "rb");

    if (f != NULL)
      {
	strcpy (config_file, tmp_home);
	fclose (f);
      }
    else
      strcpy (config_file, "/etc/hugo.ini");
  }
#endif


  init_config ();

  parse_INIfile_raw ();

  dispose_config ();
# endif

}
Esempio n. 12
0
void main(void){
   
   init_config();
           
   if(input(IR_RECEIVER)){ fprintf(SERIAL, "Conexión no iniciada.\n\r\n\r"); }
   
   while(input(IR_RECEIVER));
      
   fprintf(SERIAL, "Conexión iniciada.\n\r\n\r");         
   RBIF=0;                          // Se limpia la bandera de interrupcion por cambio de estado de RB.
   enable_interrupts(GLOBAL);       // Permiso Global de interrupciones.
   
   while(1){            
      adcPwmEnhanced(52.0); //52 es el valor de CCPRxL:CCPxCON<5:4> cuando el "duty" esta al 100%.
      
      //Si hay algo que notificar entonces se realiza por medio de una comunicacion serial.
      if(notification){
         notification=false;     //Se desactiva la notificacion serial.
         serialNotification();   
      }
            
      //Si el enlace esta bloqueado da vuelta, sino camina hacia adelante.            
      if(really_blocked){
         driverStop();
         driverLeft();
      }
      else{ driverForward(); }
      
      //Calculo para la distancia recorrida y velocidad (odometro).
      if(sec_odom){
         sec_odom=false;
         odometer(2, 0.01);         
      }
      
   }  //</while>
   
}  //</main>
Esempio n. 13
0
File: fifo.c Progetto: CESNET/torque
/*
 *
 * schedinit - initialize conf struct and parse conf files
 *
 *   argc - passed in from main
 *   argv - passed in from main
 *
 * Returns Success/Failure
 *
 *
 */
int schedinit(int argc, char *argv[])
  {
  init_config();
  parse_config(CONFIG_FILE);
  parse_holidays(HOLIDAYS_FILE);

  time(&(cstat.current_time));

  if (is_prime_time())
    init_prime_time();
  else
    init_non_prime_time();

  parse_ded_file(DEDTIME_FILE);

  /* preload the static members to the fairshare tree */
  preload_tree();

  parse_group(RESGROUP_FILE);

  calc_fair_share_perc(conf.group_root -> child, UNSPECIFIED);

  if (conf.prime_fs || conf.non_prime_fs)
    {
    read_usage();

    /*
     * initialize the last_decay to the current time, since we do not know when
     * the last decay happened
     */
    last_sync = last_decay = cstat.current_time;
    }

  token_acct_open((char *)0);

  return 0;
  }
Esempio n. 14
0
static int in_group(const char *clientconfdir, const char *client, strlist_t **grouplist, int gcount, struct config *conf)
{
	int i=0;
	char *ccfile=NULL;
	struct config cconf;

	if(!(ccfile=prepend(clientconfdir, client, "/"))) return -1;
	init_config(&cconf);
	if(set_client_global_config(conf, &cconf, client)
	  || load_config(ccfile, &cconf, 0))
	{
		logp("could not load config for client %s\n", client);
		free(ccfile);
		return 0;
	}
	free(ccfile);

	if(!cconf.dedup_group) return 0;

	for(i=0; i<gcount; i++)
		if(!strcmp(grouplist[i]->path, cconf.dedup_group))
			return 1;
	return 0;
}
Esempio n. 15
0
AwnApplet *
awn_applet_factory_initp (const gchar *name, gchar* uid, gint panel_id)
{
  g_on_error_stack_trace (NULL);
  html_init ();
  WebApplet *webapplet = g_malloc (sizeof (WebApplet));
  webapplet->uid=g_strdup(uid);
  webapplet->check_home = NULL;
  webapplet->location_dialog = NULL;
  webapplet->start = NULL;
  webapplet->applet = AWN_APPLET (awn_applet_simple_new (name, uid, panel_id));
  init_config (webapplet);
  gint height = awn_applet_get_size(webapplet->applet);

  awn_applet_simple_set_icon_name(AWN_APPLET_SIMPLE(webapplet->applet),
                                  ICON_NAME);
 
  /*gtk_widget_show_all (GTK_WIDGET (webapplet->applet));*/
  awn_html_dialog_new (webapplet);
  gtk_window_set_focus_on_map (GTK_WINDOW (webapplet->mainwindow), TRUE);
  g_signal_connect_after (G_OBJECT (webapplet->applet), "realize",
                          G_CALLBACK (_bloody_thing_has_style), webapplet);
  return webapplet->applet;
}
Esempio n. 16
0
void check_config()
{
	int i;

	if(strcmp(setting.vercnf, VERCNF)){
		init_config();
		return;
	}
	if(setting.speed > 100)
	  setting.speed = 30;
	if(setting.gb_type>4)
		setting.gb_type = 0;
	if(setting.gb_palette<=PAL_MONOCHROME || setting.gb_palette>=PAL_SGB)
		setting.gb_palette = PAL_DARK_GREEN;
	if(setting.frameskip > 9)
		setting.frameskip=0;
	if(setting.sound_buffer>2)
		setting.sound_buffer = 0;
	
	if(setting.autosave < 0 || setting.autosave > 9999)
		setting.autosave = 100;
		
	lcd_set_mpal(setting.gb_palette);
}
Esempio n. 17
0
/*
 * load the HDFS client configuration
 */
static NNHAConf* 
load_hdfs_client_config(const char *nameservice)
{
	int len, i;
	NNHAConf *conf;
	Namenode *nns = hdfsGetHANamenodes(nameservice, &len);
	
	if (nns == NULL)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("nameservice %s not found in client configuration. No HA namenodes provided",
						nameservice)));
	
	if (len == HA_ONE_NODE)
		ereport(ERROR,
				(errcode(ERRCODE_INTERNAL_ERROR),
				 errmsg("High availability for nameservice %s was configured with only one node. A high availability scheme requires at least two nodes ",
						nameservice)));
		
	conf = init_config(len, nameservice);
	
	for (i = 0; i < conf->numn; i++)
		set_one_namenode(conf, i, &nns[i]);
	
	/* 
	 * If we succeeded to create NNHAConf from the input Namenode array in set_one_namenode(), 
	 * we can at least say that the Namenode array has no NULL or empty strings inside.
	 * Then we can safely trace it to the log so we can record what was received from 
	 * the configuration.
	 */
	traceNamenodeArr(nns, len);
	
	hdfsFreeNamenodeInformation(nns, len);
	
	return conf;
}
Esempio n. 18
0
int
main(int argc, char **argv) {
    const char *config_file = "/etc/sniproxy.conf";
    int background_flag = 1;
    int max_nofiles = 65536;
    int opt;

    while ((opt = getopt(argc, argv, "fc:n:V")) != -1) {
        switch (opt) {
            case 'c':
                config_file = optarg;
                break;
            case 'f': /* foreground */
                background_flag = 0;
                break;
            case 'n':
                max_nofiles = atoi(optarg);
                break;
            case 'V':
                printf("sniproxy %s\n", sniproxy_version);
#ifdef HAVE_LIBUDNS
                printf("compiled with udns support\n");
#endif
                return EXIT_SUCCESS;
            default:
                usage();
                return EXIT_FAILURE;
        }
    }

    config = init_config(config_file, EV_DEFAULT);
    if (config == NULL) {
        fprintf(stderr, "Unable to load %s\n", config_file);
        usage();
        return EXIT_FAILURE;
    }

    /* ignore SIGPIPE, or it will kill us */
    signal(SIGPIPE, SIG_IGN);

    if (background_flag) {
        if (config->pidfile != NULL)
            remove(config->pidfile);

        daemonize();


        if (config->pidfile != NULL)
            write_pidfile(config->pidfile, getpid());
    }

    start_binder();

    set_limits(max_nofiles);

    init_listeners(&config->listeners, &config->tables, EV_DEFAULT);

    /* Drop permissions only when we can */
    drop_perms(config->user ? config->user : default_username);

    ev_signal_init(&sighup_watcher, signal_cb, SIGHUP);
    ev_signal_init(&sigusr1_watcher, signal_cb, SIGUSR1);
    ev_signal_init(&sigusr2_watcher, signal_cb, SIGUSR2);
    ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
    ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
    ev_signal_start(EV_DEFAULT, &sighup_watcher);
    ev_signal_start(EV_DEFAULT, &sigusr1_watcher);
    ev_signal_start(EV_DEFAULT, &sigusr2_watcher);
    ev_signal_start(EV_DEFAULT, &sigint_watcher);
    ev_signal_start(EV_DEFAULT, &sigterm_watcher);

    resolv_init(EV_DEFAULT, config->resolver.nameservers,
            config->resolver.search, config->resolver.mode);

    init_connections();

    ev_run(EV_DEFAULT, 0);

    free_connections(EV_DEFAULT);
    resolv_shutdown(EV_DEFAULT);

    free_config(config, EV_DEFAULT);

    stop_binder();

    return 0;
}
Esempio n. 19
0
File: conf.c Progetto: barroque/burp
void free_config(struct config *conf)
{
	if(!conf) return;
	if(conf->port) free(conf->port);
	if(conf->configfile) free(conf->configfile);
	if(conf->clientconfdir) free(conf->clientconfdir);
	if(conf->cname) free(conf->cname);
	if(conf->directory) free(conf->directory);
	if(conf->timestamp_format) free(conf->timestamp_format);
	if(conf->ca_conf) free(conf->ca_conf);
	if(conf->ca_name) free(conf->ca_name);
	if(conf->ca_server_name) free(conf->ca_server_name);
	if(conf->ca_burp_ca) free(conf->ca_burp_ca);
	if(conf->ca_csr_dir) free(conf->ca_csr_dir);
	if(conf->lockfile) free(conf->lockfile);
	if(conf->password) free(conf->password);
	if(conf->passwd) free(conf->passwd);
	if(conf->server) free(conf->server);
	if(conf->working_dir_recovery_method)
		free(conf->working_dir_recovery_method);
 	if(conf->ssl_cert_ca) free(conf->ssl_cert_ca);
        if(conf->ssl_cert) free(conf->ssl_cert);
        if(conf->ssl_key) free(conf->ssl_key);
        if(conf->ssl_key_password) free(conf->ssl_key_password);
        if(conf->ssl_ciphers) free(conf->ssl_ciphers);
        if(conf->ssl_dhfile) free(conf->ssl_dhfile);
        if(conf->ssl_peer_cn) free(conf->ssl_peer_cn);
        if(conf->user) free(conf->user);
        if(conf->group) free(conf->group);
        if(conf->encryption_password) free(conf->encryption_password);
	if(conf->client_lockdir) free(conf->client_lockdir);
	if(conf->autoupgrade_dir) free(conf->autoupgrade_dir);
	if(conf->autoupgrade_os) free(conf->autoupgrade_os);

	if(conf->timer_script) free(conf->timer_script);
	strlists_free(conf->timer_arg, conf->tacount);

	if(conf->notify_success_script) free(conf->notify_success_script);
	strlists_free(conf->notify_success_arg, conf->nscount);

	if(conf->notify_failure_script) free(conf->notify_failure_script);
	strlists_free(conf->notify_failure_arg, conf->nfcount);

	strlists_free(conf->rclients, conf->rccount);

	if(conf->backup_script_pre) free(conf->backup_script_pre);
	strlists_free(conf->backup_script_pre_arg, conf->bprecount);
	if(conf->backup_script_post) free(conf->backup_script_post);
	strlists_free(conf->backup_script_post_arg, conf->bpostcount);
	if(conf->restore_script_pre) free(conf->restore_script_pre);
	strlists_free(conf->restore_script_pre_arg, conf->rprecount);
	if(conf->restore_script_post) free(conf->restore_script_post);
	strlists_free(conf->restore_script_post_arg, conf->rpostcount);

	if(conf->server_script_pre) free(conf->server_script_pre);
	strlists_free(conf->server_script_pre_arg, conf->sprecount);
	if(conf->server_script_post) free(conf->server_script_post);
	strlists_free(conf->server_script_post_arg, conf->spostcount);

	if(conf->backup_script) free(conf->backup_script);
	if(conf->restore_script) free(conf->restore_script);
	strlists_free(conf->backup_script_arg, conf->bscount);
	strlists_free(conf->restore_script_arg, conf->rscount);

	if(conf->server_script) free(conf->server_script);
	strlists_free(conf->server_script_arg, conf->sscount);

	strlists_free(conf->keep, conf->kpcount);

	if(conf->dedup_group) free(conf->dedup_group);
	if(conf->browsefile) free(conf->browsefile);
	if(conf->browsedir) free(conf->browsedir);
	if(conf->restore_client) free(conf->restore_client);
	if(conf->restore_path) free(conf->restore_path);
	if(conf->orig_client) free(conf->orig_client);

	free_incexcs(conf);

	init_config(conf);
}
Esempio n. 20
0
/* set_config_string:
 *  Writes a string to the configuration file.
 */
void set_config_string(char *section, char *name, char *val)
{
   CONFIG *the_config;
   CONFIG_HOOK *hook;
   CONFIG_ENTRY *p, *prev;
   char section_name[256];

   init_config(TRUE);

   prettify_section_name(section, section_name);

   /* check for hooked sections */
   hook = config_hook;

   while (hook) {
      if (stricmp(section_name, hook->section) == 0) {
	 if (hook->stringsetter)
	    hook->stringsetter(name, val);
	 return;
      }
      hook = hook->next;
   }

   /* decide which config file to use */
   if ((name[0] == '#') || ((section_name[0] == '[') && (section_name[1] == '#')))
      the_config = system_config;
   else
      the_config = config[0];

   if (the_config) {
      p = find_config_string(the_config, section_name, name, &prev);

      if (p) {
	 if ((val) && (*val)) {
	    /* modify existing variable */
	    if (p->data)
	       free(p->data);

	    p->data = malloc(strlen(val)+1);
	    if (p->data)
	       strcpy(p->data, val);
	 }
	 else {
	    /* delete variable */
	    if (p->name)
	       free(p->name);

	    if (p->data)
	       free(p->data);

	    if (prev)
	       prev->next = p->next;
	    else
	       the_config->head = p->next;

	    free(p);
	 }
      }
      else {
	 if ((val) && (*val)) {
	    /* add a new variable */
	    if (section_name[0]) {
	       p = find_config_string(the_config, NULL, section_name, &prev);

	       if (!p) {
		  /* create a new section */
		  p = the_config->head;
		  while ((p) && (p->next))
		     p = p->next;

		  if ((p) && (p->data) && (*p->data))
		     p = insert_variable(the_config, p, NULL, NULL);

		  p = insert_variable(the_config, p, section_name, NULL);
	       }

	       /* append to the end of the section */
	       while ((p) && (p->next) && 
		      (((p->next->name) && (*p->next->name)) || 
		       ((p->next->data) && (*p->next->data))))
		  p = p->next;

	       p = insert_variable(the_config, p, name, val);
	    }
	    else {
	       /* global variable */
	       p = the_config->head;
	       insert_variable(the_config, NULL, name, val);
	       the_config->head->next = p;
	    }
	 } 
      }

      the_config->dirty = TRUE;
   }
}
Esempio n. 21
0
static void set_config(CONFIG **config, char *data, int length, char *filename)
{
   char name[256];
   char val[256];
   CONFIG_SECTION **prev, *p;
   CONFIG_ENTRY	**prev_e, *p_e;
   int pos;
   int	in_section = 0;

   init_config(FALSE);

   if (*config) {
      destroy_config(*config);
      *config = NULL;
   }

   *config = malloc(sizeof(CONFIG));
   if (!(*config))
      return;

   (*config)->head = NULL;
   (*config)->dirty = FALSE;

   if (filename) {
      (*config)->filename = malloc(strlen(filename)+1);
      if ((*config)->filename)
	 strcpy((*config)->filename, filename); 
   }
   else
      (*config)->filename = NULL;

   prev = &(*config)->head;
   pos = 0;

   while (pos < length) {
      pos += get_line(data+pos, length-pos, name, val);

      if (in_section && name[0] == '[')
	  {
	      in_section = 0;
	  }

      if (in_section)
      {
	  p_e = malloc(sizeof(CONFIG_ENTRY));
          if (!p_e)
    	    return;

          if (name[0]) {
	     p_e->name = malloc(strlen(name)+1);
	     if (p_e->name)
		strcpy(p_e->name, name);
	  }
	  else
	     p_e->name = NULL;

	  p_e->data = malloc(strlen(val)+1);
	  if (p_e->data)
	     strcpy(p_e->data, val);

	  p_e->next = NULL;
	  *prev_e = p_e;
	  prev_e = &p_e->next;

	  continue;
      }	

      p = malloc(sizeof(CONFIG_SECTION));
      if (!p)
	 return;

      p->key = NULL;

      if (name[0]) {
	 p->name = malloc(strlen(name)+1);
	 if (p->name)
	    strcpy(p->name, name);
      }
      else
	 p->name = NULL;

      p->data = malloc(strlen(val)+1);
      if (p->data)
	 strcpy(p->data, val);

      p->next = NULL;
      *prev = p;
      prev = &p->next;

      // FIXME
      if (name[0] == '[')
      {
	  prev_e = &p->head;
	  in_section = 1;
      }
   }
}
Esempio n. 22
0
int main(int argc, char** argv) {
	init_config();

	int execute_cmd(char* line, bool is_dump) {
		//if is_dump == true then file cmd
		//   is_dump == false then stdin cmd
		if(is_dump == true)
			printf("%s\n", line);
		
		sendto(sock, line, strlen(line) + 1, 0,(struct sockaddr*)&lb_addr, sizeof(lb_addr));
		cmd_exec(line);

		printf("> ");
		fflush(stdout);

		return 0;
	}
	
	List* fd_list = list_create(NULL);
	
	for(int i = 1; i < argc; i++) {
		int fd = open(argv[i], O_RDONLY);
		if(fd != -1) {
			list_add(fd_list, (void*)(int64_t)fd);
		}
	}
	list_add(fd_list, STDIN_FILENO); //fd of stdin

	void get_cmd_line(int fd) {
		static char line[MAX_LINE_SIZE] = {0, };
		char* head;
		int seek = 0;
		static int eod = 0; //end of data

		while((eod += read(fd, &line[eod], MAX_LINE_SIZE - eod))) {
			head = line;
			for(; seek < eod; seek++) {
				if(line[seek] == '\n') {
					line[seek] = '\0';
					int ret = execute_cmd(head, fd != STDIN_FILENO);

					if(fd != STDIN_FILENO && ret != 0 && ret != CMD_STATUS_ASYNC_CALL) {//parsing file and return error code
						printf("stop parsing file\n");
						eod = 0;
						return;
					}
					head = &line[seek] + 1;
				}
			}
			if(head == line && eod == MAX_LINE_SIZE){ //not found '\n' and head == 0
				printf("Command line is too long %d > %d\n", eod, MAX_LINE_SIZE);
				eod = 0; 
				return;
			} else { //not found '\n' and seek != 0
				memmove(line, head, eod - (head - line));
				eod -= head - line;
				seek = eod;
				if(fd == STDIN_FILENO) {
					return;
				} else
					continue;
			}
		}
		if(eod != 0) {
			line[eod] = '\0';
			execute_cmd(&line[0], fd != STDIN_FILENO);
		}
		eod = 0;
		return;
	}
	
	int fd = (int)(int64_t)list_remove_first(fd_list);
	int retval;
	char buf[CMD_RESULT_SIZE] = {0, };
	
	fd_set in_put;
	fd_set temp_in;

	FD_ZERO(&in_put);
	FD_SET(sock, &in_put);
	FD_SET(fd, &in_put);

	printf(">");
	fflush(stdout);
	
	while(is_continue) {
		temp_in = in_put;

		retval = select(fd > sock ? (fd + 1) : (sock + 1), &temp_in, 0, 0, NULL);

		if(retval == -1) {
			printf("selector error\n");
			return -1;
		} else if(retval == 0) {
			printf("selector timeout\n");
			continue;
		} else {
			if(FD_ISSET(sock, &temp_in) != 0) {
				struct sockaddr_in recv_addr;
				socklen_t recv_addr_size;
				recvfrom(sock, buf, CMD_RESULT_SIZE - 1, 0, (struct sockaddr*)&recv_addr, &recv_addr_size);
				printf("%s\n",buf);
				fflush(stdout);
			}
			if(FD_ISSET(fd, &temp_in) != 0) {
				get_cmd_line(fd);
				if(fd != STDIN_FILENO) {
					FD_CLR(fd, &in_put);
					close(fd);
					fd = (int)(int64_t)list_remove_first(fd_list);
					FD_SET(fd, &in_put);
				}
			}
		}

	}
}
Esempio n. 23
0
char *config_get(const int key_path, const char* dir, char *name)
{

	char run[512]={0};
	memset(run, 0, sizeof(run));

	strcpy(run , init_config( key_path, dir, name));

	if( strcmp( run , "NVRAM") == 0 )
	{
		//先处理nvram值

		sprintf(run, "nvram get %s", name);
		char *nvram_value = NULL;
		nvram_value = run_command( 1 , run);

		if(nvram_value == NULL)
		{
			return NULL;
		}
		else
		{
			if(strlen( nvram_value ) == 0)
			{
				return NULL;
			}

			static char array_value[256] = {0};	
			strcpy(array_value, nvram_value);
			return array_value;
		}

	}


	if(access(run,0)==0)
	{
		char path[256]={0} ;
		FILE *f;

		if ((f = fopen(run, "rb")) == NULL) 
		{
			return NULL;
		}
		static char buffValueGet[64]={0};
		memset(buffValueGet, '\0', sizeof(buffValueGet));
		fgets(buffValueGet, 64, f);
		fclose(f);
		if( buffValueGet )
		{
			char *tmpstr=NULL;
			tmpstr=strtok(buffValueGet,"\n");
			//			printf("-----4---test=%s\n",buffValue);

			if(tmpstr!=NULL)
				strcpy(buffValueGet,tmpstr);
			//			printf("-----5---test=%s\n",buffValue);
		}
		//		printf("-----6---test=%s\n",buffValue);
		return  buffValueGet;

	}
	else		
	{	
		return NULL;
	}

}
Esempio n. 24
0
/**
* @file libConfig.c
* @brief 判断变量是否相等  
*       参数      存储位置   目录    变量名  变量值
*                1 永久存储  0 临时存储  2 nvram或其他内置存储
* @author lvlai.lin
* @version v2
* @date 2018-05-11
*/
int config_match(const int key_path, const char* dir, char *name, char *match) 
{

	if (!name) {
		return E_FAILURE;
	}

	if (!match) {
		return E_FAILURE;
	}


	char run[512]={0};
	memset(run, 0, sizeof(run));

	strcpy(run , init_config( key_path, dir, name));

	if( strcmp( run , "NVRAM") == 0 )
	{
		//先处理nvram值
		sprintf(run, "nvram get %s", name);
		char *nvram_value = NULL;
		nvram_value = run_command( 1 , run);

		if(nvram_value == NULL)
			return E_FAILURE;
		else
		{
			if( strcmp( nvram_value, match )  == 0)
				return E_SUCCESS;
			else 
				return E_FAILURE;
		}

	}

	if(access(run,0)==0)
	{
		char path[256]={0} ;
		FILE *f;

		if ((f = fopen(run, "rb")) == NULL) 
		{
			return E_FAILURE;
		}
		static char matchValue[64]={0};

		memset(matchValue, '\0', sizeof(matchValue));
		fgets(matchValue, 64, f);
		fclose(f);

		if( matchValue )
		{
			char *tmpstr=NULL;
			tmpstr=strtok(matchValue,"\n");

			if(tmpstr!=NULL)
			{
				strcpy(matchValue,tmpstr);
				if(strcmp(matchValue,match)==0)
					return E_SUCCESS;
				else 
					return E_FAILURE;

			}else
			{
				return E_FAILURE;
			}
		}else
		{
			return E_FAILURE;
		}


	}
	else		
		return E_FAILURE;

}
Esempio n. 25
0
int32_t main (int32_t argc, char *argv[])
{
	int32_t i, j;
	prog_name = argv[0];
	if (pthread_key_create(&getclient, NULL)) {
		fprintf(stderr, "Could not create getclient, exiting...");
		exit(1);
	}

  void (*mod_def[])(struct s_module *)=
  {
#ifdef MODULE_MONITOR
           module_monitor,
#endif
#ifdef MODULE_CAMD33
           module_camd33,
#endif
#ifdef MODULE_CAMD35
           module_camd35,
#endif
#ifdef MODULE_CAMD35_TCP
           module_camd35_tcp,
#endif
#ifdef MODULE_NEWCAMD
           module_newcamd,
#endif
#ifdef MODULE_CCCAM
           module_cccam,
#endif
#ifdef MODULE_PANDORA
           module_pandora,
#endif
#ifdef MODULE_GHTTP
           module_ghttp,
#endif
#ifdef CS_CACHEEX
           module_csp,
#endif
#ifdef MODULE_GBOX
           module_gbox,
#endif
#ifdef MODULE_CONSTCW
           module_constcw,
#endif
#ifdef MODULE_RADEGAST
           module_radegast,
#endif
#ifdef MODULE_SERIAL
           module_serial,
#endif
#ifdef HAVE_DVBAPI
	   module_dvbapi,
#endif
           0
  };

  void (*cardsystem_def[])(struct s_cardsystem *)=
  {
#ifdef READER_NAGRA
	reader_nagra,
#endif
#ifdef READER_IRDETO
	reader_irdeto,
#endif
#ifdef READER_CONAX
	reader_conax,
#endif
#ifdef READER_CRYPTOWORKS
	reader_cryptoworks,
#endif
#ifdef READER_SECA
	reader_seca,
#endif
#ifdef READER_VIACCESS
	reader_viaccess,
#endif
#ifdef READER_VIDEOGUARD
	reader_videoguard1,
	reader_videoguard2,
	reader_videoguard12,
#endif
#ifdef READER_DRE
	reader_dre,
#endif
#ifdef READER_TONGFANG
	reader_tongfang,
#endif
#ifdef READER_BULCRYPT
	reader_bulcrypt,
#endif
#ifdef READER_GRIFFIN
	reader_griffin,
#endif
#ifdef READER_DGCRYPT
	reader_dgcrypt,
#endif
	0
  };

  void (*cardreader_def[])(struct s_cardreader *)=
  {
#ifdef CARDREADER_DB2COM
	cardreader_db2com,
#endif
#if defined(CARDREADER_INTERNAL_AZBOX)
	cardreader_internal_azbox,
#elif defined(CARDREADER_INTERNAL_COOLAPI)
	cardreader_internal_cool,
#elif defined(CARDREADER_INTERNAL_SCI)
	cardreader_internal_sci,
#endif
#ifdef CARDREADER_PHOENIX
	cardreader_mouse,
#endif
#ifdef CARDREADER_MP35
	cardreader_mp35,
#endif
#ifdef CARDREADER_PCSC
	cardreader_pcsc,
#endif
#ifdef CARDREADER_SC8IN1
	cardreader_sc8in1,
#endif
#ifdef CARDREADER_SMARGO
	cardreader_smargo,
#endif
#ifdef CARDREADER_SMART
	cardreader_smartreader,
#endif
#ifdef CARDREADER_STAPI
	cardreader_stapi,
#endif
	0
  };

  parse_cmdline_params(argc, argv);

  if (bg && do_daemon(1,0))
  {
    printf("Error starting in background (errno=%d: %s)", errno, strerror(errno));
    cs_exit(1);
  }

  get_random_bytes_init();

#ifdef WEBIF
  if (cs_restart_mode)
    restart_daemon();
#endif

  memset(&cfg, 0, sizeof(struct s_config));
  cfg.max_pending = max_pending;

  if (cs_confdir[strlen(cs_confdir) - 1] != '/') strcat(cs_confdir, "/");
  init_signal_pre(); // because log could cause SIGPIPE errors, init a signal handler first
  init_first_client();
  cs_lock_create(&system_lock, 5, "system_lock");
  cs_lock_create(&config_lock, 10, "config_lock");
  cs_lock_create(&gethostbyname_lock, 10, "gethostbyname_lock");
  cs_lock_create(&clientlist_lock, 5, "clientlist_lock");
  cs_lock_create(&readerlist_lock, 5, "readerlist_lock");
  cs_lock_create(&fakeuser_lock, 5, "fakeuser_lock");
  cs_lock_create(&ecmcache_lock, 5, "ecmcache_lock");
  cs_lock_create(&readdir_lock, 5, "readdir_lock");
  cs_lock_create(&cwcycle_lock, 5, "cwcycle_lock");
  cs_lock_create(&hitcache_lock, 5, "hitcache_lock");
  coolapi_open_all();
  init_config();
  cs_init_log();
  if (!oscam_pidfile && cfg.pidfile)
    oscam_pidfile = cfg.pidfile;
  if (!oscam_pidfile) {
    oscam_pidfile = get_tmp_dir_filename(default_pidfile, sizeof(default_pidfile), "oscam.pid");
  }
  if (oscam_pidfile)
    pidfile_create(oscam_pidfile);
  cs_init_statistics();
  init_check();
  init_stat();

  // These initializations *MUST* be called after init_config()
  // because modules depend on config values.
  for (i=0; mod_def[i]; i++)
  {
	struct s_module *module = &modules[i];
	mod_def[i](module);
  }
  for (i=0; cardsystem_def[i]; i++)
  {
	memset(&cardsystems[i], 0, sizeof(struct s_cardsystem));
	cardsystem_def[i](&cardsystems[i]);
  }
  for (i=0; cardreader_def[i]; i++)
  {
	memset(&cardreaders[i], 0, sizeof(struct s_cardreader));
	cardreader_def[i](&cardreaders[i]);
  }

  init_sidtab();
  init_readerdb();
  cfg.account = init_userdb();
  init_signal();
  init_srvid();
  init_tierid();
  init_provid();

  start_garbage_collector(gbdb);

  cacheex_init();

  init_len4caid();
  init_irdeto_guess_tab();

  write_versionfile(false);

  led_init();
  led_status_default();

  azbox_init();

  mca_init();

  global_whitelist_read();
  cacheex_load_config_file();

	for (i = 0; i < CS_MAX_MOD; i++) {
		struct s_module *module = &modules[i];
		if ((module->type & MOD_CONN_NET)) {
			for (j = 0; j < module->ptab.nports; j++) {
				start_listener(module, &module->ptab.ports[j]);
			}
		}
	}

	//set time for server to now to avoid 0 in monitor/webif
	first_client->last=time((time_t *)0);

	webif_init();

	start_thread((void *) &reader_check, "reader check");
	cw_process_thread_start();

	lcd_thread_start();

	do_report_emm_support();

	init_cardreader();

	cs_waitforcardinit();

	led_status_starting();

	ac_init();

	for (i = 0; i < CS_MAX_MOD; i++) {
		struct s_module *module = &modules[i];
		if ((module->type & MOD_CONN_SERIAL) && module->s_handler)
			module->s_handler(NULL, NULL, i);
	}

	// main loop function
	process_clients();

	cw_process_thread_wakeup(); // Stop cw_process thread
	pthread_cond_signal(&reader_check_sleep_cond); // Stop reader_check thread

	// Cleanup
	webif_close();
	azbox_close();
	coolapi_close_all();
	mca_close();

	led_status_stopping();
	led_stop();
	lcd_thread_stop();

	remove_versionfile();

	stat_finish();
	cccam_done_share();

	kill_all_clients();
	kill_all_readers();

	if (oscam_pidfile)
		unlink(oscam_pidfile);

	webif_tpls_free();
	init_free_userdb(cfg.account);
	cfg.account = NULL;
	init_free_sidtab();
	free_readerdb();
	free_irdeto_guess_tab();
	config_free();

	cs_log("cardserver down");
	log_free();

	stop_garbage_collector();

	free(first_client->account);
	free(first_client);

	// This prevents the compiler from removing config_mak from the final binary
	syslog_ident = config_mak;

	return exit_oscam;
}
Esempio n. 26
0
void init (int argc,char *argv[])
{
    struct lac *lac;
    struct in_addr listenaddr;
    int myRet=0;

    init_args (argc,argv);
    srand( time(NULL) );
    rand_source = 0;
    init_addr ();
    if (init_config ())
    {
        log (LOG_CRIT, "%s: Unable to load config file\n", __FUNCTION__);
        exit (1);
    }
    init_tunnel_list (&tunnels);
    if (init_network ())
        exit (1);
    //if (gconfig.daemon)
	//daemonize ();
    signal (SIGTERM, &death_handler);
    signal (SIGINT, &death_handler);
    signal (SIGCHLD, &child_handler);
    signal (SIGUSR1, &status_handler);
    signal (SIGHUP, &null_handler);
    init_scheduler ();

    unlink (gconfig.controlfile);
    myRet=mkfifo (gconfig.controlfile, 0600);
//    log (LOG_LOG,"gconfig.controlfile=%s, myRet=%d,errno=%d",gconfig.controlfile,myRet,errno);//Added for test
    if(myRet<0)
    {
    	 log (LOG_CRIT, "%s: Unable to mkfifo %s.",__FUNCTION__, gconfig.controlfile);
        exit (1);
    }
    control_fd = open (gconfig.controlfile, O_RDONLY | O_NONBLOCK, 0600);
    if (control_fd < 0)
    {
        log (LOG_CRIT, "%s: Unable to open %s for reading.",
             __FUNCTION__, gconfig.controlfile);
        exit (1);
    }
    log (LOG_LOG, "l2tpd version " SERVER_VERSION " started on %s PID:%d\n",
         hostname, getpid ());
    log (LOG_LOG,
         "Written by Mark Spencer, Copyright (C) 1998, Adtran, Inc.\n");
    log (LOG_LOG, "Forked by Scott Balmos and David Stipp, (C) 2001\n");
    log (LOG_LOG, "Inherited by Jeff McAdams, (C) 2002\n");
    listenaddr.s_addr = gconfig.listenaddr;
    log (LOG_LOG, "Listening on IP address %s, port %d\n",
	 inet_ntoa(listenaddr), gconfig.port);
    lac = laclist;
    while (lac)
    {
        if (lac->autodial)
        {
#ifdef DEBUG_MAGIC
            log (LOG_DEBUG, "%s: Autodialing '%s'\n", __FUNCTION__,
                 lac->entname[0] ? lac->entname : "(unnamed)");
#endif
            lac->active = -1;
            switch_io = 1;      /* If we're a LAC, autodials will be ICRQ's */
            magic_lac_dial (lac);
        }
        lac = lac->next;
    }
}
Esempio n. 27
0
File: util.c Progetto: umbrant/iowt
int main (int argc, char *argv[])
{
    int rv;
    // Read and initialize configuration settings
    init_config();


	request_t request;
	int dest;

    // Get local machine's eth0 ip address
    struct ifaddrs *ifaddress = NULL;
    getifaddrs(&ifaddress);
    for(getifaddrs(&ifaddress); ifaddress != NULL; ifaddress = ifaddress->ifa_next) {
        if(ifaddress->ifa_addr->sa_family == AF_INET) {
            if(!strcmp(ifaddress->ifa_name, "eth0")) {
                void* tmp_ptr = &((struct sockaddr_in *)ifaddress->ifa_addr)->sin_addr;
                inet_ntop(AF_INET, tmp_ptr, ipaddress, INET_ADDRSTRLEN);
                break; 
            }
        }
    }


    if(argc < 3) {
        usage();
        exit(1);
    }
    // Server
    if(strcmp(argv[1],"server") == 0) {
        // Init the mutexs used for determining filename
        pthread_mutex_init(&filecount_64_mutex, NULL);
        pthread_mutex_init(&filecount_256_mutex, NULL);
        // Init their counters too
        filecount_64_1 = 'a';
        filecount_64_2 = 'a';
        filecount_256 = 'a';
        NUM_WORKER_THREADS = atoi(argv[2]);
        pthread_t manager;
        // Create manager thread, which spans more handlers
        rv = pthread_create(&manager, NULL, manager_main, NULL);
        if(rv) {
            printf("Error, could not start server manager thread.\n");
            exit(-1);
        }
        pthread_join(manager, NULL);
    }
    // Client
    else if(strcmp(argv[1],"client") == 0) {
		make_request(argc, argv, &request, &dest);
        send_request(request, dest);
    }
    // Benchmark
    else if(strcmp(argv[1], "benchmark") == 0) {
        // Init crypt mutex
        pthread_mutex_init(&crypt_mutex, NULL);
        if(argc != 7) {
            usage();
        } else {
            // We have to pad argv/argc with a dummy destination
            // so make_request gets what it expects
            int targc = 8;
            char dummy_char = '0';
            char* targv[8];
            targv[0] = argv[0];
            targv[1] = &dummy_char; // unused
            targv[2] = argv[1];
            targv[3] = argv[2];
            targv[4] = argv[3];
            targv[5] = argv[4];
            targv[6] = argv[5];
            targv[7] = argv[6];
		    make_request(targc, targv, &request, &dest);
            int num_requests = atoi(argv[5]);
            int num_threads = atoi(argv[6]);
            benchmark(request, num_requests, num_threads);
        }
    }
    // Default to showing usage()
    else {
        usage();
    }
    pthread_exit(NULL);
}
Esempio n. 28
0
int main(int argc, char *argv[]) {
  pool *p;
  const char *remote_name;
  pr_netaddr_t *remote_addr;
  conn_t *client_conn, *ctrl_conn, *data_conn;
  unsigned int connect_timeout, remote_port;
  struct proxy_ftp_client *ftp;
  int res, timerno;
  char buf[1024];

  /* Seed the random number generator. */
  /* XXX Use random(3) in the future? */
  srand((unsigned int) (time(NULL) * getpid()));

  init_pools();
  init_privs();
  init_log();
  init_regexp();
  init_inet();
  init_netio();
  init_netaddr();
  init_fs();
  init_class();
  init_config();
  init_stash();

  pr_log_setdebuglevel(10);
  log_stderr(TRUE);
  pr_trace_use_stderr(TRUE);
  pr_trace_set_levels("DEFAULT", 1, 20);

  p = make_sub_pool(permanent_pool);
  pr_pool_tag(p, "FTP Client Pool");

  remote_name = "ftp.proftpd.org";

  remote_addr = pr_netaddr_get_addr(p, remote_name, NULL);
  if (remote_addr == NULL) {
    fprintf(stderr, "Failed to get addr for '%s': %s\n", remote_name,
      strerror(errno));
    destroy_pool(p);
    return 1;
  } 

  fprintf(stdout, "Resolved name '%s' to IP address '%s'\n", remote_name,
    pr_netaddr_get_ipstr(remote_addr));

  remote_port = 21;
  connect_timeout = 5;
  ftp = proxy_ftp_connect(p, remote_addr, remote_port, connect_timeout, NULL);
  if (ftp == NULL) {
    fprintf(stderr, "Error connecting to FTP server: %s\n", strerror(errno));
    destroy_pool(p);
    return 1;
  }

  fprintf(stdout, "Successfully connected to %s:%d from %s:%d\n", remote_name,
    remote_port, pr_netaddr_get_ipstr(client_conn->local_addr),
    ntohs(pr_netaddr_get_port(client_conn->local_addr)));

  res = proxy_ftp_disconnect(ftp);
  if (res < 0) {
    fprintf(stderr, "Error disconnecting from FTP server: %s\n",
      strerror(errno));
    destroy_pool(p);
    return 1;
  }

  ctrl_conn = pr_inet_openrw(p, client_conn, NULL, PR_NETIO_STRM_OTHR,
    -1, -1, -1, FALSE);
  if (ctrl_conn == NULL) {
    fprintf(stderr, "Error opening control connection: %s\n", strerror(errno));

    pr_inet_close(p, client_conn);
    destroy_pool(p);
    return 1;
  }

  fprintf(stdout, "Reading response from %s:%d\n", remote_name, remote_port);

  /* Read the response */
  memset(buf, '\0', sizeof(buf));

  /* XXX We need to write our own version of netio_telnet_gets(), with
   * the buffering to handle reassembly of a full FTP response out of
   * multiple TCP packets.  Not sure why the existing netio_telnet_gets()
   * is not sufficient.  But we don't need the handling of Telnet codes
   * in our reading.  But DO generate the 'core.ctrl-read' event, so that
   * any event listeners get a chance to process the data we've received.
   * (Or maybe use 'mod_proxy.server-read', and differentiate between
   * client and server reads/writes?)
   */
  if (pr_netio_read(ctrl_conn->instrm, buf, sizeof(buf)-1, 5) < 0) {
    fprintf(stderr, "Error reading response from server: %s\n",
      strerror(errno));

  } else {
    fprintf(stdout, "Response: \"%s\"\n", buf);
  }

  /* Disconnect */
  res = pr_netio_printf(ctrl_conn->outstrm, "%s\r\n", C_QUIT);
  if (res < 0) {
    fprintf(stderr, "Error writing command to server: %s", strerror(errno));
  }

  pr_inet_close(p, ctrl_conn);
  pr_inet_close(p, client_conn);
  destroy_pool(p);
  return 0;
}
Esempio n. 29
0
int 
main(int argc, char *argv[])
{
  int            x; 
  int            result;
  DATA           D    = new_data();
  ARRAY          urls = new_array();
  CREW           crew;  
  LINES          *lines;   
  CLIENT         *client; 
  pthread_t      cease; 
  pthread_t      timer;  
  pthread_attr_t scope_attr; 
  void *statusp;
  sigset_t sigs;

  sigemptyset(&sigs);
  sigaddset(&sigs, SIGHUP);
  sigaddset(&sigs, SIGINT);
  sigaddset(&sigs, SIGALRM);
  sigaddset(&sigs, SIGTERM);
  sigprocmask(SIG_BLOCK, &sigs, NULL);

  lines = xcalloc(1, sizeof *lines);
  lines->index   = 0;
  lines->line    = NULL;

  memset(&my, 0, sizeof(struct CONFIG));

  parse_rc_cmdline(argc, argv); 
  if (init_config() < 0) {      /* defined in init.h   */
    exit( EXIT_FAILURE );       /* polly was a girl... */
  } 
  parse_cmdline(argc, argv);    /* defined above       */
  ds_module_check();            /* check config integ  */

  /**
   * XXX: we should consider moving the following
   * if-checks into the ds_module_check
   */

  if (my.config) {
    show_config(TRUE);    
  }

  if (my.url != NULL) {
    my.length = 1; 
  } else { 
    my.length = read_cfg_file(lines, my.file); 
  }

  if (my.reps < 0) {
    my.reps = my.length;
  }

  if (my.length == 0) { 
    display_help();
  }

  /* cookie is an EXTERN, defined in setup */ 
  cookie = xcalloc(sizeof(COOKIE), 1); 
  cookie->first = NULL;
  if ((result = pthread_mutex_init( &(cookie->mutex), NULL)) !=0) {
    NOTIFY(FATAL, "pthread_mutex_init" );
  } 

  /* memory allocation for threads and clients */
  client = xcalloc(my.cusers, sizeof(CLIENT));
  if ((crew = new_crew(my.cusers, my.cusers, FALSE)) == NULL) {
    NOTIFY(FATAL, "unable to allocate memory for %d simulated browser", my.cusers);  
  }

  /** 
   * determine the source of the url(s),
   * command line or file, and add them
   * to the urls struct.
   */

  if (my.url != NULL) {
    URL tmp = new_url(my.url);
    url_set_ID(tmp, 0);
    if (my.get && url_get_method(tmp) != POST && url_get_method(tmp) != PUT) {
      url_set_method(tmp, my.method); 
    }
    array_npush(urls, tmp, URLSIZE); // from cmd line
  } else { 
    for (x = 0; x < my.length; x++) {
      URL tmp = new_url(lines->line[x]);
      url_set_ID(tmp, x);
      array_npush(urls, tmp, URLSIZE);
    }
  } 

  /**
   * display information about the siege
   * to the user and prepare for verbose 
   * output if necessary.
   */
  if (!my.get && !my.quiet) {
    fprintf(stderr, "** "); 
    display_version(FALSE);
    fprintf(stderr, "** Preparing %d concurrent users for battle.\n", my.cusers);
    fprintf(stderr, "The server is now under siege...");
    if (my.verbose) { fprintf(stderr, "\n"); }
  }

  /**
   * record start time before spawning threads
   * as the threads begin hitting the server as
   * soon as they are created.
   */
  data_set_start(D);

  /**
   * for each concurrent user, spawn a thread and
   * loop until condition or pthread_cancel from the
   * handler thread.
   */
  pthread_attr_init(&scope_attr);
  pthread_attr_setscope(&scope_attr, PTHREAD_SCOPE_SYSTEM);
#if defined(_AIX)
  /* AIX, for whatever reason, defies the pthreads standard and  *
   * creates threads detached by default. (see pthread.h on AIX) */
  pthread_attr_setdetachstate(&scope_attr, PTHREAD_CREATE_JOINABLE);
#endif

  /** 
   * invoke OpenSSL's thread safety
   */
#ifdef HAVE_SSL
  SSL_thread_setup();
#endif

  /**
   * create the signal handler and timer;  the
   * signal handler thread (cease) responds to
   * ctrl-C (sigterm) and the timer thread sends
   * sigterm to cease on time out.
   */
  if ((result = pthread_create(&cease, NULL, (void*)sig_handler, (void*)crew)) < 0) {
    NOTIFY(FATAL, "failed to create handler: %d\n", result);
  }
  if (my.secs > 0) {
    if ((result = pthread_create(&timer, NULL, (void*)siege_timer, (void*)cease)) < 0) {
      NOTIFY(FATAL, "failed to create handler: %d\n", result);
    } 
  }

  /**
   * loop until my.cusers and create a corresponding thread...
   */  
  for (x = 0; x < my.cusers && crew_get_shutdown(crew) != TRUE; x++) {
    client[x].id              = x; 
    client[x].bytes           = 0;
    client[x].time            = 0.0;
    client[x].hits            = 0;
    client[x].code            = 0;
    client[x].ok200           = 0;   
    client[x].fail            = 0; 
    client[x].urls            = urls;
    client[x].auth.www        = 0;
    client[x].auth.proxy      = 0;
    client[x].auth.type.www   = BASIC;
    client[x].auth.type.proxy = BASIC;
    client[x].rand_r_SEED     = urandom();
    result = crew_add(crew, (void*)start_routine, &(client[x]));
    if (result == FALSE) { 
      my.verbose = FALSE;
      fprintf(stderr, "Unable to spawn additional threads; you may need to\n");
      fprintf(stderr, "upgrade your libraries or tune your system in order\n"); 
      fprintf(stderr, "to exceed %d users.\n", my.cusers);
      NOTIFY(FATAL, "system resources exhausted"); 
    }
  } /* end of for pthread_create */

  crew_join(crew, TRUE, &statusp);

#ifdef HAVE_SSL
  SSL_thread_cleanup();
#endif

  /**
   * collect all the data from all the threads that
   * were spawned by the run.
   */
  for (x = 0; x < ((crew_get_total(crew) > my.cusers || 
                    crew_get_total(crew)==0 ) ? my.cusers : crew_get_total(crew)); x++) {
    data_increment_count(D, client[x].hits);
    data_increment_bytes(D, client[x].bytes);
    data_increment_total(D, client[x].time);
    data_increment_code (D, client[x].code);
    data_increment_ok200(D, client[x].ok200);
    data_increment_fail (D, client[x].fail);
    data_set_highest    (D, client[x].himark);
    data_set_lowest     (D, client[x].lomark);
    client[x].rand_r_SEED = urandom();
  } /* end of stats accumulation */
  
  /**
   * record stop time
   */
  data_set_stop(D);

  /**
   * cleanup crew
   */ 
  crew_destroy(crew);

  for (x = 0; x < my.cusers; x++) {
    // XXX: TODO
    //digest_challenge_destroy(client[x].auth.wwwchlg);
    //digest_credential_destroy(client[x].auth.wwwcred);
    //digest_challenge_destroy(client[x].auth.proxychlg);
    //digest_credential_destroy(client[x].auth.proxycred);
  }
  array_destroy(my.lurl);
  xfree(client);

  if (my.get) {
    if (data_get_ok200(D) > 0) {
       exit(EXIT_SUCCESS);
    } else {
      if (!my.quiet) echo("[done]\n");
      exit(EXIT_FAILURE);
    }
  }

  /**
   * take a short nap  for  cosmetic  effect
   * this does NOT affect performance stats.
   */
  pthread_usleep_np(10000);
  if (my.verbose)
    fprintf(stderr, "done.\n");
  else
    fprintf(stderr, "\b      done.\n");

  /**
   * prepare and print statistics.
   */
  if (my.failures > 0 && my.failed >= my.failures) {
    fprintf(stderr, "%s aborted due to excessive socket failure; you\n", program_name);
    fprintf(stderr, "can change the failure threshold in $HOME/.%src\n", program_name);
  }
  fprintf(stderr, "\nTransactions:\t\t%12u hits\n",        data_get_count(D));
  fprintf(stderr, "Availability:\t\t%12.2f %%\n",          data_get_count(D)==0 ? 0 :
                                                           (double)data_get_count(D) /
                                                           (data_get_count(D)+my.failed)
                                                           *100
  );
  fprintf(stderr, "Elapsed time:\t\t%12.2f secs\n",        data_get_elapsed(D));
  fprintf(stderr, "Data transferred:\t%12.2f MB\n",        data_get_megabytes(D)); /*%12llu*/
  fprintf(stderr, "Response time:\t\t%12.3f secs\n",       data_get_response_time(D));
  fprintf(stderr, "Transaction rate:\t%12.2f trans/sec\n", data_get_transaction_rate(D));
  fprintf(stderr, "Throughput:\t\t%12.2f MB/sec\n",        data_get_throughput(D));
  fprintf(stderr, "Concurrency:\t\t%12.2f\n",              data_get_concurrency(D));
  fprintf(stderr, "Successful transactions:%12u\n",        data_get_code(D)); 
  if (my.debug) {
    fprintf(stderr, "HTTP OK received:\t%12u\n",             data_get_ok200(D));
  }
  fprintf(stderr, "Failed transactions:\t%12u\n",          my.failed);
  fprintf(stderr, "Longest transaction:\t%12.3f\n",        data_get_highest(D));
  fprintf(stderr, "Shortest transaction:\t%12.3f\n",       data_get_lowest(D));
  fprintf(stderr, " \n");
  if(my.mark)    mark_log_file(my.markstr);
  if(my.logging) log_transaction(D);

  data_destroy(D);
  if (my.url == NULL) {
    for (x = 0; x < my.length; x++)
      xfree(lines->line[x]);
    xfree(lines->line);
    xfree(lines);
  } else {
    xfree(lines->line);
    xfree(lines);
  }

  pthread_mutex_destroy( &(cookie->mutex));

  /** 
   * I should probably take a deeper look 
   * at cookie content to free it but at 
   * this point we're two lines from exit
   */
  xfree (cookie);
  xfree (my.url);

  exit(EXIT_SUCCESS);  
} /* end of int main **/
Esempio n. 30
0
int main(int argc, char *argv[])
{
	int 				policy;
	struct 	sched_param param;
	pthread_attr_t 		attr;
	char				buffer[1024];
	int 				err;

	dprintf("init\n");
	if(argc != 2) {
		perr(AR_ERR_BAD_INIT_PARAM);
		printf("Useage: %s INSTANCE\n", AR_MODULE_NAME);
		return(AR_ERR_BAD_INIT_PARAM);
	}

	memset(&config, 0, sizeof(config));
	erret(init_config(AR_MODULE_NAME, atoi(argv[1]), &config.base));
	erret(read_config_int(config.base.name, 	"PRIORITY", &config.priority));
	erret(read_config_int(config.base.name, 	"PRIORITY_DGPS_CORR_DATA", &config.priority_dgps_corr_data));
	erret(read_config_string(config.base.name,	"DEVICE", config.ser_device, sizeof(config.ser_device)));
	err = read_config_int_tab(config.base.name, "QUEUE_INDEX", "QUEUE_IN_GPS_CORR", &config.queue_corr_data);
	if(err != 0) {
		erret(read_config_string(config.base.name,	"DEVICE_CORR_DATA_READ", config.ser_device_corr_data_read, sizeof(config.ser_device_corr_data_read)));
//		fprintf(stderr, "DGPS correction data from ser. device <%s>\n", config.ser_device_corr_data_read);
	} else {
//		fprintf(stderr, "DGPS correction data from queue <%d>\n", config.queue_corr_data);
	}
	memset(buffer, 0, sizeof(buffer));
	config.corr_mode = -1;
	erret(read_config_string(config.base.name,	"CORRECTION_MODE", buffer, sizeof(buffer)));
	if(strnicmp(buffer, "RTCA", strlen("RTCA")) == 0) {
		config.corr_mode = OEM4_RTCA_MODE;
	} else if(strnicmp(buffer, "RTCM", strlen("RTCM")) == 0) {
		config.corr_mode = OEM4_RTCM_MODE;
	} else {
		perrs(AR_ERR_BAD_INIT_PARAM, "Correction data mode not specified (RTCA | RTCM).");
	//	return(AR_ERR_BAD_INIT_PARAM);
	}
	erret(read_config_int_tab(config.base.name, "SHM_INDEX", "SHM_OUT_GPS_POS",	&config.ishm_pos_out));
	erret(read_config_int_tab(config.base.name, "SHM_INDEX", "SHM_OUT_GPS_VEL",	&config.ishm_vel_out));
	if(read_config_int(config.base.name, "UTC_OFFSET", &config.utc_offset)) {
		config.utc_offset = 15;
	}

	erret(SHM_Init());
	erret(SHM_InitSlot(config.ishm_pos_out, sizeof(gps_pos_novatel_t)));
	erret(SHM_InitSlot(config.ishm_vel_out, sizeof(gps_vel_novatel_t)));

	if(config.queue_corr_data != 0) {
		erret(Q_Init());
		erret(Q_InitSlot(config.queue_corr_data, sizeof(gps_corr_t), MAX_GPS_CORRECTION_Q_ITEMS_NUMBER, 1));
	} else if (strlen(config.ser_device_corr_data_read)>0){
		erret(open_comport(&fd_corr_data_read, config.ser_device_corr_data_read, O_RDWR, 115200));
	}

	erret(open_comport(&fd, config.ser_device, O_RDWR, 57600));
	if(0){
		struct termios 	termios_p;
		if(tcgetattr(fd, &termios_p)==0) {
			termios_p.c_cc[VTIME] = 1; // 2*0.1s = 0.2s
			termios_p.c_cc[VMIN] = 0;
			tcsetattr(fd, TCSADRAIN, &termios_p);
		} else fprintf(stderr, "failed to set read timeout\n");
	}


	//create thread for reading and writing of the correction data:
	ifret(pthread_getschedparam(pthread_self(), &policy, &param), AR_ERR_SYS_RESOURCES);
	param.sched_priority = config.priority_dgps_corr_data;
	pthread_attr_init( &attr );
	ifret(pthread_attr_setschedparam(&attr, &param), AR_ERR_SYS_RESOURCES);
	ifret(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED), AR_ERR_SYS_RESOURCES);
	ifret(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED), AR_ERR_SYS_RESOURCES);
	if(config.corr_mode == OEM4_RTCA_MODE) {
		ifret(write(fd, OEM4_INIT_ROVER_RTCA, strlen(OEM4_INIT_ROVER_RTCA))==-1, AR_ERR_IO_ERROR);
		ifret(pthread_create(&pthreads[0], &attr, &corr_data_thread_func, NULL), AR_ERR_SYS_RESOURCES);
	} else if(config.corr_mode == OEM4_RTCM_MODE) {
		ifret(write(fd, OEM4_INIT_ROVER_RTCM, strlen(OEM4_INIT_ROVER_RTCM))==-1, AR_ERR_IO_ERROR);
		ifret(pthread_create(&pthreads[0], &attr, &corr_data_thread_func, NULL), AR_ERR_SYS_RESOURCES);
	} else
	{
		ifret(write(fd, OEM4_INIT_ROVER_COM1, strlen(OEM4_INIT_ROVER_COM1))==-1, AR_ERR_IO_ERROR);
		printf("running without differential data\n");
	}


	ifret(pthread_getschedparam(pthread_self(), &policy, &param), AR_ERR_SYS_RESOURCES);
	param.sched_priority = config.priority;
	ifret(pthread_setschedparam(pthread_self(), policy, &param), AR_ERR_SYS_RESOURCES);
	while(1) {
		errp(read_data());
	}
	return 0;
}