Ejemplo n.º 1
0
// {{{ session_get_user()
int session_get_user(const char *sessid, char *user, size_t len)
{
   struct config_t cfg;
   config_init(&cfg);
   config_setting_t *cs;
   config_setting_t *vs;

   if(!config_read_file(&cfg, OD_SESSION_FILE))
      return -1;

   int i=0;
   for(i=0; ;i++)
   {
      if( !(cs = config_setting_get_elem(cfg.root, i)) )
         break;

      if( !(vs = config_setting_get_member(cs, "sessid")) )
         continue;

      char *session_user = config_setting_name(cs);
      if(!session_user)
         continue;

      const char *res = config_setting_get_string(vs);
      if(res)
         if(strcmp(res, sessid)==0)
         {
            sstrncpy(user, session_user, len);
            config_destroy(&cfg);
            return 0;
         }

   }

   config_destroy(&cfg);
   return -1;
}
Ejemplo n.º 2
0
Archivo: config.c Proyecto: Detegr/HBot
int config_load(struct config* conf, const char* filename)
{
	config_init(conf);
	FILE* f=fopen(filename, "r");
	if(!f) return -1;
	int r=1;
	char* line=NULL;
	size_t s=0;
	char header[ITEM_MAXLEN];
	char left[ITEM_MAXLEN];
	char right[ITEM_MAXLEN];
	while((r = getline(&line, &s, f)) != -1)
	{
		int h=sscanf(line, "[%[^\n]", header);
		if(!h)
		{
			h=sscanf(line, "%*[ \t]%[^=]=%[^\n]", left, right);
			if(h==1)
			{
				h=sscanf(line, "%*[ \t]%[^\n]", left);
				if(h==1) config_add(conf, header, left, NULL);
				else return -1;
			}
			else if(h==2) config_add(conf, header, left, right);
			else return -1;
		}
		else
		{
			size_t hlen = strnlen(header, ITEM_MAXLEN)-1;
			if(header[hlen]==']') header[hlen]=0;
			else return -1;
		}
	}
	free(line);
	fclose(f);
	return 0;
}
Ejemplo n.º 3
0
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;
}
Ejemplo n.º 4
0
/* main:
 * Entry point. See usage(). */
int main(int argc, char **argv) {
    pthread_t thread;
    struct sigaction sa = {};

    setlocale(LC_ALL, "");

    /* TODO: tidy this up */
    /* read command line options and config file */   
    config_init();
    options_set_defaults();
    options_read_args(argc, argv);
    /* If a config was explicitly specified, whinge if it can't be found */
    read_config(options.config_file, options.config_file_specified);
    options_make();
    
    sa.sa_handler = finish;
    sigaction(SIGINT, &sa, NULL);

    pthread_mutex_init(&tick_mutex, NULL);

    packet_init();

    init_history();

    ui_init();

    pthread_create(&thread, NULL, (void*)&packet_loop, NULL);

    ui_loop();

    //pthread_cancel(thread); // bionic c have no pthread_cancel, by dove

    ui_finish();
    
    return 0;
}
Ejemplo n.º 5
0
void Settings::Load()
{
	FILE* fileHnd;

	fileHnd = fopen( "settings.cfg", "rb" );
	if( fileHnd != 0 )
	{
		fclose( fileHnd );

		config_t cfg;
		config_setting_t *setting;

		config_init(&cfg);
		config_read_file( &cfg, "settings.cfg" );

		setting = config_lookup( &cfg, "Graphics" );
		config_setting_lookup_int( setting, "FullScreen", &FullScreen );

		setting = config_lookup( &cfg, "Audio" );
		config_setting_lookup_int( setting, "PlaySFX", &PlaySFX );
		config_setting_lookup_int( setting, "PlayMusic", &PlayMusic );

		setting = config_lookup( &cfg, "Input" );
		config_setting_lookup_int( setting, "keyLeft", (int*)&keyLeft );
		config_setting_lookup_int( setting, "keyRight", (int*)&keyRight );
		config_setting_lookup_int( setting, "keyUp", (int*)&keyUp );
		config_setting_lookup_int( setting, "keyDown", (int*)&keyDown );
		config_setting_lookup_int( setting, "keyFire1", (int*)&keyFire1 );
		config_setting_lookup_int( setting, "keyFire2", (int*)&keyFire2 );
		config_setting_lookup_int( setting, "keyQuit", (int*)&keyQuit );

		config_destroy(&cfg);
	} else {
		Init();
	}
}
Ejemplo n.º 6
0
/*
 * this function needs to get enough configured to do a console
 * basically this means start attaching the grfxx's that support 
 * the console. Kinda hacky but it works.
 */
void
config_console(void)
{	
	cfdata_t cf;

	config_init();

	/*
	 * we need mainbus' cfdata.
	 */
	cf = config_rootsearch(NULL, "mainbus", __UNCONST("mainbus"));
	if (cf == NULL)
		panic("no mainbus");

	/*
	 * Note: The order of the 'atari_config_found()' calls is
	 * important! On the Hades, the 'pci-side' of the config does
	 * some setup for the 'grf-side'. This make it possible to use
	 * a PCI card for both wscons and grfabs.
	 */
	atari_config_found(cf, NULL, __UNCONST("pcib")  , NULL);
	atari_config_found(cf, NULL, __UNCONST("isab")  , NULL);
	atari_config_found(cf, NULL, __UNCONST("grfbus"), NULL);
}
Ejemplo n.º 7
0
int* print_colour()
{
	config_setting_t *color_list, *layout;
	config_t layout_config;
	int color_len, i;
	const char* color_value;
	int* RGB_array;

	config_init(&layout_config);
	if (!config_read_file(&layout_config, "./layout.cfg")) {
        	fprintf(stderr, "%s:%d - %s\n",
           				config_error_file(&layout_config),
            			config_error_line(&layout_config),
            			config_error_text(&layout_config));
        	config_destroy(&layout_config);
        	return NULL;
    	}
	
	color_list = config_lookup(&layout_config, "application.colors");
	color_len = config_setting_length(color_list);
	RGB_array=malloc(sizeof (int)*3*color_len);
	for(i = 0; i < color_len; i++)
	{
		layout = config_setting_get_elem(color_list, i);
		config_setting_lookup_string(layout, "name", &color_value);
		printf(" %i)\t", i+1);
		printf("%s\n", color_value);
		config_setting_lookup_int(layout, "r", &RGB_array[i*3]);
		config_setting_lookup_int(layout, "g", &RGB_array[i*3+1]);
		config_setting_lookup_int(layout, "b", &RGB_array[i*3+2]);
		printf("\tR-G-B: %i-%i-%i\n",RGB_array[i*3],RGB_array[i*3+1],RGB_array[i*3+2]);
	}
	
	config_destroy(&layout_config);
	return RGB_array;
}
Ejemplo n.º 8
0
int main(int argc, char *argv[])
{
    config_init(argc, argv);

    if (glue_init() != 0)
    {
        iotc_error("glue init failed!");
        return -1;
    }

    if (0 != connection_init())
    {
        iotc_error("socket_init failed!");
        return -1;
    }

    uloop_init();
    uloop_fd_add(&iotc_monitor_uloop_fd, ULOOP_READ);
    uloop_timeout_set(&g_sendDevOnlineTm, 2000);
    uloop_run();
    uloop_done();

    return 0;
}
Ejemplo n.º 9
0
// ----------------------------------------------------------------------------------------
// Sistema Multilinguagem
// ----------------------------------------------------------------------------------------
// read_message("Grupo.SubGrupo.String");
// ----------------------------------------------------------------------------------------
// http://www.hyperrealm.com/libconfig/libconfig_manual.html
// ----------------------------------------------------------------------------------------
char *read_message(const char *param)
{
	static char message[512];
	config_setting_t *str;
	config_t configLang;

	config_init(&configLang);

	if(!config_read_file(&configLang, (!strlen(bra_config.lang_file)?"conf/lang/pt_br.conf":bra_config.lang_file))) {
		ShowError("read_message erro: %s:%d - %s\n", config_error_file(&configLang), config_error_line(&configLang), config_error_text(&configLang));
		config_destroy(&configLang);
		return "";
	}

	if(!(str = config_lookup(&configLang, param))) {
		ShowError("read_message erro: %s\n", param);
		config_destroy(&configLang);
		return "";
	}
	
	strncpy(message, config_setting_get_string(str), sizeof(message));
	config_destroy(&configLang);
	return message;
}
Ejemplo n.º 10
0
int
main(int argc, char **argv)
{
    int result;
    static TestUtilsTest tests[] = {
        TU_TEST(test_vfs_free_space, 90),
	TU_END()
    };

    glib_init();
    config_init(0, NULL);
    device_api_init();

    /* TODO: if more tests are added, we'll need a setup/cleanup hook
     * for testutils */
    device_path = setup_vtape_dir();

    result = testutils_run_tests(argc, argv, tests);

    cleanup_vtape_dir(device_path);
    amfree(device_path);

    return result;
}
Ejemplo n.º 11
0
void get_defaults(char *filename, struct udata *ud)
{
	config_t cfg, *cf;
	const char *value;
#if LIBCONFIG_VER_MAJOR == 1
# if LIBCONFIG_VER_MINOR >= 4
	int ival;
# endif
# else
	long ival;
#endif

	if (access(filename, R_OK) == -1) {
		olog(LOG_ERR, "Cannot read defaults from %s: %s", filename, strerror(errno));
		return;
	}

	config_init(cf = &cfg);

	if (!config_read_file(cf, filename)) {
		olog(LOG_ERR, "Syntax error in %s:%d - %s",
			filename,
			config_error_line(cf),
			config_error_text(cf));
		config_destroy(cf);
		exit(2);
	}

	if (config_lookup_string(cf, "OTR_STORAGEDIR", &value) != CONFIG_FALSE)
		strcpy(STORAGEDIR, value);

	if (ud == NULL) {
		/* being invoked by ocat; return */
		return;
	}
#if WITH_MQTT
	if (config_lookup_string(cf, "OTR_HOST", &value) != CONFIG_FALSE) {
		if (ud->hostname) free(ud->hostname);
		ud->hostname = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_int(cf, "OTR_PORT", &ival) != CONFIG_FALSE) {
		ud->port = ival;
	}
	if (config_lookup_string(cf, "OTR_USER", &value) != CONFIG_FALSE) {
		if (ud->username) free(ud->username);
		ud->username = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_string(cf, "OTR_PASS", &value) != CONFIG_FALSE) {
		if (ud->password) free(ud->password);
		ud->password = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_int(cf, "OTR_QOS", &ival) != CONFIG_FALSE) {
		ud->qos = ival;
	}
	if (config_lookup_string(cf, "OTR_CLIENTID", &value) != CONFIG_FALSE) {
		if (ud->clientid) free(ud->clientid);
		ud->clientid = (value) ? strdup(value) : NULL;
	}

	if (config_lookup_string(cf, "OTR_CAFILE", &value) != CONFIG_FALSE) {
		if (ud->cafile) free(ud->cafile);
		ud->cafile = (value) ? strdup(value) : NULL;
	}

	/* Topics is a blank-separated string of words; split and add to JSON array */
	if (config_lookup_string(cf, "OTR_TOPICS", &value) != CONFIG_FALSE) {
		char *parts[40];
		int np, n;
		if (ud->topics) json_delete(ud->topics);

		if ((np = splitter((char *)value, " ", parts)) < 1) {
			olog(LOG_ERR, "Illegal value in OTR_TOPICS");
			exit(2);
		}
		ud->topics = json_mkarray();

		for (n = 0; n < np; n++) {
			json_append_element(ud->topics, json_mkstring(parts[n]));
		}
		splitterfree(parts);
	}
#endif /* WITH_MQTT */

	if (config_lookup_string(cf, "OTR_GEOKEY", &value) != CONFIG_FALSE) {
		if (ud->geokey) free(ud->geokey);
		ud->geokey = (value) ? strdup(value) : NULL;
	}

	if (config_lookup_int(cf, "OTR_PRECISION", &ival) != CONFIG_FALSE) {
		geohash_setprec(ival);
	}

#if WITH_HTTP
	if (config_lookup_string(cf, "OTR_HTTPHOST", &value) != CONFIG_FALSE) {
		if (ud->http_host) free(ud->http_host);
		ud->http_host = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_int(cf, "OTR_HTTPPORT", &ival) != CONFIG_FALSE) {
		ud->http_port = ival;
	}
	if (config_lookup_string(cf, "OTR_HTTPLOGDIR", &value) != CONFIG_FALSE) {
		if (ud->http_logdir) free(ud->http_logdir);
		ud->http_logdir = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_string(cf, "OTR_BROWSERAPIKEY", &value) != CONFIG_FALSE) {
		if (ud->browser_apikey) free(ud->browser_apikey);
		ud->browser_apikey = (value) ? strdup(value) : NULL;
	}
#endif /* WITH_HTTP */

#if WITH_LUA
	if (config_lookup_string(cf, "OTR_LUASCRIPT", &value) != CONFIG_FALSE) {
		if (ud->luascript) free(ud->luascript);
		ud->luascript = (value) ? strdup(value) : NULL;
	}
#endif

	config_destroy(cf);
}
Ejemplo n.º 12
0
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;
}
Ejemplo n.º 13
0
int
main(int argc, char **argv)
{
  int i;
  sigset_t set;
#if ENABLE_MPEGTS
  uint32_t adapter_mask = 0;
#endif
  int  log_level   = LOG_INFO;
  int  log_options = TVHLOG_OPT_MILLIS | TVHLOG_OPT_STDERR | TVHLOG_OPT_SYSLOG;
  const char *log_debug = NULL, *log_trace = NULL;
  gid_t gid = -1;
  uid_t uid = -1;
  char buf[512];
  FILE *pidfile = NULL;
  extern int dvb_bouquets_parse;

  main_tid = pthread_self();

  /* Setup global mutexes */
  pthread_mutex_init(&fork_lock, NULL);
  pthread_mutex_init(&global_lock, NULL);
  pthread_mutex_init(&tasklet_lock, NULL);
  pthread_mutex_init(&atomic_lock, NULL);
  pthread_cond_init(&gtimer_cond, NULL);
  pthread_cond_init(&tasklet_cond, NULL);
  TAILQ_INIT(&tasklets);

  /* Defaults */
  tvheadend_webui_port      = 9981;
  tvheadend_webroot         = NULL;
  tvheadend_htsp_port       = 9982;
  tvheadend_htsp_port_extra = 0;
  time(&dispatch_clock);

  /* Command line options */
  int         opt_help         = 0,
              opt_version      = 0,
              opt_fork         = 0,
              opt_firstrun     = 0,
              opt_stderr       = 0,
              opt_syslog       = 0,
              opt_nosyslog     = 0,
              opt_uidebug      = 0,
              opt_abort        = 0,
              opt_noacl        = 0,
              opt_fileline     = 0,
              opt_threadid     = 0,
              opt_libav        = 0,
              opt_ipv6         = 0,
              opt_satip_rtsp   = 0,
#if ENABLE_TSFILE
              opt_tsfile_tuner = 0,
#endif
              opt_dump         = 0,
              opt_xspf         = 0,
              opt_dbus         = 0,
              opt_dbus_session = 0,
              opt_nobackup     = 0,
              opt_nobat        = 0;
  const char *opt_config       = NULL,
             *opt_user         = NULL,
             *opt_group        = NULL,
             *opt_logpath      = NULL,
             *opt_log_debug    = NULL,
             *opt_log_trace    = NULL,
             *opt_pidpath      = "/var/run/tvheadend.pid",
#if ENABLE_LINUXDVB
             *opt_dvb_adapters = NULL,
#endif
             *opt_bindaddr     = NULL,
             *opt_subscribe    = NULL,
             *opt_user_agent   = NULL;
  str_list_t  opt_satip_xml    = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) };
  str_list_t  opt_tsfile       = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) };
  cmdline_opt_t cmdline_opts[] = {
    {   0, NULL,        N_("Generic Options"),         OPT_BOOL, NULL         },
    { 'h', "help",      N_("Show this page"),          OPT_BOOL, &opt_help    },
    { 'v', "version",   N_("Show version information"),OPT_BOOL, &opt_version },

    {   0, NULL,        N_("Service Configuration"),   OPT_BOOL, NULL         },
    { 'c', "config",    N_("Alternate config path"),   OPT_STR,  &opt_config  },
    { 'B', "nobackup",  N_("Don't backup config tree at upgrade"), OPT_BOOL, &opt_nobackup },
    { 'f', "fork",      N_("Fork and run as daemon"),  OPT_BOOL, &opt_fork    },
    { 'u', "user",      N_("Run as user"),             OPT_STR,  &opt_user    },
    { 'g', "group",     N_("Run as group"),            OPT_STR,  &opt_group   },
    { 'p', "pid",       N_("Alternate pid path"),      OPT_STR,  &opt_pidpath },
    { 'C', "firstrun",  N_("If no user account exists then create one with\n"
	                   "no username and no password. Use with care as\n"
	                   "it will allow world-wide administrative access\n"
	                   "to your Tvheadend installation until you edit/create\n"
	                   "access-control from within the Tvheadend UI"),
      OPT_BOOL, &opt_firstrun },
#if ENABLE_DBUS_1
    { 'U', "dbus",      N_("Enable DBus"),
      OPT_BOOL, &opt_dbus },
    { 'e', "dbus_session", N_("DBus - use the session message bus instead system one"),
      OPT_BOOL, &opt_dbus_session },
#endif
#if ENABLE_LINUXDVB
    { 'a', "adapters",  N_("Only use specified DVB adapters (comma separated)"),
      OPT_STR, &opt_dvb_adapters },
#endif
#if ENABLE_SATIP_SERVER
    {   0, "satip_rtsp", N_("SAT>IP RTSP port number for server\n"
                            "(default: -1 = disable, 0 = webconfig, standard port is 554)"),
      OPT_INT, &opt_satip_rtsp },
#endif
#if ENABLE_SATIP_CLIENT
    {   0, "satip_xml", N_("URL with the SAT>IP server XML location"),
      OPT_STR_LIST, &opt_satip_xml },
#endif
    {   0, NULL,         N_("Server Connectivity"),    OPT_BOOL, NULL         },
    { '6', "ipv6",       N_("Listen on IPv6"),         OPT_BOOL, &opt_ipv6    },
    { 'b', "bindaddr",   N_("Specify bind address"),   OPT_STR,  &opt_bindaddr},
    {   0, "http_port",  N_("Specify alternative http port"),
      OPT_INT, &tvheadend_webui_port },
    {   0, "http_root",  N_("Specify alternative http webroot"),
      OPT_STR, &tvheadend_webroot },
    {   0, "htsp_port",  N_("Specify alternative htsp port"),
      OPT_INT, &tvheadend_htsp_port },
    {   0, "htsp_port2", N_("Specify extra htsp port"),
      OPT_INT, &tvheadend_htsp_port_extra },
    {   0, "useragent",  N_("Specify User-Agent header for the http client"),
      OPT_STR, &opt_user_agent },
    {   0, "xspf",       N_("Use XSPF playlist instead of M3U"),
      OPT_BOOL, &opt_xspf },

    {   0, NULL,        N_("Debug Options"),           OPT_BOOL, NULL         },
    { 'd', "stderr",    N_("Enable debug on stderr"),  OPT_BOOL, &opt_stderr  },
    { 's', "syslog",    N_("Enable debug to syslog"),  OPT_BOOL, &opt_syslog  },
    { 'S', "nosyslog",  N_("Disable syslog (all msgs)"), OPT_BOOL, &opt_nosyslog },
    { 'l', "logfile",   N_("Enable debug to file"),    OPT_STR,  &opt_logpath },
    {   0, "debug",     N_("Enable debug subsystems"),  OPT_STR,  &opt_log_debug },
#if ENABLE_TRACE
    {   0, "trace",     N_("Enable trace subsystems"), OPT_STR,  &opt_log_trace },
#endif
    {   0, "fileline",  N_("Add file and line numbers to debug"), OPT_BOOL, &opt_fileline },
    {   0, "threadid",  N_("Add the thread ID to debug"), OPT_BOOL, &opt_threadid },
#if ENABLE_LIBAV
    {   0, "libav",     N_("More verbose libav log"),  OPT_BOOL, &opt_libav },
#endif
    {   0, "uidebug",   N_("Enable webUI debug (non-minified JS)"), OPT_BOOL, &opt_uidebug },
    { 'A', "abort",     N_("Immediately abort"),       OPT_BOOL, &opt_abort   },
    { 'D', "dump",      N_("Enable coredumps for daemon"), OPT_BOOL, &opt_dump },
    {   0, "noacl",     N_("Disable all access control checks"),
      OPT_BOOL, &opt_noacl },
    {   0, "nobat",     N_("Disable DVB bouquets"),
      OPT_BOOL, &opt_nobat },
    { 'j', "join",      N_("Subscribe to a service permanently"),
      OPT_STR, &opt_subscribe },


#if ENABLE_TSFILE || ENABLE_TSDEBUG
    { 0, NULL, N_("Testing options"), OPT_BOOL, NULL },
    { 0, "tsfile_tuners", N_("Number of tsfile tuners"), OPT_INT, &opt_tsfile_tuner },
    { 0, "tsfile", N_("tsfile input (mux file)"), OPT_STR_LIST, &opt_tsfile },
#endif
#if ENABLE_TSDEBUG
    { 0, "tsdebug", N_("Output directory for tsdebug"), OPT_STR, &tvheadend_tsdebug },
#endif

  };

  /* Get current directory */
  tvheadend_cwd0 = dirname(tvh_strdupa(argv[0]));
  tvheadend_cwd = dirname(tvh_strdupa(tvheadend_cwd0));

  /* Set locale */
  setlocale(LC_ALL, "");
  setlocale(LC_NUMERIC, "C");

  /* make sure the timezone is set */
  tzset();

  /* Process command line */
  for (i = 1; i < argc; i++) {

    /* Find option */
    cmdline_opt_t *opt
      = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]);
    if (!opt)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 _("invalid option specified [%s]"), argv[i]);

    /* Process */
    if (opt->type == OPT_BOOL)
      *((int*)opt->param) = 1;
    else if (++i == argc)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 _("option %s requires a value"), opt->lopt);
    else if (opt->type == OPT_INT)
      *((int*)opt->param) = atoi(argv[i]);
    else if (opt->type == OPT_STR_LIST) {
      str_list_t *strl = opt->param;
      if (strl->num < strl->max)
        strl->str[strl->num++] = argv[i];
    }
    else
      *((char**)opt->param) = argv[i];

    /* Stop processing */
    if (opt_help)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL);
    if (opt_version)
      show_version(argv[0]);
  }

  /* Additional cmdline processing */
  if (opt_nobat)
    dvb_bouquets_parse = 0;
#if ENABLE_LINUXDVB
  if (!opt_dvb_adapters) {
    adapter_mask = ~0;
  } else {
    char *p, *e;
    char *r = NULL;
    char *dvb_adapters = strdup(opt_dvb_adapters);
    adapter_mask = 0x0;
    p = strtok_r(dvb_adapters, ",", &r);
    while (p) {
      int a = strtol(p, &e, 10);
      if (*e != 0 || a < 0 || a > 31) {
        fprintf(stderr, _("Invalid adapter number '%s'\n"), p);
        free(dvb_adapters);
        return 1;
      }
      adapter_mask |= (1 << a);
      p = strtok_r(NULL, ",", &r);
    }
    free(dvb_adapters);
    if (!adapter_mask) {
      fprintf(stderr, "%s", _("No adapters specified!\n"));
      return 1;
    }
  }
#endif
  if (tvheadend_webroot) {
    char *tmp;
    if (*tvheadend_webroot == '/')
      tmp = strdup(tvheadend_webroot);
    else {
      tmp = malloc(strlen(tvheadend_webroot)+2);
      *tmp = '/';
      strcpy(tmp+1, tvheadend_webroot);
    }
    if (tmp[strlen(tmp)-1] == '/')
      tmp[strlen(tmp)-1] = '\0';
    tvheadend_webroot = tmp;
  }
  tvheadend_webui_debug = opt_uidebug;

  /* Setup logging */
  if (isatty(2))
    log_options |= TVHLOG_OPT_DECORATE;
  if (opt_stderr || opt_syslog || opt_logpath) {
    if (!opt_log_trace && !opt_log_debug)
      log_debug      = "all";
    log_level      = LOG_DEBUG;
    if (opt_stderr)
      log_options   |= TVHLOG_OPT_DBG_STDERR;
    if (opt_syslog)
      log_options   |= TVHLOG_OPT_DBG_SYSLOG;
    if (opt_logpath)
      log_options   |= TVHLOG_OPT_DBG_FILE;
  }
  if (opt_nosyslog)
    log_options &= ~(TVHLOG_OPT_SYSLOG|TVHLOG_OPT_DBG_SYSLOG);
  if (opt_fileline)
    log_options |= TVHLOG_OPT_FILELINE;
  if (opt_threadid)
    log_options |= TVHLOG_OPT_THREAD;
  if (opt_libav)
    log_options |= TVHLOG_OPT_LIBAV;
  if (opt_log_trace) {
    log_level  = LOG_TRACE;
    log_trace  = opt_log_trace;
  }
  if (opt_log_debug)
    log_debug  = opt_log_debug;
    
  tvhlog_init(log_level, log_options, opt_logpath);
  tvhlog_set_debug(log_debug);
  tvhlog_set_trace(log_trace);
  tvhinfo("main", "Log started");
 
  signal(SIGPIPE, handle_sigpipe); // will be redundant later
  signal(SIGILL, handle_sigill);   // see handler..

  /* Set priviledges */
  if(opt_fork || opt_group || opt_user) {
    const char *homedir;
    struct group  *grp = getgrnam(opt_group ?: "video");
    struct passwd *pw  = opt_user ? getpwnam(opt_user) : NULL;

    if(grp != NULL) {
      gid = grp->gr_gid;
    } else {
      gid = 1;
    }

    if (pw != NULL) {
      if (getuid() != pw->pw_uid) {
        gid_t glist[16];
        int gnum;
        gnum = get_user_groups(pw, glist, ARRAY_SIZE(glist));
        if (gnum > 0 && setgroups(gnum, glist)) {
          char buf[256] = "";
          int i;
          for (i = 0; i < gnum; i++)
            snprintf(buf + strlen(buf), sizeof(buf) - 1 - strlen(buf),
                     ",%d", glist[i]);
          tvhlog(LOG_ALERT, "START",
                 "setgroups(%s) failed, do you have permission?", buf+1);
          return 1;
        }
      }
      uid     = pw->pw_uid;
      homedir = pw->pw_dir;
      setenv("HOME", homedir, 1);
    } else {
      uid = 1;
    }
  }

  uuid_init();
  config_boot(opt_config, gid, uid);
  tcp_server_preinit(opt_ipv6);
  http_server_init(opt_bindaddr);    // bind to ports only
  htsp_init(opt_bindaddr);	     // bind to ports only
  satip_server_init(opt_satip_rtsp); // bind to ports only

  if (opt_fork)
    pidfile = tvh_fopen(opt_pidpath, "w+");

  if (gid != -1 && (getgid() != gid) && setgid(gid)) {
    tvhlog(LOG_ALERT, "START",
           "setgid(%d) failed, do you have permission?", gid);
    return 1;
  }
  if (uid != -1 && (getuid() != uid) && setuid(uid)) {
    tvhlog(LOG_ALERT, "START",
           "setuid(%d) failed, do you have permission?", uid);
    return 1;
  }

  /* Daemonise */
  if(opt_fork) {
    if(daemon(0, 0)) {
      exit(2);
    }
    if(pidfile != NULL) {
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    }

    /* Make dumpable */
    if (opt_dump) {
#ifdef PLATFORM_LINUX
      if (chdir("/tmp"))
        tvhwarn("START", "failed to change cwd to /tmp");
      prctl(PR_SET_DUMPABLE, 1);
#else
      tvhwarn("START", "Coredumps not implemented on your platform");
#endif
    }

    umask(0);
  }

  tvheadend_running = 1;

  /* Start log thread (must be done post fork) */
  tvhlog_start();

  /* Alter logging */
  if (opt_fork)
    tvhlog_options &= ~TVHLOG_OPT_STDERR;
  if (!isatty(2))
    tvhlog_options &= ~TVHLOG_OPT_DECORATE;
  
  /* Initialise clock */
  pthread_mutex_lock(&global_lock);
  time(&dispatch_clock);

  /* Signal handling */
  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);
  trap_init(argv[0]);

  /* SSL library init */
  OPENSSL_config(NULL);
  SSL_load_error_strings();
  SSL_library_init();

  /* Initialise configuration */
  notify_init();
  idnode_init();
  spawn_init();
  config_init(opt_nobackup == 0);

  /**
   * Initialize subsystems
   */

  epg_in_load = 1;

  tvhthread_create(&tasklet_tid, NULL, tasklet_thread, NULL);

  dbus_server_init(opt_dbus, opt_dbus_session);

  intlconv_init();
  
  api_init();

  fsmonitor_init();

  libav_init();

  tvhtime_init();

  profile_init();

  imagecache_init();

  http_client_init(opt_user_agent);
  esfilter_init();

  bouquet_init();

  service_init();

  dvb_init();

#if ENABLE_MPEGTS
  mpegts_init(adapter_mask, &opt_satip_xml, &opt_tsfile, opt_tsfile_tuner);
#endif

  channel_init();

  bouquet_service_resolve();

  subscription_init();

  dvr_config_init();

  access_init(opt_firstrun, opt_noacl);

#if ENABLE_TIMESHIFT
  timeshift_init();
#endif

  tcp_server_init();
  webui_init(opt_xspf);
#if ENABLE_UPNP
  upnp_server_init(opt_bindaddr);
#endif

  service_mapper_init();

  descrambler_init();

  epggrab_init();
  epg_init();

  dvr_init();

  dbus_server_start();

  http_server_register();
  satip_server_register();
  htsp_register();

  if(opt_subscribe != NULL)
    subscription_dummy_join(opt_subscribe, 1);

  avahi_init();
  bonjour_init();

  epg_updated(); // cleanup now all prev ref's should have been created
  epg_in_load = 0;

  pthread_mutex_unlock(&global_lock);

  /**
   * Wait for SIGTERM / SIGINT, but only in this thread
   */

  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, "
         "running as PID:%d UID:%d GID:%d, CWD:%s CNF:%s",
         tvheadend_version,
         getpid(), getuid(), getgid(), getcwd(buf, sizeof(buf)),
         hts_settings_get_root());

  if(opt_abort)
    abort();

  mainloop();

#if ENABLE_DBUS_1
  tvhftrace("main", dbus_server_done);
#endif
#if ENABLE_UPNP
  tvhftrace("main", upnp_server_done);
#endif
  tvhftrace("main", satip_server_done);
  tvhftrace("main", htsp_done);
  tvhftrace("main", http_server_done);
  tvhftrace("main", webui_done);
  tvhftrace("main", fsmonitor_done);
  tvhftrace("main", http_client_done);
  tvhftrace("main", tcp_server_done);

  // Note: the locking is obviously a bit redundant, but without
  //       we need to disable the gtimer_arm call in epg_save()
  pthread_mutex_lock(&global_lock);
  tvhftrace("main", epg_save);

#if ENABLE_TIMESHIFT
  tvhftrace("main", timeshift_term);
#endif
  pthread_mutex_unlock(&global_lock);

  tvhftrace("main", epggrab_done);
#if ENABLE_MPEGTS
  tvhftrace("main", mpegts_done);
#endif
  tvhftrace("main", descrambler_done);
  tvhftrace("main", service_mapper_done);
  tvhftrace("main", service_done);
  tvhftrace("main", channel_done);
  tvhftrace("main", bouquet_done);
  tvhftrace("main", dvr_done);
  tvhftrace("main", subscription_done);
  tvhftrace("main", access_done);
  tvhftrace("main", epg_done);
  tvhftrace("main", avahi_done);
  tvhftrace("main", bonjour_done);
  tvhftrace("main", imagecache_done);
  tvhftrace("main", lang_code_done);
  tvhftrace("main", api_done);

  tvhtrace("main", "tasklet enter");
  pthread_cond_signal(&tasklet_cond);
  pthread_join(tasklet_tid, NULL);
  tvhtrace("main", "tasklet thread end");
  tasklet_flush();
  tvhtrace("main", "tasklet leave");

  tvhftrace("main", hts_settings_done);
  tvhftrace("main", dvb_done);
  tvhftrace("main", lang_str_done);
  tvhftrace("main", esfilter_done);
  tvhftrace("main", profile_done);
  tvhftrace("main", intlconv_done);
  tvhftrace("main", urlparse_done);
  tvhftrace("main", idnode_done);
  tvhftrace("main", notify_done);
  tvhftrace("main", spawn_done);

  tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend");
  tvhlog_end();

  tvhftrace("main", config_done);

  if(opt_fork)
    unlink(opt_pidpath);
    
#if ENABLE_TSFILE
  free(opt_tsfile.str);
#endif
  free(opt_satip_xml.str);

  /* OpenSSL - welcome to the "cleanup" hell */
  ENGINE_cleanup();
  RAND_cleanup();
  CRYPTO_cleanup_all_ex_data();
  EVP_cleanup();
  CONF_modules_free();
#ifndef OPENSSL_NO_COMP
  COMP_zlib_cleanup();
#endif
  ERR_remove_state(0);
  ERR_free_strings();
#ifndef OPENSSL_NO_COMP
  sk_SSL_COMP_free(SSL_COMP_get_compression_methods());
#endif
  /* end of OpenSSL cleanup code */

#if ENABLE_DBUS_1
  extern void dbus_shutdown(void);
  if (opt_dbus) dbus_shutdown();
#endif
  return 0;
}

/**
 *
 */
void
tvh_str_set(char **strp, const char *src)
{
  free(*strp);
  *strp = src ? strdup(src) : NULL;
}


/**
 *
 */
int
tvh_str_update(char **strp, const char *src)
{
  if(src == NULL)
    return 0;
  free(*strp);
  *strp = strdup(src);
  return 1;
}


/**
 *
 */
void
scopedunlock(pthread_mutex_t **mtxp)
{
  pthread_mutex_unlock(*mtxp);
}
Ejemplo n.º 14
0
int
main(
    int		argc,
    char **	argv)
{
#ifdef GNUTAR
    int i;
    char *e;
    char *dbf;
    char *cmdline;
    GPtrArray *array = g_ptr_array_new();
    gchar **strings;
    char **new_argv;
#endif

    if (argc > 1 && argv[1] && g_str_equal(argv[1], "--version")) {
	printf("runtar-%s\n", VERSION);
	return (0);
    }

    /*
     * Configure program for internationalization:
     *   1) Only set the message locale for now.
     *   2) Set textdomain for all amanda related programs to "amanda"
     *      We don't want to be forced to support dozens of message catalogs.
     */
    setlocale(LC_MESSAGES, "C");
    textdomain("amanda"); 

    safe_fd(-1, 0);
    safe_cd();

    set_pname("runtar");

    /* Don't die when child closes pipe */
    signal(SIGPIPE, SIG_IGN);

    dbopen(DBG_SUBDIR_CLIENT);
    config_init(CONFIG_INIT_CLIENT, NULL);

    if (argc < 3) {
	error(_("Need at least 3 arguments\n"));
	/*NOTREACHED*/
    }

    dbprintf(_("version %s\n"), VERSION);

    if (!g_str_equal(argv[3], "--create")) {
	error(_("Can only be used to create tar archives\n"));
	/*NOTREACHED*/
    }

#ifndef GNUTAR

    g_fprintf(stderr,_("gnutar not available on this system.\n"));
    dbprintf(_("%s: gnutar not available on this system.\n"), argv[0]);
    dbclose();
    return 1;

#else

    /*
     * Print out version information for tar.
     */
    do {
	FILE *	version_file;
	char	version_buf[80];

	if ((version_file = popen(GNUTAR " --version 2>&1", "r")) != NULL) {
	    if (fgets(version_buf, (int)sizeof(version_buf), version_file) != NULL) {
		dbprintf(_(GNUTAR " version: %s\n"), version_buf);
	    } else {
		if (ferror(version_file)) {
		    dbprintf(_(GNUTAR " version: Read failure: %s\n"), strerror(errno));
		} else {
		    dbprintf(_(GNUTAR " version: Read failure; EOF\n"));
		}
	    }
	} else {
	    dbprintf(_(GNUTAR " version: unavailable: %s\n"), strerror(errno));
	}
    } while(0);

#ifdef WANT_SETUID_CLIENT
    check_running_as(RUNNING_AS_CLIENT_LOGIN | RUNNING_AS_UID_ONLY);
    if (!become_root()) {
	error(_("error [%s could not become root (is the setuid bit set?)]\n"), get_pname());
	/*NOTREACHED*/
    }
#else
    check_running_as(RUNNING_AS_CLIENT_LOGIN);
#endif

    /* skip argv[0] */
    argc--;
    argv++;

    dbprintf(_("config: %s\n"), argv[0]);
    if (!g_str_equal(argv[0], "NOCONFIG"))
	dbrename(argv[0], DBG_SUBDIR_CLIENT);
    argc--;
    argv++;

    new_argv = g_new0(char *, argc+1);

    new_argv[0] = g_strdup_printf("%s", argv[0]);
    g_ptr_array_add(array, g_strdup(GNUTAR));
    for (i = 1; argv[i]; i++) {
        g_ptr_array_add(array, quote_string(argv[i]));
	new_argv[i] = g_strdup_printf("%s", argv[i]);
    }

    g_ptr_array_add(array, NULL);
    strings = (gchar **)g_ptr_array_free(array, FALSE);

    cmdline = g_strjoinv(" ", strings);
    g_strfreev(strings);

    dbprintf(_("running: %s\n"), cmdline);
    amfree(cmdline);

    dbf = dbfn();
    if (dbf) {
	dbf = g_strdup(dbf);
    }
    dbclose();

    execve(GNUTAR, new_argv, safe_env());

    e = strerror(errno);
    dbreopen(dbf, "more");
    amfree(dbf);
    dbprintf(_("execve of %s failed (%s)\n"), GNUTAR, e);
    dbclose();

    g_fprintf(stderr, _("runtar: could not exec %s: %s\n"), GNUTAR, e);
    return 1;
#endif
}
Ejemplo n.º 15
0
int main(int argc, char **argv) {
    config_init(argc, argv);
    initproctitle(argc, argv);

    return _main(&CONFIG);
}
Ejemplo n.º 16
0
/**
 * This function performs the task of authenticating the user
 * @param pam_handle The PAM handle
 * @param pam_flags The authentication flags
 * @param pam_argc The system arguments count
 * @param pam_argv The system arguments array
 * @return A PAM return code
 */
PAM_EXTERN int 
pam_sm_authenticate(pam_handle_t *pam_handle, int pam_flags, int pam_argc, 
const char **pam_argv)
{
    /* The module dialogs */
    struct pam_message *pam_dialog_message[1];
    struct pam_message pam_dialog_message_ptr[1];
    struct pam_response *pam_dialog_response;
    char *pam_dialog_input;

    /* The module parameters */
    int pam_config_permit_bypass = 0;
    int pam_config_code_length = 8;

    /* The module configuration */
    config_t pam_config;
    FILE *pam_config_fd;

    /* The module status */
    int pam_status;

    /* The module data */
    const char *pam_user;
    char pam_email[320];
    char *pam_code;
    char *pam_str_buffer;

    /* The module randomization */
    FILE *pam_urandom_fd;
    int pam_random;

    /* Init PAM dialog variables */
    pam_dialog_message[0] = &pam_dialog_message_ptr[0];
    pam_dialog_response = NULL;

    /* Init configuration */
    config_init(&pam_config);

    /* Init configuration file stream */
    if((pam_config_fd = fopen("/etc/aurora/email.conf", "r")) == NULL)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Unable to open configuration";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Properly destroy the configuration */
        config_destroy(&pam_config);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Read and parse the configuration file */
    if(config_read(&pam_config, pam_config_fd) == CONFIG_FALSE)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Unable to read configuration";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Properly destroy the configuration */
        config_destroy(&pam_config);

        /* Properly destroy the configuration file stream */
        fclose(pam_config_fd);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Get settings */
    config_lookup_int(&pam_config, "code_length", 
        &pam_config_code_length);
    config_lookup_int(&pam_config, "permit_bypass", 
        &pam_config_permit_bypass);

    /* Properly destroy the configuration */
    config_destroy(&pam_config);

    /* Get user login */
    if((pam_status = pam_get_user(pam_handle, &pam_user, "login: "******"[ERROR] Unable to get username";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Reject authentication */
        return pam_status;
    }

    /* Initialise the code */
    pam_code = (char*) malloc((pam_config_code_length + 1) * sizeof(char));

    /* Init the random stream */
    if((pam_urandom_fd = fopen("/dev/urandom", "r")) == NULL)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Unable to generate a code";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Extract a random number */
    fread(&pam_random, sizeof(pam_random), 1, pam_urandom_fd);

    /* Properly close the random stream */
    fclose(pam_urandom_fd);

    /* Store the random code */
    snprintf(pam_code, pam_config_code_length + 1, "%u", pam_random);

    /* Look for user email in directory */
    if((pam_status = pam_directory_lookup(pam_handle, pam_user, pam_email)) 
        != PAM_SUCCESS)
    {
        /* Return response (the error has already been transmit) */
        return pam_status;
    }

    /* Transmit the code */
    if((pam_status = pam_transmit_code(pam_handle, (const char*) pam_user,
	(const char*) pam_email, (const char*) pam_code)) != PAM_SUCCESS)
    {
        /* Apply bypass policy */
        if(! pam_config_permit_bypass)
        {
            /* An error occurs */
            pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
            pam_dialog_message_ptr[0].msg = 
                "[ERROR] Unable to send the code";
            pam_converse(pam_handle, 1, pam_dialog_message, 
                &pam_dialog_response);

            /* Free memory */
            free(pam_code);

            /* Reject authentication */
            return pam_status;
        }

        /* Free memory */
        free(pam_code);

        /* Bypass the module */
        return PAM_SUCCESS;
    }

    /* Prompt user code */
    pam_str_buffer = (char*) malloc(
        (672 + 1 + (strlen(pam_user) > 70? strlen(pam_user) - 70: 0)) * 
        sizeof(char));

    sprintf(pam_str_buffer, "\n"\
        "########################################"\
        "########################################\n"\
        "#                                        "\
        "                                      #\n"\
        "#    Hi %-70s #\n"\
        "#    You've just received by email a generated code."\
        "                           #\n"\
        "#    This code is only valid for the current authentication."\
        "                   #\n"\
        "#    To finish your authentication, thank you to enter this code."\
        "              #\n"\
        "#                                        "\
        "                                      #\n"\
        "########################################"\
        "########################################\n\n"\
        "Please type the code: ", pam_user);

    pam_dialog_message_ptr[0].msg_style = PAM_PROMPT_ECHO_ON;
    pam_dialog_message_ptr[0].msg = (const char *) pam_str_buffer;

    if((pam_status = pam_converse(pam_handle, 1, pam_dialog_message, 
        &pam_dialog_response)) != PAM_SUCCESS)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Unable to converse with PAM";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Free memory */
        free(pam_str_buffer);
        free(pam_code);

        /* Reject authentication */
        return pam_status;
    }

    /* Get user input */
    if(pam_dialog_response)
    {
        if((pam_flags & PAM_DISALLOW_NULL_AUTHTOK) 
            && pam_dialog_response[0].resp == NULL)
        {
            /* An error occurs */
            pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
            pam_dialog_message_ptr[0].msg = 
                "[ERROR] Unable to get the response";
            pam_converse(pam_handle, 1, pam_dialog_message, 
                &pam_dialog_response);

            /* Free memory */
            free(pam_dialog_response);
            free(pam_str_buffer);
            free(pam_code);

            /* Fail authentication */
            return PAM_AUTH_ERR;
        }

        /* Get user input */
        pam_dialog_input = pam_dialog_response[0].resp;
        pam_dialog_response[0].resp = NULL;
    }
    else
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
           "[ERROR] Unable to converse with PAM";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Free memory */
        free(pam_str_buffer);
        free(pam_code);

        /* Fail authentication */
        return PAM_CONV_ERR;
    }

    /* Verify user code */
    if(pam_dialog_input == NULL || strcmp(pam_dialog_input, pam_code) != 0)
    {
        /* Announce echec in PAM dialog */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = "Wrong code, please try again";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Free memory */
        free(pam_dialog_input);
        free(pam_str_buffer);
        free(pam_code);

        /* Fail authentication */
        return PAM_AUTH_ERR;
    }

    /* Free memory */
    free(pam_dialog_input);
    free(pam_str_buffer);
    free(pam_code);

    /* User successfully logged */
    return PAM_SUCCESS;
}
Ejemplo n.º 17
0
/**
 * This function looks for user data in directory
 * @param pam_handle The PAM handle
 * @param pam_user_login The user login
 * @param pam_user_email The email destination
 * @return A PAM return code
 */
int
pam_directory_lookup(pam_handle_t *pam_handle, const char *pam_user_login, 
char *pam_user_email)
{
    /* The module dialogs */
    struct pam_message *pam_dialog_message[1];
    struct pam_message pam_dialog_message_ptr[1];
    struct pam_response *pam_dialog_response;

    /* The module directory */
    config_t pam_directory;
    FILE *pam_directory_fd;
    config_setting_t *pam_directory_emails;

    /* The email buffer */
    const char *stored_user_email;

    /* Init PAM dialog variables */
    pam_dialog_message[0] = &pam_dialog_message_ptr[0];
    pam_dialog_response = NULL;

    /* Init configuration */
    config_init(&pam_directory);

    /* Init configuration file stream */
    if((pam_directory_fd = fopen("/etc/aurora/directory.conf", "r")) == NULL)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Unable to open directory";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Properly destroy the directory */
        config_destroy(&pam_directory);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Read and parse the configuration file */
    if(config_read(&pam_directory, pam_directory_fd) == CONFIG_FALSE)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Unable to read directory";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Properly destroy the directory */
        config_destroy(&pam_directory);

        /* Properly destroy the directory file stream */
        fclose(pam_directory_fd);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Get the emails collection */
    pam_directory_emails = config_lookup(&pam_directory, "emails");

    /* Look for user email */
    if (config_setting_lookup_string(pam_directory_emails, 
        pam_user_login, &stored_user_email) == CONFIG_FALSE)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Email not found in directory";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Properly destroy the directory */
        config_destroy(&pam_directory);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Check the email address length */
    if(strlen(stored_user_email) > 320)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Email address too long (max 320 chars)";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Properly destroy the directory */
        config_destroy(&pam_directory);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Copy email */
    strcpy(pam_user_email, stored_user_email);

    /* Properly destroy the directory */
    config_destroy(&pam_directory);

    /* User email found */
    return PAM_SUCCESS;
}
Ejemplo n.º 18
0
int
main(
    int		argc,
    char **	argv)
{
#ifndef ERRMSG
    char *dump_program;
    int i;
    char *e;
    char *cmdline;
#endif /* ERRMSG */

    /*
     * Configure program for internationalization:
     *   1) Only set the message locale for now.
     *   2) Set textdomain for all amanda related programs to "amanda"
     *      We don't want to be forced to support dozens of message catalogs.
     */  
    setlocale(LC_MESSAGES, "C");
    textdomain("amanda"); 

    safe_fd(-1, 0);
    safe_cd();

    set_pname("rundump");

    /* Don't die when child closes pipe */
    signal(SIGPIPE, SIG_IGN);

    dbopen(DBG_SUBDIR_CLIENT);
    config_init(CONFIG_INIT_CLIENT, NULL);

    if (argc < 3) {
	error(_("Need at least 3 arguments\n"));
	/*NOTREACHED*/
    }

    dbprintf(_("version %s\n"), VERSION);

#ifdef ERRMSG							/* { */

    g_fprintf(stderr, ERRMSG);
    dbprintf("%s: %s", argv[0], ERRMSG);
    dbclose();
    return 1;

#else								/* } { */

#ifdef WANT_SETUID_CLIENT
    check_running_as(RUNNING_AS_CLIENT_LOGIN | RUNNING_AS_UID_ONLY);
    if (!become_root()) {
	error(_("error [%s could not become root (is the setuid bit set?)]\n"), get_pname());
	/*NOTREACHED*/
    }
#else
    check_running_as(RUNNING_AS_CLIENT_LOGIN);
#endif

    /* skip argv[0] */
    argc--;
    argv++;

    dbprintf(_("config: %s\n"), argv[0]);
    if (strcmp(argv[0], "NOCONFIG") != 0)
	dbrename(argv[0], DBG_SUBDIR_CLIENT);
    argc--;
    argv++;

#ifdef XFSDUMP

    if (strcmp(argv[0], "xfsdump") == 0)
        dump_program = XFSDUMP;
    else /* strcmp(argv[0], "xfsdump") != 0 */

#endif

#ifdef VXDUMP

    if (strcmp(argv[0], "vxdump") == 0)
        dump_program = VXDUMP;
    else /* strcmp(argv[0], "vxdump") != 0 */

#endif

#ifdef VDUMP

    if (strcmp(argv[0], "vdump") == 0)
	dump_program = VDUMP;
    else /* strcmp(argv[0], "vdump") != 0 */

#endif

#if defined(DUMP)
        dump_program = DUMP;
#else
# if defined(XFSDUMP)
        dump_program = XFSDUMP;
# else
#  if defined(VXDUMP)
	dump_program = VXDUMP;
#  else
        dump_program = "dump";
#  endif
# endif
#endif

    cmdline = stralloc(dump_program);
    for (i = 1; argv[i]; i++) {
	char *quoted;

	quoted = quote_string(argv[i]);
	cmdline = vstrextend(&cmdline, " ", quoted, NULL);
	amfree(quoted);
    }
    dbprintf(_("running: %s\n"), cmdline);
    amfree(cmdline);

    execve(dump_program, argv, safe_env());

    e = strerror(errno);
    dbprintf(_("failed (%s)\n"), e);
    dbclose();

    g_fprintf(stderr, _("rundump: could not exec %s: %s\n"), dump_program, e);
    return 1;
#endif								/* } */
}
Ejemplo n.º 19
0
void readConf(const char *aFilename, Config * config) {
  config_t cfg;
  config_init(&cfg);

  // Open config file
  if (!config_read_file(&cfg, aFilename)) {
    error("Can't open config file %s: %d - %s\n", aFilename, config_error_line(&cfg), config_error_text(&cfg));
    config_destroy(&cfg);
    exit(-1);
  }

  config->filename = aFilename;

  config->videoType = UNKNOWN;
  config->ledType = EMPTY;
  config->ledControllerType = NONE;

  // Load config groups
  config_setting_t * video = config_lookup(&cfg, "video");
  if (!video) {
    error("Missing video configuration in config file %s\n", aFilename);
    exit(-1);
  }

  config_setting_t * videoDevice = config_lookup(&cfg, "video/device");
  if (!videoDevice) {
    error("Missing video device configuration in config file %s\n", aFilename);
    exit(-1);
  }

  config_setting_t * leds = config_lookup(&cfg, "leds");
  if (!leds) {
    error("Missing leds configuration in config file %s\n", aFilename);
    exit(-1);
  }

  config_setting_t * ledController = config_lookup(&cfg, "leds/controller");
  if (!ledController) {
    error("Missing led controller configuration in config file %s\n", aFilename);
    exit(-1);
  }

  // Load params

  // Video width
  int width;
  if (!config_setting_lookup_int(video, "width", &width))
    confError(aFilename, "video/width");

  config->width = width;

  // Video height
  int height;
  if (!config_setting_lookup_int(video, "height", &height))
    confError(aFilename, "video/height");

  config->height = height;

  // Video device type
  const char *videoDeviceType;
  if (!config_setting_lookup_string(videoDevice, "type", &videoDeviceType))
    confError(aFilename, "video/device/type");

  if (strcmp(videoDeviceType, "CAPTURER") == 0) config->videoType = CAPTURER;
  if (strcmp(videoDeviceType, "PLAYER") == 0) config->videoType = PLAYER; 
  if (config->videoType == UNKNOWN) confInvalid(aFilename, "video/device/type", videoDeviceType);

  // Video device path
  if (!config_setting_lookup_string(videoDevice, "path", &config->videoPath))
    confError(aFilename, "video/device/path");

  // Led type
  const char *ledDeviceType;
  if (!config_setting_lookup_string(leds, "type", &ledDeviceType))
    confError(aFilename, "leds/type");

  if (strcmp(ledDeviceType, "WS2801") == 0) config->ledType = WS2801;
  if (strcmp(ledDeviceType, "WS2812B") == 0) config->ledType = WS2812B;
  if (strcmp(ledDeviceType, "TM1804") == 0) config->ledType = TM1804;
  if (config->ledType == EMPTY) confInvalid(aFilename, "leds/type", ledDeviceType);

  // Leds left
  if (!config_setting_lookup_int(leds, "left", &config->ledsLeft))
    confError(aFilename, "leds/left");

  // Leds up
  if (!config_setting_lookup_int(leds, "up", &config->ledsUp))
    confError(aFilename, "leds/up");

  // Leds right
  if (!config_setting_lookup_int(leds, "right", &config->ledsRight))
    confError(aFilename, "leds/right");

  // Leds down
  if (!config_setting_lookup_int(leds, "down", &config->ledsDown))
    confError(aFilename, "leds/down");

  // Led controller type
  const char *ledControllerDeviceType;
  if (!config_setting_lookup_string(ledController, "type", &ledControllerDeviceType))
    confError(aFilename, "leds/controller/type");

  if (strcmp(ledControllerDeviceType, "ARDUINO") == 0) config->ledControllerType = ARDUINO;
  if (strcmp(ledControllerDeviceType, "RASPBERRY") == 0) config->ledControllerType = RASPBERRY;
  if (config->ledControllerType == NONE) confInvalid(aFilename, "leds/controller/type", ledControllerDeviceType);

  // Led controller device pat
  if (!config_setting_lookup_string(ledController, "path", &config->ledControllerPath))
    confError(aFilename, "leds/controller/path");
}
Ejemplo n.º 20
0
void init_register(const char *scfile){
    share_config_file = strdup(scfile);
      
  // try to open share_config_file for reading
  // if it fails try writing a default config file 
      sem_init(&cfgsem,0,1);   
	  strcat(servername,"Unknown");
	  FILE *file;
	  file = fopen(share_config_file, "r");
	  if (file) { 
		  fclose(file);
	  }else{
		  file = fopen(share_config_file,"w");
		  if (file) {
			fprintf(file,"%s\n","# Simple config file for ghpsdr3's dspserver.");
			fprintf(file,"%s\n","# default file is located at ~/dspserver.conf when dsp server is started with --share");
			fprintf(file,"%s\n","# The information below will be supplied to a web database which will aid QtRadio");
			fprintf(file,"%s\n","# users find active dspservers to connect to.  You may also see the current list at");
			fprintf(file,"%s\n","# http://napan.ca/qtradio/qtradio.pl");
			fprintf(file,"%s\n","# valid fields are call, location, band, rig and ant");
			fprintf(file,"%s\n","# lines must end with ; and any characters after a # is a comment and ignored");
			fprintf(file,"%s\n","# field values must be enclosed with \" ie: \"xxxx\"");
			fprintf(file,"%s\n","# This default file will be created if dspserver is started with the --share option and ~/dspserver.cfg does not exist");
			fprintf(file,"%s\n","# You may also start dspserver with an alternate config file by starting dspserver with --shareconfig /home/alternate_filename.conf");
			fprintf(file,"%s\n","# Note field names are all lowercase!");

			fprintf(file,"\n%s\n","call = \"Unknown\";");
			fprintf(file,"%s\n","location = \"Unknown\";");
			fprintf(file,"%s\n","band = \"Unknown\";");
			fprintf(file,"%s\n","rig = \"Unknown\";");
			fprintf(file,"%s\n","ant = \"Unknown\";");
			fprintf(file,"%s\n","share = \"yes\"; # Can be yes, no");
			fprintf(file,"%s\n","lookupcountry = \"no\"; # Can be yes, no");
			fprintf(file,"\n%s\n","#### Following are new TX options #####");
			fprintf(file,"\n%s\n","tx = \"no\";  #Can be: no, yes, password");
			fprintf(file,"\n%s\n","#ve9gj = \"secretpassword\";  #add users/passwords one per line (Remove leading # ! max 20 characters each");
			fprintf(file,"\n%s\n","groupnames = [\"txrules1\"];  #add group or rulesset names in [\"name1\", \"name2\"]; format (max 20 characters each");
			fprintf(file,"\n%s\n", "# Add user names in [\"call1\", \"call2\"]; format to list members for each groupname above with an suffix of \"_members\" ");
			fprintf(file,"%s\n","txrules1_members = [\"ve9gj\", \"call2\"]; ");
			fprintf(file,"\n%s\n","# Rule sets are defined as group or rulesset name =( (\"mode\", StartFreq in Mhz, End Freq in Mhz),(\"mode\", StartFreq in Mhz, End Freq in Mhz) );");
			fprintf(file,"%s\n","#  Valid modes are  * SSB, CW, AM, DIG, FM, DRM ,SAM, SPEC Where * means any mode is OK");
			fprintf(file,"%s\n","#  The two rules below allow any mode on 20M and CW only on the bottom 100Khz of 80M");
			fprintf(file,"%s\n","#  You can make as many rules and rulesets as you wish. The first matching rule will allow TX");
			fprintf(file,"\n%s\n","txrules1 = (\n     (\"*\",14.0,14.350), # mode, StartFreq Mhz, EndFreq Mhz");
			fprintf(file,"%s\n","     (\"CW\",3.5,3.6)");
			fprintf(file,"%s\n","          );");
			
			fclose(file);
			fprintf(stderr,"%s\n", "**********************************************************");
			fprintf(stderr,"%s\n", "  A new  dspserver config file template has been created at: ");
			fprintf(stderr,"  %s\n", share_config_file);
			fprintf(stderr,"%s\n", "  Please edit this file and fill in your station details!");
			fprintf(stderr,"%s\n", "***********************************************************");
		  } else{
			  fprintf(stderr, "Error Can't create config file %s\n", share_config_file);
		  }
		  
	  }           
  
  
  
  
  const char *str;
  config_init(&cfg);
  if(! config_read_file(&cfg, share_config_file))
  {
    fprintf(stderr, "Error - %s\n",  config_error_text(&cfg));
    config_destroy(&cfg);
    
  }else{
	 if(config_lookup_string(&cfg, "call", &str)){
         call = str;
         strncpy(servername,str, 20);
     }
     if(config_lookup_string(&cfg, "location", &str)){
         location = str;
     }
     if(config_lookup_string(&cfg, "band", &str)){
         band = str;
     }
	 if(config_lookup_string(&cfg, "rig", &str)){
         rig = str;
     }
     if(config_lookup_string(&cfg, "ant", &str)){
         ant = str;
     }
     if(config_lookup_string(&cfg, "share", &str)){
         if (strcmp(str, "yes") == 0){
			 toShareOrNotToShare = 1;
         }else{
             toShareOrNotToShare = 0;
         }
     }else{
		fprintf(stderr, "Conf File Error - %s%s%s\n",  "Your ",share_config_file, " is missing a share= setting!!" );
	 } 
     if(config_lookup_string(&cfg, "lookupcountry", &str)){
         if (strcmp(str, "yes") == 0){
			 setprintcountry();
         }
     }else{
		fprintf(stderr, "Conf File Error - %s%s%s\n",  "Your ",share_config_file, " is missing a lookupcountry= setting!!" );
	 } 
     if(config_lookup_string(&cfg, "tx", &str)){
         if (strcmp(str, "yes") == 0){
			 txcfg = TXALL;
         }else if(strcmp(str, "password") == 0){
             txcfg = TXPASSWD;
         }else{
			 txcfg = TXNONE;
		 }
     }else{
		fprintf(stderr, "Conf File Error - %s%s%s\n",  "Your ",share_config_file, " is missing a tx= setting!!\n TX is now disabled" );
		txcfg = TXNONE;
	 } 
     
  }	    
  
    if (strcmp(call, "Unknown") == 0){
		fprintf(stderr,"%s\n", "**********************************************************");
		fprintf(stderr,"%s\n", "  Your config file located at: ");
		fprintf(stderr,"  %s\n", share_config_file);
		fprintf(stderr,"%s\n", "  Contains Unknown for a Call");
		fprintf(stderr,"%s\n", "  Please edit this file and fill in your station details!");
		fprintf(stderr,"%s\n", "***********************************************************");
	}
    call = url_encode(call);
    location = url_encode(location);
    band = url_encode(band);
    rig = url_encode(rig);
    ant = url_encode(ant); 
    
    pthread_t thread1;
    int ret;
    if (toShareOrNotToShare){
      ret = pthread_create( &thread1, NULL, doReg, (void*) NULL);
      ret = pthread_detach(thread1);
    }
}
Ejemplo n.º 21
0
int main(int argc, char *argv[])
{
	gchar *filename;
	gboolean default_used;
	GtkWidget *notebook;
	GtkActionGroup *action_group;
	GtkUIManager *ui_manager;
	GtkWidget *vbox;
	GtkWidget *menubar;
	GtkAccelGroup *accel_group;
	GError *error = NULL;
	gchar *icon_file;
	GOptionContext *context;

	default_game = g_build_filename(get_pioneers_dir(), "default.game",
					NULL);

	/* Gtk+ handles the locale, we must bind the translations */
	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	bind_textdomain_codeset(PACKAGE, "UTF-8");

GtkOSXApplication *theApp = g_object_new(GTK_TYPE_OSX_APPLICATION, NULL);

	context =
	    /* Long description in the command line: --help */
	    g_option_context_new(_("- Editor for games of Pioneers"));
	g_option_context_add_main_entries(context, commandline_entries,
					  GETTEXT_PACKAGE);
	g_option_context_add_group(context, gtk_get_option_group(TRUE));
	g_option_context_parse(context, &argc, &argv, &error);
	if (error != NULL) {
		g_print("%s\n", error->message);
		g_error_free(error);
		return 1;
	}
	if (show_version) {
		g_print(_("Pioneers version:"));
		g_print(" ");
		g_print(FULL_VERSION);
		g_print("\n");
		return 0;
	}

	if (filenames != NULL)
		filename = g_strdup(filenames[0]);
	else
		filename = NULL;

	toplevel = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	g_signal_connect(G_OBJECT(toplevel), "delete_event",
			 G_CALLBACK(exit_cb), NULL);

	action_group = gtk_action_group_new("MenuActions");
	gtk_action_group_set_translation_domain(action_group, PACKAGE);
	gtk_action_group_add_actions(action_group, entries,
				     G_N_ELEMENTS(entries), toplevel);

	ui_manager = gtk_ui_manager_new();
	gtk_ui_manager_insert_action_group(ui_manager, action_group, 0);

	accel_group = gtk_ui_manager_get_accel_group(ui_manager);
	gtk_window_add_accel_group(GTK_WINDOW(toplevel), accel_group);

	error = NULL;
	if (!gtk_ui_manager_add_ui_from_string(ui_manager, ui_description,
					       -1, &error)) {
		g_message(_("Building menus failed: %s"), error->message);
		g_error_free(error);
		return 1;
	}

	config_init("pioneers-editor");

	icon_file =
	    g_build_filename(g_get_user_runtime_dir(), "pixmaps", MAINICON_FILE, NULL);
	if (g_file_test(icon_file, G_FILE_TEST_EXISTS)) {
		gtk_window_set_default_icon_from_file(icon_file, NULL);
	} else {
		/* Missing pixmap, main icon file */
		g_warning("Pixmap not found: %s", icon_file);
	}
	g_free(icon_file);

	themes_init();
	colors_init();

	notebook = gtk_notebook_new();
	gtk_notebook_set_tab_pos(GTK_NOTEBOOK(notebook), GTK_POS_TOP);

	gtk_notebook_append_page(GTK_NOTEBOOK(notebook), build_map(),
				 /* Tab page name */
				 gtk_label_new(_("Map")));

	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
				 build_settings(GTK_WINDOW(toplevel)),
				 /* Tab page name */
				 gtk_label_new(_("Settings")));

	terrain_menu = build_terrain_menu();
	roll_menu = build_roll_menu();
	port_menu = build_port_menu();

	vbox = gtk_vbox_new(FALSE, 0);
	gtk_container_add(GTK_CONTAINER(toplevel), vbox);

	menubar = gtk_ui_manager_get_widget(ui_manager, "/MainMenu");
	gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, FALSE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), notebook, TRUE, TRUE, 0);

	if (filename == NULL) {
		filename =
		    config_get_string("editor/last-game", &default_used);
		if (default_used
		    || !g_file_test(filename, G_FILE_TEST_EXISTS)) {
			g_free(filename);
			filename = NULL;
		}
	}

	load_game(filename, FALSE);
	g_free(filename);
	if (params == NULL)
		return 1;

	gtk_widget_show_all(toplevel);

	gtk_accel_map_load(g_getenv("ACCEL_MAP"));
	gtk_widget_hide (menubar);
	gtk_osxapplication_set_menu_bar(theApp, GTK_MENU_SHELL(menubar));
	gtk_osxapplication_ready(theApp);

	gtk_main();

	config_finish();
	guimap_delete(gmap);
	g_free(default_game);

	g_option_context_free(context);
	return 0;
}
Ejemplo n.º 22
0
int iteliec_soap_register (char *username, char *password) {
    herror_t err;
    SoapCtx *request;
    SoapCtx *response;

    config_t cfg;
    config_setting_t *setting, *root;
    const char *cfile;

    cfile = iteliec_config_file ();
    
    config_init (&cfg);

    /* Read the file. If there is an error, report it and exit. */
    if (!config_read_file (&cfg, cfile)) {
        iteliec_log (ITELIEC_ERR, "Please ensure configuration file %s exists and is valid", cfile);
        //printf ("\n%s:%d - %s", config_error_file (&cfg), config_error_line (&cfg), config_error_text (&cfg));
        
        config_destroy (&cfg);
        
        return;
    }

    root = config_root_setting (&cfg);

    /* Init */
    err = soap_client_init_args (0, NULL);
    if (err != H_OK)  {
        err_soap (err);
        
        return ITELIEC_ERR;
    }

    err = soap_ctx_new_with_method ("", "sendAuth", &request);
    if (err != H_OK) {
        err_soap (err);
        soap_client_destroy ();

        return ITELIEC_ERR;
    }

    /* Add login details */
    soap_env_add_item (request->env, "xsd:string", "username", username);
    soap_env_add_item (request->env, "xsd:string", "password", password);

    /* Trade for response */
    err = soap_client_invoke (request, &response, "http://api.iteliec.com/register/auth/ws/", "");
    if (err != H_OK)  {
        err_soap (err);
        soap_ctx_free (request);
        soap_client_destroy ();
        
        return ITELIEC_ERR;
    }

    /* Parse response */
    auth_type* ret = parse_auth_response (response);
    if (ret->auth == true) {
        printf ("Success\n");
        
        setting = config_setting_get_member (root, "api");
        if(!setting) {
            setting = config_setting_add (root, "api", CONFIG_TYPE_GROUP);        
        }

        setting = config_setting_add (setting, "hash", CONFIG_TYPE_STRING);
        config_setting_set_string (setting, ret->token);

        /* Write out the updated configuration. */
        if(! config_write_file(&cfg, cfile)) {
            fprintf (stderr, "Error while writing file.\n");
            config_destroy (&cfg);
            
            return (ITELIEC_OK);
        }

        printf("\nConfiguration file updated. Server is ready to run.\n");

    } else {
        printf("Auth failed\n");
    }

    /* Destroy */
    soap_ctx_free (request);
    soap_ctx_free (response);
    
    soap_client_destroy ();
    config_destroy (&cfg);

    return ITELIEC_OK;
}
Ejemplo n.º 23
0
int writeCfg (void)
{
	config_t cfg;
	config_setting_t *tonTemp = 0;
	config_setting_t *toffTemp = 0;
	config_setting_t *thighTemp = 0;
	config_setting_t *tonHum = 0;
	config_setting_t *toffHum = 0;
	config_setting_t *twebOR = 0;
	config_setting_t *ttempState = 0;
	config_setting_t *thumState = 0;

	config_init(&cfg);

	if (!config_read_file(&cfg, config_file_name))
	{
		printf("\n%s:%d - %s", config_error_file(&cfg), config_error_line(&cfg), config_error_text(&cfg));
		config_destroy(&cfg);
		return -1;
	}

	/* lookup variables in config file */
	tonTemp = config_lookup(&cfg, "onTemp");
	toffTemp = config_lookup(&cfg, "offTemp");
	thighTemp = config_lookup(&cfg, "highTemp");
	tonHum = config_lookup(&cfg, "onHum");
	toffHum = config_lookup(&cfg, "offHum");
	twebOR = config_lookup(&cfg, "webOR");
	ttempState = config_lookup(&cfg, "tempState");
	thumState = config_lookup(&cfg, "humState");

	/* get variables from config file then print the variables that changed */
	if (config_setting_get_int(tonTemp) != onTemp) {
		printf("\nonTemp: %i -> ", config_setting_get_int(tonTemp));
		config_setting_set_int(tonTemp, onTemp);
		printf("%i", config_setting_get_int(tonTemp));
	}

	if (config_setting_get_int(toffTemp) != offTemp) {
		printf("\noffTemp: %i -> ", config_setting_get_int(toffTemp));
		config_setting_set_int(toffTemp, offTemp);
		printf("%i", config_setting_get_int(toffTemp));
	}

	if (config_setting_get_int(thighTemp) != highTemp) {
		printf("\nhighTemp: %i -> ", config_setting_get_int(thighTemp));
		config_setting_set_int(thighTemp, highTemp);
		printf("%i", config_setting_get_int(thighTemp));
	}

	if (config_setting_get_int(tonHum) != onHum) {
		printf("\nonHum: %i -> ", config_setting_get_int(tonHum));
		config_setting_set_int(tonHum, onHum);
		printf("%i", config_setting_get_int(tonHum));
	}

	if (config_setting_get_int(toffHum) != offHum) {
		printf("\noffHum: %i -> ", config_setting_get_int(toffHum));
		config_setting_set_int(toffHum, offHum);
		printf("%i", config_setting_get_int(toffHum));
	}

	if (config_setting_get_int(twebOR) != webOR) {
		printf("\nwebOR: %i -> ", config_setting_get_int(twebOR));
		config_setting_set_int(twebOR, webOR);
		printf("%i", config_setting_get_int(twebOR));
	}

	if (config_setting_get_int(ttempState) != tempState) {
		printf("\ntempState: %i -> ", config_setting_get_int(ttempState));
		config_setting_set_int(ttempState, tempState);
		printf("%i", config_setting_get_int(ttempState));
	}

	if (config_setting_get_int(thumState) != humState) {
		printf("\nhumState: %i -> ", config_setting_get_int(thumState));
		config_setting_set_int(thumState, humState);
		printf("%i", config_setting_get_int(thumState));
	}

	/* write the modified config file */
	config_write_file(&cfg, config_file_name);

	config_destroy(&cfg);

	return 0;
}
Ejemplo n.º 24
0
static int __config_read(config_t *config, FILE *stream, const char *filename,
                         const char *str)
{
  yyscan_t scanner;
  struct scan_context scan_ctx;
  struct parse_context parse_ctx;
  YY_BUFFER_STATE buffer = NULL;
  int r;

  /* Reinitialize the config */
  void (*destructor)(void *) = config->destructor;
  const char *include_dir = config->include_dir;
  unsigned short tab_width = config->tab_width;
  unsigned short flags = config->flags;

  config->include_dir = NULL;
  config_destroy(config);
  config_init(config);

  config->destructor = destructor;
  config->include_dir = include_dir;
  config->tab_width = tab_width;
  config->flags = flags;

  parsectx_init(&parse_ctx);
  parse_ctx.config = config;
  parse_ctx.parent = config->root;
  parse_ctx.setting = config->root;

  __config_locale_override();

  scanctx_init(&scan_ctx, filename);
  scan_ctx.config = config;
  libconfig_yylex_init_extra(&scan_ctx, &scanner);

  if(stream)
    libconfig_yyrestart(stream, scanner);
  else /* read from string */
    buffer = libconfig_yy_scan_string(str, scanner);

  libconfig_yyset_lineno(1, scanner);
  r = libconfig_yyparse(scanner, &parse_ctx, &scan_ctx);

  if(r != 0)
  {
    YY_BUFFER_STATE buf;

    config->error_file = scanctx_current_filename(&scan_ctx);
    config->error_type = CONFIG_ERR_PARSE;

    /* Unwind the include stack, freeing the buffers and closing the files. */
    while((buf = (YY_BUFFER_STATE)scanctx_pop_include(&scan_ctx)) != NULL)
      libconfig_yy_delete_buffer(buf, scanner);
  }

  libconfig_yylex_destroy(scanner);
  config->filenames = scanctx_cleanup(&scan_ctx, &(config->num_filenames));
  parsectx_cleanup(&parse_ctx);

  __config_locale_restore();

  return(r == 0 ? CONFIG_TRUE : CONFIG_FALSE);
}
Ejemplo n.º 25
0
int
cgi_main (fastphoto_t * params)
{
  int err = 0;
  char * path_info;
  char * path_translated;
  char * query_string;
  char * if_modified_since;
  time_t since_time;

  httpdate_init ();

  path_info = getenv ("PATH_INFO");
  path_translated = getenv ("PATH_TRANSLATED");
  query_string = getenv ("QUERY_STRING");
  if_modified_since = getenv ("HTTP_IF_MODIFIED_SINCE");

  photo_init (&params->in, path_translated);

  if (if_modified_since != NULL) {
    int len;

    fprintf (stderr, "If-Modified-Since: %s\n", if_modified_since);

    len = strlen (if_modified_since) + 1;
    since_time = httpdate_parse (if_modified_since, len);

    if (params->in.mtime <= since_time) {
      header_not_modified();
      header_end();
      return 1;
    }
  }

  header_content_type_jpeg ();

  config_init (params);

  parse_query (params, query_string);

  if (params->x || params->y || params->scale || params->gray ||
      params->quality) {
    cache_init (params, path_info);
  } else {
    params->nochange = 1;
  }

  err = 0;
  if (!(params->nochange || params->cached)) {
    err = resize (params);
  }
  
  if (!err) {
    cgi_send (params);
  }

  if (params->out.name) {
    free (params->out.name);
  }

  return err;
}
Ejemplo n.º 26
0
/**
 * Initialize the application configuration based on the config file content
 * Read the config file, get mandatory variables and devices
 */
int build_config_from_file(struct config_elements * config) {
  
  config_t cfg;
  config_setting_t * root, * database;
  const char * cur_prefix, * cur_log_mode, * cur_log_level, * cur_log_file = NULL, * one_log_mode, 
             * db_type, * db_sqlite_path, * db_mariadb_host = NULL, * db_mariadb_user = NULL, * db_mariadb_password = NULL, * db_mariadb_dbname = NULL;
  int db_mariadb_port = 0;
  
  config_init(&cfg);
  
  if (!config_read_file(&cfg, config->config_file)) {
    fprintf(stderr, "Error parsing config file %s\nOn line %d error: %s\n", config_error_file(&cfg), config_error_line(&cfg), config_error_text(&cfg));
    config_destroy(&cfg);
    return 0;
  }
  
  if (config->instance->port == -1) {
    // Get Port number to listen to
    int port;
    config_lookup_int(&cfg, "port", &port);
    config->instance->port = port;
  }
  
  if (config->url_prefix == NULL) {
    // Get prefix url
    if (config_lookup_string(&cfg, "url_prefix", &cur_prefix)) {
      config->url_prefix = o_strdup(cur_prefix);
      if (config->url_prefix == NULL) {
        fprintf(stderr, "Error allocating config->url_prefix, exiting\n");
        config_destroy(&cfg);
        return 0;
      }
    }
  }

  if (config->log_mode == Y_LOG_MODE_NONE) {
    // Get log mode
    if (config_lookup_string(&cfg, "log_mode", &cur_log_mode)) {
      one_log_mode = strtok((char *)cur_log_mode, ",");
      while (one_log_mode != NULL) {
        if (0 == strncmp("console", one_log_mode, strlen("console"))) {
          config->log_mode |= Y_LOG_MODE_CONSOLE;
        } else if (0 == strncmp("syslog", one_log_mode, strlen("syslog"))) {
          config->log_mode |= Y_LOG_MODE_SYSLOG;
        } else if (0 == strncmp("file", one_log_mode, strlen("file"))) {
          config->log_mode |= Y_LOG_MODE_FILE;
          // Get log file path
          if (config->log_file == NULL) {
            if (config_lookup_string(&cfg, "log_file", &cur_log_file)) {
              config->log_file = o_strdup(cur_log_file);
              if (config->log_file == NULL) {
                fprintf(stderr, "Error allocating config->log_file, exiting\n");
                config_destroy(&cfg);
                return 0;
              }
            }
          }
        }
        one_log_mode = strtok(NULL, ",");
      }
    }
  }
  
  if (config->log_level == Y_LOG_LEVEL_NONE) {
    // Get log level
    if (config_lookup_string(&cfg, "log_level", &cur_log_level)) {
      if (0 == strncmp("NONE", cur_log_level, strlen("NONE"))) {
        config->log_level = Y_LOG_LEVEL_NONE;
      } else if (0 == strncmp("ERROR", cur_log_level, strlen("ERROR"))) {
        config->log_level = Y_LOG_LEVEL_ERROR;
      } else if (0 == strncmp("WARNING", cur_log_level, strlen("WARNING"))) {
        config->log_level = Y_LOG_LEVEL_WARNING;
      } else if (0 == strncmp("INFO", cur_log_level, strlen("INFO"))) {
        config->log_level = Y_LOG_LEVEL_INFO;
      } else if (0 == strncmp("DEBUG", cur_log_level, strlen("DEBUG"))) {
        config->log_level = Y_LOG_LEVEL_DEBUG;
      }
    }
  }

  if (!y_init_logs(GARETH_LOG_NAME, config->log_mode, config->log_level, config->log_file, "Starting Gareth alert and messenger service")) {
    fprintf(stderr, "Error initializing logs\n");
    exit_server(&config, GARETH_ERROR);
  }
    
  root = config_root_setting(&cfg);
  database = config_setting_get_member(root, "database");
  if (database != NULL) {
    if (config_setting_lookup_string(database, "type", &db_type) == CONFIG_TRUE) {
      if (0 == strncmp(db_type, "sqlite3", strlen("sqlite3"))) {
        if (config_setting_lookup_string(database, "path", &db_sqlite_path) == CONFIG_TRUE) {
          config->conn = h_connect_sqlite(db_sqlite_path);
          if (config->conn == NULL) {
            config_destroy(&cfg);
            fprintf(stderr, "Error opening sqlite database %s\n", db_sqlite_path);
            return 0;
          }
        } else {
          config_destroy(&cfg);
          fprintf(stderr, "Error, no sqlite database specified\n");
          return 0;
        }
      } else if (0 == strncmp(db_type, "mariadb", strlen("mariadb"))) {
        config_setting_lookup_string(database, "host", &db_mariadb_host);
        config_setting_lookup_string(database, "user", &db_mariadb_user);
        config_setting_lookup_string(database, "password", &db_mariadb_password);
        config_setting_lookup_string(database, "dbname", &db_mariadb_dbname);
        config_setting_lookup_int(database, "port", &db_mariadb_port);
        config->conn = h_connect_mariadb(db_mariadb_host, db_mariadb_user, db_mariadb_password, db_mariadb_dbname, db_mariadb_port, NULL);
        if (config->conn == NULL) {
          fprintf(stderr, "Error opening mariadb database %s\n", db_mariadb_dbname);
          config_destroy(&cfg);
          return 0;
        }
      } else {
        config_destroy(&cfg);
        fprintf(stderr, "Error, database type unknown\n");
        return 0;
      }
    } else {
      config_destroy(&cfg);
      fprintf(stderr, "Error, no database type found\n");
      return 0;
    }
  } else {
    config_destroy(&cfg);
    fprintf(stderr, "Error, no database setting found\n");
    return 0;
  }
  
  config_destroy(&cfg);
  return 1;
}
Ejemplo n.º 27
0
static int config_parse_file(mme_config_t *mme_config_p)
{
  config_t          cfg;
  config_setting_t *setting_mme                      = NULL;
  config_setting_t *setting                          = NULL;
  config_setting_t *subsetting                       = NULL;
  config_setting_t *sub2setting                      = NULL;

  long int         alongint;
  int              i, num;
  char             *astring                          = NULL;
  char             *address                          = NULL;
  char             *cidr                             = NULL;

  const char*       tac                              = NULL;
  const char*       mcc                              = NULL;
  const char*       mnc                              = NULL;

  char             *sgw_ip_address_for_S1u_S12_S4_up = NULL;
  char             *mme_interface_name_for_S1_MME    = NULL;
  char             *mme_ip_address_for_S1_MME        = NULL;
  char             *mme_interface_name_for_S11       = NULL;
  char             *mme_ip_address_for_S11           = NULL;
  char             *sgw_ip_address_for_S11           = NULL;
  char                system_cmd[256];

  config_init(&cfg);

  if(mme_config_p->config_file != NULL) {
    /* Read the file. If there is an error, report it and exit. */
    if(! config_read_file(&cfg, mme_config_p->config_file)) {
      fprintf(stdout, "ERROR: %s:%d - %s\n", mme_config_p->config_file, config_error_line(&cfg), config_error_text(&cfg));
      config_destroy(&cfg);
      AssertFatal (1 == 0, "Failed to parse MME configuration file %s!\n", mme_config_p->config_file);
    }
  } else {
    fprintf(stdout, "ERROR No MME configuration file provided!\n");
    config_destroy(&cfg);
    AssertFatal (0, "No MME configuration file provided!\n");
  }

  setting_mme = config_lookup(&cfg, MME_CONFIG_STRING_MME_CONFIG);

  if(setting_mme != NULL) {
    // GENERAL MME SETTINGS
    if(  (config_setting_lookup_string( setting_mme, MME_CONFIG_STRING_REALM, (const char **)&astring) )) {
      mme_config_p->realm = strdup(astring);
      mme_config_p->realm_length = strlen(mme_config_p->realm);
    }

    if(  (config_setting_lookup_int( setting_mme, MME_CONFIG_STRING_MAXENB, &alongint) )) {
      mme_config_p->max_eNBs = (uint32_t)alongint;
    }

    if(  (config_setting_lookup_int( setting_mme, MME_CONFIG_STRING_MAXUE, &alongint) )) {
      mme_config_p->max_ues = (uint32_t)alongint;
    }

    if(  (config_setting_lookup_int( setting_mme, MME_CONFIG_STRING_RELATIVE_CAPACITY, &alongint) )) {
      mme_config_p->relative_capacity = (uint8_t)alongint;
    }

    if(  (config_setting_lookup_int( setting_mme, MME_CONFIG_STRING_STATISTIC_TIMER, &alongint) )) {
      mme_config_p->mme_statistic_timer = (uint32_t)alongint;
    }

    if(  (config_setting_lookup_string( setting_mme, MME_CONFIG_STRING_EMERGENCY_ATTACH_SUPPORTED, (const char **)&astring) )) {
      if (strcasecmp(astring , "yes") == 0)
        mme_config_p->emergency_attach_supported = 1;
      else
        mme_config_p->emergency_attach_supported = 0;
    }

    if(  (config_setting_lookup_string( setting_mme, MME_CONFIG_STRING_UNAUTHENTICATED_IMSI_SUPPORTED, (const char **)&astring) )) {
      if (strcasecmp(astring , "yes") == 0)
        mme_config_p->unauthenticated_imsi_supported = 1;
      else
        mme_config_p->unauthenticated_imsi_supported = 0;
    }

    if(  (config_setting_lookup_string( setting_mme, MME_CONFIG_STRING_ASN1_VERBOSITY, (const char **)&astring) )) {
      if (strcasecmp(astring , MME_CONFIG_STRING_ASN1_VERBOSITY_NONE) == 0)
        mme_config_p->verbosity_level = 0;
      else if (strcasecmp(astring , MME_CONFIG_STRING_ASN1_VERBOSITY_ANNOYING) == 0)
        mme_config_p->verbosity_level = 2;
      else if (strcasecmp(astring , MME_CONFIG_STRING_ASN1_VERBOSITY_INFO) == 0)
        mme_config_p->verbosity_level = 1;
      else
        mme_config_p->verbosity_level = 0;
    }

    // ITTI SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_INTERTASK_INTERFACE_CONFIG);

    if (setting != NULL) {
      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_INTERTASK_INTERFACE_QUEUE_SIZE, &alongint) )) {
        mme_config_p->itti_config.queue_size = (uint32_t)alongint;
      }
    }

    // S6A SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_S6A_CONFIG);

    if (setting != NULL) {
      if(  (config_setting_lookup_string( setting, MME_CONFIG_STRING_S6A_CONF_FILE_PATH, (const char **)&astring) )) {
        if (astring != NULL)
          mme_config_p->s6a_config.conf_file = strdup(astring);
      }

      if(  (config_setting_lookup_string( setting, MME_CONFIG_STRING_S6A_HSS_HOSTNAME, (const char **)&astring) )) {
        if (astring != NULL)
          mme_config_p->s6a_config.hss_host_name  = strdup(astring);
        else
          AssertFatal (1 == 0,
                       "You have to provide a valid HSS hostname %s=...\n",
                       MME_CONFIG_STRING_S6A_HSS_HOSTNAME);
      }
    }

    // SCTP SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_SCTP_CONFIG);

    if (setting != NULL) {
      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_SCTP_INSTREAMS, &alongint) )) {
        mme_config_p->sctp_config.in_streams = (uint16_t)alongint;
      }

      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_SCTP_OUTSTREAMS, &alongint) )) {
        mme_config_p->sctp_config.out_streams = (uint16_t)alongint;
      }
    }

    // S1AP SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_S1AP_CONFIG);

    if (setting != NULL) {
      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_S1AP_OUTCOME_TIMER, &alongint) )) {
        mme_config_p->s1ap_config.outcome_drop_timer_sec = (uint8_t)alongint;
      }

      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_S1AP_PORT, &alongint) )) {
        mme_config_p->s1ap_config.port_number = (uint16_t)alongint;
      }
    }

    // GUMMEI SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_GUMMEI_CONFIG);

    if (setting != NULL) {
      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_MME_CODE);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (mme_config_p->gummei.nb_mmec != num) {
          if (mme_config_p->gummei.mmec != NULL) {
            free(mme_config_p->gummei.mmec);
          }

          mme_config_p->gummei.mmec = calloc(num, sizeof(*mme_config_p->gummei.mmec));
        }

        mme_config_p->gummei.nb_mmec = num;

        for (i = 0; i < num; i++) {
          mme_config_p->gummei.mmec[i] = config_setting_get_int_elem(subsetting, i);
        }
      }

      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_MME_GID);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (mme_config_p->gummei.nb_mme_gid != num) {
          if (mme_config_p->gummei.mme_gid != NULL) {
            free(mme_config_p->gummei.mme_gid);
          }

          mme_config_p->gummei.mme_gid = calloc(num, sizeof(*mme_config_p->gummei.mme_gid));
        }

        mme_config_p->gummei.nb_mme_gid = num;

        for (i = 0; i < num; i++) {
          mme_config_p->gummei.mme_gid[i] = config_setting_get_int_elem(subsetting, i);
        }
      }

      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_TAI_LIST);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (mme_config_p->gummei.nb_plmns != num) {
          if (mme_config_p->gummei.plmn_mcc != NULL)     free(mme_config_p->gummei.plmn_mcc);

          if (mme_config_p->gummei.plmn_mnc != NULL)     free(mme_config_p->gummei.plmn_mnc);

          if (mme_config_p->gummei.plmn_mnc_len != NULL) free(mme_config_p->gummei.plmn_mnc_len);

          if (mme_config_p->gummei.plmn_tac != NULL)     free(mme_config_p->gummei.plmn_tac);

          mme_config_p->gummei.plmn_mcc     = calloc(num, sizeof(*mme_config_p->gummei.plmn_mcc));
          mme_config_p->gummei.plmn_mnc     = calloc(num, sizeof(*mme_config_p->gummei.plmn_mnc));
          mme_config_p->gummei.plmn_mnc_len = calloc(num, sizeof(*mme_config_p->gummei.plmn_mnc_len));
          mme_config_p->gummei.plmn_tac     = calloc(num, sizeof(*mme_config_p->gummei.plmn_tac));
        }

        mme_config_p->gummei.nb_plmns = num;

        for (i = 0; i < num; i++) {
          sub2setting =  config_setting_get_elem(subsetting, i);

          if (sub2setting != NULL) {
            if(  (config_setting_lookup_string( sub2setting, MME_CONFIG_STRING_MCC, &mcc) )) {
              mme_config_p->gummei.plmn_mcc[i] = (uint16_t)atoi(mcc);
            }

            if(  (config_setting_lookup_string( sub2setting, MME_CONFIG_STRING_MNC, &mnc) )) {
              mme_config_p->gummei.plmn_mnc[i] = (uint16_t)atoi(mnc);
              mme_config_p->gummei.plmn_mnc_len[i] = strlen(mnc);
              AssertFatal((mme_config_p->gummei.plmn_mnc_len[i] == 2) || (mme_config_p->gummei.plmn_mnc_len[i] == 3),
                          "Bad MNC length %u, must be 2 or 3", mme_config_p->gummei.plmn_mnc_len[i]);
            }

            if(  (config_setting_lookup_string( sub2setting, MME_CONFIG_STRING_TAC, &tac) )) {
              mme_config_p->gummei.plmn_tac[i] = (uint16_t)atoi(tac);
              AssertFatal(mme_config_p->gummei.plmn_tac[i] != 0,
                          "TAC must not be 0");
            }
          }
        }
      }
    }

    // NETWORK INTERFACE SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_NETWORK_INTERFACES_CONFIG);

    if(setting != NULL) {
      if(  (
             config_setting_lookup_string( setting, MME_CONFIG_STRING_INTERFACE_NAME_FOR_S1_MME,
                                           (const char **)&mme_interface_name_for_S1_MME)
             && config_setting_lookup_string( setting, MME_CONFIG_STRING_IPV4_ADDRESS_FOR_S1_MME,
                                              (const char **)&mme_ip_address_for_S1_MME)
             && config_setting_lookup_string( setting, MME_CONFIG_STRING_INTERFACE_NAME_FOR_S11_MME,
                                              (const char **)&mme_interface_name_for_S11)
             && config_setting_lookup_string( setting, MME_CONFIG_STRING_IPV4_ADDRESS_FOR_S11_MME,
                                              (const char **)&mme_ip_address_for_S11)
           )
        ) {
        mme_config_p->ipv4.mme_interface_name_for_S1_MME = strdup(mme_interface_name_for_S1_MME);
        cidr = strdup(mme_ip_address_for_S1_MME);
        address = strtok(cidr, "/");
        IPV4_STR_ADDR_TO_INT_NWBO ( address, mme_config_p->ipv4.mme_ip_address_for_S1_MME, "BAD IP ADDRESS FORMAT FOR MME S1_MME !\n" )
        free(cidr);

        mme_config_p->ipv4.mme_interface_name_for_S11 = strdup(mme_interface_name_for_S11);
        cidr = strdup(mme_ip_address_for_S11);
        address = strtok(cidr, "/");
        IPV4_STR_ADDR_TO_INT_NWBO ( address, mme_config_p->ipv4.mme_ip_address_for_S11, "BAD IP ADDRESS FORMAT FOR MME S11 !\n" )
        free(cidr);

        if (strncasecmp("tun",mme_config_p->ipv4.mme_interface_name_for_S1_MME, strlen("tun")) == 0) {
          if (snprintf(system_cmd, 256,
                       "ip link set %s down ;openvpn --rmtun --dev %s",
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME,
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME
                      ) > 0) {
            mme_system(system_cmd, 1);
          } else {
            fprintf(stderr, "Del %s\n", mme_config_p->ipv4.mme_interface_name_for_S1_MME);
          }

          if (snprintf(system_cmd, 256,
                       "openvpn --mktun --dev %s;sync;ifconfig  %s up;sync",
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME,
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME) > 0) {
            mme_system(system_cmd, 1);
          } else {
            fprintf(stderr, "Create %s\n", mme_config_p->ipv4.mme_interface_name_for_S1_MME);
          }

          if (snprintf(system_cmd, 256,
                       "ip -4 addr add %s  dev %s",
                       mme_ip_address_for_S1_MME,
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME) > 0) {
            mme_system(system_cmd, 1);
          } else {
            fprintf(stderr, "Set IPv4 address on %s\n", mme_config_p->ipv4.mme_interface_name_for_S1_MME);
          }
        }

      }
    }

    // NAS SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_NAS_CONFIG);

    if (setting != NULL) {
      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_NAS_SUPPORTED_INTEGRITY_ALGORITHM_LIST);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (num <= 8) {
          for (i = 0; i < num; i++) {
            astring = config_setting_get_string_elem(subsetting, i);

            if (strcmp("EIA0", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA1", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA1;
            else if (strcmp("EIA2", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA2;
            else if (strcmp("EIA3", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA4", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA5", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA6", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA7", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
          }

          for (i = num; i < 8; i++) {
            mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
          }
        }
      }

      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_NAS_SUPPORTED_CIPHERING_ALGORITHM_LIST);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (num <= 8) {
          for (i = 0; i < num; i++) {
            astring = config_setting_get_string_elem(subsetting, i);

            if (strcmp("EEA0", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA1", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA1;
            else if (strcmp("EEA2", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA2;
            else if (strcmp("EEA3", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA4", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA5", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA6", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA7", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
          }

          for (i = num; i < 8; i++) {
            mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
          }
        }
      }

    }
  }

  setting = config_lookup(&cfg, SGW_CONFIG_STRING_SGW_CONFIG);

  if(setting != NULL) {
    subsetting = config_setting_get_member (setting, SGW_CONFIG_STRING_NETWORK_INTERFACES_CONFIG);

    if(subsetting != NULL) {
      if(  (
             config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_IPV4_ADDRESS_FOR_S1U_S12_S4_UP,
                                           (const char **)&sgw_ip_address_for_S1u_S12_S4_up)
             && config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_IPV4_ADDRESS_FOR_S11,
                                              (const char **)&sgw_ip_address_for_S11)
             && config_setting_lookup_int( subsetting, SGW_CONFIG_STRING_SGW_PORT_FOR_S1U_S12_S4_UP, &alongint)
           )
        ) {
        cidr = strdup(sgw_ip_address_for_S1u_S12_S4_up);
        address = strtok(cidr, "/");
        IPV4_STR_ADDR_TO_INT_NWBO ( address, mme_config_p->ipv4.sgw_ip_address_for_S1u_S12_S4_up, "BAD IP ADDRESS FORMAT FOR SGW S1u_S12_S4 !\n" )
        free(cidr);

        cidr = strdup(sgw_ip_address_for_S11);
        address = strtok(cidr, "/");
        IPV4_STR_ADDR_TO_INT_NWBO ( address, mme_config_p->ipv4.sgw_ip_address_for_S11, "BAD IP ADDRESS FORMAT FOR SGW S11 !\n" )
        free(cidr);

        mme_config_p->gtpv1u_config.port_number = (uint16_t) alongint;
      }
    }
  }

  return 0;
}
Ejemplo n.º 28
0
bool
process_attach()
{
    int rununder_mask;
    int should_inject;
    bool takeover = true;
#if VERBOSE
    int len;
    char exename[MAX_PATH];
#endif
    /* FIXME: append to event log to indicate we're in the address space */
    VERBOSE_MESSAGE("inside preinject dll\n");

    ntdll_init();
#ifndef PARAMS_IN_REGISTRY
    /* i#85/PR 212034: use config files */
    config_init();
#endif

#if VERBOSE
    len = GetModuleFileName(NULL, exename, MAX_PATH);
    ASSERT(len > 0);
#endif
#if 0 /* PR 314367: re-enable once it all works */
#    ifndef X64
    /* PR 253431: one method of injecting 64-bit DR into a WOW64 process is
     * via 32-bit AppInit drpreinject.
     * x64 configuration takes precedence over wow64.
     */
    if (is_wow64_process(NT_CURRENT_PROCESS)) {
        should_inject = systemwide_should_preinject_64(NULL, &rununder_mask);
        if (((INJECT_TRUE & should_inject) != 0) &&
            ((INJECT_EXPLICIT & should_inject) == 0) &&
            !is_safe_mode() &&
            parameters_present(true)) {
            VERBOSE_MESSAGE("<"PRODUCT_NAME" is taking over process %d (%s) as x64>\n",
                            GetCurrentProcessId(), exename);
            check_for_run_once(NULL, rununder_mask);
            /* we commit to x64 takeover based on there being a positive
             * rununder setting and an AUTOINJECT entry.  if the AUTOINJECT
             * turns out to be invalid, we'll try the 32-bit.
             */
            takeover = !load_dynamorio_lib(true);
        }
    }
#    endif
#endif /* 0 */
    if (takeover) {
        should_inject = systemwide_should_preinject(NULL, &rununder_mask);
        if (((INJECT_TRUE & should_inject) == 0) ||
            ((INJECT_EXPLICIT & should_inject) != 0) || is_safe_mode() ||
            !parameters_present(IF_NOT_X64(false))) {
            /* not taking over */
            VERBOSE_MESSAGE(PRODUCT_NAME " is NOT taking over process %d (%s)\n",
                            GetCurrentProcessId(), exename);
        } else {
            /* yes, load in dynamo to take over! */
            VERBOSE_MESSAGE("<" PRODUCT_NAME " is taking over process %d (%s)>\n",
                            GetCurrentProcessId(), exename);
            check_for_run_once(NULL, rununder_mask);
            load_dynamorio_lib(IF_NOT_X64(false));
        }
    }
    ntdll_exit();
    /* i#1522: self-unloading messes up the win8+ loader so we return false instead */
    if (running_on_win8_or_later())
        return false;
    else
        return true;
}
Ejemplo n.º 29
0
int main() {
	int ret = 0, i;
	struct ModuleInfo modinf;
	struct ModuleInfo config_modinf;
	struct KeyValueArray proto_cfg;
	//char Buffer[40];

	memset(&modinf, 0, sizeof(struct ModuleInfo));
	config_init(NULL, main_callback, &config_modinf);
	config_control(0, 3, NULL, (void *) &proto_cfg);
	ret = proto_init(&proto_cfg, main_callback, &modinf);

	if (ret <= -1) {
		printf("初始化失败,程序退出\n");
		return -1;
	}

	while (1) {
		//提示信息
		puts("\n选择要测试的功能:");
		puts("1: 登录到服务器");
		puts("2: 登出服务器");
		puts("3: 前端设备注册");
		puts("4: 前端设备帐号修改");
		puts("5: 前端设备帐号注销");
		puts("6: 消息推送请求");
		puts("7: 升级查询");
		puts("8: 文件传输");
		puts("0: 退出程序\n");

		scanf("%d", &i);

		//执行用户选择
		switch (i) {
		case 1:
			modinf.control(0, PROTO_CONTROL_LOGIN, NULL, NULL);
			break;

		case 2:
			modinf.control(0, PROTO_CONTROL_LOGINOUT, NULL, NULL);
			break;

		case 3: {
			register_data data;
			char info[20] = { "\0" };
			init_register_data(&data);
			modinf.control(0, PROTO_CONTROL_REGISTER, (register_data*) &data,
					info);
			PLOG("register info:%s\n", info);
		}
			break;

		case 4: {
			register_data data;
			char info[20] = { "\0" };
			init_accmod_data(&data);
			modinf.control(0, PROTO_CONTROL_MODIFY, (register_data*) &data,
					info);
			PLOG("register info:%s\n", info);
		}
			break;
		case 5:
			modinf.control(0, PROTO_CONTROL_LOGOUT, NULL, NULL);
			PLOG("Logout suceess\n");
			break;
		case 6:
			proto_deliver_reauest_start();
			break;
		case 7:
			proto_upgrade_request_start();
			break;
		case 8:
			proto_fileinfo_request_start();
			break;
		case 0:
			modinf.control(0, PROTO_CONTROL_LOGINOUT, NULL, NULL);
			modinf.close();
			exit(1);
			break;

		default:
			printf("ERROR!\n");
		}
	}

	//程序退出处理
	modinf.close();

	return 0;
}
Ejemplo n.º 30
0
/**
 * This function transmits the code to the user
 * @param pam_user The user login
 * @param pam_email The user email address
 * @param pam_code The generated code
 * @return A PAM return code
 */
int
pam_transmit_code(pam_handle_t *pam_handle, const char *pam_user,
const char *pam_email, const char *pam_code)
{
    /* The curl instance */
    CURL *curl;

    /* The curl return */
    CURLcode res = CURLE_OK;

    /* The recipents list */
    struct curl_slist *recipients = NULL;

    /* The email contect */
    struct pam_email_ctx email_ctx;
    
    /* The email id */
    uuid_t uuid;
    char email_id[37];

    /* The mail server configuration */
    const char *pam_mail_server_host;
    const char *pam_mail_server_user;
    const char *pam_mail_server_pass;

    /* The module configuration */
    config_t pam_config;
    FILE *pam_config_fd;

    /* The module dialogs */
    struct pam_message *pam_dialog_message[1];
    struct pam_message pam_dialog_message_ptr[1];
    struct pam_response *pam_dialog_response;

    /* Init PAM dialog variables */
    pam_dialog_message[0] = &pam_dialog_message_ptr[0];
    pam_dialog_response = NULL;

    /* Generate a random id for email */
    uuid_generate_random(uuid);

    /* Init configuration */
    config_init(&pam_config);

    /* Init configuration file stream */
    if((pam_config_fd = fopen("/etc/aurora/email.conf", "r")) == NULL)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Unable to open configuration";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Properly destroy the configuration */
        config_destroy(&pam_config);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Read and parse the configuration file */
    if(config_read(&pam_config, pam_config_fd) == CONFIG_FALSE)
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Unable to read configuration";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Properly destroy the configuration */
        config_destroy(&pam_config);

        /* Properly destroy the configuration file stream */
        fclose(pam_config_fd);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Get mail server settings */
    if(
        (config_lookup_string(&pam_config, "mail_server_host", 
            &pam_mail_server_host) == CONFIG_FALSE) ||
        (config_lookup_string(&pam_config, "mail_server_user", 
            &pam_mail_server_user) == CONFIG_FALSE) ||
        (config_lookup_string(&pam_config, "mail_server_pass", 
            &pam_mail_server_pass) == CONFIG_FALSE)
    )
    {
        /* An error occurs */
        pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
        pam_dialog_message_ptr[0].msg = 
            "[ERROR] Mail server configuration not found";
        pam_converse(pam_handle, 1, pam_dialog_message, &pam_dialog_response);

        /* Properly destroy the directory */
        config_destroy(&pam_config);

        /* Reject authentication */
        return PAM_AUTH_ERR;
    }

    /* Set email context */
    email_ctx.from = (char*) pam_mail_server_user;
    email_ctx.to = (char*) pam_email;
    email_ctx.user = (char*) pam_user;
    email_ctx.code = (char*) pam_code;
    uuid_unparse(uuid, email_id);
    email_ctx.uuid = email_id;
    email_ctx.current_line = 0;
    
    /* Init curl */
    curl = curl_easy_init();

    if(curl) {
	/* Set server url */
        curl_easy_setopt(curl, CURLOPT_URL, (char*) pam_mail_server_host);

	/* Set username */
        curl_easy_setopt(curl, CURLOPT_USERNAME, (char*) pam_mail_server_user);

	/* Set password */
        curl_easy_setopt(curl, CURLOPT_PASSWORD, (char*) pam_mail_server_pass);

	/* Enable SSL */
        curl_easy_setopt(curl, CURLOPT_USE_SSL, (long) CURLUSESSL_ALL);

	/* Set sender */
        curl_easy_setopt(curl, CURLOPT_MAIL_FROM, (void *) email_ctx.from);

	/* Set secipients */
        recipients = curl_slist_append(recipients, (void *) email_ctx.to);
        curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

	/* Register the payload function */
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, pam_payload_email_source);

	/* Set the email context */
        curl_easy_setopt(curl, CURLOPT_READDATA, &email_ctx);

	/* Enable upload */
        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

	/* Send email */
        res = curl_easy_perform(curl);

        if(res != CURLE_OK)
	{
            /* An error occurs */
            pam_dialog_message_ptr[0].msg_style = PAM_ERROR_MSG;
            pam_dialog_message_ptr[0].msg = 
                "[ERROR] Email transmission failure";
            pam_converse(pam_handle, 1, pam_dialog_message, 
                &pam_dialog_response);


            /* Free memory */
            config_destroy(&pam_config);
            curl_slist_free_all(recipients);
            curl_easy_cleanup(curl);

	    /* Reject authentication */
            return PAM_AUTH_ERR;
	}

	/* Free memory */
        config_destroy(&pam_config);
        curl_slist_free_all(recipients);
        curl_easy_cleanup(curl);
    }
  
    /* Transmission success */
    return PAM_SUCCESS;
}