static void
do_arguments(globalstate *gstate, int ac, char **av)

{
    int i;
    double f;

    /* this appears to keep getopt happy */
    optind = 1;

#ifdef HAVE_GETOPT_LONG
    while ((i = getopt_long(ac, av, "1CDSITabcinp:qtuvs:d:U:o:m:", longopts, NULL)) != -1)
#else
    while ((i = getopt(ac, av, "1CDSITabcinp:qtuvs:d:U:o:m:")) != EOF)
#endif
    {
	switch(i)
	{
	case '1':
	    gstate->percpustates = !gstate->percpustates;
	    break;
#ifdef ENABLE_COLOR
	case 'C':
	    gstate->use_color = !gstate->use_color;
	    break;
#endif

	case 'D':
	    debug_set(1);
	    break;

	case 'v':
	    fprintf(stderr, "%s: version %s\n", myname, version_string());
	    exit(EX_OK);
	    break;

	case 'b':
	case 'n':
	    gstate->interactive = No;
	    break;

	case 'a':
	    gstate->displays = Infinity;
	    gstate->topn = Infinity;
	    break;

	case 'i':
	    gstate->interactive = Yes;
	    break;

	case 'o':
	    gstate->order_name = optarg;
	    break;

	case 'd':
	    i = atoiwi(optarg);
	    if (i == Invalid || i == 0)
	    {
		message_error(" Bad display count");
	    }
	    else
	    {
		gstate->displays = i;
	    }
	    break;

	case 's':
	    f = atof(optarg);
	    if (f < 0 || (f == 0 && getuid() != 0))
	    {
		message_error(" Bad seconds delay");
	    }
	    else
	    {
		gstate->delay = f;
	    }
	    break;

	case 'u':
	    gstate->show_usernames = !gstate->show_usernames;
	    break;

	case 'U':
	    i = userid(optarg);
	    if (i == -1)
	    {
		message_error(" Unknown user '%s'", optarg);
	    }
	    else
	    {
		gstate->pselect.uid = i;
	    }
	    break;

	case 'm':
	    i = atoi(optarg);
	    gstate->pselect.mode = i;
	    break;

	case 'S':
	    gstate->pselect.system = !gstate->pselect.system;
	    break;

	case 'I':
	    gstate->pselect.idle = !gstate->pselect.idle;
	    break;

#ifdef ENABLE_COLOR
	case 'T':
	    gstate->show_tags = 1;
	    break;
#endif

	case 'c':
	    gstate->pselect.fullcmd = !gstate->pselect.fullcmd;
	    break;

	case 't':
	    gstate->pselect.threads = !gstate->pselect.threads;
	    break;

	case 'p':
	    gstate->pselect.pid = atoi(optarg);
	    break;

	case 'q':		/* be quick about it */
	    /* only allow this if user is really root */
	    if (getuid() == 0)
	    {
		/* be very un-nice! */
		(void) nice(-20);
	    }
	    else
	    {
		message_error(" Option -q can only be used by root");
	    }
	    break;

	default:
	    fprintf(stderr, "\
Top version %s\n\
Usage: %s [-1CISTabcinqtuv] [-d count] [-m mode] [-o field] [-p pid]\n\
           [-s time] [-U username] [number]\n",
		    version_string(), myname);
	    exit(EX_USAGE);
	}
    }

    /* get count of top processes to display */
    if (optind < ac && *av[optind])
    {
	if ((i = atoiwi(av[optind])) == Invalid)
	{
	    message_error(" Process count not a number");
	}
	else
	{
	    gstate->topn = i;
	}
    }
}
void eBackgroundFileEraser::thread()
{
	nice(5);
	exec();
}
Exemple #3
0
static ERTS_INLINE int
prepare_crash_dump(int secs)
{
#define NUFBUF (3)
    int i;
    char env[21]; /* enough to hold any 64-bit integer */
    size_t envsz;
    DeclareTmpHeapNoproc(heap,NUFBUF);
    Port *heart_port;
    Eterm *hp = heap;
    Eterm list = NIL;
    int has_heart = 0;

    UseTmpHeapNoproc(NUFBUF);

    if (ERTS_PREPARED_CRASH_DUMP)
	return 0; /* We have already been called */

    heart_port = erts_get_heart_port();

    /* Positive secs means an alarm must be set
     * 0 or negative means no alarm
     *
     * Set alarm before we try to write to a port
     * we don't want to hang on a port write with
     * no alarm.
     *
     */

    if (secs >= 0) {
	alarm((unsigned int)secs);
    }

    /* close all viable sockets via emergency close callbacks.
     * Specifically we want to close epmd sockets.
     */

    erts_emergency_close_ports();

    if (heart_port) {
	has_heart = 1;
	list = CONS(hp, make_small(8), list); hp += 2;
	/* send to heart port, CMD = 8, i.e. prepare crash dump =o */
	erts_port_output(NULL, ERTS_PORT_SIG_FLG_FORCE_IMM_CALL, heart_port,
			 heart_port->common.id, list, NULL);
    }

    /* Make sure we have a fd for our crashdump file. */
    close(crashdump_companion_cube_fd);

    envsz = sizeof(env);
    i = erts_sys_getenv__("ERL_CRASH_DUMP_NICE", env, &envsz);
    if (i >= 0) {
	int nice_val;
	nice_val = i != 0 ? 0 : atoi(env);
	if (nice_val > 39) {
	    nice_val = 39;
	}
	erts_silence_warn_unused_result(nice(nice_val));
    }

    UnUseTmpHeapNoproc(NUFBUF);
#undef NUFBUF
    return has_heart;
}
/* load exerciser : start exerciser process */
int htxd_load_exerciser(struct htxshm_HE *p_HE)
{

	int exerciser_pid;
	int temp_int;
	char exerciser_path[512];
	char exerciser_name[64];
	char device_name[64];
	char run_mode[64];
	char rule_path[64];
	int emc_mode;
	char trace_str[256];


	HTXD_FUNCTION_TRACE(FUN_ENTRY, "htxd_load_exerciser");
	sprintf(trace_str, "loading exerciser <%s>", p_HE->sdev_id);
	HTXD_TRACE(LOG_OFF, trace_str);
	exerciser_pid = htxd_create_child_process();
	switch(exerciser_pid)
	{
	case 0:
		setsid();

		temp_int = p_HE->priority;
		nice(temp_int);

		sleep(5);   /* let daemon update shared memory */

		strcpy(exerciser_name, p_HE->HE_name);

		if (strcmp(p_HE->HE_name, "hxemem64") == 0) {
			putenv("CORE_NOSHM=true");
		}

		if (strcmp(p_HE->HE_name, "hxepowermixer") == 0) {
			putenv("MEMORY_AFFINITY=MCM");
		}

		strcpy(exerciser_path, global_htx_home_dir);
		strcat(exerciser_path, "/bin/");
		strcat(exerciser_path, exerciser_name);

		strcpy(device_name, "/dev/");
		strcat(device_name, p_HE->sdev_id);

		emc_mode = htxd_get_emc_mode();
		if(emc_mode == 1) {
			strcpy(run_mode, "EMC");
		} else {
			strcpy(run_mode, "REG");
		}

		if(emc_mode == 1) {
			if(p_HE->emc_rules[0] != '/') {
				sprintf(rule_path, "%s/rules/emc/%s", global_htx_home_dir, p_HE->emc_rules);
			} else {
				strcpy(rule_path, p_HE->emc_rules);
			}
		} else {
			if(p_HE->reg_rules[0] != '/') {
				sprintf(rule_path, "%s/rules/reg/%s", global_htx_home_dir, p_HE->reg_rules);
			} else {
				strcpy(rule_path, p_HE->reg_rules);
			}
		}

		/* system("export EXTSHM=OFF"); */
		unsetenv("EXTSHM");

		if ( (execl(exerciser_path, exerciser_name, device_name, run_mode, rule_path, (char *) 0) ) == -1) {
			sprintf(trace_str, "execl() failed  exerciser_path <%s> exerciser_name <%s> errno = <%d>\n", exerciser_path, exerciser_name, errno);
			htxd_send_message (trace_str, 0, HTX_SYS_SOFT_ERROR, HTX_SYS_MSG);
			HTXD_TRACE(LOG_ON, trace_str);
			exit(-1);
		}

	case -1:
		sprintf(trace_str, "exerciser <%s> fork failed with error <%d>", p_HE->sdev_id, errno);
		HTXD_TRACE(LOG_ON, trace_str);
		return -1;

	default:
		p_HE->PID = exerciser_pid;
		htxd_update_exer_pid_in_exer_list(htxd_get_exer_table(), p_HE->sdev_id, exerciser_pid);
		sprintf(trace_str, "exerciser <%s> forked with PID <%d>", p_HE->sdev_id, p_HE->PID);
		HTXD_TRACE(LOG_OFF, trace_str);
		break;
	}
	htxd_reset_FD_close_on_exec_flag();

	HTXD_FUNCTION_TRACE(FUN_EXIT, "htxd_load_exerciser");
	return 0;
}
Exemple #5
0
int					/* O - Process ID or 0 */
cupsdStartProcess(
    const char  *command,		/* I - Full path to command */
    char        *argv[],		/* I - Command-line arguments */
    char        *envp[],		/* I - Environment */
    int         infd,			/* I - Standard input file descriptor */
    int         outfd,			/* I - Standard output file descriptor */
    int         errfd,			/* I - Standard error file descriptor */
    int         backfd,			/* I - Backchannel file descriptor */
    int         sidefd,			/* I - Sidechannel file descriptor */
    int         root,			/* I - Run as root? */
    void        *profile,		/* I - Security profile to use */
    cupsd_job_t *job,			/* I - Job associated with process */
    int         *pid)			/* O - Process ID */
{
  int		i;			/* Looping var */
  const char	*exec_path = command;	/* Command to be exec'd */
  char		*real_argv[110],	/* Real command-line arguments */
		cups_exec[1024],	/* Path to "cups-exec" program */
		user_str[16],		/* User string */
		group_str[16],		/* Group string */
		nice_str[16];		/* FilterNice string */
  uid_t		user;			/* Command UID */
  cupsd_proc_t	*proc;			/* New process record */
#if USE_POSIX_SPAWN
  posix_spawn_file_actions_t actions;	/* Spawn file actions */
  posix_spawnattr_t attrs;		/* Spawn attributes */
  sigset_t	defsignals;		/* Default signals */
#elif defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
  struct sigaction action;		/* POSIX signal handler */
#endif /* USE_POSIX_SPAWN */
#if defined(__APPLE__)
  char		processPath[1024],	/* CFProcessPath environment variable */
		linkpath[1024];		/* Link path for symlinks... */
  int		linkbytes;		/* Bytes for link path */
#endif /* __APPLE__ */


  *pid = 0;

 /*
  * Figure out the UID for the child process...
  */

  if (RunUser)
    user = RunUser;
  else if (root)
    user = 0;
  else
    user = User;

 /*
  * Check the permissions of the command we are running...
  */

  if (_cupsFileCheck(command, _CUPS_FILE_CHECK_PROGRAM, !RunUser,
                     cupsdLogFCMessage, job ? job->printer : NULL))
    return (0);

#if defined(__APPLE__)
  if (envp)
  {
   /*
    * Add special voodoo magic for OS X - this allows OS X programs to access
    * their bundle resources properly...
    */

    if ((linkbytes = readlink(command, linkpath, sizeof(linkpath) - 1)) > 0)
    {
     /*
      * Yes, this is a symlink to the actual program, nul-terminate and
      * use it...
      */

      linkpath[linkbytes] = '\0';

      if (linkpath[0] == '/')
	snprintf(processPath, sizeof(processPath), "CFProcessPath=%s",
		 linkpath);
      else
	snprintf(processPath, sizeof(processPath), "CFProcessPath=%s/%s",
		 dirname((char *)command), linkpath);
    }
    else
      snprintf(processPath, sizeof(processPath), "CFProcessPath=%s", command);

    envp[0] = processPath;		/* Replace <CFProcessPath> string */
  }
#endif	/* __APPLE__ */

 /*
  * Use helper program when we have a sandbox profile...
  */

#if !USE_POSIX_SPAWN
  if (profile)
#endif /* !USE_POSIX_SPAWN */
  {
    snprintf(cups_exec, sizeof(cups_exec), "%s/daemon/cups-exec", ServerBin);
    snprintf(user_str, sizeof(user_str), "%d", user);
    snprintf(group_str, sizeof(group_str), "%d", Group);
    snprintf(nice_str, sizeof(nice_str), "%d", FilterNice);

    real_argv[0] = cups_exec;
    real_argv[1] = (char *)"-g";
    real_argv[2] = group_str;
    real_argv[3] = (char *)"-n";
    real_argv[4] = nice_str;
    real_argv[5] = (char *)"-u";
    real_argv[6] = user_str;
    real_argv[7] = profile ? profile : "none";
    real_argv[8] = (char *)command;

    for (i = 0;
         i < (int)(sizeof(real_argv) / sizeof(real_argv[0]) - 10) && argv[i];
	 i ++)
      real_argv[i + 9] = argv[i];

    real_argv[i + 9] = NULL;

    argv      = real_argv;
    exec_path = cups_exec;
  }

  if (LogLevel == CUPSD_LOG_DEBUG2)
  {
    cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: Preparing to start \"%s\", arguments:", command);

    for (i = 0; argv[i]; i ++)
      cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: argv[%d] = \"%s\"", i, argv[i]);
  }

#if USE_POSIX_SPAWN
 /*
  * Setup attributes and file actions for the spawn...
  */

  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: Setting spawn attributes.");
  sigemptyset(&defsignals);
  sigaddset(&defsignals, SIGTERM);
  sigaddset(&defsignals, SIGCHLD);
  sigaddset(&defsignals, SIGPIPE);

  posix_spawnattr_init(&attrs);
  posix_spawnattr_setflags(&attrs, POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGDEF);
  posix_spawnattr_setpgroup(&attrs, 0);
  posix_spawnattr_setsigdefault(&attrs, &defsignals);

  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: Setting file actions.");
  posix_spawn_file_actions_init(&actions);
  if (infd != 0)
  {
    if (infd < 0)
      posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0);
    else
      posix_spawn_file_actions_adddup2(&actions, infd, 0);
  }

  if (outfd != 1)
  {
    if (outfd < 0)
      posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0);
    else
      posix_spawn_file_actions_adddup2(&actions, outfd, 1);
  }

  if (errfd != 2)
  {
    if (errfd < 0)
      posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0);
    else
      posix_spawn_file_actions_adddup2(&actions, errfd, 2);
  }

  if (backfd != 3 && backfd >= 0)
    posix_spawn_file_actions_adddup2(&actions, backfd, 3);

  if (sidefd != 4 && sidefd >= 0)
    posix_spawn_file_actions_adddup2(&actions, sidefd, 4);

  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: Calling posix_spawn.");

  if (posix_spawn(pid, exec_path, &actions, &attrs, argv, envp ? envp : environ))
  {
    cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork %s - %s.", command, strerror(errno));

    *pid = 0;
  }
  else
    cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: pid=%d", (int)*pid);

  posix_spawn_file_actions_destroy(&actions);
  posix_spawnattr_destroy(&attrs);

#else
 /*
  * Block signals before forking...
  */

  cupsdHoldSignals();

  if ((*pid = fork()) == 0)
  {
   /*
    * Child process goes here; update stderr as needed...
    */

    if (errfd != 2)
    {
      if (errfd < 0)
        errfd = open("/dev/null", O_WRONLY);

      if (errfd != 2)
      {
        dup2(errfd, 2);
	close(errfd);
      }
    }

   /*
    * Put this process in its own process group so that we can kill any child
    * processes it creates.
    */

#  ifdef HAVE_SETPGID
    if (!RunUser && setpgid(0, 0))
      exit(errno + 100);
#  else
    if (!RunUser && setpgrp())
      exit(errno + 100);
#  endif /* HAVE_SETPGID */

   /*
    * Update the remaining file descriptors as needed...
    */

    if (infd != 0)
    {
      if (infd < 0)
        infd = open("/dev/null", O_RDONLY);

      if (infd != 0)
      {
        dup2(infd, 0);
	close(infd);
      }
    }

    if (outfd != 1)
    {
      if (outfd < 0)
        outfd = open("/dev/null", O_WRONLY);

      if (outfd != 1)
      {
        dup2(outfd, 1);
	close(outfd);
      }
    }

    if (backfd != 3 && backfd >= 0)
    {
      dup2(backfd, 3);
      close(backfd);
      fcntl(3, F_SETFL, O_NDELAY);
    }

    if (sidefd != 4 && sidefd >= 0)
    {
      dup2(sidefd, 4);
      close(sidefd);
      fcntl(4, F_SETFL, O_NDELAY);
    }

   /*
    * Change the priority of the process based on the FilterNice setting.
    * (this is not done for root processes...)
    */

    if (!root)
      nice(FilterNice);

   /*
    * Reset group membership to just the main one we belong to.
    */

    if (!RunUser && setgid(Group))
      exit(errno + 100);

    if (!RunUser && setgroups(1, &Group))
      exit(errno + 100);

   /*
    * Change user to something "safe"...
    */

    if (!RunUser && user && setuid(user))
      exit(errno + 100);

   /*
    * Change umask to restrict permissions on created files...
    */

    umask(077);

   /*
    * Unblock signals before doing the exec...
    */

#  ifdef HAVE_SIGSET
    sigset(SIGTERM, SIG_DFL);
    sigset(SIGCHLD, SIG_DFL);
    sigset(SIGPIPE, SIG_DFL);
#  elif defined(HAVE_SIGACTION)
    memset(&action, 0, sizeof(action));

    sigemptyset(&action.sa_mask);
    action.sa_handler = SIG_DFL;

    sigaction(SIGTERM, &action, NULL);
    sigaction(SIGCHLD, &action, NULL);
    sigaction(SIGPIPE, &action, NULL);
#  else
    signal(SIGTERM, SIG_DFL);
    signal(SIGCHLD, SIG_DFL);
    signal(SIGPIPE, SIG_DFL);
#  endif /* HAVE_SIGSET */

    cupsdReleaseSignals();

   /*
    * Execute the command; if for some reason this doesn't work, log an error
    * exit with a non-zero value...
    */

    if (envp)
      execve(exec_path, argv, envp);
    else
      execv(exec_path, argv);

    exit(errno + 100);
  }
  else if (*pid < 0)
  {
   /*
    * Error - couldn't fork a new process!
    */

    cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork %s - %s.", command,
                    strerror(errno));

    *pid = 0;
  }

  cupsdReleaseSignals();
#endif /* USE_POSIX_SPAWN */

  if (*pid)
  {
    if (!process_array)
      process_array = cupsArrayNew((cups_array_func_t)compare_procs, NULL);

    if (process_array)
    {
      if ((proc = calloc(1, sizeof(cupsd_proc_t) + strlen(command))) != NULL)
      {
        proc->pid    = *pid;
	proc->job_id = job ? job->id : 0;
	_cups_strcpy(proc->name, command);

	cupsArrayAdd(process_array, proc);
      }
    }
  }

  cupsdLogMessage(CUPSD_LOG_DEBUG2,
		  "cupsdStartProcess(command=\"%s\", argv=%p, envp=%p, "
		  "infd=%d, outfd=%d, errfd=%d, backfd=%d, sidefd=%d, root=%d, "
		  "profile=%p, job=%p(%d), pid=%p) = %d",
		  command, argv, envp, infd, outfd, errfd, backfd, sidefd,
		  root, profile, job, job ? job->id : 0, pid, *pid);

  return (*pid);
}
Exemple #6
0
void execute_submit(char *workdir, int language, int *usedtime, int *timelimit, int *casetimelimit, int *memlimit)
{
    nice(19);
    struct rlimit lim;
    //time limit
    if(*casetimelimit)
        lim.rlim_cur=*casetimelimit/1000+1;
    else
        lim.rlim_cur=(*timelimit-*usedtime)/1000+1;
    //java need more time
    if(language==LANG_JAVA)lim.rlim_cur*=2;

    lim.rlim_max=lim.rlim_cur;
    setrlimit(RLIMIT_CPU, &lim);
    alarm(0);
    alarm((int)(lim.rlim_max*10));

    //file size limit
    lim.rlim_max=STD_F_LIM+STD_MB;
    lim.rlim_cur=STD_F_LIM;
    setrlimit(RLIMIT_FSIZE, &lim);

    //proc limit
    lim.rlim_cur=lim.rlim_max=(language==LANG_JAVA)?50:1;
    setrlimit(RLIMIT_NPROC, &lim);

    //stack size limit
    lim.rlim_cur=lim.rlim_max=STD_MB<<6;
    setrlimit(RLIMIT_STACK, &lim);

    //memory limit
    lim.rlim_cur=STD_MB/1024*(*memlimit)/2*3;
    lim.rlim_max=STD_MB/1024*(*memlimit)*2;
    if(language!=LANG_JAVA)setrlimit(RLIMIT_AS, &lim);

    chdir(workdir);
    //open files
    freopen("data.in", "r", stdin);
    freopen("user.out", "w", stdout);
    freopen("error.out", "a+", stderr);

    //begin trace
    ptrace(PTRACE_TRACEME, 0, NULL, NULL);
    
    if(language!=LANG_JAVA)chroot(workdir);

    //change uid eid sid, prevention of malicious programs
    //while(setuid(USER_JUDGER)!=0)sleep(1);
    //while(setgid(USER_JUDGER)!=0)sleep(1);
    
    switch(language)
    {
        case LANG_C:
            execl("./main", "./main", (char *)NULL);
            break;
        case LANG_CC:
            execl("./main", "./main", (char *)NULL);
            break;
        case LANG_JAVA:
            execl(java, java, "Main", (char *)NULL);
            break;
    }
    exit(0);
}
Exemple #7
0
int main(int argc, char **argv) {
	int i, j;
	long int procid;
	char outstring1[100];
	FILE *in, *image1, *image2, *image3, *image4, *out;
	struct parsed_options options;
	unsigned short *samples = NULL;

	umask(000);

	init_parsed_options(&options);
	parse_options(&options, argc, argv);

	nice(10);

	sprintf(instring,"%s/process_rt_data_running",options.tmpdir);
	out = fopen(instring, "r");
	if (out != NULL) {
		fprintf(stderr, "\nrprocess_rt_data found a lock file ... ");
		fscanf(out, "%lu", &procid);
		fprintf(stderr, "\n  PID: %lu", procid);
		fclose(out);
		sprintf(outstring1,"/proc/%lu/cmdline",procid);
		out = fopen(outstring1, "r");
		if (out != NULL) {
			fscanf(out, "%s", outstring1);
			sprintf(instring,"process_real_time_data");
			//if( strncmp(outstring1,"/home/radio",11)==0 )
			if (strstr(outstring1, instring) != NULL) {
				fprintf(stderr, "\n  Process Exists. Exiting ...\n\n");
				fclose(out);
				exit(0);
			}
			fclose(out);
		}
		sprintf(instring,"%s/process_rt_data_running",options.tmpdir);
		remove(instring);
		fprintf(stderr, "\n  Process Does Not Exist. Lock File Removed\n");
	}

	sprintf(instring,"%s/process_rt_data_running",options.tmpdir);

	out = fopen(instring, "w");

	if (out != NULL) {
		fprintf(out, "%lu", (long unsigned int) getpid());
		fclose(out);
	} else {
		fprintf(stderr, "Couldn't write lock file %s?!", instring);
		exit(-1);
	}

	/* initialize the images */
	for (i = 0; i < 512; i++)
		for (j = 0; j < IMAGE_WIDTH; j++) {
			im1o[i][j] = 20.;
			im2o[i][j] = 20.;
			im3o[i][j] = 20.;
			im4o[i][j] = 20.;
		}

	/* initialize Hann window */
	for (i = 0; i < 1024; i++) {
		hann[i] = 0.5 * (1 - cos(2*M_PI*i/1023));
	}

	/* initialize the fftw3 plans */
	plan_forward1 = fftw_plan_r2r_1d(1024, fft_samples1, out1, FFTW_R2HC, FFTW_MEASURE);
	plan_forward2 = fftw_plan_r2r_1d(1024, fft_samples2, out2, FFTW_R2HC, FFTW_MEASURE);
	plan_forward3 = fftw_plan_r2r_1d(1024, fft_samples3, out3, FFTW_R2HC, FFTW_MEASURE);
	plan_forward4 = fftw_plan_r2r_1d(1024, fft_samples4, out4, FFTW_R2HC, FFTW_MEASURE);


	while (1) {
		/* read in the new data */
		read_new_samples(samples, &options);
		/* fft the new data */
		fft_new_samples(samples);

		sprintf(instring,"%s/hf2_display_running",options.tmpdir);
		in = fopen(instring, "r");
		if (in != NULL) {
			write_data = 1;
			fclose(in);
		} else
			write_data = 0;

		sprintf(instring,"%s/levels.grayscale",options.tmpdir);
		in = fopen(instring, "r");
		if (in != NULL) {
			fscanf(in, "%d %d", &gray_min, &gray_max);
			fclose(in);
		} else {
			gray_min = 0;
			gray_max = 60.;
		}
		if (old_gray_min != gray_min || old_gray_max != gray_max)
			rescale_images();
		if (write_data) {
			sprintf(instring,"%s/test.data",options.tmpdir);
			out = fopen(instring, "w");
		} else {
			printf("hf2_display not running?\n");
		}

		for (i = 0; i < 512; i++) {
			x[i] = i * df;
			memcpy(*(im1+i),&im1[i][1],IMAGE_WIDTH-1);
			memcpy(*(im2+i),&im2[i][1],IMAGE_WIDTH-1);
			memcpy(*(im3+i),&im3[i][1],IMAGE_WIDTH-1);
			memcpy(*(im4+i),&im4[i][1],IMAGE_WIDTH-1);
			memcpy((im1o+i),&im1o[i][1],(IMAGE_WIDTH-1)*sizeof(float));
			memcpy((im2o+i),&im2o[i][1],(IMAGE_WIDTH-1)*sizeof(float));
			memcpy((im3o+i),&im3o[i][1],(IMAGE_WIDTH-1)*sizeof(float));
			memcpy((im4o+i),&im4o[i][1],(IMAGE_WIDTH-1)*sizeof(float));
			r1 = out1[i];
			r2 = out2[i];
			r3 = out3[i];
			r4 = out4[i];
			im1o[512 - i][IMAGE_WIDTH-1] = r1;
			im2o[512 - i][IMAGE_WIDTH-1] = r2;
			im3o[512 - i][IMAGE_WIDTH-1] = r3;
			im4o[512 - i][IMAGE_WIDTH-1] = r4;
			v1 = a + r1 * b + 0.5;
			v2 = a + r2 * b + 0.5;
			v3 = a + r3 * b + 0.5;
			v4 = a + r4 * b + 0.5;
			if (v1 < 0)
				v1 = 0;
			if (v2 < 0)
				v2 = 0;
			if (v3 < 0)
				v3 = 0;
			if (v4 < 0)
				v4 = 0;
			if (v1 > 255)
				v1 = 255;
			if (v2 > 255)
				v2 = 255;
			if (v3 > 255)
				v3 = 255;
			if (v4 > 255)
				v4 = 255;

			im1[512 - i][IMAGE_WIDTH-1] = 255 - (unsigned char) v1;
			im2[512 - i][IMAGE_WIDTH-1] = 255 - (unsigned char) v2;
			im3[512 - i][IMAGE_WIDTH-1] = 255 - (unsigned char) v3;
			im4[512 - i][IMAGE_WIDTH-1] = 255 - (unsigned char) v4;

			if (write_data)
				fprintf(out, "%.0f %.2f %.2f %.2f\n", x[i], r1, r2, r3);
		}

		if (write_data) {
			fclose(out);

			sprintf(instring,"%s/test.image1",options.tmpdir);
			image1 = fopen(instring, "w");
			fprintf(image1, "P5\n%i 512\n255\n",IMAGE_WIDTH);
			fwrite(im1, sizeof(im1), 1, image1);
			fclose(image1);

			sprintf(instring,"%s/test.image2",options.tmpdir);
			image2 = fopen(instring, "w");
			fprintf(image2, "P5\n%i 512\n255\n",IMAGE_WIDTH);
			fwrite(im2, sizeof(im2), 1, image2);
			fclose(image2);

			sprintf(instring,"%s/test.image3",options.tmpdir);
			image3 = fopen(instring, "w");
			fprintf(image3, "P5\n%i 512\n255\n",IMAGE_WIDTH);
			fwrite(im3, sizeof(im3), 1, image3);
			fclose(image3);

			sprintf(instring,"%s/test.image4",options.tmpdir);
			image4 = fopen(instring, "w");
			fprintf(image4, "P5\n%i 512\n255\n",IMAGE_WIDTH);
			fwrite(im4, sizeof(im4), 1, image4);
			fclose(image4);
		}
		usleep(1e4);
	}
	return (0);
}
Exemple #8
0
int
sys_nice(void)
{
	return nice();
}
void parse_common_args(int *argc,char *argv[],unsigned long Flags,
		       int nfile,t_filenm fnm[],int npargs,t_pargs *pa,
		       int ndesc,char **desc,int nbugs,char **bugs)
{
  static bool bHelp=FALSE,bHidden=FALSE,bQuiet=FALSE;
  static char *manstr[]      = { NULL, "no", "html", "tex", "nroff", "ascii", "completion", "py", "xml", "wiki", NULL };
  static int  nicelevel=0,mantp=0,npri=0,debug_level=0;
  static char *deffnm=NULL;
  static real tbegin=0,tend=0,tdelta=0;
       
  t_pargs *all_pa=NULL;
  
  t_pargs npri_pa   = { "-npri", FALSE, etINT,   {&npri},
		       "HIDDEN Set non blocking priority (try 128)" };
  t_pargs nice_pa   = { "-nice", FALSE, etINT,   {&nicelevel}, 
		       "Set the nicelevel" };
  t_pargs deffnm_pa = { "-deffnm", FALSE, etSTR, {&deffnm}, 
		       "Set the default filename for all file options" };
  t_pargs begin_pa  = { "-b",    FALSE, etTIME,  {&tbegin},        
		       "First frame (%t) to read from trajectory" };
  t_pargs end_pa    = { "-e",    FALSE, etTIME,  {&tend},        
		       "Last frame (%t) to read from trajectory" };
  t_pargs dt_pa     = { "-dt",   FALSE, etTIME,  {&tdelta},        
		       "Only use frame when t MOD dt = first time (%t)" };
  t_pargs view_pa   = { "-w",    FALSE, etBOOL,  {&bView},
		       "View output xvg, xpm, eps and pdb files" };
  t_pargs code_pa   = { "-xvgr", FALSE, etBOOL,  {&bXvgrCodes},
		       "Add specific codes (legends etc.) in the output xvg files for the xmgrace program" };
  t_pargs time_pa   = { "-tu",   FALSE, etENUM,  {timestr},
			"Time unit" };
  /* Maximum number of extra arguments */
#define EXTRA_PA 16

  t_pargs pca_pa[] = {
    { "-h",    FALSE, etBOOL, {&bHelp},     
      "Print help info and quit" }, 
    { "-hidden", FALSE, etBOOL, {&bHidden},
      "HIDDENPrint hidden options" },
    { "-quiet",FALSE, etBOOL, {&bQuiet},
      "HIDDENDo not print help info" },
    { "-man",  FALSE, etENUM,  {manstr},
      "HIDDENWrite manual and quit" },
    { "-debug",FALSE, etINT, {&debug_level},
      "HIDDENWrite file with debug information, 1: short, 2: also x and f" },
  };
#define NPCA_PA asize(pca_pa)
  FILE *fp;  
  bool bPrint,bExit,bXvgr;
  int  i,j,k,npall,max_pa,cmdlength;
  char *ptr,*newdesc;
  char *envstr;

#define FF(arg) ((Flags & arg)==arg)

  cmdlength = strlen(argv[0]);
  /* Check for double arguments */
  for (i=1; (i<*argc); i++) {
    cmdlength += strlen(argv[i]);
    if (argv[i] && (strlen(argv[i]) > 1) && (!isdigit(argv[i][1]))) {
      for (j=i+1; (j<*argc); j++) {
	if ( (argv[i][0]=='-') && (argv[j][0]=='-') && 
	     (strcmp(argv[i],argv[j])==0) ) {
	  if (FF(PCA_NOEXIT_ON_ARGS))
	    fprintf(stderr,"Double command line argument %s\n",argv[i]);
	  else
	    gmx_fatal(FARGS,"Double command line argument %s\n",argv[i]);
	}
      }
    }
  }
  debug_gmx();

  /* Fill the cmdline string */
  snew(cmdline,cmdlength+*argc+1);
  for (i=0; (i<*argc); i++) {
    strcat(cmdline,argv[i]);
    strcat(cmdline," ");
  }
  
  /* Handle the flags argument, which is a bit field 
   * The FF macro returns whether or not the bit is set
   */
  bPrint        = !FF(PCA_SILENT);
  
  set_program_name(argv[0]);

  /* Check ALL the flags ... */
  max_pa = NPCA_PA + EXTRA_PA + npargs;
  snew(all_pa,max_pa);
  
  for(i=npall=0; (i<NPCA_PA); i++)
    npall = add_parg(npall,all_pa,&(pca_pa[i]));

#ifdef __sgi
  envstr = getenv("GMXNPRIALL");
  if (envstr)
    npri=atoi(envstr);
  if (FF(PCA_BE_NICE)) {
    envstr = getenv("GMXNPRI");
    if (envstr)
      npri=atoi(envstr);
  }
  npall = add_parg(npall,all_pa,&npri_pa);
#endif

  if (FF(PCA_BE_NICE)) 
    nicelevel=19;
  npall = add_parg(npall,all_pa,&nice_pa);

  if (FF(PCA_CAN_SET_DEFFNM)) 
    npall = add_parg(npall,all_pa,&deffnm_pa);   
  if (FF(PCA_CAN_BEGIN)) 
    npall = add_parg(npall,all_pa,&begin_pa);
  if (FF(PCA_CAN_END))
    npall = add_parg(npall,all_pa,&end_pa);
  if (FF(PCA_CAN_DT))
    npall = add_parg(npall,all_pa,&dt_pa);
  if (FF(PCA_TIME_UNIT)) {
    envstr = getenv("GMXTIMEUNIT");
    if ( envstr == NULL )
      envstr="ps";
    set_default_time_unit(envstr);
    npall = add_parg(npall,all_pa,&time_pa);
  } else
    set_default_time_unit("ps");
  if (FF(PCA_CAN_VIEW)) 
    npall = add_parg(npall,all_pa,&view_pa);
    
  bXvgr = FALSE;
  for(i=0; (i<nfile); i++)
    bXvgr = bXvgr ||  (fnm[i].ftp == efXVG);
  if (bXvgr)
    npall = add_parg(npall,all_pa,&code_pa);
  
  /* Now append the program specific arguments */
  for(i=0; (i<npargs); i++)
    npall = add_parg(npall,all_pa,&(pa[i]));

  /* set etENUM options to default */
  for(i=0; (i<npall); i++)
    if (all_pa[i].type==etENUM)
      all_pa[i].u.c[0]=all_pa[i].u.c[1];
  
  /* Now parse all the command-line options */
  get_pargs(argc,argv,npall,all_pa,FF(PCA_KEEP_ARGS));

  if (FF(PCA_CAN_SET_DEFFNM) && (deffnm!=NULL))
    set_default_file_name(deffnm);

  /* Parse the file args */
  parse_file_args(argc,argv,nfile,fnm,FF(PCA_KEEP_ARGS));

  /* Open the debug file */
  if (debug_level > 0) {
    char buf[256];

    if (gmx_mpi_initialized())
      sprintf(buf,"%s%d.log",ShortProgram(),gmx_node_rank());
    else
      sprintf(buf,"%s.log",ShortProgram());
      
    init_debug(debug_level,buf);
    fprintf(stderr,"Opening debug file %s (src code file %s, line %d)\n",
	    buf,__FILE__,__LINE__);
  }

  /* Now copy the results back... */
  for(i=0,k=npall-npargs; (i<npargs); i++,k++) 
    memcpy(&(pa[i]),&(all_pa[k]),(size_t)sizeof(pa[i]));
  
  for(i=0; (i<npall); i++)
    all_pa[i].desc = mk_desc(&(all_pa[i]), time_unit() );

  bExit = bHelp || (strcmp(manstr[0],"no") != 0);

#if (defined __sgi && USE_SGI_FPE)
  doexceptions();
#endif

  /* Set the nice level */
#ifdef __sgi
  if (npri != 0 && !bExit) {
    schedctl(MPTS_RTPRI,0,npri);
  }
#endif 

#ifdef HAVE_UNISTD_H

#ifndef GMX_NO_NICE
  /* The some system, e.g. the catamount kernel on cray xt3 do not have nice(2). */
  if (nicelevel != 0 && !bExit)
    i=nice(nicelevel); /* assign ret value to avoid warnings */
#endif

#endif
  
  if (!(FF(PCA_QUIET) || bQuiet )) {
    if (bHelp)
      write_man(stderr,"help",program,ndesc,desc,nfile,fnm,npall,all_pa,
		nbugs,bugs,bHidden);
    else if (bPrint) {
      pr_fns(stderr,nfile,fnm);
      print_pargs(stderr,npall,all_pa,FALSE);
    }
  }

  if (strcmp(manstr[0],"no") != 0) {
    if(!strcmp(manstr[0],"completion")) {
      /* one file each for csh, bash and zsh if we do completions */
      fp=man_file(program,"completion-zsh");
      write_man(fp,"completion-zsh",program,ndesc,desc,nfile,fnm,npall,all_pa,nbugs,bugs,bHidden);
      gmx_fio_fclose(fp);
      fp=man_file(program,"completion-bash");
      write_man(fp,"completion-bash",program,ndesc,desc,nfile,fnm,npall,all_pa,nbugs,bugs,bHidden);
      gmx_fio_fclose(fp);
      fp=man_file(program,"completion-csh");
      write_man(fp,"completion-csh",program,ndesc,desc,nfile,fnm,npall,all_pa,nbugs,bugs,bHidden);
      gmx_fio_fclose(fp);
    } else {
      fp=man_file(program,manstr[0]);
      write_man(fp,manstr[0],program,ndesc,desc,nfile,fnm,npall,all_pa,nbugs,bugs,bHidden);
      gmx_fio_fclose(fp);
    }
  }
  
  /* convert time options, must be done after printing! */
  init_time_factor();
  for(i=0; i<npall; i++) {
    if ((all_pa[i].type == etTIME) && (*all_pa[i].u.r >= 0)) {
      *all_pa[i].u.r *= timeinvfac;
    }
  }

  /* Extract Time info from arguments */
  if (FF(PCA_CAN_BEGIN) && opt2parg_bSet("-b",npall,all_pa))
    setTimeValue(TBEGIN,opt2parg_real("-b",npall,all_pa));

  if (FF(PCA_CAN_END) && opt2parg_bSet("-e",npall,all_pa))
    setTimeValue(TEND,opt2parg_real("-e",npall,all_pa));
  
  if (FF(PCA_CAN_DT) && opt2parg_bSet("-dt",npall,all_pa))
    setTimeValue(TDELTA,opt2parg_real("-dt",npall,all_pa));
  
  /* clear memory */
  sfree(all_pa);
  
  if (!FF(PCA_NOEXIT_ON_ARGS)) {
    if (*argc > 1) {
      gmx_cmd(argv[1]);
    }
  } 
  if (bExit) {
    if (gmx_parallel_env)
      gmx_abort(gmx_node_rank(),gmx_node_num(),0);
    else
      exit(0);
  }
#undef FF
}
Exemple #10
0
int main(int argc, char **argv) {
	int help_flag = 0;
	int aahelp_flag = 0;
	int justoutput_flag = 0;
	int loadavg_flag = 0;
	int ipc_flag = 0;
	int port_num = DEFPORT;
	int max_iterations = 0;
	int delay = 0;
	int normal_load;
	int socket_fd = -1;
	float randomizestyletime = 0;
	float randomizesitetime  = 0;
	char *endptr;

	setlocale(LC_ALL, "");
	bindtextdomain("aajm", LOCALEDIR);
	textdomain("aajm");

	char options[] = "aljhip:n:d:m:t:s:T:S:";
	static struct option long_options[] =
        {
		{"help", no_argument, &help_flag, 1},
		{"aahelp", no_argument, &aahelp_flag, 1},
		{"justoutput", no_argument, &justoutput_flag, 1},
		{"ipc", no_argument, &ipc_flag, 1},
		{"loadavg", no_argument, &loadavg_flag, 1},
		{"maxiterations", required_argument, 0, 'm'},
		{"port", required_argument, 0, 'p'},
		{"normalload", required_argument, 0, 'n'},
		{"delay", required_argument, 0, 'd'},
		{"siteswap", required_argument, 0, 's'},
		{"style", required_argument, 0, 't'},
		{"rstyle", required_argument, 0, 'S'},
		{"rsiteswap", required_argument, 0, 'T'},
		{0,0,0,0}
	};

	normal_load = (int)(DEFLOAD * 100);
	char optch;
	int option_index = 0;

	//jmlib = new JMLib(errorCB);
    jmlib = JMLib::alloc();
	jmlib->setPatternDefault();
	jmlib->setStyleDefault();
	jmlib->startJuggle();

	aa_parseoptions(NULL, NULL, &argc, argv);

	while( (optch = getopt_long(argc,argv,options,
			long_options,&option_index)) != -1)
		switch(optch) {
			case 's':
				jmlib->setPattern("Something",optarg,
					HR_DEF, DR_DEF);
				break;
			case 't':
				jmlib->setStyle(optarg);
				break;
			case 'S':
				randomizesitetime = strtod(optarg, &endptr);
				if (endptr==optarg || *endptr != 0) {
						randomizesitetime = DEFRANDOMSITETIME;
				}
				break;
			case 'T':
				randomizestyletime = strtod(optarg, &endptr);
				if (endptr==optarg || *endptr != 0) {
						randomizestyletime = DEFRANDOMSTYLETIME;
				}
				break;
			case 'h':
				help_flag=1;
				break;
			case 'a':
				aahelp_flag=1;
				break;
			case 'j':
				justoutput_flag=1;
				break;
			case 'm':
				max_iterations = atoi(optarg);
				break;
			case 'd':
				delay = atoi(optarg);
				break;
			case 'l':
				loadavg_flag=1;
				break;
			case 'n':
				normal_load = (int)(100*atof(optarg));
				break;
			case 'i':
				ipc_flag=1;
				break;
			case 'p':
				port_num=atoi(optarg);
				break;
		}

	if(aahelp_flag || help_flag) {
		printf(gettext("AAJM, An ASCII Art Juggling program\n"));
		printf(gettext("Usage: %s [OPTIONS]\n"),argv[0]);
	}
	if(help_flag) {
		printf(gettext("Jugglemaster Options:\n"));
		printf(gettext("  -s, --siteswap=XX          show siteswap XX (3)\n"));
		printf(gettext("  -t, --style=XX             use style XX (\"Normal\")\n"));
		printf(gettext("  -S, --rsiteswap=XX         Randomize siteswap every XX seconds (%f)\n"), DEFRANDOMSITETIME);
		printf(gettext("  -T, --rstyle=XX            Randomize style every XX seconds (%f)\n"), DEFRANDOMSTYLETIME);
		printf(gettext("  -d, --delay=XX             delay XX ms between frames (%i)\n"), (int)DEFSPEED/1000);
		printf(gettext("  -m, --maxiterations=XX     do at most XX iterations\n"));
		printf(gettext("  -j, --justoutput           only output [don't init kb or mouse]\n"));
		printf(gettext("  -i, --ipc                  enable IPC\n"));
		printf(gettext("  -p, --port=XX              use port XX for IPC (%i)\n"),DEFPORT);
		printf(gettext("  -l, --loadavg              change speed based on load average\n"));
		printf(gettext("  -n, --normalload=XX        a normal load average for your machine (%2.2f)\n"),DEFLOAD);
		printf(gettext("  -h, --help                 get help [this screen]\n"));
		printf(gettext("  -a, --aahelp               get help on AA options\n\n"));
	}
	if(aahelp_flag) {
		printf(gettext("AALib Options:\n%s\n\n"),aa_help);
	}
	if(aahelp_flag || help_flag) {
		return 0;
	}


	context = aa_autoinit(&aa_defparams);
	if (context == NULL) {
		printf(gettext("Failed to initialize aalib\n"));
		exit(1);
	}

	if(!justoutput_flag) {
		aa_autoinitkbd(context, 0);
		aa_hidecursor(context);
	}
	params = aa_getrenderparams();
	jmlib->setWindowSize(aa_imgwidth(context),aa_imgheight(context));
	jmlib->startJuggle();

	aa_resizehandler(context, resizehandler);

	if(loadavg_flag) {
		/* If we're doing that thing where we care, then this
			can go down to as-low-as-possible priority */
		nice(19);
	}

	if(ipc_flag) {
		socket_fd = startlistening(port_num);
	}

	main_loop(max_iterations,delay,loadavg_flag,normal_load, socket_fd,
                  randomizestyletime, randomizesitetime);

	if(socket_fd > 0) {
		stoplistening(socket_fd);
	}
	aa_close(context);

	delete jmlib;
	return 1;
}
Exemple #11
0
/******************************************************************************
 ** Function Name : main
 ** Description   : This function is Entry Point for JE. Calls all initialization
 **                  routines and invokes JE Daemon.
 ** Input params  : argc - Number of Arguments
 **                : argv - Argument Vector
 ** Output params : None
 ** Return value  : OF_SUCCESS in Success
 **                  OF_FAILURE in Failure case
 *******************************************************************************/
int main (int32_t argc, char * argv[])
{
   int32_t argIndex;
#ifdef CM_LDSV_SUPPORT
   unsigned char bUCMNoLoadCfg=FALSE;
#endif

   signal (SIGPIPE, SIG_IGN);
   if ((argc == 1) || ((argc == 2) && (of_strcmp (argv[1], "-f"))))
   {
      daemon_init ();
   }

   if (nice (UCMJE_SCHEDULING_PRIORITY) != OF_SUCCESS)
   {
      CM_JE_DEBUG_PRINT ("Couldn't set priority");
   }

   cm_je_init ();
   cm_dm_init ();
#ifdef CM_ROLES_PERM_SUPPORT
   cmi_dm_role_perm_init();
#endif
#ifdef CM_EVENT_NOTIFMGR_SUPPORT
   cm_evmgr_register_all_events();
#endif /*CM_EVENT_NOTIFMGR_SUPPORT */


//#ifdef OF_CM_CBKINI_SUPPORT
#if OF_CM_CNTRL_SUPPORT
   UCMCBKInit();
#endif

#ifdef OF_CM_SWITCH_CBK_SUPPORT
   UCMSwitchCBKInit();
#endif


#ifdef OF_UCMGLU_SUPPORT
#ifdef CM_SECAPPL_DLL_SUPPORT
  // IGWUCMRootInit ();         /* Call back Library */
   //cm_sec_appl_init();
#else
  // IGWUCMRootInit ();         /* Call back Library */
#endif
#endif


#ifdef CM_EVENT_NOTIFMGR_SUPPORT
   cm_evmgr_init();
#endif

#ifdef CM_LDSV_SUPPORT
   for (argIndex=1; argIndex < argc; argIndex++)
   {
      if (!of_strcmp (argv[argIndex],CM_JE_NO_LOAD_CONFIGURATION))
      {
         bUCMNoLoadCfg=TRUE;
         break;
      }
   }
   if(bUCMNoLoadCfg==FALSE)
   {
      cm_je_ldsv_init ();
   }
#endif
   cm_je_daemon ();
  return 0;
}
Exemple #12
0
void
set_options (int argc, char *argv[])
{
	int opt;
	int sethost = 0;
	int index;
	char *lip;

	opts.log = 1;
	opts.rrtp = NULL;
	opts.disc_host = "239.255.255.250";
	opts.start_rtp = 5500;
	opts.http_port = 8080;
	opts.http_host = NULL;
	opts.log = 0;
	opts.timeout_sec = 30000;
	opts.force_sadapter = 0;
	opts.force_tadapter = 0;
	opts.force_cadapter = 0;
	opts.mac[0] = 0;
	opts.daemon = 1;
	opts.bw = 0;
	opts.device_id = 0;
	opts.bootid = 0;
	opts.force_scan = 0;
	opts.dvr_buffer = DVR_BUFFER;
	opts.adapter_buffer = ADAPTER_BUFFER;
	opts.file_line = 0;
	opts.dvbapi_port = 0;
	opts.dvbapi_host = NULL;
	opts.drop_encrypted = 1;
	opts.rtsp_port = 554;
	opts.clean_psi = 0;
	opts.satip_addpids = 0;
	opts.output_buffer = 512*1024;
	opts.satip_servers[0] = 0;
	memset(opts.playlist, sizeof(opts.playlist), 0);
	
	
	while ((opt = getopt_long (argc, argv, "flr:a:td:w:p:s:hc:b:m:p:e:x:u:j:o:gy:zi:D:V", long_options, NULL)) != -1)
	{
		//              printf("options %d %c %s\n",opt,opt,optarg);
		switch (opt)
		{
			case FOREGROUND_OPT:
			{
				opts.daemon = 0;
				break;
			}
			case MAC_OPT:
			{
				strncpy (opts.mac, optarg, 12);
				opts.mac[12] = 0;
				break;
			}
			case RRTP_OPT:
			{
				opts.rrtp = optarg;
				break;
			}

			case DEVICEID_OPT:
			{
				opts.device_id = atoi (optarg);
				break;
			}

			case HTTPSERVER_OPT:
			{
				//                              int i=0;
				opts.http_host = optarg;
				sethost = 1;
				break;
			}

			case LOG_OPT:
			{
				opts.log++;
				break;
			}

			case SYSLOG_OPT:
			{
				opts.slog++;
				break;
			}

			case HELP_OPT:
			{
				usage ();
				exit (0);
			}
			
			case VERSION_OPT:
			{
				LOGL(0, "minisatip version %s, compiled with s2api version: %04X",VERSION, DVBAPIVERSION);
				exit (0);	
			}

			case HTTPPORT_OPT:
			{
				opts.http_port = atoi (optarg);
				break;
			}

			case BW_OPT:
			{
				opts.bw = atoi (optarg) * 1024;
				break;
			}

			case DVRBUFFER_OPT:
			{
				sscanf(optarg,"%d:%d", &opts.adapter_buffer, &opts.dvr_buffer) ;
				opts.adapter_buffer = (opts.adapter_buffer/188) * 188;
				if(opts.adapter_buffer < ADAPTER_BUFFER)
					opts.adapter_buffer = ADAPTER_BUFFER;
				if(opts.dvr_buffer == 0 )
					opts.dvr_buffer = DVR_BUFFER;
					
				break;
			}

			case DVBS2_ADAPTERS_OPT:
			{
				sscanf(optarg,"%d:%d:%d", &opts.force_sadapter, &opts.force_tadapter, &opts.force_cadapter) ;
				break;
			}

			case CLEANPSI_OPT:
			{
				opts.clean_psi = 1;
				break;
			}
			
			case SCAN_OPT:
			{
				opts.force_scan = 1;
				break;
			}

			case PLAYLIST_OPT:
			{
				snprintf(opts.playlist, sizeof(opts.playlist), "<satip:X_SATIPM3U xmlns:satip=\"urn:ses-com:satip\">%s</satip:X_SATIPM3U>\r\n",optarg);
				break;
			}
			
			case ENABLE_ADAPTERS_OPT:
			{
				enable_adapters(optarg);
				break;
			}
			
			case UNICABLE_OPT:
			{
				set_unicable_adapters(optarg, SWITCH_UNICABLE);
				break;
			}

			case JESS_OPT:
			{
				set_unicable_adapters(optarg, SWITCH_JESS);
				break;
			}
			
			case DISEQC_OPT:
			{
				set_diseqc_adapters(optarg);
			}
			
			case DVBAPI_OPT:
			{
				char* sep1 = strchr(optarg, ':');
				if ( sep1 != NULL)
				{
					*sep1 = 0;
					opts.dvbapi_host = optarg;
					opts.dvbapi_port = map_int(sep1 + 1, NULL );
				}
				break;
			}
			
			case RTSPPORT_OPT:
			{
				opts.rtsp_port = atoi (optarg);
				break;
			}

			case SATIPCLIENT_OPT:
				if(strlen(optarg) + strlen(opts.satip_servers) > sizeof(opts.satip_servers))
					break;
					
				if(opts.satip_servers[0])
					sprintf(opts.satip_servers + strlen(opts.satip_servers), ",%s", optarg );
				else 
					sprintf(opts.satip_servers, "%s", optarg );
				break;

			case PRIORITY_OPT:
			
				if(nice(map_int(optarg, NULL)) == -1)
					LOG("Failed to set priority %s", strerror(errno));
				break;
			
		}
			
	}
	
	if(opts.bw && (opts.bw < opts.adapter_buffer))
			opts.adapter_buffer = (opts.bw / 188) * 188;
			
	lip = getlocalip ();
	if (!opts.http_host)
	{
		opts.http_host = (char *) malloc (MAX_HOST);
		sprintf (opts.http_host, "%s:%d", lip, opts.http_port);
	}
}
int
main(int argc, char *argv[])
{
#define	 check(ol,al)		if (argv[i][ol] || \
				badarg(argc-i-1,argv+i+1,al)) \
				goto badopt
#define	 check_bool(olen,var)		switch (argv[i][olen]) { \
				case '\0': var = !var; break; \
				case 'y': case 'Y': case 't': case 'T': \
				case '+': case '1': var = 1; break; \
				case 'n': case 'N': case 'f': case 'F': \
				case '-': case '0': var = 0; break; \
				default: goto badopt; }
	char  *octnm = NULL;
	char  *err;
	int  rval;
	int  i;
					/* global program name */
	progname = argv[0] = fixargv0(argv[0]);
					/* set our defaults */
	shadthresh = .1;
	shadcert = .25;
	directrelay = 0;
	vspretest = 128;
	srcsizerat = 0.;
	specthresh = .3;
	specjitter = 1.;
	maxdepth = 6;
	minweight = 1e-2;
	ambacc = 0.3;
	ambres = 32;
	ambdiv = 256;
	ambssamp = 64;
					/* option city */
	for (i = 1; i < argc; i++) {
						/* expand arguments */
		while ((rval = expandarg(&argc, &argv, i)) > 0)
			;
		if (rval < 0) {
			sprintf(errmsg, "cannot expand '%s'", argv[i]);
			error(SYSTEM, errmsg);
		}
		if (argv[i] == NULL || argv[i][0] != '-')
			break;			/* break from options */
		if (!strcmp(argv[i], "-version")) {
			puts(VersionID);
			quit(0);
		}
		if (!strcmp(argv[i], "-defaults") ||
				!strcmp(argv[i], "-help")) {
			printdefaults();
			quit(0);
		}
		if (!strcmp(argv[i], "-devices")) {
			printdevices();
			quit(0);
		}
		rval = getrenderopt(argc-i, argv+i);
		if (rval >= 0) {
			i += rval;
			continue;
		}
		rval = getviewopt(&ourview, argc-i, argv+i);
		if (rval >= 0) {
			i += rval;
			continue;
		}
		switch (argv[i][1]) {
		case 'n':				/* # processes */
			check(2,"i");
			nproc = atoi(argv[++i]);
			if (nproc <= 0)
				error(USER, "bad number of processes");
			break;
		case 'v':				/* view file */
			if (argv[i][2] != 'f')
				goto badopt;
			check(3,"s");
			rval = viewfile(argv[++i], &ourview, NULL);
			if (rval < 0) {
				sprintf(errmsg,
				"cannot open view file \"%s\"",
						argv[i]);
				error(SYSTEM, errmsg);
			} else if (rval == 0) {
				sprintf(errmsg,
					"bad view file \"%s\"",
						argv[i]);
				error(USER, errmsg);
			}
			break;
		case 'b':				/* grayscale */
			check_bool(2,greyscale);
			break;
		case 'p':				/* pixel */
			switch (argv[i][2]) {
			case 's':				/* sample */
				check(3,"i");
				psample = atoi(argv[++i]);
				break;
			case 't':				/* threshold */
				check(3,"f");
				maxdiff = atof(argv[++i]);
				break;
			case 'e':				/* exposure */
				check(3,"f");
				exposure = atof(argv[++i]);
				if (argv[i][0] == '+' || argv[i][0] == '-')
					exposure = pow(2.0, exposure);
				break;
			default:
				goto badopt;
			}
			break;
		case 'w':				/* warnings */
			rval = erract[WARNING].pf != NULL;
			check_bool(2,rval);
			if (rval) erract[WARNING].pf = wputs;
			else erract[WARNING].pf = NULL;
			break;
		case 'e':				/* error file */
			check(2,"s");
			errfile = argv[++i];
			break;
		case 'o':				/* output device */
			check(2,"s");
			dvcname = argv[++i];
			break;
		case 'R':				/* render input file */
			check(2,"s");
			strcpy(rifname, argv[++i]);
			break;
		default:
			goto badopt;
		}
	}
	err = setview(&ourview);	/* set viewing parameters */
	if (err != NULL)
		error(USER, err);
						/* set up signal handling */
	sigdie(SIGINT, "Interrupt");
	sigdie(SIGTERM, "Terminate");
#if !defined(_WIN32) && !defined(_WIN64)
	sigdie(SIGHUP, "Hangup");
	sigdie(SIGPIPE, "Broken pipe");
	sigdie(SIGALRM, "Alarm clock");
#endif
					/* open error file */
	if (errfile != NULL) {
		if (freopen(errfile, "a", stderr) == NULL)
			quit(2);
		fprintf(stderr, "**************\n*** PID %5d: ",
				getpid());
		printargs(argc, argv, stderr);
		putc('\n', stderr);
		fflush(stderr);
	}
#ifdef	NICE
	nice(NICE);			/* lower priority */
#endif
					/* get octree */
	if (i == argc)
		octnm = NULL;
	else if (i == argc-1)
		octnm = argv[i];
	else
		goto badopt;
	if (octnm == NULL)
		error(USER, "missing octree argument");
					/* set up output & start process(es) */
	SET_FILE_BINARY(stdout);
	
	ray_init(octnm);		/* also calls ray_init_pmap() */
	
/* temporary shortcut, until winrview is refactored into a "device" */
#ifndef WIN_RVIEW
	rview();			/* run interactive viewer */


	devclose();			/* close output device */
#endif

	/* PMAP: free photon maps */
	ray_done_pmap();
	
#ifdef WIN_RVIEW
	return 1;
#endif
	quit(0);

badopt:
	sprintf(errmsg, "command line error at '%s'", argv[i]);
	error(USER, errmsg);
	return 1; /* pro forma return */

#undef	check
#undef	check_bool
}
Exemple #14
0
void join(pid_t pid, int argc, char **argv, int index) {
	EUID_ASSERT();
	char *homedir = cfg.homedir;

	extract_command(argc, argv, index);
	signal (SIGTERM, signal_handler);

	// if the pid is that of a firejail  process, use the pid of the first child process
	EUID_ROOT();
	char *comm = pid_proc_comm(pid);
	EUID_USER();
	if (comm) {
		if (strcmp(comm, "firejail") == 0) {
			pid_t child;
			if (find_child(pid, &child) == 0) {
				pid = child;
				if (!arg_quiet)
					printf("Switching to pid %u, the first child process inside the sandbox\n", (unsigned) pid);
			}
		}
		free(comm);
	}

	// check privileges for non-root users
	uid_t uid = getuid();
	if (uid != 0) {
		uid_t sandbox_uid = pid_get_uid(pid);
		if (uid != sandbox_uid) {
			fprintf(stderr, "Error: permission is denied to join a sandbox created by a different user.\n");
			exit(1);
		}
	}

	EUID_ROOT();
	// in user mode set caps seccomp, cpu, cgroup, etc
	if (getuid() != 0) {
		extract_caps_seccomp(pid);
		extract_cpu(pid);
		extract_cgroup(pid);
		extract_nogroups(pid);
		extract_user_namespace(pid);
	}
	
	// set cgroup
	if (cfg.cgroup)	// not available for uid 0
		set_cgroup(cfg.cgroup);
		
	// join namespaces
	if (arg_join_network) {
		if (join_namespace(pid, "net"))
			exit(1);
	}
	else if (arg_join_filesystem) {
		if (join_namespace(pid, "mnt"))
			exit(1);
	}
	else {
		if (join_namespace(pid, "ipc") ||
		    join_namespace(pid, "net") ||
		    join_namespace(pid, "pid") ||
		    join_namespace(pid, "uts") ||
		    join_namespace(pid, "mnt"))
			exit(1);
	}

	pid_t child = fork();
	if (child < 0)
		errExit("fork");
	if (child == 0) {
		// chroot into /proc/PID/root directory
		char *rootdir;
		if (asprintf(&rootdir, "/proc/%d/root", pid) == -1)
			errExit("asprintf");
			
		int rv;
		if (!arg_join_network) {
			rv = chroot(rootdir); // this will fail for processes in sandboxes not started with --chroot option
			if (rv == 0)
				printf("changing root to %s\n", rootdir);
		}
		
		prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); // kill the child in case the parent died
		if (chdir("/") < 0)
			errExit("chdir");
		if (homedir) {
			struct stat s;
			if (stat(homedir, &s) == 0) {
				/* coverity[toctou] */
				if (chdir(homedir) < 0)
					errExit("chdir");
			}
		}
		
		// set cpu affinity
		if (cfg.cpus)	// not available for uid 0
			set_cpu_affinity();
					
		// set caps filter
		if (apply_caps == 1)	// not available for uid 0
			caps_set(caps);
#ifdef HAVE_SECCOMP
		// read cfg.protocol from file
		if (getuid() != 0)
			protocol_filter_load(RUN_PROTOCOL_CFG);
		if (cfg.protocol) {	// not available for uid 0
			seccomp_load(RUN_SECCOMP_PROTOCOL);	// install filter	
		}
				
		// set seccomp filter
		if (apply_seccomp == 1)	// not available for uid 0
			seccomp_load(RUN_SECCOMP_CFG);
#endif

		// mount user namespace or drop privileges
		if (arg_noroot) {	// not available for uid 0
			if (arg_debug)
				printf("Joining user namespace\n");
			if (join_namespace(1, "user"))
				exit(1);

			// user namespace resets capabilities
			// set caps filter
			if (apply_caps == 1)	// not available for uid 0
				caps_set(caps);
		}
		else 
			drop_privs(arg_nogroups);	// nogroups not available for uid 0


		// set nice
		if (arg_nice) {
			errno = 0;
			int rv = nice(cfg.nice);
			(void) rv;
			if (errno) {
				fwarning("cannot set nice value\n");
				errno = 0;
			}
		}

		env_defaults();
		if (cfg.command_line == NULL) {
			assert(cfg.shell);
			cfg.command_line = cfg.shell;
			cfg.window_title = cfg.shell;
		}

		int cwd = 0;
		if (cfg.cwd) {
			if (chdir(cfg.cwd) == 0)
				cwd = 1;
		}

		if (!cwd) {
			if (chdir("/") < 0)
				errExit("chdir");
			if (cfg.homedir) {
				struct stat s;
				if (stat(cfg.homedir, &s) == 0) {
					/* coverity[toctou] */
					if (chdir(cfg.homedir) < 0)
						errExit("chdir");
				}
			}
		}

		start_application();

		// it will never get here!!!
	}

	// wait for the child to finish
	waitpid(child, NULL, 0);
	flush_stdin();
	exit(0);
}
Exemple #15
0
int main(int argc, char **argv)
{
    char led;
    int chosenled = 1;
    char hearth[]={1,0,1,1,0,0,0,0,0,0,0,0,0};
    int udelay = 100000;
    int load = 0;
    char *prgname = argv[0];
    FILE *f;

    if (argc > 1 && isdigit(argv[1][0])) { /* the time delay */
        udelay = 1000 * atoi(argv[1]);
        if (udelay < 1000)
            fprintf(stderr, "%s: delay too short\n", prgname);
        else {
            argv++; argc--;
        }
    }

    nice(-20); /* in case is succeeds... */

    udelay *= 100; /* prepare for a later division */

    if (argc > 1 && strlen(argv[1]) == 1) {
        argv++, argc--;
        if (tolower(argv[0][0]) == 's') chosenled = 1; /* scroll lock */
        else 
            if (tolower(argv[0][0]) == 'n') chosenled = 2; /* num lock */
        else
            if (tolower(argv[0][0]) == 'c') chosenled = 4; /* caps lock */
        else {
            fprintf(stderr, "%s: unknown led '%s'\n", prgname, argv[1]);
            argc++;
        }
    }
    if (argc>1) {
        fprintf(stderr, "%s: usage \"%s [delay ms] [ n | c | s ]\"\n",
                prgname, prgname);
        exit(1);
    }

   
    
    /* ok, now do your loop */

    for (;;) {
        int consolefd=open("/dev/tty0",O_RDONLY);

        int i;
        f=fopen("/proc/loadavg", "r");
        if (f) {
            fscanf(f, "%d.%d", &load, &i);
            fclose(f);
        } else {
            load = i = 0;
        }
        load = 100 + load * 100 + i;

        for (i=0; i < sizeof(hearth)/sizeof(hearth[0]); i++) {
            if (ioctl(consolefd, KDGETLED, &led)
                || ioctl(consolefd, KDSETLED,
                         (led & ~chosenled) | chosenled * hearth[i])) {
                fprintf(stderr, "%s: ioctl(): %s\n", prgname, strerror(errno));
                exit(2);
            }
            usleep(udelay/load);
        }
        close(consolefd);
    }
    exit(0); /* never happen */
}
Exemple #16
0
int wm_exec(char *command, char **output, int *exitcode, int secs)
{
    static char* const envp[] = { NULL };
    char **argv = wm_strtok(command);
    pid_t pid;
    int pipe_fd[2];
    ThreadInfo tinfo = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, NULL };
    pthread_t thread;
    struct timespec timeout = { 0, 0 };
    struct sigaction action = { .sa_handler = NULL };
    int retval = -1;
    int status;

    // Create pipe for child's stdout

    if (pipe(pipe_fd) < 0)
        return -1;

    // Fork

    switch (pid = fork()) {
    case -1:

        // Error

        merror("%s: ERROR: fork()", ARGV0);
        return -1;

    case 0:

        // Child

        close(pipe_fd[0]);
        dup2(pipe_fd[1], STDOUT_FILENO);
        dup2(pipe_fd[1], STDERR_FILENO);

        setsid();
        if (nice(wm_task_nice)) {}

        if (execve(argv[0], argv, envp) < 0)
            exit(EXECVE_ERROR);

        // Child won't return

    default:

        // Parent

        close(pipe_fd[1]);
        tinfo.pipe = pipe_fd[0];

        // Launch thread

        pthread_mutex_lock(&tinfo.mutex);

        if (pthread_create(&thread, NULL, reader, &tinfo)) {
            merror("%s: ERROR: Couldn't create reading thread.", ARGV0);
            pthread_mutex_unlock(&tinfo.mutex);
            return -1;
        }

        get_time(&timeout);
        timeout.tv_sec += secs;

        // Wait for reading termination

        switch (pthread_cond_timedwait(&tinfo.finished, &tinfo.mutex, &timeout)) {
        case 0:
            retval = 0;
            break;

        case ETIMEDOUT:
            retval = WM_ERROR_TIMEOUT;

        default:
            action.sa_handler = handler;
            sigaction(SIGCHLD, &action, NULL);
            kill(-pid, SIGTERM);
            sleep(WM_MAX_WAIT);
            action.sa_handler = SIG_DFL;
            sigaction(SIGCHLD, &action, NULL);
            pthread_cancel(thread);
        }

        // Wait for thread

        pthread_mutex_unlock(&tinfo.mutex);
        pthread_join(thread, NULL);

        // Wait for child process

        switch (waitpid(pid, &status, retval ? 0 : WNOHANG)) {
        case -1:
            merror("%s: ERROR: waitpid()", ARGV0);
            retval = -1;
            break;

        case 0:
            kill(-pid, SIGKILL);
            waitpid(pid, &status, 0);
            merror("%s: WARN: Subprocess was killed.", ARGV0);
            break;

        default:
            if (WEXITSTATUS(status) == EXECVE_ERROR)
                retval = -1;
            else if (exitcode)
                *exitcode = WEXITSTATUS(status);
        }

        // Setup output

        if (retval >= 0)
            *output = tinfo.output ? tinfo.output : strdup("");
        else
            free(tinfo.output);

        // Cleanup

        pthread_mutex_destroy(&tinfo.mutex);
        pthread_cond_destroy(&tinfo.finished);
        free(argv);

        return retval;
    }
}
int main(int argc, char **argv) {
	int result = 0;
	int i;

  userui_ops[0] = &userui_text_ops;
	userui_ops[1] = FBSPLASH_OPS;
	userui_ops[2] = USPLASH_OPS;
	active_ops = &userui_text_ops;

	handle_params(argc, argv);
	setup_signal_handlers();
	open_console();
	open_misc();
	if (!test_run) {
		open_netlink();
		get_nofreeze();
		get_info();
	}

	lock_memory();

	prepare_console();

	/* Initialise all that we can, use the first */
//  active_ops = NULL;
	for (i = 0; i < NUM_UIS; i++) {
		if (userui_ops[i] && userui_ops[i]->load) {
			result = userui_ops[i]->load();
			if (result) {
				if (test_run)
					fprintf(stderr, "Failed to initialise %s module.\n", userui_ops[i]->name);
				else
					printk("Failed to initialise %s module.\n", userui_ops[i]->name);
			} else
				if (!active_ops)
					active_ops = userui_ops[i];
		}
	}

	if (active_ops->prepare)
		active_ops->prepare();

	register_keypress_handler();

	need_cleanup = 1;
	running = 1;

	result = nice(1);

	if (active_ops->memory_required)
		reserve_memory(active_ops->memory_required());
	else
		reserve_memory(4*1024*1024); /* say 4MB */

	enforce_lifesavers();

	if (test_run) {
		safe_to_exit = 0;

		do_test_run();
		return 0;
	}

	if (send_ready())
		message_loop();

	/* The only point we ever reach here is if message_loop crashed out.
	 * If this is the case, we should spin for a few hours before exiting to
	 * ensure that we don't corrupt stuff on disk (if we're past the atomic
	 * copy).
	 */
	sleep(60*60*1); /* 1 hours */
	_exit(1);
}
Exemple #18
0
int
main(int argc, char *argv[])
{
#define	 check(ol,al)		if (argv[i][ol] || \
				badarg(argc-i-1,argv+i+1,al)) \
				goto badopt
#define	 bool(olen,var)		switch (argv[i][olen]) { \
				case '\0': var = !var; break; \
				case 'y': case 'Y': case 't': case 'T': \
				case '+': case '1': var = 1; break; \
				case 'n': case 'N': case 'f': case 'F': \
				case '-': case '0': var = 0; break; \
				default: goto badopt; }
	char	*curout = NULL;
	char	*prms = NULL;
	char	*binval = NULL;
	int	bincnt = 0;
	int	rval;
	int	i;
					/* global program name */
	progname = argv[0] = fixargv0(argv[0]);
	gargv = argv;
	gargc = argc;
					/* initialize calcomp routines early */
	initfunc();
	setcontext(RCCONTEXT);
					/* option city */
	for (i = 1; i < argc; i++) {
						/* expand arguments */
		while ((rval = expandarg(&argc, &argv, i)) > 0)
			;
		if (rval < 0) {
			sprintf(errmsg, "cannot expand '%s'", argv[i]);
			error(SYSTEM, errmsg);
		}
		if (argv[i] == NULL || argv[i][0] != '-')
			break;			/* break from options */
		if (!strcmp(argv[i], "-version")) {
			puts(VersionID);
			quit(0);
		}
		if (!strcmp(argv[i], "-defaults") ||
				!strcmp(argv[i], "-help")) {
			override_options();
			printdefaults();
			quit(0);
		}
		rval = getrenderopt(argc-i, argv+i);
		if (rval >= 0) {
			i += rval;
			continue;
		}
		switch (argv[i][1]) {
		case 'n':			/* number of cores */
			check(2,"i");
			nproc = atoi(argv[++i]);
			if (nproc <= 0)
				error(USER, "bad number of processes");
			break;
		case 'V':			/* output contributions */
			bool(2,contrib);
			break;
		case 'x':			/* x resolution */
			check(2,"i");
			xres = atoi(argv[++i]);
			break;
		case 'y':			/* y resolution */
			check(2,"i");
			yres = atoi(argv[++i]);
			break;
		case 'w':			/* warnings */
			rval = (erract[WARNING].pf != NULL);
			bool(2,rval);
			if (rval) erract[WARNING].pf = wputs;
			else erract[WARNING].pf = NULL;
			break;
		case 'e':			/* expression */
			check(2,"s");
			scompile(argv[++i], NULL, 0);
			break;
		case 'l':			/* limit distance */
			if (argv[i][2] != 'd')
				goto badopt;
			bool(3,lim_dist);
			break;
		case 'I':			/* immed. irradiance */
			bool(2,imm_irrad);
			break;
		case 'f':			/* file or force or format */
			if (!argv[i][2]) {
				check(2,"s");
				loadfunc(argv[++i]);
				break;
			}
			if (argv[i][2] == 'o') {
				bool(3,force_open);
				break;
			}
			setformat(argv[i]+2);
			break;
		case 'o':			/* output */
			check(2,"s");
			curout = argv[++i];
			break;
		case 'c':			/* input rays per output */
			check(2,"i");
			accumulate = atoi(argv[++i]);
			break;
		case 'r':			/* recover output */
			bool(2,recover);
			break;
		case 'h':			/* header output */
			bool(2,header);
			break;
		case 'p':			/* parameter setting(s) */
			check(2,"s");
			set_eparams(prms = argv[++i]);
			break;
		case 'b':			/* bin expression/count */
			if (argv[i][2] == 'n') {
				check(3,"s");
				bincnt = (int)(eval(argv[++i]) + .5);
				break;
			}
			check(2,"s");
			binval = argv[++i];
			break;
		case 'm':			/* modifier name */
			check(2,"s");
			addmodifier(argv[++i], curout, prms, binval, bincnt);
			break;
		case 'M':			/* modifier file */
			check(2,"s");
			addmodfile(argv[++i], curout, prms, binval, bincnt);
			break;
		default:
			goto badopt;
		}
	}
	if (nmods <= 0)
		error(USER, "missing required modifier argument");
					/* override some option settings */
	override_options();
					/* initialize object types */
	initotypes();
					/* initialize urand */
	if (rand_samp) {
		srandom((long)time(0));
		initurand(0);
	} else {
		srandom(0L);
		initurand(2048);
	}
					/* set up signal handling */
	sigdie(SIGINT, "Interrupt");
#ifdef SIGHUP
	sigdie(SIGHUP, "Hangup");
#endif
	sigdie(SIGTERM, "Terminate");
#ifdef SIGPIPE
	sigdie(SIGPIPE, "Broken pipe");
#endif
#ifdef SIGALRM
	sigdie(SIGALRM, "Alarm clock");
#endif
#ifdef	SIGXCPU
	sigdie(SIGXCPU, "CPU limit exceeded");
	sigdie(SIGXFSZ, "File size exceeded");
#endif
#ifdef	NICE
	nice(NICE);			/* lower priority */
#endif
					/* get octree */
	if (i == argc)
		octname = NULL;
	else if (i == argc-1)
		octname = argv[i];
	else
		goto badopt;
	if (octname == NULL)
		error(USER, "missing octree argument");

	readoct(octname, ~(IO_FILES|IO_INFO), &thescene, NULL);
	nsceneobjs = nobjects;

	marksources();			/* find and mark sources */

	setambient();			/* initialize ambient calculation */

	rcontrib();			/* trace ray contributions (loop) */

	ambsync();			/* flush ambient file */

	quit(0);	/* exit clean */

badopt:
	fprintf(stderr,
"Usage: %s [-n nprocs][-V][-r][-e expr][-f source][-o ospec][-p p1=V1,p2=V2][-b binv][-bn N] {-m mod | -M file} [rtrace options] octree\n",
			progname);
	sprintf(errmsg, "command line error at '%s'", argv[i]);
	error(USER, errmsg);
	return(1);	/* pro forma return */

#undef	check
#undef	bool
}
Exemple #19
0
int sandbox(void* sandbox_arg) {
	// Get rid of unused parameter warning
	(void)sandbox_arg;

	pid_t child_pid = getpid();
	if (arg_debug)
		printf("Initializing child process\n");	

 	// close each end of the unused pipes
 	close(parent_to_child_fds[1]);
 	close(child_to_parent_fds[0]);
 
 	// wait for parent to do base setup
 	wait_for_other(parent_to_child_fds[0]);

	if (arg_debug && child_pid == 1)
		printf("PID namespace installed\n");


	//****************************
	// set hostname
	//****************************
	if (cfg.hostname) {
		if (sethostname(cfg.hostname, strlen(cfg.hostname)) < 0)
			errExit("sethostname");
	}

	//****************************
	// mount namespace
	//****************************
	// mount events are not forwarded between the host the sandbox
	if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
		chk_chroot();
	}
	
	
	//****************************
	// log sandbox data
	//****************************
	if (cfg.name)
		fs_logger2("sandbox name:", cfg.name);
	fs_logger2int("sandbox pid:", (int) sandbox_pid);
	if (cfg.chrootdir)
		fs_logger("sandbox filesystem: chroot");
	else if (arg_overlay)	
		fs_logger("sandbox filesystem: overlay");
	else
		fs_logger("sandbox filesystem: local");
	fs_logger("install mount namespace");
	
	//****************************
	// netfilter etc.
	//****************************
	if (arg_netfilter && any_bridge_configured()) { // assuming by default the client filter
		netfilter(arg_netfilter_file);
	}
	if (arg_netfilter6 && any_bridge_configured()) { // assuming by default the client filter
		netfilter6(arg_netfilter6_file);
	}

	// load IBUS env variables
	if (arg_nonetwork || any_bridge_configured() || any_interface_configured()) {
		// do nothing - there are problems with ibus version 1.5.11
	}
	else
		env_ibus_load();
	
	// grab a copy of cp command
	fs_build_cp_command();
	
	// trace pre-install
	if (arg_trace || arg_tracelog)
		fs_trace_preload();

	//****************************
	// configure filesystem
	//****************************
#ifdef HAVE_SECCOMP
	int enforce_seccomp = 0;
#endif
#ifdef HAVE_CHROOT		
	if (cfg.chrootdir) {
		fs_chroot(cfg.chrootdir);

//		// redo cp command
//		fs_build_cp_command();
		
		// force caps and seccomp if not started as root
		if (getuid() != 0) {
			// force default seccomp inside the chroot, no keep or drop list
			// the list build on top of the default drop list is kept intact
			arg_seccomp = 1;
#ifdef HAVE_SECCOMP
			enforce_seccomp = 1;
#endif
			if (cfg.seccomp_list_drop) {
				free(cfg.seccomp_list_drop);
				cfg.seccomp_list_drop = NULL;
			}
			if (cfg.seccomp_list_keep) {
				free(cfg.seccomp_list_keep);
				cfg.seccomp_list_keep = NULL;
			}
			
			// disable all capabilities
			if (arg_caps_default_filter || arg_caps_list)
				fprintf(stderr, "Warning: all capabilities disabled for a regular user in chroot\n");
			arg_caps_drop_all = 1;
			
			// drop all supplementary groups; /etc/group file inside chroot
			// is controlled by a regular usr
			arg_nogroups = 1;
			if (!arg_quiet)
				printf("Dropping all Linux capabilities and enforcing default seccomp filter\n");
		}
		else
			arg_seccomp = 1;
						
		//****************************
		// trace pre-install, this time inside chroot
		//****************************
		if (arg_trace || arg_tracelog)
			fs_trace_preload();
	}
	else 
#endif		
	if (arg_overlay)	
		fs_overlayfs();
	else
		fs_basic_fs();
	
	//****************************
	// set hostname in /etc/hostname
	//****************************
	if (cfg.hostname) {
		fs_hostname(cfg.hostname);
	}
	
	//****************************
	// private mode
	//****************************
	if (arg_private) {
		if (cfg.home_private)	// --private=
			fs_private_homedir();
		else // --private
			fs_private();
	}
	
   if (arg_private_template) 
      fs_private_template();

	if (arg_private_dev)
		fs_private_dev();
	if (arg_private_etc) {
		if (cfg.chrootdir)
			fprintf(stderr, "Warning: private-etc feature is disabled in chroot\n");
		else {
			fs_private_etc_list();
			// create /etc/ld.so.preload file again
			if (arg_trace || arg_tracelog)
				fs_trace_preload();
		}
	}
	if (arg_private_bin) {
		if (cfg.chrootdir)
			fprintf(stderr, "Warning: private-bin feature is disabled in chroot\n");
		else
			fs_private_bin_list();
	}
	if (arg_private_tmp)
		fs_private_tmp();
	
	//****************************
	// update /proc, /sys, /dev, /boot directorymy
	//****************************
	fs_proc_sys_dev_boot();
	
	//****************************
	// apply the profile file
	//****************************
	if (cfg.profile) {
		// apply all whitelist commands ... 
		fs_whitelist();
		
		// ... followed by blacklist commands
		fs_blacklist();
	}
	
	//****************************
	// install trace
	//****************************
	if (arg_trace || arg_tracelog)
		fs_trace();
		
	//****************************
	// --nosound and fix for pulseaudio 7.0
	//****************************
	if (arg_nosound) {
		// disable pulseaudio
		pulseaudio_disable();

		// disable /dev/snd
		fs_dev_disable_sound();
	}
	else
		pulseaudio_init();
	
	//****************************
	// networking
	//****************************
	int gw_cfg_failed = 0; // default gw configuration flag
	if (arg_nonetwork) {
		net_if_up("lo");
		if (arg_debug)
			printf("Network namespace enabled, only loopback interface available\n");
	}
	else if (any_bridge_configured() || any_interface_configured()) {
		// configure lo and eth0...eth3
		net_if_up("lo");
		
		if (mac_not_zero(cfg.bridge0.macsandbox))
			net_config_mac(cfg.bridge0.devsandbox, cfg.bridge0.macsandbox);
		sandbox_if_up(&cfg.bridge0);
		
		if (mac_not_zero(cfg.bridge1.macsandbox))
			net_config_mac(cfg.bridge1.devsandbox, cfg.bridge1.macsandbox);
		sandbox_if_up(&cfg.bridge1);
		
		if (mac_not_zero(cfg.bridge2.macsandbox))
			net_config_mac(cfg.bridge2.devsandbox, cfg.bridge2.macsandbox);
		sandbox_if_up(&cfg.bridge2);
		
		if (mac_not_zero(cfg.bridge3.macsandbox))
			net_config_mac(cfg.bridge3.devsandbox, cfg.bridge3.macsandbox);
		sandbox_if_up(&cfg.bridge3);
		
		// enable interfaces
		if (cfg.interface0.configured && cfg.interface0.ip) {
			if (arg_debug)
				printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface0.ip), cfg.interface0.dev);
			net_if_ip(cfg.interface0.dev, cfg.interface0.ip, cfg.interface0.mask, cfg.interface0.mtu);
			net_if_up(cfg.interface0.dev);
		}			
		if (cfg.interface1.configured && cfg.interface1.ip) {
			if (arg_debug)
				printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface1.ip), cfg.interface1.dev);
			net_if_ip(cfg.interface1.dev, cfg.interface1.ip, cfg.interface1.mask, cfg.interface1.mtu);
			net_if_up(cfg.interface1.dev);
		}			
		if (cfg.interface2.configured && cfg.interface2.ip) {
			if (arg_debug)
				printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface2.ip), cfg.interface2.dev);
			net_if_ip(cfg.interface2.dev, cfg.interface2.ip, cfg.interface2.mask, cfg.interface2.mtu);
			net_if_up(cfg.interface2.dev);
		}			
		if (cfg.interface3.configured && cfg.interface3.ip) {
			if (arg_debug)
				printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface3.ip), cfg.interface3.dev);
			net_if_ip(cfg.interface3.dev, cfg.interface3.ip, cfg.interface3.mask, cfg.interface3.mtu);
			net_if_up(cfg.interface3.dev);
		}			
			
		// add a default route
		if (cfg.defaultgw) {
			// set the default route
			if (net_add_route(0, 0, cfg.defaultgw)) {
				fprintf(stderr, "Warning: cannot configure default route\n");
				gw_cfg_failed = 1;
			}
		}

		if (arg_debug)
			printf("Network namespace enabled\n");
	}
	
	// if any dns server is configured, it is time to set it now
	fs_resolvconf();
	fs_logger_print();
	fs_logger_change_owner();

	// print network configuration
	if (!arg_quiet) {
		if (any_bridge_configured() || any_interface_configured() || cfg.defaultgw || cfg.dns1) {
			printf("\n");
			if (any_bridge_configured() || any_interface_configured())
				net_ifprint();
			if (cfg.defaultgw != 0) {
				if (gw_cfg_failed)
					printf("Default gateway configuration failed\n");
				else
					printf("Default gateway %d.%d.%d.%d\n", PRINT_IP(cfg.defaultgw));
			}
			if (cfg.dns1 != 0)
				printf("DNS server %d.%d.%d.%d\n", PRINT_IP(cfg.dns1));
			if (cfg.dns2 != 0)
				printf("DNS server %d.%d.%d.%d\n", PRINT_IP(cfg.dns2));
			if (cfg.dns3 != 0)
				printf("DNS server %d.%d.%d.%d\n", PRINT_IP(cfg.dns3));
			printf("\n");
		}
	}
	
	fs_delete_cp_command();

	//****************************
	// set application environment
	//****************************
	prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); // kill the child in case the parent died
	int cwd = 0;
	if (cfg.cwd) {
		if (chdir(cfg.cwd) == 0)
			cwd = 1;
	}
	
	if (!cwd) {
		if (chdir("/") < 0)
			errExit("chdir");
		if (cfg.homedir) {
			struct stat s;
			if (stat(cfg.homedir, &s) == 0) {
				/* coverity[toctou] */
				if (chdir(cfg.homedir) < 0)
					errExit("chdir");
			}
		}
	}
	
	// set environment
	env_defaults();
	
	// set user-supplied environment variables
	env_apply();

	// set nice
	if (arg_nice) {
		errno = 0;
		int rv = nice(cfg.nice);
		(void) rv;
		if (errno) {
			fprintf(stderr, "Warning: cannot set nice value\n");
			errno = 0;
		}
	}
	
	// clean /tmp/.X11-unix sockets
	fs_x11();
	
	//****************************
	// set security filters
	//****************************
	// set capabilities
//	if (!arg_noroot)
		set_caps();

	// set rlimits
	set_rlimits();

	// set seccomp
#ifdef HAVE_SECCOMP
	// install protocol filter
	if (cfg.protocol) {
		protocol_filter();	// install filter	
		protocol_filter_save();	// save filter in PROTOCOL_CFG
	}

	// if a keep list is available, disregard the drop list
	if (arg_seccomp == 1) {
		if (cfg.seccomp_list_keep)
			seccomp_filter_keep();
		else if (cfg.seccomp_list_errno)
			seccomp_filter_errno(); 
		else
			seccomp_filter_drop(enforce_seccomp);
	}
#endif

	// set cpu affinity
	if (cfg.cpus) {
		save_cpu(); // save cpu affinity mask to CPU_CFG file
		set_cpu_affinity();
	}
	
	// save cgroup in CGROUP_CFG file
	if (cfg.cgroup)
		save_cgroup();

	//****************************************
	// drop privileges or create a new user namespace
	//****************************************
	save_nogroups();
	if (arg_noroot) {
		int rv = unshare(CLONE_NEWUSER);
		if (rv == -1) {
			fprintf(stderr, "Warning: cannot create a new user namespace, going forward without it...\n");
			drop_privs(arg_nogroups);
			arg_noroot = 0;
		}
	}
	else
		drop_privs(arg_nogroups);
	
	// notify parent that new user namespace has been created so a proper
 	// UID/GID map can be setup
 	notify_other(child_to_parent_fds[1]);
 	close(child_to_parent_fds[1]);
 
 	// wait for parent to finish setting up a proper UID/GID map
 	wait_for_other(parent_to_child_fds[0]);
 	close(parent_to_child_fds[0]);

	// somehow, the new user namespace resets capabilities;
	// we need to do them again
	if (arg_noroot) {
		if (arg_debug)
			printf("noroot user namespace installed\n");
		set_caps();
	}
	
	//****************************************
	// Set NO_NEW_PRIVS if desired
	//****************************************
	if (arg_nonewprivs) {
		int no_new_privs = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);

		if(no_new_privs != 0)
			fprintf(stderr, "Warning: NO_NEW_PRIVS disabled, it requires a Linux kernel version 3.5 or newer.\n");
		else if (arg_debug)
			printf("NO_NEW_PRIVS set\n");
	}

	//****************************************
	// fork the application and monitor it
	//****************************************
	pid_t app_pid = fork();
	if (app_pid == -1)
		errExit("fork");

	if (app_pid == 0) {
#ifdef HAVE_APPARMOR
		if (arg_apparmor) {
			errno = 0;
			if (aa_change_onexec("firejail-default")) {
				fprintf(stderr, "Error: cannot confine the application using AppArmor.\n");
				fprintf(stderr, "Maybe firejail-default AppArmor profile is not loaded into the kernel.\n");
				fprintf(stderr, "As root, run \"aa-enforce firejail-default\" to load it.\n");
				exit(1);
			}
			else if (arg_debug)
				printf("AppArmor enabled\n");
		}
#endif		
		prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); // kill the child in case the parent died
		start_application();	// start app
	}

	int status = monitor_application(app_pid);	// monitor application

	if (WIFEXITED(status)) {
		// if we had a proper exit, return that exit status
		return WEXITSTATUS(status);
	} else {
		// something else went wrong!
		return -1;
	}
}
Exemple #20
0
/*
 * Set the process priority
 */
static void
set_process_priority(void)
{

#ifdef DEBUG
	if (debug > 1)
		msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
			((priority_done)
			 ? "Leave priority alone"
			 : "Attempt to set priority"
				),
			priority_done);
#endif /* DEBUG */

#ifdef SYS_WINNT
	priority_done += NT_set_process_priority();
#endif

#if defined(HAVE_SCHED_SETSCHEDULER)
	if (!priority_done) {
		extern int config_priority_override, config_priority;
		int pmax, pmin;
		struct sched_param sched;

		pmax = sched_get_priority_max(SCHED_FIFO);
		sched.sched_priority = pmax;
		if ( config_priority_override ) {
			pmin = sched_get_priority_min(SCHED_FIFO);
			if ( config_priority > pmax )
				sched.sched_priority = pmax;
			else if ( config_priority < pmin )
				sched.sched_priority = pmin;
			else
				sched.sched_priority = config_priority;
		}
		if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
			msyslog(LOG_ERR, "sched_setscheduler(): %m");
		else
			++priority_done;
	}
#endif /* HAVE_SCHED_SETSCHEDULER */
#if defined(HAVE_RTPRIO)
# ifdef RTP_SET
	if (!priority_done) {
		struct rtprio srtp;

		srtp.type = RTP_PRIO_REALTIME;	/* was: RTP_PRIO_NORMAL */
		srtp.prio = 0;		/* 0 (hi) -> RTP_PRIO_MAX (31,lo) */

		if (rtprio(RTP_SET, getpid(), &srtp) < 0)
			msyslog(LOG_ERR, "rtprio() error: %m");
		else
			++priority_done;
	}
# else /* not RTP_SET */
	if (!priority_done) {
		if (rtprio(0, 120) < 0)
			msyslog(LOG_ERR, "rtprio() error: %m");
		else
			++priority_done;
	}
# endif /* not RTP_SET */
#endif  /* HAVE_RTPRIO */
#if defined(NTPD_PRIO) && NTPD_PRIO != 0
# ifdef HAVE_ATT_NICE
	if (!priority_done) {
		errno = 0;
		if (-1 == nice (NTPD_PRIO) && errno != 0)
			msyslog(LOG_ERR, "nice() error: %m");
		else
			++priority_done;
	}
# endif /* HAVE_ATT_NICE */
# ifdef HAVE_BSD_NICE
	if (!priority_done) {
		if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
			msyslog(LOG_ERR, "setpriority() error: %m");
		else
			++priority_done;
	}
# endif /* HAVE_BSD_NICE */
#endif /* NTPD_PRIO && NTPD_PRIO != 0 */
	if (!priority_done)
		msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
}
Exemple #21
0
int main(int argc, const char * const argv[]) {
  int rc;
  int stat = 0;
  const char *ip = NULL;
  char *msg = NULL;
  qos_geo_t *geo;
  int size;
  const char *db = NULL;
  apr_table_t *entries;
  apr_pool_t *pool;
  const char *cmd = strrchr(argv[0], '/');
  apr_app_initialize(&argc, &argv, NULL);
  apr_pool_create(&pool, NULL);
  entries = apr_table_make(pool, 100);

  if(cmd == NULL) {
    cmd = (char *)argv[0];
  } else {
    cmd++;
  }

  argc--;
  argv++;
  while(argc >= 1) {
    if(strcmp(*argv, "-d") == 0) {
      if (--argc >= 1) {
	db = *(++argv);
      }
    } else if(strcmp(*argv, "-ip") == 0) {
      if (--argc >= 1) {
	ip = *(++argv);
      }
    } else if(strcmp(*argv, "-s") == 0) {
      stat = 1;
    } else if(strcmp(*argv, "-l") == 0) {
      m_inject = 1;
    } else if(strcmp(*argv,"-h") == 0) {
      usage(cmd, 0);
    } else if(strcmp(*argv,"--help") == 0) {
      usage(cmd, 0);
    } else if(strcmp(*argv,"-?") == 0) {
      usage(cmd, 0);
    } else if(strcmp(*argv,"--man") == 0) {
      usage(cmd, 1);
    } else {
      usage(cmd, 0);
    }
    argc--;
    argv++;
  }

  if(db == NULL) {
    usage(cmd, 0);
  }

  rc = nice(10);
  if(rc == -1) {
    fprintf(stderr, "ERROR, failed to change nice value: %s\n", strerror(errno));
  }

  geo = qos_loadgeo(pool, db, &size, &msg);
  if(geo == NULL || msg != NULL) {
    fprintf(stderr, "failed to load database: %s\n", msg ? msg : "-");
    exit(1);
  }
  if(m_inject) {
    exit(0);
  }
  
  if(ip) {
    qos_geo_t *pB;
    unsigned long search = qos_geo_str2long(pool, ip);
    printf("search %lu: ", search);
    pB = bsearch(&search,
		 geo,
		 size,
		 sizeof(qos_geo_t),
		 qos_geo_comp);
    if(pB) {
      printf("%s\n", pB->country);
    } else {
      printf("n/a\n");
    }
    return 0;
  }

  // start reading from stdin
  {
    char prev;
    qos_geo_t *pB;
    apr_pool_t *tmp;
    char line[HUGE_STRING_LEN];
    regex_t preg;
    regex_t preg2;
    regmatch_t ma[MAX_REG_MATCH];
    apr_pool_create(&tmp, NULL);
    if(regcomp(&preg, IPPATTERN, REG_EXTENDED)) {
      exit(1);
    }
    regcomp(&preg2, IPPATTERN2, REG_EXTENDED);
    while(fgets(line, sizeof(line), stdin) != NULL) {
      int match = regexec(&preg, line, MAX_REG_MATCH, ma, 0);
      if(match != 0) {
        char *dx = strchr(line, ';');
        if(dx && ((dx - line) <= 15)) {
          // file starts probably with <ip>; => a qslog -pc file?
          match = regexec(&preg2, line, MAX_REG_MATCH, ma, 0);
        }
      }
      if(match == 0) {
        unsigned long search;
        prev = line[ma[1].rm_eo];
        line[ma[1].rm_eo] = '\0';
        search = qos_geo_str2long(tmp, &line[ma[1].rm_so]);
        apr_pool_clear(tmp);
        pB = bsearch(&search,
                     geo,
                     size,
                     sizeof(qos_geo_t),
                     qos_geo_comp);
        if(stat) {
          /* creates a single statistic entry for each country (used to collect
             requests per source country) */
          if(pB) {
            qos_geo_stat_t *s = (qos_geo_stat_t *)apr_table_get(entries, pB->country);
            if(s == NULL) {
              s = apr_pcalloc(pool, sizeof(qos_geo_stat_t));
              s->num = 0;
              s->c = pB->c;
              apr_table_addn(entries, apr_pstrdup(pool, pB->country), (char *)s);
            }
            s->num++;
          }
        } else {
          /* modifies each log line inserting the country code
           */
          char cr = prev;
          char delw[2];
          char delx[2];
          delw[1] = '\0';
          delw[0] = ' ';
          delx[1] = '\0';
          delx[0] = ' ';
          if(line[ma[1].rm_eo+1] == ' ') {
            delx[0] = '\0';
          }
          if(line[ma[1].rm_eo+1] == ';') {
            delx[0] = ';';
          }
          if(prev <= CR) {
            prev = ' ';
          }
          if(prev == ' ') {
            delw[0] = '\0';
          }
          if(prev == ';') {
            delw[0] = '\0';
            delx[0] = ';';
          }
          if(pB) {
            printf("%s%c%s%s%s%s", line, prev,
                   delw,
                   pB->country,
                   delx,
                   &line[ma[1].rm_eo+1]);
          } else {
            printf("%s%c%s--%s%s", line, prev,
                   delw,
                   delx,
                   &line[ma[1].rm_eo+1]);
          }
          if(cr <= CR) {
            printf("\n");
          }
        }
      } else {
        printf("%s", line);
      }
      fflush(stdout);
    }
    if(stat) {
      int i;
      apr_table_entry_t *entry = (apr_table_entry_t *)apr_table_elts(entries)->elts;
      for(i = 0; i < apr_table_elts(entries)->nelts; i++) {
	qos_geo_stat_t *s = (qos_geo_stat_t *)entry[i].val;
	printf("%7.d %s %s\n", s->num, entry[i].key, s->c ? s->c : "");
      }
    }
  }
  return 0;
}
//---------------------------------------------------------------------------
//
// Function:            main
//
// Description:         main function of demo application
//
// Parameters:
//
// Returns:
//---------------------------------------------------------------------------
int  main (int argc, char **argv)
{
    tEplKernel                  EplRet = kEplSuccessful;
    static tEplApiInitParam     EplApiInitParam;
    char*                       sHostname = HOSTNAME;
    char                        cKey = 0;

#ifdef CONFIG_POWERLINK_USERSTACK
    // variables for Pcap
    char                        sErr_Msg[ PCAP_ERRBUF_SIZE ];
    char                        devName[128];
    pcap_if_t *                 alldevs;
    pcap_if_t *                 seldev;
    int                         i = 0;
    int                         inum;
#endif

    int                         opt;

#if (TARGET_SYSTEM == _LINUX_)
    /* get command line parameters */
    while ((opt = getopt(argc, argv, "c:l:")) != -1)
    {
        switch (opt)
        {
        case 'c':
            uiCycleLen_g = strtoul(optarg, NULL, 10);
            break;

        case 'l':
            pLogFile_g = optarg;
            break;

        default: /* '?' */
            fprintf (stderr, "Usage: %s [-c CYCLE_TIME] [-l LOGFILE]\n", argv[0]);
            goto Exit;
        }
    }
#endif

#ifdef CONFIG_POWERLINK_USERSTACK

#if (TARGET_SYSTEM == _LINUX_)
    struct sched_param          schedParam;

    /* adjust process priority */
    if (nice (-20) == -1)         // push nice level in case we have no RTPreempt
    {
        EPL_DBGLVL_ERROR_TRACE("%s() couldn't set nice value! (%s)\n", __func__, strerror(errno));
    }
    schedParam.__sched_priority = MAIN_THREAD_PRIORITY;
    if (pthread_setschedparam(pthread_self(), SCHED_RR, &schedParam) != 0)
    {
        EPL_DBGLVL_ERROR_TRACE("%s() couldn't set thread scheduling parameters! %d\n",
                __func__, schedParam.__sched_priority);
    }

    /* Initialize target specific stuff */
    EplTgtInit();

#elif (TARGET_SYSTEM == _WIN32_)

    // activate realtime priority class
    SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
    // lower the priority of this thread
    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE);

#endif // (TARGET_SYSTEM == _WIN32_)

#endif // CONFIG_POWERLINK_USERSTACK

#if (TARGET_SYSTEM == _LINUX_)
#ifdef SET_CPU_AFFINITY
    {
        /* binds all openPOWERLINK threads to the second CPU core */
        cpu_set_t                   affinity;

        CPU_ZERO(&affinity);
        CPU_SET(1, &affinity);
        sched_setaffinity(0, sizeof(cpu_set_t), &affinity);
    }
#endif
#endif


    /* Enabling ftrace for debugging */
    FTRACE_OPEN();
    FTRACE_ENABLE(TRUE);

    /*
    EPL_DBGLVL_ALWAYS_TRACE("%s(): Main Thread Id:%ld\n", __func__,
                             syscall(SYS_gettid));
                             */
    printf("----------------------------------------------------\n");
    printf("openPOWERLINK console MN DEMO application\n");
    printf("----------------------------------------------------\n");

    EPL_MEMSET(&EplApiInitParam, 0, sizeof (EplApiInitParam));
    EplApiInitParam.m_uiSizeOfStruct = sizeof (EplApiInitParam);

#ifdef CONFIG_POWERLINK_USERSTACK

    /* Retrieve the device list on the local machine */
    if (pcap_findalldevs(&alldevs, sErr_Msg) == -1)
    {
        fprintf(stderr, "Error in pcap_findalldevs: %s\n", sErr_Msg);
        EplRet = kEplNoResource;
        goto Exit;
    }

    PRINTF("--------------------------------------------------\n");
    PRINTF("List of Ethernet Cards Found in this System: \n");
    PRINTF("--------------------------------------------------\n");

     /* Print the list */
    for (seldev = alldevs; seldev != NULL; seldev = seldev->next)
    {
        PRINTF("%d. ", ++i);

        if (seldev->description)
        {
            PRINTF("%s\n      %s\n", seldev->description, seldev->name);
        }
        else
        {
            PRINTF("%s\n", seldev->name);
        }
    }

    if (i == 0)
    {
        PRINTF("\nNo interfaces found! Make sure pcap library is installed.\n");
        EplRet = kEplNoResource;
        goto Exit;
    }

    PRINTF("--------------------------------------------------\n");
    PRINTF("Select the interface to be used for POWERLINK (1-%d):",i);
    if (scanf("%d", &inum) == EOF)
    {
        pcap_freealldevs(alldevs);
        EplRet = kEplNoResource;
        goto Exit;
    }
    PRINTF("--------------------------------------------------\n");
    if ((inum < 1) || (inum > i))
    {
        PRINTF("\nInterface number out of range.\n");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        EplRet = kEplNoResource;
        goto Exit;
    }

    /* Jump to the selected adapter */
    for (seldev = alldevs, i = 0;
         i < (inum - 1);
         seldev = seldev->next, i++)
    {   // do nothing
    }

    strncpy(devName, seldev->name, 127);
    // pass selected device name to Edrv
    EplApiInitParam.m_HwParam.m_pszDevName = devName;

#endif

    EplApiInitParam.m_uiNodeId = uiNodeId_g = NODEID;
    EplApiInitParam.m_dwIpAddress = (0xFFFFFF00 & IP_ADDR) | EplApiInitParam.m_uiNodeId;

    /* write 00:00:00:00:00:00 to MAC address, so that the driver uses the real hardware address */
    EPL_MEMCPY(EplApiInitParam.m_abMacAddress, abMacAddr, sizeof (EplApiInitParam.m_abMacAddress));

    EplApiInitParam.m_fAsyncOnly = FALSE;

    EplApiInitParam.m_dwFeatureFlags            = -1;
    EplApiInitParam.m_dwCycleLen                = uiCycleLen_g;     // required for error detection
    EplApiInitParam.m_uiIsochrTxMaxPayload      = 256;              // const
    EplApiInitParam.m_uiIsochrRxMaxPayload      = 256;              // const
    EplApiInitParam.m_dwPresMaxLatency          = 50000;            // const; only required for IdentRes
    EplApiInitParam.m_uiPreqActPayloadLimit     = 36;               // required for initialisation (+28 bytes)
    EplApiInitParam.m_uiPresActPayloadLimit     = 36;               // required for initialisation of Pres frame (+28 bytes)
    EplApiInitParam.m_dwAsndMaxLatency          = 150000;           // const; only required for IdentRes
    EplApiInitParam.m_uiMultiplCycleCnt         = 0;                // required for error detection
    EplApiInitParam.m_uiAsyncMtu                = 1500;             // required to set up max frame size
    EplApiInitParam.m_uiPrescaler               = 2;                // required for sync
    EplApiInitParam.m_dwLossOfFrameTolerance    = 500000;
    EplApiInitParam.m_dwAsyncSlotTimeout        = 3000000;
    EplApiInitParam.m_dwWaitSocPreq             = 150000;
    EplApiInitParam.m_dwDeviceType              = -1;               // NMT_DeviceType_U32
    EplApiInitParam.m_dwVendorId                = -1;               // NMT_IdentityObject_REC.VendorId_U32
    EplApiInitParam.m_dwProductCode             = -1;               // NMT_IdentityObject_REC.ProductCode_U32
    EplApiInitParam.m_dwRevisionNumber          = -1;               // NMT_IdentityObject_REC.RevisionNo_U32
    EplApiInitParam.m_dwSerialNumber            = -1;               // NMT_IdentityObject_REC.SerialNo_U32

    EplApiInitParam.m_dwSubnetMask              = SUBNET_MASK;
    EplApiInitParam.m_dwDefaultGateway          = 0;
    EPL_MEMCPY(EplApiInitParam.m_sHostname, sHostname, sizeof(EplApiInitParam.m_sHostname));
    EplApiInitParam.m_uiSyncNodeId              = EPL_C_ADR_SYNC_ON_SOA;
    EplApiInitParam.m_fSyncOnPrcNode            = FALSE;

    // set callback functions
    EplApiInitParam.m_pfnCbEvent = AppCbEvent;

#ifdef CONFIG_POWERLINK_USERSTACK
    EplApiInitParam.m_pfnObdInitRam = EplObdInitRam;
    EplApiInitParam.m_pfnCbSync  = AppCbSync;
#else
    EplApiInitParam.m_pfnCbSync = NULL;
#endif


    printf("\n\nHello, I'm a Userspace POWERLINK node running as %s!\n  (build: %s / %s)\n\n",
            (uiNodeId_g == EPL_C_ADR_MN_DEF_NODE_ID ?
                "Managing Node" : "Controlled Node"),
            __DATE__, __TIME__);

    // initialize POWERLINK stack
    printf ("Initializing openPOWERLINK stack...\n");
    EplRet = EplApiInitialize(&EplApiInitParam);
    if(EplRet != kEplSuccessful)
    {
        printf("EplApiInitialize() failed (Error:0x%x!\n", EplRet);
        goto Exit;
    }

    // initialize application
    printf ("Initializing openPOWERLINK application...\n");
    EplRet = AppInit();
    if(EplRet != kEplSuccessful)
    {
        printf("ApiInit() failed!\n");
        goto Exit;
    }


#ifdef CONFIG_POWERLINK_USERSTACK
    /* At this point, we don't need any more the device list. Free it */
    pcap_freealldevs(alldevs);

    EplRet = EplApiSetCdcFilename(pszCdcFilename_g);
    if(EplRet != kEplSuccessful)
    {
        goto Exit;
    }
#else
    // create event thread
    if (pthread_create(&eventThreadId, NULL,
                   &powerlinkEventThread, NULL) != 0)
    {
        goto Exit;
    }

    // create sync thread
    if (pthread_create(&syncThreadId, NULL,
                   &powerlinkSyncThread, NULL) != 0)
    {
        goto Exit;
    }
#endif

    printf("Initializing process image...\n");
    printf("Size of input process image: %ld\n", sizeof(AppProcessImageIn_g));
    printf("Size of output process image: %ld\n", sizeof (AppProcessImageOut_g));
    AppProcessImageCopyJob_g.m_fNonBlocking = FALSE;
    AppProcessImageCopyJob_g.m_uiPriority = 0;
    AppProcessImageCopyJob_g.m_In.m_pPart = &AppProcessImageIn_g;
    AppProcessImageCopyJob_g.m_In.m_uiOffset = 0;
    AppProcessImageCopyJob_g.m_In.m_uiSize = sizeof (AppProcessImageIn_g);
    AppProcessImageCopyJob_g.m_Out.m_pPart = &AppProcessImageOut_g;
    AppProcessImageCopyJob_g.m_Out.m_uiOffset = 0;
    AppProcessImageCopyJob_g.m_Out.m_uiSize = sizeof (AppProcessImageOut_g);

    EplRet = EplApiProcessImageAlloc(sizeof (AppProcessImageIn_g), sizeof (AppProcessImageOut_g), 2, 2);
    if (EplRet != kEplSuccessful)
    {
        goto Exit;
    }

    EplRet = EplApiProcessImageSetup();
    if (EplRet != kEplSuccessful)
    {
        goto Exit;
    }

    // start processing
    EplRet = EplApiExecNmtCommand(kEplNmtEventSwReset);
    if (EplRet != kEplSuccessful)
    {
        goto ExitShutdown;
    }

    printf("\n-------------------------------\n");
    printf("Press Esc to leave the program\n");
    printf("Press r to reset the node\n");
    printf("-------------------------------\n\n");
    // wait for key hit
    while (cKey != 0x1B)
    {
        if( EplTgtKbhit() )
        {
            cKey    = (BYTE) EplTgtGetch();

            switch (cKey)
            {
                case 'r':
                {
                    EplRet = EplApiExecNmtCommand(kEplNmtEventSwReset);
                    if (EplRet != kEplSuccessful)
                    {
                        goto ExitShutdown;
                    }
                    break;
                }

                case 'c':
                {
                    EplRet = EplApiExecNmtCommand(kEplNmtEventNmtCycleError);
                    if (EplRet != kEplSuccessful)
                    {
                        goto ExitShutdown;
                    }
                    break;
                }

                default:
                {
                    break;
                }
            }
        }

        EplTgtMilliSleep( 1500 );
    }

    FTRACE_ENABLE(FALSE);

ExitShutdown:
    // halt the NMT state machine
    // so the processing of POWERLINK frames stops
    EplRet = EplApiExecNmtCommand(kEplNmtEventSwitchOff);

    // delete process image
    EplRet = EplApiProcessImageFree();

    // delete instance for all modules
    EplRet = EplApiShutdown();

Exit:
    PRINTF("main(): returns 0x%X\n", EplRet);

#if (TARGET_SYSTEM == _WIN32_)
    PRINTF("Press Enter to quit!\n");
    EplTgtGetch();
#endif

    return EplRet;
}
/// \cond
int main(int argc, char **argv)
{
    int fd;
    char *s;
    unsigned char ope_code;
    unsigned char prev_code;
    unsigned char data_size;
    unsigned char prev_size;
    int len;
    int baud;
    char ret;
    
    printf("bcm2835_for_java ver1.01 start priority=%d\n", nice(1) );
    if( argc != 2 )
    {
        printf("bcm2835_for_java needs 1 parameter like as /tmp/shared_mem\n");
      exit ( -1 );
    }
    else
    {
      fd = open( argv[1], O_RDWR);
      if( fd == -1 )
      {
        printf("file %s can't open\n",argv[1]);
        exit(-1);
      }
      else
      {
         s = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
         if( s == MAP_FAILED )
         {
            printf("we can't create mapping file\n");
         }
      }
    }

  
    r_buff = (struct ring_buff *)s;
    w_buff = (struct ring_buff *)(s+sizeof(struct ring_buff) );
    bi_send_buff = (char *)( s + 2*sizeof(struct ring_buff) );
    bi_rec_buff = (char *)( bi_send_buff + TEMP_BUFF_SIZE );
    sync_code = (int *)( bi_rec_buff + TEMP_BUFF_SIZE );
    reply_code = (int *)( sync_code + 1 );
    
    init_ring_buff(w_buff,WRITER_INIT);
    init_ring_buff(r_buff,READER_INIT);
    
    bi_status = STATUS_FINE;
    
    while( 1 )
    {
        if( calc_data_size( r_buff ) != 0 )
        {
          prev_code = ope_code;
          prev_size = data_size;
          get_ope_code();
          ope_code = buff[0];
          data_size = calc_data_size( r_buff );
          switch( ope_code )
            {
                case OPE_INIT:
                    bcm_init();
                    break;
                case OPE_CLOSE:
                    bcm_close();
                    break;
                case OPE_SET_DEBUG:
                    ope_set_debug();
                    break;
                case OPE_PERI_READ:
                    ope_peri_read();
                    break;
                case OPE_PERI_READ_NB:
                    ope_peri_read_nb();
                    break;
                case OPE_PERI_WRITE:
                    ope_peri_write();
                    break;
                case OPE_PERI_WRITE_NB:
                    ope_peri_write_nb();
                    break;
                case OPE_PERI_SET_BITS:
                    ope_peri_set_bits();
                    break;
                case OPE_GPIO_FSEL:
                    ope_gpio_fsel();
                    break;
                case OPE_GPIO_SET:
                    ope_gpio_set();
                    break;
                case OPE_GPIO_CLR:
                    ope_gpio_clr();
                    break;
                case OPE_GPIO_SET_MULTI:
                    ope_gpio_set_multi();
                    break;
                case OPE_GPIO_CLR_MULTI:
                    ope_gpio_clr_multi();
                    break;
                case OPE_GPIO_LEV:
                    ope_gpio_lev();
                    break;
                case OPE_GPIO_EDS:
                    ope_gpio_eds();
                    break;
                case OPE_GPIO_SET_EDS:
                    ope_gpio_set_eds();
                    break;
                case OPE_GPIO_REN:
                    ope_gpio_ren();
                    break;
                case OPE_GPIO_CLR_REN:
                    ope_gpio_clr_ren();
                    break;
                case OPE_GPIO_FEN:
                    ope_gpio_fen();
                    break;
                case OPE_GPIO_CLR_FEN:
                    ope_gpio_clr_fen();
                    break;
                case OPE_GPIO_HEN:
                    ope_gpio_hen();
                    break;
                case OPE_GPIO_CLR_HEN:
                    ope_gpio_clr_hen();
                    break;
                case OPE_GPIO_LEN:
                    ope_gpio_len();
                    break;
                case OPE_GPIO_CLR_LEN:
                    ope_gpio_clr_len();
                    break;
                case OPE_GPIO_AREN:
                    ope_gpio_aren();
                    break;
                case OPE_GPIO_CLR_AREN:
                    ope_gpio_clr_aren();
                    break;
                case OPE_GPIO_AFEN:
                    ope_gpio_afen();
                    break;
                case OPE_GPIO_CLR_AFEN:
                    ope_gpio_clr_afen();
                    break;
                case OPE_GPIO_PUD:
                    ope_gpio_pud();
                    break;
                case OPE_GPIO_PUDCLK:
                    ope_gpio_pudclk();
                    break;
                case OPE_GPIO_WRITE:
                    ope_gpio_write();
                    break;
                case OPE_GPIO_PAD:
                    ope_gpio_pad();
                    break;
                case OPE_GPIO_SET_PAD:
                    ope_gpio_set_pad();
                    break;
                case OPE_DELAY:
                    ope_delay();
                    break;
                case OPE_DELAYMICROSECONDS:
                    ope_delaymicroseconds();
                    break;
                case OPE_GPIO_WRITE_MULTI:
                    ope_gpio_write_multi();
                    break;
                case OPE_GPIO_WRITE_MASK:
                    ope_gpio_write_mask();
                    break;
                case OPE_GPIO_SET_PUD:
                    ope_gpio_set_pud();
                    break;
                case OPE_SPI_BEGIN:
                    ope_spi_begin();
                    break;
                case OPE_SPI_END:
                    ope_spi_end();
                    break;
                case OPE_SPI_SETBITORDER:
                    ope_spi_setbitorder();
                    break;
                case OPE_SPI_SETCLOCKDIVIDER:
                    ope_spi_setclockdivider();
                    break;
                case OPE_SPI_SETDATAMODE:
                    ope_spi_setdatamode();
                    break;
                case OPE_SPI_CHIPSELECT:
                    ope_spi_chipselect();
                    break;
                case OPE_SPI_SETCHIPSELECTPOLARITY:
                    ope_spi_setchipselectpolarity();
                    break;
                case OPE_SPI_TRANSFER:
                    ope_spi_transfer();
                    break;
                case OPE_SPI_TRANSFERNB:
                    ope_spi_transfernb();
                    break;
                case OPE_SPI_TRANSFERN:
                    ope_spi_transfern();
                    break;
                case OPE_SPI_WRITENB:
                    ope_spi_writenb();
                    break;
                case OPE_I2C_BEGIN:
                    ope_i2c_begin();
                    break;
                case OPE_I2C_END:
                    ope_i2c_end();
                    break;
                case OPE_I2C_SETSLAVEADDRESS:
                    ope_i2c_setslaveaddress();
                    break;
                case OPE_I2C_SETCLOCKDIVIDER:
                    ope_i2c_setclockdivider();
                    break;
                case OPE_I2C_SET_BAUDRATE:
                    ope_i2c_set_baudrate();
                    break;
                case OPE_I2C_WRITE:
                    ope_i2c_write();
                    break;
                case OPE_I2C_READ:
                    ope_i2c_read();
                    break;
                case OPE_I2C_READ_REGISTER_RS:
                    ope_i2c_read_register_rs();
                    break;
                case OPE_ST_READ:
                    ope_st_read();
                    break;
                case OPE_ST_DELAY:
                    ope_st_delay();
                    break;
                case OPE_HELLO:
                    get_int_code();
                    len = *(int *)(buff+1);
                    set_ope_code( OPE_REPLY );
                    strcpy( bi_rec_buff, "Nice to meet you." );
                    set_int_code( strlen(bi_rec_buff) );
                    put_reply();
                    mark_sync();
                    usleep(5000);
                    break;
                case OPE_SYNC:
                    mark_sync();
                    break;
                case OPE_EXIT:
                    goto BREAK_LINE;
                    break;
                case OPE_OPEN_UART:
                    open_uart();
                    break;
                case OPE_CONFIG_UART:
                    configure_uart();
                    break;
                case OPE_SEND_UART:
                    send_uart();
                    break;
                case OPE_RECEIVE_UART:
                    receive_uart();
                    break;
                case OPE_CLOSE_UART:
                    close_uart();
                    break;
            default:
              printf("prev_code %02x \n",prev_code);
              printf("prev_size %d \n",prev_size);
              printf("ope_code error %02x \n",ope_code);
              printf("data_size=%d \n",data_size);
              break;
            }
        }
        else
        {
            usleep(5000);
        }
    }
BREAK_LINE:
    printf("Close bcm2835_for_java\n");
    exit(0);
}
Exemple #24
0
int
main(int argc, char **argv, char **envp)
{
  char *s;
  int i, exit_code;

#ifndef _MSC_VER
  /* catch SIGUSR1 and dump intermediate stats */
  signal(SIGUSR1, signal_sim_stats);

  /* catch SIGUSR2 and dump final stats and exit */
  signal(SIGUSR2, signal_exit_now);
#endif /* _MSC_VER */

  /* register an error handler */
  fatal_hook(sim_print_stats);

  /* set up a non-local exit point */
  if ((exit_code = setjmp(sim_exit_buf)) != 0)
    {
      /* special handling as longjmp cannot pass 0 */
      exit_now(exit_code-1);
    }

  /* register global options */
  sim_odb = opt_new(orphan_fn);
  opt_reg_flag(sim_odb, "-h", "print help message",
	       &help_me, /* default */FALSE, /* !print */FALSE, NULL);
  opt_reg_flag(sim_odb, "-v", "verbose operation",
	       &verbose, /* default */FALSE, /* !print */FALSE, NULL);
#ifdef DEBUG
  opt_reg_flag(sim_odb, "-d", "enable debug message",
	       &debugging, /* default */FALSE, /* !print */FALSE, NULL);
#endif /* DEBUG */
  opt_reg_flag(sim_odb, "-i", "start in Dlite debugger",
	       &dlite_active, /* default */FALSE, /* !print */FALSE, NULL);
  opt_reg_int(sim_odb, "-seed",
	      "random number generator seed (0 for timer seed)",
	      &rand_seed, /* default */1, /* print */TRUE, NULL);
  opt_reg_flag(sim_odb, "-q", "initialize and terminate immediately",
	       &init_quit, /* default */FALSE, /* !print */FALSE, NULL);
  opt_reg_string(sim_odb, "-chkpt", "restore EIO trace execution from <fname>",
		 &sim_chkpt_fname, /* default */NULL, /* !print */FALSE, NULL);

  /* stdio redirection options */
  opt_reg_string(sim_odb, "-redir:sim",
		 "redirect simulator output to file (non-interactive only)",
		 &sim_simout,
		 /* default */NULL, /* !print */FALSE, NULL);
  opt_reg_string(sim_odb, "-redir:prog",
		 "redirect simulated program output to file",
		 &sim_progout, /* default */NULL, /* !print */FALSE, NULL);

#ifndef _MSC_VER
  /* scheduling priority option */
  opt_reg_int(sim_odb, "-nice",
	      "simulator scheduling priority", &nice_priority,
	      /* default */NICE_DEFAULT_VALUE, /* print */TRUE, NULL);
#endif

  /* FIXME: add stats intervals and max insts... */

  /* register all simulator-specific options */
  sim_reg_options(sim_odb);

  /* parse simulator options */
  exec_index = -1;
  opt_process_options(sim_odb, argc, argv);

  /* redirect I/O? */
  if (sim_simout != NULL)
    {
      /* send simulator non-interactive output (STDERR) to file SIM_SIMOUT */
      fflush(stderr);
      if (!freopen(sim_simout, "w", stderr))
	fatal("unable to redirect simulator output to file `%s'", sim_simout);
    }

  if (sim_progout != NULL)
    {
      /* redirect simulated program output to file SIM_PROGOUT */
      sim_progfd = fopen(sim_progout, "w");
      if (!sim_progfd)
	fatal("unable to redirect program output to file `%s'", sim_progout);
    }

  /* need at least two argv values to run */
  if (argc < 2)
    {
      banner(stderr, argc, argv);
      usage(stderr, argc, argv);
      exit(1);
    }

  /* opening banner */
  banner(stderr, argc, argv);

  if (help_me)
    {
      /* print help message and exit */
      usage(stderr, argc, argv);
      exit(1);
    }

  /* seed the random number generator */
  if (rand_seed == 0)
    {
      /* seed with the timer value, true random */
      mysrand(time((time_t *)NULL));
    }
  else
    {
      /* seed with default or user-specified random number generator seed */
      mysrand(rand_seed);
    }

  /* exec_index is set in orphan_fn() */
  if (exec_index == -1)
    {
      /* executable was not found */
      fprintf(stderr, "error: no executable specified\n");
      usage(stderr, argc, argv);
      exit(1);
    }
  /* else, exec_index points to simulated program arguments */

  /* check simulator-specific options */
  sim_check_options(sim_odb, argc, argv);

#ifndef _MSC_VER
  /* set simulator scheduling priority */
  if (nice(0) < nice_priority)
    {
      if (nice(nice_priority - nice(0)) < 0)
        fatal("could not renice simulator process");
    }
#endif

  /* default architected value... */
  sim_num_insn = 0;

#ifdef BFD_LOADER
  /* initialize the bfd library */
  bfd_init();
#endif /* BFD_LOADER */

  /* initialize the instruction decoder */
  md_init_decoder();

  /* initialize all simulation modules */
  sim_init();

  /* initialize architected state */
  sim_load_prog(argv[exec_index], argc-exec_index, argv+exec_index, envp);

  /* register all simulator stats */
  sim_sdb = stat_new();
  sim_reg_stats(sim_sdb);
#if 0 /* not portable... :-( */
  stat_reg_uint(sim_sdb, "sim_mem_usage",
		"total simulator (data) memory usage",
		&sim_mem_usage, sim_mem_usage, "%11dk");
#endif

  /* record start of execution time, used in rate stats */
  sim_start_time = time((time_t *)NULL);

  /* emit the command line for later reuse */
  fprintf(stderr, "sim: command line: ");
  for (i=0; i < argc; i++)
    fprintf(stderr, "%s ", argv[i]);
  fprintf(stderr, "\n");

  /* output simulation conditions */
  s = ctime(&sim_start_time);
  if (s[strlen(s)-1] == '\n')
    s[strlen(s)-1] = '\0';
  fprintf(stderr, "\nsim: simulation started @ %s, options follow:\n", s);
  opt_print_options(sim_odb, stderr, /* short */TRUE, /* notes */TRUE);
  sim_aux_config(stderr);
  fprintf(stderr, "\n");

  /* omit option dump time from rate stats */
  sim_start_time = time((time_t *)NULL);

  if (init_quit)
    exit_now(0);

  running = TRUE;
  sim_main();

  /* simulation finished early */
  exit_now(0);

  return 0;
}
Exemple #25
0
R_API int r_run_start(RRunProfile *p) {
#if LIBC_HAVE_FORK
	if (p->_execve) {
		exit (execv (p->_program, (char* const*)p->_args));
	}
#endif
#if __APPLE__ && !__POWERPC__ && LIBC_HAVE_FORK
	posix_spawnattr_t attr = {0};
	pid_t pid = -1;
	int ret;
	posix_spawnattr_init (&attr);
	if (p->_args[0]) {
		char **envp = r_sys_get_environ();
		ut32 spflags = 0; //POSIX_SPAWN_START_SUSPENDED;
		spflags |= POSIX_SPAWN_SETEXEC;
		if (p->_aslr == 0) {
#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
			spflags |= _POSIX_SPAWN_DISABLE_ASLR;
		}
		(void)posix_spawnattr_setflags (&attr, spflags);
		if (p->_bits) {
			size_t copied = 1;
			cpu_type_t cpu;
#if __i386__ || __x86_64__
			cpu = CPU_TYPE_I386;
			if (p->_bits == 64) {
				cpu |= CPU_ARCH_ABI64;
			}
#else
			cpu = CPU_TYPE_ANY;
#endif
			posix_spawnattr_setbinpref_np (
					&attr, 1, &cpu, &copied);
		}
		ret = posix_spawnp (&pid, p->_args[0],
			NULL, &attr, p->_args, envp);
		switch (ret) {
		case 0:
			break;
		case 22:
			eprintf ("posix_spawnp: Invalid argument\n");
			break;
		case 86:
			eprintf ("posix_spawnp: Unsupported architecture\n");
			break;
		default:
			eprintf ("posix_spawnp: unknown error %d\n", ret);
			perror ("posix_spawnp");
			break;
		}
		exit (ret);
	}
#endif
	if (p->_system) {
		if (p->_pid) {
			eprintf ("PID: Cannot determine pid with 'system' directive. Use 'program'.\n");
		}
		exit (r_sys_cmd (p->_system));
	}
	if (p->_program) {
		if (!r_file_exists (p->_program)) {
			char *progpath = r_file_path (p->_program);
			if (progpath && *progpath) {
				free (p->_program);
				p->_program = progpath;
			} else {
				free (progpath);
				eprintf ("rarun2: %s: file not found\n", p->_program);
				return 1;
			}
		}
#if __UNIX__
		// XXX HACK close all non-tty fds
		{ int i;
			for (i = 3; i < 10; i++) {
				close (i);
			}
		}
		// TODO: use posix_spawn
		if (p->_setgid) {
			int ret = setgid (atoi (p->_setgid));
			if (ret < 0) {
				return 1;
			}
		}
		if (p->_pid) {
			eprintf ("PID: %d\n", getpid ());
		}
		if (p->_pidfile) {
			char pidstr[32];
			snprintf (pidstr, sizeof (pidstr), "%d\n", getpid ());
			r_file_dump (p->_pidfile,
				(const ut8*)pidstr,
				strlen (pidstr), 0);
		}
#endif

		if (p->_nice) {
#if __UNIX__ && !defined(__HAIKU__)
			if (nice (p->_nice) == -1) {
				return 1;
			}
#else
			eprintf ("nice not supported for this platform\n");
#endif
		}
// TODO: must be HAVE_EXECVE
#if LIBC_HAVE_FORK
		exit (execv (p->_program, (char* const*)p->_args));
#endif
	}
	if (p->_runlib) {
		if (!p->_runlib_fcn) {
			eprintf ("No function specified. Please set runlib.fcn\n");
			return 1;
		}
		void *addr = r_lib_dl_open (p->_runlib);
		if (!addr) {
			eprintf ("Could not load the library '%s'\n", p->_runlib);
			return 1;
		}
		void (*fcn)(void) = r_lib_dl_sym (addr, p->_runlib_fcn);
		if (!fcn) {
			eprintf ("Could not find the function '%s'\n", p->_runlib_fcn);
			return 1;
		}
		switch (p->_argc) {
		case 0:
			fcn ();
			break;
		case 1:
			r_run_call1 (fcn, p->_args[1]);
			break;
		case 2:
			r_run_call2 (fcn, p->_args[1], p->_args[2]);
			break;
		case 3:
			r_run_call3 (fcn, p->_args[1], p->_args[2], p->_args[3]);
			break;
		case 4:
			r_run_call4 (fcn, p->_args[1], p->_args[2], p->_args[3], p->_args[4]);
			break;
		case 5:
			r_run_call5 (fcn, p->_args[1], p->_args[2], p->_args[3], p->_args[4],
				p->_args[5]);
			break;
		case 6:
			r_run_call6 (fcn, p->_args[1], p->_args[2], p->_args[3], p->_args[4],
				p->_args[5], p->_args[6]);
			break;
		case 7:
			r_run_call7 (fcn, p->_args[1], p->_args[2], p->_args[3], p->_args[4],
				p->_args[5], p->_args[6], p->_args[7]);
			break;
		case 8:
			r_run_call8 (fcn, p->_args[1], p->_args[2], p->_args[3], p->_args[4],
				p->_args[5], p->_args[6], p->_args[7], p->_args[8]);
			break;
		case 9:
			r_run_call9 (fcn, p->_args[1], p->_args[2], p->_args[3], p->_args[4],
				p->_args[5], p->_args[6], p->_args[7], p->_args[8], p->_args[9]);
			break;
		case 10:
			r_run_call10 (fcn, p->_args[1], p->_args[2], p->_args[3], p->_args[4],
				p->_args[5], p->_args[6], p->_args[7], p->_args[8], p->_args[9], p->_args[10]);
			break;
		default:
			eprintf ("Too many arguments.\n");
			return 1;
		}
		r_lib_dl_close (addr);
	}
	return 0;
}
Exemple #26
0
pid_t
my_pty_fork(int *ptr_master_fd,
            const struct termios *slave_termios,
            const struct winsize *slave_winsize)
{
  int fdm, fds = -1;
  int ttyfd;
  pid_t pid;
  const char *slave_name;
  struct termios pterm;
  int only_sigchld[] = { SIGCHLD, 0 };


  ptytty_openpty(&fdm, &fds, &slave_name);

  slave_pty_fd = fds;

  block_signals(only_sigchld);  /* block SIGCHLD until we have had a chance to install a handler for it after the fork() */

  if ((pid = fork()) < 0) {
    myerror("Cannot fork");
    return(42); /* the compiler may not know that myerror() won't return */
  } else if (pid == 0) {                /* child */
    DEBUG_RANDOM_SLEEP;
    i_am_child = TRUE;          /* remember who I am */
    unblock_all_signals();
    
    close(fdm);                 /* fdm not used in child */
    ptytty_control_tty(fds, slave_name);

    if (dup2(fds, STDIN_FILENO) != STDIN_FILENO)
      myerror("dup2 to stdin failed");
    if (isatty(STDOUT_FILENO) && dup2(fds, STDOUT_FILENO) != STDOUT_FILENO)
      myerror("dup2 to stdout failed");
    if (isatty(STDERR_FILENO) && dup2(fds, STDERR_FILENO) != STDERR_FILENO)
      myerror("dup2 to stderr failed");
    if (fds > STDERR_FILENO)
      close(fds);


    if (slave_termios != NULL)
      if (tcsetattr(STDIN_FILENO, TCSANOW, slave_termios) < 0)
        myerror("tcsetattr failed on slave pty");


    return (0);
  } else {                      /* parent */
    srand(pid); DEBUG_RANDOM_SLEEP;
    command_pid = pid;            /* the SIGCHLD signal handler needs this global variable */
 
    *ptr_master_fd = fdm;
    if (!command_is_dead && tcgetattr(fdm, &pterm) < 0) {
      sleep(1);                 /* we might be more succesful after the child command has
                                   initialized its terminal. As there is no reliable way to sense this
                                   from the parent, we just wait a little */
      if (tcgetattr(slave_pty_fd, &pterm) < 0) {
        fprintf(stderr,         /* don't use mywarn() because of the strerror() message *within* the text */
                "Warning: %s cannot determine terminal mode of %s\n"
                "(because: %s).\n"
                "Readline mode will always be on (as if -a option was set);\n"
                "passwords etc. *will* be echoed and saved in history list!\n\n",
                program_name, command_name, strerror(errno));
        always_echo = TRUE;
      }
    }
    if (!isatty(STDOUT_FILENO) || !isatty(STDERR_FILENO)) {     /* stdout or stderr redirected? */
      ttyfd = open("/dev/tty", O_WRONLY);                       /* open users terminal          */
      DPRINTF1(DEBUG_TERMIO, "stdout or stderr are not a terminal, onpening /dev/tty with fd=%d", ttyfd);       
      if (ttyfd <0)     
        myerror("Could not open /dev/tty");
      if (dup2(ttyfd, STDOUT_FILENO) != STDOUT_FILENO) 
        myerror("dup2 of stdout to ttyfd failed");  
      if (dup2(ttyfd, STDERR_FILENO) != STDERR_FILENO)
        myerror("dup2 of stderr to ttyfd failed");
      close (ttyfd);
    }
    if (renice && !nice(1)) /* impossible */
      myerror("could not increase my own niceness"); 

    if (slave_winsize != NULL)
      if (ioctl(fdm, TIOCSWINSZ, slave_winsize) < 0) /* this assumes that master and slave have identical winsizes */
        myerror("TIOCSWINSZ failed on master pty"); 

    return (pid); /* returns in parent and in child (and pid lets us determine who we are) */
  }
}
Exemple #27
0
/*VARARGS 1*/
void
execute(struct command *t, volatile int wanttty, int *pipein, int *pipeout,
    int do_glob)
{
    int    forked = 0;
    const struct biltins * volatile bifunc;
    pid_t pid = 0;
    int     pv[2];
    sigset_t set;
    static sigset_t csigset;
#ifdef VFORK
    static int onosigchld = 0;
#endif /* VFORK */
    static int nosigchld = 0;

    (void) &wanttty;
    (void) &forked;
    (void) &bifunc;

    if (t == 0) 
	return;

#ifdef WINNT_NATIVE
    {
        if ((varval(STRNTslowexec) == STRNULL) &&
            !t->t_dcdr && !t->t_dcar && !t->t_dflg && !didfds &&
            (intty || intact) && (t->t_dtyp == NODE_COMMAND) &&
	    !isbfunc(t)) {
	    if ((t->t_dcom[0][0] & (QUOTE | TRIM)) == QUOTE)
		(void) Strcpy(t->t_dcom[0], t->t_dcom[0] + 1);
	    Dfix(t);
            if (nt_try_fast_exec(t) == 0)
                return;
        }
    }
#endif /* WINNT_NATIVE */

    /*
     * Ed [email protected] & Dominic [email protected]
     * Sat Feb 25 03:13:11 PST 1995
     * try implicit cd if we have a 1 word command 
     */
    if (implicit_cd && (intty || intact) && t->t_dcom && t->t_dcom[0] &&
	 t->t_dcom[0][0] && (blklen(t->t_dcom) == 1) && !noexec) {
	Char *sCName;
	struct stat stbuf;
	char *pathname;

	sCName = dollar(t->t_dcom[0]);
	if (sCName != NULL && sCName[0] == '~') {
	    struct Strbuf buf = Strbuf_INIT;
	    const Char *name_end;

	    for (name_end = sCName + 1; *name_end != '\0' && *name_end != '/';
		 name_end++)
		continue;
	    if (name_end != sCName + 1) {
		Char *name, *home;

		name = Strnsave(sCName + 1, name_end - (sCName + 1));
		home = gethdir(name);
		if (home != NULL) {
		    Strbuf_append(&buf, home);
		    xfree(home);
		} else
		    Strbuf_append(&buf, name);
		xfree(name);
	    } else
		Strbuf_append(&buf, varval(STRhome));
	    Strbuf_append(&buf, name_end);
	    xfree(sCName);
	    sCName = Strbuf_finish(&buf);
	}

	pathname = short2str(sCName);
	xfree(sCName);
	/* if this is a dir, tack a "cd" on as the first arg */
	if (pathname != NULL &&
	    ((stat(pathname, &stbuf) != -1 && S_ISDIR(stbuf.st_mode))
#ifdef WINNT_NATIVE
	     || (pathname[0] && pathname[1] == ':' && pathname[2] == '\0')
#endif /* WINNT_NATIVE */
	     )) {
	    Char *vCD[2];
	    Char **ot_dcom = t->t_dcom;
	
	    vCD[0] = Strsave(STRcd);
	    vCD[1] = NULL;
	    t->t_dcom = blkspl(vCD, ot_dcom);
	    xfree(ot_dcom);
	    if (implicit_cd > 1) {
		blkpr(t->t_dcom);
		xputchar( '\n' );
	    }
	}
    }

    /*
     * From: Michael Schroeder <*****@*****.**>
     * Don't check for wantty > 0...
     */
    if (t->t_dflg & F_AMPERSAND)
	wanttty = 0;
    switch (t->t_dtyp) {

    case NODE_COMMAND:
	if ((t->t_dcom[0][0] & (QUOTE | TRIM)) == QUOTE)
	    memmove(t->t_dcom[0], t->t_dcom[0] + 1,
		    (Strlen(t->t_dcom[0] + 1) + 1) * sizeof (*t->t_dcom[0]));
	if ((t->t_dflg & F_REPEAT) == 0)
	    Dfix(t);		/* $ " ' \ */
	if (t->t_dcom[0] == 0) {
	    return;
	}
	/*FALLTHROUGH*/

    case NODE_PAREN:
#ifdef BACKPIPE
	if (t->t_dflg & F_PIPEIN)
	    mypipe(pipein);
#else /* !BACKPIPE */
	if (t->t_dflg & F_PIPEOUT)
	    mypipe(pipeout);
#endif /* BACKPIPE */
	/*
	 * Must do << early so parent will know where input pointer should be.
	 * If noexec then this is all we do.
	 */
	if (t->t_dflg & F_READ) {
	    xclose(0);
	    heredoc(t->t_dlef);
	    if (noexec)
		xclose(0);
	}

	setcopy(STRstatus, STR0, VAR_READWRITE);

	/*
	 * This mess is the necessary kludge to handle the prefix builtins:
	 * nice, nohup, time.  These commands can also be used by themselves,
	 * and this is not handled here. This will also work when loops are
	 * parsed.
	 */
	while (t->t_dtyp == NODE_COMMAND)
	    if (eq(t->t_dcom[0], STRnice)) {
		if (t->t_dcom[1]) {
		    if (strchr("+-", t->t_dcom[1][0])) {
			if (t->t_dcom[2]) {
			    setname("nice");
			    t->t_nice = (unsigned char)getn(t->t_dcom[1]);
			    lshift(t->t_dcom, 2);
			    t->t_dflg |= F_NICE;
			}
			else
			    break;
		    }
		    else {
			t->t_nice = 4;
			lshift(t->t_dcom, 1);
			t->t_dflg |= F_NICE;
		    }
		}
		else
		    break;
	    }
	    else if (eq(t->t_dcom[0], STRnohup)) {
		if (t->t_dcom[1]) {
		    t->t_dflg |= F_NOHUP;
		    lshift(t->t_dcom, 1);
		}
		else
		    break;
	    }
	    else if (eq(t->t_dcom[0], STRhup)) {
		if (t->t_dcom[1]) {
		    t->t_dflg |= F_HUP;
		    lshift(t->t_dcom, 1);
		}
		else
		    break;
	    }
	    else if (eq(t->t_dcom[0], STRtime)) {
		if (t->t_dcom[1]) {
		    t->t_dflg |= F_TIME;
		    lshift(t->t_dcom, 1);
		}
		else
		    break;
	    }
#ifdef F_VER
	    else if (eq(t->t_dcom[0], STRver))
		if (t->t_dcom[1] && t->t_dcom[2]) {
		    setname("ver");
		    t->t_systype = getv(t->t_dcom[1]);
		    lshift(t->t_dcom, 2);
		    t->t_dflg |= F_VER;
		}
		else
		    break;
#endif  /* F_VER */
	    else
		break;

	/* is it a command */
	if (t->t_dtyp == NODE_COMMAND) {
	    /*
	     * Check if we have a builtin function and remember which one.
	     */
	    bifunc = isbfunc(t);
 	    if (noexec) {
		/*
		 * Continue for builtins that are part of the scripting language
		 */
		if (bifunc == NULL)
		    break;
		if (bifunc->bfunct != (bfunc_t)dobreak	&&
		    bifunc->bfunct != (bfunc_t)docontin	&&
		    bifunc->bfunct != (bfunc_t)doelse	&&
		    bifunc->bfunct != (bfunc_t)doend	&&
		    bifunc->bfunct != (bfunc_t)doforeach&&
		    bifunc->bfunct != (bfunc_t)dogoto	&&
		    bifunc->bfunct != (bfunc_t)doif	&&
		    bifunc->bfunct != (bfunc_t)dorepeat	&&
		    bifunc->bfunct != (bfunc_t)doswbrk	&&
		    bifunc->bfunct != (bfunc_t)doswitch	&&
		    bifunc->bfunct != (bfunc_t)dowhile	&&
		    bifunc->bfunct != (bfunc_t)dozip)
		    break;
	    }
	}
	else {			/* not a command */
	    bifunc = NULL;
	    if (noexec)
		break;
	}

	/* 
	 * GrP Executing a command - run jobcmd hook
	 * Don't run for builtins
	 * Don't run if we're not in a tty
	 * Don't run if we're not really executing 
	 */
	/*
	 * CR  -  Charles Ross Aug 2005
	 * added "isoutatty".
	 * The new behavior is that the jobcmd won't be executed
	 * if stdout (SHOUT) isnt attached to a tty.. IE when
	 * redirecting, or using backquotes etc..
	 */
	if (t->t_dtyp == NODE_COMMAND && !bifunc && !noexec && intty && isoutatty) {
	    Char *cmd = unparse(t);

	    cleanup_push(cmd, xfree);
	    job_cmd(cmd);
	    cleanup_until(cmd);
	}
	   
	/*
	 * We fork only if we are timed, or are not the end of a parenthesized
	 * list and not a simple builtin function. Simple meaning one that is
	 * not pipedout, niced, nohupped, or &'d. It would be nice(?) to not
	 * fork in some of these cases.
	 */
#ifdef BACKPIPE
	/*
	 * Can't have NOFORK for the tail of a pipe - because it is not the
	 * last command spawned (even if it is at the end of a parenthesised
	 * list).
	 */
	if (t->t_dflg & F_PIPEIN)
	    t->t_dflg &= ~(F_NOFORK);
#else
	/*
	 * "command | builtin" may cause major misbehaviour as noted in
	 * in the BUGS file entry
	 * Subject: Redirected input to built-in functions misbehaves badly
	 * forking when the builtin is the end of the pipe corrects the
	 * problem.
	 */
	if (bifunc && (t->t_dflg & F_PIPEIN))
	    t->t_dflg &= ~(F_NOFORK);
#endif /* BACKPIPE */
	/*
	 * Prevent forking cd, pushd, popd, chdir cause this will cause the
	 * shell not to change dir! (XXX: but only for nice?)
	 */
	if (bifunc && (bifunc->bfunct == (bfunc_t)dochngd ||
		       bifunc->bfunct == (bfunc_t)dopushd ||
		       bifunc->bfunct == (bfunc_t)dopopd))
	    t->t_dflg &= ~(F_NICE);

	if (((t->t_dflg & F_TIME) || ((t->t_dflg & F_NOFORK) == 0 &&
	     (!bifunc || t->t_dflg &
	      (F_PIPEOUT | F_AMPERSAND | F_NICE | F_NOHUP | F_HUP)))) ||
	/*
	 * We have to fork for eval too.
	 */
	    (bifunc && (t->t_dflg & F_PIPEIN) != 0 &&
	     bifunc->bfunct == (bfunc_t)doeval)) {
#ifdef VFORK
	    if (t->t_dtyp == NODE_PAREN ||
		t->t_dflg & (F_REPEAT | F_AMPERSAND) || bifunc)
#endif /* VFORK */
	    {
		forked++;
		/*
		 * We need to block SIGCHLD here, so that if the process does
		 * not die before we can set the process group
		 */
		if (wanttty >= 0 && !nosigchld) {
		    sigemptyset(&set);
		    sigaddset(&set, SIGCHLD);
		    (void)sigprocmask(SIG_BLOCK, &set, &csigset);

		    nosigchld = 1;
		}

		pid = pfork(t, wanttty);
		if (pid == 0 && nosigchld) {
		    sigprocmask(SIG_SETMASK, &csigset, NULL);
		    nosigchld = 0;
		}
		else if (pid != 0 && (t->t_dflg & F_AMPERSAND))
		    backpid = pid;
	    }

#ifdef VFORK
	    else {
		int     ochild, osetintr, ohaderr, odidfds;
		int     oSHIN, oSHOUT, oSHDIAG, oOLDSTD, otpgrp;
		int     oisoutatty, oisdiagatty;
		sigset_t oset, ocsigset;
# ifndef CLOSE_ON_EXEC
		int     odidcch;
# endif  /* !CLOSE_ON_EXEC */

		/*
		 * Prepare for the vfork by saving everything that the child
		 * corrupts before it exec's. Note that in some signal
		 * implementations which keep the signal info in user space
		 * (e.g. Sun's) it will also be necessary to save and restore
		 * the current sigvec's for the signals the child touches
		 * before it exec's.
		 */

		/*
		 * Sooooo true... If this is a Sun, save the sigvec's. (Skip
		 * Gilbrech - 11/22/87)
		 */
# ifdef SAVESIGVEC
		struct sigaction savesv[NSIGSAVED];
		sigset_t savesm;

# endif /* SAVESIGVEC */
		if (wanttty >= 0 && !nosigchld && !noexec) {
		    sigemptyset(&set);
		    sigaddset(&set, SIGCHLD);
		    (void)sigprocmask(SIG_BLOCK, &set, &csigset);
		    nosigchld = 1;
		}
		sigemptyset(&set);
		sigaddset(&set, SIGCHLD);
		sigaddset(&set, SIGINT);
		(void)sigprocmask(SIG_BLOCK, &set, &oset);
		ochild = child;
		osetintr = setintr;
		ohaderr = haderr;
		odidfds = didfds;
# ifndef CLOSE_ON_EXEC
		odidcch = didcch;
# endif /* !CLOSE_ON_EXEC */
		oSHIN = SHIN;
		oSHOUT = SHOUT;
		oSHDIAG = SHDIAG;
		oOLDSTD = OLDSTD;
		otpgrp = tpgrp;
		oisoutatty = isoutatty;
		oisdiagatty = isdiagatty;
		ocsigset = csigset;
		onosigchld = nosigchld;
		Vsav = Vdp = 0;
		Vexpath = 0;
		Vt = 0;
# ifdef SAVESIGVEC
		savesigvec(savesv, savesm);
# endif /* SAVESIGVEC */
		if (use_fork)
		    pid = fork();
		else
		    pid = vfork();

		if (pid < 0) {
# ifdef SAVESIGVEC
		    restoresigvec(savesv, savesm);
# endif /* SAVESIGVEC */
		    sigprocmask(SIG_SETMASK, &oset, NULL);
		    stderror(ERR_NOPROC);
		}
		forked++;
		if (pid) {	/* parent */
# ifdef SAVESIGVEC
		    restoresigvec(savesv, savesm);
# endif /* SAVESIGVEC */
		    child = ochild;
		    setintr = osetintr;
		    haderr = ohaderr;
		    didfds = odidfds;
		    SHIN = oSHIN;
# ifndef CLOSE_ON_EXEC
		    didcch = odidcch;
# endif /* !CLOSE_ON_EXEC */
		    SHOUT = oSHOUT;
		    SHDIAG = oSHDIAG;
		    OLDSTD = oOLDSTD;
		    tpgrp = otpgrp;
		    isoutatty = oisoutatty;
		    isdiagatty = oisdiagatty;
		    csigset = ocsigset;
		    nosigchld = onosigchld;

		    xfree(Vsav);
		    Vsav = 0;
		    xfree(Vdp);
		    Vdp = 0;
		    xfree(Vexpath);
		    Vexpath = 0;
		    blk_cleanup(Vt);
		    Vt = 0;
		    /* this is from pfork() */
		    palloc(pid, t);
		    sigprocmask(SIG_SETMASK, &oset, NULL);
		}
		else {		/* child */
		    /* this is from pfork() */
		    pid_t pgrp;
		    int    ignint = 0;
		    if (nosigchld) {
			sigprocmask(SIG_SETMASK, &csigset, NULL);
			nosigchld = 0;
		    }

		    if (setintr)
			ignint = (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT))
				|| (gointr && eq(gointr, STRminus));
		    pgrp = pcurrjob ? pcurrjob->p_jobid : getpid();
		    child++;
		    if (setintr) {
			setintr = 0;
/*
 * casts made right for SunOS 4.0 by Douglas C. Schmidt
 * <*****@*****.**>
 * (thanks! -- PWP)
 *
 * ignint ifs cleaned by Johan Widen <[email protected]>
 * (thanks again)
 */
			if (ignint) {
			    (void) signal(SIGINT, SIG_IGN);
			    (void) signal(SIGQUIT, SIG_IGN);
			}
			else {
			    (void) signal(SIGINT, vffree);
			    (void) signal(SIGQUIT, SIG_DFL);
			}
# ifdef BSDJOBS
			if (wanttty >= 0) {
			    (void) signal(SIGTSTP, SIG_DFL);
			    (void) signal(SIGTTIN, SIG_DFL);
			    (void) signal(SIGTTOU, SIG_DFL);
			}
# endif /* BSDJOBS */

			sigaction(SIGTERM, &parterm, NULL);
		    }
		    else if (tpgrp == -1 &&
			     (t->t_dflg & F_NOINTERRUPT)) {
			(void) signal(SIGINT, SIG_IGN);
			(void) signal(SIGQUIT, SIG_IGN);
		    }

		    pgetty(wanttty, pgrp);

		    if (t->t_dflg & F_NOHUP)
			(void) signal(SIGHUP, SIG_IGN);
		    if (t->t_dflg & F_HUP)
			(void) signal(SIGHUP, SIG_DFL);
		    if (t->t_dflg & F_NICE) {
			int nval = SIGN_EXTEND_CHAR(t->t_nice);
# if defined(HAVE_SETPRIORITY) && defined(PRIO_PROCESS)
			if (setpriority(PRIO_PROCESS, 0, nval) == -1 && errno)
				stderror(ERR_SYSTEM, "setpriority",
				    strerror(errno));
# else /* !HAVE_SETPRIORITY || !PRIO_PROCESS */
			(void) nice(nval);
# endif /* HAVE_SETPRIORITY && PRIO_PROCESS */
		    }
# ifdef F_VER
		    if (t->t_dflg & F_VER) {
			tsetenv(STRSYSTYPE, t->t_systype ? STRbsd43 : STRsys53);
			dohash(NULL, NULL);
		    }
# endif /* F_VER */
		}

	    }
#endif /* VFORK */
	}
	if (pid != 0) {
	    /*
	     * It would be better if we could wait for the whole job when we
	     * knew the last process had been started.  Pwait, in fact, does
	     * wait for the whole job anyway, but this test doesn't really
	     * express our intentions.
	     */
#ifdef BACKPIPE
	    if (didfds == 0 && t->t_dflg & F_PIPEOUT) {
		xclose(pipeout[0]);
		xclose(pipeout[1]);
	    }
	    if ((t->t_dflg & F_PIPEIN) != 0)
		break;
#else /* !BACKPIPE */
	    if (didfds == 0 && t->t_dflg & F_PIPEIN) {
		xclose(pipein[0]);
		xclose(pipein[1]);
	    }
	    if ((t->t_dflg & F_PIPEOUT) != 0)
		break;
#endif /* BACKPIPE */

	    if (nosigchld) {
		sigprocmask(SIG_SETMASK, &csigset, NULL);
		nosigchld = 0;
	    }
	    if ((t->t_dflg & F_AMPERSAND) == 0)
		pwait();
	    break;
	}

	doio(t, pipein, pipeout);
#ifdef BACKPIPE
	if (t->t_dflg & F_PIPEIN) {
	    xclose(pipein[0]);
	    xclose(pipein[1]);
	}
#else /* !BACKPIPE */
	if (t->t_dflg & F_PIPEOUT) {
	    xclose(pipeout[0]);
	    xclose(pipeout[1]);
	}
#endif /* BACKPIPE */
	/*
	 * Perform a builtin function. If we are not forked, arrange for
	 * possible stopping
	 */
	if (bifunc) {
	    if (forked) {
		func(t, bifunc);
		exitstat();
	    } else {
		jmp_buf_t oldexit;
		int ohaderr = haderr;

		getexit(oldexit);
		if (setexit() == 0)
		    func(t, bifunc);
		resexit(oldexit);
		haderr = ohaderr;

		if (adrof(STRprintexitvalue)) {
		    int rv = getn(varval(STRstatus));
		    if (rv != 0)
			xprintf(CGETS(17, 2, "Exit %d\n"), rv);
		}
	    }
	    break;
	}
	if (t->t_dtyp != NODE_PAREN) {
	    doexec(t, do_glob);
	    /* NOTREACHED */
	}
	/*
	 * For () commands must put new 0,1,2 in FSH* and recurse
	 */
	if ((OLDSTD = dcopy(0, FOLDSTD)) >= 0)
	    (void)close_on_exec(OLDSTD, 1);
	if ((SHOUT = dcopy(1, FSHOUT)) >= 0) {
	    (void)close_on_exec(SHOUT, 1);
	    isoutatty = isatty(SHOUT);
	}
	if ((SHDIAG = dcopy(2, FSHDIAG)) >= 0) {
	    (void)close_on_exec(SHDIAG, 1);
	    isdiagatty = isatty(SHDIAG);
    	}
	xclose(SHIN);
	SHIN = -1;
#ifndef CLOSE_ON_EXEC
	didcch = 0;
#else
	(void) close_on_exec(FSHOUT, 1);
	(void) close_on_exec(FSHDIAG, 1);
	(void) close_on_exec(FOLDSTD, 1);
#endif /* !CLOSE_ON_EXEC */
	didfds = 0;
	wanttty = -1;
	t->t_dspr->t_dflg |= t->t_dflg & (F_NOINTERRUPT | F_BACKQ);
	execute(t->t_dspr, wanttty, NULL, NULL, do_glob);
	exitstat();

    case NODE_PIPE:
#ifdef BACKPIPE
	t->t_dcdr->t_dflg |= F_PIPEIN | (t->t_dflg &
	    (F_PIPEOUT | F_AMPERSAND | F_NOFORK | F_NOINTERRUPT | F_BACKQ));
	execute(t->t_dcdr, wanttty, pv, pipeout, do_glob);
	t->t_dcar->t_dflg |= F_PIPEOUT | (t->t_dflg &
	    (F_PIPEIN | F_AMPERSAND | F_STDERR | F_NOINTERRUPT | F_BACKQ));
	execute(t->t_dcar, wanttty, pipein, pv, do_glob);
#else /* !BACKPIPE */
	t->t_dcar->t_dflg |= F_PIPEOUT | (t->t_dflg &
	    (F_PIPEIN | F_AMPERSAND | F_STDERR | F_NOINTERRUPT | F_BACKQ));
	execute(t->t_dcar, wanttty, pipein, pv, do_glob);
	t->t_dcdr->t_dflg |= F_PIPEIN | (t->t_dflg &
	    (F_PIPEOUT | F_AMPERSAND | F_NOFORK | F_NOINTERRUPT | F_BACKQ));
	execute(t->t_dcdr, wanttty, pv, pipeout, do_glob);
#endif /* BACKPIPE */
	break;

    case NODE_LIST:
	if (t->t_dcar) {
	    t->t_dcar->t_dflg |= t->t_dflg & (F_NOINTERRUPT | F_BACKQ);
	    execute(t->t_dcar, wanttty, NULL, NULL, do_glob);
	    /*
	     * In strange case of A&B make a new job after A
	     */
	    if (t->t_dcar->t_dflg & F_AMPERSAND && t->t_dcdr &&
		(t->t_dcdr->t_dflg & F_AMPERSAND) == 0)
		pendjob();
	}
	if (t->t_dcdr) {
	    t->t_dcdr->t_dflg |= t->t_dflg &
		(F_NOFORK | F_NOINTERRUPT | F_BACKQ);
	    execute(t->t_dcdr, wanttty, NULL, NULL, do_glob);
	}
	break;

    case NODE_OR:
    case NODE_AND:
	if (t->t_dcar) {
	    t->t_dcar->t_dflg |= t->t_dflg & (F_NOINTERRUPT | F_BACKQ);
	    execute(t->t_dcar, wanttty, NULL, NULL, do_glob);
	    if ((getn(varval(STRstatus)) == 0) !=
		(t->t_dtyp == NODE_AND)) {
		return;
	    }
	}
	if (t->t_dcdr) {
	    t->t_dcdr->t_dflg |= t->t_dflg &
		(F_NOFORK | F_NOINTERRUPT | F_BACKQ);
	    execute(t->t_dcdr, wanttty, NULL, NULL, do_glob);
	}
	break;

    default:
	break;
    }
    /*
     * Fall through for all breaks from switch
     * 
     * If there will be no more executions of this command, flush all file
     * descriptors. Places that turn on the F_REPEAT bit are responsible for
     * doing donefds after the last re-execution
     */
    if (didfds && !(t->t_dflg & F_REPEAT))
	donefds();
}
Exemple #28
0
int main(int argc, char *argv[])
{
	lnode *conf;
	struct sigaction sa;
	int i;

#ifndef DEBUG
	/* Make sure we are root */
	if (getuid() != 0) {
		fprintf(stderr, "You must be root to run this program.\n");
		return 4;
	}
#endif
	set_aumessage_mode(MSG_SYSLOG, DBG_YES);

	/* Clear any procmask set by libev */
	sigfillset (&sa.sa_mask);
	sigprocmask (SIG_UNBLOCK, &sa.sa_mask, 0);

	/* Register sighandlers */
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);
	/* Ignore all signals by default */
	sa.sa_handler = SIG_IGN;
	for (i=1; i<NSIG; i++)
		sigaction(i, &sa, NULL);
	/* Set handler for the ones we care about */
	sa.sa_handler = term_handler;
	sigaction(SIGTERM, &sa, NULL);
	sa.sa_handler = hup_handler;
	sigaction(SIGHUP, &sa, NULL);
	sa.sa_handler = alarm_handler;
	sigaction(SIGALRM, &sa, NULL);
	sa.sa_handler = child_handler;
	sigaction(SIGCHLD, &sa, NULL);

	/* move stdin to its own fd */
	if (argc == 3 && strcmp(argv[1], "--input") == 0) 
		audit_fd = open(argv[2], O_RDONLY);
	else
		audit_fd = dup(0);
	if (audit_fd < 0) {
		syslog(LOG_ERR, "Failed setting up input, exiting");
		return 1;
	}

	/* Make all descriptors point to dev null */
	i = open("/dev/null", O_RDWR);
	if (i >= 0) {
		if (dup2(0, i) < 0 || dup2(1, i) < 0 || dup2(2, i) < 0) {
			syslog(LOG_ERR, "Failed duping /dev/null %s, exiting",
					strerror(errno));
			return 1;
		}
		close(i);
	} else {
		syslog(LOG_ERR, "Failed opening /dev/null %s, exiting",
					strerror(errno));
		return 1;
	}
	if (fcntl(audit_fd, F_SETFD, FD_CLOEXEC) < 0) {
		syslog(LOG_ERR, "Failed protecting input %s, exiting",
					strerror(errno));
		return 1;
	}

	/* init the daemon's config */
	if (load_config(&daemon_config, config_file))
		return 6;

	load_plugin_conf(&plugin_conf);

	/* if no plugins - exit */
	if (plist_count(&plugin_conf) == 0) {
		syslog(LOG_ERR, "No plugins found, exiting");
		return 0;
	}

	/* Plugins are started with the auditd priority */
	i = start_plugins(&plugin_conf);

	/* Now boost priority to make sure we are getting time slices */
	if (daemon_config.priority_boost != 0) {
		int rc;

		errno = 0;
		rc = nice((int)-daemon_config.priority_boost);
		if (rc == -1 && errno) {
			syslog(LOG_ERR, "Cannot change priority (%s)",
					strerror(errno));
			/* Stay alive as this is better than stopping */
		}
	}

	/* Let the queue initialize */
	init_queue(daemon_config.q_depth);
	syslog(LOG_NOTICE, 
		"audispd initialized with q_depth=%d and %d active plugins",
		daemon_config.q_depth, i);

	/* Tell it to poll the audit fd */
	if (add_event(audit_fd, process_inbound_event) < 0) {
		syslog(LOG_ERR, "Cannot add event, exiting");
		return 1;
	}

	/* Create inbound thread */
	pthread_create(&inbound_thread, NULL, inbound_thread_main, NULL); 

	/* Start event loop */
	while (event_loop()) {
		hup = 0;
		if (reconfigure() == 0) {
			syslog(LOG_INFO,
		"After reconfigure, there are no active plugins, exiting");
			break;
		}
	}

	/* Tell plugins we are going down */
	signal_plugins(SIGTERM);

	/* Cleanup builtin plugins */
	destroy_af_unix();
	destroy_syslog();

	/* Give it 5 seconds to clear the queue */
	alarm(5);
	pthread_join(inbound_thread, NULL);

	/* Release configs */
	plist_first(&plugin_conf);
	conf = plist_get_cur(&plugin_conf);
	while (conf) {
		free_pconfig(conf->p);
		conf = plist_next(&plugin_conf);
	}
	plist_clear(&plugin_conf);

	/* Cleanup the queue */
	destroy_queue();
	free_config(&daemon_config);
	
	return 0;
}
Exemple #29
0
int
main(int  argc, char  *argv[])
{
#define	 check(ol,al)		if (argv[i][ol] || \
				badarg(argc-i-1,argv+i+1,al)) \
				goto badopt
#define	 bool(olen,var)		switch (argv[i][olen]) { \
				case '\0': var = !var; break; \
				case 'y': case 'Y': case 't': case 'T': \
				case '+': case '1': var = 1; break; \
				case 'n': case 'N': case 'f': case 'F': \
				case '-': case '0': var = 0; break; \
				default: goto badopt; }
	char  *err;
	char  *recover = NULL;
	char  *outfile = NULL;
	char  *zfile = NULL;
	int  loadflags = ~IO_FILES;
	int  seqstart = 0;
	int  persist = 0;
	int  duped1 = -1;
	int  rval;
	int  i;
					/* record start time */
	tstart = time((time_t *)NULL);
					/* global program name */
	progname = argv[0] = fixargv0(argv[0]);
					/* option city */
	for (i = 1; i < argc; i++) {
						/* expand arguments */
		while ((rval = expandarg(&argc, &argv, i)) > 0)
			;
		if (rval < 0) {
			sprintf(errmsg, "cannot expand '%s'", argv[i]);
			error(SYSTEM, errmsg);
		}
		if (argv[i] == NULL || argv[i][0] != '-')
			break;			/* break from options */
		if (!strcmp(argv[i], "-version")) {
			puts(VersionID);
			quit(0);
		}
		if (!strcmp(argv[i], "-defaults") ||
				!strcmp(argv[i], "-help")) {
			printdefaults();
			quit(0);
		}
		rval = getrenderopt(argc-i, argv+i);
		if (rval >= 0) {
			i += rval;
			continue;
		}
		rval = getviewopt(&ourview, argc-i, argv+i);
		if (rval >= 0) {
			i += rval;
			continue;
		}
						/* rpict options */
		switch (argv[i][1]) {
		case 'v':				/* view file */
			if (argv[i][2] != 'f')
				goto badopt;
			check(3,"s");
			rval = viewfile(argv[++i], &ourview, NULL);
			if (rval < 0) {
				sprintf(errmsg,
				"cannot open view file \"%s\"",
						argv[i]);
				error(SYSTEM, errmsg);
			} else if (rval == 0) {
				sprintf(errmsg,
					"bad view file \"%s\"",
						argv[i]);
				error(USER, errmsg);
			}
			break;
		case 'p':				/* pixel */
			switch (argv[i][2]) {
			case 's':				/* sample */
				check(3,"i");
				psample = atoi(argv[++i]);
				break;
			case 't':				/* threshold */
				check(3,"f");
				maxdiff = atof(argv[++i]);
				break;
			case 'j':				/* jitter */
				check(3,"f");
				dstrpix = atof(argv[++i]);
				break;
			case 'a':				/* aspect */
				check(3,"f");
				pixaspect = atof(argv[++i]);
				break;
			case 'm':				/* motion */
				check(3,"f");
				mblur = atof(argv[++i]);
				break;
			case 'd':				/* aperture */
				check(3,"f");
				dblur = atof(argv[++i]);
				break;
			default:
				goto badopt;
			}
			break;
		case 'x':				/* x resolution */
			check(2,"i");
			hresolu = atoi(argv[++i]);
			break;
		case 'y':				/* y resolution */
			check(2,"i");
			vresolu = atoi(argv[++i]);
			break;
		case 'S':				/* slave index */
			check(2,"i");
			seqstart = atoi(argv[++i]);
			break;
		case 'o':				/* output file */
			check(2,"s");
			outfile = argv[++i];
			break;
		case 'z':				/* z file */
			check(2,"s");
			zfile = argv[++i];
			break;
		case 'r':				/* recover file */
			if (argv[i][2] == 'o') {		/* +output */
				check(3,"s");
				outfile = argv[i+1];
			} else
				check(2,"s");
			recover = argv[++i];
			break;
		case 't':				/* timer */
			check(2,"i");
			ralrm = atoi(argv[++i]);
			break;
#ifdef  PERSIST
		case 'P':				/* persist file */
			if (argv[i][2] == 'P') {
				check(3,"s");
				persist = PARALLEL;
			} else {
				check(2,"s");
				persist = PERSIST;
			}
			persistfile(argv[++i]);
			break;
#endif
		case 'w':				/* warnings */
			rval = erract[WARNING].pf != NULL;
			bool(2,rval);
			if (rval) erract[WARNING].pf = wputs;
			else erract[WARNING].pf = NULL;
			break;
		case 'e':				/* error file */
			check(2,"s");
			errfile = argv[++i];
			break;
		default:
			goto badopt;
		}
	}
	err = setview(&ourview);	/* set viewing parameters */
	if (err != NULL)
		error(USER, err);
					/* initialize object types */
	initotypes();
					/* initialize urand */
	if (rand_samp) {
		srandom((long)time(0));
		initurand(0);
	} else {
		srandom(0L);
		initurand(2048);
	}
					/* set up signal handling */
	sigdie(SIGINT, "Interrupt");
#ifdef SIGHUP
	sigdie(SIGHUP, "Hangup");
#endif
	sigdie(SIGTERM, "Terminate");
#ifdef SIGPIPE
	sigdie(SIGPIPE, "Broken pipe");
#endif
#ifdef SIGALRM
	sigdie(SIGALRM, "Alarm clock");
#endif
#ifdef	SIGXCPU
	sigdie(SIGXCPU, "CPU limit exceeded");
	sigdie(SIGXFSZ, "File size exceeded");
#endif
					/* open error file */
	if (errfile != NULL) {
		if (freopen(errfile, "a", stderr) == NULL)
			quit(2);
		fprintf(stderr, "**************\n*** PID %5d: ",
				getpid());
		printargs(argc, argv, stderr);
		putc('\n', stderr);
		fflush(stderr);
	}
#ifdef	NICE
	nice(NICE);			/* lower priority */
#endif
					/* get octree */
	if (i == argc)
		octname = NULL;
	else if (i == argc-1)
		octname = argv[i];
	else
		goto badopt;
	if (seqstart > 0 && octname == NULL)
		error(USER, "missing octree argument");
					/* set up output */
#ifdef  PERSIST
	if (persist) {
		if (recover != NULL)
			error(USER, "persist option used with recover file");
		if (seqstart <= 0)
			error(USER, "persist option only for sequences");
		if (outfile == NULL)
		duped1 = dup(fileno(stdout));	/* don't lose our output */
		openheader();
	} else
#endif
	if (outfile != NULL)
		openheader();
#ifdef	_WIN32
	SET_FILE_BINARY(stdout);
	if (octname == NULL)
		SET_FILE_BINARY(stdin);
#endif
	readoct(octname, loadflags, &thescene, NULL);
	nsceneobjs = nobjects;

	if (loadflags & IO_INFO) {	/* print header */
		printargs(i, argv, stdout);
		printf("SOFTWARE= %s\n", VersionID);
	}

	marksources();			/* find and mark sources */

	setambient();			/* initialize ambient calculation */

#ifdef  PERSIST
	if (persist) {
		fflush(stdout);
		if (outfile == NULL) {		/* reconnect stdout */
			dup2(duped1, fileno(stdout));
			close(duped1);
		}
		if (persist == PARALLEL) {	/* multiprocessing */
			preload_objs();		/* preload scene */
			shm_boundary = (char *)malloc(16);
			strcpy(shm_boundary, "SHM_BOUNDARY");
			while ((rval=fork()) == 0) {	/* keep on forkin' */
				pflock(1);
				pfhold();
				tstart = time((time_t *)NULL);
				ambsync();		/* load new values */
			}
			if (rval < 0)
				error(SYSTEM, "cannot fork child for persist function");
			pfdetach();		/* parent will run then exit */
		}
	}
runagain:
	if (persist) {
		if (outfile == NULL)			/* if out to stdout */
			dupheader();			/* send header */
		else					/* if out to file */
			duped1 = dup(fileno(stdout));	/* hang onto pipe */
	}
#endif
					/* batch render picture(s) */
	rpict(seqstart, outfile, zfile, recover);
					/* flush ambient file */
	ambsync();
#ifdef  PERSIST
	if (persist == PERSIST) {	/* first run-through */
		if ((rval=fork()) == 0) {	/* child loops until killed */
			pflock(1);
			persist = PCHILD;
		} else {			/* original process exits */
			if (rval < 0)
				error(SYSTEM, "cannot fork child for persist function");
			pfdetach();		/* parent exits */
		}
	}
	if (persist == PCHILD) {	/* wait for a signal then go again */
		if (outfile != NULL)
			close(duped1);		/* release output handle */
		pfhold();
		tstart = time((time_t *)NULL);	/* reinitialize */
		raynum = nrays = 0;
		goto runagain;
	}
#endif
	quit(0);

badopt:
	sprintf(errmsg, "command line error at '%s'", argv[i]);
	error(USER, errmsg);
	return 1; /* pro forma return */

#undef	check
#undef	bool
}
Exemple #30
0
int main(int argc, char *argv[]) {
	if (argc < 10) {
		// TODO: if argv > 3, assume pok[] is given, notifify parent.
		// usage() and a man-page (help2man) would not be bad, either :)
		return -1;
	}

	int pok[2];
	int pin[2];
	int pout[2];

	pok[0]  = atoi(argv[1]);
	pok[1]  = atoi(argv[2]);
	pin[0]  = atoi(argv[3]);
	pin[1]  = atoi(argv[4]);
	pout[0] = atoi(argv[5]);
	pout[1] = atoi(argv[6]);

	int stderr_mode = atoi(argv[7]);
	int nicelevel = atoi(argv[8]);

	/* vfork()ed child process - exec external process */
	close_fd(&pok[0]);
	fcntl(pok[1], F_SETFD, FD_CLOEXEC);

	close_fd(&pin[1]);
	if (pin[0] != STDIN_FILENO) {
		dup2(pin[0], STDIN_FILENO);
	}
	close_fd(&pin[0]);
	close_fd(&pout[0]);
	if (pout[1] != STDOUT_FILENO) {
		dup2(pout[1], STDOUT_FILENO);
	}

	if (stderr_mode == 2) {
		/* merge STDERR into output */
		if (pout[1] != STDERR_FILENO) {
			dup2(pout[1], STDERR_FILENO);
		}
	} else if (stderr_mode == 1) {
		/* ignore STDERR */
		close(STDERR_FILENO);
	} else {
		/* keep STDERR */
	}

	if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
		close_fd(&pout[1]);
	}

	if (nicelevel !=0) {
		nice(nicelevel);
	}

	/* copy current environment */
	char **envp = NULL;
	int i=0;
	envp = (char **) calloc(1, sizeof(char*));
	for (i=0;environ[i];++i) {
		envp[i] = strdup(environ[i]);
		envp = (char **) realloc(envp, (i+2) * sizeof(char*));
	}
	envp[i] = 0;

#ifdef HAVE_SIGSET
	sigset(SIGPIPE, SIG_DFL);
#else
	signal(SIGPIPE, SIG_DFL);
#endif

	/* all systems go */
	execve(argv[9], &argv[9], envp);

	/* if we reach here something went wrong.. */
	char buf = 0;
	(void) write(pok[1], &buf, 1 );
	close_fd(&pok[1]);

#ifdef __clang_analyzer__
	// the clang static analyzer warns about a memleak here,
	// but we don't care. The OS will clean up after us in a jiffy.
	for (i=0; envp && envp[i]; ++i) {
		free (envp[i]);
	}
	free (envp);
#endif
	return -1;
}