int sed_main(int argc, char *argv[]) { int c, fflag; char *temp_arg; // init all flags: aflag = eflag = sed_nflag = rflags = 0; infile = NULL; outfile = NULL; fl_nextp = &files; if (files != NULL) { while (files != NULL) { struct s_flist *next = files->next; free(files); files = next; } } cu_nextp = &script; if (script != NULL) { while (script != NULL) { struct s_compunit *next = script->next; free(script); script = next; } } rval = 0; /* Exit status */ (void) setlocale(LC_ALL, ""); fflag = 0; inplace = NULL; while ((c = getopt(argc, argv, "Eae:f:i:ln")) != -1) switch (c) { case 'E': rflags = REG_EXTENDED; break; case 'a': aflag = 1; break; case 'e': eflag = 1; if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL) fprintf(stderr, "sed: malloc: %s\n", strerror(errno)); // err(1, "malloc"); strcpy(temp_arg, optarg); strcat(temp_arg, "\n"); add_compunit(CU_STRING, temp_arg); break; case 'f': fflag = 1; add_compunit(CU_FILE, optarg); break; case 'i': inplace = optarg; break; case 'l': if(setlinebuf(stdout) != 0) fprintf(stderr, "sed: setlinebuf() failed\n"); // warnx("setlinebuf() failed"); break; case 'n': sed_nflag = 1; break; default: case '?': usage(); } argc -= optind; argv += optind; /* First usage case; script is the first arg */ if (!eflag && !fflag && *argv) { add_compunit(CU_STRING, *argv); argv++; } compile(); /* Continue with first and start second usage */ if (*argv) for (; *argv; argv++) add_file(*argv); else add_file(NULL); process(); cfclose(prog, NULL); // if (fclose(stdout)) // err(1, "stdout"); // exit(rval); if ((infile != NULL) && (infile != stdin)) fclose(infile); if ((outfile != NULL) && (outfile != stdout)) fclose(outfile); return 0; }
static #endif int real_main(int argc, char *argv[]) { int ret=1; int option=0; int daemon=1; int forking=1; int strip=0; int randomise=0; struct lock *lock=NULL; struct conf **confs=NULL; int forceoverwrite=0; enum action act=ACTION_LIST; const char *backup=NULL; const char *backup2=NULL; char *restoreprefix=NULL; char *stripfrompath=NULL; const char *regex=NULL; const char *browsefile=NULL; char *browsedir=NULL; const char *conffile=get_conf_path(); const char *orig_client=NULL; const char *logfile=NULL; // The orig_client is the original client that the normal client // would like to restore from. #ifndef HAVE_WIN32 int generate_ca_only=0; #endif int vss_restore=1; int test_confs=0; enum burp_mode mode; log_init(argv[0]); #ifndef HAVE_WIN32 if(!strcmp(prog, "bedup")) return run_bedup(argc, argv); if(!strcmp(prog, "bsigs")) return run_bsigs(argc, argv); #endif while((option=getopt(argc, argv, "a:b:c:C:d:fFghil:nq:Qr:s:tvxjz:?"))!=-1) { switch(option) { case 'a': if(parse_action(&act, optarg)) goto end; break; case 'b': // The diff command may have two backups // specified. if(!backup2 && backup) backup2=optarg; if(!backup) backup=optarg; break; case 'c': conffile=optarg; break; case 'C': orig_client=optarg; break; case 'd': restoreprefix=optarg; // for restores browsedir=optarg; // for lists break; case 'f': forceoverwrite=1; break; case 'F': daemon=0; break; case 'g': #ifndef HAVE_WIN32 generate_ca_only=1; #endif break; case 'i': cmd_print_all(); ret=0; goto end; case 'l': logfile=optarg; break; case 'n': forking=0; break; case 'q': randomise=atoi(optarg); break; case 'Q': log_force_quiet(); break; case 'r': regex=optarg; break; case 's': strip=atoi(optarg); break; case 'v': printf("%s-%s\n", progname(), VERSION); ret=0; goto end; case 'x': vss_restore=0; break; case 't': test_confs=1; break; case 'z': browsefile=optarg; break; case 'h': case '?': default: usage(); goto end; } } if(optind<argc) { usage(); goto end; } if(act==ACTION_MONITOR) { // Try to output everything in JSON. log_set_json(1); #ifndef HAVE_WIN32 // Need to do this so that processes reading stdout get the // result of the printfs of logp straight away. setlinebuf(stdout); #endif } if(!(confs=confs_alloc())) goto end; if(reload(confs, conffile, 1)) goto end; // Dry run to test config file syntax. if(test_confs) { ret=run_test_confs(confs, orig_client); goto end; } if(!backup) switch(act) { case ACTION_DELETE: logp("No backup specified for deletion.\n"); goto end; case ACTION_RESTORE: case ACTION_VERIFY: case ACTION_DIFF: case ACTION_DIFF_LONG: logp("No backup specified. Using the most recent.\n"); backup="0"; default: break; } if(!backup2) switch(act) { case ACTION_DIFF: case ACTION_DIFF_LONG: logp("No second backup specified. Using file system scan.\n"); backup2="n"; // For 'next'. default: break; } // The logfile option is only used for the status client stuff. if(logfile && (act!=ACTION_STATUS && act!=ACTION_STATUS_SNAPSHOT)) logp("-l <logfile> option obsoleted\n"); if(orig_client && *orig_client && set_string(confs[OPT_ORIG_CLIENT], orig_client)) goto end; // The random delay needs to happen before the lock is got, otherwise // you would never be able to use burp by hand. if(randomise) set_int(confs[OPT_RANDOMISE], randomise); mode=get_e_burp_mode(confs[OPT_BURP_MODE]); if(mode==BURP_MODE_CLIENT && (act==ACTION_BACKUP_TIMED || act==ACTION_TIMER_CHECK)) random_delay(confs); if(mode==BURP_MODE_SERVER && act==ACTION_CHAMP_CHOOSER) { // These server modes need to run without getting the lock. } else if(mode==BURP_MODE_CLIENT && (act==ACTION_LIST || act==ACTION_LIST_LONG || act==ACTION_DIFF || act==ACTION_DIFF_LONG || act==ACTION_STATUS || act==ACTION_STATUS_SNAPSHOT || act==ACTION_MONITOR)) { // These client modes need to run without getting the lock. } else { const char *lockfile=confs_get_lockfile(confs); if(!(lock=lock_alloc_and_init(lockfile))) goto end; lock_get(lock); switch(lock->status) { case GET_LOCK_GOT: break; case GET_LOCK_NOT_GOT: logp("Could not get lockfile.\n"); logp("Another process is probably running,\n"); goto end; case GET_LOCK_ERROR: default: logp("Could not get lockfile.\n"); logp("Maybe you do not have permissions to write to %s.\n", lockfile); goto end; } } set_int(confs[OPT_OVERWRITE], forceoverwrite); set_int(confs[OPT_STRIP], strip); set_int(confs[OPT_FORK], forking); set_int(confs[OPT_DAEMON], daemon); strip_trailing_slashes(&restoreprefix); strip_trailing_slashes(&browsedir); if(replace_conf_str(confs[OPT_BACKUP], backup) || replace_conf_str(confs[OPT_BACKUP2], backup2) || replace_conf_str(confs[OPT_RESTOREPREFIX], restoreprefix) || replace_conf_str(confs[OPT_STRIP_FROM_PATH], stripfrompath) || replace_conf_str(confs[OPT_REGEX], regex) || replace_conf_str(confs[OPT_BROWSEFILE], browsefile) || replace_conf_str(confs[OPT_BROWSEDIR], browsedir) || replace_conf_str(confs[OPT_MONITOR_LOGFILE], logfile)) goto end; base64_init(); hexmap_init(); if(mode==BURP_MODE_SERVER) { #ifdef HAVE_WIN32 logp("Sorry, server mode is not implemented for Windows.\n"); #else ret=server_modes(act, conffile, lock, generate_ca_only, confs); #endif } else { ret=client(confs, act, vss_restore); } end: lock_release(lock); lock_free(&lock); confs_free(&confs); return ret; }
int main (int argc, char *argv[]) { char *dev = NULL; char errbuf [ERRBUF_SIZE]; /* Error string */ struct bpf_program fp; /* The compiled filter */ char filter_exp[] = "ether proto 0x88d9"; //"port 80"; /* The filter expression */ bpf_u_int32 mask; /* Our netmask */ bpf_u_int32 net; /* Our IP */ struct pcap_pkthdr header; const u_char *packet; int c,i; libnet_t *l; libnet_ptag_t eth_ptag = 0; u_char buf[0x100]; struct itimerspec tspec; memset(&tspec, 0, sizeof(tspec)); tspec.it_value.tv_sec = 3; while ((c = getopt(argc, argv, "t:i:hvu")) != EOF) { switch (c) { case 'i': // interface dev = optarg; break; case 't': // timeout i = atoi(optarg); if( i>0 ) { #ifndef __linux__ if( i > PCAP_PERIOD ) i-=PCAP_PERIOD-10; // try to be more precise #endif tspec.it_value.tv_sec = i/1000; tspec.it_value.tv_nsec = (i%1000)*1000000; } break; case 'v': // verbosity verbose++; break; case 'u': // unicode support unicode = 1; break; case 'h': // show usage usage(argv[0]); exit(EXIT_SUCCESS); default: exit(EXIT_FAILURE); } } argc -= optind; argv += optind; if( argc > 1 ) { usage(argv[0]); exit(EXIT_FAILURE); } if( argc == 1 ) { if( strlen(argv[0]) != 17 ) { fprintf(stderr, "Invalid MAC-address: '%s'\n", argv[0]); exit(EXIT_FAILURE); } mac_to_find = argv[0]; } setlinebuf(stdout); if(!dev) dev = pcap_lookupdev(errbuf); if (dev == NULL) { fprintf(stderr, "Couldn't find default device: %s\n", errbuf); return (2); } printf("interface %s\n",dev); l = libnet_init(LIBNET_LINK, dev, errbuf); if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } /* Find the properties for the device */ if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) { fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf); net = 0; mask = 0; } struct ether_addr *ha = NULL; if ((ha = (struct ether_addr *) libnet_get_hwaddr(l)) == NULL) { fprintf(stderr, "%s", libnet_geterror(l)); exit(EXIT_FAILURE); } // LLTP magic packet char* payload = "\x01\x00\x00\x00\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00"; char* hwdst = "\xff\xff\xff\xff\xff\xff"; memcpy(buf,payload,18); memcpy(buf+10, ha, 6); gettimeofday(&start_time, NULL); memcpy(buf+16, &start_time.tv_sec, 2); // emulate sequence number eth_ptag = libnet_build_ethernet( hwdst, /* ethernet destination */ ha->ether_addr_octet, /* ethernet source */ 0x88d9, /* protocol type */ buf, /* payload */ 18, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (eth_ptag == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); libnet_destroy(l); exit(EXIT_FAILURE); } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); libnet_destroy(l); exit(EXIT_FAILURE); } /* Open the session in promiscuous mode */ pcap_handle = pcap_open_live(dev, BUFSIZ, 1, PCAP_PERIOD, errbuf); if (pcap_handle == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf); libnet_destroy(l); return (2); } /* Compile and apply the filter */ if (pcap_compile(pcap_handle, &fp, filter_exp, 0, net) == -1) { fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(pcap_handle)); libnet_destroy(l); return (2); } if (pcap_setfilter(pcap_handle, &fp) == -1) { fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(pcap_handle)); libnet_destroy(l); return (2); } signal(SIGALRM, on_alarm); gettimeofday(&start_time, NULL); timer_create(CLOCK_MONOTONIC, NULL, &timer_id); timer_settime(timer_id, 0, &tspec, NULL); // don't know why, but pcap_dispatch does not return control to main after // timeout expires. so, we use nonblocking pcap on linux. #ifdef __linux__ pcap_setnonblock(pcap_handle, 1, errbuf); #endif while( !do_stop ) { pcap_dispatch(pcap_handle, -1, got_packet, NULL); #ifdef __linux__ usleep(1000); #endif } pcap_close(pcap_handle); i = tv_diff2msec(NULL); printf("found %d hosts in %d.%d seconds", nhosts, i/1000, i%1000); if( mac_to_find && !mac_found ) { printf(", but '%s' is not found.\n", mac_to_find); } else { puts(""); } return (0); }
static int testserver_exec(struct ast_channel *chan, const char *data) { int res = 0; char testid[80]=""; char fn[80]; FILE *f; if (ast_channel_state(chan) != AST_STATE_UP) res = ast_answer(chan); /* Read version */ ast_debug(1, "Read client version\n"); if (!res) res = ast_app_getdata(chan, NULL, testid, sizeof(testid) - 1, 0); if (res > 0) res = 0; ast_debug(1, "client version: %s\n", testid); ast_debug(1, "Transmit server version\n"); res = ast_safe_sleep(chan, 1000); if (!res) res = ast_dtmf_stream(chan, NULL, "8378*1#", 0, 0); if (res > 0) res = 0; if (!res) res = ast_app_getdata(chan, NULL, testid, sizeof(testid) - 1, 0); ast_debug(1, "read test identifier: %s\n", testid); /* Check for sneakyness */ if (strchr(testid, '/')) res = -1; if ((res >=0) && (!ast_strlen_zero(testid))) { /* Got a Test ID! Whoo hoo! */ /* Make the directory to hold the test results in case it's not there */ snprintf(fn, sizeof(fn), "%s/testresults", ast_config_AST_LOG_DIR); ast_mkdir(fn, 0777); snprintf(fn, sizeof(fn), "%s/testresults/%s-server.txt", ast_config_AST_LOG_DIR, testid); if ((f = fopen(fn, "w+"))) { setlinebuf(f); fprintf(f, "SERVERCHAN: %s\n", ast_channel_name(chan)); fprintf(f, "SERVERTEST ID: %s\n", testid); fprintf(f, "ANSWER: PASS\n"); ast_debug(1, "Processing Test ID '%s'\n", testid); res = ast_safe_sleep(chan, 1000); if (!res) { /* Step 1: Send "1" */ ast_debug(1, "TestServer: 1. Send DTMF 1\n"); res = ast_dtmf_stream(chan, NULL, "1", 0,0 ); fprintf(f, "SEND DTMF 1: %s\n", (res < 0) ? "FAIL" : "PASS"); if (res > 0) res = 0; } if (!res) { /* Step 2: Wait for "2" */ ast_debug(1, "TestServer: 2. Wait DTMF 2\n"); res = ast_waitfordigit(chan, 3000); fprintf(f, "WAIT DTMF 2: %s\n", (res != '2') ? "FAIL" : "PASS"); if (res == '2') res = 0; else res = -1; } if (!res) { /* Step 3: Measure noise */ ast_debug(1, "TestServer: 3. Measure noise\n"); res = measurenoise(chan, 6000, "TestServer"); fprintf(f, "MEASURENOISE: %s (%d)\n", (res < 0) ? "FAIL" : "PASS", res); if (res > 0) res = 0; } if (!res) { /* Step 4: Send "4" */ ast_debug(1, "TestServer: 4. Send DTMF 4\n"); res = ast_dtmf_stream(chan, NULL, "4", 0, 0); fprintf(f, "SEND DTMF 4: %s\n", (res < 0) ? "FAIL" : "PASS"); if (res > 0) res = 0; } if (!res) { /* Step 5: Wait one second */ ast_debug(1, "TestServer: 5. Wait one second\n"); res = ast_safe_sleep(chan, 1000); fprintf(f, "WAIT 1 SEC: %s\n", (res < 0) ? "FAIL" : "PASS"); if (res > 0) res = 0; } if (!res) { /* Step 6: Measure noise */ ast_debug(1, "TestServer: 6. Measure tone\n"); res = measurenoise(chan, 4000, "TestServer"); fprintf(f, "MEASURETONE: %s (%d)\n", (res < 0) ? "FAIL" : "PASS", res); if (res > 0) res = 0; } if (!res) { /* Step 7: Send "5" */ ast_debug(1, "TestServer: 7. Send DTMF 5\n"); res = ast_dtmf_stream(chan, NULL, "5", 0, 0); fprintf(f, "SEND DTMF 5: %s\n", (res < 0) ? "FAIL" : "PASS"); if (res > 0) res = 0; } if (!res) { /* Step 8: Transmit tone noise */ ast_debug(1, "TestServer: 8. Transmit tone\n"); res = sendnoise(chan, 6000); fprintf(f, "SENDTONE: %s\n", (res < 0) ? "FAIL" : "PASS"); } if (!res || (res == '7')) { /* Step 9: Wait for "7" */ ast_debug(1, "TestServer: 9. Wait DTMF 7\n"); if (!res) res = ast_waitfordigit(chan, 3000); fprintf(f, "WAIT DTMF 7: %s\n", (res != '7') ? "FAIL" : "PASS"); if (res == '7') res = 0; else res = -1; } if (!res) { res = ast_safe_sleep(chan, 1000); } if (!res) { /* Step 10: Send "8" */ ast_debug(1, "TestServer: 10. Send DTMF 8\n"); res = ast_dtmf_stream(chan, NULL, "8", 0, 0); fprintf(f, "SEND DTMF 8: %s\n", (res < 0) ? "FAIL" : "PASS"); if (res > 0) res = 0; } if (!res) { /* Step 11: Wait for hangup to arrive! */ ast_debug(1, "TestServer: 11. Waiting for hangup\n"); res = ast_safe_sleep(chan, 10000); fprintf(f, "WAIT HANGUP: %s\n", (res < 0) ? "PASS" : "FAIL"); } ast_log(LOG_NOTICE, "-- TEST COMPLETE--\n"); fprintf(f, "-- END TEST--\n"); fclose(f); res = -1; } else res = -1; } else { ast_log(LOG_NOTICE, "Did not read a test ID on '%s'\n", ast_channel_name(chan)); res = -1; } return res; }
int main(int argc, char *argv[]) { int foreground = 0, do_syslog = 1; fd_set fds; int nfds, fd, n = -1, i, ch; struct sigaction sa; struct option long_options[] = { { "config", 1, 0, 'f' }, { "no-fallback", 0, 0, 500 }, { "disable-vifs", 0, 0, 'N' }, { "foreground", 0, 0, 'n' }, { "help", 0, 0, 'h' }, { "ident", 1, 0, 'I' }, { "loglevel", 1, 0, 'l' }, { "pidfile", 1, 0, 'P' }, { "syslog", 0, 0, 's' }, { "table-id", 1, 0, 't' }, { "version", 0, 0, 'v' }, { NULL, 0, 0, 0 } }; snprintf(versionstring, sizeof (versionstring), "pimd version %s", PACKAGE_VERSION); prognm = ident = progname(argv[0]); while ((ch = getopt_long(argc, argv, "d:f:hI:l:nNP:rst:v", long_options, NULL)) != EOF) { const char *errstr; switch (ch) { case 'd': { char *p,*q; size_t i, len; struct debugname *d; debug = 0; p = optarg; q = NULL; while (p) { q = strchr(p, ','); if (q) *q++ = '\0'; len = strlen(p); for (i = 0, d = debugnames; i < ARRAY_LEN(debugnames); i++, d++) { if (len >= d->nchars && strncmp(d->name, p, len) == 0) break; } if (i == ARRAY_LEN(debugnames)) return usage(1); debug |= d->level; p = q; } } break; case 'f': config_file = optarg; break; case 500: no_fallback = 1; break; case 'h': return usage(0); case 'I': /* --ident=NAME */ ident = optarg; break; case 'l': loglevel = loglvl(optarg); if (-1 == loglevel) return usage(1); break; case 'n': do_syslog--; foreground = 1; break; case 'N': do_vifs = 0; break; case 'P': /* --pidfile=NAME */ pid_file = strdup(optarg); break; case 'r': retry_forever++; break; case 's': do_syslog++; break; case 't': mrt_table_id = strtonum(optarg, 0, 999999999, &errstr); if (errstr) { fprintf(stderr, "Table ID %s!\n", errstr); return usage(1); } break; case 'v': printf("%s\n", versionstring); return 0; default: return usage(1); } } argc -= optind; if (argc > 0) return usage(1); if (geteuid() != 0) errx(1, "Need root privileges to start."); compose_paths(); setlinebuf(stderr); if (debug != 0) { struct debugname *d; char c; int tmpd = debug; fprintf(stderr, "debug level 0x%lx ", debug); c = '('; for (d = debugnames; d < debugnames + ARRAY_LEN(debugnames); d++) { if ((tmpd & d->level) == d->level) { tmpd &= ~d->level; fprintf(stderr, "%c%s", c, d->name); c = ','; } } fprintf(stderr, ")\n"); } if (!debug && !foreground) { /* Detach from the terminal */ haveterminal = 0; if (fork()) exit(0); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); fd = open("/dev/null", O_RDWR, 0); if (fd >= 0) { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); close(fd); } #ifdef SYSV setpgrp(); #else #ifdef TIOCNOTTY fd = open("/dev/tty", 2); if (fd >= 0) { (void)ioctl(fd, TIOCNOTTY, (char *)0); close(fd); } #else if (setsid() < 0) perror("setsid"); #endif /* TIOCNOTTY */ #endif /* SYSV */ } /* End of child process code */ /* * Create directory for runtime files */ if (-1 == mkdir(_PATH_PIMD_RUNDIR, 0755) && errno != EEXIST) err(1, "Failed creating %s directory for runtime files", _PATH_PIMD_RUNDIR); /* * Setup logging */ log_init(haveterminal && do_syslog > 0); logit(LOG_NOTICE, 0, "%s starting ...", versionstring); do_randomize(); callout_init(); init_igmp(); init_pim(); init_routesock(); /* Both for Linux netlink and BSD routing socket */ init_pim_mrt(); init_timers(); ipc_init(); /* Start up the log rate-limiter */ resetlogging(NULL); /* TODO: check the kernel DVMRP/MROUTED/PIM support version */ init_vifs(); init_rp_and_bsr(); /* Must be after init_vifs() */ add_static_rp(); /* Must be after init_vifs() */ #ifdef RSRR rsrr_init(); #endif /* RSRR */ sa.sa_handler = handle_signals; sa.sa_flags = 0; /* Interrupt system calls */ sigemptyset(&sa.sa_mask); sigaction(SIGALRM, &sa, NULL); sigaction(SIGHUP, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); sigaction(SIGUSR1, &sa, NULL); sigaction(SIGUSR2, &sa, NULL); IF_DEBUG(DEBUG_IF) dump_vifs(stderr); IF_DEBUG(DEBUG_PIM_MRT) dump_pim_mrt(stderr); /* schedule first timer interrupt */ timer_setTimer(TIMER_INTERVAL, timer, NULL); if (pidfile(pid_file)) warn("Cannot create pidfile"); /* * Main receive loop. */ while (1) { if (check_signals()) break; FD_ZERO(&fds); for (i = 0, nfds = 0; i < nhandlers; i++) { FD_SET(ihandlers[i].fd, &fds); if (ihandlers[i].fd >= nfds) nfds = ihandlers[i].fd + 1; } n = select(nfds, &fds, NULL, NULL, timeout(n)); if (n < 0) { if (errno != EINTR) /* SIGALRM is expected */ logit(LOG_WARNING, errno, "select failed"); continue; } for (i = 0; n > 0 && i < nhandlers; i++) { if (FD_ISSET(ihandlers[i].fd, &fds)) ihandlers[i].func(ihandlers[i].fd); } } logit(LOG_NOTICE, 0, "%s exiting.", versionstring); cleanup(); exit(0); }
/* Adapted from auditd auditd-event.c */ static gboolean open_log_file (const char *filename, int *fdp, FILE **filep) { int flags; int fd; FILE *file; gboolean ret; ret = FALSE; /* * Likely errors on rotate: ENFILE, ENOMEM, ENOSPC */ flags = O_WRONLY | O_APPEND; #ifdef O_NOFOLLOW flags |= O_NOFOLLOW; #endif retry: fd = g_open (filename, flags, 0600); if (fd < 0) { if (errno == ENOENT) { /* FIXME: should we just skip if file doesn't exist? */ fd = g_open (filename, O_CREAT | O_EXCL | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP); if (fd < 0) { g_warning ("Couldn't create log file %s (%s)", filename, g_strerror (errno)); goto out; } close (fd); fd = g_open (filename, flags, 0600); } else if (errno == ENFILE) { /* All system descriptors used, try again... */ goto retry; } if (fd < 0) { g_warning ("Couldn't open log file %s (%s)", filename, g_strerror (errno)); goto out; } } if (fcntl (fd, F_SETFD, FD_CLOEXEC) == -1) { close (fd); g_warning ("Error setting log file CLOEXEC flag (%s)", g_strerror (errno)); goto out; } if (fchown (fd, 0, 0) == -1) { g_warning ("Error changing owner of log file (%s)", g_strerror (errno)); } file = fdopen (fd, "a"); if (file == NULL) { g_warning ("Error setting up log descriptor (%s)", g_strerror (errno)); close (fd); goto out; } /* Set it to line buffering */ setlinebuf (file); ret = TRUE; if (fdp != NULL) { *fdp = fd; } if (filep != NULL) { *filep = file; } out: return ret; }
/** process command line options */ struct ldb_cmdline *ldb_cmdline_process(struct ldb_context *ldb, int argc, const char **argv, void (*usage)(struct ldb_context *)) { struct ldb_cmdline *ret=NULL; poptContext pc; int num_options = 0; int opt; unsigned int flags = 0; int rc; struct poptOption **popt_options; /* make the ldb utilities line buffered */ setlinebuf(stdout); ret = talloc_zero(ldb, struct ldb_cmdline); if (ret == NULL) { fprintf(stderr, "Out of memory!\n"); goto failed; } options = *ret; /* pull in URL */ options.url = getenv("LDB_URL"); /* and editor (used by ldbedit) */ options.editor = getenv("VISUAL"); if (!options.editor) { options.editor = getenv("EDITOR"); } if (!options.editor) { options.editor = "vi"; } options.scope = LDB_SCOPE_DEFAULT; popt_options = ldb_module_popt_options(ldb); (*popt_options) = builtin_popt_options; rc = ldb_modules_hook(ldb, LDB_MODULE_HOOK_CMDLINE_OPTIONS); if (rc != LDB_SUCCESS) { fprintf(stderr, "ldb: failed to run command line hooks : %s\n", ldb_strerror(rc)); goto failed; } pc = poptGetContext(argv[0], argc, argv, *popt_options, POPT_CONTEXT_KEEP_FIRST); while((opt = poptGetNextOpt(pc)) != -1) { switch (opt) { case 's': { const char *arg = poptGetOptArg(pc); if (strcmp(arg, "base") == 0) { options.scope = LDB_SCOPE_BASE; } else if (strcmp(arg, "sub") == 0) { options.scope = LDB_SCOPE_SUBTREE; } else if (strcmp(arg, "one") == 0) { options.scope = LDB_SCOPE_ONELEVEL; } else { fprintf(stderr, "Invalid scope '%s'\n", arg); goto failed; } break; } case 'v': options.verbose++; break; case 'o': options.options = talloc_realloc(ret, options.options, const char *, num_options+3); if (options.options == NULL) { fprintf(stderr, "Out of memory!\n"); goto failed; } options.options[num_options] = poptGetOptArg(pc); options.options[num_options+1] = NULL; num_options++; break; case 'c': { const char *cs = poptGetOptArg(pc); const char *p; for (p = cs; p != NULL; ) { const char *t, *c; t = strchr(p, ','); if (t == NULL) { c = talloc_strdup(options.controls, p); p = NULL; } else { c = talloc_strndup(options.controls, p, t-p); p = t + 1; } if (c == NULL || !add_control(ret, c)) { fprintf(stderr, __location__ ": out of memory\n"); goto failed; } } break; } case 'P': if (!add_control(ret, "paged_results:1:1024")) { fprintf(stderr, __location__ ": out of memory\n"); goto failed; } break; case 'D': if (!add_control(ret, "show_deleted:1")) { fprintf(stderr, __location__ ": out of memory\n"); goto failed; } break; case 'R': if (!add_control(ret, "show_recycled:0")) { fprintf(stderr, __location__ ": out of memory\n"); goto failed; } break; case 'd': if (!add_control(ret, "show_deactivated_link:0")) { fprintf(stderr, __location__ ": out of memory\n"); goto failed; } break; case 'r': if (!add_control(ret, "reveal_internals:0")) { fprintf(stderr, __location__ ": out of memory\n"); goto failed; } break; case CMDLINE_RELAX: if (!add_control(ret, "relax:0")) { fprintf(stderr, __location__ ": out of memory\n"); goto failed; } break; case 'N': if (!add_control(ret, "search_options:1:2")) { fprintf(stderr, __location__ ": out of memory\n"); goto failed; } break; case 'E': if (!add_control(ret, "extended_dn:1:1")) { fprintf(stderr, __location__ ": out of memory\n"); goto failed; } break; default: fprintf(stderr, "Invalid option %s: %s\n", poptBadOption(pc, 0), poptStrerror(opt)); if (usage) usage(ldb); goto failed; } } /* setup the remaining options for the main program to use */ options.argv = poptGetArgs(pc); if (options.argv) { options.argv++; while (options.argv[options.argc]) options.argc++; } *ret = options; /* all utils need some option */ if (ret->url == NULL) { fprintf(stderr, "You must supply a url with -H or with $LDB_URL\n"); if (usage) usage(ldb); goto failed; } if (strcmp(ret->url, "NONE") == 0) { return ret; } if (options.nosync) { flags |= LDB_FLG_NOSYNC; } if (options.show_binary) { flags |= LDB_FLG_SHOW_BINARY; } if (options.tracing) { flags |= LDB_FLG_ENABLE_TRACING; } if (options.modules_path != NULL) { ldb_set_modules_dir(ldb, options.modules_path); } rc = ldb_modules_hook(ldb, LDB_MODULE_HOOK_CMDLINE_PRECONNECT); if (rc != LDB_SUCCESS) { fprintf(stderr, "ldb: failed to run preconnect hooks : %s\n", ldb_strerror(rc)); goto failed; } /* now connect to the ldb */ if (ldb_connect(ldb, ret->url, flags, ret->options) != LDB_SUCCESS) { fprintf(stderr, "Failed to connect to %s - %s\n", ret->url, ldb_errstring(ldb)); goto failed; } rc = ldb_modules_hook(ldb, LDB_MODULE_HOOK_CMDLINE_POSTCONNECT); if (rc != LDB_SUCCESS) { fprintf(stderr, "ldb: failed to run post connect hooks : %s\n", ldb_strerror(rc)); goto failed; } return ret; failed: talloc_free(ret); exit(LDB_ERR_OPERATIONS_ERROR); return NULL; }
/* * ut_start -- initialize unit test framework, indicate test started */ void ut_start(const char *file, int line, const char *func, int argc, char * const argv[], const char *fmt, ...) { va_list ap; int saveerrno = errno; char logname[MAXLOGNAME]; char *logsuffix; va_start(ap, fmt); if (getenv("UNITTEST_NO_SIGHANDLERS") == NULL) ut_register_sighandlers(); if (getenv("UNITTEST_QUIET") != NULL) Quiet++; Testname = getenv("UNITTEST_NAME"); if ((logsuffix = getenv("UNITTEST_NUM")) == NULL) logsuffix = ""; snprintf(logname, MAXLOGNAME, "out%s.log", logsuffix); if ((Outfp = fopen(logname, "w")) == NULL) { perror(logname); exit(1); } snprintf(logname, MAXLOGNAME, "err%s.log", logsuffix); if ((Errfp = fopen(logname, "w")) == NULL) { perror(logname); exit(1); } snprintf(logname, MAXLOGNAME, "trace%s.log", logsuffix); if ((Tracefp = fopen(logname, "w")) == NULL) { perror(logname); exit(1); } setlinebuf(Outfp); setlinebuf(Errfp); setlinebuf(Tracefp); setlinebuf(stdout); prefix(file, line, func, 0); vout(OF_LOUD|OF_NAME, "START", fmt, ap); out(OF_NONL, 0, " args:"); for (int i = 0; i < argc; i++) out(OF_NONL, " %s", argv[i]); out(0, NULL); va_end(ap); /* generate a uuid so the leaked fd gets recorded */ uuid_t u; uuid_generate(u); record_open_files(); long long sc = sysconf(_SC_PAGESIZE); if (sc < 0) abort(); Ut_pagesize = (unsigned long)sc; errno = saveerrno; }
/* * The main guy. */ int main(int argc, char *argv[]) { int rcode; int argval; int spawn_flag = TRUE; int dont_fork = FALSE; int flag = 0; #ifdef HAVE_SIGACTION struct sigaction act; #endif #ifdef OSFC2 set_auth_parameters(argc,argv); #endif if ((progname = strrchr(argv[0], FR_DIR_SEP)) == NULL) progname = argv[0]; else progname++; #ifdef WIN32 { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 0), &wsaData)) { fprintf(stderr, "%s: Unable to initialize socket library.\n", progname); return 1; } } #endif debug_flag = 0; spawn_flag = TRUE; radius_dir = strdup(RADIUS_DIR); /* * Ensure that the configuration is initialized. */ memset(&mainconfig, 0, sizeof(mainconfig)); mainconfig.myip.af = AF_UNSPEC; mainconfig.port = -1; mainconfig.name = "radiusd"; #ifdef HAVE_SIGACTION memset(&act, 0, sizeof(act)); act.sa_flags = 0 ; sigemptyset( &act.sa_mask ) ; #endif /* * Don't put output anywhere until we get told a little * more. */ mainconfig.radlog_dest = RADLOG_NULL; mainconfig.radlog_fd = -1; mainconfig.log_file = NULL; /* Process the options. */ while ((argval = getopt(argc, argv, "Cd:fhi:l:mMn:p:stvxX")) != EOF) { switch(argval) { case 'C': check_config = TRUE; spawn_flag = FALSE; dont_fork = TRUE; break; case 'd': if (radius_dir) free(radius_dir); radius_dir = strdup(optarg); break; case 'f': dont_fork = TRUE; break; case 'h': usage(0); break; case 'l': if (strcmp(optarg, "stdout") == 0) { goto do_stdout; } mainconfig.log_file = strdup(optarg); mainconfig.radlog_dest = RADLOG_FILES; mainconfig.radlog_fd = open(mainconfig.log_file, O_WRONLY | O_APPEND | O_CREAT, 0640); if (mainconfig.radlog_fd < 0) { fprintf(stderr, "radiusd: Failed to open log file %s: %s\n", mainconfig.log_file, strerror(errno)); exit(1); } fr_log_fp = fdopen(mainconfig.radlog_fd, "a"); break; case 'i': if (ip_hton(optarg, AF_UNSPEC, &mainconfig.myip) < 0) { fprintf(stderr, "radiusd: Invalid IP Address or hostname \"%s\"\n", optarg); exit(1); } flag |= 1; break; case 'n': mainconfig.name = optarg; break; case 'm': mainconfig.debug_memory = 1; break; case 'M': memory_report = 1; mainconfig.debug_memory = 1; break; case 'p': mainconfig.port = atoi(optarg); if ((mainconfig.port <= 0) || (mainconfig.port >= 65536)) { fprintf(stderr, "radiusd: Invalid port number %s\n", optarg); exit(1); } flag |= 2; break; case 's': /* Single process mode */ spawn_flag = FALSE; dont_fork = TRUE; break; case 't': /* no child threads */ spawn_flag = FALSE; break; case 'v': /* Don't print timestamps */ debug_flag += 2; fr_log_fp = stdout; mainconfig.radlog_dest = RADLOG_STDOUT; mainconfig.radlog_fd = STDOUT_FILENO; version(); exit(0); case 'X': spawn_flag = FALSE; dont_fork = TRUE; debug_flag += 2; mainconfig.log_auth = TRUE; mainconfig.log_auth_badpass = TRUE; mainconfig.log_auth_goodpass = TRUE; do_stdout: fr_log_fp = stdout; mainconfig.radlog_dest = RADLOG_STDOUT; mainconfig.radlog_fd = STDOUT_FILENO; break; case 'x': debug_flag++; break; default: usage(1); break; } } if (memory_report) { talloc_enable_null_tracking(); talloc_set_log_fn(log_talloc); } /* * Mismatch between build time OpenSSL and linked SSL, * better to die here than segfault later. */ #ifdef HAVE_OPENSSL_CRYPTO_H if (ssl_check_version() < 0) { exit(1); } #endif if (flag && (flag != 0x03)) { fprintf(stderr, "radiusd: The options -i and -p cannot be used individually.\n"); exit(1); } if (debug_flag) version(); /* Read the configuration files, BEFORE doing anything else. */ if (read_mainconfig(0) < 0) { exit(1); } #ifndef __MINGW32__ /* * Disconnect from session */ if (dont_fork == FALSE) { pid_t pid = fork(); if (pid < 0) { radlog(L_ERR, "Couldn't fork: %s", strerror(errno)); exit(1); } /* * The parent exits, so the child can run in the background. */ if (pid > 0) { exit(0); } #ifdef HAVE_SETSID setsid(); #endif } #endif /* * Ensure that we're using the CORRECT pid after forking, * NOT the one we started with. */ radius_pid = getpid(); /* * If we're running as a daemon, close the default file * descriptors, AFTER forking. */ if (!debug_flag) { int devnull; devnull = open("/dev/null", O_RDWR); if (devnull < 0) { radlog(L_ERR, "Failed opening /dev/null: %s\n", strerror(errno)); exit(1); } dup2(devnull, STDIN_FILENO); if (mainconfig.radlog_dest == RADLOG_STDOUT) { setlinebuf(stdout); mainconfig.radlog_fd = STDOUT_FILENO; } else { dup2(devnull, STDOUT_FILENO); } if (mainconfig.radlog_dest == RADLOG_STDERR) { setlinebuf(stderr); mainconfig.radlog_fd = STDERR_FILENO; } else { dup2(devnull, STDERR_FILENO); } close(devnull); } else { setlinebuf(stdout); /* unbuffered output */ } /* * Now we have logging check that the OpenSSL */ /* * Initialize the event pool, including threads. */ radius_event_init(mainconfig.config, spawn_flag); /* * Now that we've set everything up, we can install the signal * handlers. Before this, if we get any signal, we don't know * what to do, so we might as well do the default, and die. */ #ifdef SIGPIPE signal(SIGPIPE, SIG_IGN); #endif #ifdef HAVE_SIGACTION act.sa_handler = sig_hup; sigaction(SIGHUP, &act, NULL); act.sa_handler = sig_fatal; sigaction(SIGTERM, &act, NULL); #else #ifdef SIGHUP signal(SIGHUP, sig_hup); #endif signal(SIGTERM, sig_fatal); #endif /* * If we're debugging, then a CTRL-C will cause the * server to die immediately. Use SIGTERM to shut down * the server cleanly in that case. */ if ((mainconfig.debug_memory == 1) || (debug_flag == 0)) { #ifdef HAVE_SIGACTION act.sa_handler = sig_fatal; sigaction(SIGINT, &act, NULL); sigaction(SIGQUIT, &act, NULL); #else signal(SIGINT, sig_fatal); #ifdef SIGQUIT signal(SIGQUIT, sig_fatal); #endif #endif } /* * Everything seems to have loaded OK, exit gracefully. */ if (check_config) { DEBUG("Configuration appears to be OK."); exit(0); } #ifdef WITH_STATS radius_stats_init(0); #endif /* * Only write the PID file if we're running as a daemon. * * And write it AFTER we've forked, so that we write the * correct PID. */ if (dont_fork == FALSE) { FILE *fp; fp = fopen(mainconfig.pid_file, "w"); if (fp != NULL) { /* * FIXME: What about following symlinks, * and having it over-write a normal file? */ fprintf(fp, "%d\n", (int) radius_pid); fclose(fp); } else { radlog(L_ERR, "Failed creating PID file %s: %s\n", mainconfig.pid_file, strerror(errno)); exit(1); } } exec_trigger(NULL, NULL, "server.start", FALSE); /* * Process requests until HUP or exit. */ while ((rcode = radius_event_process()) == 0x80) { #ifdef WITH_STATS radius_stats_init(1); #endif hup_mainconfig(); } if (rcode < 0) { radlog(L_ERR, "Exiting due to internal error: %s", fr_strerror()); rcode = 2; } else { radlog(L_INFO, "Exiting normally."); } exec_trigger(NULL, NULL, "server.stop", FALSE); /* * Ignore the TERM signal: we're * about to die. */ signal(SIGTERM, SIG_IGN); /* * Send a TERM signal to all * associated processes * (including us, which gets * ignored.) */ #ifndef __MINGW32__ if (spawn_flag) kill(-radius_pid, SIGTERM); #endif /* * We're exiting, so we can delete the PID * file. (If it doesn't exist, we can ignore * the error returned by unlink) */ if (dont_fork == FALSE) { unlink(mainconfig.pid_file); } radius_event_free(); /* * Detach any modules. */ detach_modules(); xlat_free(); /* modules may have xlat's */ /* * Free the configuration items. */ free_mainconfig(); free(radius_dir); #ifdef WIN32 WSACleanup(); #endif if (memory_report) { log_talloc_report(NULL); } return (rcode - 1); }
int main(int argc, char *argv[]) { int c; int sts; int ctx; int i; int lflag = 0; /* no label by default */ int nfile; int n; char *p; struct dirent **namelist; __pmContext *ctxp; char *archpathname; /* from the command line */ char *archdirname; /* after dirname() */ char archname[MAXPATHLEN]; /* full pathname to base of archive name */ while ((c = pmGetOptions(argc, argv, &opts)) != EOF) { switch (c) { case 'l': /* display the archive label */ lflag = 1; break; case 'v': /* bump verbosity */ vflag++; break; } } if (!opts.errors && opts.optind >= argc) { pmprintf("Error: no archive specified\n\n"); opts.errors++; } if (opts.errors) { pmUsageMessage(&opts); exit(EXIT_FAILURE); } sep = __pmPathSeparator(); setlinebuf(stderr); __pmAddOptArchive(&opts, argv[opts.optind]); opts.flags &= ~PM_OPTFLAG_DONE; __pmEndOptions(&opts); archpathname = argv[opts.optind]; archbasename = strdup(basename(strdup(archpathname))); /* * treat foo, foo.index, foo.meta, foo.NNN as all equivalent * to "foo" */ p = strrchr(archbasename, '.'); if (p != NULL) { if (strcmp(p, ".index") == 0 || strcmp(p, ".meta") == 0) *p = '\0'; else { char *q = p; q++; if (isdigit(*q)) { /* * foo.<digit> ... if archpathname does exist, then * safe to strip digits, else leave as is for the * case of, e.g. archive-20150415.041154 which is the * pmmgr basename for an archive with a first volume * named archive-20150415.041154.0 */ if (access(archpathname, F_OK) == 0) { q++; while (*q && isdigit(*q)) q++; if (*q == '\0') *p = '\0'; } } } } archdirname = dirname(strdup(archpathname)); if (vflag) fprintf(stderr, "Scanning for components of archive \"%s\"\n", archpathname); nfile = scandir(archdirname, &namelist, filter, NULL); if (nfile < 1) { fprintf(stderr, "%s: no PCP archive files match \"%s\"\n", pmProgname, archpathname); exit(EXIT_FAILURE); } /* * Pass 0 for data, metadata and index files ... check physical * archive record structure, then label record */ sts = STS_OK; for (i = 0; i < nfile; i++) { char path[MAXPATHLEN]; if (strcmp(archdirname, ".") == 0) { /* skip ./ prefix */ strncpy(path, namelist[i]->d_name, sizeof(path)); } else { snprintf(path, sizeof(path), "%s%c%s", archdirname, sep, namelist[i]->d_name); } if (pass0(path) == STS_FATAL) /* unrepairable or unrepaired error */ sts = STS_FATAL; } if (meta_state == STATE_MISSING) { fprintf(stderr, "%s%c%s.meta: missing metadata file\n", archdirname, sep, archbasename); sts = STS_FATAL; } if (log_state == STATE_MISSING) { fprintf(stderr, "%s%c%s.0 (or similar): missing log file \n", archdirname, sep, archbasename); sts = STS_FATAL; } if (sts == STS_FATAL) { if (vflag) fprintf(stderr, "Due to earlier errors, cannot continue ... bye\n"); exit(EXIT_FAILURE); } if ((sts = ctx = pmNewContext(PM_CONTEXT_ARCHIVE, archpathname)) < 0) { fprintf(stderr, "%s: cannot open archive \"%s\": %s\n", pmProgname, archpathname, pmErrStr(sts)); fprintf(stderr, "Checking abandoned.\n"); exit(EXIT_FAILURE); } if (pmGetContextOptions(ctx, &opts) < 0) { pmflush(); /* runtime errors only at this stage */ exit(EXIT_FAILURE); } if (lflag) dumpLabel(); /* * Note: ctxp->c_lock remains locked throughout ... __pmHandleToPtr() * is only called once, and a single context is used throughout * ... so there is no PM_UNLOCK(ctxp->c_lock) anywhere in the * pmchecklog code. * This works because ctxp->c_lock is a recursive lock and * pmchecklog is single-threaded. */ if ((n = pmWhichContext()) >= 0) { if ((ctxp = __pmHandleToPtr(n)) == NULL) { fprintf(stderr, "%s: botch: __pmHandleToPtr(%d) returns NULL!\n", pmProgname, n); exit(EXIT_FAILURE); } } else { fprintf(stderr, "%s: botch: %s!\n", pmProgname, pmErrStr(PM_ERR_NOCONTEXT)); exit(EXIT_FAILURE); } if (strcmp(archdirname, ".") == 0) /* skip ./ prefix */ strncpy(archname, archbasename, sizeof(archname) - 1); else snprintf(archname, sizeof(archname), "%s%c%s", archdirname, sep, archbasename); sts = pass1(ctxp, archname); if (index_state == STATE_BAD) { /* prevent subsequent use of bad temporal index */ ctxp->c_archctl->ac_log->l_numti = 0; } sts = pass2(ctxp, archname); sts = pass3(ctxp, archname, &opts); if (vflag) { if (result_count > 0) fprintf(stderr, "Processed %d pmResult records\n", result_count); if (mark_count > 0) fprintf(stderr, "Processed %d <mark> records\n", mark_count); } return 0; }
/**************************************************************************** main program ****************************************************************************/ int main(int argc,char *argv[]) { TALLOC_CTX *frame = talloc_stackframe(); struct user_auth_info local_auth_info; struct poptOption long_options[] = { POPT_AUTOHELP { "broadcast", 'b', POPT_ARG_VAL, &use_bcast, True, "Use broadcast instead of using the master browser" }, { "domains", 'D', POPT_ARG_VAL, &level, LEV_WORKGROUP, "List only domains (workgroups) of tree" }, { "servers", 'S', POPT_ARG_VAL, &level, LEV_SERVER, "List domains(workgroups) and servers of tree" }, POPT_COMMON_SAMBA POPT_COMMON_CREDENTIALS POPT_TABLEEND }; poptContext pc; /* Initialise samba stuff */ load_case_tables(); setlinebuf(stdout); dbf = x_stderr; setup_logging(argv[0],True); pc = poptGetContext("smbtree", argc, (const char **)argv, long_options, POPT_CONTEXT_KEEP_FIRST); while(poptGetNextOpt(pc) != -1); poptFreeContext(pc); lp_load(get_dyn_CONFIGFILE(),True,False,False,True); load_interfaces(); /* Parse command line args */ if (get_cmdline_auth_info_use_machine_account() && !set_cmdline_auth_info_machine_account_creds()) { TALLOC_FREE(frame); return 1; } if (!get_cmdline_auth_info_got_pass()) { char *pass = getpass("Password: "); if (pass) { set_cmdline_auth_info_password(pass); } } /* Now do our stuff */ if (!get_cmdline_auth_info_copy(&local_auth_info)) { return 1; } if (!print_tree(&local_auth_info)) { TALLOC_FREE(frame); return 1; } TALLOC_FREE(frame); return 0; }
int main(int argc, char* argv[]) { setlinebuf(stdout); #ifdef _WIN32 // initialize winsock WSAData wsaData; int nCode; if ((nCode = WSAStartup(MAKEWORD(1, 1), &wsaData)) != 0) { scprintf( "WSAStartup() failed with error code %d.\n", nCode ); return 1; } #endif int udpPortNum = -1; int tcpPortNum = -1; std::string bindTo("0.0.0.0"); WorldOptions options = kDefaultWorldOptions; for (int i=1; i<argc;) { if (argv[i][0] != '-' || argv[i][1] == 0 || strchr("utBaioczblndpmwZrCNSDIOMHvVRUhPL", argv[i][1]) == 0) { scprintf("ERROR: Invalid option %s\n", argv[i]); Usage(); } int j = i; switch (argv[j][1]) { case 'u' : checkNumArgs(2); udpPortNum = atoi(argv[j+1]); break; case 't' : checkNumArgs(2); tcpPortNum = atoi(argv[j+1]); break; case 'B': checkNumArgs(2); bindTo = argv[j+1]; break; case 'a' : checkNumArgs(2); options.mNumAudioBusChannels = atoi(argv[j+1]); break; case 'i' : checkNumArgs(2); options.mNumInputBusChannels = atoi(argv[j+1]); break; case 'o' : checkNumArgs(2); options.mNumOutputBusChannels = atoi(argv[j+1]); break; case 'c' : checkNumArgs(2); options.mNumControlBusChannels = atoi(argv[j+1]); break; case 'z' : checkNumArgs(2); options.mBufLength = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'Z' : checkNumArgs(2); options.mPreferredHardwareBufferFrameSize = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'b' : checkNumArgs(2); options.mNumBuffers = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'l' : checkNumArgs(2); options.mMaxLogins = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'n' : checkNumArgs(2); options.mMaxNodes = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'd' : checkNumArgs(2); options.mMaxGraphDefs = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'p' : checkNumArgs(2); options.mPassword = argv[j+1]; break; case 'm' : checkNumArgs(2); options.mRealTimeMemorySize = atoi(argv[j+1]); break; case 'w' : checkNumArgs(2); options.mMaxWireBufs = atoi(argv[j+1]); break; case 'r' : checkNumArgs(2); options.mNumRGens = atoi(argv[j+1]); break; case 'S' : checkNumArgs(2); options.mPreferredSampleRate = (uint32)atof(argv[j+1]); break; case 'D' : checkNumArgs(2); options.mLoadGraphDefs = atoi(argv[j+1]); break; case 'N' : #ifdef NO_LIBSNDFILE scprintf("NRT mode not supported: scsynth compiled without libsndfile\n"); exit(0); #endif // -N cmd-filename input-filename output-filename sample-rate header-format sample-format checkNumArgs(7); options.mRealTime = false; options.mNonRealTimeCmdFilename = strcmp(argv[j+1], "_") ? argv[j+1] : 0; options.mNonRealTimeInputFilename = strcmp(argv[j+2], "_") ? argv[j+2] : 0; options.mNonRealTimeOutputFilename = argv[j+3]; options.mPreferredSampleRate = (uint32)atof(argv[j+4]); options.mNonRealTimeOutputHeaderFormat = argv[j+5]; options.mNonRealTimeOutputSampleFormat = argv[j+6]; break; #ifdef __APPLE__ case 'I' : checkNumArgs(2); options.mInputStreamsEnabled = argv[j+1]; break; case 'O' : checkNumArgs(2); options.mOutputStreamsEnabled = argv[j+1]; break; case 'M': #endif case 'H' : checkNumArgs(2); options.mInDeviceName = argv[j+1]; #ifdef __APPLE__ if (i+1>argc || argv[j+2][0]=='-') { options.mOutDeviceName = options.mInDeviceName; } else { // If there's a second argument then the user wants separate I/O devices options.mOutDeviceName = argv[j+2]; ++i; } #else options.mOutDeviceName = options.mInDeviceName; // Non-Mac platforms always use same device #endif break; case 'L' : checkNumArgs(1); #if (_POSIX_MEMLOCK - 0) >= 200112L options.mMemoryLocking = true; #else options.mMemoryLocking = false; #endif break; case 'V' : checkNumArgs(2); options.mVerbosity = atoi(argv[j+1]); break; case 'v' : scprintf("scsynth %s (%s)\n", SC_VersionString().c_str(), SC_BuildString().c_str()); exit(0); break; case 'R' : checkNumArgs(2); options.mRendezvous = atoi(argv[j+1]) > 0; break; case 'U' : checkNumArgs(2); options.mUGensPluginPath = argv[j+1]; break; case 'P' : checkNumArgs(2); options.mRestrictedPath = argv[j+1]; break; case 'C' : checkNumArgs(2); break; case 'h': default: Usage(); } } if (udpPortNum == -1 && tcpPortNum == -1 && options.mRealTime) { scprintf("ERROR: There must be a -u and/or a -t options, or -N for nonrealtime.\n"); Usage(); } if (options.mNumInputBusChannels + options.mNumOutputBusChannels > options.mNumAudioBusChannels) { scprintf("ERROR: number of audio bus channels < inputs + outputs.\n"); Usage(); } if (options.mRealTime) { int port = (udpPortNum > 0) ? udpPortNum : tcpPortNum; options.mSharedMemoryID = port; } else options.mSharedMemoryID = 0; struct World *world = World_New(&options); if (!world) return 1; if (!options.mRealTime) { #ifdef NO_LIBSNDFILE return 1; #else int exitCode = 0; try { World_NonRealTimeSynthesis(world, &options); } catch (std::exception& exc) { scprintf("%s\n", exc.what()); exitCode = 1; } return exitCode; #endif } if (udpPortNum >= 0) { if (!World_OpenUDP(world, bindTo.c_str(), udpPortNum)) { World_Cleanup(world,true); return 1; } } if (tcpPortNum >= 0) { if (!World_OpenTCP(world, bindTo.c_str(), tcpPortNum, options.mMaxLogins, 8)) { World_Cleanup(world,true); return 1; } } if(options.mVerbosity >=0){ #ifdef NDEBUG scprintf("SuperCollider 3 server ready.\n"); #else scprintf("SuperCollider 3 server ready (debug build).\n"); #endif } fflush(stdout); World_WaitForQuit(world,true); #ifdef _WIN32 // clean up winsock WSACleanup(); #endif // _WIN32 return 0; }
int main(int argc, char** argv) { int optchar; pthread_t threadid; char semaphore_name[32]; while ((optchar = getopt(argc, argv, "dmp")) != EOF) { switch (optchar) { case 'd': s_debug = 1; break; case 'm': s_do_mutual_exclusion = 1; break; case 'p': s_do_printf = 1; break; default: assert(0); } } /* * Use the ipcs and ipcrm commands to clean up named semaphores left by * aborted instances of this process. */ snprintf(semaphore_name, sizeof(semaphore_name), "/drd-sem-open-test-%d", getpid()); s_sem = sem_open(semaphore_name, O_CREAT | O_EXCL, 0600, 1); if (s_sem == SEM_FAILED) { fprintf(stderr, "Failed to create a semaphore with name %s\n", semaphore_name); exit(1); } /* * Switch to line-buffered mode, such that timing information can be * obtained for each printf() call with strace. */ setlinebuf(stdout); if (s_debug) { printf("&s_d1 = %p; &s_d2 = %p; &s_d3 = %p\n", &s_d1, &s_d2, &s_d3); } s_d1 = 1; s_d3 = 3; pthread_create(&threadid, 0, thread_func, 0); sleep(1); /* Wait until thread_func() finished. */ { if (s_do_mutual_exclusion) sem_wait(s_sem); s_d3++; if (s_do_mutual_exclusion) sem_post(s_sem); } /* Wait until the thread finished. */ pthread_join(threadid, 0); if (s_do_printf) printf("s_d2 = %g (should be 2)\n", s_d2); if (s_do_printf) printf("s_d3 = %g (should be 5)\n", s_d3); sem_close(s_sem); sem_unlink(semaphore_name); return 0; }
void GenericAgentInitialize(EvalContext *ctx, GenericAgentConfig *config) { int force = false; struct stat statbuf, sb; char vbuff[CF_BUFSIZE]; char ebuff[CF_EXPANDSIZE]; #ifdef __MINGW32__ InitializeWindows(); #endif DetermineCfenginePort(); EvalContextClassPutHard(ctx, "any", "source=agent"); GenericAgentAddEditionClasses(ctx); /* Define trusted directories */ const char *workdir = GetWorkDir(); if (!workdir) { FatalError(ctx, "Error determining working directory"); } OpenLog(LOG_USER); SetSyslogFacility(LOG_USER); Log(LOG_LEVEL_VERBOSE, "Work directory is %s", workdir); snprintf(vbuff, CF_BUFSIZE, "%s%cupdate.conf", GetInputDir(), FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%cbin%ccf-agent -D from_cfexecd", workdir, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%coutputs%cspooled_reports", workdir, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%clastseen%cintermittencies", workdir, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%creports%cvarious", workdir, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%c.", GetLogDir(), FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%c.", GetPidDir(), FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%c.", GetStateDir(), FILE_SEPARATOR); MakeParentDirectory(vbuff, force); MakeParentDirectory(GetLogDir(), force); snprintf(vbuff, CF_BUFSIZE, "%s", GetInputDir()); if (stat(vbuff, &sb) == -1) { FatalError(ctx, " No access to WORKSPACE/inputs dir"); } /* ensure WORKSPACE/inputs directory has all user bits set (u+rwx) */ if ((sb.st_mode & 0700) != 0700) { chmod(vbuff, sb.st_mode | 0700); } snprintf(vbuff, CF_BUFSIZE, "%s%coutputs", workdir, FILE_SEPARATOR); if (stat(vbuff, &sb) == -1) { FatalError(ctx, " No access to WORKSPACE/outputs dir"); } /* ensure WORKSPACE/outputs directory has all user bits set (u+rwx) */ if ((sb.st_mode & 0700) != 0700) { chmod(vbuff, sb.st_mode | 0700); } const char* const statedir = GetStateDir(); snprintf(ebuff, sizeof(ebuff), "%s%ccf_procs", statedir, FILE_SEPARATOR); MakeParentDirectory(ebuff, force); if (stat(ebuff, &statbuf) == -1) { CreateEmptyFile(ebuff); } snprintf(ebuff, sizeof(ebuff), "%s%ccf_rootprocs", statedir, FILE_SEPARATOR); if (stat(ebuff, &statbuf) == -1) { CreateEmptyFile(ebuff); } snprintf(ebuff, sizeof(ebuff), "%s%ccf_otherprocs", statedir, FILE_SEPARATOR); if (stat(ebuff, &statbuf) == -1) { CreateEmptyFile(ebuff); } snprintf(ebuff, sizeof(ebuff), "%s%cprevious_state%c", statedir, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(ebuff, force); snprintf(ebuff, sizeof(ebuff), "%s%cdiff%c", statedir, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(ebuff, force); snprintf(ebuff, sizeof(ebuff), "%s%cuntracked%c", statedir, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(ebuff, force); snprintf(ebuff, sizeof(ebuff), "%s%cpromise_log%c", statedir, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(ebuff, force); OpenNetwork(); CryptoInitialize(); CheckWorkingDirectories(ctx); /* Initialize keys and networking. cf-key, doesn't need keys. In fact it must function properly even without them, so that it generates them! */ if (config->agent_type != AGENT_TYPE_KEYGEN) { LoadSecretKeys(); char *bootstrapped_policy_server = ReadPolicyServerFile(workdir); PolicyHubUpdateKeys(bootstrapped_policy_server); free(bootstrapped_policy_server); } size_t cwd_size = PATH_MAX; while (true) { char cwd[cwd_size]; if (!getcwd(cwd, cwd_size)) { if (errno == ERANGE) { cwd_size *= 2; continue; } else { Log(LOG_LEVEL_WARNING, "Could not determine current directory (getcwd: %s)", GetErrorStr()); break; } } EvalContextSetLaunchDirectory(ctx, cwd); break; } if (!MINUSF) { GenericAgentConfigSetInputFile(config, GetInputDir(), "promises.cf"); } setlinebuf(stdout); if (config->agent_specific.agent.bootstrap_policy_server) { snprintf(vbuff, CF_BUFSIZE, "%s%cfailsafe.cf", GetInputDir(), FILE_SEPARATOR); if (stat(vbuff, &statbuf) == -1) { GenericAgentConfigSetInputFile(config, GetInputDir(), "failsafe.cf"); } else { GenericAgentConfigSetInputFile(config, GetInputDir(), vbuff); } } }
static void SalvageServer(void) { int pid, ret; struct SalvageQueueNode * node; pthread_t tid; pthread_attr_t attrs; int slot; VolumePackageOptions opts; /* All entries to the log will be appended. Useful if there are * multiple salvagers appending to the log. */ CheckLogFile((char *)AFSDIR_SERVER_SALSRVLOG_FILEPATH); #ifndef AFS_NT40_ENV #ifdef AFS_LINUX20_ENV fcntl(fileno(logFile), F_SETFL, O_APPEND); /* Isn't this redundant? */ #else fcntl(fileno(logFile), F_SETFL, FAPPEND); /* Isn't this redundant? */ #endif #endif setlinebuf(logFile); fprintf(logFile, "%s\n", cml_version_number); Log("Starting OpenAFS Online Salvage Server %s (%s)\n", SalvageVersion, commandLine); /* Get and hold a lock for the duration of the salvage to make sure * that no other salvage runs at the same time. The routine * VInitVolumePackage2 (called below) makes sure that a file server or * other volume utilities don't interfere with the salvage. */ /* even demand attach online salvager * still needs this because we don't want * a stand-alone salvager to conflict with * the salvager daemon */ ObtainSharedSalvageLock(); child_slot = (int *) malloc(Parallel * sizeof(int)); assert(child_slot != NULL); memset(child_slot, 0, Parallel * sizeof(int)); /* initialize things */ VOptDefaults(salvageServer, &opts); if (VInitVolumePackage2(salvageServer, &opts)) { Log("Shutting down: errors encountered initializing volume package\n"); Exit(1); } DInit(10); queue_Init(&pending_q); queue_Init(&log_cleanup_queue); assert(pthread_mutex_init(&worker_lock, NULL) == 0); assert(pthread_cond_init(&worker_cv, NULL) == 0); assert(pthread_cond_init(&log_cleanup_queue.queue_change_cv, NULL) == 0); assert(pthread_attr_init(&attrs) == 0); /* start up the reaper and log cleaner threads */ assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0); assert(pthread_create(&tid, &attrs, &SalvageChildReaperThread, NULL) == 0); assert(pthread_create(&tid, &attrs, &SalvageLogCleanupThread, NULL) == 0); assert(pthread_create(&tid, &attrs, &SalvageLogScanningThread, NULL) == 0); /* loop forever serving requests */ while (1) { node = SALVSYNC_getWork(); assert(node != NULL); Log("dispatching child to salvage volume %u...\n", node->command.sop.parent); VOL_LOCK; /* find a slot */ for (slot = 0; slot < Parallel; slot++) { if (!child_slot[slot]) break; } assert (slot < Parallel); do_fork: pid = Fork(); if (pid == 0) { VOL_UNLOCK; ret = DoSalvageVolume(node, slot); Exit(ret); } else if (pid < 0) { Log("failed to fork child worker process\n"); sleep(1); goto do_fork; } else { child_slot[slot] = pid; node->pid = pid; VOL_UNLOCK; assert(pthread_mutex_lock(&worker_lock) == 0); current_workers++; /* let the reaper thread know another worker was spawned */ assert(pthread_cond_broadcast(&worker_cv) == 0); /* if we're overquota, wait for the reaper */ while (current_workers >= Parallel) { assert(pthread_cond_wait(&worker_cv, &worker_lock) == 0); } assert(pthread_mutex_unlock(&worker_lock) == 0); } } }
/** * Extracts command line options and sets flags internally. * * @param argc Argument count * @param argv Argument vector * * @author Martin Turon * * @version 2004/3/10 mturon Intial version * @n 2004/3/12 mturon Added -b,-s,-q,-x * @n 2004/8/04 mturon Added -l [ver. 1.11] * @n 2004/8/22 mturon Added -i [ver. 1.13] * @n 2004/9/27 mturon Added -t [ver. 1.15] * @n 2004/9/29 mturon Added -f,-a [v 1.16] */ void parse_args(int argc, char **argv) { // This value is set if/when the bitflag is set. unsigned baudrate = 0; char *server, *port; g_params.flat = 0; /* default to no params set */ xpacket_initialize(); while (argc) { if ((argv[argc]) && (*argv[argc] == '-')) { switch(argv[argc][1]) { case '?': g_params.bits.display_help = 1; break; case 'q': g_params.bits.mode_quiet = 1; break; case 'p': g_params.bits.display_parsed = 1; break; case 'r': g_params.bits.display_raw = 1; break; case 'a': g_params.bits.display_ascii = 1; break; case 'c': g_params.bits.display_cooked = 1; break; case 'x': switch (argv[argc][2]) { case 'r': g_params.bits.export_parsed = 1; break; default: g_params.bits.export_cooked = 1; break; } break; case 'f': { switch (argv[argc][2]) { case '=': // specify arbitrary offset g_params.bits.mode_framing = atoi(argv[argc]+3)&3; break; case 'a': // automatic deframing g_params.bits.mode_framing = 0; break; case '0': case 'n': // assume no framing g_params.bits.mode_framing = 2; break; case '1': // force framing default: g_params.bits.mode_framing = 1; break; } break; } case 'w': case 'h': { int offset = XPACKET_DATASTART_MULTIHOP; g_params.bits.mode_header = 1; switch (argv[argc][2]) { case '=': // specify arbitrary offset offset = atoi(argv[argc]+3); break; case '0': // direct uart (no wireless) case '1': // single hop offset offset = XPACKET_DATASTART_STANDARD; break; } xpacket_set_start(offset); break; } case 'l': g_params.bits.log_cooked = 1; if (argv[argc][2] == '=') { xdb_set_table(argv[argc]+3); // xdb_create_table(argv[argc]+3); } case 'b': if (argv[argc][2] == '=') { baudrate = xserial_set_baud(argv[argc]+3); g_params.bits.display_baud = 1; } break; case 's': if (argv[argc][2] == '=') { xserial_set_device(argv[argc]+3); } break; case 't': g_params.bits.display_time = 1; break; case 'i': g_params.bits.mode_socket = 1; if (argv[argc][2] == '=') { server = argv[argc]+3; port = strchr(server, ':'); if (port) { *port++ = '\0'; xsocket_set_port(port); } xsocket_set_server(server); } break; case 'v': g_params.bits.mode_version = 1; break; case 'd': g_params.bits.mode_debug = 1; break; } } argc--; } if (!g_params.bits.mode_quiet) { // Summarize parameter settings printf("xlisten Ver:%s\n", g_version); if (g_params.bits.mode_version) xpacket_print_versions(); printf("Using params: "); if (g_params.bits.display_help) printf("[help] "); if (g_params.bits.display_baud) printf("[baud=0x%04x] ", baudrate); if (g_params.bits.display_raw) printf("[raw] "); if (g_params.bits.display_ascii) printf("[ascii] "); if (g_params.bits.display_parsed) printf("[parsed] "); if (g_params.bits.display_cooked) printf("[cooked] "); if (g_params.bits.export_parsed) printf("[export] "); if (g_params.bits.display_time) printf("[timed] "); if (g_params.bits.export_cooked) printf("[convert] "); if (g_params.bits.log_cooked) printf("[logging] "); if (g_params.bits.mode_framing==1)printf("[framed] "); if (g_params.bits.mode_framing==2)printf("[unframed] "); if (g_params.bits.mode_header) printf("[header=%i] ", xpacket_get_start()); if (g_params.bits.mode_socket) printf("[inet=%s:%u] ", xsocket_get_server(), xsocket_get_port()); if (g_params.bits.mode_debug) { printf("[debug - serial dump!] \n"); xserial_port_dump(); } printf("\n"); } if (g_params.bits.display_help) { printf( "\nUsage: xlisten <-?|r|p|c|x|l|d|v|q> <-l=table>" "\n <-s=device> <-b=baud> <-i=server:port>" "\n -? = display help [help]" "\n -r = raw display of tos packets [raw]" "\n -a = ascii display of tos packets [ascii]" "\n -p = parse packet into raw sensor readings [parsed]" "\n -x = export readings in csv spreadsheet format [export]" "\n -c = convert data to engineering units [cooked]" "\n -l = log data to database or file [logged]" "\n -d = debug serial port by dumping bytes [debug]" "\n -b = set the baudrate [baud=#|mica2|mica2dot]" "\n -s = set serial port device [device=com1]" "\n -i = use serial forwarder input [inet=host:port]" "\n -o = output (forward serial) to port [onet=port] -!TBA!-" "\n -h = specify header size [header=offset]" "\n -t = display time packet was received [timed]" "\n -q = quiet mode (suppress headers)" "\n -v = show version of all modules" "\n" ); exit(0); } /* Default to displaying packets as raw, parsed, and cooked. */ if (g_params.options.output == 0) { g_params.bits.display_raw = 1; g_params.bits.display_parsed = 1; g_params.bits.display_cooked = 1; } /* Stream initialization */ // Set STDOUT and STDERR to be line buffered, so output is not delayed. setlinebuf(stdout); setlinebuf(stderr); if (g_params.bits.mode_socket) { g_istream = xsocket_port_open(); } else { g_istream = xserial_port_open(); } }
int main(int argc, char **argv) { int verbose = 0; int one_shot = 1; double rate; setlinebuf (stdout); setlinebuf (stderr); char *optstring = "hr:v"; char c; struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "rate", required_argument, 0, 'r' }, { "verbose", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; while( (c = getopt_long( argc, argv, optstring, long_opts, 0 )) >= 0 ) { switch( c ) { case 'r': one_shot = 0; rate = strtof (optarg, NULL); printf ("Triggering at %f Hz\n", rate); break; case 'v': verbose = 1; break; case 'h': default: usage( argv[0] ); return 1; }; } dc1394camera_t ** cameras; unsigned int num_cameras = 0; dc1394error_t err = dc1394_find_cameras (&cameras, &num_cameras); if (err != DC1394_SUCCESS) { fprintf (stderr, "Error: %s\n", dc1394_error_strings[err]); return 1; } if (num_cameras == 0) { fprintf (stderr, "No cameras found\n"); return 0; } dc1394_camera_set_broadcast (cameras[0], DC1394_ON); if (verbose) printf ("Triggering...\n"); dc1394_software_trigger_set_power (cameras[0], DC1394_ON); if (one_shot) goto abort; signal (SIGINT, sig_handler); while (!do_quit) { usleep (1000000 / rate); dc1394_software_trigger_set_power (cameras[0], DC1394_ON); if (verbose) { printf ("."); fflush (stdout); } } printf ("\n"); abort: for (int i = 0; i < num_cameras; i++) dc1394_free_camera (cameras[i]); free (cameras); return 0; }
int main(int argc, char *argv[]) { const char *file = NULL; char *from = ""; char *to = ""; char *output = NULL; const char *preload_modules[] = {NULL, NULL}; FILE *out = stdout; int fd; smb_iconv_t cd; /* make sure the vars that get altered (4th field) are in a fixed location or certain compilers complain */ poptContext pc; struct poptOption long_options[] = { POPT_AUTOHELP { "from-code", 'f', POPT_ARG_STRING, &from, 0, "Encoding of original text" }, { "to-code", 't', POPT_ARG_STRING, &to, 0, "Encoding for output" }, { "output", 'o', POPT_ARG_STRING, &output, 0, "Write output to this file" }, { "preload-modules", 'p', POPT_ARG_STRING, &preload_modules[0], 0, "Modules to load" }, POPT_COMMON_SAMBA POPT_TABLEEND }; setlinebuf(stdout); pc = poptGetContext("smbiconv", argc, (const char **) argv, long_options, 0); poptSetOtherOptionHelp(pc, "[FILE] ..."); while(poptGetNextOpt(pc) != -1); /* the following functions are part of the Samba debugging facilities. See lib/debug.c */ setup_logging("smbiconv", True); if (preload_modules[0]) smb_load_modules(preload_modules); if(output) { out = fopen(output, "w"); if(!out) { DEBUG(0, ("Can't open output file '%s': %s, exiting...\n", output, strerror(errno))); return 1; } } cd = smb_iconv_open(to, from); if((int)cd == -1) { DEBUG(0,("unable to find from or to encoding, exiting...\n")); return 1; } while((file = poptGetArg(pc))) { if(strcmp(file, "-") == 0) fd = 0; else { fd = open(file, O_RDONLY); if(!fd) { DEBUG(0, ("Can't open input file '%s': %s, ignoring...\n", file, strerror(errno))); continue; } } /* Loop thru all arguments */ process_fd(cd, fd, out); close(fd); } poptFreeContext(pc); fclose(out); return 0; }
void OsInit(void) { static Bool been_here = FALSE; #ifndef XQUARTZ static const char *devnull = "/dev/null"; char fname[PATH_MAX]; #endif if (!been_here) { #if !defined(WIN32) || defined(__CYGWIN__) struct sigaction act, oact; int i; int siglist[] = { SIGSEGV, SIGQUIT, SIGILL, SIGFPE, SIGBUS, SIGSYS, SIGXCPU, SIGXFSZ, #ifdef SIGEMT SIGEMT, #endif 0 /* must be last */ }; sigemptyset(&act.sa_mask); #ifdef SA_SIGINFO act.sa_sigaction = OsSigHandler; act.sa_flags = SA_SIGINFO; #else act.sa_handler = OsSigHandler; act.sa_flags = 0; #endif for (i = 0; siglist[i] != 0; i++) { if (sigaction(siglist[i], &act, &oact)) { ErrorF("failed to install signal handler for signal %d: %s\n", siglist[i], strerror(errno)); } } #endif /* !WIN32 || __CYGWIN__ */ #ifdef BUSFAULT busfault_init(); #endif #ifdef HAVE_BACKTRACE /* * initialize the backtracer, since the ctor calls dlopen(), which * calls malloc(), which isn't signal-safe. */ do { void *array; backtrace(&array, 1); } while (0); #endif #ifdef RTLD_DI_SETSIGNAL /* Tell runtime linker to send a signal we can catch instead of SIGKILL * for failures to load libraries/modules at runtime so we can clean up * after ourselves. */ { int failure_signal = SIGQUIT; dlinfo(RTLD_SELF, RTLD_DI_SETSIGNAL, &failure_signal); } #endif #if !defined(XQUARTZ) /* STDIN is already /dev/null and STDOUT/STDERR is managed by console_redirect.c */ # if defined(__APPLE__) int devnullfd = open(devnull, O_RDWR, 0); assert(devnullfd > 2); dup2(devnullfd, STDIN_FILENO); dup2(devnullfd, STDOUT_FILENO); close(devnullfd); # elif !defined(__CYGWIN__) fclose(stdin); fclose(stdout); # endif /* * If a write of zero bytes to stderr returns non-zero, i.e. -1, * then writing to stderr failed, and we'll write somewhere else * instead. (Apparently this never happens in the Real World.) */ if (write(2, fname, 0) == -1) { FILE *err; if (strlen(display) + strlen(ADMPATH) + 1 < sizeof fname) snprintf(fname, sizeof(fname), ADMPATH, display); else strlcpy(fname, devnull, sizeof(fname)); /* * uses stdio to avoid os dependencies here, * a real os would use * open (fname, O_WRONLY|O_APPEND|O_CREAT, 0666) */ if (!(err = fopen(fname, "a+"))) err = fopen(devnull, "w"); if (err && (fileno(err) != 2)) { dup2(fileno(err), 2); fclose(err); } #if defined(SYSV) || defined(SVR4) || defined(WIN32) || defined(__CYGWIN__) { static char buf[BUFSIZ]; setvbuf(stderr, buf, _IOLBF, BUFSIZ); } #else setlinebuf(stderr); #endif } #endif /* !XQUARTZ */ #if !defined(WIN32) || defined(__CYGWIN__) if (getpgrp() == 0) setpgid(0, 0); #endif #ifdef RLIMIT_DATA if (limitDataSpace >= 0) { struct rlimit rlim; if (!getrlimit(RLIMIT_DATA, &rlim)) { if ((limitDataSpace > 0) && (limitDataSpace < rlim.rlim_max)) rlim.rlim_cur = limitDataSpace; else rlim.rlim_cur = rlim.rlim_max; (void) setrlimit(RLIMIT_DATA, &rlim); } } #endif #ifdef RLIMIT_STACK if (limitStackSpace >= 0) { struct rlimit rlim; if (!getrlimit(RLIMIT_STACK, &rlim)) { if ((limitStackSpace > 0) && (limitStackSpace < rlim.rlim_max)) rlim.rlim_cur = limitStackSpace; else rlim.rlim_cur = rlim.rlim_max; (void) setrlimit(RLIMIT_STACK, &rlim); } } #endif #ifdef RLIMIT_NOFILE if (limitNoFile >= 0) { struct rlimit rlim; if (!getrlimit(RLIMIT_NOFILE, &rlim)) { if ((limitNoFile > 0) && (limitNoFile < rlim.rlim_max)) rlim.rlim_cur = limitNoFile; else rlim.rlim_cur = rlim.rlim_max; (void) setrlimit(RLIMIT_NOFILE, &rlim); } } #endif LockServer(); been_here = TRUE; } TimerInit(); OsVendorInit(); OsResetSignals(); /* * No log file by default. OsVendorInit() should call LogInit() with the * log file name if logging to a file is desired. */ LogInit(NULL, NULL); SmartScheduleInit(); }
/* VTY shell main routine. */ int main (int argc, char **argv, char **env) { char *p; int opt; int dryrun = 0; int boot_flag = 0; const char *daemon_name = NULL; struct cmd_rec { const char *line; struct cmd_rec *next; } *cmd = NULL; struct cmd_rec *tail = NULL; int echo_command = 0; int no_error = 0; /* Preserve name of myself. */ progname = ((p = strrchr (argv[0], '/')) ? ++p : argv[0]); /* if logging open now */ if ((p = getenv("VTYSH_LOG")) != NULL) logfile = fopen(p, "a"); /* Option handling. */ while (1) { opt = getopt_long (argc, argv, "be:c:d:nEhC", longopts, 0); if (opt == EOF) break; switch (opt) { case 0: break; case 'b': boot_flag = 1; break; case 'e': case 'c': { struct cmd_rec *cr; cr = XMALLOC(0, sizeof(*cr)); cr->line = optarg; cr->next = NULL; if (tail) tail->next = cr; else cmd = cr; tail = cr; } break; case 'd': daemon_name = optarg; break; case 'n': no_error = 1; break; case 'E': echo_command = 1; break; case 'C': dryrun = 1; break; case 'h': usage (0); break; default: usage (1); break; } } /* Initialize user input buffer. */ line_read = NULL; setlinebuf(stdout); /* Signal and others. */ vtysh_signal_init (); init_timer_mgr (); /* Make vty structure and register commands. */ vtysh_init_vty (); vtysh_init_cmd (); vtysh_user_init (); vtysh_config_init (); vty_init_vtysh (); sort_node (); /* Read vtysh configuration file before connecting to daemons. */ vtysh_read_config (config_default); /* Start execution only if not in dry-run mode */ if(dryrun) return(0); /* Ignore error messages */ if (no_error) freopen("/dev/null", "w", stdout); /* Make sure we pass authentication before proceeding. */ vtysh_auth (); /* Do not connect until we have passed authentication. */ if (vtysh_connect_all (daemon_name) <= 0) { fprintf(stderr, "Exiting: NetworkOS not initialized.\n"); exit(1); } /* If eval mode. */ if (cmd) { /* Enter into enable node. */ vtysh_execute ("enable"); while (cmd != NULL) { int ret; char *eol; while ((eol = strchr(cmd->line, '\n')) != NULL) { *eol = '\0'; if (echo_command) printf("%s%s\n", vtysh_prompt(), cmd->line); if (logfile) log_it(cmd->line); ret = vtysh_execute_no_pager(cmd->line); if (!no_error && ! (ret == CMD_SUCCESS || ret == CMD_SUCCESS_DAEMON || ret == CMD_WARNING)) exit(1); cmd->line = eol+1; } if (echo_command) printf("%s%s\n", vtysh_prompt(), cmd->line); if (logfile) log_it(cmd->line); ret = vtysh_execute_no_pager(cmd->line); if (!no_error && ! (ret == CMD_SUCCESS || ret == CMD_SUCCESS_DAEMON || ret == CMD_WARNING)) exit(1); { struct cmd_rec *cr; cr = cmd; cmd = cmd->next; XFREE(0, cr); } } exit (0); } /* Boot startup configuration file. */ if (boot_flag) { if (vtysh_read_config (integrate_default)) { fprintf (stderr, "Can't open configuration file [%s]\n", integrate_default); exit (1); } else exit (0); } vtysh_pager_init (); vtysh_readline_init (); vty_hello (vty); /* Enter into enable node. */ //vtysh_execute ("enable"); /* Preparation for longjmp() in sigtstp(). */ sigsetjmp (jmpbuf, 1); jmpflag = 1; snprintf(history_file, sizeof(history_file), "%s/.history_quagga", getenv("HOME")); read_history(history_file); /* Main command loop. */ while (vtysh_rl_gets ()) vtysh_execute (line_read); history_truncate_file(history_file,1000); printf ("\n"); /* Rest in peace. */ exit (0); }
static int testclient_exec(struct ast_channel *chan, const char *data) { int res = 0; const char *testid=data; char fn[80]; char serverver[80]; FILE *f; /* Check for test id */ if (ast_strlen_zero(testid)) { ast_log(LOG_WARNING, "TestClient requires an argument - the test id\n"); return -1; } if (ast_channel_state(chan) != AST_STATE_UP) res = ast_answer(chan); /* Wait a few just to be sure things get started */ res = ast_safe_sleep(chan, 3000); /* Transmit client version */ if (!res) res = ast_dtmf_stream(chan, NULL, "8378*1#", 0, 0); ast_debug(1, "Transmit client version\n"); /* Read server version */ ast_debug(1, "Read server version\n"); if (!res) res = ast_app_getdata(chan, NULL, serverver, sizeof(serverver) - 1, 0); if (res > 0) res = 0; ast_debug(1, "server version: %s\n", serverver); if (res > 0) res = 0; if (!res) res = ast_safe_sleep(chan, 1000); /* Send test id */ if (!res) res = ast_dtmf_stream(chan, NULL, testid, 0, 0); if (!res) res = ast_dtmf_stream(chan, NULL, "#", 0, 0); ast_debug(1, "send test identifier: %s\n", testid); if ((res >=0) && (!ast_strlen_zero(testid))) { /* Make the directory to hold the test results in case it's not there */ snprintf(fn, sizeof(fn), "%s/testresults", ast_config_AST_LOG_DIR); ast_mkdir(fn, 0777); snprintf(fn, sizeof(fn), "%s/testresults/%s-client.txt", ast_config_AST_LOG_DIR, testid); if ((f = fopen(fn, "w+"))) { setlinebuf(f); fprintf(f, "CLIENTCHAN: %s\n", ast_channel_name(chan)); fprintf(f, "CLIENTTEST ID: %s\n", testid); fprintf(f, "ANSWER: PASS\n"); res = 0; if (!res) { /* Step 1: Wait for "1" */ ast_debug(1, "TestClient: 2. Wait DTMF 1\n"); res = ast_waitfordigit(chan, 3000); fprintf(f, "WAIT DTMF 1: %s\n", (res != '1') ? "FAIL" : "PASS"); if (res == '1') res = 0; else res = -1; } if (!res) { res = ast_safe_sleep(chan, 1000); } if (!res) { /* Step 2: Send "2" */ ast_debug(1, "TestClient: 2. Send DTMF 2\n"); res = ast_dtmf_stream(chan, NULL, "2", 0, 0); fprintf(f, "SEND DTMF 2: %s\n", (res < 0) ? "FAIL" : "PASS"); if (res > 0) res = 0; } if (!res) { /* Step 3: Wait one second */ ast_debug(1, "TestClient: 3. Wait one second\n"); res = ast_safe_sleep(chan, 1000); fprintf(f, "WAIT 1 SEC: %s\n", (res < 0) ? "FAIL" : "PASS"); if (res > 0) res = 0; } if (!res) { /* Step 4: Measure noise */ ast_debug(1, "TestClient: 4. Measure noise\n"); res = measurenoise(chan, 5000, "TestClient"); fprintf(f, "MEASURENOISE: %s (%d)\n", (res < 0) ? "FAIL" : "PASS", res); if (res > 0) res = 0; } if (!res) { /* Step 5: Wait for "4" */ ast_debug(1, "TestClient: 5. Wait DTMF 4\n"); res = ast_waitfordigit(chan, 3000); fprintf(f, "WAIT DTMF 4: %s\n", (res != '4') ? "FAIL" : "PASS"); if (res == '4') res = 0; else res = -1; } if (!res) { /* Step 6: Transmit tone noise */ ast_debug(1, "TestClient: 6. Transmit tone\n"); res = sendnoise(chan, 6000); fprintf(f, "SENDTONE: %s\n", (res < 0) ? "FAIL" : "PASS"); } if (!res || (res == '5')) { /* Step 7: Wait for "5" */ ast_debug(1, "TestClient: 7. Wait DTMF 5\n"); if (!res) res = ast_waitfordigit(chan, 3000); fprintf(f, "WAIT DTMF 5: %s\n", (res != '5') ? "FAIL" : "PASS"); if (res == '5') res = 0; else res = -1; } if (!res) { /* Step 8: Wait one second */ ast_debug(1, "TestClient: 8. Wait one second\n"); res = ast_safe_sleep(chan, 1000); fprintf(f, "WAIT 1 SEC: %s\n", (res < 0) ? "FAIL" : "PASS"); if (res > 0) res = 0; } if (!res) { /* Step 9: Measure noise */ ast_debug(1, "TestClient: 9. Measure tone\n"); res = measurenoise(chan, 4000, "TestClient"); fprintf(f, "MEASURETONE: %s (%d)\n", (res < 0) ? "FAIL" : "PASS", res); if (res > 0) res = 0; } if (!res) { /* Step 10: Send "7" */ ast_debug(1, "TestClient: 10. Send DTMF 7\n"); res = ast_dtmf_stream(chan, NULL, "7", 0, 0); fprintf(f, "SEND DTMF 7: %s\n", (res < 0) ? "FAIL" : "PASS"); if (res > 0) res =0; } if (!res) { /* Step 11: Wait for "8" */ ast_debug(1, "TestClient: 11. Wait DTMF 8\n"); res = ast_waitfordigit(chan, 3000); fprintf(f, "WAIT DTMF 8: %s\n", (res != '8') ? "FAIL" : "PASS"); if (res == '8') res = 0; else res = -1; } if (!res) { res = ast_safe_sleep(chan, 1000); } if (!res) { /* Step 12: Hangup! */ ast_debug(1, "TestClient: 12. Hangup\n"); } ast_debug(1, "-- TEST COMPLETE--\n"); fprintf(f, "-- END TEST--\n"); fclose(f); res = -1; } else res = -1; } else { ast_log(LOG_NOTICE, "Did not read a test ID on '%s'\n", ast_channel_name(chan)); res = -1; } return res; }
/**************************************************************************** main program ****************************************************************************/ int main(int argc,char *argv[]) { char *share[NSERVERS]; int opt; int seed, server; int username_count=0; struct tevent_context *ev; struct loadparm_context *lp_ctx; poptContext pc; int argc_new, i; char **argv_new; enum {OPT_UNCLIST=1000}; struct poptOption long_options[] = { POPT_AUTOHELP {"seed", 0, POPT_ARG_INT, &seed, 0, "Seed to use for randomizer", NULL}, {"num-ops", 0, POPT_ARG_INT, &numops, 0, "num ops", NULL}, {"lockrange", 0, POPT_ARG_INT, &lock_range,0, "locking range", NULL}, {"lockbase", 0, POPT_ARG_INT, &lock_base, 0, "locking base", NULL}, {"minlength", 0, POPT_ARG_INT, &min_length,0, "min lock length", NULL}, {"hidefails", 0, POPT_ARG_NONE, &hide_unlock_fails,0,"hide unlock fails", NULL}, {"oplocks", 0, POPT_ARG_NONE, &use_oplocks,0, "use oplocks", NULL}, {"showall", 0, POPT_ARG_NONE, &showall, 0, "display all operations", NULL}, {"analyse", 0, POPT_ARG_NONE, &analyze, 0, "do backtrack analysis", NULL}, {"zerozero", 0, POPT_ARG_NONE, &zero_zero, 0, "do zero/zero lock", NULL}, {"exacterrors", 0, POPT_ARG_NONE, &exact_error_codes,0,"use exact error codes", NULL}, {"unclist", 0, POPT_ARG_STRING, NULL, OPT_UNCLIST, "unclist", NULL}, { "user", 'U', POPT_ARG_STRING, NULL, 'U', "Set the network username", "[DOMAIN/]USERNAME[%PASSWORD]" }, POPT_COMMON_SAMBA POPT_COMMON_CONNECTION POPT_COMMON_CREDENTIALS POPT_COMMON_VERSION { NULL } }; setlinebuf(stdout); seed = time(NULL); pc = poptGetContext("locktest", argc, (const char **) argv, long_options, POPT_CONTEXT_KEEP_FIRST); poptSetOtherOptionHelp(pc, "<unc1> <unc2>"); lp_ctx = cmdline_lp_ctx; servers[0] = cli_credentials_init(talloc_autofree_context()); servers[1] = cli_credentials_init(talloc_autofree_context()); cli_credentials_guess(servers[0], lp_ctx); cli_credentials_guess(servers[1], lp_ctx); while((opt = poptGetNextOpt(pc)) != -1) { switch (opt) { case OPT_UNCLIST: lp_set_cmdline(cmdline_lp_ctx, "torture:unclist", poptGetOptArg(pc)); break; case 'U': if (username_count == 2) { usage(pc); exit(1); } cli_credentials_parse_string(servers[username_count], poptGetOptArg(pc), CRED_SPECIFIED); username_count++; break; } } argv_new = discard_const_p(char *, poptGetArgs(pc)); argc_new = argc; for (i=0; i<argc; i++) { if (argv_new[i] == NULL) { argc_new = i; break; } } if (!(argc_new >= 3)) { usage(pc); exit(1); } setup_logging("locktest", DEBUG_STDOUT); for (server=0;server<NSERVERS;server++) { share[server] = argv_new[1+server]; all_string_sub(share[server],"/","\\",0); } lp_ctx = cmdline_lp_ctx; if (username_count == 0) { usage(pc); return -1; } if (username_count == 1) { servers[1] = servers[0]; } ev = s4_event_context_init(talloc_autofree_context()); gensec_init(lp_ctx); DEBUG(0,("seed=%u base=%d range=%d min_length=%d\n", seed, lock_base, lock_range, min_length)); srandom(seed); return test_locks(ev, lp_ctx, NULL, share); }
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 glite_srvbones_run( slave_data_init_hnd slave_data_init, struct glite_srvbones_service *service_table, size_t table_sz, int dbg) { struct sigaction sa; sigset_t sset; int sock_slave[2], i; assert(service_table); assert(table_sz > 0); services = service_table; services_ct = table_sz; debug = dbg; setlinebuf(stdout); setlinebuf(stderr); dprintf(("Master pid %d\n", getpid())); if ( socketpair(AF_UNIX, SOCK_STREAM, 0, sock_slave) ) { perror("socketpair()"); return 1; } memset(&sa, 0, sizeof(sa)); assert(sa.sa_handler == NULL); sa.sa_handler = catchsig; sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sa.sa_handler = catch_chld; sigaction(SIGCHLD, &sa, NULL); sa.sa_handler = SIG_IGN; sigaction(SIGUSR1, &sa, NULL); sigemptyset(&sset); sigaddset(&sset, SIGCHLD); sigaddset(&sset, SIGTERM); sigaddset(&sset, SIGINT); sigprocmask(SIG_BLOCK, &sset, NULL); for ( i = 0; i < set_slaves_ct; i++ ) slave(slave_data_init, sock_slave[1]); while ( !die ) { fd_set fds; int ret, mx; FD_ZERO(&fds); FD_SET(sock_slave[0], &fds); for ( i = 0, mx = sock_slave[0]; i < services_ct; i++ ) { FD_SET(services[i].conn, &fds); if ( mx < services[i].conn ) mx = services[i].conn; } sigprocmask(SIG_UNBLOCK, &sset, NULL); ret = select(mx+1, &fds, NULL, NULL, NULL); sigprocmask(SIG_BLOCK, &sset, NULL); if ( ret == -1 && errno != EINTR ) { if ( debug ) perror("select()"); else syslog(LOG_CRIT,"select(): %m"); return 1; } if ( child_died ) { int pid; while ( (pid = waitpid(-1, NULL, WNOHANG)) > 0 ) { if ( !die ) { int newpid = slave(slave_data_init, sock_slave[1]); dprintf(("[master] Servus mortuus [%d] miraculo resurrexit [%d]\n", pid, newpid)); } } child_died = 0; continue; } if ( die ) continue; if (FD_ISSET(sock_slave[0],&fds)) { /* slave accepted a request */ unsigned long a; if ( (recv(sock_slave[0], &a, sizeof(a), MSG_WAITALL) == sizeof(a)) && (a <= clnt_dispatched) && (a > clnt_accepted || clnt_accepted > clnt_dispatched) ) clnt_accepted = a; } for ( i = 0; i < services_ct; i++ ) if ( FD_ISSET(services[i].conn, &fds) && dispatchit(sock_slave[0], services[i].conn ,i) ) /* Be carefull!!! * This must break this for cykle but start the * while (!die) master cykle from the top also */ break; } dprintf(("[master] Terminating on signal %d\n", die)); if (!debug) syslog(LOG_INFO, "Terminating on signal %d\n", die); kill(0, die); return 0; }
/** * Daemon main loop. Sets up named pipe and captures commands * given through named pipe. * * Can be stopped with "stop" command or with SIGTERM. * * @return int Returns negative integer on error. */ int daemon_main(){ char buf[128] = {0}; FILE *fp; struct sigaction act; sigset_t mask; int res = 0; sigemptyset(&mask); sigaddset(&mask,SIGTERM); sigaddset(&mask,SIGCHLD); sigaddset(&mask,SIGHUP); setlinebuf(stdout); bzero(&act, sizeof(act)); act.sa_sigaction = sig_handler; act.sa_mask = mask; act.sa_flags = SA_NOCLDSTOP|SA_SIGINFO; sigaction(SIGTERM, &act, NULL); sigaction(SIGCHLD, &act, NULL); sigaction(SIGHUP, &act, NULL); if((res = loadConfig()) != 0){ if (res == 1) return res; fprintf(stderr, "Failed to load conf, continuing with defaults.\n"); } updateInstances(); unlink(OPAFMD_PIPE); // cleanup any bad states if (mkfifo(OPAFMD_PIPE, 0660) == -1){ fprintf(stderr, "Failed to create pipe: %s\n", strerror(errno)); return(2); } if((fd = open(OPAFMD_PIPE, O_RDWR)) == -1){ fprintf(stderr, "Failed to open pipe for reading: %s\n", strerror(errno)); unlink(OPAFMD_PIPE); // cleanup any bad states return(2); } if((fp = fdopen(fd, "r")) == NULL){ fprintf(stderr, "Failed to open pipe for reading: %s\n", strerror(errno)); unlink(OPAFMD_PIPE); // cleanup any bad states return(2); } sigprocmask(SIG_BLOCK, &mask, NULL); while(!doStop){ char *s; sigprocmask(SIG_UNBLOCK, &mask, NULL); s = fgets(buf, 127, fp); sigprocmask(SIG_BLOCK, &mask, NULL); if (s != NULL) { parseInput(buf); } } sigprocmask(SIG_UNBLOCK, &mask, NULL); fclose(fp); doStop = -(doStop - 1); // Use doStop value as return value. Allows systemd to show daemon status on failure. unlink(OPAFMD_PIPE); // Destroy pipe pthread_exit(&doStop); // Allows any running background threads to terminate properly. }
void parser_opts(int argc, char **argv){ int Getopts, option_index = 0; int tmp; timeout = 10; retry_times = 5; while( (Getopts = getopt_long(argc, argv, OPTS, long_options, &option_index)) != -1){ switch(Getopts){ case 0: if(!strcmp(long_options[option_index].name, "connect-timeout")){ tmp = (int) strtol(optarg, NULL, 10); if( !IN_RANGE(tmp, 5, 120) ) die("--connect-timeout error: please set a value between 5 and 120 seconds",0); else timeout = (size_t) tmp; } else if(!strcmp(long_options[option_index].name, "ssh-port")){ tmp = (int) strtol(optarg, NULL, 10); if( !IN_RANGE(tmp, 1, 65535) ) die("--ssh-port error: set a valide port (1 .. 65535)",0); else xpl.ssh_port = (size_t) tmp; } else if(!strcmp(long_options[option_index].name, "ssh-target")){ if( valid_ip_hostname(optarg) ) xpl.ssh_host = optarg; else die("--ssh-target error: invalid ip/hostname",0); } else if(!strcmp(long_options[option_index].name, "retry-times")){ tmp = (int) strtol(optarg, NULL, 10); if( !IN_RANGE(tmp, 0, 10) ) die("--retry-times error: value must be between 0 and 10",0); else retry_times = (size_t) tmp; } else if(!strcmp(long_options[option_index].name, "threads")){ tmp = (int) strtol(optarg, NULL, 10); if( !IN_RANGE(tmp, 2, 1000) ) die("--threads error: set a valide value (2..1000)",0); else options.threads = (size_t) tmp; } else if(!strcmp(long_options[option_index].name, "inject-at")){ xpl.p_name = optarg; } else if(!strcmp(long_options[option_index].name, "proxy")){ if( regex_match(PROXY_REGEX, optarg, 0, 0) ) proxy = optarg; else die("--proxy invalid syntax",0); } break; case 'h': help(); break; case 'B': cookies = optarg; break; case 'A': UA = optarg; break; case 'u': if( regex_match(URL_REGEX, optarg, 0, 0) ) options.url = optarg; else die("-u, --url URL Have invalid syntax",0); break; case 'U': options.url_list = xfopen(optarg,"r"); break; case 't': xpl.vuln_uri = optarg; break; case 'X': if(!strcmp("environ",optarg)) xpl.tech = ENVIRON; else if(!strcmp("auth",optarg)) xpl.tech = AUTH; else if (!strcmp("input",optarg)) xpl.tech = INPUT; else if (!strcmp("data", optarg)) xpl.tech = DATA; else die("-X, --rce-technique Invalid RCE technique",0); break; case 'C': if( regex_match("^\\s*?\\<\\?.+\\?\\>\\s*?$",optarg,0,PCRE_DOTALL) ) xpl.code = optarg; else die("-C, --code parameter must contain php brackets",0); break; case 'c': xpl.cmd = optarg; break; case 's': options.shell = true; break; case 'r': options.reverse_shell = true; break; case 'b': options.bind_shell = true; break; case 'i': if( valid_ip_hostname(optarg) ) options.ip_addr = optarg; else die("-i, --connect-to error: Invalid IP/Hostname",0); break; case 'p': tmp = (int) strtol(optarg, NULL, 10); if( !IN_RANGE(tmp, 1, 65535) ) die("-p, --port error: set a valide port (1 .. 65535)",0); else options.port = (size_t) tmp; break; case 'G': options.get_source = true; break; case 'f': options.filename = optarg; break; case 'o': output = xfopen(optarg,"a"); setlinebuf(output); break; case 'O': options.source_output = xfopen(optarg,"a"); break; case 'l': tmp = (int) strtol(optarg, NULL, 10); if( !IN_RANGE(tmp, 1, 65535) ) die("-l, --listen error: set a valide port (1 .. 65535)",0); else options.listen = (size_t) tmp; break; default: abort(); } } if(options.reverse_shell && options.bind_shell) die("error: reverse connection & bind connection are enabled",0); if(options.reverse_shell && !options.listen) die("error: -r,reverse-shell required -l, --listen option",0); if(options.threads && !options.url_list) die("error: --threads required -U, --url-list option",0); if(!xpl.p_name && xpl.tech == DATA) die("error: RCE data type required --inject-at option",0); if(!options.url && !options.url_list && !xpl.vuln_uri) die("kadimus: try 'kadimus -h' or 'kadimus --help' for display help",0); }
int main(int argc, char **argv) { struct pkt pkt; int c; while ((c = getopt(argc, argv, "l:T:qP:")) != EOF) switch (c) { case 'l': data_lines = atoi(optarg); break; case 'T': test_duration = atoi(optarg); alarm(test_duration); break; case 'q': quiet = 1; break; case 'P': benchdev_no = atoi(optarg); break; default: fprintf(stderr, "usage: latency [options]\n" " [-l <data-lines per header>] # default=21, 0 to supress headers\n" " [-T <test_duration_seconds>] # default=0, so ^C to end\n" " [-q] # supresses RTD, RTH lines if -T is used\n" " [-P <rt_pipe_no>] # number of testing pipe, default=auto\n"); exit(2); } if (!test_duration && quiet) { fprintf(stderr, "latency: -q only works if -T has been given.\n"); quiet = 0; } time(&test_start); signal(SIGINT, sighand); signal(SIGTERM, sighand); signal(SIGHUP, sighand); signal(SIGALRM, sighand); setlinebuf(stdout); if (benchdev_no == -1) { benchdev = open("/proc/xenomai/registry/native/pipes/klat_pipe", O_RDONLY); if (benchdev == -1) { perror("open(/proc/xenomai/registry/native/pipes/klat_pipe)"); fprintf(stderr, "modprobe klat_mod or try the -P option?\n"); exit(EXIT_FAILURE); } } else { char devname[64]; snprintf(devname, sizeof(devname), "/dev/rtp%d", benchdev_no); benchdev = open(devname, O_RDONLY); if (benchdev == -1) { fprintf(stderr, "open(%s): %s\n", devname, strerror(errno)); exit(EXIT_FAILURE); } } if (read(benchdev, &pkt, sizeof(pkt)) == -1) { perror("read"); exit(EXIT_FAILURE); } test_mode = pkt.config.mode; priority = pkt.config.priority; period_ns = pkt.config.period; freeze_max = pkt.config.freeze_max; printf("== Sampling period: %Ld us\n" "== Test mode: %s\n" "== All results in microseconds\n", period_ns / 1000, test_mode_names[test_mode]); display(); return 0; }
/* * out_init -- initialize the log * * This is called from the library initialization code. */ void out_init(const char *log_prefix, const char *log_level_var, const char *log_file_var, int major_version, int minor_version) { static int once; /* only need to initialize the out module once */ if (once) return; once++; Log_prefix = log_prefix; #ifdef DEBUG char *log_level; char *log_file; if ((log_level = getenv(log_level_var)) != NULL) { Log_level = atoi(log_level); if (Log_level < 0) { Log_level = 0; } } if ((log_file = getenv(log_file_var)) != NULL) { size_t cc = strlen(log_file); /* reserve more than enough space for a PID + '\0' */ char *log_file_pid = alloca(cc + 30); if (cc > 0 && log_file[cc - 1] == '-') { snprintf(log_file_pid, cc + 30, "%s%d", log_file, getpid()); log_file = log_file_pid; } if ((Out_fp = fopen(log_file, "w")) == NULL) { fprintf(stderr, "Error (%s): %s=%s: %s\n", log_prefix, log_file_var, log_file, strerror(errno)); abort(); } } #endif /* DEBUG */ char *log_alignment = getenv("NVML_LOG_ALIGN"); if (log_alignment) { int align = atoi(log_alignment); if (align > 0) Log_alignment = (unsigned)align; } if (Out_fp == NULL) Out_fp = stderr; else setlinebuf(Out_fp); #ifdef DEBUG LOG(1, "pid %d: program: %s", getpid(), getexecname()); #endif LOG(1, "%s version %d.%d", log_prefix, major_version, minor_version); LOG(1, "src version %s", nvml_src_version); #ifdef USE_VG_PMEMCHECK /* * Attribute "used" to prevent compiler from optimizing out the variable * when LOG expands to no code (!DEBUG) */ static __attribute__((used)) const char *pmemcheck_msg = "compiled with support for Valgrind pmemcheck"; LOG(1, "%s", pmemcheck_msg); #endif /* USE_VG_PMEMCHECK */ #ifdef USE_VG_HELGRIND static __attribute__((used)) const char *helgrind_msg = "compiled with support for Valgrind helgrind"; LOG(1, "%s", helgrind_msg); #endif /* USE_VG_HELGRIND */ #ifdef USE_VG_MEMCHECK static __attribute__((used)) const char *memcheck_msg = "compiled with support for Valgrind memcheck"; LOG(1, "%s", memcheck_msg); #endif /* USE_VG_MEMCHECK */ #ifdef USE_VG_DRD static __attribute__((used)) const char *drd_msg = "compiled with support for Valgrind drd"; LOG(1, "%s", drd_msg); #endif /* USE_VG_DRD */ Last_errormsg_key_alloc(); }
void GenericAgentInitialize(EvalContext *ctx, GenericAgentConfig *config) { int force = false; struct stat statbuf, sb; char vbuff[CF_BUFSIZE]; char ebuff[CF_EXPANDSIZE]; SHORT_CFENGINEPORT = htons((unsigned short) 5308); snprintf(STR_CFENGINEPORT, 15, "5308"); EvalContextHeapAddHard(ctx, "any"); strcpy(VPREFIX, GetConsolePrefix()); /* Define trusted directories */ { const char *workdir = GetWorkDir(); if (!workdir) { FatalError(ctx, "Error determining working directory"); } strcpy(CFWORKDIR, workdir); MapName(CFWORKDIR); } /* On windows, use 'binary mode' as default for files */ #ifdef __MINGW32__ _fmode = _O_BINARY; #endif OpenLog(LOG_USER); SetSyslogFacility(LOG_USER); if (!LOOKUP) /* cf-know should not do this in lookup mode */ { Log(LOG_LEVEL_VERBOSE, "Work directory is %s", CFWORKDIR); snprintf(vbuff, CF_BUFSIZE, "%s%cinputs%cupdate.conf", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%cbin%ccf-agent -D from_cfexecd", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%coutputs%cspooled_reports", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%clastseen%cintermittencies", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%creports%cvarious", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(vbuff, force); snprintf(vbuff, CF_BUFSIZE, "%s%cinputs", CFWORKDIR, FILE_SEPARATOR); if (stat(vbuff, &sb) == -1) { FatalError(ctx, " No access to WORKSPACE/inputs dir"); } else { chmod(vbuff, sb.st_mode | 0700); } snprintf(vbuff, CF_BUFSIZE, "%s%coutputs", CFWORKDIR, FILE_SEPARATOR); if (stat(vbuff, &sb) == -1) { FatalError(ctx, " No access to WORKSPACE/outputs dir"); } else { chmod(vbuff, sb.st_mode | 0700); } sprintf(ebuff, "%s%cstate%ccf_procs", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR); MakeParentDirectory(ebuff, force); if (stat(ebuff, &statbuf) == -1) { CreateEmptyFile(ebuff); } sprintf(ebuff, "%s%cstate%ccf_rootprocs", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR); if (stat(ebuff, &statbuf) == -1) { CreateEmptyFile(ebuff); } sprintf(ebuff, "%s%cstate%ccf_otherprocs", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR); if (stat(ebuff, &statbuf) == -1) { CreateEmptyFile(ebuff); } } OpenNetwork(); CryptoInitialize(); if (!LOOKUP) { CheckWorkingDirectories(ctx); } const char *bootstrapped_policy_server = ReadPolicyServerFile(CFWORKDIR); /* Initialize keys and networking. cf-key, doesn't need keys. In fact it must function properly even without them, so that it generates them! */ if (config->agent_type != AGENT_TYPE_KEYGEN) { LoadSecretKeys(bootstrapped_policy_server); cfnet_init(); } if (!MINUSF) { GenericAgentConfigSetInputFile(config, GetWorkDir(), "promises.cf"); } DetermineCfenginePort(); VIFELAPSED = 1; VEXPIREAFTER = 1; setlinebuf(stdout); if (config->agent_specific.agent.bootstrap_policy_server) { snprintf(vbuff, CF_BUFSIZE, "%s%cinputs%cfailsafe.cf", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR); #ifndef HAVE_ENTERPRISE if (stat(vbuff, &statbuf) == -1) { GenericAgentConfigSetInputFile(config, GetWorkDir(), "failsafe.cf"); } else #endif { GenericAgentConfigSetInputFile(config, GetWorkDir(), vbuff); } } }
int main(int argc, char *argv[]) { char **sp; nltype **timesortnlp; char **defaultEs; --argc; argv++; debug = 0; bflag = TRUE; while ( *argv != 0 && **argv == '-' ) { (*argv)++; switch ( **argv ) { case 'a': aflag = TRUE; break; case 'b': bflag = FALSE; break; case 'C': Cflag = TRUE; cyclethreshold = atoi( *++argv ); break; case 'c': #if defined(__i386__) || defined(__vax__) || defined(__tahoe__) || \ defined(__sparc__) || defined(__sparc64__) cflag = TRUE; #else fprintf(stderr, "%s: -c isn't supported on this architecture yet\n", __progname); exit(1); #endif break; case 'd': dflag = TRUE; setlinebuf(stdout); debug |= atoi( *++argv ); debug |= ANYDEBUG; # ifdef DEBUG printf("[main] debug = %d\n", debug); # else /* not DEBUG */ warnx("-d ignored"); # endif /* DEBUG */ break; case 'E': ++argv; addlist( Elist , *argv ); Eflag = TRUE; addlist( elist , *argv ); eflag = TRUE; break; case 'e': addlist( elist , *++argv ); eflag = TRUE; break; case 'F': ++argv; addlist( Flist , *argv ); Fflag = TRUE; addlist( flist , *argv ); fflag = TRUE; break; case 'f': addlist( flist , *++argv ); fflag = TRUE; break; case 'k': addlist( kfromlist , *++argv ); addlist( ktolist , *++argv ); kflag = TRUE; break; case 's': sflag = TRUE; break; case 'z': zflag = TRUE; break; } argv++; } if ( *argv != 0 ) { a_outname = *argv; argv++; } else { a_outname = A_OUTNAME; } if ( *argv != 0 ) { gmonname = *argv; argv++; } else { gmonname = GMONNAME; } /* * get information about a.out file. */ if (getnfile(a_outname, &defaultEs) == -1) errx(1, "%s: bad format", a_outname); /* * sort symbol table. */ qsort(nl, nname, sizeof(nltype), valcmp); /* * turn off default functions */ for ( sp = &defaultEs[0] ; *sp ; sp++ ) { Eflag = TRUE; addlist( Elist , *sp ); eflag = TRUE; addlist( elist , *sp ); } /* * get information about mon.out file(s). */ do { getpfile( gmonname ); if ( *argv != 0 ) { gmonname = *argv; } } while ( *argv++ != 0 ); /* * how many ticks per second? * if we can't tell, report time in ticks. */ if (hz == 0) { hz = 1; warnx("time is in ticks, not seconds"); } /* * dump out a gmon.sum file if requested */ if ( sflag ) { dumpsum( GMONSUM ); } /* * assign samples to procedures */ asgnsamples(); /* * assemble the dynamic profile */ timesortnlp = doarcs(); /* * print the dynamic profile */ printgprof( timesortnlp ); /* * print the flat profile */ printprof(); /* * print the index */ printindex(); return (0); }