Exemple #1
0
extern "C" DLL_EXPORT void CDECL_CALL EmuMain(char *rom)
{
    int i;
    char *s;

    /* If we have special perms, drop them ASAP! */
    vid_preinit();

    init_exports();

    s = strdup(".");
    sys_sanitize(s);
    sys_initpath(s);

    for (i = 0; defaultconfig[i]; i++)
        rc_command(defaultconfig[i]);

    /* FIXME - make interface modules responsible for atexit() */
    atexit(shutdown);
    catch_signals();
    vid_init();
    pcm_init();

    rom = strdup(rom);
    sys_sanitize(rom);

    loader_init(rom);

    emu_reset();
    emu_run();
}
Exemple #2
0
int		main(int argc, char **argv, char **envp)
{
	t_ftsh	*sh;

	sh = NULL;
	sh = intialize_sh(argc, argv, envp);
	if (!sh)
	{
		ft_putendl_fd("Error : could'nt initialize shell", 2);
		return (1);
	}
	while (1)
	{
		catch_signals();
		if (sh->line)
			free(sh->line);
		sh->line = NULL;
		write(1, sh->prompt, ft_strlen(sh->prompt));
		if ((sh->line = get_command_line()) != NULL)
		{
			sh->ret = execute_command_line(sh, &(sh->env_dup));
			ft_tabfree(sh->path_dir);
			sh->path_dir = extract_path_directories(sh->env_dup);
		}
		else
			exit(1);
	}
}
Exemple #3
0
int main(int argc, char *argv[]) 
{
	FILE *input = stdin;
		// Used to keep track of which buffer should be read in (added for scripting purposes)
	char *tokens[100]; 
		// An array storing argvs for the program to be executed
	char commands[80]; // Stores the string entered on the 'command line'
		// Note - command must be kept intact due to the way strtok functions!
	int times_run = 0;

	printf("Welcome to the terminal.\n");
	catch_signals();


	do
	{

		if (times_run >= 1) 
		{
			commands[strlen(commands) - 1] = '\0';
			tokenize(commands, tokens);
			check_commands(tokens);
		}
		pid_t pid = fork();
		if(pid > 0) 
		{ 	// Parent; prompt for new command
			printf(">");
			if (argc > 1 && times_run == 0) 
			{
				FILE *script = fopen(argv[1], "r");
				input = script;
				times_run++;
				continue;
			}
			
			
			int status;
			wait(&status);
			times_run++;
		}

		else if (pid == 0 && times_run >=1) 
		{ 	// This program is child process
			if (execvp(tokens[0], tokens) == -1) 
			{
				error("Unable to run command, please try again.");
			}
		}	

		else //if (pid < 0)
		{				// Error, quit child process
			exit(1);
		}

	} while (fgets(commands, 100, input) != NULL);

	return 0;
}
void stream_server::run()
{
#ifdef UNIX
    catch_signals();
#endif
    while(true) {
        if (interrupted) {
            std::cout << "Interrupted..." << std::endl;
            break;
        }
        peer_connection conn = accept_connection();
        if (interrupted) {
            std::cout << "Interrupted..." << std::endl;
            break;
        }
        service_fn(conn);
    }
    disconnect();
}
Exemple #5
0
int main(int argc, char** argv) {
    /* Parameters (can be set using -options) */
    char* port_name = NULL;
    int delay = 10;
    int baudrate = 9600;

    /* Handle -options */
    int c;
    while ((c = getopt(argc, argv, "hb:d:")) != -1) {
        switch (c) {
            case 'b':
                sscanf(optarg, "%d", &baudrate);
                break;
            case 'd':
                sscanf(optarg, "%d", &delay);
                break;
            case 'h':
                printf("Usage: %s [-b <BAUDRATE>] [-d <DELAY>] PORT\n", argv[0]);
                printf("Saves time from a GPS receiver connected to PORT as local time.\n");
                printf("Waits specified time until valid $GPRMC NMEA sentence is received. If no valid time information is received (i.e. the signal is poor), the local time remains unchanged.\n");
                printf("This program has to be run with root privilegies in order to configure local time.\n");
                printf("\n");
                printf("  -b BAUDRATE  Sets specified baudrate. Only limited baudrate set {2400, 4800, ..., 230400} is supported (Default %d bd).\n", baudrate);
                printf("  -d DELAY     Sets the maximum time in seconds or -1 for infinite loop (Default %d s).\n", delay);
                printf("  -h           Displays this help.\n");
                printf("\n");
                printf("(c) 2014 Adam Heinrich, www.adamheinrich.com\n");
                return 0;
                break;
            case '?':
                if (optopt == 'b' || optopt == 'd') {
                    fprintf(stderr, "Option -%c requires an argument.\nUse %s -h for help.\n", optopt, argv[0]);
                } else {
                    fprintf(stderr, "Unknown option character '%c'.\nUse %s -h for help.\n", optopt, argv[0]);
                }
                return 1;
            default:
                fprintf(stderr, "Usage: %s [-b <BAUDRATE>] [-d <DELAY>] PORT_NAME\n", argv[0]);
                return 1;
        }
    }

    /* Save port name */
    if (optind < argc) {
        port_name = argv[optind];
    } else {
        fprintf(stderr, "Port name must be specified.\nUse %s -h for help.\n", argv[0]);
        return 1;
    }
    
    /* Check baudrate */
    if (baudrate_constant(baudrate) == -1) {
        fprintf(stderr, "Unsupported baudrate: %d.\nUse %s -h for help.\n", baudrate, argv[0]);
        return 1;
    }

    /* Open port */
    int fd = open_port(port_name, baudrate);
    if (fd == -1) {
        fprintf(stderr, "Can't open port %s\n", port_name);
        return 1;
    }

    /* Real gentlemen clean up after finishing the job! */
    catch_signals();

    int nread;
    char buffer[32];
    time_t first_time;
    time_t curr_time;
    time(&first_time);

    read_gps = 1;

    while (read_gps) {
        nread = read(fd, buffer, 32);
        if (nread > 0) {
            nmea_parse(nread, buffer, &message_complete);
        }

        time(&curr_time);
        if (read_gps && delay != -1 && (curr_time - first_time) >= delay) {
            printf("No valid time information from GPS in last %d seconds.\n", delay);
            read_gps = 0;
        }
    }

    close(fd);

    return 0;
}
Exemple #6
0
int main(int argc, char *argv[])
{
	int i;
	char *opt, *arg, *cmd, *s, *rom = 0;

	/* Avoid initializing video if we don't have to */
	for (i = 1; i < argc; i++)
	{
		if (!strcmp(argv[i], "--help"))
			help(base(argv[0]));
		else if (!strcmp(argv[i], "--version"))
			version(base(argv[0]));
		else if (!strcmp(argv[i], "--copying"))
			copying();
		else if (!strcmp(argv[i], "--bind")) i += 2;
		else if (!strcmp(argv[i], "--source")) i++;
		else if (!strcmp(argv[i], "--showvars"))
		{
			show_exports();
			exit(0);
		}
		else if (argv[i][0] == '-' && argv[i][1] == '-');
		else if (argv[i][0] == '-' && argv[i][1]);
		else rom = argv[i];
	}
	
	if (!rom) usage(base(argv[0]));

	/* If we have special perms, drop them ASAP! */
	vid_preinit();

	init_exports();

	s = strdup(argv[0]);
	sys_sanitize(s);
	sys_initpath(s);

	for (i = 0; defaultconfig[i]; i++)
		rc_command(defaultconfig[i]);

	for (i = 1; i < argc; i++)
	{
		if (!strcmp(argv[i], "--bind"))
		{
			if (i + 2 >= argc) die("missing arguments to bind\n");
			cmd = malloc(strlen(argv[i+1]) + strlen(argv[i+2]) + 9);
			sprintf(cmd, "bind %s \"%s\"", argv[i+1], argv[i+2]);
			rc_command(cmd);
			free(cmd);
			i += 2;
		}
		else if (!strcmp(argv[i], "--source"))
		{
			if (i + 1 >= argc) die("missing argument to source\n");
			cmd = malloc(strlen(argv[i+1]) + 6);
			sprintf(cmd, "source %s", argv[++i]);
			rc_command(cmd);
			free(cmd);
		}
		else if (!strncmp(argv[i], "--no-", 5))
		{
			opt = strdup(argv[i]+5);
			while ((s = strchr(opt, '-'))) *s = '_';
			cmd = malloc(strlen(opt) + 7);
			sprintf(cmd, "set %s 0", opt);
			rc_command(cmd);
			free(cmd);
			free(opt);
		}
		else if (argv[i][0] == '-' && argv[i][1] == '-')
		{
			opt = strdup(argv[i]+2);
			if ((s = strchr(opt, '=')))
			{
				*s = 0;
				arg = s+1;
			}
			else arg = "1";
			while ((s = strchr(opt, '-'))) *s = '_';
			while ((s = strchr(arg, ','))) *s = ' ';
			
			cmd = malloc(strlen(opt) + strlen(arg) + 6);
			sprintf(cmd, "set %s %s", opt, arg);
			
			rc_command(cmd);
			free(cmd);
			free(opt);
		}
		/* short options not yet implemented */
		else if (argv[i][0] == '-' && argv[i][1]);
	}

	/* FIXME - make interface modules responsible for atexit() */
	atexit(shutdown);
	catch_signals();
	vid_init();
	pcm_init();

	rom = strdup(rom);
	sys_sanitize(rom);
	
	loader_init(rom);
	
	emu_reset();
	emu_run();

	/* never reached */
	return 0;
}
Exemple #7
0
int cmd_server(int argc, char *argv[]) {
    void *context = zmq_init(1);
    assert(context);

    void *subscriber = zmq_socket(context, ZMQ_SUB);
    assert(subscriber);

    int rc;
    rc = zmq_connect(subscriber, "tcp://localhost:50000");
    assert_rc;

    rc = zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0);
    assert_rc;

    void *publisher = zmq_socket(context, ZMQ_PUB);
    assert(publisher);

    rc = zmq_bind(publisher, "tcp://*:50001");
    assert_rc;

    timeval tv_start;
    gettimeofday_exn(&tv_start);
    long long num_msgs = 0;
    catch_signals();
    while (!interrupted) {
        zmq_msg_t in_message;
        rc = zmq_msg_init(&in_message);
        assert_rc;

        rc = zmq_recv(subscriber, &in_message, 0);
        if (0 != rc)
            break;

        int size = zmq_msg_size(&in_message);

        zmq_msg_t out_message;

        rc = zmq_msg_init_size(&out_message, size);
        assert_rc;

        memcpy(zmq_msg_data(&out_message), zmq_msg_data(&in_message),
               size);
        rc = zmq_send(publisher, &out_message, 0);
        assert_rc;

        ignore(zmq_msg_close(&out_message));
        ignore(zmq_msg_close(&in_message));

        ++num_msgs;
        timeval tv_interval_end;
        gettimeofday_exn(&tv_interval_end);
        if (num_msgs % 100000 == 0) {
            printf("\rMsgs: %lld; Freq: %lld msgs/sec;  ", num_msgs,
                   ((num_msgs * 1000000) / diff_us(&tv_interval_end,
                                                   &tv_start)));
            fflush(stdout);
        }
    }

    printf("\nExited cleanly\n");

    ignore(zmq_close(subscriber));
    ignore(zmq_close(publisher));
    ignore(zmq_term(context));
    return 0;
}
Exemple #8
0
/*
 * gpasswd - administer the /etc/group file
 */
int main (int argc, char **argv)
{
	struct group grent;
#ifdef SHADOWGRP
	struct sgrp sgent;
#endif
	struct passwd *pw = NULL;

#ifdef WITH_AUDIT
	audit_help_open ();
#endif

	sanitize_env ();
	(void) setlocale (LC_ALL, "");
	(void) bindtextdomain (PACKAGE, LOCALEDIR);
	(void) textdomain (PACKAGE);

	/*
	 * Make a note of whether or not this command was invoked by root.
	 * This will be used to bypass certain checks later on. Also, set
	 * the real user ID to match the effective user ID. This will
	 * prevent the invoker from issuing signals which would interfere
	 * with this command.
	 */
	bywho = getuid ();
	Prog = Basename (argv[0]);

	OPENLOG ("gpasswd");
	setbuf (stdout, NULL);
	setbuf (stderr, NULL);

#ifdef SHADOWGRP
	is_shadowgrp = sgr_file_present ();
#endif

	/*
	 * Determine the name of the user that invoked this command. This
	 * is really hit or miss because there are so many ways that command
	 * can be executed and so many ways to trip up the routines that
	 * report the user name.
	 */
	pw = get_my_pwent ();
	if (NULL == pw) {
		fprintf (stderr, _("%s: Cannot determine your user name.\n"),
		         Prog);
		SYSLOG ((LOG_WARN,
		         "Cannot determine the user name of the caller (UID %lu)",
		         (unsigned long) getuid ()));
		exit (E_NOPERM);
	}
	myname = xstrdup (pw->pw_name);

	/*
	 * Register an exit function to warn for any inconsistency that we
	 * could create.
	 */
	if (atexit (do_cleanups) != 0) {
		fprintf(stderr, "%s: cannot set exit function\n", Prog);
		exit (1);
	}

	/* Parse the options */
	process_flags (argc, argv);

	/*
	 * Replicate the group so it can be modified later on.
	 */
#ifdef SHADOWGRP
	get_group (&grent, &sgent);
#else
	get_group (&grent);
#endif

	/*
	 * Check if the user is allowed to change the password of this group.
	 */
#ifdef SHADOWGRP
	check_perms (&grent, &sgent);
#else
	check_perms (&grent);
#endif

	/*
	 * Removing a password is straight forward. Just set the password
	 * field to a "".
	 */
	if (rflg) {
		grent.gr_passwd = "";	/* XXX warning: const */
#ifdef SHADOWGRP
		sgent.sg_passwd = "";	/* XXX warning: const */
#endif
		goto output;
	} else if (Rflg) {
		/*
		 * Same thing for restricting the group. Set the password
		 * field to "!".
		 */
		grent.gr_passwd = "!";	/* XXX warning: const */
#ifdef SHADOWGRP
		sgent.sg_passwd = "!";	/* XXX warning: const */
#endif
		goto output;
	}

	/*
	 * Adding a member to a member list is pretty straightforward as
	 * well. Call the appropriate routine and split.
	 */
	if (aflg) {
		printf (_("Adding user %s to group %s\n"), user, group);
		grent.gr_mem = add_list (grent.gr_mem, user);
#ifdef SHADOWGRP
		if (is_shadowgrp) {
			sgent.sg_mem = add_list (sgent.sg_mem, user);
		}
#endif
		goto output;
	}

	/*
	 * Removing a member from the member list is the same deal as adding
	 * one, except the routine is different.
	 */
	if (dflg) {
		bool removed = false;

		printf (_("Removing user %s from group %s\n"), user, group);

		if (is_on_list (grent.gr_mem, user)) {
			removed = true;
			grent.gr_mem = del_list (grent.gr_mem, user);
		}
#ifdef SHADOWGRP
		if (is_shadowgrp) {
			if (is_on_list (sgent.sg_mem, user)) {
				removed = true;
				sgent.sg_mem = del_list (sgent.sg_mem, user);
			}
		}
#endif
		if (!removed) {
			fprintf (stderr,
			         _("%s: user '%s' is not a member of '%s'\n"),
			         Prog, user, group);
			exit (E_BAD_ARG);
		}
		goto output;
	}
#ifdef SHADOWGRP
	/*
	 * Replacing the entire list of administrators is simple. Check the
	 * list to make sure everyone is a real user. Then slap the new list
	 * in place.
	 */
	if (Aflg) {
		sgent.sg_adm = comma_to_list (admins);
		if (!Mflg) {
			goto output;
		}
	}
#endif				/* SHADOWGRP */

	/*
	 * Replacing the entire list of members is simple. Check the list to
	 * make sure everyone is a real user. Then slap the new list in
	 * place.
	 */
	if (Mflg) {
#ifdef SHADOWGRP
		sgent.sg_mem = comma_to_list (members);
#endif
		grent.gr_mem = comma_to_list (members);
		goto output;
	}

	/*
	 * If the password is being changed, the input and output must both
	 * be a tty. The typical keyboard signals are caught so the termio
	 * modes can be restored.
	 */
	if ((isatty (0) == 0) || (isatty (1) == 0)) {
		fprintf (stderr, _("%s: Not a tty\n"), Prog);
		exit (E_NOPERM);
	}

	catch_signals (0);	/* save tty modes */

	(void) signal (SIGHUP, catch_signals);
	(void) signal (SIGINT, catch_signals);
	(void) signal (SIGQUIT, catch_signals);
	(void) signal (SIGTERM, catch_signals);
#ifdef SIGTSTP
	(void) signal (SIGTSTP, catch_signals);
#endif

	/* Prompt for the new password */
#ifdef SHADOWGRP
	change_passwd (&grent, &sgent);
#else
	change_passwd (&grent);
#endif

	/*
	 * This is the common arrival point to output the new group file.
	 * The freshly crafted entry is in allocated space. The group file
	 * will be locked and opened for writing. The new entry will be
	 * output, etc.
	 */
      output:
	if (setuid (0) != 0) {
		fputs (_("Cannot change ID to root.\n"), stderr);
		SYSLOG ((LOG_ERR, "can't setuid(0)"));
		closelog ();
		exit (E_NOPERM);
	}
	pwd_init ();

	open_files ();

#ifdef SHADOWGRP
	update_group (&grent, &sgent);
#else
	update_group (&grent);
#endif

	close_files ();

	nscd_flush_cache ("group");

	exit (E_SUCCESS);
}
Exemple #9
0
int main(int argc, char **argv)
{
    if (argc < 2) {
        printf("\n");
        printf("rs_test LIO_COMMON_OPTIONS\n");
        lio_print_options(stdout);
        return(1);
    }

    int thread_nbr;

    lio_init(&argc, &argv);

    thread_nbr = lio_parallel_task_count;

    //*** Parses the args
    char *svr_proto, *svr_addr, *svr_port, *zmq_svr;

    //** Retrieves remote zmq server name, transport protocol, and lisenting port
    svr_proto = inip_get_string(lio_gc->ifd, "zmq_server", "protocol", RS_ZMQ_DFT_PROTO);
    svr_addr = inip_get_string(lio_gc->ifd, "zmq_server", "server", NULL);
    svr_port = inip_get_string(lio_gc->ifd, "zmq_server", "port", RS_ZMQ_DFT_PORT);
    asprintf(&zmq_svr, "%s://%s:%s", string_trim(svr_proto), string_trim(svr_addr), string_trim(svr_port));


    //** Creates zmq context
    void *context = zmq_ctx_new();
    assert(context != NULL);

    //** Creates zmq router and binds it to tcp://*:5555
    //** It talks to rs client
    void *router = zmq_socket(context, ZMQ_ROUTER);
    assert(router != NULL);
    int rc = zmq_bind(router, zmq_svr);
    assert(rc != -1);
    printf("ZMQ router socket created.\n");

    // Creates and binds DEALER socket to inproc://worker
    // It talks to workers
    void *dealer = zmq_socket(context, ZMQ_DEALER);
    assert(dealer != NULL);
    rc = zmq_bind(dealer, "inproc://worker");
    assert(rc != -1);
    printf("ZMQ dealer socket created.\n");

    //** Blocks the SIGINT, SIGTERM signals
    sigemptyset(&signal_mask);
    sigaddset(&signal_mask, SIGINT);
    sigaddset(&signal_mask, SIGTERM);
    rc = pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
    assert(rc == 0);

    //** Launches thread pool
    printf("Launching threads...\n");
    int thread_count;
    rs_zmq_thread_arg_t **arg;
    type_malloc_clear(arg, rs_zmq_thread_arg_t *, thread_nbr);
    pthread_t *workers;
    type_malloc_clear(workers, pthread_t, thread_nbr);
    for (thread_count = 0; thread_count < thread_nbr; thread_count++) {
        type_malloc_clear(arg[thread_count], rs_zmq_thread_arg_t, 1);
        arg[thread_count]->zmq_context = context;
        arg[thread_count]->rs = lio_gc->rs;
        arg[thread_count]->da = ds_attr_create(lio_gc->ds);
        arg[thread_count]->ds = lio_gc->ds;
        arg[thread_count]->timeout = lio_gc->timeout;
        pthread_create(&workers[thread_count], NULL, rs_zmq_worker_routine, (void *)arg[thread_count]);
    }
    printf("Launched all %d threads.\n", thread_nbr);

    //** Unblocks the SIGINT, SIGTERM signals
    rc = pthread_sigmask(SIG_UNBLOCK, &signal_mask, NULL);
    assert(rc == 0);

    //** Catches the SIGNIT, SIGTERM signals
    catch_signals();

    //** Uses a QUEUE device to connect router and dealer
    zmq_device(ZMQ_QUEUE, router, dealer);

    if (s_interrupted == 1)
        printf("Interrupt received, killing server...\n");

    //** Shutdown zmq should go before cleaning thread resources
    zmq_close(router);
    zmq_close(dealer);
    printf("Destroied ZMQ router and dealer\n");
    zmq_ctx_destroy(context); //** This "trigers" the exit of all threads, because it makes all blocking operations on sockets return
    printf("Destroied ZMQ context\n");
    fflush(stdout);

    //** Waits for all threads to exit
    for (thread_count = 0; thread_count < thread_nbr; thread_count++) {
        pthread_join(workers[thread_count], NULL);
    }

    //** Destroys allocations for threads
    for (thread_count = 0; thread_count < thread_nbr; thread_count++) {
        ds_attr_destroy(lio_gc->ds, arg[thread_count]->da);
        free(arg[thread_count]);
    }
    free(arg);
    free(workers);

    free(svr_proto);
    free(svr_addr);
    free(svr_port);
    free(zmq_svr);

    lio_shutdown();

    return(0);
}
Exemple #10
0
int
main(int argc, char **argv)
{
	struct stat buf;
	int ret;
	char scratch[BUFSIZ];
	char log[BUFSIZ];
	char olog[BUFSIZ];
	char *scratch_p = scratch;
	char *mytag_p;
	FILE *fp;
	extern char *getenv();
	char *parse();
	int	c;
	extern	char *optarg;
	extern	int optind;
	int i;
	char	*Mytag_p = Mytag;

	/* Get my port monitor tag out of the environment		*/
	if ((mytag_p = getenv("PMTAG")) == NULL) {
		/* no place to write */
		exit(1);
	}
	strcpy(Mytag, mytag_p);

	/* open log file */
	sprintf(log, "%s/%s/%s", ALTDIR, Mytag_p, LOGNAME);
	sprintf(olog, "%s/%s/%s", ALTDIR, Mytag_p, OLOGNAME);
	if (stat(log, &buf) == 0) {
		/* file exists, try and save it but if we can't don't worry */
		unlink(olog);
		rename(log, olog);
	}
	if ((i = open(log, O_WRONLY|O_CREAT|O_APPEND, 0444)) < 0)
		logexit(1, nologfile);
	/* as stated above, the log file should be file descriptor 5 */
	if ((ret = fcntl(i, F_DUPFD, 5)) != 5)
		logexit(1, nologfile);
	Logfp = fdopen(ret, "a+");

	/* Get my port monitor tag out of the environment		*/
	if ((mytag_p = getenv("PMTAG")) == NULL) {
		logexit(1, nopmtag);
	}
	strcpy(Mytag, mytag_p);

	(void) umask(022);
	Readdb = FALSE;

	if (geteuid() != (uid_t) 0) {
		logmessage("Must be root to start listener");
		logexit(1, badstart);
	}

	while ((c = getopt(argc, argv, "m:")) != EOF) 
		switch (c) {
		case 'm':
			Minor_prefix = optarg;
			break;
		default:
			logexit(1, usage);
			break;
		}

	if ((Netspec = argv[optind]) == NULL) {
		logexit(1, usage);
	}
	if ((Netconf = getnetconfigent(Netspec)) == NULL) {
		sprintf(scratch, "no netconfig entry for <%s>", Netspec);
		logmessage(scratch);
		logexit(1, badstart);
	}
	if (!Minor_prefix)
		Minor_prefix = argv[optind];

	if ((int) strlen(Netspec) > PATHSIZE)  {
		logmessage(badnspmsg);
		logexit(1, badstart);
	}

	/* 
	 * SAC will start the listener in the correct directory, so we
	 * don't need to chdir there, as we did in older versions
	 */

	strcpy(Provbuf, "/dev/");
	strcat(Provbuf, Netspec);

	(void) umask(0);

	init_files();		/* open Accept, Sac, Pm, Pass files	*/
	pid_open();		/* create pid file			*/

#ifdef	DEBUGMODE
	sprintf(scratch, "%s/%s/%s", ALTDIR, Mytag, DBGNAME);
	Debugfp = fopen(scratch, "w");
#endif


#ifdef	DEBUGMODE
	if ((!Logfp) || (!Debugfp)) 
#else
	if (!Logfp)
#endif
		logexit(1, badstart);

/*
 * In case we started with no environment, find out what timezone we're
 * in.  This will get passed to children, so only need to do once.
 */

	if (getenv("TZ") == NULL) {
		fp = fopen(TZFILE, "r");
		if (fp) {
			while (fgets(tzenv, BUFSIZ, fp)) {
				if (tzenv[strlen(tzenv) - 1] == '\n')
					tzenv[strlen(tzenv) - 1] = '\0';
				if (!strncmp(TZSTR, tzenv, strlen(TZSTR))) {
					putenv(parse(tzenv));
					break;
				}
			}
			fclose(fp);
		}
		else {
			sprintf(scratch, "couldn't open %s, default to GMT",
			    TZFILE);
			logmessage(scratch);
		}
	}

	logmessage("@(#)listen:listen.c	1.19.9.1");

#ifdef	DEBUGMODE
	logmessage("Listener process with DEBUG capability");
#endif

	sprintf(scratch, "Listener port monitor tag: %s", Mytag_p);
	logmessage(scratch);
	DEBUG((9, "Minor prefix: %s  Netspec %s", Minor_prefix, Netspec));

	/* fill in Pmmesg fields that always stay the same */

	Pmmsg.pm_maxclass = MAXCLASS;
	strcpy(Pmmsg.pm_tag, Mytag_p);
	Pmmsg.pm_size = 0;

	/* Find out what state to start in.  If not in env, exit */
	if ((scratch_p = getenv("ISTATE")) == NULL)
		logexit(1, "ERROR: ISTATE variable not set in environment");
	
	if (!strcmp(scratch_p, "enabled")) {
		State = PM_ENABLED;
		logmessage("Starting state: ENABLED");
	}
	else {
		State = PM_DISABLED;
		logmessage("Starting state: DISABLED");
	}

	/* try to get my "basename"		*/
	Progname = strrchr(argv[0], '/');
	if (Progname && Progname[1])
		++Progname;
	else
		Progname = argv[0];

	catch_signals();

	/* 
	 * Allocate memory for private address and file descriptor table 
	 * Here we are assuming that no matter how many private addresses
	 * exist in the system if the system limit is 20 then we will only
	 * get 20 file descriptors
	 */

	Ndesc = ulimit(4,0L);		/* get num of file des on system */

	read_dbf(DB_INIT);
	net_open();			/* init, open, bind names 	*/

	for (i = 3; i < Ndesc; i++)  {	/* leave stdout, stderr open	*/
		fcntl(i, F_SETFD, 1);	/* set close on exec flag*/
	}

	logmessage("Initialization Complete");

	listen();
	return (0);
}
Exemple #11
0
int
main(int argc, char **argv)
{
    int i, opt, rc;
    int sock;
    struct timeval now;

    gettime(&now);

    inet_pton(AF_INET6, "ff02::1:6", &babel_group);
    babel_port = 6696;

    srand(now.tv_sec ^ now.tv_usec);

    while(1) {
        opt = getopt(argc, argv, "p:u:h:c:");
        if(opt < 0)
            break;

        switch(opt) {
        case 'p':               /* prefix */
            if(have_prefix)
                goto usage;
            rc = inet_pton(AF_INET6, optarg, &myprefix);
            if(rc != 1)
                goto usage;
            have_prefix = 1;
            break;
        case 'u':               /* update interval */
            update_interval = atoi(optarg);
            if(update_interval <= 0)
                goto usage;
            break;
        case 'h':               /* hello interval */
            hello_interval = atoi(optarg);
            if(hello_interval <= 0)
                goto usage;
            break;
        case 'c':               /* link cost */
            link_cost = atoi(optarg);
            if(link_cost <= 0)
                goto usage;
            break;
        default:
            goto usage;
        }
    }

    if(!have_prefix)
        fprintf(stderr, "Warning: you didn't ask me to announce a prefix.\n");

    if(argc - optind > MAXINTERFACES) {
        fprintf(stderr, "Too many interfaces.\n");
        exit(1);
    }

    for(i = 0; i < argc - optind; i++) {
        int index;

        index = if_nametoindex(argv[optind + i]);
        if(index <= 0) {
            fprintf(stderr, "Unknown interface %s\n", argv[i]);
            exit(1);
        }
        memset(&interfaces[i], 0, sizeof(interfaces[i]));
        interfaces[i].ifindex = index;
        interfaces[i].ifname = argv[optind + i];
        rc = get_local_address(interfaces[i].ifindex, &interfaces[i].address);
        if(rc < 0) {
            perror("get_local_address");
            fprintf(stderr, "Continuing anyway -- "
                    "won't perform reachibility detection "
                    "on interface %s.\n", interfaces[i].ifname);
        }
        interfaces[i].seqno = rand() & 0xFFFF;
    }
    numinterfaces = argc - optind;

    random_eui64(my_router_id);
    myseqno = rand() & 0xFFFF;

    sock = babel_socket(babel_port);
    if(sock < 0) {
        perror("babel_socket");
        exit(1);
    }

    for(i = 0; i < numinterfaces; i++) {
        rc = join_group(sock, interfaces[i].ifindex, &babel_group);
        if(rc < 0) {
            perror("setsockopt(IPV6_JOIN_GROUP)");
            exit(1);
        }
    }

    catch_signals(sigexit);

    while(!exiting) {
        struct sockaddr_in6 sin6;
        unsigned char buf[BUF_SIZE];
        struct timeval tv, update, zerotv = {0, 0};
        fd_set readfds;
        int hello_count = 0;

        /* Compute when to wake up. */
        gettime(&now);
        timeval_add_msec(&tv, &last_hello, hello_interval * 700 + rand() % 300);
        timeval_add_msec(&update, &last_update,
                         update_interval * 700 + rand() % 300);
        timeval_min(&tv, &update);

        if(selected_nexthop_metric < INFINITY) {
            int n = find_neighbour(selected_interface, &selected_nexthop, 0);
            assert(n >= 0);
            timeval_min(&tv, &neighbours[n].timeout);
            timeval_min(&tv, &selected_nexthop_timeout);
        }

        if(timeval_compare(&tv, &now) > 0)
            timeval_minus(&tv, &tv, &now);
        else
            tv = zerotv;

        FD_ZERO(&readfds);
        FD_SET(sock, &readfds);

        rc = select(sock + 1, &readfds, NULL, NULL, &tv);
        if(rc < 0 && errno != EINTR) {
            perror("select");
            nap(1000);
            continue;
        }

        if(rc > 0) {
            /* Oh good, a packet. */
            socklen_t sin6len = sizeof(sin6);
            rc = recvfrom(sock, buf, BUF_SIZE, 0,
                          (struct sockaddr*)&sin6, &sin6len);

            if(rc < 0 || rc >= BUF_SIZE) {
                if(rc < 0 && errno != EAGAIN) {
                    perror("recv");
                    nap(100);
                }
                continue;
            }

            if(sin6.sin6_family != PF_INET6) {
                fprintf(stderr, "Received unexpected packet in family %d.\n",
                        sin6.sin6_family);
                nap(100);
                continue;
            }

            i = find_interface(sin6.sin6_scope_id);
            if(i < 0) {
                fprintf(stderr, "Received packet on unknown interface %d.\n",
                        sin6.sin6_scope_id);
                nap(100);
                continue;
            }
            handle_packet(sock, buf, rc, &interfaces[i], &sin6.sin6_addr);
        }

        gettime(&now);

        if(selected_nexthop_metric < INFINITY) {
            int n = find_neighbour(selected_interface, &selected_nexthop, 0);
            assert(n >= 0);

            if(neighbour_expired(n, &now)) {
                /* Expire neighbour. */
                flush_default_route();
                delete_neighbour(n);
            } else if(timeval_compare(&now, &selected_nexthop_timeout) > 0) {
                /* Expire route. */
                flush_default_route();
            }
            /* Send a request? */
        }

        /* Is it time to send hellos? */
        if(timeval_minus_msec(&now, &last_hello) > hello_interval * 700) {
            for(i = 0; i < numinterfaces; i++)
                send_hello(sock, &interfaces[i]);
            last_hello = now;
            hello_count++;
            /* Make an expiry pass every ten hellos. */
            if(hello_count >= 10) {
                expire_neighbours();
                hello_count = 0;
            }
        }

        /* Is it time to send an update? */
        if(timeval_minus_msec(&now, &last_update) > update_interval * 700) {
            for(i = 0; i < numinterfaces; i++)
                send_update(sock, &interfaces[i], 0);
            last_update = now;
        }
    }

    /* Send a bunch of retractions. */
    for(i = 0; i < numinterfaces; i++)
        send_update(sock, &interfaces[i], 1);

    flush_default_route();

    return 0;

 usage:
    fprintf(stderr,
            "Usage: sbabeld "
            "[-p prefix] [-u interval] [-h interval] [-c cost] interface...\n");
    return 1;
}
Exemple #12
0
/*
 * IMAPFilter: an IMAP mail filtering utility.
 */
int
main(int argc, char *argv[])
{
	int c;
	char *cafile = NULL, *capath = NULL;

	setlocale(LC_CTYPE, "");

	opts.verbose = 0;
	opts.interactive = 0;
	opts.log = NULL;
	opts.config = NULL;
	opts.oneline = NULL;
	opts.debug = NULL;

	opts.truststore = NULL;
	if (exists_dir("/etc/ssl/certs"))
		opts.truststore = "/etc/ssl/certs";
	else if (exists_file("/etc/ssl/cert.pem"))
		opts.truststore = "/etc/ssl/cert.pem";

	env.home = NULL;
	env.pathmax = -1;

	while ((c = getopt(argc, argv, "Vc:d:e:il:t:v?")) != -1) {
		switch (c) {
		case 'V':
			version();
			/* NOTREACHED */
			break;
		case 'c':
			opts.config = optarg;
			break;
		case 'd':
			opts.debug = optarg;
			break;
		case 'e':
			opts.oneline = optarg;
			break;
		case 'i':
			opts.interactive = 1;
			break;
		case 'l':
			opts.log = optarg;
			break;
		case 't':
			opts.truststore = optarg;
			break;
		case 'v':
			opts.verbose = 1;
			break;
		case '?':
		default:
			usage();
			/* NOTREACHED */
			break;
		}
	}

	get_pathmax();
	open_debug();
	create_homedir();
	catch_signals();
	open_log();
	if (opts.config == NULL)
		opts.config = get_filepath("config.lua");

	buffer_init(&ibuf, INPUT_BUF);
	buffer_init(&obuf, OUTPUT_BUF);
	buffer_init(&nbuf, NAMESPACE_BUF);
	buffer_init(&cbuf, CONVERSION_BUF);

	regexp_compile(responses);

	SSL_library_init();
	SSL_load_error_strings();
	ssl3ctx = SSL_CTX_new(SSLv3_client_method());
	ssl23ctx = SSL_CTX_new(SSLv23_client_method());
	tls1ctx = SSL_CTX_new(TLSv1_client_method());
#if OPENSSL_VERSION_NUMBER >= 0x01000100fL
	tls11ctx = SSL_CTX_new(TLSv1_1_client_method());
	tls12ctx = SSL_CTX_new(TLSv1_2_client_method());
#endif
	if (exists_dir(opts.truststore))
		capath = opts.truststore;
	else if (exists_file(opts.truststore))
		cafile = opts.truststore;
	SSL_CTX_load_verify_locations(ssl3ctx, cafile, capath);
	SSL_CTX_load_verify_locations(ssl23ctx, cafile, capath);
	SSL_CTX_load_verify_locations(tls1ctx, cafile, capath);
#if OPENSSL_VERSION_NUMBER >= 0x01000100fL
	SSL_CTX_load_verify_locations(tls11ctx, cafile, capath);
	SSL_CTX_load_verify_locations(tls12ctx, cafile, capath);
#endif

	start_lua();
#if LUA_VERSION_NUM < 502
	{
		list *l;
		session *s;

		l = sessions;
		while (l != NULL) {
			s = l->data;
			l = l->next;

			request_logout(s);
		}
	}
#endif
	stop_lua();

	SSL_CTX_free(ssl3ctx);
	SSL_CTX_free(ssl23ctx);
	SSL_CTX_free(tls1ctx);
#if OPENSSL_VERSION_NUMBER >= 0x01000100fL
	SSL_CTX_free(tls11ctx);
	SSL_CTX_free(tls12ctx);
#endif
	ERR_free_strings();

	regexp_free(responses);

	buffer_free(&ibuf);
	buffer_free(&obuf);
	buffer_free(&nbuf);
	buffer_free(&cbuf);

	xfree(env.home);

	close_log();
	close_debug();

	exit(0);
}
Exemple #13
0
int main(int argc, char const *argv[]) {

	shmem *mem;
	const char *geometry;
	int lemon_in, lemon_out;
	int tries=0;
	struct pollfd fds[1];

	fds[0].events = POLLIN;

	geometry = (argc < 2) ? DEFAULT_GEOM : argv[1];
	if (validate_geometry(geometry) < 0){
		fprintf(stderr, "please provide a valid window geometry. E.g. 1920x22+0+0  (widthxheight+X+Y)\n");
		return -1;
	}

	if ((mem = setup_memory(0)) == MEM_FAILED){
		printf("Spawning data daemon\n");

		if (spawn_daemon() < 0){
			fprintf(stderr, "failed to start daemon\n");
			exit(-1);
		}

		while ((mem = setup_memory(0)) == MEM_FAILED){
			if (tries++ > 10){
				fprintf(stderr, "failed to connect to daemon\n");
				exit(-1);
			}
			sleep(1);
		}

		printf("connected to new data source\n");
	} else {
		printf("Connected to running data source.\n");
	}

	spawn_bar(&lemon_in, &lemon_out, geometry);
	fds[0].fd = lemon_out;
	
	notify_server(mem->server);
	catch_signals();

	//@todo allow an escape for when server dies
	while (1) {
		DEBUG_(printf("waiting for wakeup signal\n"));

		//block. wait here for lemonbar click output, or update signal from server
		//we could block with read() or something, but let's plan for multiple
		//sources for the future.
		if (poll(fds, 1, -1) < 0){
			if (errno != EINTR){
				perror("poll");
				break;
			}
		}

		if (fds[0].revents & POLLIN) {
			fds[0].revents = 0; //clear for next round
			//something was clicked
			process_click(fds[0].fd);
		} else {
			//must have gotten pinged by server
			//@todo verify SIGUSR1 vs other signals (which generally just exit anyway)
			update_bar(mem,lemon_in);
		}
	}

	return -1;
}
Exemple #14
0
/*
 * IMAPFilter: an IMAP mail filtering utility.
 */
int
main(int argc, char *argv[])
{
	int c;

	setlocale(LC_CTYPE, "");

	opts.verbose = 0;
	opts.interactive = 0;
	opts.log = NULL;
	opts.config = NULL;
	opts.oneline = NULL;
	opts.debug = NULL;

	env.home = NULL;
	env.pathmax = -1;

	while ((c = getopt(argc, argv, "Vc:d:e:il:v?")) != -1) {
		switch (c) {
		case 'V':
			version();
			/* NOTREACHED */
			break;
		case 'c':
			opts.config = optarg;
			break;
		case 'd':
			opts.debug = optarg;
			break;
		case 'e':
			opts.oneline = optarg;
			break;
		case 'i':
			opts.interactive = 1;
			break;
		case 'l':
			opts.log = optarg;
			break;
		case 'v':
			opts.verbose = 1;
			break;
		case '?':
		default:
			usage();
			/* NOTREACHED */
			break;
		}
	}

	get_pathmax();
	open_debug();
	create_homedir();
	catch_signals();
	open_log();
	if (opts.config == NULL)
		opts.config = get_filepath("config.lua");

	buffer_init(&ibuf, INPUT_BUF);
	buffer_init(&obuf, OUTPUT_BUF);
	buffer_init(&nbuf, NAMESPACE_BUF);
	buffer_init(&cbuf, CONVERSION_BUF);

	regexp_compile(responses);

	SSL_library_init();
	SSL_load_error_strings();

	start_lua();
#if LUA_VERSION_NUM < 502
	{
		list *l;
		session *s;

		l = sessions;
		while (l != NULL) {
			s = l->data;
			l = l->next;

			request_logout(s);
		}
	}
#endif
	stop_lua();

	ERR_free_strings();

	regexp_free(responses);

	buffer_free(&ibuf);
	buffer_free(&obuf);
	buffer_free(&nbuf);
	buffer_free(&cbuf);

	xfree(env.home);

	close_log();
	close_debug();

	exit(0);
}
Exemple #15
0
int
main(int argc, char *argv[])
{
  fd_set rfds;                  /* the structure for the select call */
  int code;                    /* return code from system calls */
  char out_buff[MAXLINE];       /* from child and stdin */
  int out_flag[MAXLINE] ; /* initialize the output flags */
  char *program;          /* a string to hold the child program invocation */
  char **pargs = 0;             /* holds parts of the command line */
  int not_command = 1;          /* a flag while parsing the command line */



  /* try to get a pseudoterminal to play with */
  if (ptyopen(&contNum, &serverNum, controllerPath, serverPath) == -1) {
    perror("ptyopen failed");
    exit(-1);
  }

  /* call the routine that handles signals */
  catch_signals();

  /* parse the command line arguments - as with the aixterm  the command
     argument -e should be last on the line. */

  while(*++argv && not_command) {
    if(!strcmp(*argv, "-f"))
      load_wct_file(*++argv);
    else if(!strcmp(*argv, "-e")) {
      not_command = 0;
      pargs = ++argv;
    }
    else {
      fprintf(stderr, "usage: clef [-f fname] -e command\n");
      exit(-1);
    }
  }
  skim_wct();

#ifdef log
  sprintf(logpath, "/tmp/cleflog%d", getpid());
  logfd = open(logpath, O_CREAT | O_RDWR, 0666);
#endif

  /* get the original termio settings, so the child has them */

  if(tcgetattr(0,&childbuf) == -1) {
    perror("clef trying to get the initial terminal settings");
    exit(-1);
  }

  /* start the child process */

  child_pid = fork();
  switch(child_pid) {
  case -1 :
    perror("clef can't create a new process");
    exit(-1);
  case 0:
    /* CHILD */
    /* Dissasociate form my parents group so all my child processes
       look at my terminal as the controlling terminal for the group */
    setsid();

    serverNum = open(serverPath,O_RDWR);
    if (serverNum == -1) perror("open serverPath failed");

    /* since I am the child, I can close ptc, and dup pts for all it
       standard descriptors */
    if (dup2(serverNum, 0) == -1) perror("dup2 0 failed");
    if (dup2(serverNum, 1) == -1) perror("dup2 1 failed");
    if (dup2(serverNum, 2) == -1) perror("dup2 2 failed");
    if( (dup2(serverNum, 0) == -1)  ||
        (dup2(serverNum, 1) == -1) ||
        (dup2(serverNum, 2) == -1)  ) {
      perror("clef trying to dup2");
      exit(-1);
    }

    /* since they have been duped, close them */
    close(serverNum);
    close(contNum);


    /* To make sure everything is nice, set off enhedit */
    /*    childbuf.c_line = 0; */

    /* reconfigure the child's terminal get echoing */
    if(tcsetattr(0, TCSAFLUSH, &childbuf) == -1) {
      perror("clef child trying to set child's terminal");
      exit(-1);
    }

    /* fire up the child's process */
    if(pargs){
      execvp( pargs[0], pargs);
      perror("clef trying to execvp its argument");
      fprintf(stderr, "Process --> %s\n", pargs[0]);
    }
    else{
      program = getenv("SHELL");
      if (!program)
        program = strdup("/bin/sh");
      else
        program = strdup (program);
      execlp( program,program, 0);
      perror("clef trying to execlp the default child");
      fprintf(stderr, "Process --> %s\n", program);
    }
    exit(-1);
    break;
    /* end switch */
  }
  /* PARENT */
  /* Since I am the parent, I should start to initialize some stuff.
     I have to close the pts side for it to work properly */

  close(serverNum);
  ppid = getppid();

  /* Iinitialize some stuff for the reading and writing */
  init_flag(out_flag, MAXLINE);
  define_function_keys();
  init_reader();
  PTY = 1;
  init_parent();

  /* Here is the main loop, it simply starts reading characters from
     the std input, and from the child. */

  while(1)  {           /* loop forever */

    /* use select to see who has stuff waiting for me to handle */
    /* set file descriptors for ptc and stdin */
    FD_ZERO(&rfds);
    FD_SET(contNum,&rfds);
    FD_SET(0,&rfds);
    set_function_chars();
#ifdef log
    {
      char modepath[30];
      sprintf(modepath, "\nMODE = %d\n", MODE);
      write(logfd, modepath, strlen(modepath));
    }
#endif
#ifdef logterm
    {
      struct termio ptermio;
      char pbuff[1024];
      tcgetattr(contNum, &ptermio);
      sprintf(pbuff, "child's settings: Lflag = %d, Oflag = %d, Iflag = %d\n",
              ptermio.c_lflag, ptermio.c_oflag, ptermio.c_iflag);
      write(logfd, pbuff, strlen(pbuff));
    }
#endif

    code = select(FD_SETSIZE,(void *) &rfds, NULL, NULL, NULL);
    for(; code < 0 ;) {
      if(errno == EINTR) {
        check_flip();
        code = select(FD_SETSIZE,(void *) &rfds, NULL, NULL, NULL);
      }
      else  {
        perror("clef select failure");
        exit(-1);
      }
    }

    /* reading from the child **/
    if( FD_ISSET(contNum,&rfds)) {
      if( (num_read = read(contNum, out_buff, MAXLINE)) == -1) {
        num_read = 0;
      }
#ifdef log
      write(logfd, "OUT<<<<<", strlen("OUT<<<<<"));
      write(logfd, out_buff, num_read);
#endif
      if(num_read > 0) {
        /* now do the printing to the screen */
        if(MODE!= CLEFRAW) {
          back_up(buff_pntr);
          write(1,out_buff, num_read);
          print_whole_buff();    /* reprint the input buffer */
        }
        else write(1,out_buff, num_read);
      }
    } /* done the child stuff */
    /* I should read from std input */
    else  {
      if(FD_ISSET(0,&rfds)) {
        num_read = read(0, in_buff, MAXLINE);
#ifdef log
        write(logfd, "IN<<<<<", strlen("IN<<<<<"));
        write(logfd, in_buff, num_read);
#endif
        check_flip();
        if(MODE == CLEFRAW )
          write(contNum, in_buff, num_read);
        else
          do_reading();
      }
    }
  }
}