Example #1
1
File: remunge.c Project: dun/munge
int
main (int argc, char *argv[])
{
    conf_t conf;

    /*  FIXME: Revamp signal handlers.
     */
    if (posignal (SIGHUP, SIG_IGN) == SIG_ERR) {
        log_err (EMUNGE_SNAFU, LOG_ERR, "Failed to ignore signal=%d", SIGHUP);
    }
    if (posignal (SIGPIPE, SIG_IGN) == SIG_ERR) {
        log_err (EMUNGE_SNAFU, LOG_ERR, "Failed to ignore signal=%d", SIGPIPE);
    }
    /*  Close stdin since it is not used.
     */
    if (close (STDIN_FILENO) < 0) {
        log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to close standard input");
    }
    /*  Set stdout to be line buffered.
     */
    if (setvbuf (stdout, NULL, _IOLBF, 0) < 0) {
        log_err (EMUNGE_SNAFU, LOG_ERR,
            "Failed to line-buffer standard output");
    }
    log_open_file (stderr, argv[0], LOG_INFO, LOG_OPT_PRIORITY);
    conf = create_conf ();
    parse_cmdline (conf, argc, argv);

    start_threads (conf);
    process_creds (conf);
    stop_threads (conf);

    destroy_conf (conf);
    log_close_file ();
    exit (EMUNGE_SUCCESS);
}
Example #2
0
int start_logging (ice_config_t *config)
{
    if (strcmp (config->error_log.name, "-") == 0)
        errorlog = log_open_file (stderr);
    if (strcmp(config->access_log.name, "-") == 0)
        config->access_log.logid = log_open_file (stderr);
    return restart_logging (config);
}
void log_reopen(void)
{
    struct logger *l = &logger;

    int ret = 0;
    int type = l->type;
    if (type & GENERIC_FILE)
    {
        close(l->fd);
        l->fd = log_open_file(l->name);
        if (l->fd < 0)
        {
            log_debug(LOG_DEBUG, "reopening log file '%s' failed, ignored: %s", l->name, strerror(errno));
        }
    }

    if (type & DATABASE)
    {
        ret = log_init_db(l->ip, l->port);
    }

    if (type & LEVELDB)
    {
        ret = log_init_leveldb(l->name);
    }
}
static void *async_write(void *argv)
{
    struct logger *l = &logger;

    pthread_detach(pthread_self());
    while (1)
    {
        mysleep_millisec(l->write_interval);
        if (l->nerror == 1)
        {
            close(l->fd);
            l->fd = -1;
            if (log_open_file(l->name) < 0)
            {
                printf("open log file failed\n");
                continue;
            }
        }

        int wpos = 0;
        int index = l->buffer_index;
        l->buffer_index = (l->buffer_index + 1) % 2;

        pthread_mutex_lock(&l->buffer_locks[index]);
        wpos = l->buffer_wpos[index];

        if (wpos > 0 && my_write(l->fd, l->buffer[index], wpos) < 0)
        {
            l->nerror = 1;
        }
        l->buffer_wpos[index] = 0;
        pthread_mutex_unlock(&l->buffer_locks[index]);
    }
}
Example #5
0
int log_open(const char *filename)
{
    int id;
    FILE *file;

    if (filename == NULL) return LOG_EINSANE;
    if (strcmp(filename, "") == 0) return LOG_EINSANE;
    
    file = fopen(filename, "a");

    id = log_open_file(file);

    if (id >= 0)
    {
        struct stat st;

        setvbuf (loglist [id] . logfile, NULL, IO_BUFFER_TYPE, 0);
        free (loglist [id] . filename);
        loglist [id] . filename = strdup (filename);
        if (stat (loglist [id] . filename, &st) == 0)
            loglist [id] . size = st.st_size;
        loglist [id] . entries = 0;
        loglist [id] . log_head = NULL;
        loglist [id] . log_tail = NULL;
    }

    return id;
}
//file init
int log_init_file(char *name)
{
    struct logger *l = &logger;

    l->max_buffer_size = 1024 * 1024 * 10;
    l->write_interval = 100;
    l->buffer_index = 0;
    l->name = strdup(name);
    if (name == NULL || !strlen(name))
    {
        l->fd = STDERR_FILENO;
        return 0;
    }
    else
    {
        l->fd = log_open_file(name);
        if (l->fd < 0)
        {
            l->fd = STDERR_FILENO;
            return 0;
        }
    }

    //init buffer
    int i = 0;
    while (i < 2)
    {
        pthread_mutex_init(&l->buffer_locks[i], NULL);
        char *buffer = (char *)calloc(1, l->max_buffer_size);
        if (NULL == buffer)
        {
            goto failed;
        }
        l->buffer[i] = buffer;
        l->buffer_wpos[i] = 0;
        i++;
    }

    //init buffer write thread
    if (pthread_create(&l->file_async_writer, NULL, async_write, NULL) < 0)
    {
        goto failed;
    }

    l->inited = 1;
    return 0;

failed:
    i = 0;
    while (i < 2)
    {
        if (l->buffer[i] != NULL)
        {
            free(l->buffer[i]);
        }
        i++;
    }
    return -1;
}
Example #7
0
static void
log_write (session *sess, char *text, time_t ts)
{
	char *temp;
	char *stamp;
	char *file;
	int len;

	if (sess->text_logging == SET_DEFAULT)
	{
		if (!prefs.hex_irc_logging)
			return;
	}
	else
	{
		if (sess->text_logging != SET_ON)
			return;
	}

	if (sess->logfd == -1)
		log_open (sess);

	/* change to a different log file? */
	file = log_create_pathname (sess->server->servername, sess->channel,
										 server_get_network (sess->server, FALSE));
	if (file)
	{
		if (g_access (file, F_OK) != 0)
		{
			close (sess->logfd);
			sess->logfd = log_open_file (sess->server->servername, sess->channel,
												  server_get_network (sess->server, FALSE));
		}
		g_free (file);
	}

	if (prefs.hex_stamp_log)
	{
		if (!ts) ts = time(0);
		len = get_stamp_str (prefs.hex_stamp_log_format, ts, &stamp);
		if (len)
		{
			write (sess->logfd, stamp, len);
			g_free (stamp);
		}
	}
	temp = strip_color (text, -1, STRIP_ALL);
	len = strlen (temp);
	write (sess->logfd, temp, len);
	/* lots of scripts/plugins print without a \n at the end */
	if (temp[len - 1] != '\n')
		write (sess->logfd, "\n", 1);	/* emulate what xtext would display */
	g_free (temp);
}
Example #8
0
void
logfile(const char *name)
{
	char	*path;

	log_close();
	if (debug_level > 0) {
		xasprintf(&path, "tmux-%s-%ld.log", name, (long) getpid());
		log_open_file(debug_level, path);
		xfree(path);
	}
}
Example #9
0
static int _start_logging(void)
{
    char fn_error[FILENAME_MAX];
    char fn_access[FILENAME_MAX];
    char pbuf[1024];

    ice_config_t *config = config_get_config_unlocked();

    if(strcmp(config->error_log, "-")) {
        snprintf(fn_error, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->error_log);
        errorlog = log_open(fn_error);
    } else {
        errorlog = log_open_file(stderr);
    }
    if(strcmp(config->access_log, "-")) {
        snprintf(fn_access, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->access_log);
        accesslog = log_open(fn_access);
    } else {
        accesslog = log_open_file(stderr);
    }
    
    log_set_level(errorlog, config->loglevel);
    log_set_level(accesslog, 4);

    if (errorlog < 0) {
        _fatal_error("FATAL: could not open error logging");
    }
    if (accesslog < 0) {
        memset(pbuf, '\000', sizeof(pbuf));
        snprintf(pbuf, sizeof(pbuf)-1, "FATAL: could not open access logging");
        _fatal_error(pbuf);
    }
    if (errorlog >= 0 && accesslog >= 0) return 1;
    
    return 0;
}
Example #10
0
void initialize_subsystems(void)
{
    log_initialize();
    errorlog = log_open_file (stderr);
    thread_initialize();
    sock_initialize();
    resolver_initialize();
    config_initialize();
    connection_initialize();
    global_initialize();
    refbuf_initialize();

    stats_initialize();
    xslt_initialize();
#ifdef HAVE_CURL_GLOBAL_INIT
    curl_global_init (CURL_GLOBAL_ALL);
#endif
}
Example #11
0
static void log_open(session *sess)
{
	static bool log_error = FALSE;

	log_close(sess);
	sess->logfd = log_open_file(sess->server->servername, sess->channel,
								server_get_network(sess->server, FALSE));

	if (!log_error && sess->logfd == -1)
	{
		char message[512];
		snprintf(message, sizeof(message),
					_("* Can't open log file(s) for writing. Check the\n" \
					"  permissions on %s/xchatlogs"), get_xdir_utf8());
		fe_message(message, FE_MSG_WAIT | FE_MSG_ERROR);

		log_error = TRUE;
	}
}
Example #12
0
static void
log_open (session *sess)
{
	static gboolean log_error = FALSE;

	log_close (sess);
	sess->logfd = log_open_file (sess->server->servername, sess->channel,
										  server_get_network (sess->server, FALSE));

	if (!log_error && sess->logfd == -1)
	{
		char *message;

		message = g_strdup_printf (_("* Can't open log file(s) for writing. Check the\npermissions on %s"),
			log_create_pathname (sess->server->servername, sess->channel, server_get_network (sess->server, FALSE)));

		fe_message (message, FE_MSG_WAIT | FE_MSG_ERROR);

		g_free (message);
		log_error = TRUE;
	}
}
Example #13
0
/**
 * @param {level} level Message log level
 * @param {format} format format of the message as used for printf
 * @param {...} Variables used in the message
 */
int	log_write(int level, const char *format, ...)
{
	FILE	*log_file;
	char	message[MAX_LINE_LEN];
	va_list	args;

	log_file = NULL;
	if (!log_check_level(level))
	{
		return 0;
	}

	if (xiniparser_getint("Logs:use_syslog", 0))
	{
		openlog(SYSLOG_IDENT, LOG_PID, LOG_DAEMON);
		va_start(args, format);
		vsyslog(level, format, args);
		va_end(args);
		closelog();
		return 0;
	}

	if ((log_file = log_open_file()) == NULL)
	{
		return -1;
	}

	va_start(args, format);
	if ((vsprintf(message, format, args)) > 0)
	{
		log_write_in(log_file, message);
	}

	va_end(args);
	xfclose(log_file);
	return 0;
}
Example #14
0
int log_set_file(char *file) {
    strncpy(log_file_name, file, 128);
    log2file = 1;
    log_open_file();
    return 0;
}
Example #15
0
File: main.c Project: asdr/PCA
int main ( int argc, char** argv ) {
  FILE* pipe;
  SHAREDBUFFER* shared_buffer;
  CONFIG* config;
  char main_process_lifetime[15];
  int producer_count = 0;
  char producer_lifetime[15];
  int consumer_count = 0;
  int child_exit_status = 0;
  int child_exit_pid;
  int child_pid;
  int i = 0;
  int logfd;
  char message[150];
  char dir[255];
  int available_process_count = 10000;

  strncpy(dir, argv[0], last_index_of(argv[0], '/'));
  chdir(dir);

  logfd = log_open_file( NULL );
  if ( !logfd )
    {
      printf("Unable to open log file.\n");
      return EXIT_FAILURE;
    }

  log_event( "--------------------------------" );
  log_event( "Main process started." );

  // first of all load configuration file
  config = load_config_file();

  if ( !config )
    {
      log_event( "Unable to access configuration." );
      return EXIT_FAILURE;
    }

  // read values from configuration
  producer_count = atoi(read_configuration(config, "producer_count", "5"));
  consumer_count = atoi(read_configuration(config, "consumer_count", "2"));
  strcpy(producer_lifetime, read_configuration(config, "producer_lifetime", "10"));
  strcpy(main_process_lifetime, read_configuration(config, "main_process_lifetime", "40"));

  destroy_config( config );

  log_event( "Fetching available process count of system." );
  pipe = popen(PROCESS_COUNT_SCRIPT, "r");
  if ( pipe )
    {
      fgets(message, 100, pipe);
      pclose(pipe);
      available_process_count = atoi(message);
    }

  if ( producer_count + consumer_count + 1 > available_process_count )
    {
      log_event( "Requested total process count is more than available process count of system." );
      goto SAFE_EXIT;
    }

  //initialize shared buffer
  shared_buffer = create_shared_buffer();

  if ( !shared_buffer )
    {
      log_event( "Unable to initialize shared buffer." );
      destroy_config( config );
      return EXIT_FAILURE;
    }

  // create and start producer processes
  // producer processes run for a specified lifetime ( in seconds )
  // which is read from configuration
  for ( i=0; i<producer_count; ++i)
    {
      child_pid = vfork();
      if ( child_pid == 0 ) // producer process
        {
          execl("producer", "producer", producer_lifetime, NULL);
          exit(0);
        }
    }

  // start consumer processes
  // consumer processes run until a SIGKILL signal
  // there is no specific entry in the requirements that
  // when a consumer process should end.
  for ( i=0; i<consumer_count; ++i)
    {
      child_pid = vfork();
      if ( child_pid == 0 ) // consumer process
        {
          execl("consumer", "consumer", NULL);
          exit(0);
        }
    }

  // start controller process
  // controller process checks elapsed time
  // once in every 5 seconds
  // if total execution time is above a specified time (in seconds)
  // signals all child processes except itself, to force exit
  child_pid = vfork();
  if ( child_pid == 0 ) //controller process
    {
      execl("controller", "controller", main_process_lifetime, NULL);
      exit(0);
    }

  // in order to catch all child processes exits
  // we need a common wait for all them
  // here exitting processes is cought with pid and exit status
  // wait childs to exit
  while( (child_exit_pid = wait(&child_exit_status)) > 0 )
    {
      sprintf( message, "Process [PID:%d] exitid with status: %d", child_exit_pid, child_exit_status );
      log_event( message );
    }

 SAFE_EXIT:
  log_event( "Main process is being closed." );

  // relase allocated data structures to OS
  destroy_shared_buffer( shared_buffer );

  log_close_file(  );

  return EXIT_SUCCESS;
}
Example #16
0
int main(int argc, char **argv)
{
    char logpath[FILENAME_MAX];
    int log;

    if (argc != 2) 
    {
        fprintf(stderr, PACKAGE_STRING "\n"
                "  (c) Copyright 2001-2004 The IceS Development Team <*****@*****.**>\n"
                "        Michael Smith <*****@*****.**>\n"
                "        Karl Heyes    <*****@*****.**>\n"
                "        and others\n"
                "\n"
                "Usage: \"ices config.xml\"\n");
        return 1;
    }

    config_initialize();

    if (config_read(argv[1]) <= 0) 
    {
        fprintf(stderr, "Failed to read config file \"%s\"\n", argv[1]);
        goto fail;
    }
	
    if (ices_config->background)
    {
#ifndef _WIN32		
        int ret = 0;
        /* Start up new session, to lose old session and process group */
        switch (fork())
        {
        case 0: break; /* child continues */
        case -1: perror ("fork"); ret = -1;
        default:
            exit (ret);
        }

        /* Disassociate process group and controlling terminal */ 
        setsid();

        /* Become a NON-session leader so that a */
        /* control terminal can't be reacquired */
        switch (fork())
        {
        case 0: break; /* child continues */
        case -1: perror ("fork"); ret = -1;
        default:
            exit (ret);
        }
#else
        FreeConsole();
#endif    		
    }

    log_initialize();
    thread_initialize();
    shout_init();
    encode_init();
#ifndef _WIN32	
    signals_setup();
#endif

    snprintf(logpath, FILENAME_MAX, "%s/%s", ices_config->logpath, 
            ices_config->logfile);
    if(ices_config->log_stderr)
        log = log_open_file(stderr);
    else
    {
        log = log_open(logpath);
        if (log < 0)
            fprintf (stderr, "unable to open log %s\n", logpath);
        log_set_trigger (log, ices_config->logsize);
    }
    /* Set the log level, if requested - defaults to 2 (WARN) otherwise */
    if (ices_config->loglevel)
        log_set_level(log, ices_config->loglevel);

    ices_config->log_id = log;

    LOG_INFO0(PACKAGE_STRING " started...");
    if (ices_config->pidfile != NULL)
    {
        FILE *f = fopen (ices_config->pidfile, "w");
        if (f)
        {
            fprintf (f, "%i", getpid());
            fclose (f);
        }
        else
        {
            LOG_WARN1("pidfile \"%s\" cannot be written to", ices_config->pidfile);
            xmlFree (ices_config->pidfile);
            ices_config->pidfile = NULL;
        }
    }

    /* Start the core streaming loop */
    input_loop();

    if (ices_config->pidfile)
        remove (ices_config->pidfile);

    LOG_INFO0("Shutdown complete");

    log_close(log);

 fail:
    encode_close();
    shout_shutdown();
    config_shutdown();
    thread_shutdown();
    log_shutdown();

    return 0;
}
Example #17
0
int
kubl_main (int argc, char **argv, int called_as_service, DWORD * errptr)
{
  int i, exit_after_options = 0, started_with_itself = 0;
  int read_from_rebuilt_database = 0;	/* For -R option. */
  int dump_for_recovery = 0;	/* For -D option. */
  char *empty = "";
  char *mode = empty;
  char *addr = KUBL_DEFAULT_PORT;
  char *service_name = (called_as_service ? argv[0] : NULL);
  char *s;

#ifdef PMN_LOG
  log_open_fp (stderr, LOG_DEBUG, L_MASK_ALL, L_STYLE_GROUP|L_STYLE_TIME);

  log_open_file ("wi.err", LOG_DEBUG, L_MASK_ALL, L_STYLE_GROUP | L_STYLE_TIME);
#endif

  /* If not overridden with any arguments specified with StartService,
     (i.e. either there are no args at all, or there is just -S)
     then use the permanent arguments (saved into wisvc_Main_G_argv)
     got from the original BinaryPath constructed in
     wisvc_Handle_I_and_J_options
   */
  if (called_as_service &&
      (((argc == 2) && !strncmp (argv[1], "-S", 2)) || (argc < 2))
    )
    {
      if (argc == 2)
	{
	  started_with_itself = 1;
	}
      argc = wisvc_Main_G_argc;
      argv = wisvc_Main_G_argv;
    }

  /* For debugging
     log_error (
     "kubl_main called with argc=%d, argv[0]=%s, argv[1]=%s, called_as_service=%d pid=%d",
     argc, argv[0], ((argc > 1) ? argv[1] : "NULL"),
     called_as_service, getpid());
   */

  /* If coming from KublServiceStart then argv vector seems to be NOT
     terminated by NULL (contrary to what MS documentation claims),
     so let's check that i stays smaller than argc. */
  for (i = 1; i < argc; i++)
    {
      s = argv[i];
      if ('-' == *s)
	{
	  if (mode == empty)
	    {
	      mode = s;
	    }
	  switch (*(s + 1))
	    {
#ifdef WIN32
	    case 'I':
	    case 'J':		/* Install to services. I =with autostart */
	      {
		int stat;
		if (mode == s)
		  {
		    mode = empty;
		  }
		if (called_as_service)
		  {
		    break;
		  }		/* Ignore in service. */
		stat = wisvc_Handle_I_and_J_options (argc, argv, s, i,
						     ('I' == *(s + 1)));
		kubl_main_exit (stat);
	      }
	    case 'S':		/* Start a previously installed service. */
	      {			/* Might be on the same command line as -J (or -I) */
		/* in which case Handle_I_and_J_options has the
		   responsibility to start it, directly from
		   CreateKublServices */
		int j, stat;
		char *service_name =
		(*(s + 2) ? (s + 2) : WISVC_DEFAULT_SERVICE_NAME);
		SC_HANDLE schandle;

		if (mode == s)
		  {
		    mode = empty;
		  }
		if (called_as_service)
		  {
		    started_with_itself = 1;
		    break;
		  }		/* Ignore in service. */

		/* We COULD copy the rest of argv vector one left, squashing -S
		   itself out of the existence, but we DON'T do it, as
		   -S option is an important signal to the started server
		   that it was started with wi.exe itself, not by clicking
		   the start button in services icon of Control Panel.
		   The difference is that with the latter starting way
		   the service is reported to be successfully started almost
		   immediately (before the initializations and log roll forward)
		   while the wi -S way of starting ensures that after the wi -S
		   command exits we know that the service is really started
		   all the way up and listening. This feature is needed in few
		   test scripts that turn Kubl server on and off, on and off. */
		/* for(j=i; j < argc; j++) { argv[j] = argv[j+1]; } argc--; */

		schandle = wisvc_OpenKublService (argv, service_name, "start",
					  (GENERIC_EXECUTE | GENERIC_READ));

		/* Returns 1 if started for sure, 0 if failed or unsure. */
		stat = wisvc_StartKublService (argc, argv, schandle,
					       service_name, argv[0], 0);

		/* Returns exit status 0 (= success) if certainly started, */
		kubl_main_exit (!stat);		/* otherwise 1 (= failure). */
		break;
	      }
	    case 'U':		/* Uninstall from Services. */
	      {
		char *service_name =
		(*(s + 2) ? (s + 2) : WISVC_DEFAULT_SERVICE_NAME);

		if (mode == s)
		  {
		    mode = empty;
		  }

		wisvc_UninstallKublService (argv, service_name);

		exit_after_options = 1;
		break;
	      }
#endif
	    case 'd':
#ifdef DBG_BLOB_PAGES_ACCOUNT
	      f_backup_dump = 1;
#endif
	      is_db_to_log = 1;
	      break;
	    case 'D':
	      {
		dump_for_recovery = (i + 1);
		goto out;
	      }
	    case 'R':
	      {
		read_from_rebuilt_database = 1;
		f_read_from_rebuilt_database = 1;
		break;
	      }
	    case 'j':
	      ob_just_report = 1;
	      /* fall to the next */
	    case 'r':
	      {
		if (i < argc - 1)
		  recover_file_prefix = argv[i+1];
		i++;
		break;
	      }
	    case 'B':
	      {
		if (i < argc - 1)
		  backup_dirs = argv[i+1];
		goto out;
	      }
	    case 'W':		/* Change working directory. */
	      {
		int stat;

		if (mode == s)
		  {
		    mode = empty;
		  }
		stat = wisvc_Handle_W_option (argc, argv, s, &i, called_as_service);
		if (stat)
		  {
		    kubl_main_exit (stat);
		  }
		break;
	      }
	    default:		/* E.g. everything else like -? -H or -h for help. */
	      {
		chil_usage (argv);
		kubl_main_exit (0);
	      }
	    }
	}
      else if (isdigit (*s))
	{
	  addr = s;
	}
      else
	{
	  dbg_printf (("%s: Don't know what to do with command line argument \"%s\". Read this:\n",
	      argv[0], s));
	  chil_usage (argv);
	  kubl_main_exit (1);
	}
    }				/* For loop over arguments. */
out:;

  if (exit_after_options)
    {
      kubl_main_exit (0);
    }

  /* If called as service and this was not started with wi -S
     (The -S option was not present in command line arguments)
     then this presumably is started with a start button from
     services manager of Control Panel. In that case, send
     SERVICE_RUNNING status immediately, so that it won't start waiting
     for memory initializations and log roll forwards, as its patience
     would not be enough for it, and it would instead falsely claim
     that:
     "Could not start the Kubl service on \\ARTAUD. Error 2186:
     The service is not responding to the control function."
   */

  if (called_as_service && !started_with_itself)
    {
      wisvc_send_service_running_status ();
    }

#ifndef WIN32
  signal (SIGPIPE, SIG_IGN);
#endif
  srv_global_init (mode);

  if (recover_file_prefix)
    {
      kubl_main_exit (0);
    }

  if (read_from_rebuilt_database)
    {
      kubl_main_exit (0);
    }


  if (is_db_to_log)
    {
      db_to_log ();
      kubl_main_exit (0);
    }

  /* If there was -D option, then dump_for_recovery is set to
     an index of argv one right to it, where might be one or more
     recovery keys. */
  if (dump_for_recovery)
    {
      for (i = dump_for_recovery; i < argc; i++)
	{
	  int k = atoi (argv[i]);
	  if (k)
	    db_recover_key (k, k);
	}
      db_crash_to_log (mode);
      kubl_main_exit (0);
    }

  tcpses_set_reuse_address (1);
  listening = PrpcListen (addr, SESCLASS_TCPIP);
  server_port = tcpses_get_port (listening->dks_session);
  if (!DKSESSTAT_ISSET (listening, SST_LISTENING))
    {
      kubl_main_exit (1);
    }
  if (service_name)		/* Started as a Windows NT service? */
    {
      log_info ("Server started at %s as service %s, pid=%d",
	  addr, service_name, getpid ());
    }
  else
    {
      log_info ("Server started at %s, pid=%d", addr, getpid ());
    }
  virtuoso_server_initialized = 1;


  if (!strchr (mode, 'b'))
    http_init_part_two ();
#ifdef REPLICATION
  if (read_from_rebuilt_database)	/* if booting from crash log, */
    {				/* go read the account levels from db */
      repl_read_db_levels ();
    }

  repl_sync_server (NULL, NULL);
#endif

  /* If called as Windows NT service, return now back to
     wisvc_KublServiceStart which in turn will call main_the_rest
     after it has set */
  if (called_as_service)
    {
      return (0);
    }				/* 0 = NO_ERROR */

#ifndef WIN32
  signal (SIGINT, sig_catcher);
  signal (SIGTERM, sig_catcher);
  signal (SIGHUP, sig_catcher);
  signal (SIGQUIT, sig_catcher);
#endif

  main_the_rest ();
  return 0;
}
Example #18
0
File: log.c Project: jkadlec/knot
int log_reconfigure(conf_t *conf, void *data)
{
	// Data not used
	UNUSED(data);

	// Use defaults if no 'log' section is configured.
	if (conf_id_count(conf, C_LOG) == 0) {
		log_close();
		log_init();
		return KNOT_EOK;
	}

	// Find maximum log facility id
	unsigned files = 0;
	conf_iter_t iter = conf_iter(conf, C_LOG);
	while (iter.code == KNOT_EOK) {
		conf_val_t id = conf_iter_id(conf, &iter);
		if (get_logtype(conf_str(&id)) == LOGT_FILE) {
			++files;
		}

		conf_iter_next(conf, &iter);
	}
	conf_iter_finish(conf, &iter);

	// Initialize logsystem
	struct log_sink *log = sink_setup(files);
	if (log == NULL) {
		return KNOT_ENOMEM;
	}

	// Setup logs
	iter = conf_iter(conf, C_LOG);
	while (iter.code == KNOT_EOK) {
		conf_val_t id = conf_iter_id(conf, &iter);
		const char *logname = conf_str(&id);

		// Get facility.
		int facility = get_logtype(logname);
		if (facility == LOGT_FILE) {
			facility = log_open_file(log, logname);
			if (facility < 0) {
				log_error("failed to open log, file '%s'",
				          logname);
				conf_iter_next(conf, &iter);
				continue;
			}
		}

		conf_val_t level_val;
		unsigned level;

		// Set SERVER logging.
		level_val = conf_id_get(conf, C_LOG, C_SERVER, &id);
		level = conf_opt(&level_val);
		sink_levels_add(log, facility, LOG_SERVER, level);

		// Set ZONE logging.
		level_val = conf_id_get(conf, C_LOG, C_ZONE, &id);
		level = conf_opt(&level_val);
		sink_levels_add(log, facility, LOG_ZONE, level);

		// Set ANY logging.
		level_val = conf_id_get(conf, C_LOG, C_ANY, &id);
		level = conf_opt(&level_val);
		sink_levels_add(log, facility, LOG_ANY, level);

		conf_iter_next(conf, &iter);
	}
	conf_iter_finish(conf, &iter);

	sink_publish(log);

	return KNOT_EOK;
}
Example #19
0
static int _start_logging(void)
{
    char fn_error[FILENAME_MAX];
    char fn_access[FILENAME_MAX];
    char fn_playlist[FILENAME_MAX];
    char buf[1024];
    int log_to_stderr;

    ice_config_t *config = config_get_config_unlocked();

    if(strcmp(config->error_log, "-")) {
        snprintf(fn_error, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->error_log);
        errorlog = log_open(fn_error);
        log_to_stderr = 0;
    } else {
        errorlog = log_open_file(stderr);
        log_to_stderr = 1;
    }

    if (errorlog < 0) {
        buf[sizeof(buf)-1] = 0;
        snprintf(buf, sizeof(buf)-1, 
                "FATAL: could not open error logging (%s): %s",
                log_to_stderr?"standard error":fn_error,
                strerror(errno));
        _fatal_error(buf);
    }
    log_set_level(errorlog, config->loglevel);

    if(strcmp(config->access_log, "-")) {
        snprintf(fn_access, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->access_log);
        accesslog = log_open(fn_access);
        log_to_stderr = 0;
    } else {
        accesslog = log_open_file(stderr);
        log_to_stderr = 1;
    }

    if (accesslog < 0) {
        buf[sizeof(buf)-1] = 0;
        snprintf(buf, sizeof(buf)-1, 
                "FATAL: could not open access logging (%s): %s",
                log_to_stderr?"standard error":fn_access,
                strerror(errno));
        _fatal_error(buf);
    }

    if(config->playlist_log) {
        snprintf(fn_playlist, FILENAME_MAX, "%s%s%s", config->log_dir, PATH_SEPARATOR, config->playlist_log);
        playlistlog = log_open(fn_playlist);
        if (playlistlog < 0) {
            buf[sizeof(buf)-1] = 0;
            snprintf(buf, sizeof(buf)-1, 
                "FATAL: could not open playlist logging (%s): %s",
                log_to_stderr?"standard error":fn_playlist,
                strerror(errno));
            _fatal_error(buf);
        }
        log_to_stderr = 0;
    } else {
        playlistlog = -1;
    }

    log_set_level(errorlog, config->loglevel);
    log_set_level(accesslog, 4);
    log_set_level(playlistlog, 4);

    if (errorlog >= 0 && accesslog >= 0) return 1;
    
    return 0;
}
Example #20
0
/** Daemon main run loop. */
int daemon_main (int argc, const char *argv[]) {
    const char *buf;
    size_t sz;

    if (strcmp (APP.logpath, "@syslog") == 0) {
        log_open_syslog ("opticon-agent", APP.loglevel);
    }
    else {
        log_open_file (APP.logpath, APP.loglevel);
    }
    
    probelist_start (&APP.probes);
    APP.resender = authresender_create (APP.transport);
    
    time_t tlast = time (NULL);
    time_t nextslow = tlast + 5;
    time_t nextsend = tlast + 10;
    time_t lastkeyrotate = 0;
    int slowround = 0;

    log_info ("Daemonized");
    while (1) {
        time_t tnow = tlast = time (NULL);
        
        slowround = 0;
        
        /* If a slow round is due at this time, use the excuse to send an
           authentication packet */
        if (nextslow <= tnow) {
            slowround = 1;
            uint32_t sid = APP.auth.sessionid;
            if (! sid) sid = gen_sessionid();
            log_debug ("Authenticating session <%08x>", sid);
            APP.auth.sessionid = sid;
            APP.auth.serial = 0;
            APP.auth.tenantid = APP.tenantid;
            APP.auth.hostid = APP.hostid;
            
            /* Only rotate the AES key every half hour */
            if (tnow - lastkeyrotate > 1800) {
                APP.auth.sessionkey = aeskey_create();
                lastkeyrotate = tnow;
            }
            APP.auth.tenantkey = APP.collectorkey;
            
            /* Dispatch */
            ioport *io_authpkt = ioport_wrap_authdata (&APP.auth,
                                                       gen_serial());
            
            sz = ioport_read_available (io_authpkt);
            buf = ioport_get_buffer (io_authpkt);
            outtransport_send (APP.transport, (void*) buf, sz);
            authresender_schedule (APP.resender, buf, sz);
            ioport_close (io_authpkt);
            
            /* Schedule next slow round */
            nextslow = nextslow + 300;
        }
        
        log_debug ("Poking probes");

        probe *p = APP.probes.first;
        time_t wakenext = tnow + 300;

        /* Go over the probes to figure out whether we should kick them */        
        while (p) {
            time_t firewhen = p->lastpulse + p->interval;
            if (firewhen <= tnow) {
                conditional_signal (&p->pulse);
                p->lastpulse = tnow;
            }
            
            /* Figure out whether the next event for this probe is sooner
               than the next wake-up time we determined so far */
            if (p->lastpulse + p->interval < wakenext) {
                wakenext = p->lastpulse + p->interval;
            }
            
            p = p->next;
        }
        
        int collected = 0;
        int ncollected = 0;
        host *h = host_alloc();
        var *vnagios = var_alloc();
        var *vchkwarn = var_get_array_forkey (vnagios, "chkwarn");
        var *vchkalert = var_get_array_forkey (vnagios, "chkalert");
        
        /* If we're in a slow round, we already know we're scheduled. Otherwise,
           see if the next scheduled moment for sending a (fast lane) packet
           has passed. */
        if (slowround || (tnow >= nextsend)) {
            h->uuid = APP.hostid;
            host_begin_update (h, time (NULL));

            if (! slowround) while (nextsend <= tnow) nextsend += 60;
            log_debug ("Collecting probes");
        
            /* Go over the probes again, picking up the ones relevant to the
               current round being performed */
            p = APP.probes.first;
            while (p) {
                pthread_mutex_lock (&p->vlock);
                volatile var *v = p->vcurrent;
                /* See if data for this probe has been collected since the last kick */
                if (v && (p->lastdispatch <= p->lastreply)) {
                    /* Filter probes for the current lane */
                    if ((slowround && p->interval>60) ||
                        ((!slowround) && p->interval<61)) {
                        log_debug ("Collecting <%s>", p->call);
                        
                        if (p->type == PROBE_NAGIOS) {
                            /* Check for alert/warning state and
                             * summarize before adding to host struct */
                             int pstatus = var_get_int_forkey ((var*)v, "status");
                             if (pstatus) {
                                 var *arr;
                                 switch (pstatus) {
                                    case 1:
                                        var_add_str (vchkwarn, p->id);
                                        break;
                                    
                                    default:
                                        var_add_str (vchkalert, p->id);
                                        break;
                                }
                                collected++;
                            }
                            ncollected++;
                        }
                        else {
                            host_import (h, (var *) v);
                            collected++;
                        }
                        p->lastdispatch = tnow;
                    }
                }
                else {
                    if (tnow - p->lastreply > (2*(p->interval))) {
                        log_warn ("Probe <%s> seems stuck after %i seconds",
                                  p->call, tnow - p->lastreply);
                    }
                }
                pthread_mutex_unlock (&p->vlock);
                p = p->next;
            }
        }
        
        /* Add the chk tree with nagios self-checks to the data */
        if (ncollected) host_import (h, vnagios);
         
        /* If any data was collected, encode it */
        if (collected) {
            log_debug ("Encoding probes");
        
            ioport *encoded = ioport_create_buffer (NULL, 4096);
            if (! encoded) {
                log_warn ("Error creating ioport");
                ioport_close (encoded);
                host_delete (h);
                continue;
            }
        
            if (! codec_encode_host (APP.codec, encoded, h)) {
                log_warn ("Error encoding host");
                ioport_close (encoded);
                host_delete (h);
                continue;
            }

            if (APP.dumppath) {
                FILE *pktf = fopen (APP.dumppath,"a");
                fprintf (pktf, "\n--- %s ---\n\n", slowround?"Slow":"Fast");
                ioport *dump = ioport_create_filewriter (pktf);
                log_debug ("dump %llx", dump);
                codec *jsonc = codec_create_json();
                log_debug ("jsonc %llx", jsonc);
                codec_encode_host (jsonc, dump, h);
                codec_release (jsonc);
                ioport_close (dump);
                fclose (pktf);
            }
        
            log_debug ("Encoded %i bytes", ioport_read_available (encoded));

            ioport *wrapped = ioport_wrap_meterdata (APP.auth.sessionid,
                                                     gen_serial(),
                                                     APP.auth.sessionkey,
                                                     encoded);
        
        
            if (! wrapped) {
                log_error ("Error wrapping");
                ioport_close (encoded);
                host_delete (h);
                continue;
            }
        
            sz = ioport_read_available (wrapped);
            buf = ioport_get_buffer (wrapped);
        
            /* Send it off into space */
            outtransport_send (APP.transport, (void*) buf, sz);
            log_info ("%s lane packet sent: %i bytes", 
                      slowround ? "Slow":"Fast", sz);

            ioport_close (wrapped);
            ioport_close (encoded);
        }
        
        /* Done with the host object */
        host_delete (h);

        /* Figure out what the next scheduled wake-up time is */
        tnow = time (NULL);
        if (nextsend < wakenext) wakenext = nextsend;
        if (nextslow < wakenext) wakenext = nextslow;
        if (wakenext > tnow) {
            log_debug ("Sleeping for %i seconds", (wakenext-tnow));
            sleep (wakenext-tnow);
        }
    }
    return 666;
}
Example #21
0
int main(int argc, char **argv)
{
    cardmanager_t* CTX;
    cardreader_t* READER;
    int opt;
    int opt_index = 0;
    int run_gui = 1;
    char* reader_name = NULL;
    char* exec_command = NULL;

#ifndef _WIN32
    SSL_load_error_strings();
#endif

    signal(SIGSEGV, save_what_can_be_saved);

    path_config_init();

    log_open_file();

    while ((opt = getopt_long(argc,argv,"r:e:vh",long_options,&opt_index))!=-1)
    {
        switch (opt)
        {
        case 'r':
            reader_name = g_strdup(optarg);
            break;
        case 'e':
            exec_command = optarg;
            break;
        case 'v':
            display_readers_and_version();
            run_gui = 0;
            break;
        default:
            display_help(argv[0]);
            run_gui = 0;
        }
    }

    if (run_gui)
    {
        /* if we want threads:
           gdk_threads_init();
           gdk_threads_enter();
         */

        gui_init(&argc,&argv);

        gui_create();

        log_printf(LOG_INFO,"Running %s",system_string_info());

        install_dot_file();

        luax_init();


        CTX = cardmanager_new();

        if (reader_name == NULL)
        {
            reader_name = gui_select_reader(cardmanager_count_readers(CTX),
                                            cardmanager_reader_name_list(CTX));
        }

        READER = cardreader_new(reader_name);

        cardmanager_free(CTX);

        if (READER)
        {
            luax_set_card_reader(READER);

            cardreader_set_callback(READER,gui_readerview_print,NULL);

            if (exec_command)
                g_idle_add(run_command_from_cli,exec_command);
            else
                update_cardpeek();
            /*else
              g_idle_add(run_update_checks,NULL);
             */
            gui_run();

            cardreader_free(READER);
        }
        else
        {
            fprintf(stderr,"Failed to open smart card reader '%s'.\n",reader_name);
            log_printf(LOG_ERROR,"Failed to open smart card reader '%s'.", reader_name);
        }

        luax_config_table_save();

        luax_release();

        /* if we want threads:
           gdk_threads_leave();
         */
    }

    if (reader_name) g_free(reader_name);

    log_close_file();

    path_config_release();

    ERR_free_strings();

    return 0;
}
Example #22
0
static int
daemonize_init (char *progname)
{
/*  Begins the daemonization of the process.
 *  Despite the fact that this routine backgrounds the process, control
 *    will not be returned to the shell until daemonize_fini() is called.
 *  Returns an 'fd' to pass to daemonize_fini() to complete the daemonization.
 */
    int         fds [2];
    pid_t       pid;
    int         n;
    signed char priority;
    char        ebuf [1024];

    /*  Clear file mode creation mask.
     */
    umask (0);

    /*  Create pipe for IPC so parent process will wait to terminate until
     *    signaled by grandchild process.  This allows messages written to
     *    stdout/stderr by the grandchild to be properly displayed before
     *    the parent process returns control to the shell.
     */
    if (pipe (fds) < 0) {
        log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to create daemon pipe");
    }
    /*  Set the fd used by log_err() to return status back to the parent.
     */
    log_set_err_pipe (fds[1]);

    /*  Automatically background the process and
     *    ensure child is not a process group leader.
     */
    if ((pid = fork ()) < 0) {
        log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to create child process");
    }
    else if (pid > 0) {
        log_set_err_pipe (-1);
        if (close (fds[1]) < 0) {
            log_errno (EMUNGE_SNAFU, LOG_ERR,
                "Failed to close write-pipe in parent process");
        }
        if ((n = read (fds[0], &priority, sizeof (priority))) < 0) {
            log_errno (EMUNGE_SNAFU, LOG_ERR,
                "Failed to read status from grandchild process");
        }
        if ((n > 0) && (priority >= 0)) {
            if ((n = read (fds[0], ebuf, sizeof (ebuf))) < 0) {
                log_errno (EMUNGE_SNAFU, LOG_ERR,
                    "Failed to read err msg from grandchild process");
            }
            if ((n > 0) && (ebuf[0] != '\0')) {
                log_open_file (stderr, progname, priority, LOG_OPT_PRIORITY);
                log_msg (priority, "%s", ebuf);
            }
            exit (EXIT_FAILURE);
        }
        exit (EXIT_SUCCESS);
    }
    if (close (fds[0]) < 0) {
        log_errno (EMUNGE_SNAFU, LOG_ERR,
            "Failed to close read-pipe in child process");
    }
    /*  Become a session leader and process group leader
     *    with no controlling tty.
     */
    if (setsid () < 0) {
        log_errno (EMUNGE_SNAFU, LOG_ERR,
            "Failed to disassociate controlling tty");
    }
    /*  Ignore SIGHUP to keep child from terminating when
     *    the session leader (ie, the parent) terminates.
     */
    if (posignal (SIGHUP, SIG_IGN) == SIG_ERR) {
        log_err (EMUNGE_SNAFU, LOG_ERR, "Failed to ignore signal=%d", SIGHUP);
    }
    /*  Abdicate session leader position in order to guarantee
     *    daemon cannot automatically re-acquire a controlling tty.
     */
    if ((pid = fork ()) < 0) {
        log_errno (EMUNGE_SNAFU, LOG_ERR,
            "Failed to create grandchild process");
    }
    else if (pid > 0) {
        exit (EXIT_SUCCESS);
    }
    return (fds[1]);
}
Example #23
0
static void
open_logfile (const char *logfile, int priority, int got_force)
{
    int          got_symlink;
    struct stat  st;
    int          n;
    char         logdir [PATH_MAX];
    char         ebuf [1024];
    mode_t       mask;
    FILE        *fp;

    /*  Check file permissions and whatnot.
     */
    got_symlink = (lstat (logfile, &st) == 0) ? S_ISLNK (st.st_mode) : 0;

    if (((n = stat (logfile, &st)) < 0) && (errno == ENOENT)) {
        if (!got_symlink) {
            ; /* A missing logfile is not considered an error. */
        }
        else if (!got_force) {
            log_err (EMUNGE_SNAFU, LOG_ERR,
                "Logfile is insecure: \"%s\" should be a regular file",
                logfile);
        }
        else {
            log_msg (LOG_WARNING,
                "Logfile is insecure: \"%s\" should not be a symlink",
                logfile);
        }
    }
    else {
        if (n < 0) {
            log_errno (EMUNGE_SNAFU, LOG_ERR,
                "Failed to check logfile \"%s\"", logfile);
        }
        if (!S_ISREG (st.st_mode) || got_symlink) {
            if (!got_force || !got_symlink)
                log_err (EMUNGE_SNAFU, LOG_ERR,
                    "Logfile is insecure: \"%s\" should be a regular file",
                    logfile);
            else
                log_msg (LOG_WARNING,
                    "Logfile is insecure: \"%s\" should not be a symlink",
                    logfile);
        }
        if (st.st_uid != geteuid ()) {
            if (!got_force)
                log_err (EMUNGE_SNAFU, LOG_ERR,
                    "Logfile is insecure: \"%s\" should be owned by UID %u",
                    logfile, (unsigned) geteuid ());
            else
                log_msg (LOG_WARNING,
                    "Logfile is insecure: \"%s\" should be owned by UID %u",
                    logfile, (unsigned) geteuid ());
        }
        if (st.st_mode & (S_IWGRP | S_IWOTH)) {
            if (!got_force)
                log_err (EMUNGE_SNAFU, LOG_ERR,
                    "Logfile is insecure: \"%s\" should not be writable "
                    "by group or world", logfile);
            else
                log_msg (LOG_WARNING,
                    "Logfile is insecure: \"%s\" should not be writable "
                    "by group or world", logfile);
        }
    }
    /*  Ensure logfile dir is secure against modification by others.
     */
    if (path_dirname (logfile, logdir, sizeof (logdir)) < 0) {
        log_err (EMUNGE_SNAFU, LOG_ERR,
            "Failed to determine dirname of logfile \"%s\"", logfile);
    }
    n = path_is_secure (logdir, ebuf, sizeof (ebuf));
    if (n < 0) {
        log_err (EMUNGE_SNAFU, LOG_ERR,
            "Failed to check logfile dir \"%s\": %s", logdir, ebuf);
    }
    else if ((n == 0) && (!got_force)) {
        log_err (EMUNGE_SNAFU, LOG_ERR, "Logfile is insecure: %s", ebuf);
    }
    else if (n == 0) {
        log_msg (LOG_WARNING, "Logfile is insecure: %s", ebuf);
    }
    /*  Protect logfile against unauthorized access by removing write-access
     *    from group and all access from other.
     */
    mask = umask (0);
    umask (mask | 027);
    fp = fopen (logfile, "a");
    umask (mask);

    if (!fp) {
        log_errno (EMUNGE_SNAFU, LOG_ERR,
            "Failed to open logfile \"%s\"", logfile);
    }
    log_open_file (fp, NULL, priority,
        LOG_OPT_JUSTIFY | LOG_OPT_PRIORITY | LOG_OPT_TIMESTAMP);
    return;
}
Example #24
0
int
main (int argc, char *argv[])
{
    int   fd = -1;
    char *log_identity = argv[0];
    int   log_priority = LOG_INFO;
    int   log_options = LOG_OPT_PRIORITY;

#ifndef NDEBUG
    log_priority = LOG_DEBUG;
    log_options |= LOG_OPT_TIMESTAMP;
#endif /* NDEBUG */
    log_open_file (stderr, log_identity, log_priority, log_options);

    disable_core_dumps ();
    conf = create_conf ();
    parse_cmdline (conf, argc, argv);
    auth_recv_init (conf->auth_server_dir, conf->auth_client_dir,
        conf->got_force);

    if (!conf->got_foreground) {
        fd = daemonize_init (argv[0]);
        if (conf->got_syslog) {
            log_open_file (NULL, NULL, 0, 0);
            log_open_syslog (log_identity, LOG_DAEMON);
        }
        else {
            open_logfile (conf->logfile_name, log_priority, conf->got_force);
        }
    }
    handle_signals ();
    lookup_ip_addr (conf);
    write_pidfile (conf->pidfile_name, conf->got_force);
    if (conf->got_mlockall) {
        lock_memory ();
    }
    crypto_init ();
    if (random_init (conf->seed_name) < 0) {
        if (conf->seed_name) {
            free (conf->seed_name);
            conf->seed_name = NULL;
        }
    }
    create_subkeys (conf);
    conf->gids = gids_create (conf->gids_update_secs, conf->got_group_stat);
    replay_init ();
    timer_init ();
    sock_create (conf);

    if (!conf->got_foreground) {
        daemonize_fini (fd);
    }
    log_msg (LOG_NOTICE, "Starting %s daemon (pid %d)",
        META_ALIAS, (int) getpid ());

    job_accept (conf);

    sock_destroy (conf);
    timer_fini ();
    replay_fini ();
    gids_destroy (conf->gids);
    random_fini (conf->seed_name);
    crypto_fini ();
    destroy_conf (conf);

    log_msg (LOG_NOTICE, "Stopping %s daemon (pid %d)",
        META_ALIAS, (int) getpid ());

    exit (EMUNGE_SUCCESS);
}