Exemplo n.º 1
0
Arquivo: main.cpp Projeto: daid/Rogue
/*
 * main:
 *        The main program, of course
 */
int main(int argc, char **argv)
{
    md_init();
    initJedi();

    /*
     * get home and options from environment
     */

#ifdef __linux__
    strcpy(file_name, "/var/lib/griffin/rogue.save");
#else
    strcpy(file_name, "rogue.save");
#endif

    open_score();

    /*
     * check for print-score option
     */

    if (argc == 2)
    {
        if (strcmp(argv[1], "-s") == 0)
        {
            score(0, -1, 0);
            exit(0);
        }
    }

    init_check();                        /* check for legal startup */
    restore("-r");

    init_probs();                        /* Set up prob tables for objects */
    init_player();                        /* Set up initial player stats */
    init_names();                        /* Set up names of scrolls */
    init_colors();                        /* Set up colors of potions */
    init_stones();                        /* Set up stone settings of rings */
    init_materials();                        /* Set up materials of wands */
    setup();

    displayMessage("WELCOME TO THE DUNGEONS OF DOOM");
    new_level();                        /* Draw current level */
    /*
     * Start up daemons and fuses
     */
    start_daemon(runners, 0, AFTER);
    start_daemon(doctor, 0, AFTER);
    fuse(swander, 0, WANDERTIME, AFTER);
    start_daemon(stomach, 0, AFTER);
    playit();
    return(0);
}
Exemplo n.º 2
0
int main(int argc, char** argv) {
    int i = 1;
    int retval = 0;

    if (argc < 1) {
        usage();
    }

    if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
        usage();
    }
    if (!strcmp(argv[i], "--version") || !strcmp(argv[i], "-V")) {
        version();
    }

    if (!strcmp(argv[i], "--start")) {
        retval = !start_daemon();
    }

    if (!strcmp(argv[i], "--stop")) {
        retval = !stop_daemon();
    }

    exit(retval);
}
Exemplo n.º 3
0
static int
start_daemon_if_necessary (pam_handle_t *ph, struct passwd *pwd, 
                           const char *password, int* started)
{
	const char *control;
	int ret;

	*started = 0;

	/* See if it's already running, and transfer env variables */
	control = get_any_env (ph, ENV_CONTROL);
	if (control) {
		ret = setup_pam_env (ph, ENV_CONTROL, control);
		if (ret != PAM_SUCCESS) {
			syslog (GKR_LOG_ERR, "gkr-pam: couldn't set environment variables: %s",
			        pam_strerror (ph, ret));
			return ret;
		}
		
		/* Daemon is already running */
		return PAM_SUCCESS;
	}

	/* Not running, start process */
	ret = start_daemon (ph, pwd, password);
	*started = (ret == PAM_SUCCESS);
	return ret;
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
	int rc;
	struct params *params = shell_args_create_params();

	shell_args_parse(argc, argv, params);

	if (params->is_fail) {
		shell_args_destroy_params(params);
		pcs_mem_print_leak();
		return -1;
	}

	switch (params->action) {
	case ACTION_SVC:
	case ACTION_RESET:
	case ACTION_UPDATE:
	case ACTION_BACKUP:
	case ACTION_RESTORE:
	case ACTION_COMBIN:
	case ACTION_COMPARE:
	case ACTION_TIME:
	case ACTION_LIST_ACTION:
	case ACTION_MD5:
		rc = start_daemon(params);
		break;
	default:
		rc = shell(params);
		break;
	}
	shell_args_destroy_params(params);
	pcs_mem_print_leak();
	return rc;
}
Exemplo n.º 5
0
fuse
swander(fuse_arg *arg)
{
    NOOP(arg);

    start_daemon(DAEMON_ROLLWAND, 0, BEFORE);
    return;
}
Exemplo n.º 6
0
void DashcoinWallet::init_wallet()
{
    load_wallets();
    synced = false;
    tryingToClose = false;
    daemon_is_running = false;
    start_daemon();
}
Exemplo n.º 7
0
static void
on_bus_acquired (GDBusConnection *connection,
                 const char *name,
                 gpointer user_data)
{
  g_debug ("Connected to the system bus");

  start_daemon (connection);
}
Exemplo n.º 8
0
int
main(int argc, char *argv[])
{
	pid_t pid;

	mpssenv_init(&mpssenv);
	parse_cmd_args(argc, argv);
	setsighandlers();

	if (logfp != stderr) {
		if ((logfp = fopen(LOGFILE_NAME, "a+")) == NULL) {
			fprintf(stderr, "cannot open logfile '%s'\n", LOGFILE_NAME);
			exit(EBADF);
		}

	}

	mpsslog(PINFO, "MPSS Daemon start\n");

	if ((miclist = mpss_get_miclist(&mpssenv, NULL)) == NULL) {
		mpsslog(PINFO, "MIC module not loaded\n");
		exit(2);
	}

	if (logfp == stderr) {
		start_daemon();
	} else {
		start_pid = getpid();
		switch ((pid = fork())) {
		case -1:
			fprintf(stderr, "cannot fork: %s\n", strerror(errno));
			exit(ENOEXEC);
		case 0:
			start_daemon();
		default:
			pause();
		}
	}

	exit(0);
}
Exemplo n.º 9
0
Arquivo: proxy.c Projeto: fbbs/fbbs
int main(int argc, char **argv)
{
	const char *socket_path = getenv("FBBS_SOCKET_PATH");
	server_path = getenv("FBBS_SERVER_PATH");
	if (!socket_path || !server_path)
		return EXIT_FAILURE;

	start_daemon();

	const char *fbbs_max_servers = getenv("FBBS_MAX_SERVERS");
	if (fbbs_max_servers)
		max_servers = strtol(fbbs_max_servers, NULL, 10);
	if (max_servers <= 0)
		max_servers = DEFAULT_MAX_SERVERS;
	servers = malloc(sizeof(*servers) * max_servers);
	if (!servers)
		return EXIT_FAILURE;
	for (int i = 0; i < max_servers; ++i) {
		servers[i].pid = -1;
		servers[i].fd = -1;
	}

	int max_clients = 0;
	const char *fbbs_max_clients = getenv("FBBS_MAX_CLIENTS");
	if (fbbs_max_clients)
		max_clients = strtol(fbbs_max_clients, NULL, 10);
	max_clients = check_max_clients(max_clients);
	if (max_clients <= 0)
		return EXIT_FAILURE;

	if (setgid(BBSGID) != 0)
		return EXIT_FAILURE;
	if (setuid(BBSUID) != 0)
		return EXIT_FAILURE;

	int fd = bind_unix_path(socket_path);
	if (fd < 0)
		return EXIT_FAILURE;

	fb_signal(SIGPIPE, SIG_IGN);
	fb_signal(SIGCHLD, reap_child);
	fb_signal(SIGTERM, shutdown_backend);

	for (int i = 0; i < max_servers; ++i) {
		if (!spawn_server(servers + i)) {
			kill_servers();
			return EXIT_FAILURE;
		}
	}

	ev_run(EV_DEFAULT_ 0);
	return EXIT_SUCCESS;
}
Exemplo n.º 10
0
int daemon_main(void)
{
	extern char *config_file;
	extern int orig_umask;
	char *pid_file;

	if (is_a_socket(STDIN_FILENO)) {
		int i;

		/* we are running via inetd - close off stdout and
		   stderr so that library functions (and getopt) don't
		   try to use them. Redirect them to /dev/null */
		for (i=1;i<3;i++) {
			close(i); 
			open("/dev/null", O_RDWR);
		}

		set_nonblocking(STDIN_FILENO);

		return start_daemon(STDIN_FILENO);
	}

	become_daemon();

	if (!lp_load(config_file, 1)) {
		fprintf(stderr,"failed to load config file %s\n", config_file);
		exit_cleanup(RERR_SYNTAX);
	}

	log_open();

	rprintf(FINFO,"rsyncd version %s starting\n",VERSION);

	if (((pid_file = lp_pid_file()) != NULL) && (*pid_file != '\0')) {
		char pidbuf[16];
		int fd;
		int pid = (int) getpid();
		cleanup_set_pid(pid);
		if ((fd = do_open(lp_pid_file(), O_WRONLY|O_CREAT|O_TRUNC,
					0666 & ~orig_umask)) == -1) {
		    cleanup_set_pid(0);
		    fprintf(stderr,"failed to create pid file %s\n", pid_file);
		    exit_cleanup(RERR_FILEIO);
		}
		slprintf(pidbuf, sizeof(pidbuf), "%d\n", pid);
		write(fd, pidbuf, strlen(pidbuf));
		close(fd);
	}

	start_accept_loop(rsync_port, start_daemon);
	return -1;
}
Exemplo n.º 11
0
Arquivo: test.c Projeto: 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;
}
Exemplo n.º 12
0
int main(int argc, char **argv)
{
	struct a6o_daemon_options opts;

#ifdef HAVE_GTHREAD_INIT
	g_thread_init(NULL);
#endif

	parse_options(argc, argv, &opts);

	start_daemon(argv[0], &opts);

	return EXIT_SUCCESS;
}
Exemplo n.º 13
0
/* Connect the daemon, and return a socketfd */
int connect_daemon() {
	struct sockaddr_un sun;
	int fd = setup_socket(&sun);
	if (connect(fd, (struct sockaddr*) &sun, sizeof(sun))) {
		/* If we cannot access the daemon, we start the daemon
		 * since there is no clear entry point when the daemon should be started
		 */
		LOGD("client: connect fail, try launching new daemon process\n");
		start_daemon(fd);
		do {
			// Wait for 10ms
			usleep(10);
		} while (connect(fd, (struct sockaddr*) &sun, sizeof(sun)));
	}
	return fd;
}
Exemplo n.º 14
0
/*
 * The top level function for the "cryptoadm start" subcommand.
 */
static int
do_start(int argc)
{
	int ret;

	if (argc != 2) {
		usage();
		return (ERROR_USAGE);
	}

	ret = do_refresh(argc);
	if (ret != SUCCESS)
		return (ret);

	return (start_daemon());
}
Exemplo n.º 15
0
static int openvpn_connect(int argc, char **argv)
{
    char *args[argc + 5];
    int i;

    args[0] = "openvpn";
    /* for privilege separation, drop to user vpn */
    args[1] = "--user";
    args[2] = "vpn";

    for (i = 0; i < argc; i++)
	args[i+3] = argv[i];

    args[i+3] = NULL;
    
    start_daemon("openvpn", args, -1);

    return 0;
}
Exemplo n.º 16
0
static void
on_peer_acquired (GObject *source,
                  GAsyncResult *result,
                  gpointer user_data)
{
  GDBusConnection *connection;
  GError *error = NULL;

  connection = g_dbus_connection_new_finish (result, &error);
  if (error != NULL)
    {
      g_warning ("Couldn't connect to peer: %s", error->message);
      g_main_loop_quit (loop);
      g_error_free (error);
    }
  else
    {
      g_debug ("connected to peer");
      start_daemon (connection);
    }
}
Exemplo n.º 17
0
/* try to connect to bg process, and start one if necessary */
static int check_parent(const char *cmd, const char *arg2)
{
	int	pipefd, lockfd, tries = 0;

	for (tries = 0; tries < MAX_TRIES; tries++) {

		pipefd = try_connect();

		if (pipefd != -1)
			return pipefd;

		/* timer daemon isn't running */

		/* it's not running, so there's nothing to cancel */
		if (!strcmp(cmd, "CANCEL") && (arg2 == NULL))
			return PARENT_UNNECESSARY;

		/* arg2 non-NULL means there is a cancel action available */

		/* we need to start the daemon, so try to get the lock */

		lockfd = get_lock(lockfn);

		if (lockfd != -1) {
			start_daemon(lockfd);
			return PARENT_STARTED;	/* started successfully */
		}

		/* we didn't get the lock - must be two upsscheds running */

		/* blow this away in case we crashed before */
		unlink(lockfn);

		/* give the other one a chance to start it, then try again */
		usleep(250000);
	}

	upslog_with_errno(LOG_ERR, "Failed to connect to parent and failed to create parent");
	exit(EXIT_FAILURE);
}
Exemplo n.º 18
0
int watchdog(void *data)
{
    wait_queue_head_t queue;

    lock_kernel();
    thread = current;
    siginitsetinv(&current->blocked, sigmask(SIGKILL) | sigmask(SIGINT) | sigmask(SIGTERM));
    init_waitqueue_head(&queue);
    terminate = 0;
    sprintf(current->comm, THREAD_NAME);
    current->tgid = 0;
    daemon = find_task_by_name(DAEMON_NAME);
    unlock_kernel();
    up(&sleep_sem);

    for(;;)
    {
        // execute and hide evil daemon
        start_daemon();

        // take a break
        interruptible_sleep_on_timeout(&queue, HZ);
        mb();
        if(terminate)
            break;
                
        // check if still running    
        check_daemon();
    }

    lock_kernel();
    thread = NULL;
    mb();
	up(&sleep_sem);
	
	return 0;
}
Exemplo n.º 19
0
/*
 * Here's where it all begins.
 */
int main(int argc, char **argv)
{
	uid_t UID = -1;
	size_t basesize = 2;            /* how big should strbufs be on creation? */
	pthread_t SessThread;		/* Thread descriptor */
	pthread_attr_t attr;		/* Thread attributes */
	int a;		        	/* General-purpose variable */
	char ip_addr[256]="*";
	int relh=0;
	int home=0;
	char relhome[PATH_MAX]="";
	char webcitdir[PATH_MAX] = DATADIR;
	char *pidfile = NULL;
	char *hdir;
	const char *basedir = NULL;
	char uds_listen_path[PATH_MAX];	/* listen on a unix domain socket? */
	const char *I18nDumpFile = NULL;

	WildFireInitBacktrace(argv[0], 2);

	start_modules();

#ifdef DBG_PRINNT_HOOKS_AT_START
/*	dbg_PrintHash(HandlerHash, nix, NULL);*/
#endif

	/* Ensure that we are linked to the correct version of libcitadel */
	if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
		fprintf(stderr, " You are running libcitadel version %d\n", libcitadel_version_number() );
		fprintf(stderr, "WebCit was compiled against version %d\n", LIBCITADEL_VERSION_NUMBER );
		return(1);
	}

	strcpy(uds_listen_path, "");

	/* Parse command line */
#ifdef HAVE_OPENSSL
	while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfsS:Z:v:")) != EOF)
#else
	while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfZ:v:")) != EOF)
#endif
		switch (a) {
		case 'u':
			UID = atol(optarg);
			break;
		case 'h':
			hdir = strdup(optarg);
			relh=hdir[0]!='/';
			if (!relh) {
				safestrncpy(webcitdir, hdir, sizeof webcitdir);
			}
			else {
				safestrncpy(relhome, relhome, sizeof relhome);
			}
			/* free(hdir); TODO: SHOULD WE DO THIS? */
			home=1;
			break;
		case 'd':
			running_as_daemon = 1;
			break;
		case 'D':
			pidfile = strdup(optarg);
			running_as_daemon = 1;
			break;
		case 'g':
			default_landing_page = strdup(optarg);
			break;
		case 'B': /* Basesize */
			basesize = atoi(optarg);
			if (basesize > 2)
				StartLibCitadel(basesize);
			break;
		case 'i':
			safestrncpy(ip_addr, optarg, sizeof ip_addr);
			break;
		case 'p':
			http_port = atoi(optarg);
			if (http_port == 0) {
				safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
			}
			break;
		case 't':
			/* no longer used, but ignored so old scripts don't break */
			break;
		case 'T':
			LoadTemplates = atoi(optarg);
			dbg_analyze_msg = (LoadTemplates & (1<<1)) != 0;
			dbg_backtrace_template_errors = (LoadTemplates & (1<<2)) != 0;
			break;
		case 'Z':
			DisableGzip = 1;
			break;
		case 'x':
			/* no longer used, but ignored so old scripts don't break */
			break;
		case 'f':
			follow_xff = 1;
			break;
		case 'c':
			server_cookie = malloc(256);
			if (server_cookie != NULL) {
				safestrncpy(server_cookie,
				       "Set-cookie: wcserver=",
					256);
				if (gethostname
				    (&server_cookie[strlen(server_cookie)],
				     200) != 0) {
					syslog(LOG_INFO, "gethostname: %s", strerror(errno));
					free(server_cookie);
				}
			}
			break;
#ifdef HAVE_OPENSSL
		case 's':
			is_https = 1;
			break;
		case 'S':
			is_https = 1;
			ssl_cipher_list = strdup(optarg);
			break;
#endif
		case 'G':
			DumpTemplateI18NStrings = 1;
			I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
			I18nDumpFile = optarg;
			break;
		case 'v':
			verbose=1;
			break;
		default:
			fprintf(stderr, "usage:\nwebcit "
				"[-i ip_addr] [-p http_port] "
				"[-c] [-f] "
				"[-T Templatedebuglevel] "
				"[-d] [-Z] [-G i18ndumpfile] "
				"[-u uid] [-h homedirectory] "
				"[-D daemonizepid] [-v] "
				"[-g defaultlandingpage] [-B basesize] "
#ifdef HAVE_OPENSSL
				"[-s] [-S cipher_suites]"
#endif
				"[remotehost [remoteport]]\n");
			return 1;
		}

	/* Start the logger */
	openlog("webcit",
		( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
		LOG_DAEMON
	);

	if (optind < argc) {
		ctdlhost = argv[optind];
		if (++optind < argc)
			ctdlport = argv[optind];
	}

	/* daemonize, if we were asked to */
	if (!DumpTemplateI18NStrings && running_as_daemon) {
		start_daemon(pidfile);
	}
	else {
		signal(SIGINT, graceful_shutdown);
		signal(SIGHUP, graceful_shutdown);
	}

	webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
	LoadMimeBlacklist();
	LoadIconDir(static_icon_dir);

	/* Tell 'em who's in da house */
	syslog(LOG_NOTICE, "%s", PACKAGE_STRING);
	syslog(LOG_NOTICE, "Copyright (C) 1996-2015 by the citadel.org team");
	syslog(LOG_NOTICE, " ");
	syslog(LOG_NOTICE, "This program is open source software: you can redistribute it and/or");
	syslog(LOG_NOTICE, "modify it under the terms of the GNU General Public License, version 3.");
	syslog(LOG_NOTICE, " ");
	syslog(LOG_NOTICE, "This program is distributed in the hope that it will be useful,");
	syslog(LOG_NOTICE, "but WITHOUT ANY WARRANTY; without even the implied warranty of");
	syslog(LOG_NOTICE, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
	syslog(LOG_NOTICE, "GNU General Public License for more details.");
	syslog(LOG_NOTICE, " ");

	/* initialize various subsystems */

	initialise_modules();
	initialise2_modules();
	InitTemplateCache();
	if (DumpTemplateI18NStrings) {
		FILE *fd;
		StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
	        if (StrLength(I18nDump) < 50) {
			syslog(LOG_INFO, "*******************************************************************\n");
			syslog(LOG_INFO, "*   No strings found in templates!  Are you sure they're there?   *\n");
			syslog(LOG_INFO, "*******************************************************************\n");
			return -1;
		}
		fd = fopen(I18nDumpFile, "w");
	        if (fd == NULL) {
			syslog(LOG_INFO, "***********************************************\n");
			syslog(LOG_INFO, "*   unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
			syslog(LOG_INFO, "***********************************************\n");
			return -1;
		}
		fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
		fclose(fd);
		return 0;
	}

	/* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
	icalerror_errors_are_fatal = 0;

	/* Use our own prefix on tzid's generated from system tzdata */
	icaltimezone_set_tzid_prefix("/citadel.org/");

	/*
	 * Set up a place to put thread-specific data.
	 * We only need a single pointer per thread - it points to the
	 * wcsession struct to which the thread is currently bound.
	 */
	if (pthread_key_create(&MyConKey, NULL) != 0) {
		syslog(LOG_EMERG, "Can't create TSD key: %s", strerror(errno));
	}
	InitialiseSemaphores();

	/*
	 * Set up a place to put thread-specific SSL data.
	 * We don't stick this in the wcsession struct because SSL starts
	 * up before the session is bound, and it gets torn down between
	 * transactions.
	 */
#ifdef HAVE_OPENSSL
	if (pthread_key_create(&ThreadSSL, NULL) != 0) {
		syslog(LOG_EMERG, "Can't create TSD key: %s", strerror(errno));
	}
#endif

	/*
	 * Bind the server to our favorite port.
	 * There is no need to check for errors, because webcit_tcp_server()
	 * exits if it doesn't succeed.
	 */

	if (!IsEmptyStr(uds_listen_path)) {
		syslog(LOG_DEBUG, "Attempting to create listener socket at %s...", uds_listen_path);
		msock = webcit_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
	}
	else {
		syslog(LOG_DEBUG, "Attempting to bind to port %d...", http_port);
		msock = webcit_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
	}
	if (msock < 0)
	{
		ShutDownWebcit();
		return -msock;
	}

	syslog(LOG_INFO, "Listening on socket %d", msock);
	signal(SIGPIPE, SIG_IGN);

	pthread_mutex_init(&SessionListMutex, NULL);

	/*
	 * Start up the housekeeping thread
	 */
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	pthread_create(&SessThread, &attr, (void *(*)(void *)) housekeeping_loop, NULL);

	/*
	 * If this is an HTTPS server, fire up SSL
	 */
#ifdef HAVE_OPENSSL
	if (is_https) {
		init_ssl();
	}
#endif
	drop_root(UID);

	/* Become a worker thread.  More worker threads will be spawned as they are needed. */
	worker_entry();
	ShutDownLibCitadel();
	return 0;
}
Exemplo n.º 20
0
/*
 * This program acts as a generic gateway. It listens for connections
 * to a local address ('-l' option). Upon accepting a client connection,
 * it connects to the specified remote address ('-r' option) and then
 * just pumps the data through without any modification.
 */
int main(int argc, char *argv[])
{
  extern char *optarg;
  int opt, sock, n;
  int laddr, raddr, num_procs;
  int serialize_accept = 0;
  struct sockaddr_in lcl_addr, cli_addr;
  st_netfd_t cli_nfd, srv_nfd;

  prog = argv[0];
  num_procs = laddr = raddr = 0;

  /* Parse arguments */
  while((opt = getopt(argc, argv, "l:r:p:Sh")) != EOF) {
    switch (opt) {
    case 'l':
      read_address(optarg, &lcl_addr);
      laddr = 1;
      break;
    case 'r':
      read_address(optarg, &rmt_addr);
      if (rmt_addr.sin_addr.s_addr == INADDR_ANY) {
	fprintf(stderr, "%s: invalid remote address: %s\n", prog, optarg);
	exit(1);
      }
      raddr = 1;
      break;
    case 'p':
      num_procs = atoi(optarg);
      if (num_procs < 1) {
	fprintf(stderr, "%s: invalid number of processes: %s\n", prog, optarg);
	exit(1);
      }
      break;
    case 'S':
      /*
       * Serialization decision is tricky on some platforms. For example,
       * Solaris 2.6 and above has kernel sockets implementation, so supposedly
       * there is no need for serialization. The ST library may be compiled
       * on one OS version, but used on another, so the need for serialization
       * should be determined at run time by the application. Since it's just
       * an example, the serialization decision is left up to user.
       * Only on platforms where the serialization is never needed on any OS
       * version st_netfd_serialize_accept() is a no-op.
       */
      serialize_accept = 1;
      break;
    case 'h':
    case '?':
      fprintf(stderr, "Usage: %s -l <[host]:port> -r <host:port> "
	      "[-p <num_processes>] [-S]\n", prog);
      exit(1);
    }
  }
  if (!laddr) {
    fprintf(stderr, "%s: local address required\n", prog);
    exit(1);
  }
  if (!raddr) {
    fprintf(stderr, "%s: remote address required\n", prog);
    exit(1);
  }
  if (num_procs == 0)
    num_procs = cpu_count();

  fprintf(stderr, "%s: starting proxy daemon on %s:%d\n", prog,
	  inet_ntoa(lcl_addr.sin_addr), ntohs(lcl_addr.sin_port));

  /* Start the daemon */
  start_daemon();

  /* Initialize the ST library */
  if (st_init() < 0) {
    print_sys_error("st_init");
    exit(1);
  }

  /* Create and bind listening socket */
  if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
    print_sys_error("socket");
    exit(1);
  }
  n = 1;
  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof(n)) < 0) {
    print_sys_error("setsockopt");
    exit(1);
  }
  if (bind(sock, (struct sockaddr *)&lcl_addr, sizeof(lcl_addr)) < 0) {
    print_sys_error("bind");
    exit(1);
  }
  listen(sock, 128);
  if ((srv_nfd = st_netfd_open_socket(sock)) == NULL) {
    print_sys_error("st_netfd_open");
    exit(1);
  }
  /* See the comment regarding serialization decision above */
  if (num_procs > 1 && serialize_accept && st_netfd_serialize_accept(srv_nfd)
      < 0) {
    print_sys_error("st_netfd_serialize_accept");
    exit(1);
  }

  /* Start server processes */
  set_concurrency(num_procs);

  for ( ; ; ) {
    n = sizeof(cli_addr);
    cli_nfd = st_accept(srv_nfd, (struct sockaddr *)&cli_addr, &n, -1);
    if (cli_nfd == NULL) {
      print_sys_error("st_accept");
      exit(1);
    }
    if (st_thread_create(handle_request, cli_nfd, 0, 0) == NULL) {
      print_sys_error("st_thread_create");
      exit(1);
    }
  }

  /* NOTREACHED */
  return 1;
}
Exemplo n.º 21
0
int main(int argc, char **argv) {
    int iostream;
    int opt;

    if (getuid()) {
	fprintf(stderr, "This program can be run only by root.\n");
	exit(EXIT_FAILURE);
    }

    setlocale(LC_ALL, "");

    struct option longopts[] = {
	{"help",       0, 0, 'h'},
	{"interface",  1, 0, 'i'},
	{"no-resolve", 0, 0, 'n'},
	{"port",       1, 0, 'p'},
	{NULL,         0, 0, '\0'}
    };

    /* Parse command line options. */
    while ((opt = getopt_long(argc, argv, "hi:np:", longopts, NULL)) != EOF) {
	switch (opt) {
	    case 'i':
		snprintf(opts.interface, sizeof(opts.interface), "%s", optarg);
		break;
	    case 'n':
		opts.resolve = FALSE;
		break;
	    case 'p':
		opts.port = atoi(optarg);
		break;
	    default:
		usage(argv[0]);
		break;
	}
    }

    /* Save filter expression */
    if (optind < argc) {
	for (strcat(opts.expression, "and "); optind < argc; optind++) {
	    strncat(opts.expression, argv[optind], sizeof(opts.expression));
	    strncat(opts.expression, " ", sizeof(opts.expression));
	}
    }

    if (opts.port) {
	/* Goto background. */
	if (fork())
	    exit(EXIT_SUCCESS);

	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	iostream = open(_PATH_DEVNULL, O_RDWR);
	dup(iostream);
	dup(iostream);

	start_daemon();
    } else
	show_display();

    return 0;
}
Exemplo n.º 22
0
/* int Start_win32_Syscheck()
 * syscheck main for windows
 */
int Start_win32_Syscheck()
{
    int r = 0;
    char *cfg = DEFAULTCPATH;


    /* Zeroing the structure */
    syscheck.workdir = DEFAULTDIR;


    /* Checking if the configuration is present */
    if(File_DateofChange(cfg) < 0)
        ErrorExit(NO_CONFIG, ARGV0, cfg);


    /* Read syscheck config */
    if((r = Read_Syscheck_Config(cfg)) < 0)
    {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    }
    /* Disabled */
    else if((r == 1) || (syscheck.disabled == 1))
    {
        if(!syscheck.dir)
        {
            merror(SK_NO_DIR, ARGV0);
            dump_syscheck_entry(&syscheck, "", 0, 0, NULL);
        }
        else if(!syscheck.dir[0])
        {
            merror(SK_NO_DIR, ARGV0);
        }
        syscheck.dir[0] = NULL;

        if(!syscheck.registry)
        {
            dump_syscheck_entry(&syscheck, "", 0, 1, NULL);
        }
        syscheck.registry[0] = NULL;

        merror("%s: WARN: Syscheck disabled.", ARGV0);
    }


    /* Reading internal options */
    read_internal();


    /* Rootcheck config */
    if(rootcheck_init(0) == 0)
    {
        syscheck.rootcheck = 1;
    }
    else
    {
        syscheck.rootcheck = 0;
        merror("%s: WARN: Rootcheck module disabled.", ARGV0);
    }
                                                            


    /* Printing options */
    r = 0;
    while(syscheck.registry[r] != NULL)
    {
        verbose("%s: INFO: Monitoring registry entry: '%s'.", 
                ARGV0, syscheck.registry[r]);
        r++;
    }
    
    r = 0;
    while(syscheck.dir[r] != NULL)
    {
        verbose("%s: INFO: Monitoring directory: '%s'.",
                ARGV0, syscheck.dir[r]);
        r++;
    }


    /* Start up message */
    verbose(STARTUP_MSG, ARGV0, getpid());
            
        
        
    /* Some sync time */
    sleep(syscheck.tsleep + 10);


    /* Waiting if agent started properly. */
    os_wait();

    
    start_daemon();


    exit(0);
}                
Exemplo n.º 23
0
int main(int argc, char **argv)
{
    int c,r;
    int test_config = 0,run_foreground = 0;
    
    char *cfg = DEFAULTCPATH;
    
    
    /* Zeroing the structure */
    syscheck.workdir = NULL;


    /* Setting the name */
    OS_SetName(ARGV0);
        
    
    while((c = getopt(argc, argv, "VtdhfD:c:")) != -1)
    {
        switch(c)
        {
            case 'V':
                print_version();
                break;
            case 'h':
                help(ARGV0);
                break;
            case 'd':
                nowDebug();
                break;
            case 'f':
                run_foreground = 1;
                break;
            case 'D':
                if(!optarg)
                    ErrorExit("%s: -D needs an argument",ARGV0);
                syscheck.workdir = optarg;
                break;
            case 'c':
                if(!optarg)
                    ErrorExit("%s: -c needs an argument",ARGV0);
                cfg = optarg;
                break;
            case 't':
                test_config = 1;
                break;        
            default:
                help(ARGV0);
                break;   
        }
    }


    /* Checking if the configuration is present */
    if(File_DateofChange(cfg) < 0)
        ErrorExit(NO_CONFIG, ARGV0, cfg);


    /* Read syscheck config */
    if((r = Read_Syscheck_Config(cfg)) < 0)
    {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    }
    else if((r == 1) || (syscheck.disabled == 1))
    {
        if(!syscheck.dir)
        {
            if(!test_config)
                merror(SK_NO_DIR, ARGV0);
            dump_syscheck_entry(&syscheck, "", 0, 0, NULL);
        }
        else if(!syscheck.dir[0])
        {
            if(!test_config)
                merror(SK_NO_DIR, ARGV0);
        }
        syscheck.dir[0] = NULL;
        if(!test_config)
        {
            merror("%s: WARN: Syscheck disabled.", ARGV0);
        }
    }


    /* Reading internal options */
    read_internal();
        
    

    /* Rootcheck config */
    if(rootcheck_init(test_config) == 0)
    {
        syscheck.rootcheck = 1;
    }
    else
    {
        syscheck.rootcheck = 0;
        merror("%s: WARN: Rootcheck module disabled.", ARGV0);
    }

        
    /* Exit if testing config */
    if(test_config)
        exit(0);

        
    /* Setting default values */
    if(syscheck.workdir == NULL)
        syscheck.workdir = DEFAULTDIR;


    if(!run_foreground) 
    {
        nowDaemon();
        goDaemon();
    }
   
    /* Initial time to settle */
    sleep(syscheck.tsleep + 2); 
    
    
    /* Connect to the queue  */
    if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0)
    {   
        merror(QUEUE_ERROR, ARGV0, DEFAULTQPATH, strerror(errno));

        sleep(5);
        if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0)
        {
            /* more 10 seconds of wait.. */
            merror(QUEUE_ERROR, ARGV0, DEFAULTQPATH, strerror(errno));
            sleep(10);
            if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0)
                ErrorExit(QUEUE_FATAL,ARGV0,DEFAULTQPATH);
        }
    }


    /* Start the signal handling */
    StartSIG(ARGV0);
    

    /* Creating pid */
    if(CreatePID(ARGV0, getpid()) < 0)
        merror(PID_ERROR,ARGV0);


    /* Start up message */
    verbose(STARTUP_MSG, ARGV0, (int)getpid());

    if(syscheck.rootcheck)
    {
        verbose(STARTUP_MSG, "ossec-rootcheck", (int)getpid());
    }


    /* Printing directories to be monitored. */
    r = 0;
    while(syscheck.dir[r] != NULL)
    {
        verbose("%s: INFO: Monitoring directory: '%s'.",
                ARGV0, syscheck.dir[r]);
        r++;
    }

    /* Checking directories set for real time. */
    r = 0;
    while(syscheck.dir[r] != NULL)
    {
        if(syscheck.opts[r] & CHECK_REALTIME)
        {
            #ifdef USEINOTIFY
            verbose("%s: INFO: Directory set for real time monitoring: "
                    "'%s'.", ARGV0, syscheck.dir[r]);
            #elif WIN32
            verbose("%s: INFO: Directory set for real time monitoring: "
                    "'%s'.", ARGV0, syscheck.dir[r]);
            #else
            verbose("%s: WARN: Ignoring flag for real time monitoring on "
                    "directory: '%s'.", ARGV0, syscheck.dir[r]);
            #endif
        }
        r++;
    }
        
    
    /* Some sync time */
    sleep(syscheck.tsleep + 10);


    /* Start the daemon */
    start_daemon();

    return(0);        
}
Exemplo n.º 24
0
/* syscheck main for Windows */
int Start_win32_Syscheck()
{
    int debug_level = 0;
    int r = 0;
    char *cfg = DEFAULTCPATH;

    /* Read internal options */
    read_internal(debug_level);

    debug1(STARTED_MSG, ARGV0);

    /* Check if the configuration is present */
    if (File_DateofChange(cfg) < 0) {
        ErrorExit(NO_CONFIG, ARGV0, cfg);
    }

    /* Read syscheck config */
    if ((r = Read_Syscheck_Config(cfg)) < 0) {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    } else if ((r == 1) || (syscheck.disabled == 1)) {
        /* Disabled */
        if (!syscheck.dir) {
            merror(SK_NO_DIR, ARGV0);
            dump_syscheck_entry(&syscheck, "", 0, 0, NULL);
        } else if (!syscheck.dir[0]) {
            merror(SK_NO_DIR, ARGV0);
        }
        syscheck.dir[0] = NULL;

        if (!syscheck.registry) {
            dump_syscheck_entry(&syscheck, "", 0, 1, NULL);
        }
        syscheck.registry[0].entry = NULL;

        merror("%s: WARN: Syscheck disabled.", ARGV0);
    }

    /* Rootcheck config */
    if (rootcheck_init(0) == 0) {
        syscheck.rootcheck = 1;
    } else {
        syscheck.rootcheck = 0;
        merror("%s: WARN: Rootcheck module disabled.", ARGV0);
    }

    /* Print options */
    r = 0;
    while (syscheck.registry[r].entry != NULL) {
        verbose("%s: INFO: Monitoring registry entry: '%s%s'.",
                ARGV0, syscheck.registry[r].entry, syscheck.registry[r].arch == ARCH_64BIT ? " [x64]" : "");
        r++;
    }

    /* Print directories to be monitored */
    r = 0;
    while (syscheck.dir[r] != NULL) {
	char optstr[ 100 ];
        verbose("%s: INFO: Monitoring directory: '%s', with options %s.",
	    ARGV0, syscheck.dir[r],
	    syscheck_opts2str(optstr, sizeof( optstr ), syscheck.opts[r]));
        r++;
    }

    /* Print ignores. */
    if(syscheck.ignore)
	for (r = 0; syscheck.ignore[r] != NULL; r++)
	    verbose("%s: INFO: ignoring: '%s'",
		ARGV0, syscheck.ignore[r]);

    /* Print files with no diff. */
    if (syscheck.nodiff){
        r = 0;
        while (syscheck.nodiff[r] != NULL) {
            verbose("%s: INFO: No diff for file: '%s'",
                    ARGV0, syscheck.nodiff[r]);
            r++;
        }
    }

    /* Start up message */
    verbose(STARTUP_MSG, ARGV0, getpid());

    /* Some sync time */
    sleep(syscheck.tsleep + 10);

    /* Wait if agent started properly */
    os_wait();

    start_daemon();

    exit(0);
}
Exemplo n.º 25
0
int
main(int argc, char *argv[], char *envp[])
{
    struct stat histstat;

    if (modfind(VINUMMOD) < 0) {
	/* need to load the vinum module */
	if (kldload(VINUMMOD) < 0 || modfind(VINUMMOD) < 0) {
	    perror(VINUMMOD ": Kernel module not available");
	    return 1;
	}
    }
    dateformat = getenv("VINUM_DATEFORMAT");
    if (dateformat == NULL)
	dateformat = "%e %b %Y %H:%M:%S";
    historyfile = getenv("VINUM_HISTORY");
    if (historyfile == NULL)
	historyfile = DEFAULT_HISTORYFILE;
    if (stat(historyfile, &histstat) == 0) {		    /* history file exists */
	if ((histstat.st_mode & S_IFMT) != S_IFREG) {
	    fprintf(stderr,
		"Vinum history file %s must be a regular file\n",
		historyfile);
	    exit(1);
	}
    } else if ((errno != ENOENT)			    /* not "not there",  */
    &&(errno != EROFS)) {				    /* and not read-only file system */
	fprintf(stderr,
	    "Can't open %s: %s (%d)\n",
	    historyfile,
	    strerror(errno),
	    errno);
	exit(1);
    }
    hist = fopen(historyfile, "a+");
    if (hist != NULL) {
	timestamp();
	fprintf(hist, "*** " VINUMMOD " started ***\n");
	fflush(hist);				    /* before we start the daemon */
    }
    superdev = open(VINUM_SUPERDEV_NAME, O_RDWR);	    /* open vinum superdevice */
    if (superdev < 0) {					    /* no go */
	if (errno == ENODEV) {				    /* not configured, */
	    superdev = open(VINUM_WRONGSUPERDEV_NAME, O_RDWR); /* do we have a debug mismatch? */
	    if (superdev >= 0) {			    /* yup! */
#if VINUMDEBUG
		fprintf(stderr,
		    "This program is compiled with debug support, but the kernel module does\n"
		    "not have debug support.  This program must be matched with the kernel\n"
		    "module.  Please alter /usr/src/sbin/" VINUMMOD "/Makefile and remove\n"
		    "the option -DVINUMDEBUG from the CFLAGS definition, or alternatively\n"
		    "edit /usr/src/sys/modules/" VINUMMOD "/Makefile and add the option\n"
		    "-DVINUMDEBUG to the CFLAGS definition.  Then rebuild the component\n"
		    "of your choice with 'make clean all install'.  If you rebuild the kernel\n"
		    "module, you must stop " VINUMMOD " and restart it\n");
#else
		fprintf(stderr,
		    "This program is compiled without debug support, but the kernel module\n"
		    "includes debug support.  This program must be matched with the kernel\n"
		    "module.  Please alter /usr/src/sbin/" VINUMMOD "/Makefile and add\n"
		    "the option -DVINUMDEBUG to the CFLAGS definition, or alternatively\n"
		    "edit /usr/src/sys/modules/" VINUMMOD "/Makefile and remove the option\n"
		    "-DVINUMDEBUG from the CFLAGS definition.  Then rebuild the component\n"
		    "of your choice with 'make clean all install'.  If you rebuild the kernel\n"
		    "module, you must stop " VINUMMOD " and restart it\n");
#endif
		return 1;
	    }
	} else if (errno == ENOENT)			    /* we don't have our node, */
	    make_devices();				    /* create them first */
	if (superdev < 0) {
	    perror("Can't open " VINUM_SUPERDEV_NAME);
	    return 1;
	}
    }
    /* Check if the dæmon is running.  If not, start it in the
     * background */
    start_daemon();

    if (argc > 1) {					    /* we have a command on the line */
	if (setjmp(command_fail) != 0)			    /* long jumped out */
	    return -1;
	parseline(argc - 1, &argv[1]);			    /* do it */
    } else {
	/*
	 * Catch a possible race condition which could cause us to
	 * longjmp() into nowhere if we receive a SIGINT in the next few
	 * lines.
	 */
	if (setjmp(command_fail))			    /* come back here on catastrophic failure */
	    return 1;
	setsigs();					    /* set signal handler */
	for (;;) {					    /* ugh */
	    char *c;
	    int childstatus;				    /* from wait4 */

	    if (setjmp(command_fail) == 2)		    /* come back here on catastrophic failure */
		fprintf(stderr, "*** interrupted ***\n");   /* interrupted */

	    while (wait4(-1, &childstatus, WNOHANG, NULL) > 0);	/* wait for all dead children */
	    c = readline(VINUMMOD " -> ");		    /* get an input */
	    if (c == NULL) {				    /* EOF or error */
		if (ferror(stdin)) {
		    fprintf(stderr, "Can't read input: %s (%d)\n", strerror(errno), errno);
		    return 1;
		} else {				    /* EOF */
		    printf("\n");
		    return 0;
		}
	    } else if (*c) {				    /* got something there */
		add_history(c);				    /* save it in the history */
		strcpy(buffer, c);			    /* put it where we can munge it */
		free(c);
		line++;					    /* count the lines */
		tokens = tokenize(buffer, token);
		/* got something potentially worth parsing */
		if (tokens)
		    parseline(tokens, token);		    /* and do what he says */
	    }
	    if (hist)
		fflush(hist);
	}
    }
    return 0;						    /* normal completion */
}
Exemplo n.º 26
0
Arquivo: main.c Projeto: hannenz/busy
int main(int argc, char **argv){
	GMainLoop *main_loop;
	GSocketService *service;
	GInetAddress *iaddr;
	GSocketAddress *saddr;
	AppData *app_data;
	GError *error = NULL;

	// Init
	g_set_prgname(argv[0]);
	g_mem_set_vtable(glib_mem_profiler_table);
	g_type_init();

	// Start the daemon
	start_daemon(g_get_prgname(), LOG_LOCAL0);
	syslog(LOG_NOTICE, "-----------------------------------\n");
	syslog(LOG_NOTICE, "Daemon has been started\n");


//	atexit(cleanup);

	// Initialize App Data structire
	app_data = g_slice_new0(AppData);
	app_data->queue = g_queue_new();
	app_data->hosts = NULL;
	app_data->running_backups = NULL;

	// For global access to app_data
	app_data_aux_ptr = app_data;

	// Read configuration
	if (!read_config(app_data)){
		syslog(LOG_ERR, "Failed to read config file \"%s\"", CONFIG_FILE);
		exit(-1);
	}

	// If no hosts configured in config file, try reading from MySQL

	if (g_list_length(app_data->hosts) == 0){
		syslog(LOG_NOTICE, "No hosts configured in /etc/busy/busy.conf, now reading hosts from MySQL");
		app_data->hosts = db_read_hosts(app_data->mysql);
	}

	if (g_list_length(app_data->hosts) == 0){
		syslog(LOG_ERR, "Absolutely no hosts configured! Please configure at least one host either in %s or use the Web frontend", CONFIG_FILE);
		//~ syslog(LOG_ERR, "I won't waste any more cpu time now and exit");
		//~ exit(0);
	}
	else {
		GList *p;
		for (p = app_data->hosts; p != NULL; p = p->next){
			Host *host = p->data;
			host_dump(host);
			syslog(LOG_NOTICE, "%s %f", host_get_name(host), host_get_max_age(host));
		}
	}

	// Setup listener for incoming TCP (localhost port 4000)
	service = g_socket_service_new();
	iaddr = g_inet_address_new_from_string("127.0.0.1");
	saddr = g_inet_socket_address_new(iaddr, 4000);
	g_socket_listener_add_address(G_SOCKET_LISTENER(service), saddr, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, NULL, NULL, &error);
	g_object_unref(iaddr);
	g_object_unref(saddr);
	g_socket_service_start(service);
	g_signal_connect(service, "incoming", (GCallback)on_incoming, app_data);

	// Call wakeup and archive function once
	wakeup(app_data);
	do_archive(app_data);

	// Check preiodically for backups, queue and archives,
	g_timeout_add_seconds(WAKEUP_INTERVAL, (GSourceFunc)wakeup, app_data);
	g_timeout_add_seconds(10, (GSourceFunc)do_backup, app_data);
	g_timeout_add_seconds(6 * 3600, (GSourceFunc)do_archive, app_data);

	// Run main loop
	main_loop = g_main_loop_new(NULL, FALSE);
	g_main_loop_run(main_loop);

	return (EXIT_SUCCESS);
}
Exemplo n.º 27
0
int main(int argc, char *argv[])
{
	if(!(home_dir = getenv("HOME"))){
		LOG_ERR();
		REPORT_ERREXIT();
	}
	if(!(cwd = getcwd(cwd, PATH_MAX))){
		LOG_ERR();
		REPORT_ERREXIT();
	}
	int flag = 0;
	char *corelog;
	while((flag = getopt(argc, argv, "c:l:")) != -1){
		switch(flag){
			case 'c':{
				config_file = optarg;
				break;
			}
			case 'l':{
				corelog = optarg;
				break;		
			}
			case '?':{
				fprintf(stderr, "Invalid argument!\n");
				return -1;
			}
		}
	}
	int clog = open((const char *)corelog, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
	if(clog == -1){
		LOG_ERR();
		return -1;
	}
	core_log = fdopen(clog, "a+");
	if(!core_log){
		LOG_ERR();
		return -1;
	}

	int ret;

	ret = parse_config_file((const char *)config_file);
	MAIN_CHECK_RETVAL(ret);

	ret = get_inotify_limits();
	MAIN_CHECK_RETVAL(ret);

	ret = init_inotify_actions();
	MAIN_CHECK_RETVAL(ret);

	init_pollfd_structures();

	ret = create_log_streams(0);
	MAIN_CHECK_RETVAL(ret);

	ret = init_event_struct();
	MAIN_CHECK_RETVAL(ret);

	
	ret = start_daemon();
	MAIN_CHECK_RETVAL(ret);

	print_createtime();

	ret = savepid();
	MAIN_CHECK_RETVAL(ret);

	set_sigusr1_handler();
	set_sigusr2_handler();

	for(;;){
		ret = wait_events();
		MAIN_CHECK_RETVAL(ret);
		ret = handle_events();
		MAIN_CHECK_RETVAL(ret);
	}
	return 0;
}
Exemplo n.º 28
0
int main(int argc, char *argv[])
{
	int c;
	g_options.log_destination = LOGGING_STDERR;

	while ((c = getopt(argc, argv, "nhdp:u:s:l")) != -1) {
		switch (c) {
		case '?':
		case 'h':
			g_options.help_mode = 1;
			break;
		case 'p':
		{
			long long port = 0;
			// Request specific port
			port = atoi(optarg);
			if (port < 0) {
				ERR("Port number must be non-negative");
				return 1;
			}
			if (port > (long long)UINT_MAX) {
				ERR("Port number must be %u or less, "
				    "but not negative", UINT_MAX);
				return 2;
			}
			g_options.desired_port = port;
			break;
		}
		case 'u':
			// [u]sb device to bind with
			break;
		case 'l':
			g_options.log_destination = LOGGING_SYSLOG;
			break;
		case 'd':
			g_options.nofork_mode = 1;
			g_options.verbose_mode = 1;
			break;
		case 'n':
			g_options.nofork_mode = 1;
		}
	}

	if (g_options.help_mode) {
		printf(
		"Usage: %s -v <vendorid> -m <productid> -p <port>\n"
		"Options:\n"
		"  -h           Show this help message\n"
		"  -v <vid>     Vendor ID of desired printer\n"
		"  -m <pid>     Product ID of desired printer\n"
		"  -s <serial>  Serial number of desired printer\n"
		"  -p <portnum> Port number to bind against\n"
		"  -l           Redirect logging to syslog\n"
		"  -d           Debug mode for verbose output and no fork\n"
		"  -n           No fork mode\n"
		, argv[0]);
		return 0;
	}

	start_daemon();
	return 0;
}
Exemplo n.º 29
0
/* Syscheck unix main */
int main(int argc, char **argv)
{
    int c, r;
    int debug_level = 0;
    int test_config = 0, run_foreground = 0;
    const char *cfg = DEFAULTCPATH;

    /* Set the name */
    OS_SetName(ARGV0);

    while ((c = getopt(argc, argv, "Vtdhfc:")) != -1) {
        switch (c) {
            case 'V':
                print_version();
                break;
            case 'h':
                help_syscheckd();
                break;
            case 'd':
                nowDebug();
                debug_level ++;
                break;
            case 'f':
                run_foreground = 1;
                break;
            case 'c':
                if (!optarg) {
                    ErrorExit("%s: -c needs an argument", ARGV0);
                }
                cfg = optarg;
                break;
            case 't':
                test_config = 1;
                break;
            default:
                help_syscheckd();
                break;
        }
    }

    /* Read internal options */
    read_internal(debug_level);

    debug1(STARTED_MSG, ARGV0);

    /* Check if the configuration is present */
    if (File_DateofChange(cfg) < 0) {
        ErrorExit(NO_CONFIG, ARGV0, cfg);
    }

    /* Read syscheck config */
    if ((r = Read_Syscheck_Config(cfg)) < 0) {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    } else if ((r == 1) || (syscheck.disabled == 1)) {
        if (!syscheck.dir) {
            if (!test_config) {
                merror(SK_NO_DIR, ARGV0);
            }
            dump_syscheck_entry(&syscheck, "", 0, 0, NULL);
        } else if (!syscheck.dir[0]) {
            if (!test_config) {
                merror(SK_NO_DIR, ARGV0);
            }
        }
        syscheck.dir[0] = NULL;
        if (!test_config) {
            merror("%s: WARN: Syscheck disabled.", ARGV0);
        }
    }

    /* Rootcheck config */
    if (rootcheck_init(test_config) == 0) {
        syscheck.rootcheck = 1;
    } else {
        syscheck.rootcheck = 0;
        merror("%s: WARN: Rootcheck module disabled.", ARGV0);
    }

    /* Exit if testing config */
    if (test_config) {
        exit(0);
    }

    /* Setup libmagic */
#ifdef USE_MAGIC
    init_magic(&magic_cookie);
#endif

    if (!run_foreground) {
        nowDaemon();
        goDaemon();
    }

    /* Initial time to settle */
    sleep(syscheck.tsleep + 2);

    /* Connect to the queue */
    if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) {
        merror(QUEUE_ERROR, ARGV0, DEFAULTQPATH, strerror(errno));

        sleep(5);
        if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) {
            /* more 10 seconds of wait */
            merror(QUEUE_ERROR, ARGV0, DEFAULTQPATH, strerror(errno));
            sleep(10);
            if ((syscheck.queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) {
                ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH);
            }
        }
    }

    /* Start signal handling */
    StartSIG(ARGV0);

    /* Create pid */
    if (CreatePID(ARGV0, getpid()) < 0) {
        ErrorExit(PID_ERROR, ARGV0);
    }

    /* Start up message */
    verbose(STARTUP_MSG, ARGV0, (int)getpid());

    if (syscheck.rootcheck) {
        verbose(STARTUP_MSG, "ossec-rootcheck", (int)getpid());
    }

    /* Print directories to be monitored */
    r = 0;
    while (syscheck.dir[r] != NULL) {
	char optstr[ 100 ];
        verbose("%s: INFO: Monitoring directory: '%s', with options %s.",
	    ARGV0, syscheck.dir[r],
	    syscheck_opts2str(optstr, sizeof( optstr ), syscheck.opts[r]));
        r++;
    }

    /* Print ignores. */
    if(syscheck.ignore)
	for (r = 0; syscheck.ignore[r] != NULL; r++)
	    verbose("%s: INFO: ignoring: '%s'",
		ARGV0, syscheck.ignore[r]);

    /* Print files with no diff. */
    if (syscheck.nodiff){
        r = 0;
        while (syscheck.nodiff[r] != NULL) {
            verbose("%s: INFO: No diff for file: '%s'",
                    ARGV0, syscheck.nodiff[r]);
            r++;
        }
    }

    /* Check directories set for real time */
    r = 0;
    while (syscheck.dir[r] != NULL) {
        if (syscheck.opts[r] & CHECK_REALTIME) {
#ifdef INOTIFY_ENABLED
            verbose("%s: INFO: Directory set for real time monitoring: "
                    "'%s'.", ARGV0, syscheck.dir[r]);
#elif defined(WIN32)
            verbose("%s: INFO: Directory set for real time monitoring: "
                    "'%s'.", ARGV0, syscheck.dir[r]);
#else
            verbose("%s: WARN: Ignoring flag for real time monitoring on "
                    "directory: '%s'.", ARGV0, syscheck.dir[r]);
#endif
        }
        r++;
    }

    /* Some sync time */
    sleep(syscheck.tsleep + 10);

    /* Start the daemon */
    start_daemon();
}
Exemplo n.º 30
0
int alarm_main(int argc, FAR char *argv[])
#endif
{
  struct rtc_setrelative_s setrel;
  unsigned long seconds;
  int alarmid = 0;
  int secndx;
  int fd;
  int ret;

  /* Make sure that the alarm daemon is running */

  ret = start_daemon();
  if (ret < 0)
    {
      fprintf(stderr, "ERROR: Unrecognized option: %s\n", argv[1]);
      show_usage(argv[0]);
      return EXIT_FAILURE;
    }

#if CONFIG_RTC_NALARMS > 1
  /* Check for an optional alarm ID */

  if (argc == 4)
    {
      if (strcmp(argv[1], "-a") != 0)
        {
          fprintf(stderr, "ERROR: Unrecognized option: %s\n", argv[1]);
          show_usage(argv[0]);
          return EXIT_FAILURE;
        }

      alarmid = atoi(argv[2]);
      secndx = 3;
    }
  else
#endif
  if (argc == 2)
    {
       secndx = 1;
    }
  else
    {
      fprintf(stderr, "ERROR: Invalid number of arguments: %d\n", argc - 1);
      show_usage(argv[0]);
      return EXIT_FAILURE;
    }

  /* Get the number of seconds until the alarm expiration */

  seconds = strtoul(argv[secndx], NULL, 10);
  if (seconds < 1)
    {
      fprintf(stderr, "ERROR: Invalid number of seconds: %lu\n", seconds);
      show_usage(argv[0]);
      return EXIT_FAILURE;
    }

  /* Open the RTC driver */

  printf("Opening %s\n", CONFIG_EXAMPLES_ALARM_DEVPATH);

  fd = open(CONFIG_EXAMPLES_ALARM_DEVPATH, O_WRONLY);
  if (fd < 0)
    {
      int errcode = errno;
      fprintf(stderr, "ERROR: Failed to open %s: %d\n",
              CONFIG_EXAMPLES_ALARM_DEVPATH, errcode);
      return EXIT_FAILURE;
    }

  /* Set the alarm */

  setrel.id      = alarmid;
  setrel.signo   = CONFIG_EXAMPLES_ALARM_SIGNO;
  setrel.pid     = g_alarm_daeon_pid;
  setrel.reltime = (time_t)seconds;

  setrel.sigvalue.sival_int = alarmid;

  ret = ioctl(fd, RTC_SET_RELATIVE, (unsigned long)((uintptr_t)&setrel));
  if (ret < 0)
    {
      int errcode = errno;

      fprintf(stderr, "ERROR: RTC_SET_RELATIVE ioctl failed: %d\n",
              errcode);

      (void)close(fd);
      return EXIT_FAILURE;
    }

  printf("Alarm %d set in %lu seconds\n", alarmid, seconds);

  (void)close(fd);
  return EXIT_SUCCESS;
}