Esempio n. 1
0
int main(int argc, char *argv[])
{
    char *devname;
    tapdev_info_t *ctlinfo;
    int tap_pfd, store_pfd, xs_fd, ret, timeout, pfd_count, count=0;
    struct xs_handle *h;
    struct pollfd  pfd[NUM_POLL_FDS];
    pid_t process;
    char buf[128];

    __init_blkif();
    snprintf(buf, sizeof(buf), "BLKTAPCTRL[%d]", getpid());
    openlog(buf, LOG_CONS|LOG_ODELAY, LOG_DAEMON);
    if (daemon(0,0)) {
        DPRINTF("daemon failed (%d)\n", errno);
        goto open_failed;
    }

    print_drivers();
    init_driver_list();
    init_rng();

    register_new_blkif_hook(blktapctrl_new_blkif);
    register_new_devmap_hook(map_new_blktapctrl);
    register_new_unmap_hook(unmap_blktapctrl);

    ctlfd = blktap_interface_open();
    if (ctlfd < 0) {
        DPRINTF("couldn't open blktap interface\n");
        goto open_failed;
    }

#ifdef MEMSHR
    memshr_daemon_initialize();
#endif

retry:
    /* Set up store connection and watch. */
    h = xs_daemon_open();
    if (h == NULL) {
        DPRINTF("xs_daemon_open failed -- "
                "is xenstore running?\n");
        if (count < MAX_ATTEMPTS) {
            count++;
            sleep(2);
            goto retry;
        } else goto open_failed;
    }

    ret = setup_probe_watch(h);
    if (ret != 0) {
        DPRINTF("Failed adding device probewatch\n");
        xs_daemon_close(h);
        goto open_failed;
    }

    ioctl(ctlfd, BLKTAP_IOCTL_SETMODE, BLKTAP_MODE_INTERPOSE );

    process = getpid();
    write_pidfile(process);
    ret = ioctl(ctlfd, BLKTAP_IOCTL_SENDPID, process );

    /*Static pollhooks*/
    pfd_count = 0;
    tap_pfd = pfd_count++;
    pfd[tap_pfd].fd = ctlfd;
    pfd[tap_pfd].events = POLLIN;

    store_pfd = pfd_count++;
    pfd[store_pfd].fd = xs_fileno(h);
    pfd[store_pfd].events = POLLIN;

    while (run) {
        timeout = 1000; /*Milliseconds*/
        ret = poll(pfd, pfd_count, timeout);

        if (ret > 0) {
            if (pfd[store_pfd].revents) {
                ret = xs_fire_next_watch(h);
            }
        }
    }

    xs_daemon_close(h);
    ioctl(ctlfd, BLKTAP_IOCTL_SETMODE, BLKTAP_MODE_PASSTHROUGH );
    close(ctlfd);
    closelog();

    return 0;

open_failed:
    DPRINTF("Unable to start blktapctrl\n");
    closelog();
    return -1;
}
Esempio n. 2
0
int ngx_cdecl
main(int argc, char *const *argv)
{
    ngx_int_t         i;
    ngx_log_t        *log;
    ngx_cycle_t      *cycle, init_cycle;
    ngx_core_conf_t  *ccf;

    if (ngx_get_options(argc, argv) != NGX_OK) {
        return 1;
    }

    if (ngx_show_version) {
        ngx_log_stderr(0, "nginx version: " NGINX_VER);

        if (ngx_show_help) {
            ngx_log_stderr(0,
                "Usage: nginx [-?hvVt] [-s signal] [-c filename] "
                             "[-p prefix] [-g directives]" CRLF CRLF
                "Options:" CRLF
                "  -?,-h         : this help" CRLF
                "  -v            : show version and exit" CRLF
                "  -V            : show version and configure options then exit"
                                   CRLF
                "  -t            : test configuration and exit" CRLF
                "  -s signal     : send signal to a master process: "
                                   "stop, quit, reopen, reload" CRLF
#ifdef NGX_PREFIX
                "  -p prefix     : set prefix path (default: "
                                   NGX_PREFIX ")" CRLF
#else
                "  -p prefix     : set prefix path (default: NONE)" CRLF
#endif
                "  -c filename   : set configuration file (default: "
                                   NGX_CONF_PATH ")" CRLF
                "  -g directives : set global directives out of configuration "
                                   "file" CRLF
                );
        }

        if (ngx_show_configure) {
#ifdef NGX_COMPILER
            ngx_log_stderr(0, "built by " NGX_COMPILER);
#endif
#if (NGX_SSL)
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
            ngx_log_stderr(0, "TLS SNI support enabled");
#else
            ngx_log_stderr(0, "TLS SNI support disabled");
#endif
#endif
            ngx_log_stderr(0, "configure arguments:" NGX_CONFIGURE);
        }

        if (!ngx_test_config) {
            return 0;
        }
    }

#if (NGX_FREEBSD)
    ngx_debug_init();
#endif

    /* TODO */ ngx_max_sockets = -1;

    ngx_time_init();

#if (NGX_PCRE)
    ngx_regex_init();
#endif

    ngx_pid = ngx_getpid();

    log = ngx_log_init(ngx_prefix);
    if (log == NULL) {
        return 1;
    }

    /* STUB */
#if (NGX_OPENSSL)
    ngx_ssl_init(log);
#endif

    /* SYSLOG SUPPORT */
#ifdef USE_SYSLOG
    openlog("nginx", LOG_ODELAY, LOG_DAEMON);
#endif

    /*
     * init_cycle->log is required for signal handlers and
     * ngx_process_options()
     */

    ngx_memzero(&init_cycle, sizeof(ngx_cycle_t));
    init_cycle.log = log;
    ngx_cycle = &init_cycle;

    init_cycle.pool = ngx_create_pool(1024, log);
    if (init_cycle.pool == NULL) {
        return 1;
    }

    if (ngx_save_argv(&init_cycle, argc, argv) != NGX_OK) {
        return 1;
    }

    if (ngx_process_options(&init_cycle) != NGX_OK) {
        return 1;
    }

    if (ngx_os_init(log) != NGX_OK) {
        return 1;
    }

    /*
     * ngx_crc32_table_init() requires ngx_cacheline_size set in ngx_os_init()
     */

    if (ngx_crc32_table_init() != NGX_OK) {
        return 1;
    }

    if (ngx_add_inherited_sockets(&init_cycle) != NGX_OK) {
        return 1;
    }

    ngx_max_module = 0;
    for (i = 0; ngx_modules[i]; i++) {
        ngx_modules[i]->index = ngx_max_module++;
    }

    cycle = ngx_init_cycle(&init_cycle);
    if (cycle == NULL) {
        if (ngx_test_config) {
            ngx_log_stderr(0, "configuration file %s test failed",
                           init_cycle.conf_file.data);
        }

        return 1;
    }

    if (ngx_test_config) {
        ngx_log_stderr(0, "configuration file %s test is successful",
                       cycle->conf_file.data);
        return 0;
    }

    if (ngx_signal) {
        return ngx_signal_process(cycle, ngx_signal);
    }

    ngx_os_status(cycle->log);

    ngx_cycle = cycle;

    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    if (ccf->master && ngx_process == NGX_PROCESS_SINGLE) {
        ngx_process = NGX_PROCESS_MASTER;
    }

#if !(NGX_WIN32)

    if (ngx_init_signals(cycle->log) != NGX_OK) {
        return 1;
    }

    if (!ngx_inherited && ccf->daemon) {
        if (ngx_daemon(cycle->log) != NGX_OK) {
            return 1;
        }

        ngx_daemonized = 1;
    }

#endif

    if (ngx_create_pidfile(&ccf->pid, cycle->log) != NGX_OK) {
        return 1;
    }

    if (cycle->log->file->fd != ngx_stderr) {

        if (ngx_set_stderr(cycle->log->file->fd) == NGX_FILE_ERROR) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          ngx_set_stderr_n " failed");
            return 1;
        }
    }

    if (log->file->fd != ngx_stderr) {
        if (ngx_close_file(log->file->fd) == NGX_FILE_ERROR) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          ngx_close_file_n " built-in log failed");
        }
    }

    ngx_use_stderr = 0;

    if (ngx_process == NGX_PROCESS_SINGLE) {
        ngx_single_process_cycle(cycle);

    } else {
        ngx_master_process_cycle(cycle);
    }

#ifdef USE_SYSLOG
    closelog();
#endif

    return 0;
}
Esempio n. 3
0
// main function
int main(int argc, char *argv[])
{
	gboolean show_version = FALSE;
	gboolean log_info = FALSE;
	gboolean log_debug = FALSE;
	gboolean no_daemon = FALSE;
	gboolean test_mode = FALSE;
	gint poll_interval = -1;
	gboolean success;
	GOptionContext *opt_ctx;

	thd_daemonize = TRUE;
	dbus_enable = FALSE;

	GOptionEntry options[] =
	{
		{
			"version", 0, 0, G_OPTION_ARG_NONE, &show_version, N_(
			"Print thermald version and exit"), NULL
		}
		,
		{
			"no-daemon", 0, 0, G_OPTION_ARG_NONE, &no_daemon, N_(
			"Don't become a daemon: Default is daemon mode"), NULL
		}
		,
		{
			"loglevel=info", 0, 0, G_OPTION_ARG_NONE, &log_info, N_(
			"log severity: info level and up"), NULL
		}
		,
		{
			"loglevel=debug", 0, 0, G_OPTION_ARG_NONE, &log_debug, N_(
			"log severity: debug level and up: Max logging"), NULL
		}
		,
		{
			"test-mode", 0, 0, G_OPTION_ARG_NONE, &test_mode, N_(
			"Test Mode only: Allow non root user"), NULL
		}
		,
		{
			"poll-interval", 0, 0, G_OPTION_ARG_INT, &poll_interval, N_(
			"Poll interval in seconds: Poll for zone temperature changes. "
			"If want to disable polling set to zero."), NULL
		}
		,
		{
			"dbus-enable", 0, 0, G_OPTION_ARG_NONE, &dbus_enable, N_(
			"Enable Dbus."), NULL
		}
		,
		{
			"use-thermal-sysfs", 0, 0, G_OPTION_ARG_NONE, &use_thermal_sys_fs, N_(
			"Use thermal sysfs instead of DTS sensors, default use dts."), NULL
		}
		,

		{
			NULL
		}
	};

	if(!g_module_supported())
	{
		fprintf(stderr, _("GModules are not supported on your platform!\n"));
		exit(1);
	}

	/* Set locale to be able to use environment variables */
	setlocale(LC_ALL, "");

	bindtextdomain(GETTEXT_PACKAGE, TDLOCALEDIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
	textdomain(GETTEXT_PACKAGE);
	/* Parse options */
	opt_ctx = g_option_context_new(NULL);
	g_option_context_set_translation_domain(opt_ctx, GETTEXT_PACKAGE);
	g_option_context_set_ignore_unknown_options(opt_ctx, FALSE);
	g_option_context_set_help_enabled(opt_ctx, TRUE);
	g_option_context_add_main_entries(opt_ctx, options, NULL);

	g_option_context_set_summary(opt_ctx, _(
		"Thermal daemon monitors temperature sensors and decides the best action "
		"based on the temperature readings and user preferences."));

	success = g_option_context_parse(opt_ctx, &argc, &argv, NULL);
	g_option_context_free(opt_ctx);

	if(!success)
	{
		fprintf(stderr, _(
			"Invalid option.  Please use --help to see a list of valid options.\n"));
		exit(1);
	}

	if(show_version)
	{
		fprintf(stdout, TD_DIST_VERSION "\n");
		exit(0);
	}

	if(getuid() != 0 && !test_mode)
	{
		fprintf(stderr, _("You must be root to run thermald!\n"));
		exit(1);
	}
	if(g_mkdir_with_parents(TDRUNDIR, 0755) != 0)
	{
		fprintf(stderr, "Cannot create '%s': %s", TDRUNDIR, strerror(errno));
		exit(1);
	}
	g_mkdir_with_parents(TDCONFDIR, 0755); // Don't care return value as directory
	// may already exist
	if(log_info)
	{
		thd_log_level |= G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO;
	}
	if(log_debug)
	{
		thd_log_level |= G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG;
	}
	if(poll_interval >= 0)
	{
		fprintf(stdout, "Polling enabled: %d\n", poll_interval);
		thd_poll_interval = poll_interval;
	}

	openlog("thermald", LOG_PID, LOG_USER | LOG_DAEMON | LOG_SYSLOG);
	// Don't care return val
	//setlogmask(LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_DEBUG | LOG_INFO);
	thd_daemonize = !no_daemon;
	g_log_set_handler(NULL, G_LOG_LEVEL_MASK, thd_logger, NULL);

	if(no_daemon)
		signal(SIGINT, sig_int_handler);

	// dbus glib processing begin
	thd_dbus_server_proc(no_daemon);

	fprintf(stdout, "Exiting ..\n");
	closelog();
	exit(success ? 0 : 1);
}
Esempio n. 4
0
/* Called before a cyrus application starts (but after command line parameters
 * are read) */
int cyrus_init(const char *alt_config, const char *ident, unsigned flags)
{
    char *p;
    const char *val;
    const char *prefix;
    int umaskval = 0;
    int syslog_opts = LOG_PID;

    if(cyrus_init_run != NOT_RUNNING) {
	fatal("cyrus_init called twice!", EC_CONFIG);
    } else {
	cyrus_init_run = RUNNING;
    }

    cyrus_init_nodb = (flags & CYRUSINIT_NODB);
#ifdef LOG_PERROR
    if ((flags & CYRUSINIT_PERROR))
	syslog_opts |= LOG_PERROR;
#endif

    initialize_imap_error_table();
    initialize_mupd_error_table();

    if(!ident)
	fatal("service name was not specified to cyrus_init", EC_CONFIG);

    config_ident = ident;
    
    /* xxx we lose here since we can't have the prefix until we load the
     * config file */
    openlog(config_ident, syslog_opts, SYSLOG_FACILITY);

    /* Load configuration file.  This will set config_dir when it finds it */
    config_read(alt_config);

    prefix = config_getstring(IMAPOPT_SYSLOG_PREFIX);

    /* Reopen the log with the new prefix, if needed  */    
    if(prefix) {
	int size = strlen(prefix) + 1 + strlen(ident) + 1;
	char *ident_buf = xmalloc(size);
	
	strlcpy(ident_buf, prefix, size);
	strlcat(ident_buf, "/", size);
	strlcat(ident_buf, ident, size);

	closelog();
	openlog(ident_buf, syslog_opts, SYSLOG_FACILITY);

	/* don't free the openlog() string! */
    }

    /* allow debug logging */
    if (!config_debug)
	setlogmask(~LOG_MASK(LOG_DEBUG));

    /* Look up default partition */
    config_defpartition = config_getstring(IMAPOPT_DEFAULTPARTITION);
    for (p = (char *)config_defpartition; p && *p; p++) {
	if (!Uisalnum(*p))
	  fatal("defaultpartition option contains non-alphanumeric character",
		EC_CONFIG);
	if (Uisupper(*p)) *p = tolower((unsigned char) *p);
    }

    /* Look up umask */
    val = config_getstring(IMAPOPT_UMASK);
    while (*val) {
	if (*val >= '0' && *val <= '7') umaskval = umaskval*8 + *val - '0';
	val++;
    }
    umask(umaskval);

    config_fulldirhash = config_getswitch(IMAPOPT_FULLDIRHASH);

    /* look up and canonify the implicit rights of mailbox owners */
    config_implicitrights =
	cyrus_acl_strtomask(config_getstring(IMAPOPT_IMPLICIT_OWNER_RIGHTS));

    config_metapartition_files = config_getbitfield(IMAPOPT_METAPARTITION_FILES);

    val = config_getstring(IMAPOPT_SUPPRESS_CAPABILITIES);
    if (val)
	suppressed_capabilities = strarray_split(val, NULL);
    if (config_getswitch(IMAPOPT_SEARCH_SKIPDIACRIT))
	charset_flags |= CHARSET_SKIPDIACRIT;

    switch (config_getenum(IMAPOPT_SEARCH_WHITESPACE)) {
	case IMAP_ENUM_SEARCH_WHITESPACE_MERGE:
	    charset_flags |= CHARSET_MERGESPACE;
	    break;
	case IMAP_ENUM_SEARCH_WHITESPACE_SKIP:
	    charset_flags |= CHARSET_SKIPSPACE;
	    break;
	default:
	    break;
    }

    if (!cyrus_init_nodb) {
	/* lookup the database backends */
	config_mboxlist_db = config_getstring(IMAPOPT_MBOXLIST_DB);
	config_quota_db = config_getstring(IMAPOPT_QUOTA_DB);
	config_subscription_db = config_getstring(IMAPOPT_SUBSCRIPTION_DB);
	config_annotation_db = config_getstring(IMAPOPT_ANNOTATION_DB);
	config_seenstate_db = config_getstring(IMAPOPT_SEENSTATE_DB);
	config_mboxkey_db = config_getstring(IMAPOPT_MBOXKEY_DB);
	config_duplicate_db = config_getstring(IMAPOPT_DUPLICATE_DB);
	config_tlscache_db = config_getstring(IMAPOPT_TLSCACHE_DB);
	config_ptscache_db = config_getstring(IMAPOPT_PTSCACHE_DB);
	config_statuscache_db = config_getstring(IMAPOPT_STATUSCACHE_DB);
	config_userdeny_db = config_getstring(IMAPOPT_USERDENY_DB);

	/* configure libcyrus as needed */
	libcyrus_config_setstring(CYRUSOPT_CONFIG_DIR, config_dir);
	libcyrus_config_setswitch(CYRUSOPT_AUTH_UNIX_GROUP_ENABLE,
				  config_getswitch(IMAPOPT_UNIX_GROUP_ENABLE));
	libcyrus_config_setswitch(CYRUSOPT_USERNAME_TOLOWER,
				  config_getswitch(IMAPOPT_USERNAME_TOLOWER));
	libcyrus_config_setswitch(CYRUSOPT_SKIPLIST_UNSAFE,
				  config_getswitch(IMAPOPT_SKIPLIST_UNSAFE));
	libcyrus_config_setstring(CYRUSOPT_TEMP_PATH,
				  config_getstring(IMAPOPT_TEMP_PATH));
	libcyrus_config_setint(CYRUSOPT_PTS_CACHE_TIMEOUT,
			       config_getint(IMAPOPT_PTSCACHE_TIMEOUT));
	libcyrus_config_setswitch(CYRUSOPT_FULLDIRHASH,
				  config_getswitch(IMAPOPT_FULLDIRHASH));
	libcyrus_config_setstring(CYRUSOPT_PTSCACHE_DB,
				  config_getstring(IMAPOPT_PTSCACHE_DB));
	libcyrus_config_setstring(CYRUSOPT_PTSCACHE_DB_PATH,
				  config_getstring(IMAPOPT_PTSCACHE_DB_PATH));
	libcyrus_config_setstring(CYRUSOPT_PTLOADER_SOCK,
				  config_getstring(IMAPOPT_PTLOADER_SOCK));
	libcyrus_config_setswitch(CYRUSOPT_VIRTDOMAINS,
				  config_getenum(IMAPOPT_VIRTDOMAINS));
	libcyrus_config_setint(CYRUSOPT_BERKELEY_CACHESIZE,
			       config_getint(IMAPOPT_BERKELEY_CACHESIZE));
	libcyrus_config_setstring(CYRUSOPT_AUTH_MECH,
				  config_getstring(IMAPOPT_AUTH_MECH));
	libcyrus_config_setint(CYRUSOPT_BERKELEY_LOCKS_MAX,
			       config_getint(IMAPOPT_BERKELEY_LOCKS_MAX));
	libcyrus_config_setint(CYRUSOPT_BERKELEY_TXNS_MAX,
			       config_getint(IMAPOPT_BERKELEY_TXNS_MAX));
	libcyrus_config_setstring(CYRUSOPT_DELETERIGHT,
				  config_getstring(IMAPOPT_DELETERIGHT));
	libcyrus_config_setstring(CYRUSOPT_SQL_DATABASE,
				  config_getstring(IMAPOPT_SQL_DATABASE));
	libcyrus_config_setstring(CYRUSOPT_SQL_ENGINE,
				  config_getstring(IMAPOPT_SQL_ENGINE));
	libcyrus_config_setstring(CYRUSOPT_SQL_HOSTNAMES,
				  config_getstring(IMAPOPT_SQL_HOSTNAMES));
	libcyrus_config_setstring(CYRUSOPT_SQL_USER,
				  config_getstring(IMAPOPT_SQL_USER));
	libcyrus_config_setstring(CYRUSOPT_SQL_PASSWD,
				  config_getstring(IMAPOPT_SQL_PASSWD));
	libcyrus_config_setswitch(CYRUSOPT_SQL_USESSL,
				  config_getswitch(IMAPOPT_SQL_USESSL));
	libcyrus_config_setswitch(CYRUSOPT_SKIPLIST_ALWAYS_CHECKPOINT,
				  config_getswitch(IMAPOPT_SKIPLIST_ALWAYS_CHECKPOINT));

	/* Not until all configuration parameters are set! */
	libcyrus_init();
    }
    
    return 0;
}
Esempio n. 5
0
/**
 * iucvtty_worker() - Handle an incoming client connection
 * @client:	Client file descriptor
 * @master:	PTY master file descriptor
 * @slave:	PTY slave file descriptor
 * @cfg:	IUCV TTY configuration structure.
 */
static int iucvtty_worker(int client, int master, int slave,
                          const struct iucvterm_cfg *cfg)
{
    int rc;
    struct iucvtty_msg *msg;
    pid_t child;
    fd_set set;
    size_t chunk;
    char term_env[TERM_BUFSIZE];


    /* flush pending terminal data */
    tcflush(master, TCIOFLUSH);

    /* read terminal parameters from client */
    if (iucvtty_rx_termenv(client, term_env, TERM_BUFSIZE))
        sprintf(term_env, TERM_DEFAULT);

    /* start login program */
    child = fork();
    if (child == -1) {
        print_error("Creating a new process to run the "
                    "login program failed");
        iucvtty_tx_error(client, ERR_FORK);
        return 1;	/* return from worker */
    }
    if (child == 0) {	/* child process */
        closelog();	/* close syslog */

        /* setup terminal */
        if (login_tty(slave)) {
            print_error("Setting up a terminal for user login failed");
            iucvtty_tx_error(client, ERR_SETUP_LOGIN_TTY);
            exit(2);
        }
        setenv("TERM", term_env, 1);
        if (exec_login_prog(cfg->cmd_parms)) {
            print_error("Running the login program failed");
            iucvtty_tx_error(client, ERR_CANNOT_EXEC_LOGIN);
        }
        exit(3);	/* we only reach here if exec has failed */
    }

    /* setup buffers */
    msg = malloc(MSG_BUFFER_SIZE);
    if (msg == NULL) {
        print_error("Allocating memory for the data buffer failed");
        rc = 2;
        goto out_kill_login;
    }

    /* multiplex i/o between login program and socket. */
    rc = 0;
    chunk = 0;
    while (!sig_shutdown) {
        FD_ZERO(&set);
        FD_SET(client, &set);
        FD_SET(master, &set);

        if (select(max(master, client) + 1, &set,
                   NULL, NULL, NULL) == -1) {
            if (errno == EINTR)
                continue;
            break;
        }

        if (FD_ISSET(client, &set)) {
            if (iucvtty_read_msg(client, msg,
                                 MSG_BUFFER_SIZE, &chunk))
                break;
            switch (msg->type) {
            case MSG_TYPE_DATA:
                iucvtty_copy_data(master, msg);
                break;
            case MSG_TYPE_WINSIZE:
                if (msg->datalen != sizeof(struct winsize))
                    break;
                if (ioctl(master, TIOCSWINSZ,
                          (struct winsize *) msg->data))
                    print_error("Resizing the terminal "
                                "window failed");
                break;
            case MSG_TYPE_TERMIOS:	/* ignored */
                break;
            case MSG_TYPE_ERROR:
                iucvtty_error(msg);
                break;
            }
        }

        if (FD_ISSET(master, &set))
            if (iucvtty_tx_data(client, master,
                                msg, MSG_BUFFER_SIZE))
                break;
    }
    free(msg);

out_kill_login:
    /* ensure the chld is terminated before calling waitpid:
     * - in case a sigterm has been received,
     * - or a sigchld from other than the chld
     */
    kill(child, SIGKILL);	/* cause a sigchld */
    waitpid(child, NULL, 0);

    return rc;
}
Esempio n. 6
0
SysLog::~SysLog()
{
	closelog();
}
Esempio n. 7
0
static void KRB5_CALLCONV
close_syslog(void *data)
{
    free(data);
    closelog();
}
void CSyslog::close()
{
	if(this->where == TOLOG)
		closelog();
	this->where = TOTTY;
}
Esempio n. 9
0
ContextdPluginLogger::~ContextdPluginLogger()
{
    closelog();
}
Esempio n. 10
0
int main(int argc, char **argv)
{
	const char *sopts = "hVvit:o:";
	struct option lopts[] = {
		{ "help", 0, 0, 'h' },
		{ "version", 0, 0, 'V' },
		{ "verbose", 0, 0, 'v' },
		{ "interactive", 0, 0, 'i' },
		{ "log", 1, 0, 'l' },
		{ "log-dir", 1, 0, 'r' },
		{ "pid-file", 1, 0, 'p' },
		{ "timestamp", 1, 0, 't' },
		{ "overflow-data", 1, 0, 'o'},
		{ 0 },
	};
	bool is_interactive = false;
	int ch;
	int syslog_option = LOG_CONS;
	int syslog_mask = LOG_MASK(LOG_WARNING)|LOG_MASK(LOG_ERR)|LOG_MASK(LOG_CRIT)|\
		          LOG_MASK(LOG_ALERT)|LOG_MASK(LOG_EMERG);
	int opt_ind = 0;
	char *pidfile = NULL;

	while ((ch = getopt_long(argc, argv, sopts, lopts, &opt_ind)) != -1) {
		switch (ch) {
		case 'h':
			usage(argv[0]);
			exit(0);
		case 'V':
			version(argv[0]);
			exit(0);
		case 'v':
#ifndef __sun__
			syslog_option |= LOG_PERROR;
#endif
			syslog_mask |= LOG_MASK(LOG_NOTICE)|LOG_MASK(LOG_INFO)| \
				      LOG_MASK(LOG_DEBUG);
			break;
		case 'i':
			is_interactive = true;
			break;
		case 'l':
		        if (!strcmp(optarg, "all")) {
			      log_hv = 1;
			      log_guest = 1;
			} else if (!strcmp(optarg, "hv")) {
			      log_hv = 1;
			} else if (!strcmp(optarg, "guest")) {
			      log_guest = 1;
			}
			break;
		case 'r':
		        log_dir = strdup(optarg);
			break;
		case 'p':
		        pidfile = strdup(optarg);
			break;
		case 't':
			if (!strcmp(optarg, "all")) {
				log_time_hv = 1;
				log_time_guest = 1;
			} else if (!strcmp(optarg, "hv")) {
				log_time_hv = 1;
			} else if (!strcmp(optarg, "guest")) {
				log_time_guest = 1;
			} else if (!strcmp(optarg, "none")) {
				log_time_guest = 0;
				log_time_hv = 0;
			}
			break;
		case 'o':
			if (!strcmp(optarg, "keep")) {
				discard_overflowed_data = 0;
			} else if (!strcmp(optarg, "discard")) {
				discard_overflowed_data = 1;
			}
			break;
		case '?':
			fprintf(stderr,
				"Try `%s --help' for more information\n",
				argv[0]);
			exit(EINVAL);
		}
	}

	if (!log_dir) {
		log_dir = strdup("/var/log/xen/console");
	}

	if (geteuid() != 0) {
		fprintf(stderr, "%s requires root to run.\n", argv[0]);
		exit(EPERM);
	}

	signal(SIGHUP, handle_hup);

	openlog("xenconsoled", syslog_option, LOG_DAEMON);
	setlogmask(syslog_mask);

	if (!is_interactive) {
		daemonize(pidfile ? pidfile : "/var/run/xenconsoled.pid");
	}

	if (!xen_setup())
		exit(1);

	handle_io();

	closelog();
	free(log_dir);
	free(pidfile);

	return 0;
}
Esempio n. 11
0
bool f_closelog() {
  closelog();
  return true;
}
Esempio n. 12
0
void
ns_os_shutdown(void) {
	closelog();
	cleanup_pidfile();
}
Esempio n. 13
0
void CLog::Close()
{
    Log::Debug("Close debug log");
    Log::TransAction("Close transaction log");
    closelog();
}
Esempio n. 14
0
static foreign_t
pl_closelog(void)
{ closelog();

  return TRUE;
}
Esempio n. 15
0
static void sigterm_handler()
{
  syslog(LOG_INFO, "Exiting daemon");
  closelog();
  exit(EXIT_SUCCESS);
} // sigterm_handler()
Esempio n. 16
0
/* Main */
int
main(int argc, char *argv[]) 
{
	struct sigaction	 sa;
	struct sockaddr_rfcomm	 ra;
	bdaddr_t		 addr;
	int			 n, background, channel, service,
				 s, amaster, aslave, fd, doserver,
				 dopty;
	fd_set			 rfd;
	char			*tty = NULL, *ep = NULL, buf[SPPD_BUFFER_SIZE];

	memcpy(&addr, NG_HCI_BDADDR_ANY, sizeof(addr));
	background = channel = 0;
	service = SDP_SERVICE_CLASS_SERIAL_PORT;
	doserver = 0;
	dopty = 0;

	/* Parse command line options */
	while ((n = getopt(argc, argv, "a:bc:thS")) != -1) {
		switch (n) { 
		case 'a': /* BDADDR */
			if (!bt_aton(optarg, &addr)) {
				struct hostent	*he = NULL;

				if ((he = bt_gethostbyname(optarg)) == NULL)
					errx(1, "%s: %s", optarg, hstrerror(h_errno));

				memcpy(&addr, he->h_addr, sizeof(addr));
			}
			break;

		case 'c': /* RFCOMM channel */
			channel = strtoul(optarg, &ep, 10);
			if (*ep != '\0') {
				channel = 0;
				switch (tolower(optarg[0])) {
				case 'd': /* DialUp Networking */
					service = SDP_SERVICE_CLASS_DIALUP_NETWORKING;
					break;

				case 'f': /* Fax */
					service = SDP_SERVICE_CLASS_FAX;
					break;

				case 'l': /* LAN */
					service = SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP;
					break;

				case 's': /* Serial Port */
					service = SDP_SERVICE_CLASS_SERIAL_PORT;
					break;

				default:
					errx(1, "Unknown service name: %s",
						optarg);
					/* NOT REACHED */
				}
			}
			break;

		case 'b': /* Run in background */
			background = 1;
			break;

		case 't': /* Open pseudo TTY */
			dopty = 1;
			break;

		case 'S':
			doserver = 1;
			break;

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

	/* Check if we have everything we need */
	if (!doserver && memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) == 0)
		usage();
		/* NOT REACHED */

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

	if (sigaction(SIGTERM, &sa, NULL) < 0)
		err(1, "Could not sigaction(SIGTERM)");
 
	if (sigaction(SIGHUP, &sa, NULL) < 0)
		err(1, "Could not sigaction(SIGHUP)");
 
	if (sigaction(SIGINT, &sa, NULL) < 0)
		err(1, "Could not sigaction(SIGINT)");

	sa.sa_handler = SIG_IGN;
	sa.sa_flags = SA_NOCLDWAIT;

	if (sigaction(SIGCHLD, &sa, NULL) < 0)
		err(1, "Could not sigaction(SIGCHLD)");

	/* Open TTYs */
	if (dopty) {
		if (sppd_ttys_open(&tty, &amaster, &aslave) < 0)
			exit(1);

		fd = amaster;
	} else {
		if (background)
			usage();

		amaster = STDIN_FILENO;
		fd = STDOUT_FILENO;
	}

	/* Open RFCOMM connection */

	if (doserver) {
		struct sockaddr_rfcomm	 ma;
		bdaddr_t		 bt_addr_any;
		sdp_sp_profile_t	 sp;
		void			*ss;
		uint32_t		 sdp_handle;
		int			 acceptsock, aaddrlen;

		acceptsock = socket(PF_BLUETOOTH, SOCK_STREAM,
					BLUETOOTH_PROTO_RFCOMM);
		if (acceptsock < 0)
			err(1, "Could not create socket");

		memcpy(&bt_addr_any, NG_HCI_BDADDR_ANY, sizeof(bt_addr_any));

		memset(&ma, 0, sizeof(ma));
		ma.rfcomm_len = sizeof(ma);
		ma.rfcomm_family = AF_BLUETOOTH;
		memcpy(&ma.rfcomm_bdaddr, &bt_addr_any, sizeof(bt_addr_any));
		ma.rfcomm_channel = channel;

		if (bind(acceptsock, (struct sockaddr *)&ma, sizeof(ma)) < 0)
			err(1, "Could not bind socket on channel %d", channel);
		if (listen(acceptsock, 10) != 0)
			err(1, "Could not listen on socket");

		aaddrlen = sizeof(ma);
		if (getsockname(acceptsock, (struct sockaddr *)&ma, &aaddrlen) < 0)
			err(1, "Could not get socket name");
		channel = ma.rfcomm_channel;

		ss = sdp_open_local(NULL);
		if (ss == NULL)
			errx(1, "Unable to create local SDP session");
		if (sdp_error(ss) != 0)
			errx(1, "Unable to open local SDP session. %s (%d)",
			    strerror(sdp_error(ss)), sdp_error(ss));
		memset(&sp, 0, sizeof(sp));
		sp.server_channel = channel;

		if (sdp_register_service(ss, SDP_SERVICE_CLASS_SERIAL_PORT,
				&bt_addr_any, (void *)&sp, sizeof(sp),
				&sdp_handle) != 0) {
			errx(1, "Unable to register LAN service with "
			    "local SDP daemon. %s (%d)",
			    strerror(sdp_error(ss)), sdp_error(ss));
		}

		s = -1;
		while (s < 0) {
			aaddrlen = sizeof(ra);
			s = accept(acceptsock, (struct sockaddr *)&ra,
			    &aaddrlen);
			if (s < 0)
				err(1, "Unable to accept()");
			if (memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) &&
			    memcmp(&addr, &ra.rfcomm_bdaddr, sizeof(addr))) {
				warnx("Connect from wrong client");
				close(s);
				s = -1;
			}
		}
		sdp_unregister_service(ss, sdp_handle);
		sdp_close(ss);
		close(acceptsock);
	} else {
		/* Check channel, if was not set then obtain it via SDP */
		if (channel == 0 && service != 0)
			if (rfcomm_channel_lookup(NULL, &addr,
				    service, &channel, &n) != 0)
				errc(1, n, "Could not obtain RFCOMM channel");
		if (channel <= 0 || channel > 30)
			errx(1, "Invalid RFCOMM channel number %d", channel);

		s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM);
		if (s < 0)
			err(1, "Could not create socket");

		memset(&ra, 0, sizeof(ra));
		ra.rfcomm_len = sizeof(ra);
		ra.rfcomm_family = AF_BLUETOOTH;

		if (bind(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
			err(1, "Could not bind socket");

		memcpy(&ra.rfcomm_bdaddr, &addr, sizeof(ra.rfcomm_bdaddr));
		ra.rfcomm_channel = channel;

		if (connect(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
			err(1, "Could not connect socket");
	}

	/* Became daemon if required */
	if (background && daemon(0, 0) < 0)
		err(1, "Could not daemon()");

	openlog(SPPD_IDENT, LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_DAEMON);
	syslog(LOG_INFO, "Starting on %s...", (tty != NULL)? tty : "stdin/stdout");

	/* Print used tty on stdout for wrappers to pick up */
	if (!background)
		fprintf(stdout, "%s\n", tty);

	for (done = 0; !done; ) {
		FD_ZERO(&rfd);
		FD_SET(amaster, &rfd);
		FD_SET(s, &rfd);

		n = select(max(amaster, s) + 1, &rfd, NULL, NULL, NULL);
		if (n < 0) {
			if (errno == EINTR)
				continue;

			syslog(LOG_ERR, "Could not select(). %s",
					strerror(errno));
			exit(1);
		}

		if (n == 0)
			continue;

		if (FD_ISSET(amaster, &rfd)) {
			n = sppd_read(amaster, buf, sizeof(buf));
			if (n < 0) {
				syslog(LOG_ERR, "Could not read master pty, " \
					"fd=%d. %s", amaster, strerror(errno));
				exit(1);
			}

			if (n == 0)
				break; /* XXX */

			if (sppd_write(s, buf, n) < 0) {
				syslog(LOG_ERR, "Could not write to socket, " \
					"fd=%d, size=%d. %s",
					s, n, strerror(errno));
				exit(1);
			}
		}

		if (FD_ISSET(s, &rfd)) {
			n = sppd_read(s, buf, sizeof(buf));
			if (n < 0) {
				syslog(LOG_ERR, "Could not read socket, " \
					"fd=%d. %s", s, strerror(errno));
				exit(1);
			}

			if (n == 0)
				break;

			if (sppd_write(fd, buf, n) < 0) {
				syslog(LOG_ERR, "Could not write to master " \
					"pty, fd=%d, size=%d. %s",
					fd, n, strerror(errno));
				exit(1);
			}
		}
	}

	syslog(LOG_INFO, "Completed on %s", (tty != NULL)? tty : "stdin/stdout");
	closelog();

	close(s);

	if (tty != NULL) {
		close(aslave);
		close(amaster);
	}	

	return (0);
}
Esempio n. 17
0
int su_main(int argc UNUSED_PARAM, char **argv)
{
	unsigned flags;
	char *opt_shell = NULL;
	char *opt_command = NULL;
	const char *opt_username = "******";
	struct passwd *pw;
	uid_t cur_uid = getuid();
	const char *tty;
#if ENABLE_FEATURE_UTMP
	char user_buf[64];
#endif
	const char *old_user;

	flags = getopt32(argv, "mplc:s:", &opt_command, &opt_shell);
	//argc -= optind;
	argv += optind;

	if (argv[0] && LONE_DASH(argv[0])) {
		flags |= SU_OPT_l;
		argv++;
	}

	/* get user if specified */
	if (argv[0]) {
		opt_username = argv[0];
		argv++;
	}

	if (ENABLE_FEATURE_SU_SYSLOG) {
		/* The utmp entry (via getlogin) is probably the best way to
		 * identify the user, especially if someone su's from a su-shell.
		 * But getlogin can fail -- usually due to lack of utmp entry.
		 * in this case resort to getpwuid.  */
#if ENABLE_FEATURE_UTMP
		old_user = user_buf;
		if (getlogin_r(user_buf, sizeof(user_buf)) != 0)
#endif
		{
			pw = getpwuid(cur_uid);
			old_user = pw ? xstrdup(pw->pw_name) : "";
		}
		tty = xmalloc_ttyname(2);
		if (!tty) {
			tty = "none";
		}
		openlog(applet_name, 0, LOG_AUTH);
	}

	pw = xgetpwnam(opt_username);

	if (cur_uid == 0 || ask_and_check_password(pw) > 0) {
		if (ENABLE_FEATURE_SU_SYSLOG)
			syslog(LOG_NOTICE, "%c %s %s:%s",
				'+', tty, old_user, opt_username);
	} else {
		if (ENABLE_FEATURE_SU_SYSLOG)
			syslog(LOG_NOTICE, "%c %s %s:%s",
				'-', tty, old_user, opt_username);
		bb_do_delay(LOGIN_FAIL_DELAY);
		bb_error_msg_and_die("incorrect password");
	}

	if (ENABLE_FEATURE_CLEAN_UP && ENABLE_FEATURE_SU_SYSLOG) {
		closelog();
	}

	if (!opt_shell && (flags & SU_OPT_mp)) {
		/* -s SHELL is not given, but "preserve env" opt is */
		opt_shell = getenv("SHELL");
	}

#if ENABLE_FEATURE_SU_CHECKS_SHELLS
	if (opt_shell && cur_uid != 0 && pw->pw_shell && restricted_shell(pw->pw_shell)) {
		/* The user being su'd to has a nonstandard shell, and so is
		 * probably a uucp account or has restricted access.  Don't
		 * compromise the account by allowing access with a standard
		 * shell.  */
		bb_error_msg("using restricted shell");
		opt_shell = NULL; /* ignore -s PROG */
	}
	/* else: user can run whatever he wants via "su -s PROG USER".
	 * This is safe since PROG is run under user's uid/gid. */
#endif
	if (!opt_shell)
		opt_shell = pw->pw_shell;

	change_identity(pw);
	setup_environment(opt_shell,
			((flags & SU_OPT_l) / SU_OPT_l * SETUP_ENV_CLEARENV)
			+ (!(flags & SU_OPT_mp) * SETUP_ENV_CHANGEENV)
			+ (!(flags & SU_OPT_l) * SETUP_ENV_NO_CHDIR),
			pw);
	IF_SELINUX(set_current_security_context(NULL);)
Esempio n. 18
0
	virtual ~CAdminLogMod() {
		Log("Logging ended.");
		closelog();
	}
Esempio n. 19
0
/* Signal to syslog that we're finished logging */
void terminate_syslog (void)
{
  closelog ();
}
Esempio n. 20
0
void wpa_debug_close_syslog(void)
{
	if (wpa_debug_syslog)
		closelog();
}
int main(int argc, char **argv) {

	openlog("redirect_rewrite", LOG_PID|LOG_CONS, LOG_USER);

	compile_patterns();
	/* Allocate some memory */
	content = (char*) malloc(sizeof(char) * BUF_SIZE);
	memset (content,0,sizeof(char) * BUF_SIZE);
	/* Check if the memory couldn't be allocated; if it's the case, handle the problem as appropriate. */
	if (NULL == content) {
#ifdef DEBUG
		perror("Could not allocate memory");
#endif
		return EXIT_FAILURE;
	}
	unsigned int n = 0;
	unsigned int localAllocatedSize, oldSize;
	localAllocatedSize = allocatedSize;

	memset (content,0,sizeof(char) * localAllocatedSize);
	int c;
	while((c = fgetc(stdin)) != EOF){

		if(n==localAllocatedSize){
			oldSize = localAllocatedSize;
			localAllocatedSize += INCR_SIZE;
			allocatedSize = localAllocatedSize;
			content = (char*) realloc(content, sizeof(char) * localAllocatedSize);
			if (NULL == content) {
				perror("Could not allocate memory");
				exit(1);
			}
			if(oldSize<localAllocatedSize)
				memset (content+oldSize,0,sizeof(char) * INCR_SIZE);
		}

		/* Read line into contents */
		if (c != '\n'){
			content[n] = c;
			n++;
			continue;
		}
		n=0;

		//printf("[X]Content %s \n\n", content);

		/* Grab the text up to the space character */
		char* channel = strtok (content, " ");

		char* url;
		if(channel != NULL){
			url = match(channel);

			/* Grab more text up to the next space character
			 * and try to get a redirect url match */
			char* original_url;
			if(NULL == url){
				original_url = strtok (NULL, " ");
				if(NULL != original_url){
					url = match(original_url);
				}
				printf("%s ", channel);
			}
			if(NULL == url){
				printf("\n");
				fflush(stdout);
			}else{

				if(NULL != url){
					char buffer[2048];
					printf("302:%s\n", url);
					fflush(stdout);
					sprintf (buffer, "Redirecting: %s", url);
					syslog(LOG_INFO, buffer);
				}else{
					printf("\n");
					fflush(stdout);
				}
			}

		}else{
			syslog(LOG_INFO, "No url found");
		}
		memset (content,0,sizeof(char) * localAllocatedSize);
	}
	closelog();
	return EXIT_SUCCESS;
}
Esempio n. 22
0
File: main.c Progetto: queensun/qtun
int main(int argc, char* argv[])
{
#ifdef HAVE_EXECINFO_H
    signal(SIGSEGV, crash_sig);
    signal(SIGABRT, crash_sig);
    signal(SIGPIPE, SIG_IGN);
#endif

#ifdef WIN32
    HANDLE localfd;
    WSADATA wsa;
    enum_device_t devs[MAX_DEVICE_COUNT];
#else
    int localfd;
#endif
    char cmd[1024];
    int remotefd;
    library_conf_t conf;
    int opt;
    struct in_addr a;

    struct option long_options[] = {
        { "conf", 1, NULL, 'c' },
        { NULL,   0, NULL,  0  }
    };
    char short_options[512] = {0};
    longopt2shortopt(long_options, sizeof(long_options) / sizeof(struct option), short_options);
#ifdef HAVE_SYSLOG_H
    openlog(argv[0], LOG_PERROR | LOG_CONS | LOG_PID, LOG_LOCAL0);
#endif

    qtun = calloc(sizeof(*qtun), 1);

#ifdef WIN32
    remotefd = -1;
    localfd = INVALID_HANDLE_VALUE;
#else
    localfd = remotefd = -1;
#endif
    {
        char path[MAX_PATH] = {0};
#ifdef WIN32
        strcpy(path, argv[0]);
#elif defined(__APPLE__)
        char tmp_path[sizeof(path)] = {0};
        uint32_t len = sizeof(path);
        if (_NSGetExecutablePath(tmp_path, &len) == -1) {
            perror("_NSGetExecutablePath");
            return 1;
        }
        if (readlink(tmp_path, path, sizeof(path)) == -1) {
            if (errno == EINVAL) strcpy(path, tmp_path);
            else {
                perror("readlink");
                return 1;
            }
        }
#else
        if (readlink("/proc/self/exe", path, sizeof(path)) == -1)
        {
            perror("readlink");
            return 1;
        }
#endif
        init_path(path);
    }
    conf_init(&conf);

    while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1)
    {
        switch (opt)
        {
        case 'c':
            {
                char* path = realpath(optarg, NULL);
                if (path == NULL) {
                    perror("realpath");
                    return 1;
                }
                strcpy(conf.conf_file, path);
                free(path);
            }
            break;
        default:
            fprintf(stderr, "param error\n");
            return 1;
        }
    }

#ifdef WIN32
    {
        size_t count = enum_devices(devs);
        if (count == 0)
        {
            fprintf(stderr, "have no QTun Virtual Adapter\n");
            return 1;
        }
        else if (count == 1)
        {
            strcpy(conf.dev_symbol, devs[0].dev_path);
            strcpy(conf.dev_name, devs[0].dev_name);
        }
        else
        {
            size_t i;
            char str[20] = { 0 };
            int n = -1;
            printf("Have Adapters:\n");
            for (i = 0; i < count; ++i)
            {
                printf("%lu: %s\n", i + 1, devs[i].dev_name);
            }
            printf("Choose One[1]: ");
            while (n == -1)
            {
                if (str[0] == '\n' && str[1] == 0) n = 1;
                else
                {
                    if (!is_int(str, sizeof(str))) continue;
                    n = atoi(str);
                    if (n < 1 || n > (int)count)
                    {
                        fprintf(stderr, "Invalid Number must >= 1 and <= %lu\n", count);
                        n = -1;
                        continue;
                    }
                }
            }
            strcpy(conf.dev_symbol, devs[n].dev_path);
            strcpy(conf.dev_name, devs[n].dev_name);
        }
    }
#endif
    
    init_lua();
    show_logo();
    script_load_config(qtun->lua, &conf, conf.conf_file);

#ifdef WIN32
    if (strlen(conf.dev_symbol) == 0)
    {
        fprintf(stderr, "Missing param [-e] or [--device]\n");
        return 1;
    }
#endif

#ifdef WIN32
    localfd = tun_open(conf.dev_symbol);
    if (localfd == INVALID_HANDLE_VALUE) return 1;
    fprintf(stdout, "%s opened\n", conf.dev_name);
#else
    memset(qtun->dev_name, 0, IFNAMSIZ);
    localfd = tun_open(qtun->dev_name);
    if (localfd == -1) return 1;
    syslog(LOG_INFO, "%s opened\n", qtun->dev_name);
#endif
    a.s_addr = conf.localip;

#ifdef WIN32
    WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
    if (strlen(conf.server) == 0)
    {
        if (conf.netmask == 0 || conf.netmask > 31)
        {
#ifdef WIN32
            WSACleanup();
#endif

            fprintf(stderr, "netmask must > 0 and <= 31\n");
            return 1;
        }
        library_init(conf);
        if (conf.localip == 0)
        {
            fprintf(stderr, "localip is zero\n");
            return 1;
        }
        if (strlen(conf.signature_file) == 0) {
            fprintf(stderr, "missing signature file\n");
            return 1;
        }
        qtun->is_server = 1;
        remotefd = bind_and_listen(conf.server_port);
        if (remotefd == -1)
        {
#ifdef WIN32
            WSACleanup();
#endif
            return 1;
        }
#ifdef WIN32
        {
            a.s_addr = conf.localip;
            sprintf(cmd, "netsh interface ip set address name=\"%s\" static %s %s", conf.dev_name, inet_ntoa(a), STR_LEN2MASK(conf.netmask));
            SYSTEM_EXIT(cmd);
        }
#elif defined(__APPLE__)
        {
            sprintf(cmd, "ifconfig %s %s/%u up", qtun->dev_name, inet_ntoa(a), conf.netmask);
            SYSTEM_EXIT(cmd);
            a.s_addr = conf.localip & LEN2MASK(conf.netmask);
            sprintf(cmd, "route add -net %s/%u %s", inet_ntoa(a), conf.netmask, inet_ntoa(a));
            SYSTEM_EXIT(cmd);
        }
#else
        {
            sprintf(cmd, "ifconfig %s %s/%u up", qtun->dev_name, inet_ntoa(a), conf.netmask);
            SYSTEM_EXIT(cmd);
            a.s_addr = conf.localip & LEN2MASK(conf.netmask);
            sprintf(cmd, "route add -net %s/%u dev %s", inet_ntoa(a), conf.netmask, qtun->dev_name);
            SYSTEM_EXIT(cmd);
        }
#endif
        server_loop(remotefd, localfd);
    }
    else
    {
#ifdef unix
        unsigned char mask;
#endif
        int inited = 0;
        library_init(conf);
        qtun->is_server = 0;
        while (1)
        {
            remotefd = connect_server(conf.server, conf.server_port);
            if (remotefd == -1)
            {
                SLEEP(5);
                continue;
            }
            a.s_addr = qtun->localip;
            if (qtun->localip == 0)
            {
                fprintf(stderr, "localip is zero\n");
                return 1;
            }
            if (strlen(conf.signature_file) == 0) {
                fprintf(stderr, "missing signature file\n");
                return 1;
            }
            if (!inited)
            {
#ifdef WIN32
                {
                    sprintf(cmd, "netsh interface ip set address name=\"%s\" static %s %s", conf.dev_name, inet_ntoa(a), STR_LEN2MASK(conf.netmask));
                    SYSTEM_EXIT(cmd);
                }
#elif defined(__APPLE__)
                {
                    char ip1[16], ip2[16];
                    a.s_addr = qtun->localip;
                    strcpy(ip1, inet_ntoa(a));
                    a.s_addr = qtun->client.local_ip;
                    strcpy(ip2, inet_ntoa(a));
                    sprintf(cmd, "ifconfig %s inet %s %s up", qtun->dev_name, ip1, ip2);
                    SYSTEM_EXIT(cmd);
                    mask = netmask();
                    a.s_addr = qtun->localip & LEN2MASK(mask);
                    sprintf(cmd, "route add -net %s/%u %s", inet_ntoa(a), mask, ip2);
                    SYSTEM_EXIT(cmd);
                }
#else
                {
                    sprintf(cmd, "ifconfig %s %s up", qtun->dev_name, inet_ntoa(a));
                    SYSTEM_EXIT(cmd);
                    mask = netmask();
                    a.s_addr = qtun->localip & LEN2MASK(mask);
                    sprintf(cmd, "route add -net %s/%u dev %s", inet_ntoa(a), mask, qtun->dev_name);
                    SYSTEM_EXIT(cmd);
                }
#endif
                inited = 1;
            }
            client_loop(remotefd, localfd);
            close(remotefd);
            SYSLOG(LOG_WARNING, "retry");
        }
    }
#ifdef WIN32
    WSACleanup();
#endif

#ifdef HAVE_SYSLOG_H
    closelog();
#endif

    library_free();
    return 0;
}
Esempio n. 23
0
/**
 * main() - IUCV TTY program startup
 */
int main(int argc, char *argv[])
{
    struct iucvterm_cfg	conf;		/* program configuration */
    struct sockaddr_iucv	saddr, caddr;	/* IUCV socket address info */
    char 			client_host[9];	/* client guest name */
    int 			server, client;	/* socket file descriptors */
    int 			master, slave;	/* pre-allocated PTY fds */
    struct sigaction	sigact;		/* signal handler */
    int 			rc;
    socklen_t		len;


    /* gettext initialization */
    gettext_init();

    /* parse command line arguments */
    parse_options(PROG_IUCV_TTY, &conf, argc, argv);

    /* create server socket... */
    server = iucvtty_socket(&saddr, NULL, conf.service);
    if (server == -1) {
        print_error((errno == EAFNOSUPPORT)
                    ? N_("The AF_IUCV address family is not available")
                    : N_("Creating the AF_IUCV socket failed"));
        return 1;
    }
    if (bind(server, (struct sockaddr *) &saddr, sizeof(saddr)) == -1) {
        print_error("Binding the AF_IUCV socket failed");
        close(server);
        return 1;
    }
    if (listen(server, 1) == -1) {
        print_error("Listening for incoming connections failed");
        close(server);
        return 1;
    }

    /* pre-allocate PTY master/slave file descriptors */
    if (openpty(&master, &slave, NULL, NULL, NULL)) {
        print_error("Opening a new PTY master/slave device pair failed");
        close(server);
        return 1;
    }

    /* set close-on-exec for file descriptors */
    fcntl(master, F_SETFD, FD_CLOEXEC);
    fcntl(server, F_SETFD, FD_CLOEXEC);

    /* syslog */
    openlog(SYSLOG_IDENT, LOG_PID, LOG_AUTHPRIV);
    syslog(LOG_INFO, "Listening on terminal ID: %s, using pts device: %s",
           conf.service, ttyname(slave));

    rc = 0;
    len = sizeof(struct sockaddr_iucv);
    /* accept a new client connection */
    client = accept(server, (struct sockaddr *) &caddr, &len);
    if (client == -1) {
        print_error("An incoming connection could not be accepted");
        rc = 2;
        goto exit_on_error;
    }

    /* check if client is allowed to connect */
    userid_cpy(client_host, caddr.siucv_user_id);
    if (is_client_allowed(client_host, &conf)) {
        iucvtty_tx_error(client, ERR_NOT_AUTHORIZED);
        syslog(LOG_WARNING, "Rejected client connection from %s; "
               "Client is not allowed to connect.",
               client_host);
        rc = 3;

    } else { /* client is allowed to connect */
        syslog(LOG_INFO, "Accepted client connection from %s",
               client_host);
        /* set close-on-exec for client socket */
        fcntl(client, F_SETFD, FD_CLOEXEC);
        /* close server socket */
        close(server);

        /* setup signal handler to notify shutdown signal */
        sigemptyset(&sigact.sa_mask);
        sigact.sa_flags = SA_RESTART;
        sigact.sa_handler = sig_handler;
        if (sigaction(SIGCHLD, &sigact, NULL)
                || sigaction(SIGTERM, &sigact, NULL)
                || sigaction(SIGINT,  &sigact, NULL)
                || sigaction(SIGPIPE, &sigact, NULL)) {
            print_error("Registering a signal handler failed");
            rc = 4;
            goto exit_on_error;
        }

        /* handle client terminal connection */
        rc = iucvtty_worker(client, master, slave, &conf);
    }

    close(client);

exit_on_error:
    close(slave);
    close(master);
    closelog();

    return rc;
}
Esempio n. 24
0
int
main(int argc, char *argv[])
{
	int ch, ret, mode = MODE_LOGIN;
	FILE *f = NULL;
	char *username, *password = NULL;
	char response[1024];

	setpriority(PRIO_PROCESS, 0, 0);
	openlog(NULL, LOG_ODELAY, LOG_AUTH);

	while ((ch = getopt(argc, argv, "dv:s:")) != -1) {
		switch (ch) {
		case 'd':
			f = stdout;
			break;
		case 'v':
			break;
		case 's':
			if (!strcmp(optarg, "login"))
				mode = MODE_LOGIN;
			else if (!strcmp(optarg, "response"))
				mode = MODE_RESPONSE;
			else if (!strcmp(optarg, "challenge"))
				mode = MODE_CHALLENGE;
			else {
				syslog(LOG_ERR, "%s: invalid service", optarg);
				exit(EXIT_FAILURE);
			}
			break;
		default:
			syslog(LOG_ERR, "usage error1");
			exit(EXIT_FAILURE);
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 2 && argc != 1) {
		syslog(LOG_ERR, "usage error2");
		exit(EXIT_FAILURE);
	}
	username = argv[0];
	/* passed by sshd(8) for non-existing users */
	if (!strcmp(username, "NOUSER"))
		exit(EXIT_FAILURE);
	if (!clean_string(username)) {
		syslog(LOG_ERR, "clean_string username");
		exit(EXIT_FAILURE);
	}

	if (f == NULL && (f = fdopen(3, "r+")) == NULL) {
		syslog(LOG_ERR, "user %s: fdopen: %m", username);
		exit(EXIT_FAILURE);
	}

	switch (mode) {
		case MODE_LOGIN:
			if ((password = getpass("Password:"******"user %s: getpass: %m",
				    username);
				exit(EXIT_FAILURE);
			}
			break;
		case MODE_CHALLENGE:
			/* see login.conf(5) section CHALLENGES */
			fprintf(f, "%s\n", BI_SILENT);
			exit(EXIT_SUCCESS);
			break;
		case MODE_RESPONSE: {
			/* see login.conf(5) section RESPONSES */
			/* this happens e.g. when called from sshd(8) */
			int count;
			mode = 0;
			count = -1;
			while (++count < sizeof(response) &&
			    read(3, &response[count], (size_t)1) ==
			    (ssize_t)1) {
				if (response[count] == '\0' && ++mode == 2)
					break;
				if (response[count] == '\0' && mode == 1) {
					password = response + count + 1;
				}
			}
			if (mode < 2) {
				syslog(LOG_ERR, "user %s: protocol error "
				    "on back channel", username);
				exit(EXIT_FAILURE);
			}
			break;
		}
	}

	ret = yubikey_login(username, password);
	memset(password, 0, strlen(password));
	if (ret == AUTH_OK) {
		syslog(LOG_INFO, "user %s: authorize", username);
		fprintf(f, "%s\n", BI_AUTH);
	} else {
		syslog(LOG_INFO, "user %s: reject", username);
		fprintf(f, "%s\n", BI_REJECT);
	}
	closelog();
	return (EXIT_SUCCESS);
}
Esempio n. 25
0
void *statistica(void *in) // in ?
{
struct ethhdr *packet;
struct sockaddr_ll sock_ether;
struct prism *hdr;
struct beacon *beacon_sniffed;

unsigned char buf[BUFSIZE];

int bytes_received, eth_index;
int sd;
fd_set fds;

//flags per le if
int beacon_flag=0;
int data_flag=0;
int wds_flag=0;
int retry_flag=0;
int adhoc_flag=0;
int vlan_flag=0;

char ESSID[MAXESSIDSIZE]; 
unsigned char MACTEMP[7];
char command[50];

int record=3;

//statistiche generali per tutto l'AP
int bestRSSI=-100;
int worstRSSI=1;
int avgRSSI=0;


if (DEBUG) printf("Sniff IFACE is set to %s\n",SNIFF_IFACE);

//Let's open the raw socket with the sniffing interface
if((sd=socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))<0)
{
perror("socket");
exit(errno); //no return() perchè è un thread
}

if (DEBUG) printf("Checkpoint1\n");

if((eth_index = initialize(SNIFF_IFACE, sd, 1))<0)
{
exit(errno);
}

if (DEBUG) printf("Checkpoint2\n");

memset(&sock_ether, 0, sizeof(sock_ether));
sock_ether.sll_family = AF_PACKET;
sock_ether.sll_protocol = htons(ETH_P_ALL);
sock_ether.sll_ifindex = eth_index;

if(bind(sd, (struct sockaddr *)(&sock_ether), sizeof(sock_ether))<0)
{
perror("bind");
exit(errno);
}



while(1)
{
FD_ZERO(&fds);
FD_SET (sd, &fds);

if ((select(sd+1, &fds, NULL, NULL, NULL)) < 0)
{
perror ("select");
exit(errno);
}

if(FD_ISSET(sd, &fds))
{
if((bytes_received=read(sd, buf, sizeof buf))<0)
{
perror("read from ethernet failed");
exit(errno);
}
//Inserisco i dati del buffer nelle strutture per pescare le informazioni
packet = (struct ethhdr *)buf;
hdr = (struct prism *)buf;
beacon_sniffed = (struct beacon *)buf;

//Setto i vari flags analizzando il pacchetto:

//Data o Beacon?
/*
if (hdr->fc.header != 0x80 && hdr->fc.header != 0x08)
printf("WARNING, header type not known %02X\n",hdr->fc.header);
*/ 
 if (hdr->fc.header == 0x80) 
 beacon_flag=1;
else  
 beacon_flag=0;

 if (hdr->fc.header == 0x08) 
 data_flag=1;
else  
 data_flag=0;

 //controllo il bit retry (dovrei farlo solo per pacchetti data?)
if ((hdr->fc.flags | 0xF7) == 0xFF)
 retry_flag=1;
else
 retry_flag=0;

//Controllo bits toDS e fromDS per vedere di che tipo è il frame
if ((hdr->fc.flags | 0xFC) == 0xFF)
 wds_flag=1;
else 
 wds_flag=0;

 if ((hdr->fc.flags | 0xFC) == 0xFC) 
 adhoc_flag=1;
else 
 adhoc_flag=0;

//Controllo se il frame ha un tag vlan
if (hdr->llclayer.type == 0x0081) //zozzata, dovrebbe essere 8100, ma non faccio swap 
	vlan_flag=1;
else
	vlan_flag=0;

if (beacon_flag) 
{

if (DEBUG) printf("Entro in if beacon_flag\n");

//inserisco nella variabile di tipo string "ESSID" l'ESSID del beacon che sto processando
memset(ESSID,0,MAXESSIDSIZE);
memcpy(ESSID,&(beacon_sniffed->Tagged_Parameters[2]),beacon_sniffed->Tagged_Parameters[1]);

	if (!strcmp(ESSID,myESSID)) //controllo se è un beacon con ESSID uguale al mio
	{	
	
	if (DEBUG) printf("è arrivato un beacon uguale al mio\n");
	
	//Inserisco dentro MACTEMP il MAC dell'AP con ESSID uguale al mio, 

	memset(MACTEMP,0,7);
	MACTEMP[0]=beacon_sniffed->MAC2[0];
	MACTEMP[1]=beacon_sniffed->MAC2[1];
	MACTEMP[2]=beacon_sniffed->MAC2[2];
	MACTEMP[3]=beacon_sniffed->MAC2[3];
	MACTEMP[4]=beacon_sniffed->MAC2[4];
	MACTEMP[5]=beacon_sniffed->MAC2[5];	
	
	//ora devo controllare che non ho gia un WDS con lui e se no aggiungerlo ai miei WDS
	
	//semaforo
	if (DEBUG) printf("Aspetto il semafono\n");
	sem_wait(&(primo->mutex));
	
			if (primo->next==NULL)//se non esiste un secondo
			{ 
					//controllo se il primo è vuoto
					if (primo->MAC_AP[0] == 0xFF)
					{//se si lo riempio
					memset(primo->MAC_AP,0,7);										
					primo->MAC_AP[0]=MACTEMP[0];
					primo->MAC_AP[1]=MACTEMP[1];
					primo->MAC_AP[2]=MACTEMP[2];
					primo->MAC_AP[3]=MACTEMP[3];
					primo->MAC_AP[4]=MACTEMP[4];
					primo->MAC_AP[5]=MACTEMP[5];
				
					primo->bestRSSI=-100;
					primo->worstRSSI=1;
					primo->avgRSSI=0;
					primo->bestRSSIcolor5=-100;
					primo->worstRSSIcolor5=1;
					primo->avgRSSIcolor5=0;
					primo->bestRSSIcolor6=-100;
					primo->worstRSSIcolor6=1;
					primo->avgRSSIcolor6=0;
					primo->record_number=3;
					
					if (BROADCOM) 
					{
					memset(command,0,50);
					sprintf(command,"wl wds | wl wds %02X:%02X:%02X:%02X:%02X:%02X ",MACTEMP[0],MACTEMP[1],MACTEMP[2],MACTEMP[3],MACTEMP[4],MACTEMP[5]);
					system(command);
					}
					if (ATHEROS) 
					{
					memset(command,0,50);
					sprintf(command,"wlanconfig ath%d create wlandev wifi0 wlanmode wds",3);
					system(command);
					memset(command,0,50);
					sprintf(command,"iwpriv ath%d wds_add %02X:%02X:%02X:%02X:%02X:%02X ",3,MACTEMP[0],MACTEMP[1],MACTEMP[2],MACTEMP[3],MACTEMP[4],MACTEMP[5]);
					system(command);
					memset(command,0,50);
					sprintf(command,"iwpriv ath%d wds 1",3);
					system(command);
					//ifconfig ath1 up
					}
					
					}
			else
			{ //se il primo è pieno
						
					if( memcmp(primo->MAC_AP,MACTEMP,sizeof(primo->MAC_AP)) ) //check che non sia gia un WDS noto
					{
					succ=(struct statistica_link*) malloc(sizeof(struct statistica_link));
					if (sem_init(&succ->mutex,0,1) == -1 )  //va fatto ogni volta che si fa un malloc
					{
					perror("Non sono riuscito ad inizializzare i semafori");
					exit(errno);
					}
					memcpy(succ->MAC_AP,MACTEMP,7);
					succ->bestRSSI=-100;
					succ->worstRSSI=1;
					succ->avgRSSI=0;
					succ->bestRSSIcolor5=-100;
					succ->worstRSSIcolor5=1;
					succ->avgRSSIcolor5=0;
					succ->bestRSSIcolor6=-100;
					succ->worstRSSIcolor6=1;
					succ->avgRSSIcolor6=0;
					succ->record_number=4;
					
					
					if (BROADCOM)
					{
					memset(command,0,50);
					sprintf(command,"wl wds | wl wds %02X:%02X:%02X:%02X:%02X:%02X ",MACTEMP[0],MACTEMP[1],MACTEMP[2],MACTEMP[3],MACTEMP[4],MACTEMP[5]);					
					system(command);
					}
					
					if (ATHEROS)
					{					
					memset(command,0,50);
					sprintf(command,"wlanconfig ath%d create wlandev wifi0 wlanmode wds",4);
					system(command);
					memset(command,0,50);
					sprintf(command,"iwpriv ath%d wds_add %02X:%02X:%02X:%02X:%02X:%02X ",4,MACTEMP[0],MACTEMP[1],MACTEMP[2],MACTEMP[3],MACTEMP[4],MACTEMP[5]);
					system(command);
					memset(command,0,50);
					sprintf(command,"iwpriv ath%d wds 1",4);
					system(command);
					
					}
					primo->next=succ;
					succ->next=NULL;
					succ=primo;
					}
			}
			}
			else //(se il primo e il secondo sono pieni) 
			{		
					do
					{
					prec=prec->next;
					record=record+1;
						if (!memcmp(prec->MAC_AP,MACTEMP,sizeof(prec->MAC_AP)))
						{
						prec=primo;
						succ=primo;
						record=3;
						break;
						}
					}
					while (prec->next!=NULL);
			
				if (prec->next == NULL)
				{
				succ=(struct statistica_link*) malloc(sizeof(struct statistica_link));
				memcpy(succ->MAC_AP,MACTEMP,7);
				succ->bestRSSI=-100;
				succ->worstRSSI=1;
				succ->avgRSSI=0;
				succ->bestRSSIcolor5=-100;
				succ->worstRSSIcolor5=1;
				succ->avgRSSIcolor5=0;
				succ->bestRSSIcolor6=-100;
				succ->worstRSSIcolor6=1;
				succ->avgRSSIcolor6=0;
				succ->record_number=record;
				
				if (BROADCOM)
				{				
				memset(command,0,50);
				sprintf(command,"wl wds | wl wds %02X:%02X:%02X:%02X:%02X:%02X ",MACTEMP[0],MACTEMP[1],MACTEMP[2],MACTEMP[3],MACTEMP[4],MACTEMP[5]);				
				system(command);
				}
				if (ATHEROS)
				{
				memset(command,0,50);
				sprintf(command,"wlanconfig ath%d create wlandev wifi0 wlanmode wds",record);
				system(command);
				memset(command,0,50);
				sprintf(command,"iwpriv ath%d wds_add %02X:%02X:%02X:%02X:%02X:%02X ",record,MACTEMP[0],MACTEMP[1],MACTEMP[2],MACTEMP[3],MACTEMP[4],MACTEMP[5]);
				system(command);
				memset(command,0,50);
				sprintf(command,"iwpriv ath%d wds 1",record);
				system(command);
				}
				
				prec->next=succ;
				succ->next=NULL;
				prec=primo;
				succ=primo;
				record=3;
				}
				 
			}
		sem_post(&primo->mutex); //libero il semaforo
	}


//debug to display
if (DEBUG) {
printf("Beacon Received\n");
printf("Lenght of ESSID: %d\n",beacon_sniffed->Tagged_Parameters[1]);
printf("ESSID: %s\n",ESSID);
if (BROADCOM) system("wl wds");
printf("\n");
}

} //end if beacon_flag

if (wds_flag)
{
	//faccio i conti sull'RSSI generico, variabili globali non quelle nella lista a puntatori
	if (hdr->RSSI.value > bestRSSI) bestRSSI=hdr->RSSI.value;

	if (hdr->RSSI.value < worstRSSI) worstRSSI=hdr->RSSI.value;
	
	if (avgRSSI != 0) avgRSSI=avgRSSI*(1-PESO)+(hdr->RSSI.value*PESO);
	else avgRSSI=hdr->RSSI.value;
	
	//Metto in MACTEMP il MAC sorgente del pacchetto arrivato
    memset(MACTEMP,0,7);
    MACTEMP[7]='\0';
    memcpy(MACTEMP,hdr->MAC2,6);
    
	
	//Write statistics to syslogd
	openlog("RASTA", LOG_WARNING || LOG_PID, LOG_DAEMON);
	syslog(LOG_WARNING,"RSSI: %d\t MAC:%s\n",hdr->RSSI.value,MACTEMP);
	closelog();
	
	if (primo->next==NULL)//se non esiste un secondo
			{ 
					if(!memcmp(primo->MAC_AP,MACTEMP,sizeof(primo->MAC_AP))) // se il primo record è gia quello giusto
					{
						if (hdr->RSSI.value > primo->bestRSSI) primo->bestRSSI=hdr->RSSI.value;
						if (hdr->RSSI.value < primo->worstRSSI) primo->worstRSSI=hdr->RSSI.value;
	
						if (primo->avgRSSI != 0) primo->avgRSSI=primo->avgRSSI*(1-PESO)+(hdr->RSSI.value*PESO);
						else primo->avgRSSI=hdr->RSSI.value;
					
						if (vlan_flag)
						{
							if (hdr->vlan.info[1] == 0x05)
							{
								if (hdr->RSSI.value > primo->bestRSSIcolor5) primo->bestRSSIcolor5=hdr->RSSI.value;
								if (hdr->RSSI.value < primo->worstRSSIcolor5) primo->worstRSSIcolor5=hdr->RSSI.value;
	
								if (primo->avgRSSIcolor5 != 0) primo->avgRSSIcolor5=primo->avgRSSIcolor5*(1-PESO)+(hdr->RSSI.value*PESO);
								else primo->avgRSSIcolor5=hdr->RSSI.value;
							}
	
							if (hdr->vlan.info[1] == 0x06)
							{
								if (hdr->RSSI.value > primo->bestRSSIcolor6) primo->bestRSSIcolor6=hdr->RSSI.value;
								if (hdr->RSSI.value < primo->worstRSSIcolor6) primo->worstRSSIcolor6=hdr->RSSI.value;
	
								if (primo->avgRSSIcolor6 != 0) primo->avgRSSIcolor6=primo->avgRSSIcolor6*(1-PESO)+(hdr->RSSI.value*PESO);
								else primo->avgRSSIcolor6=hdr->RSSI.value;
							}
							
							
						}					
					}
			
			}
			else //(se il primo non è quello giusto)
			{		
					do
					{
					prec=prec->next;
						if (!memcmp(prec->MAC_AP,MACTEMP,sizeof(prec->MAC_AP)))
						{
							if (hdr->RSSI.value > prec->bestRSSI) prec->bestRSSI=hdr->RSSI.value;
							if (hdr->RSSI.value < prec->worstRSSI) prec->worstRSSI=hdr->RSSI.value;
	
							if (prec->avgRSSI != 0) prec->avgRSSI=prec->avgRSSI*(1-PESO)+(hdr->RSSI.value*PESO);
							else prec->avgRSSI=hdr->RSSI.value;
					
							if (vlan_flag)
							{
								if (hdr->vlan.info[1] == 0x05)
								{
									if (hdr->RSSI.value > prec->bestRSSIcolor5) prec->bestRSSIcolor5=hdr->RSSI.value;
									if (hdr->RSSI.value < prec->worstRSSIcolor5) prec->worstRSSIcolor5=hdr->RSSI.value;
	
									if (prec->avgRSSIcolor5 != 0) prec->avgRSSIcolor5=prec->avgRSSIcolor5*(1-PESO)+(hdr->RSSI.value*PESO);
									else prec->avgRSSIcolor5=hdr->RSSI.value;
								}
							
							
								if (hdr->vlan.info[1] == 0x06)
								{
									if (hdr->RSSI.value > prec->bestRSSIcolor6) prec->bestRSSIcolor6=hdr->RSSI.value;
									if (hdr->RSSI.value < prec->worstRSSIcolor6) prec->worstRSSIcolor6=hdr->RSSI.value;	
									if (prec->avgRSSIcolor6 != 0) prec->avgRSSIcolor6=prec->avgRSSIcolor6*(1-PESO)+(hdr->RSSI.value*PESO);
									else prec->avgRSSIcolor6=hdr->RSSI.value;
								}							
							}						
							prec=primo;
							succ=primo;
							break;
						}
					}
					while (prec->next!=NULL);	
				prec=primo;
				succ=primo;
			}
/* if (DEBUG) {
//debug to display
printf("---------------------\n");
printf("Best RSSI is: %d\n", bestRSSI);
printf("Worst RSSI is: %d\n", worstRSSI);
printf("Average RSSI is: %d\n", avgRSSI);

printf("Bytes Received");
printf("  %d\n\n", bytes_received);

//controllo il bit retry
if (retry_flag) printf("Frame is a Retrasmission\n");
//debug printf("hdr->llclayer.type %04X\n",hdr->llclayer.type);
if (vlan_flag) printf("Frame is vlan tagged of color %02X%02X\n",hdr->vlan.info[0],hdr->vlan.info[1]);

// debug printf("Header: 08 è Data, 80 è Mng, io ho letto %02X\n",hdr->fc.header);
printf("RSSI");
printf("  %d\n\n", hdr->RSSI.value);

printf("Data Rate");
printf("  %d\n\n", hdr->Data_Rate.value);

printf("Receiver MAC Address");
printf("  %02X:%02X:%02X:%02X:%02X:%02X\n\n", hdr->MAC1[0], hdr->MAC1[1], hdr->MAC1[2], hdr->MAC1[3], hdr->MAC1[4], hdr->MAC1[5]);
printf("Transmitter MAC Address");
printf("  %02X:%02X:%02X:%02X:%02X:%02X\n\n", hdr->MAC2[0], hdr->MAC2[1], hdr->MAC2[2], hdr->MAC2[3], hdr->MAC2[4], hdr->MAC2[5]);
printf("3rd MAC Address");
printf("  %02X:%02X:%02X:%02X:%02X:%02X\n\n", hdr->MAC3[0], hdr->MAC3[1], hdr->MAC3[2], hdr->MAC3[3], hdr->MAC3[4], hdr->MAC3[5]);
printf("4th MAC Address");
printf("  %02X:%02X:%02X:%02X:%02X:%02X\n\n", hdr->MAC4[0], hdr->MAC4[1], hdr->MAC4[2], hdr->MAC4[3], hdr->MAC4[4], hdr->MAC4[5]);

printf("Sequence Number");
printf("  %d\n", hdr->Sequence_Number);
}
*/
} //end if wds_flag

}
} //end while(1)
return NULL;
}
Esempio n. 26
0
int main(int argc, char *argv[]) {

	// To set our logging mask and open the log.
	//
	// int setlogmask(int mask);
	// mask:
	// LOG_NOTICE, normal, but significant, condition
	setlogmask( LOG_UPTO(LOG_NOTICE) );

	// send messages to the system logger.
	//
	// void openlog(const char *ident, int option, int facility);
	// The option argument specifies flags which control the operation of openlog().
	// The facility argument establishes a default to be used if none is specified
	// in subsequent calls to syslog().
	openlog(DAEMON_NAME,  LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER);
	syslog(LOG_INFO, "Entering Daemon");


	pid_t pid, sid;

	// To fork a parent rocess.
	// On success, the PID of the child process is returned in the parent,
	// and 0 is returned in the child.
	pid = fork();

	// error
	if (pid < 0) {

		printf("error happen\n");
		exit(EXIT_FAILURE);

	// child process
	}else if (pid == 0){

		printf("in the child, pid: %d\n", pid);

	// parent process
	}else if (pid > 0) {

		printf("in the parent, pid: %d\n", pid);
		exit(EXIT_SUCCESS);

	}

	// To change file mask.
	umask(0);

	// To create a new session for our child.
	sid = setsid();
	if (sid < 0) {
		 exit(EXIT_FAILURE);
	}

	// To change directory.
	ret_chdir = chdir("~/");
	if (ret_chdir < 0) {
		 exit(EXIT_FAILURE);
	}

	// To close standard file descriptors.
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	// The daemon is starting.
	while(1){

		process();    // run our process
		sleep(3);

	}

	// To close the log.
	closelog ();
}
Esempio n. 27
0
// Setup dbus server
static int thd_dbus_server_proc(gboolean no_daemon)
{
	DBusGConnection *bus;
	DBusGProxy *bus_proxy;
	GMainLoop *main_loop;
	GError *error = NULL;
	guint result;
	PrefObject *value_obj;

	// Initialize the GType/GObject system
	g_type_init();

	// Create a main loop that will dispatch callbacks
	main_loop = g_main_loop_new(NULL, FALSE);
	if(main_loop == NULL)
	{
		thd_log_error("Couldn't create GMainLoop:");
		return THD_FATAL_ERROR;
	}
	if(dbus_enable)
	{
		bus = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
		if(error != NULL)
		{
			thd_log_error("Couldn't connect to session bus: %s:", error->message);
			return THD_FATAL_ERROR;
		}

		// Get a bus proxy instance
		bus_proxy = dbus_g_proxy_new_for_name(bus, DBUS_SERVICE_DBUS, DBUS_PATH_DBUS,
	DBUS_INTERFACE_DBUS);
		if(bus_proxy == NULL)
		{
			thd_log_error("Failed to get a proxy for D-Bus:");
			return THD_FATAL_ERROR;
		}

		thd_log_debug("Registering the well-known name (%s)\n", THD_SERVICE_NAME);
		// register the well-known name
		if(!dbus_g_proxy_call(bus_proxy, "RequestName",  &error, G_TYPE_STRING,
	THD_SERVICE_NAME, G_TYPE_UINT, 0, G_TYPE_INVALID, G_TYPE_UINT,  &result,
	G_TYPE_INVALID))
		{
			thd_log_error("D-Bus.RequestName RPC failed: %s\n", error->message);
			return THD_FATAL_ERROR;
		}
		thd_log_debug("RequestName returned %d.\n", result);
		if(result != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
		{
			thd_log_error("Failed to get the primary well-known name:");
			return THD_FATAL_ERROR;
		}
		value_obj = (PrefObject*)g_object_new(PREF_TYPE_OBJECT, NULL);
		if(value_obj == NULL)
		{
			thd_log_error("Failed to create one Value instance:");
			return THD_FATAL_ERROR;
		}

		thd_log_debug("Registering it on the D-Bus.\n");
		dbus_g_connection_register_g_object(bus, THD_SERVICE_OBJECT_PATH, G_OBJECT
	(value_obj));
	}
	if(!no_daemon)
	{
		printf("Ready to serve requests: Daemonizing.. %d\n", thd_daemonize);
		thd_log_info("thermald ver %s: Ready to serve requests: Daemonizing..\n", TD_DIST_VERSION);

		if(daemon(0, 1) != 0)
		{
			thd_log_error("Failed to daemonize.\n");
			return THD_FATAL_ERROR;
		}
	}

	if(use_thermal_sys_fs)
		thd_engine = new cthd_engine_therm_sysfs();
	else
	{
		cthd_parse parser;
		bool matched = false;

		// if there is XML config for this platform
		// Use this instead of default DTS sensor and associated cdevs
		if(parser.parser_init() == THD_SUCCESS)
		{
			if(parser.start_parse() == THD_SUCCESS)
			{
				matched = parser.platform_matched();
			}
		}
		if (matched) {
			thd_log_warn("UUID matched, so will load zones and cdevs from thermal-conf.xml\n");
			thd_engine = new cthd_engine_therm_sysfs();
		}
		else
			thd_engine = new cthd_engine_dts();
	}
	// Initialize thermald objects
	if(thd_engine->thd_engine_start() != THD_SUCCESS)
	{
		thd_log_error("THD engine start failed: ");
		closelog();
		exit(1);
	}

	// Start service requests on the D-Bus
	thd_log_debug("Start main loop\n");
	g_main_loop_run(main_loop);
	thd_log_warn("Oops g main loop exit..\n");
	return THD_SUCCESS;
}
Esempio n. 28
0
/**
  * Read an integer giving the maximum size of a fragment.
  */
int main( int argc, char *argv[] ) {

	int fail = 0;

	erl_init(NULL,0);
#ifdef _DEBUG
	openlog( "erlang-port", 0, LOG_USER );
	syslog( LOG_INFO, "%s is alive\n", argv[0] );
#endif
	while( ! fail ) {

		ETERM *fragsize_term = NULL;
		byte buf[100 /*WIRE_SIZEOF_INT*/];
		if( read_lpm( buf, sizeof(buf) ) <= 0 ) {
#ifdef _DEBUG
			syslog( LOG_ERR, "failed reading fragment size:\n" );
#endif
			break;
		}

		fragsize_term = erl_decode( buf );

		if( fragsize_term ) {

			ETERM **array;
			unsigned int count;
			unsigned int SIZEOF_FRAGMENT
				= ERL_INT_UVALUE(fragsize_term);
			erl_free_term( fragsize_term );

			if( SIZEOF_FRAGMENT == 0 /* the explicit signal to shutdown */ )
				break;

#ifdef _DEBUG
			syslog( LOG_INFO, "received sizeof fragment: %d\n", SIZEOF_FRAGMENT );
#endif

			count = min_packet_count( SIZEOF_IMAGE, SIZEOF_FRAGMENT );
			array = calloc( count, sizeof(ETERM*) );
			if( array ) {
				ETERM *frags;
				for(int i = 0; i < count; i++ ) {
					const size_t S
						= i+1 < count
						? SIZEOF_FRAGMENT
						: (SIZEOF_IMAGE % SIZEOF_FRAGMENT);
					array[i] = erl_mk_binary(
						TEST_IMAGE + i*SIZEOF_FRAGMENT, S );
					if( array[i] == NULL ) {
						count = i; // ...for erl_free_array below.
						fail = 1;
						break;
					}
				}
				if( fail )
					goto cleanup;
				frags = erl_mk_list( array, count );
				if( frags ) {
					const int nbyte = erl_term_len( frags );
					byte *buf = calloc( nbyte, sizeof(byte) );
					if( buf ) {
						if( erl_encode( frags, buf ) == nbyte ) {
							if( write_lpm( buf, nbyte ) != nbyte )
								fail = 1;
						} else
							fail = 1;
						free( buf );
					} else
						fail = 1;
				} else
					fail = 1;
cleanup:
				erl_free_array( array, count );
				free( array );
			}
		} else
			break;
	}
#ifdef _DEBUG
	closelog();
#endif
	return 0;
}
Esempio n. 29
0
/**
 * atexit handler to close everything on shutdown
 */
static void cleanup(void)
{
	closelog();
	library_deinit();
}
Esempio n. 30
0
void cleanup_error (void) {
	closelog ();
}