int main(int argc, char *argv[]) { int ch; char opts[] = "ispuU:cC:dvV:"; struct rlimit rlp; long nn; if(argc==1) return help(); while ((ch = getopt(argc,argv,opts))!=EOF) switch (ch) { case 'i': re_and_eff_ID(); break; case 's': setpgid(0,0); break; case 'p': proc_ID(); break; case 'u': printf("ulimit = %ld\n", ulimit(1)); break; case 'U': nn=atol(optarg); ulimit(2, nn); if(ulimit(1)!= nn) printf("Error, you can't change ulimit!\n"); break; case 'c': getrlimit(RLIMIT_CORE, &rlp); printf("Core size = %ld\n", rlp.rlim_cur); break; case 'C': set_core_size(optarg); break; case 'd': printf("Current work directory is: %s\n", getcwd(0,255)); break; case 'v': print_env(); break; case 'V': putenv(optarg); break; } return 0; }
EPollEngine::EPollEngine() { int max = ulimit(4, 0); if (max > 0) { MAX_DESCRIPTORS = max; } else { ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: Can't determine maximum number of open sockets!"); std::cout << "ERROR: Can't determine maximum number of open sockets!" << std::endl; ServerInstance->Exit(EXIT_STATUS_SOCKETENGINE); } // This is not a maximum, just a hint at the eventual number of sockets that may be polled. EngineHandle = epoll_create(GetMaxFds() / 4); if (EngineHandle == -1) { ServerInstance->Logs->Log("SOCKET",LOG_DEFAULT, "ERROR: Could not initialize socket engine: %s", strerror(errno)); ServerInstance->Logs->Log("SOCKET",LOG_DEFAULT, "ERROR: Your kernel probably does not have the proper features. This is a fatal error, exiting now."); std::cout << "ERROR: Could not initialize epoll socket engine: " << strerror(errno) << std::endl; std::cout << "ERROR: Your kernel probably does not have the proper features. This is a fatal error, exiting now." << std::endl; ServerInstance->Exit(EXIT_STATUS_SOCKETENGINE); } ref = new EventHandler* [GetMaxFds()]; events = new struct epoll_event[GetMaxFds()]; memset(ref, 0, GetMaxFds() * sizeof(EventHandler*)); }
PortsEngine::PortsEngine() { int max = ulimit(4, 0); if (max > 0) { MAX_DESCRIPTORS = max; } else { ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: Can't determine maximum number of open sockets!"); std::cout << "ERROR: Can't determine maximum number of open sockets!" << std::endl; ServerInstance->Exit(EXIT_STATUS_SOCKETENGINE); } EngineHandle = port_create(); if (EngineHandle == -1) { ServerInstance->Logs->Log("SOCKET", LOG_SPARSE, "ERROR: Could not initialize socket engine: %s", strerror(errno)); ServerInstance->Logs->Log("SOCKET", LOG_SPARSE, "ERROR: This is a fatal error, exiting now."); std::cout << "ERROR: Could not initialize socket engine: " << strerror(errno) << std::endl; std::cout << "ERROR: This is a fatal error, exiting now." << std::endl; ServerInstance->Exit(EXIT_STATUS_SOCKETENGINE); } CurrentSetSize = 0; ref = new EventHandler* [GetMaxFds()]; events = new port_event_t[GetMaxFds()]; memset(ref, 0, GetMaxFds() * sizeof(EventHandler*)); }
void set_filesize_limit (int blocks) { #if HAVE_ULIMIT_H ulimit (UL_SETFSIZE, blocks); #elif defined(RLIMIT_FSIZE) struct rlimit rlimit_fsize; rlimit_fsize.rlim_cur = rlimit_fsize.rlim_max = 512L * blocks; setrlimit (RLIMIT_FSIZE, &rlimit_fsize); #endif }
static void storeQualifierU(void* ptr, int qualifier, uintmax_t data) { switch (qualifier) { case 'H': *(unsigned char*)ptr = (unsigned char)ulimit(data, UCHAR); break; case 'h': *(unsigned short*)ptr = (unsigned short)ulimit(data, USHRT); break; case 'l': *(unsigned long*)ptr = (unsigned long)ulimit(data, ULONG); break; case 'L': *(unsigned long long*)ptr = (unsigned long long)ulimit(data, ULLONG); break; case 'j': *(uintmax_t*)ptr = data; break; case 'z': *(size_t*)ptr = (size_t)ulimit(data, UINTPTR); break; case 't': *(ptrdiff_t*)ptr = (ptrdiff_t)limit(data, INTPTR); break; default: *(unsigned int*)ptr = (unsigned int)ulimit(data, UINT); break; } }
void SocketEngine::Init() { max = ulimit(4, 0); if (max <= 0) throw SocketException("Can't determine maximum number of open sockets"); EngineHandle = epoll_create(max / 4); if (EngineHandle == -1) throw SocketException("Could not initialize epoll socket engine: " + Anope::LastError()); events = new epoll_event[max]; memset(events, 0, sizeof(epoll_event) * max); }
void set_file_limit(off_t limit) { #ifdef USE_ULIMIT if (ulimit(UL_SETFSIZE, limit / ULIMIT_BLOCK_SIZE) < 0) msg_fatal("ulimit: %m"); #else struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = limit; if (setrlimit(RLIMIT_FSIZE, &rlim) < 0) msg_fatal("setrlimit: %m"); #ifdef SIGXFSZ if (signal(SIGXFSZ, SIG_IGN) == SIG_ERR) msg_fatal("signal(SIGXFSZ,SIG_IGN): %m"); #endif #endif /* USE_ULIMIT */ }
int set_filesize_limit (int blocks) { int ret = -1; #if HAVE_ULIMIT_H if (ulimit (UL_SETFSIZE, blocks) != -1) { ret = 0; } #elif defined(RLIMIT_FSIZE) struct rlimit rlimit_fsize; rlimit_fsize.rlim_cur = 512L * blocks; rlimit_fsize.rlim_max = rlimit_fsize.rlim_cur; ret = setrlimit (RLIMIT_FSIZE, &rlimit_fsize); #endif return ret; }
void SocketEngine::Init() { // MAX_DESCRIPTORS is mainly used for display purposes, no problem if ulimit() fails and returns a negative number MAX_DESCRIPTORS = ulimit(4, 0); // 128 is not a maximum, just a hint at the eventual number of sockets that may be polled, // and it is completely ignored by 2.6.8 and later kernels, except it must be larger than zero. EngineHandle = epoll_create(128); if (EngineHandle == -1) { ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: Could not initialize socket engine: %s", strerror(errno)); ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: Your kernel probably does not have the proper features. This is a fatal error, exiting now."); std::cout << "ERROR: Could not initialize epoll socket engine: " << strerror(errno) << std::endl; std::cout << "ERROR: Your kernel probably does not have the proper features. This is a fatal error, exiting now." << std::endl; ServerInstance->QuickExit(EXIT_STATUS_SOCKETENGINE); } }
int PortsEngine::GetMaxFds() { if (MAX_DESCRIPTORS) return MAX_DESCRIPTORS; int max = ulimit(4, 0); if (max > 0) { MAX_DESCRIPTORS = max; return max; } else { ServerInstance->Logs->Log("SOCKET", DEFAULT, "ERROR: Can't determine maximum number of open sockets!"); printf("ERROR: Can't determine maximum number of open sockets!\n"); ServerInstance->Exit(EXIT_STATUS_SOCKETENGINE); } #include <ulimit.h> }
off_t get_file_limit(void) { off_t limit; #ifdef USE_ULIMIT if ((limit = ulimit(UL_GETFSIZE, 0)) < 0) msg_fatal("ulimit: %m"); if (limit > OFF_T_MAX / ULIMIT_BLOCK_SIZE) limit = OFF_T_MAX / ULIMIT_BLOCK_SIZE; return (limit * ULIMIT_BLOCK_SIZE); #else struct rlimit rlim; if (getrlimit(RLIMIT_FSIZE, &rlim) < 0) msg_fatal("getrlimit: %m"); limit = rlim.rlim_cur; return (limit < 0 ? OFF_T_MAX : rlim.rlim_cur); #endif /* USE_ULIMIT */ }
static void get_lim_data () { extern long ulimit (); lim_data = -1; /* Use the ulimit call, if we seem to have it. */ #if !defined (ULIMIT_BREAK_VALUE) || defined (GNU_LINUX) lim_data = ulimit (3, 0); #endif /* If that didn't work, just use the macro's value. */ #ifdef ULIMIT_BREAK_VALUE if (lim_data == -1) lim_data = ULIMIT_BREAK_VALUE; #endif lim_data -= (long) data_space_start; }
void rktio_close_fds_after_fork(int skip1, int skip2, int skip3) { int i; # ifdef USE_ULIMIT i = ulimit(4, 0); # elif defined(__ANDROID__) i = sysconf(_SC_OPEN_MAX); # else i = getdtablesize(); # endif while (i--) { int cr; if ((i != skip1) && (i != skip2) && (i != skip3)) { do { cr = close(i); } while ((cr == -1) && (errno == EINTR)); } } }
openfiles() { int i; int rc = 0; struct stat statbuf; int nfiles; # ifndef _NFILE # if defined(usl_us5) nfiles = (int)ulimit(4, 0L); # else /* usl_us5 */ extern int getdtablesize(); nfiles = getdtablesize(); # endif /* usl_us5 */ # else nfiles = _NFILE; # endif for (i = 0; i< nfiles ; i++) { if (-1 != fstat(i, &statbuf)) { fprintf(stderr, "fd %d: inode %d, uid %d, gid %d, size %d, mode 0%o\n", i, statbuf.st_ino, statbuf.st_uid, statbuf.st_gid, statbuf.st_size, statbuf.st_mode); rc = 1; } } return(rc); }
int PollEngine::GetMaxFds() { #ifndef __FreeBSD__ if (MAX_DESCRIPTORS) return MAX_DESCRIPTORS; int max = ulimit(4, 0); if (max > 0) { MAX_DESCRIPTORS = max; return max; } else { MAX_DESCRIPTORS = 0; ServerInstance->Logs->Log("SOCKET", DEFAULT, "ERROR: Can't determine maximum number of open sockets: %s", strerror(errno)); printf("ERROR: Can't determine maximum number of open sockets: %s\n", strerror(errno)); ServerInstance->Exit(EXIT_STATUS_SOCKETENGINE); } return 0; #else if (!MAX_DESCRIPTORS) { int mib[2], maxfiles; size_t len; mib[0] = CTL_KERN; mib[1] = KERN_MAXFILES; len = sizeof(maxfiles); sysctl(mib, 2, &maxfiles, &len, NULL, 0); MAX_DESCRIPTORS = maxfiles; return maxfiles; } return MAX_DESCRIPTORS; #endif }
int main(int ac, char **av) { int lc; /* loop counter */ int i; /* inner loop (test case) counter */ const char *msg; /* message returned from parse_opts */ int tmp; TST_TOTAL = sizeof(Scenarios)/sizeof(struct limits_t); /*************************************************************** * parse standard options ***************************************************************/ if ( (msg=parse_opts(ac, av, (option_t *)NULL, NULL)) != (char *) NULL ) { tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); tst_exit(); } /*************************************************************** * perform global setup for test ***************************************************************/ setup(); /*************************************************************** * check looping state if -c option given ***************************************************************/ for (lc=0; TEST_LOOPING(lc); lc++) { /* reset Tst_count in case we are looping. */ Tst_count=0; for ( i=0; i<TST_TOTAL; i++) { cmd=Scenarios[i].cmd; limit=Scenarios[i].newlimit; /* * Call ulimit(2) */ TEST(ulimit(cmd, limit)); /* check return code */ if ( TEST_RETURN == -1 ) { if ( Scenarios[i].exp_fail ) { if ( STD_FUNCTIONAL_TEST ) { tst_resm(TPASS, "ulimit(%d, %d) Failed, errno=%d : %s", cmd, limit, TEST_ERRNO, strerror(TEST_ERRNO)); } } else { tst_resm(TFAIL, "ulimit(%d, %d) Failed, errno=%d : %s", cmd, limit, TEST_ERRNO, strerror(TEST_ERRNO)); } } else { if ( Scenarios[i].exp_fail ) { tst_resm(TFAIL, "ulimit(%d, %d) returned %d", cmd, limit, TEST_RETURN); } else if ( STD_FUNCTIONAL_TEST ) { tst_resm(TPASS, "ulimit(%d, %d) returned %d", cmd, limit, TEST_RETURN); } /* * Save the UL_GETFSIZE return value in the newlimit field * for UL_SETFSIZE test cases. */ if ( cmd == UL_GETFSIZE ) { for (tmp=i+1; tmp<TST_TOTAL; tmp++) { if ( Scenarios[tmp].nlim_flag == 1 ) { Scenarios[tmp].newlimit = TEST_RETURN; } if ( Scenarios[tmp].nlim_flag == 2 ) { Scenarios[tmp].newlimit = TEST_RETURN-1; } } } } } } /* End for TEST_LOOPING */ /*************************************************************** * cleanup and exit ***************************************************************/ cleanup(); return 0; } /* End main */
QString Container::toString() const { QStringList ret; bool func=false; Operator *op=0; for(int i=0; i<m_params.count(); i++) { if(m_params[i]==0) { qDebug() << "kkk"; return "<<kk>>"; } if(m_params[i]->type() == Object::oper) op = (Operator*) m_params[i]; else if(m_params[i]->type() == Object::variable) { Ci *b = (Ci*) m_params[i]; if(b->isFunction()) func=true; ret << b->toString(); } else if(m_params[i]->type() == Object::container) { Container *c = (Container*) m_params[i]; QString s = c->toString(); Operator child_op = c->firstOperator(); if(op!=0 && op->weight()>child_op.weight() && child_op.nparams()!=1) s=QString("(%1)").arg(s); if(c->containerType() == Object::bvar) { Container *ul = ulimit(), *dl = dlimit(); if(ul!=0 || dl!=0) { if(dl!=0) s += dl->toString(); s += ".."; if(ul!=0) s += ul->toString(); } } if(c->containerType()!=Object::uplimit && c->containerType()!=Object::downlimit) ret << s; } else ret << m_params[i]->toString(); } QString toret; switch(containerType()) { case Object::declare: toret += ret.join(":="); break; case Object::lambda: toret += ret.join(""); break; case Object::math: toret += ret.join("; "); break; case Object::apply: if(func){ QString n = ret.takeFirst(); toret += QString("%1(%2)").arg(n).arg(ret.join(", ")); } else if(op==0) toret += ret.join(" "); else switch(op->operatorType()) { case Object::plus: toret += ret.join("+"); break; case Object::times: toret += ret.join("*"); break; case Object::divide: toret += ret.join("/"); break; case Object::minus: if(ret.count()==1) toret += "-"+ret[0]; else toret += ret.join("-"); break; case Object::power: toret += ret.join("^"); break; default: toret += QString("%1(%2)").arg(op->toString()).arg(ret.join(", ")); break; } break; case Object::uplimit: //x->(n1..n2) is put at the same time case Object::downlimit: break; case Object::bvar: toret += ret.join("->")+"->"; break; default: toret += ret.join(" ?? "); break; } return toret; }
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; }
int main(int ac, char **av) { int lc; int i; char *msg; int tmp; TST_TOTAL = sizeof(Scenarios) / sizeof(struct limits_t); /*************************************************************** * parse standard options ***************************************************************/ if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) { tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); tst_exit(); } /*************************************************************** * perform global setup for test ***************************************************************/ setup(); /*************************************************************** * check looping state if -c option given ***************************************************************/ for (lc = 0; TEST_LOOPING(lc); lc++) { Tst_count = 0; for (i = 0; i < TST_TOTAL; i++) { cmd = Scenarios[i].cmd; limit = Scenarios[i].newlimit; /* * Call ulimit(2) */ TEST(ulimit(cmd, limit)); /* check return code */ if (TEST_RETURN == -1) { if (Scenarios[i].exp_fail) { if (STD_FUNCTIONAL_TEST) { tst_resm(TPASS | TTERRNO, "ulimit(%d, %ld) Failed expectedly", cmd, limit); } } else { tst_resm(TFAIL | TTERRNO, "ulimit(%d, %ld) Failed", cmd, limit); } } else { if (Scenarios[i].exp_fail) { tst_resm(TFAIL, "ulimit(%d, %ld) returned %ld, succeeded unexpectedly", cmd, limit, TEST_RETURN); } else if (STD_FUNCTIONAL_TEST) { tst_resm(TPASS, "ulimit(%d, %ld) returned %ld", cmd, limit, TEST_RETURN); } /* * Save the UL_GETFSIZE return value in the newlimit field * for UL_SETFSIZE test cases. */ if (cmd == UL_GETFSIZE) { for (tmp = i + 1; tmp < TST_TOTAL; tmp++) { if (Scenarios[tmp].nlim_flag == 1) { Scenarios[tmp].newlimit = TEST_RETURN; } if (Scenarios[tmp].nlim_flag == 2) { Scenarios[tmp].newlimit = TEST_RETURN - 1; } } } } } } /*************************************************************** * cleanup and exit ***************************************************************/ cleanup(); tst_exit(); }
int main(int argc, char **argv) { struct stat buf; int ret; char scratch[BUFSIZ]; char log[BUFSIZ]; char olog[BUFSIZ]; char *scratch_p = scratch; char *mytag_p; FILE *fp; extern char *getenv(); char *parse(); int c; extern char *optarg; extern int optind; int i; char *Mytag_p = Mytag; /* Get my port monitor tag out of the environment */ if ((mytag_p = getenv("PMTAG")) == NULL) { /* no place to write */ exit(1); } strcpy(Mytag, mytag_p); /* open log file */ sprintf(log, "%s/%s/%s", ALTDIR, Mytag_p, LOGNAME); sprintf(olog, "%s/%s/%s", ALTDIR, Mytag_p, OLOGNAME); if (stat(log, &buf) == 0) { /* file exists, try and save it but if we can't don't worry */ unlink(olog); rename(log, olog); } if ((i = open(log, O_WRONLY|O_CREAT|O_APPEND, 0444)) < 0) logexit(1, nologfile); /* as stated above, the log file should be file descriptor 5 */ if ((ret = fcntl(i, F_DUPFD, 5)) != 5) logexit(1, nologfile); Logfp = fdopen(ret, "a+"); /* Get my port monitor tag out of the environment */ if ((mytag_p = getenv("PMTAG")) == NULL) { logexit(1, nopmtag); } strcpy(Mytag, mytag_p); (void) umask(022); Readdb = FALSE; if (geteuid() != (uid_t) 0) { logmessage("Must be root to start listener"); logexit(1, badstart); } while ((c = getopt(argc, argv, "m:")) != EOF) switch (c) { case 'm': Minor_prefix = optarg; break; default: logexit(1, usage); break; } if ((Netspec = argv[optind]) == NULL) { logexit(1, usage); } if ((Netconf = getnetconfigent(Netspec)) == NULL) { sprintf(scratch, "no netconfig entry for <%s>", Netspec); logmessage(scratch); logexit(1, badstart); } if (!Minor_prefix) Minor_prefix = argv[optind]; if ((int) strlen(Netspec) > PATHSIZE) { logmessage(badnspmsg); logexit(1, badstart); } /* * SAC will start the listener in the correct directory, so we * don't need to chdir there, as we did in older versions */ strcpy(Provbuf, "/dev/"); strcat(Provbuf, Netspec); (void) umask(0); init_files(); /* open Accept, Sac, Pm, Pass files */ pid_open(); /* create pid file */ #ifdef DEBUGMODE sprintf(scratch, "%s/%s/%s", ALTDIR, Mytag, DBGNAME); Debugfp = fopen(scratch, "w"); #endif #ifdef DEBUGMODE if ((!Logfp) || (!Debugfp)) #else if (!Logfp) #endif logexit(1, badstart); /* * In case we started with no environment, find out what timezone we're * in. This will get passed to children, so only need to do once. */ if (getenv("TZ") == NULL) { fp = fopen(TZFILE, "r"); if (fp) { while (fgets(tzenv, BUFSIZ, fp)) { if (tzenv[strlen(tzenv) - 1] == '\n') tzenv[strlen(tzenv) - 1] = '\0'; if (!strncmp(TZSTR, tzenv, strlen(TZSTR))) { putenv(parse(tzenv)); break; } } fclose(fp); } else { sprintf(scratch, "couldn't open %s, default to GMT", TZFILE); logmessage(scratch); } } logmessage("@(#)listen:listen.c 1.19.9.1"); #ifdef DEBUGMODE logmessage("Listener process with DEBUG capability"); #endif sprintf(scratch, "Listener port monitor tag: %s", Mytag_p); logmessage(scratch); DEBUG((9, "Minor prefix: %s Netspec %s", Minor_prefix, Netspec)); /* fill in Pmmesg fields that always stay the same */ Pmmsg.pm_maxclass = MAXCLASS; strcpy(Pmmsg.pm_tag, Mytag_p); Pmmsg.pm_size = 0; /* Find out what state to start in. If not in env, exit */ if ((scratch_p = getenv("ISTATE")) == NULL) logexit(1, "ERROR: ISTATE variable not set in environment"); if (!strcmp(scratch_p, "enabled")) { State = PM_ENABLED; logmessage("Starting state: ENABLED"); } else { State = PM_DISABLED; logmessage("Starting state: DISABLED"); } /* try to get my "basename" */ Progname = strrchr(argv[0], '/'); if (Progname && Progname[1]) ++Progname; else Progname = argv[0]; catch_signals(); /* * Allocate memory for private address and file descriptor table * Here we are assuming that no matter how many private addresses * exist in the system if the system limit is 20 then we will only * get 20 file descriptors */ Ndesc = ulimit(4,0L); /* get num of file des on system */ read_dbf(DB_INIT); net_open(); /* init, open, bind names */ for (i = 3; i < Ndesc; i++) { /* leave stdout, stderr open */ fcntl(i, F_SETFD, 1); /* set close on exec flag*/ } logmessage("Initialization Complete"); listen(); return (0); }
/* * Main program. Initialize us, disconnect us from the tty if necessary, * and loop waiting for I/O and/or timer expiries. */ int ntpdmain( int argc, char *argv[] ) { l_fp now; struct recvbuf *rbuf; #ifdef _AIX /* HMS: ifdef SIGDANGER? */ struct sigaction sa; #endif progname = argv[0]; initializing = 1; /* mark that we are initializing */ process_commandline_opts(&argc, &argv); init_logging(progname, 1); /* Open the log file */ char *error = NULL; if (sandbox_init("ntpd", SANDBOX_NAMED, &error) == -1) { msyslog(LOG_ERR, "sandbox_init(ntpd, SANDBOX_NAMED) failed: %s", error); sandbox_free_error(error); } #ifdef HAVE_UMASK { mode_t uv; uv = umask(0); if(uv) (void) umask(uv); else (void) umask(022); } #endif #if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */ { uid_t uid; uid = getuid(); if (uid && !HAVE_OPT( SAVECONFIGQUIT )) { msyslog(LOG_ERR, "ntpd: must be run as root, not uid %ld", (long)uid); printf("must be run as root, not uid %ld\n", (long)uid); exit(1); } } #endif /* getstartup(argc, argv); / * startup configuration, may set debug */ #ifdef DEBUG debug = DESC(DEBUG_LEVEL).optOccCt; DPRINTF(1, ("%s\n", Version)); #endif /* honor -l/--logfile option to log to a file */ setup_logfile(); /* * Enable the Multi-Media Timer for Windows? */ #ifdef SYS_WINNT if (HAVE_OPT( MODIFYMMTIMER )) set_mm_timer(MM_TIMER_HIRES); #endif if (HAVE_OPT( NOFORK ) || HAVE_OPT( QUIT ) #ifdef DEBUG || debug #endif || HAVE_OPT( SAVECONFIGQUIT )) nofork = 1; 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 ); isc_netaddr_t netaddr; while (ifacect-- > 0) { add_nic_rule( is_ip_address(*ifaces, &netaddr) ? MATCH_IFADDR : MATCH_IFNAME, *ifaces, -1, ACTION_LISTEN); ifaces++; } } if (HAVE_OPT( NICE )) priority_done = 0; #if defined(HAVE_SCHED_SETSCHEDULER) if (HAVE_OPT( PRIORITY )) { config_priority = OPT_VALUE_PRIORITY; config_priority_override = 1; priority_done = 0; } #endif #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)); #if !defined(VMS) # ifndef NODETACH /* * Detach us from the terminal. May need an #ifndef GIZMO. */ if (!nofork) { /* * 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); # ifndef SYS_WINNT # ifdef HAVE_DAEMON daemon(0, 0); # else /* not HAVE_DAEMON */ if (fork()) /* HMS: What about a -1? */ exit(0); { #if !defined(F_CLOSEM) u_long s; int max_fd; #endif /* !FCLOSEM */ if (syslog_file != NULL) { fclose(syslog_file); syslog_file = NULL; } #if defined(F_CLOSEM) /* * From 'Writing Reliable AIX Daemons,' SG24-4946-00, * by Eric Agar (saves us from doing 32767 system * calls) */ if (fcntl(0, F_CLOSEM, 0) == -1) msyslog(LOG_ERR, "ntpd: failed to close open files(): %m"); #else /* not F_CLOSEM */ # if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX) max_fd = sysconf(_SC_OPEN_MAX); # else /* HAVE_SYSCONF && _SC_OPEN_MAX */ max_fd = getdtablesize(); # endif /* HAVE_SYSCONF && _SC_OPEN_MAX */ for (s = 0; s < max_fd; s++) (void) close((int)s); #endif /* not F_CLOSEM */ (void) open("/", 0); (void) dup2(0, 1); (void) dup2(0, 2); init_logging(progname, 0); /* we lost our logfile (if any) daemonizing */ setup_logfile(); #ifdef SYS_DOMAINOS { uid_$t puid; status_$t st; proc2_$who_am_i(&puid); proc2_$make_server(&puid, &st); } #endif /* SYS_DOMAINOS */ #if defined(HAVE_SETPGID) || defined(HAVE_SETSID) # ifdef HAVE_SETSID if (setsid() == (pid_t)-1) msyslog(LOG_ERR, "ntpd: setsid(): %m"); # else if (setpgid(0, 0) == -1) msyslog(LOG_ERR, "ntpd: setpgid(): %m"); # endif #else /* HAVE_SETPGID || HAVE_SETSID */ { # if defined(TIOCNOTTY) int fid; fid = open("/dev/tty", 2); if (fid >= 0) { (void) ioctl(fid, (u_long) TIOCNOTTY, (char *) 0); (void) close(fid); } # endif /* defined(TIOCNOTTY) */ # ifdef HAVE_SETPGRP_0 (void) setpgrp(); # else /* HAVE_SETPGRP_0 */ (void) setpgrp(0, getpid()); # endif /* HAVE_SETPGRP_0 */ } #endif /* HAVE_SETPGID || HAVE_SETSID */ #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; (void) sigaction(SIGDANGER, &sa, NULL); #endif /* _AIX */ } # endif /* not HAVE_DAEMON */ # endif /* SYS_WINNT */ } # endif /* NODETACH */ #endif /* VMS */ #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. */ { int fd = open("/dev/at1", O_RDONLY); if (fd >= 0) { int zero = 0; if (ioctl(fd, ACPU_LOCK, &zero) < 0) msyslog(LOG_ERR, "cannot lock to base CPU: %m"); close( fd ); } /* else ... * If we can't open the device, this probably just isn't * a multiprocessor system, so we're A-OK. */ } #endif #if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT) && defined(MCL_FUTURE) # ifdef HAVE_SETRLIMIT /* * Set the stack limit to something smaller, so that we don't lock a lot * of unused stack memory. */ { struct rlimit rl; /* HMS: must make the rlim_cur amount configurable */ if (getrlimit(RLIMIT_STACK, &rl) != -1 && (rl.rlim_cur = 50 * 4096) < rl.rlim_max) { if (setrlimit(RLIMIT_STACK, &rl) == -1) { msyslog(LOG_ERR, "Cannot adjust stack limit for mlockall: %m"); } } # 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 privlege. To be useful the value * has to be larger than the largest ntpd resident set size. */ rl.rlim_cur = rl.rlim_max = 32*1024*1024; if (setrlimit(RLIMIT_MEMLOCK, &rl) == -1) { msyslog(LOG_ERR, "Cannot set RLIMIT_MEMLOCK: %m"); } # endif /* RLIMIT_MEMLOCK */ } # endif /* HAVE_SETRLIMIT */ /* * lock the process into memory */ if (mlockall(MCL_CURRENT|MCL_FUTURE) < 0) msyslog(LOG_ERR, "mlockall(): %m"); #else /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */ # 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 on AIX: %m"); } # endif /* _AIX */ /* * lock the process into memory */ if (plock(PROCLOCK) < 0) msyslog(LOG_ERR, "plock(PROCLOCK): %m"); # else /* not PROCLOCK */ # ifdef TXTLOCK /* * Lock text into ram */ if (plock(TXTLOCK) < 0) msyslog(LOG_ERR, "plock(TXTLOCK) error: %m"); # else /* not TXTLOCK */ msyslog(LOG_ERR, "plock() - don't know what to lock!"); # endif /* not TXTLOCK */ # endif /* not PROCLOCK */ # endif /* HAVE_PLOCK */ #endif /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */ /* * Set up signals we pay attention to locally. */ #ifdef SIGDIE1 (void) signal_no_reset(SIGDIE1, finish); #endif /* SIGDIE1 */ #ifdef SIGDIE2 (void) signal_no_reset(SIGDIE2, finish); #endif /* SIGDIE2 */ #ifdef SIGDIE3 (void) signal_no_reset(SIGDIE3, finish); #endif /* SIGDIE3 */ #ifdef SIGDIE4 (void) signal_no_reset(SIGDIE4, finish); #endif /* SIGDIE4 */ #ifdef SIGBUS (void) signal_no_reset(SIGBUS, finish); #endif /* SIGBUS */ #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. */ #if defined SIGPIPE (void) signal_no_reset(SIGPIPE, SIG_IGN); #endif /* SIGPIPE */ /* * Call the init_ routines to initialize the data structures. * * Exactly what command-line options are we expecting here? */ init_auth(); init_util(); init_restrict(); init_mon(); init_timer(); init_lib(); 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); NLOG(NLOG_SYSINFO) /* 'if' clause for syslog */ msyslog(LOG_NOTICE, "%s", Version); report_event(EVNT_SYSRESTART, NULL, NULL); loop_config(LOOP_DRIFTCOMP, old_drift); initializing = 0; #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); } #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 */ 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) { user = strdup(pw->pw_name); if (NULL == user) { msyslog(LOG_ERR, "strdup() failed: %m"); exit (-1); } 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); } } 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 (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); } #ifndef HAVE_LINUX_CAPABILITIES /* * 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 if (disable_dynamic_updates && interface_interval) { interface_interval = 0; msyslog(LOG_INFO, "running in unprivileged mode disables dynamic interface tracking"); } #ifdef HAVE_LINUX_CAPABILITIES do { /* * 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 = (interface_interval) ? "cap_sys_time,cap_net_bind_service=ipe" : "cap_sys_time=ipe"; if( ! ( caps = cap_from_text( captext ) ) ) { msyslog( LOG_ERR, "cap_from_text() failed: %m" ); exit(-1); } if( cap_set_proc( caps ) == -1 ) { msyslog( LOG_ERR, "cap_set_proc() failed to drop root privileges: %m" ); exit(-1); } cap_free( caps ); } while(0); #endif /* HAVE_LINUX_CAPABILITIES */ } /* if( droproot ) */ #endif /* HAVE_DROPROOT */ /* * Use select() on all on all input fd's for unlimited * time. select() will terminate on SIGALARM or on the * reception of input. Using select() means we can't do * robust signal handling and we get a potential race * between checking for alarms and doing the select(). * Mostly harmless, I think. */ /* On VMS, I suspect that select() can't be interrupted * by a "signal" either, so I take the easy way out and * have select() time out after one second. * System clock updates really aren't time-critical, * and - lacking a hardware reference clock - I have * yet to learn about anything else that is. */ #if defined(HAVE_IO_COMPLETION_PORT) for (;;) { GetReceivedBuffers(); #else /* normal I/O */ BLOCK_IO_AND_ALARM(); was_alarmed = 0; for (;;) { # if !defined(HAVE_SIGNALED_IO) extern fd_set activefds; extern int maxactivefd; fd_set rdfdes; int nfound; # endif if (alarm_flag) /* alarmed? */ { was_alarmed = 1; alarm_flag = 0; } if (!was_alarmed && has_full_recv_buffer() == ISC_FALSE) { /* * Nothing to do. Wait for something. */ # ifndef HAVE_SIGNALED_IO rdfdes = activefds; # if defined(VMS) || defined(SYS_VXWORKS) /* make select() wake up after one second */ { struct timeval t1; t1.tv_sec = 1; t1.tv_usec = 0; nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0, (fd_set *)0, &t1); } # else nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0, (fd_set *)0, (struct timeval *)0); # endif /* VMS */ if (nfound > 0) { l_fp ts; get_systime(&ts); (void)input_handler(&ts); } else if (nfound == -1 && errno != EINTR) msyslog(LOG_ERR, "select() error: %m"); # ifdef DEBUG else if (debug > 5) msyslog(LOG_DEBUG, "select(): nfound=%d, error: %m", nfound); # endif /* DEBUG */ # else /* HAVE_SIGNALED_IO */ wait_for_signal(); # endif /* HAVE_SIGNALED_IO */ if (alarm_flag) /* alarmed? */ { was_alarmed = 1; alarm_flag = 0; } } if (was_alarmed) { UNBLOCK_IO_AND_ALARM(); /* * Out here, signals are unblocked. Call timer routine * to process expiry. */ timer(); was_alarmed = 0; 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 = 1; alarm_flag = 0; } UNBLOCK_IO_AND_ALARM(); if (was_alarmed) { /* avoid timer starvation during lengthy I/O handling */ timer(); was_alarmed = 0; } /* * Call the data procedure to handle each received * packet. */ if (rbuf->receiver != NULL) /* This should always be true */ { #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, "receive buffer corruption - receiver found to be NULL - ABORTING"); 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, "Attemping 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 = 0; } } #endif /* HAVE_DNSREGISTRATION */ } UNBLOCK_IO_AND_ALARM(); return 1; } #ifdef SIGDIE2 /* * finish - exit gracefully */ static RETSIGTYPE finish( int sig ) { msyslog(LOG_NOTICE, "ntpd exiting on signal %d", sig); #ifdef HAVE_DNSREGISTRATION if (mdns != NULL) DNSServiceRefDeallocate(mdns); #endif switch (sig) { # ifdef SIGBUS case SIGBUS: printf("\nfinish(SIGBUS)\n"); exit(0); # endif case 0: /* Should never happen... */ return; default: exit(0); } }
int main(int argt, char* argvnum[],char* envp[]) { char command_buf[256]; char *argv[10]; int i = 0; for(i = 0 ; i < 5; i++) { argv[i] = (char*)malloc(20); } //printf("argt is %x\n",argt); volatile int run_shell = 1; while(run_shell == 1) { // Show prompt and read from the user show_prompt(); int argc = 0; //printf("argt is %x\n",argt); //Read the command from the user scanf("%s",command_buf); // Parse the input at the prompt and tokenize(space as token) it to get individual args. int index = 0,start_index = 0; //Strip leading spaces while(command_buf[index] != '\0') { // Parse command_buf and put arguments into argv if(command_buf[index] == ' ') { if((index - start_index) > 0 ) { //printf("\nallocating %d bytes",index-start_index); //argv[argc++] = (char*)malloc((index-start_index) + 1); argc++; strncpy(argv[argc-1],command_buf+start_index,index-start_index); start_index = index + 1; } } index++; } if(index > 0) { //argv[argc++] = (char*)malloc((index-start_index) + 1); argc++; strncpy(argv[argc-1],command_buf+start_index,index-start_index); } // Compare argv[0] to determine the file name.. // printf("argc is %d\n",argc); // int temp; // for(temp = 0; temp < argc; temp++) // printf("%s\n",argv[temp]); // printf("argv[0] is %s\n",argv[0]); // printf("\n PATH is %s\n",PATH); // printf("argv[0] is %s\n",argv[0]); if(strcmp_x(argv[0],"cd")) { // printf("\ndo cd\n"); cd(argv[1]); continue; } else if (strcmp_x(argv[0],"ulimit")) { //printf("\ndo ulimit\n"); ulimit(atoi_u(argv[1],10)); continue; } if(index > 0) { index = 0,start_index = 0; char tempbuf[64]; while(PATH[index] != '\0') { if(PATH[index] == ':') { if(index - start_index > 0) { strncpy(tempbuf,PATH+start_index,index-start_index); strcat_x(tempbuf,argv[0]); start_index = index + 1; int fd; fd = open(tempbuf); if(fd > 0) { //int flag = 0; //printf("File exists!!\n"); //if(strcmp_x(argv[0],"sh")) { // flag = 1; //} volatile uint16_t val = fork(); if(val == 0) execvpe(tempbuf,argc,argv); else { waitpid(val); } } else { printf("\nCommand not found\n"); break; } close(fd); if(fd > 0) break; } } index++; } if((start_index == 0) && ( index > 0)) { strncpy(tempbuf,PATH+start_index,index-start_index); strcat_x(tempbuf,argv[0]); //printf("start_index is %d\n",start_index); //printf("-------tempbuf is %s\n",tempbuf); int fd; fd = open(tempbuf); if(fd > 0) { //printf("------File exists!!\n"); //int flag = 0; //if(strcmp_x(argv[0],"sh")) { // flag = 1; // } volatile uint16_t val = fork(); if(val == 0) execvpe(tempbuf,argc,argv); else { waitpid(val); } } else printf("\nCommand not found\n"); close(fd); } } } // strcmp to check if the command is valid // if yes, then execute // printf("%s",command_buf); return 0; }