int cpmain(int argc, char *argv[]) { struct stat to_stat, tmp_stat; enum op type; int fts_options, r; char *target; fts_options = FTS_NOCHDIR | FTS_PHYSICAL; myuid = getuid(); /* Copy the umask for explicit mode setting. */ myumask = umask(0); (void)umask(myumask); /* Save the target base in "to". */ target = argv[--argc]; if (strlcpy(to.p_path, target, sizeof to.p_path) >= sizeof(to.p_path)) errx(1, "%s: name too long", target); to.p_end = to.p_path + strlen(to.p_path); if (to.p_path == to.p_end) { *to.p_end++ = '.'; *to.p_end = '\0'; } to.target_end = to.p_end; /* Set end of argument list for fts(3). */ argv[argc] = NULL; /* * Cp has two distinct cases: * * cp [-R] source target * cp [-R] source1 ... sourceN directory * * In both cases, source can be either a file or a directory. * * In (1), the target becomes a copy of the source. That is, if the * source is a file, the target will be a file, and likewise for * directories. * * In (2), the real target is not directory, but "directory/source". */ r = stat(to.p_path, &to_stat); if (r == -1 && errno != ENOENT) err(1, "%s", to.p_path); if (r == -1 || !S_ISDIR(to_stat.st_mode)) { /* * Case (1). Target is not a directory. */ if (argc > 1) usage(); /* * Need to detect the case: * cp -R dir foo * Where dir is a directory and foo does not exist, where * we want pathname concatenations turned on but not for * the initial mkdir(). */ if (r == -1) { lstat(*argv, &tmp_stat); if (S_ISDIR(tmp_stat.st_mode)) type = DIR_TO_DNE; else type = FILE_TO_FILE; } else type = FILE_TO_FILE; } else { /* * Case (2). Target is a directory. */ type = FILE_TO_DIR; } return (copy(argv, type, fts_options)); }
int main(int argc, char **argv) { FILE *fp = stdin; int c; if (argc == 1) { usage(0); } thiszone = gmt2local(0); while ((c = getopt(argc, argv, "acdf:HlnvxDFPphVrk?")) != -1) { switch (c) { case 'c': f_mode = MODE_STDIN; #ifdef HAVE_READLINE /* disable filename completion */ rl_bind_key('\t', rl_insert); #endif break; case 'f': f_mode = MODE_SCRIPT; if (strcmp(optarg, "-") == 0) { fp = stdin; } else if ((fp = fopen(optarg, "r")) == NULL) { err(1, "Can't open `%s'", optarg); } break; case 'D': f_mode = MODE_CMDDUMP; break; case 'F': f_mode = MODE_CMDFLUSH; break; case 'a': f_all = 1; break; case 'l': f_forever = 1; break; case 'n': f_notreally = 1; break; #ifdef __NetBSD__ case 'h': #endif case 'H': f_hexdump = 1; break; case 'x': f_mode = MODE_PROMISC; f_tflag++; break; case 'P': f_policy = 1; break; case 'p': f_withports = 1; break; case 'v': f_verbose = 1; break; case 'r': #ifdef HAVE_POLICY_FWD f_rfcmode = 1; #else rkwarn(); #endif break; case 'k': #ifdef HAVE_POLICY_FWD f_rfcmode = 0; #else rkwarn(); #endif break; case 'V': usage(1); break; #ifndef __NetBSD__ case 'h': #endif case '?': default: usage(0); } } argc -= optind; argv += optind; if (argc > 0) { while (argc--) { if (fileproc(*argv++) < 0) { err(1, "%s", argv[-1]); } } exit(0); } so = pfkey_open(); if (so < 0) { perror("pfkey_open"); exit(1); } switch (f_mode) { case MODE_CMDDUMP: sendkeyshort(f_policy ? SADB_X_SPDDUMP : SADB_DUMP); break; case MODE_CMDFLUSH: sendkeyshort(f_policy ? SADB_X_SPDFLUSH: SADB_FLUSH); break; case MODE_SCRIPT: if (get_supported() < 0) { errx(1, "%s", ipsec_strerror()); } if (parse(&fp)) exit(1); break; case MODE_STDIN: if (get_supported() < 0) { errx(1, "%s", ipsec_strerror()); } stdin_loop(); break; case MODE_PROMISC: promisc(); /* NOTREACHED */ default: usage(0); } exit(0); }
/* * Read the process's memory map using procfs, and return a list of * VM map entries. Only the non-device read/writable segments are * returned. The map entries in the list aren't fully filled in; only * the items we need are present. */ static vm_map_entry_t readmap(pid_t pid) { char mapname[64]; int mapfd; ssize_t mapsize; size_t bufsize; char *mapbuf; int pos; vm_map_entry_t map; vm_map_entry_t *linkp; snprintf(mapname, sizeof mapname, "/proc/%d/map", pid); if ((mapfd = open(mapname, O_RDONLY)) == -1) err(1, "cannot open %s", mapname); /* * Procfs requires (for consistency) that the entire memory map * be read with a single read() call. Start with a reasonbly sized * buffer, and double it until it is big enough. */ bufsize = 8 * 1024; mapbuf = NULL; for ( ; ; ) { if ((mapbuf = realloc(mapbuf, bufsize + 1)) == NULL) errx(1, "out of memory"); mapsize = read(mapfd, mapbuf, bufsize); if (mapsize != -1 || errno != EFBIG) break; bufsize *= 2; /* This lseek shouldn't be necessary, but it is. */ lseek(mapfd, (off_t)0, SEEK_SET); } if (mapsize == -1) err(1, "read error from %s", mapname); if (mapsize == 0) errx(1, "empty map file %s", mapname); mapbuf[mapsize] = 0; close(mapfd); pos = 0; map = NULL; linkp = ↦ while (pos < mapsize) { vm_map_entry_t ent; vm_offset_t start; vm_offset_t end; char prot[4]; char type[16]; int n; int len; len = 0; n = sscanf(mapbuf + pos, "%lx %lx %*d %*d %*x %3[-rwx]" " %*d %*d %*x %*s %*s %16s %*s%*[\n]%n", &start, &end, prot, type, &len); if (n != 4) errx(1, "ill-formed line in %s", mapname); pos += len; /* Ignore segments of the wrong kind, and unwritable ones */ if (strncmp(prot, "rw", 2) != 0 || (strcmp(type, "default") != 0 && strcmp(type, "vnode") != 0 && strcmp(type, "swap") != 0)) continue; if ((ent = (vm_map_entry_t)calloc(1, sizeof *ent)) == NULL) errx(1, "out of memory"); ent->start = start; ent->end = end; ent->protection = VM_PROT_READ | VM_PROT_WRITE; if (prot[2] == 'x') ent->protection |= VM_PROT_EXECUTE; *linkp = ent; linkp = &ent->next; } free(mapbuf); return map; }
void badcnt(char *s) { errx(1, "%s: bad byte count", s); }
void badfmt(const char *fmt) { errx(1, "\"%s\": bad format", fmt); }
int main( int argc, char *argv[] ) { //srand(time(NULL)); if( argc > 2 ) { const int LEN = atoi(argv[1]); const int INI = atoi(argv[2]); struct boolean_vector *v = bv_create( LEN, INI ); if( v ) { int n; bool state = false, _3arg = false; /** * Every argument must be a /([CcSs]|[0-9]+)/ * Perform a command-line-specified series of operations * on the boolean_vector, then... */ for(int i = 3; i < argc; i++ ) { const char *arg = argv[i]; if( isdigit( arg[0] ) ) { const int flag = atoi(arg); if( _3arg ) { v->setstate( v, flag, state ); } else { if( state ) v->set( v, flag ); else v->clr( v, flag ); } } else { switch( arg[0] ) { case 's': state = true; _3arg = false; break; case 'c': state = false; _3arg = false; break; case 'S': state = true; _3arg = true; break; case 'C': state = false; _3arg = true; break; default: abort(); } } } /** * ...dump the results by .write as well as .pop. */ n = v->popcount(v); if( n > 0 ) { uint32_t *arr; printf( "Set bits (accessed by .write):\n" ); arr = alloca( n * sizeof(uint32_t)); v->write(v, arr, n ); printf( "%d", arr[0] ); for(int i = 1; i < n; i++ ) printf( ",%d", arr[i] ); printf( "\nSet bits (accessed by .pop):\n" ); printf( "%d", v->pop(v) ); while( (n = v->pop(v)) >= 0 ) printf( ",%d", n ); putchar( '\n' ); } else puts( "no bits set" ); assert( v->popcount(v) == 0 ); // exhausted by .pop above. v->destroy( v ); } } else errx( -1, "%s <len> <init_set> bit1 [ bit2 bit3 ... ]\n", argv[0] ); return EXIT_SUCCESS; }
int main(int argc, char **argv) { gss_OID_set oidset = GSS_C_NULL_OID_SET; gss_OID mechoid = GSS_C_NO_OID; OM_uint32 maj_stat, min_stat; gss_cred_id_t cred; gss_name_t target = GSS_C_NO_NAME; int i, optidx = 0; OM_uint32 flag; gss_OID type; setprogname(argv[0]); 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); } argc -= optidx; argv += optidx; if (argc != 0) usage(1); if (acquire_type) { if (strcasecmp(acquire_type, "both") == 0) flag = GSS_C_BOTH; else if (strcasecmp(acquire_type, "accept") == 0) flag = GSS_C_ACCEPT; else if (strcasecmp(acquire_type, "initiate") == 0) flag = GSS_C_INITIATE; else errx(1, "unknown type %s", acquire_type); } else flag = GSS_C_ACCEPT; if (name_type) { if (strcasecmp("hostbased-service", name_type) == 0) type = GSS_C_NT_HOSTBASED_SERVICE; else if (strcasecmp("user-name", name_type) == 0) type = GSS_C_NT_USER_NAME; else errx(1, "unknown name type %s", name_type); } else type = GSS_C_NT_HOSTBASED_SERVICE; if (ccache) { maj_stat = gss_krb5_ccache_name(&min_stat, ccache, NULL); if (GSS_ERROR(maj_stat)) errx(1, "gss_krb5_ccache_name %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } if (kerberos_flag) { mechoid = GSS_KRB5_MECHANISM; maj_stat = gss_create_empty_oid_set(&min_stat, &oidset); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_create_empty_oid_set: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); maj_stat = gss_add_oid_set_member(&min_stat, GSS_KRB5_MECHANISM, &oidset); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_add_oid_set_member: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } if (target_name) { gss_buffer_desc name; name.value = target_name; name.length = strlen(target_name); maj_stat = gss_import_name(&min_stat, &name, GSS_C_NT_HOSTBASED_SERVICE, &target); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_import_name: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } for (i = 0; i < num_loops; i++) { cred = acquire_cred_service(acquire_name, type, oidset, flag); if (enctype) { int32_t enctypelist = enctype; maj_stat = gss_krb5_set_allowable_enctypes(&min_stat, cred, 1, &enctypelist); if (maj_stat) errx(1, "gss_krb5_set_allowable_enctypes: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } if (target) { gss_ctx_id_t context = GSS_C_NO_CONTEXT; gss_buffer_desc out; out.length = 0; out.value = NULL; maj_stat = gss_init_sec_context(&min_stat, cred, &context, target, mechoid, GSS_C_MUTUAL_FLAG, 0, NULL, GSS_C_NO_BUFFER, NULL, &out, NULL, NULL); if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED) errx(1, "init_sec_context failed: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); gss_release_buffer(&min_stat, &out); gss_delete_sec_context(&min_stat, &context, NULL); } gss_release_cred(&min_stat, &cred); } return 0; }
static void translate(Dwarf_Debug dbg, const char* addrstr) { Dwarf_Die die, ret_die; Dwarf_Line *lbuf; Dwarf_Error de; Dwarf_Half tag; Dwarf_Unsigned lopc, hipc, addr, lineno, plineno; Dwarf_Signed lcount; Dwarf_Addr lineaddr, plineaddr; char *funcname; char *file, *file0, *pfile; char demangled[1024]; int i, ret; addr = strtoull(addrstr, NULL, 16); addr += section_base; lineno = 0; file = unknown; die = NULL; lbuf = NULL; lcount = 0; while ((ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL, NULL, &de)) == DW_DLV_OK) { die = NULL; while (dwarf_siblingof(dbg, die, &ret_die, &de) == DW_DLV_OK) { if (die != NULL) dwarf_dealloc(dbg, die, DW_DLA_DIE); die = ret_die; if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) { warnx("dwarf_tag failed: %s", dwarf_errmsg(de)); goto next_cu; } /* XXX: What about DW_TAG_partial_unit? */ if (tag == DW_TAG_compile_unit) break; } if (ret_die == NULL) { warnx("could not find DW_TAG_compile_unit die"); goto next_cu; } if (!dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) && !dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc, &de)) { /* * Check if the address falls into the PC range of * this CU. */ if (handle_high_pc(die, lopc, &hipc) != DW_DLV_OK) goto next_cu; if (addr < lopc || addr >= hipc) goto next_cu; } switch (dwarf_srclines(die, &lbuf, &lcount, &de)) { case DW_DLV_OK: break; case DW_DLV_NO_ENTRY: /* If a CU lacks debug info, just skip it. */ goto next_cu; default: warnx("dwarf_srclines: %s", dwarf_errmsg(de)); goto out; } plineaddr = ~0ULL; plineno = 0; pfile = unknown; for (i = 0; i < lcount; i++) { if (dwarf_lineaddr(lbuf[i], &lineaddr, &de)) { warnx("dwarf_lineaddr: %s", dwarf_errmsg(de)); goto out; } if (dwarf_lineno(lbuf[i], &lineno, &de)) { warnx("dwarf_lineno: %s", dwarf_errmsg(de)); goto out; } if (dwarf_linesrc(lbuf[i], &file0, &de)) { warnx("dwarf_linesrc: %s", dwarf_errmsg(de)); } else file = file0; if (addr == lineaddr) goto out; else if (addr < lineaddr && addr > plineaddr) { lineno = plineno; file = pfile; goto out; } plineaddr = lineaddr; plineno = lineno; pfile = file; } next_cu: if (die != NULL) { dwarf_dealloc(dbg, die, DW_DLA_DIE); die = NULL; } } out: funcname = NULL; if (ret == DW_DLV_OK && func) { search_func(dbg, die, addr, &funcname); die = NULL; } if (func) { if (funcname == NULL) if ((funcname = strdup(unknown)) == NULL) err(EXIT_FAILURE, "strdup"); if (demangle && !elftc_demangle(funcname, demangled, sizeof(demangled), 0)) printf("%s\n", demangled); else printf("%s\n", funcname); free(funcname); } (void) printf("%s:%ju\n", base ? basename(file) : file, lineno); if (die != NULL) dwarf_dealloc(dbg, die, DW_DLA_DIE); /* * Reset internal CU pointer, so we will start from the first CU * next round. */ while (ret != DW_DLV_NO_ENTRY) { if (ret == DW_DLV_ERROR) errx(EXIT_FAILURE, "dwarf_next_cu_header: %s", dwarf_errmsg(de)); ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL, NULL, &de); } }
int main(int argc, char **argv) { Elf *e; Dwarf_Debug dbg; Dwarf_Error de; const char *exe, *section; char line[1024]; int fd, i, opt; exe = NULL; section = NULL; while ((opt = getopt_long(argc, argv, "b:Ce:fj:sHV", longopts, NULL)) != -1) { switch (opt) { case 'b': /* ignored */ break; case 'C': demangle = 1; break; case 'e': exe = optarg; break; case 'f': func = 1; break; case 'j': section = optarg; break; case 's': base = 1; break; case 'H': usage(); case 'V': version(); default: usage(); } } argv += optind; argc -= optind; if (exe == NULL) exe = "a.out"; if ((fd = open(exe, O_RDONLY)) < 0) err(EXIT_FAILURE, "%s", exe); if (dwarf_init(fd, DW_DLC_READ, NULL, NULL, &dbg, &de)) errx(EXIT_FAILURE, "dwarf_init: %s", dwarf_errmsg(de)); if (dwarf_get_elf(dbg, &e, &de) != DW_DLV_OK) errx(EXIT_FAILURE, "dwarf_get_elf: %s", dwarf_errmsg(de)); if (section) find_section_base(exe, e, section); else section_base = 0; if (argc > 0) for (i = 0; i < argc; i++) translate(dbg, argv[i]); else while (fgets(line, sizeof(line), stdin) != NULL) { translate(dbg, line); fflush(stdout); } dwarf_finish(dbg, &de); (void) elf_end(e); exit(0); }
static void vlan_cb(int s, void *arg) { if ((params.vlr_tag != NOTAG) ^ (params.vlr_parent[0] != '\0')) errx(1, "both vlan and vlandev must be specified"); }
static void search_func(Dwarf_Debug dbg, Dwarf_Die die, Dwarf_Addr addr, char **rlt_func) { Dwarf_Die ret_die, spec_die; Dwarf_Error de; Dwarf_Half tag; Dwarf_Unsigned lopc, hipc; Dwarf_Off ref; Dwarf_Attribute sub_at, spec_at; char *func0; const char *func1; int ret; if (*rlt_func != NULL) goto done; if (dwarf_tag(die, &tag, &de)) { warnx("dwarf_tag: %s", dwarf_errmsg(de)); goto cont_search; } if (tag == DW_TAG_subprogram) { if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) || dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc, &de)) goto cont_search; if (handle_high_pc(die, lopc, &hipc) != DW_DLV_OK) goto cont_search; if (addr < lopc || addr >= hipc) goto cont_search; /* Found it! */ if ((*rlt_func = strdup(unknown)) == NULL) err(EXIT_FAILURE, "strdup"); ret = dwarf_attr(die, DW_AT_name, &sub_at, &de); if (ret == DW_DLV_ERROR) goto done; if (ret == DW_DLV_OK) { if (dwarf_formstring(sub_at, &func0, &de) == DW_DLV_OK) { free(*rlt_func); if ((*rlt_func = strdup(func0)) == NULL) err(EXIT_FAILURE, "strdup"); } goto done; } /* * If DW_AT_name is not present, but DW_AT_specification is * present, then probably the actual name is in the DIE * referenced by DW_AT_specification. */ if (dwarf_attr(die, DW_AT_specification, &spec_at, &de)) goto done; if (dwarf_global_formref(spec_at, &ref, &de)) goto done; if (dwarf_offdie(dbg, ref, &spec_die, &de)) goto done; if (dwarf_attrval_string(spec_die, DW_AT_name, &func1, &de) == DW_DLV_OK) { free(*rlt_func); if ((*rlt_func = strdup(func1)) == NULL) err(EXIT_FAILURE, "strdup"); } goto done; } cont_search: /* Search children. */ ret = dwarf_child(die, &ret_die, &de); if (ret == DW_DLV_ERROR) errx(EXIT_FAILURE, "dwarf_child: %s", dwarf_errmsg(de)); else if (ret == DW_DLV_OK) search_func(dbg, ret_die, addr, rlt_func); /* Search sibling. */ ret = dwarf_siblingof(dbg, die, &ret_die, &de); if (ret == DW_DLV_ERROR) errx(EXIT_FAILURE, "dwarf_siblingof: %s", dwarf_errmsg(de)); else if (ret == DW_DLV_OK) search_func(dbg, ret_die, addr, rlt_func); done: dwarf_dealloc(dbg, die, DW_DLA_DIE); }
/* * main() */ int main(int ac, char *av[]) { struct ngm_connect ngc; const char *path = NULL; const char *hook = DEFAULT_HOOKNAME; int csock, dsock; int asciiFlag = 0; int loopFlag = 0; int noInput = 0; int execFlag = 0; int ch; if ((msgs = sl_init()) == NULL) err(EX_OSERR, NULL); /* Parse flags */ while ((ch = getopt(ac, av, "aedlm:nsS")) != -1) { switch (ch) { case 'a': asciiFlag = 1; break; case 'd': NgSetDebug(NgSetDebug(-1) + 1); break; case 'e': execFlag = 1; break; case 'l': loopFlag = 1; break; case 'n': noInput = 1; break; case 'm': if (sl_add(msgs, optarg) == -1) err(EX_OSERR, NULL); break; case 's': outfd = STDIN_FILENO; break; case 'S': infd = STDOUT_FILENO; break; case '?': default: Usage(); } } ac -= optind; av += optind; if (execFlag) { if (asciiFlag || loopFlag) { fprintf(stderr, "conflicting options\n"); Usage(); } if (ac < 3) Usage(); path = av[0]; hook = av[1]; av += 2; ac -= 2; } else { /* Get params */ switch (ac) { case 2: hook = av[1]; /* FALLTHROUGH */ case 1: path = av[0]; break; default: Usage(); } } /* Get sockets */ if (NgMkSockNode(NULL, &csock, &dsock) < 0) errx(EX_OSERR, "can't get sockets"); /* Connect socket node to specified node */ snprintf(ngc.path, sizeof(ngc.path), "%s", path); snprintf(ngc.ourhook, sizeof(ngc.ourhook), NG_SOCK_HOOK_NAME); snprintf(ngc.peerhook, sizeof(ngc.peerhook), "%s", hook); if (NgSendMsg(csock, ".", NGM_GENERIC_COOKIE, NGM_CONNECT, &ngc, sizeof(ngc)) < 0) errx(EX_OSERR, "can't connect to node"); if (execFlag) { /* move dsock to fd 0 and 1 */ (void)close(0); (void)close(1); if (!noInput) (void)dup2(dsock, 0); (void)dup2(dsock, 1); send_msgs(csock, path); /* try executing the program */ (void)execv(av[0], av); err(EX_OSERR, "%s", av[0]); } else send_msgs(csock, path); /* Close standard input if not reading from it */ if (noInput) fclose(stdin); /* Relay data */ while (1) { fd_set rfds; /* Setup bits */ FD_ZERO(&rfds); if (!noInput) FD_SET(infd, &rfds); FD_SET(dsock, &rfds); /* Wait for something to happen */ if (select(FD_SETSIZE, &rfds, NULL, NULL, NULL) < 0) err(EX_OSERR, "select"); /* Check data from socket */ if (FD_ISSET(dsock, &rfds)) { char buf[BUF_SIZE]; int rl, wl; /* Read packet from socket */ if ((rl = NgRecvData(dsock, buf, sizeof(buf), NULL)) < 0) err(EX_OSERR, "read(hook)"); if (rl == 0) errx(EX_OSERR, "read EOF from hook?!"); /* Write packet to stdout */ if (asciiFlag) WriteAscii((u_char *) buf, rl); else if ((wl = write(outfd, buf, rl)) != rl) { if (wl < 0) { err(EX_OSERR, "write(stdout)"); } else { errx(EX_OSERR, "stdout: read %d, wrote %d", rl, wl); } } /* Loopback */ if (loopFlag) { if (NgSendData(dsock, NG_SOCK_HOOK_NAME, buf, rl) < 0) err(EX_OSERR, "write(hook)"); } } /* Check data from stdin */ if (FD_ISSET(infd, &rfds)) { char buf[BUF_SIZE]; int rl; /* Read packet from stdin */ if ((rl = read(infd, buf, sizeof(buf))) < 0) err(EX_OSERR, "read(stdin)"); if (rl == 0) errx(EX_OSERR, "EOF(stdin)"); /* Write packet to socket */ if (NgSendData(dsock, NG_SOCK_HOOK_NAME, buf, rl) < 0) err(EX_OSERR, "write(hook)"); } } }
int main(int argc, char *argv[]) { char *audio_device; char *output_file; char *input_file; int audio_fd; size_t buffer_size; audio_device_t audio_dev; audio_info_t audio_if; u_int sample_rate; u_int channels; u_int mode; u_int encoding; int flags; int use_duplex; int use_nonblock; int use_poll; int use_select; int use_bufinfo; int verbose; int loops; const char *errstr; int ch; extern char *optarg; extern int optind; audio_device = "/dev/audio"; input_file = NULL; output_file = NULL; audio_fd = -1; buffer_size = 8192; sample_rate = 48000; channels = 2; encoding = 0; loops = 64; use_nonblock = 0; use_select = 0; use_poll = 0; use_bufinfo = 0; use_duplex = 0; verbose = 0; while ((ch = getopt(argc, argv, "b:c:e:f:i:l:o:r:dnpsv")) != -1) { switch (ch) { case 'b': buffer_size = (size_t)strtonum(optarg, 32, 65536, &errstr); if (errstr != NULL) errx(1, "could not grok buffer_size: %s", errstr); break; case 'c': channels = (u_int)strtonum(optarg, 1, 2, &errstr); if (errstr != NULL) errx(1, "could not grok channels: %s", errstr); break; case 'd': use_duplex = 1; break; case 'e': encoding = (u_int)strtonum(optarg, 0, 24, &errstr); if (errstr != NULL) errx(1, "could not grok encoding: %s", errstr); break; case 'f': audio_device = optarg; break; case 'i': input_file = optarg; break; case 'l': loops = (int)strtonum(optarg, 0, INT_MAX, &errstr); if (errstr != NULL) errx(1, "could not grok loops: %s", errstr); break; case 'n': use_bufinfo = 1; break; case 'o': output_file = optarg; break; case 'p': use_poll = 1; use_nonblock = 1; break; case 'r': sample_rate = (u_int)strtonum(optarg, 0, INT_MAX, &errstr); if (errstr != NULL) errx(1, "could not grok sample_rate: %s", errstr); break; case 's': use_select = 1; use_nonblock = 1; break; case 'v': verbose = 1; break; default: useage(); exit(1); break; } } argc -= optind; argv += optind; if (use_select + use_poll + use_bufinfo > 1) errx(1, "can only use one of select, poll or buffer info"); if ((input_file == NULL) && (output_file == NULL)) errx(1, "no input or output file specified"); if ((input_file != NULL) && (output_file != NULL)) use_duplex = 1; mode = 0; flags = 0; if (output_file != NULL) { mode |= AUMODE_RECORD; flags = O_RDONLY; } if (input_file != NULL) { mode |= AUMODE_PLAY; flags = O_WRONLY; } if (use_duplex) flags = O_RDWR; if (use_nonblock) flags |= O_NONBLOCK; if ((audio_fd = open(audio_device, flags)) < 0) err(1, "open %s", audio_device); if (audio_set_duplex(audio_fd, audio_device, use_duplex)) errx(1, "could not set duplex mode"); if (audio_set_info(audio_fd, mode, encoding, sample_rate, channels, &buffer_size)) errx(1, "could not initialize audio device"); if (verbose) { AUDIO_INITINFO(&audio_if); if (ioctl(audio_fd, AUDIO_GETINFO, &audio_if) < 0) err(1, "AUDIO_GETINFO"); if (ioctl(audio_fd, AUDIO_GETDEV, &audio_dev) < 0) err(1, "AUDIO_GETDEV"); warnx("audio device: %s: %s ver %s, config: %s", audio_device, audio_dev.name, audio_dev.version, audio_dev.config); warnx("blocksize: %u", audio_if.blocksize); warnx("lowat: %u", audio_if.lowat); warnx("hiwat: %u", audio_if.hiwat); warnx("play.buffer_size: %u", audio_if.play.buffer_size); warnx("record.buffer_size: %u", audio_if.record.buffer_size); if (output_file != NULL) warnx("output file: %s", output_file); if (input_file != NULL) warnx("input file: %s", input_file); warnx("flags: %d", flags); warnx("mode: %u", mode); warnx("encoding: %u", encoding); warnx("sample_rate: %u", sample_rate); warnx("channels: %u", channels); warnx("use_select: %d", use_select); warnx("use_poll: %d", use_poll); warnx("use_bufinfo: %d", use_bufinfo); warnx("use_duplex: %d", use_duplex); warnx("buffer_size: %lu", (unsigned long)buffer_size); } /* need to trigger recording in duplex mode */ if (use_duplex && (mode & AUMODE_RECORD)) if (audio_trigger_record(audio_fd)) exit(1); if (audio_do_test(audio_fd, buffer_size, input_file, output_file, mode, use_poll, use_select, use_bufinfo, loops, verbose)) exit(1); if (verbose) warnx("test completed"); if (audio_fd >= 0) close(audio_fd); exit(0); }
int main(int argc, char *argv[]) { struct passwd *pw; struct servent *sp; struct sgttyb ttyb; long omask; int argoff, ch, dflag, Dflag, one, uid; char *host, *localname, *p, *user, term[1024]; #ifdef KERBEROS char *k; #endif struct sockaddr_storage ss; int sslen; argoff = dflag = Dflag = 0; one = 1; host = localname = user = NULL; if ((p = strrchr(argv[0], '/'))) ++p; else p = argv[0]; if (strcmp(p, "rlogin")) host = p; /* handle "rlogin host flags" */ if (!host && argc > 2 && argv[1][0] != '-') { host = argv[1]; argoff = 1; } #ifdef KERBEROS #define OPTIONS "468DEKLde:i:k:l:x" #else #define OPTIONS "468DEKLde:i:l:" #endif while ((ch = getopt(argc - argoff, argv + argoff, OPTIONS)) != -1) switch(ch) { case '4': family = PF_INET; break; case '6': family = PF_INET6; break; case '8': eight = 1; break; case 'D': Dflag = 1; break; case 'E': noescape = 1; break; case 'K': #ifdef KERBEROS use_kerberos = 0; #endif break; case 'L': litout = 1; break; case 'd': dflag = 1; break; case 'e': noescape = 0; escapechar = getescape(optarg); break; case 'i': if (getuid() != 0) errx(1, "-i user: permission denied"); localname = optarg; break; #ifdef KERBEROS case 'k': dest_realm = dst_realm_buf; (void)strncpy(dest_realm, optarg, REALM_SZ); break; #endif case 'l': user = optarg; break; #ifdef CRYPT #ifdef KERBEROS case 'x': doencrypt = 1; break; #endif #endif case '?': default: usage(); } optind += argoff; /* if haven't gotten a host yet, do so */ if (!host && !(host = argv[optind++])) usage(); if (argv[optind]) usage(); if (!(pw = getpwuid(uid = getuid()))) errx(1, "unknown user id"); if (!user) user = pw->pw_name; if (!localname) localname = pw->pw_name; sp = NULL; #ifdef KERBEROS k = auth_getval("auth_list"); if (k && !strstr(k, "kerberos")) use_kerberos = 0; if (use_kerberos) { sp = getservbyname((doencrypt ? "eklogin" : "klogin"), "tcp"); if (sp == NULL) { use_kerberos = 0; warn("can't get entry for %s/tcp service", doencrypt ? "eklogin" : "klogin"); } } #endif if (sp == NULL) sp = getservbyname("login", "tcp"); if (sp == NULL) errx(1, "login/tcp: unknown service"); #define MAX_TERM_LENGTH (sizeof(term) - 1 - MAX_SPEED_LENGTH - 1) (void)strncpy(term, (p = getenv("TERM")) ? p : "network", MAX_TERM_LENGTH); term[MAX_TERM_LENGTH] = '\0'; if (ioctl(0, TIOCGETP, &ttyb) == 0) { (void)strcat(term, "/"); (void)strcat(term, speeds[(int)ttyb.sg_ospeed]); } (void)get_window_size(0, &winsize); (void)signal(SIGPIPE, lostpeer); /* will use SIGUSR1 for window size hack, so hold it off */ omask = sigblock(sigmask(SIGURG) | sigmask(SIGUSR1)); /* * We set SIGURG and SIGUSR1 below so that an * incoming signal will be held pending rather than being * discarded. Note that these routines will be ready to get * a signal by the time that they are unblocked below. */ (void)signal(SIGURG, copytochild); (void)signal(SIGUSR1, writeroob); #ifdef KERBEROS if (use_kerberos) { setuid(getuid()); rem = KSUCCESS; errno = 0; if (dest_realm == NULL) dest_realm = krb_realmofhost(host); #ifdef CRYPT if (doencrypt) { rem = krcmd_mutual(&host, sp->s_port, user, term, 0, dest_realm, &cred, schedule); des_set_key(&cred.session, schedule); } else #endif /* CRYPT */ rem = krcmd(&host, sp->s_port, user, term, 0, dest_realm); if (rem < 0) { int i; char **newargv; sp = getservbyname("login", "tcp"); if (sp == NULL) errx(1, "unknown service login/tcp"); if (errno == ECONNREFUSED) warn("remote host doesn't support Kerberos"); if (errno == ENOENT) warn("can't provide Kerberos auth data"); newargv = malloc((argc + 2) * sizeof(*newargv)); if (newargv == NULL) err(1, "malloc"); newargv[0] = argv[0]; newargv[1] = "-K"; for(i = 1; i < argc; ++i) newargv[i + 1] = argv[i]; newargv[argc + 1] = NULL; execv(_PATH_RLOGIN, newargv); } } else { #ifdef CRYPT if (doencrypt) errx(1, "the -x flag requires Kerberos authentication"); #endif /* CRYPT */ rem = rcmd_af(&host, sp->s_port, localname, user, term, 0, family); } #else rem = rcmd_af(&host, sp->s_port, localname, user, term, 0, family); #endif /* KERBEROS */ if (rem < 0) exit(1); if (dflag && setsockopt(rem, SOL_SOCKET, SO_DEBUG, &one, sizeof(one)) < 0) warn("setsockopt"); if (Dflag && setsockopt(rem, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) < 0) warn("setsockopt NODELAY (ignored)"); sslen = sizeof(ss); one = IPTOS_LOWDELAY; if (getsockname(rem, (struct sockaddr *)&ss, &sslen) == 0 && ss.ss_family == AF_INET) { if (setsockopt(rem, IPPROTO_IP, IP_TOS, (char *)&one, sizeof(int)) < 0) warn("setsockopt TOS (ignored)"); } else if (ss.ss_family == AF_INET) warn("setsockopt getsockname failed"); (void)setuid(uid); doit(omask); /*NOTREACHED*/ }
/* * Entry point */ int main(int argc, char *argv[]) { struct stat sb; struct sigaction sa; const char *p, *s; char *end, *q; int c, e, r; while ((c = getopt(argc, argv, "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:")) != -1) switch (c) { case '1': once_flag = 1; break; case '4': family = PF_INET; break; case '6': family = PF_INET6; break; case 'A': A_flag = 1; break; case 'a': a_flag = 1; break; case 'B': B_size = (off_t)strtol(optarg, &end, 10); if (*optarg == '\0' || *end != '\0') errx(1, "invalid buffer size (%s)", optarg); break; case 'b': warnx("warning: the -b option is deprecated"); b_flag = 1; break; case 'c': c_dirname = optarg; break; case 'd': d_flag = 1; break; case 'F': F_flag = 1; break; case 'f': f_filename = optarg; break; case 'H': warnx("the -H option is now implicit, " "use -U to disable"); break; case 'h': h_hostname = optarg; break; case 'i': i_flag = 1; i_filename = optarg; break; case 'l': l_flag = 1; break; case 'o': o_flag = 1; o_filename = optarg; break; case 'M': case 'm': if (r_flag) errx(1, "the -m and -r flags " "are mutually exclusive"); m_flag = 1; break; case 'N': N_filename = optarg; break; case 'n': n_flag = 1; break; case 'P': case 'p': p_flag = 1; break; case 'q': v_level = 0; break; case 'R': R_flag = 1; break; case 'r': if (m_flag) errx(1, "the -m and -r flags " "are mutually exclusive"); r_flag = 1; break; case 'S': S_size = (off_t)strtol(optarg, &end, 10); if (*optarg == '\0' || *end != '\0') errx(1, "invalid size (%s)", optarg); break; case 's': s_flag = 1; break; case 'T': T_secs = strtol(optarg, &end, 10); if (*optarg == '\0' || *end != '\0') errx(1, "invalid timeout (%s)", optarg); break; case 't': t_flag = 1; warnx("warning: the -t option is deprecated"); break; case 'U': U_flag = 1; break; case 'v': v_level++; break; case 'w': a_flag = 1; w_secs = strtol(optarg, &end, 10); if (*optarg == '\0' || *end != '\0') errx(1, "invalid delay (%s)", optarg); break; default: usage(); exit(1); } argc -= optind; argv += optind; if (h_hostname || f_filename || c_dirname) { if (!h_hostname || !f_filename || argc) { usage(); exit(1); } /* XXX this is a hack. */ if (strcspn(h_hostname, "@:/") != strlen(h_hostname)) errx(1, "invalid hostname"); if (asprintf(argv, "ftp://%s/%s/%s", h_hostname, c_dirname ? c_dirname : "", f_filename) == -1) errx(1, "%s", strerror(ENOMEM)); argc++; } if (!argc) { usage(); exit(1); } /* allocate buffer */ if (B_size < MINBUFSIZE) B_size = MINBUFSIZE; if ((buf = malloc(B_size)) == NULL) errx(1, "%s", strerror(ENOMEM)); /* timeouts */ if ((s = getenv("FTP_TIMEOUT")) != NULL) { ftp_timeout = strtol(s, &end, 10); if (*s == '\0' || *end != '\0' || ftp_timeout < 0) { warnx("FTP_TIMEOUT (%s) is not a positive integer", s); ftp_timeout = 0; } } if ((s = getenv("HTTP_TIMEOUT")) != NULL) { http_timeout = strtol(s, &end, 10); if (*s == '\0' || *end != '\0' || http_timeout < 0) { warnx("HTTP_TIMEOUT (%s) is not a positive integer", s); http_timeout = 0; } } /* signal handling */ sa.sa_flags = 0; sa.sa_handler = sig_handler; sigemptyset(&sa.sa_mask); sigaction(SIGALRM, &sa, NULL); sa.sa_flags = SA_RESETHAND; sigaction(SIGINT, &sa, NULL); fetchRestartCalls = 0; /* output file */ if (o_flag) { if (strcmp(o_filename, "-") == 0) { o_stdout = 1; } else if (stat(o_filename, &sb) == -1) { if (errno == ENOENT) { if (argc > 1) errx(1, "%s is not a directory", o_filename); } else { err(1, "%s", o_filename); } } else { if (sb.st_mode & S_IFDIR) o_directory = 1; } } /* check if output is to a tty (for progress report) */ v_tty = isatty(STDERR_FILENO); if (v_tty) pgrp = getpgrp(); r = 0; /* authentication */ if (v_tty) fetchAuthMethod = query_auth; if (N_filename != NULL) setenv("NETRC", N_filename, 1); while (argc) { if ((p = strrchr(*argv, '/')) == NULL) p = *argv; else p++; if (!*p) p = "fetch.out"; fetchLastErrCode = 0; if (o_flag) { if (o_stdout) { e = fetch(*argv, "-"); } else if (o_directory) { asprintf(&q, "%s/%s", o_filename, p); e = fetch(*argv, q); free(q); } else { e = fetch(*argv, o_filename); } } else { e = fetch(*argv, p); } if (sigint) kill(getpid(), SIGINT); if (e == 0 && once_flag) exit(0); if (e) { r = 1; if ((fetchLastErrCode && fetchLastErrCode != FETCH_UNAVAIL && fetchLastErrCode != FETCH_MOVED && fetchLastErrCode != FETCH_URL && fetchLastErrCode != FETCH_RESOLV && fetchLastErrCode != FETCH_UNKNOWN)) { if (w_secs && v_level) fprintf(stderr, "Waiting %ld seconds " "before retrying\n", w_secs); if (w_secs) sleep(w_secs); if (a_flag) continue; } } argc--, argv++; } exit(r); }
int main(int argc, char **argv) { size_t sz; size_t buf_sz; int i, j; for (i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) { char *buf; sz = unparse_time(tests[i].val, NULL, 0); if (sz != tests[i].size) errx(1, "sz (%lu) != tests[%d].size (%lu)", (unsigned long)sz, i, (unsigned long)tests[i].size); for (buf_sz = 0; buf_sz < tests[i].size + 2; buf_sz++) { buf = rk_test_mem_alloc(RK_TM_OVERRUN, "overrun", NULL, buf_sz); sz = unparse_time(tests[i].val, buf, buf_sz); if (sz != tests[i].size) errx(1, "sz (%lu) != tests[%d].size (%lu) with in size %lu", (unsigned long)sz, i, (unsigned long)tests[i].size, (unsigned long)buf_sz); if (buf_sz > 0 && memcmp(buf, tests[i].str, buf_sz - 1) != 0) errx(1, "test %i wrong result %s vs %s", i, buf, tests[i].str); if (buf_sz > 0 && buf[buf_sz - 1] != '\0') errx(1, "test %i not zero terminated", i); rk_test_mem_free("overrun"); buf = rk_test_mem_alloc(RK_TM_UNDERRUN, "underrun", NULL, tests[i].size); sz = unparse_time(tests[i].val, buf, min(buf_sz, tests[i].size)); if (sz != tests[i].size) errx(1, "sz (%lu) != tests[%d].size (%lu) with insize %lu", (unsigned long)sz, i, (unsigned long)tests[i].size, (unsigned long)buf_sz); if (buf_sz > 0 && strncmp(buf, tests[i].str, min(buf_sz, tests[i].size) - 1) != 0) errx(1, "test %i wrong result %s vs %s", i, buf, tests[i].str); if (buf_sz > 0 && buf[min(buf_sz, tests[i].size) - 1] != '\0') errx(1, "test %i not zero terminated", i); rk_test_mem_free("underrun"); } buf = rk_test_mem_alloc(RK_TM_OVERRUN, "overrun", tests[i].str, tests[i].size + 1); j = parse_time(buf, "s"); if (j != tests[i].val) errx(1, "parse_time failed for test %d", i); rk_test_mem_free("overrun"); buf = rk_test_mem_alloc(RK_TM_UNDERRUN, "underrun", tests[i].str, tests[i].size + 1); j = parse_time(buf, "s"); if (j != tests[i].val) errx(1, "parse_time failed for test %d", i); rk_test_mem_free("underrun"); } return 0; }
int main(int argc, char *argv[]) { struct stat to_stat, tmp_stat; enum op type; int Hflag, Lflag, Pflag, ch, fts_options, r; char *target; (void)setlocale(LC_ALL, ""); Hflag = Lflag = Pflag = Rflag = xflag = 0; while ((ch = getopt(argc, argv, "HLPRfiprvx")) != -1) switch (ch) { case 'H': Hflag = 1; Lflag = Pflag = 0; break; case 'L': Lflag = 1; Hflag = Pflag = 0; break; case 'P': Pflag = 1; Hflag = Lflag = 0; break; case 'R': Rflag = 1; break; case 'f': fflag = 1; iflag = 0; break; case 'i': iflag = isatty(STDIN_FILENO); fflag = 0; break; case 'p': pflag = 1; break; case 'r': rflag = 1; break; case 'v': vflag = 1; break; case 'x': xflag = 1; break; default: usage(); break; } argc -= optind; argv += optind; if (argc < 2) usage(); fts_options = FTS_NOCHDIR | FTS_PHYSICAL; if (xflag) fts_options |= FTS_XDEV; if (rflag) { if (Rflag) errx(1, "the -R and -r options may not be specified together."); if (Hflag || Lflag || Pflag) errx(1, "the -H, -L, and -P options may not be specified with the -r option."); fts_options &= ~FTS_PHYSICAL; fts_options |= FTS_LOGICAL; } if (Rflag) { if (Hflag) fts_options |= FTS_COMFOLLOW; if (Lflag) { fts_options &= ~FTS_PHYSICAL; fts_options |= FTS_LOGICAL; } } else { fts_options &= ~FTS_PHYSICAL; fts_options |= FTS_LOGICAL; } myuid = getuid(); /* Copy the umask for explicit mode setting. */ myumask = umask(0); (void)umask(myumask); /* Save the target base in "to". */ target = argv[--argc]; if (strlcpy(to.p_path, target, sizeof to.p_path) >= sizeof(to.p_path)) errx(1, "%s: name too long", target); to.p_end = to.p_path + strlen(to.p_path); if (to.p_path == to.p_end) { *to.p_end++ = '.'; *to.p_end = '\0'; } to.target_end = to.p_end; /* Set end of argument list for fts(3). */ argv[argc] = NULL; /* * Cp has two distinct cases: * * cp [-R] source target * cp [-R] source1 ... sourceN directory * * In both cases, source can be either a file or a directory. * * In (1), the target becomes a copy of the source. That is, if the * source is a file, the target will be a file, and likewise for * directories. * * In (2), the real target is not directory, but "directory/source". */ r = stat(to.p_path, &to_stat); if (r == -1 && errno != ENOENT) err(1, "%s", to.p_path); if (r == -1 || !S_ISDIR(to_stat.st_mode)) { /* * Case (1). Target is not a directory. */ if (argc > 1) usage(); /* * Need to detect the case: * cp -R dir foo * Where dir is a directory and foo does not exist, where * we want pathname concatenations turned on but not for * the initial mkdir(). */ if (r == -1) { if (rflag || (Rflag && (Lflag || Hflag))) stat(*argv, &tmp_stat); else lstat(*argv, &tmp_stat); if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag)) type = DIR_TO_DNE; else type = FILE_TO_FILE; } else type = FILE_TO_FILE; } else { /* * Case (2). Target is a directory. */ type = FILE_TO_DIR; } exit(copy(argv, type, fts_options)); }
int main(int argc, char **argv) { struct passwd *pwd; int ch, count, newline; const char *file; char *sender, *p; #if MAXPATHLEN > BUFSIZ char buf[MAXPATHLEN]; #else char buf[BUFSIZ]; #endif file = sender = NULL; count = -1; while ((ch = getopt(argc, argv, "cf:s:")) != -1) switch (ch) { case 'c': count = 0; break; case 'f': file = optarg; break; case 's': sender = optarg; for (p = sender; *p; ++p) *p = tolower(*p); break; case '?': default: usage(); } argv += optind; if (file == NULL) { if (*argv) { snprintf(buf, sizeof(buf), "%s/%s", _PATH_MAILDIR, *argv); file = buf; } else { if ((file = getenv("MAIL")) == NULL) { if (!(pwd = getpwuid(getuid()))) errx(1, "no password file entry for you"); file = pwd->pw_name; snprintf(buf, sizeof(buf), "%s/%s", _PATH_MAILDIR, file); file = buf; } } } /* read from stdin */ if (strcmp(file, "-") == 0) { } else if (freopen(file, "r", stdin) == NULL) { err(1, "can't read %s", file); } for (newline = 1; fgets(buf, sizeof(buf), stdin);) { if (*buf == '\n') { newline = 1; continue; } if (newline && !strncmp(buf, "From ", 5) && (!sender || match(buf + 5, sender))) { if (count != -1) count++; else printf("%s", buf); } newline = 0; } if (count != -1) printf("There %s %d message%s in your incoming mailbox.\n", count == 1 ? "is" : "are", count, count == 1 ? "" : "s"); exit(0); }
int main(int argc, char *argv[]) { struct npestatfoo *wf; const char *ifname; int c, banner = 1; ifname = getenv("NPE"); if (ifname == NULL) ifname = "npe0"; wf = npestats_new(ifname, getfmt("default")); while ((c = getopt(argc, argv, "bi:lo:z")) != -1) { switch (c) { case 'b': banner = 0; break; case 'i': wf->setifname(wf, optarg); break; case 'l': wf->print_fields(wf, stdout); return 0; case 'o': wf->setfmt(wf, getfmt(optarg)); break; default: errx(-1, "usage: %s [-a] [-i ifname] [-l] [-o fmt] [interval]\n", argv[0]); /*NOTREACHED*/ } } argc -= optind; argv += optind; if (argc > 0) { u_long interval = strtoul(argv[0], NULL, 0); int line, omask; if (interval < 1) interval = 1; signal(SIGALRM, catchalarm); signalled = 0; alarm(interval); banner: if (banner) wf->print_header(wf, stdout); line = 0; loop: if (line != 0) { wf->collect_cur(wf); wf->print_current(wf, stdout); wf->update_tot(wf); } else { wf->collect_tot(wf); wf->print_total(wf, stdout); } fflush(stdout); omask = sigblock(sigmask(SIGALRM)); if (!signalled) sigpause(0); sigsetmask(omask); signalled = 0; alarm(interval); line++; if (line == 21) /* XXX tty line count */ goto banner; else goto loop; /*NOTREACHED*/ } else { wf->collect_tot(wf); wf->print_verbose(wf, stdout); } return 0; }
static void test_super(int *start, size_t * length) { struct stat st; /* find the physical size of the file or block device */ if (stat(filename, &st) < 0) err(FSCK_EX_ERROR, _("stat failed: %s"), filename); fd = open(filename, O_RDONLY); if (fd < 0) err(FSCK_EX_ERROR, _("open failed: %s"), filename); if (S_ISBLK(st.st_mode)) { unsigned long long bytes; if (blkdev_get_size(fd, &bytes)) err(FSCK_EX_ERROR, _("ioctl failed: unable to determine device size: %s"), filename); *length = bytes; } else if (S_ISREG(st.st_mode)) *length = st.st_size; else errx(FSCK_EX_ERROR, _("not a block device or file: %s"), filename); if (*length < sizeof(struct cramfs_super)) errx(FSCK_EX_UNCORRECTED, _("file length too short")); /* find superblock */ if (read(fd, &super, sizeof(super)) != sizeof(super)) err(FSCK_EX_ERROR, _("read failed: %s"), filename); if (get_superblock_endianness(super.magic) != -1) *start = 0; else if (*length >= (PAD_SIZE + sizeof(super))) { lseek(fd, PAD_SIZE, SEEK_SET); if (read(fd, &super, sizeof(super)) != sizeof(super)) err(FSCK_EX_ERROR, _("read failed: %s"), filename); if (get_superblock_endianness(super.magic) != -1) *start = PAD_SIZE; else errx(FSCK_EX_UNCORRECTED, _("superblock magic not found")); } else errx(FSCK_EX_UNCORRECTED, _("superblock magic not found")); if (opt_verbose) printf(_("cramfs endianness is %s\n"), cramfs_is_big_endian ? _("big") : _("little")); super_toggle_endianness(cramfs_is_big_endian, &super); if (super.flags & ~CRAMFS_SUPPORTED_FLAGS) errx(FSCK_EX_ERROR, _("unsupported filesystem features")); if (super.size < page_size) errx(FSCK_EX_UNCORRECTED, _("superblock size (%d) too small"), super.size); if (super.flags & CRAMFS_FLAG_FSID_VERSION_2) { if (super.fsid.files == 0) errx(FSCK_EX_UNCORRECTED, _("zero file count")); if (*length < super.size) errx(FSCK_EX_UNCORRECTED, _("file length too short")); else if (*length > super.size) fprintf(stderr, _("warning: file extends past end of filesystem\n")); } else fprintf(stderr, _("warning: old cramfs format\n")); }
void rewrite(FS *fs) { enum { NOTOKAY, USEBCNT, USEPREC } sokay; PR *pr, **nextpr = NULL; FU *fu; unsigned char *p1, *p2, *fmtp; char savech, cs[3]; int nconv, prec = 0; for (fu = fs->nextfu; fu; fu = fu->nextfu) { /* * Break each format unit into print units; each conversion * character gets its own. */ for (nconv = 0, fmtp = fu->fmt; *fmtp; nextpr = &pr->nextpr) { if ((pr = calloc(1, sizeof(PR))) == NULL) err(1, NULL); if (!fu->nextpr) fu->nextpr = pr; else *nextpr = pr; /* Skip preceding text and up to the next % sign. */ for (p1 = fmtp; *p1 && *p1 != '%'; ++p1); /* Only text in the string. */ if (!*p1) { pr->fmt = fmtp; pr->flags = F_TEXT; break; } /* * Get precision for %s -- if have a byte count, don't * need it. */ if (fu->bcnt) { sokay = USEBCNT; /* Skip to conversion character. */ for (++p1; strchr(spec, *p1); ++p1); } else { /* Skip any special chars, field width. */ while (strchr(spec + 1, *++p1)); if (*p1 == '.' && isdigit(*++p1)) { sokay = USEPREC; prec = atoi(p1); while (isdigit(*++p1)); } else sokay = NOTOKAY; } p2 = p1 + 1; /* Set end pointer. */ cs[0] = *p1; /* Set conversion string. */ cs[1] = '\0'; /* * Figure out the byte count for each conversion; * rewrite the format as necessary, set up blank- * padding for end of data. */ switch(cs[0]) { case 'c': pr->flags = F_CHAR; switch(fu->bcnt) { case 0: case 1: pr->bcnt = 1; break; default: p1[1] = '\0'; badcnt(p1); } break; case 'd': case 'i': pr->flags = F_INT; goto isint; case 'o': case 'u': case 'x': case 'X': pr->flags = F_UINT; isint: cs[2] = '\0'; cs[1] = cs[0]; cs[0] = 'q'; switch(fu->bcnt) { case 0: case 4: pr->bcnt = 4; break; case 1: pr->bcnt = 1; break; case 2: pr->bcnt = 2; break; default: p1[1] = '\0'; badcnt(p1); } break; case 'e': case 'E': case 'f': case 'g': case 'G': pr->flags = F_DBL; switch(fu->bcnt) { case 0: case 8: pr->bcnt = 8; break; case 4: pr->bcnt = 4; break; default: if (fu->bcnt == sizeof(long double)) { cs[2] = '\0'; cs[1] = cs[0]; cs[0] = 'L'; pr->bcnt = sizeof(long double); } else { p1[1] = '\0'; badcnt(p1); } } break; case 's': pr->flags = F_STR; switch(sokay) { case NOTOKAY: badsfmt(); case USEBCNT: pr->bcnt = fu->bcnt; break; case USEPREC: pr->bcnt = prec; break; } break; case '_': ++p2; switch(p1[1]) { case 'A': endfu = fu; fu->flags |= F_IGNORE; /* FALLTHROUGH */ case 'a': pr->flags = F_ADDRESS; ++p2; switch(p1[2]) { case 'd': case 'o': case'x': cs[0] = 'q'; cs[1] = p1[2]; cs[2] = '\0'; break; default: p1[3] = '\0'; badconv(p1); } break; case 'c': pr->flags = F_C; /* cs[0] = 'c'; set in conv_c */ goto isint2; case 'p': pr->flags = F_P; cs[0] = 'c'; goto isint2; case 'u': pr->flags = F_U; /* cs[0] = 'c'; set in conv_u */ isint2: switch(fu->bcnt) { case 0: case 1: pr->bcnt = 1; break; default: p1[2] = '\0'; badcnt(p1); } break; default: p1[2] = '\0'; badconv(p1); } break; default: p1[1] = '\0'; badconv(p1); } /* * Copy to PR format string, set conversion character * pointer, update original. */ savech = *p2; p1[0] = '\0'; if ((pr->fmt = calloc(1, strlen(fmtp) + 2)) == NULL) err(1, NULL); (void)strcpy(pr->fmt, fmtp); (void)strcat(pr->fmt, cs); *p2 = savech; pr->cchar = pr->fmt + (p1 - fmtp); fmtp = p2; /* Only one conversion character if byte count. */ if (!(pr->flags&F_ADDRESS) && fu->bcnt && nconv++) errx(1, "byte count with multiple conversion characters"); } /* * If format unit byte count not specified, figure it out * so can adjust rep count later. */ if (!fu->bcnt) for (pr = fu->nextpr; pr; pr = pr->nextpr) fu->bcnt += pr->bcnt; } /* * If the format string interprets any data at all, and it's * not the same as the blocksize, and its last format unit * interprets any data at all, and has no iteration count, * repeat it as necessary. * * If, rep count is greater than 1, no trailing whitespace * gets output from the last iteration of the format unit. */ for (fu = fs->nextfu; fu; fu = fu->nextfu) { if (!fu->nextfu && fs->bcnt < blocksize && !(fu->flags&F_SETREP) && fu->bcnt) fu->reps += (blocksize - fs->bcnt) / fu->bcnt; if (fu->reps > 1) { for (pr = fu->nextpr;; pr = pr->nextpr) if (!pr->nextpr) break; for (p1 = pr->fmt, p2 = NULL; *p1; ++p1) p2 = isspace(*p1) ? p1 : NULL; if (p2) pr->nospace = p2; } } #ifdef DEBUG for (fu = fs->nextfu; fu; fu = fu->nextfu) { (void)printf("fmt:"); for (pr = fu->nextpr; pr; pr = pr->nextpr) (void)printf(" {%s}", pr->fmt); (void)printf("\n"); } #endif }
static void test_crc(int start) { void *buf; uint32_t crc; if (!(super.flags & CRAMFS_FLAG_FSID_VERSION_2)) { #ifdef INCLUDE_FS_TESTS return; #else errx(FSCK_EX_USAGE, _("unable to test CRC: old cramfs format")); #endif } crc = crc32(0L, Z_NULL, 0); buf = mmap(NULL, super.size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if (buf == MAP_FAILED) { buf = mmap(NULL, super.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (buf != MAP_FAILED) { lseek(fd, 0, SEEK_SET); if (read(fd, buf, super.size) < 0) err(FSCK_EX_ERROR, _("read failed: %s"), filename); } } if (buf != MAP_FAILED) { ((struct cramfs_super *)(buf + start))->fsid.crc = crc32(0L, Z_NULL, 0); crc = crc32(crc, buf + start, super.size - start); munmap(buf, super.size); } else { int retval; size_t length = 0; buf = xmalloc(4096); lseek(fd, start, SEEK_SET); for (;;) { retval = read(fd, buf, 4096); if (retval < 0) err(FSCK_EX_ERROR, _("read failed: %s"), filename); else if (retval == 0) break; if (length == 0) ((struct cramfs_super *)buf)->fsid.crc = crc32(0L, Z_NULL, 0); length += retval; if (length > (super.size - start)) { crc = crc32(crc, buf, retval - (length - (super.size - start))); break; } crc = crc32(crc, buf, retval); } free(buf); } if (crc != super.fsid.crc) errx(FSCK_EX_UNCORRECTED, _("crc error")); }
void badsfmt(void) { errx(1, "%%s: requires a precision or a byte count"); }
static void fetch_l3(npf_bpf_t *ctx, sa_family_t af, u_int flags) { u_int ver; switch (af) { case AF_INET: ver = IPVERSION; break; case AF_INET6: ver = IPV6_VERSION >> 4; break; case AF_UNSPEC: ver = 0; break; default: abort(); } /* * The memory store is populated with: * - BPF_MW_IPVER: IP version (4 or 6). * - BPF_MW_L4OFF: L4 header offset. * - BPF_MW_L4PROTO: L4 protocol. */ if ((ctx->flags & FETCHED_L3) == 0 || (af && ctx->af == 0)) { const uint8_t jt = ver ? 0 : JUMP_MAGIC; const uint8_t jf = ver ? JUMP_MAGIC : 0; bool ingroup = ctx->ingroup; /* * L3 block cannot be inserted in the middle of a group. * In fact, it never is. Check and start the group after. */ if (ingroup) { assert(ctx->nblocks == ctx->gblock); npfctl_bpf_endgroup(ctx); } /* * A <- IP version; A == expected-version? * If no particular version specified, check for non-zero. */ struct bpf_insn insns_af[] = { BPF_STMT(BPF_LD+BPF_W+BPF_MEM, BPF_MW_IPVER), BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, ver, jt, jf), }; add_insns(ctx, insns_af, __arraycount(insns_af)); ctx->flags |= FETCHED_L3; ctx->af = af; if (af) { uint32_t mwords[] = { BM_IPVER, 1, af }; done_raw_block(ctx, mwords, sizeof(mwords)); } if (ingroup) { npfctl_bpf_group(ctx); } } else if (af && af != ctx->af) { errx(EXIT_FAILURE, "address family mismatch"); } if ((flags & X_EQ_L4OFF) != 0 && (ctx->flags & X_EQ_L4OFF) == 0) { /* X <- IP header length */ struct bpf_insn insns_hlen[] = { BPF_STMT(BPF_LDX+BPF_MEM, BPF_MW_L4OFF), }; add_insns(ctx, insns_hlen, __arraycount(insns_hlen)); ctx->flags |= X_EQ_L4OFF; } }
void badconv(char *ch) { errx(1, "%%%s: bad conversion character", ch); }
int main(int argc, char *argv[]) { char *domnam = NULL, *master; char *map = NULL; struct ypmaplist *ypml, *y; struct hostent *hent; struct sockaddr_in lsin; int notrans, mode; int c, r; u_int i; notrans = mode = 0; while ((c = getopt(argc, argv, "xd:mt")) != -1) switch (c) { case 'x': for (i = 0; i<sizeof ypaliases/sizeof ypaliases[0]; i++) printf("\"%s\" is an alias for \"%s\"\n", ypaliases[i].alias, ypaliases[i].name); exit(0); case 'd': domnam = optarg; break; case 't': notrans++; break; case 'm': mode++; break; default: usage(); } if (!domnam) yp_get_default_domain(&domnam); if (mode == 0) { switch (argc-optind) { case 0: bzero(&lsin, sizeof lsin); lsin.sin_family = AF_INET; lsin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); if (bind_host(domnam, &lsin)) exit(ERR_NOBINDING); break; case 1: bzero(&lsin, sizeof lsin); lsin.sin_family = AF_INET; if ((lsin.sin_addr.s_addr = inet_addr(argv[optind])) == INADDR_NONE) { hent = gethostbyname(argv[optind]); if (!hent) errx(ERR_NOSUCHHOST, "host %s unknown", argv[optind]); bcopy((char *)hent->h_addr_list[0], (char *)&lsin.sin_addr, sizeof lsin.sin_addr); } if (bind_host(domnam, &lsin)) exit(ERR_NOBINDING); break; default: usage(); } exit(0); } if (argc-optind > 1) usage(); if (argv[optind]) { map = argv[optind]; for (i = 0; (!notrans) && i<sizeof ypaliases/sizeof ypaliases[0]; i++) if (strcmp(map, ypaliases[i].alias) == 0) map = ypaliases[i].name; r = yp_master(domnam, map, &master); switch (r) { case 0: printf("%s\n", master); free(master); break; case YPERR_YPBIND: errx(ERR_NOYPBIND, "not running ypbind"); default: errx(ERR_NOMASTER, "can't find master for map %s: reason: %s", map, yperr_string(r)); } exit(0); } ypml = NULL; r = yp_maplist(domnam, &ypml); switch (r) { case 0: for (y = ypml; y;) { ypml = y; r = yp_master(domnam, ypml->ypml_name, &master); switch (r) { case 0: printf("%s %s\n", ypml->ypml_name, master); free(master); break; default: warnx("can't find the master of %s: reason: %s", ypml->ypml_name, yperr_string(r)); break; } y = ypml->ypml_next; free(ypml); } break; case YPERR_YPBIND: errx(ERR_NOYPBIND, "not running ypbind"); default: errx(ERR_NOMASTER, "can't get map list for domain %s: reason: %s", domnam, yperr_string(r)); } exit(0); }
static void usage(void) { errx(1, "usage: dataman {start|stop|status|poweronrestart|inflightrestart}"); }
int main(int argc, char *argv[]) { struct pidfh *ppfh, *pfh; sigset_t mask, oldmask; int ch, nochdir, noclose, restart, serrno; const char *pidfile, *ppidfile, *user; pid_t otherpid, pid; nochdir = noclose = 1; restart = 0; ppidfile = pidfile = user = NULL; while ((ch = getopt(argc, argv, "cfp:P:ru:")) != -1) { switch (ch) { case 'c': nochdir = 0; break; case 'f': noclose = 0; break; case 'p': pidfile = optarg; break; case 'P': ppidfile = optarg; break; case 'r': restart = 1; break; case 'u': user = optarg; break; default: usage(); } } argc -= optind; argv += optind; if (argc == 0) usage(); ppfh = pfh = NULL; /* * Try to open the pidfile before calling daemon(3), * to be able to report the error intelligently */ if (pidfile != NULL) { pfh = pidfile_open(pidfile, 0600, &otherpid); if (pfh == NULL) { if (errno == EEXIST) { errx(3, "process already running, pid: %d", otherpid); } err(2, "pidfile ``%s''", pidfile); } } /* Do the same for actual daemon process. */ if (ppidfile != NULL) { ppfh = pidfile_open(ppidfile, 0600, &otherpid); if (ppfh == NULL) { serrno = errno; pidfile_remove(pfh); errno = serrno; if (errno == EEXIST) { errx(3, "process already running, pid: %d", otherpid); } err(2, "ppidfile ``%s''", ppidfile); } } if (daemon(nochdir, noclose) == -1) { warn("daemon"); goto exit; } /* Write out parent pidfile if needed. */ pidfile_write(ppfh); /* * If the pidfile or restart option is specified the daemon * executes the command in a forked process and wait on child * exit to remove the pidfile or restart the command. Normally * we don't want the monitoring daemon to be terminated * leaving the running process and the stale pidfile, so we * catch SIGTERM and forward it to the children expecting to * get SIGCHLD eventually. */ pid = -1; if (pidfile != NULL || restart) { /* * Restore default action for SIGTERM in case the * parent process decided to ignore it. */ if (signal(SIGTERM, SIG_DFL) == SIG_ERR) { warn("signal"); goto exit; } /* * Because SIGCHLD is ignored by default, setup dummy handler * for it, so we can mask it. */ if (signal(SIGCHLD, dummy_sighandler) == SIG_ERR) { warn("signal"); goto exit; } /* * Block interesting signals. */ sigemptyset(&mask); sigaddset(&mask, SIGTERM); sigaddset(&mask, SIGCHLD); if (sigprocmask(SIG_SETMASK, &mask, &oldmask) == -1) { warn("sigprocmask"); goto exit; } /* * Try to protect against pageout kill. Ignore the * error, madvise(2) will fail only if a process does * not have superuser privileges. */ (void)madvise(NULL, 0, MADV_PROTECT); restart: /* * Spawn a child to exec the command, so in the parent * we could wait for it to exit and remove pidfile. */ pid = fork(); if (pid == -1) { warn("fork"); goto exit; } } if (pid <= 0) { if (pid == 0) { /* Restore old sigmask in the child. */ if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1) err(1, "sigprocmask"); } /* Now that we are the child, write out the pid. */ pidfile_write(pfh); if (user != NULL) restrict_process(user); execvp(argv[0], argv); /* * execvp() failed -- report the error. The child is * now running, so the exit status doesn't matter. */ err(1, "%s", argv[0]); } setproctitle("%s[%d]", argv[0], pid); if (wait_child(pid, &mask) == 0 && restart) { sleep(1); goto restart; } exit: pidfile_remove(pfh); pidfile_remove(ppfh); exit(1); /* If daemon(3) succeeded exit status does not matter. */ }
/* * Write an ELF coredump for the given pid to the given fd. */ void elf_coredump(int fd, pid_t pid) { vm_map_entry_t map; struct sseg_closure seginfo; void *hdr; size_t hdrsize; char memname[64]; int memfd; Elf_Phdr *php; int i; /* Get the program's memory map. */ map = readmap(pid); /* Size the program segments. */ seginfo.count = 0; seginfo.size = 0; each_writable_segment(map, cb_size_segment, &seginfo); /* * Calculate the size of the core file header area by making * a dry run of generating it. Nothing is written, but the * size is calculated. */ hdrsize = 0; elf_puthdr(map, NULL, &hdrsize, NULL, NULL, NULL, seginfo.count); /* * Allocate memory for building the header, fill it up, * and write it out. */ hdr = malloc(hdrsize); if ((hdr = malloc(hdrsize)) == NULL) errx(1, "out of memory"); elf_corehdr(fd, pid, map, seginfo.count, hdr, hdrsize); /* Write the contents of all of the writable segments. */ snprintf(memname, sizeof memname, "/proc/%d/mem", pid); if ((memfd = open(memname, O_RDONLY)) == -1) err(1, "cannot open %s", memname); php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1; for (i = 0; i < seginfo.count; i++) { int nleft = php->p_filesz; lseek(memfd, (off_t)php->p_vaddr, SEEK_SET); while (nleft > 0) { char buf[8*1024]; int nwant; int ngot; nwant = nleft; if (nwant > sizeof buf) nwant = sizeof buf; ngot = read(memfd, buf, nwant); if (ngot == -1) err(1, "read from %s", memname); if (ngot < nwant) errx(1, "short read from %s:" " wanted %d, got %d\n", memname, nwant, ngot); ngot = write(fd, buf, nwant); if (ngot == -1) err(1, "write of segment %d failed", i); if (ngot != nwant) errx(1, "short write"); nleft -= nwant; } php++; } close(memfd); free(hdr); freemap(map); }
int main(int argc, char *argv[]) { char ch, *ep; double bm_sigma = 0.2, temp_end = 1, temp_init = 100, init_state = 0; double k = 0; FILE *toimport = NULL; FILE *log = NULL; while ((ch = getopt(argc, argv, "f:i:s:e:b:k:l:?h")) != -1) switch (ch) { case 'l': if ((log = fopen(optarg, "w")) == NULL) errx(EX_DATAERR, "Unable to open file %s", optarg); break; case 'f': if ((toimport = fopen(optarg, "r")) == NULL) errx(EX_DATAERR, "Unable to open file %s", optarg); break; case 'i': if ((init_state = strtod(optarg, &ep)) < 0) usage(); init_state = fmod(init_state, 2 * M_PI); break; case 's': if ((bm_sigma = strtod(optarg, &ep)) <= 0) usage(); break; case 'e': if ((temp_end = strtod(optarg, &ep)) <= 0) usage(); break; case 'b': if ((temp_init = strtod(optarg, &ep)) <= 0) usage(); break; case 'k': if ((k = strtod(optarg, &ep)) <= 0) usage(); break; case '?': case 'h': default: usage(); } if (toimport == NULL) { warnx("No import file!"); usage(); } if (temp_end > temp_init) { warnx("The end temperature must be smaller than the begin temperature."); usage(); } warnx("Start solving with initial state %1.4lf begin temp %04.2lf \ end temp %04.2lf Brownian motion sigma %lf", init_state, temp_init, temp_end, bm_sigma); argc -= optind; argv += optind; /* Load and initialize the tsp data set for the renormalization. */ tsp = import_tsp(toimport); preprocess_routes(); fclose(toimport); double energy = thermo_sa(temp_init, temp_end, 0.01, init_state, bm_sigma, k, log); warnx("Best energy found %lf", energy); fclose(log); return EX_OK; }