示例#1
0
文件: test.c 项目: zgbkny/ctoolx
/* ARGSUSED */
static void *process_signals(void *arg)
{
  int signo;

  for ( ; ; ) {
    /* Read the next signal from the signal pipe */
    if (st_read(sig_pipe[0], &signo, sizeof(int),
     ST_UTIME_NO_TIMEOUT) != sizeof(int))
      err_sys_quit(errfd, "ERROR: process %d (pid %d): signal processor:"
		   " st_read", my_index, my_pid);

    switch (signo) {
    case SIGHUP:
      err_report(errfd, "INFO: process %d (pid %d): caught SIGHUP,"
		 " reloading configuration", my_index, my_pid);
      if (interactive_mode) {
	load_configs();
	break;
      }
      /* Reopen log files - needed for log rotation */
      if (log_access) {
	logbuf_flush();
	logbuf_close();
	logbuf_open();
      }
      close(errfd);
      if ((errfd = open(ERRORS_FILE, O_CREAT | O_WRONLY | O_APPEND, 0644)) < 0)
	err_sys_quit(STDERR_FILENO, "ERROR: process %d (pid %d): signal"
		     " processor: open", my_index, my_pid);
      /* Reload configuration */
      load_configs();
      break;
    case SIGTERM:
      /*
       * Terminate ungracefully since it is generally not known how long
       * it will take to gracefully complete all client sessions.
       */
      err_report(errfd, "INFO: process %d (pid %d): caught SIGTERM,"
		 " terminating", my_index, my_pid);
      if (log_access)
	logbuf_flush();
      exit(0);
    case SIGUSR1:
      err_report(errfd, "INFO: process %d (pid %d): caught SIGUSR1",
		 my_index, my_pid);
      /* Print server info to stderr */
      dump_server_info();
      break;
    default:
      err_report(errfd, "INFO: process %d (pid %d): caught signal %d",
		 my_index, my_pid, signo);
    }
  }

  /* NOTREACHED */
  return NULL;
}
示例#2
0
文件: test.c 项目: zgbkny/ctoolx
/*
 * General server example: accept a client connection and do something.
 * This program just outputs a short HTML page, but can be easily adapted
 * to do other things.
 *
 * This server creates a constant number of processes ("virtual processors"
 * or VPs) and replaces them when they die. Each virtual processor manages
 * its own independent set of state threads (STs), the number of which varies
 * with load against the server. Each state thread listens to exactly one
 * listening socket. The initial process becomes the watchdog, waiting for
 * children (VPs) to die or for a signal requesting termination or restart.
 * Upon receiving a restart signal (SIGHUP), all VPs close and then reopen
 * log files and reload configuration. All currently active connections remain
 * active. It is assumed that new configuration affects only request
 * processing and not the general server parameters such as number of VPs,
 * thread limits, bind addresses, etc. Those are specified as command line
 * arguments, so the server has to be stopped and then started again in order
 * to change them.
 *
 * Each state thread loops processing connections from a single listening
 * socket. Only one ST runs on a VP at a time, and VPs do not share memory,
 * so no mutual exclusion locking is necessary on any data, and the entire
 * server is free to use all the static variables and non-reentrant library
 * functions it wants, greatly simplifying programming and debugging and
 * increasing performance (for example, it is safe to ++ and -- all global
 * counters or call inet_ntoa(3) without any mutexes). The current thread on
 * each VP maintains equilibrium on that VP, starting a new thread or
 * terminating itself if the number of spare threads exceeds the lower or
 * upper limit.
 *
 * All I/O operations on sockets must use the State Thread library's I/O
 * functions because only those functions prevent blocking of the entire VP
 * process and perform state thread scheduling.
 */
int main(int argc, char *argv[])
{
  /* Parse command-line options */
  parse_arguments(argc, argv);

  /* Allocate array of server pids */
  if ((vp_pids = calloc(vp_count, sizeof(pid_t))) == NULL)
    err_sys_quit(errfd, "ERROR: calloc failed");

  /* Start the daemon */
  if (!interactive_mode)
    start_daemon();

  /* Initialize the ST library */
  if (st_init() < 0)
    err_sys_quit(errfd, "ERROR: initialization failed: st_init");

  /* Set thread throttling parameters */
  set_thread_throttling();

  /* Create listening sockets */
  create_listeners();

  /* Change the user */
  if (username)
    change_user();

  /* Open log files */
  open_log_files();

  /* Start server processes (VPs) */
  start_processes();

  /* Turn time caching on */
  st_timecache_set(1);

  /* Install signal handlers */
  install_sighandlers();

  /* Load configuration from config files */
  load_configs();

  /* Start all threads */
  start_threads();

  /* Become a signal processing thread */
  process_signals(NULL);

  /* NOTREACHED */
  return 1;
}
示例#3
0
/**
 * Main function, starts the conftest daemon.
 */
int main(int argc, char *argv[])
{
	struct sigaction action;
	int status = 0;
	sigset_t set;
	int sig;
	char *suite_file = "suite.conf", *test_file = NULL;
	file_logger_t *logger;

	if (!library_init(NULL))
	{
		library_deinit();
		return SS_RC_LIBSTRONGSWAN_INTEGRITY;
	}
	if (!libhydra_init("conftest"))
	{
		libhydra_deinit();
		library_deinit();
		return SS_RC_INITIALIZATION_FAILED;
	}
	if (!libcharon_init("conftest"))
	{
		libcharon_deinit();
		libhydra_deinit();
		library_deinit();
		return SS_RC_INITIALIZATION_FAILED;
	}

	INIT(conftest,
		.creds = mem_cred_create(),
		.config = config_create(),
		.hooks = linked_list_create(),
		.loggers = linked_list_create(),
	);
	lib->credmgr->add_set(lib->credmgr, &conftest->creds->set);

	logger = file_logger_create("stdout");
	logger->set_options(logger, NULL, FALSE);
	logger->open(logger, FALSE, FALSE);
	logger->set_level(logger, DBG_ANY, LEVEL_CTRL);
	charon->bus->add_logger(charon->bus, &logger->logger);
	conftest->loggers->insert_last(conftest->loggers, logger);

	atexit(cleanup);

	while (TRUE)
	{
		struct option long_opts[] = {
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "suite", required_argument, NULL, 's' },
			{ "test", required_argument, NULL, 't' },
			{ 0,0,0,0 }
		};
		switch (getopt_long(argc, argv, "", long_opts, NULL))
		{
			case EOF:
				break;
			case 'h':
				usage(stdout);
				return 0;
			case 'v':
				printf("strongSwan %s conftest\n", VERSION);
				return 0;
			case 's':
				suite_file = optarg;
				continue;
			case 't':
				test_file = optarg;
				continue;
			default:
				usage(stderr);
				return 1;
		}
		break;
	}

	if (!load_configs(suite_file, test_file))
	{
		return 1;
	}
	load_loggers(logger);

	if (!lib->plugins->load(lib->plugins, NULL,
			conftest->test->get_str(conftest->test, "preload", "")))
	{
		return 1;
	}
	if (!charon->initialize(charon, PLUGINS))
	{
		return 1;
	}
	if (!load_certs(conftest->test, conftest->suite_dir))
	{
		return 1;
	}
	if (!load_keys(conftest->test, conftest->suite_dir))
	{
		return 1;
	}
	load_cdps(conftest->test);
	if (!load_hooks())
	{
		return 1;
	}
	charon->backends->add_backend(charon->backends, &conftest->config->backend);
	conftest->config->load(conftest->config, conftest->test);
	conftest->actions = actions_create();

	/* set up thread specific handlers */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaddset(&action.sa_mask, SIGHUP);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);
	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* start thread pool */
	charon->start(charon);

	/* handle SIGINT/SIGTERM in main thread */
	sigemptyset(&set);
	sigaddset(&set, SIGINT);
	sigaddset(&set, SIGHUP);
	sigaddset(&set, SIGTERM);
	sigprocmask(SIG_BLOCK, &set, NULL);

	while (sigwait(&set, &sig) == 0)
	{
		switch (sig)
		{
			case SIGINT:
			case SIGTERM:
				fprintf(stderr, "\nshutting down...\n");
				break;
			default:
				continue;
		}
		break;
	}
	return status;
}
示例#4
0
	void config_cache::get_config(const std::string& path, config& cfg)
	{
		load_configs(path, cfg);
	}
示例#5
0
/*=================================
 * init_lifelines_global -- Initialization options & misc. stuff
 *  This is called before first (or later) database opened
 *===============================*/
BOOLEAN
init_lifelines_global (STRING configfile, STRING * pmsg, void (*notify)(STRING db, BOOLEAN opening))
{
    STRING e;
    STRING dirvars[] = { "LLPROGRAMS", "LLREPORTS", "LLARCHIVES"
                         , "LLDATABASES",
                       };
    INT i;

    check_installation_path();

    /* request notification when options change */
    register_notify(&update_useropts);
    suppress_reload = TRUE;

    dbnotify_set(notify);

    if (!load_configs(configfile, pmsg)) {
        suppress_reload = FALSE;
        update_useropts(NULL);
        return FALSE;
    }

    pre_codesets_hook(); /* For MS-Windows user config of console codepages */

    /* now that codeset variables are set from config file, lets initialize codesets */
    /* although int_codeset can't be determined yet, we need GUI codeset for gettext */
    init_codesets();

    post_codesets_hook(); /* For Windows, link dynamically to gettext & iconv if available */


    /* until we have an internal codeset (which is until we open a database)
    we want output in display codeset */
    llgettext_init(PACKAGE, gui_codeset_out);

    /* read available translation tables */
    transl_load_all_tts();
    /* set up translations (for first time, will do it again after
    loading config table, and then again after loading database */
    transl_load_xlats();

    /* check if any directories not specified, and try environment
    variables, and default to "." */
    for (i=0; i<ARRSIZE(dirvars); ++i) {
        STRING str = getenv(dirvars[i]);
        if (!str)
            str = ".";
        setoptstr_fallback(dirvars[i], str);
    }
    /* also check environment variable for editor */
    {
        STRING str = getenv("LLEDITOR");
        if (!str)
            str = environ_determine_editor(PROGRAM_LIFELINES);
        setoptstr_fallback("LLEDITOR", str);
    }
    /* editor falls back to platform-specific default */
    e = getlloptstr("LLEDITOR", NULL);
    /* configure tempfile & edit command */
    editfile = environ_determine_tempfile();
    if (!editfile) {
        *pmsg = strsave("Error creating temp file");
        return FALSE;
    }
    editfile = strsave(editfile );
    editstr = (STRING) stdalloc(strlen(e) + strlen(editfile) + 2);
    sprintf(editstr, "%s %s", e, editfile);
    set_usersort(custom_sort);
    suppress_reload = FALSE;
    update_useropts(0);

    /* Finnish always uses custom character sets */
    if (opt_finnish ) {
        opt_mychar = TRUE;
        mych_set_table(ISO_Latin1);
    }


    return TRUE;
}
示例#6
0
int oversight_main(int argc,char **argv,int send_content_type_header)
{
    int result=0;
    int done=0;

    g_start_clock = time(NULL);
    assert(sizeof(long long) >= 8);

    init_view();
    adjust_path();

    char *q=getenv("QUERY_STRING");
    char *sp=getenv("SCRIPT_NAME");

    char *p;
    char *req;
    if (q && (p = delimited_substring(q,"&",REMOTE_VOD_PREFIX2,"=",1,0)) != NULL) {

        gaya_auto_load(p+strlen(REMOTE_VOD_PREFIX2)+1);
        done=1;

    } else if (q && strstr(q,YAMJ_PREFIX2)) {

        g_query=parse_query_string(q,g_query);
        //req = url_decode(q+strlen(YAMJ_PREFIX2));
        req = url_decode(query_val("yamj"));
        yamj_xml(req);
        FREE(req);
        done=1;
    } else if (sp && (req=strstr(sp,YAMJ_PREFIX)) != NULL) {
        // If oversight script is launched as /oversight/yamj/xxxxx.xml
        // then use xxxxxx.xml as a yamj xml request.
        // This is to allow for Apache ModAlias to serve static images whilst calling oversight for CGI
        // The rewrite rules should be 
        //    ScriptAliasMatch ^/oversight/yamj/(.*).xml  /share/Apps/oversight/oversight.cgi
        //    AliasMatch ^/oversight/yamj/banner_(.*jpg) /oversight/db/global/_b/ovs_$1
        //    AliasMatch ^/oversight/yamj/fanart_(.*jpg) /oversight/db/global/_fa/ovs_$1
        //    AliasMatch ^/oversight/yamj/poster_(.*jpg) /oversight/db/global/_J/ovs_$1
        //    AliasMatch ^/oversight/yamj/thumb_(.*).jpg  /oversight/db/global/_J/ovs_$1.thumb.jpg
        //    AliasMatch ^/oversight/yamj/boxset_(.*).jpg  /oversight/db/global/_J/ovs_$1.thumb.boxset.jpg`
        //
        req += strlen(YAMJ_PREFIX);
        yamj_xml(req);
        done=1;

    } else if (q == NULL || strchr(q,'=') == NULL ) {

        if (argc > 1 ) {

            if ( argv[1] && *argv[1] && argv[2] == NULL && util_starts_with(argv[1],YAMJ_PREFIX) ) {
                char *req = url_decode(argv[1]+strlen(YAMJ_PREFIX));
                yamj_xml(req);
                FREE(req);
                done=1;

            } else if ( argv[1] && *argv[1] && argv[2] == NULL && strchr(argv[1],'=') == NULL) {
                // Single argument passed.
                //
                char *path = url_decode(argv[1]);
                char *dot = strrchr(path,'.');
                if (dot < path) dot = strchr(path,'\0');
                int result = 0;

                fprintf(stderr,"path=[%s]",path);

                // should really use file command or magic number to determine file type

                if (dot && STRCMP(dot,".png") == 0 ) {

                    result = cat(CONTENT_TYPE"image/png",path);

                } else if (dot &&  STRCMP(dot,".jpg") == 0 ) {

                    result = cat(CONTENT_TYPE"image/jpeg",path);

                } else if (dot &&  STRCMP(dot,".gif") == 0) {

                    result = cat(CONTENT_TYPE"image/gif",path);

                } else if (dot &&  (STRCMP(dot,".swf") == 0 || STRCMP(dot,".phf" ) == 0) ) {

                    result = cat(CONTENT_TYPE"application/x-shockwave-flash",path);

                } else if (browsing_from_lan() ) {

                    if (is_dir(path)) {

                        // load_configs(); // load configs so we can use file_to_url() functions 
                        result = ls(path);
                    } else {
                        int exists = is_file(path);

                        char *all_headers = NULL;
                        char *content_headers = NULL;

                        if (exists) {
                            if (strstr(path,".tar.gz") || strcmp(dot,".tgz") == 0) {

                                ovs_asprintf(&content_headers,"%s%s\n%s%s",
                                        CONTENT_TYPE,"application/x-tar",CONTENT_ENC,"gzip");

                            } else if (strcmp(dot,".gz") == 0 ) {

                                ovs_asprintf(&content_headers,"%s%s\n%s%s",
                                        CONTENT_TYPE,"application/x-gzip",CONTENT_ENC,"identity");

                            } else if (strcmp(dot,".html") == 0 ) {

                                ovs_asprintf(&content_headers,"%s%s",
                                        CONTENT_TYPE,"text/html;charset=utf-8");

                            } else {
                                ovs_asprintf(&content_headers,"%s%s",
                                        CONTENT_TYPE,"text/plain;charset=utf-8");
                            }
                        } else {
                            // .gz.txt is a fake extension added by the ls command to view log.gz inline without browser downloading.
                            if (strstr(path,".gz.txt")) {
                                ovs_asprintf(&content_headers,"%s%s\n%s%s",
                                        CONTENT_TYPE,"text/plain;charset=utf-8", CONTENT_ENC,"gzip");
                                // remove .txt to get real zip file.
                                // .txt is needed so a certain browser displays inline. (might be other ways)
                                *dot = '\0';
                            } else {
                                // 404 error would be here
                            }
                        }
                        ovs_asprintf(&all_headers,"%s\n%s%ld",content_headers,CONTENT_LENGTH,file_size(path));
                        FREE(content_headers);
                        result = cat(all_headers,path);
                        FREE(all_headers);

                    }
                }
                FREE(path);
                fflush(stdout);
                done=1;
            }
        }
    }



    if (!done) {
        if (send_content_type_header) {
            printf("Content-Type: text/html; charset=utf-8\n\n");

            start_page("CGI");
        } else {
            start_page("WGET");
        }

        html_log_level_set(2);

        load_configs();
        //html_hashtable_dump(0,"settings",g_nmt_settings);

        long log_level;
        if (config_check_long(g_oversight_config,"ovs_log_level",&log_level)) {
            html_log_level_set(log_level);
        }

        html_comment("Appdir= [%s]",appDir());

        //array_unittest();
        //util_unittest();
        //config_unittest();

        g_query = string_string_hashtable("g_query2",16);

        html_comment("default query ... ");
        add_default_html_parameters(g_query);
        html_hashtable_dump(0,"prequery",g_query);

        html_comment("read query ... ");
        g_query=parse_query_string(getenv("QUERY_STRING"),g_query);
        html_hashtable_dump(0,"query",g_query);

        html_comment("read post ... ");

        struct hashtable *post=read_post_data(getenv("TEMP_FILE"));
        html_hashtable_dump(0,"post",g_query);
        
        html_comment("merge query and post data");
        merge_hashtables(g_query,post,1); // post is destroyed

        html_hashtable_dump(0,"query final",g_query);


#if 0
        html_comment("utf8len expect 2 = %d",utf8len("a"));
        html_comment("utf8len expect 2 = %d",utf8len("à€€a"));
        html_comment("utf8len expect 2 = %d",utf8len("ü€€€€€a"));
        html_comment("utf8cmp_char 0 = %d",utf8cmp_char("ü€€€€€a","ü€€€€€b"));
        html_comment("utf8cmp_char !0 = %d",utf8cmp_char("ü€€€€€a","ü€€€€€a"));
        html_comment("utf8cmp_char 0 = %d",utf8cmp_char("a","a"));
        html_comment("utf8cmp_char !0 = %d",utf8cmp_char("a","b"));
        html_comment("utf8cmp_char !0 = %d",utf8cmp_char("ü€€€€€a","üa"));
        html_comment("utf8cmp_char !0 = %d",utf8cmp_char("a","ü€€€€€a"));
        Abet *a = abet_create("abcdefghijklmnopqrstuvwxyz");
        html_comment("inc a %d",abet_letter_inc_or_add(a,"a",1));
        html_comment("inc a %d",abet_letter_inc_or_add(a,"a",1));
        html_comment("inc z %d",abet_letter_inc_or_add(a,"z",1));
        html_comment("inc 4 %d",abet_letter_inc_or_add(a,"4",1));
        html_comment("inc 5 %d",abet_letter_inc_or_add(a,"5",1));
        html_comment("inc 5 %d",abet_letter_inc_or_add(a,"5",1));
        html_comment("inc 6* %d",abet_letter_inc_or_add(a,"6",0));
        html_comment("inc 7* %d",abet_letter_inc_or_add(a,"7",0));
        html_comment("inc a %d",abet_letter_inc_or_add(a,"a",1));
        abet_free(a);
#endif


        config_read_dimensions(1);

        HTML_LOG(0,"Begin Actions");
        do_actions();
       
        ViewMode *view;

        DbSortedRows *sortedRows = NULL;


        while(1) {
            view=get_view_mode(1);  
            HTML_LOG(0,"view mode = [%s]",view->name);

            // If movie view but all ids have been removed , then move up
            if (view == VIEW_MOVIE && !*query_val(QUERY_PARAM_IDLIST)) {
                query_pop();
                view=get_view_mode(1);  
            }

            sortedRows = get_sorted_rows_from_params();
            dump_all_rows("sorted",sortedRows->num_rows,sortedRows->rows);

            // If it's not a tv/movie detail or boxset view then break
            if (view == VIEW_MENU ||  view == VIEW_ADMIN ) {
                break;
            }

            // Found some data - as we are on a smaller view - filter it
            if (sortedRows->num_rows && sortedRows->num_rows < 50 ) {
                int new_num = sortedRows->num_rows;
                int max_new = sortedRows->num_rows;
                DbItem **new_list = filter_page_items(0,sortedRows->num_rows,sortedRows->rows,max_new,&new_num);
                FREE(sortedRows->rows);
                sortedRows->rows = new_list;
                sortedRows->num_rows=new_num;
            }
            if (sortedRows->num_rows) break;

            // No data found in this view - try to return to the previous view.
            query_pop();
            // Adjust config - 
            // TODO Change the config structure to reload more efficiently.
            //reload_configs();

            config_read_dimensions(1);

            // Now refetch all data again with new parameters.
            sorted_rows_free_all(sortedRows);
            HTML_LOG(0,"reparsing database");
        }

        // Remove and store the last navigation cell. eg if user clicked on cell 12 this is passed in 
        // the URL as @i=12. The url that returns to this page then has i=12. If we have returned to this
        // page we must remove i=12 from the query so that it is not passed to the new urls created for this 
        // page.
        set_selected_item();

        char *skin_name=get_skin_name();


        if (strchr(skin_name,'/') || *skin_name == '.' || !*skin_name ) {

            html_error("Invalid skin name[%s]",skin_name);

        } else {

            playlist_open();
            //exp_test();

            if (view->view_class == VIEW_CLASS_ADMIN) {

                setPermissions();
                display_admin(sortedRows);

            } else {

                char *template = query_val(QUERY_PARAM_TEMPLATE_NAME);
                if (EMPTY_STR(template)) {