Exemplo n.º 1
0
void init(int argc, char **argv){
	if(argc < 2){
		usage(argc, argv);
		exit(0);
	}

	bool is_daemon = false;
	const char *conf_file = NULL;
	for(int i=1; i<argc; i++){
		if(strcmp(argv[i], "-d") == 0){
			is_daemon = true;
		}else{
			conf_file = argv[i];
		}
	}

	if(conf_file == NULL){
		usage(argc, argv);
		exit(0);
	}

	if(!is_file(conf_file)){
		fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
		exit(0);
	}

	conf = Config::load(conf_file);
	if(!conf){
		fprintf(stderr, "error loading conf file: '%s'", conf_file);
		exit(0);
	}
	{
		std::string conf_dir = real_dirname(conf_file);
		if(chdir(conf_dir.c_str()) == -1){
			fprintf(stderr, "error chdir: %s\n", conf_dir.c_str());
			exit(0);
		}
	}

	std::string work_dir;
	{
		work_dir = conf->get_str("work_dir");
		if(work_dir.empty()){
			work_dir = ".";
		}
		if(!is_dir(work_dir.c_str())){
			fprintf(stderr, "'%s' is not a directory or not exists!\n", work_dir.c_str());
			exit(0);
		}
		/*
		if(chdir(work_dir.c_str()) == -1){
			fprintf(stderr, "error chdir: %s\n", work_dir.c_str());
			exit(0);
		}
		*/
	}
	
	check_pidfile();

	std::string log_output;
	int log_rotate_size = 0;
	{ // logger
		int log_level = Logger::get_level(conf->get_str("logger.level"));
		log_rotate_size = conf->get_num("logger.rotate.size");
		log_output = conf->get_str("logger.output");
		if(log_output == ""){
			log_output = "stdout";
		}
		if(log_open(log_output.c_str(), log_level, true, log_rotate_size) == -1){
			fprintf(stderr, "error open log file: %s", log_output.c_str());
			exit(0);
		}
	}

	log_info("ssdb-server %s", SSDB_VERSION);
	log_info("conf_file       : %s", conf_file);
	log_info("work_dir        : %s", work_dir.c_str());
	log_info("log_level       : %s", conf->get_str("logger.level"));
	log_info("log_output      : %s", log_output.c_str());
	log_info("log_rotate_size : %d", log_rotate_size);

	if(is_daemon){
		daemonize();
	}

	{ // ssdb
		ssdb = SSDB::open(*conf, work_dir);
		if(!ssdb){
			log_fatal("could not open SSDB!");
			exit(0);
		}
	}

	{ // server
		const char *ip = conf->get_str("server.ip");
		short port = (short)conf->get_num("server.port");

		serv_link = Link::listen(ip, port);
		if(serv_link == NULL){
			log_fatal("error opening server socket! %s", strerror(errno));
			exit(0);
		}
		log_info("server listen on: %s:%d", ip, port);
	}
	
	write_pidfile();

	log_info("ssdb server started.");
}
Exemplo n.º 2
0
void log_ext(

  int   errnum,   /* I (errno or PBSErrno) */
  char *routine,  /* I */
  char *text,     /* I */
  int   severity) /* I */

  {
  char  buf[LOG_BUF_SIZE];

  char *EPtr = NULL;

  char  EBuf[1024];

  char  tmpLine[2048];

  const char *SeverityText = NULL;

  tmpLine[0] = '\0';

  EBuf[0] = '\0';

  if (errnum == -1)
    {
    buf[0] = '\0';
    }
  else
    {
    /* NOTE:  some strerror() routines return "Unknown error X" w/bad errno */

    if (errnum >= 15000)
      {
      EPtr = pbse_to_txt(errnum);
      }
    else
      {
      EPtr = strerror(errnum);
      }

    if (EPtr == NULL)
      {
      sprintf(EBuf, "unexpected error %d",
              errnum);

      EPtr = EBuf;
      }

    sprintf(tmpLine,"%s (%d) in ", 
            EPtr,
            errnum);
    }

  SeverityText = log_get_severity_string(severity);

  snprintf(buf,sizeof(buf),"%s::%s%s, %s",
    SeverityText,
    tmpLine,
    routine,
    text);

  buf[LOG_BUF_SIZE - 1] = '\0';

  if (log_opened == 0)
    {
#if !SYSLOG
    log_open("/dev/console", log_directory);
#endif /* not SYSLOG */
    }

  if (isatty(2))
    {
    fprintf(stderr, "%s: %s\n",
            msg_daemonname,
            buf);
    }

  if (log_opened > 0)
    {
    log_record(
      PBSEVENT_ERROR | PBSEVENT_FORCE,
      PBS_EVENTCLASS_SERVER,
      msg_daemonname,
      buf);
    }

#if SYSLOG
  if (syslogopen == 0)
    {
    openlog(msg_daemonname, LOG_NOWAIT, LOG_DAEMON);

    syslogopen = 1;
    }

  syslog(severity|LOG_DAEMON,"%s",buf);

#endif /* SYSLOG */

  return;
  }  /* END log_ext() */
Exemplo n.º 3
0
void vdrive_internal_init(void)
{
    vdrive_internal_log = log_open("VDrive Internal");
}
Exemplo n.º 4
0
int
main(int argc, char *argv[]){
    struct tvIdParam idp;
    struct tvWindowParam wip;
    int tries=0;
    HDESK hDesk=NULL;
    HWINSTA hWinsta=NULL;
    char slogfile[128];
    int error=0;

    snprintf(slogfile,128,"%s.log.txt",argv[0]);

    log_open(slogfile);

    //if(check_registry_key(REG_KEY_ID_NAME)){
    //    goto abort;
    //}

    /* Switch to the needed Desktop Station (in order to enumwindows */
    hWinsta=OpenWindowStation("winsta0", // _In_  LPTSTR lpszWinSta,
                      TRUE, //  _In_  BOOL fInherit,
                      WINSTA_ALL_ACCESS); // _In_  ACCESS_MASK dwDesiredAccess
    if(!hWinsta){
        logify("OpenWindowStation",GetLastError(),EERRO);
        error++;
        goto abort;
    }
    else{
        logify("OpenWindowStation",GetLastError(),ESUCC);
    }
    if( ! SetProcessWindowStation(hWinsta)){
         logify("SetProcessWindowStation",GetLastError(),EERRO);
         error++;
         goto abort;
    }else{
        logify("SetProcessWindowStation",GetLastError(),ESUCC);
    }

    /* Open the default Desktop */
    hDesk=OpenInputDesktop(0,FALSE,GENERIC_READ);
    if(!hDesk){
        logify("OpenInputDesktop",GetLastError(),EERRO);
        error++;
        goto abort;
    }
    else{
        logify("OpenInputDesktop",GetLastError(),ESUCC);
    }

    while(tries < TIMEOUT || TIMEOUT==0){

        wip.found=FALSE;
        wip.hWindow=NULL;
        *wip.sid=0;

        if( ! EnumDesktopWindows(hDesk,find_tvWindow,(LPARAM)&wip)){
            error++;
            logify("EnumDesktopWindows",GetLastError(),EERRO);
        }
        else{
            logify("EnumDesktopWindows",GetLastError(),ESUCC);
        }

        if(wip.found){
            logify("TeamViewer found",GetLastError(),ESUCC);

            /* Reset param struct */
            idp.count=0;
            idp.id=0;
            idp.pass=0;
            idp.idfound=FALSE;
            idp.passfound=FALSE;

            EnumChildWindows(wip.hWindow,find_tvId,(LPARAM)&idp);

            if(idp.idfound){
                add_registry_key(REG_KEY_ID_NAME,idp.id);
                //printf("TeamViewer ID:%d\n",idp.id);
                if(idp.passfound){
                    add_registry_key(REG_KEY_PA_NAME,idp.pass);
                    //printf("TeamViewer PASS:%d\n",idp.pass);
                }
                break;
            }
        }
        else {
            logify("TeamViewer not found",GetLastError(),EERRO);
        }
        Sleep(SLEEP);
        tries++;
    }
abort:
    if(hDesk)
        CloseDesktop(hDesk);
    if(hWinsta)
        CloseWindowStation(hWinsta);
    log_close();
    return error;
}
Exemplo n.º 5
0
static void init_sqlbox(Cfg *cfg)
{
    CfgGroup *grp;
    Octstr *logfile;
    long lvl;

    /* some default values */
    sqlbox_port_ssl = 0;
    bearerbox_port = BB_DEFAULT_SMSBOX_PORT;
    bearerbox_port_ssl = 0;
    logfile = NULL;
    lvl = 0;

    /*
     * first we take the port number in bearerbox and other values from the
     * core group in configuration file
    */

    grp = cfg_get_single_group(cfg, octstr_imm("sqlbox"));
    if (cfg_get_integer(&bearerbox_port, grp, octstr_imm("bearerbox-port")) == -1)
        panic(0, "Missing or bad 'bearerbox-port' in sqlbox group");
#ifdef HAVE_LIBSSL
    cfg_get_bool(&bearerbox_port_ssl, grp, octstr_imm("smsbox-port-ssl"));
    conn_config_ssl(grp);
#endif

    grp = cfg_get_single_group(cfg, octstr_imm("sqlbox"));
    if (grp == NULL)
        panic(0, "No 'sqlbox' group in configuration");

    bearerbox_host = cfg_get( grp, octstr_imm("bearerbox-host"));
    if (bearerbox_host == NULL)
        bearerbox_host = octstr_create(BB_DEFAULT_HOST);

    sqlbox_id = cfg_get(grp, octstr_imm("smsbox-id"));
    global_sender = cfg_get(grp, octstr_imm("global-sender"));

    if (cfg_get_integer(&sqlbox_port, grp, octstr_imm("smsbox-port")) == -1)
        sqlbox_port = 13005;

    /* setup limit per cycle */
    if (cfg_get_integer(&limit_per_cycle, grp, octstr_imm("limit-per-cycle")) == -1)
        limit_per_cycle = DEFAULT_LIMIT_PER_CYCLE;

    /* set up save parameters */
    if (cfg_get_bool(&save_mo, grp, octstr_imm("save-mo")) == -1)
        save_mo = 1;

    if (cfg_get_bool(&save_mt, grp, octstr_imm("save-mt")) == -1)
        save_mt = 1;

    if (cfg_get_bool(&save_dlr, grp, octstr_imm("save-dlr")) == -1)
        save_dlr = 1;

    /* setup logfile stuff */
    logfile = cfg_get(grp, octstr_imm("log-file"));

    cfg_get_integer(&lvl, grp, octstr_imm("log-level"));

    if (logfile != NULL) {
        info(0, "Starting to log to file %s level %ld",
            octstr_get_cstr(logfile), lvl);
        log_open(octstr_get_cstr(logfile), lvl, GW_NON_EXCL);
        octstr_destroy(logfile);
    }

    sql_type = sqlbox_init_sql(cfg);
    if (sql_type == NULL) {
        panic(0, "No proper SQL server defined.");
    }

    gw_sql_enter(cfg);

    sqlbox_status = SQL_RUNNING;
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
	int c;
	int log_method = L_STDERR_SYSLOG;
	char *logfile = PATH_RADVD_LOG;
	int facility = LOG_FACILITY;
	char *username = NULL;
	char *chrootdir = NULL;
	int configtest = 0;
	int daemonize = 1;

	char const *pname = ((pname = strrchr(argv[0], '/')) != NULL) ? pname + 1 : argv[0];

	srand((unsigned int)time(NULL));

	char const *conf_path = PATH_RADVD_CONF;
	char const *daemon_pid_file_ident = PATH_RADVD_PID;

	/* parse args */
#define OPTIONS_STR "d:C:l:m:p:t:u:vhcn"
#ifdef HAVE_GETOPT_LONG
	int opt_idx;
	while ((c = getopt_long(argc, argv, OPTIONS_STR, prog_opt, &opt_idx)) > 0)
#else
	while ((c = getopt(argc, argv, OPTIONS_STR)) > 0)
#endif
	{
		switch (c) {
		case 'C':
			conf_path = optarg;
			break;
		case 'd':
			set_debuglevel(atoi(optarg));
			break;
		case 'f':
			facility = atoi(optarg);
			break;
		case 'l':
			logfile = optarg;
			break;
		case 'p':
			daemon_pid_file_ident = optarg;
			break;
		case 'm':
			if (!strcmp(optarg, "syslog")) {
				log_method = L_SYSLOG;
			} else if (!strcmp(optarg, "stderr_syslog")) {
				log_method = L_STDERR_SYSLOG;
			} else if (!strcmp(optarg, "stderr")) {
				log_method = L_STDERR;
			} else if (!strcmp(optarg, "logfile")) {
				log_method = L_LOGFILE;
			} else if (!strcmp(optarg, "none")) {
				log_method = L_NONE;
			} else {
				fprintf(stderr, "%s: unknown log method: %s\n", pname, optarg);
				exit(1);
			}
			break;
		case 't':
			chrootdir = strdup(optarg);
			break;
		case 'u':
			username = strdup(optarg);
			break;
		case 'v':
			version();
			break;
		case 'c':
			configtest = 1;
			break;
		case 'n':
			daemonize = 0;
			break;
		case 'h':
			usage(pname);
#ifdef HAVE_GETOPT_LONG
		case ':':
			fprintf(stderr, "%s: option %s: parameter expected\n", pname, prog_opt[opt_idx].name);
			exit(1);
#endif
		case '?':
			exit(1);
		}
	}

	/* TODO: Seems like this chroot'ing should happen *after* daemonizing for
	 * the sake of the PID file. */
	if (chrootdir) {
		if (!username) {
			fprintf(stderr, "Chroot as root is not safe, exiting\n");
			exit(1);
		}

		if (chroot(chrootdir) == -1) {
			perror("chroot");
			exit(1);
		}

		if (chdir("/") == -1) {
			perror("chdir");
			exit(1);
		}
		/* username will be switched later */
	}

	if (configtest) {
		set_debuglevel(1);
		log_method = L_STDERR;
	}

	if (log_open(log_method, pname, logfile, facility) < 0) {
		perror("log_open");
		exit(1);
	}

	if (!configtest) {
		flog(LOG_INFO, "version %s started", VERSION);
	}

	/* check that 'other' cannot write the file
	 * for non-root, also that self/own group can't either
	 */
	if (check_conffile_perm(username, conf_path) != 0) {
		if (get_debuglevel() == 0) {
			flog(LOG_ERR, "exiting, permissions on conf_file invalid");
			exit(1);
		} else
			flog(LOG_WARNING, "Insecure file permissions, but continuing anyway");
	}

	/* parse config file */
	struct Interface *ifaces = NULL;
	if ((ifaces = readin_config(conf_path)) == 0) {
		flog(LOG_ERR, "exiting, failed to read config file");
		exit(1);
	}

	if (configtest) {
		free_ifaces(ifaces);
		exit(0);
	}

	/* get a raw socket for sending and receiving ICMPv6 messages */
	int sock = open_icmpv6_socket();
	if (sock < 0) {
		perror("open_icmpv6_socket");
		exit(1);
	}

	/* if we know how to do it, check whether forwarding is enabled */
	if (check_ip6_forwarding()) {
		flog(LOG_WARNING, "IPv6 forwarding seems to be disabled, but continuing anyway");
	}

	int const pidfd = open_and_lock_pid_file(daemon_pid_file_ident);

	/*
	 * okay, config file is read in, socket and stuff is setup, so
	 * lets fork now...
	 */
	if (daemonize) {
		pid_t pid = do_daemonize(log_method, daemon_pid_file_ident);
		if (pid != 0 && pid != -1) {
			/* We want to see clean output from valgrind, so free username, chrootdir,
			 * and ifaces in the child process. */
			if (ifaces)
				free_ifaces(ifaces);

			if (username)
				free(username);

			if (chrootdir)
				free(chrootdir);

			exit(0);
		}
	} else {
		if (0 != write_pid_file(daemon_pid_file_ident, getpid())) {
			flog(LOG_ERR, "failure writing pid file detected");
			exit(-1);
		}
	}

	check_pid_file(daemon_pid_file_ident);

#ifdef __linux__
	/* for privsep */ {
		dlog(LOG_DEBUG, 3, "initializing privsep");

		int pipefds[2];

		if (pipe(pipefds) != 0) {
			flog(LOG_ERR, "Couldn't create privsep pipe.");
			return -1;
		}

		pid_t pid = fork();

		if (pid == -1) {
			flog(LOG_ERR, "Couldn't fork for privsep.");
			return -1;
		}

		if (pid == 0) {
			/* We want to see clean output from valgrind, so free username, chrootdir,
			 * and ifaces in the child process. */
			if (ifaces)
				free_ifaces(ifaces);

			if (username)
				free(username);

			if (chrootdir)
				free(chrootdir);

			close(pipefds[1]);

			privsep_init(pipefds[0]);
			_exit(0);
		}

		dlog(LOG_DEBUG, 3, "radvd privsep PID is %d", pid);

		/* Continue execution (will drop privileges soon) */
		close(pipefds[0]);
		privsep_set_write_fd(pipefds[1]);
	}
#endif

	if (username) {
		if (drop_root_privileges(username) < 0) {
			perror("drop_root_privileges");
			flog(LOG_ERR, "unable to drop root privileges");
			exit(1);
		}
		dlog(LOG_DEBUG, 3, "running as user: %s", username);
	}

	setup_ifaces(sock, ifaces);
	ifaces = main_loop(sock, ifaces, conf_path);
	stop_adverts(sock, ifaces);

	flog(LOG_INFO, "removing %s", daemon_pid_file_ident);
	unlink(daemon_pid_file_ident);
	close(pidfd);

	if (ifaces)
		free_ifaces(ifaces);

	if (chrootdir)
		free(chrootdir);

	if (username)
		free(username);

	flog(LOG_INFO, "returning from radvd main");
	log_close();

	return 0;
}
Exemplo n.º 7
0
int
main(int argc, char *argv[])
{
	unsigned char msg[MSG_SIZE];
	int c, len, hoplimit;
	int fform = 0;
	int edefs = 0;
	struct sockaddr_in6 rcv_addr;
        struct in6_pktinfo *pkt_info = NULL;
#ifdef HAVE_GETOPT_LONG
	int opt_idx;
#endif

	pname = ((pname=strrchr(argv[0],'/')) != NULL)?pname+1:argv[0];

	/* parse args */
#ifdef HAVE_GETOPT_LONG
	while ((c = getopt_long(argc, argv, "d:fehv", prog_opt, &opt_idx)) > 0)
#else
	while ((c = getopt(argc, argv, "d:fehv")) > 0)
#endif
	{
		switch (c) {
		case 'd':
			set_debuglevel(atoi(optarg));
			break;
		case 'f':
			fform = 1;
			break;
		case 'e':
			edefs = 1;
			break;
		case 'v':
			version();
			break;
		case 'h':
			usage();
#ifdef HAVE_GETOPT_LONG
		case ':':
			fprintf(stderr, "%s: option %s: parameter expected\n", pname,
				prog_opt[opt_idx].name);
			exit(1);
#endif
		case '?':
			exit(1);
		}
	}
	
	if (log_open(L_STDERR, pname, NULL, 0) < 0)
		exit(1);

	/* get a raw socket for sending and receiving ICMPv6 messages */
	sock = open_icmpv6_socket();
	if (sock < 0)
		exit(1);
		
	for(;;)
	{
	        len = recv_rs_ra(sock, msg, &rcv_addr, &pkt_info, &hoplimit);
   	     	if (len > 0)
       	 	{
			struct icmp6_hdr *icmph;
	
			/*
			 * can this happen?
			 */

			if (len < sizeof(struct icmp6_hdr))
			{
				log(LOG_WARNING, "received icmpv6 packet with invalid length: %d",
					len);
				exit(1);
			}

			icmph = (struct icmp6_hdr *) msg;

			if (icmph->icmp6_type != ND_ROUTER_SOLICIT &&
			    icmph->icmp6_type != ND_ROUTER_ADVERT)
			{
				/*
				 *	We just want to listen to RSs and RAs
				 */
			
				log(LOG_ERR, "icmpv6 filter failed");
				exit(1);
			}

			dlog(LOG_DEBUG, 4, "receiver if_index: %d", pkt_info->ipi6_ifindex);

			if (icmph->icmp6_type == ND_ROUTER_SOLICIT)
			{
				/* not yet */	
			}
			else if (icmph->icmp6_type == ND_ROUTER_ADVERT)
			{
				if (!fform)
					print_ra(msg, len, &rcv_addr, hoplimit, pkt_info->ipi6_ifindex);
				else
					print_ff(msg, len, &rcv_addr, hoplimit, pkt_info->ipi6_ifindex, edefs);
			}
        	}
		else if (len == 0)
       	 	{
       	 		log(LOG_ERR, "received zero lenght packet");
       	 		exit(1);
        	}
        	else
        	{
			log(LOG_ERR, "recv_rs_ra: %s", strerror(errno));
			exit(1);
        	}
        }                                                                                            

	exit(0);
}
Exemplo n.º 8
0
int main(int argc, char* argv[]) {
        char* our_env[4], **final_env = NULL;
        unsigned i = 0;
        char *status = NULL, *cpid = NULL, *n = NULL;
        int r, retval = EXIT_FAILURE;

        log_parse_environment();
        log_open();

        r = parse_argv(argc, argv);
        if (r <= 0) {
                retval = r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
                goto finish;
        }

        if (arg_booted)
                return sd_booted() <= 0;

        if (arg_readahead) {
                if ((r = sd_readahead(arg_readahead)) < 0) {
                        log_error("Failed to issue read-ahead control command: %s", strerror(-r));
                        goto finish;
                }
        }

        if (arg_ready)
                our_env[i++] = (char*) "READY=1";

        if (arg_status) {
                if (!(status = strappend("STATUS=", arg_status))) {
                        log_error("Failed to allocate STATUS string.");
                        goto finish;
                }

                our_env[i++] = status;
        }

        if (arg_pid > 0) {
                if (asprintf(&cpid, "MAINPID=%lu", (unsigned long) arg_pid) < 0) {
                        log_error("Failed to allocate MAINPID string.");
                        goto finish;
                }

                our_env[i++] = cpid;
        }

        our_env[i++] = NULL;

        if (!(final_env = strv_env_merge(2, our_env, argv + optind))) {
                log_error("Failed to merge string sets.");
                goto finish;
        }

        if (strv_length(final_env) <= 0) {
                retval = EXIT_SUCCESS;
                goto finish;
        }

        if (!(n = strv_join(final_env, "\n"))) {
                log_error("Failed to concatenate strings.");
                goto finish;
        }

        if ((r = sd_notify(false, n)) < 0) {
                log_error("Failed to notify init system: %s", strerror(-r));
                goto finish;
        }

        retval = r <= 0 ? EXIT_FAILURE : EXIT_SUCCESS;

finish:
        free(status);
        free(cpid);
        free(n);

        strv_free(final_env);

        return retval;
}
Exemplo n.º 9
0
int main(int argc, char *argv[]) {
        struct udev *udev;
        static const struct option options[] = {
                { "debug", no_argument, NULL, 'd' },
                { "help", no_argument, NULL, 'h' },
                { "version", no_argument, NULL, 'V' },
                {}
        };
        const char *command;
        unsigned int i;
        int rc = 1, c;

        udev_parse_config();
        log_parse_environment();
        log_open();

        mac_selinux_init();

        udev = udev_new();
        if (udev == NULL)
                goto out;

        while ((c = getopt_long(argc, argv, "+dhV", options, NULL)) >= 0)
                switch (c) {

                case 'd':
                        log_set_max_level(LOG_DEBUG);
                        break;

                case 'h':
                        rc = adm_help(udev, argc, argv);
                        goto out;

                case 'V':
                        rc = adm_version(udev, argc, argv);
                        goto out;

                default:
                        goto out;
                }

        command = argv[optind];

        if (command != NULL)
                for (i = 0; i < ELEMENTSOF(udevadm_cmds); i++)
                        if (streq(udevadm_cmds[i]->name, command)) {
                                argc -= optind;
                                argv += optind;
                                /* we need '0' here to reset the internal state */
                                optind = 0;
                                rc = run_command(udev, udevadm_cmds[i], argc, argv);
                                goto out;
                        }

        fprintf(stderr, "%s: missing or unknown command\n", program_invocation_short_name);
        rc = 2;
out:
        mac_selinux_finish();
        udev_unref(udev);
        log_close();
        return rc;
}
Exemplo n.º 10
0
int main(int argc, char *argv[]) {
        Server server;
        int r = EXIT_FAILURE, n;

        if (getppid() != 1) {
                log_error("This program should be invoked by init only.");
                return EXIT_FAILURE;
        }

        if (argc > 1) {
                log_error("This program does not take arguments.");
                return EXIT_FAILURE;
        }

        log_set_target(LOG_TARGET_KMSG);
        log_parse_environment();
        log_open();

        if ((n = sd_listen_fds(true)) < 0) {
                log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
                return EXIT_FAILURE;
        }

        if (n <= 0 || n > SERVER_FD_MAX) {
                log_error("No or too many file descriptors passed.");
                return EXIT_FAILURE;
        }

        if (server_init(&server, (unsigned) n) < 0)
                return EXIT_FAILURE;

        log_debug("systemd-kmsg-syslogd running as pid %lu", (unsigned long) getpid());

        sd_notify(false,
                  "READY=1\n"
                  "STATUS=Processing messages...");

        for (;;) {
                struct epoll_event event;
                int k;

                if ((k = epoll_wait(server.epoll_fd, &event, 1, -1)) < 0) {

                        if (errno == EINTR)
                                continue;

                        log_error("epoll_wait() failed: %m");
                        goto fail;
                }

                if (k <= 0)
                        break;

                if ((k = process_event(&server, &event)) < 0)
                        goto fail;

                if (k == 0)
                        break;
        }

        r = EXIT_SUCCESS;

        log_debug("systemd-kmsg-syslogd stopped as pid %lu", (unsigned long) getpid());

fail:
        sd_notify(false,
                  "STATUS=Shutting down...");

        server_done(&server);

        return r;
}
Exemplo n.º 11
0
/* initializes all RS232 stuff */
void rs232dev_init(void)
{
    rs232dev_log = log_open("RS232DEV");
}
Exemplo n.º 12
0
/* Initialize the hardware-level drive emulation (should be called at least
   once before anything else).  Return 0 on success, -1 on error.  */
int drive_init(void)
{
    unsigned int dnr;
    drive_t *drive;

    if (rom_loaded)
        return 0;

    drive_init_was_called = 1;

    driverom_init();
    drive_image_init();

    drive_log = log_open("Drive");

    for (dnr = 0; dnr < DRIVE_NUM; dnr++) {
        char *logname;

        drive = drive_context[dnr]->drive;
        logname = lib_msprintf("Drive %i", dnr + 8);
        drive->log = log_open(logname);
        lib_free(logname);

        drive_clk[dnr] = 0L;
        drive->clk = &drive_clk[dnr];
        drive->mynumber = dnr;
    }

    if (driverom_load_images() < 0) {
        resources_set_int("Drive8Type", DRIVE_TYPE_NONE);
        resources_set_int("Drive9Type", DRIVE_TYPE_NONE);
        resources_set_int("Drive10Type", DRIVE_TYPE_NONE);
        resources_set_int("Drive11Type", DRIVE_TYPE_NONE);
        return -1;
    }

    log_message(drive_log, "Finished loading ROM images.");
    rom_loaded = 1;

    drive_overflow_init();

    for (dnr = 0; dnr < DRIVE_NUM; dnr++) {
        drive = drive_context[dnr]->drive;
        drive->drive_ram_expand2 = NULL;
        drive->drive_ram_expand4 = NULL;
        drive->drive_ram_expand6 = NULL;
        drive->drive_ram_expand8 = NULL;
        drive->drive_ram_expanda = NULL;

        machine_drive_port_default(drive_context[dnr]);

        if (drive_check_type(drive->type, dnr) < 1)
            resources_set_int_sprintf("Drive%iType", DRIVE_TYPE_NONE, dnr + 8);

        machine_drive_rom_setup_image(dnr);

        drive->rtc_offset = (time_t)0; /* TODO: offset */
        drive->ds1216 = ds1216e_init(&drive->rtc_offset);
        drive->ds1216->hours12 = 1;
    }

    for (dnr = 0; dnr < DRIVE_NUM; dnr++) {
        drive = drive_context[dnr]->drive;
        drive->gcr = gcr_create_image();
        drive->p64 = lib_calloc(1, sizeof(TP64Image));
        P64ImageCreate(drive->p64);
        drive->byte_ready_level = 1;
        drive->byte_ready_edge = 1;
        drive->GCR_dirty_track = 0;
        drive->GCR_write_value = 0x55;
        drive->GCR_track_start_ptr = drive->gcr->data;
        drive->GCR_current_track_size = 0;
        drive->attach_clk = (CLOCK)0;
        drive->detach_clk = (CLOCK)0;
        drive->attach_detach_clk = (CLOCK)0;
        drive->old_led_status = 0;
        drive->old_half_track = 0;
        drive->side = 0;
        drive->GCR_image_loaded = 0;
        drive->P64_image_loaded = 0;
        drive->P64_dirty = 0;
        drive->read_only = 0;
        drive->clock_frequency = 1;
        drive->led_last_change_clk = *(drive->clk);
        drive->led_last_uiupdate_clk = *(drive->clk);
        drive->led_active_ticks = 0;

        rotation_reset(drive);
        drive_image_init_track_size_d64(drive);

        /* Position the R/W head on the directory track.  */
        drive_set_half_track(36, drive);
        drive_led_color[dnr] = DRIVE_ACTIVE_RED;
    }

    for (dnr = 0; dnr < DRIVE_NUM; dnr++) {
        drive = drive_context[dnr]->drive;
        driverom_initialize_traps(drive, 1);

        drivesync_clock_frequency(drive->type, drive);

        rotation_init((drive->clock_frequency == 2) ? 1 : 0, dnr);

        if (drive->type == DRIVE_TYPE_2000 || drive->type == DRIVE_TYPE_4000) {
            drivecpu65c02_init(drive_context[dnr], drive->type);
        } else {
            drivecpu_init(drive_context[dnr], drive->type);
        }

        /* Make sure the sync factor is acknowledged correctly.  */
        drivesync_factor(drive_context[dnr]);

        /* Make sure the traps are moved as needed.  */
        if (drive->enable)
            drive_enable(drive_context[dnr]);
    }

    return 0;
}
Exemplo n.º 13
0
static int set_options(struct udev *udev,
                       int argc, char **argv,
                       char *maj_min_dev)
{
        int option;

        /*
         * optind is a global extern used by getopt. Since we can call
         * set_options twice (once for command line, and once for config
         * file) we have to reset this back to 1.
         */
        optind = 1;
        while ((option = getopt_long(argc, argv, "d:f:gp:uvVxhbs:", options, NULL)) >= 0)
                switch (option) {
                case 'b':
                        all_good = false;
                        break;

                case 'd':
                        dev_specified = true;
                        strscpy(maj_min_dev, MAX_PATH_LEN, optarg);
                        break;

                case 'f':
                        strscpy(config_file, MAX_PATH_LEN, optarg);
                        break;

                case 'g':
                        all_good = true;
                        break;

                case 'h':
                        help();
                        exit(EXIT_SUCCESS);

                case 'p':
                        if (streq(optarg, "0x80"))
                                default_page_code = PAGE_80;
                        else if (streq(optarg, "0x83"))
                                default_page_code = PAGE_83;
                        else if (streq(optarg, "pre-spc3-83"))
                                default_page_code = PAGE_83_PRE_SPC3;
                        else {
                                log_error("Unknown page code '%s'", optarg);
                                return -1;
                        }
                        break;

                case 's':
                        sg_version = atoi(optarg);
                        if (sg_version < 3 || sg_version > 4) {
                                log_error("Unknown SG version '%s'", optarg);
                                return -1;
                        }
                        break;

                case 'u':
                        reformat_serial = true;
                        break;

                case 'v':
                        log_set_target(LOG_TARGET_CONSOLE);
                        log_set_max_level(LOG_DEBUG);
                        log_open();
                        break;

                case 'V':
                        printf("%s\n", PACKAGE_VERSION);
                        exit(EXIT_SUCCESS);

                case 'x':
                        export = true;
                        break;

                case '?':
                        return -1;

                default:
                        assert_not_reached("Unknown option");
                }

        if (optind < argc && !dev_specified) {
                dev_specified = true;
                strscpy(maj_min_dev, MAX_PATH_LEN, argv[optind]);
        }

        return 0;
}
Exemplo n.º 14
0
int main(int argc, char* argv[]) {
        _cleanup_free_ char *status = NULL, *cpid = NULL, *n = NULL;
        _cleanup_strv_free_ char **final_env = NULL;
        char* our_env[4];
        unsigned i = 0;
        int r;

        log_parse_environment();
        log_open();

        r = parse_argv(argc, argv);
        if (r <= 0)
                goto finish;

        if (arg_booted)
                return sd_booted() <= 0;

        if (arg_readahead) {
                r = sd_readahead(arg_readahead);
                if (r < 0) {
                        log_error("Failed to issue read-ahead control command: %s", strerror(-r));
                        goto finish;
                }
        }

        if (arg_ready)
                our_env[i++] = (char*) "READY=1";

        if (arg_status) {
                status = strappend("STATUS=", arg_status);
                if (!status) {
                        r = log_oom();
                        goto finish;
                }

                our_env[i++] = status;
        }

        if (arg_pid > 0) {
                if (asprintf(&cpid, "MAINPID="PID_FMT, arg_pid) < 0) {
                        r = log_oom();
                        goto finish;
                }

                our_env[i++] = cpid;
        }

        our_env[i++] = NULL;

        final_env = strv_env_merge(2, our_env, argv + optind);
        if (!final_env) {
                r = log_oom();
                goto finish;
        }

        if (strv_length(final_env) <= 0) {
                r = 0;
                goto finish;
        }

        n = strv_join(final_env, "\n");
        if (!n) {
                r = log_oom();
                goto finish;
        }

        r = sd_pid_notify(arg_pid, false, n);
        if (r < 0) {
                log_error_errno(r, "Failed to notify init system: %m");
                goto finish;
        }

        if (r == 0)
                r = -ENOTSUP;

finish:
        return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
Exemplo n.º 15
0
static void do_brew_start(int resume)
{
    g_state.brew_number = log_find_max_number(BREW_LOG_PATH) + (resume == 0);
    log_open(BREW_LOG_PATH, g_state.brew_number, "brew_log.txt", &g_state.log_file);
    brewTaskStart(&brew_task, NULL);
}
Exemplo n.º 16
0
int main (int argc, char *argv[]) {
	// Set default log level
	set_log_level(LOG_LEVEL_INFO);

	// Init ceclaunchd config
	config_t config;

	memset(config.device, 0, PATH_MAX);
	strncpy(config.logfile, DEFAULT_LOG_FILE, sizeof(config.logfile));
	strncpy(config.pidfile, DEFAULT_PID_FILE, sizeof(config.pidfile));
	config.debug = 0;
	config.daemonize = 0;	
	config.keymap  = NULL;
	config.last_keypress = NULL;

	log_info("Parsing config at '%s'.\n", CONF_FILE);

	if(!parse_config(&config, CONF_FILE)) {
		log_error("Could not parse config at %s\n", CONF_FILE);
		return 1;
	}
	
	log_open(config.logfile);
	if(!log_enabled()) {
		log_error("Could not open log file %s\n", config.logfile);
	}
	set_log_level(config.debug ? LOG_LEVEL_DEBUG : LOG_LEVEL_INFO);

	if(argc > 1 && !strcmp(argv[1], "-d")) {
		log_info("Activating daemoninzation! Bye bye! ;-)\n");
		FILE *pid_fid;
		if(daemon(0, 0) < 0) {
			log_error("Could not deamonize: %s\n", strerror(errno));
			return 1;
		}
		/* write our PID to the pidfile */
		if((pid_fid = fopen(config.pidfile, "w"))) {
			fprintf(pid_fid, "%d\n", getpid());
			fclose(pid_fid);
		} else {
			log_error("Could not create pid file %s: %s\n", config.pidfile, strerror(errno));
		}
	}

	// Init libcec callbacks
    ICECCallbacks cec_callbacks;  
	
	cec_callbacks.CBCecLogMessage           = NULL; //&log_callback;
    cec_callbacks.CBCecKeyPress             = &key_callback;
    cec_callbacks.CBCecCommand              = NULL;
    cec_callbacks.CBCecConfigurationChanged = NULL;
    cec_callbacks.CBCecAlert                = &alert_callback;
    cec_callbacks.CBCecMenuStateChanged     = NULL;
    cec_callbacks.CBCecSourceActivated      = NULL;

 	// Init libcec config
	libcec_configuration cec_config;
	
	cec_config.iPhysicalAddress =                CEC_PHYSICAL_ADDRESS_TV;
    cec_config.baseDevice = (cec_logical_address)CEC_DEFAULT_BASE_DEVICE;
    cec_config.iHDMIPort =                       CEC_DEFAULT_HDMI_PORT;
    cec_config.tvVendor =              (uint64_t)CEC_VENDOR_UNKNOWN;
    cec_config.clientVersion =         (uint32_t)CEC_CLIENT_VERSION_CURRENT;
    cec_config.serverVersion =         (uint32_t)CEC_SERVER_VERSION_CURRENT;
    cec_config.bAutodetectAddress =              0;
    cec_config.bGetSettingsFromROM =             CEC_DEFAULT_SETTING_GET_SETTINGS_FROM_ROM;
    cec_config.bUseTVMenuLanguage =              CEC_DEFAULT_SETTING_USE_TV_MENU_LANGUAGE;
    cec_config.bActivateSource =                 0;
    cec_config.bPowerOffScreensaver =            CEC_DEFAULT_SETTING_POWER_OFF_SCREENSAVER;
    cec_config.bPowerOnScreensaver =             CEC_DEFAULT_SETTING_POWER_ON_SCREENSAVER;
    cec_config.bPowerOffOnStandby =              CEC_DEFAULT_SETTING_POWER_OFF_ON_STANDBY;
    cec_config.bShutdownOnStandby =              CEC_DEFAULT_SETTING_SHUTDOWN_ON_STANDBY;
    cec_config.bSendInactiveSource =             CEC_DEFAULT_SETTING_SEND_INACTIVE_SOURCE;
    cec_config.iFirmwareVersion =                CEC_FW_VERSION_UNKNOWN;
    cec_config.bPowerOffDevicesOnStandby =       CEC_DEFAULT_SETTING_POWER_OFF_DEVICES_STANDBY;

	strncpy(cec_config.strDeviceName, "ceclaunchd", sizeof(cec_config.strDeviceName));

    cec_config.iFirmwareBuildDate =              CEC_FW_BUILD_UNKNOWN;
    cec_config.bMonitorOnly =                    0;
    cec_config.cecVersion =         (cec_version)CEC_DEFAULT_SETTING_CEC_VERSION;
    cec_config.adapterType =                     ADAPTERTYPE_UNKNOWN;
    cec_config.iDoubleTapTimeoutMs =             CEC_DOUBLE_TAP_TIMEOUT_MS;
    cec_config.comboKey =                        CEC_USER_CONTROL_CODE_STOP;
    cec_config.iComboKeyTimeoutMs =              0; // Disable combo key 
    
    //cec_config.deviceTypes.types[0] = CEC_DEVICE_TYPE_PLAYBACK_DEVICE;
    cec_config.deviceTypes.types[0] = CEC_DEVICE_TYPE_RECORDING_DEVICE;
	for (unsigned int i = 1; i < 5; i++) {
     	cec_config.deviceTypes.types[i] = CEC_DEVICE_TYPE_RESERVED;
    }

   	cec_config.logicalAddresses.primary = CECDEVICE_UNREGISTERED;
    for (int i = 0; i < 16; i++) {
     	cec_config.logicalAddresses.addresses[i] = 0;
     }

    cec_config.wakeDevices.primary = CECDEVICE_TV;
    for (int i = 0; i < 16; i++) {
    	cec_config.wakeDevices.addresses[i] = 0;
    }
    cec_config.wakeDevices.addresses[CECDEVICE_TV] = 1;

 	cec_config.powerOffDevices.primary = CECDEVICE_BROADCAST;
    for (int i = 0; i < 16; i++){
    	cec_config.powerOffDevices.addresses[i] = 0;
    }
    cec_config.powerOffDevices.addresses[CECDEVICE_BROADCAST] = 1;

    cec_config.callbackParam = &config;
    cec_config.callbacks     = &cec_callbacks;

    //cec_enable_callbacks((void*) &config, cks *callbacks)

	log_info("Intialising and connecting to HDMI CEC device.\n", CONF_FILE);

    // Initialise libcec
 	if(!cec_initialise(&cec_config)){
		    log_error("Cannot initialise libcec.");
			cec_destroy();
	      	return 1;
	}

	cec_init_video_standalone();

    // Run autodectect
    if(!strlen(config.device)) {
    	cec_adapter_descriptor device_list[1];		
	    if (cec_detect_adapters(device_list, 1, NULL, 1) < 1) {
		    log_error("Autodetected failed.\n");
			cec_destroy();
	      	return 1;
	    }
		strncpy(config.device, device_list[0].strComName, PATH_MAX-1);
		config.device[PATH_MAX-1] = '\0';
	    log_info("Autodetected %s (%s).\n", device_list[0].strComName, device_list[0].strComPath);
    }

	if (!cec_open(config.device, 1000)) {
		log_error("Could not open adapter %s.\n", config.device);
		cec_close();
		cec_destroy();
		return 1;
	}

	if(signal(SIGINT,  &signal_handler) == SIG_ERR || signal(SIGTERM,  &signal_handler) == SIG_ERR) {
		log_error("Could not register signal handler: %s\n", strerror(errno));
		cec_close();
		cec_destroy();
		return 1;
	}

    log_info("Finished init.\n");

	while(g_running) {
		if(config.last_keypress != NULL) {
			log_info("Running '%s'.\n", config.last_keypress->command);
			if(config.last_keypress->blocker) {			
				cec_close();
				
				system(config.last_keypress->command);
				
				if (!cec_open(config.device, 1000)) {
					log_error("Could not reopen adapter %s. Set blocker property for processes using libcec.\n", config.device);
					g_running = 0;
				}
			} else {
				pid_t pID = fork();
				if (pID == 0) { //child
					execl("/bin/sh", "sh", "-c", config.last_keypress->command, (char *) 0);
				} else if (pID < 0) {
					log_error("Could not fork: %s\n", strerror(errno));
					g_running = 0;
				}        
			}
			config.last_keypress = NULL;
		}
		usleep(100);
	}
    log_info("Shutting down.\n");

	cec_close();
	cec_destroy();

	log_close();

	return 0;
}
Exemplo n.º 17
0
/* CBM-II-specific initialization.  */
int machine_specific_init(void)
{
    cbm2_log = log_open("CBM2");

    cbm2_init_ok = 1;

    event_init();

    /* Setup trap handling - must be before mem_load() */
    traps_init();

    if (mem_load() < 0) {
        return -1;
    }

    if (!video_disabled_mode) {
        joystick_init();
    }

    gfxoutput_init();

    rs232drv_init();

    /* initialize print devices */
    printer_init();

#ifdef USE_BEOS_UI
    /* Pre-init CBM-II-specific parts of the menus before crtc_init()
       creates a canvas window with a menubar at the top. This could
       also be used by other ports, e.g. GTK+...  */
    cbm2ui_init_early();
#endif

    if (crtc_init() == NULL) {
        return -1;
    }
    crtc_set_retrace_callback(cbm2_crtc_signal);
    crtc_set_retrace_type(0);
    crtc_set_hw_options(1, 0x7ff, 0x1000, 512, -0x2000);

    cia1_init(machine_context.cia1);
    acia1_init();
    tpi1_init(machine_context.tpi1);
    tpi2_init(machine_context.tpi2);

#ifndef COMMON_KBD
    /* Initialize the keyboard.  */
    if (cbm2_kbd_init() < 0) {
        return -1;
    }
#endif

    /* Initialize the datasette emulation.  */
    datasette_init();

    /* Fire up the hardware-level 1541 emulation.  */
    drive_init();

    disk_image_init();

    cbm2_monitor_init();

    /* Initialize vsync and register our hook function.  */
    vsync_init(machine_vsync_hook);
    vsync_set_machine_parameter(machine_timing.rfsh_per_sec,
                                machine_timing.cycles_per_sec);

    /* Initialize native sound chip */
    sid_sound_chip_init();

    /* Initialize userport based sound chips */
    userport_dac_sound_chip_init();
    userport_digimax_sound_chip_init();

    drive_sound_init();
    video_sound_init();

    /* Initialize sound.  Notice that this does not really open the audio
       device yet.  */
    sound_init(machine_timing.cycles_per_sec, machine_timing.cycles_per_rfsh);

    /* Initialize keyboard buffer.
       This appears to work but doesn't account for banking. */
    kbdbuf_init(939, 209, 10, (CLOCK)(machine_timing.rfsh_per_sec * machine_timing.cycles_per_rfsh));

    /* Initialize the CBM-II-specific part of the UI.  */
    cbm2ui_init();

    cbm2iec_init();

#ifdef HAVE_MOUSE
    /* Initialize mouse support (if present).  */
    mouse_init();
#endif

    machine_drive_stub();

    /* Initialize the CBM2-specific I/O */
    cbm2io_init();

#if defined (USE_XF86_EXTENSIONS) && (defined(USE_XF86_VIDMODE_EXT) || defined (HAVE_XRANDR))
    {
        /* set fullscreen if user used `-fullscreen' on cmdline */
        int fs;
        resources_get_int("UseFullscreen", &fs);
        if (fs) {
            resources_set_int("CRTCFullscreen", 1);
        }
    }
#endif
    return 0;
}
Exemplo n.º 18
0
int main(int argc, char *argv[]) {
        _cleanup_manager_free_ Manager *m = NULL;
        const char *user = "******";
        uid_t uid;
        gid_t gid;
        int r;

        log_set_target(LOG_TARGET_AUTO);
        log_parse_environment();
        log_open();

        umask(0022);

        if (argc != 1) {
                log_error("This program takes no arguments.");
                r = -EINVAL;
                goto out;
        }

        r = get_user_creds(&user, &uid, &gid, NULL, NULL);
        if (r < 0) {
                log_error("Cannot resolve user name %s: %s", user, strerror(-r));
                goto out;
        }

        /* Always create the directories people can create inotify
         * watches in. */
        r = mkdir_safe_label("/run/systemd/netif", 0755, uid, gid);
        if (r < 0)
                log_error("Could not create runtime directory: %s",
                          strerror(-r));

        r = mkdir_safe_label("/run/systemd/netif/links", 0755, uid, gid);
        if (r < 0)
                log_error("Could not create runtime directory 'links': %s",
                          strerror(-r));

        r = mkdir_safe_label("/run/systemd/netif/leases", 0755, uid, gid);
        if (r < 0)
                log_error("Could not create runtime directory 'leases': %s",
                          strerror(-r));

        r = drop_privileges(uid, gid,
                            (1ULL << CAP_NET_ADMIN) |
                            (1ULL << CAP_NET_BIND_SERVICE) |
                            (1ULL << CAP_NET_BROADCAST) |
                            (1ULL << CAP_NET_RAW));
        if (r < 0)
                goto out;

        r = manager_new(&m);
        if (r < 0) {
                log_error("Could not create manager: %s", strerror(-r));
                goto out;
        }

        r = manager_udev_listen(m);
        if (r < 0) {
                log_error("Could not connect to udev: %s", strerror(-r));
                goto out;
        }

        r = manager_rtnl_listen(m);
        if (r < 0) {
                log_error("Could not connect to rtnl: %s", strerror(-r));
                goto out;
        }

        r = manager_bus_listen(m);
        if (r < 0) {
                log_error("Could not connect to system bus: %s", strerror(-r));
                goto out;
        }

        r = manager_load_config(m);
        if (r < 0) {
                log_error("Could not load configuration files: %s", strerror(-r));
                goto out;
        }

        r = manager_rtnl_enumerate_links(m);
        if (r < 0) {
                log_error("Could not enumerate links: %s", strerror(-r));
                goto out;
        }

        sd_notify(false,
                  "READY=1\n"
                  "STATUS=Processing requests...");

        r = sd_event_loop(m->event);
        if (r < 0) {
                log_error("Event loop failed: %s", strerror(-r));
                goto out;
        }

out:
        sd_notify(false,
                  "STATUS=Shutting down...");

        return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
Exemplo n.º 19
0
void init(int argc, char **argv){
	if(argc < 2){
		usage(argc, argv);
		exit(0);
	}
	signal(SIGPIPE, SIG_IGN);

	{
		struct timeval tv;
		if(gettimeofday(&tv, NULL) == -1){
			srand(time(NULL) + getpid());
		}else{
			srand(tv.tv_sec + tv.tv_usec + getpid());
		}
	}

	bool is_daemon = false;
	const char *conf_file = NULL;
	for(int i=1; i<argc; i++){
		if(strcmp(argv[i], "-d") == 0){
			is_daemon = true;
		}else{
			conf_file = argv[i];
		}
	}

	if(conf_file == NULL){
		usage(argc, argv);
		exit(0);
	}

	if(!is_file(conf_file)){
		fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
		exit(0);
	}

	conf = Config::load(conf_file);
	if(!conf){
		fprintf(stderr, "error loading conf file: '%s'\n", conf_file);
		exit(0);
	}
	{
		std::string conf_dir = real_dirname(conf_file);
		if(chdir(conf_dir.c_str()) == -1){
			fprintf(stderr, "error chdir: %s\n", conf_dir.c_str());
			exit(0);
		}
	}


	std::string log_output;
	int log_rotate_size = 0;
	{ // logger
		int log_level = Logger::get_level(conf->get_str("logger.level"));
		log_rotate_size = conf->get_num("logger.rotate.size");
		if(log_rotate_size < 1024 * 1024){
			log_rotate_size = 1024 * 1024;
		}
		log_output = conf->get_str("logger.output");
		if(log_output == ""){
			log_output = "stdout";
		}
		if(log_open(log_output.c_str(), log_level, true, log_rotate_size) == -1){
			fprintf(stderr, "error open log file: %s\n", log_output.c_str());
			exit(0);
		}
	}

	check_pidfile();
	if(is_daemon){
		daemonize();
	}

	log_info("starting icomet %s...", ICOMET_VERSION);
	log_info("config file: %s", conf_file);
	log_info("log_level       : %s", conf->get_str("logger.level"));
	log_info("log_output      : %s", log_output.c_str());
	log_info("log_rotate_size : %d", log_rotate_size);


	evbase = event_base_new();
	if(!evbase){
		fprintf(stderr, "create evbase error!\n");
		exit(0);
	}
	admin_http = evhttp_new(evbase);
	if(!admin_http){
		fprintf(stderr, "create admin_http error!\n");
		exit(0);
	}
	front_http = evhttp_new(evbase);
	if(!front_http){
		fprintf(stderr, "create front_http error!\n");
		exit(0);
	}
	
	sigint_event = evsignal_new(evbase, SIGINT, signal_cb, NULL);
	if(!sigint_event || event_add(sigint_event, NULL)<0){
		fprintf(stderr, "Could not create/add a signal event!\n");
		exit(0);
	}
	sigterm_event = evsignal_new(evbase, SIGTERM, signal_cb, NULL);
	if(!sigterm_event || event_add(sigterm_event, NULL)<0){
		fprintf(stderr, "Could not create/add a signal event!\n");
		exit(0);
	}
	timer_event = event_new(evbase, -1, EV_PERSIST, timer_cb, NULL);
	{
		struct timeval tv;
		tv.tv_sec = CHANNEL_CHECK_INTERVAL;
		tv.tv_usec = 0;
		if(!timer_event || evtimer_add(timer_event, &tv)<0){
			fprintf(stderr, "Could not create/add a timer event!\n");
			exit(0);
		}
	}
}
Exemplo n.º 20
0
int main(int argc, char **argv)
#endif
{
  long cache_hits, cache_misses;

#if CHROMIUM
  char *argv[] = { "vncreflector" };
  (void) parse_args;
  (void) report_usage;
  /*opt_log_filename = "reflector.log";*/
  opt_log_filename = NULL;
  opt_no_banner = 1;
  opt_foreground = 1;
  opt_stderr_loglevel = 5;
#else
  /* Parse command line, exit on error */
  parse_args(argc, argv);
#endif


  if (!opt_no_banner) {
    fprintf(stderr,
"VNC Reflector %s.  Copyright (C) 2001-2003 HorizonLive.com, Inc.\n\n"
"HorizonLive provides e-Learning and collaborative synchronous presentation\n"
"solutions in a totally Web-based environment.  For more information about\n"
"HorizonLive, please see our website at http://www.horizonlive.com/\n\n",
            VERSION);
  }

  if (!log_open(opt_log_filename, opt_file_loglevel,
                (opt_foreground) ? opt_stderr_loglevel : -1)) {
    fprintf(stderr, "%s: error opening log file (ignoring this error)\n",
            argv[0]);
  }

  log_write(LL_MSG, "Starting VNC Reflector %s", VERSION);

  /* Fork the process to the background if necessary */
  if (!opt_foreground) {
    if (!opt_no_banner) {
      fprintf(stderr, "Starting in the background, "
              "see the log file for errors and other messages.\n");
    }

    if (getpid() != 1) {
      signal(SIGTTIN, SIG_IGN);
      signal(SIGTTOU, SIG_IGN);
      signal(SIGTSTP, SIG_IGN);
      if (fork ())
        return 0;
      setsid();
    }
    close(0);
    close(1);
    close(2);
    log_write(LL_INFO, "Switched to the background mode");
  }

  /* Initialization */
  if (init_screen_info()) {
    read_password_file();
    set_host_encodings(opt_request_tight, opt_tight_level);
    set_client_passwords(opt_client_password, opt_client_ro_password);
    fbs_set_prefix(opt_fbs_prefix, opt_join_sessions);

    set_active_file(opt_active_filename);
    set_actions_file(opt_actions_filename);

    aio_init();
    if (opt_bind_ip != NULL) {
      if (aio_set_bind_address(opt_bind_ip)) {
        log_write(LL_INFO, "Would bind listening sockets to address %s",
                  opt_bind_ip);
      } else {
        log_write(LL_WARN, "Illegal address to bind listening sockets to: %s",
                  opt_bind_ip);
      }
    }

    /* Main work */
    if (vnc_spu.server_port == -1)
    {
      /* Try a series of port numbers until we find one that's free
       * for us.  Then, signal our parent thread that the port number
       * is available.
       */
      int i;
      for (i = 0; i < NUM_SERVER_PORTS; i++) {
        int p = FIRST_SERVER_PORT + i;
	if (wait_for_client(p)) {
	  /* OK, we've got our port number now.  So signal parent thread. */
	  crLockMutex(&vnc_spu.lock);
	  vnc_spu.server_port = p;
	  opt_cl_listen_port = vnc_spu.server_port;
	  crSignalCondition(&vnc_spu.cond);
	  crUnlockMutex(&vnc_spu.lock);

	  if (write_pid_file()) {
	    /*set_control_signals()*/
	    aio_mainloop();
	    remove_pid_file();
	  }
	  break;
	}
      }
      if (i == NUM_SERVER_PORTS) {
	log_write(LL_ERROR, "Unable to find a free port in the range"
		  " %d through %d",
		  FIRST_SERVER_PORT, FIRST_SERVER_PORT + NUM_SERVER_PORTS - 1);
	exit(1);
      }
    }
    else {
      /* user-configured port number */
      opt_cl_listen_port = vnc_spu.server_port;
      if (wait_for_client(opt_cl_listen_port)) {
	if (write_pid_file()) {
	  /*set_control_signals()*/
	  aio_mainloop();
	  remove_pid_file();
	}
      }
    }

    /* Cleanup */
    if (g_framebuffer != NULL) {
      log_write(LL_DETAIL, "Freeing framebuffer and associated structures");
      free(g_framebuffer);
      free_enc_cache();
    }
    if (g_screen_info.name != NULL)
      free(g_screen_info.name);

    get_hextile_caching_stats(&cache_hits, &cache_misses);
    if (cache_hits + cache_misses != 0) {
      log_write(LL_INFO, "Hextile BGR233 caching efficiency: %d%%",
                (int)((cache_hits * 100 + (cache_hits + cache_misses) / 2)
                      / (cache_hits + cache_misses)));
    }
  }

  log_write(LL_MSG, "Terminating");

  /* Close logs */
  if (!log_close() && opt_foreground) {
    fprintf(stderr, "%s: error closing log file (ignoring this error)\n",
            argv[0]);
  }

  /* Done */
  exit(1);
}
Exemplo n.º 21
0
void plus256k_init(void)
{
    plus256k_log = log_open("PLUS256K");
}
Exemplo n.º 22
0
int
main(int argc, char *argv[])
{
	server_t		 server;
	char const		*control = SDP_LOCAL_PATH;
	char const		*user = "******", *group = "_sdpd";
	char const		*sgroup = NULL;
	int			 opt;
	bool			 detach = true;
	struct sigaction	 sa;

	while ((opt = getopt(argc, argv, "c:dG:g:hu:")) != -1) {
		switch (opt) {
		case 'c': /* control */
			control = optarg;
			break;

		case 'd': /* do not detach */
			detach = false;
			break;

		case 'G': /* super group */
			sgroup = optarg;
			break;

		case 'g': /* group */
			group = optarg;
			break;

		case 'u': /* user */
			user = optarg;
			break;

		case 'h':
		default:
			usage();
			/* NOT REACHED */
		}
	}

	log_open(SDPD, !detach);

	/* Become daemon if required */
	if (detach && daemon(0, 0) < 0) {
		log_crit("Could not become daemon. %s (%d)",
		    strerror(errno), errno);

		exit(EXIT_FAILURE);
	}

	/* Set signal handlers */
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sighandler;

	if (sigaction(SIGTERM, &sa, NULL) < 0
	    || sigaction(SIGHUP,  &sa, NULL) < 0
	    || sigaction(SIGINT,  &sa, NULL) < 0) {
		log_crit("Could not install signal handlers. %s (%d)",
		    strerror(errno), errno);

		exit(EXIT_FAILURE);
	}

	sa.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &sa, NULL) < 0) {
		log_crit("Could not install signal handlers. %s (%d)",
		    strerror(errno), errno);

		exit(EXIT_FAILURE);
	}

	/* Initialize server */
	if (!server_init(&server, control, sgroup))
		exit(EXIT_FAILURE);

	if ((user != NULL || group != NULL) && !drop_root(user, group))
		exit(EXIT_FAILURE);

	for (done = 0; !done; ) {
		if (!server_do(&server))
			done++;
	}

	server_shutdown(&server);
	log_close();

	exit(EXIT_SUCCESS);
}
Exemplo n.º 23
0
/* C64-specific initialization.  */
int machine_specific_init(void)
{
    int delay;

    c64_log = log_open("C64");

    if (mem_load() < 0) {
        return -1;
    }

    /* Setup trap handling.  */
    traps_init();

    /* Initialize serial traps.  */
    if (serial_init(c64_serial_traps) < 0) {
        return -1;
    }

    serial_trap_init(0xa4);
    serial_iec_bus_init();

    /* Initialize RS232 handler.  */
    rs232drv_init();
    c64_rsuser_init();

    /* Initialize print devices.  */
    printer_init();

    /* Initialize the tape emulation.  */
    tape_init(&tapeinit);

    /* Initialize the datasette emulation.  */
    datasette_init();

    /* Fire up the hardware-level drive emulation.  */
    drive_init();

    resources_get_int("AutostartDelay", &delay);
    if (delay == 0) {
        delay = 3; /* default */
    }

    /* Initialize autostart.  */
    autostart_init((CLOCK)(delay * C64_PAL_RFSH_PER_SEC * C64_PAL_CYCLES_PER_RFSH), 1, 0xcc, 0xd1, 0xd3, 0xd5);

    if (vicii_init(VICII_STANDARD) == NULL && !video_disabled_mode) {
        return -1;
    }

    c64_mem_init();

    cia1_init(machine_context.cia1);
    cia2_init(machine_context.cia2);

#ifndef COMMON_KBD
    /* Initialize the keyboard.  */
    if (c64_kbd_init() < 0) {
        return -1;
    }
#endif
    c64keyboard_init();

    c64_monitor_init();

    /* Initialize vsync and register our hook function.  */
    vsync_init(machine_vsync_hook);
    vsync_set_machine_parameter(machine_timing.rfsh_per_sec, machine_timing.cycles_per_sec);

    /* Initialize native sound chip */
    sid_sound_chip_init();

    /* Initialize cartridge based sound chips */
    cartridge_sound_chip_init();

    drive_sound_init();
    video_sound_init();

    /* Initialize sound.  Notice that this does not really open the audio
       device yet.  */
    sound_init(machine_timing.cycles_per_sec, machine_timing.cycles_per_rfsh);

    /* Initialize keyboard buffer.  */
    kbdbuf_init(631, 198, 10, (CLOCK)(machine_timing.rfsh_per_sec * machine_timing.cycles_per_rfsh));

    /* Initialize the C64-specific I/O */
    c64io_init();

    /* Initialize the C64-specific part of the UI.  */
    if (!console_mode) {
        if (machine_class == VICE_MACHINE_C64SC) {
            c64scui_init();
        } else {
            c64ui_init();
        }
    }

    /* Initialize glue logic.  */
    c64_glue_init();

    /* Initialize the +60K.  */
    plus60k_init();

    /* Initialize the +256K.  */
    plus256k_init();

    /* Initialize the C64 256K.  */
    c64_256k_init();

#ifdef HAVE_MOUSE
    /* Initialize mouse support (if present).  */
    mouse_init();

    /* Initialize lightpen support and register VICII callbacks */
    lightpen_init();
    lightpen_register_timing_callback(vicii_lightpen_timing, 0);
    lightpen_register_trigger_callback(vicii_trigger_light_pen);
#endif
    c64iec_init();
    c64fastiec_init();

    cartridge_init();

    machine_drive_stub();
#if defined (USE_XF86_EXTENSIONS) && (defined(USE_XF86_VIDMODE_EXT) || defined (HAVE_XRANDR))
    {
        /* set fullscreen if user used `-fullscreen' on cmdline */
        int fs;
        resources_get_int("UseFullscreen", &fs);
        if (fs) {
            resources_set_int("VICIIFullscreen", 1);
        }
    }
#endif

    return 0;
}
Exemplo n.º 24
0
int
main(int argc, char *argv[])
{
	char pidstr[16];
	ssize_t ret;
	int c, log_method;
	char *logfile, *pidfile;
	int facility, fd;
	char *username = NULL;
	char *chrootdir = NULL;
	int configtest = 0;
	int singleprocess = 0;
#ifdef HAVE_GETOPT_LONG
	int opt_idx;
#endif

	pname = ((pname=strrchr(argv[0],'/')) != NULL)?pname+1:argv[0];

	srand((unsigned int)time(NULL));

	log_method = L_STDERR_SYSLOG;
	logfile = PATH_RADVD_LOG;
	conf_file = PATH_RADVD_CONF;
	facility = LOG_FACILITY;
	pidfile = PATH_RADVD_PID;

	/* parse args */
#define OPTIONS_STR "d:C:l:m:p:t:u:vhcs"
#ifdef HAVE_GETOPT_LONG
	while ((c = getopt_long(argc, argv, OPTIONS_STR, prog_opt, &opt_idx)) > 0)
#else
	while ((c = getopt(argc, argv, OPTIONS_STR)) > 0)
#endif
	{
		switch (c) {
		case 'C':
			conf_file = optarg;
			break;
		case 'd':
			set_debuglevel(atoi(optarg));
			break;
		case 'f':
			facility = atoi(optarg);
			break;
		case 'l':
			logfile = optarg;
			break;
		case 'p':
			pidfile = optarg;
			break;
		case 'm':
			if (!strcmp(optarg, "syslog"))
			{
				log_method = L_SYSLOG;
			}
			else if (!strcmp(optarg, "stderr_syslog"))
			{
				log_method = L_STDERR_SYSLOG;
			}
			else if (!strcmp(optarg, "stderr"))
			{
				log_method = L_STDERR;
			}
			else if (!strcmp(optarg, "logfile"))
			{
				log_method = L_LOGFILE;
			}
			else if (!strcmp(optarg, "none"))
			{
				log_method = L_NONE;
			}
			else
			{
				fprintf(stderr, "%s: unknown log method: %s\n", pname, optarg);
				exit(1);
			}
			break;
		case 't':
			chrootdir = strdup(optarg);
			break;
		case 'u':
			username = strdup(optarg);
			break;
		case 'v':
			version();
			break;
		case 'c':
			configtest = 1;
			break;
		case 's':
			singleprocess = 1;
			break;
		case 'h':
			usage();
#ifdef HAVE_GETOPT_LONG
		case ':':
			fprintf(stderr, "%s: option %s: parameter expected\n", pname,
				prog_opt[opt_idx].name);
			exit(1);
#endif
		case '?':
			exit(1);
		}
	}

	if (chrootdir) {
		if (!username) {
			fprintf(stderr, "Chroot as root is not safe, exiting\n");
			exit(1);
		}

		if (chroot(chrootdir) == -1) {
			perror("chroot");
			exit (1);
		}

		if (chdir("/") == -1) {
			perror("chdir");
			exit (1);
		}
		/* username will be switched later */
	}

	if (configtest) {
		log_method = L_STDERR;
	}

	if (log_open(log_method, pname, logfile, facility) < 0) {
		perror("log_open");
		exit(1);
	}

	if (!configtest) {
		flog(LOG_INFO, "version %s started", VERSION);
	}

	/* get a raw socket for sending and receiving ICMPv6 messages */
	sock = open_icmpv6_socket();
	if (sock < 0) {
		perror("open_icmpv6_socket");
		exit(1);
	}

#if 0 //brcm: no need to check
	/* check that 'other' cannot write the file
         * for non-root, also that self/own group can't either
         */
	if (check_conffile_perm(username, conf_file) < 0) {
		if (get_debuglevel() == 0) {
			flog(LOG_ERR, "Exiting, permissions on conf_file invalid.\n");
			exit(1);
		}
		else
			flog(LOG_WARNING, "Insecure file permissions, but continuing anyway");
	}

	/* if we know how to do it, check whether forwarding is enabled */
	if (check_ip6_forwarding()) {
		flog(LOG_WARNING, "IPv6 forwarding seems to be disabled, but continuing anyway.");
	}
#endif

	/* parse config file */
	if (readin_config(conf_file) < 0) {
		flog(LOG_ERR, "Exiting, failed to read config file.\n");
		exit(1);
	}

	if (configtest) {
		fprintf(stderr, "Syntax OK\n");
		exit(0);
	}

	/* drop root privileges if requested. */
	if (username) {
		if (!singleprocess) {
		 	dlog(LOG_DEBUG, 3, "Initializing privsep");
		 	if (privsep_init() < 0)
				flog(LOG_WARNING, "Failed to initialize privsep.");
		}

		if (drop_root_privileges(username) < 0) {
			perror("drop_root_privileges");
			exit(1);
		}
	}

	if ((fd = open(pidfile, O_RDONLY, 0)) > 0)
	{
		ret = read(fd, pidstr, sizeof(pidstr) - 1);
		if (ret < 0)
		{
			flog(LOG_ERR, "cannot read radvd pid file, terminating: %s", strerror(errno));
			exit(1);
		}
		pidstr[ret] = '\0';
		if (!kill((pid_t)atol(pidstr), 0))
		{
			flog(LOG_ERR, "radvd already running, terminating.");
			exit(1);
		}
		close(fd);
		fd = open(pidfile, O_CREAT|O_TRUNC|O_WRONLY, 0644);
	}
	else	/* FIXME: not atomic if pidfile is on an NFS mounted volume */
		fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);

	if (fd < 0)
	{
		flog(LOG_ERR, "cannot create radvd pid file, terminating: %s", strerror(errno));
		exit(1);
	}

	/*
	 * okay, config file is read in, socket and stuff is setup, so
	 * lets fork now...
	 */
#if 0 //brcm
	if (get_debuglevel() == 0) {

		/* Detach from controlling terminal */
		if (daemon(0, 0) < 0)
			perror("daemon");

		/* close old logfiles, including stderr */
		log_close();

		/* reopen logfiles, but don't log to stderr unless explicitly requested */
		if (log_method == L_STDERR_SYSLOG)
			log_method = L_SYSLOG;
		if (log_open(log_method, pname, logfile, facility) < 0) {
			perror("log_open");
			exit(1);
		}

	}
#endif
	/*
	 *	config signal handlers
	 */
	signal(SIGHUP, sighup_handler);
	signal(SIGTERM, sigterm_handler);
	signal(SIGINT, sigint_handler);
	signal(SIGUSR1, sigusr1_handler);

	snprintf(pidstr, sizeof(pidstr), "%ld\n", (long)getpid());

	ret = write(fd, pidstr, strlen(pidstr));
	if (ret != strlen(pidstr))
	{
		flog(LOG_ERR, "cannot write radvd pid file, terminating: %s", strerror(errno));
		exit(1);
	}

	close(fd);

	config_interface();
	kickoff_adverts();
	main_loop();
	stop_adverts();
	unlink(pidfile);

	return 0;
}
Exemplo n.º 25
0
void log_roll(

  int max_depth)

  {
  int i, suffix_size, file_buf_len, as;
  int err = 0;
  char *source  = NULL;
  char *dest    = NULL;

  if (!log_opened)
    {
    return;
    }

  /* save value of log_auto_switch */

  as = log_auto_switch;

  log_close(1);

  /* find out how many characters the suffix could be. (save in suffix_size)
     start at 1 to account for the "."  */

  for (i = max_depth, suffix_size = 1;i > 0;suffix_size++, i /= 10);

  /* allocate memory for rolling */

  file_buf_len = sizeof(char) * (strlen(logpath) + suffix_size + 1);

  source = (char*)malloc(file_buf_len);

  dest   = (char*)malloc(file_buf_len);

  if ((source == NULL) || (dest == NULL))
    {
    err = errno;

    goto done_roll;
    }

  /* call unlink to delete logname.max_depth - it doesn't matter if it
     doesn't exist, so we'll ignore ENOENT */

  sprintf(dest, "%s.%d",
    logpath,
    max_depth);

  if ((unlink(dest) != 0) && (errno != ENOENT))
    {
    err = errno;
    goto done_roll;
    }

  /* logname.max_depth is gone, so roll the rest of the log files */

  for (i = max_depth - 1;i >= 0;i--)
    {
    if (i == 0)
      {
      strcpy(source, logpath);
      }
    else
      {
      sprintf(source, "%s.%d",
        logpath,
        i);
      }

    sprintf(dest, "%s.%d",
      logpath,
      i + 1);

    /* rename file if it exists */

    if ((rename(source, dest) != 0) && (errno != ENOENT))
      {
      err = errno;
      goto done_roll;
      }
    }    /* END for (i) */

done_roll:

  if (as)
    {
    log_open(NULL, log_directory);
    }
  else
    {
    log_open(logpath, log_directory);
    }

  if (source != NULL)
    free(source);

  if (dest != NULL)
    free(dest);

  if (err != 0)
    {
    log_err(err, "log_roll", "error while rollng logs");
    }
  else
    {
    log_record(
      PBSEVENT_SYSTEM,
      PBS_EVENTCLASS_SERVER,
      "Log",
      "Log Rolled");
    }

  return;
  } /* END log_roll() */
Exemplo n.º 26
0
int main(int argc, char *argv[]) {
        int r;
        Hashmap *a = NULL, *b = NULL;
        unsigned iteration = 0;
        usec_t last_refresh = 0;
        bool quit = false, immediate_refresh = false;

        log_parse_environment();
        log_open();

        r = parse_argv(argc, argv);
        if (r <= 0)
                goto finish;

        a = hashmap_new(string_hash_func, string_compare_func);
        b = hashmap_new(string_hash_func, string_compare_func);
        if (!a || !b) {
                r = log_oom();
                goto finish;
        }

        signal(SIGWINCH, columns_lines_cache_reset);

        if (!on_tty())
                arg_iterations = 1;

        while (!quit) {
                Hashmap *c;
                usec_t t;
                char key;
                char h[FORMAT_TIMESPAN_MAX];

                t = now(CLOCK_MONOTONIC);

                if (t >= last_refresh + arg_delay || immediate_refresh) {

                        r = refresh(a, b, iteration++);
                        if (r < 0)
                                goto finish;

                        group_hashmap_clear(b);

                        c = a;
                        a = b;
                        b = c;

                        last_refresh = t;
                        immediate_refresh = false;
                }

                r = display(b);
                if (r < 0)
                        goto finish;

                if (arg_iterations && iteration >= arg_iterations)
                        break;

                if (arg_batch) {
                        usleep(last_refresh + arg_delay - t);
                } else {
                        r = read_one_char(stdin, &key,
                                          last_refresh + arg_delay - t, NULL);
                        if (r == -ETIMEDOUT)
                                continue;
                        if (r < 0) {
                                log_error("Couldn't read key: %s", strerror(-r));
                                goto finish;
                        }
                }

                fputs("\r \r", stdout);
                fflush(stdout);

                if (arg_batch)
                        continue;

                switch (key) {

                case ' ':
                        immediate_refresh = true;
                        break;

                case 'q':
                        quit = true;
                        break;

                case 'p':
                        arg_order = ORDER_PATH;
                        break;

                case 't':
                        arg_order = ORDER_TASKS;
                        break;

                case 'c':
                        arg_order = ORDER_CPU;
                        break;

                case 'm':
                        arg_order = ORDER_MEMORY;
                        break;

                case 'i':
                        arg_order = ORDER_IO;
                        break;

                case '%':
                        arg_cpu_type = arg_cpu_type == CPU_TIME ? CPU_PERCENT : CPU_TIME;
                        break;

                case '+':
                        if (arg_delay < USEC_PER_SEC)
                                arg_delay += USEC_PER_MSEC*250;
                        else
                                arg_delay += USEC_PER_SEC;

                        fprintf(stdout, "\nIncreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
                        fflush(stdout);
                        sleep(1);
                        break;

                case '-':
                        if (arg_delay <= USEC_PER_MSEC*500)
                                arg_delay = USEC_PER_MSEC*250;
                        else if (arg_delay < USEC_PER_MSEC*1250)
                                arg_delay -= USEC_PER_MSEC*250;
                        else
                                arg_delay -= USEC_PER_SEC;

                        fprintf(stdout, "\nDecreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
                        fflush(stdout);
                        sleep(1);
                        break;

                case '?':
                case 'h':
                        fprintf(stdout,
                                "\t<" ON "P" OFF "> By path; <" ON "T" OFF "> By tasks; <" ON "C" OFF "> By CPU; <" ON "M" OFF "> By memory; <" ON "I" OFF "> By I/O\n"
                                "\t<" ON "+" OFF "> Increase delay; <" ON "-" OFF "> Decrease delay; <" ON "%%" OFF "> Toggle time\n"
                                "\t<" ON "Q" OFF "> Quit; <" ON "SPACE" OFF "> Refresh");
                        fflush(stdout);
                        sleep(3);
                        break;

                default:
                        fprintf(stdout, "\nUnknown key '%c'. Ignoring.", key);
                        fflush(stdout);
                        sleep(1);
                        break;
                }
        }

        r = 0;

finish:
        group_hashmap_free(a);
        group_hashmap_free(b);

        if (r < 0) {
                log_error("Exiting with failure: %s", strerror(-r));
                return EXIT_FAILURE;
        }

        return EXIT_SUCCESS;
}
Exemplo n.º 27
0
void log_record(

  int   eventtype,  /* I */
  int   objclass,   /* I */
  char *objname,    /* I */
  char *text)       /* I */

  {
  int tryagain = 2;
  time_t now;

  struct tm *ptm;
  struct tm  tmpPtm;
  int    rc = 0;
  FILE  *savlog;
  char  *start = NULL, *end = NULL;
  size_t nchars;

  if (log_opened < 1)
    {
    return;
    }

  now = time((time_t *)0); /* get time for message */

  ptm = localtime_r(&now,&tmpPtm);

  /* Do we need to switch the log? */

  if (log_auto_switch && (ptm->tm_yday != log_open_day))
    {
    log_close(1);

    log_open(NULL, log_directory);

    if (log_opened < 1)
      {
      return;
      }
    }

  /*
   * Looking for the newline characters and splitting the output message
   * on them.  Sequence "\r\n" is mapped to the single newline.
   */
  start = text;

  while (1)
    {
    for (end = start; *end != '\n' && *end != '\r' && *end != '\0'; end++)
      ;

    nchars = end - start;

    if (*end == '\r' && *(end + 1) == '\n')
      end++;

    while (tryagain)
      {
      rc = fprintf(logfile,
              "%02d/%02d/%04d %02d:%02d:%02d;%04x;%10.10s;%s;%s;%s%.*s\n",
              ptm->tm_mon + 1,
              ptm->tm_mday,
              ptm->tm_year + 1900,
              ptm->tm_hour,
              ptm->tm_min,
              ptm->tm_sec,
              (eventtype & ~PBSEVENT_FORCE),
              msg_daemonname,
              class_names[objclass],
              objname,
              (text == start ? "" : "[continued]"),
              (int)nchars,
              start);

      if ((rc < 0) &&
          (errno == EPIPE) &&
          (tryagain == 2))
        {
        /* the log file descriptor has been changed--it now points to a socket!
         * reopen log and leave the previous file descriptor alone--do not close it */

        log_opened = 0;
        log_open(NULL, log_directory);
        tryagain--;
        }
      else
        {
        tryagain = 0;
        }
      }

    if (rc < 0)
      break;

    if (*end == '\0')
      break;

    start = end + 1;
    }  /* END while (1) */

  fflush(logfile);

  if (rc < 0)
    {
    rc = errno;
    clearerr(logfile);
    savlog = logfile;
    logfile = fopen("/dev/console", "w");
    /* we need to add this check to make sure the disk isn't full so we don't segfault 
     * if we can't open this then we're going to have a nice surprise failure */
    if (logfile != NULL)
      {
      log_err(rc, "log_record", "PBS cannot write to its log");
      fclose(logfile);
      }
    logfile = savlog;
    }

  return;
  }  /* END log_record() */
Exemplo n.º 28
0
int main(int argc, char* argv[])
{
    int sock, s_sock, client_fd;
    socklen_t client_size;
    struct sockaddr_in addr, client_addr;
    struct timeval tv;
    static pool pool;
    sigset_t mask;

    if (argc != 9)  usage_exit();

    // parse arguments
    STATE.port = (int)strtol(argv[1], (char**)NULL, 10);
    STATE.s_port = (int)strtol(argv[2], (char**)NULL, 10);
    strcpy(STATE.log_path, argv[3]);
    strcpy(STATE.lck_path, argv[4]);
    strcpy(STATE.www_path, argv[5]);
    strcpy(STATE.cgi_path, argv[6]);
    strcpy(STATE.key_path, argv[7]);
    strcpy(STATE.ctf_path, argv[8]);

    if (STATE.www_path[strlen(STATE.www_path)-1] == '/')
         STATE.www_path[strlen(STATE.www_path)-1] = '\0';

    daemonize();
    STATE.log = log_open(STATE.log_path);
    
    Log("Start Liso server. Server is running in background. \n");

    /* all networked programs must create a socket
     * PF_INET - IPv4 Internet protocols
     * SOCK_STREAM - sequenced, reliable, two-way, connection-based byte stream
     * 0 (protocol) - use default protocol
     */
    // create sock for HTTP connection
    if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
    {
        Log("Error: failed creating socket for HTTP connection.\n");
        fclose(STATE.log);
        return EXIT_FAILURE;
    }

    STATE.sock = sock;
    Log("Create socket success: sock =  %d \n", sock);

    addr.sin_family = AF_INET;
    addr.sin_port = htons(STATE.port);
    addr.sin_addr.s_addr = INADDR_ANY;
    /* servers bind sockets to ports---notify the OS they accept connections */
    if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)))
    {
        Log("Error: failed binding socket.\n");
        clean();
        return EXIT_FAILURE;
    }
    Log("Bind success! \n");

    if (listen(sock, MAX_CONN))
    {
        Log("Error: listening on socket.\n");
        clean();
        return EXIT_FAILURE;
    }
    Log("Listen success! >>>>>>>>>>>>>>>>>>>> \n");

    // create sock for HTTPS connection
    Log("Create sock for HTTPS connection \n");
    if ((s_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
    {
        Log("Error: failed creating socket for HTTPS connection.\n");
        close(sock);
        fclose(STATE.log);
        return EXIT_FAILURE;
    }

    STATE.s_sock = s_sock;
    Log("Create HTTPS socket success: sock =  %d \n", s_sock);

    addr.sin_family = AF_INET;
    addr.sin_port = htons(STATE.s_port);
    addr.sin_addr.s_addr = INADDR_ANY;
    /* servers bind sockets to ports---notify the OS they accept connections */
    if (bind(s_sock, (struct sockaddr *) &addr, sizeof(addr)))
    {
        Log("Error: failed binding socket.\n");
        close(sock); close(s_sock); fclose(STATE.log);
        return EXIT_FAILURE;
    }
    Log("Bind success! \n");

    if (listen(s_sock, MAX_CONN))
    {
        Log("Error: listening on socket.\n");
        close(sock); close(s_sock); fclose(STATE.log);
        return EXIT_FAILURE;
    }
    Log("Listen success! >>>>>>>>>>>>>>>>>>>> \n");
    init_pool(&pool);

    // the main loop to wait for connections and serve requests
    while (KEEPON)
    {
       tv.tv_sec = 1; // timeout = 1 sec
       tv.tv_usec = 0;
       pool.ready_set = pool.read_set;

       sigemptyset(&mask);
       sigaddset(&mask, SIGHUP);
       sigprocmask(SIG_BLOCK, &mask, NULL);
       pool.nready = select(pool.maxfd+1, &pool.ready_set, NULL, NULL, &tv);
       sigprocmask(SIG_UNBLOCK, &mask, NULL);

       if (pool.nready < 0)
       {
           if (errno == EINTR)
           {
               Log("Shut down Server >>>>>>>>>>>>>>>>>>>> \n");
               break;
           }
          
           Log("Error: select error \n");
           continue;
       }

       // if there is new connection, accept and add the new client to pool
       if (FD_ISSET(sock, &pool.ready_set))
       {
           client_size = sizeof(client_addr);
           client_fd = accept(sock, (struct sockaddr *) &client_addr,
                              &client_size);

           if (client_fd < 0) ///TODO
           {
               Log("Error: accepting connection. \n");
               continue;
           }

           Log("accept client: client_fd=%d \n", client_fd);

           if (STATE.is_full)
           {
               pool.nready--;
               serve_error(client_fd, "503", "Service Unavailable",
                    "Server is too busy right now. Please try again later.", 1);
               close(client_fd);
           }
           else
              add_client(client_fd, &pool);
       }

       // process each ready connected descriptor
       check_clients(&pool);
    }

    lisod_shutdown();

    return EXIT_SUCCESS; // to make compiler happy
}
Exemplo n.º 29
0
int main(int argc, char **argv)
{
    output_t outputti = NORMAL_OUT;
    FILE *fp = NULL;
    Octstr *output = NULL;
    Octstr *filename = NULL;
    Octstr *wml_text = NULL;
    Octstr *charset = NULL;
    Octstr *wml_binary = NULL;
    int i, ret = 0, opt, file = 0, zero = 0, numstatus = 0, wml_strict = 1;
    long num = 0;

    /* You can give an wml text file as an argument './wml_tester main.wml' */

    gwlib_init();

    while ((opt = getopt(argc, argv, "hsbzrn:f:c:")) != EOF) {
	switch (opt) {
	case 'h':
	    help();
	    exit(0);
	case 's':
	    if (outputti == NORMAL_OUT)
		outputti = SOURCE_OUT;
	    else {
		help();
		exit(0);
	    }
	    break;
	case 'b':
	    if (outputti == NORMAL_OUT)
		outputti = BINARY_OUT;
	    else {
		help();
		exit(0);
	    }
	    break;
	case 'z':
	    zero = 1;
	    break;
    case 'r':
        wml_strict = 0;
        break;
	case 'n':
	    numstatus = octstr_parse_long(&num, octstr_imm(optarg), 0, 0);
	    if (numstatus == -1) { 
		/* Error in the octstr_parse_long */
		error(num, "Error in the handling of argument to option n");
		help();
		panic(0, "Stopping.");
	    }
	    break;
	case 'f':
	    file = 1;
	    filename = octstr_create(optarg);
	    fp = fopen(optarg, "a");
	    if (fp == NULL)
		panic(0, "Couldn't open output file.");	
	    break;
	case 'c':
	    charset = octstr_create(optarg);
	    break;
	case '?':
	default:
	    error(0, "Invalid option %c", opt);
	    help();
	    panic(0, "Stopping.");
	}
    }

    if (optind >= argc) {
	error(0, "Missing arguments.");
	help();
	panic(0, "Stopping.");
    }

    if (outputti == BINARY_OUT)
	 log_set_output_level(GW_PANIC);
    wml_init(wml_strict);

    while (optind < argc) {
	wml_text = octstr_read_file(argv[optind]);
	if (wml_text == NULL)
	    panic(0, "Couldn't read WML source file.");

	if (zero)
	    set_zero(wml_text);

	for (i = 0; i <= num; i++) {
	    ret = wml_compile(wml_text, charset, &wml_binary, NULL);
	    if (i < num)
		octstr_destroy(wml_binary);
	}
	optind++;

	output = octstr_format("wml_compile returned: %d\n\n", ret);
    
	if (ret == 0) {
	    if (fp == NULL)
		fp = stdout;

	    if (outputti != BINARY_OUT) {
		if (outputti == SOURCE_OUT) {
		    octstr_insert(output, wml_text, octstr_len(output));
		    octstr_append_char(output, '\n');
		}

		octstr_append(output, octstr_imm(
		    "Here's the binary output: \n\n"));
		octstr_print(fp, output);
	    }

	    if (file && outputti != BINARY_OUT) {
		fclose(fp);
		log_open(octstr_get_cstr(filename), 0, GW_NON_EXCL);
		octstr_dump(wml_binary, 0);
		log_close_all();
		fp = fopen(octstr_get_cstr(filename), "a");
	    } else if (outputti != BINARY_OUT)
		octstr_dump(wml_binary, 0);
	    else 
		octstr_print(fp, wml_binary);

	    if (outputti != BINARY_OUT) {
		octstr_destroy(output);
		output = octstr_format("\n And as a text: \n\n");
		octstr_print(fp, output);
      
		octstr_pretty_print(fp, wml_binary);
		octstr_destroy(output);
		output = octstr_format("\n\n");
		octstr_print(fp, output);
	    }
	}

	octstr_destroy(wml_text);
	octstr_destroy(output);
	octstr_destroy(wml_binary);
    }
	
    if (file) {
	fclose(fp);
	octstr_destroy(filename);
    }
    
    if (charset != NULL)
	octstr_destroy(charset);

    wml_shutdown();
    gwlib_shutdown();
    
    return ret;
}
Exemplo n.º 30
0
int main(int argc, char *argv[]) {
        enum {
                FD_SOCKET,
                FD_WALL_TIMER,
                FD_NOLOGIN_TIMER,
                FD_SHUTDOWN_TIMER,
                _FD_MAX
        };

        int r = EXIT_FAILURE, n_fds;
        int one = 1;
        struct shutdownd_command c;
        struct pollfd pollfd[_FD_MAX];
        bool exec_shutdown = false, unlink_nologin = false, failed = false;
        unsigned i;

        if (getppid() != 1) {
                log_error("This program should be invoked by init only.");
                return EXIT_FAILURE;
        }

        if (argc > 1) {
                log_error("This program does not take arguments.");
                return EXIT_FAILURE;
        }

        log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
        log_parse_environment();
        log_open();

        if ((n_fds = sd_listen_fds(true)) < 0) {
                log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
                return EXIT_FAILURE;
        }

        if (n_fds != 1) {
                log_error("Need exactly one file descriptor.");
                return EXIT_FAILURE;
        }

        if (setsockopt(SD_LISTEN_FDS_START, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
                log_error("SO_PASSCRED failed: %m");
                return EXIT_FAILURE;
        }

        zero(c);
        zero(pollfd);

        pollfd[FD_SOCKET].fd = SD_LISTEN_FDS_START;
        pollfd[FD_SOCKET].events = POLLIN;

        for (i = 0; i < _FD_MAX; i++) {

                if (i == FD_SOCKET)
                        continue;

                pollfd[i].events = POLLIN;

                if ((pollfd[i].fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC)) < 0) {
                        log_error("timerfd_create(): %m");
                        failed = true;
                }
        }

        if (failed)
                goto finish;

        log_debug("systemd-shutdownd running as pid %lu", (unsigned long) getpid());

        sd_notify(false,
                  "READY=1\n"
                  "STATUS=Processing requests...");

        do {
                int k;
                usec_t n;

                if (poll(pollfd, _FD_MAX, -1) < 0) {

                        if (errno == EAGAIN || errno == EINTR)
                                continue;

                        log_error("poll(): %m");
                        goto finish;
                }

                n = now(CLOCK_REALTIME);

                if (pollfd[FD_SOCKET].revents) {

                        if ((k = read_packet(pollfd[FD_SOCKET].fd, &c)) < 0)
                                goto finish;
                        else if (k > 0 && c.elapse > 0) {
                                struct itimerspec its;
                                char date[FORMAT_TIMESTAMP_MAX];

                                if (c.warn_wall) {
                                        /* Send wall messages every so often */
                                        zero(its);
                                        timespec_store(&its.it_value, when_wall(n, c.elapse));
                                        if (timerfd_settime(pollfd[FD_WALL_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
                                                log_error("timerfd_settime(): %m");
                                                goto finish;
                                        }

                                        /* Warn immediately if less than 15 minutes are left */
                                        if (n < c.elapse &&
                                            n + 15*USEC_PER_MINUTE >= c.elapse)
                                                warn_wall(n, &c);
                                }

                                /* Disallow logins 5 minutes prior to shutdown */
                                zero(its);
                                timespec_store(&its.it_value, when_nologin(c.elapse));
                                if (timerfd_settime(pollfd[FD_NOLOGIN_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
                                        log_error("timerfd_settime(): %m");
                                        goto finish;
                                }

                                /* Shutdown after the specified time is reached */
                                zero(its);
                                timespec_store(&its.it_value, c.elapse);
                                if (timerfd_settime(pollfd[FD_SHUTDOWN_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
                                        log_error("timerfd_settime(): %m");
                                        goto finish;
                                }

                                sd_notifyf(false,
                                           "STATUS=Shutting down at %s...",
                                           format_timestamp(date, sizeof(date), c.elapse));
                        }
                }

                if (pollfd[FD_WALL_TIMER].revents) {
                        struct itimerspec its;

                        warn_wall(n, &c);
                        flush_fd(pollfd[FD_WALL_TIMER].fd);

                        /* Restart timer */
                        zero(its);
                        timespec_store(&its.it_value, when_wall(n, c.elapse));
                        if (timerfd_settime(pollfd[FD_WALL_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
                                log_error("timerfd_settime(): %m");
                                goto finish;
                        }
                }

                if (pollfd[FD_NOLOGIN_TIMER].revents) {
                        int e;

                        log_info("Creating /run/nologin, blocking further logins...");

                        if ((e = write_one_line_file("/run/nologin", "System is going down.")) < 0)
                                log_error("Failed to create /run/nologin: %s", strerror(-e));
                        else
                                unlink_nologin = true;

                        flush_fd(pollfd[FD_NOLOGIN_TIMER].fd);
                }

                if (pollfd[FD_SHUTDOWN_TIMER].revents) {
                        exec_shutdown = true;
                        goto finish;
                }

        } while (c.elapse > 0);

        r = EXIT_SUCCESS;

        log_debug("systemd-shutdownd stopped as pid %lu", (unsigned long) getpid());

finish:

        for (i = 0; i < _FD_MAX; i++)
                if (pollfd[i].fd >= 0)
                        close_nointr_nofail(pollfd[i].fd);

        if (unlink_nologin)
                unlink("/run/nologin");

        if (exec_shutdown) {
                char sw[3];

                sw[0] = '-';
                sw[1] = c.mode;
                sw[2] = 0;

                execl(SYSTEMCTL_BINARY_PATH,
                      "shutdown",
                      sw,
                      "now",
                      (c.warn_wall && c.wall_message[0]) ? c.wall_message :
                      (c.warn_wall ? NULL : "--no-wall"),
                      NULL);

                log_error("Failed to execute /sbin/shutdown: %m");
        }

        sd_notify(false,
                  "STATUS=Exiting...");

        return r;
}