int main(int argc, char **argv) { bool quiet = false; int ch, i, *fds, fd; int ret = EXIT_SUCCESS; size_t nfds; FILE *fp; while ((ch = getopt(argc, argv, "qV")) != -1) { switch (ch) { case 'q': quiet = true; break; case 'V': /* Do nothing, compat with GNU rcs's ident */ return (EXIT_SUCCESS); default: errx(EXIT_FAILURE, "usage: %s [-q] [-V] [file...]", getprogname()); } } argc -= optind; argv += optind; if (caph_limit_stdio() < 0) err(EXIT_FAILURE, "unable to limit stdio"); if (argc == 0) { nfds = 1; fds = malloc(sizeof(*fds)); if (fds == NULL) err(EXIT_FAILURE, "unable to allocate fds array"); fds[0] = STDIN_FILENO; } else { nfds = argc; fds = malloc(sizeof(*fds) * nfds); if (fds == NULL) err(EXIT_FAILURE, "unable to allocate fds array"); for (i = 0; i < argc; i++) { fds[i] = fd = open(argv[i], O_RDONLY); if (fd < 0) { warn("%s", argv[i]); ret = EXIT_FAILURE; continue; } if (caph_limit_stream(fd, CAPH_READ) < 0) err(EXIT_FAILURE, "unable to limit fcntls/rights for %s", argv[i]); } } /* Enter Capsicum sandbox. */ if (cap_enter() < 0 && errno != ENOSYS) err(EXIT_FAILURE, "unable to enter capability mode"); for (i = 0; i < (int)nfds; i++) { if (fds[i] < 0) continue; fp = fdopen(fds[i], "r"); if (fp == NULL) { warn("%s", argv[i]); ret = EXIT_FAILURE; continue; } if (scan(fp, argc == 0 ? NULL : argv[i], quiet) != EXIT_SUCCESS) ret = EXIT_FAILURE; fclose(fp); } return (ret); }
static void usage (int ret) { fprintf(stderr, "usage: %s [--quite/-q] [--help/-h]\n", getprogname()); exit (ret); }
int main(int argc, char **argv) { const char *progname = getprogname(); #ifndef SMALL char *gzip; int len; #endif int ch; #ifndef SMALL if ((gzip = getenv("GZIP")) != NULL) prepend_gzip(gzip, &argc, &argv); signal(SIGINT, sigint_handler); #endif /* * XXX * handle being called `gunzip', `zcat' and `gzcat' */ if (strcmp(progname, "gunzip") == 0) dflag = 1; else if (strcmp(progname, "zcat") == 0 || strcmp(progname, "gzcat") == 0) dflag = cflag = 1; #ifdef SMALL #define OPT_LIST "123456789cdhlV" #else #define OPT_LIST "123456789acdfhklLNnqrS:tVv" #endif while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) { switch (ch) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': numflag = ch - '0'; break; case 'c': cflag = 1; break; case 'd': dflag = 1; break; case 'l': lflag = 1; dflag = 1; break; case 'V': display_version(); /* NOTREACHED */ #ifndef SMALL case 'a': fprintf(stderr, "%s: option --ascii ignored on this system\n", progname); break; case 'f': fflag = 1; break; case 'k': kflag = 1; break; case 'L': display_license(); /* NOT REACHED */ case 'N': nflag = 0; Nflag = 1; break; case 'n': nflag = 1; Nflag = 0; break; case 'q': qflag = 1; break; case 'r': rflag = 1; break; case 'S': len = strlen(optarg); if (len != 0) { if (len > SUFFIX_MAXLEN) errx(1, "incorrect suffix: '%s': too long", optarg); suffixes[0].zipped = optarg; suffixes[0].ziplen = len; } else { suffixes[NUM_SUFFIXES - 1].zipped = ""; suffixes[NUM_SUFFIXES - 1].ziplen = 0; } break; case 't': cflag = 1; tflag = 1; dflag = 1; break; case 'v': vflag = 1; break; #endif default: usage(); /* NOTREACHED */ } } argv += optind; argc -= optind; if (argc == 0) { if (dflag) /* stdin mode */ handle_stdin(); else /* stdout mode */ handle_stdout(); } else { do { handle_pathname(argv[0]); } while (*++argv); } #ifndef SMALL if (qflag == 0 && lflag && argc > 1) print_list(-1, 0, "(totals)", 0); #endif exit(exit_value); }
int main(int argc, char *argv[]) { char *System = NULL; int c, i; char *p; const char *q; char sbuf[12]; int cmdlineBR; int fcarg; setprogname(argv[0]); gid = getgid(); egid = getegid(); uid = getuid(); euid = geteuid(); if (strcmp(getprogname(), "cu") == 0) { cumode = 1; cumain(argc, argv); goto cucommon; } if (argc > 4) tipusage(); if (!isatty(0)) errx(EXIT_FAILURE, "must be interactive"); cmdlineBR = 0; while((c = getopt(argc, argv, "v0123456789")) != -1) { switch(c) { case 'v': vflag++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': cmdlineBR = cmdlineBR * 10 + (c - '0'); BR = cmdlineBR; break; default: warnx("%s, unknown option", argv[1]); break; } } argc -= optind; argv += optind; if (argc != 1) tipusage(); else System = argv[0]; if (System == NULL) goto notnumber; if (isalpha((unsigned char)*System)) goto notnumber; /* * System name is really a phone number... * Copy the number then stomp on the original (in case the number * is private, we don't want 'ps' or 'w' to find it). */ if (strlen(System) > sizeof PNbuf - 1) { errx(1, "phone number too long (max = %d bytes)", (int)sizeof(PNbuf) - 1); } (void)strlcpy(PNbuf, System, sizeof(PNbuf)); for (p = System; *p; p++) *p = '\0'; PN = PNbuf; (void)snprintf(sbuf, sizeof sbuf, "tip%d", (int)BR); System = sbuf; notnumber: (void)signal(SIGINT, cleanup); (void)signal(SIGQUIT, cleanup); (void)signal(SIGHUP, cleanup); (void)signal(SIGTERM, cleanup); if ((i = hunt(System)) == 0) { errx(3, "all ports busy"); } if (i == -1) { errx(3, "link down"); } setbuf(stdout, NULL); /* * Kludge, their's no easy way to get the initialization * in the right order, so force it here */ if ((PH = getenv("PHONES")) == NULL) PH = path_phones; vinit(); /* init variables */ setparity("none"); /* set the parity table */ /* * Hardwired connections require the * line speed set before they make any transmissions * (this is particularly true of things like a DF03-AC) */ if (HW) { if (ttysetup((speed_t)number(value(BAUDRATE))) != 0) { errx(3, "bad baud rate %d", (int)number(value(BAUDRATE))); } } if ((q = tip_connect()) != NULL) { errx(1, "\07%s\n[EOT]", q); } if (!HW) { if (ttysetup((speed_t)number(value(BAUDRATE))) != 0) { errx(3, "bad baud rate %d", (int)number(value(BAUDRATE))); } } cucommon: /* * From here down the code is shared with * the "cu" version of tip. */ /* * Direct connections with no carrier require using O_NONBLOCK on * open, but we don't want to keep O_NONBLOCK after open because it * will cause busy waits. */ if (DC && ((fcarg = fcntl(FD, F_GETFL, 0)) < 0 || fcntl(FD, F_SETFL, fcarg & ~O_NONBLOCK) < 0)) { err(1, "can't clear O_NONBLOCK"); } (void)tcgetattr(0, &defterm); term = defterm; term.c_lflag &= ~(ICANON|IEXTEN|ECHO); term.c_iflag &= ~(INPCK|ICRNL); term.c_oflag &= ~OPOST; term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 0; defchars = term; term.c_cc[VINTR] = term.c_cc[VQUIT] = term.c_cc[VSUSP] = term.c_cc[VDSUSP] = term.c_cc[VDISCARD] = term.c_cc[VLNEXT] = _POSIX_VDISABLE; raw(); (void)pipe(attndes); (void)pipe(fildes); (void)pipe(repdes); (void)signal(SIGALRM, alrmtimeout); /* * Everything's set up now: * connection established (hardwired or dialup) * line conditioned (baud rate, mode, etc.) * internal data structures (variables) * so, fork one process for local side and one for remote. */ (void)printf("%s", cumode ? "Connected\r\n" : "\07connected\r\n"); switch (pid = fork()) { default: tipin(); break; case 0: tipout(); break; case -1: err(1, "can't fork"); } /*NOTREACHED*/ exit(0); /* XXX: pacify gcc */ }
int main(int argc, char **argv) { krb5_error_code ret; krb5_context context; krb5_auth_context auth_context; void *kadm_handle; kadm5_server_context *server_context; kadm5_config_params conf; int master_fd; krb5_ccache ccache; krb5_principal server; char **files; int optidx = 0; time_t reconnect_min; time_t backoff; time_t reconnect_max; time_t reconnect; time_t before = 0; const char *master; setprogname(argv[0]); if(getarg(args, num_args, argc, argv, &optidx)) usage(1); if(help_flag) usage(0); if(version_flag) { print_version(NULL); exit(0); } ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); setup_signal(); if (config_file == NULL) { asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context)); if (config_file == NULL) errx(1, "out of memory"); } ret = krb5_prepend_config_files_default(config_file, &files); if (ret) krb5_err(context, 1, ret, "getting configuration files"); ret = krb5_set_config_files(context, files); krb5_free_config_files(files); if (ret) krb5_err(context, 1, ret, "reading configuration files"); argc -= optidx; argv += optidx; if (argc != 1) usage(1); master = argv[0]; #ifdef SUPPORT_DETACH if (detach_from_console) daemon(0, 0); #endif pidfile (NULL); krb5_openlog (context, "ipropd-slave", &log_facility); krb5_set_warn_dest(context, log_facility); ret = krb5_kt_register(context, &hdb_kt_ops); if(ret) krb5_err(context, 1, ret, "krb5_kt_register"); time_before_lost = parse_time (server_time_lost, "s"); if (time_before_lost < 0) krb5_errx (context, 1, "couldn't parse time: %s", server_time_lost); memset(&conf, 0, sizeof(conf)); if(realm) { conf.mask |= KADM5_CONFIG_REALM; conf.realm = realm; } ret = kadm5_init_with_password_ctx (context, KADM5_ADMIN_SERVICE, NULL, KADM5_ADMIN_SERVICE, &conf, 0, 0, &kadm_handle); if (ret) krb5_err (context, 1, ret, "kadm5_init_with_password_ctx"); server_context = (kadm5_server_context *)kadm_handle; ret = kadm5_log_init (server_context); if (ret) krb5_err (context, 1, ret, "kadm5_log_init"); get_creds(context, keytab_str, &ccache, master); ret = krb5_sname_to_principal (context, master, IPROP_NAME, KRB5_NT_SRV_HST, &server); if (ret) krb5_err (context, 1, ret, "krb5_sname_to_principal"); auth_context = NULL; master_fd = -1; krb5_appdefault_time(context, config_name, NULL, "reconnect-min", 10, &reconnect_min); krb5_appdefault_time(context, config_name, NULL, "reconnect-max", 300, &reconnect_max); krb5_appdefault_time(context, config_name, NULL, "reconnect-backoff", 10, &backoff); reconnect = reconnect_min; while (!exit_flag) { time_t now, elapsed; int connected = FALSE; now = time(NULL); elapsed = now - before; if (elapsed < reconnect) { time_t left = reconnect - elapsed; krb5_warnx(context, "sleeping %d seconds before " "retrying to connect", (int)left); sleep(left); } before = now; master_fd = connect_to_master (context, master, port_str); if (master_fd < 0) goto retry; reconnect = reconnect_min; if (auth_context) { krb5_auth_con_free(context, auth_context); auth_context = NULL; krb5_cc_destroy(context, ccache); get_creds(context, keytab_str, &ccache, master); } ret = krb5_sendauth (context, &auth_context, &master_fd, IPROP_VERSION, NULL, server, AP_OPTS_MUTUAL_REQUIRED, NULL, NULL, ccache, NULL, NULL, NULL); if (ret) { krb5_warn (context, ret, "krb5_sendauth"); goto retry; } krb5_warnx(context, "ipropd-slave started at version: %ld", (long)server_context->log_context.version); ret = ihave (context, auth_context, master_fd, server_context->log_context.version); if (ret) goto retry; connected = TRUE; while (connected && !exit_flag) { krb5_data out; krb5_storage *sp; int32_t tmp; fd_set readset; struct timeval to; #ifndef NO_LIMIT_FD_SETSIZE if (master_fd >= FD_SETSIZE) krb5_errx (context, 1, "fd too large"); #endif FD_ZERO(&readset); FD_SET(master_fd, &readset); to.tv_sec = time_before_lost; to.tv_usec = 0; ret = select (master_fd + 1, &readset, NULL, NULL, &to); if (ret < 0) { if (errno == EINTR) continue; else krb5_err (context, 1, errno, "select"); } if (ret == 0) krb5_errx (context, 1, "server didn't send a message " "in %d seconds", time_before_lost); ret = krb5_read_priv_message(context, auth_context, &master_fd, &out); if (ret) { krb5_warn (context, ret, "krb5_read_priv_message"); connected = FALSE; continue; } sp = krb5_storage_from_mem (out.data, out.length); krb5_ret_int32 (sp, &tmp); switch (tmp) { case FOR_YOU : receive (context, sp, server_context); ret = ihave (context, auth_context, master_fd, server_context->log_context.version); if (ret) connected = FALSE; break; case TELL_YOU_EVERYTHING : ret = receive_everything (context, master_fd, server_context, auth_context); if (ret) connected = FALSE; break; case ARE_YOU_THERE : send_im_here (context, master_fd, auth_context); break; case NOW_YOU_HAVE : case I_HAVE : case ONE_PRINC : case I_AM_HERE : default : krb5_warnx (context, "Ignoring command %d", tmp); break; } krb5_storage_free (sp); krb5_data_free (&out); } retry: if (connected == FALSE) krb5_warnx (context, "disconnected for server"); if (exit_flag) krb5_warnx (context, "got an exit signal"); if (master_fd >= 0) close(master_fd); reconnect += backoff; if (reconnect > reconnect_max) reconnect = reconnect_max; } if (0); #ifndef NO_SIGXCPU else if(exit_flag == SIGXCPU) krb5_warnx(context, "%s CPU time limit exceeded", getprogname()); #endif else if(exit_flag == SIGINT || exit_flag == SIGTERM) krb5_warnx(context, "%s terminated", getprogname()); else krb5_warnx(context, "%s unexpected exit reason: %ld", getprogname(), (long)exit_flag); return 0; }
static void usage (void) { fprintf(stderr, "usage: %s [-l lcid | -L] [-phZ]\n", getprogname()); exit (EX_USAGE); }
void usage(void) { fprintf(stderr, "usage: %s catfile msgfile ...\n", getprogname()); exit(1); }
void usage(void) { (void)fprintf(stderr, "usage: %s [-l] [--] [# ...]\n", getprogname()); exit(1); }
/* * Periodically pat the watchdog, preventing it from firing. */ int main(int argc, char *argv[]) { struct rtprio rtp; struct pidfh *pfh; pid_t otherpid; if (getuid() != 0) errx(EX_SOFTWARE, "not super user"); parseargs(argc, argv); if (do_syslog) openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR, LOG_DAEMON); rtp.type = RTP_PRIO_REALTIME; rtp.prio = 0; if (rtprio(RTP_SET, 0, &rtp) == -1) err(EX_OSERR, "rtprio"); if (!is_dry_run && watchdog_init() == -1) errx(EX_SOFTWARE, "unable to initialize watchdog"); if (is_daemon) { if (watchdog_onoff(1) == -1) err(EX_OSERR, "patting the dog"); pfh = pidfile_open(pidfile, 0600, &otherpid); if (pfh == NULL) { if (errno == EEXIST) { watchdog_onoff(0); errx(EX_SOFTWARE, "%s already running, pid: %d", getprogname(), otherpid); } warn("Cannot open or create pidfile"); } if (debugging == 0 && daemon(0, 0) == -1) { watchdog_onoff(0); pidfile_remove(pfh); err(EX_OSERR, "daemon"); } signal(SIGHUP, SIG_IGN); signal(SIGINT, sighandler); signal(SIGTERM, sighandler); pidfile_write(pfh); if (madvise(0, 0, MADV_PROTECT) != 0) warn("madvise failed"); if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0) warn("mlockall failed"); watchdog_loop(); /* exiting */ pidfile_remove(pfh); return (EX_OK); } else { if (passive) timeout |= WD_PASSIVE; else timeout |= WD_ACTIVE; if (watchdog_patpat(timeout) < 0) err(EX_OSERR, "patting the dog"); return (EX_OK); } }
int main(int argc, const char **argv) { struct partition_metadata *md; const char *progname, *prompt; struct partedit_item *items = NULL; struct gmesh mesh; int i, op, nitems, nscroll; int error; progname = getprogname(); if (strcmp(progname, "sade") == 0) sade_mode = 1; TAILQ_INIT(&part_metadata); init_fstab_metadata(); init_dialog(stdin, stdout); if (!sade_mode) dialog_vars.backtitle = __DECONST(char *, "FreeBSD Installer"); dialog_vars.item_help = TRUE; nscroll = i = 0; /* Revert changes on SIGINT */ signal(SIGINT, sigint_handler); if (strcmp(progname, "autopart") == 0) { /* Guided */ prompt = "Please review the disk setup. When complete, press " "the Finish button."; /* Experimental ZFS autopartition support */ if (argc > 1 && strcmp(argv[1], "zfs") == 0) { part_wizard("zfs"); } else { part_wizard("ufs"); } } else if (strcmp(progname, "scriptedpart") == 0) { error = scripted_editor(argc, argv); prompt = NULL; if (error != 0) { end_dialog(); return (error); } } else { prompt = "Create partitions for FreeBSD. No changes will be " "made until you select Finish."; } /* Show the part editor either immediately, or to confirm wizard */ while (prompt != NULL) { dlg_clear(); dlg_put_backtitle(); error = geom_gettree(&mesh); if (error == 0) items = read_geom_mesh(&mesh, &nitems); if (error || items == NULL) { dialog_msgbox("Error", "No disks found. If you need to " "install a kernel driver, choose Shell at the " "installation menu.", 0, 0, TRUE); break; } get_mount_points(items, nitems); if (i >= nitems) i = nitems - 1; op = diskeditor_show("Partition Editor", prompt, items, nitems, &i, &nscroll); switch (op) { case 0: /* Create */ gpart_create((struct gprovider *)(items[i].cookie), NULL, NULL, NULL, NULL, 1); break; case 1: /* Delete */ gpart_delete((struct gprovider *)(items[i].cookie)); break; case 2: /* Modify */ gpart_edit((struct gprovider *)(items[i].cookie)); break; case 3: /* Revert */ gpart_revert_all(&mesh); while ((md = TAILQ_FIRST(&part_metadata)) != NULL) { if (md->fstab != NULL) { free(md->fstab->fs_spec); free(md->fstab->fs_file); free(md->fstab->fs_vfstype); free(md->fstab->fs_mntops); free(md->fstab->fs_type); free(md->fstab); } if (md->newfs != NULL) free(md->newfs); free(md->name); TAILQ_REMOVE(&part_metadata, md, metadata); free(md); } init_fstab_metadata(); break; case 4: /* Auto */ part_wizard("ufs"); break; } error = 0; if (op == 5) { /* Finished */ dialog_vars.ok_label = __DECONST(char *, "Commit"); dialog_vars.extra_label = __DECONST(char *, "Revert & Exit"); dialog_vars.extra_button = TRUE; dialog_vars.cancel_label = __DECONST(char *, "Back"); op = dialog_yesno("Confirmation", "Your changes will " "now be written to disk. If you have chosen to " "overwrite existing data, it will be PERMANENTLY " "ERASED. Are you sure you want to commit your " "changes?", 0, 0); dialog_vars.ok_label = NULL; dialog_vars.extra_button = FALSE; dialog_vars.cancel_label = NULL; if (op == 0 && validate_setup()) { /* Save */ error = apply_changes(&mesh); if (!error) apply_workaround(&mesh); break; } else if (op == 3) { /* Quit */ gpart_revert_all(&mesh); error = -1; break; } } geom_deletetree(&mesh); free(items); }
FcChar8 *FcGetPrgname(void) { FcChar8 *prgname; retry: prgname = fc_atomic_ptr_get(&default_prgname); if (!prgname) { #ifdef _WIN32 char buf[MAX_PATH + 1]; /* TODO This is ASCII-only; fix it. */ if (GetModuleFileNameA(GetModuleHandle(NULL), buf, sizeof(buf) / sizeof(buf[0])) > 0) { char *p; unsigned int len; p = strrchr(buf, '\\'); if (p) p++; else p = buf; len = strlen(p); if (len > 4 && 0 == strcmp(p + len - 4, ".exe")) { len -= 4; buf[len] = '\0'; } prgname = FcStrdup(p); } #elif defined(HAVE_GETPROGNAME) const char *q = getprogname(); if (q) prgname = FcStrdup(q); else prgname = FcStrdup(""); #else #if defined(HAVE_GETEXECNAME) const char *p = getexecname(); #elif defined(HAVE_READLINK) char buf[PATH_MAX + 1]; int len; char *p = NULL; len = readlink("/proc/self/exe", buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; p = buf; } #else char *p = NULL; #endif if (p) { char *r = strrchr(p, '/'); if (r) r++; else r = p; prgname = FcStrdup(r); } if (!prgname) prgname = FcStrdup(""); #endif if (!fc_atomic_ptr_cmpexch(&default_prgname, NULL, prgname)) { free(prgname); goto retry; } } if (prgname && !prgname[0]) return NULL; return prgname; }
__private_extern__ Boolean __SCPreferencesCreate_helper(SCPreferencesRef prefs) { CFDataRef data = NULL; CFMutableDictionaryRef info; CFNumberRef num; Boolean ok; SCPreferencesPrivateRef prefsPrivate = (SCPreferencesPrivateRef)prefs; uint32_t status = kSCStatusOK; CFStringRef str; uint32_t pid = getpid(); // start helper ok = _SCHelperOpen(prefsPrivate->authorizationData, &prefsPrivate->helper_port); if (!ok) { goto fail; } // create a dictionary of information to pass to the helper info = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); // save prefsID if (prefsPrivate->prefsID != NULL) { CFDictionarySetValue(info, CFSTR("prefsID"), prefsPrivate->prefsID); } // save options if (prefsPrivate->options != NULL) { CFDictionarySetValue(info, CFSTR("options"), prefsPrivate->options); } // save preferences session "name" CFDictionarySetValue(info, CFSTR("name"), prefsPrivate->name); // save PID num = CFNumberCreate(NULL, kCFNumberSInt32Type, &pid); CFDictionarySetValue(info, CFSTR("PID"), num); CFRelease(num); // save process name str = CFStringCreateWithCString(NULL, getprogname(), kCFStringEncodingUTF8); CFDictionarySetValue(info, CFSTR("PROC_NAME"), str); CFRelease(str); // serialize the info ok = _SCSerialize(info, &data, NULL, NULL); CFRelease(info); if (data == NULL || !ok) { goto fail; } // have the helper "open" the prefs ok = _SCHelperExec(prefsPrivate->helper_port, SCHELPER_MSG_PREFS_OPEN, data, &status, NULL); if (data != NULL) CFRelease(data); if (!ok) { goto fail; } if (status != kSCStatusOK) { goto error; } return TRUE; fail : // close helper if (prefsPrivate->helper_port != MACH_PORT_NULL) { _SCHelperClose(&prefsPrivate->helper_port); } status = kSCStatusAccessError; error : // return error _SCErrorSet(status); return FALSE; }
struct pidfh * pidfile_open(const char *path, mode_t mode, pid_t *pidptr) { struct pidfh *pfh; struct stat sb; int error, fd, len, count; struct timespec rqtp; pfh = malloc(sizeof(*pfh)); if (pfh == NULL) return (NULL); if (path == NULL) len = snprintf(pfh->pf_path, sizeof(pfh->pf_path), "/var/run/%s.pid", getprogname()); else len = snprintf(pfh->pf_path, sizeof(pfh->pf_path), "%s", path); if (len >= (int)sizeof(pfh->pf_path)) { free(pfh); errno = ENAMETOOLONG; return (NULL); } /* * Open the PID file and obtain exclusive lock. * We truncate PID file here only to remove old PID immediatelly, * PID file will be truncated again in pidfile_write(), so * pidfile_write() can be called multiple times. */ fd = flopen(pfh->pf_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NONBLOCK, mode); if (fd == -1) { if (errno == EWOULDBLOCK) { if (pidptr == NULL) { errno = EEXIST; } else { count = 20; rqtp.tv_sec = 0; rqtp.tv_nsec = 5000000; for (;;) { errno = pidfile_read(pfh->pf_path, pidptr); if (errno != EAGAIN || --count == 0) break; nanosleep(&rqtp, 0); } if (errno == EAGAIN) *pidptr = -1; if (errno == 0 || errno == EAGAIN) errno = EEXIST; } } free(pfh); return (NULL); } /* * Remember file information, so in pidfile_write() we are sure we write * to the proper descriptor. */ if (fstat(fd, &sb) == -1) { error = errno; unlink(pfh->pf_path); close(fd); free(pfh); errno = error; return (NULL); } pfh->pf_fd = fd; pfh->pf_dev = sb.st_dev; pfh->pf_ino = sb.st_ino; return (pfh); }
static int scan(FILE *fp, const char *name, bool quiet) { int c; bool hasid = false; bool subversion = false; analyzer_states state = INIT; struct sbuf *id = sbuf_new_auto(); locale_t l; l = newlocale(LC_ALL_MASK, "C", NULL); if (name != NULL) printf("%s:\n", name); while ((c = fgetc(fp)) != EOF) { switch (state) { case INIT: if (c == '$') { /* Transit to DELIM_SEEN if we see $ */ state = DELIM_SEEN; } else { /* Otherwise, stay in INIT state */ continue; } break; case DELIM_SEEN: if (isalpha_l(c, l)) { /* Transit to KEYWORD if we see letter */ sbuf_clear(id); sbuf_putc(id, '$'); sbuf_putc(id, c); state = KEYWORD; continue; } else if (c == '$') { /* Or, stay in DELIM_SEEN if more $ */ continue; } else { /* Otherwise, transit back to INIT */ state = INIT; } break; case KEYWORD: sbuf_putc(id, c); if (isalpha_l(c, l)) { /* * Stay in KEYWORD if additional letter is seen */ continue; } else if (c == ':') { /* * See ':' for the first time, transit to * PUNC_SEEN. */ state = PUNC_SEEN; subversion = false; } else if (c == '$') { /* * Incomplete ident. Go back to DELIM_SEEN * state because we see a '$' which could be * the beginning of a keyword. */ state = DELIM_SEEN; } else { /* * Go back to INIT state otherwise. */ state = INIT; } break; case PUNC_SEEN: case PUNC_SEEN_SVN: sbuf_putc(id, c); switch (c) { case ':': /* * If we see '::' (seen : in PUNC_SEEN), * activate subversion treatment and transit * to PUNC_SEEN_SVN state. * * If more than two :'s were seen, the ident * is invalid and we would therefore go back * to INIT state. */ if (state == PUNC_SEEN) { state = PUNC_SEEN_SVN; subversion = true; } else { state = INIT; } break; case ' ': /* * A space after ':' or '::' indicates we are at the * last component of potential ident. */ state = TEXT; break; default: /* All other characters are invalid */ state = INIT; break; } break; case TEXT: sbuf_putc(id, c); if (iscntrl_l(c, l)) { /* Control characters are not allowed in this state */ state = INIT; } else if (c == '$') { sbuf_finish(id); /* * valid ident should end with a space. * * subversion extension uses '#' to indicate that * the keyword expansion have exceeded the fixed * width, so it is also permitted if we are in * subversion mode. No length check is enforced * because GNU RCS ident(1) does not do it either. */ c = sbuf_data(id)[sbuf_len(id) - 2]; if (c == ' ' || (subversion && c == '#')) { printf(" %s\n", sbuf_data(id)); hasid = true; } state = INIT; } /* Other characters: stay in the state */ break; } } sbuf_delete(id); freelocale(l); if (!hasid) { if (!quiet) fprintf(stderr, "%s warning: no id keywords in %s\n", getprogname(), name ? name : "standard input"); return (EXIT_FAILURE); } return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct kevent kev; Action anAction = kActionStart; int ch, r, kq = kqueue(); assert(kq != -1); EV_SET(&kev, SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, 0); r = kevent(kq, &kev, 1, NULL, 0, NULL); assert(r != -1); signal(SIGTERM, dummy_sig); while ((ch = getopt(argc, argv, "gvxirdDqn?")) != -1) { switch (ch) { case 'v': gVerboseFlag = true; break; case 'x': case 'g': case 'r': case 'q': break; case 'd': case 'D': gDebugFlag = true; break; case 'n': gNoRunFlag = true; break; case '?': default: usage(); break; } } argc -= optind; argv += optind; if (argc > 2) { usage(); } openlog(getprogname(), LOG_PID|LOG_CONS|(gDebugFlag ? LOG_PERROR : 0), LOG_DAEMON); if (gDebugFlag) { setlogmask(LOG_UPTO(LOG_DEBUG)); } else if (gVerboseFlag) { setlogmask(LOG_UPTO(LOG_INFO)); } else { setlogmask(LOG_UPTO(LOG_NOTICE)); } if (!gNoRunFlag && (getuid() != 0)) { syslog(LOG_ERR, "must be root to run"); exit(EXIT_FAILURE); } if (argc > 0) { if (strcmp(argv[0], "start") == 0) { anAction = kActionStart; } else if (strcmp(argv[0], "stop") == 0) { anAction = kActionStop; } else if (strcmp(argv[0], "restart") == 0) { anAction = kActionRestart; } else { usage(); } } if (argc == 2) { exit(system_starter(anAction, argv[1])); } unlink(kFixerPath); mach_timespec_t w = { 600, 0 }; kern_return_t kr; /* * Too many old StartupItems had implicit dependancies on "Network" via * other StartupItems that are now no-ops. * * SystemStarter is not on the critical path for boot up, so we'll * stall here to deal with this legacy dependancy problem. */ if ((kr = IOKitWaitQuiet(kIOMasterPortDefault, &w)) != kIOReturnSuccess) { syslog(LOG_NOTICE, "IOKitWaitQuiet: %d\n", kr); } fwexec("/usr/sbin/ipconfig", "waitall", NULL); autodiskmount(); /* wait for Disk Arbitration to report idle */ system_starter(kActionStart, NULL); if (StartupItemSecurityCheck("/etc/rc.local")) { fwexec(_PATH_BSHELL, "/etc/rc.local", NULL); } CFNotificationCenterPostNotificationWithOptions( CFNotificationCenterGetDistributedCenter(), CFSTR("com.apple.startupitems.completed"), NULL, NULL, kCFNotificationDeliverImmediately | kCFNotificationPostToAllSessions); r = kevent(kq, NULL, 0, &kev, 1, NULL); assert(r != -1); assert(kev.filter == EVFILT_SIGNAL && kev.ident == SIGTERM); if (StartupItemSecurityCheck("/etc/rc.shutdown.local")) { fwexec(_PATH_BSHELL, "/etc/rc.shutdown.local", NULL); } system_starter(kActionStop, NULL); exit(EXIT_SUCCESS); }
Error OS_Unix::execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id,String* r_pipe,int *r_exitcode) { if (p_blocking && r_pipe) { String argss; argss="\""+p_path+"\""; for(int i=0;i<p_arguments.size();i++) { argss+=String(" \"")+p_arguments[i]+"\""; } argss+=" 2>/dev/null"; //silence stderr FILE* f=popen(argss.utf8().get_data(),"r"); ERR_FAIL_COND_V(!f,ERR_CANT_OPEN); char buf[65535]; while(fgets(buf,65535,f)) { (*r_pipe)+=buf; } int rv = pclose(f); if (r_exitcode) *r_exitcode=rv; return OK; } pid_t pid = fork(); ERR_FAIL_COND_V(pid<0,ERR_CANT_FORK); if (pid==0) { // is child Vector<CharString> cs; cs.push_back(p_path.utf8()); for(int i=0;i<p_arguments.size();i++) cs.push_back(p_arguments[i].utf8()); Vector<char*> args; for(int i=0;i<cs.size();i++) args.push_back((char*)cs[i].get_data());// shitty C cast args.push_back(0); #ifdef __FreeBSD__ if(p_path.find("/")) { // exec name contains path so use it execv(p_path.utf8().get_data(),&args[0]); }else{ // use program name and search through PATH to find it execvp(getprogname(),&args[0]); } #else execv(p_path.utf8().get_data(),&args[0]); #endif // still alive? something failed.. fprintf(stderr,"**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n",p_path.utf8().get_data()); abort(); } if (p_blocking) { int status; pid_t rpid = waitpid(pid,&status,0); if (r_exitcode) *r_exitcode=WEXITSTATUS(status); } else { if (r_child_id) *r_child_id=pid; } return OK; }
int main(int argc, char *argv[]) { struct stat sb; size_t len; #ifdef __minix int ch; #else int ch, mib[2]; #endif /* def __minix */ char *p, *std, path[MAXPATHLEN]; const char *t; int which = strcmp(getprogname(), "which") == 0; int useenvpath = which, found = 0; gid_t egid = getegid(); uid_t euid = geteuid(); /* To make access(2) do what we want */ if (setgid(egid) == -1) err(1, "Can't set gid to %lu", (unsigned long)egid); if (setuid(euid) == -1) err(1, "Can't set uid to %lu", (unsigned long)euid); while ((ch = getopt(argc, argv, "ap")) != -1) switch (ch) { case 'a': which = 0; break; case 'p': useenvpath = 1; /* use environment for PATH */ break; case '?': default: usage(); } argc -= optind; argv += optind; if (argc == 0) usage(); if (useenvpath) { if ((std = getenv("PATH")) == NULL) errx(1, "PATH environment variable is not set"); } else { /* Retrieve the standard path. */ #ifdef __minix /* Note: This path is currently defined here and should probably be defined here, in "ash" or in "sh". To minimize code changes, the path has been hard coded into this file. However, if this path needs to be used in other ported programs, please move this define to <minix/paths.h> and add the include to this file and all files that use _PATH_USER_CS_PATH. */ #define _PATH_USER_CS_PATH "/usr/X11R7/sbin:/usr/local/sbin:/usr/pkg/sbin:/usr/sbin:/sbin:/usr/X11R7/bin:/usr/local/bin:/usr/pkg/bin:/usr/bin:/bin:/usr/games" std = strdup(_PATH_USER_CS_PATH); #else mib[0] = CTL_USER; mib[1] = USER_CS_PATH; if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) err(1, "sysctl: user.cs_path"); if (len == 0) errx(1, "sysctl: user.cs_path (zero length)"); if ((std = malloc(len)) == NULL) err(1, NULL); if (sysctl(mib, 2, std, &len, NULL, 0) == -1) err(1, "sysctl: user.cs_path"); #endif /* def __minix */ } /* For each path, for each program... */ for (; *argv; ++argv) { if (**argv == '/') { if (stat(*argv, &sb) == -1) continue; /* next argv */ if (!S_ISREG(sb.st_mode)) continue; /* next argv */ if (access(*argv, X_OK) == -1) continue; /* next argv */ (void)printf("%s\n", *argv); found++; if (which) continue; /* next argv */ } else for (p = std; p; ) { t = p; if ((p = strchr(p, ':')) != NULL) { *p = '\0'; if (t == p) t = "."; } else if (strlen(t) == 0) t = "."; (void)snprintf(path, sizeof(path), "%s/%s", t, *argv); len = snprintf(path, sizeof(path), "%s/%s", t, *argv); if (p) *p++ = ':'; if (len >= sizeof(path)) continue; /* next p */ if (stat(path, &sb) == -1) continue; /* next p */ if (!S_ISREG(sb.st_mode)) continue; /* next p */ if (access(path, X_OK) == -1) continue; /* next p */ (void)printf("%s\n", path); found++; if (which) break; /* next argv */ } } return ((found == 0) ? 3 : ((found >= argc) ? 0 : 2)); }
void usage(void) { fprintf(stderr, "Usage: %s dir\n", getprogname()); exit(1); }
int main(int argc, char *argv[]) { int c, tout, flags, flush, restore; const char *spath, **blsock; size_t nblsock, maxblsock; setprogname(argv[0]); spath = NULL; blsock = NULL; maxblsock = nblsock = 0; flush = 0; restore = 0; tout = 0; flags = O_RDWR|O_EXCL|O_CLOEXEC; while ((c = getopt(argc, argv, "C:c:D:dfP:rR:s:t:v")) != -1) { switch (c) { case 'C': controlprog = optarg; break; case 'c': configfile = optarg; break; case 'D': dbfile = optarg; break; case 'd': debug++; break; case 'f': flush++; break; case 'P': spath = optarg; break; case 'R': rulename = optarg; break; case 'r': restore++; break; case 's': if (nblsock >= maxblsock) { maxblsock += 10; void *p = realloc(blsock, sizeof(*blsock) * maxblsock); if (p == NULL) err(EXIT_FAILURE, "Can't allocate memory for %zu sockets", maxblsock); blsock = p; } blsock[nblsock++] = optarg; break; case 't': tout = atoi(optarg) * 1000; break; case 'v': vflag++; break; default: usage(c); } } argc -= optind; if (argc) usage(0); signal(SIGHUP, sighup); signal(SIGINT, sigdone); signal(SIGQUIT, sigdone); signal(SIGTERM, sigdone); signal(SIGUSR1, sigusr1); signal(SIGUSR2, sigusr2); openlog(getprogname(), LOG_PID, LOG_DAEMON); if (debug) { lfun = dlog; if (tout == 0) tout = 5000; } else { if (tout == 0) tout = 15000; } update_interfaces(); conf_parse(configfile); if (flush) { rules_flush(); flags |= O_TRUNC; } struct pollfd *pfd = NULL; bl_t *bl = NULL; size_t nfd = 0; size_t maxfd = 0; for (size_t i = 0; i < nblsock; i++) addfd(&pfd, &bl, &nfd, &maxfd, blsock[i]); free(blsock); if (spath) { FILE *fp = fopen(spath, "r"); char *line; if (fp == NULL) err(EXIT_FAILURE, "Can't open `%s'", spath); for (; (line = fparseln(fp, NULL, NULL, NULL, 0)) != NULL; free(line)) addfd(&pfd, &bl, &nfd, &maxfd, line); fclose(fp); } if (nfd == 0) addfd(&pfd, &bl, &nfd, &maxfd, _PATH_BLSOCK); state = state_open(dbfile, flags, 0600); if (state == NULL) state = state_open(dbfile, flags | O_CREAT, 0600); if (state == NULL) return EXIT_FAILURE; if (restore) rules_restore(); if (!debug) { if (daemon(0, 0) == -1) err(EXIT_FAILURE, "daemon failed"); if (pidfile(NULL) == -1) err(EXIT_FAILURE, "Can't create pidfile"); } for (size_t t = 0; !done; t++) { if (readconf) { readconf = 0; conf_parse(configfile); } switch (poll(pfd, (nfds_t)nfd, tout)) { case -1: if (errno == EINTR) continue; (*lfun)(LOG_ERR, "poll (%m)"); return EXIT_FAILURE; case 0: state_sync(state); break; default: for (size_t i = 0; i < nfd; i++) if (pfd[i].revents & POLLIN) process(bl[i]); } if (t % 100 == 0) state_sync(state); if (t % 10000 == 0) update_interfaces(); update(); } state_close(state); return 0; }
int main(int argc, char **argv, char **envp) { FILE *config; char *line, *cp, *from, *to, *ap; const char *progname; size_t len, lineno = 0; int i; struct arglist al; /* change progname to mailwrapper so we get sensible error messages */ progname = getprogname(); setprogname("mailwrapper"); if ((config = fopen(_PATH_MAILERCONF, "r")) == NULL) { openlog("mailwrapper", LOG_PID, LOG_MAIL); syslog(LOG_INFO, "can't open %s, using %s as default MTA", _PATH_MAILERCONF, _PATH_DEFAULTMTA); closelog(); execve(_PATH_DEFAULTMTA, argv, envp); err(1, "cannot exec %s", _PATH_DEFAULTMTA); /*NOTREACHED*/ } initarg(&al); addarg(&al, argv[0], 0); for (;;) { if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL) { if (feof(config)) errx(1, "no mapping in %s", _PATH_MAILERCONF); err(1, NULL); } #define WS " \t\n" cp = line; cp += strspn(cp, WS); if (cp[0] == '\0') { /* empty line */ free(line); continue; } if ((from = strsep(&cp, WS)) == NULL) goto parse_error; cp += strspn(cp, WS); if ((to = strsep(&cp, WS)) == NULL) goto parse_error; if (strcmp(from, progname) == 0) { for (ap = strsep(&cp, WS); ap != NULL; ap = strsep(&cp, WS)) if (*ap) addarg(&al, ap, 0); break; } free(line); } fclose(config); for (i = 1; i < argc; i++) addarg(&al, argv[i], 0); addarg(&al, NULL, 0); execve(to, al.argv, envp); err(1, "cannot exec %s", to); /*NOTREACHED*/ parse_error: errx(1, "parse error in %s at line %lu", _PATH_MAILERCONF, (u_long)lineno); /*NOTREACHED*/ }
int main(int argc, char **argv) { int ofd, ifd; char *catfile = NULL; int c; #define DEPRECATEDMSG 1 #ifdef DEPRECATEDMSG while ((c = getopt(argc, argv, "new")) != -1) { #else while ((c = getopt(argc, argv, "")) != -1) { #endif switch (c) { #ifdef DEPRECATEDMSG case 'n': fprintf(stderr, "WARNING: Usage of \"-new\" argument is deprecated.\n"); case 'e': case 'w': break; #endif case '?': default: usage(); /* NOTREACHED */ } } argc -= optind; argv += optind; if (argc < 2) { usage(); /* NOTREACHED */ } catfile = *argv++; for (; *argv; argv++) { if ((ifd = open(*argv, O_RDONLY)) < 0) err(1, "Unable to read %s", *argv); MCParse(ifd); close(ifd); } if ((ofd = open(catfile, O_WRONLY | O_TRUNC | O_CREAT, 0666)) < 0) err(1, "Unable to create a new %s", catfile); MCWriteCat(ofd); exit(0); } static void warning(const char *cptr, const char *msg) { fprintf(stderr, "%s: %s on line %ld\n", getprogname(), msg, lineno); fprintf(stderr, "%s\n", curline); if (cptr) { char *tptr; for (tptr = curline; tptr < cptr; ++tptr) putc(' ', stderr); fprintf(stderr, "^\n"); } }
/* See RFC 5280 section 4.2.1.6 for SubjectAltName details. */ int tls_check_subject_altname(struct tls *ctx, X509 *cert, const char *name) { STACK_OF(GENERAL_NAME) *altname_stack = NULL; union { struct in_addr ip4; struct in6_addr ip6; } addrbuf; int addrlen, type; int count, i; int rv = -1; altname_stack = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL); if (altname_stack == NULL) return -1; if (inet_pton(AF_INET, name, &addrbuf) == 1) { type = GEN_IPADD; addrlen = 4; } else if (inet_pton(AF_INET6, name, &addrbuf) == 1) { type = GEN_IPADD; addrlen = 16; } else { type = GEN_DNS; addrlen = 0; } count = sk_GENERAL_NAME_num(altname_stack); for (i = 0; i < count; i++) { GENERAL_NAME *altname; altname = sk_GENERAL_NAME_value(altname_stack, i); if (altname->type != type) continue; if (type == GEN_DNS) { unsigned char *data; int format, len; format = ASN1_STRING_type(altname->d.dNSName); if (format == V_ASN1_IA5STRING) { data = ASN1_STRING_data(altname->d.dNSName); len = ASN1_STRING_length(altname->d.dNSName); if (len < 0 || len != strlen(data)) { tls_set_error(ctx, "error verifying name '%s': " "NUL byte in subjectAltName, " "probably a malicious certificate", name); rv = -2; break; } /* * Per RFC 5280 section 4.2.1.6: * " " is a legal domain name, but that * dNSName must be rejected. */ if (strcmp(data, " ") == 0) { tls_set_error(ctx, "error verifying name '%s': " "a dNSName of \" \" must not be " "used", name); rv = -2; break; } if (tls_match_name(data, name) == 0) { rv = 0; break; } } else { #ifdef DEBUG fprintf(stdout, "%s: unhandled subjectAltName " "dNSName encoding (%d)\n", getprogname(), format); #endif } } else if (type == GEN_IPADD) { unsigned char *data; int datalen; datalen = ASN1_STRING_length(altname->d.iPAddress); data = ASN1_STRING_data(altname->d.iPAddress); if (datalen < 0) { tls_set_error(ctx, "Unexpected negative length for an " "IP address: %d", datalen); rv = -2; break; } /* * Per RFC 5280 section 4.2.1.6: * IPv4 must use 4 octets and IPv6 must use 16 octets. */ if (datalen == addrlen && memcmp(data, &addrbuf, addrlen) == 0) { rv = 0; break; } } } sk_GENERAL_NAME_pop_free(altname_stack, GENERAL_NAME_free); return rv; }
int event_callback(void *data, struct pkg_event *ev) { struct pkg *pkg = NULL; int *debug = data; (void) debug; const char *filename; struct pkg_event_conflict *cur_conflict; switch(ev->type) { case PKG_EVENT_ERRNO: warnx("%s(%s): %s", ev->e_errno.func, ev->e_errno.arg, strerror(ev->e_errno.no)); break; case PKG_EVENT_ERROR: warnx("%s", ev->e_pkg_error.msg); break; case PKG_EVENT_NOTICE: if (!quiet) warnx("%s", ev->e_pkg_notice.msg); break; case PKG_EVENT_DEVELOPER_MODE: warnx("DEVELOPER_MODE: %s", ev->e_pkg_error.msg); break; case PKG_EVENT_FETCHING: if (quiet || !isatty(fileno(stdin))) break; if (fetched == 0) { filename = strrchr(ev->e_fetching.url, '/'); if (filename != NULL) { filename++; } else { /* * We failed at being smart, so display * the entire url. */ filename = ev->e_fetching.url; } strlcpy(url, filename, sizeof(url)); start_progress_meter(url, ev->e_fetching.total, &fetched); } fetched = ev->e_fetching.done; if (ev->e_fetching.done == ev->e_fetching.total) { stop_progress_meter(); fetched = 0; } break; case PKG_EVENT_INSTALL_BEGIN: if (quiet) break; else { struct sbuf *msg; nbdone++; msg = sbuf_new_auto(); if (msg == NULL) { warn("sbuf_new_auto() failed"); break; } print_status_begin(msg); pkg = ev->e_install_begin.pkg; pkg_sbuf_printf(msg, "Installing %n-%v...", pkg, pkg); print_status_end(msg); } break; case PKG_EVENT_INSTALL_FINISHED: if (quiet) break; printf(" done\n"); if (pkg_has_message(ev->e_install_finished.pkg)) { if (messages == NULL) messages = sbuf_new_auto(); pkg_sbuf_printf(messages, "%M\n", ev->e_install_finished.pkg); } break; case PKG_EVENT_INTEGRITYCHECK_BEGIN: if (quiet) break; printf("Checking integrity..."); break; case PKG_EVENT_INTEGRITYCHECK_FINISHED: if (quiet) break; printf(" done\n"); break; case PKG_EVENT_INTEGRITYCHECK_CONFLICT: printf("\nConflict found on path %s between %s-%s(%s) and ", ev->e_integrity_conflict.pkg_path, ev->e_integrity_conflict.pkg_name, ev->e_integrity_conflict.pkg_version, ev->e_integrity_conflict.pkg_origin); cur_conflict = ev->e_integrity_conflict.conflicts; while (cur_conflict) { if (cur_conflict->next) printf("%s-%s(%s), ", cur_conflict->name, cur_conflict->version, cur_conflict->origin); else printf("%s-%s(%s)", cur_conflict->name, cur_conflict->version, cur_conflict->origin); cur_conflict = cur_conflict->next; } printf("\n"); break; case PKG_EVENT_DEINSTALL_BEGIN: if (quiet) break; else { struct sbuf *msg; nbdone++; msg = sbuf_new_auto(); if (msg == NULL) { warn("sbuf_new_auto() failed"); break; } print_status_begin(msg); pkg = ev->e_install_begin.pkg; pkg_sbuf_printf(msg, "Deleting %n-%v...", pkg, pkg); print_status_end(msg); } break; case PKG_EVENT_DEINSTALL_FINISHED: if (quiet) break; printf(" done\n"); break; case PKG_EVENT_UPGRADE_BEGIN: if (quiet) break; else { struct sbuf *msg; pkg = ev->e_upgrade_begin.pkg; nbdone++; msg = sbuf_new_auto(); if (msg == NULL) { warn("sbuf_new_auto() failed"); break; } print_status_begin(msg); switch (pkg_version_change(pkg)) { case PKG_DOWNGRADE: pkg_sbuf_printf(msg, "Downgrading %n from %V to %v...", pkg, pkg, pkg); break; case PKG_REINSTALL: pkg_sbuf_printf(msg, "Reinstalling %n-%V...", pkg, pkg); break; case PKG_UPGRADE: pkg_sbuf_printf(msg, "Upgrading %n from %V to %v...", pkg, pkg, pkg); break; } print_status_end(msg); } break; case PKG_EVENT_UPGRADE_FINISHED: if (quiet) break; printf(" done\n"); if (pkg_has_message(ev->e_upgrade_finished.pkg)) { if (messages == NULL) messages = sbuf_new_auto(); pkg_sbuf_printf(messages, "%M\n", ev->e_upgrade_finished.pkg); } break; case PKG_EVENT_LOCKED: pkg = ev->e_locked.pkg; pkg_fprintf(stderr, "\n%n-%v is locked and may not be modified\n", pkg, pkg); break; case PKG_EVENT_REQUIRED: pkg = ev->e_required.pkg; pkg_fprintf(stderr, "\n%n-%v is required by: %r%{%rn-%rv%| %}", pkg, pkg, pkg); if (ev->e_required.force == 1) fprintf(stderr, ", deleting anyway\n"); else fprintf(stderr, "\n"); break; case PKG_EVENT_ALREADY_INSTALLED: if (quiet) break; pkg = ev->e_already_installed.pkg; pkg_printf("%n-%v already installed\n", pkg, pkg); break; case PKG_EVENT_NOT_FOUND: printf("Package '%s' was not found in " "the repositories\n", ev->e_not_found.pkg_name); break; case PKG_EVENT_MISSING_DEP: fprintf(stderr, "missing dependency %s-%s\n", pkg_dep_name(ev->e_missing_dep.dep), pkg_dep_version(ev->e_missing_dep.dep)); break; case PKG_EVENT_NOREMOTEDB: fprintf(stderr, "Unable to open remote database \"%s\". " "Try running '%s update' first.\n", ev->e_remotedb.repo, getprogname()); break; case PKG_EVENT_NOLOCALDB: fprintf(stderr, "Local package database nonexistent!\n"); break; case PKG_EVENT_NEWPKGVERSION: newpkgversion = true; printf("New version of pkg detected; it needs to be " "installed first.\n"); break; case PKG_EVENT_FILE_MISMATCH: pkg = ev->e_file_mismatch.pkg; pkg_fprintf(stderr, "%n-%v: checksum mismatch for %S\n", pkg, pkg, pkg_file_path(ev->e_file_mismatch.file)); break; case PKG_EVENT_PLUGIN_ERRNO: warnx("%s: %s(%s): %s", pkg_plugin_get(ev->e_plugin_errno.plugin, PKG_PLUGIN_NAME), ev->e_plugin_errno.func, ev->e_plugin_errno.arg, strerror(ev->e_plugin_errno.no)); break; case PKG_EVENT_PLUGIN_ERROR: warnx("%s: %s", pkg_plugin_get(ev->e_plugin_error.plugin, PKG_PLUGIN_NAME), ev->e_plugin_error.msg); break; case PKG_EVENT_PLUGIN_INFO: if (quiet) break; printf("%s: %s\n", pkg_plugin_get(ev->e_plugin_info.plugin, PKG_PLUGIN_NAME), ev->e_plugin_info.msg); break; case PKG_EVENT_INCREMENTAL_UPDATE: if (!quiet) printf("Incremental update completed, %d packages " "processed:\n" "%d packages updated, %d removed and %d added.\n", ev->e_incremental_update.processed, ev->e_incremental_update.updated, ev->e_incremental_update.removed, ev->e_incremental_update.added); break; case PKG_EVENT_DEBUG: fprintf(stderr, "DBG(%d)> %s\n", ev->e_debug.level, ev->e_debug.msg); break; default: break; } return 0; }
int main(int argc, char **argv) { krb5_error_code ret; int optidx = 0; int exit_status = 0; setprogname (argv[0]); setlocale (LC_ALL, ""); bindtextdomain ("heimdal_kuser", HEIMDAL_LOCALEDIR); textdomain("heimdal_kuser"); ret = krb5_init_context(&kcc_context); if (ret == KRB5_CONFIG_BADFORMAT) errx (1, "krb5_init_context failed to parse configuration file"); else if (ret) errx(1, "krb5_init_context failed: %d", ret); /* * Support linking of kcc to commands */ if (!command_alias(getprogname())) { if (argc == 1) { sl_slc_help(commands, 0, NULL); return 1; } if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag) { print_version(NULL); exit(0); } } else { argv[0] = rk_UNCONST(getprogname()); } argc -= optidx; argv += optidx; if (argc != 0) { ret = sl_command(commands, argc, argv); if(ret == -1) krb5_warnx(kcc_context, "unrecognized command: %s", argv[0]); else if (ret == -2) ret = 0; if(ret != 0) exit_status = 1; } else { sl_slc_help(commands, argc, argv); exit_status = 1; } krb5_free_context(kcc_context); return exit_status; }
struct pidfh * pidfile_open(const char *path, mode_t mode, pid_t *pidptr, char **argv) { struct pidfh *pfh; struct stat sb; int error, fd, len, count; struct timespec rqtp; pfh = malloc(sizeof(*pfh)); if (pfh == NULL) return (NULL); if (path == NULL) len = snprintf(pfh->pf_path, sizeof(pfh->pf_path), "/var/run/%s.pid", getprogname()); else len = snprintf(pfh->pf_path, sizeof(pfh->pf_path), "%s", path); if (len >= (int)sizeof(pfh->pf_path)) { free(pfh); errno = ENAMETOOLONG; return (NULL); } fd = flopen(pfh->pf_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NONBLOCK, mode); if (fd == -1) { if (errno == EWOULDBLOCK) { if (pidptr == NULL) { errno = EEXIST; } else { count = 20; rqtp.tv_sec = 0; rqtp.tv_nsec = 5000000; for(;;) { errno = pidfile_read(pfh->pf_path, pidptr); if (errno != EAGAIN || --count == 0) break; nanosleep(&rqtp, 0); } if (errno == EAGAIN) *pidptr = -1; if (errno == 0 || errno == EAGAIN) errno = EEXIST; } } free(pfh); return(NULL); } if (fstat(fd, &sb) == -1) { error = errno; unlink(pfh->pf_path); close(fd); free(pfh); errno = error; return (NULL); } pfh->pf_fd = fd; pfh->pf_dev = sb.st_dev; pfh->pf_ino = sb.st_ino; return (pfh); }
int main(int argc, char **argv) { int c, pid; extern char version[]; while ((c = getopt(argc, argv, "34adfs:v")) != -1) { switch (c) { case '3': Not3Flag++; break; case '4': Not4Flag++; break; case 'a': AllFlag++; break; case 'd': DebugFlag++; break; case 'f': ForegroundFlag++; break; case 's': MopdDir = optarg; break; case 'v': VersionFlag++; break; default: Usage(); /* NOTREACHED */ } } argc -= optind; argv += optind; if (VersionFlag) { fprintf(stdout,"%s: version %s\n", getprogname(), version); exit(0); } if ((AllFlag && argc != 0) || (!AllFlag && argc == 0) || (Not3Flag && Not4Flag)) Usage(); /* All error reporting is done through syslogs. */ openlog("mopd", LOG_PID, LOG_DAEMON); if ((!ForegroundFlag) && DebugFlag) fprintf(stdout, "%s: not running as daemon, -d given.\n", getprogname()); if ((!ForegroundFlag) && (!DebugFlag)) { pid = fork(); if (pid > 0) /* Parent exits, leaving child in background. */ exit(0); else if (pid == -1) { syslog(LOG_ERR, "cannot fork"); exit(0); } /* Fade into the background */ daemon(0, 0); pidfile(NULL); } syslog(LOG_INFO, "%s %s started.", getprogname(), version); if (AllFlag) deviceInitAll(); else { while (argc--) deviceInitOne(*argv++); } Loop(); /* NOTREACHED */ return (0); }
int main(int argc, char **argv) { krb5_error_code ret; krb5_context context; void *kadm_handle; kadm5_server_context *server_context; kadm5_config_params conf; krb5_socket_t signal_fd, listen_fd; int log_fd; slave *slaves = NULL; uint32_t current_version = 0, old_version = 0; uint32_t current_tstamp = 0; krb5_keytab keytab; char **files; int aret; int optidx = 0; int restarter_fd = -1; struct stat st; setprogname(argv[0]); if (getarg(args, num_args, argc, argv, &optidx)) krb5_std_usage(1, args, num_args); if (help_flag) krb5_std_usage(0, args, num_args); if (version_flag) { print_version(NULL); exit(0); } if (detach_from_console && daemon_child == -1) roken_detach_prep(argc, argv, "--daemon-child"); rk_pidfile(NULL); ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_context failed: %d", ret); setup_signal(); if (config_file == NULL) { aret = asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context)); if (aret == -1 || config_file == NULL) errx(1, "out of memory"); } ret = krb5_prepend_config_files_default(config_file, &files); if (ret) krb5_err(context, 1, ret, "getting configuration files"); ret = krb5_set_config_files(context, files); krb5_free_config_files(files); if (ret) krb5_err(context, 1, ret, "reading configuration files"); time_before_gone = parse_time (slave_time_gone, "s"); if (time_before_gone < 0) krb5_errx (context, 1, "couldn't parse time: %s", slave_time_gone); time_before_missing = parse_time (slave_time_missing, "s"); if (time_before_missing < 0) krb5_errx (context, 1, "couldn't parse time: %s", slave_time_missing); krb5_openlog(context, "ipropd-master", &log_facility); krb5_set_warn_dest(context, log_facility); ret = krb5_kt_register(context, &hdb_get_kt_ops); if(ret) krb5_err(context, 1, ret, "krb5_kt_register"); ret = krb5_kt_resolve(context, keytab_str, &keytab); if(ret) krb5_err(context, 1, ret, "krb5_kt_resolve: %s", keytab_str); memset(&conf, 0, sizeof(conf)); if(realm) { conf.mask |= KADM5_CONFIG_REALM; conf.realm = realm; } ret = kadm5_init_with_skey_ctx (context, KADM5_ADMIN_SERVICE, NULL, KADM5_ADMIN_SERVICE, &conf, 0, 0, &kadm_handle); if (ret) krb5_err (context, 1, ret, "kadm5_init_with_password_ctx"); server_context = (kadm5_server_context *)kadm_handle; log_fd = open (server_context->log_context.log_file, O_RDONLY, 0); if (log_fd < 0) krb5_err (context, 1, errno, "open %s", server_context->log_context.log_file); if (fstat(log_fd, &st) == -1) krb5_err(context, 1, errno, "stat %s", server_context->log_context.log_file); if (flock(log_fd, LOCK_SH) == -1) krb5_err(context, 1, errno, "shared flock %s", server_context->log_context.log_file); kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST, ¤t_version, ¤t_tstamp); flock(log_fd, LOCK_UN); signal_fd = make_signal_socket (context); listen_fd = make_listen_socket (context, port_str); krb5_warnx(context, "ipropd-master started at version: %lu", (unsigned long)current_version); roken_detach_finish(NULL, daemon_child); restarter_fd = restarter(context, NULL); while (exit_flag == 0){ slave *p; fd_set readset; int max_fd = 0; struct timeval to = {30, 0}; uint32_t vers; struct stat st2;; #ifndef NO_LIMIT_FD_SETSIZE if (signal_fd >= FD_SETSIZE || listen_fd >= FD_SETSIZE || restarter_fd >= FD_SETSIZE) krb5_errx (context, IPROPD_RESTART, "fd too large"); #endif FD_ZERO(&readset); FD_SET(signal_fd, &readset); max_fd = max(max_fd, signal_fd); FD_SET(listen_fd, &readset); max_fd = max(max_fd, listen_fd); if (restarter_fd > -1) { FD_SET(restarter_fd, &readset); max_fd = max(max_fd, restarter_fd); } for (p = slaves; p != NULL; p = p->next) { if (p->flags & SLAVE_F_DEAD) continue; FD_SET(p->fd, &readset); max_fd = max(max_fd, p->fd); } ret = select (max_fd + 1, &readset, NULL, NULL, &to); if (ret < 0) { if (errno == EINTR) continue; else krb5_err (context, IPROPD_RESTART, errno, "select"); } if (stat(server_context->log_context.log_file, &st2) == -1) { krb5_warn(context, errno, "could not stat log file by path"); st2 = st; } if (st2.st_dev != st.st_dev || st2.st_ino != st.st_ino) { (void) close(log_fd); log_fd = open(server_context->log_context.log_file, O_RDONLY, 0); if (log_fd < 0) krb5_err(context, 1, IPROPD_RESTART_SLOW, "open %s", server_context->log_context.log_file); if (fstat(log_fd, &st) == -1) krb5_err(context, IPROPD_RESTART_SLOW, errno, "stat %s", server_context->log_context.log_file); if (flock(log_fd, LOCK_SH) == -1) krb5_err(context, IPROPD_RESTART, errno, "shared flock %s", server_context->log_context.log_file); kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST, ¤t_version, ¤t_tstamp); flock(log_fd, LOCK_UN); } if (ret == 0) { /* Recover from failed transactions */ if (kadm5_log_init_nb(server_context) == 0) kadm5_log_end(server_context); if (flock(log_fd, LOCK_SH) == -1) krb5_err(context, IPROPD_RESTART, errno, "could not lock log file"); kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST, ¤t_version, ¤t_tstamp); flock(log_fd, LOCK_UN); if (current_version > old_version) { krb5_warnx(context, "Missed a signal, updating slaves %lu to %lu", (unsigned long)old_version, (unsigned long)current_version); for (p = slaves; p != NULL; p = p->next) { if (p->flags & SLAVE_F_DEAD) continue; send_diffs (server_context, p, log_fd, database, current_version, current_tstamp); } old_version = current_version; } } if (ret && FD_ISSET(restarter_fd, &readset)) { exit_flag = SIGTERM; break; } if (ret && FD_ISSET(signal_fd, &readset)) { #ifndef NO_UNIX_SOCKETS struct sockaddr_un peer_addr; #else struct sockaddr_storage peer_addr; #endif socklen_t peer_len = sizeof(peer_addr); if(recvfrom(signal_fd, (void *)&vers, sizeof(vers), 0, (struct sockaddr *)&peer_addr, &peer_len) < 0) { krb5_warn (context, errno, "recvfrom"); continue; } --ret; assert(ret >= 0); old_version = current_version; if (flock(log_fd, LOCK_SH) == -1) krb5_err(context, IPROPD_RESTART, errno, "shared flock %s", server_context->log_context.log_file); kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST, ¤t_version, ¤t_tstamp); flock(log_fd, LOCK_UN); if (current_version != old_version) { /* * If current_version < old_version then the log got * truncated and we'll end up doing full propagations. * * Truncating the log when the current version is * numerically small can lead to race conditions. * Ideally we should identify log versions as * {init_or_trunc_time, vno}, then we could not have any * such race conditions, but this would either require * breaking backwards compatibility for the protocol or * adding new messages to it. */ krb5_warnx(context, "Got a signal, updating slaves %lu to %lu", (unsigned long)old_version, (unsigned long)current_version); for (p = slaves; p != NULL; p = p->next) { if (p->flags & SLAVE_F_DEAD) continue; send_diffs (server_context, p, log_fd, database, current_version, current_tstamp); } } else { krb5_warnx(context, "Got a signal, but no update in log version %lu", (unsigned long)current_version); } } for(p = slaves; p != NULL; p = p->next) { if (p->flags & SLAVE_F_DEAD) continue; if (ret && FD_ISSET(p->fd, &readset)) { --ret; assert(ret >= 0); if(process_msg (server_context, p, log_fd, database, current_version, current_tstamp)) slave_dead(context, p); } else if (slave_gone_p (p)) slave_dead(context, p); else if (slave_missing_p (p)) send_are_you_there (context, p); } if (ret && FD_ISSET(listen_fd, &readset)) { add_slave (context, keytab, &slaves, listen_fd); --ret; assert(ret >= 0); } write_stats(context, slaves, current_version); } if(exit_flag == SIGINT || exit_flag == SIGTERM) krb5_warnx(context, "%s terminated", getprogname()); #ifdef SIGXCPU else if(exit_flag == SIGXCPU) krb5_warnx(context, "%s CPU time limit exceeded", getprogname()); #endif else krb5_warnx(context, "%s unexpected exit reason: %ld", getprogname(), (long)exit_flag); write_master_down(context); return 0; }
void usage() { fprintf(stderr, "Usage: %s device\n", getprogname()); exit(1); }
// Initializes memory allocation framework once per process. static void malloc_init_impl() { const char* so_name = NULL; MallocDebugInit malloc_debug_initialize = NULL; unsigned int qemu_running = 0; unsigned int memcheck_enabled = 0; char env[PROP_VALUE_MAX]; char memcheck_tracing[PROP_VALUE_MAX]; char debug_program[PROP_VALUE_MAX]; // Get custom malloc debug level. Note that emulator started with // memory checking option will have priority over debug level set in // libc.debug.malloc system property. if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) { qemu_running = 1; if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) { if (memcheck_tracing[0] != '0') { // Emulator has started with memory tracing enabled. Enforce it. g_malloc_debug_level = 20; memcheck_enabled = 1; } } } // If debug level has not been set by memcheck option in the emulator, // lets grab it from libc.debug.malloc system property. if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) { g_malloc_debug_level = atoi(env); } // Debug level 0 means that we should use default allocation routines. if (g_malloc_debug_level == 0) { return; } // If libc.debug.malloc.program is set and is not a substring of progname, // then exit. if (__system_property_get("libc.debug.malloc.program", debug_program)) { if (!strstr(getprogname(), debug_program)) { return; } } // mksh is way too leaky. http://b/7291287. if (g_malloc_debug_level >= 10) { if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) { return; } } // Choose the appropriate .so for the requested debug level. switch (g_malloc_debug_level) { case 1: case 5: case 10: so_name = "libc_malloc_debug_leak.so"; break; case 20: // Quick check: debug level 20 can only be handled in emulator. if (!qemu_running) { error_log("%s: Debug level %d can only be set in emulator\n", getprogname(), g_malloc_debug_level); return; } // Make sure that memory checking has been enabled in emulator. if (!memcheck_enabled) { error_log("%s: Memory checking is not enabled in the emulator\n", getprogname()); return; } so_name = "libc_malloc_debug_qemu.so"; break; default: error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level); return; } // Load .so that implements the required malloc debugging functionality. void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY); if (malloc_impl_handle == NULL) { error_log("%s: Missing module %s required for malloc debug level %d: %s", getprogname(), so_name, g_malloc_debug_level, dlerror()); return; } // Initialize malloc debugging in the loaded module. malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle, "malloc_debug_initialize")); if (malloc_debug_initialize == NULL) { error_log("%s: Initialization routine is not found in %s\n", getprogname(), so_name); dlclose(malloc_impl_handle); return; } if (!malloc_debug_initialize(&g_hash_table, &__libc_malloc_default_dispatch)) { dlclose(malloc_impl_handle); return; } if (g_malloc_debug_level == 20) { // For memory checker we need to do extra initialization. typedef int (*MemCheckInit)(int, const char*); MemCheckInit memcheck_initialize = reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle, "memcheck_initialize")); if (memcheck_initialize == NULL) { error_log("%s: memcheck_initialize routine is not found in %s\n", getprogname(), so_name); dlclose(malloc_impl_handle); return; } if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) { dlclose(malloc_impl_handle); return; } } // No need to init the dispatch table because we can only get // here if debug level is 1, 5, 10, or 20. static MallocDebug malloc_dispatch_table __attribute__((aligned(32))); switch (g_malloc_debug_level) { case 1: InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak"); break; case 5: InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill"); break; case 10: InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk"); break; case 20: InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented"); break; default: break; } // Make sure dispatch table is initialized if ((malloc_dispatch_table.calloc == NULL) || (malloc_dispatch_table.free == NULL) || (malloc_dispatch_table.mallinfo == NULL) || (malloc_dispatch_table.malloc == NULL) || (malloc_dispatch_table.malloc_usable_size == NULL) || (malloc_dispatch_table.memalign == NULL) || (malloc_dispatch_table.posix_memalign == NULL) || #if defined(HAVE_DEPRECATED_MALLOC_FUNCS) (malloc_dispatch_table.pvalloc == NULL) || #endif (malloc_dispatch_table.realloc == NULL) #if defined(HAVE_DEPRECATED_MALLOC_FUNCS) || (malloc_dispatch_table.valloc == NULL) #endif ) { error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)", getprogname(), g_malloc_debug_level); dlclose(malloc_impl_handle); } else { __libc_malloc_dispatch = &malloc_dispatch_table; libc_malloc_impl_handle = malloc_impl_handle; } }
void usage(void) { fprintf(stderr, "Usage: %s <threadcount> <count> <program> [<arg1> [<arg2> ...]]\n", getprogname()); exit(1); }