コード例 #1
0
/*-------------------------------------------------------------------------
 * Function:    out_nl
 *
 * Purpose:     Ends the current line.  The new line is not started until
 *              output occurs on the new line.  If writing a linefeed would
 *              cause information to scroll off the top of a terminal, then
 *              the output is paused.
 *
 * Return:      void
 *
 * Programmer:  Robb Matzke
 *              [email protected]
 *              Dec 11 1996
 *
 * Modifications:
 *
 *      Robb Matzke, 23 Jan 1997
 *      The `more?' prompt has been modified to be more interactive
 *      by placing the terminal in raw mode.
 *
 *      Robb Matzke, 6 Feb 1997
 *      Lines which would have nothing after the equal are left blank.
 *
 *-------------------------------------------------------------------------
 */
void
out_nl(out_t *f)
{
    char                buf[256];
    int                 i, n, rawmode=false;
    struct termios      oldtio, tio;
    static const char   *prompt = "more? ('q' to quit) ";

    if (out_brokenpipe(f)) return;
    if (isatty(fileno(f->f))) out_progress(NULL);

    putc('\n', f->f);
    f->row += 1;
    f->col = 0;

    /* Pause output if it's going to a terminal. */    
 again:
    if (PAGER_ACTIVE(f) && f->row+1==OUT_NROWS) {
        fputs(prompt, f->f);
        fflush(f->f);

        if (tcgetattr(STDIN_FILENO, &tio)>=0) {
            oldtio = tio;
            tio.c_lflag &= ~(ECHO | ICANON);
            tio.c_lflag &= ~ISIG; /*we handle them below*/
            tio.c_cc[VMIN] = 1;
            tio.c_cc[VTIME] = 0;
            if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio)>=0) rawmode=true;
        }

        while (0==out_brokenpipe(f) &&
               (n=read(STDIN_FILENO, &buf, 1))<0 &&
               EINTR==errno) /*void*/;
      
        if (rawmode) {
            tcsetattr(STDIN_FILENO, TCSAFLUSH, &oldtio);
            for (i=0; i<strlen(prompt); i++) putc('\b', f->f);
            for (i=0; i<strlen(prompt); i++) putc(' ', f->f);
            for (i=0; i<strlen(prompt); i++) putc('\b', f->f);
            fflush(f->f);
        }
        if (1==n && 'q'==buf[0]) handle_signals(SIGPIPE);
        if (1==n && 'n'==buf[0]) {
            f->pflags = PAGER_NEXT_SECTION;
            fputs("Skipping...\n", f->f);
        }
        if (1==n && tio.c_cc[VEOF]==buf[0]) f->pflags = PAGER_NEXT_CMD;
        if (1==n && tio.c_cc[VINTR]==buf[0]) handle_signals(SIGINT);
        if (1==n && tio.c_cc[VQUIT]==buf[0]) kill(getpid(), SIGQUIT);
        if (1==n && tio.c_cc[VSUSP]==buf[0]) {
            kill(getpid(), SIGTSTP);
            goto again;
        }
        f->row = 0;
    }
}
コード例 #2
0
ファイル: server.c プロジェクト: SylvanHuang/Http-Server
int initialize_server()
{
	struct sockaddr_in myaddr;
	int    sfd; 
	int    optval = 1;

	sfd = socket(AF_INET,SOCK_STREAM,0);    //creating socket

	if(sfd == -1)
	{
		print_log(ERROR,"socket");
		exit(0);
	}

	if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1)
		print_log(WARNING,"\nsetsockopt");

	memset(&myaddr,0,sizeof(myaddr));
	myaddr.sin_family      = AF_INET;
	myaddr.sin_port        = htons(port_number);
	myaddr.sin_addr.s_addr = INADDR_ANY;

	if(bind(sfd, (struct sockaddr*) &myaddr, sizeof(myaddr)) == -1)  
	{	
		print_log(ERROR,"PORT NO NOT FOUND GLOBAL ERROR STATUS IS:");
		exit(0);
	}
	if(listen(sfd,BACKLOG)==-1)                                     
		print_log(WARNING,"\nLISTEN FAILED");             

	handle_signals();
	return sfd;
}
コード例 #3
0
ファイル: process.c プロジェクト: Tayyib/uludag
struct ProcChild *
proc_fork(void (*child_func)(void), const char *desc)
{
	pid_t pid;
	int fdr[2], fdw[2];

	pipe(fdr);
	pipe(fdw);
	pid = fork();
	if (pid == -1) return NULL;

	if (pid == 0) {
		// new child process starts
		close(fdw[1]);
		close(fdr[0]);
		memset(&my_proc, 0, sizeof(struct Proc));
		my_proc.parent.from = fdw[0];
		my_proc.parent.to = fdr[1];
		my_proc.parent.pid = getppid();
		my_proc.desc = desc;
		handle_signals();
		log_debug(LOG_PROC, "%s process %d started\n", desc, getpid());
		child_func();
		proc_finish();
		while (1) {} // to keep gcc happy
	} else {
		// parent process continues
		close(fdw[0]);
		close(fdr[1]);
		return add_child(pid, fdw[1], fdr[0], desc);
	}
}
コード例 #4
0
ファイル: daemon.c プロジェクト: jeffpc/blahgd
int main(int argc, char **argv)
{
	int ret;

	ASSERT0(putenv("TZ=UTC"));

	cmn_err(CE_INFO, "blahgd version %s", version_string);

	/* drop unneeded privs */
	ret = drop_privs();
	if (ret)
		goto err;

	jeffpc_init(&init_ops);
	init_math(true);
	init_pipe_subsys();
	init_req_subsys();
	init_post_subsys();
	init_file_cache();

	ret = config_load((argc >= 2) ? argv[1] : NULL);
	if (ret)
		goto err;

	ret = load_all_posts();
	if (ret)
		goto err;

	handle_signals();

	ret = start_helpers();
	if (ret)
		goto err_helpers;

	ret = start_listening();
	if (ret)
		goto err_helpers;

	accept_conns();

	stop_listening();

	stop_helpers();

	free_all_posts();
	uncache_all_files();

	return 0;

err_helpers:
	stop_helpers();

err:
	DBG("Failed to inintialize: %s", xstrerror(ret));

	return ret;
}
コード例 #5
0
ファイル: notebook.c プロジェクト: amery/clip-angelo
/*********************** SIGNALS **************************/
gint
handle_switch_page_signal(GtkNotebook * notebook, GtkNotebookPage * page, gint page_num, C_signal * cs)
{
   ClipVar   cv, mpage, mreq, mallc;

   int       ret;

   C_widget *cwid;

   memset(&cv, 0, sizeof(ClipVar));
   _clip_map(cs->cw->cmachine, &cv);
   memset(&mpage, 0, sizeof(ClipVar));
   _clip_map(cs->cw->cmachine, &mpage);
   memset(&mreq, 0, sizeof(ClipVar));
   _clip_map(cs->cw->cmachine, &mreq);
   memset(&mallc, 0, sizeof(ClipVar));
   _clip_map(cs->cw->cmachine, &mallc);
   cwid = _list_get_cwidget(cs->cw->cmachine, page->child);
   if (!cwid)
      cwid = _register_widget(cs->cw->cmachine, page->child, NULL);
   if (cwid)
      _clip_madd(cs->cw->cmachine, &mpage, HASH_CHILD, &cwid->obj);
   cwid = _list_get_cwidget(cs->cw->cmachine, page->tab_label);
   if (!cwid)
      cwid = _register_widget(cs->cw->cmachine, page->tab_label, NULL);
   if (cwid)
      _clip_madd(cs->cw->cmachine, &mpage, HASH_TABLABEL, &cwid->obj);
   cwid = _list_get_cwidget(cs->cw->cmachine, page->menu_label);
   if (!cwid)
      cwid = _register_widget(cs->cw->cmachine, page->menu_label, NULL);
   if (cwid)
      _clip_madd(cs->cw->cmachine, &mpage, HASH_MENULABEL, &cwid->obj);
   _clip_mputn(cs->cw->cmachine, &mreq, HASH_WIDTH, page->requisition.width);
   _clip_mputn(cs->cw->cmachine, &mreq, HASH_HEIGHT, page->requisition.height);
   _clip_madd(cs->cw->cmachine, &mpage, HASH_REQUISITION, &mreq);
   _clip_mputn(cs->cw->cmachine, &mallc, HASH_X, page->allocation.x);
   _clip_mputn(cs->cw->cmachine, &mallc, HASH_Y, page->allocation.y);
   _clip_mputn(cs->cw->cmachine, &mallc, HASH_WIDTH, page->allocation.width);
   _clip_mputn(cs->cw->cmachine, &mallc, HASH_HEIGHT, page->allocation.height);
   _clip_madd(cs->cw->cmachine, &mpage, HASH_ALLOCATION, &mallc);
   _clip_mputn(cs->cw->cmachine, &mpage, HASH_DEFAULTMENU, page->default_menu);
   _clip_mputn(cs->cw->cmachine, &mpage, HASH_DEFAULTTAB, page->default_tab);
   _clip_mputn(cs->cw->cmachine, &mpage, HASH_EXPAND, page->expand);
   _clip_mputn(cs->cw->cmachine, &mpage, HASH_PACK, page->pack);
   _clip_mputn(cs->cw->cmachine, &mpage, HASH_FILL, page->fill);
   _clip_madd(cs->cw->cmachine, &cv, HASH_PAGE, &mpage);
   _clip_mputn(cs->cw->cmachine, &cv, HASH_PAGENUM, page_num + 1);
   ret = handle_signals(GTK_WIDGET(notebook), cs, &cv);
   _clip_destroy(cs->cw->cmachine, &cv);
   _clip_destroy(cs->cw->cmachine, &mpage);
   _clip_destroy(cs->cw->cmachine, &mreq);
   _clip_destroy(cs->cw->cmachine, &mallc);
   return ret;
}
コード例 #6
0
ファイル: process.c プロジェクト: Tayyib/uludag
void
proc_init(void)
{
	memset(&my_proc, 0, sizeof(struct Proc));
	my_proc.parent.to = -1;
	my_proc.parent.from = -1;
	my_proc.desc = "MainSwitch";
	my_proc.max_children = 8;
	my_proc.children = calloc(8, sizeof(struct ProcChild));
	handle_signals();
}
コード例 #7
0
ファイル: memprobed.c プロジェクト: oboguev/membalance
/*
 * Open connection to xenstore.
 *
 * @pollfds defines of signal-handling descriptors to be watched
 * if has to wait.
 *
 * Will not touch pollfds[NPFD_XS].
 */
static void open_xs_connection(struct pollfd *pollfds)
{
	struct timespec ts0;
	int64_t wsec;
	bool displayed_msg = false;
	int k;

	/*
	 * If we are running as a daemon during system startup, there
	 * can be a race condition with continuing Xen initialization
	 * (/proc/xen including /proc/xen/privcmd may be unavailable yet,
	 * still to be created even though Xen service startup completion
	 * has already been signalled), so wait for a while if necessary.
	 */
	for (ts0 = getnow();;)
	{
		if (!xs)
			xs = xs_open(0);
		if (xs)
			break;

		/* time since the start */
		wsec = timespec_diff_ms(getnow(), ts0) / MSEC_PER_SEC;

		if (run_as_daemon && wsec < max_xen_init_retries)
		{
			if (wsec >= xen_init_retry_msg && !displayed_msg)
			{
				notice_msg("waiting for Xen to initialize");
				displayed_msg = true;
			}

			if (pollfds != NULL)
			{
				int npollfds = NPFD_COUNT - 1;
				for (k = 0;  k < npollfds;  k++)
					pollfds[k].revents = 0;
				if (poll(pollfds, npollfds, 1 * MSEC_PER_SEC) < 0)
					fatal_perror("poll");
				handle_signals(pollfds, NULL);
			}
			else
			{
				sleep(1);
			}
		}
		else
		{
			fatal_perror("unable to open connection to xenstore");
		}
	}
}
コード例 #8
0
ファイル: unit_test.c プロジェクト: flsafe/programming_tutor
void run_tests(){
  int err;
  pid_t stat;

  /* Each of the test functions will be called in its own fork */
  void (** unit_test) (void);
  void (* test_fns[N_UNIT_TESTS + 1]) (void) = 
    {
     test_first_char,
     test_last_char,
     test_3,
     test_4,
     test_5
     ,NULL
    };

  for (unit_test = test_fns ; *unit_test ; unit_test++){

    err = pipe(pipe_des);
    quitif(err);

    switch (fork()){

      case -1:
        quitif(-1);
        break;

      /* Execute the unit test in the child */
      case 0:
        close(pipe_des[IN]);

        handle_signals();
        
        (*unit_test)();
        err = close(pipe_des[OUT]);
        quitif(err);

        exit(0);
        break;

      /* Wait for the child to finish the unit test */
      default:
        close(pipe_des[OUT]);

        err = wait(&stat);
        quitif(err);

        print_results();
        break;
    }
  }
}
コード例 #9
0
ファイル: process.c プロジェクト: Tayyib/uludag
struct ProcChild *
proc_fork(void (*child_func)(void), const char *desc)
{
	pid_t pid;
	int fdr[2], fdw[2];
	int i;

	pipe(fdr);
	pipe(fdw);
	pid = fork();
	if (pid == -1) return NULL;

	if (pid == 0) {
		// new child process starts
		// we have to close unneeded pipes inherited from the parent
		if (my_proc.parent.to != -1) close(my_proc.parent.to);
		if (my_proc.parent.from != -1) close(my_proc.parent.from);
		for (i = 0; i < my_proc.nr_children; i++) {
			close(my_proc.children[i].to);
			close(my_proc.children[i].from);
		}
		close(fdw[1]);
		close(fdr[0]);
		// stop parent's pipes from propagating through an exec()
		fcntl(fdw[0], F_SETFD, FD_CLOEXEC);
		fcntl(fdr[1], F_SETFD, FD_CLOEXEC);
		// now setup our own data
		memset(&my_proc, 0, sizeof(struct Proc));
		my_proc.parent.from = fdw[0];
		my_proc.parent.to = fdr[1];
		my_proc.parent.pid = getppid();
		my_proc.desc = desc;
		handle_signals();
		set_my_name(desc);
		log_debug(LOG_PROC, "%s process %d started\n", desc, getpid());
		// finally jump to the real function
		child_func();
		proc_finish();
		while (1) {} // to keep gcc happy
	} else {
		// parent process continues
		close(fdw[0]);
		close(fdr[1]);
		return add_child(pid, fdw[1], fdr[0], desc);
	}
}
コード例 #10
0
ファイル: object.c プロジェクト: amery/clip-itk
static int
extra_signal_emitter (C_widget *cwid, const gchar *signal_name)
{
	C_signal *cs;
	long sigid = _clip_hashstr(signal_name);

	if (cwid && cwid->siglist)
	{
		for (cs = cwid->siglist; cs; cs = cs->next)
		{
			if (cs->sigid == sigid && strcmp(cs->signame, signal_name)==0)
			{
				ClipVar *cv = _clip_spar(cs->cw->cmachine,3);
				if (handle_signals(cs->cw->widget, cs, cv))
					break;
			}
		}
	}
	return 0;
}
コード例 #11
0
ファイル: process.c プロジェクト: Tayyib/uludag
void
proc_init(int argc, char *argv[])
{
	int i;

	name_addr = argv[0];
	name_size = 0;
	for (i = 0; i < argc; i++) {
		name_size += strlen(argv[i]) + 1;
	}

	memset(&my_proc, 0, sizeof(struct Proc));
	my_proc.parent.to = -1;
	my_proc.parent.from = -1;
	my_proc.desc = "Comar";
	my_proc.max_children = 8;
	my_proc.children = calloc(8, sizeof(struct ProcChild));
	handle_signals();
	set_my_name(my_proc.desc);
}
コード例 #12
0
/** *****************************************************************************************************************
  @brief the main event loop.

  This will handle signals, poll buddies, poll clients, publish events, and cleanup sockets.
 ********************************************************************************************************************/
void
event_loop(int32_t listen_sock)
{
    upk_conn_handle_meta_t *clients;
    fd_set                  lfds;
    double                  sel_ival = upk_runtime_configuration.BuddyPollingInterval / 2;
    struct timeval          timeout, timeoutv = { 0, 0 };

#ifdef UPK_CONTROLLER_TERMINATE_FOR_TESTING_AFTER_N
    int                     connections = 0;
#endif

    clients = ctrl_init();

    while(1) {
        handle_signals();
        handle_buddies();

        FD_ZERO(&lfds);
        FD_SET(listen_sock, &lfds);

        timeout = timeoutv;
        if(select(listen_sock + 1, &lfds, NULL, NULL, &timeout) > 0) {
            if(FD_ISSET(listen_sock, &lfds)) {
                upk_debug1("Accepting connection\n");
                ctrl_accept_conn(listen_sock, clients);
#ifdef UPK_CONTROLLER_TERMINATE_FOR_TESTING_AFTER_N
                connections++;
#endif
            }
        }

        upk_net_event_dispatcher(clients, sel_ival);
        upk_net_flush_closed_sockets(clients);
#ifdef UPK_CONTROLLER_TERMINATE_FOR_TESTING_AFTER_N
        if(n++ > 50 || connections > UPK_CONTROLLER_TERMINATE_FOR_TESTING_AFTER_N)
            break;
#endif
    }
}
コード例 #13
0
ファイル: server.c プロジェクト: caxenie/code-snippets
/**
 * Server that exposes a method call and waits for it to be called
 */
void listen_to_clients() 
{
   DBusMessage* msg;
   DBusMessage* reply;
   DBusMessageIter args;
   int ret;
   char* param;

   printf("Listening for method calls & signals\n");

   // loop, testing for new messages
   while (1) {
      // non blocking read of the next available message
      dbus_connection_read_write(conn, 0);
      msg = dbus_connection_pop_message(conn);

      // loop again if we haven't got a message
      if (NULL == msg) { 
         sleep(1); 
         continue; 
      }
      
      // check this is a method call for the right interface & method
      if (dbus_message_is_method_call(msg, SERVER_METHOD_INTERFACE, METHOD1)) 
         			handle_methods(msg);

      if (dbus_message_is_signal(msg, SERVER_SIGNAL_INTERFACE, SIGNAL1) ||
		  dbus_message_is_signal(msg, SERVER_SIGNAL_INTERFACE, SIGNAL2) || 
		  dbus_message_is_signal(msg, SERVER_SIGNAL_INTERFACE, SIGNAL3) ||
		  dbus_message_is_signal(msg, SERVER_SIGNAL_INTERFACE, SIGNAL4))

				 	handle_signals(msg);

      // free the message
      dbus_message_unref(msg);
   }
}
コード例 #14
0
ファイル: s6-svscan.c プロジェクト: rmoorman/s6
int main (int argc, char const *const *argv)
{
  iopause_fd x[2] = { { -1, IOPAUSE_READ, 0 }, { -1, IOPAUSE_READ, 0 } } ;
  PROG = "s6-svscan" ;
  {
    subgetopt_t l = SUBGETOPT_ZERO ;
    unsigned int t = 5000 ;
    for (;;)
    {
      register int opt = subgetopt_r(argc, argv, "t:c:", &l) ;
      if (opt == -1) break ;
      switch (opt)
      {
        case 't' : if (uint0_scan(l.arg, &t)) break ;
        case 'c' : if (uint0_scan(l.arg, &max)) break ;
        default : strerr_dieusage(100, USAGE) ;
      }
    }
    argc -= l.ind ; argv += l.ind ;
    if (t) tain_from_millisecs(&defaulttimeout, t) ;
    else defaulttimeout = tain_infinite_relative ;
    if (max < 2) max = 2 ;
  }

  /* Init phase.
     If something fails here, we can die, because it means that
     something is seriously wrong with the system, and we can't
     run correctly anyway.
  */

  if (argc && (chdir(argv[0]) < 0)) strerr_diefu1sys(111, "chdir") ;
  x[1].fd = s6_supervise_lock(S6_SVSCAN_CTLDIR) ;
  x[0].fd = selfpipe_init() ;
  if (x[0].fd < 0) strerr_diefu1sys(111, "selfpipe_init") ;

  if (sig_ignore(SIGPIPE) < 0) strerr_diefu1sys(111, "ignore SIGPIPE") ;
  {
    sigset_t set ;
    sigemptyset(&set) ;
    sigaddset(&set, SIGCHLD) ;
    sigaddset(&set, SIGALRM) ;
    sigaddset(&set, SIGTERM) ;
    sigaddset(&set, SIGHUP) ;
    sigaddset(&set, SIGQUIT) ;
    sigaddset(&set, SIGABRT) ;
    sigaddset(&set, SIGINT) ;
    sigaddset(&set, SIGUSR1) ;
    if (selfpipe_trapset(&set) < 0) strerr_diefu1sys(111, "trap signals") ;
  }


  {
    struct svinfo_s blob[max] ; /* careful with that stack, Eugene */
    services = blob ;
    tain_now_g() ;


    /* Loop phase.
       From now on, we must not die.
       Temporize on recoverable errors, and panic on serious ones. */

    while (cont)
    {
      int r ;
      tain_add_g(&deadline, &defaulttimeout) ;
      reap() ;
      scan() ;
      killthem() ;
      r = iopause_g(x, 2, &deadline) ;
      if (r < 0) panic("iopause") ;
      else if (!r) wantscan = 1 ;
      else
      {
        if ((x[0].revents | x[1].revents) & IOPAUSE_EXCEPT)
        {
          errno = EIO ;
          panic("check internal pipes") ;
        }
        if (x[0].revents & IOPAUSE_READ) handle_signals() ;
        if (x[1].revents & IOPAUSE_READ) handle_control(x[1].fd) ;
      }
    }


    /* Finish phase. */

    selfpipe_finish() ;
    killthem() ;
    reap() ;
  }
  {
    char const *eargv[3] = { FINISH_PROG, finish_arg, 0 } ;
    execve(eargv[0], (char **)eargv, (char *const *)environ) ;
  }
  panicnosp("exec finish script " FINISH_PROG) ;
}
コード例 #15
0
ファイル: bevt_relayd.c プロジェクト: debosvi/bozEvent
int main (int argc, char const *const *argv) {
    tain_t deadline ;
    int sfd ;
    PROG = "bevt_relayd" ;

    if (argc < 2) strerr_dieusage(100, USAGE) ;
    if (ndelay_on(0) < 0) strerr_diefu2sys(111, "ndelay_on ", "0") ;
    if (ndelay_on(1) < 0) strerr_diefu2sys(111, "ndelay_on ", "1") ;
    if (sig_ignore(SIGPIPE) < 0) strerr_diefu1sys(111, "ignore SIGPIPE") ;

    sfd = selfpipe_init() ;
    if (sfd < 0) strerr_diefu1sys(111, "selfpipe_init") ;
    {
        sigset_t set ;
        sigemptyset(&set) ;
        sigaddset(&set, SIGCHLD) ;
        sigaddset(&set, SIGTERM) ;
        sigaddset(&set, SIGQUIT) ;
        sigaddset(&set, SIGHUP) ;
        sigaddset(&set, SIGABRT) ;
        sigaddset(&set, SIGINT) ;
        if (selfpipe_trapset(&set) < 0)
            strerr_diefu1sys(111, "trap signals") ;
    }

    if(bevt_relay_db_init(argv[1])<0)
        strerr_diefu1sys(111, "db init failed") ;

    tain_now_g() ;
    tain_addsec_g(&deadline, 2) ;

    if (!skaclient_server_01x_init_g(BEVT_RELAY_BANNER1, BEVT_RELAY_BANNER1_LEN, BEVT_RELAY_BANNER2, BEVT_RELAY_BANNER2_LEN, &deadline))
        strerr_diefu1sys(111, "sync with client") ;

    for (;;) {
        register unsigned int n = 0 ;
        iopause_fd x[6 + n] ;
        int r ;

        if(mfd<0) handle_connect_central();

        tain_add_g(&deadline, &tain_infinite_relative) ;
        x[0].fd = 0 ; x[0].events = IOPAUSE_EXCEPT | IOPAUSE_READ ;
        x[1].fd = 1 ; x[1].events = IOPAUSE_EXCEPT | (unixmessage_sender_isempty(unixmessage_sender_1) ? 0 : IOPAUSE_WRITE ) ;
        x[2].fd = sfd ; x[2].events = IOPAUSE_READ ;
        x[3].fd = bozclient_sfd(&central_client_g); x[3].events = IOPAUSE_READ ;
        x[4].fd = bozclient_sfd(&central_client_g); x[4].events = (bozclient_siswritable(&central_client_g) ? IOPAUSE_WRITE : 0) ;
        x[5].fd = unixmessage_sender_fd(unixmessage_sender_x) ; x[5].events = (unixmessage_sender_isempty(unixmessage_sender_x) ? 0 : IOPAUSE_WRITE)  ;

        r = iopause_g(x, 5 + n, &deadline) ;
        if (r < 0) {
            cleanup() ;
            strerr_diefu1sys(111, "iopause") ;
        }

        /* client closed */
        if ((x[0].revents | x[1].revents) & IOPAUSE_EXCEPT) break ;

        /* client is sync reading */
        if (x[1].revents & IOPAUSE_WRITE) {
            if (!unixmessage_sender_flush(unixmessage_sender_1) && !error_isagain(errno)) {
                cleanup() ;
                strerr_diefu1sys(111, "flush sync out") ;
            }
        }

        /* client is async rzading */
        if (x[5].revents & IOPAUSE_WRITE) {
            if (!unixmessage_sender_flush(unixmessage_sender_x) && !error_isagain(errno)) {
                cleanup() ;
                strerr_diefu1sys(111, "flush async out") ;
            }
        }

        /* signals arrived */
        if (x[2].revents & (IOPAUSE_READ | IOPAUSE_EXCEPT)) handle_signals() ;

        /* main socket read or close */
        if (x[3].revents & IOPAUSE_READ) {
            handle_close_central();
            continue;
        }

        /* main socket close */
        if (x[4].revents & IOPAUSE_WRITE) {
            bozclient_flush(&central_client_g);
        }

        /* main socket close */
        if (x[5].revents & IOPAUSE_WRITE) {
            if (!unixmessage_sender_flush(unixmessage_sender_x) && !error_isagain(errno)) {
                cleanup() ;
                strerr_diefu1sys(111, "flush stdout") ;
            }
        }

        /* client is sync writing */
        if (!unixmessage_receiver_isempty(unixmessage_receiver_0) || x[0].revents & IOPAUSE_READ)
        {
            if (unixmessage_handle(unixmessage_receiver_0, &bevt_relay_parse_prot_cmd, 0) < 0)
            {
                if (errno == EPIPE) break ; /* normal exit */
                cleanup() ;
                strerr_diefu1sys(111, "handle messages from client") ;
            }
        }
    }
    cleanup() ;
    return 0 ;
}
コード例 #16
0
ファイル: widget.c プロジェクト: amery/clip-itk
static gint handle_drag_data_delete_signal (GtkWidget *widget, GdkDragContext *drag_context, C_signal *cs)
  { return handle_signals (widget, cs, NULL); }
コード例 #17
0
ファイル: mpg321.c プロジェクト: mvd7793/RED-SIREN
int main(int argc, char *argv[])
{
    int fd = 0;
    char *currentfile, old_dir[PATH_MAX];
    playlist *pl = NULL;
    struct id3_file *id3struct = NULL;
    struct id3_tag *id3tag = NULL;
    int retval;

    buffer playbuf;
    
    struct mad_decoder decoder;
    pthread_t keyb_thread;

    key_t sem_key;
    key_t mem_key;
    key_t frames_key;

    union semun sem_ops;
    int shm_id;
    int frames_id;
    mad_decoder_position = 0;
    output_buffer_position = 0;
    
    old_dir[0] = '\0';

    playbuf.pl = pl = new_playlist();

    if (!pl)
    {
        fprintf(stderr, "malloc failed at startup!\n");
        exit(1);
    }

    loop_remaining = 1;

    options.volume = MAD_F_ONE;

    status = MPG321_PLAYING;
    
    /* Get the command line options */
    parse_options(argc, argv, pl);

    if(options.opt & MPG321_PRINT_FFT)
	    if(!(options.opt & MPG321_REMOTE_PLAY))
	    {
		    /* printf("FFT analysis can only be used in Remote mode play.\n\n"); */
		    usage(argv[0]);			
		    exit(0);
	    }


    /* If there were no files and no playlist specified just print the usage */
    if (!playlist_file && optind == argc)
    {
        usage(argv[0]);
        exit(0);
    }

    if (playlist_file)
        load_playlist(pl, playlist_file);

    if(options.opt & MPG321_RECURSIVE_DIR)
	    add_cmdline_files_recursive_dir(pl, argv);
    else
	    add_cmdline_files(pl, argv);

    if (shuffle_play)
        shuffle_files(pl);

    if(options.opt & MPG321_ENABLE_BUFFER)
    {
	    /* Initialize semaphore and shared memeory */
	    if(access(argv[0],X_OK) == 0)
		    sem_key = ftok(argv[0],0);
	    else
		    sem_key = ftok(MPG321_PATH,0);
	    if(sem_key == -1)
	    {
		    perror("Cannot obtain resources for semaphores");
		    exit(EXIT_FAILURE);
	    }
	    semarray = semget(sem_key,3,IPC_CREAT | IPC_EXCL | S_IRWXU);
	    if(semarray == -1)
	    {
		    perror("Cannot initialize semaphores");
		    exit(EXIT_FAILURE);
	    }
	    sem_ops.val = buffer_size-1;
	    if(semctl(semarray,0,SETVAL,sem_ops) == -1)
	    {
		    perror("Error while initializing mad_decoder semaphore");
		    if(semctl(semarray,0,IPC_RMID) == -1)
			    perror("Error while destroying semaphores");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    sem_ops.val = 0;
	    if(semctl(semarray,1,SETVAL,sem_ops) == -1)
	    {
		    perror("Error while initializing mad_decoder semaphore");
		    if(semctl(semarray,0,IPC_RMID) == -1)
			    perror("Error while destroying semaphores");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    sem_ops.val = 0;
	    if(semctl(semarray,2,SETVAL,sem_ops) == -1)
	    {
		    perror("Error while initializing mad_decoder semaphore");
		    if(semctl(semarray,0,IPC_RMID) == -1)
			    perror("Error while destroying semaphores");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }

	    /* Shared Memory */
	    mem_key = ftok(argv[0],1);
	    shm_id = shmget(mem_key,buffer_size * sizeof(output_frame), IPC_CREAT | S_IREAD | S_IWRITE);
	    if(shm_id == -1)
	    {
		    perror("Cannot initialize shared buffer");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    Output_Queue = shmat(shm_id,NULL,0);
	    if(*(int *)Output_Queue == -1)
	    {
		    perror("Error while attaching shared buffer to mad_decoder");
		    if(shmctl(shm_id,IPC_RMID,NULL))
			    perror("Cannot destroy shared buffer");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    static int n;
	    for(n=0;n<buffer_size;n++)
	    {
		    memset((Output_Queue+n)->data,'\0',4608);
		    memset((Output_Queue+n)->time,'\0',80);
		    (Output_Queue+n)->length = 0;
		    (Output_Queue+n)->seconds = 0;
		    (Output_Queue+n)->num_frames = 0;
	    }
	    
	    frames_key = ftok(argv[0],2);
	    frames_id = shmget(frames_key,buffer_size * sizeof(decoded_frames), IPC_CREAT | S_IREAD | S_IWRITE);
	    if(frames_id == -1)
	    {
		    perror("Cannot initialize shared frames counter");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    Decoded_Frames = shmat(frames_id,NULL,0);
	    if(*(int *)Decoded_Frames == -1)
	    {
		    perror("Error while attaching shared frames counter to mad_decoder");
		    if(shmctl(frames_id,IPC_RMID,NULL))
			    perror("Cannot destroy shared frames counter");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    	
	    Decoded_Frames->is_http = 0;
	    Decoded_Frames->is_file = 0;

    }
    else {
	    ao_initialize();
	    check_default_play_device();
    }
    
    if (!(options.opt & MPG321_REMOTE_PLAY))
    {
        handle_signals(-1); /* initialize signal handler */
        remote_input_buf[0] = '\0';
    }
    
    if (!(options.opt & MPG321_QUIET_PLAY)) 
        mpg123_boilerplate();
    
    if (options.opt & MPG321_REMOTE_PLAY)
    {
        printf ("@R MPG123\n");
	if(options.opt & MPG321_ENABLE_BUFFER)
	{
#ifdef HAVE_ALSA
		init_alsa_volume_control("default"); /* For the moment use "default", it works on most of the systems. Tested in Debian,Fedora,Ubuntu,RedHat,CentOS,Gentoo */
		if(options.volume != MAD_F_ONE)
			mpg321_alsa_set_volume((long)options.volume*volume_max/100);
#endif
	}
    }

    /* Fork here. */
    if(options.opt & MPG321_ENABLE_BUFFER)
    {
	    output_pid = fork();
	    if(output_pid == -1)
	    {
		    perror("Error while forking output process");
		    goto out; /* Release shared memeory and semaphores */
		//    exit(EXIT_FAILURE);
	    }

	    if(output_pid == 0)
	    {
		    frame_buffer_p();
		    exit(EXIT_SUCCESS);
	    }
	    signal(SIGUSR1,handle_signals);
	    if(!(options.opt & MPG321_REMOTE_PLAY))
	    {
#ifdef HAVE_ALSA
		    init_alsa_volume_control("default");
		    if(options.volume != MAD_F_ONE)
			    mpg321_alsa_set_volume((long)options.volume*volume_max/100);
#endif
	    }
    }

    if( (options.volume != MAD_F_ONE) && !(options.opt & MPG321_ENABLE_BUFFER))
    {
	    options.volume = mad_f_tofixed((long)options.volume/100.0);
    }
    else{
	    options.volume = MAD_F_ONE; /* When using the buffer options.volume when decoding each frame should be equal to MAD_F_ONE */
//	    options.volume = mad_f_tofixed((long)100.0/100.0);
    }

    if (!(options.opt & MPG321_REMOTE_PLAY))
    {
	     if(options.opt & MPG321_ENABLE_BASIC)
	     {
	 	     /* Now create and detach the basic controls thread */
		     sem_init(&main_lock,0,0);
	 	     pthread_create(&keyb_thread,NULL,read_keyb,NULL);
		     pthread_detach(keyb_thread);
	     }
     }
    if(set_xterm)
    {
	    tty_control();
	    get_term_title(title);
    }else
    {
     	
	    if (!(options.opt & MPG321_REMOTE_PLAY))
	    {
	    	    if (tcgetattr(0, &terminal_settings) < 0)
	    		    perror("tcgetattr()");
	    	    memcpy(&old_terminal_settings, &terminal_settings, sizeof(struct termios));
		    /* Early thread start */
		    sem_post(&main_lock);
	    }
    }
    /* Play the mpeg files or zip it! */
    while((currentfile = get_next_file(pl, &playbuf)))
    {
        //printf("Current File: %s\n",currentfile);
	   if (quit_now) 
            break;
        
        signal(SIGINT, SIG_DFL);
        
        playbuf.buf = NULL;
        playbuf.fd = -1;
        playbuf.length = 0;
        playbuf.done = 0;
        playbuf.num_frames = 0;
        current_frame = 0;
        playbuf.max_frames = -1;
        strncpy(playbuf.filename,currentfile, PATH_MAX);
        playbuf.filename[PATH_MAX-1] = '\0';
        
        if (status == MPG321_PLAYING || status == MPG321_STOPPED) 
            file_change = 1;

        mad_timer_reset(&playbuf.duration);
        
        mad_timer_reset(&current_time);

	id3struct = NULL;

        if (!(options.opt & MPG321_QUIET_PLAY) && file_change)
        {
           /* id3struct = id3_file_open (currentfile, ID3_FILE_MODE_READONLY);*/

            if (id3struct == NULL)
		    get_id3_info(currentfile, &id3struct, &id3tag);
	    if(id3tag)
		    show_id3(id3tag);
	}

	scrobbler_time = -1;
	if(options.opt & MPG321_USE_SCROBBLER)
	{
		if(id3struct == NULL)
			get_id3_info(currentfile,&id3struct,&id3tag);
                
	    if (id3tag)
	    {
		    char emptystring[31], emptyyear[5] = "    ";
		    int i;

		    if(parse_id3(scrobbler_args, id3tag))
		    {
			    memset(emptystring, ' ', 30);
			    emptystring[30] = '\0';
	    		    if((options.opt & MPG321_VERBOSE_PLAY) && (options.opt & MPG321_USE_SCROBBLER))
			    {
				    fprintf(stderr, "\nPreparing for the AudioScrobbler:\n");
				    for(i = 0; i < 6; i++)
				    {
					    if(scrobbler_args[i] == NULL)
						    scrobbler_args[i] =
							    ( i == 3 ? emptyyear: emptystring);
					    fprintf(stderr, "- %s\n", scrobbler_args[i]);
				    }
			    }
		    }
	    }
	}
      

        if (options.opt & MPG321_REMOTE_PLAY && file_change)
        {
		if(id3struct == NULL)
			get_id3_info(currentfile, &id3struct, &id3tag);
		if(id3tag)
                {
                    if (!show_id3(id3tag))
                    {
                        /* This shouldn't be necessary, but it appears that
                           libid3tag doesn't necessarily know if there are no
                           id3 tags on a given mp3 */
                        char * basec = strdup(currentfile);
                        char * basen = basename(basec);
                        
                        char * dot = strrchr(basen, '.');
                        
                        if (dot)
                            *dot = '\0';
                        
                        printf("@I %s\n", basen);

                        free(basec);
                    }
                }
            else
            {
                char * basec = strdup(currentfile);
                char * basen = basename(basec);
                
                char * dot = strrchr(basen, '.');
                
                if (dot)
                    *dot = '\0';
                
                printf("@I %s\n", basen);

                free(basec);
            }
        }

	if(id3struct != NULL)
		id3_file_close(id3struct);

        /* Create the MPEG stream */
        /* Check if source is on the network */
        if((fd = raw_open(currentfile)) != 0 || (fd = http_open(currentfile)) != 0
            || (fd = ftp_open(currentfile)) != 0)
        {
            playbuf.fd = fd;
            playbuf.buf = malloc(BUF_SIZE);
            playbuf.length = BUF_SIZE;
	    if(options.opt & MPG321_ENABLE_BUFFER)
	    {
		    Decoded_Frames->is_http = 1;
		    Decoded_Frames->is_file = 0;
	    }
	    calc_http_length(&playbuf);

            mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0,
                            output, handle_error, /* message */ 0);
        }

        /* Check if we are to use stdin for input */
        else if(strcmp(currentfile, "-") == 0)
        {
            playbuf.fd = fileno(stdin);
            playbuf.buf = malloc(BUF_SIZE);
            playbuf.length = BUF_SIZE;

            mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0,
                            output, handle_error, /* message */ 0);
        }
            
        /* currentfile is a local file (presumably.) mmap() it */
        else
        {
            struct stat stat;
            
            if((fd = open(currentfile, O_RDONLY)) == -1)
            {
	    
                mpg321_error(currentfile);
		/* Restore TTY from keyboard reader thread */
	        if(options.opt & MPG321_ENABLE_BASIC)
			if (tcsetattr(0, TCSANOW, &old_terminal_settings) < 0)
				perror("tcsetattr ICANON");
		if(set_xterm)
	    	{
			set_tty_restore();
	    		osc_print(0,0,title);
	    		if (ctty)
	    			fclose(ctty);
	    	}
		if( options.opt & MPG321_REMOTE_PLAY)
			if(remote_restart)
			{	
				clear_remote_file(pl); /* If restart is enabled, restart remote shell when file doesn't exist*/
				continue;
			}
		if(options.opt & MPG321_ENABLE_BUFFER)
			goto out;
		else
			exit(1);
                /* mpg123 stops immediately if it can't open a file */
		/* If sth goes wrong break!!!*/
                break;
            }

	    if(options.opt & MPG321_ENABLE_BUFFER)
	    {
		    Decoded_Frames->is_http = 0;
		    Decoded_Frames->is_file = 1;
	    }
            
            if(fstat(fd, &stat) == -1)
            {
                mpg321_error(currentfile);
		close(fd);
                continue;
            }
            
            if (!S_ISREG(stat.st_mode))
            {
		    if(S_ISFIFO(stat.st_mode))
		    {
			    fallback = 1;
			    goto fall_back_to_read_from_fd;
		    }

		close(fd);    
                continue;
            }
            
            retval = calc_length(currentfile, &playbuf); //FIXME Check also if it is an mp3 file. If not break and go to the next file possible
	    if(retval < 0)
	    {
		    if(options.opt & MPG321_REMOTE_PLAY)
		    {
			    fprintf(stderr,"@E Corrupted file: %s\n",currentfile);
			    close(fd);
			    if(remote_restart)
			    {
				    clear_remote_file(pl); /* If restart is enabled, restart remote shell when file is corrupted */
				    continue;
			    }
			    break;
		    }
		    mpg321_error(currentfile);
		    close(fd);
//		    break; //FIXME Break and stop OR continue the playlist ????
		    continue;
	    }

	    if((options.opt & MPG321_VERBOSE_PLAY) && (options.opt & MPG321_USE_SCROBBLER))
		    fprintf(stderr, "Track duration: %ld seconds\n",playbuf.duration.seconds);

	    if(options.opt & MPG321_USE_SCROBBLER)
		    scrobbler_set_time(playbuf.duration.seconds);

            if ((options.maxframes != -1) && (options.maxframes <= playbuf.num_frames))
            { 
                playbuf.max_frames = options.maxframes;
            }
            
            playbuf.frames = malloc((playbuf.num_frames + 1) * sizeof(void*));
            playbuf.times = malloc((playbuf.num_frames + 1) * sizeof(mad_timer_t));
#ifdef __uClinux__
	    if((playbuf.buf = mmap(0, playbuf.length, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
#else       
 	    if((playbuf.buf = mmap(0, playbuf.length, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
#endif		    
            {
                mpg321_error(currentfile);
                continue;
            }
            
            playbuf.frames[0] = playbuf.buf;
		    
	    mad_decoder_init(&decoder, &playbuf, read_from_mmap, read_header, /*filter*/0,
            
	    		    output, handle_error, /* message */ 0);
fall_back_to_read_from_fd:	//FIXME. Reported that on some embedded systems with low memory, less than 16MB doesn't work properly.
	    if(fallback)
	    {
	    
		    playbuf.fd = fd;
		    playbuf.buf = malloc(BUF_SIZE);
		    playbuf.length = BUF_SIZE;
		    mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0,
				    output, handle_error, /* message */ 0);
		    fallback = 1;
	    }
        }

        if(!(options.opt & MPG321_QUIET_PLAY))/*zip it!!!*/
        {
            /* Because dirname might modify the argument */
            char * dirc = strdup(currentfile);
            char * basec = strdup(currentfile);

            char * basen = basename(basec);
            char * dirn = dirname(dirc);
            
            /* make sure that the file has a pathname; otherwise don't print out
               a Directory: listing */
            if(strchr(currentfile, '/') && strncmp(old_dir, dirn, PATH_MAX) != 0)
            {
                /* Print information about the file */
                fprintf(stderr, "\n");
                fprintf(stderr,"Directory: %s\n", dirn);
                
                strncpy(old_dir, dirn, PATH_MAX);
                old_dir[PATH_MAX-1] = '\0';
            }
            
            /* print a newline between different songs only, not after
               Directory: listing */
            else
            {
                fprintf(stderr, "\n");
            }

            fprintf(stderr,"Playing MPEG stream from %s ...\n", basen);
            
	    /* Printing xterm title */
	    if(set_xterm)
	    {
		    osc_print(0,0,basen);
	    }
	    
            free(dirc);
            free(basec);
        }    

        signal(SIGINT, handle_signals);
	signal(SIGCHLD, handle_sigchld);
        /*Give control back so that we can implement SIG's*/
	if(set_xterm)
	{
		set_tty_restore();
		if (tcgetattr(0, &terminal_settings) < 0)
			perror("tcgetattr()");
		memcpy(&old_terminal_settings, &terminal_settings, sizeof(struct termios));
		/* disable canonical mode processing in the line discipline driver */
		terminal_settings.c_lflag &= ~(ICANON | ECHO);
		/* apply our new settings */
		if (tcsetattr(0, TCSANOW, &terminal_settings) < 0)
			perror("tcsetattr ICANON");
		if(options.opt & MPG321_ENABLE_BASIC)
		{
			/* Late thread start */
			sem_post(&main_lock);
		}
	}
        /* Every time the user gets us to rewind, we exit decoding,
           reinitialize it, and re-start it */
	    
	if(options.opt & MPG321_ENABLE_BUFFER)
    	{
		Decoded_Frames->total_decoded_frames = 0;
		Decoded_Frames->done = 0;
	}
      
        while (1)
        {
            decoder.options |= MAD_OPTION_IGNORECRC;
            mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);
	    if(options.opt & MPG321_ENABLE_BUFFER)
	    {
		    static struct sembuf start_sops = {2,-1,0};
		    semop(semarray,&start_sops,1);
		    mad_decoder_position = 0;
		    output_buffer_position = 0;
		    union semun sem_ops;
		    sem_ops.val = 0;
		    semctl(semarray,2,SETVAL,sem_ops);
		    Decoded_Frames->total_decoded_frames = 0;
		    Decoded_Frames->done = 0;
		    Decoded_Frames->is_http = 0;
		    Decoded_Frames->is_file = 0;
	    }
            /* if we're rewinding on an mmap()ed stream */
            if(status == MPG321_REWINDING && playbuf.fd == -1) 
            {
                mad_decoder_init(&decoder, &playbuf, read_from_mmap, read_header, /*filter*/0,
                    output, /*error*/0, /* message */ 0);
            }    
            else
                break;
        } 

        if (!(options.opt & MPG321_QUIET_PLAY))
        {
            char time_formatted[11];
            mad_timer_string(current_time, time_formatted, "%.1u:%.2u", MAD_UNITS_MINUTES,
                       MAD_UNITS_SECONDS, 0);
	    fprintf(stderr,"                                                                            \r");
	    fprintf(stderr, "\n[%s] Decoding of %s finished.\n",time_formatted, basename(currentfile)); /* Report total decoded seconds. Maybe for the frame buffer report only total played time?? */
        }
        
        if (options.opt & MPG321_REMOTE_PLAY && status == MPG321_STOPPED)
        {
            clear_remote_file(pl);
        }

        mad_decoder_finish(&decoder);

        if (playbuf.frames)
             free(playbuf.frames);

        if (playbuf.times)
            free(playbuf.times);
            
        if (playbuf.fd == -1)
        {
            munmap(playbuf.buf, playbuf.length);
            close(fd);
        }

        else
        {
            free(playbuf.buf);
            if (playbuf.fd != fileno(stdin)) 
                close(playbuf.fd);
        }
    }

    if(!(options.opt & MPG321_ENABLE_BUFFER))
    {
  	     if(playdevice)
		     ao_close(playdevice);
	     ao_shutdown();
     }

     if (!(options.opt & MPG321_REMOTE_PLAY))
     {
	     if(options.opt & MPG321_ENABLE_BASIC)
	     {
	 	     pflag = 1;
		     /* Restore TTY from keyboard reader thread */
	 	     if (tcsetattr(0, TCSANOW, &old_terminal_settings) < 0)
		 	     perror("tcsetattr ICANON");
	     }
     }
    /*Restoring TTY*/
    if(set_xterm)
    {
	    set_tty_restore();
	    osc_print(0,0,title);
	    if (ctty)
		    fclose(ctty);
    }

out:
    if(options.opt & MPG321_ENABLE_BUFFER)
    {
	    if(kill(output_pid,SIGUSR1) == -1)
		    perror("Error while stopping output process");
	    static int wstatus;
	    wait(&wstatus);
	    if(wstatus == -1)
		    perror("Error while waiting for output process to exit");
	    if(semctl(semarray,0,IPC_RMID) == -1)
		    perror("Error while destroying semaphores");
	    if(shmdt(Output_Queue) == -1)
		    perror("Error while detaching shared buffer");
	    if(shmctl(shm_id,IPC_RMID,NULL))
		    perror("Cannot destroy shared buffer");
	    if(shmctl(frames_id,IPC_RMID,NULL))
		    perror("Cannot destroy shared buffer");
    }
    return(0);
}
コード例 #18
0
ファイル: widget.c プロジェクト: amery/clip-itk
static gint handle_drag_drop_signal (GtkWidget *widget, GdkDragContext *drag_context,
				    gint x, gint y, guint time, C_signal *cs)
  { return handle_signals (widget, cs, NULL); }
コード例 #19
0
ファイル: s6-ftrig-listen.c プロジェクト: 8l/s6
int main (int argc, char const **argv, char const *const *envp)
{
  iopause_fd x[2] = { { -1, IOPAUSE_READ, 0 }, { -1, IOPAUSE_READ, 0 } } ;
  tain_t deadline, tto ;
  ftrigr_t a = FTRIGR_ZERO ;
  int argc1 ;
  unsigned int i = 0 ;
  char or = 0 ;
  PROG = "s6-ftrig-listen" ;
  {
    unsigned int t = 0 ;
    for (;;)
    {
      register int opt = subgetopt(argc, argv, "aot:") ;
      if (opt == -1) break ;
      switch (opt)
      {
        case 'a' : or = 0 ; break ;
        case 'o' : or = 1 ; break ;
        case 't' : if (uint0_scan(subgetopt_here.arg, &t)) break ;
        default : dieusage() ;
      }
    }
    if (t) tain_from_millisecs(&tto, t) ; else tto = tain_infinite_relative ;
    argc -= subgetopt_here.ind ; argv += subgetopt_here.ind ;
  }
  if (argc < 4) dieusage() ;
  argc1 = el_semicolon(argv) ;
  if (!argc1 || (argc1 & 1) || (argc == argc1 + 1)) dieusage() ;
  if (argc1 >= argc) strerr_dief1x(100, "unterminated fifodir+regex block") ;
  tain_now_g() ;
  tain_add_g(&deadline, &tto) ;
  x[0].fd = selfpipe_init() ;
  if (x[0].fd < 0) strerr_diefu1sys(111, "selfpipe_init") ;
  if (selfpipe_trap(SIGCHLD) < 0) strerr_diefu1sys(111, "selfpipe_trap") ;
  if (sig_ignore(SIGPIPE) < 0) strerr_diefu1sys(111, "sig_ignore") ;

  if (!ftrigr_startf_g(&a, &deadline)) strerr_diefu1sys(111, "ftrigr_startf") ;
  x[1].fd = ftrigr_fd(&a) ;

  {
    int pid = 0 ;
    unsigned int idlen = argc1 >> 1 ;
    uint16 ids[idlen] ;
    for (; i < idlen ; i++)
    {
      ids[i] = ftrigr_subscribe_g(&a, argv[i<<1], argv[(i<<1)+1], 0, &deadline) ;
      if (!ids[i]) strerr_diefu4sys(111, "subscribe to ", argv[i<<1], " with regexp ", argv[(i<<1)+1]) ;
    }

    pid = child_spawn0(argv[argc1 + 1], argv + argc1 + 1, envp) ;
    if (!pid) strerr_diefu2sys(111, "spawn ", argv[argc1 + 1]) ;

    for (;;)
    {
      register int r ;
      i = 0 ;
      while (i < idlen)
      {
        char dummy ;
        r = ftrigr_check(&a, ids[i], &dummy) ;
        if (r < 0) strerr_diefu1sys(111, "ftrigr_check") ;
        else if (!r) i++ ;
        else if (or) idlen = 0 ;
        else ids[i] = ids[--idlen] ;
      }
      if (!idlen) break ;
      r = iopause_g(x, 2, &deadline) ;
      if (r < 0) strerr_diefu1sys(111, "iopause") ;
      else if (!r)
      {
        errno = ETIMEDOUT ;
        strerr_diefu1sys(1, "get expected event") ;
      }
      if (x[0].revents & IOPAUSE_READ) handle_signals() ;
      if (x[1].revents & IOPAUSE_READ)
      {
        if (ftrigr_update(&a) < 0) strerr_diefu1sys(111, "ftrigr_update") ;
      }
    }
  }
  return 0 ;
}
コード例 #20
0
ファイル: object.c プロジェクト: amery/clip-itk
/* Signal handlers */
gint handle_destroy_signal (GtkObject *wid, C_signal *cs)
  { return handle_signals (cs->cw->widget, cs, NULL); }
コード例 #21
0
ファイル: widget.c プロジェクト: amery/clip-itk
static gint handle_drag_data_received_signal (GtkWidget *widget, GdkDragContext *drag_context,
	    gint x, gint y, GtkSelectionData *data, guint info, guint time, C_signal *cs)
  { return handle_signals (widget, cs, NULL); }
コード例 #22
0
ファイル: widget.c プロジェクト: amery/clip-itk
static gint handle_debug_msg_signal (GtkWidget *widget, gchar *message, C_signal *cs)
  { return handle_signals (widget, cs, NULL); }
コード例 #23
0
ファイル: cpuworker.c プロジェクト: kitsune-dsu/kitsune-tor
/** Implement a cpuworker.  'data' is an fdarray as returned by socketpair.
 * Read and writes from fdarray[1].  Reads requests, writes answers.
 *
 *   Request format:
 *          Task type           [1 byte, always CPUWORKER_TASK_ONION]
 *          Opaque tag          TAG_LEN
 *          Onionskin challenge ONIONSKIN_CHALLENGE_LEN
 *   Response format:
 *          Success/failure     [1 byte, boolean.]
 *          Opaque tag          TAG_LEN
 *          Onionskin challenge ONIONSKIN_REPLY_LEN
 *          Negotiated keys     KEY_LEN*2+DIGEST_LEN*2
 *
 *  (Note: this _should_ be by addr/port, since we're concerned with specific
 * connections, not with routers (where we'd use identity).)
 */
static void
cpuworker_main(void *data)
{
  char question[ONIONSKIN_CHALLENGE_LEN];
  uint8_t question_type;
  int *fdarray = data;
  int fd;

  /* variables for onion processing */
  char keys[CPATH_KEY_MATERIAL_LEN];
  char reply_to_proxy[ONIONSKIN_REPLY_LEN];
  char buf[LEN_ONION_RESPONSE];
  char tag[TAG_LEN];
  crypto_pk_env_t *onion_key = NULL, *last_onion_key = NULL;

  fd = fdarray[1]; /* this side is ours */
#ifndef TOR_IS_MULTITHREADED
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
                                 * parent uses */
  tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  handle_signals(0); /* ignore interrupts from the keyboard, etc */
#endif
  tor_free(data);

  dup_onion_keys(&onion_key, &last_onion_key);

  for (;;) {
    ssize_t r;

    if ((r = recv(fd, &question_type, 1, 0)) != 1) {
//      log_fn(LOG_ERR,"read type failed. Exiting.");
      if (r == 0) {
        log_info(LD_OR,
                 "CPU worker exiting because Tor process closed connection "
                 "(either rotated keys or died).");
      } else {
        log_info(LD_OR,
                 "CPU worker exiting because of error on connection to Tor "
                 "process.");
        log_info(LD_OR,"(Error on %d was %s)",
                 fd, tor_socket_strerror(tor_socket_errno(fd)));
      }
      goto end;
    }
    tor_assert(question_type == CPUWORKER_TASK_ONION);

    if (read_all(fd, tag, TAG_LEN, 1) != TAG_LEN) {
      log_err(LD_BUG,"read tag failed. Exiting.");
      goto end;
    }

    if (read_all(fd, question, ONIONSKIN_CHALLENGE_LEN, 1) !=
        ONIONSKIN_CHALLENGE_LEN) {
      log_err(LD_BUG,"read question failed. Exiting.");
      goto end;
    }

    if (question_type == CPUWORKER_TASK_ONION) {
      if (onion_skin_server_handshake(question, onion_key, last_onion_key,
          reply_to_proxy, keys, CPATH_KEY_MATERIAL_LEN) < 0) {
        /* failure */
        log_debug(LD_OR,"onion_skin_server_handshake failed.");
        *buf = 0; /* indicate failure in first byte */
        memcpy(buf+1,tag,TAG_LEN);
        /* send all zeros as answer */
        memset(buf+1+TAG_LEN, 0, LEN_ONION_RESPONSE-(1+TAG_LEN));
      } else {
        /* success */
        log_debug(LD_OR,"onion_skin_server_handshake succeeded.");
        buf[0] = 1; /* 1 means success */
        memcpy(buf+1,tag,TAG_LEN);
        memcpy(buf+1+TAG_LEN,reply_to_proxy,ONIONSKIN_REPLY_LEN);
        memcpy(buf+1+TAG_LEN+ONIONSKIN_REPLY_LEN,keys,CPATH_KEY_MATERIAL_LEN);
      }
      if (write_all(fd, buf, LEN_ONION_RESPONSE, 1) != LEN_ONION_RESPONSE) {
        log_err(LD_BUG,"writing response buf failed. Exiting.");
        goto end;
      }
      log_debug(LD_OR,"finished writing response.");
    }
  }
 end:
  if (onion_key)
    crypto_free_pk_env(onion_key);
  if (last_onion_key)
    crypto_free_pk_env(last_onion_key);
  tor_close_socket(fd);
  crypto_thread_cleanup();
  spawn_exit();
}
コード例 #24
0
ファイル: main.c プロジェクト: hreinecke/s390-tools
int main(int argc, char *argv[])
{
	double interval;
	int fd, rc;

	reload_pending = 0;
	sym_names_count = sizeof(sym_names) / sizeof(struct symbol_names);
	varinfo_size = VARINFO_SIZE;
	varinfo = calloc(varinfo_size, 1);
	if (!varinfo) {
		cpuplugd_error("Out of memory: varinfo\n");
		exit(1);
	}
	/*
	 * varinfo must start with '\n' for correct string matching
	 * in get_var_rvalue().
	 */
	varinfo[0] = '\n';

	/* Parse the command line options */
	parse_options(argc, argv);

	/* flock() lock file to prevent multiple instances of cpuplugd */
	fd = open(LOCKFILE, O_CREAT | O_RDONLY, S_IRUSR);
	if (fd == -1) {
		cpuplugd_error("Cannot open lock file %s: %s\n", LOCKFILE,
			       strerror(errno));
		exit(1);
	}
	rc = flock(fd, LOCK_EX | LOCK_NB);
	if (rc) {
		cpuplugd_error("flock() failed on lock file %s: %s\nThis might "
			       "indicate that an instance of this daemon is "
			       "already running.\n", LOCKFILE, strerror(errno));
		exit(1);
	}

	/* Make sure that the daemon is not started multiple times */
	check_if_started_twice();
	/* Store daemon pid also in foreground mode */
	handle_signals();
	handle_sighup();

	/* Need 1 history level minimum for internal symbols */
	history_max = 1;
	/*
	 * Parse arguments from the configuration file, also calculate
	 * history_max
	 */
	parse_configfile(configfile);
	if (history_max > MAX_HISTORY)
		cpuplugd_exit("History depth %i exceeded maximum (%i)\n",
			      history_max, MAX_HISTORY);
	/* Check the settings in the configuration file */
	check_config();

	if (!foreground) {
		rc = daemon(1, 0);
		if (rc < 0)
			cpuplugd_exit("Detach from terminal failed: %s\n",
				      strerror(errno));
	}
	/* Store daemon pid */
	store_pid();
	/* Unlock lock file */
	flock(fd, LOCK_UN);
	close(fd);

	/* Install signal handler for floating point exceptions */
	rc = feenableexcept(FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW |
			    FE_INVALID);
	act.sa_flags = SA_NODEFER;
	sigemptyset(&act.sa_mask);
	act.sa_handler = sigfpe_handler;
	if (sigaction(SIGFPE, &act, NULL) < 0)
		cpuplugd_exit("sigaction( SIGFPE, ... ) failed - reason %s\n",
			      strerror(errno));

	setup_history();

	/* Main loop */
	while (1) {
		if (reload_pending) {		// check for daemon reload
			reload_daemon();
			reload_pending = 0;
		}

		history_prev = history_current;
		history_current = (history_current + 1) % (history_max + 1);
		time_read(&timestamps[history_current]);
		proc_read(meminfo + history_current * meminfo_size,
			  "/proc/meminfo", meminfo_size);
		proc_read(vmstat + history_current * vmstat_size,
			  "/proc/vmstat", vmstat_size);
		proc_cpu_read(cpustat + history_current * cpustat_size);
		interval = timestamps[history_current] -
			   timestamps[history_prev];
		cpuplugd_debug("config update interval: %ld seconds\n",
			       cfg.update);
		cpuplugd_debug("real update interval: %f seconds\n", interval);

		/* Run code that may signal failure via longjmp. */
		if (cpu == 1) {
			if (setjmp(jmpenv) == 0)
				eval_cpu_rules();
			else
				cpuplugd_error("Floating point exception, "
					       "skipping cpu rule "
					       "evaluation.\n");
		}
		if (memory == 1) {
			if (setjmp(jmpenv) == 0)
				eval_mem_rules(interval);
			else
				cpuplugd_error("Floating point exception, "
					       "skipping memory rule "
					       "evaluation.\n");
		}
		sleep(cfg.update);
	}
	return 0;
}
コード例 #25
0
ファイル: mhpdbg.c プロジェクト: andrewbird/dosemu2
static void mhp_poll_loop(void)
{
   static int in_poll_loop;
   char *ptr, *ptr1;
   if (in_poll_loop) {
      error("mhp_poll_loop() reentered\n");
      return;
   }
   in_poll_loop++;
   for (;;) {
      int ostopped;
      handle_signals();
      /* hack: set stopped to 1 to not allow DPMI to run */
      ostopped = mhpdbgc.stopped;
      mhpdbgc.stopped = 1;
      coopth_run();
      mhpdbgc.stopped = ostopped;
      /* NOTE: if there is input on mhpdbg.fdin, as result of handle_signals
       *       io_select() is called and this then calls mhp_input.
       *       ( all clear ? )
       */
      if (mhpdbg.nbytes <= 0) {
         if (traceloop && mhpdbgc.stopped) {
           mhpdbg.nbytes=strlen(loopbuf);
           memcpy(mhpdbg.recvbuf,loopbuf,mhpdbg.nbytes+1);
         }
         else {
          if (mhpdbgc.stopped) {
            usleep(JIFFIE_TIME/10);
            continue;
          }
          else break;
        }
      }
      else {
        if (traceloop) { traceloop=loopbuf[0]=0; }
      }
      if ((mhpdbg.recvbuf[0] == 'q') && (mhpdbg.recvbuf[1] <= ' ')) {
	 if (mhpdbgc.stopped) {
	   mhp_cmd("g");
	   mhp_send();
	 }
	 mhpdbg.active = 0;
	 mhpdbg.sendptr = 0;
         mhpdbg.nbytes = 0;
         break;
      }
      mhpdbg.recvbuf[mhpdbg.nbytes] = 0x00;
      ptr = (char *)mhpdbg.recvbuf;
      while (ptr && *ptr) {
	ptr1 = strsep(&ptr, "\r\n");
	if (!ptr1)
	  ptr1 = ptr;
	if (!ptr1)
	  break;
        mhp_cmd(ptr1);
        mhp_send();
      }
      mhpdbg.nbytes = 0;
   }
   in_poll_loop--;
}
コード例 #26
0
ファイル: fwknopd.c プロジェクト: weizn11/fwknop
int
main(int argc, char **argv)
{
    fko_srv_options_t   opts;
    int depth = 0;

    while(1)
    {
        /* Handle command line
        */
        //处理启动参数。
        config_init(&opts, argc, argv);

#if HAVE_LIBFIU
        /* Set any fault injection points early
        */
        enable_fault_injections(&opts);
#endif

        /* Process any options that do their thing and exit.
        */

        /* Kill the currently running fwknopd process?
        */
        if(opts.kill == 1)
            clean_exit(&opts, NO_FW_CLEANUP, stop_fwknopd(&opts));

        /* Status of the currently running fwknopd process?
        */
        if(opts.status == 1)
            clean_exit(&opts, NO_FW_CLEANUP, status_fwknopd(&opts));

        /* Restart the currently running fwknopd process?
        */
        if(opts.restart == 1)
            clean_exit(&opts, NO_FW_CLEANUP, restart_fwknopd(&opts));

        /* Initialize logging.
        */
        init_logging(&opts);

        /* Update the verbosity level for the log module */
        log_set_verbosity(LOG_DEFAULT_VERBOSITY + opts.verbose);

#if HAVE_LOCALE_H
        /* Set the locale if specified.
        */
        set_locale(&opts);
#endif

        /* Make sure we have a valid run dir and path leading to digest file
         * in case it configured to be somewhere other than the run dir.
        */
        if(!opts.afl_fuzzing
                && ! check_dir_path((const char *)opts.config[CONF_FWKNOP_RUN_DIR], "Run", 0))
            clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);

        /* Initialize the firewall rules handler based on the fwknopd.conf
         * file, but (for iptables firewalls) don't flush any rules or create
         * any chains yet. This allows us to dump the current firewall rules
         * via fw_rules_dump() in --fw-list mode before changing around any rules
         * of an existing fwknopd process.
        */
        if(fw_config_init(&opts) != 1)
            clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);

        if(opts.fw_list == 1 || opts.fw_list_all == 1)
        {
            fw_dump_rules(&opts);
            clean_exit(&opts, NO_FW_CLEANUP, EXIT_SUCCESS);
        }

        if(opts.fw_flush == 1)
        {
            fprintf(stdout, "Deleting any existing firewall rules...\n");
            clean_exit(&opts, FW_CLEANUP, EXIT_SUCCESS);
        }

        if (opts.config[CONF_ACCESS_FOLDER] != NULL) //If we have an access folder, process it
        {
            if (parse_access_folder(&opts, opts.config[CONF_ACCESS_FOLDER], &depth) != EXIT_SUCCESS)
            {
                clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);
            }
        }
        /* Process the access.conf file, but only if no access.conf folder was specified.
        */
        //读入access.conf中的数据。
        else if (parse_access_file(&opts, opts.config[CONF_ACCESS_FILE], &depth) != EXIT_SUCCESS)
        {
            clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);
        }

        /* We must have at least one valid access stanza at this point
        */
        //检查有没有合法的stanza。
        if(! valid_access_stanzas(opts.acc_stanzas))
        {
            log_msg(LOG_ERR, "Fatal, could not find any valid access.conf stanzas");
            clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);
        }

        /* Show config (including access.conf vars) and exit dump config was
         * wanted.
        */
        if(opts.dump_config == 1)
        {
            dump_config(&opts);
            dump_access_list(&opts);
            clean_exit(&opts, NO_FW_CLEANUP, EXIT_SUCCESS);
        }

        /* Now is the right time to bail if we're just parsing the configs
        */
        if(opts.exit_after_parse_config)
        {
            log_msg(LOG_INFO, "Configs parsed, exiting.");
            clean_exit(&opts, NO_FW_CLEANUP, EXIT_SUCCESS);
        }

        /* Acquire pid, become a daemon or run in the foreground, write pid
         * to pid file.
        */
        if(! opts.exit_parse_digest_cache)
            setup_pid(&opts);

        if(opts.verbose > 1 && opts.foreground)
        {
            dump_config(&opts);
            dump_access_list(&opts);
        }

        /* Initialize the digest cache for replay attack detection (either
         * with dbm support or with the default simple cache file strategy)
         * if so configured.
        */
        init_digest_cache(&opts);

        if(opts.exit_parse_digest_cache)
        {
            log_msg(LOG_INFO, "Digest cache parsed, exiting.");
            clean_exit(&opts, NO_FW_CLEANUP, EXIT_SUCCESS);
        }

#if AFL_FUZZING
        /* SPA data from STDIN. */
        if(opts.afl_fuzzing)
        {
            if(opts.config[CONF_AFL_PKT_FILE] != 0x0)
            {
                afl_enc_pkt_from_file(&opts);
            }
            else
            {
                afl_pkt_from_stdin(&opts);
            }
        }
#endif

        /* Prepare the firewall - i.e. flush any old rules and (for iptables)
         * create fwknop chains.
        */
        if(!opts.test && opts.enable_fw && (fw_initialize(&opts) != 1))
            clean_exit(&opts, FW_CLEANUP, EXIT_FAILURE);

        /* If we are to acquire SPA data via a UDP socket, start it up here.
        */
        //启动UDP监听。
        if(opts.enable_udp_server ||
                strncasecmp(opts.config[CONF_ENABLE_UDP_SERVER], "Y", 1) == 0)
        {
            if(run_udp_server(&opts) < 0)
            {
                log_msg(LOG_ERR, "Fatal run_udp_server() error");
                clean_exit(&opts, FW_CLEANUP, EXIT_FAILURE);
            }
            else
            {
                break;
            }
        }

        /* If the TCP server option was set, fire it up here. Note that in
         * this mode, fwknopd still acquires SPA packets via libpcap. If you
         * want to use UDP only without the libpcap dependency, then fwknop
         * needs to be compiled with --enable-udp-server. Note that the UDP
         * server can be run even when fwknopd links against libpcap as well,
         * but there is no reason to link against it if SPA packets are
         * always going to be acquired via a UDP socket.
        */
        if(strncasecmp(opts.config[CONF_ENABLE_TCP_SERVER], "Y", 1) == 0)
        {
            if(run_tcp_server(&opts) < 0)
            {
                log_msg(LOG_ERR, "Fatal run_tcp_server() error");
                clean_exit(&opts, FW_CLEANUP, EXIT_FAILURE);
            }
        }

#if USE_LIBPCAP
        /* Intiate pcap capture mode...
        */
        if(!opts.enable_udp_server
                && strncasecmp(opts.config[CONF_ENABLE_UDP_SERVER], "N", 1) == 0)
        {
            pcap_capture(&opts);
        }
#endif

        /* Deal with any signals that we've received and break out
         * of the loop for any terminating signals
        */
        if(handle_signals(&opts) == 1)
            break;
    }

    log_msg(LOG_INFO, "Shutting Down fwknopd.");

    /* Kill the TCP server (if we have one running).
    */
    if(opts.tcp_server_pid > 0)
    {
        log_msg(LOG_INFO, "Killing the TCP server (pid=%i)",
            opts.tcp_server_pid);

        kill(opts.tcp_server_pid, SIGTERM);

        /* --DSS XXX: This seems to be necessary if the tcp server
         *            was restarted by this program. We need to
         *            investigate and fix this. For now, this works
         *            (it is kludgy, but does no harm afaik).
        */
        kill(opts.tcp_server_pid, SIGKILL);
    }

    clean_exit(&opts, FW_CLEANUP, EXIT_SUCCESS);

    return(EXIT_SUCCESS);  /* This never gets called */
}
コード例 #27
0
ファイル: cpuworker.c プロジェクト: AllardJ/Tomato
/** Implement a cpuworker.  'data' is an fdarray as returned by socketpair.
 * Read and writes from fdarray[1].  Reads requests, writes answers.
 *
 *   Request format:
 *          cpuworker_request_t.
 *   Response format:
 *          cpuworker_reply_t
 */
static void
cpuworker_main(void *data)
{
  /* For talking to the parent thread/process */
  tor_socket_t *fdarray = data;
  tor_socket_t fd;

  /* variables for onion processing */
  server_onion_keys_t onion_keys;
  cpuworker_request_t req;
  cpuworker_reply_t rpl;

  fd = fdarray[1]; /* this side is ours */
#ifndef TOR_IS_MULTITHREADED
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
                                 * parent uses */
  tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  handle_signals(0); /* ignore interrupts from the keyboard, etc */
#endif
  tor_free(data);

  setup_server_onion_keys(&onion_keys);

  for (;;) {
    if (read_all(fd, (void *)&req, sizeof(req), 1) != sizeof(req)) {
      log_info(LD_OR, "read request failed. Exiting.");
      goto end;
    }
    tor_assert(req.magic == CPUWORKER_REQUEST_MAGIC);

    memset(&rpl, 0, sizeof(rpl));

    if (req.task == CPUWORKER_TASK_ONION) {
      const create_cell_t *cc = &req.create_cell;
      created_cell_t *cell_out = &rpl.created_cell;
      struct timeval tv_start = {0,0}, tv_end;
      int n;
      rpl.timed = req.timed;
      rpl.started_at = req.started_at;
      rpl.handshake_type = cc->handshake_type;
      if (req.timed)
        tor_gettimeofday(&tv_start);
      n = onion_skin_server_handshake(cc->handshake_type,
                                      cc->onionskin, cc->handshake_len,
                                      &onion_keys,
                                      cell_out->reply,
                                      rpl.keys, CPATH_KEY_MATERIAL_LEN,
                                      rpl.rend_auth_material);
      if (n < 0) {
        /* failure */
        log_debug(LD_OR,"onion_skin_server_handshake failed.");
        memset(&rpl, 0, sizeof(rpl));
        memcpy(rpl.tag, req.tag, TAG_LEN);
        rpl.success = 0;
      } else {
        /* success */
        log_debug(LD_OR,"onion_skin_server_handshake succeeded.");
        memcpy(rpl.tag, req.tag, TAG_LEN);
        cell_out->handshake_len = n;
        switch (cc->cell_type) {
        case CELL_CREATE:
          cell_out->cell_type = CELL_CREATED; break;
        case CELL_CREATE2:
          cell_out->cell_type = CELL_CREATED2; break;
        case CELL_CREATE_FAST:
          cell_out->cell_type = CELL_CREATED_FAST; break;
        default:
          tor_assert(0);
          goto end;
        }
        rpl.success = 1;
      }
      rpl.magic = CPUWORKER_REPLY_MAGIC;
      if (req.timed) {
        struct timeval tv_diff;
        int64_t usec;
        tor_gettimeofday(&tv_end);
        timersub(&tv_end, &tv_start, &tv_diff);
        usec = ((int64_t)tv_diff.tv_sec)*1000000 + tv_diff.tv_usec;
        if (usec < 0 || usec > MAX_BELIEVABLE_ONIONSKIN_DELAY)
          rpl.n_usec = MAX_BELIEVABLE_ONIONSKIN_DELAY;
        else
          rpl.n_usec = (uint32_t) usec;
      }
      if (write_all(fd, (void*)&rpl, sizeof(rpl), 1) != sizeof(rpl)) {
        log_err(LD_BUG,"writing response buf failed. Exiting.");
        goto end;
      }
      log_debug(LD_OR,"finished writing response.");
    } else if (req.task == CPUWORKER_TASK_SHUTDOWN) {
      log_info(LD_OR,"Clean shutdown: exiting");
      goto end;
    }
    memwipe(&req, 0, sizeof(req));
    memwipe(&rpl, 0, sizeof(req));
  }
 end:
  memwipe(&req, 0, sizeof(req));
  memwipe(&rpl, 0, sizeof(req));
  release_server_onion_keys(&onion_keys);
  tor_close_socket(fd);
  crypto_thread_cleanup();
  spawn_exit();
}
コード例 #28
0
ファイル: yersinia.c プロジェクト: digininja/yersinia
/*
 * Use global *tty_tmp and term_parent
 */
int
main( int argc, char **argv )
{
   struct cl_args *cl_args;
   struct term_node *tty_node = NULL;
   pid_t pid;
   pid_t parent_id;
#if defined(HAVE_PTHREAD_SETCONCURRENCY) && !defined(LINUX)
   int concurrent;
#endif

   handle_signals_parent();

   tcgetattr(0, &term_parent);   

   parent_id = getpid();

   if ((pid = fork()) < 0)
   {
      exit(1);
   }
   else
   {
      if (pid != 0)
      {
         wait(NULL);
         tcsetattr(0, TCSANOW, &term_parent);
         exit(0);
      }
   }

   fatal_error = 4;

   /* Disable all signals while initializing data...*/
   handle_signals();

   setvbuf(stdout, NULL, _IONBF, 0);

   tty_tmp = (struct term_tty *)calloc(1,sizeof(struct term_tty));

   if (tty_tmp == NULL)
   {
      printf("Out of memory on calloc tty_tmp\n");
      clean_exit();
   }

   tty_tmp->term = (struct termios *)calloc(1,sizeof(struct termios));      

   if (tty_tmp->term == NULL)
   {
      printf("Out of memory on calloc tty_tmp->term\n");
      clean_exit();
   }

   /* default values */
   tty_tmp->interactive = 0;
   tty_tmp->gtk = 0;
   tty_tmp->attack = -1;
   tty_tmp->mac_spoofing = -1;
   tty_tmp->splash = -1;
   strncpy(tty_tmp->username, VTY_USER, MAX_USERNAME);
   strncpy(tty_tmp->password, VTY_PASS, MAX_PASSWORD);
   strncpy(tty_tmp->e_password, VTY_ENABLE, MAX_PASSWORD);
   tty_tmp->port = VTY_PORT;
   tty_tmp->ip_filter = NULL;
#ifdef HAVE_GTK
   tty_tmp->buffer_log = NULL;
#endif

   cl_args = (struct cl_args *)calloc(1,sizeof(struct cl_args));

   if (cl_args == NULL)
   {
      printf("Out of memory on calloc cl_args\n");
      clean_exit();
   }

   if ( argc == 1 )                                                          
   {
      printf("GNU %s %s %s\n", PACKAGE, VERSION,
            "$Date: 2006/03/23 08:40:14 $");
      printf("Try '%s -h' to display the help.\n",PACKAGE);
      clean_exit();
   }

   if (getuid() != 0) 
   {
      printf("You must be root to run %s %s\n", PACKAGE, VERSION);
      clean_exit();
   }

   if (term_init() < 0)
      g00dbye();

   /* Register all the protocols */
   protocol_init();

   cl_args->proto_index = -1;

   if (parser_initial(tty_tmp, cl_args, argc, argv) < 0) {
      clean_exit();
   } 

   init_log();

#if defined(HAVE_PTHREAD_SETCONCURRENCY) && !defined(LINUX)
/*   concurrent = pthread_getconcurrency();*/

   concurrent = 15;/*(MAX_TERMS*MAX_PROTOCOLS*MAX_THREAD_ATTACK*2)+3;*/

   if (pthread_setconcurrency(concurrent) != 0)
   {
      thread_error("init pthread_setconcurrency()",errno);
      g00dbye();
   }
#endif

   if (interfaces_init(&terms->pcap_listen_th) < 0 )
      g00dbye();

   /* Establish TERM signal handler...*/
   posix_signal(SIGTERM, final);


#ifdef HAVE_REMOTE_ADMIN
   if (tty_tmp->daemonize)
   {
      if (admin_init(tty_tmp) < 0)
         g00dbye();
   }
#endif 

   if (thread_create(&terms->uptime_th.id, &th_uptime, (void *)NULL) < 0)
      g00dbye();

   /* Command line and ncurses cannot be choosed simultaneously...*/
   if ((!tty_tmp->interactive) && (!tty_tmp->gtk) && (cl_args->proto_index != -1)) 
   {
      terms->work_state = INITIAL;
      tty_node = term_type[TERM_TTY].list;
      if (thread_create(&tty_node[0].thread.id, &th_tty_peer, 
               (void *)cl_args) < 0)
         g00dbye();

      while(terms->work_state != STOPPED)
         thread_usleep(100000);
   }

#ifdef HAS_CURSES
   if (tty_tmp->interactive)
   {
      terms->work_state = INITIAL;
      if (thread_create(&terms->gui_th.id, &ncurses_gui, NULL) < 0 )
         g00dbye();
      /* Wait until the ncurses GUI is over */
      while(terms->work_state != STOPPED)
         thread_usleep(100000);
   }
   else
   {
#endif
#ifdef HAVE_GTK
      if (tty_tmp->gtk)
      {
         terms->work_state = INITIAL;
         if (thread_create(&terms->gui_gtk_th.id, &gtk_gui, NULL) < 0 )
            g00dbye();
         /* Wait until the GTK GUI is over */
         while(terms->work_state != STOPPED)
            thread_usleep(100000);
      }
#endif
#ifdef HAS_CURSES
   }
#endif

#ifdef HAVE_REMOTE_ADMIN
   if (tty_tmp->daemonize)
   {
      /* Ok, now that console (ncurses) is finished
       * we can become a true daemon... */
      become_daemon(parent_id);

      /* Wait until some important thread exits due to fatal_error...*/
      while (fatal_error == 4)
         thread_usleep(100000);
   }
#endif

   g00dbye();

   exit(1);
}
コード例 #29
0
ファイル: main.c プロジェクト: John-He-928/fdkaac
int main(int argc, char **argv)
{
    static m4af_io_callbacks_t m4af_io = {
        read_callback, write_callback, seek_callback, tell_callback
    };
    aacenc_param_ex_t params = { 0 };

    int result = 2;
    char *output_filename = 0;
    pcm_reader_t *reader = 0;
    HANDLE_AACENCODER encoder = 0;
    AACENC_InfoStruct aacinfo = { 0 };
    m4af_ctx_t *m4af = 0;
    const pcm_sample_description_t *sample_format;
    int frame_count = 0;
    int sbr_mode = 0;
    unsigned scale_shift = 0;

    setlocale(LC_CTYPE, "");
    setbuf(stderr, 0);

    if (parse_options(argc, argv, &params) < 0)
        return 1;

    if ((reader = open_input(&params)) == 0)
        goto END;

    sample_format = pcm_get_format(reader);

    sbr_mode = aacenc_is_sbr_active((aacenc_param_t*)&params);
    if (sbr_mode && !aacenc_is_sbr_ratio_available()) {
        fprintf(stderr, "WARNING: Only dual-rate SBR is available "
                        "for this version\n");
        params.sbr_ratio = 2;
    }
    scale_shift = aacenc_is_dual_rate_sbr((aacenc_param_t*)&params);
    params.sbr_signaling =
        (params.transport_format == TT_MP4_LOAS) ? 2 :
        (params.transport_format == TT_MP4_RAW)  ? 1 : 0;
    if (sbr_mode && !scale_shift)
        params.sbr_signaling = 2;

    if (aacenc_init(&encoder, (aacenc_param_t*)&params, sample_format,
                    &aacinfo) < 0)
        goto END;

    if (!params.output_filename) {
        const char *ext = params.transport_format ? ".aac" : ".m4a";
        output_filename = generate_output_filename(params.input_filename, ext);
        params.output_filename = output_filename;
    }

    if ((params.output_fp = aacenc_fopen(params.output_filename, "wb+")) == 0) {
        aacenc_fprintf(stderr, "ERROR: %s: %s\n", params.output_filename,
                       strerror(errno));
        goto END;
    }
    handle_signals();

    if (!params.transport_format) {
        uint32_t scale;
        unsigned framelen = aacinfo.frameLength;
        scale = sample_format->sample_rate >> scale_shift;
        if ((m4af = m4af_create(M4AF_CODEC_MP4A, scale, &m4af_io,
                                params.output_fp)) < 0)
            goto END;
        m4af_set_decoder_specific_info(m4af, 0,
                                       aacinfo.confBuf, aacinfo.confSize);
        m4af_set_fixed_frame_duration(m4af, 0,
                                      framelen >> scale_shift);
        m4af_set_vbr_mode(m4af, 0, params.bitrate_mode);
        m4af_set_priming_mode(m4af, params.gapless_mode + 1);
        m4af_begin_write(m4af);
    }
コード例 #30
0
ファイル: notes.c プロジェクト: tylerberry/newts
int
main (int argc, char **argv)
{
  List nflist;

  short file_flag = FALSE;
  short quit_flag = FALSE;
  int result;

  newts_failed_malloc_hook = curses_malloc_die;

  srand ((unsigned) time (NULL));

  time (&orig_seqtime);
  time (&seqtime);

#ifdef __GLIBC__
  program_name = program_invocation_short_name;
#else
  program_name = base_name (argv[0]);
#endif

  /* Initialize i18n. */

#ifdef HAVE_SETLOCALE
  if (setlocale (LC_ALL, "") == NULL)
    {
      fprintf (stderr, _("%s: could not determine your locale\nCheck the "
                         "environment variables LANG, LC_ALL, etc.\n"),
               program_name);

      exit (EXIT_FAILURE);
    }
#endif

#if ENABLE_NLS
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
#endif

  /* Initial setup and global variable init. */

  init_blacklist ();
  list_init (&nflist,
             (void * (*) (void)) nfref_alloc,
             (void (*) (void *)) nfref_free,
             NULL);

  setup ();

  while (1)
    {
      int opt;
      short override_flag = FALSE;

      static struct option long_options[] =
        {
          {"alternate",       required_argument, 0, 'a'},
          {"black-threads",   no_argument,       0, 'b'},
          {"debug",           no_argument,       0, 'D'},
          {"seq-own-notes",   no_argument,       0, 'e'},
          {"file",            required_argument, 0, 'f'},
          {"no-signature",    no_argument,       0, 'g'},
          {"index",           no_argument,       0, 'i'},
          {"skip-own-notes",  no_argument,       0, 'k'},
          {"modern",          no_argument,       0, 'm'},
          {"no-sequencer",    no_argument,       0, 'n'},
          {"time",            required_argument, 0, 'o'},
          {"sequencer",       no_argument,       0, 's'},
          {"traditional",     no_argument,       0, 't'},
          {"user",            required_argument, 0, 'u'},
          {"white-basenotes", no_argument,       0, 'w'},
          {"extended",        no_argument,       0, 'x'},
          {"imsa",            no_argument,       0, 'y'},
          {"no-blacklist",    no_argument,       0, 'z'},
          {"help",            no_argument,       0, 'h'},
          {"version",         no_argument,       0, 0},
          {0, 0, 0, 0}
        };

      opt = getopt_long (argc, argv, "a:bDef:ghikmno:stu:wxz",
                         long_options, NULL);

      if (opt == -1)
        break;

      switch (opt)
        {
        case 0:
          {
            char *version_string;

            asprintf (&version_string, _("revision: %s"), newts_revision);
            printf (N_("notes - %s %s (%s)\n"), PACKAGE_NAME, VERSION,
                    version_string);

            free (version_string);

            list_destroy (&nflist);
            teardown ();

            if (fclose (stdout) == EOF)
              error (EXIT_FAILURE, errno, _("error writing output"));

            exit (EXIT_SUCCESS);
          }

        case 'a':
          {
            alt_sequencer = TRUE;

            if (sequencer == NONE)
              sequencer = SEQUENCER;

            newts_nrealloc (seqname, strlen (username) + strlen (optarg) + 2,
                            sizeof (char));
            strcpy (seqname, username);
            strcat (seqname, ":");
            strcat (seqname, optarg);

            if (alt_seqname)
              newts_free (alt_seqname);
            alt_seqname = newts_strdup (optarg);

            break;
          }

        case 'b':
          black_skip_seq = TRUE;
          break;

        case 'D':
          debug = TRUE;
          break;

        case 'f':
          if (parse_file (optarg, &nflist))
            file_flag = TRUE;
          break;

        case 'g':
          signature = FALSE;
          break;

        case 'i':
          sequencer = INDEX;
          break;

        case 'k':
          seq_own_notes = FALSE;
          override_flag = TRUE;
          break;

        case 'm':
          seq_own_notes = TRUE;
          break;

        case 'n':
          sequencer = NONE;
          break;

        case 'o':
          {
            struct timespec parsed_time, now;
            now.tv_sec = orig_seqtime;

            if (parse_datetime (&parsed_time, optarg, &now))
              {
                if (alt_time)
                  {
                    fprintf (stderr, _("%s: cannot specify multiple alternate times\n"),
                             program_name);
                    fprintf (stderr, _("See 'info newts' for more information.\n"));

                    list_destroy (&nflist);
                    teardown ();

                    exit (EXIT_FAILURE);
                  }
                else if (parsed_time.tv_sec <= orig_seqtime)
                  {
                    orig_seqtime = seqtime = parsed_time.tv_sec;
                    if (sequencer == NONE)
                      sequencer = SEQUENCER;
                    alt_time = TRUE;
                  }
                else
                  {
                    fprintf (stderr, _("%s: parsed time '%s' in the future\n"),
                             program_name, optarg);
                    fprintf (stderr, _("See 'info newts' for more information.\n"));

                    list_destroy (&nflist);
                    teardown ();

                    exit (EXIT_FAILURE);
                  }
              }
            else
              {
                fprintf (stderr, _("%s: error parsing time '%s'\n"),
                         program_name, optarg);

                list_destroy (&nflist);
                teardown ();

                exit (EXIT_FAILURE);
              }

            break;
          }

        case 's':
          sequencer = SEQUENCER;
          break;

        case 't':
        case 'y':   /* Pseudo-option for --imsa */
          traditional = TRUE;
          if (!override_flag)
            seq_own_notes = TRUE;
          break;

        case 'u':
          {
            struct passwd *pw;

            if (getuid () != 0)
              {
                fprintf (stderr, _("%s: only root is allowed to use '--user'\n"),
                         program_name);

                list_destroy (&nflist);
                teardown ();

                exit (EXIT_FAILURE);
              }

            pw = getpwnam (optarg);
            if (pw)
              {
                seteuid (pw->pw_uid);

                newts_free (username);
                username = newts_strdup (pw->pw_name);

                if (alt_sequencer)
                  {
                    newts_nrealloc (seqname,
                                    strlen (username) + strlen (alt_seqname) + 2,
                                    sizeof (char));
                    strcpy (seqname, username);
                    strcat (seqname, ":");
                    strcat (seqname, alt_seqname);
                  }
                else
                  {
                    newts_free (seqname);
                    seqname = newts_strdup (username);
                  }
              }

            else
              {
                fprintf (stderr, _("%s: no such user: '******'\n"), program_name,
                         optarg);

                list_destroy (&nflist);
                teardown ();

                exit (EXIT_FAILURE);
              }
          }
          break;

        case 'w':
          white_basenotes = TRUE;
          break;

        case 'x':
          sequencer = EXTENDED;
          break;

        case 'z':
          no_blacklist = TRUE;
          break;

        case 'h':
          printf (_("Usage: %s [OPTION]... NOTESFILE...\n"
                    "Run the UIUC-compatible notesfile client.\n\n"),
                  program_name);

          printf (_("If an argument to a long option is mandatory, it is also mandatory "
                    "for the\ncorresponding short option.\n\n"));

          printf (_("General options:\n"
                    "  -f, --file=FILE         Read list of notesfiles to view from specified file\n"
                    "  -g, --no-signature      Turn off automatic signature inclusion\n"
                    "  -h, --help              Display this help and exit\n"
                    "  -u, --user=USER         As root, run notes as the specified user\n"
                    "      --debug             Print debugging messages to stderr\n"
                    "      --version           Display version information and exit\n\n"));

          printf (_("Display options:\n"
                    "  -m, --modern            Use modern, consistent display style (default)\n"
                    "  -t, --traditional       Use traditional UIUC-style display\n"
                    "      --imsa              Use IMSA-style display (same as -t)\n\n"));

          printf (_("Blacklist options:\n"
                    "  -b, --black-threads     Skip threads with blacklisted basenotes while seqing\n"
                    "  -w, --white-basenotes   Do not apply blacklist to basenotes\n"
                    "  -z, --no-blacklist      Do not use the blacklist\n\n"));

          printf (_("Sequencer options:\n"
                    "  -a, --alternate=SEQ     Use alternate sequencer SEQ\n"
                    "  -e, --seq-own-notes     Make the sequencer view your notes\n"
                    "  -i, --index             Use the index sequencer\n"
                    "  -k, --skip-own-notes    Make the sequencer ignore your notes (default)\n"
                    "  -n, --no-sequencer      Do not use the sequencer (default)\n"
                    "  -o, --time=TIME         Use this date and time for the sequencer\n"
                    "  -s, --sequencer         Use the sequencer to read notes\n"
                    "  -x, --extended          Use the extended sequencer\n\n"));

          printf (_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);

          list_destroy (&nflist);
          teardown ();

          if (fclose (stdout) == EOF)
            error (EXIT_FAILURE, errno, _("error writing output"));

          exit (EXIT_SUCCESS);

        case '?':
          fprintf (stderr, _("Try '%s --help' for more information.\n"),
                   program_name);

          list_destroy (&nflist);
          teardown ();

          exit (EXIT_FAILURE);
        }
    }

  if (optind == argc && !file_flag)
    {
      if (sequencer == NONE)
        {
          struct stat statbuf;

          fprintf (stderr, _("%s: too few arguments\n"), program_name);
          fprintf (stderr, _("Try '%s --help' for more information.\n"),
                   program_name);

          /* FIXME: should be a call to the notes system. */

          if (stat ("/etc/avail.notes", &statbuf) == 0)
            {
              fprintf (stderr,
                       _("Hit <RET> for a list of notesfiles on this system.\n"));
              getchar ();

              spawn_process (NULL, pager, "/etc/avail.notes", NULL);
            }

          list_destroy (&nflist);
          teardown ();

          exit (EXIT_FAILURE);
        }
      else
        {
          char *copy, *list, *token, *nfseq;

          nfseq = getenv ("NFSEQ");
          if (nfseq == NULL)
            {
              fprintf (stderr, _("%s: NFSEQ environment variable not set\n"),
                       program_name);
              fprintf (stderr, _("See 'info newts' for more information.\n"));

              list_destroy (&nflist);
              teardown ();

              exit (EXIT_FAILURE);
            }

          copy = newts_strdup (nfseq);

          token = strtok_r (copy, ", ", &list);
          while (token != NULL)
            {
              parse_nf (token, &nflist);
              token = strtok_r (NULL, ", ", &list);
            }

          newts_free (copy);
        }
    }
  else
    {
      while (optind < argc)
        parse_nf (argv[optind++], &nflist);
    }

  handle_signals ();

  /* For each notesfile, start up the master routine and go. */

  {
    ListNode *node = list_head (&nflist);

    while (node && !quit_flag)
      {
        newts_nfref *ref = (newts_nfref *) list_data (node);

        result = master (ref);

        node = list_next (node);

        if (result == QUITSEQ || result == QUITNOSEQ)
          quit_flag = TRUE;
      }
  }

  ignore_signals ();
  exit_curses ();

  if (*messages != '\0')
    printf ("%s", messages);

  teardown ();

  if (fclose (stdout) == EOF)
    error (EXIT_FAILURE, errno, _("error writing output"));

  exit (EXIT_SUCCESS);
}