Beispiel #1
0
void
setUp(void)
{
	init_lib();

	return;
}
Beispiel #2
0
struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type) {
	static char buf[16];
	static char ipv4[4];
	static char *list[2];
	static struct hostent he;

	if(!init_l)
		init_lib();

	PDEBUG("TODO: proper gethostbyaddr hook\n");

	if(!proxychains_resolver)
		return true_gethostbyaddr(addr, len, type);
	else {

		PDEBUG("len %u\n", len);
		if(len != 4)
			return NULL;
		he.h_name = buf;
		memcpy(ipv4, addr, 4);
		list[0] = ipv4;
		list[1] = NULL;
		he.h_addr_list = list;
		he.h_addrtype = AF_INET;
		he.h_aliases = NULL;
		he.h_length = 4;
		inet_ntop(AF_INET, addr, buf, sizeof(buf));
		return &he;
	}
	return NULL;
}
Beispiel #3
0
int one_time_library_init()
{
	static enum init_lib_state __init_lib_state__ = not_done_state;
	int result;

	result = 0;

	switch(__init_lib_state__)
	{
		case not_done_state:
			__init_lib_state__ = being_done_state;
			init_lib();
			__init_lib_state__ = done_state;
			break;
		case being_done_state:
			// if a network related function call is done during the init_lib() procedure
			// this function will be called. 
			// In this case we don't want ipv6-care to analyse this function:
			result = -1;
			break;
		case done_state:
			break;
	}

	return result;
}
Beispiel #4
0
void
setUp(void)
{
	init_recvbuff(RECV_INIT);
	init_lib();

	return;
}
Beispiel #5
0
void
setUp()
{
    ntpcal_set_timefunc(timefunc);
    settime(1970, 1, 1, 0, 0, 0);
    init_lib();

    return;
}
Beispiel #6
0
extern "C" void* wrap(calloc)(size_t num, size_t sz)
{
	init_lib();

	void* p = wrap(malloc)(num * sz);
	if (p)
		memset(p, 0, num * sz);

	return p;
}
Beispiel #7
0
extern "C" void wrap(free)(void *p)
{
	init_lib();

	void* p1 = STUB_PTR(p);

	if (p1)
		fibjs::MemPool::global().remove(p1);

	__real_free(p1);
}
Beispiel #8
0
void		init_communication(char *ip, int port)
{
  pthread_t	thread;

  clt_com = my_xmalloc(sizeof(*clt_com));
  init_lib(clt_com, ip, port);
  signal(SIGINT, &end_connexion);
  clt_com->flag = 1;
  pthread_create(&thread, NULL, &game_thread, clt_com);
  pthread_join(thread, NULL);
}
Beispiel #9
0
int connect(int sock, const struct sockaddr *addr, unsigned int len) {
	int socktype = 0, flags = 0, ret = 0;
	socklen_t optlen = 0;
	ip_type dest_ip;
#ifdef DEBUG
	char str[256];
#endif
	struct in_addr *p_addr_in;
	unsigned short port;
	size_t i;

	if(!init_l)
		init_lib();
	optlen = sizeof(socktype);
	getsockopt(sock, SOL_SOCKET, SO_TYPE, &socktype, &optlen);
	if(!(SOCKFAMILY(*addr) == AF_INET && socktype == SOCK_STREAM))
		return true_connect(sock, addr, len);

	p_addr_in = &((struct sockaddr_in *) addr)->sin_addr;
	port = ntohs(((struct sockaddr_in *) addr)->sin_port);

#ifdef DEBUG
//      PDEBUG("localnet: %s; ", inet_ntop(AF_INET,&in_addr_localnet, str, sizeof(str)));
//      PDEBUG("netmask: %s; " , inet_ntop(AF_INET, &in_addr_netmask, str, sizeof(str)));
	PDEBUG("target: %s\n", inet_ntop(AF_INET, p_addr_in, str, sizeof(str)));
	PDEBUG("port: %d\n", port);
#endif
	for(i = 0; i < num_localnet_addr; i++) {
		if((localnet_addr[i].in_addr.s_addr & localnet_addr[i].netmask.s_addr)
		   == (p_addr_in->s_addr & localnet_addr[i].netmask.s_addr)) {
			if(localnet_addr[i].port || localnet_addr[i].port == port) {
				PDEBUG("accessing localnet using true_connect\n");
				return true_connect(sock, addr, len);
			}
		}
	}

	flags = fcntl(sock, F_GETFL, 0);
	if(flags & O_NONBLOCK)
		fcntl(sock, F_SETFL, !O_NONBLOCK);

	dest_ip.as_int = SOCKADDR(*addr);

	ret = connect_proxy_chain(sock,
				  dest_ip,
				  SOCKPORT(*addr),
				  proxychains_pd, proxychains_proxy_count, proxychains_ct, proxychains_max_chain);

	fcntl(sock, F_SETFL, flags);
	if(ret != SUCCESS)
		errno = ECONNREFUSED;
	return ret;
}
Beispiel #10
0
struct hostent *gethostbyname(const char *name) {
	if(!init_l)
		init_lib();

	PDEBUG("gethostbyname: %s\n", name);

	if(proxychains_resolver)
		return proxy_gethostbyname(name);
	else
		return true_gethostbyname(name);

	return NULL;
}
Beispiel #11
0
void* operator new[] (size_t sz)
{
	init_lib();

	void* p1 = __real_malloc(FULL_SIZE(sz));

	if (p1) {
		memset(p1, 0, STUB_SIZE);
		fibjs::MemPool::global().add(p1, sz);
	}

	return MEM_PTR(p1);
}
Beispiel #12
0
extern "C" void* wrap(malloc)(size_t sz)
{
	init_lib();

	void* p1 = __real_malloc(FULL_SIZE(sz));

	if (p1) {
		memset(p1, 0, STUB_SIZE);
		fibjs::MemPool::global().add(p1, sz);
	}

	return MEM_PTR(p1);
}
Beispiel #13
0
bool Manager::load_library( const std::string& type ) {

  // If no plugin sub-directory is defined, no need to look for
  // a plugin.
  if( plugin_subdir_.empty() ) return false ;


  typedef int (*InitFnPtr)( );

  std::string libname = plugin_dir_ + plugin_subdir_ + 
                        "/lib" + type + dll_extension_;
  
  /*
  void * lib = dlopen( libname.c_str(), RTLD_LAZY );
  if ( !lib ){
    appli_warning( "Dynamic link failure for " << libname << ": "
		  << dlerror() << std::endl );
    return false;
  }

  std::string init_function_name( libname + "init" );
  InitFnPtr init_lib = (InitFnPtr) dlsym( lib, init_function_name.c_str() );
  if ( !init_lib ){
    appli_warning( "Can't find function " << init_function_name 
    << "in library " << libname << std::endl );
    return false;
  }
  */
 
  std::string init_function_name( libname + "init" );
  QLibrary myplugin( libname.c_str() );

  //!!!qt4 doesn't support auto unload!!!
  //myplugin.setAutoUnload( false );
  
  InitFnPtr init_lib = (InitFnPtr) myplugin.resolve( init_function_name.c_str() );
  if ( !init_lib ) {
    if( myplugin.isLoaded() ) {
      appli_warning( "Unable to load " << libname );
    }
    else {
      appli_warning( "Can't find function " << init_function_name << "in library " << libname );
    }
    return false;
  }

  init_lib();

  return true;
}
Beispiel #14
0
void
ssl_init(void)
{
	init_lib();

	if (ssl_init_done)
		return;

	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	atexit(&atexit_ssl_cleanup);

	ssl_init_done = true;
}
Beispiel #15
0
int
main(int argc,char **argv)
{
  anthy_context_t ac;
  FILE *fp;
  struct input cur_input;
  struct res_db *db;
  struct condition cond;

  cur_input.serial = 0;
  cur_input.str = 0;
  init_condition(&cond);

  parse_args(&cond, argc, argv);
  db = create_db();
  read_db(db, expdata);

  printf("./test_anthy --help to print usage.\n");

  print_run_env();

  fp = fopen(testdata, "r");
  if (!fp) {
    printf("failed to open %s.\n", testdata);
    return 0;
  }
  
  ac = init_lib(cond.use_utf8);

  /* ファイルを読んでいくループ */
  while (!read_file(fp, &cur_input)) {
    if (check_cond(&cond, &cur_input)) {
      set_string(&cond, db, &cur_input, ac);
    }
  }

  anthy_release_context(ac);
  anthy_quit();

  if (cond.ask) {
    /* ユーザに聞く */
    ask_results(db);
  }

  show_stat(db);
  save_db(expdata, db);

  return 0;
}
Beispiel #16
0
int open(const char* path, int flags, ...)
{
   init_lib();
#if DEBUG
   fprintf(stderr, "open(): %s\n", path);
#endif
   mode_t mode = 0;

   if ( flags & O_CREAT )
   {
      va_list args;
      va_start(args, flags);
      if (sizeof(mode_t) < sizeof(int))
         mode = (mode_t)va_arg(args, int);
      else
Beispiel #17
0
int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res) {
	int ret = 0;

	if(!init_l)
		init_lib();

	PDEBUG("getaddrinfo: %s %s\n", node, service);

	if(proxychains_resolver)
		ret = proxy_getaddrinfo(node, service, hints, res);
	else
		ret = true_getaddrinfo(node, service, hints, res);

	return ret;
}
Beispiel #18
0
int	main(int ac, char **argv)
{
  pthread_t	thread;

  if (ac == 3)
    {
      slib = malloc(sizeof(*slib));
      init_lib(slib, argv[1], atoi(argv[2]));
      slib->flag = 1;
      pthread_create(&thread, NULL, &exec_thread, slib);
      pthread_join(thread, NULL);
    }
  else
    printf("Usage : %s <IP_addr> <Port>\n", argv[0]);
  return (0);
}
Beispiel #19
0
void freeaddrinfo(struct addrinfo *res) {
	if(!init_l)
		init_lib();

	PDEBUG("freeaddrinfo %p \n", res);

	if(!proxychains_resolver)
		true_freeaddrinfo(res);
	else {
		if (res != NULL) {
			free(res->ai_addr);
			free(res);
		}
	}
	return;
}
Beispiel #20
0
extern "C" void* wrap(realloc)(void* p, size_t sz)
{
	init_lib();

	fibjs::MemPool& mp = fibjs::MemPool::global();

	if (p == 0)
	{
		void* p1 = __real_malloc(FULL_SIZE(sz));

		if (p1) {
			memset(p1, 0, STUB_SIZE);
			mp.add(p1, sz);
		}

		return MEM_PTR(p1);
	}

	if (sz == 0)
	{
		void* p1 = STUB_PTR(p);

		if (p1)
			mp.remove(p1);

		__real_free(p1);
		return 0;
	}

	void* p1 = STUB_PTR(p);

	mp.remove(p1);
	void* p2 = __real_realloc(p1, FULL_SIZE(sz));
	if (p2) {
		memset(p2, 0, STUB_SIZE);
		mp.add(p2, sz);
	}
	else
		mp.add(p1);

	return MEM_PTR(p2);
}
Beispiel #21
0
PUBLIC int main(int argc, char **argv)
{
     init_lex();
     init_symtab();
     init_type();
     init_lib();

     if (argc != 2) 
	  filename = "standard input";
     else {
	  filename = argv[1];
	  if ((yyin = fopen(filename, "r")) == NULL) {
	       perror(filename);
	       exit(1);
	  }
     }

     yyparse();
     return (err_count == 0 ? 0 : 1);
}
Beispiel #22
0
	void dump()
	{
		Item* items;
		Item* p;
		int32_t n = 0;
		int32_t i;
		char fname[32];

		init_lib();

		m_lock.lock();
		items = (Item*)__real_malloc(sizeof(Item) * m_list.count());

		p = m_list.head();
		while (p)
		{
			memcpy(items + n ++, p, sizeof(Item));
			p = m_list.next(p);
		}
		m_lock.unlock();

		caller root(0);
		for (i = 0; i < n; i ++)
			root.put(items[i].m_sz, items[i].m_frames, items[i].m_frame_count);

		sprintf(fname, "fibjs.%d.heap", getpid());
		FILE* fp = fopen(fname, "w");
		if (fp)
		{
			fprintf(fp, "\nfound %d times, total ", root.m_times);
			out_size(fp, root.m_sz);
			root.dumpSubs(fp);
			fclose(fp);
		}

		__real_free(items);
	}
Beispiel #23
0
int getnameinfo(const struct sockaddr *sa,
		socklen_t salen, char *host, socklen_t hostlen, char *serv, socklen_t servlen, int flags)
#endif
{
	char ip_buf[16];
	int ret = 0;

	if(!init_l)
		init_lib();

	PDEBUG("getnameinfo: %s %s\n", host, serv);

	if(!proxychains_resolver) {
		ret = true_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
	} else {
		if(hostlen) {
			inet_ntop(AF_INET, (unsigned char*) &(SOCKADDR_2(*sa)), ip_buf, sizeof(ip_buf));
			strncpy(host, ip_buf, hostlen);
		}
		if(servlen)
			snprintf(serv, servlen, "%d", ntohs(SOCKPORT(*sa)));
	}
	return ret;
}
Beispiel #24
0
int ntpsim(int argc, char *argv[])
{
    Event *curr_event;
    struct timeval seed;

    /* Initialize the local Clock 
     */
    simclock.local_time = 0;
    simclock.adj = 0;
    simclock.slew = 0;

    /* Initialize the simulation 
     */
    simulation.num_of_servers = 0;
    simulation.beep_delay = BEEP_DLY;
    simulation.sim_time = 0;
    simulation.end_time = SIM_TIME;

    /*
     * Initialize ntp variables
     */
    initializing = 1;
    init_auth();
    init_util();
    init_restrict();
    init_mon();
    init_timer();
    init_lib();
    init_request();
    init_control();
    init_peer();
    init_proto();
    init_io();
    init_loopfilter();
    mon_start(MON_OFF);    

    /* Call getconfig to parse the configuration file */
    getconfig(argc, argv);
    initializing = 0;
    loop_config(LOOP_DRIFTCOMP, old_drift / 1e6);

    /*
     * Watch out here, we want the real time, not the silly stuff.
     */
    gettimeofday(&seed, NULL);
    ntp_srandom(seed.tv_usec);


    /* Initialize the event queue */
    event_queue = create_priority_queue((int(*)(void *, void*)) 
					determine_event_ordering);

    /* Initialize the receive queue */
    recv_queue = create_priority_queue((int(*)(void *, void*))
				       determine_recv_buf_ordering);

    /* Push a beep and a timer on the event queue */
    enqueue(event_queue, event(0, BEEP));
    enqueue(event_queue, event(simulation.sim_time + 1.0, TIMER));
    /* 
     * Pop the queue until nothing is left or time is exceeded
     */
    /* maxtime = simulation.sim_time + simulation.end_time;*/
    while (simulation.sim_time <= simulation.end_time &&
	   (!empty(event_queue))) {
	curr_event = dequeue(event_queue);
	/* Update all the clocks to the time on the event */
	sim_update_clocks(curr_event);

	/* Execute the function associated with the event */
	event_ptr[curr_event->function](curr_event);
	free_node(curr_event);
    }
    return (0);
}
Beispiel #25
0
WiimoteScannerWindows::WiimoteScannerWindows()
{
  init_lib();
}
Beispiel #26
0
/*
 * main - parse arguments and handle options
 */
int
main(
	int argc,
	char *argv[]
	)
{
	int c;
	int errflg = 0;
	off_t tickadj_offset;
	off_t tick_offset;
	off_t dosync_offset;
	off_t noprintf_offset;
	int tickadj, ktickadj;	/* HMS: Why isn't this u_long? */
	int tick, ktick;	/* HMS: Why isn't this u_long? */
	int dosynctodr;
	int noprintf;
	int hz;
	int hz_int, hz_hundredths;
	int recommend_tickadj;
	long tmp;

	init_lib();

	progname = argv[0];
	while ((c = ntp_getopt(argc, argv, "a:Adkpqst:")) != EOF)
	{
		switch (c)
		{
		    case 'a':
			writetickadj = atoi(ntp_optarg);
			if (writetickadj <= 0)
			{
				(void) fprintf(stderr,
					       "%s: unlikely value for tickadj: %s\n",
					       progname, ntp_optarg);
				errflg++;
			}

#if defined SCO5_CLOCK
			if (writetickadj % HZ) 
			{
				writetickadj = (writetickadj / HZ) * HZ;
				(void) fprintf(stderr,
					       "tickadj truncated to: %d\n", writetickadj);
			}
#endif /* SCO5_CLOCK */

			break;
		    case 'A':
			writeopttickadj = 1;
			break;
		    case 'd':
			++debug;
			break;
		    case 'k':
			dokmem = 1;
			break;
		    case 'p':
			setnoprintf = 1;
			break;
		    case 'q':
			quiet = 1;
			break;
		    case 's':
			unsetdosync = 1;
			break;
		    case 't':
			writetick = atoi(ntp_optarg);
			if (writetick <= 0)
			{
				(void) fprintf(stderr,
					       "%s: unlikely value for tick: %s\n",
					       progname, ntp_optarg);
				errflg++;
			}
			break;
		    default:
			errflg++;
			break;
		}
	}
	if (errflg || ntp_optind != argc)
	{
		(void) fprintf(stderr,
			       "usage: %s [-Adkpqs] [-a newadj] [-t newtick]\n", progname);
		exit(2);
	}

	getoffsets(&tick_offset, &tickadj_offset, &dosync_offset, &noprintf_offset);

	if (debug)
	{
		(void) printf("tick offset = %lu\n", (unsigned long)tick_offset);
		(void) printf("tickadj offset = %lu\n", (unsigned long)tickadj_offset);
		(void) printf("dosynctodr offset = %lu\n", (unsigned long)dosync_offset);
		(void) printf("noprintf offset = %lu\n", (unsigned long)noprintf_offset);
	}

	if (writetick && (tick_offset == 0))
	{
		(void) fprintf(stderr, 
			       "No tick kernel variable\n");
		errflg++;
	}
	
	if (writeopttickadj && (tickadj_offset == 0))
	{
		(void) fprintf(stderr, 
			       "No tickadj kernel variable\n");
		errflg++;
	}

	if (unsetdosync && (dosync_offset == 0))
	{
		(void) fprintf(stderr, 
			       "No dosynctodr kernel variable\n");
		errflg++;
	}
	
	if (setnoprintf && (noprintf_offset == 0))
	{
		(void) fprintf(stderr, 
			       "No noprintf kernel variable\n");
		errflg++;
	}

	if (tick_offset != 0)
	{
		readvar(fd, tick_offset, &tick);
#if defined(TICK_NANO) && defined(K_TICK_NAME)
		if (!quiet)
		    (void) printf("KERNEL %s = %d nsec\n", K_TICK_NAME, tick);
#endif /* TICK_NANO && K_TICK_NAME */

#ifdef TICK_NANO
		tick /= 1000;
#endif
	}
	else
	{
		tick = 0;
	}

	if (tickadj_offset != 0)
	{
		readvar(fd, tickadj_offset, &tickadj);

#ifdef SCO5_CLOCK
		/* scale from nsec/sec to usec/tick */
		tickadj /= (1000L * HZ);
#endif /*SCO5_CLOCK */

#if defined(TICKADJ_NANO) && defined(K_TICKADJ_NAME)
		if (!quiet)
		    (void) printf("KERNEL %s = %d nsec\n", K_TICKADJ_NAME, tickadj);
#endif /* TICKADJ_NANO && K_TICKADJ_NAME */

#ifdef TICKADJ_NANO
		tickadj += 999;
		tickadj /= 1000;
#endif
	}
	else
	{
		tickadj = 0;
	}

	if (dosync_offset != 0)
	{
		readvar(fd, dosync_offset, &dosynctodr);
	}

	if (noprintf_offset != 0)
	{
		readvar(fd, noprintf_offset, &noprintf);
	}

	(void) close(fd);

	if (unsetdosync && dosync_offset == 0)
	{
		(void) fprintf(stderr,
			       "%s: can't find %s in namelist\n",
			       progname,
#ifdef K_DOSYNCTODR_NAME
			       K_DOSYNCTODR_NAME
#else /* not K_DOSYNCTODR_NAME */
			       "dosynctodr"
#endif /* not K_DOSYNCTODR_NAME */
			       );
		exit(1);
	}

	hz = HZ;
#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
	hz = (int) sysconf (_SC_CLK_TCK);
#endif /* not HAVE_SYSCONF && _SC_CLK_TCK */
#ifdef OVERRIDE_HZ
	hz = DEFAULT_HZ;
#endif
	ktick = tick;
#ifdef PRESET_TICK
	tick = PRESET_TICK;
#endif /* PRESET_TICK */
#ifdef TICKADJ_NANO
	tickadj /= 1000;
	if (tickadj == 0)
	    tickadj = 1;
#endif
	ktickadj = tickadj;
#ifdef PRESET_TICKADJ
	tickadj = (PRESET_TICKADJ) ? PRESET_TICKADJ : 1;
#endif /* PRESET_TICKADJ */

	if (!quiet)
	{
		if (tick_offset != 0)
		{
			(void) printf("KERNEL tick = %d usec (from %s kernel variable)\n",
				      ktick,
#ifdef K_TICK_NAME
				      K_TICK_NAME
#else
				      "<this can't happen>"
#endif			
				      );
		}
#ifdef PRESET_TICK
		(void) printf("PRESET tick = %d usec\n", tick);
#endif /* PRESET_TICK */
		if (tickadj_offset != 0)
		{
			(void) printf("KERNEL tickadj = %d usec (from %s kernel variable)\n",
				      ktickadj,
#ifdef K_TICKADJ_NAME
				      K_TICKADJ_NAME
#else
				      "<this can't happen>"
#endif
				      );
		}
#ifdef PRESET_TICKADJ
		(void) printf("PRESET tickadj = %d usec\n", tickadj);
#endif /* PRESET_TICKADJ */
		if (dosync_offset != 0)
		{
			(void) printf("dosynctodr is %s\n", dosynctodr ? "on" : "off");
		}
		if (noprintf_offset != 0)
		{
			(void) printf("kernel level printf's: %s\n",
				      noprintf ? "off" : "on");
		}
	}

	if (tick <= 0)
	{
		(void) fprintf(stderr, "%s: the value of tick is silly!\n",
			       progname);
		exit(1);
	}

	hz_int = (int)(1000000L / (long)tick);
	hz_hundredths = (int)((100000000L / (long)tick) - ((long)hz_int * 100L));
	if (!quiet)
	{
		(void) printf("KERNEL hz = %d\n", hz);
		(void) printf("calculated hz = %d.%02d Hz\n", hz_int,
			      hz_hundredths);
	}

#if defined SCO5_CLOCK
	recommend_tickadj = 100;
#else /* SCO5_CLOCK */
	tmp = (long) tick * 500L;
	recommend_tickadj = (int)(tmp / 1000000L);
	if (tmp % 1000000L > 0)
	{
		recommend_tickadj++;
	}

#ifdef MIN_REC_TICKADJ
	if (recommend_tickadj < MIN_REC_TICKADJ)
	{
		recommend_tickadj = MIN_REC_TICKADJ;
	}
#endif /* MIN_REC_TICKADJ */
#endif /* SCO5_CLOCK */
  

	if ((!quiet) && (tickadj_offset != 0))
	{
		(void) printf("recommended value of tickadj = %d us\n",
			      recommend_tickadj);
	}

	if (   writetickadj == 0
	       && !writeopttickadj
	       && !unsetdosync
	       && writetick == 0
	       && !setnoprintf)
	{
		exit(errflg ? 1 : 0);
	}

	if (writetickadj == 0 && writeopttickadj)
	{
		writetickadj = recommend_tickadj;
	}

	fd = openfile(file, O_WRONLY);

	if (setnoprintf && (noprintf_offset != 0))
	{
		if (!quiet)
		{
			(void) fprintf(stderr, "setting noprintf: ");
			(void) fflush(stderr);
		}
		writevar(fd, noprintf_offset, 1);
		if (!quiet)
		{
			(void) fprintf(stderr, "done!\n");
		}
	}

	if ((writetick > 0) && (tick_offset != 0))
	{
		if (!quiet)
		{
			(void) fprintf(stderr, "writing tick, value %d: ",
				       writetick);
			(void) fflush(stderr);
		}
		writevar(fd, tick_offset, writetick);
		if (!quiet)
		{
			(void) fprintf(stderr, "done!\n");
		}
	}

	if ((writetickadj > 0) && (tickadj_offset != 0))
	{
		if (!quiet)
		{
			(void) fprintf(stderr, "writing tickadj, value %d: ",
				       writetickadj);
			(void) fflush(stderr);
		}

#ifdef SCO5_CLOCK
		/* scale from usec/tick to nsec/sec */
		writetickadj *= (1000L * HZ);
#endif /* SCO5_CLOCK */

		writevar(fd, tickadj_offset, writetickadj);
		if (!quiet)
		{
			(void) fprintf(stderr, "done!\n");
		}
	}

	if (unsetdosync && (dosync_offset != 0))
	{
		if (!quiet)
		{
			(void) fprintf(stderr, "zeroing dosynctodr: ");
			(void) fflush(stderr);
		}
		writevar(fd, dosync_offset, 0);
		if (!quiet)
		{
			(void) fprintf(stderr, "done!\n");
		}
	}
	(void) close(fd);
	return(errflg ? 1 : 0);
}
Beispiel #27
0
/*
 * The actual main function.
 */
int
sntp_main (
	int argc,
	char **argv,
	const char *sntpVersion
	)
{
	int			i;
	int			exitcode;
	int			optct;
	struct event_config *	evcfg;

	/* Initialize logging system - sets up progname */
	sntp_init_logging(argv[0]);

	if (!libevent_version_ok())
		exit(EX_SOFTWARE);

	init_lib();
	init_auth();

	optct = ntpOptionProcess(&sntpOptions, argc, argv);
	argc -= optct;
	argv += optct;


	debug = OPT_VALUE_SET_DEBUG_LEVEL;

	TRACE(2, ("init_lib() done, %s%s\n",
		  (ipv4_works)
		      ? "ipv4_works "
		      : "",
		  (ipv6_works)
		      ? "ipv6_works "
		      : ""));
	ntpver = OPT_VALUE_NTPVERSION;
	steplimit = OPT_VALUE_STEPLIMIT / 1e3;
	gap.tv_usec = max(0, OPT_VALUE_GAP * 1000);
	gap.tv_usec = min(gap.tv_usec, 999999);

	if (HAVE_OPT(LOGFILE))
		open_logfile(OPT_ARG(LOGFILE));

	msyslog(LOG_INFO, "%s", sntpVersion);

	if (0 == argc && !HAVE_OPT(BROADCAST) && !HAVE_OPT(CONCURRENT)) {
		printf("%s: Must supply at least one of -b hostname, -c hostname, or hostname.\n",
		       progname);
		exit(EX_USAGE);
	}


	/*
	** Eventually, we probably want:
	** - separate bcst and ucst timeouts (why?)
	** - multiple --timeout values in the commandline
	*/

	response_timeout = OPT_VALUE_TIMEOUT;
	response_tv.tv_sec = response_timeout;
	response_tv.tv_usec = 0;

	/* IPv6 available? */
	if (isc_net_probeipv6() != ISC_R_SUCCESS) {
		ai_fam_pref = AF_INET;
		TRACE(1, ("No ipv6 support available, forcing ipv4\n"));
	} else {
		/* Check for options -4 and -6 */
		if (HAVE_OPT(IPV4))
			ai_fam_pref = AF_INET;
		else if (HAVE_OPT(IPV6))
			ai_fam_pref = AF_INET6;
	}

	/* TODO: Parse config file if declared */

	/*
	** Init the KOD system.
	** For embedded systems with no writable filesystem,
	** -K /dev/null can be used to disable KoD storage.
	*/
	kod_init_kod_db(OPT_ARG(KOD), FALSE);

	// HMS: Should we use arg-defalt for this too?
	if (HAVE_OPT(KEYFILE))
		auth_init(OPT_ARG(KEYFILE), &keys);

	/*
	** Considering employing a variable that prevents functions of doing
	** anything until everything is initialized properly
	**
	** HMS: What exactly does the above mean?
	*/
	event_set_log_callback(&sntp_libevent_log_cb);
	if (debug > 0)
		event_enable_debug_mode();
#ifdef WORK_THREAD
	evthread_use_pthreads();
	/* we use libevent from main thread only, locks should be academic */
	if (debug > 0)
		evthread_enable_lock_debuging();
#endif
	evcfg = event_config_new();
	if (NULL == evcfg) {
		printf("%s: event_config_new() failed!\n", progname);
		return -1;
	}
#ifndef HAVE_SOCKETPAIR
	event_config_require_features(evcfg, EV_FEATURE_FDS);
#endif
	/* all libevent calls are from main thread */
	/* event_config_set_flag(evcfg, EVENT_BASE_FLAG_NOLOCK); */
	base = event_base_new_with_config(evcfg);
	event_config_free(evcfg);
	if (NULL == base) {
		printf("%s: event_base_new() failed!\n", progname);
		return -1;
	}

	/* wire into intres resolver */
	worker_per_query = TRUE;
	addremove_io_fd = &sntp_addremove_fd;

	open_sockets();

	if (HAVE_OPT(BROADCAST)) {
		int		cn = STACKCT_OPT(  BROADCAST );
		const char **	cp = STACKLST_OPT( BROADCAST );

		while (cn-- > 0) {
			handle_lookup(*cp, CTX_BCST);
			cp++;
		}
	}

	if (HAVE_OPT(CONCURRENT)) {
		int		cn = STACKCT_OPT( CONCURRENT );
		const char **	cp = STACKLST_OPT( CONCURRENT );

		while (cn-- > 0) {
			handle_lookup(*cp, CTX_UCST | CTX_CONC);
			cp++;
		}
	}

	for (i = 0; i < argc; ++i)
		handle_lookup(argv[i], CTX_UCST);

	gettimeofday_cached(base, &start_tv);
	event_base_dispatch(base);
	event_base_free(base);

	if (!time_adjusted &&
	    (ENABLED_OPT(STEP) || ENABLED_OPT(SLEW)))
		exitcode = 1;
	else
		exitcode = 0;

	return exitcode;
}
Beispiel #28
0
/*
 * main - parse arguments and handle options
 */
int
ntpdcmain(
	int argc,
	char *argv[]
	)
{
	extern int ntp_optind;

	delay_time.l_ui = 0;
	delay_time.l_uf = DEFDELAY;

#ifdef SYS_VXWORKS
	clear_globals();
	taskPrioritySet(taskIdSelf(), 100 );
#endif

	init_lib();	/* sets up ipv4_works, ipv6_works */
	ssl_applink();

	/* Check to see if we have IPv6. Otherwise default to IPv4 */
	if (!ipv6_works)
		ai_fam_default = AF_INET;

	progname = argv[0];

	{
		int optct = ntpOptionProcess(&ntpdcOptions, argc, argv);
		argc -= optct;
		argv += optct;
	}

	if (HAVE_OPT(IPV4))
		ai_fam_templ = AF_INET;
	else if (HAVE_OPT(IPV6))
		ai_fam_templ = AF_INET6;
	else
		ai_fam_templ = ai_fam_default;

	if (HAVE_OPT(COMMAND)) {
		int		cmdct = STACKCT_OPT( COMMAND );
		const char**	cmds  = STACKLST_OPT( COMMAND );

		while (cmdct-- > 0) {
			ADDCMD(*cmds++);
		}
	}

	debug = DESC(DEBUG_LEVEL).optOccCt;

	if (HAVE_OPT(INTERACTIVE)) {
		interactive = 1;
	}

	if (HAVE_OPT(NUMERIC)) {
		showhostnames = 0;
	}

	if (HAVE_OPT(LISTPEERS)) {
		ADDCMD("listpeers");
	}

	if (HAVE_OPT(PEERS)) {
		ADDCMD("peers");
	}

	if (HAVE_OPT(SHOWPEERS)) {
		ADDCMD("dmpeers");
	}

	if (ntp_optind == argc) {
		ADDHOST(DEFHOST);
	} else {
		for (; ntp_optind < argc; ntp_optind++)
		    ADDHOST(argv[ntp_optind]);
	}

	if (numcmds == 0 && interactive == 0
	    && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
		interactive = 1;
	}

#if 0
	ai_fam_templ = ai_fam_default;
	while ((c = ntp_getopt(argc, argv, "46c:dilnps")) != EOF)
	    switch (c) {
		case '4':
		    ai_fam_templ = AF_INET;
		    break;
		case '6':
		    ai_fam_templ = AF_INET6;
		    break;
		case 'c':
		    ADDCMD(ntp_optarg);
		    break;
		case 'd':
		    ++debug;
		    break;
		case 'i':
		    interactive = 1;
		    break;
		case 'l':
		    ADDCMD("listpeers");
		    break;
		case 'n':
		    showhostnames = 0;
		    break;
		case 'p':
		    ADDCMD("peers");
		    break;
		case 's':
		    ADDCMD("dmpeers");
		    break;
		default:
		    errflg++;
		    break;
	    }

	if (errflg) {
		(void) fprintf(stderr,
			       "usage: %s [-46dilnps] [-c cmd] host ...\n",
			       progname);
		exit(2);
	}

	if (ntp_optind == argc) {
		ADDHOST(DEFHOST);
	} else {
		for (; ntp_optind < argc; ntp_optind++)
		    ADDHOST(argv[ntp_optind]);
	}

	if (numcmds == 0 && interactive == 0
	    && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
		interactive = 1;
	}
#endif

#ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
	if (interactive)
	    (void) signal_no_reset(SIGINT, abortcmd);
#endif /* SYS_WINNT */

	/*
	 * Initialize the packet data buffer
	 */
	pktdatasize = INITDATASIZE;
	pktdata = emalloc(INITDATASIZE);

	if (numcmds == 0) {
		(void) openhost(chosts[0]);
		getcmds();
	} else {
		int ihost;
		int icmd;

		for (ihost = 0; ihost < numhosts; ihost++) {
			if (openhost(chosts[ihost]))
			    for (icmd = 0; icmd < numcmds; icmd++) {
				    if (numhosts > 1) 
					printf ("--- %s ---\n",chosts[ihost]);
				    docmd(ccmds[icmd]);
			    }
		}
	}
#ifdef SYS_WINNT
	WSACleanup();
#endif
	return(0);
} /* main end */
Beispiel #29
0
void
setUp(void) { 
	init_lib(); 
}
Beispiel #30
0
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;
}