Exemplo n.º 1
0
void daemonize() {
	pid_t pid;
	if ((pid = fork()) < 0) {
		fprintf(stderr, "daemon can't fork\n");
		exit(1);
	} else if (pid != 0) {
		exit(0);
	}
	setsid();

	signal_handler(SIGHUP, SIG_IGN);
	signal_handler(SIGTERM, SIG_IGN);
	signal_handler(SIGPIPE, SIG_IGN);
}
Exemplo n.º 2
0
int		get_input(t_command *command,
			   t_uchar ret,
			   char **env)
{
  char		*input_raw;
  char		*input_clean;

  input_raw = get_input_raw(command, ret, env);
  if (input_raw == NULL && signal_handler(GETSIG, 0) != SIGINT)
    {
      input_clean = my_strdup("exit");
      if ((command->argv = parse_command(input_clean)) == NULL)
	return (EXIT_FAILURE);
      free(input_clean);
      return (EXIT_SUCCESS);
    }
  input_clean = my_epur_str(input_raw);
  free(input_raw);
  if (input_clean == NULL || input_clean[0] == '\0')
    {
      free(input_clean);
      return (EXIT_FAILURE);
    }
  if ((command->argv = parse_command(input_clean)) == NULL)
    return (EXIT_FAILURE);
  free(input_clean);
  command->argv_tmp = NULL;
  return (EXIT_SUCCESS);
}
Exemplo n.º 3
0
int main(int argc, char **argv)
{
    int i;
    char buffer[MAXBUFSIZE];
    int done=0;

    set_defaults();
    handle_args(argc, argv, 0);
    srand(time(NULL));

    if(num_clients < 1)
        FATALERR("More than 1 node is required to run\n");

    // Capture exit signals to safetly close the program
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGABRT, signal_handler);

    // If there was no ip address set in the command line, listen for a broadcast from the server
    if(server_addr.sin_addr.s_addr == 0)
    {
        setup_listen_socket();
        obtain_server();
    }

    // Attempt to create a TCP connection to the server
    if(!connectTCP())
        QUIT();

    send_data();

    signal_handler(0);
}
Exemplo n.º 4
0
int		main(int argc, char *argv[], char *envp[])
{
	t_key	*key;
	char	*user_input;
	int		retour;

	if (argc)
	{
		if (!envp || !*envp)
			envp = fill_empty_env(argv);
		key = env_str_to_list(envp);
		signal_handler();
		while (key)
		{
			draw_prompt(key);
			retour = get_next_line(0, &user_input);
			if (retour < 0 || parse_user_input(user_input, key))
				ft_putstr("Erreur");
			free(user_input);
			if (!retour)
				break ;
		}
	}
	return (0);
}
Exemplo n.º 5
0
int main()
{
	int  i;
	for (i=-5; i<5; i++)
		signal_handler(i);
	return 0;
}
Exemplo n.º 6
0
int		main(int argc, char **argv, char **environ)
{
  t_builtin_ptr	**builtins;
  t_command	command;
  t_uchar	ret;
  char		**env;

  (void)(argc + argv);
  ret = EXIT_SUCCESS;
  env = my_envcpy(environ);
  if (!(builtins = malloc(sizeof(t_builtin_ptr *) * (BUILTINS_NBR + 1)))
      || init_builtins(builtins) == 1)
    return (EXIT_FAILURE);
  while (true)
    {
      command.last_ret = ret;
      signal_handler(SETSIG, SIGINT_REGULAR);
      chkenv(&env);
      if (!get_input(&command, ret, env)
	  && !(ret = chck_command_logic(command)))
	ret = handle_command_logic(builtins, &env, command);
      my_free_2d_tab(command.argv);
    }
  return (EXIT_SUCCESS);
}
Exemplo n.º 7
0
/*
 * this function disables health-check servers so that the process will quickly be ignored
 * by load balancers. Note that if a proxy was already in the PAUSED state, then its grace
 * time will not be used since it would already not listen anymore to the socket.
 */
void soft_stop(void)
{
	struct proxy *p;
	struct peers *prs;

	stopping = 1;
	p = proxy;
	tv_update_date(0,1); /* else, the old time before select will be used */
	while (p) {
		if (p->state != PR_STSTOPPED) {
			Warning("Stopping %s %s in %d ms.\n", proxy_cap_str(p->cap), p->id, p->grace);
			send_log(p, LOG_WARNING, "Stopping %s %s in %d ms.\n", proxy_cap_str(p->cap), p->id, p->grace);
			p->stop_time = tick_add(now_ms, p->grace);
		}
		if (p->table.size && p->table.sync_task)
			 task_wakeup(p->table.sync_task, TASK_WOKEN_MSG);

		/* wake every proxy task up so that they can handle the stopping */
		task_wakeup(p->task, TASK_WOKEN_MSG);
		p = p->next;
	}

	prs = peers;
	while (prs) {
		stop_proxy((struct proxy *)prs->peers_fe);
		prs = prs->next;
	}
	/* signal zero is used to broadcast the "stopping" event */
	signal_handler(0);
}
Exemplo n.º 8
0
int		main(int argc, char *argv[], char *envp[])
{
	char	**current_env;
	char	*user_input;
	int		retour;

	if (argc)
	{
		if (!envp || !*envp)
			current_env = fill_empty_env(argv);
		else
			current_env = ft_dup_char_tab(envp);
		signal_handler();
		while (current_env)
		{
			draw_prompt(current_env);
			retour = get_next_line(0, &user_input);
			if (retour < 0 || parse_user_input(user_input, current_env))
				ft_putstr("Erreur");
			free(user_input);
			if (!retour)
				break ;
		}
	}
	return (0);
}
Exemplo n.º 9
0
Arquivo: sdiff.c Projeto: 0mp/freebsd
static void
trapsigs (void)
{
  int i;

#if HAVE_SIGACTION
  catchaction.sa_flags = SA_RESTART;
  sigemptyset (&catchaction.sa_mask);
  for (i = 0;  i < NUM_SIGS;  i++)
    sigaddset (&catchaction.sa_mask, sigs[i]);
#endif

  for (i = 0;  i < NUM_SIGS;  i++)
    {
#if HAVE_SIGACTION
      sigaction (sigs[i], 0, &initial_action[i]);
#else
      initial_action[i] = signal (sigs[i], SIG_IGN);
#endif
      if (initial_handler (i) != SIG_IGN)
	signal_handler (sigs[i], catchsig);
    }

#ifdef SIGCHLD
  /* System V fork+wait does not work if SIGCHLD is ignored.  */
  signal (SIGCHLD, SIG_DFL);
#endif

  sigs_trapped = true;
}
Exemplo n.º 10
0
/* Can I use safe functions in a interupt handler? */
static void sigsegv_handler(int signum)
{
	if (current_engine.stack_protected) {
		unprotect_stack(&current_engine);
		signal_handler(ALSSIG_STACK_OVERFLOW);
	} else {
		signal(signum, SIG_DFL);
	}
}
Exemplo n.º 11
0
/*
  signal handler with SA_SIGINFO - redirects to registered signals
*/
static void signal_handler_info(int signum, siginfo_t *info, void *uctx)
{
	uint32_t count = sig_count(sig_state->signal_count[signum]);
	sig_state->sig_info[signum][count] = *info;

	signal_handler(signum);

	/* handle SA_SIGINFO */
	if (count+1 == SA_INFO_QUEUE_COUNT) {
		/* we've filled the info array - block this signal until
		   these ones are delivered */
		sigset_t set;
		sigemptyset(&set);
		sigaddset(&set, signum);
		sigprocmask(SIG_BLOCK, &set, NULL);
		SIG_INCREMENT(sig_state->sig_blocked[signum]);
	}
}
Exemplo n.º 12
0
static DBusHandlerResult
message_filter(DBusConnection *conn, DBusMessage *msg, void *data)
{
	lua_State *S = data;

	(void)conn;

	switch (dbus_message_get_type(msg)) {
	case DBUS_MESSAGE_TYPE_SIGNAL:
		return signal_handler(S, msg);
	case DBUS_MESSAGE_TYPE_METHOD_CALL:
		return method_call_handler(S, msg);
	}

	lem_debug("Hmm.. received %s message",
	          dbus_message_type_to_string(dbus_message_get_type(msg)));
	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
Exemplo n.º 13
0
int main(int argc, char** argv){
	assert(argc == 2);
	f_path = argv[1];
	if (!reg_signals()) return 0;

	fifo = open_write_fifo(f_path);
	assert(fifo != 0);

	char line[1024];
	while (fgets(line, 1024, stdin) != NULL) {
		if (write(fifo, line, strlen(line)) == -1){
			printf("Error writing to FIFO: %s\n", strerror(errno));
			return 0;
		}
	}

	signal_handler(SIGTERM);
	return 0;
}
Exemplo n.º 14
0
static void server_mainloop( ) {
  static time_t ot_last_clean_time;
  time_t        next_timeout_check = g_now + OT_CLIENT_TIMEOUT_CHECKINTERVAL;
  struct        iovec *iovector;
  int           iovec_entries;

  for( ; ; ) {
    int64 i;

    io_wait();

    while( ( i = io_canread( ) ) != -1 ) {
      const void *cookie = io_getcookie( i );
      if( cookie == FLAG_TCP )
        handle_accept( i );
      else if( cookie == FLAG_UDP )
        handle_udp4( i );
      else
        handle_read( i );
    }

    while( ( i = mutex_workqueue_popresult( &iovec_entries, &iovector ) ) != -1 )
      http_sendiovecdata( i, iovec_entries, iovector );

    while( ( i = io_canwrite( ) ) != -1 )
      handle_write( i );

    if( g_now > next_timeout_check ) {
      while( ( i = io_timeouted() ) != -1 )
        handle_dead( i );
      next_timeout_check = g_now + OT_CLIENT_TIMEOUT_CHECKINTERVAL;
    }

    /* See if we need to move our pools */
    if( NOW != ot_last_clean_time ) {
      ot_last_clean_time = NOW;
      clean_all_torrents();
    }

    /* Enforce setting the clock */
    signal_handler( SIGALRM );
  }
}
Exemplo n.º 15
0
bool		start_server(t_server *server)
{
  int		size[2];

  size[0] = server->args->x;
  size[1] = server->args->y;
  signal_handler();
  if (init_server_struct(server) == false)
    return (false);
  if (init_server(server) == false)
    return (false);
  init_map(&server->map, size);
  server->fd_type[server->socket] = FD_SERVER;
  server->exec[server->socket] = &add_client;
  spawn_res(&server->map);
  if (handler_connection(server) == false)
    return (false);
  return (true);
}
Exemplo n.º 16
0
Arquivo: mce.c Projeto: spiiroin/mce
/** GIO callback for reading signals from pipe
 *
 * @param channel   io channel for signal pipe
 * @param condition call reason
 * @param data      user data
 *
 * @return TRUE (or aborts on error)
 */
static gboolean mce_rx_signal_cb(GIOChannel *channel,
				 GIOCondition condition, gpointer data)
{
	// we just want the cb ...
	(void)channel; (void)condition; (void)data;

	int sig = 0;
	int got = TEMP_FAILURE_RETRY(read(signal_pipe[0], &sig, sizeof sig));

	if( got != sizeof sig ) {
		mce_abort();
	}

	/* handle the signal */
	signal_handler(sig);

	/* keep the io watch */
	return TRUE;
}
bool InitSignal(void (*func)(int))
{
	if (regist_signal_stack() == false)
		return false;

	struct sigaction sa;
	memset(&sa, 0, sizeof(sa));
	sigemptyset(&sa.sa_mask);

	for (unsigned i = 0; exceptionSignals[i] != -1; ++i)
		sigaddset(&sa.sa_mask, exceptionSignals[i]);

	sa.sa_sigaction = sig_handler;
	sa.sa_flags = SA_ONSTACK | SA_SIGINFO;

	for (unsigned i = 0; exceptionSignals[i] != -1; ++i)
	{
		struct sigaction* old = new struct sigaction;
		if (sigaction( exceptionSignals[i], &sa, old ) == -1)
		{
			LOG_ERROR("sigaction() error : %d", exceptionSignals[i]);
			return false;
		}
	}

	local_func = func;

	sigset_t sigset;
	sigemptyset(&sigset);
	sigaddset(&sigset, SIGTERM);

	pthread_sigmask(SIG_BLOCK, &sigset, NULL);

	boost::thread signal_handler(thrad_signal_handler);

	return true;
}
Exemplo n.º 18
0
void* sigmgr_thread(){
    sigset_t   waitset;
    //siginfo_t  info;
    int        sig;
    int        rc;
    pthread_t  ppid = pthread_self();

    pthread_detach(ppid);

    sigemptyset(&waitset);
    sigaddset(&waitset,SIGTERM);

    while (1)  {
        rc = sigwait(&waitset, &sig);
        if (rc != -1) {
#ifdef MYDEBUG
            printf("sigwait() fetch the signal - %d\n", sig);
#endif
            signal_handler(sig);
        } else {
            printf("sigwaitinfo() returned err: %d; %s\n", errno, strerror(errno));
        }
    }
}
Exemplo n.º 19
0
int child_t::child_prefork_init() {

	status = CLD_UNKNOWN_STATUS;

	// PREPARE CHILD
	inp.reopen();
	outp.reopen();
	errp.reopen();

	// prevent fork-loop
	//if (time(NULL)-last_restart_time < MIN_FORK_DELTA_T ) {
	//	fprintf(stderr, "%ld %s > info='child respawn too quick -- aborting.'\n", time(NULL), clientid);
	//	return -1;
	//}

	// catch SIGCHLD
	signal_block(SIGCHLD);	// do not interrupt parent to early
	if ( signal_handler(SIGCHLD, sigchld_handler) < 0) {
		fprintf(stderr, "ERROR: Could not retister SIGCHLD handler. Bailing out.\n");
		return 1;
	}

	return 0;
}
Exemplo n.º 20
0
static gboolean
sigterm_handler_cb (MainData *data)
{
	signal_handler (SIGTERM, data);
	return FALSE;
}
Exemplo n.º 21
0
Arquivo: sdiff.c Projeto: 0mp/freebsd
int
main (int argc, char *argv[])
{
  int opt;
  char const *prog;

  exit_failure = EXIT_TROUBLE;
  initialize_main (&argc, &argv);
  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
  c_stack_action (cleanup);

  prog = getenv ("EDITOR");
  if (prog)
    editor_program = prog;

  diffarg (DEFAULT_DIFF_PROGRAM);

  /* parse command line args */
  while ((opt = getopt_long (argc, argv, "abBdEHiI:lo:stvw:W", longopts, 0))
	 != -1)
    {
      switch (opt)
	{
	case 'a':
	  diffarg ("-a");
	  break;

	case 'b':
	  diffarg ("-b");
	  break;

	case 'B':
	  diffarg ("-B");
	  break;

	case 'd':
	  diffarg ("-d");
	  break;

	case 'E':
	  diffarg ("-E");
	  break;

	case 'H':
	  diffarg ("-H");
	  break;

	case 'i':
	  diffarg ("-i");
	  break;

	case 'I':
	  diffarg ("-I");
	  diffarg (optarg);
	  break;

	case 'l':
	  diffarg ("--left-column");
	  break;

	case 'o':
	  output = optarg;
	  break;

	case 's':
	  suppress_common_lines = true;
	  break;

	case 't':
	  diffarg ("-t");
	  break;

	case 'v':
	  version_etc (stdout, "sdiff", PACKAGE_NAME, PACKAGE_VERSION,
		       "Thomas Lord", (char *) 0);
	  check_stdout ();
	  return EXIT_SUCCESS;

	case 'w':
	  diffarg ("-W");
	  diffarg (optarg);
	  break;

	case 'W':
	  diffarg ("-w");
	  break;

	case DIFF_PROGRAM_OPTION:
	  diffargv[0] = optarg;
	  break;

	case HELP_OPTION:
	  usage ();
	  check_stdout ();
	  return EXIT_SUCCESS;

	case STRIP_TRAILING_CR_OPTION:
	  diffarg ("--strip-trailing-cr");
	  break;

	case TABSIZE_OPTION:
	  diffarg ("--tabsize");
	  diffarg (optarg);
	  break;

	default:
	  try_help (0, 0);
	}
    }

  if (argc - optind != 2)
    {
      if (argc - optind < 2)
	try_help ("missing operand after `%s'", argv[argc - 1]);
      else
	try_help ("extra operand `%s'", argv[optind + 2]);
    }

  if (! output)
    {
      /* easy case: diff does everything for us */
      if (suppress_common_lines)
	diffarg ("--suppress-common-lines");
      diffarg ("-y");
      diffarg ("--");
      diffarg (argv[optind]);
      diffarg (argv[optind + 1]);
      diffarg (0);
      execvp (diffargv[0], (char **) diffargv);
      perror_fatal (diffargv[0]);
    }
  else
    {
      char const *lname, *rname;
      FILE *left, *right, *out, *diffout;
      bool interact_ok;
      struct line_filter lfilt;
      struct line_filter rfilt;
      struct line_filter diff_filt;
      bool leftdir = diraccess (argv[optind]);
      bool rightdir = diraccess (argv[optind + 1]);

      if (leftdir & rightdir)
	fatal ("both files to be compared are directories");

      lname = expand_name (argv[optind], leftdir, argv[optind + 1]);
      left = ck_fopen (lname, "r");
      rname = expand_name (argv[optind + 1], rightdir, argv[optind]);
      right = ck_fopen (rname, "r");
      out = ck_fopen (output, "w");

      diffarg ("--sdiff-merge-assist");
      diffarg ("--");
      diffarg (argv[optind]);
      diffarg (argv[optind + 1]);
      diffarg (0);

      trapsigs ();

#if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
      {
	size_t cmdsize = 1;
	char *p, *command;
	int i;

	for (i = 0;  diffargv[i];  i++)
	  cmdsize += quote_system_arg (0, diffargv[i]) + 1;
	command = p = xmalloc (cmdsize);
	for (i = 0;  diffargv[i];  i++)
	  {
	    p += quote_system_arg (p, diffargv[i]);
	    *p++ = ' ';
	  }
	p[-1] = 0;
	errno = 0;
	diffout = popen (command, "r");
	if (! diffout)
	  perror_fatal (command);
	free (command);
      }
#else
      {
	int diff_fds[2];
# if HAVE_WORKING_VFORK
	sigset_t procmask;
	sigset_t blocked;
# endif

	if (pipe (diff_fds) != 0)
	  perror_fatal ("pipe");

# if HAVE_WORKING_VFORK
	/* Block SIGINT and SIGPIPE.  */
	sigemptyset (&blocked);
	sigaddset (&blocked, SIGINT);
	sigaddset (&blocked, SIGPIPE);
	sigprocmask (SIG_BLOCK, &blocked, &procmask);
# endif
	diffpid = vfork ();
	if (diffpid < 0)
	  perror_fatal ("fork");
	if (! diffpid)
	  {
	    /* Alter the child's SIGINT and SIGPIPE handlers;
	       this may munge the parent.
	       The child ignores SIGINT in case the user interrupts the editor.
	       The child does not ignore SIGPIPE, even if the parent does.  */
	    if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
	      signal_handler (SIGINT, SIG_IGN);
	    signal_handler (SIGPIPE, SIG_DFL);
# if HAVE_WORKING_VFORK
	    /* Stop blocking SIGINT and SIGPIPE in the child.  */
	    sigprocmask (SIG_SETMASK, &procmask, 0);
# endif
	    close (diff_fds[0]);
	    if (diff_fds[1] != STDOUT_FILENO)
	      {
		dup2 (diff_fds[1], STDOUT_FILENO);
		close (diff_fds[1]);
	      }

	    execvp (diffargv[0], (char **) diffargv);
	    _exit (errno == ENOENT ? 127 : 126);
	  }

# if HAVE_WORKING_VFORK
	/* Restore the parent's SIGINT and SIGPIPE behavior.  */
	if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
	  signal_handler (SIGINT, catchsig);
	if (initial_handler (handler_index_of_SIGPIPE) != SIG_IGN)
	  signal_handler (SIGPIPE, catchsig);
	else
	  signal_handler (SIGPIPE, SIG_IGN);

	/* Stop blocking SIGINT and SIGPIPE in the parent.  */
	sigprocmask (SIG_SETMASK, &procmask, 0);
# endif

	close (diff_fds[1]);
	diffout = fdopen (diff_fds[0], "r");
	if (! diffout)
	  perror_fatal ("fdopen");
      }
#endif

      lf_init (&diff_filt, diffout);
      lf_init (&lfilt, left);
      lf_init (&rfilt, right);

      interact_ok = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);

      ck_fclose (left);
      ck_fclose (right);
      ck_fclose (out);

      {
	int wstatus;
	int werrno = 0;

#if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
	wstatus = pclose (diffout);
	if (wstatus == -1)
	  werrno = errno;
#else
	ck_fclose (diffout);
	while (waitpid (diffpid, &wstatus, 0) < 0)
	  if (errno == EINTR)
	    checksigs ();
	  else
	    perror_fatal ("waitpid");
	diffpid = 0;
#endif

	if (tmpname)
	  {
	    unlink (tmpname);
	    tmpname = 0;
	  }

	if (! interact_ok)
	  exiterr ();

	check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
	untrapsig (0);
	checksigs ();
	exit (WEXITSTATUS (wstatus));
      }
    }
  return EXIT_SUCCESS;			/* Fool `-Wall'.  */
}
Exemplo n.º 22
0
int main(int argc, char *argv[])
{
   /*
    * Alloc the global structures
    * We can access these structs via the macro in ec_globals.h
    */
        
   globals_alloc();
  
   GBL_PROGRAM = strdup(EC_PROGRAM);
   GBL_VERSION = strdup(EC_VERSION);
   SAFE_CALLOC(GBL_DEBUG_FILE, strlen(EC_PROGRAM) + strlen("-") + strlen(EC_VERSION) + strlen("_debug.log") + 1, sizeof(char));
   sprintf(GBL_DEBUG_FILE, "%s-%s_debug.log", GBL_PROGRAM, EC_VERSION);
   
   DEBUG_INIT();
   DEBUG_MSG("main -- here we go !!");

   /* initialize the filter mutex */
   filter_init_mutex();
   
   /* register the main thread as "init" */
   ec_thread_register(EC_PTHREAD_SELF, "init", "initialization phase");
   
   /* activate the signal handler */
   signal_handler();
   
   /* ettercap copyright */
   fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n", 
         GBL_PROGRAM, GBL_VERSION, EC_COPYRIGHT, EC_AUTHORS);
   
   /* getopt related parsing...  */
   parse_options(argc, argv);

   /* check the date */
   time_check();

   /* load the configuration file */
   load_conf();
  
   /* 
    * get the list of available interfaces 
    * 
    * this function will not return if the -I option was
    * specified on command line. it will instead print the
    * list and exit
    */
   capture_getifs();
   
   /* initialize the user interface */
   ui_init();
   
   /* initialize the network subsystem */
   network_init();
   
   /* 
    * always disable the kernel ip forwarding (except when reading from file).
    * the forwarding will be done by ettercap.
    */
   if(!GBL_OPTIONS->read && !GBL_OPTIONS->unoffensive && !GBL_OPTIONS->only_mitm) {
      disable_ip_forward();
	
#ifdef OS_LINUX
      if (!GBL_OPTIONS->read)
      	disable_interface_offload();
#endif
      /* binds ports and set redirect for ssl wrapper */
      if(GBL_SNIFF->type == SM_UNIFIED && GBL_OPTIONS->ssl_mitm)
         ssl_wrap_init();
   }
   
   /* 
    * drop root privileges 
    * we have already opened the sockets with high privileges
    * we don't need anymore root privs.
    */
   drop_privs();

/***** !! NO PRIVS AFTER THIS POINT !! *****/

   /* load all the plugins */
   plugin_load_all();

   /* print how many dissectors were loaded */
   conf_dissectors();
   
   /* load the mac-fingerprints */
   manuf_init();

   /* load the tcp-fingerprints */
   fingerprint_init();
   
   /* load the services names */
   services_init();
   
   /* load http known fileds for user/pass */
   http_fields_init();

#ifdef HAVE_EC_LUA
   /* Initialize lua */
   ec_lua_init();
#endif

   /* set the encoding for the UTF-8 visualization */
   set_utf8_encoding((u_char*)GBL_CONF->utf8_encoding);
  
   /* print all the buffered messages */
   if (GBL_UI->type == UI_TEXT)
      USER_MSG("\n");
   
   ui_msg_flush(MSG_ALL);

/**** INITIALIZATION PHASE TERMINATED ****/
   
   /* 
    * we are interested only in the mitm attack i
    * if entered, this function will not return...
    */
   if (GBL_OPTIONS->only_mitm)
      only_mitm();
   
   /* create the dispatcher thread */
   ec_thread_new("top_half", "dispatching module", &top_half, NULL);

   /* this thread becomes the UI then displays it */
   ec_thread_register(EC_PTHREAD_SELF, GBL_PROGRAM, "the user interface");
   ui_start();

/******************************************** 
 * reached only when the UI is shutted down 
 ********************************************/

   /* Call all the proper stop methods to ensure
    * that no matter what UI was selected, everything is 
    * turned off gracefully */
   clean_exit(0);

   return 0; //Never reaches here
}
Exemplo n.º 23
0
static int message_thread()
{
    rtapi_msgheader_t *msg;
    size_t msg_size;
    size_t payload_length;
    int retval;
    char *cp;
    int sigfd;
    sigset_t sigset;

    // sigset of all the signals that we're interested in
    retval = sigemptyset(&sigset);        assert(retval == 0);
    retval = sigaddset(&sigset, SIGINT);  assert(retval == 0);
    retval = sigaddset(&sigset, SIGKILL); assert(retval == 0);
    retval = sigaddset(&sigset, SIGTERM); assert(retval == 0);
    retval = sigaddset(&sigset, SIGSEGV); assert(retval == 0);
    retval = sigaddset(&sigset, SIGFPE);  assert(retval == 0);

    // block the signals in order for signalfd to receive them
    retval = sigprocmask(SIG_BLOCK, &sigset, NULL); assert(retval == 0);

    sigfd = signalfd(-1, &sigset, 0);
    assert(sigfd != -1);

    struct pollfd pfd[1];
    int ret;

    pfd[0].fd = sigfd;
    pfd[0].events = POLLIN | POLLERR | POLLHUP;

    global_data->magic = GLOBAL_READY;

    do {
	if (global_data->rtapi_app_pid == 0) {
	    syslog_async(LOG_ERR,
		   "msgd:%d: rtapi_app exit detected - shutting down",
		   rtapi_instance);
	    msgd_exit++;
	}
	while ((retval = record_read(&rtapi_msg_buffer,
					   (const void **) &msg, &msg_size)) == 0) {
	    payload_length = msg_size - sizeof(rtapi_msgheader_t);

	    switch (msg->encoding) {
	    case MSG_ASCII:
		// strip trailing newlines
		while ((cp = strrchr(msg->buf,'\n')))
		    *cp = '\0';
		syslog_async(rtapi2syslog(msg->level), "%s:%d:%s %.*s",
		       msg->tag, msg->pid, origins[msg->origin],
		       (int) payload_length, msg->buf);
		break;
	    case MSG_STASHF:
		break;
	    case MSG_PROTOBUF:
		break;
	    default: ;
		// whine
	    }
	    record_shift(&rtapi_msg_buffer);
	    msg_poll = msg_poll_min;
	}

	ret = poll(pfd, 1, msg_poll);
	if (ret < 0) {
	    syslog_async(LOG_ERR, "msgd:%d: poll(): %s - shutting down\n",
		   rtapi_instance, strerror(errno));
	    msgd_exit++;
	} else if (pfd[0].revents & POLLIN) { // signal received
	    struct signalfd_siginfo info;
	    size_t bytes = read(sigfd, &info, sizeof(info));
	    assert(bytes == sizeof(info));
	    signal_handler(info.ssi_signo);
	}
	
	msg_poll += msg_poll_inc;
	if (msg_poll > msg_poll_max)
	    msg_poll = msg_poll_max;

    } while (!msgd_exit);

    return 0;
}
Exemplo n.º 24
0
int
main (int argc, char *argv[])
{

//////////////////////////////////////////////
//will be removed
//	sample_rate=44100;
	sample_rate=48000;
//	period_size=2048;
	period_size=4096;
//	period_size=256;
	//period_size=128;
	bytes_per_sample=4;

	//osc
	const char *listenPort;

	//command line options parsing
	//http://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html
	static struct option long_options[] =
	{
		{"help",	no_argument,		0, 'h'},
		{"version",     no_argument,            0, 'v'},
		{"loinfo",      no_argument,            0, 'x'},
		{"out",		required_argument, 	0, 'o'},
		{"offset",	required_argument, 	0, 'f'},
		{"16",          no_argument,            0, 'y'},
		{"max",		required_argument,	0, 'm'},//max (allocate) buffer
		{"update",	required_argument,	0, 'u'},//screen info update every nth cycle
		{"limit",	required_argument,	0, 'l'},//test, stop after n processed
		{0, 0, 0, 0}
	};

	//print program header
	if(argc>1 && strcmp(argv[1],"--version"))
	{
		print_header("audio_post_send");
	}

	if (argc - optind < 1)
	{
		fprintf (stderr, "Missing arguments, see --help.\n\n");
		exit(1);
	}

	int opt;
 	//do until command line options parsed
	while (1)
	{
		/* getopt_long stores the option index here. */
		int option_index = 0;

		opt = getopt_long (argc, argv, "", long_options, &option_index);

		/* Detect the end of the options. */
		if (opt == -1)
		{
			break;
		}
		switch (opt)
		{
			case 0:

			 /* If this option set a flag, do nothing else now. */
			if (long_options[option_index].flag != 0)
			{
				break;
			}

			case 'h':
				print_help();
				break;

			case 'v':
				print_version();
				break;

			case 'x':
				check_lo_props(1);
				return 1;

			case 'o':
				output_port_count=atoi(optarg);

				if(output_port_count>max_channel_count)
				{
					fprintf(stderr,"*** limiting playback ports to %d, sry\n",max_channel_count);
					output_port_count=max_channel_count;
				}
				port_count=fmin(input_port_count,output_port_count);
				break;

			case 'f':
				channel_offset=atoi(optarg);
				break;

			case 'm':
				//min 1 MB
				max_buffer_size=fmax(1,(uint64_t)atoll(optarg)*1000*1000);
				break;

			case 'u':
				update_display_every_nth_cycle=fmax(1,(uint64_t)atoll(optarg));
				break;

			case 'l':
				receive_max=fmax(1,(uint64_t)atoll(optarg));
				test_mode=1;
				fprintf(stderr,"*** limiting number of messages: %" PRId64 "\n",receive_max);

				break;

			case '?': //invalid commands
				/* getopt_long already printed an error message. */
				fprintf (stderr, "Wrong arguments, see --help.\n\n");
				exit(1);

				break;
 	 
			default:
				break;
		 } //end switch op
	}//end while(1)

	//remaining non optional parameters listening port, remote host, remote port
	if(argc-optind != 3)
	{
		fprintf (stderr, "Wrong arguments, see --help.\n\n");
		exit(1);
	}

	if(check_lo_props(0)>0)
	{
		return 1;
	}

	if(have_libjack()!=0)
	{
		fprintf(stderr,"/!\\ libjack not found (JACK not installed?). this is fatal: audio_post_send needs JACK to run.\n");
		//io_quit("nolibjack");
		exit(1);
	}

	listenPort=argv[optind];

	//tcp target
	remote_tcp_host=argv[optind+1];
	remote_tcp_port=argv[optind+2];

	loa_tcp = lo_address_new_with_proto(LO_TCP, remote_tcp_host, remote_tcp_port);

	//initialize time
	gettimeofday(&tv, NULL);
	tt_prev.sec=tv.tv_sec;
	tt_prev.frac=tv.tv_usec;

	//print startup info

	fprintf(stderr,"listening on UDP port: %s\n",listenPort);
	//udp/tcp use the same port for now
	fprintf(stderr,"started TCP server on port: %s\n",listenPort);

	fprintf(stderr,"channels (forward): %d\n",output_port_count);
	fprintf(stderr,"channel offset: %d\n",channel_offset);

	fprintf(stderr, "TCP target: %s:%s\n",remote_tcp_host,remote_tcp_port);

	fprintf(stderr, "period size (TCP forward): %d samples\n",period_size);

	fprintf(stderr, "delay between TCP sends: %d ms\n",delay_between_tcp_sends);
	fprintf(stderr, "delay between TCP retries on broken connection: %d ms\n",delay_between_tcp_retries);

	//ringbuffer size bytes
	uint64_t rb_size;

	//use as given via param --max or:
	if(max_buffer_size==0)
	{
		//default
		//10 MB           .  .  
		max_buffer_size=10000000;
	}

	//
	rb_size=max_buffer_size;

	fprintf(stderr,"allocated buffer size: %" PRId64 " bytes (%.2f MB)\n",max_buffer_size,(float)max_buffer_size/1000/1000);

	//====================================
	//main ringbuffer osc blobs -> jack output
	rb = rb_new (rb_size);
	//helper ringbuffer: used when remote period size < local period size
	rb_helper = rb_new (rb_size);

	if(rb==NULL)
	{
		fprintf(stderr,"could not create a ringbuffer with that size.\n");
		fprintf(stderr,"try --max <smaller size>.\n");
		exit(1);
	}

	/* install a signal handler to properly quits jack client */
#ifndef _WIN
	signal(SIGQUIT, signal_handler);
	signal(SIGHUP, signal_handler);
#endif
	signal(SIGTERM, signal_handler);
	signal(SIGINT, signal_handler);

	//add osc hooks & start UDP server
	registerOSCMessagePatterns(listenPort);
	lo_server_thread_start(lo_st);

	//start TCP server, for forwarding to final receiver
	lo_st_tcp = lo_server_thread_new_with_proto(listenPort, LO_TCP, error);
	lo_server_thread_start(lo_st_tcp);

	fflush(stderr);

	/* keep running until the Ctrl+C */
	while(1) 
	{
		//possibly clean shutdown without any glitches
		if(shutdown_in_progress==1)
		{
			signal_handler(42);
		}

		//if tcp message could not be sent
		if(process()<0)
		{
			//wait x and update info
			int i;
			for(i=0;i<delay_between_tcp_retries;i++)
			{
				usleep(1000);
				print_info();
			}
		}
		else
		{
			//wait y and update info
			int i;
			for(i=0;i<delay_between_tcp_sends;i++)
			{
				usleep(1000);
				print_info();
			}
		}
	}
	exit (0);
}
Exemplo n.º 25
0
int
admin_handler()
{
	int so2;
	struct sockaddr_storage from;
	socklen_t fromlen = sizeof(from);
	struct admin_com com;
	char *combuf = NULL;
	pid_t pid = -1;
	int len, error = -1;

	so2 = accept(lcconf->sock_admin, (struct sockaddr *)&from, &fromlen);
	if (so2 < 0) {
		plog(LLV_ERROR, LOCATION, NULL,
			"failed to accept admin command: %s\n",
			strerror(errno));
		return -1;
	}

	/* get buffer length */
	while ((len = recv(so2, (char *)&com, sizeof(com), MSG_PEEK)) < 0) {
		if (errno == EINTR)
			continue;
		plog(LLV_ERROR, LOCATION, NULL,
			"failed to recv admin command: %s\n",
			strerror(errno));
		goto end;
	}

	/* sanity check */
	if (len < sizeof(com)) {
		plog(LLV_ERROR, LOCATION, NULL,
			"invalid header length of admin command\n");
		goto end;
	}

	/* get buffer to receive */
	if ((combuf = racoon_malloc(com.ac_len)) == 0) {
		plog(LLV_ERROR, LOCATION, NULL,
			"failed to alloc buffer for admin command\n");
		goto end;
	}

	/* get real data */
	while ((len = recv(so2, combuf, com.ac_len, 0)) < 0) {
		if (errno == EINTR)
			continue;
		plog(LLV_ERROR, LOCATION, NULL,
			"failed to recv admin command: %s\n",
			strerror(errno));
		goto end;
	}

	if (com.ac_cmd == ADMIN_RELOAD_CONF) {
		/* reload does not work at all! */
		signal_handler(SIGHUP);
		goto end;
	}

	error = admin_process(so2, combuf);

    end:
	(void)close(so2);
	if (combuf)
		racoon_free(combuf);

	/* exit if child's process. */
	if (pid == 0 && !f_foreground)
		exit(error);

	return error;
}
Exemplo n.º 26
0
void process(int flags)
{
    char *interface=NULL;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program prog;
	bpf_u_int32 network, netmask;
	char *filter=NULL;
	int flagdef;

	filter="tcp";

	signal(SIGHUP, SIG_IGN);
	signal(SIGINT, signal_handler);
	signal(SIGQUIT, signal_handler);
	signal(SIGTERM, signal_handler);

	/* Attempt to find the interface */
	interface=pcap_lookupdev(errbuf);
	if(interface==NULL) {
	    fprintf(stderr, "pcap_lookupdev: %s\n", errbuf);
		exit(-1);
	}

	if(pcap_lookupnet(interface, &network, &netmask, errbuf) < 0) {
	    fprintf(stderr, "pcap_lookupnet: %s\n", errbuf);
		exit(-1);
	}

	if(flags&FLAG_BIT(FLAG_PROMISC)) /* find out if we want to be promisc */
		flagdef=1;
	else
	    flagdef=0;

	pcap_socket=pcap_open_live(interface, 1024, flagdef, 1024, errbuf);

	if(pcap_socket==NULL) {
	    fprintf(stderr, "pcap_open_live: %s\n", errbuf);
		exit(-1);
	}

	switch(pcap_datalink(pcap_socket)) {
	    case DLT_EN10MB:
		    dlt_len=14;
			break;
	    case DLT_SLIP:
		    dlt_len=16;
			break;
		case DLT_PPP:
			dlt_len=4;
		    break;
		case DLT_FDDI:
			fprintf(stderr, "Sorry, can't do FDDI\n");
			signal_handler(-1);
			break;
	    default:
			dlt_len=4;
	}

	if(pcap_compile(pcap_socket, &prog, filter, 1, netmask) < 0) {
	    fprintf(stderr, "pcap_compile: %s\n", errbuf);
		signal_handler(-1);
	}

	if(pcap_setfilter(pcap_socket, &prog) < 0) {
	    fprintf(stderr, "pcap_setfilter: %s\n", errbuf);
		signal_handler(-1);
	}

	fprintf(stderr, "interface: %s, filter: %s, promiscuous: %s\n",
	        interface, filter, (flags&FLAG_BIT(FLAG_PROMISC))?"yes":"no");

	for(;;)
	    pcap_loop(pcap_socket, -1, (pcap_handler)filter_packet, NULL);
}
Exemplo n.º 27
0
//================================================================
// /quit
int osc_quit_handler(const char *path, const char *types, lo_arg **argv, int argc,
	void *data, void *user_data)
{
	signal_handler(42);	
	return 0;
}
Exemplo n.º 28
0
//================================================================
int main(int argc, char *argv[])
{
	//jack
	const char **ports;
	//jack_options_t options = JackNullOption;
	jack_status_t status;

//options struct was here

	if(argc-optind<1)
	{
		print_header("jack_audio_receive");
		fprintf(stderr, "Missing arguments, see --help.\n\n");
		exit(1);
	}

	int opt;
 	//do until command line options parsed
	while(1)
	{
		/* getopt_long stores the option index here. */
		int option_index=0;

		opt=getopt_long(argc, argv, "", long_options, &option_index);

		/* Detect the end of the options. */
		if(opt==-1)
		{
			break;
		}
		switch(opt)
		{
			case 0:

			 /* If this option set a flag, do nothing else now. */
			if(long_options[option_index].flag!=0)
			{
				break;
			}

			case 'h':
				print_header("jack_audio_receive");
				print_help();
				break;

			case 'v':
				print_version();
				break;

			case 'x':
				print_header("jack_audio_receive");
				check_lo_props(1);
				return 1;

			case 'o':
				output_port_count=atoi(optarg);

				if(output_port_count>max_channel_count)
				{
					output_port_count=max_channel_count;
				}
				port_count=fmin(input_port_count,output_port_count);
				break;

			case 'f':
				channel_offset=atoi(optarg);
				break;

			case 'y':
				bytes_per_sample=2;
				break;

			case 'n':
				client_name=optarg;
				break;

			case 's':
				server_name=optarg;
				jack_opts |= JackServerName;
				break;

			case 'b':
				pre_buffer_size=fmax(1,(uint64_t)atoll(optarg));
				break;

			case 'm':
				max_buffer_size=fmax(1,(uint64_t)atoll(optarg));
				break;

			case 'u':
				update_display_every_nth_cycle=fmax(1,(uint64_t)atoll(optarg));
				break;

			case 'l':
				receive_max=fmax(1,(uint64_t)atoll(optarg));
				test_mode=1;
				break;

			case 'a':
				io_host=optarg;
				break;

			case 'c':
				io_port=optarg;
				break;

			case 't':
				use_tcp=1;
				remote_tcp_server_port=optarg;
				break;

			case '?': //invalid commands
				/* getopt_long already printed an error message. */
				print_header("jack_audio_receive");
				fprintf(stderr, "Wrong arguments, see --help.\n\n");
				exit(1);

				break;
 	 
			default:
				break;
		 } //end switch op
	}//end while(1)


	//remaining non optional parameters listening port
	if(argc-optind!=1)
	{
		print_header("jack_audio_receive");
		fprintf(stderr, "Wrong arguments, see --help.\n\n");
		exit(1);
	}

	localPort=argv[optind];

	//for commuication with a gui / other controller / visualizer
	loio=lo_address_new_with_proto(LO_UDP, io_host, io_port);

	//if was set to use random port
	if(atoi(localPort)==0)
	{
		//for lo_server_thread_new_with_proto
		localPort=NULL;
	}

	//add osc hooks & start osc server early (~right after cmdline parsing)
	registerOSCMessagePatterns(localPort);

	lo_server_thread_start(lo_st);

	//read back port (in case of random)
	//could use 
	//int lo_server_thread_get_port(lo_server_thread st)
	const char *osc_server_url=lo_server_get_url(lo_server_thread_get_server(lo_st));
	localPort=lo_url_get_port(osc_server_url);
	//int lport=lo_server_thread_get_port(lo_st);

	//notify osc gui
	if(io_())
	{
		lo_message msgio=lo_message_new();
		lo_message_add_float(msgio, version);
		lo_message_add_float(msgio, format_version);
		lo_send_message(loio, "/startup", msgio);
		lo_message_free(msgio);
	}

	if(check_lo_props(0)>0)
	{
		return 1;
	}


	if(use_tcp==1)
	{
		lo_proto=LO_TCP;
	}

	if(shutup==0)
	{
		print_header("jack_audio_receive");

		if(output_port_count>max_channel_count)
		{
			fprintf(stderr,"/!\\ limiting playback ports to %d, sry\n",max_channel_count);
		}

		if(test_mode==1)
		{
			fprintf(stderr,"/!\\ limiting number of messages: %" PRId64 "\n",receive_max);
		}
	}

	//check for default jack server env var
	char *evar=getenv("JACK_DEFAULT_SERVER");
	if(evar==NULL || strlen(evar)<1)
	{
#ifndef _WIN
		unsetenv("JACK_DEFAULT_SERVER");
#endif
	}

	else if(server_name==NULL)
	{
		//use env var if no server was given with --sname
		server_name=evar;
	}

	if(server_name==NULL || strlen(server_name)<=0)
	{
		server_name="default";
	}

	if(client_name==NULL)
	{
		client_name="receive";
	}

	if(have_libjack()!=0)
	{
		fprintf(stderr,"/!\\ libjack not found (JACK not installed?). this is fatal: jack_audio_receive needs JACK to run.\n");
		io_quit("nolibjack");
		exit(1);
	}

	//initialize time
	gettimeofday(&tv, NULL);
	tt_prev.sec=tv.tv_sec;
	tt_prev.frac=tv.tv_usec;

	//create an array of input ports
	ioPortArray=(jack_port_t**) malloc(output_port_count * sizeof(jack_port_t*));

	//open a client connection to the JACK server
	client=jack_client_open(client_name, jack_opts, &status, server_name);
	if(client==NULL) 
		{
		fprintf(stderr,"jack_client_open() failed, status = 0x%2.0x\n", status);
		if(status & JackServerFailed) 
		{
			fprintf(stderr,"Unable to connect to JACK server.\n");
			io_quit("nojack");
		}
		exit(1);
	}

	if(use_tcp==1)
	{

		if(shutup==0)
		{
			fprintf(stderr,"receiving on TCP port: %s\n",localPort);
		}
	}
	else
	{
		if(shutup==0)
		{
			fprintf(stderr,"receiving on UDP port: %s\n",localPort);
	}
	}

	client_name=jack_get_client_name(client);

	if(shutup==0)
	{
		fprintf(stderr,"started JACK client '%s' on server '%s'\n",client_name,server_name);
		if(status & JackNameNotUnique) 
		{
			fprintf(stderr, "/!\\ name '%s' was automatically assigned\n", client_name);
		}
	}

	if(status & JackNameNotUnique) 
	{
		io_simple("/client_name_changed");
	}

	//print startup info

	read_jack_properties();

	if(shutup==0)
	{
		print_common_jack_properties();

		fprintf(stderr,"channels (playback): %d\n",output_port_count);
		fprintf(stderr,"channel offset: %d\n",channel_offset);

		print_bytes_per_sample();

		fprintf(stderr,"multi-channel period size: %d bytes\n",
			output_port_count*period_size*bytes_per_sample
		);

		char *strat="fill with zero (silence)";
		if(zero_on_underflow==0)
		{
			strat="re-use last available period";
		}

		fprintf(stderr,"underflow strategy: %s\n",strat);

		if(rebuffer_on_restart==1)
		{
			fprintf(stderr,"rebuffer on sender restart: yes\n");
		}
		else
		{
			fprintf(stderr,"rebuffer on sender restart: no\n");
		}

		if(rebuffer_on_underflow==1)
		{
			fprintf(stderr,"rebuffer on underflow: yes\n");
		}
		else
		{
			fprintf(stderr,"rebuffer on underflow: no\n");
		}

		if(allow_remote_buffer_control==1)
		{
			fprintf(stderr,"allow external buffer control: yes\n");
		}
		else
		{
			fprintf(stderr,"allow external buffer control: no\n");
		}

		if(close_on_incomp==1)
		{
			fprintf(stderr,"shutdown receiver when incompatible data received: yes\n");
		}
		else
		{
			fprintf(stderr,"shutdown receiver when incompatible data received: no\n");
		}

	}//end cond. print

	char buf[64];
	format_seconds(buf,(float)pre_buffer_size*period_size/(float)sample_rate);

	uint64_t rb_size_pre=pre_buffer_size*output_port_count*period_size*bytes_per_sample;

	if(shutup==0)
	{
		fprintf(stderr,"initial buffer size: %" PRId64 " mc periods (%s, %" PRId64 " bytes, %.2f MB)\n",
			pre_buffer_size,
			buf,
			rb_size_pre,
			(float)rb_size_pre/1000/1000
		);
	}
	buf[0]='\0';

	//ringbuffer size bytes
	uint64_t rb_size;

	//ringbuffer mc periods
	int max_buffer_mc_periods;

	//max given as param (user knows best. if pre=max, overflows are likely)
	if(max_buffer_size>0)
	{
		max_buffer_mc_periods=fmax(pre_buffer_size,max_buffer_size);
		rb_size=max_buffer_mc_periods
			*output_port_count*period_size*bytes_per_sample;
	}
	else //"auto"
	{
		//make max buffer 0.5 seconds larger than pre buffer
		max_buffer_mc_periods=pre_buffer_size+ceil(0.5*(float)sample_rate/period_size);
		rb_size=max_buffer_mc_periods
			*output_port_count*period_size*bytes_per_sample;
	}

	max_buffer_size=max_buffer_mc_periods;

	format_seconds(buf,(float)max_buffer_mc_periods*period_size/sample_rate);
	if(shutup==0)
	{
		fprintf(stderr,"allocated buffer size: %" PRId64 " mc periods (%s, %" PRId64 " bytes, %.2f MB)\n",
			max_buffer_size,
			buf,
			rb_size,
			(float)rb_size/1000/1000
		);
	}
	buf[0]='\0';

	io_dump_config();

	//====================================
	//main ringbuffer osc blobs -> jack output
	rb=jack_ringbuffer_create(rb_size);
	//helper ringbuffer: used when remote period size < local period size
	rb_helper=jack_ringbuffer_create(rb_size);

	if(rb==NULL)
	{
		fprintf(stderr,"could not create a ringbuffer with that size.\n");
		fprintf(stderr,"try --max <smaller size>.\n");
		io_quit("ringbuffer_too_large");
		exit(1);
	}

	//JACK will call process() for every cycle (given by JACK)
	//NULL could be config/data struct
	jack_set_process_callback(client, process, NULL);

	jack_set_xrun_callback(client, xrun_handler, NULL);

	//register hook to know when JACK shuts down or the connection 
	//was lost (i.e. client zombified)
	jack_on_shutdown(client, jack_shutdown_handler, 0);

	// Register each output port
	int port;
	for(port=0; port<output_port_count; port ++)
	{
		// Create port name
		char* portName;
		if(asprintf(&portName, "output_%d", (port+1)) < 0) 
		{
			fprintf(stderr,"Could not create portname for port %d", port);
			io_quit("port_error");
			exit(1);
		}

		// Register the output port
		ioPortArray[port]=jack_port_register(client, portName, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
		if(ioPortArray[port]==NULL) 
		{
			fprintf(stderr,"Could not create output port %d\n", (port+1));
			io_quit("port_error");
			exit(1);
		}
	}

	/* Tell the JACK server that we are ready to roll. Our
	 * process() callback will start running now. */
	if(jack_activate(client)) 
	{
		fprintf(stderr, "cannot activate client");
		io_quit("cannot_activate_client");
		exit(1);
	}

	/* Connect the ports. You can't do this before the client is
	 * activated, because we can't make connections to clients
	 * that aren't running. Note the confusing (but necessary)
	 * orientation of the driver backend ports: playback ports are
	 * "input" to the backend, and capture ports are "output" from
	 * it.
	 */
	//prevent to get physical midi ports
	const char* pat="audio";

	ports=jack_get_ports(client, NULL, pat, JackPortIsPhysical|JackPortIsInput);

	if(ports==NULL) 
	{
		if(shutup==0)		
		{
			fprintf(stderr,"no physical playback ports\n");
		}
		//exit(1);
	}
	
	if(autoconnect==1)
	{
		fprintf(stderr, "\n");

		int j=0;
		int i;
		for(i=0;i<output_port_count;i++)
		{
			if(ports[i]!=NULL 
				&& ioPortArray[j]!=NULL 
				&& jack_port_name(ioPortArray[j])!=NULL)
			{
				if(!jack_connect(client, jack_port_name(ioPortArray[j]), ports[i]))
				{
					if(shutup==0)
					{
						fprintf(stderr, "autoconnect: %s -> %s\n",
							jack_port_name(ioPortArray[j]),ports[i]
						);
					}
					io_simple_string_double("/autoconnect",jack_port_name(ioPortArray[j]),ports[i]);
					j++;
				}
				else
				{
					if(shutup==0)
					{
						fprintf(stderr, "autoconnect: failed: %s -> %s\n",
							jack_port_name(ioPortArray[j]),ports[i]
						);
					}
				}
			}
			else
			{
				//no more playback ports
				break;
			}
		}//end for all output ports

		if(shutup==0)
		{
			fprintf(stderr, "\n");
		}
	}

	free(ports);

	fflush(stderr);

	/* install a signal handler to properly quits jack client */
#ifndef _WIN
	signal(SIGQUIT, signal_handler);
	signal(SIGHUP, signal_handler);
#endif
	signal(SIGTERM, signal_handler);
	signal(SIGINT, signal_handler);

	if(use_tcp==1)
	{
		//10 MB max
		int desired_max_tcp_size=10000000;

		lo_server s=lo_server_thread_get_server(lo_st);
		int ret_set_size=lo_server_max_msg_size(s, desired_max_tcp_size);

		if(shutup==0)
		{
			printf("set tcp max size return: %d\n",ret_set_size);
			io_simple("/tcp_max_size_xxxx");
		}
	}

	not_yet_ready=0;

	io_simple("/start_main_loop");

	//run possibly forever until not interrupted by any means
	while(1) 
	{
		//possibly clean shutdown without any glitches
		if(shutdown_in_progress==1)
		{
			signal_handler(42);
		}
#ifdef WIN_
		Sleep(1000);
#else
		sleep(1);
#endif
	}

	exit(0);
}//end main
Exemplo n.º 29
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
    {
      // The usual server side boilerplate code.

      CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);

      CORBA::Object_var obj =
        orb->resolve_initial_references ("RootPOA");

      PortableServer::POA_var root_poa =
        PortableServer::POA::_narrow (obj.in ());

      PortableServer::POAManager_var poa_manager =
        root_poa->the_POAManager ();

      poa_manager->activate ();

      // "built-in" strategies are the following:
      //   0 = RoundRobin
      //   1 = Random
      //   2 = LeastLoaded
      int default_strategy = 1;

      // Check the non-ORB arguments.
      ::parse_args (argc,
                    argv,
                    default_strategy);

      TAO_LB_LoadManager * lm = 0;
      ACE_NEW_THROW_EX (lm,
        TAO_LB_LoadManager(::ping_timeout_milliseconds,
                           ::ping_interval_seconds),
                          CORBA::NO_MEMORY (
                          CORBA::SystemException::_tao_minor_code (
                            TAO::VMCID,
                            ENOMEM),
                          CORBA::COMPLETED_NO));

      PortableServer::ServantBase_var safe_lm = lm;

      // Initalize the LoadManager servant.
      lm->initialize (orb->orb_core ()->reactor (),
                      orb.in (),
                      root_poa.in ());

      PortableGroup::Properties props (1);
      props.length (1);
      props[0].nam.length (1);
      props[0].nam[0].id =
        CORBA::string_dup ("org.omg.CosLoadBalancing.StrategyInfo");

      CosLoadBalancing::StrategyInfo strategy_info;

      switch (default_strategy)
        {
        case 0:
          strategy_info.name = CORBA::string_dup ("RoundRobin");
          break;
        case 1:
          strategy_info.name = CORBA::string_dup ("Random");
          break;
        case 2:
          strategy_info.name = CORBA::string_dup ("LeastLoaded");
          break;
        default:
          ORBSVCS_ERROR_RETURN ((LM_ERROR,
                            ACE_TEXT ("ERROR: LoadBalancer internal error.\n")
                            ACE_TEXT ("       Unknown built-in strategy.\n")),
                            -1);
        }

      props[0].val <<= strategy_info;

      lm->set_default_properties (props);

      CosLoadBalancing::LoadManager_var load_manager =
        lm->_this ();

      CORBA::String_var str =
        orb->object_to_string (load_manager.in ());

      // to support corbaloc
      // Get a reference to the IOR table.
      CORBA::Object_var tobj = orb->resolve_initial_references ("IORTable");

      IORTable::Table_var table = IORTable::Table::_narrow (tobj.in ());

      // bind your stringified IOR in the IOR table
      table->bind ("LoadManager", str.in ());

      FILE * lm_ior = ACE_OS::fopen (lm_ior_file, "w");
      ACE_OS::fprintf (lm_ior, "%s", str.in ());
      ACE_OS::fclose (lm_ior);

#if defined (linux) && defined (ACE_HAS_THREADS)
      if (ACE_Thread_Manager::instance ()->spawn (::TAO_LB_run_load_manager,
                                                  orb.in ()) == -1)
        {
          ORBSVCS_ERROR_RETURN ((LM_ERROR,
                             "ERROR:  Unable to spawn TAO LoadManager's "
                             "ORB thread.\n"),
                            -1);
        }

      ACE_Sig_Set sigset;
      sigset.sig_add (SIGINT);
      sigset.sig_add (SIGTERM);

      int signum = -1;

      // Block waiting for the registered signals.
      if (ACE_OS::sigwait (sigset, &signum) == -1)
        {
          ORBSVCS_ERROR_RETURN ((LM_ERROR,
                             "(%P|%t) %p\n",
                             "ERROR waiting on signal"),
                            -1);
        }

      ACE_ASSERT (signum == SIGINT || signum == SIGTERM);
#else
      // Activate/register the signal handler that (attempts) to
      // ensure graceful shutdown of the LoadManager so that remote
      // resources created by the LoadManager can be cleaned up.
      TAO_LB_Signal_Handler signal_handler (orb.in (), root_poa.in ());

      if (signal_handler.activate () != 0)
        {
          ORBSVCS_ERROR_RETURN ((LM_ERROR,
                             "Error: can't activate LB signal handler, exiting.\n"),
                             -1);
        }

      // @@ There is a subtle race condition here.  If the signal
      //    handler thread shuts down the ORB before it is run, the
      //    below call to ORB::run() will throw a CORBA::BAD_INV_ORDER
      //    exception.
      orb->run ();

      // Wait for the signal handler thread to finish
      // before the process exits.
      signal_handler.wait ();
#endif  /* linux && ACE_HAS_THREADS */

      orb->destroy ();
    }
//   catch (const PortableGroup::InvalidProperty& ex)
//     {
//       ORBSVCS_DEBUG ((LM_DEBUG, "Property ----> %s\n", ex.nam[0].id.in ()));
//     }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("TAO Load Manager");

      return -1;
    }

  return 0;
}
Exemplo n.º 30
0
static gboolean
sigint_handler_cb (MainData *data)
{
	signal_handler (SIGINT, data);
	return FALSE;
}