예제 #1
0
파일: loader.c 프로젝트: abbrev/xs
/*! \return 0 on success.
*/
int lnp_assured_write(const unsigned char *data, unsigned char length,
                      unsigned char dest, unsigned char srcport) {
  int i;
  struct timeval timeout,now;
  unsigned long total,elapsed;
  
  for(i=0; i<XMIT_RETRIES; i++) {
    receivedAck=0;
    
    lnp_addressing_write(data,length,dest,srcport);
    
    gettimeofday(&timeout,0);
    total=REPLY_TIMEOUT+length*BYTE_TIME;
    elapsed=0;

    do {
#if defined(_WIN32)
      io_handler();
#else
      struct timeval tv;
      fd_set fds;

      FD_ZERO(&fds);
      FD_SET(rcxFD(), &fds);

      tv.tv_sec = (total - elapsed) / 1000000;
      tv.tv_usec = (total - elapsed) % 1000000;
      select(rcxFD() + 1, &fds, NULL, NULL, &tv);
      if (FD_ISSET(rcxFD(), &fds))
	io_handler();
#endif
 
      gettimeofday(&now,0);
      elapsed=1000000*(now.tv_sec  - timeout.tv_sec ) +
	       	       now.tv_usec - timeout.tv_usec;
      
    } while((!receivedAck) && (elapsed < total));
    
    if(i || !receivedAck)
      if(verbose_flag)
        fprintf(stderr,"try %d: ack:%d\n",i,receivedAck);
    
    if(receivedAck)
      return 0;    
   }
  
  return -1;
}
예제 #2
0
파일: mrtrix.cpp 프로젝트: emanuele/mrtrix3
    std::unique_ptr<ImageIO::Base> MRtrix::create (Header& H) const
    {
      File::OFStream out (H.name(), std::ios::out | std::ios::binary);

      out << "mrtrix image\n";

      write_mrtrix_header (H, out);

      bool single_file = Path::has_suffix (H.name(), ".mif");

      int64_t offset = 0;
      out << "file: ";
      if (single_file) {
        offset = out.tellp() + int64_t(18);
        offset += ((4 - (offset % 4)) % 4);
        out << ". " << offset << "\nEND\n";
      }
      else out << Path::basename (H.name().substr (0, H.name().size()-4) + ".dat") << "\n";

      out.close();

      std::unique_ptr<ImageIO::Base> io_handler (new ImageIO::Default (H));
      if (single_file) {
        File::resize (H.name(), offset + footprint(H));
        io_handler->files.push_back (File::Entry (H.name(), offset));
      }
      else {
        std::string data_file (H.name().substr (0, H.name().size()-4) + ".dat");
        File::create (data_file, footprint(H));
        io_handler->files.push_back (File::Entry (data_file));
      }

      return io_handler;
    }
예제 #3
0
    std::unique_ptr<ImageIO::Base> MRtrix_sparse::create (Header& H) const
    {

      const auto name_it = H.keyval().find (Sparse::name_key);
      if (name_it == H.keyval().end())
        throw Exception ("Cannot create sparse image " + H.name() + "; no knowledge of underlying data class type");

      const auto size_it = H.keyval().find (Sparse::size_key);
      if (size_it == H.keyval().end())
        throw Exception ("Cannot create sparse image " + H.name() + "; no knowledge of underlying data class size");

      H.datatype() = DataType::UInt64;
      H.datatype().set_byte_order_native();

      File::OFStream out (H.name(), std::ios::out | std::ios::binary);

      out << "mrtrix sparse image\n";

      write_mrtrix_header (H, out);

      bool single_file = Path::has_suffix (H.name(), ".msf");

      int64_t image_offset = 0, sparse_offset = 0;
      std::string image_path, sparse_path;
      if (single_file) {

        image_offset = out.tellp() + int64_t(54);
        image_offset += ((4 - (image_offset % 4)) % 4);
        sparse_offset = image_offset + footprint(H);

        out << "file: . " << image_offset << "\nsparse_file: . " << sparse_offset << "\nEND\n";

        File::resize (H.name(), sparse_offset);
        image_path = H.name();
        sparse_path = H.name();

      } else {

        image_path  = Path::basename (H.name().substr (0, H.name().size()-4) + ".dat");
        sparse_path = Path::basename (H.name().substr (0, H.name().size()-4) + ".sdat");

        out << "file: " << image_path << "\nsparse_file: " << sparse_path << "\nEND\n";

        File::create (image_path, footprint(H));
        File::create (sparse_path);

      }

      std::unique_ptr<ImageIO::Sparse> io_handler (new ImageIO::Sparse (H, name_it->second, to<size_t>(size_it->second), File::Entry (sparse_path, sparse_offset)));
      io_handler->files.push_back (File::Entry (image_path, image_offset));

      return std::move (io_handler);
    }
예제 #4
0
    std::unique_ptr<ImageIO::Base> MRtrix_sparse::read (Header& H) const
    {
      if (!Path::has_suffix (H.name(), ".msh") && !Path::has_suffix (H.name(), ".msf"))
        return std::unique_ptr<ImageIO::Base>();

      File::KeyValue kv (H.name(), "mrtrix sparse image");

      read_mrtrix_header (H, kv);

      // Although the endianness of the image data itself (the sparse data offsets) actually doesn't matter
      //   (the Image class would deal with this conversion), the sparse data itself needs to have
      //   the correct endianness for the system. Since MRtrix_sparse::create() forces the endianness of the
      //   offset data to be native, this is the easiest way to verify that the sparse data also has the
      //   correct endianness
#ifdef MRTRIX_BYTE_ORDER_BIG_ENDIAN
      const DataType dt = DataType::UInt64BE;
#else
      const DataType dt = DataType::UInt64LE;
#endif
      if (H.datatype() != dt)
        throw Exception ("Cannot open sparse image file " + H.name() + " due to type mismatch; expect " + dt.description() + ", file is " + H.datatype().description());

      const auto name_it = H.keyval().find (Sparse::name_key);
      if (name_it == H.keyval().end())
        throw Exception ("sparse data class name not specified in sparse image header " + H.name());

      const auto size_it = H.keyval().find (Sparse::size_key);
      if (size_it == H.keyval().end())
        throw Exception ("sparse data class size not specified in sparse image header " + H.name());

      std::string image_fname, sparse_fname;
      size_t image_offset, sparse_offset;

      get_mrtrix_file_path (H, "file", image_fname, image_offset);

      File::ParsedName::List image_list;
      std::vector<int> image_num = image_list.parse_scan_check (image_fname);

      get_mrtrix_file_path (H, "sparse_file", sparse_fname, sparse_offset);

      std::unique_ptr<ImageIO::Sparse> io_handler (new ImageIO::Sparse (H, name_it->second, to<size_t>(size_it->second), File::Entry (sparse_fname, sparse_offset)));
      for (size_t n = 0; n < image_list.size(); ++n)
        io_handler->files.push_back (File::Entry (image_list[n].name(), image_offset));

      return std::move (io_handler);
    }
예제 #5
0
size_t 
listen_handler(MSP_SOCKET sock, msp_state_t state,
			const uint8_t *payload, size_t len, void *context)
{
	std::cout << "listen handler" << std::endl;

	if (state & (MSP_STATE_ERROR | MSP_STATE_CLOSED))
		quit = 1;
	else {
		// ... set up resources needed for the new connection ...
		msp_set_handler(sock, io_handler, NULL);

		if (payload && len)
			return io_handler(sock, state, payload, len, NULL);
	}

	return 0;
}
예제 #6
0
파일: mrtrix.cpp 프로젝트: emanuele/mrtrix3
    std::unique_ptr<ImageIO::Base> MRtrix::read (Header& H) const
    {
      if (!Path::has_suffix (H.name(), ".mih") && !Path::has_suffix (H.name(), ".mif"))
        return std::unique_ptr<ImageIO::Base>();

      File::KeyValue kv (H.name(), "mrtrix image");

      read_mrtrix_header (H, kv);

      std::string fname;
      size_t offset;
      get_mrtrix_file_path (H, "file", fname, offset);

      File::ParsedName::List list;
      auto num = list.parse_scan_check (fname);

      std::unique_ptr<ImageIO::Base> io_handler (new ImageIO::Default (H));
      for (size_t n = 0; n < list.size(); ++n)
        io_handler->files.push_back (File::Entry (list[n].name(), offset));

      return io_handler;
    }
예제 #7
0
    std::unique_ptr<ImageIO::Base> Pipe::read (Header& H) const
    {
      if (H.name() == "-") {
        std::string name;
        getline (std::cin, name);
        H.name() = name;
      }
      else {
        if (!File::is_tempfile (H.name())) 
          return std::unique_ptr<ImageIO::Base>();
      }

      if (H.name().empty())
        throw Exception ("no filename supplied to standard input (broken pipe?)");

      SignalHandler::mark_file_for_deletion (H.name());

      if (!Path::has_suffix (H.name(), ".mif"))
        throw Exception ("MRtrix only supports the .mif format for command-line piping");

      std::unique_ptr<ImageIO::Base> original_handler (mrtrix_handler.read (H));
      std::unique_ptr<ImageIO::Pipe> io_handler (new ImageIO::Pipe (std::move (*original_handler)));
      return std::move (io_handler);
    }
예제 #8
0
파일: ntpd.c 프로젝트: ajinkya93/netbsd-src
int
ntpdmain(
	int argc,
	char *argv[]
	)
{
	l_fp		now;
	struct recvbuf *rbuf;
	const char *	logfilename;
# ifdef HAVE_UMASK
	mode_t		uv;
# endif
# if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
	uid_t		uid;
# endif
# if defined(HAVE_WORKING_FORK)
	long		wait_sync = 0;
	int		pipe_fds[2];
	int		rc;
	int		exit_code;
#  ifdef _AIX
	struct sigaction sa;
#  endif
#  if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
	int		fid;
#  endif
# endif	/* HAVE_WORKING_FORK*/
# ifdef SCO5_CLOCK
	int		fd;
	int		zero;
# endif

# ifdef NEED_PTHREAD_WARMUP
	my_pthread_warmup();
# endif
	
# ifdef HAVE_UMASK
	uv = umask(0);
	if (uv)
		umask(uv);
	else
		umask(022);
# endif
	saved_argc = argc;
	saved_argv = argv;
	progname = argv[0];
	initializing = TRUE;		/* mark that we are initializing */
	parse_cmdline_opts(&argc, &argv);
# ifdef DEBUG
	debug = OPT_VALUE_SET_DEBUG_LEVEL;
#  ifdef HAVE_SETLINEBUF
	setlinebuf(stdout);
#  endif
# endif

	if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
# ifdef DEBUG
	    || debug
# endif
	    || HAVE_OPT(SAVECONFIGQUIT))
		nofork = TRUE;

	init_logging(progname, NLOG_SYNCMASK, TRUE);
	/* honor -l/--logfile option to log to a file */
	if (HAVE_OPT(LOGFILE)) {
		logfilename = OPT_ARG(LOGFILE);
		syslogit = FALSE;
		change_logfile(logfilename, FALSE);
	} else {
		logfilename = NULL;
		if (nofork)
			msyslog_term = TRUE;
		if (HAVE_OPT(SAVECONFIGQUIT))
			syslogit = FALSE;
	}
	msyslog(LOG_NOTICE, "%s: Starting", Version);

	{
		int i;
		char buf[1024];	/* Secret knowledge of msyslog buf length */
		char *cp = buf;

		/* Note that every arg has an initial space character */
		snprintf(cp, sizeof(buf), "Command line:");
		cp += strlen(cp);

		for (i = 0; i < saved_argc ; ++i) {
			snprintf(cp, sizeof(buf) - (cp - buf),
				" %s", saved_argv[i]);
			cp += strlen(cp);
		}
		msyslog(LOG_INFO, "%s", buf);
	}

	/*
	 * Install trap handlers to log errors and assertion failures.
	 * Default handlers print to stderr which doesn't work if detached.
	 */
	isc_assertion_setcallback(assertion_failed);
	isc_error_setfatal(library_fatal_error);
	isc_error_setunexpected(library_unexpected_error);

	/* MPE lacks the concept of root */
# if defined(HAVE_GETUID) && !defined(MPE)
	uid = getuid();
	if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
		msyslog_term = TRUE;
		msyslog(LOG_ERR,
			"must be run as root, not uid %ld", (long)uid);
		exit(1);
	}
# endif

/*
 * Enable the Multi-Media Timer for Windows?
 */
# ifdef SYS_WINNT
	if (HAVE_OPT( MODIFYMMTIMER ))
		set_mm_timer(MM_TIMER_HIRES);
# endif

#ifdef HAVE_DNSREGISTRATION
/*
 * Enable mDNS registrations?
 */
	if (HAVE_OPT( MDNS )) {
		mdnsreg = TRUE;
	}
#endif  /* HAVE_DNSREGISTRATION */

	if (HAVE_OPT( NOVIRTUALIPS ))
		listen_to_virtual_ips = 0;

	/*
	 * --interface, listen on specified interfaces
	 */
	if (HAVE_OPT( INTERFACE )) {
		int		ifacect = STACKCT_OPT( INTERFACE );
		const char**	ifaces  = STACKLST_OPT( INTERFACE );
		sockaddr_u	addr;

		while (ifacect-- > 0) {
			add_nic_rule(
				is_ip_address(*ifaces, AF_UNSPEC, &addr)
					? MATCH_IFADDR
					: MATCH_IFNAME,
				*ifaces, -1, ACTION_LISTEN);
			ifaces++;
		}
	}

	if (HAVE_OPT( NICE ))
		priority_done = 0;

# ifdef HAVE_SCHED_SETSCHEDULER
	if (HAVE_OPT( PRIORITY )) {
		config_priority = OPT_VALUE_PRIORITY;
		config_priority_override = 1;
		priority_done = 0;
	}
# endif

# ifdef HAVE_WORKING_FORK
	/* make sure the FDs are initialised */
	pipe_fds[0] = -1;
	pipe_fds[1] = -1;
	do {					/* 'loop' once */
		if (!HAVE_OPT( WAIT_SYNC ))
			break;
		wait_sync = OPT_VALUE_WAIT_SYNC;
		if (wait_sync <= 0) {
			wait_sync = 0;
			break;
		}
		/* -w requires a fork() even with debug > 0 */
		nofork = FALSE;
		if (pipe(pipe_fds)) {
			exit_code = (errno) ? errno : -1;
			msyslog(LOG_ERR,
				"Pipe creation failed for --wait-sync: %m");
			exit(exit_code);
		}
		waitsync_fd_to_close = pipe_fds[1];
	} while (0);				/* 'loop' once */
# endif	/* HAVE_WORKING_FORK */

	init_lib();
# ifdef SYS_WINNT
	/*
	 * Start interpolation thread, must occur before first
	 * get_systime()
	 */
	init_winnt_time();
# endif
	/*
	 * Initialize random generator and public key pair
	 */
	get_systime(&now);

	ntp_srandom((int)(now.l_i * now.l_uf));

	/*
	 * Detach us from the terminal.  May need an #ifndef GIZMO.
	 */
	if (!nofork) {

# ifdef HAVE_WORKING_FORK
		rc = fork();
		if (-1 == rc) {
			exit_code = (errno) ? errno : -1;
			msyslog(LOG_ERR, "fork: %m");
			exit(exit_code);
		}
		if (rc > 0) {	
			/* parent */
			exit_code = wait_child_sync_if(pipe_fds[0],
						       wait_sync);
			exit(exit_code);
		}
		
		/*
		 * child/daemon 
		 * close all open files excepting waitsync_fd_to_close.
		 * msyslog() unreliable until after init_logging().
		 */
		closelog();
		if (syslog_file != NULL) {
			fclose(syslog_file);
			syslog_file = NULL;
			syslogit = TRUE;
		}
		close_all_except(waitsync_fd_to_close);
		INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
			&& 2 == dup2(0, 2));

		init_logging(progname, 0, TRUE);
		/* we lost our logfile (if any) daemonizing */
		setup_logfile(logfilename);

#  ifdef SYS_DOMAINOS
		{
			uid_$t puid;
			status_$t st;

			proc2_$who_am_i(&puid);
			proc2_$make_server(&puid, &st);
		}
#  endif	/* SYS_DOMAINOS */
#  ifdef HAVE_SETSID
		if (setsid() == (pid_t)-1)
			msyslog(LOG_ERR, "setsid(): %m");
#  elif defined(HAVE_SETPGID)
		if (setpgid(0, 0) == -1)
			msyslog(LOG_ERR, "setpgid(): %m");
#  else		/* !HAVE_SETSID && !HAVE_SETPGID follows */
#   ifdef TIOCNOTTY
		fid = open("/dev/tty", 2);
		if (fid >= 0) {
			ioctl(fid, (u_long)TIOCNOTTY, NULL);
			close(fid);
		}
#   endif	/* TIOCNOTTY */
		ntp_setpgrp(0, getpid());
#  endif	/* !HAVE_SETSID && !HAVE_SETPGID */
#  ifdef _AIX
		/* Don't get killed by low-on-memory signal. */
		sa.sa_handler = catch_danger;
		sigemptyset(&sa.sa_mask);
		sa.sa_flags = SA_RESTART;
		sigaction(SIGDANGER, &sa, NULL);
#  endif	/* _AIX */
# endif		/* HAVE_WORKING_FORK */
	}

# ifdef SCO5_CLOCK
	/*
	 * SCO OpenServer's system clock offers much more precise timekeeping
	 * on the base CPU than the other CPUs (for multiprocessor systems),
	 * so we must lock to the base CPU.
	 */
	fd = open("/dev/at1", O_RDONLY);		
	if (fd >= 0) {
		zero = 0;
		if (ioctl(fd, ACPU_LOCK, &zero) < 0)
			msyslog(LOG_ERR, "cannot lock to base CPU: %m");
		close(fd);
	}
# endif

	/* Setup stack size in preparation for locking pages in memory. */
# if defined(HAVE_MLOCKALL)
#  ifdef HAVE_SETRLIMIT
	ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
#   ifdef RLIMIT_MEMLOCK
	/*
	 * The default RLIMIT_MEMLOCK is very low on Linux systems.
	 * Unless we increase this limit malloc calls are likely to
	 * fail if we drop root privilege.  To be useful the value
	 * has to be larger than the largest ntpd resident set size.
	 */
	ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
#   endif	/* RLIMIT_MEMLOCK */
#  endif	/* HAVE_SETRLIMIT */
# else	/* !HAVE_MLOCKALL follows */
#  ifdef HAVE_PLOCK
#   ifdef PROCLOCK
#    ifdef _AIX
	/*
	 * set the stack limit for AIX for plock().
	 * see get_aix_stack() for more info.
	 */
	if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
		msyslog(LOG_ERR,
			"Cannot adjust stack limit for plock: %m");
#    endif	/* _AIX */
#   endif	/* PROCLOCK */
#  endif	/* HAVE_PLOCK */
# endif	/* !HAVE_MLOCKALL */

	/*
	 * Set up signals we pay attention to locally.
	 */
# ifdef SIGDIE1
	signal_no_reset(SIGDIE1, finish);
	signal_no_reset(SIGDIE2, finish);
	signal_no_reset(SIGDIE3, finish);
	signal_no_reset(SIGDIE4, finish);
# endif
# ifdef SIGBUS
	signal_no_reset(SIGBUS, finish);
# endif

# if !defined(SYS_WINNT) && !defined(VMS)
#  ifdef DEBUG
	(void) signal_no_reset(MOREDEBUGSIG, moredebug);
	(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
#  else
	(void) signal_no_reset(MOREDEBUGSIG, no_debug);
	(void) signal_no_reset(LESSDEBUGSIG, no_debug);
#  endif	/* DEBUG */
# endif	/* !SYS_WINNT && !VMS */

	/*
	 * Set up signals we should never pay attention to.
	 */
# ifdef SIGPIPE
	signal_no_reset(SIGPIPE, SIG_IGN);
# endif

	/*
	 * Call the init_ routines to initialize the data structures.
	 *
	 * Exactly what command-line options are we expecting here?
	 */
	INIT_SSL();
	init_auth();
	init_util();
	init_restrict();
	init_mon();
	init_timer();
	init_request();
	init_control();
	init_peer();
# ifdef REFCLOCK
	init_refclock();
# endif
	set_process_priority();
	init_proto();		/* Call at high priority */
	init_io();
	init_loopfilter();
	mon_start(MON_ON);	/* monitor on by default now	  */
				/* turn off in config if unwanted */

	/*
	 * Get the configuration.  This is done in a separate module
	 * since this will definitely be different for the gizmo board.
	 */
	getconfig(argc, argv);

	if (-1 == cur_memlock) {
# if defined(HAVE_MLOCKALL)
		/*
		 * lock the process into memory
		 */
		if (   !HAVE_OPT(SAVECONFIGQUIT)
#  ifdef RLIMIT_MEMLOCK
		    && -1 != DFLT_RLIMIT_MEMLOCK
#  endif
		    && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
			msyslog(LOG_ERR, "mlockall(): %m");
# else	/* !HAVE_MLOCKALL follows */
#  ifdef HAVE_PLOCK
#   ifdef PROCLOCK
		/*
		 * lock the process into memory
		 */
		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
			msyslog(LOG_ERR, "plock(PROCLOCK): %m");
#   else	/* !PROCLOCK follows  */
#    ifdef TXTLOCK
		/*
		 * Lock text into ram
		 */
		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
			msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
#    else	/* !TXTLOCK follows */
		msyslog(LOG_ERR, "plock() - don't know what to lock!");
#    endif	/* !TXTLOCK */
#   endif	/* !PROCLOCK */
#  endif	/* HAVE_PLOCK */
# endif	/* !HAVE_MLOCKALL */
	}

	loop_config(LOOP_DRIFTINIT, 0);
	report_event(EVNT_SYSRESTART, NULL, NULL);
	initializing = FALSE;

# ifdef HAVE_DROPROOT
	if (droproot) {
		/* Drop super-user privileges and chroot now if the OS supports this */

#  ifdef HAVE_LINUX_CAPABILITIES
		/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
		if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
			msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
			exit(-1);
		}
#  elif HAVE_SOLARIS_PRIVS
		/* Nothing to do here */
#  else
		/* we need a user to switch to */
		if (user == NULL) {
			msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
			exit(-1);
		}
#  endif	/* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */

		if (user != NULL) {
			if (isdigit((unsigned char)*user)) {
				sw_uid = (uid_t)strtoul(user, &endp, 0);
				if (*endp != '\0')
					goto getuser;

				if ((pw = getpwuid(sw_uid)) != NULL) {
					free(user);
					user = estrdup(pw->pw_name);
					sw_gid = pw->pw_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find user ID %s", user);
					exit (-1);
				}

			} else {
getuser:
				errno = 0;
				if ((pw = getpwnam(user)) != NULL) {
					sw_uid = pw->pw_uid;
					sw_gid = pw->pw_gid;
				} else {
					if (errno)
						msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
					else
						msyslog(LOG_ERR, "Cannot find user `%s'", user);
					exit (-1);
				}
			}
		}
		if (group != NULL) {
			if (isdigit((unsigned char)*group)) {
				sw_gid = (gid_t)strtoul(group, &endp, 0);
				if (*endp != '\0')
					goto getgroup;
			} else {
getgroup:
				if ((gr = getgrnam(group)) != NULL) {
					sw_gid = gr->gr_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find group `%s'", group);
					exit (-1);
				}
			}
		}

		if (chrootdir ) {
			/* make sure cwd is inside the jail: */
			if (chdir(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chroot(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chdir("/")) {
				msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
				exit (-1);
			}
		}
#  ifdef HAVE_SOLARIS_PRIVS
		if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
			msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
			exit(-1);
		}
		if ((highprivs = priv_allocset()) == NULL) {
			msyslog(LOG_ERR, "priv_allocset() failed:%m");
			exit(-1);
		}
		(void) getppriv(PRIV_PERMITTED, highprivs);
		(void) priv_intersect(highprivs, lowprivs);
		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
			msyslog(LOG_ERR, "setppriv() failed:%m");
			exit(-1);
		}
#  endif /* HAVE_SOLARIS_PRIVS */
		if (user && initgroups(user, sw_gid)) {
			msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
			exit (-1);
		}
		if (group && setgid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
			exit (-1);
		}
		if (group && setegid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
			exit (-1);
		}
		if (group) {
			if (0 != setgroups(1, &sw_gid)) {
				msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
				exit (-1);
			}
		}
		else if (pw)
			if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
				msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
				exit (-1);
			}
		if (user && setuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
			exit (-1);
		}
		if (user && seteuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
			exit (-1);
		}

#  if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
		/*
		 * for now assume that the privilege to bind to privileged ports
		 * is associated with running with uid 0 - should be refined on
		 * ports that allow binding to NTP_PORT with uid != 0
		 */
		disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
#  endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */

		if (disable_dynamic_updates && interface_interval) {
			interface_interval = 0;
			msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
		}

#  ifdef HAVE_LINUX_CAPABILITIES
		{
			/*
			 *  We may be running under non-root uid now, but we still hold full root privileges!
			 *  We drop all of them, except for the crucial one or two: cap_sys_time and
			 *  cap_net_bind_service if doing dynamic interface tracking.
			 */
			cap_t caps;
			char *captext;
			
			captext = (0 != interface_interval)
				      ? "cap_sys_time,cap_net_bind_service=pe"
				      : "cap_sys_time=pe";
			caps = cap_from_text(captext);
			if (!caps) {
				msyslog(LOG_ERR,
					"cap_from_text(%s) failed: %m",
					captext);
				exit(-1);
			}
			if (-1 == cap_set_proc(caps)) {
				msyslog(LOG_ERR,
					"cap_set_proc() failed to drop root privs: %m");
				exit(-1);
			}
			cap_free(caps);
		}
#  endif	/* HAVE_LINUX_CAPABILITIES */
#  ifdef HAVE_SOLARIS_PRIVS
		if (priv_delset(lowprivs, "proc_setid") == -1) {
			msyslog(LOG_ERR, "priv_delset() failed:%m");
			exit(-1);
		}
		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
			msyslog(LOG_ERR, "setppriv() failed:%m");
			exit(-1);
		}
		priv_freeset(lowprivs);
		priv_freeset(highprivs);
#  endif /* HAVE_SOLARIS_PRIVS */
		root_dropped = TRUE;
		fork_deferred_worker();
	}	/* if (droproot) */
# endif	/* HAVE_DROPROOT */

/* libssecomp sandboxing */
#if defined (LIBSECCOMP) && (KERN_SECCOMP)
	scmp_filter_ctx ctx;

	if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
		msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
	else {
		msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
	}

#ifdef __x86_64__
int scmp_sc[] = {
	SCMP_SYS(adjtimex),
	SCMP_SYS(bind),
	SCMP_SYS(brk),
	SCMP_SYS(chdir),
	SCMP_SYS(clock_gettime),
	SCMP_SYS(clock_settime),
	SCMP_SYS(close),
	SCMP_SYS(connect),
	SCMP_SYS(exit_group),
	SCMP_SYS(fstat),
	SCMP_SYS(fsync),
	SCMP_SYS(futex),
	SCMP_SYS(getitimer),
	SCMP_SYS(getsockname),
	SCMP_SYS(ioctl),
	SCMP_SYS(lseek),
	SCMP_SYS(madvise),
	SCMP_SYS(mmap),
	SCMP_SYS(munmap),
	SCMP_SYS(open),
	SCMP_SYS(poll),
	SCMP_SYS(read),
	SCMP_SYS(recvmsg),
	SCMP_SYS(rename),
	SCMP_SYS(rt_sigaction),
	SCMP_SYS(rt_sigprocmask),
	SCMP_SYS(rt_sigreturn),
	SCMP_SYS(select),
	SCMP_SYS(sendto),
	SCMP_SYS(setitimer),
	SCMP_SYS(setsid),
	SCMP_SYS(socket),
	SCMP_SYS(stat),
	SCMP_SYS(time),
	SCMP_SYS(write),
};
#endif
#ifdef __i386__
int scmp_sc[] = {
	SCMP_SYS(_newselect),
	SCMP_SYS(adjtimex),
	SCMP_SYS(brk),
	SCMP_SYS(chdir),
	SCMP_SYS(clock_gettime),
	SCMP_SYS(clock_settime),
	SCMP_SYS(close),
	SCMP_SYS(exit_group),
	SCMP_SYS(fsync),
	SCMP_SYS(futex),
	SCMP_SYS(getitimer),
	SCMP_SYS(madvise),
	SCMP_SYS(mmap),
	SCMP_SYS(mmap2),
	SCMP_SYS(munmap),
	SCMP_SYS(open),
	SCMP_SYS(poll),
	SCMP_SYS(read),
	SCMP_SYS(rename),
	SCMP_SYS(rt_sigaction),
	SCMP_SYS(rt_sigprocmask),
	SCMP_SYS(select),
	SCMP_SYS(setitimer),
	SCMP_SYS(setsid),
	SCMP_SYS(sigprocmask),
	SCMP_SYS(sigreturn),
	SCMP_SYS(socketcall),
	SCMP_SYS(stat64),
	SCMP_SYS(time),
	SCMP_SYS(write),
};
#endif
	{
		int i;

		for (i = 0; i < COUNTOF(scmp_sc); i++) {
			if (seccomp_rule_add(ctx,
			    SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
				msyslog(LOG_ERR,
				    "%s: seccomp_rule_add() failed: %m",
				    __func__);
			}
		}
	}

	if (seccomp_load(ctx) < 0)
		msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
		    __func__);	
	else {
		msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
	}
#endif /* LIBSECCOMP and KERN_SECCOMP */

# ifdef HAVE_IO_COMPLETION_PORT

	for (;;) {
		GetReceivedBuffers();
# else /* normal I/O */

	BLOCK_IO_AND_ALARM();
	was_alarmed = FALSE;

	for (;;) {
		if (alarm_flag) {	/* alarmed? */
			was_alarmed = TRUE;
			alarm_flag = FALSE;
		}

		if (!was_alarmed && !has_full_recv_buffer()) {
			/*
			 * Nothing to do.  Wait for something.
			 */
			io_handler();
		}

		if (alarm_flag) {	/* alarmed? */
			was_alarmed = TRUE;
			alarm_flag = FALSE;
		}

		if (was_alarmed) {
			UNBLOCK_IO_AND_ALARM();
			/*
			 * Out here, signals are unblocked.  Call timer routine
			 * to process expiry.
			 */
			timer();
			was_alarmed = FALSE;
			BLOCK_IO_AND_ALARM();
		}

# endif		/* !HAVE_IO_COMPLETION_PORT */

# ifdef DEBUG_TIMING
		{
			l_fp pts;
			l_fp tsa, tsb;
			int bufcount = 0;

			get_systime(&pts);
			tsa = pts;
# endif
			rbuf = get_full_recv_buffer();
			while (rbuf != NULL) {
				if (alarm_flag) {
					was_alarmed = TRUE;
					alarm_flag = FALSE;
				}
				UNBLOCK_IO_AND_ALARM();

				if (was_alarmed) {
					/* avoid timer starvation during lengthy I/O handling */
					timer();
					was_alarmed = FALSE;
				}

				/*
				 * Call the data procedure to handle each received
				 * packet.
				 */
				if (rbuf->receiver != NULL) {
# ifdef DEBUG_TIMING
					l_fp dts = pts;

					L_SUB(&dts, &rbuf->recv_time);
					DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
					collect_timing(rbuf, "buffer processing delay", 1, &dts);
					bufcount++;
# endif
					(*rbuf->receiver)(rbuf);
				} else {
					msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
					abort();
				}

				BLOCK_IO_AND_ALARM();
				freerecvbuf(rbuf);
				rbuf = get_full_recv_buffer();
			}
# ifdef DEBUG_TIMING
			get_systime(&tsb);
			L_SUB(&tsb, &tsa);
			if (bufcount) {
				collect_timing(NULL, "processing", bufcount, &tsb);
				DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
			}
		}
# endif

		/*
		 * Go around again
		 */

# ifdef HAVE_DNSREGISTRATION
		if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
			mdnsreg = current_time;
			msyslog(LOG_INFO, "Attempting to register mDNS");
			if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, 
			    htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
				if (!--mdnstries) {
					msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
				} else {	
					msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
				}
			} else {
				msyslog(LOG_INFO, "mDNS service registered.");
				mdnsreg = FALSE;
			}
		}
# endif /* HAVE_DNSREGISTRATION */

	}
	UNBLOCK_IO_AND_ALARM();
	return 1;
}
#endif	/* !SIM */


#if !defined(SIM) && defined(SIGDIE1)
/*
 * finish - exit gracefully
 */
static RETSIGTYPE
finish(
	int sig
	)
{
	const char *sig_desc;

	sig_desc = NULL;
#ifdef HAVE_STRSIGNAL
	sig_desc = strsignal(sig);
#endif
	if (sig_desc == NULL)
		sig_desc = "";
	msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
		sig, sig_desc);
	/* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
# ifdef HAVE_DNSREGISTRATION
	if (mdns != NULL)
		DNSServiceRefDeallocate(mdns);
# endif
	peer_cleanup();
	exit(0);
}
#endif	/* !SIM && SIGDIE1 */


#ifndef SIM
/*
 * wait_child_sync_if - implements parent side of -w/--wait-sync
 */
# ifdef HAVE_WORKING_FORK
static int
wait_child_sync_if(
	int	pipe_read_fd,
	long	wait_sync
	)
{
	int	rc;
	int	exit_code;
	time_t	wait_end_time;
	time_t	cur_time;
	time_t	wait_rem;
	fd_set	readset;
	struct timeval wtimeout;

	if (0 == wait_sync) 
		return 0;

	/* waitsync_fd_to_close used solely by child */
	close(waitsync_fd_to_close);
	wait_end_time = time(NULL) + wait_sync;
	do {
		cur_time = time(NULL);
		wait_rem = (wait_end_time > cur_time)
				? (wait_end_time - cur_time)
				: 0;
		wtimeout.tv_sec = wait_rem;
		wtimeout.tv_usec = 0;
		FD_ZERO(&readset);
		FD_SET(pipe_read_fd, &readset);
		rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
			    &wtimeout);
		if (-1 == rc) {
			if (EINTR == errno)
				continue;
			exit_code = (errno) ? errno : -1;
			msyslog(LOG_ERR,
				"--wait-sync select failed: %m");
			return exit_code;
		}
		if (0 == rc) {
			/*
			 * select() indicated a timeout, but in case
			 * its timeouts are affected by a step of the
			 * system clock, select() again with a zero 
			 * timeout to confirm.
			 */
			FD_ZERO(&readset);
			FD_SET(pipe_read_fd, &readset);
			wtimeout.tv_sec = 0;
			wtimeout.tv_usec = 0;
			rc = select(pipe_read_fd + 1, &readset, NULL,
				    NULL, &wtimeout);
			if (0 == rc)	/* select() timeout */
				break;
			else		/* readable */
				return 0;
		} else			/* readable */
			return 0;
	} while (wait_rem > 0);

	fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
		progname, wait_sync);
	return ETIMEDOUT;
}
예제 #9
0
struct seq_stats* collect_data(struct seq_stats* seq_stats,struct parameters* param,int (*fp)(struct read_info** ,struct parameters*,FILE* ),int file_num)
{
	struct read_info** ri = 0;
	int i,j,c;
	int test = 1;
	int numseq;
	int qual_key = 0;
	int aln_len = 0;
	//char command[1000];
	//char  tmp[1000];
	FILE* file = 0;
	FILE* unmapped = 0;
	
	ri = malloc(sizeof(struct read_info*) * param->num_query);
	
	for(i = 0; i < param->num_query;i++){
		ri[i] = malloc(sizeof(struct read_info));
		ri[i]->seq = 0;
		ri[i]->name = 0;
		ri[i]->qual = 0;
		ri[i]->len = 0;
		ri[i]->cigar = 0;
		ri[i]->md = 0;
		ri[i]->xp = 0;
		ri[i]->priors = 0;// malloc(sizeof(unsigned int)* (LIST_STORE_SIZE+1));
		ri[i]->strand = malloc(sizeof(unsigned int)* (LIST_STORE_SIZE+1));
		ri[i]->hits = malloc(sizeof(unsigned int)* (LIST_STORE_SIZE+1));
		ri[i]->identity = malloc(sizeof(float)* (LIST_STORE_SIZE+1));
	}
	file =  io_handler(file, file_num,param);
	
	if(param->print_unmapped){
		if (!(unmapped = fopen(param->print_unmapped, "w" ))){
			fprintf(stderr,"Cannot open file '%s'\n",param->print_unmapped);
			exit(-1);
		}
	}
	
	while ((numseq = fp(ri, param,file)) != 0){
		//fprintf(stderr,"rread: %d\n",numseq);
		for(i = 0; i < numseq;i++){
			if(ri[i]->len > seq_stats->max_len){
				seq_stats->max_len = ri[i]->len;
			}
			
			if(ri[i]->len < seq_stats->min_len ){
				seq_stats->min_len = ri[i]->len;
			}
			if(ri[i]->hits[0] == 0){
				qual_key = 5;
				if(param->print_unmapped){
					print_seq(ri[i],unmapped);
				}				
			}else{
				if(ri[i]->mapq < 3){
					qual_key = 0;
				}else if(ri[i]->mapq < 10){
					qual_key = 1;
				}else if(ri[i]->mapq < 20){
					qual_key = 2;
				}else if(ri[i]->mapq < 30){
					qual_key = 3;
				}else{
					qual_key = 4;
				}
			}
			
			if(ri[i]->errors > param->k_errors_allowed && param->k_errors_allowed != -1){
				qual_key = 5;
			}
			
			if(ri[i]->cigar && ri[i]->md){
				if(ri[i]->cigar[0] != '*'){
					aln_len = parse_cigar_md(ri[i],seq_stats, qual_key);
					seq_stats->md = 1;
				}
			}
			
			if(ri[i]->strand[0] != 0){
				ri[i]->seq = reverse_complement2(ri[i]->seq,ri[i]->len);
				if(ri[i]->qual[0] != '*'){
					ri[i]->qual = reverse_without_complement(ri[i]->qual, ri[i]->len);
				}
				
				if(ri[i]->xp){
					ri[i]->xp =  reverse_without_complement(ri[i]->xp, ri[i]->len);
				}
				
			}
			if(ri[i]->qual){
				if(ri[i]->qual[0] != '*'){
					param->print_qual  = 1;
					for(j = 0; j < ri[i]->len;j++){
						
						seq_stats->seq_quality[qual_key][j] += (int)(ri[i]->qual[j]);
						
						
						if((int)(ri[i]->qual[j]) > 80){
							param->solexa = 1;
						}
						
						//fprintf(stderr,"%d	%d	%c	%d\n",j,qual_key,ri[i]->qual[j] , (int)(ri[i]->qual[j] -33));
					}
				}
			}
			
			if(ri[i]->xp){
				
				param->print_posteriors  = 1;
				for(j = 0; j < ri[i]->len;j++){
					seq_stats->posterior_mappability[qual_key][j] += (int)(ri[i]->xp[j])-33;
				}
				
			}
			
			seq_stats->alignments[qual_key]++;
			
			// sequence length
			if(ri[i]->len >=  MAX_SEQ_LEN){
				seq_stats->seq_len[qual_key][MAX_SEQ_LEN-1]++;
			}else{
				seq_stats->seq_len[qual_key][ri[i]->len]++;
			}
			// sequence composition
			for(j = 0;j <  ri[i]->len;j++){
				seq_stats->nuc_num[ri[i]->seq[j]]++; 
				seq_stats->nuc_composition[qual_key][j][ri[i]->seq[j]]++; 
			}
			
			//kmers 
			for(j = 0;j <=  ri[i]->len - param->kmer_size;j++){
				//check for 'N'
				test = 1;
				for(c = j;c < j + param->kmer_size;c++){
					if(ri[i]->seq[c] >= 4){
						test = 0;
						break;
					}
				}
				// no 'N'?  ok proceed
				
				if(test){
					test = 0;
					for(c = j;c < j + param->kmer_size;c++){
						test = test << 2 | ri[i]->seq[c];
					}
					
					seq_stats->kmers[qual_key][j][test]++;    
				}
			}
			
			// ten mers.
			for(j = 0;j <=  ri[i]->len - KMERLEN;j++){
				//check for 'N'
				test = 1;
				for(c = j;c < j + KMERLEN;c++){
					if(ri[i]->seq[c] >= 4){
						test = 0;
						break;
					}
				}
				// no 'N'?  ok proceed
				
				if(test){
					test = 0;
					for(c = j;c < j + KMERLEN;c++){
						test = test << 2 | ri[i]->seq[c];
					}
					seq_stats->ten_mers[qual_key][test]->count++;    
					//seq_stats->overall_kmers[test]+= 1.0f;
				}
			}
			
			//errors
			
			if(ri[i]->errors != -1){
				
				
				seq_stats->percent_identity[qual_key] +=(((double)aln_len - (double)ri[i]->errors) / (double)aln_len * 100.0);// ((float)aln_len - (float)ri[i]->errors) / (float) aln_len * 100.0f;
				
				//if((int)  floor((((float)aln_len - (float)ri[i]->errors) / (float)aln_len * 1000.0f) + 0.5f ) > 1000 || (int)  floor((((float)aln_len - (float)ri[i]->errors) / (float)aln_len * 1000.0f) + 0.5f ) < 0 ){
				//	fprintf(stderr,"ERROR: %f	%f\n", (float)aln_len,  (float)ri[i]->errors);
				//}	
				
				//fprintf(stderr,"%d	%d	%d	%d\n",qual_key,aln_len,ri[i]->errors,(int)  floor((((float)aln_len - (float)ri[i]->errors) / (float)aln_len * 1000.0f) + 0.5 ));
				if(ri[i]->errors >= MAXERROR){
					seq_stats->errors[qual_key][MAXERROR-1]++;
				}else{
					seq_stats->errors[qual_key][ri[i]->errors]++;
				}
			}
			
			
		}
	}
	
	if(param->print_unmapped){
		fclose(unmapped);
	}
		
	for(i = 0; i < param->num_query;i++){
		free(ri[i]->strand); 
		free(ri[i]->hits);
		free(ri[i]->identity);
		
		if(ri[i]->cigar){
			free(ri[i]->cigar);
		}
		if(ri[i]->md){
			free(ri[i]->md);
		}
		
		free(ri[i]);
	}
	free(ri);
	//fprintf(stderr,"%p\n",file);
	if(param->sam == 2 || param->sam == 1){
		pclose(file);
	}else{
		//if(file_num != -1){
		fclose(file);
		//}
	}
	return seq_stats;
}
예제 #10
0
파일: networking.c 프로젝트: rodan/iotcpd
int network_glue(void)
{
    struct sockaddr_in s4;
    struct sockaddr_in6 s6;
    struct sockaddr_storage ss;
    int sfd, s;
    int efd;
    struct epoll_event event;
    socklen_t len;
    int optval;

    if (strlen(ip4) > 0) {
        s4.sin_family = AF_INET;
        inet_pton(AF_INET, ip4, &(s4.sin_addr));
        s4.sin_port = htons(port);
        memcpy(&ss, &s4, sizeof(s4));
    } else if (strlen(ip6) > 0) {
        s6.sin6_family = AF_INET6;
        inet_pton(AF_INET6, ip6, &(s6.sin6_addr));
        s6.sin6_port = htons(port);
        memcpy(&ss, &s6, sizeof(s6));
    } else {
        fprintf(stderr, "IPv4/IPv6 unspecified\n");
        return EXIT_FAILURE;
    }

    sfd = socket(ss.ss_family, SOCK_STREAM, 0);

    if (sfd == -1) {
        perror("socket() failed");
        return EXIT_FAILURE;
    }

    make_socket_non_blocking(sfd);

#ifndef WIN32
    int one = 1;
    if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
        perror("setsockopt() failed");
        close(sfd);
        return EXIT_FAILURE;
    }
#endif

    if (bind(sfd, (struct sockaddr *)&ss, sizeof(ss)) < 0) {
        perror("bind() failed");
        close(sfd);
        return EXIT_FAILURE;
    }

    if (listen(sfd, num_daemons) < 0) {
        perror("listen() failed");
        close(sfd);
        return EXIT_FAILURE;
    }

    efd = epoll_create1(0);
    if (efd == -1) {
        perror("epoll_create() failed");
        close(sfd);
        return EXIT_FAILURE;
    }

    event.data.fd = sfd;
    event.events = EPOLLIN | EPOLLET;   // set edge-trigger
    s = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event);
    if (s == -1) {
        perror("epoll_ctl(sfd) failed");
        close(sfd);
        return EXIT_FAILURE;
    }

    events = calloc(num_daemons, sizeof event);

    // the event loop
    while (1) {
        int n, i;

        n = epoll_wait(efd, events, num_daemons, -1);
        for (i = 0; i < n; i++) {
            if ((events[i].events & EPOLLERR) ||
                (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) {
                // an error has occured on this fd, or the socket is not
                // ready for reading 
                // (happens when the client closes the connection due to timeout)
                //fprintf(stderr, "epoll error\n");
                st.queries_timeout++;
                close(events[i].data.fd);
                continue;
            }

            else if (sfd == events[i].data.fd) {
                // we have a notification on the listening socket, which
                // means one or more incoming connections.
                while (1) {
                    struct sockaddr in_addr;
                    socklen_t in_len;
                    int infd;

                    in_len = sizeof in_addr;
                    infd = accept(sfd, &in_addr, &in_len);
                    if (infd == -1) {
                        if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
                            // we have processed all incoming
                            // connections.
                            break;
                        } else {
                            perror("accept() failed");
                            break;
                        }
                    }
#ifdef CONFIG_VERBOSE
                    char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
                    s = getnameinfo(&in_addr, in_len,
                                    hbuf, sizeof hbuf,
                                    sbuf, sizeof sbuf, NI_NUMERICHOST | NI_NUMERICSERV);
                    if (s == 0) {
                        printf("new connection - fd %d, host %s, port %s\n", infd, hbuf, sbuf);
                    }
#endif

                    // make the incoming socket non-blocking and add it to the
                    // list of fds to monitor.
                    s = make_socket_non_blocking(infd);
                    if (s == -1) {
                        perror("make_socket_non_blocking(infd) failed");
                        st.queries_failed++;
                        close(infd);
                        break;
                    }

                    event.data.fd = infd;
                    event.events = EPOLLIN | EPOLLET;
                    s = epoll_ctl(efd, EPOLL_CTL_ADD, infd, &event);
                    if (s == -1) {
                        perror("epoll_ctl(infd) failed");
                        st.queries_failed++;
                        close(infd);
                        break;
                    }
                }
                continue;
            } else {
                // data is present on the fd and it's ready to be read
                if (getsockopt(events[i].data.fd, SOL_SOCKET, SO_ERROR, &optval, &len) == 0) {
                    if (optval == 0) {
                        io_handler(events[i].data.fd);
                    }
                }
            }
        }
    }

    close(sfd);
    return EXIT_SUCCESS;
}
예제 #11
0
int main(int argc, char* argv[])
{
  const char* pname = argv[0];
  const char* devroot = "/dev/input";
  char* device = NULL;
  char* sockname = DEFAULT_SOCKET_NAME;
  char* stdin_file = NULL;
  int use_stdin = 0;

  int opt;
  while ((opt = getopt(argc, argv, "d:n:vif:h")) != -1) {
    switch (opt) {
      case 'd':
        device = optarg;
        break;
      case 'n':
        sockname = optarg;
        break;
      case 'v':
        g_verbose = 1;
        break;
      case 'i':
        use_stdin = 1;
        break;
      case 'f':
        stdin_file = optarg;
        break;
      case '?':
        usage(pname);
        return EXIT_FAILURE;
      case 'h':
        usage(pname);
        return EXIT_SUCCESS;
    }
  }

  internal_state_t state = {0};

  if (device != NULL)
  {
    if (!consider_device(device, &state))
    {
      fprintf(stderr, "%s is not a supported touch device\n", device);
      return EXIT_FAILURE;
    }
  }
  else
  {
    if (walk_devices(devroot, &state) != 0)
    {
      fprintf(stderr, "Unable to crawl %s for touch devices\n", devroot);
      return EXIT_FAILURE;
    }
  }

  if (state.evdev == NULL)
  {
    fprintf(stderr, "Unable to find a suitable touch device\n");
    return EXIT_FAILURE;
  }

  state.has_mtslot =
    libevdev_has_event_code(state.evdev, EV_ABS, ABS_MT_SLOT);
  state.has_tracking_id =
    libevdev_has_event_code(state.evdev, EV_ABS, ABS_MT_TRACKING_ID);
  state.has_key_btn_touch =
    libevdev_has_event_code(state.evdev, EV_KEY, BTN_TOUCH);
  state.has_touch_major =
    libevdev_has_event_code(state.evdev, EV_ABS, ABS_MT_TOUCH_MAJOR);
  state.has_width_major =
    libevdev_has_event_code(state.evdev, EV_ABS, ABS_MT_WIDTH_MAJOR);

  state.has_pressure =
    libevdev_has_event_code(state.evdev, EV_ABS, ABS_MT_PRESSURE);
  state.min_pressure = state.has_pressure ?
    libevdev_get_abs_minimum(state.evdev, ABS_MT_PRESSURE) : 0;
  state.max_pressure= state.has_pressure ?
    libevdev_get_abs_maximum(state.evdev, ABS_MT_PRESSURE) : 0;

  state.max_x = libevdev_get_abs_maximum(state.evdev, ABS_MT_POSITION_X);
  state.max_y = libevdev_get_abs_maximum(state.evdev, ABS_MT_POSITION_Y);

  state.max_tracking_id = state.has_tracking_id
    ? libevdev_get_abs_maximum(state.evdev, ABS_MT_TRACKING_ID)
    : INT_MAX;

  if (!state.has_mtslot && state.max_tracking_id == 0)
  {
    // The touch device reports incorrect values. There would be no point
    // in supporting ABS_MT_TRACKING_ID at all if the maximum value was 0
    // (i.e. one contact). This happens on Lenovo Yoga Tablet B6000-F,
    // which actually seems to support ~10 contacts. So, we'll just go with
    // as many as we can and hope that the system will ignore extra contacts.
    state.max_tracking_id = MAX_SUPPORTED_CONTACTS - 1;
    fprintf(stderr,
      "Note: type A device reports a max value of 0 for ABS_MT_TRACKING_ID. "
      "This means that the device is most likely reporting incorrect "
      "information. Guessing %d.\n",
      state.max_tracking_id
    );
  }

  state.max_contacts = state.has_mtslot
    ? libevdev_get_abs_maximum(state.evdev, ABS_MT_SLOT) + 1
    : (state.has_tracking_id ? state.max_tracking_id + 1 : 2);

  state.tracking_id = 0;

  int contact;
  for (contact = 0; contact < MAX_SUPPORTED_CONTACTS; ++contact)
  {
    state.contacts[contact].enabled = 0;
  }

  fprintf(stderr,
    "%s touch device %s (%dx%d with %d contacts) detected on %s (score %d)\n",
    state.has_mtslot ? "Type B" : "Type A",
    libevdev_get_name(state.evdev),
    state.max_x, state.max_y, state.max_contacts,
    state.path, state.score
  );

  if (state.max_contacts > MAX_SUPPORTED_CONTACTS) {
    fprintf(stderr, "Note: hard-limiting maximum number of contacts to %d\n",
      MAX_SUPPORTED_CONTACTS);
    state.max_contacts = MAX_SUPPORTED_CONTACTS;
  }

  FILE* input;
  FILE* output;

  if (use_stdin || stdin_file != NULL)
  {
    if (stdin_file != NULL)
    {
      // Reading from a file
      input = fopen(stdin_file, "r");
      if (NULL == input)
      {
        fprintf(stderr, "Unable to open '%s': %s\n",
                stdin_file, strerror(errno));
        exit(EXIT_FAILURE);
      }
      else
      {
        fprintf(stderr, "Reading commands from '%s'\n",
                stdin_file);
      }
    }
    else
    {
      // Reading from terminal
      input = stdin;
      fprintf(stderr, "Reading from STDIN\n");
    }

    output = stderr;
    io_handler(input, output, &state);
    fclose(input);
    fclose(output);
    exit(EXIT_SUCCESS);
  }

  struct sockaddr_un client_addr;
  socklen_t client_addr_length = sizeof(client_addr);

  int server_fd = start_server(sockname);

  if (server_fd < 0)
  {
    fprintf(stderr, "Unable to start server on %s\n", sockname);
    return EXIT_FAILURE;
  }

  while (1)
  {
    int client_fd = accept(server_fd, (struct sockaddr *) &client_addr,
      &client_addr_length);

    if (client_fd < 0)
    {
      perror("accepting client");
      exit(1);
    }

    fprintf(stderr, "Connection established\n");

    input = fdopen(client_fd, "r");
    if (input == NULL)
    {
      fprintf(stderr, "%s: fdopen(client_fd,'r')\n", strerror(errno));
      exit(1);
    }

    output = fdopen(dup(client_fd), "w");
    if (output == NULL)
    {
      fprintf(stderr, "%s: fdopen(client_fd,'w')\n", strerror(errno));
      exit(1);
    }

    io_handler(input, output, &state);

    fprintf(stderr, "Connection closed\n");
    fclose(input);
    fclose(output);
    close(client_fd);
  }

  close(server_fd);

  libevdev_free(state.evdev);
  close(state.fd);

  return EXIT_SUCCESS;
}
예제 #12
0
 std::unique_ptr<ImageIO::Base> Pipe::create (Header& H) const
 {
   std::unique_ptr<ImageIO::Base> original_handler (mrtrix_handler.create (H));
   std::unique_ptr<ImageIO::Pipe> io_handler (new ImageIO::Pipe (std::move (*original_handler)));
   return std::move (io_handler);
 }