Exemplo n.º 1
0
int main(int argc, char *argv[])
{
    struct match *list, *match;
    struct pci_domain *pci_domain;

    openconsole(&dev_null_r, &dev_stdcon_w);
    pci_domain = pci_scan();

    if (pci_domain) {
	list = parse_config(argc < 2 ? NULL : argv[1]);

	match = find_pci_device(pci_domain, list);

	if (match)
	    syslinux_run_command(match->filename);
    }

    /* On error, return to the command line */
    fputs("Error: no recognized network card found!\n", stderr);
    return 1;
}
Exemplo n.º 2
0
static int load_module(void)
{
	int res = 0;

	if (parse_config(0))
		return AST_MODULE_LOAD_DECLINE;

	res |= ast_register_translator(&speextolin);
	res |= ast_register_translator(&lintospeex);
	res |= ast_register_translator(&speexwbtolin16);
	res |= ast_register_translator(&lin16tospeexwb);
	res |= ast_register_translator(&speexuwbtolin32);
	res |= ast_register_translator(&lin32tospeexuwb);

	if (res) {
		unload_module();
		return res;
	}

	return res;
}
Exemplo n.º 3
0
int init_config ()
{
    FILE *f;
    int returnedValue;

    gconfig.port = UDP_LISTEN_PORT;
    gconfig.sarefnum = IP_IPSEC_REFINFO; /* default use the latest we know */
    gconfig.listenaddr = htonl(INADDR_ANY); /* Default is to bind (listen) to all interfaces */
    gconfig.debug_avp = 0;
    gconfig.debug_network = 0;
    gconfig.packet_dump = 0;
    gconfig.debug_tunnel = 0;
    gconfig.debug_state = 0;
    lnslist = NULL;
    laclist = NULL;
    deflac = (struct lac *) calloc (1, sizeof (struct lac));

    f = fopen (gconfig.configfile, "r");
    if (!f) 
    {
        f = fopen (gconfig.altconfigfile, "r");
        if (f)
        {
	     l2tp_log (LOG_WARNING, "%s: Using old style config files %s and %s\n",
		__FUNCTION__, gconfig.altconfigfile, gconfig.altauthfile);
            strncpy (gconfig.authfile, gconfig.altauthfile, 
            	sizeof (gconfig.authfile));
        }
        else
        {
            l2tp_log (LOG_CRIT, "%s: Unable to open config file %s or %s\n",
                 __FUNCTION__, gconfig.configfile, gconfig.altconfigfile);
            return -1;
        }

    }
    returnedValue = parse_config (f);
    fclose (f);
    return (returnedValue);
}
Exemplo n.º 4
0
int lxc_read_seccomp_config(struct lxc_conf *conf)
{
	FILE *f;
	int ret;

	if (!conf->seccomp)
		return 0;

#if HAVE_SCMP_FILTER_CTX
	/* XXX for debug, pass in SCMP_ACT_TRAP */
	conf->seccomp_ctx = seccomp_init(SCMP_ACT_ERRNO(31));
	ret = !conf->seccomp_ctx;
#else
	ret = seccomp_init(SCMP_ACT_ERRNO(31)) < 0;
#endif
	if (ret) {
		ERROR("failed initializing seccomp");
		return -1;
	}

	/* turn of no-new-privs.  We don't want it in lxc, and it breaks
	 * with apparmor */
	if (seccomp_attr_set(
#if HAVE_SCMP_FILTER_CTX
			conf->seccomp_ctx,
#endif
			SCMP_FLTATR_CTL_NNP, 0)) {
		ERROR("failed to turn off n-new-privs\n");
		return -1;
	}

	f = fopen(conf->seccomp, "r");
	if (!f) {
		SYSERROR("failed to open seccomp policy file %s\n", conf->seccomp);
		return -1;
	}
	ret = parse_config(f, conf);
	fclose(f);
	return ret;
}
Exemplo n.º 5
0
Arquivo: main.c Projeto: stm2/server
int main(int argc, char **argv)
{
    int err = 0;
    lua_State *L;
    setup_signal_handler();
    /* ini file sets defaults for arguments*/
    parse_config(inifile);
    if (!global.inifile) {
        log_error("could not open ini configuration %s\n", inifile);
    }
    /* parse arguments again, to override ini file */
    parse_args(argc, argv, &err);

    log_open(logfile);
    locale_init();

#ifdef CRTDBG
    init_crtdbg();
#endif

    L = lua_init();
    game_init();
    bind_monsters(L);
    err = eressea_run(L, luafile);
    if (err) {
        log_error("script %s failed with code %d\n", luafile, err);
        return err;
    }
#ifdef MSPACES
    malloc_stats();
#endif

    game_done();
    lua_done(L);
    log_close();
    if (global.inifile) {
        iniparser_freedict(global.inifile);
    }
    return 0;
}
Exemplo n.º 6
0
terrain_builder::terrain_builder(const config& level,
		const gamemap* m, const std::string& offmap_image) :
	map_(m),
	tile_map_(map().w(), map().h()),
	terrain_by_type_()
{
	image::precache_file_existence("terrain/");

	if(building_rules_.empty() && rules_cfg_){
		// parse global terrain rules
		parse_global_config(*rules_cfg_);
	} else {
		// use cached global rules but clear local rules
		flush_local_rules();
	}

	// parse local rules
	parse_config(level);
	add_off_map_rule(offmap_image);

	build_terrains();
}
Exemplo n.º 7
0
Arquivo: config.c Projeto: Aconex/pcp
void
read_config(FILE *conf)
{
    struct stat stat_buf;
    long size;
    int sts;
    size_t nread;

    /* get length of file */
    sts = fstat(fileno(conf), &stat_buf);
    if (sts < 0) {
	(void)fprintf(stderr, "%s: Failure to stat configuration file \"%s\": %s\n",
	    pmProgname, configfile, osstrerror());
	exit(1);
    }
    size = (long)stat_buf.st_size;

    /* create buffer */
    conf_buffer = (char*)malloc(size+1*sizeof(char));
    if (conf_buffer == NULL) {
	(void)fprintf(stderr, "%s: Failure to create buffer for configuration file \"%s\"\n",
	    pmProgname, configfile);
	exit(1);
    }

    conf_buffer_ptr = conf_buffer;

    /* read whole file into buffer */
    nread = fread(conf_buffer, sizeof(char), size, conf);
    if (nread != size) {
	(void)fprintf(stderr, "%s: Failure to read configuration file \"%s\" into buffer\n",
	    pmProgname, configfile);
	exit(1);
    }
    conf_buffer[size] = '\0'; /* terminate the buffer */

    if (parse_config(&the_tree) != 0)
        exit(1);
}
Exemplo n.º 8
0
int main(int ac, char *av[]) {
  int rv = 0;

  int sfd = setup_signalfd();

  struct config *config = parse_config("amtredird.ini");
  if (config && validate_config(config)) {
    if (init_amt(config)) {
      if (sfd != -1) {
        rv = (run_server(config, sfd) == 0);
      } else {
        rv = 1;
      }
      teardown_amt(config);
    }
  } else {
    rv = 1;
  }
  close(sfd);
  free_config(config);
  return rv;
}
Exemplo n.º 9
0
Arquivo: main.c Projeto: bastianh/tg
int main (int argc, char **argv) {
  signal (SIGSEGV, sig_segv_handler);
  signal (SIGABRT, sig_abrt_handler);

  log_level = 10;
  
  args_parse (argc, argv);
  printf (
    "Telegram-client version " TG_VERSION ", Copyright (C) 2013 Vitaly Valtman\n"
    "Telegram-client comes with ABSOLUTELY NO WARRANTY; for details type `show_license'.\n"
    "This is free software, and you are welcome to redistribute it\n"
    "under certain conditions; type `show_license' for details.\n"
  );
  running_for_first_time ();
  parse_config ();


  get_terminal_attributes ();

  #ifdef USE_LUA
  if (lua_file) {
    lua_init (lua_file);
  }
  #endif

  #ifdef USE_PYTHON
  if (python_file) {
    python_init(python_file);
  }
  #endif
  inner_main ();
  
  #ifdef USE_PYTHON
  if (python_file) {
    python_finalize();
  }
  #endif
  return 0;
}
Exemplo n.º 10
0
char *
conf_aliases(char *cfgpath)
{
	struct table	*table;
	char		*path;
	char		*p;

	if (parse_config(env, cfgpath, 0))
		exit(1);

	table = table_find("aliases", NULL);
	if (table == NULL)
		return (PATH_ALIASES);

	path = xstrdup(table->t_config, "conf_aliases");
	p = strstr(path, ".db");
	if (p == NULL || strcmp(p, ".db") != 0) {
		return (path);
	}
	*p = '\0';
	return (path);
}
Exemplo n.º 11
0
int main(int argc, char **argv)
{
    if (argc < 2)
    {
        printf("argc < 2\n");
        return 0;
    }

    if (0 != parse_config(argv[1]))
        return 0;

    //fio_register_handler(FIO_CBF_SINGLE_THREAD, single_mode_handle);
    //fio_register_handler(IPPROTO_UDP, handle_audp);
    switch (sysconfig.single_thread)
    {
        case FIO_MODE_1_SND_OR_RCV /*2*/:
            fio_register_handler(T_FIO_PKT_INTD, handle_dns_resp);
            break;
        case FIO_MODE_2CARDS /*3*/:
            fio_register_handler(T_FIO_PKT_INTD, handle_udps_2cards);
            break;
        case FIO_MODE_N_BRG_OUT /*4*/:
            fio_register_handler(T_FIO_PKT_INTD, handle_udps);
            break;
        default:
            fio_register_handler(T_FIO_PKT_INTD, handle_udps_in);
            break;
    }

    if (0 != fio_init() || 0 != fio_start())
        return 0;
	signal(SIGINT, fio_sigint_h);
    fio_start_statistics();

    fio_wait();
    fio_shutdown();

    return 0;
}
Exemplo n.º 12
0
/*
 * Initialize slog library. Function parses config file and reads log 
 * level and save to file flag from config. First argument is file name 
 * where log will be saved and second argument conf is config file path 
 * to be parsedand third argument lvl is log level for this message.
 */
void slog_init(const char* fname, const char* conf, int lvl, int flvl, int t_safe)
{
    int status = 0;

    /* Set up default values */
    slg.level = lvl;
    slg.file_level = flvl;
    slg.to_file = 0;
    slg.pretty = 0;
    slg.filestamp = 1;
    slg.td_safe = t_safe;

    /* Init mutex sync */
    if (t_safe)
    {
        /* Init mutex attribute */
        pthread_mutexattr_t m_attr;
        if (pthread_mutexattr_init(&m_attr) ||
            pthread_mutexattr_settype(&m_attr, PTHREAD_MUTEX_RECURSIVE) ||
            pthread_mutex_init(&slog_mutex, &m_attr) ||
            pthread_mutexattr_destroy(&m_attr))
        {
            printf("<%s:%d> %s: [ERROR] Can not initialize mutex: %d\n", 
                __FILE__, __LINE__, __FUNCTION__, errno);
            slg.td_safe = 0;
        }
    }

    /* Parse config file */
    if (conf != NULL) 
    {
        slg.fname = fname;
        status = parse_config(conf);
    }

    /* Handle config parser status */
    if (!status) slog(0, SLOG_INFO, "Initializing logger values without config");
    else slog(0, SLOG_INFO, "Loading logger config from: %s", conf);
}
Exemplo n.º 13
0
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);
    }
}
Exemplo n.º 14
0
 bool Config::read_from_sd()
 {
     Serial.print("Reading config from '");
     Serial.print(CONFIG_FILE);
     Serial.println("'...");
     
     File configFile = SD.open(CONFIG_FILE);
     if(!configFile) {
         Serial.print("Unable to open config file '");
         Serial.print(CONFIG_FILE);
         Serial.println("'!");
         return false;
     }
     
     String config;
     while(configFile.available()) {
         config += configFile.readString();
     }
     
     configFile.close();
     
     return parse_config(config);
 }
Exemplo n.º 15
0
static struct acl_data* load_acl(const char* config, struct plugin_handle* handle)
{

	struct acl_data* data = parse_config(config);

	if (!data)
		return 0;

	if (!data->file || !*data->file)
	{
		free_acl(data); data = 0;
		set_error_message(handle, "No configuration file given, missing \"file=<filename>\" configuration option.");
		return 0;
	}

	if (file_read_lines(data->file, data->users, &parse_line) == -1)
	{
		fprintf(stderr, "Unable to load %s\n", data->file);
		set_error_message(handle, "Unable to load file");
	}

	return data;
}
Exemplo n.º 16
0
void main_initialize(char *arg1, char *arg2) {
    struct stat st; /* buffer for stat */

    ssl_init(); /* initialize SSL library */
    sthreads_init(); /* initialize critical sections & SSL callbacks */
    parse_config(arg1, arg2);
    log_open();
    s_log(LOG_NOTICE, "%s", stunnel_info());

    /* check if certificate exists */
    if(!options.key) /* key file not specified */
        options.key=options.cert;
    if(options.option.cert) {
        if(stat(options.key, &st)) {
            ioerror(options.key);
            exit(1);
        }
#ifndef USE_WIN32
        if(st.st_mode & 7)
            s_log(LOG_WARNING, "Wrong permissions on %s", options.key);
#endif /* defined USE_WIN32 */
    }
}
Exemplo n.º 17
0
static void traverse_layout(GenerateWebsiteWorkspace *workspace, xmlNodePtr node) {
    CongNodePtr child;

    g_assert(node);

    g_message("traverse_layout <%s>", node->name);

    for (child=node->children; child; child=child->next) {
        if (cong_node_is_element(child, NULL, "config")) {
            parse_config(workspace, child);
        } else if (cong_node_is_element(child, NULL, "copyright")) {
            parse_copyright(workspace, child);
        } else if (cong_node_is_element(child, NULL, "headlink")) {
            parse_headlink(workspace, child);
        } else if (cong_node_is_element(child, NULL, "style")) {
            parse_style(workspace, child);
        } else if (cong_node_is_element(child, NULL, "toc")) {
            parse_toc(workspace, child);
        } else if (cong_node_is_element(child, NULL, "notoc")) {
            parse_notoc(workspace, child);
        }
    }
}
Exemplo n.º 18
0
int tmain (int argc, char **argv) {
//  signal (SIGSEGV, sig_segv_handler);
//  signal (SIGABRT, sig_abrt_handler);

  log_level = 10;

  args_parse (argc, argv);
  running_for_first_time ();
  parse_config ();


  get_terminal_attributes ();

  #ifdef USE_LUA
  if (lua_file) {
    lua_init (lua_file);
  }
  #endif

  inner_main ();

  return 0;
}
Exemplo n.º 19
0
void terrain_builder::add_off_map_rule(const std::string& image)
{
	// Build a config object
	config cfg;

	config &item = cfg.add_child("terrain_graphics");

	config &tile = item.add_child("tile");
	tile["x"] = "0";
	tile["y"] = "0";
	tile["type"] = t_translation::write_terrain_code(t_translation::OFF_MAP_USER);

	config &tile_image = tile.add_child("image");
	tile_image["layer"] = "-1000";
	tile_image["name"] = image;

	item["probability"] = "100";
	item["no_flag"] = "base";
	item["set_flag"] = "base";

	// Parse the object
	parse_config(cfg);
}
Exemplo n.º 20
0
int main(int argc, char **argv)
{
    int err = 0;
    lua_State *L;
    dictionary *d = 0;
    setup_signal_handler();
    message_handle_missing(MESSAGE_MISSING_REPLACE);
    /* parse arguments again, to override ini file */
    err = parse_args(argc, argv);
    if (err != 0) {
        return (err > 0) ? 0 : err;
    }
    d = parse_config(inifile);
    if (!d) {
        log_error("could not open ini configuration %s\n", inifile);
    }

    locale_init();

    L = lua_init(d);
    game_init();
    bind_monsters(L);
    err = eressea_run(L, luafile);
    if (err) {
        log_error("script %s failed with code %d\n", luafile, err);
        return err;
    }
    game_done();
    lua_done(L);
    log_close();
    stats_write(stdout, "");
    stats_close();
    if (d) {
        iniparser_freedict(d);
    }
    return 0;
}
Exemplo n.º 21
0
Arquivo: fifo.c Projeto: 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;
  }
Exemplo n.º 22
0
static int load_module(void)
{
	int res = 0;

	if (parse_config(0))
		return AST_MODULE_LOAD_DECLINE;


	ast_format_set(&speextolin.src_format, AST_FORMAT_SPEEX, 0);
	ast_format_set(&speextolin.dst_format, AST_FORMAT_SLINEAR, 0);

	ast_format_set(&lintospeex.src_format, AST_FORMAT_SLINEAR, 0);
	ast_format_set(&lintospeex.dst_format, AST_FORMAT_SPEEX, 0);

	ast_format_set(&speexwbtolin16.src_format, AST_FORMAT_SPEEX16, 0);
	ast_format_set(&speexwbtolin16.dst_format, AST_FORMAT_SLINEAR16, 0);

	ast_format_set(&lin16tospeexwb.src_format, AST_FORMAT_SLINEAR16, 0);
	ast_format_set(&lin16tospeexwb.dst_format, AST_FORMAT_SPEEX16, 0);

	ast_format_set(&speexuwbtolin32.src_format, AST_FORMAT_SPEEX32, 0);
	ast_format_set(&speexuwbtolin32.dst_format, AST_FORMAT_SLINEAR32, 0);

	ast_format_set(&lin32tospeexuwb.src_format, AST_FORMAT_SLINEAR32, 0);
	ast_format_set(&lin32tospeexuwb.dst_format, AST_FORMAT_SPEEX32, 0);

	res |= ast_register_translator(&speextolin);
	res |= ast_register_translator(&lintospeex);
	res |= ast_register_translator(&speexwbtolin16);
	res |= ast_register_translator(&lin16tospeexwb);
	res |= ast_register_translator(&speexuwbtolin32);
	res |= ast_register_translator(&lin32tospeexuwb);


	return res;
}
Exemplo n.º 23
0
static int load_module(void)
{
	if(!parse_config())
		return AST_MODULE_LOAD_DECLINE;

	ast_mutex_lock(&pgsql_lock);

	if (!pgsql_reconnect(NULL)) {
		ast_log(LOG_WARNING,
				"Postgresql RealTime: Couldn't establish connection. Check debug.\n");
		ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
				PQerrorMessage(pgsqlConn));
	}

	ast_config_engine_register(&pgsql_engine);
	if (option_verbose) {
		ast_verbose("Postgresql RealTime driver loaded.\n");
	}
	ast_cli_register_multiple(cli_realtime, sizeof(cli_realtime) / sizeof(struct ast_cli_entry));

	ast_mutex_unlock(&pgsql_lock);

	return 0;
}
Exemplo n.º 24
0
bool
reload_config(t_configuration_options *orig_options)
{
	PGconn	   *conn;
	t_configuration_options new_options;
	bool	  config_changed = false;

	/*
	 * Re-read the configuration file: repmgr.conf
	 */
	log_info(_("reloading configuration file and updating repmgr tables\n"));

	parse_config(&new_options);
	if (new_options.node == -1)
	{
		log_warning(_("unable to parse new configuration, retaining current configuration\n"));
		return false;
	}

	if (strcmp(new_options.cluster_name, orig_options->cluster_name) != 0)
	{
		log_warning(_("unable to change cluster name, retaining current configuration\n"));
		return false;
	}

	if (new_options.node != orig_options->node)
	{
		log_warning(_("unable to change node ID, retaining current configuration\n"));
		return false;
	}

	if (strcmp(new_options.node_name, orig_options->node_name) != 0)
	{
		log_warning(_("unable to change standby name, keeping current configuration\n"));
		return false;
	}

	if (new_options.failover != MANUAL_FAILOVER && new_options.failover != AUTOMATIC_FAILOVER)
	{
		log_warning(_("new value for 'failover' must be 'automatic' or 'manual'\n"));
		return false;
	}

	if (new_options.master_response_timeout <= 0)
	{
		log_warning(_("new value for 'master_response_timeout' must be greater than zero\n"));
		return false;
	}

	if (new_options.reconnect_attempts < 0)
	{
		log_warning(_("new value for 'reconnect_attempts' must be zero or greater\n"));
		return false;
	}

	if (new_options.reconnect_interval < 0)
	{
		log_warning(_("new value for 'reconnect_interval' must be zero or greater\n"));
		return false;
	}

	if (strcmp(orig_options->conninfo, new_options.conninfo) != 0)
	{
		/* Test conninfo string */
		conn = establish_db_connection(new_options.conninfo, false);
		if (!conn || (PQstatus(conn) != CONNECTION_OK))
		{
			log_warning(_("'conninfo' string is not valid, retaining current configuration\n"));
			return false;
		}
		PQfinish(conn);
	}

	/*
	 * No configuration problems detected - copy any changed values
	 *
	 * NB: keep these in the same order as in config.h to make it easier
	 * to manage them
	 */

	/* cluster_name */
	if (strcmp(orig_options->cluster_name, new_options.cluster_name) != 0)
	{
		strcpy(orig_options->cluster_name, new_options.cluster_name);
		config_changed = true;
	}

	/* conninfo */
	if (strcmp(orig_options->conninfo, new_options.conninfo) != 0)
	{
		strcpy(orig_options->conninfo, new_options.conninfo);
		config_changed = true;
	}

	/* node */
	if (orig_options->node != new_options.node)
	{
		orig_options->node = new_options.node;
		config_changed = true;
	}

	/* failover */
	if (orig_options->failover != new_options.failover)
	{
		orig_options->failover = new_options.failover;
		config_changed = true;
	}

	/* priority */
	if (orig_options->priority != new_options.priority)
	{
		orig_options->priority = new_options.priority;
		config_changed = true;
	}

	/* node_name */
	if (strcmp(orig_options->node_name, new_options.node_name) != 0)
	{
		strcpy(orig_options->node_name, new_options.node_name);
		config_changed = true;
	}

	/* promote_command */
	if (strcmp(orig_options->promote_command, new_options.promote_command) != 0)
	{
		strcpy(orig_options->promote_command, new_options.promote_command);
		config_changed = true;
	}

	/* follow_command */
	if (strcmp(orig_options->follow_command, new_options.follow_command) != 0)
	{
		strcpy(orig_options->follow_command, new_options.follow_command);
		config_changed = true;
	}

	/*
	 * XXX These ones can change with a simple SIGHUP?
	 *
	 * strcpy (orig_options->loglevel, new_options.loglevel); strcpy
	 * (orig_options->logfacility, new_options.logfacility);
	 *
	 * logger_shutdown(); XXX do we have progname here ? logger_init(progname,
	 * orig_options.loglevel, orig_options.logfacility);
	 */

	/* rsync_options */
	if (strcmp(orig_options->rsync_options, new_options.rsync_options) != 0)
	{
		strcpy(orig_options->rsync_options, new_options.rsync_options);
		config_changed = true;
	}

	/* ssh_options */
	if (strcmp(orig_options->ssh_options, new_options.ssh_options) != 0)
	{
		strcpy(orig_options->ssh_options, new_options.ssh_options);
		config_changed = true;
	}

	/* master_response_timeout */
	if (orig_options->master_response_timeout != new_options.master_response_timeout)
	{
		orig_options->master_response_timeout = new_options.master_response_timeout;
		config_changed = true;
	}

	/* reconnect_attempts */
	if (orig_options->reconnect_attempts != new_options.reconnect_attempts)
	{
		orig_options->reconnect_attempts = new_options.reconnect_attempts;
		config_changed = true;
	}

	/* reconnect_interval */
	if (orig_options->reconnect_interval != new_options.reconnect_interval)
	{
		orig_options->reconnect_interval = new_options.reconnect_interval;
		config_changed = true;
	}

	/* pg_ctl_options */
	if (strcmp(orig_options->pg_ctl_options, new_options.pg_ctl_options) != 0)
	{
		strcpy(orig_options->pg_ctl_options, new_options.pg_ctl_options);
		config_changed = true;
	}

	/* pg_basebackup_options */
	if (strcmp(orig_options->pg_basebackup_options, new_options.pg_basebackup_options) != 0)
	{
		strcpy(orig_options->pg_basebackup_options, new_options.pg_basebackup_options);
		config_changed = true;
	}

	/* monitor_interval_secs */
	if (orig_options->monitor_interval_secs != new_options.monitor_interval_secs)
	{
		orig_options->monitor_interval_secs = new_options.monitor_interval_secs;
		config_changed = true;
	}

	/* retry_promote_interval_secs */
	if (orig_options->retry_promote_interval_secs != new_options.retry_promote_interval_secs)
	{
		orig_options->retry_promote_interval_secs = new_options.retry_promote_interval_secs;
		config_changed = true;
	}

	/* use_replication_slots */
	if (orig_options->use_replication_slots != new_options.use_replication_slots)
	{
		orig_options->use_replication_slots = new_options.use_replication_slots;
		config_changed = true;
	}

	if (config_changed == true)
	{
		log_debug(_("reload_config(): configuration has changed\n"));
	}
	else
	{
		log_debug(_("reload_config(): configuration has not changed\n"));
	}

	return config_changed;
}
Exemplo n.º 25
0
int
main(int argc, char **argv)
{
    int             ups_fd, stat_fd, ch;
    int             flags;
    int             pstatus, poldstat = 1;
    int             bstatus, boldstat = 1;
    int             count = 0;
    int             bcount = 0;
    int             tries = 0;
    int             ikill = 0;
    int             ioctlbit;
    char           *self = argv[0];
    char            killchar = ' ';
    struct upsdef  *pups;

    while ((ch = getopt(argc, argv, "kc:d:r:s:t:")) != -1)
	switch (ch) {
	  case 'k':
	    ikill = 1;
	    break;
	  case 'c':
	    config_file = optarg;
	    break;
	  case 'd':
	    upsport = optarg;
	    break;
	  case 'r':
	    rcpowerfail = optarg;
	    break;
	  case 's':
	    upsstat = optarg;
	    break;
	  case 't':
	    upstype = optarg;
	    break;
	  case '?':
	  default:
	    usage(self);
	}
    argc -= optind;
    argv += optind;
    if (argc > 0)
	usage(self);

    parse_config(config_file);

    if (upsport == NULL || upstype == NULL || upsstat == NULL) {
	usage(self);
    }
    for (pups = ups; pups; pups = pups->next) {
	if (strcmp(pups->tag, upstype) == 0)
	    break;
    }
    if (!pups) {
	fprintf(stderr, "Error: %s: UPS <%s> unknown\n", self, argv[2]);
	exit(1);
    }
    /* Start syslog. */
    openlog(self, LOG_CONS | LOG_PERROR, LOG_DAEMON);

    if ((ups_fd = open(upsport, O_RDWR | O_NDELAY)) < 0) {
	syslog(LOG_ERR, "%s: %s", upsport, strerror(errno));
	closelog();
	exit(1);
    }
    /* Kill the inverter and close out if inverter kill was selected */
    if (ikill) {
	if (pups->killtime) {

	    /* Explicitly clear both DTR and RTS as soon as possible  */
	    ioctlbit = TIOCM_RTS;
	    ioctl(ups_fd, TIOCMBIC, &ioctlbit);
	    ioctlbit = TIOCM_DTR;
	    ioctl(ups_fd, TIOCMBIC, &ioctlbit);

	    /* clear killpower, apply cablepower to enable monitoring */
	    setlevel(ups_fd, pups->kill.line, !pups->kill.inverted);
	    setlevel(ups_fd, pups->cablepower.line, !pups->cablepower.inverted);

	    if (pups->kill.line == TIOCM_ST) {
		/* Send BREAK (TX high) to kill the UPS inverter. */
		tcsendbreak(ups_fd, 1000 * pups->killtime);
	    } else {
		/* Force high to send the UPS the inverter kill signal. */
		setlevel(ups_fd, pups->kill.line, pups->kill.inverted);
		sleep(pups->killtime);
	    }
	    ioctl(ups_fd, TIOCMGET, &flags);

	    /*
	     * Feb/05/2001 Added support for Tripplite Omnismart 450PNP, this
	     * UPS shutdowns inverter when data is sent over the Tx line
	     * (jhcaiced)
	     */
	    if (pups->flags & UPS_TXD_KILL_INVERTER) {
		sleep(2);
		write(ups_fd, &killchar, 1);
	    }
	    close(ups_fd);

	    /************************************************************/
	    /* We never should have gotten here.                        */
	    /* The inverter kill has failed for one reason or another.  */
	    /* If still in powerfail mode, exit with an error.          */
	    /* If power is ok (power has returned) let rc.0 finish the  */
	    /* reboot.                                                  */
	    /************************************************************/
	    if (getlevel(&pups->powerok, flags) == 0) {
		fprintf(stderr, "%s: UPS inverter kill failed.\n", self);
		exit(1);
	    }			/* if (getlevel(&pups->powerok,flags) == 0) */
	    /* Otherwise, exit normaly, power has returned. */
	    exit(0);
	} else {
	    fprintf(stderr, "Error: %s: UPS <%s> has no support for killing the inverter.\n",
		    self, pups->tag);
	    exit(1);
	}			/* if (pups->kill) */
    }				/* if (ikill) */
    /****************************************/
    /* If no kill signal, monitor the line. */
    /****************************************/
    /* Explicitly clear both DTR and RTS as soon as possible  */
    ioctl(ups_fd, TIOCMBIC, TIOCM_RTS);
    ioctl(ups_fd, TIOCMBIC, TIOCM_DTR);

    /* clear killpower, apply cablepower to enable monitoring */
    setlevel(ups_fd, pups->kill.line, !pups->kill.inverted);
    setlevel(ups_fd, pups->cablepower.line, !pups->cablepower.inverted);

    /* Daemonize. */
#ifdef DEBUG
    closelog();
    setsid();
#else
    switch (fork()) {
      case 0:			/* Child */
	closelog();
	setsid();
	break;
      case -1:			/* Error */
	syslog(LOG_ERR, "can't fork.");
	closelog();
	exit(1);
      default:			/* Parent */
	closelog();
	exit(0);
    }
#endif				/* switch(fork()) */

    /* Restart syslog. */
    openlog(self, LOG_CONS, LOG_DAEMON);

    /* Create an info file for powerfail scripts. */
    unlink(upsstat);
    if ((stat_fd = open(upsstat, O_CREAT | O_WRONLY, 0644)) >= 0) {
	write(stat_fd, "OK\n", 3);
	close(stat_fd);
    }
    /* Give the UPS a chance to reach a stable state. */
    sleep(2);

    /* Now sample the line. */
    while (1) {
	/* Get the status. */
	ioctl(ups_fd, TIOCMGET, &flags);

	/* Calculate present status. */
	pstatus = getlevel(&pups->powerok, flags);
	bstatus = getlevel(&pups->battok, flags);

	if (pups->cableok.line) {
	    /* Check the connection. */
	    tries = 0;
	    while (getlevel(&pups->cableok, flags) == 0) {
		/* Keep on trying, and warn every two minutes. */
		if ((tries % 60) == 0)
		    syslog(LOG_ALERT, "UPS connection error");
		sleep(2);
		tries++;
		ioctl(ups_fd, TIOCMGET, &flags);
	    }			/* while(getlevel(&pups->cableok,flags) */
	    if (tries > 0)
		syslog(LOG_ALERT, "UPS connection OK");
	} else {
	    /*
	     * Do pseudo-cable check, bad power on startup == possible bad
	     * cable
	     */
	    if (tries < 1) {
		tries++;

		/* Do startup failure check */
		if (!pstatus) {
		    /*
		     * Power is out: assume bad cable, but semi-scram to be
		     * safe
		     */
		    syslog(LOG_ALERT, "No power on startup; UPS connection error?");

		    /*
		     * Set status registers to prevent further processing
		     * until
		     */
		    /* the status of the cable is changed.                      */
		    poldstat = pstatus;
		    boldstat = bstatus;

		    powerfail(PFM_CABLE);
		}		/* if (!pstatus) */
	    }			/* if (tries < 1) */
	}			/* if (pups->cableok.line) */

	/* If anything has changed, process the change */
	if (pstatus != poldstat || bstatus != boldstat) {
	    count++;
	    if (count < 4) {
		/* Wait a little to ride out short brown-outs */
		sleep(1);
		continue;
	    }			/* if (count < 4) */
	    if (pstatus != poldstat) {
		if (pstatus) {
		    /* Power is OK */
		    syslog(LOG_ALERT, "Line power restored");
		    powerfail(PFM_OK);
		} else {
		    /* Power has FAILED */
		    if (bstatus) {
			/* Battery OK, normal shutdown */
			syslog(LOG_ALERT, "Line power has failed");
			powerfail(PFM_FAIL);
		    } else {
			/* Low Battery, SCRAM! */
			syslog(LOG_ALERT, "UPS battery power is low!");
			powerfail(PFM_SCRAM);
		    }		/* if (bstatus) */
		}		/* if (pstatus) */
	    }			/* if (pstatus != poldstat) */
	    if (bstatus != boldstat) {
		if (!bstatus && !pstatus) {
		    /* Power is out and Battery is now low, SCRAM! */
		    syslog(LOG_ALERT, "UPS battery power is low!");
		    powerfail(PFM_SCRAM);
		} else {
		    /* Battery status has changed */
		    if (bstatus) {
			/* Battery power is back */
			syslog(LOG_ALERT, "UPS battery power is now OK");
		    }		/* if (!bstatus) */
		}		/* if (!bstatus && !pstatus) */
	    }			/* if (bstatus != boldstat) */
	}			/* if (pstatus != poldstat || bstatus !=
				 * boldstat) */

	if (!bstatus && pstatus) {
	    /* Line power is OK and UPS signals battery is low */
	    /* Log a message to the syslog every 10 minutes */
	    if ((bcount % 300) == 0)
		syslog(LOG_ALERT, "UPS battery power is low!");
	    bcount++;
	} else {
	    /* Reset count */
	    bcount = 0;
	}			/* if (!bstatus && pstatus) */

	/* Reset count, remember status and sleep 2 seconds. */
	count = 0;
	poldstat = pstatus;
	boldstat = bstatus;
	sleep(2);
    }				/* while(1) */
    /* Never happens */
    return (0);
}
Exemplo n.º 26
0
/*! \brief Start of execution.  Parse options, and call other other
 * functions one after another.  At the moment adding threading support
 * would be difficult, but there does not seem to be valid reason to
 * consider that.  Overall the analysis already quick enough even without
 * making it parallel.
 *
 * \return Return value indicates success or fail or analysis, unless
 * either --warning or --critical options are in use, which makes the
 * return value in some cases to match with Nagios expectations about
 * alarming. */
int main(int argc, char **argv)
{
	int i, sorts = 0;
	int option_index = 0;
	char const *tmp;
	struct range_t *tmp_ranges;
	enum {
		OPT_WARN = CHAR_MAX + 1,
		OPT_CRIT
	};
	int ret_val;

	/* Options for getopt_long */
	static struct option const long_options[] = {
		{"config", required_argument, NULL, 'c'},
		{"leases", required_argument, NULL, 'l'},
		{"format", required_argument, NULL, 'f'},
		{"sort", required_argument, NULL, 's'},
		{"reverse", no_argument, NULL, 'r'},
		{"output", required_argument, NULL, 'o'},
		{"limit", required_argument, NULL, 'L'},
		{"version", no_argument, NULL, 'v'},
		{"help", no_argument, NULL, 'h'},
		{"warning", required_argument, NULL, OPT_WARN},
		{"critical", required_argument, NULL, OPT_CRIT},
		{NULL, 0, NULL, 0}
	};

	atexit(close_stdout);

	/* FIXME: These allocations should be fully dynamic, e.g., grow
	 * if needed.  */
	config.dhcpdconf_file = xmalloc(sizeof(char) * MAXLEN);
	config.dhcpdlease_file = xmalloc(sizeof(char) * MAXLEN);
	config.output_file = xmalloc(sizeof(char) * MAXLEN);

	/* Make sure string has zero length if there is no
	 * command line option */
	config.output_file[0] = '\0';
	/* Alarming defaults. */
	config.warning = ALARM_WARN;
	config.critical = ALARM_CRIT;

	/* File location defaults */
	strncpy(config.dhcpdconf_file, DHCPDCONF_FILE, MAXLEN - 1);
	strncpy(config.dhcpdlease_file, DHCPDLEASE_FILE, MAXLEN - 1);
	tmp = OUTPUT_LIMIT;
	config.output_limit[0] = (*tmp - '0');
	tmp++;
	config.output_limit[1] = (*tmp - '0');
	config.fullhtml = false;

	/* Make sure some output format is selected by default */
	strncpy(config.output_format, OUTPUT_FORMAT, (size_t)1);

	/* Default sort order is by IPs small to big */
	config.reverse_order = false;
	config.backups_found = false;

	/* Parse command line options */
	while (1) {
		int c;
		c = getopt_long(argc, argv, "c:l:f:o:s:rL:vh",
				long_options, &option_index);

		if (c == EOF)
			break;

		switch (c) {
		case 'c':
			/* config file */
			strncpy(config.dhcpdconf_file, optarg, MAXLEN - 1);
			break;
		case 'l':
			/* lease file */
			strncpy(config.dhcpdlease_file, optarg, MAXLEN - 1);
			break;
		case 'f':
			/* Output format */
			strncpy(config.output_format, optarg, (size_t)1);
			break;
		case 's':
			/* Output sorting option */
			sorts = strlen(optarg);
			if (5 < sorts) {
				warnx
				    ("main: only first 5 sort orders will be used");
				strncpy(config.sort, optarg, (size_t)5);
				sorts = 5;
			} else {
				strncpy(config.sort, optarg, (size_t)sorts);
			}
			for (i = 0; i < sorts; i++) {
				field_selector(config.sort[i]);
			}
			break;
		case 'r':
			/* What ever sort in reverse order */
			config.reverse_order = true;
			break;
		case 'o':
			/* Output file */
			strncpy(config.output_file, optarg, MAXLEN - 1);
			break;
		case 'L':
			/* Specification what will be printed */
			for (i = 0; i < 2; i++) {
				if (optarg[i] >= '0' && optarg[i] < '8') {
					config.output_limit[i] =
					    optarg[i] - '0';
				} else {
					errx(EXIT_FAILURE,
					     "main: output mask `%s' is illegal",
					     optarg);
				}
			}
			break;
		case OPT_WARN:
			strcpy(config.output_format, "a");
			config.warning =
			    strtod_or_err(optarg, "illegal argument");
			break;
		case OPT_CRIT:
			strcpy(config.output_format, "a");
			config.critical =
			    strtod_or_err(optarg, "illegal argument");
			break;
		case 'v':
			/* Print version */
			print_version();
		case 'h':
			/* Print help */
			usage(EXIT_SUCCESS);
		default:
			errx(EXIT_FAILURE,
			     "Try `%s --help' for more information.",
			     program_invocation_short_name);
		}
	}

	/* Output function selection */
	switch (config.output_format[0]) {
	case 't':
		output_analysis = output_txt;
		break;
	case 'a':
		output_analysis = output_alarming;
		break;
	case 'h':
		output_analysis = output_html;
		break;
	case 'H':
		output_analysis = output_html;
		config.fullhtml = true;
		break;
	case 'x':
		output_analysis = output_xml;
		break;
	case 'X':
		output_analysis = output_xml;
		break;
	case 'j':
		output_analysis = output_json;
		break;
	case 'J':
		output_analysis = output_json;
		break;
	case 'c':
		output_analysis = output_csv;
		break;
	default:
		errx(EXIT_FAILURE, "main: unknown output format `%c'",
		     config.output_format[0]);
	}

	/* Do the job */
	prepare_memory();
	parse_config(true, config.dhcpdconf_file, shared_networks);

	parse_leases();
	prepare_data();
	do_counting();
	tmp_ranges = xmalloc(sizeof(struct range_t) * num_ranges);
	if (sorts != 0) {
		mergesort_ranges(ranges, num_ranges, tmp_ranges);
	}
	if (config.reverse_order == true) {
		flip_ranges(ranges, tmp_ranges);
	}
	free(tmp_ranges);
	ret_val = output_analysis();

	clean_up();
	return (ret_val);
}
Exemplo n.º 27
0
int main(int argc, char *argv[])
{
	mmatic *mm = mmatic_create();
	mmatic *mmtmp = mmatic_create();
	struct mg *mg;
	int i;

	/*
	 * initialize and parse config
	 */

	mg = mmatic_zalloc(mm, sizeof(struct mg));
	mg->mm = mm;
	mg->mmtmp = mmtmp;
	apply_defaults(mg);

	/* get my id number from hostname */
	fetch_myid(mg);

	/* parse command line options */
	if (parse_argv(mg, argc, argv))
		return 1;

	/* parse configuration file options */
	if (mg->options.conf_file) {
		if (parse_config(mg))
			return 4;
	}

	/*
	 * config syntax looks OK, see if it is feasible
	 */

	/* initialize random number generator */
	srand48(mg->options.myid);

	/* init libevent */
	mg->evb = event_init();
	event_set_log_callback(libevent_log);

	/* init stats structures so mgstats_aggregator_add() used somewhere below works */
	mgstats_init(mg);

	/* attach to raw interfaces */
	if (mgi_init(mg, handle_packet) <= 0) {
		dbg(0, "no available interfaces found\n");
		return 2;
	}

	/* parse traffic file */
	if (parse_traffic(mg))
		return 3;

	/*
	 * all OK, prepare to start
	 */

	/* synchronize time reference point on all nodes */
	mgc_sync(mg);

	/* schedule stats writing */
	mgstats_start(mg);

	/* attach global stats */
	_stats_init(mg);

	/* schedule heartbeat and disk sync signals */
	heartbeat_init(mg);
	sync_init(mg);

	/* schedule the real work of this node: line generators */
	for (i = 1; i < TRAFFIC_LINE_MAX; i++) {
		if (!(mg->lines[i] && mg->lines[i]->my))
			continue;

		/* this will schedule first execution */
		mgs_sleep(mg->lines[i], NULL);
		mg->running++;
	}

	/* suppose last frame was received now */
	gettimeofday(&mg->last, NULL);

	/*
	 * start!
	 */

	dbg(0, "Starting\n");
	event_base_dispatch(mg->evb);

	/*******************************/

	/*
	 * cleanup after end of libevent loop
	 */

	event_base_free(mg->evb);
	mmatic_free(mg->mm);
	mmatic_free(mg->mmtmp);

	fflush(NULL);
	sync();

	return 0;
}
Exemplo n.º 28
0
static int reload(void)
{
	if (parse_config(1))
		return AST_MODULE_LOAD_DECLINE;
	return AST_MODULE_LOAD_SUCCESS;
}
Exemplo n.º 29
0
/**
 * Command line analysis function.
 *
 * mpirun [-debug] [-xterm] -np N [-hostfile hfile | h1 h2 h3 ... hN] a.out [args]
 */
void commandLine(int argc, char *argv[], char *totalview_cmd, char **env)
{
    int i;
    int c, option_index;

    size_t hostname_len = 0;

    do {
        c = getopt_long_only(argc, argv, "+", option_table, &option_index);
        switch (c) {
        case '?':
        case ':':
            usage();
            exit(EXIT_FAILURE);
            break;
        case EOF:
            break;
        case 0:
            switch (option_index) {
            case 0:            /* -np */
                nprocs = atoi(optarg);
                if (nprocs < 1) {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            case 1:            /* -debug */
                debug_on = 1;
                xterm_on = 1;
                break;
            case 2:            /* -xterm */
                xterm_on = 1;
                break;
            case 3:            /* -hostfile */
                hostfile_on = 1;
                strncpy(hostfile, optarg, HOSTFILE_LEN);
                if (strlen(optarg) >= HOSTFILE_LEN - 1)
                    hostfile[HOSTFILE_LEN] = '\0';
                break;
            case 4:
                show_on = 1;
                break;
            case 5:
                use_rsh = 1;
                break;
            case 6:
                use_rsh = 0;
                break;
            case 7:
                usage();
                exit(EXIT_SUCCESS);
                break;
            case 8:
                PRINT_MVAPICH2_VERSION();
                exit(EXIT_SUCCESS);
                break;
            case 9:
                {
                    /* -tv */
                    char *tv_env;
                    int count, idx;
                    char **new_argv;
                    tv_env = getenv("TOTALVIEW");
                    if (tv_env != NULL) {
                        strncpy(totalview_cmd, tv_env, TOTALVIEW_CMD_LEN);
                    } else {
                        fprintf(stderr, "TOTALVIEW env is NULL, use default: %s\n", TOTALVIEW_CMD);
                        sprintf(totalview_cmd, "%s", TOTALVIEW_CMD);
                    }
                    new_argv = (char **) malloc(sizeof(char **) * argc + 3);
                    new_argv[0] = totalview_cmd;
                    new_argv[1] = argv[0];
                    new_argv[2] = "-a";
                    new_argv[3] = "-startedByTv";
                    idx = 4;
                    for (count = 1; count < argc; count++) {
                        if (strcmp(argv[count], "-tv"))
                            new_argv[idx++] = argv[count];
                    }
                    new_argv[idx] = NULL;
                    if (execv(new_argv[0], new_argv)) {
                        perror("execv");
                        exit(EXIT_FAILURE);
                    }

                }
                break;
            case 10:
                legacy_startup = 1;
                break;
            case 11:
                /* -startedByTv */
                use_totalview = 1;
                debug_on = 1;
                break;
            case 12:           /* spawnspec given */
                spawnfile = strdup(optarg);
                DBG(fprintf(stderr, "spawn spec file = %s\n", spawnfile));
                break;
            case 13:
                dpm = 1;
                break;
            case 14:           /* -fastssh */
#ifndef CKPT
                USE_LINEAR_SSH = 0;
#endif                          /* CKPT */
                break;
                //With this option the user want to activate the mpmd
            case 15:
                configfile_on = 1;
                strncpy(configfile, optarg, CONFILE_LEN);
                if (strlen(optarg) >= CONFILE_LEN - 1)
                    configfile[CONFILE_LEN] = '\0';
                break;
            case 16:
                spinf.totspawns = atoi(optarg);
                break;
            case 17:
                /* sg: change the active group */
                change_group = optarg;
                DBG(printf("Group change requested: '%s'\n", change_group));
                break;
            case 18:
#if defined(CKPT) && defined(CR_FTB)
                sparehosts_on = 1;
                strncpy(sparehostfile, optarg, HOSTFILE_LEN);
                if (strlen(optarg) >= HOSTFILE_LEN - 1)
                    sparehostfile[HOSTFILE_LEN] = 0;
#else
                usage();
                exit(EXIT_SUCCESS);
#endif
                break;
            default:
                fprintf(stderr, "Unknown option\n");
                usage();
                exit(EXIT_FAILURE);
                break;
            }
            break;
        default:
            fprintf(stderr, "Unreachable statement!\n");
            usage();
            exit(EXIT_FAILURE);
            break;
        }
    }
    while (c != EOF);

    if (!nprocs && !configfile_on) {
        usage();
        exit(EXIT_FAILURE);
    }

    binary_dirname = dirname(strdup(argv[0]));
    if (strlen(binary_dirname) == 1 && argv[0][0] != '.') {
        use_dirname = 0;
    }
    //If the mpmd is active we need to parse the configuration file
    if (configfile_on) {
        /*TODO In the future the user can add the nprocs on the command line. Now the
         * number of processes is defined in the configfile */
        nprocs = 0;
        plist = parse_config(configfile, &nprocs);
        DBG(fprintf(stderr, "PARSED CONFIG FILE\n"));

    }

    if (!hostfile_on) {
        /* get hostnames from argument list */
        if (strchr(argv[optind], '=') || argc - optind < nprocs + 1) {
            sprintf(hostfile, "%s/.mpirun_hosts", env2str("HOME"));
            if (file_exists(hostfile)) {
                hostfile_on = 1;
                aout_index = optind;
                goto cont;
            } else {
                fprintf(stderr, "Without hostfile option, hostnames must be " "specified on command line.\n");
                usage();
                exit(EXIT_FAILURE);
            }
        }
        aout_index = nprocs + optind;
    } else {                    /* if (!hostfile_on) */

        aout_index = optind;
    }

  cont:
    if (!configfile_on) {
        plist = malloc(nprocs * sizeof(process));
        if (plist == NULL) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }

        for (i = 0; i < nprocs; i++) {
            plist[i].state = P_NOTSTARTED;
            plist[i].device = NULL;
            plist[i].port = -1;
            plist[i].remote_pid = 0;
            //TODO ADD EXECNAME AND ARGS

        }
    }

    /* grab hosts from command line or file */
    /* TODO: remove  hostname_len variable */
    hostname_len = 0;
    if (hostfile_on) {
        hostname_len = read_hostfile(hostfile);
    } else {
        for (i = 0; i < nprocs; i++) {
            plist[i].hostname = (char *) strndup(argv[optind + i], 100);
            if (hostname_len < strlen(plist[i].hostname)) {
                hostname_len = strlen(plist[i].hostname);
            }
        }
    }

}
Exemplo n.º 30
0
/*
 * create_object parse the object fields from the command line and call the
 * appropriate object creator with a table of fields filled in.
 */
int main(
    int argc,
    char **argv)
{

    int ret = 0;
    int parse_err = 0;
    int index = 1;
    int c;
    char *obj_type;
    char *configFile = NULL;
    extern char *optarg;
    struct object_field *table;


    OPEN_LOG("create_object", LOG_USER);

    if (!my_config_load())
    {
        LOG(LOG_ERR, "can't load configuration");
        return EXIT_FAILURE;
    }


    // parse options
    while ((c = getopt(argc, argv, "hf:t:")) != -1)
    {
        switch (c)
        {
        case 'h':
            printUsage(argv);
            break;

        case 'f':
            configFile = optarg;
            break;

        case 't':
            templateFile = optarg;
            break;

        case '?':
            printUsage(argv);
            break;

        default:
            fprintf(stderr, "Illegal Option\n");
            printUsage(argv);
            break;
        }
    }

    index = optind;             // remaining arguments
    if (configFile == NULL)
        fprintf(stdout, "No Config file\n");

    if (index >= argc)
        fatal(INPUT_ARG_ERR, "No Object Type");
    else
        obj_type = argv[index++];

    if (strncasecmp(obj_type, "CERT", strlen("CERT")) == 0)
    {
        table = get_cert_field_table();
        if (configFile != NULL)
            if (parse_config(configFile, table) != 0)
            {
                warn(INPUT_ARG_ERR, parse_errstr);
                parse_err = 1;
            }

        // parse and validate arguments, exit if either or both fail
        if (parse_args(argc, argv, index, table) != 0)
        {
            warn(INPUT_ARG_ERR, parse_errstr);
            parse_err = 1;
        }
        if (validate_table(table, validate_errstr, sizeof(validate_errstr)) !=
            0)
            fatal(MISSING_FIELDS, validate_errstr);

        // if no validation error but we did have a parse err - exit
        if (parse_err)
        {
            config_unload();
            exit(INPUT_ARG_ERR);
        }

        ret = create_cert(table);
        // fprintf(stdout,"return from creating certificate %d\n", ret);
    }
    else if (strncasecmp(obj_type, "CRL", strlen("CRL")) == 0)
    {
        table = get_crl_field_table();
        if (configFile != NULL)
            if (parse_config(configFile, table) != 0)
            {
                warn(INPUT_ARG_ERR, parse_errstr);
                parse_err = 1;
            }

        if (parse_args(argc, argv, index, table) != 0)
        {
            warn(INPUT_ARG_ERR, parse_errstr);
            parse_err = 1;
        }
        if (validate_table(table, validate_errstr, sizeof(validate_errstr)) !=
            0)
            fatal(MISSING_FIELDS, validate_errstr);

        // if no validation error but we did have a parse err - exit
        if (parse_err)
        {
            config_unload();
            exit(INPUT_ARG_ERR);
        }

        ret = create_crl(table);
    }
    else if (strncasecmp(obj_type, "ROA", strlen("ROA")) == 0)
    {
        table = get_roa_field_table();
        if (configFile != NULL)
            if (parse_config(configFile, table) != 0)
            {
                warn(INPUT_ARG_ERR, parse_errstr);
                parse_err = 1;
            }

        if (parse_args(argc, argv, index, table) != 0)
            fatal(INPUT_ARG_ERR, parse_errstr);

        if (validate_table(table, validate_errstr, sizeof(validate_errstr)) !=
            0)
            fatal(MISSING_FIELDS, validate_errstr);
        ret = create_roa(table);
    }
    else if (strncasecmp(obj_type, "MANIFEST", strlen("MANIFEST")) == 0)
    {
        table = get_man_field_table();
        if (configFile != NULL)
            if (parse_config(configFile, table) != 0)
            {
                warn(INPUT_ARG_ERR, parse_errstr);
                parse_err = 1;
            }

        // parse arguments and validate table
        if (parse_args(argc, argv, index, table) != 0)
            warn(INPUT_ARG_ERR, parse_errstr);

        if (validate_table(table, validate_errstr, sizeof(validate_errstr)) !=
            0)
            fatal(MISSING_FIELDS, validate_errstr);
        ret = create_manifest(table);
    }
    else
        fatal(INPUT_ARG_ERR, argv[1]);

    config_unload();

    exit(ret);
}