int loadEffectConfigFile(const char *path)
{
    cnode *root;
    char *data;

    data = load_file(path, NULL);
    if (data == NULL) {
        return -ENODEV;
    }
    root = config_node("", "");
    if (root == NULL) {
        return -ENOMEM;
    }
    config_load(root, data);
    loadLibraries(root);
    loadEffects(root);
    config_free(root);
    free(root);
    free(data);

    return 0;
}
示例#2
0
文件: helper.c 项目: DeforaOS/Panel
/* panel_init */
static int _panel_init(Panel * panel, PanelWindowPosition position,
		PanelWindowType type, GtkIconSize iconsize)
{
	const PanelPosition top = PANEL_POSITION_TOP;
	char * filename;
	GdkRectangle rect;
	size_t i;

	if((panel->config = config_new()) == NULL)
		return -1;
	if((filename = _config_get_filename()) != NULL
			&& config_load(panel->config, filename) != 0)
		error_print(PROGNAME);
	free(filename);
	panel->prefs.iconsize = NULL;
	panel->prefs.monitor = -1;
	/* root window */
	panel->screen = gdk_screen_get_default();
	panel->root = gdk_screen_get_root_window(panel->screen);
	gdk_screen_get_monitor_geometry(panel->screen, 0, &rect);
	panel->root_height = rect.height;
	panel->root_width = rect.width;
	/* panel window */
	_helper_init(&panel->helper[top], panel, type, iconsize);
	panel->windows[top] = panel_window_new(&panel->helper[top],
			PANEL_WINDOW_TYPE_NORMAL, position, iconsize, &rect);
	panel->helper[top].window = panel->windows[top];
	for(i = 0; i < sizeof(panel->windows) / sizeof(*panel->windows); i++)
		if(i != top)
			panel->windows[i] = NULL;
	panel->source = 0;
	panel->timeout = 0;
	panel->ab_window = NULL;
	panel->lk_window = NULL;
	panel->lo_window = NULL;
	panel->sh_window = NULL;
	panel->su_window = NULL;
	return 0;
}
void ICACHE_FLASH_ATTR
user_init(void)
{
	uart_init(BIT_RATE_115200, BIT_RATE_115200);
	INFO("\r\nSDK version: %s\n", system_get_sdk_version());
	INFO("System init...\r\n");
	system_set_os_print(1);
	os_delay_us(1000000);

	INFO("Load Config\n");
	config_load();
	INFO("GPIO Init\n");
	gpio_init();
	INFO("MQTT Init");
	mqtt_init();

	INFO("Connect wifi %s\n", config.sta_ssid);
	WIFI_Connect(config.sta_ssid, config.sta_pwd, wifi_connect_cb);
	//WIFI_Connect("Wirelessabata", "TaLi100305", wifi_connect_cb);

	INFO("\r\nSystem started ...\r\n");
}
示例#4
0
void measures_init(void)
{
	sem_init(&i2c_sem);
	i2c_init(&i2c_bus, I2C_BITBANG0, CONFIG_I2C_FREQ);
	bool ret = mma845x_init(&i2c_bus, 0, MMADYN_4G);
	ASSERT(ret);

	Process *p = proc_new(acc_process, NULL, KERN_MINSTACKSIZE * 4, NULL);
	ASSERT(p);

	aux_init();

	config_register(&measures);
	config_load(&measures);

	/* Start current check process */
	p = proc_new(curr_process, NULL, KERN_MINSTACKSIZE * 4, NULL);
	ASSERT(p);

	uplink_registerCmd("curr_override", cmd_curr_override);
	uplink_registerCmd("curr_reset", cmd_curr_reset);
}
示例#5
0
文件: md_xspeed.c 项目: ifzz/xcb
static inline void load_config(void) {
	/* FIXME */
	if ((cfg = config_load("/etc/xcb/xspeed.conf"))) {
		char *cat = category_browse(cfg, NULL);

		while (cat) {
			if (!strcasecmp(cat, "general")) {
				struct variable *var = variable_browse(cfg, cat);

				while (var) {
					if (!strcasecmp(var->name, "front_ip")) {
						if (strcasecmp(var->value, ""))
							front_ip = var->value;
					} else if (!strcasecmp(var->name, "front_port")) {
						if (strcasecmp(var->value, ""))
							front_port = var->value;
					} else if (!strcasecmp(var->name, "userid")) {
						if (strcasecmp(var->value, ""))
							userid = var->value;
					} else if (!strcasecmp(var->name, "passwd")) {
						if (strcasecmp(var->value, ""))
							passwd = var->value;
					} else if (!strcasecmp(var->name, "reqid")) {
						if (strcasecmp(var->value, ""))
							reqid = atoi(var->value);
					} else if (!strcasecmp(var->name, "contracts")) {
						if (strcasecmp(var->value, ""))
							contracts= var->value;
					} else
						xcb_log(XCB_LOG_WARNING, "Unknown variable '%s' in "
							"category '%s' of xspeed.conf", var->name, cat);
					var = var->next;
				}
			}
			cat = category_browse(cfg, cat);
		}
	}
}
示例#6
0
文件: app_ema.c 项目: ArkShen/xcb
static void load_config(void) {
	/* FIXME */
	if ((cfg = config_load("/etc/xcb/ema.conf"))) {
		char *cat = category_browse(cfg, NULL);

		while (cat ) {
			if (!strcasecmp(cat, "general")) {
				struct variable *var = variable_browse(cfg, cat);

				while (var) {
					if (!strcasecmp(var->name, "number")) {
						if (strcasecmp(var->value, ""))
							n = atoi(var->value);
					} else
						xcb_log(XCB_LOG_WARNING, "Unknown variable '%s' in "
							"category '%s' of ema.conf", var->name, cat);
					var = var->next;
				}
			}
			cat = category_browse(cfg, cat);
		}
	}
}
示例#7
0
int main()
{
	int server_port			= 0;
	char *tmp_port_val		= NULL;
	int server_descriptor	= 0;
	
	if (config_load(CONFIG_PATH) != 0)
	{
		return EXIT_FAILURE;
	}
	
	if (module_load(MODULES_PATH) != 0)
	{
		free_server();
		return EXIT_FAILURE;
	}
	
	tmp_port_val = (char*)config_get_entry_value("port");
	if (tmp_port_val == NULL)
	{
		server_port = DEFAULT_SERVER_PORT;
		log_message("%s%d%s\n", "No port number was specified in server.conf! Using default (", server_port, ").");
	}
	else if ((server_port = atoi(tmp_port_val)) < 1)
	{
		server_port = DEFAULT_SERVER_PORT;
		log_message("%s%d%s\n", "Invalid port number was specified in server.conf! Using default (", server_port, ").");
	}
	
	if ((server_descriptor = connection_init(server_port)) > 0)
	{
		
	}
	
	free_server();
	return 0;
}
示例#8
0
文件: cnat.c 项目: millken/zhuxianB30
/*******************************************************************************
 函数名称  : get_connect_iden
 功能描述  : 获取要发送的连接标识
 输入参数  : 无
 输出参数  : 无
 返 回 值      : ERROR_SUCCESS
------------------------------------------------------------
 最近一次修改记录 :
 修改作者   : 阮春博
 修改目的   : 新增函数
 修改日期   : 2012年3 月21 日
*******************************************************************************/
s32 get_connect_iden(struct connect_iden * conn_iden, s32 type)
{
	CONFIG *cfg ;
	const s8* name;

	if(type == 0)
	{
		CONNECT_IDEN_0(conn_iden->iden);
		conn_iden->cmd = 0;
	}
	else if(type == 1)
	{
		CONNECT_IDEN_1(conn_iden->iden);
		conn_iden->cmd = 1;
	}
		
	
	//从配置文件中读上网地址
	cfg = config_load(UMC_SERVER_IP);
    if (NULL == cfg)
    {
    	 return ERROR_FAIL;	
    }
	else
    {
    	name = config_get(cfg, "umc_user_name","");
	}

	conn_iden->len = strlen(name);
	
	netroomname = malloc(conn_iden->len);
	strncpy(netroomname, name, conn_iden->len);
	
	config_free(cfg);

	return ERROR_SUCCESS;
}
示例#9
0
文件: umc.c 项目: millken/zhuxianB30
/*******************************************************************************
函数名称  : umc_getip
功能描述  : 配置页面修改函数
输入参数  : tab_id: 页面id, modified: 是否修改
输出参数  : 
返 回 值  : OK成功,ERROR: 失败
--------------------------------------------------------------------------------
最近一次修改记录	:
修改作者	: liyanhua
修改目的	: 新函数
修改日期	: 2011年8月3日
*******************************************************************************/
s32 umc_getip(char* ipaddr,s32 ipaddr_len, s32 *port)
{
    CONFIG *cfg ;
	s32 ret = 0;
	const s8 *ipstr = NULL;

    if(ipaddr == NULL)
	{
		return 1;
	}
	
	/*从配置文件中读服务器ip*/
	cfg = config_load(UMC_SERVER_IP);
    if (NULL == cfg)
    {
    	return 1;
		
    }
	else
    {
		ipstr = config_get(cfg, "server_ip","");
		if(ipaddr==NULL)
		{
		    ret = 1;
		    goto OUT;
	    }
		
		*port = config_getint(cfg, "port", 0);
		
    }
    strncpy(ipaddr, ipstr, ipaddr_len);
    ipaddr[ipaddr_len-1] = '\0';
OUT:
	
	config_free(cfg);
    return ret;
}
示例#10
0
文件: main.c 项目: tony/oftc-ircd
int
main(int argc, char *argv[])
{
    serverstate_set_event_loop(uv_default_loop());

    config_init();
    listener_init();
    client_init();
    module_init();
    server_init();
    command_init();
    connection_init();

    process_commandline(argv, argc);

    config_load();
    listener_start_listeners();
    module_load_all_modules();
    connection_init_tls();

    uv_run(serverstate_get_event_loop(), UV_RUN_DEFAULT);

    return 0;
}
示例#11
0
s32 ws__setIpv6RapidEnable(WS_ENV* ws_env, s32 enable, s32 *ret)
{
    CONFIG * cfg = NULL;
    s32 flag = enable;
    s32 sys_ret = ERROR_SUCCESS; 
    s32 ws_ret = ERROR_SUCCESS;
	
	cfg = config_load(IPV6_RAPID_FILE);
	cfg = config_setint(cfg, "ipv6_rapid_enable", enable);
	config_store(cfg, IPV6_RAPID_FILE);
	config_free(cfg);
    ws_ret = conplat_syscall(MODULEID_TRANS_TECH, IP6_6RD_SYSCALL_ENABLE, &flag, 
        sizeof(s32), &sys_ret);
	/*FW业务版*/
	ws_ret = conplat_syscall(FW_MODULEID_TRANS_TECH | FW_BOARD, IP6_6RD_SYSCALL_ENABLE, &flag, 
	 	sizeof(s32), &sys_ret);
	if ( ws_ret != ERROR_SUCCESS || sys_ret != ERROR_SUCCESS)
	{
		return ERR_TRANS_TECH_SYSCALL;		
	}
	
	return WS_OK;

}
示例#12
0
s32 sysctl_ipv6_forward_restore(u32 slot_type)
{    
    CONFIG *cfg = NULL;
    s32 ipv6_forward = 0;
    s32 ret = ERROR_SUCCESS;
    cfg = config_load(SYSTEM_CTL_CONF_FILE);
    if (NULL != cfg)
    {             
        ipv6_forward = config_getint(cfg, "ipv6_power_flag", 0);
    }
    config_free(cfg);
    if (FW_BOARD == (slot_type&0xFF)) {
        /* 下发防火墙业务板 */
        conplat_syscall(FW_MODULEID_ISOEM|FW_BOARD, SYSCTL_SYSCALL_IP6_FORWARD, 
            &ipv6_forward, sizeof(s32), &ret);    
    } else if (ADX_BOARD == (slot_type&0xFF)) {
        /* 下发ADX业务板 */
        conplat_syscall(ADX_MODULEID_ISOEM|ADX_BOARD, SYSCTL_SYSCALL_IP6_FORWARD, 
            &ipv6_forward, sizeof(s32), &ret);      
    }
    
    return ret;

}
示例#13
0
int
main(int argc, char **argv)
{
	int ch;

	log_init(1);
	log_verbose(~0);

	while ((ch = getopt(argc, argv, "")) != -1) {
		switch (ch) {
		default:
			fatalx("bad option");
			/* NOTREACHED */
		}
	}
	argc -= optind;
	argv += optind;

	if (argc != 1)
		fatalx("bogus argument(s)");

	conffile = argv[0];

	if ((config = config_load(conffile)) == NULL)
		fatalx("error parsing config file");
	if (config_connect(config) == 0)
		fatalx("could not connect");

	table_api_on_update(table_postgres_update);
	table_api_on_check(table_postgres_check);
	table_api_on_lookup(table_postgres_lookup);
	table_api_on_fetch(table_postgres_fetch);
	table_api_dispatch();

	return 0;
}
示例#14
0
void kernel_init(void)
{
    dINT();
    printf("kernel_init(): This is RIOT! (Version: %s)\n", VERSION);

    hwtimer_init();

    if (thread_create(idle_stack, sizeof(idle_stack), PRIORITY_IDLE, CREATE_WOUT_YIELD | CREATE_STACKTEST, idle_thread, idle_name) < 0) {
        printf("kernel_init(): error creating idle task.\n");
    }

    if (thread_create(main_stack, sizeof(main_stack), PRIORITY_MAIN, CREATE_WOUT_YIELD | CREATE_STACKTEST, MAIN_FUNC, main_name) < 0) {
        printf("kernel_init(): error creating main task.\n");
    }

#ifdef MODULE_CONFIG
    DEBUG("kernel_init(): loading config\n");
    config_load();
#endif

    printf("kernel_init(): jumping into first task...\n");

    cpu_switch_context_exit();
}
示例#15
0
void
simbatch_init(int *argc, char **argv)
{
    const char *config_file;    
    const char *deployment_file;
    const char *request = "/config/global/file[@type=\"deployment\"]/text()";
    //const char *req = "/platform_description/process[@function=\"SB_batch\"]";
    
    if (parseCmdLine(*argc, argv)) {
        xbt_die("Error parsing command line");
    }
    config_file = getParam(argv, "-f");
    
#ifdef VERBOSE
    {
        int i = 0;
        fprintf(stderr, "*** Global init ***\n");
        fprintf(stderr, "DIET MODE %s\n", (DIET_MODE)? "enabled": "disable");
        fprintf(stderr, "DIET FILE %s\n", (DIET_FILE)? DIET_FILE: "disable");
        for (i=0; i<4; ++i)
            fprintf(stderr, "DIET_PARAM[%d] = %lu\n", i, DIET_PARAM[i]);
        fprintf(stderr, "Loading config file %s... ", config_file);
    }
#endif
	
    config = config_load(config_file);
    if (!config) {
#ifdef VERBOSE
        fprintf(stderr, "failed\n");
        fprintf(stderr, "Usage : %s -f simbatch_config.xml\n", argv[0]);
#endif
        free(config);
        xbt_die("Cant'load config file");
    }
    
#ifdef VERBOSE
    fprintf(stderr, "ok\n");
    fprintf(stderr, "Check batch deployed and batch defined... ");
#endif
    
    nbBatch = config_get_nb_nodes("/config/batch");
    deployment_file = config_get_value(request);
    
    /* 
     * A bit dirty - I need just one value in the deployment file 
     * So i do a context switch instead of changing my functions
     *//*
    {
        config_t * config_backup = config;
	
        config = config_load(deployment_file);
        if (!config) {
#ifdef VERBOSE 
            fprintf(stderr, "failed\n");
#endif
            free(config_backup);
            xbt_die("Cant'load deployment file");
        }
	
        nbBatchDeployed = config_get_nb_nodes(req);
        free(config);
        config = config_backup;
    }
    
    if (nbBatchDeployed != nbBatch) {
#ifdef VERBOSE
        fprintf(stderr, "failed\n");
#endif
        free(config);
        xbt_die("Batch deployed are not equal to batch defined");
    }
    
#ifdef VERBOSE
    fprintf(stderr, "ok\n");
    
    if (nbBatch <= 0)
        fprintf(stderr, "Warning no batch used\n");
    
    fprintf(stderr, "Number of batch defined  : %d\n", nbBatch);
#endif
    */
    book_of_plugin = xbt_dict_new(); 
    
#ifdef LOG
    book_of_log = xbt_dict_new();
    config_init_log_file();
#endif
    
}
示例#16
0
static void init(void) {
  config_load();

#ifdef ENABLE_LOCALIZE
  locale_init();
#endif
  heartrate_init();
  s_gpsdata.heartrate = 255; // no data at startup
  bg_color_data_main = BG_COLOR_DATA_MAIN;

#ifdef ENABLE_NAVIGATION_FULL
  for (uint16_t i = 0; i < NAV_NB_POINTS_STORAGE - 1; i++) {
    s_gpsdata.nav_xpos[i] = s_gpsdata.nav_ypos[i] = INT16_MAX;
  }
#endif

#ifdef ENABLE_DEBUG_FIELDS_SIZE
  strcpy(s_data.speed, "188.8");
  strcpy(s_data.distance, "88.8");
  strcpy(s_data.avgspeed, "888.8");
  strcpy(s_data.altitude, "888.8");
  strcpy(s_data.ascent, "1342");
  strcpy(s_data.ascentrate, "548");
  strcpy(s_data.slope, "5");
  strcpy(s_data.accuracy, "9");
  strcpy(s_data.bearing, "270");
  strcpy(s_data.elapsedtime, "1:05:28");
  strcpy(s_data.maxspeed, "25.3");
  strcpy(s_data.heartrate, "128");
  strcpy(s_data.cadence, "90");
#endif
#ifdef ENABLE_DEMO
  strcpy(s_data.maxspeed, "26.1");
  strcpy(s_data.distance, "2.0");
  strcpy(s_data.avgspeed, "14.0");
  strcpy(s_data.altitude, "1139");
  strcpy(s_data.accuracy, "4");
  strcpy(s_data.steps, "7548");
  strcpy(s_data.elapsedtime, "1:15:28");
  strcpy(s_data.heartrate, "154");
  s_gpsdata.heartrate = 154;
  heartrate_new_data(s_gpsdata.heartrate);
  s_data.live = 1;
  s_data.state = STATE_START;

  s_gpsdata.nav_distance_to_destination100 = 12100;
  s_gpsdata.nav_next_distance1000 = 1345;
  s_gpsdata.nav_error1000 = 55;
  snprintf(s_data.nav_next_distance,   sizeof(s_data.nav_next_distance),   "%d",   s_gpsdata.nav_next_distance1000);
#else
  strcpy(s_data.speed, "0.0");
  strcpy(s_data.distance, "-");
  strcpy(s_data.avgspeed, "-");
  strcpy(s_data.altitude, "-");
  strcpy(s_data.ascent, "-");
  strcpy(s_data.ascentrate, "-");
  strcpy(s_data.slope, "-");
  strcpy(s_data.accuracy, "-");
  strcpy(s_data.bearing, "-");
  strcpy(s_data.elapsedtime, "00:00:00");
  strcpy(s_data.maxspeed, "-");
  strcpy(s_data.heartrate, "-");
  strcpy(s_data.cadence, "-");
  strcpy(s_data.nav_next_distance, "-");
  strcpy(s_data.nav_distance_to_destination, "-");
  strcpy(s_data.nav_ttd, "-");
  strcpy(s_data.nav_eta, "-");
#endif
  //strcpy(s_data.lat, "-");
  //strcpy(s_data.lon, "-");
  //strcpy(s_data.nbascent, "-");

  s_data.phone_battery_level = -1;

#ifdef PBL_PLATFORM_CHALK
  font_roboto_bold_16 = fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_ROBOTO_BOLD_16));
#endif
  font_roboto_bold_62 = fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_ROBOTO_BOLD_62));

  // set default unit of measure
  change_units(UNITS_IMPERIAL, true);

  buttons_init();

  s_data.window = window_create();
  window_set_background_color(s_data.window, BG_COLOR_WINDOW);
#ifdef PBL_SDK_2
  window_set_fullscreen(s_data.window, true);
#endif
  topbar_layer_init(s_data.window);

  screen_data_layer_init(s_data.window);
  //screen_altitude_layer_init(s_data.window);
#ifdef ENABLE_FUNCTION_LIVE
  screen_live_layer_init(s_data.window);
#endif
  screen_map_layer_init(s_data.window);

  #ifdef PRODUCTION
    #ifndef ENABLE_DEMO
      screen_reset_instant_data();
    #endif
  #endif

  action_bar_init(s_data.window);
  menu_init();

  // Reduce the sniff interval for more responsive messaging at the expense of
  // increased energy consumption by the Bluetooth module
  // The sniff interval will be restored by the system after the app has been
  // unloaded
  //app_comm_set_sniff_interval(SNIFF_INTERVAL_REDUCED);
  
  communication_init();

  screen_data_update_config(true);
  //screen_altitude_update_config();
  graph_init();
  
  window_stack_push(s_data.window, true /* Animated */);
  
  tick_timer_service_subscribe(MINUTE_UNIT, handle_tick);
  bluetooth_connection_service_subscribe(bt_callback);
  
  send_version(true);
}
示例#17
0
文件: main.c 项目: blitzed-org/bopm
int main(int argc, char **argv)
{
   char spid[16];
   pid_t pid;
   int c;
   size_t lenc, lenl, lenp;
   unsigned int nc_counter, i;
   FILE *pidout;
   struct rlimit rlim;

   nc_counter = 0;

   while (1)
   {
      c = getopt(argc, argv, "dc:");

      if (c == -1)
         break;

      switch (c)
      {
         case 'c':
            CONFNAME = strdup(optarg);
            break;
         case 'd':
            OPT_DEBUG++;
            break;
         case '?':
         default:
            /* Unknown arg, guess we'll just do nothing for now. */
            break;
      }
   }

   lenc = strlen(CONFDIR) + strlen(CONFNAME) + strlen(CONFEXT) + 3;
   lenl = strlen(LOGDIR) + strlen(CONFNAME) + strlen(LOGEXT) + 3;
   lenp = strlen(LOGDIR) + strlen(CONFNAME) + strlen(PIDEXT) + 3;

   CONFFILE = MyMalloc(lenc * sizeof *CONFFILE);
   LOGFILE = MyMalloc(lenl * sizeof *LOGFILE);

   snprintf(CONFFILE, lenc, "%s/%s.%s", CONFDIR, CONFNAME, CONFEXT);
   snprintf(LOGFILE, lenl, "%s/%s.%s", LOGDIR, CONFNAME, LOGEXT);

   /* Fork off. */

   if (OPT_DEBUG <= 0)
   {
      if ((pid = fork()) < 0)
      {
         perror("fork()");
         exit(EXIT_FAILURE);
      }
      else if (pid != 0)
      {
         _exit(EXIT_SUCCESS);
      }

      /* Get us in our own process group. */
      if (setpgid(0, 0) < 0)
      {
         perror("setpgid()");
         exit(EXIT_FAILURE);
      }

      /* Reset file mode. */
      /* shasta: o+w is BAD, mmkay? */
      umask(002);

      /* Close file descriptors. */
      close(STDIN_FILENO);
      close(STDOUT_FILENO);
      close(STDERR_FILENO);

      log_open(LOGFILE);
   }
   else
      log_printf("MAIN -> Debug level %d", OPT_DEBUG);


   log_printf("MAIN -> BOPM %s started.", VERSION);
   log_printf("MAIN -> Reading configuration file...");

   config_load(CONFFILE);

   if (OptionsItem->scanlog)
      scanlog_open(OptionsItem->scanlog);

   pid = getpid();

   pidout = fopen(OptionsItem->pidfile, "w");
   snprintf(spid, 16, "%u", pid);

   if (pidout)
   {
      fwrite(spid, sizeof(char), strlen(spid), pidout);
      fclose(pidout);
   }
   else
   {
      log_printf("MAIN -> Error opening %s: %s", OptionsItem->pidfile,
          strerror(errno));
      exit(EXIT_FAILURE);
   }

   /* Setup alarm & int handlers. */

   ALARMACTION.sa_handler = &(do_signal);
   ALARMACTION.sa_flags = SA_RESTART;
   INTACTION.sa_handler = &(do_signal);
   USR1ACTION.sa_handler = &(do_signal);

   sigaction(SIGALRM, &ALARMACTION, 0);
   sigaction(SIGINT, &INTACTION, 0);
   sigaction(SIGUSR1, &USR1ACTION, 0);

   /* Ignore SIGPIPE. */
   signal(SIGPIPE, SIG_IGN);

   alarm(1);

   while (1)
   {
      

      /* Main cycles */
      irc_cycle();
      scan_cycle();


      /* Restart bopm if main_restart() was called (usually happens by m_kill in irc.c) */
      if(RESTART)
      {
         /* If restarted in debug mode, die */
         if(OPT_DEBUG)
            return(1); 

         log_printf("MAIN -> Restarting process");

         /* Get upper file descriptor limit */
         if(getrlimit(RLIMIT_NOFILE, &rlim) == -1) 
         {
            log_printf("MAIN RESTART -> getrlimit() error retrieving RLIMIT_NOFILE (%s)", strerror(errno));
            return(1); 
         }

         /* Set file descriptors 0-rlim_cur close on exec */
         for(i = 0; i < rlim.rlim_cur; i++)
            fcntl(i, F_SETFD, FD_CLOEXEC);

         /* execute new process */
         if(execve(argv[0], argv, NULL) == -1)
            log_printf("MAIN RESTART -> Execution of \"%s\" failed. ERROR: %s", argv[0], strerror(errno));

         /* Should only get here if execve failed */
         RESTART = 0;
      }

      /* Check for log reopen */
      if(REOPEN)
      {
         log_printf("MAIN -> Caught SIGUSR1, reopening logfiles");
         log_close();
         log_open(LOGFILE);

         if(OptionsItem->scanlog)
         {
            scanlog_close();
            scanlog_open(OptionsItem->scanlog);
         }

         log_printf("MAIN -> reopened logfiles");

         REOPEN = 0;
      }

      /* Call 1 second timers */
      if(ALARMED)
      {
         irc_timer();
         scan_timer();
         command_timer();

         ALARMED = 0;
      }


   }

   if (!OPT_DEBUG)
      log_close();

   /* If there's no scanlog open then this will do nothing anyway */
   scanlog_close();

   return(0);
}
示例#18
0
int
main(int argc, char* argv[])
{
	_debug_ = 0;

	samplecat_init();

	gtk_init_check(&argc, &argv);
	type_init();
	pixmaps_init();
	icon_theme_init();

	Window win;
	GLXContext ctx;
	GLboolean fullscreen = GL_FALSE;
	static int width = 400, height = 300;

	int i; for (i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-verbose") == 0) {
			_debug_ = 1;
		}
#if 0
		else if (strcmp(argv[i], "-swap") == 0 && i + 1 < argc) {
			swap_interval = atoi( argv[i+1] );
			do_swap_interval = GL_TRUE;
			i++;
		}
		else if (strcmp(argv[i], "-forcegetrate") == 0) {
			/* This option was put in because some DRI drivers don't support the
			 * full GLX_OML_sync_control extension, but they do support
			 * glXGetMscRateOML.
			 */
			force_get_rate = GL_TRUE;
		}
#endif
		else if (strcmp(argv[i], "-fullscreen") == 0) {
			fullscreen = GL_TRUE;
		}
		else if (strcmp(argv[i], "-help") == 0) {
			printf("Usage:\n");
			printf("  glx [options]\n");
			printf("Options:\n");
			printf("  -help                   Print this information\n");
			printf("  -verbose                Output info to stdout\n");
			printf("  -swap N                 Swap no more than once per N vertical refreshes\n");
			printf("  -forcegetrate           Try to use glXGetMscRateOML function\n");
			printf("  -fullscreen             Full-screen window\n");
			return 0;
		}
	}

	Display* dpy = XOpenDisplay(NULL);
	if(!dpy){
		printf("Error: couldn't open display %s\n", XDisplayName(NULL));
		return -1;
	}

	int screen = DefaultScreen(dpy);
	make_window(dpy, "Samplcecat", (XDisplayWidth(dpy, screen) - width) / 2, (XDisplayHeight(dpy, screen) - height) / 2, width, height, fullscreen, &win, &ctx);

	agl_get_extensions();

	glx_init(dpy);

	g_main_loop_new(NULL, true);

	scene = (AGlRootActor*)agl_actor__new_root_(CONTEXT_TYPE_GLX);

	void scene_needs_redraw(AGlScene* scene, gpointer _){ need_draw = true; }
	scene->draw = scene_needs_redraw;

	gboolean add_content(gpointer _)
	{ 
		app->config_ctx.filename = g_strdup_printf("%s/.config/" PACKAGE "/" PACKAGE, g_get_home_dir());
		config_load(&app->config_ctx, &app->config);

		if (app->config.database_backend && can_use(samplecat.model->backends, app->config.database_backend)) {
			#define list_clear(L) g_list_free(L); L = NULL;
			list_clear(samplecat.model->backends);
			samplecat_model_add_backend(app->config.database_backend);
		}

		db_init(
#ifdef USE_MYSQL
			&app->config.mysql
#else
			NULL
#endif
		);
		if (!db_connect()) {
			g_warning("cannot connect to any database.\n");
			return EXIT_FAILURE;
		}

		samplecat_list_store_do_search((SamplecatListStore*)samplecat.store);

		Waveform* w = NULL;

		WaveformCanvas* wfc = wf_context_new(scene);

		agl_actor__add_child((AGlActor*)scene, actors.bg = background_actor(NULL));
		actors.bg->region.x2 = 1;
		actors.bg->region.y2 = 1;

		agl_actor__add_child((AGlActor*)scene, actors.search = search_view(NULL));
		agl_actor__add_child((AGlActor*)scene, actors.list = list_view(NULL));

		agl_actor__add_child((AGlActor*)scene, actors.wave = (AGlActor*)wf_canvas_add_new_actor(wfc, w));

		void scene_set_size(AGlActor* scene)
		{
			#define SPACING 2
			int vspace = scene->region.y2 - 40;
			int y = 20;

			int h = search_view_height((SearchView*)actors.search);
			actors.search->region = (AGliRegion){20, y, scene->region.x2 - 20, y + h};
			agl_actor__set_size(actors.search);
			vspace -= h + SPACING;
			y += h + SPACING;

			actors.list->region = (AGliRegion){20, y, scene->region.x2 - 20, y + vspace / 2};
			vspace -= vspace / 2;
			y += vspace;
			agl_actor__set_size(actors.list); // clear cache

			actors.wave->region = (AGliRegion){
				20,
				y,
				scene->region.x2 - 20,
				y + vspace
			};
			wf_actor_set_rect((WaveformActor*)actors.wave, &(WfRectangle){
				0.0,
				0.0,
				agl_actor__width(actors.wave),
				agl_actor__height(actors.wave)
			});

			need_draw = true;
		}
示例#19
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//plugin_message
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int plugin_message(int tokencount, char *tokens[], bool from_core, module* caller)
{
	char *filename;

	if (tokencount == 3 && !stricmp(tokens[2], szBActionSave))
	{
		config_save(config_path_mainscript);
		return 0;
	}
	else if (!stricmp(tokens[2], szBActionSaveAs))
	{
		if (tokencount == 4)
		{
			config_save(tokens[3]);
		}
		else
		{       
			if ((filename = dialog_file(szFilterScript, "Save Configuration Script", ".rc", config_path_plugin, true)))
			{
				config_save(filename);
			}           
		}       
		return 0;
	}
	else if (tokencount == 3 && !stricmp(tokens[2], szBActionRevert))
	{
		plugin_reconfigure(true);
		return 0;
	}
	else if (!stricmp(tokens[2], szBActionLoad))
	{
		if (tokencount == 4)
		{
			config_load2(tokens[3], caller);
			return 0;
		}
		else if (tokencount == 3)
		{
			if ((filename = dialog_file(szFilterScript, "Load Configuration Script", ".rc", config_path_plugin, false)))
			{
				config_load2(filename, caller);
			}
			return 0;
		}
		else if (tokencount == 6)
		{
			if (0 == stricmp(tokens[4], "from"))
			{
				config_load(tokens[5], caller, tokens[3]);
				return 0;
			} else if (0 == stricmp(tokens[4], "into"))
			{
				config_load(tokens[3], module_get(tokens[5]));
				return 0;
			}
		}
		else if (tokencount == 8 && 0 == stricmp(tokens[4], "from") && 0 == stricmp(tokens[6], "into"))
		{
			config_load(tokens[5], module_get(tokens[7]), tokens[3]);
			return 0;
		}
	}
	else if (!stricmp(tokens[2], szBActionAbout))
	{
		if (tokencount == 3)
		{
			MessageBox(NULL, szPluginAbout, szVersion, MB_OK|MB_SYSTEMMODAL);
			return 0;
		}
		else if (tokencount == 4 && !stricmp(tokens[3], "LastControl"))
		{
			MessageBox(NULL, szPluginAboutLastControl, szAppName, MB_OK|MB_SYSTEMMODAL);
			return 0;
		}
		else if (tokencount == 4 && !stricmp(tokens[3], "QuickHelp"))
		{
			MessageBox(NULL, szPluginAboutQuickRef, szAppName, MB_OK|MB_SYSTEMMODAL);
			return 0;
		}
	}
	else if (!stricmp(tokens[2], szBActionEdit))
	{
		//SendMessage(plugin_hwnd_blackbox, BB_EDITFILE, (WPARAM)-1, (LPARAM) config_path_mainscript);
		//return 0;
		char temp[MAX_PATH]; GetBlackboxEditor(temp);
		BBExecute(NULL, "",temp , config_path_mainscript, NULL, SW_SHOWNORMAL, false);
		return 0;
	}
	else if (tokencount == 5 && !stricmp(tokens[2], szBActionSetPluginProperty))
	{
		for (struct plugin_properties *p = plugin_properties; p->key; p++)
			if (p->data && 0 == stricmp(tokens[3], p->key)) {
				switch (p->type) {
					case M_BOL:
						if (config_set_bool(tokens[4], (bool*)p->data)) break; return 1;
					case M_INT:
						if (config_set_int(tokens[4], (int*)p->data)) break; return 1;
					case M_STR:
						if (config_set_str(tokens[4], (char**)p->data)) break; return 1;
					default: return 1;
				}
				if (p->update) control_invalidate();
				if (from_core) menu_update_global();
				return 0;
			}
	}
	else if (tokencount == 4 && !stricmp(tokens[2], szBActionOnLoad) )
	{
		config_set_str(tokens[3],&(globalmodule.actions[MODULE_ACTION_ONLOAD]));
		return 0;
	}
	else if (tokencount == 4 && !stricmp(tokens[2], szBActionOnUnload) )
	{
		config_set_str(tokens[3],&(globalmodule.actions[MODULE_ACTION_ONUNLOAD]));
		return 0;
	}
	return 1;
}
示例#20
0
文件: main.c 项目: lubomyr/Neverball
int main(int argc, char *argv[])
{
    SDL_Joystick *joy = NULL;
    int t1, t0, uniform;

    if (!fs_init(argv[0]))
    {
        fprintf(stderr, "Failure to initialize virtual file system: %s\n",
                fs_error());
        return 1;
    }

    lang_init("neverball");

    parse_args(argc, argv);

    config_paths(data_path);
    make_dirs_and_migrate();

    /* Initialize SDL system and subsystems */

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) == -1)
    {
        fprintf(stderr, "%s\n", SDL_GetError());
        return 1;
    }

    /* Intitialize the configuration */

    config_init();
    config_load();

    /* Initialize the joystick. */

    if (config_get_d(CONFIG_JOYSTICK) && SDL_NumJoysticks() > 0)
    {
        joy = SDL_JoystickOpen(config_get_d(CONFIG_JOYSTICK_DEVICE));
        if (joy)
            SDL_JoystickEventState(SDL_ENABLE);
    }

    /* Initialize the audio. */

    audio_init();
    tilt_init();

    /* Initialize the video. */

    if (!video_init(TITLE, ICON))
        return 1;

    init_state(&st_null);

    /* Initialise demo playback. */

    if (demo_path && fs_add_path(dir_name(demo_path)) &&
        progress_replay(base_name(demo_path, NULL)))
    {
        demo_play_goto(1);
        goto_state(&st_demo_play);
    }
    else
        goto_state(&st_title);

    /* Run the main game loop. */

    uniform = config_get_d(CONFIG_UNIFORM);
    t0 = SDL_GetTicks();

    while (loop())
    {
        t1 = SDL_GetTicks();

        if (uniform)
        {
            /* Step the game uniformly, as configured. */

            int u;

            for (u = 0; u < abs(uniform); ++u)
            {
                st_timer(DT);
                t0 += (int) (DT * 1000);
            }
        }
        else
        {
            /* Step the game state at least up to the current time. */

            while (t1 > t0)
            {
                st_timer(DT);
                t0 += (int) (DT * 1000);
            }
        }

        /* Render. */

        st_paint(0.001f * t0);
        video_swap();

        if (uniform < 0)
            shot();

        if (config_get_d(CONFIG_NICE))
            SDL_Delay(1);
    }

    /* Gracefully close the game */

    if (joy)
        SDL_JoystickClose(joy);

    tilt_free();
    SDL_Quit();

    config_save();

    return 0;
}
示例#21
0
int main(int argc, char **argv, char **env)
{
	int c, ret;
	my_argv	= argv;
        char *ce;

    uselogchan  = 1;
    starttime   = time(NULL);
    skip_banner = 0;

#if defined(RLIMIT_CORE) && defined(HAVE_SYS_RESOURCE_H)
    // Make sure we can dump a core
    struct rlimit   rlim;
    ret = getrlimit (RLIMIT_CORE, &rlim);

    if (ret == 0)
    {
        if (rlim.rlim_cur == 0)
        {
            //fprintf (stderr, "Core limit 0, attempting to set to %d\n", rlim.rlim_max);

            rlim.rlim_cur    = rlim.rlim_max;

            setrlimit (RLIMIT_CORE, &rlim);
        }
    }
#endif

#ifdef HAVE_GNUTLS
    gnutls_global_init ();

    gnutls_certificate_allocate_credentials (&tls_x509_cred);
#endif

		SetTime();

        sprintf (CfgSettings.conf_name, "%s/%s", EPATH, "security.cfg");

        my_env = env;

        while ((c = getopt (argc, argv, "xrshbvntd:c:l:")) != -1)
        {
            switch (c)
            {
                case 'x':
			skip_banner = 1;
			break; 
				case 'h':
					showHelp ();
                    break;
                case 'v':
                        printf("Version: \033[1;31m%s %s-%s\033[0m\n",PACKAGE_NAME,PACKAGE_VERSION,VERSION_STRING);
                        exit(0);
                case 's':
                        nomodules = 1;
                        break;
                case 'd':
						if (optarg)	{
							debug	= atoi(optarg);
							if ((debug < 1) || (debug > 3))
							{
								fprintf (stderr, "Invalid value for -d (%d)\n", debug);
								exit (0);
							}
						}
                        break;
                case 'n':
                        nofork = 1;
                        break;
                case 'c':
						if (optarg) {
	                        if ((optarg[strlen(optarg) - 4] == '.') && optarg[strlen(optarg) - 3] == 'c') {
                                if ((*optarg == '/') || (*optarg == '.'))
                                    strlcpy (CfgSettings.conf_name, optarg, sizeof(CfgSettings.conf_name));
                                else
	                                sprintf (CfgSettings.conf_name, "%s/%s", EPATH, optarg);
                            }
							else
								fprintf(stderr,"Invalid config file specified with -c option skipping.\n");
						}
                        break;
                case 'l':
                        if (optarg)
                            memcpy(logchan,optarg,sizeof(logchan));
                        break;
                case 't':
			config_test();
			exit(0);
            }
        }


        //check to see if were running under root and bail
        if ((getuid() == 0) && (getgid() == 0))
        {
            printf("Error: You are currently trying to run this program as root\n");
            printf("This program does not require root privileges ...\n");
            printf(" \n");
            printf("Running an application as root that does not require root privileges\n");
            printf("can and may have undesirable side effects. \n");
            printf("    We strongly caution against this.       \n");
            exit(0);
        }

        if (chdir (DPATH))
        {
              fprintf (stderr, "Unable to chdir to %s: %s\n", DPATH, strerror(errno));
              exit (EXIT_FAILURE);
        }


		Omega = Core_Construct(); //initialize our core class.
		
        init_lists ();
		InitDefaults();
	
        //we should work on making this more detailed in its error throws
        if (!config_load (CfgSettings.conf_name)) {
               fprintf(stderr, "Unable to read config file.\n");
               exit(0);
        } 
		VerifyConf();
		 

        DaemonSeed();

        atexit(AtExit);
	 
        Run();

        //we returned from Run() Some how :/ i shit you not.. we need to exit ;( *tear*
            Exit(0);
        return 0;
}
示例#22
0
int rarch_main(int argc, char *argv[])
{
   //Initialize bps
#ifndef HAVE_BB10
   bps_initialize();
   rarch_main_clear_state();
   strlcpy(g_settings.libretro, "app/native/lib", sizeof(g_settings.libretro));
#endif
   strlcpy(g_extern.config_path, "app/native/retroarch.cfg", sizeof(g_extern.config_path));
   strlcpy(g_settings.video.shader_dir, "app/native/shaders_glsl", sizeof(g_settings.video.shader_dir));

   config_load();

   g_extern.verbose = true;

   menu_init();

   g_extern.lifecycle_mode_state |= (1ULL << MODE_LOAD_GAME);

#ifdef HAVE_BB10
   if (!g_extern.libretro_dummy)
      menu_rom_history_push_current();
#endif

   for (;;)
   {
      if (g_extern.system.shutdown)
         break;
      else if (g_extern.lifecycle_mode_state & (1ULL << MODE_LOAD_GAME))
      {
         load_menu_game_prepare();

         // If ROM load fails, we exit RetroArch. On console it might make more sense to go back to menu though ...
         if (load_menu_game())
            g_extern.lifecycle_mode_state |= (1ULL << MODE_GAME);
         else
         {
#if defined(RARCH_CONSOLE) || defined(__BLACKBERRY_QNX__)
            g_extern.lifecycle_mode_state |= (1ULL << MODE_MENU);
#else
            return 1;
#endif
         }

         g_extern.lifecycle_mode_state &= ~(1ULL << MODE_LOAD_GAME);
      }
      else if (g_extern.lifecycle_mode_state & (1ULL << MODE_GAME))
      {
	     while ((g_extern.is_paused && !g_extern.is_oneshot) ? rarch_main_idle_iterate() : rarch_main_iterate());
	        g_extern.lifecycle_mode_state &= ~(1ULL << MODE_GAME);
      }
      else if (g_extern.lifecycle_mode_state & (1ULL << MODE_MENU))
      {
         g_extern.lifecycle_mode_state |= 1ULL << MODE_MENU_PREINIT;
         while (!g_extern.system.shutdown && menu_iterate());
         g_extern.lifecycle_mode_state &= ~(1ULL << MODE_MENU);
      }
      else
         break;
   }

   g_extern.system.shutdown = false;

   menu_free();

   if (g_extern.config_save_on_exit && *g_extern.config_path)
      config_save_file(g_extern.config_path);

   if (g_extern.main_is_init)
      rarch_main_deinit();

   rarch_deinit_msg_queue();

#ifdef PERF_TEST
   rarch_perf_log();
#endif

error:
   bps_shutdown();

   return 0;
}
示例#23
0
static void options(int *argc, char ***argv) {
	char **if_a = NULL;
	char **ks_a = NULL;
	unsigned long uint_keyspace_db;
	str str_keyspace_db;
	char **iter;
	char *listenps = NULL;
	char *listenudps = NULL;
	char *listenngs = NULL;
	char *listencli = NULL;
	char *graphitep = NULL;
	char *graphite_prefix_s = NULL;
	char *redisps = NULL;
	char *redisps_write = NULL;
	char *log_facility_cdr_s = NULL;
	char *log_facility_rtcp_s = NULL;
	char *log_facility_dtmf_s = NULL;
	char *log_format = NULL;
	int sip_source = 0;
	char *homerp = NULL;
	char *homerproto = NULL;
	char *endptr;
	int codecs = 0;
	double max_load = 0;
	double max_cpu = 0;

	GOptionEntry e[] = {
		{ "table",	't', 0, G_OPTION_ARG_INT,	&rtpe_config.kernel_table,		"Kernel table to use",		"INT"		},
		{ "no-fallback",'F', 0, G_OPTION_ARG_NONE,	&rtpe_config.no_fallback,	"Only start when kernel module is available", NULL },
		{ "interface",	'i', 0, G_OPTION_ARG_STRING_ARRAY,&if_a,	"Local interface for RTP",	"[NAME/]IP[!IP]"},
		{ "subscribe-keyspace", 'k', 0, G_OPTION_ARG_STRING_ARRAY,&ks_a,	"Subscription keyspace list",	"INT INT ..."},
		{ "listen-tcp",	'l', 0, G_OPTION_ARG_STRING,	&listenps,	"TCP port to listen on",	"[IP:]PORT"	},
		{ "listen-udp",	'u', 0, G_OPTION_ARG_STRING,	&listenudps,	"UDP port to listen on",	"[IP46|HOSTNAME:]PORT"	},
		{ "listen-ng",	'n', 0, G_OPTION_ARG_STRING,	&listenngs,	"UDP port to listen on, NG protocol", "[IP46|HOSTNAME:]PORT"	},
		{ "listen-cli", 'c', 0, G_OPTION_ARG_STRING,    &listencli,     "UDP port to listen on, CLI",   "[IP46|HOSTNAME:]PORT"     },
		{ "graphite", 'g', 0, G_OPTION_ARG_STRING,    &graphitep,     "Address of the graphite server",   "IP46|HOSTNAME:PORT"     },
		{ "graphite-interval",  'G', 0, G_OPTION_ARG_INT,    &rtpe_config.graphite_interval,  "Graphite send interval in seconds",    "INT"   },
		{ "graphite-prefix",0,  0,	G_OPTION_ARG_STRING, &graphite_prefix_s, "Prefix for graphite line", "STRING"},
		{ "tos",	'T', 0, G_OPTION_ARG_INT,	&rtpe_config.default_tos,		"Default TOS value to set on streams",	"INT"		},
		{ "control-tos",0 , 0, G_OPTION_ARG_INT,	&rtpe_config.control_tos,		"Default TOS value to set on control-ng",	"INT"		},
		{ "timeout",	'o', 0, G_OPTION_ARG_INT,	&rtpe_config.timeout,	"RTP timeout",			"SECS"		},
		{ "silent-timeout",'s',0,G_OPTION_ARG_INT,	&rtpe_config.silent_timeout,"RTP timeout for muted",	"SECS"		},
		{ "final-timeout",'a',0,G_OPTION_ARG_INT,	&rtpe_config.final_timeout,	"Call timeout",			"SECS"		},
		{ "offer-timeout",0,0,	G_OPTION_ARG_INT,	&rtpe_config.offer_timeout,	"Timeout for incomplete one-sided calls",	"SECS"		},
		{ "port-min",	'm', 0, G_OPTION_ARG_INT,	&rtpe_config.port_min,	"Lowest port to use for RTP",	"INT"		},
		{ "port-max",	'M', 0, G_OPTION_ARG_INT,	&rtpe_config.port_max,	"Highest port to use for RTP",	"INT"		},
		{ "redis",	'r', 0, G_OPTION_ARG_STRING,	&redisps,	"Connect to Redis database",	"[PW@]IP:PORT/INT"	},
		{ "redis-write",'w', 0, G_OPTION_ARG_STRING,    &redisps_write, "Connect to Redis write database",      "[PW@]IP:PORT/INT"       },
		{ "redis-num-threads", 0, 0, G_OPTION_ARG_INT, &rtpe_config.redis_num_threads, "Number of Redis restore threads",      "INT"       },
		{ "redis-expires", 0, 0, G_OPTION_ARG_INT, &rtpe_config.redis_expires_secs, "Expire time in seconds for redis keys",      "INT"       },
		{ "no-redis-required", 'q', 0, G_OPTION_ARG_NONE, &rtpe_config.no_redis_required, "Start no matter of redis connection state", NULL },
		{ "redis-allowed-errors", 0, 0, G_OPTION_ARG_INT, &rtpe_config.redis_allowed_errors, "Number of allowed errors before redis is temporarily disabled", "INT" },
		{ "redis-disable-time", 0, 0, G_OPTION_ARG_INT, &rtpe_config.redis_disable_time, "Number of seconds redis communication is disabled because of errors", "INT" },
		{ "redis-cmd-timeout", 0, 0, G_OPTION_ARG_INT, &rtpe_config.redis_cmd_timeout, "Sets a timeout in milliseconds for redis commands", "INT" },
		{ "redis-connect-timeout", 0, 0, G_OPTION_ARG_INT, &rtpe_config.redis_connect_timeout, "Sets a timeout in milliseconds for redis connections", "INT" },
		{ "b2b-url",	'b', 0, G_OPTION_ARG_STRING,	&rtpe_config.b2b_url,	"XMLRPC URL of B2B UA"	,	"STRING"	},
		{ "log-facility-cdr",0,  0, G_OPTION_ARG_STRING, &log_facility_cdr_s, "Syslog facility to use for logging CDRs", "daemon|local0|...|local7"},
		{ "log-facility-rtcp",0,  0, G_OPTION_ARG_STRING, &log_facility_rtcp_s, "Syslog facility to use for logging RTCP", "daemon|local0|...|local7"},
		{ "log-facility-dtmf",0,  0, G_OPTION_ARG_STRING, &log_facility_dtmf_s, "Syslog facility to use for logging DTMF", "daemon|local0|...|local7"},
		{ "log-format",	0, 0,	G_OPTION_ARG_STRING,	&log_format,	"Log prefix format",		"default|parsable"},
		{ "xmlrpc-format",'x', 0, G_OPTION_ARG_INT,	&rtpe_config.fmt,	"XMLRPC timeout request format to use. 0: SEMS DI, 1: call-id only, 2: Kamailio",	"INT"	},
		{ "num-threads",  0, 0, G_OPTION_ARG_INT,	&rtpe_config.num_threads,	"Number of worker threads to create",	"INT"	},
		{ "media-num-threads",  0, 0, G_OPTION_ARG_INT,	&rtpe_config.media_num_threads,	"Number of worker threads for media playback",	"INT"	},
		{ "delete-delay",  'd', 0, G_OPTION_ARG_INT,    &rtpe_config.delete_delay,  "Delay for deleting a session from memory.",    "INT"   },
		{ "sip-source",  0,  0, G_OPTION_ARG_NONE,	&sip_source,	"Use SIP source address by default",	NULL	},
		{ "dtls-passive", 0, 0, G_OPTION_ARG_NONE,	&dtls_passive_def,"Always prefer DTLS passive role",	NULL	},
		{ "max-sessions", 0, 0, G_OPTION_ARG_INT,	&rtpe_config.max_sessions,	"Limit of maximum number of sessions",	"INT"	},
		{ "max-load",	0, 0,	G_OPTION_ARG_DOUBLE,	&max_load,	"Reject new sessions if load averages exceeds this value",	"FLOAT"	},
		{ "max-cpu",	0, 0,	G_OPTION_ARG_DOUBLE,	&max_cpu,	"Reject new sessions if CPU usage (in percent) exceeds this value",	"FLOAT"	},
		{ "max-bandwidth",0, 0,	G_OPTION_ARG_INT64,	&rtpe_config.bw_limit,	"Reject new sessions if bandwidth usage (in bytes per second) exceeds this value",	"INT"	},
		{ "homer",	0,  0, G_OPTION_ARG_STRING,	&homerp,	"Address of Homer server for RTCP stats","IP46|HOSTNAME:PORT"},
		{ "homer-protocol",0,0,G_OPTION_ARG_STRING,	&homerproto,	"Transport protocol for Homer (default udp)",	"udp|tcp"	},
		{ "homer-id",	0,  0, G_OPTION_ARG_STRING,	&rtpe_config.homer_id,	"'Capture ID' to use within the HEP protocol", "INT"	},
		{ "recording-dir", 0, 0, G_OPTION_ARG_STRING,	&rtpe_config.spooldir,	"Directory for storing pcap and metadata files", "FILE"	},
		{ "recording-method",0, 0, G_OPTION_ARG_STRING,	&rtpe_config.rec_method,	"Strategy for call recording",		"pcap|proc"	},
		{ "recording-format",0, 0, G_OPTION_ARG_STRING,	&rtpe_config.rec_format,	"File format for stored pcap files",	"raw|eth"	},
#ifdef WITH_IPTABLES_OPTION
		{ "iptables-chain",0,0,	G_OPTION_ARG_STRING,	&rtpe_config.iptables_chain,"Add explicit firewall rules to this iptables chain","STRING" },
#endif
		{ "codecs",	0, 0,	G_OPTION_ARG_NONE,	&codecs,		"Print a list of supported codecs and exit",	NULL },
		{ "scheduling",	0, 0,	G_OPTION_ARG_STRING,	&rtpe_config.scheduling,"Thread scheduling policy",	"default|none|fifo|rr|other|batch|idle" },
		{ "priority",	0, 0,	G_OPTION_ARG_INT,	&rtpe_config.priority,	"Thread scheduling priority",	"INT" },
		{ "idle-scheduling",0, 0,G_OPTION_ARG_STRING,	&rtpe_config.idle_scheduling,"Idle thread scheduling policy",	"default|none|fifo|rr|other|batch|idle" },
		{ "idle-priority",0, 0,	G_OPTION_ARG_INT,	&rtpe_config.idle_priority,"Idle thread scheduling priority",	"INT" },
		{ "log-srtp-keys",'F', 0, G_OPTION_ARG_NONE,	&rtpe_config.log_keys,	"Log SRTP keys to error log", NULL },
		{ "mysql-host",	0,   0,	G_OPTION_ARG_STRING,	&rtpe_config.mysql_host,"MySQL host for stored media files","HOST|IP"	},
		{ "mysql-port",	0,   0,	G_OPTION_ARG_INT,	&rtpe_config.mysql_port,"MySQL port"				,"INT"		},
		{ "mysql-user",	0,   0,	G_OPTION_ARG_STRING,	&rtpe_config.mysql_user,"MySQL connection credentials",		"USERNAME"	},
		{ "mysql-pass",	0,   0,	G_OPTION_ARG_STRING,	&rtpe_config.mysql_pass,"MySQL connection credentials",		"PASSWORD"	},
		{ "mysql-query",0,   0,	G_OPTION_ARG_STRING,	&rtpe_config.mysql_query,"MySQL select query",			"STRING"	},
		{ NULL, }
	};

	config_load(argc, argv, e, " - next-generation media proxy",
			"/etc/rtpengine/rtpengine.conf", "rtpengine", &rtpe_config.common);

	if (codecs) {
		codeclib_init(1);
		exit(0);
	}

	if (!if_a)
		die("Missing option --interface");
	if (!listenps && !listenudps && !listenngs)
		die("Missing option --listen-tcp, --listen-udp or --listen-ng");

	struct ifaddrs *ifas;
	if (getifaddrs(&ifas)) {
		ifas = NULL;
		ilog(LOG_WARN, "Failed to retrieve list of network interfaces: %s", strerror(errno));
	}
	for (iter = if_a; *iter; iter++) {
		int ret = if_addr_parse(&rtpe_config.interfaces, *iter, ifas);
		if (ret)
			die("Invalid interface specification: '%s'", *iter);
	}
	if (ifas)
		freeifaddrs(ifas);

	if (!rtpe_config.interfaces.length)
		die("Cannot start without any configured interfaces");

	if (ks_a) {
		for (iter = ks_a; *iter; iter++) {
			str_keyspace_db.s = *iter;
			str_keyspace_db.len = strlen(*iter);
			uint_keyspace_db = strtoul(str_keyspace_db.s, &endptr, 10);

			if ((errno == ERANGE && (uint_keyspace_db == ULONG_MAX)) ||
			    (errno != 0 && uint_keyspace_db == 0)) {
				ilog(LOG_ERR, "Fail adding keyspace '%.*s' to redis notifications; errono=%d\n", str_keyspace_db.len, str_keyspace_db.s, errno);
			} else if (endptr == str_keyspace_db.s) {
				ilog(LOG_ERR, "Fail adding keyspace '%.*s' to redis notifications; no digits found\n", str_keyspace_db.len, str_keyspace_db.s);
			} else {
				g_queue_push_tail(&rtpe_config.redis_subscribed_keyspaces, GUINT_TO_POINTER(uint_keyspace_db));
			}
		}
	}

	if (listenps) {
		if (endpoint_parse_any_getaddrinfo(&rtpe_config.tcp_listen_ep, listenps))
			die("Invalid IP or port '%s' (--listen-tcp)", listenps);
	}
	if (listenudps) {
		if (endpoint_parse_any_getaddrinfo(&rtpe_config.udp_listen_ep, listenudps))
			die("Invalid IP or port '%s' (--listen-udp)", listenudps);
	}
	if (listenngs) {
		if (endpoint_parse_any_getaddrinfo(&rtpe_config.ng_listen_ep, listenngs))
			die("Invalid IP or port '%s' (--listen-ng)", listenngs);
	}

	if (listencli) {if (endpoint_parse_any_getaddrinfo(&rtpe_config.cli_listen_ep, listencli))
	    die("Invalid IP or port '%s' (--listen-cli)", listencli);
	}

	if (graphitep) {if (endpoint_parse_any_getaddrinfo_full(&rtpe_config.graphite_ep, graphitep))
	    die("Invalid IP or port '%s' (--graphite)", graphitep);
	}

	if (graphite_prefix_s)
		set_prefix(graphite_prefix_s);

	if (homerp) {
		if (endpoint_parse_any_getaddrinfo_full(&rtpe_config.homer_ep, homerp))
			die("Invalid IP or port '%s' (--homer)", homerp);
	}
	if (homerproto) {
		if (!strcmp(homerproto, "tcp"))
			rtpe_config.homer_protocol = SOCK_STREAM;
		else if (!strcmp(homerproto, "udp"))
			rtpe_config.homer_protocol = SOCK_DGRAM;
		else
			die("Invalid protocol '%s' (--homer-protocol)", homerproto);
	}

	if (rtpe_config.default_tos < 0 || rtpe_config.default_tos > 255)
		die("Invalid TOS value");

	if (rtpe_config.control_tos < 0 || rtpe_config.control_tos > 255)
		die("Invalid control-ng TOS value");

	if (rtpe_config.timeout <= 0)
		rtpe_config.timeout = 60;

	if (rtpe_config.silent_timeout <= 0)
		rtpe_config.silent_timeout = 3600;

	if (rtpe_config.offer_timeout <= 0)
		rtpe_config.offer_timeout = 3600;

	if (rtpe_config.final_timeout <= 0)
		rtpe_config.final_timeout = 0;

	if (redisps)
		if (redis_ep_parse(&rtpe_config.redis_ep, &rtpe_config.redis_db, &rtpe_config.redis_auth, "RTPENGINE_REDIS_AUTH_PW", redisps))
			die("Invalid Redis endpoint [IP:PORT/INT] '%s' (--redis)", redisps);

	if (redisps_write)
		if (redis_ep_parse(&rtpe_config.redis_write_ep, &rtpe_config.redis_write_db, &rtpe_config.redis_write_auth,
					"RTPENGINE_REDIS_WRITE_AUTH_PW", redisps_write))
			die("Invalid Redis endpoint [IP:PORT/INT] '%s' (--redis-write)", redisps_write);

	if (rtpe_config.fmt > 2)
		die("Invalid XMLRPC format");

	// XXX unify the log facility options
	if (log_facility_cdr_s) {
		if (!parse_log_facility(log_facility_cdr_s, &_log_facility_cdr)) {
			print_available_log_facilities();
			die ("Invalid log facility for CDR '%s' (--log-facility-cdr)", log_facility_cdr_s);
		}
	}

	if (log_facility_rtcp_s) {
		if (!parse_log_facility(log_facility_rtcp_s, &_log_facility_rtcp)) {
			print_available_log_facilities();
			die ("Invalid log facility for RTCP '%s' (--log-facility-rtcp)n", log_facility_rtcp_s);
		}
	}

	if (log_facility_dtmf_s) {
		if (!parse_log_facility(log_facility_dtmf_s, &_log_facility_dtmf)) {
			print_available_log_facilities();
			die ("Invalid log facility for DTMF '%s' (--log-facility-dtmf)n", log_facility_dtmf_s);
		}
	}

	if (log_format) {
		if (!strcmp(log_format, "default"))
			rtpe_config.log_format = LF_DEFAULT;
		else if (!strcmp(log_format, "parsable"))
			rtpe_config.log_format = LF_PARSABLE;
		else
			die("Invalid --log-format option");
	}

	if (!sip_source)
		trust_address_def = 1;

	rtpe_config.cpu_limit = max_cpu * 100;
	rtpe_config.load_limit = max_load * 100;

	if (rtpe_config.mysql_query) {
		// require exactly one %llu placeholder and allow no other % placeholders
		if (!strstr(rtpe_config.mysql_query, "%llu"))
			die("No '%%llu' present in --mysql-query='%s'", rtpe_config.mysql_query);
		const char *front = rtpe_config.mysql_query;
		unsigned int count = 0;
		const char *match;
		while ((match = strchr(front, '%'))) {
			front = match + 1;
			count++;
		}
		if (count != 1)
			die("Too many '%%' placeholders (%u) present in --mysql-query='%s'",
					count, rtpe_config.mysql_query);
	}
}
示例#24
0
void auto_init(void)
{
#ifdef MODULE_CONFIG
    DEBUG("Auto init loading config\n");
    config_load();
#endif

#ifdef MODULE_XTIMER
    DEBUG("Auto init xtimer module.\n");
    xtimer_init();
#endif
#ifdef MODULE_RTC
    DEBUG("Auto init rtc module.\n");
    rtc_init();
#endif
#ifdef MODULE_SHT11
    DEBUG("Auto init SHT11 module.\n");
    sht11_init();
#endif
#ifdef MODULE_GPIOINT
    DEBUG("Auto init gpioint module.\n");
    gpioint_init();
#endif
#ifdef MODULE_LTC4150
    DEBUG("Auto init ltc4150 module.\n");
    ltc4150_init();
#endif
#ifdef MODULE_MCI
    DEBUG("Auto init mci module.\n");
    MCI_initialize();
#endif
#ifdef MODULE_PROFILING
    extern void profiling_init(void);
    profiling_init();
#endif
#ifdef MODULE_GNRC_PKTBUF
    DEBUG("Auto init gnrc_pktbuf module\n");
    gnrc_pktbuf_init();
#endif
#ifdef MODULE_GNRC_PKTDUMP
    DEBUG("Auto init gnrc_pktdump module.\n");
    gnrc_pktdump_init();
#endif
#ifdef MODULE_GNRC_SIXLOWPAN
    DEBUG("Auto init gnrc_sixlowpan module.\n");
    gnrc_sixlowpan_init();
#endif
#ifdef MODULE_GNRC_IPV6
    DEBUG("Auto init gnrc_ipv6 module.\n");
    gnrc_ipv6_init();
#endif
#ifdef MODULE_GNRC_UDP
    DEBUG("Auto init UDP module.\n");
    gnrc_udp_init();
#endif


/* initialize network devices */
#ifdef MODULE_AUTO_INIT_GNRC_NETIF

#ifdef MODULE_AT86RF2XX
    extern void auto_init_at86rf2xx(void);
    auto_init_at86rf2xx();
#endif

#ifdef MODULE_ENCX24J600
    extern void auto_init_encx24j600(void);
    auto_init_encx24j600();
#endif

#ifdef MODULE_GNRC_SLIP
    extern void auto_init_slip(void);
    auto_init_slip();
#endif

#ifdef MODULE_XBEE
    extern void auto_init_xbee(void);
    auto_init_xbee();
#endif

#ifdef MODULE_KW2XRF
    extern void auto_init_kw2xrf(void);
    auto_init_kw2xrf();
#endif

#ifdef MODULE_NETDEV2_TAP
    extern void auto_init_netdev2_tap(void);
    auto_init_netdev2_tap();
#endif

#endif /* MODULE_AUTO_INIT_GNRC_NETIF */

#ifdef MODULE_GNRC_IPV6_NETIF
    gnrc_ipv6_netif_init_by_dev();
#endif
}
int main(int argc, char *argv[])
{
    int result = ACTION_NONE;
    int leave = 0;

    /* i18n */
#ifdef ENABLE_NLS
    setlocale (LC_ALL, "");
    bindtextdomain (PACKAGE, LOCALEDIR);
    textdomain (PACKAGE);
#endif
    
    /* ltris info */
    printf( "LTris %s\nCopyright 2002-2005 Michael Speck\nPublished under GNU GPL\n---\n", VERSION );
    printf( "Looking up data in: %s\n", SRC_DIR );
#ifndef SOUND
    printf( "Compiled without sound and music\n" );
#endif

    set_random_seed(); /* set random seed */

    /* game ids - not translated to be fixed independant of language */
    strcpy(gametype_ids[0],"demo");
    strcpy(gametype_ids[1],"classic");
    strcpy(gametype_ids[2],"figures");
    strcpy(gametype_ids[3],"vshuman");
    strcpy(gametype_ids[4],"vscpu");
    strcpy(gametype_ids[5],"vshumanhuman");
    strcpy(gametype_ids[6],"vshumancpu");
    strcpy(gametype_ids[7],"vscpucpu");
    /* game names - translated for display */
    strcpy(gametype_names[0],_("Demo"));
    strcpy(gametype_names[1],_("Classic"));
    strcpy(gametype_names[2],_("Figures"));
    strcpy(gametype_names[3],_("Vs Human"));
    strcpy(gametype_names[4],_("Vs CPU"));
    strcpy(gametype_names[5],_("Vs Human&Human"));
    strcpy(gametype_names[6],_("Vs Human&CPU"));
    strcpy(gametype_names[7],_("Vs CPU&CPU"));
    config_load();

    init_sdl( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER );
    set_video_mode( std_video_mode( config.fullscreen ) );
    SDL_WM_SetCaption( "LTris", 0 );
    sdl.fade = config.fade;
    SDL_SetEventFilter( event_filter );
#ifdef SOUND
    audio_open();
    sound_enable( config.sound );
    sound_volume( config.volume * 16 );
#endif

    /* create */
    hint_load_res();
    manager_create();    
    tetris_create();
    chart_load();
    /* run game */
    manager_fade( FADE_IN );
    while( !leave && !term_game ) {
        result = manager_run();
        switch( result ) {
            case ACTION_QUIT: leave = 1; break;
            case ACTION_MAKE_STAT:
                manager_fade( FADE_OUT );
                tetris_make_stat();
                manager_fade( FADE_IN );
                break;
            case ACTION_PLAY:
                manager_fade( FADE_OUT );
                if ( tetris_init() ) {
                    tetris_run();
                    tetris_clear();
                }
                manager_fade( FADE_IN );
                break;
            default: break;
        }
    }
    manager_fade( FADE_OUT );
    /* delete stuff */
    tetris_delete();
	manager_delete();
	chart_save();
    chart_delete();
    hint_delete_res();
    
#ifdef SOUND
    audio_close();
#endif
    config_save();

    return EXIT_SUCCESS;
}
示例#26
0
文件: pc.c 项目: richardg867/PCem-X
void loadconfig(char *fn)
{
    char s[512];
    char *p;

    if (!fn)
    {
        append_filename(config_file_default, pcempath, "pcem.cfg", 511);

        config_load(config_file_default);
    }
    else
        config_load(fn);

    GAMEBLASTER = config_get_int(NULL, "gameblaster", 0);
    GUS = config_get_int(NULL, "gus", 0);
    SSI2001 = config_get_int(NULL, "ssi2001", 0);
    voodoo_enabled = config_get_int(NULL, "voodoo", 0);

// #ifdef USE_NETWORKING
    //network
    ethif = config_get_int(NULL, "netinterface", 1);
    if (ethif >= inum)
        inum = ethif + 1;
    network_card_current = config_get_int(NULL, "netcard", NE2000);
// #endif

    model = config_get_int(NULL, "model", 14);

    if (model >= model_count())
        model = model_count() - 1;

    romset = model_getromset();
    cpu_manufacturer = config_get_int(NULL, "cpu_manufacturer", 0);
    cpu = config_get_int(NULL, "cpu", 0);
    cpu_use_dynarec = config_get_int(NULL, "cpu_use_dynarec", 0);

    gfxcard = config_get_int(NULL, "gfxcard", 0);
    video_speed = config_get_int(NULL, "video_speed", 3);
    sound_card_current = config_get_int(NULL, "sndcard", SB2);

    p = (char *)config_get_string(NULL, "disc_a", "");
    if (p) strcpy(discfns[0], p);
    else   strcpy(discfns[0], "");

    p = (char *)config_get_string(NULL, "disc_b", "");
    if (p) strcpy(discfns[1], p);
    else   strcpy(discfns[1], "");

    mem_size = config_get_int(NULL, "mem_size", 4);
    cdrom_drive = config_get_int(NULL, "cdrom_drive", 0);
    cdrom_enabled = config_get_int(NULL, "cdrom_enabled", 0);

    slowega = config_get_int(NULL, "slow_video", 1);
    cache = config_get_int(NULL, "cache", 3);
    cga_comp = config_get_int(NULL, "cga_composite", 0);

    vid_resize = config_get_int(NULL, "vid_resize", 0);
    vid_api = config_get_int(NULL, "vid_api", 0);
    video_fullscreen_scale = config_get_int(NULL, "video_fullscreen_scale", 0);
    video_fullscreen_first = config_get_int(NULL, "video_fullscreen_first", 1);

    hdc[0].spt = config_get_int(NULL, "hdc_sectors", 0);
    hdc[0].hpc = config_get_int(NULL, "hdc_heads", 0);
    hdc[0].tracks = config_get_int(NULL, "hdc_cylinders", 0);
    p = (char *)config_get_string(NULL, "hdc_fn", "");
    if (p) strcpy(ide_fn[0], p);
    else   strcpy(ide_fn[0], "");
    hdc[1].spt = config_get_int(NULL, "hdd_sectors", 0);
    hdc[1].hpc = config_get_int(NULL, "hdd_heads", 0);
    hdc[1].tracks = config_get_int(NULL, "hdd_cylinders", 0);
    p = (char *)config_get_string(NULL, "hdd_fn", "");
    if (p) strcpy(ide_fn[1], p);
    else   strcpy(ide_fn[1], "");
    hdc[2].spt = config_get_int(NULL, "hde_sectors", 0);
    hdc[2].hpc = config_get_int(NULL, "hde_heads", 0);
    hdc[2].tracks = config_get_int(NULL, "hde_cylinders", 0);
    p = (char *)config_get_string(NULL, "hde_fn", "");
    if (p) strcpy(ide_fn[2], p);
    else   strcpy(ide_fn[2], "");
    hdc[3].spt = config_get_int(NULL, "hdf_sectors", 0);
    hdc[3].hpc = config_get_int(NULL, "hdf_heads", 0);
    hdc[3].tracks = config_get_int(NULL, "hdf_cylinders", 0);
    p = (char *)config_get_string(NULL, "hdf_fn", "");
    if (p) strcpy(ide_fn[3], p);
    else   strcpy(ide_fn[3], "");

    p = (char *)config_get_string(NULL, "disc_a", "");
    if (p) strcpy(discfns[0], p);
    else   strcpy(discfns[0], "");
    configure_from_int(0, config_get_int(NULL, "drivetype_a", 8));

    p = (char *)config_get_string(NULL, "disc_b", "");
    if (p) strcpy(discfns[1], p);
    else   strcpy(discfns[1], "");
    configure_from_int(1, config_get_int(NULL, "drivetype_b", 8));

    force_43 = config_get_int(NULL, "force_43", 0);
    enable_overscan = config_get_int(NULL, "enable_overscan", 1);
    ps1xtide = config_get_int(NULL, "ps1xtide", 0);

    disable_xchg_dynarec = config_get_int(NULL, "disable_xchg_dynarec", 0);
    turbo = config_get_int(NULL, "turbo", 1);

    cga_color_burst = config_get_int(NULL, "cga_color_burst", 1);

    cga_brown = config_get_int(NULL, "cga_brown", 1);
}
示例#27
0
int
main (int argc, char **argv)
{
  int ret;
  int c;

  FILE *pidfile;
  struct utsname sysinfo;

  machine_type machine;

  while ((c = getopt(argc, argv, "fdv")) != -1)
    {
      switch (c)
	{
	  case 'f':
	    console = 1;
	    break;

	  case 'd':
	    debug = 1;
	    console = 1;
	    break;

	  case 'v':
	    printf("pommed v" M_VERSION " Apple laptops hotkeys handler\n");
	    printf("Copyright (C) 2006-2011 Julien BLACHE <*****@*****.**>\n");

	    exit(0);
	    break;

	  default:
	    usage();

	    exit(1);
	    break;
	}
    }

  if (geteuid() != 0)
    {
      logmsg(LOG_ERR, "pommed needs root privileges to operate");

      exit(1);
    }

  if (!console)
    {
      openlog("pommed", LOG_PID, LOG_DAEMON);
    }

  logmsg(LOG_INFO, "pommed v" M_VERSION " Apple laptops hotkeys handler");
  logmsg(LOG_INFO, "Copyright (C) 2006-2011 Julien BLACHE <*****@*****.**>");

  /* Load our configuration */
  ret = config_load();
  if (ret < 0)
    {
      exit(1);
    }

  /* Identify the machine we're running on */
  machine = check_machine();
  switch (machine)
    {
      case MACHINE_MAC_UNKNOWN:
	logmsg(LOG_ERR, "Unknown Apple machine");

	exit(1);
	break;

      case MACHINE_UNKNOWN:
	logmsg(LOG_ERR, "Unknown non-Apple machine");

	exit(1);
	break;

      case MACHINE_ERROR:
	exit(1);
	break;

      default:
	if (machine < MACHINE_LAST)
	  {
#ifdef __powerpc__
	    mops = &pb_mops[machine];
#else
	    mops = &mb_mops[machine];
#endif /* __powerpc__ */
	  }
	break;
    }

  /* Runtime sanity check: catch errors in the mb_mops and pb_mops arrays */
  if (mops->type != machine)
    {
      logmsg(LOG_ERR, "machine_ops mismatch: expected %d, found %d", machine, mops->type);

      exit(1);
    }

  if (debug)
    {
      ret = uname(&sysinfo);

      if (ret < 0)
	logmsg(LOG_ERR, "uname() failed: %s", strerror(errno));
      else
	logdebug("System: %s %s %s\n", sysinfo.sysname, sysinfo.release, sysinfo.machine);
    }

  ret = evloop_init();
  if (ret < 0)
    {
      logmsg(LOG_ERR, "Event loop initialization failed");
      exit (1);
    }

  ret = mops->lcd_backlight_probe();
  if (ret < 0)
    {
      logmsg(LOG_ERR, "LCD backlight probe failed, check debug output");

      exit(1);
    }

  ret = evdev_init();
  if (ret < 1)
    {
      logmsg(LOG_ERR, "No suitable event devices found");

      exit(1);
    }

  kbd_backlight_init();

  ret = audio_init();
  if (ret < 0)
    {
      logmsg(LOG_WARNING, "Audio initialization failed, audio support disabled");
    }

  ret = mbpdbus_init();
  if (ret < 0)
    {
      logmsg(LOG_WARNING, "Could not connect to DBus system bus");
    }

  power_init();

  if (!console)
    {
      /*
       * Detach from the console
       */
      if (daemon(0, 0) != 0)
	{
	  logmsg(LOG_ERR, "daemon() failed: %s", strerror(errno));

	  evdev_cleanup();

	  exit(1);
	}
    }

  pidfile = fopen(PIDFILE, "w");
  if (pidfile == NULL)
    {
      logmsg(LOG_WARNING, "Could not open pidfile %s: %s", PIDFILE, strerror(errno));

      evdev_cleanup();

      exit(1);
    }
  fprintf(pidfile, "%d\n", getpid());
  fclose(pidfile);

  /* Spawn the beep thread */
  beep_init();

  signal(SIGINT, sig_int_term_handler);
  signal(SIGTERM, sig_int_term_handler);


  do
    {
      ret = evloop_iteration();
    }
  while (ret >= 0);

  evdev_cleanup();

  beep_cleanup();

  mbpdbus_cleanup();

  kbd_backlight_cleanup();

  power_cleanup();

  evloop_cleanup();

  config_cleanup();

  logmsg(LOG_INFO, "Exiting");

  if (!console)
    closelog();

  unlink(PIDFILE);

  return 0;
}
示例#28
0
static int config_load2(char *filename, module* caller)
{
	if (plugin_clear_configuration_on_load)
		_restart_specific_systems();
	return config_load(filename, caller);
}
示例#29
0
int main(int argc, char **argv) {
    int i;
    int config_loaded = 0;
    int dont_fork = 0;
    size_t default_stacksize;

    // set the name for logging
    program_name = "netdata";

    // parse depercated options
    // TODO: Remove this block with the next major release.
    {
        i = 1;
        while(i < argc) {
            if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
                strncpyz(pidfile, argv[i+1], FILENAME_MAX);
                fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
                remove_option(i, &argc, argv);
            }
            else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
                dont_fork = 1;
                fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
                remove_option(i, &argc, argv);
            }
            else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
                config_set(CONFIG_SECTION_GLOBAL, "host access prefix", argv[i+1]);
                fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
                remove_option(i, &argc, argv);
            }
            else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
                config_set(CONFIG_SECTION_GLOBAL, "history", argv[i+1]);
                fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
                remove_option(i, &argc, argv);
            }
            else i++;
        }
    }

    // parse options
    {
        int num_opts = sizeof(option_definitions) / sizeof(struct option_def);
        char optstring[(num_opts * 2) + 1];

        int string_i = 0;
        for( i = 0; i < num_opts; i++ ) {
            optstring[string_i] = option_definitions[i].val;
            string_i++;
            if(option_definitions[i].arg_name) {
                optstring[string_i] = ':';
                string_i++;
            }
        }
        // terminate optstring
        optstring[string_i] ='\0';
        optstring[(num_opts *2)] ='\0';

        int opt;
        while( (opt = getopt(argc, argv, optstring)) != -1 ) {
            switch(opt) {
                case 'c':
                    if(config_load(optarg, 1) != 1) {
                        error("Cannot load configuration file %s.", optarg);
                        return 1;
                    }
                    else {
                        debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
                        config_loaded = 1;
                    }
                    break;
                case 'D':
                    dont_fork = 1;
                    break;
                case 'h':
                    return help(0);
                case 'i':
                    config_set(CONFIG_SECTION_WEB, "bind to", optarg);
                    break;
                case 'P':
                    strncpy(pidfile, optarg, FILENAME_MAX);
                    pidfile[FILENAME_MAX] = '\0';
                    break;
                case 'p':
                    config_set(CONFIG_SECTION_GLOBAL, "default port", optarg);
                    break;
                case 's':
                    config_set(CONFIG_SECTION_GLOBAL, "host access prefix", optarg);
                    break;
                case 't':
                    config_set(CONFIG_SECTION_GLOBAL, "update every", optarg);
                    break;
                case 'u':
                    config_set(CONFIG_SECTION_GLOBAL, "run as user", optarg);
                    break;
                case 'v':
                case 'V':
                    printf("%s %s\n", program_name, program_version);
                    return 0;
                case 'W':
                    {
                        char* stacksize_string = "stacksize=";
                        char* debug_flags_string = "debug_flags=";

                        if(strcmp(optarg, "unittest") == 0) {
                            if(unit_test_buffer()) return 1;
                            if(unit_test_str2ld()) return 1;
                            //default_rrd_update_every = 1;
                            //default_rrd_memory_mode = RRD_MEMORY_MODE_RAM;
                            //if(!config_loaded) config_load(NULL, 0);
                            get_netdata_configured_variables();
                            default_rrd_update_every = 1;
                            default_rrd_memory_mode = RRD_MEMORY_MODE_RAM;
                            default_health_enabled = 0;
                            rrd_init("unittest");
                            default_rrdpush_enabled = 0;
                            if(run_all_mockup_tests()) return 1;
                            if(unit_test_storage()) return 1;
                            fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
                            return 0;
                        }
                        else if(strcmp(optarg, "simple-pattern") == 0) {
                            if(optind + 2 > argc) {
                                fprintf(stderr, "%s", "\nUSAGE: -W simple-pattern 'pattern' 'string'\n\n"
                                        " Checks if 'pattern' matches the given 'string'.\n"
                                        " - 'pattern' can be one or more space separated words.\n"
                                        " - each 'word' can contain one or more asterisks.\n"
                                        " - words starting with '!' give negative matches.\n"
                                        " - words are processed left to right\n"
                                        "\n"
                                        "Examples:\n"
                                        "\n"
                                        " > match all veth interfaces, except veth0:\n"
                                        "\n"
                                        "   -W simple-pattern '!veth0 veth*' 'veth12'\n"
                                        "\n"
                                        "\n"
                                        " > match all *.ext files directly in /path/:\n"
                                        "   (this will not match *.ext files in a subdir of /path/)\n"
                                        "\n"
                                        "   -W simple-pattern '!/path/*/*.ext /path/*.ext' '/path/test.ext'\n"
                                        "\n"
                                );
                                return 1;
                            }

                            const char *heystack = argv[optind];
                            const char *needle = argv[optind + 1];
                            size_t len = strlen(needle) + 1;
                            char wildcarded[len];

                            SIMPLE_PATTERN *p = simple_pattern_create(heystack, NULL, SIMPLE_PATTERN_EXACT);
                            int ret = simple_pattern_matches_extract(p, needle, wildcarded, len);
                            simple_pattern_free(p);

                            if(ret) {
                                fprintf(stdout, "RESULT: MATCHED - pattern '%s' matches '%s', wildcarded '%s'\n", heystack, needle, wildcarded);
                                return 0;
                            }
                            else {
                                fprintf(stdout, "RESULT: NOT MATCHED - pattern '%s' does not match '%s', wildcarded '%s'\n", heystack, needle, wildcarded);
                                return 1;
                            }
                        }
                        else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
                            optarg += strlen(stacksize_string);
                            config_set(CONFIG_SECTION_GLOBAL, "pthread stack size", optarg);
                        }
                        else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
                            optarg += strlen(debug_flags_string);
                            config_set(CONFIG_SECTION_GLOBAL, "debug flags",  optarg);
                            debug_flags = strtoull(optarg, NULL, 0);
                        }
                        else if(strcmp(optarg, "set") == 0) {
                            if(optind + 3 > argc) {
                                fprintf(stderr, "%s", "\nUSAGE: -W set 'section' 'key' 'value'\n\n"
                                        " Overwrites settings of netdata.conf.\n"
                                        "\n"
                                        " These options interact with: -c netdata.conf\n"
                                        " If -c netdata.conf is given on the command line,\n"
                                        " before -W set... the user may overwrite command\n"
                                        " line parameters at netdata.conf\n"
                                        " If -c netdata.conf is given after (or missing)\n"
                                        " -W set... the user cannot overwrite the command line\n"
                                        " parameters."
                                        "\n"
                                );
                                return 1;
                            }
                            const char *section = argv[optind];
                            const char *key = argv[optind + 1];
                            const char *value = argv[optind + 2];
                            optind += 3;

                            // set this one as the default
                            // only if it is not already set in the config file
                            // so the caller can use -c netdata.conf before or
                            // after this parameter to prevent or allow overwriting
                            // variables at netdata.conf
                            config_set_default(section, key,  value);

                            // fprintf(stderr, "SET section '%s', key '%s', value '%s'\n", section, key, value);
                        }
                        else if(strcmp(optarg, "get") == 0) {
                            if(optind + 3 > argc) {
                                fprintf(stderr, "%s", "\nUSAGE: -W get 'section' 'key' 'value'\n\n"
                                        " Prints settings of netdata.conf.\n"
                                        "\n"
                                        " These options interact with: -c netdata.conf\n"
                                        " -c netdata.conf has to be given before -W get.\n"
                                        "\n"
                                );
                                return 1;
                            }

                            if(!config_loaded) {
                                fprintf(stderr, "warning: no configuration file has been loaded. Use -c CONFIG_FILE, before -W get. Using default config.\n");
                                config_load(NULL, 0);
                            }

                            backwards_compatible_config();
                            get_netdata_configured_variables();

                            const char *section = argv[optind];
                            const char *key = argv[optind + 1];
                            const char *def = argv[optind + 2];
                            const char *value = config_get(section, key, def);
                            printf("%s\n", value);
                            return 0;
                        }
                        else {
                            fprintf(stderr, "Unknown -W parameter '%s'\n", optarg);
                            return help(1);
                        }
                    }
                    break;

                default: /* ? */
                    fprintf(stderr, "Unknown parameter '%c'\n", opt);
                    return help(1);
            }
        }
    }

#ifdef _SC_OPEN_MAX
    // close all open file descriptors, except the standard ones
    // the caller may have left open files (lxc-attach has this issue)
    {
        int fd;
        for(fd = (int) (sysconf(_SC_OPEN_MAX) - 1); fd > 2; fd--)
            if(fd_is_valid(fd)) close(fd);
    }
#endif

    if(!config_loaded)
        config_load(NULL, 0);

    // ------------------------------------------------------------------------
    // initialize netdata
    {
        char *pmax = config_get(CONFIG_SECTION_GLOBAL, "glibc malloc arena max for plugins", "1");
        if(pmax && *pmax)
            setenv("MALLOC_ARENA_MAX", pmax, 1);

#if defined(HAVE_C_MALLOPT)
        i = (int)config_get_number(CONFIG_SECTION_GLOBAL, "glibc malloc arena max for netdata", 1);
        if(i > 0)
            mallopt(M_ARENA_MAX, 1);
#endif

        // prepare configuration environment variables for the plugins

        get_netdata_configured_variables();
        set_global_environment();

        // work while we are cd into config_dir
        // to allow the plugins refer to their config
        // files using relative filenames
        if(chdir(netdata_configured_config_dir) == -1)
            fatal("Cannot cd to '%s'", netdata_configured_config_dir);
    }

    char *user = NULL;

    {
        // --------------------------------------------------------------------
        // get the debugging flags from the configuration file

        char *flags = config_get(CONFIG_SECTION_GLOBAL, "debug flags",  "0x0000000000000000");
        setenv("NETDATA_DEBUG_FLAGS", flags, 1);

        debug_flags = strtoull(flags, NULL, 0);
        debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);

        if(debug_flags != 0) {
            struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
            if(setrlimit(RLIMIT_CORE, &rl) != 0)
                error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");

#ifdef HAVE_SYS_PRCTL_H
            prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
#endif
        }


        // --------------------------------------------------------------------
        // get log filenames and settings

        log_init();
        error_log_limit_unlimited();


        // --------------------------------------------------------------------
        // load stream.conf
        {
            char filename[FILENAME_MAX + 1];
            snprintfz(filename, FILENAME_MAX, "%s/stream.conf", netdata_configured_config_dir);
            appconfig_load(&stream_config, filename, 0);
        }


        // --------------------------------------------------------------------
        // setup process signals

        // block signals while initializing threads.
        // this causes the threads to block signals.
        signals_block();

        // setup the signals we want to use
        signals_init();

        // setup threads configs
        default_stacksize = netdata_threads_init();


        // --------------------------------------------------------------------
        // check which threads are enabled and initialize them

        for (i = 0; static_threads[i].name != NULL ; i++) {
            struct netdata_static_thread *st = &static_threads[i];

            if(st->config_name)
                st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);

            if(st->enabled && st->init_routine)
                st->init_routine();
        }


        // --------------------------------------------------------------------
        // get the user we should run

        // IMPORTANT: this is required before web_files_uid()
        if(getuid() == 0) {
            user = config_get(CONFIG_SECTION_GLOBAL, "run as user", NETDATA_USER);
        }
        else {
            struct passwd *passwd = getpwuid(getuid());
            user = config_get(CONFIG_SECTION_GLOBAL, "run as user", (passwd && passwd->pw_name)?passwd->pw_name:"");
        }

        // --------------------------------------------------------------------
        // create the listening sockets

        web_client_api_v1_init();
        web_server_threading_selection();

        if(web_server_mode != WEB_SERVER_MODE_NONE)
            api_listen_sockets_setup();
    }

    // initialize the log files
    open_all_log_files();

#ifdef NETDATA_INTERNAL_CHECKS
    if(debug_flags != 0) {
        struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
        if(setrlimit(RLIMIT_CORE, &rl) != 0)
            error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
#ifdef HAVE_SYS_PRCTL_H
        prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
#endif
    }
#endif /* NETDATA_INTERNAL_CHECKS */

    // get the max file limit
    if(getrlimit(RLIMIT_NOFILE, &rlimit_nofile) != 0)
        error("getrlimit(RLIMIT_NOFILE) failed");
    else
        info("resources control: allowed file descriptors: soft = %zu, max = %zu", rlimit_nofile.rlim_cur, rlimit_nofile.rlim_max);

    // fork, switch user, create pid file, set process priority
    if(become_daemon(dont_fork, user) == -1)
        fatal("Cannot daemonize myself.");

    info("netdata started on pid %d.", getpid());

    // IMPORTANT: these have to run once, while single threaded
    // but after we have switched user
    web_files_uid();
    web_files_gid();

    netdata_threads_init_after_fork((size_t)config_get_number(CONFIG_SECTION_GLOBAL, "pthread stack size", (long)default_stacksize));

    // ------------------------------------------------------------------------
    // initialize rrd, registry, health, rrdpush, etc.

    rrd_init(netdata_configured_hostname);


    // ------------------------------------------------------------------------
    // enable log flood protection

    error_log_limit_reset();


    // ------------------------------------------------------------------------
    // spawn the threads

    web_server_config_options();

    for (i = 0; static_threads[i].name != NULL ; i++) {
        struct netdata_static_thread *st = &static_threads[i];

        if(st->enabled) {
            st->thread = mallocz(sizeof(netdata_thread_t));
            debug(D_SYSTEM, "Starting thread %s.", st->name);
            netdata_thread_create(st->thread, st->name, NETDATA_THREAD_OPTION_DEFAULT, st->start_routine, st);
        }
        else debug(D_SYSTEM, "Not starting thread %s.", st->name);
    }

    info("netdata initialization completed. Enjoy real-time performance monitoring!");


    // ------------------------------------------------------------------------
    // unblock signals

    signals_unblock();

    // ------------------------------------------------------------------------
    // Handle signals

    signals_handle();

    // should never reach this point
    // but we need it for rpmlint #2752
    return 1;
}
示例#30
0
int main(int argc, char *argv[])
{
    int camera = 0;
    SDL_Joystick *joy = NULL;

    if (!fs_init(argv[0]))
    {
        fprintf(stderr, "Failure to initialize virtual file system: %s\n",
                fs_error());
        return 1;
    }

    srand((int) time(NULL));

    lang_init("neverball");

    opt_parse(argc, argv);

    config_paths(opt_data);
    fs_mkdir("Screenshots");

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) == 0)
    {
        config_init();
        config_load();

        /* Cache Neverball's camera setting. */

        camera = config_get_d(CONFIG_CAMERA);

        /* Initialize the joystick. */

        if (config_get_d(CONFIG_JOYSTICK) && SDL_NumJoysticks() > 0)
        {
            joy = SDL_JoystickOpen(config_get_d(CONFIG_JOYSTICK_DEVICE));
            if (joy)
            {
                SDL_JoystickEventState(SDL_ENABLE);
                set_joystick(joy);
            }
        }

        /* Initialize the audio. */

        audio_init();

        /* Initialize the video. */

        if (video_init(TITLE, ICON))
        {
            int t1, t0 = SDL_GetTicks();

            /* Run the main game loop. */

            init_state(&st_null);

            if (opt_hole)
            {
                const char *path = fs_resolve(opt_hole);
                int loaded = 0;

                if (path)
                {
                    hole_init(NULL);

                    if (hole_load(0, path) &&
                        hole_load(1, path) &&
                        hole_goto(1, 1))
                    {
                        goto_state(&st_next);
                        loaded = 1;
                    }
                }

                if (!loaded)
                    goto_state(&st_title);
            }
            else
                goto_state(&st_title);

            while (loop())
                if ((t1 = SDL_GetTicks()) > t0)
                {
                    st_timer((t1 - t0) / 1000.f);
                    st_paint(0.001f * t1);
                    shot_take();
                    SDL_GL_SwapWindow(video_get_window());

                    t0 = t1;

                    if (config_get_d(CONFIG_NICE))
                        SDL_Delay(1);
                }
        }

        /* Restore Neverball's camera setting. */

        config_set_d(CONFIG_CAMERA, camera);
        config_save();

        SDL_Quit();
    }
    else fprintf(stderr, "%s: %s\n", argv[0], SDL_GetError());

    return 0;
}