void procstat_threads(struct procstat *procstat, struct kinfo_proc *kipp) { struct kinfo_proc *kip; unsigned int count, i; const char *str; char *threadid; if (!hflag) xo_emit("{T:/%5s %6s %-19s %-19s %2s %4s %-7s %-9s}\n", "PID", "TID", "COMM", "TDNAME", "CPU", "PRI", "STATE", "WCHAN"); xo_emit("{ek:process_id/%d}", kipp->ki_pid); xo_emit("{e:command/%s}", strlen(kipp->ki_comm) ? kipp->ki_comm : "-"); xo_open_container("threads"); kip = procstat_getprocs(procstat, KERN_PROC_PID | KERN_PROC_INC_THREAD, kipp->ki_pid, &count); if (kip == NULL) return; kinfo_proc_sort(kip, count); for (i = 0; i < count; i++) { kipp = &kip[i]; asprintf(&threadid, "%d", kipp->ki_tid); if (threadid == NULL) xo_errc(1, ENOMEM, "Failed to allocate memory in " "procstat_threads()"); xo_open_container(threadid); xo_emit("{dk:process_id/%5d/%d} ", kipp->ki_pid); xo_emit("{:thread_id/%6d/%d} ", kipp->ki_tid); xo_emit("{d:command/%-19s/%s} ", strlen(kipp->ki_comm) ? kipp->ki_comm : "-"); xo_emit("{:thread_name/%-19s/%s} ", kinfo_proc_thread_name(kipp)); if (kipp->ki_oncpu != 255) xo_emit("{:cpu/%3d/%d} ", kipp->ki_oncpu); else if (kipp->ki_lastcpu != 255) xo_emit("{:cpu/%3d/%d} ", kipp->ki_lastcpu); else xo_emit("{:cpu/%3s/%s} ", "-"); xo_emit("{:priority/%4d/%d} ", kipp->ki_pri.pri_level); switch (kipp->ki_stat) { case SRUN: str = "run"; break; case SSTOP: str = "stop"; break; case SSLEEP: str = "sleep"; break; case SLOCK: str = "lock"; break; case SWAIT: str = "wait"; break; case SZOMB: str = "zomb"; break; case SIDL: str = "idle"; break; default: str = "??"; break; } xo_emit("{:run_state/%-7s/%s} ", str); if (kipp->ki_kiflag & KI_LOCKBLOCK) { xo_emit("{:lock_name/*%-8s/%s} ", strlen(kipp->ki_lockname) ? kipp->ki_lockname : "-"); } else { xo_emit("{:wait_channel/%-9s/%s} ", strlen(kipp->ki_wmesg) ? kipp->ki_wmesg : "-"); } xo_close_container(threadid); free(threadid); xo_emit("\n"); } xo_close_container("threads"); procstat_freeprocs(procstat, kip); }
/* * Dump ICMP6 statistics. */ void icmp6_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct icmp6stat icmp6stat, zerostat; int i, first; size_t len; len = sizeof icmp6stat; if (live) { memset(&icmp6stat, 0, len); if (zflag) memset(&zerostat, 0, len); if (sysctlbyname("net.inet6.icmp6.stats", &icmp6stat, &len, zflag ? &zerostat : NULL, zflag ? len : 0) < 0) { if (errno != ENOENT) xo_warn("sysctl: net.inet6.icmp6.stats"); return; } } else kread_counters(off, &icmp6stat, len); xo_emit("{T:/%s}:\n", name); xo_open_container(name); #define p(f, m) if (icmp6stat.f || sflag <= 1) \ xo_emit(m, (uintmax_t)icmp6stat.f, plural(icmp6stat.f)) #define p_5(f, m) if (icmp6stat.f || sflag <= 1) \ xo_emit(m, (uintmax_t)icmp6stat.f) p(icp6s_error, "\t{:icmp6-calls/%ju} " "{N:/call%s to icmp6_error}\n"); p(icp6s_canterror, "\t{:errors-not-generated-from-message/%ju} " "{N:/error%s not generated in response to an icmp6 message}\n"); p(icp6s_toofreq, "\t{:errors-discarded-by-rate-limitation/%ju} " "{N:/error%s not generated because of rate limitation}\n"); #define NELEM (int)(sizeof(icmp6stat.icp6s_outhist)/sizeof(icmp6stat.icp6s_outhist[0])) for (first = 1, i = 0; i < NELEM; i++) if (icmp6stat.icp6s_outhist[i] != 0) { if (first) { xo_open_list("output-histogram"); xo_emit("\t{T:Output histogram}:\n"); first = 0; } xo_open_instance("output-histogram"); xo_emit("\t\t{k:name/%s}: {:count/%ju}\n", icmp6names[i], (uintmax_t)icmp6stat.icp6s_outhist[i]); xo_close_instance("output-histogram"); } if (!first) xo_close_list("output-histogram"); #undef NELEM p(icp6s_badcode, "\t{:dropped-bad-code/%ju} " "{N:/message%s with bad code fields}\n"); p(icp6s_tooshort, "\t{:dropped-too-short/%ju} " "{N:/message%s < minimum length}\n"); p(icp6s_checksum, "\t{:dropped-bad-checksum/%ju} " "{N:/bad checksum%s}\n"); p(icp6s_badlen, "\t{:dropped-bad-length/%ju} " "{N:/message%s with bad length}\n"); #define NELEM (int)(sizeof(icmp6stat.icp6s_inhist)/sizeof(icmp6stat.icp6s_inhist[0])) for (first = 1, i = 0; i < NELEM; i++) if (icmp6stat.icp6s_inhist[i] != 0) { if (first) { xo_open_list("input-histogram"); xo_emit("\t{T:Input histogram}:\n"); first = 0; } xo_open_instance("input-histogram"); xo_emit("\t\t{k:name/%s}: {:count/%ju}\n", icmp6names[i], (uintmax_t)icmp6stat.icp6s_inhist[i]); xo_close_instance("input-histogram"); } if (!first) xo_close_list("input-histogram"); #undef NELEM xo_emit("\t{T:Histogram of error messages to be generated}:\n"); xo_open_container("errors"); p_5(icp6s_odst_unreach_noroute, "\t\t{:no-route/%ju} " "{N:/no route}\n"); p_5(icp6s_odst_unreach_admin, "\t\t{:admin-prohibited/%ju} " "{N:/administratively prohibited}\n"); p_5(icp6s_odst_unreach_beyondscope, "\t\t{:beyond-scope/%ju} " "{N:/beyond scope}\n"); p_5(icp6s_odst_unreach_addr, "\t\t{:address-unreachable/%ju} " "{N:/address unreachable}\n"); p_5(icp6s_odst_unreach_noport, "\t\t{:port-unreachable/%ju} " "{N:/port unreachable}\n"); p_5(icp6s_opacket_too_big, "\t\t{:packet-too-big/%ju} " "{N:/packet too big}\n"); p_5(icp6s_otime_exceed_transit, "\t\t{:time-exceed-transmit/%ju} " "{N:/time exceed transit}\n"); p_5(icp6s_otime_exceed_reassembly, "\t\t{:time-exceed-reassembly/%ju} " "{N:/time exceed reassembly}\n"); p_5(icp6s_oparamprob_header, "\t\t{:bad-header/%ju} " "{N:/erroneous header field}\n"); p_5(icp6s_oparamprob_nextheader, "\t\t{:bad-next-header/%ju} " "{N:/unrecognized next header}\n"); p_5(icp6s_oparamprob_option, "\t\t{:bad-option/%ju} " "{N:/unrecognized option}\n"); p_5(icp6s_oredirect, "\t\t{:redirects/%ju} " "{N:/redirect}\n"); p_5(icp6s_ounknown, "\t\t{:unknown/%ju} {N:unknown}\n"); p(icp6s_reflect, "\t{:reflect/%ju} " "{N:/message response%s generated}\n"); p(icp6s_nd_toomanyopt, "\t{:too-many-nd-options/%ju} " "{N:/message%s with too many ND options}\n"); p(icp6s_nd_badopt, "\t{:bad-nd-options/%ju} " "{N:/message%s with bad ND options}\n"); p(icp6s_badns, "\t{:bad-neighbor-solicitation/%ju} " "{N:/bad neighbor solicitation message%s}\n"); p(icp6s_badna, "\t{:bad-neighbor-advertisement/%ju} " "{N:/bad neighbor advertisement message%s}\n"); p(icp6s_badrs, "\t{:bad-router-solicitation/%ju} " "{N:/bad router solicitation message%s}\n"); p(icp6s_badra, "\t{:bad-router-advertisement/%ju} " "{N:/bad router advertisement message%s}\n"); p(icp6s_badredirect, "\t{:bad-redirect/%ju} " "{N:/bad redirect message%s}\n"); xo_close_container("errors"); p(icp6s_pmtuchg, "\t{:path-mtu-changes/%ju} {N:/path MTU change%s}\n"); #undef p #undef p_5 xo_close_container(name); }
int main (int argc, char **argv) { argc = xo_parse_args(argc, argv); if (argc < 0) return 1; for (argc = 1; argv[argc]; argc++) { if (strcmp(argv[argc], "xml") == 0) xo_set_style(NULL, XO_STYLE_XML); else if (strcmp(argv[argc], "json") == 0) xo_set_style(NULL, XO_STYLE_JSON); else if (strcmp(argv[argc], "text") == 0) xo_set_style(NULL, XO_STYLE_TEXT); else if (strcmp(argv[argc], "html") == 0) xo_set_style(NULL, XO_STYLE_HTML); else if (strcmp(argv[argc], "pretty") == 0) xo_set_flags(NULL, XOF_PRETTY); else if (strcmp(argv[argc], "xpath") == 0) xo_set_flags(NULL, XOF_XPATH); else if (strcmp(argv[argc], "info") == 0) xo_set_flags(NULL, XOF_INFO); } xo_set_flags(NULL, XOF_UNITS); /* Always test w/ this */ xo_open_container_h(NULL, "top"); xo_open_container("data"); xo_emit("We are {{emit}}{{ting}} some {:what}\n", "braces"); xo_message("abcdef"); close(-1); xo_message_e("abcdef"); xo_message("improper use of profanity; %s; %s", "ten yard penalty", "first down"); xo_emit("length {:length/%6.6s}\n", "abcdefghijklmnopqrstuvwxyz"); close(-1); xo_emit("close {:fd/%d} returned {:error/%m} {:test}\n", -1, "good"); close(-1); xo_emit("close {:fd/%d} returned {:error/%6.6m} {:test}\n", -1, "good"); xo_message("improper use of profanity; %s; %s", "ten yard penalty", "first down"); xo_emit(" {:lines/%7ju} {:words/%7ju} " "{:characters/%7ju} {d:filename/%s}\n", 20, 30, 40, "file"); int i; for (i = 0; i < 5; i++) xo_emit("{lw:bytes/%d}{Np:byte,bytes}\n", i); xo_emit("{:mbuf-current/%u}/{:mbuf-cache/%u}/{:mbuf-total/%u} " "{N:mbufs <&> in use (current\\/cache\\/total)}\n", 10, 20, 30); xo_emit("{:distance/%u}{Uw:miles} from {:location}\n", 50, "Boston"); xo_emit("{:memory/%u}{U:k} left out of {:total/%u}{U:kb}\n", 64, 640); xo_emit("{:memory/%u}{U:/%s} left out of {:total/%u}{U:/%s}\n", 64, "k", 640, "kilobytes"); xo_emit("{,title:/before%safter:}\n", "working"); xo_emit("{,display,white,colon:some/%s}" "{,value:ten/%ju}{,value:eleven/%ju}\n", "string", (uintmax_t) 10, (uintmax_t) 11); xo_emit("{:unknown/%u} " "{N:/packet%s here\\/there\\/everywhere}\n", 1010, "s"); xo_emit("{:unknown/%u} " "{,note:/packet%s here\\/there\\/everywhere}\n", 1010, "s"); xo_emit("({[:/%d}{n:min/15}/{n:cur/20}/{:max/%d}{]:})\n", 30, 125); xo_emit("({[:30}{:min/%u}/{:cur/%u}/{:max/%u}{]:})\n", 15, 20, 125); xo_emit("({[:-30}{n:min/15}/{n:cur/20}/{n:max/125}{]:})\n"); xo_emit("({[:}{:min/%u}/{:cur/%u}/{:max/%u}{]:/%d})\n", 15, 20, 125, -30); xo_emit("Humanize: {h:val1/%u}, {h,hn-space:val2/%u}, " "{h,hn-decimal:val3/%u}, {h,hn-1000:val4/%u}, " "{h,hn-decimal:val5/%u}\n", 21, 57 * 1024, 96 * 1024 * 1024, (42 * 1024 + 420) * 1024, 1342172800); xo_open_list("flag"); xo_emit("{lq:flag/one} {lq:flag/two} {lq:flag/three}\n"); xo_close_list("flag"); xo_emit("{n:works/%s}\n", NULL); xo_emit("{e:empty-tag/}"); xo_emit("1:{qt:t1/%*d} 2:{qt:t2/test%-*u} " "3:{qt:t3/%10sx} 4:{qt:t4/x%-*.*s}\n", 6, 1000, 8, 5000, "ten-long", 10, 10, "test"); xo_emit("{E:this is an error}\n"); xo_emit("{E:/%s more error%s}\n", "two", "s" ); xo_emit("{W:this is an warning}\n"); xo_emit("{W:/%s more warning%s}\n", "two", "s" ); xo_emit("{L:/V1\\/V2 packet%s}: {:count/%u}\n", "s", 10); int test = 4; xo_emit("{:test/%04d} {L:/tr%s}\n", test, (test == 1) ? "y" : "ies"); xo_message("improper use of profanity; %s; %s", "ten yard penalty", "first down"); xo_error("Shut 'er down, Clancey! She's a-pumpin' mud! <>!,\"!<>\n"); xo_close_container("data"); xo_close_container_h(NULL, "top"); xo_finish(); return 0; }
static void p_rtable_sysctl(int fibnum, int af) { size_t needed; int mib[7]; char *buf, *next, *lim; struct rt_msghdr *rtm; struct sockaddr *sa; int fam = AF_UNSPEC, ifindex = 0, size; int need_table_close = false; struct ifaddrs *ifap, *ifa; struct sockaddr_dl *sdl; /* * Retrieve interface list at first * since we need #ifindex -> if_xname match */ if (getifaddrs(&ifap) != 0) err(EX_OSERR, "getifaddrs"); for (ifa = ifap; ifa; ifa = ifa->ifa_next) { if (ifa->ifa_addr->sa_family != AF_LINK) continue; sdl = (struct sockaddr_dl *)ifa->ifa_addr; ifindex = sdl->sdl_index; if (ifindex >= ifmap_size) { size = roundup(ifindex + 1, 32) * sizeof(struct ifmap_entry); if ((ifmap = realloc(ifmap, size)) == NULL) errx(2, "realloc(%d) failed", size); memset(&ifmap[ifmap_size], 0, size - ifmap_size * sizeof(struct ifmap_entry)); ifmap_size = roundup(ifindex + 1, 32); } if (*ifmap[ifindex].ifname != '\0') continue; strlcpy(ifmap[ifindex].ifname, ifa->ifa_name, IFNAMSIZ); } freeifaddrs(ifap); mib[0] = CTL_NET; mib[1] = PF_ROUTE; mib[2] = 0; mib[3] = af; mib[4] = NET_RT_DUMP; mib[5] = 0; mib[6] = fibnum; if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0) err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af, fibnum); if ((buf = malloc(needed)) == NULL) errx(2, "malloc(%lu)", (unsigned long)needed); if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0) err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum); lim = buf + needed; xo_open_container("route-table"); xo_open_list("rt-family"); for (next = buf; next < lim; next += rtm->rtm_msglen) { rtm = (struct rt_msghdr *)next; if (rtm->rtm_version != RTM_VERSION) continue; /* * Peek inside header to determine AF */ sa = (struct sockaddr *)(rtm + 1); /* Only print family first time. */ if (fam != sa->sa_family) { if (need_table_close) { xo_close_list("rt-entry"); xo_close_instance("rt-family"); } need_table_close = true; fam = sa->sa_family; wid_dst = WID_DST_DEFAULT(fam); wid_gw = WID_GW_DEFAULT(fam); wid_flags = 6; wid_pksent = 8; wid_mtu = 6; wid_if = WID_IF_DEFAULT(fam); wid_expire = 6; xo_open_instance("rt-family"); pr_family(fam); xo_open_list("rt-entry"); pr_rthdr(fam); } p_rtentry_sysctl("rt-entry", rtm); } if (need_table_close) { xo_close_list("rt-entry"); xo_close_instance("rt-family"); } xo_close_list("rt-family"); xo_close_container("route-table"); free(buf); }
/* * Dump IP6 statistics structure. */ void ip6_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct ip6stat ip6stat, zerostat; int first, i; size_t len; len = sizeof ip6stat; if (live) { memset(&ip6stat, 0, len); if (zflag) memset(&zerostat, 0, len); if (sysctlbyname("net.inet6.ip6.stats", &ip6stat, &len, zflag ? &zerostat : NULL, zflag ? len : 0) < 0) { if (errno != ENOENT) xo_warn("sysctl: net.inet6.ip6.stats"); return; } } else kread_counters(off, &ip6stat, len); xo_open_container(name); xo_emit("{T:/%s}:\n", name); #define p(f, m) if (ip6stat.f || sflag <= 1) \ xo_emit(m, (uintmax_t)ip6stat.f, plural(ip6stat.f)) #define p1a(f, m) if (ip6stat.f || sflag <= 1) \ xo_emit(m, (uintmax_t)ip6stat.f) p(ip6s_total, "\t{:received-packets/%ju} " "{N:/total packet%s received}\n"); p1a(ip6s_toosmall, "\t{:dropped-below-minimum-size/%ju} " "{N:/with size smaller than minimum}\n"); p1a(ip6s_tooshort, "\t{:dropped-short-packets/%ju} " "{N:/with data size < data length}\n"); p1a(ip6s_badoptions, "\t{:dropped-bad-options/%ju} " "{N:/with bad options}\n"); p1a(ip6s_badvers, "\t{:dropped-bad-version/%ju} " "{N:/with incorrect version number}\n"); p(ip6s_fragments, "\t{:received-fragments/%ju} " "{N:/fragment%s received}\n"); p(ip6s_fragdropped, "\t{:dropped-fragment/%ju} " "{N:/fragment%s dropped (dup or out of space)}\n"); p(ip6s_fragtimeout, "\t{:dropped-fragment-after-timeout/%ju} " "{N:/fragment%s dropped after timeout}\n"); p(ip6s_fragoverflow, "\t{:dropped-fragments-overflow/%ju} " "{N:/fragment%s that exceeded limit}\n"); p(ip6s_reassembled, "\t{:reassembled-packets/%ju} " "{N:/packet%s reassembled ok}\n"); p(ip6s_delivered, "\t{:received-local-packets/%ju} " "{N:/packet%s for this host}\n"); p(ip6s_forward, "\t{:forwarded-packets/%ju} " "{N:/packet%s forwarded}\n"); p(ip6s_cantforward, "\t{:packets-not-forwardable/%ju} " "{N:/packet%s not forwardable}\n"); p(ip6s_redirectsent, "\t{:sent-redirects/%ju} " "{N:/redirect%s sent}\n"); p(ip6s_localout, "\t{:sent-packets/%ju} " "{N:/packet%s sent from this host}\n"); p(ip6s_rawout, "\t{:send-packets-fabricated-header/%ju} " "{N:/packet%s sent with fabricated ip header}\n"); p(ip6s_odropped, "\t{:discard-no-mbufs/%ju} " "{N:/output packet%s dropped due to no bufs, etc.}\n"); p(ip6s_noroute, "\t{:discard-no-route/%ju} " "{N:/output packet%s discarded due to no route}\n"); p(ip6s_fragmented, "\t{:sent-fragments/%ju} " "{N:/output datagram%s fragmented}\n"); p(ip6s_ofragments, "\t{:fragments-created/%ju} " "{N:/fragment%s created}\n"); p(ip6s_cantfrag, "\t{:discard-cannot-fragment/%ju} " "{N:/datagram%s that can't be fragmented}\n"); p(ip6s_badscope, "\t{:discard-scope-violations/%ju} " "{N:/packet%s that violated scope rules}\n"); p(ip6s_notmember, "\t{:multicast-no-join-packets/%ju} " "{N:/multicast packet%s which we don't join}\n"); for (first = 1, i = 0; i < IP6S_HDRCNT; i++) if (ip6stat.ip6s_nxthist[i] != 0) { if (first) { xo_emit("\t{T:Input histogram}:\n"); xo_open_list("input-histogram"); first = 0; } xo_open_instance("input-histogram"); xo_emit("\t\t{k:name/%s}: {:count/%ju}\n", ip6nh[i], (uintmax_t)ip6stat.ip6s_nxthist[i]); xo_close_instance("input-histogram"); } if (!first) xo_close_list("input-histogram"); xo_open_container("mbuf-statistics"); xo_emit("\t{T:Mbuf statistics}:\n"); xo_emit("\t\t{:one-mbuf/%ju} {N:/one mbuf}\n", (uintmax_t)ip6stat.ip6s_m1); for (first = 1, i = 0; i < IP6S_M2MMAX; i++) { char ifbuf[IFNAMSIZ]; if (ip6stat.ip6s_m2m[i] != 0) { if (first) { xo_emit("\t\t{N:two or more mbuf}:\n"); xo_open_list("mbuf-data"); first = 0; } xo_open_instance("mbuf-data"); xo_emit("\t\t\t{k:name/%s}= {:count/%ju}\n", if_indextoname(i, ifbuf), (uintmax_t)ip6stat.ip6s_m2m[i]); xo_close_instance("mbuf-data"); } } if (!first) xo_close_list("mbuf-data"); xo_emit("\t\t{:one-extra-mbuf/%ju} {N:one ext mbuf}\n", (uintmax_t)ip6stat.ip6s_mext1); xo_emit("\t\t{:two-or-more-extra-mbufs/%ju} " "{N:/two or more ext mbuf}\n", (uintmax_t)ip6stat.ip6s_mext2m); xo_close_container("mbuf-statistics"); p(ip6s_exthdrtoolong, "\t{:dropped-header-too-long/%ju} " "{N:/packet%s whose headers are not contiguous}\n"); p(ip6s_nogif, "\t{:discard-tunnel-no-gif/%ju} " "{N:/tunneling packet%s that can't find gif}\n"); p(ip6s_toomanyhdr, "\t{:dropped-too-many-headers/%ju} " "{N:/packet%s discarded because of too many headers}\n"); /* for debugging source address selection */ #define PRINT_SCOPESTAT(s,i) do {\ switch(i) { /* XXX hardcoding in each case */\ case 1:\ p(s, "\t\t{ke:name/interface-locals}{:count/%ju} " \ "{N:/interface-local%s}\n"); \ break;\ case 2:\ p(s,"\t\t{ke:name/link-locals}{:count/%ju} " \ "{N:/link-local%s}\n"); \ break;\ case 5:\ p(s,"\t\t{ke:name/site-locals}{:count/%ju} " \ "{N:/site-local%s}\n");\ break;\ case 14:\ p(s,"\t\t{ke:name/globals}{:count/%ju} " \ "{N:/global%s}\n");\ break;\ default:\ xo_emit("\t\t{qke:name/%x}{:count/%ju} " \ "addresses scope=%x\n",\ i, (uintmax_t)ip6stat.s, i); \ }\ } while (0); xo_open_container("source-address-selection"); p(ip6s_sources_none, "\t{:address-selection-failures/%ju} " "{N:/failure%s of source address selection}\n"); for (first = 1, i = 0; i < IP6S_SCOPECNT; i++) { if (ip6stat.ip6s_sources_sameif[i]) { if (first) { xo_open_list("outgoing-interface"); xo_emit("\tsource addresses on an outgoing " "I/F\n"); first = 0; } xo_open_instance("outgoing-interface"); PRINT_SCOPESTAT(ip6s_sources_sameif[i], i); xo_close_instance("outgoing-interface"); } } if (!first) xo_close_list("outgoing-interface"); for (first = 1, i = 0; i < IP6S_SCOPECNT; i++) { if (ip6stat.ip6s_sources_otherif[i]) { if (first) { xo_open_list("non-outgoing-interface"); xo_emit("\tsource addresses on a non-outgoing " "I/F\n"); first = 0; } xo_open_instance("non-outgoing-interface"); PRINT_SCOPESTAT(ip6s_sources_otherif[i], i); xo_close_instance("non-outgoing-interface"); } } if (!first) xo_close_list("non-outgoing-interface"); for (first = 1, i = 0; i < IP6S_SCOPECNT; i++) { if (ip6stat.ip6s_sources_samescope[i]) { if (first) { xo_open_list("same-source"); xo_emit("\tsource addresses of same scope\n"); first = 0; } xo_open_instance("same-source"); PRINT_SCOPESTAT(ip6s_sources_samescope[i], i); xo_close_instance("same-source"); } } if (!first) xo_close_list("same-source"); for (first = 1, i = 0; i < IP6S_SCOPECNT; i++) { if (ip6stat.ip6s_sources_otherscope[i]) { if (first) { xo_open_list("different-scope"); xo_emit("\tsource addresses of a different " "scope\n"); first = 0; } xo_open_instance("different-scope"); PRINT_SCOPESTAT(ip6s_sources_otherscope[i], i); xo_close_instance("different-scope"); } } if (!first) xo_close_list("different-scope"); for (first = 1, i = 0; i < IP6S_SCOPECNT; i++) { if (ip6stat.ip6s_sources_deprecated[i]) { if (first) { xo_open_list("deprecated-source"); xo_emit("\tdeprecated source addresses\n"); first = 0; } xo_open_instance("deprecated-source"); PRINT_SCOPESTAT(ip6s_sources_deprecated[i], i); xo_close_instance("deprecated-source"); } } if (!first) xo_close_list("deprecated-source"); for (first = 1, i = 0; i < IP6S_RULESMAX; i++) { if (ip6stat.ip6s_sources_rule[i]) { if (first) { xo_open_list("rules-applied"); xo_emit("\t{T:Source addresses selection " "rule applied}:\n"); first = 0; } xo_open_instance("rules-applied"); xo_emit("\t\t{ke:name/%s}{:count/%ju} {d:name/%s}\n", srcrule_str[i], (uintmax_t)ip6stat.ip6s_sources_rule[i], srcrule_str[i]); xo_close_instance("rules-applied"); } } if (!first) xo_close_list("rules-applied"); xo_close_container("source-address-selection"); #undef p #undef p1a xo_close_container(name); }
int main(int argc, char *argv[]) { struct stat stbuf; struct statfs statfsbuf, totalbuf; struct maxwidths maxwidths; struct statfs *mntbuf; #ifdef MOUNT_CHAR_DEVS struct iovec *iov = NULL; #endif const char *fstype; #ifdef MOUNT_CHAR_DEVS char *mntpath; char errmsg[255] = {0}; #endif char *mntpt; const char **vfslist; int i, mntsize; int ch, rv; #ifdef MOUNT_CHAR_DEVS int iovlen = 0; #endif fstype = "ufs"; (void)setlocale(LC_ALL, ""); memset(&maxwidths, 0, sizeof(maxwidths)); memset(&totalbuf, 0, sizeof(totalbuf)); totalbuf.f_bsize = DEV_BSIZE; strlcpy(totalbuf.f_mntfromname, "total", MNAMELEN); vfslist = NULL; argc = xo_parse_args(argc, argv); if (argc < 0) exit(1); while ((ch = getopt(argc, argv, "abcgHhiklmnPt:T,")) != -1) switch (ch) { case 'a': aflag = 1; break; case 'b': /* FALLTHROUGH */ case 'P': /* * POSIX specifically discusses the behavior of * both -k and -P. It states that the blocksize should * be set to 1024. Thus, if this occurs, simply break * rather than clobbering the old blocksize. */ if (kflag) break; setenv("BLOCKSIZE", "512", 1); hflag = 0; break; case 'c': cflag = 1; break; case 'g': setenv("BLOCKSIZE", "1g", 1); hflag = 0; break; case 'H': hflag = UNITS_SI; break; case 'h': hflag = UNITS_2; break; case 'i': iflag = 1; break; case 'k': kflag++; setenv("BLOCKSIZE", "1024", 1); hflag = 0; break; case 'l': /* Ignore duplicate -l */ if (lflag) break; if (vfslist != NULL) xo_errx(1, "-l and -t are mutually exclusive."); vfslist = makevfslist(makenetvfslist()); lflag = 1; break; case 'm': setenv("BLOCKSIZE", "1m", 1); hflag = 0; break; case 'n': nflag = 1; break; case 't': if (lflag) xo_errx(1, "-l and -t are mutually exclusive."); if (vfslist != NULL) xo_errx(1, "only one -t option may be specified"); fstype = optarg; vfslist = makevfslist(optarg); break; case 'T': Tflag = 1; break; case ',': thousands = 1; break; case '?': default: usage(); } argc -= optind; argv += optind; rv = 0; if (!*argv) { /* everything (modulo -t) */ mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); mntsize = regetmntinfo(&mntbuf, mntsize, vfslist); } else { /* just the filesystems specified on the command line */ mntbuf = malloc(argc * sizeof(*mntbuf)); if (mntbuf == NULL) xo_err(1, "malloc()"); mntsize = 0; /* continued in for loop below */ } xo_open_container("storage-system-information"); xo_open_list("filesystem"); /* iterate through specified filesystems */ for (; *argv; argv++) { if (stat(*argv, &stbuf) < 0) { if ((mntpt = getmntpt(*argv)) == NULL) { xo_warn("%s", *argv); rv = 1; continue; } #ifdef MOUNT_CHAR_DEVS } else if (S_ISCHR(stbuf.st_mode)) { if ((mntpt = getmntpt(*argv)) == NULL) { mdev.fspec = *argv; mntpath = strdup("/tmp/df.XXXXXX"); if (mntpath == NULL) { xo_warn("strdup failed"); rv = 1; continue; } mntpt = mkdtemp(mntpath); if (mntpt == NULL) { xo_warn("mkdtemp(\"%s\") failed", mntpath); rv = 1; free(mntpath); continue; } if (iov != NULL) free_iovec(&iov, &iovlen); build_iovec_argf(&iov, &iovlen, "fstype", "%s", fstype); build_iovec_argf(&iov, &iovlen, "fspath", "%s", mntpath); build_iovec_argf(&iov, &iovlen, "from", "%s", *argv); build_iovec(&iov, &iovlen, "errmsg", errmsg, sizeof(errmsg)); if (nmount(iov, iovlen, MNT_RDONLY|MNT_NOEXEC) < 0) { if (errmsg[0]) xo_warn("%s: %s", *argv, errmsg); else xo_warn("%s", *argv); rv = 1; (void)rmdir(mntpt); free(mntpath); continue; } else if (statfs(mntpt, &statfsbuf) == 0) { statfsbuf.f_mntonname[0] = '\0'; prtstat(&statfsbuf, &maxwidths); if (cflag) addstat(&totalbuf, &statfsbuf); } else { xo_warn("%s", *argv); rv = 1; } (void)unmount(mntpt, 0); (void)rmdir(mntpt); free(mntpath); continue; } #endif } else mntpt = *argv; /* * Statfs does not take a `wait' flag, so we cannot * implement nflag here. */ if (statfs(mntpt, &statfsbuf) < 0) { xo_warn("%s", mntpt); rv = 1; continue; } /* * Check to make sure the arguments we've been given are * satisfied. Return an error if we have been asked to * list a mount point that does not match the other args * we've been given (-l, -t, etc.). */ if (checkvfsname(statfsbuf.f_fstypename, vfslist)) { rv = 1; continue; } /* the user asked for it, so ignore the ignore flag */ statfsbuf.f_flags &= ~MNT_IGNORE; /* add to list */ mntbuf[mntsize++] = statfsbuf; } memset(&maxwidths, 0, sizeof(maxwidths)); for (i = 0; i < mntsize; i++) { if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0) { update_maxwidths(&maxwidths, &mntbuf[i]); if (cflag) addstat(&totalbuf, &mntbuf[i]); } } for (i = 0; i < mntsize; i++) if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0) prtstat(&mntbuf[i], &maxwidths); xo_close_list("filesystem"); if (cflag) prtstat(&totalbuf, &maxwidths); xo_close_container("storage-system-information"); xo_finish(); exit(rv); }
int main(int argc, char *argv[]) { struct kinfo_proc *kp; struct kinfo_proc *dkp; struct stat *stp; time_t touched; int ch, i, nentries, nusers, wcmd, longidle, longattime; const char *memf, *nlistf, *p, *save_p; char *x_suffix; char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX]; char fn[MAXHOSTNAMELEN]; char *dot; (void)setlocale(LC_ALL, ""); use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0'); use_comma = (*nl_langinfo(RADIXCHAR) != ','); argc = xo_parse_args(argc, argv); if (argc < 0) exit(1); /* Are we w(1) or uptime(1)? */ if (strcmp(basename(argv[0]), "uptime") == 0) { wcmd = 0; p = ""; } else { wcmd = 1; p = "dhiflM:N:nsuw"; } memf = _PATH_DEVNULL; nlistf = NULL; while ((ch = getopt(argc, argv, p)) != -1) switch (ch) { case 'd': dflag = 1; break; case 'h': header = 0; break; case 'i': sortidle = 1; break; case 'M': header = 0; memf = optarg; break; case 'N': nlistf = optarg; break; case 'n': nflag = 1; break; case 'f': case 'l': case 's': case 'u': case 'w': warnx("[-flsuw] no longer supported"); /* FALLTHROUGH */ case '?': default: usage(wcmd); } argc -= optind; argv += optind; if (!(_res.options & RES_INIT)) res_init(); _res.retrans = 2; /* resolver timeout to 2 seconds per try */ _res.retry = 1; /* only try once.. */ if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL) errx(1, "%s", errbuf); (void)time(&now); if (*argv) sel_users = argv; setutxent(); for (nusers = 0; (utmp = getutxent()) != NULL;) { if (utmp->ut_type != USER_PROCESS) continue; if (!(stp = ttystat(utmp->ut_line))) continue; /* corrupted record */ ++nusers; if (wcmd == 0) continue; if (sel_users) { int usermatch; char **user; usermatch = 0; for (user = sel_users; !usermatch && *user; user++) if (!strcmp(utmp->ut_user, *user)) usermatch = 1; if (!usermatch) continue; } if ((ep = calloc(1, sizeof(struct entry))) == NULL) errx(1, "calloc"); *nextp = ep; nextp = &ep->next; memmove(&ep->utmp, utmp, sizeof *utmp); ep->tdev = stp->st_rdev; /* * If this is the console device, attempt to ascertain * the true console device dev_t. */ if (ep->tdev == 0) { size_t size; size = sizeof(dev_t); (void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0); } touched = stp->st_atime; if (touched < ep->utmp.ut_tv.tv_sec) { /* tty untouched since before login */ touched = ep->utmp.ut_tv.tv_sec; } if ((ep->idle = now - touched) < 0) ep->idle = 0; } endutxent(); xo_open_container("uptime-information"); if (header || wcmd == 0) { pr_header(&now, nusers); if (wcmd == 0) { xo_close_container("uptime-information"); xo_finish(); (void)kvm_close(kd); exit(0); } #define HEADER_USER "USER" #define HEADER_TTY "TTY" #define HEADER_FROM "FROM" #define HEADER_LOGIN_IDLE "LOGIN@ IDLE " #define HEADER_WHAT "WHAT\n" #define WUSED (W_DISPUSERSIZE + W_DISPLINESIZE + W_DISPHOSTSIZE + \ sizeof(HEADER_LOGIN_IDLE) + 3) /* header width incl. spaces */ xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%s}", W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER, W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY, W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM, HEADER_LOGIN_IDLE HEADER_WHAT); } if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL) err(1, "%s", kvm_geterr(kd)); for (i = 0; i < nentries; i++, kp++) { if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB || kp->ki_tdev == NODEV) continue; for (ep = ehead; ep != NULL; ep = ep->next) { if (ep->tdev == kp->ki_tdev) { /* * proc is associated with this terminal */ if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) { /* * Proc is 'most interesting' */ if (proc_compare(ep->kp, kp)) ep->kp = kp; } /* * Proc debug option info; add to debug * list using kinfo_proc ki_spare[0] * as next pointer; ptr to ptr avoids the * ptr = long assumption. */ dkp = ep->dkp; ep->dkp = kp; debugproc(kp) = dkp; } } } if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 && ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 && ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0) ttywidth = 79; else ttywidth = ws.ws_col - 1; argwidth = ttywidth - WUSED; if (argwidth < 4) argwidth = 8; for (ep = ehead; ep != NULL; ep = ep->next) { if (ep->kp == NULL) { ep->args = strdup("-"); continue; } ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth), ep->kp->ki_comm, NULL, MAXCOMLEN); if (ep->args == NULL) err(1, NULL); } /* sort by idle time */ if (sortidle && ehead != NULL) { struct entry *from, *save; from = ehead; ehead = NULL; while (from != NULL) { for (nextp = &ehead; (*nextp) && from->idle >= (*nextp)->idle; nextp = &(*nextp)->next) continue; save = from; from = from->next; save->next = *nextp; *nextp = save; } } xo_open_container("user-table"); xo_open_list("user-entry"); for (ep = ehead; ep != NULL; ep = ep->next) { struct addrinfo hints, *res; struct sockaddr_storage ss; struct sockaddr *sa = (struct sockaddr *)&ss; struct sockaddr_in *lsin = (struct sockaddr_in *)&ss; struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss; time_t t; int isaddr; xo_open_instance("user-entry"); save_p = p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-"; if ((x_suffix = strrchr(p, ':')) != NULL) { if ((dot = strchr(x_suffix, '.')) != NULL && strchr(dot+1, '.') == NULL) *x_suffix++ = '\0'; else x_suffix = NULL; } isaddr = 0; memset(&ss, '\0', sizeof(ss)); if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) { lsin6->sin6_len = sizeof(*lsin6); lsin6->sin6_family = AF_INET6; isaddr = 1; } else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) { lsin->sin_len = sizeof(*lsin); lsin->sin_family = AF_INET; isaddr = 1; } if (!nflag) { /* Attempt to change an IP address into a name */ if (isaddr && realhostname_sa(fn, sizeof(fn), sa, sa->sa_len) == HOSTNAME_FOUND) p = fn; } else if (!isaddr) { /* * If a host has only one A/AAAA RR, change a * name into an IP address */ memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if (getaddrinfo(p, NULL, &hints, &res) == 0) { if (res->ai_next == NULL && getnameinfo(res->ai_addr, res->ai_addrlen, fn, sizeof(fn), NULL, 0, NI_NUMERICHOST) == 0) p = fn; freeaddrinfo(res); } } if (x_suffix) { (void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix); p = buf; } if (dflag) { xo_open_container("process-table"); xo_open_list("process-entry"); for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) { const char *ptr; ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth), dkp->ki_comm, NULL, MAXCOMLEN); if (ptr == NULL) ptr = "-"; xo_open_instance("process-entry"); xo_emit("\t\t{:process-id/%-9d/%d} {:command/%s}\n", dkp->ki_pid, ptr); xo_close_instance("process-entry"); } xo_close_list("process-entry"); xo_close_container("process-table"); } xo_emit("{:user/%-*.*s/%@**@s} {:tty/%-*.*s/%@**@s} ", W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user, W_DISPLINESIZE, W_DISPLINESIZE, *ep->utmp.ut_line ? (strncmp(ep->utmp.ut_line, "tty", 3) && strncmp(ep->utmp.ut_line, "cua", 3) ? ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-"); if (save_p && save_p != p) xo_attr("address", "%s", save_p); xo_emit("{:from/%-*.*s/%@**@s} ", W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-"); t = ep->utmp.ut_tv.tv_sec; longattime = pr_attime(&t, &now); longidle = pr_idle(ep->idle); xo_emit("{:command/%.*s/%@*@s}\n", argwidth - longidle - longattime, ep->args); xo_close_instance("user-entry"); } xo_close_list("user-entry"); xo_close_container("user-table"); xo_close_container("uptime-information"); xo_finish(); (void)kvm_close(kd); exit(0); }
int main(int argc, char *argv[]) { static char dot[] = ".", *dotav[] = {dot, NULL}; struct winsize win; int ch, fts_options, notused; char *p; const char *errstr = NULL; #ifdef COLORLS char termcapbuf[1024]; /* termcap definition buffer */ char tcapbuf[512]; /* capability buffer */ char *bp = tcapbuf; #endif (void)setlocale(LC_ALL, ""); /* Terminal defaults to -Cq, non-terminal defaults to -1. */ if (isatty(STDOUT_FILENO)) { termwidth = 80; if ((p = getenv("COLUMNS")) != NULL && *p != '\0') termwidth = strtonum(p, 0, INT_MAX, &errstr); else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_col > 0) termwidth = win.ws_col; f_nonprint = 1; } else { f_singlecol = 1; /* retrieve environment variable, in case of explicit -C */ p = getenv("COLUMNS"); if (p) termwidth = strtonum(p, 0, INT_MAX, &errstr); } if (errstr) termwidth = 80; fts_options = FTS_PHYSICAL; if (getenv("LS_SAMESORT")) f_samesort = 1; argc = xo_parse_args(argc, argv); if (argc < 0) return (1); xo_set_flags(NULL, XOF_COLUMNS); xo_set_version(LS_XO_VERSION); while ((ch = getopt(argc, argv, "1ABCD:FGHILPRSTUWXZabcdfghiklmnopqrstuwxy,")) != -1) { switch (ch) { /* * The -1, -C, -x and -l options all override each other so * shell aliasing works right. */ case '1': f_singlecol = 1; f_longform = 0; f_stream = 0; break; case 'C': f_sortacross = f_longform = f_singlecol = 0; break; case 'l': f_longform = 1; f_singlecol = 0; f_stream = 0; break; case 'x': f_sortacross = 1; f_longform = 0; f_singlecol = 0; break; /* The -c, -u, and -U options override each other. */ case 'c': f_statustime = 1; f_accesstime = 0; f_birthtime = 0; break; case 'u': f_accesstime = 1; f_statustime = 0; f_birthtime = 0; break; case 'U': f_birthtime = 1; f_accesstime = 0; f_statustime = 0; break; case 'f': f_nosort = 1; /* FALLTHROUGH */ case 'a': fts_options |= FTS_SEEDOT; /* FALLTHROUGH */ case 'A': f_listdot = 1; break; /* The -t and -S options override each other. */ case 'S': f_sizesort = 1; f_timesort = 0; break; case 't': f_timesort = 1; f_sizesort = 0; break; /* Other flags. Please keep alphabetic. */ case ',': f_thousands = 1; break; case 'B': f_nonprint = 0; f_octal = 1; f_octal_escape = 0; break; case 'D': f_timeformat = optarg; break; case 'F': f_type = 1; f_slash = 0; break; case 'G': setenv("CLICOLOR", "", 1); break; case 'H': fts_options |= FTS_COMFOLLOW; f_nofollow = 0; break; case 'I': f_noautodot = 1; break; case 'L': fts_options &= ~FTS_PHYSICAL; fts_options |= FTS_LOGICAL; f_nofollow = 0; break; case 'P': fts_options &= ~FTS_COMFOLLOW; fts_options &= ~FTS_LOGICAL; fts_options |= FTS_PHYSICAL; f_nofollow = 1; break; case 'R': f_recursive = 1; break; case 'T': f_sectime = 1; break; case 'W': f_whiteout = 1; break; case 'Z': f_label = 1; break; case 'b': f_nonprint = 0; f_octal = 0; f_octal_escape = 1; break; /* The -d option turns off the -R option. */ case 'd': f_listdir = 1; f_recursive = 0; break; case 'g': /* Compatibility with 4.3BSD. */ break; case 'h': f_humanval = 1; break; case 'i': f_inode = 1; break; case 'k': f_humanval = 0; f_kblocks = 1; break; case 'm': f_stream = 1; f_singlecol = 0; f_longform = 0; break; case 'n': f_numericonly = 1; break; case 'o': f_flags = 1; break; case 'p': f_slash = 1; f_type = 1; break; case 'q': f_nonprint = 1; f_octal = 0; f_octal_escape = 0; break; case 'r': f_reversesort = 1; break; case 's': f_size = 1; break; case 'w': f_nonprint = 0; f_octal = 0; f_octal_escape = 0; break; case 'y': f_samesort = 1; break; default: case '?': usage(); } } argc -= optind; argv += optind; /* Root is -A automatically unless -I. */ if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot) f_listdot = 1; /* Enabling of colours is conditional on the environment. */ if (getenv("CLICOLOR") && (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE"))) #ifdef COLORLS if (tgetent(termcapbuf, getenv("TERM")) == 1) { ansi_fgcol = tgetstr("AF", &bp); ansi_bgcol = tgetstr("AB", &bp); attrs_off = tgetstr("me", &bp); enter_bold = tgetstr("md", &bp); /* To switch colours off use 'op' if * available, otherwise use 'oc', or * don't do colours at all. */ ansi_coloff = tgetstr("op", &bp); if (!ansi_coloff) ansi_coloff = tgetstr("oc", &bp); if (ansi_fgcol && ansi_bgcol && ansi_coloff) f_color = 1; } #else xo_warnx("color support not compiled in"); #endif /*COLORLS*/ #ifdef COLORLS if (f_color) { /* * We can't put tabs and color sequences together: * column number will be incremented incorrectly * for "stty oxtabs" mode. */ f_notabs = 1; (void)signal(SIGINT, colorquit); (void)signal(SIGQUIT, colorquit); parsecolors(getenv("LSCOLORS")); } #endif /* * If not -F, -i, -l, -s, -S or -t options, don't require stat * information, unless in color mode in which case we do * need this to determine which colors to display. */ if (!f_inode && !f_longform && !f_size && !f_timesort && !f_sizesort && !f_type #ifdef COLORLS && !f_color #endif ) fts_options |= FTS_NOSTAT; /* * If not -F, -P, -d or -l options, follow any symbolic links listed on * the command line, unless in color mode in which case we need to * distinguish file type for a symbolic link itself and its target. */ if (!f_nofollow && !f_longform && !f_listdir && (!f_type || f_slash) #ifdef COLORLS && !f_color #endif ) fts_options |= FTS_COMFOLLOW; /* * If -W, show whiteout entries */ #ifdef FTS_WHITEOUT if (f_whiteout) fts_options |= FTS_WHITEOUT; #endif /* If -i, -l or -s, figure out block size. */ if (f_inode || f_longform || f_size) { if (f_kblocks) blocksize = 2; else { (void)getbsize(¬used, &blocksize); blocksize /= 512; } } /* Select a sort function. */ if (f_reversesort) { if (!f_timesort && !f_sizesort) sortfcn = revnamecmp; else if (f_sizesort) sortfcn = revsizecmp; else if (f_accesstime) sortfcn = revacccmp; else if (f_birthtime) sortfcn = revbirthcmp; else if (f_statustime) sortfcn = revstatcmp; else /* Use modification time. */ sortfcn = revmodcmp; } else { if (!f_timesort && !f_sizesort) sortfcn = namecmp; else if (f_sizesort) sortfcn = sizecmp; else if (f_accesstime) sortfcn = acccmp; else if (f_birthtime) sortfcn = birthcmp; else if (f_statustime) sortfcn = statcmp; else /* Use modification time. */ sortfcn = modcmp; } /* Select a print function. */ if (f_singlecol) printfcn = printscol; else if (f_longform) printfcn = printlong; else if (f_stream) printfcn = printstream; else printfcn = printcol; xo_open_container("file-information"); if (argc) traverse(argc, argv, fts_options); else traverse(1, dotav, fts_options); xo_close_container("file-information"); xo_finish(); exit(rval); }
int main(int argc, char **argv) { char *dot, *ep, *jname, *pname; int c, i, jflags, jid, lastjid, pflags, spc; argc = xo_parse_args(argc, argv); if (argc < 0) exit(1); xo_set_version(JLS_XO_VERSION); jname = NULL; pflags = jflags = jid = 0; while ((c = getopt(argc, argv, "adj:hNnqsv")) >= 0) switch (c) { case 'a': case 'd': jflags |= JAIL_DYING; break; case 'j': jid = strtoul(optarg, &ep, 10); if (!jid || *ep) { jid = 0; jname = optarg; } break; case 'h': pflags = (pflags & ~(PRINT_SKIP | PRINT_VERBOSE)) | PRINT_HEADER; break; case 'N': pflags |= PRINT_JAIL_NAME; break; case 'n': pflags = (pflags & ~PRINT_VERBOSE) | PRINT_NAMEVAL; break; case 'q': pflags |= PRINT_QUOTED; break; case 's': pflags = (pflags & ~(PRINT_HEADER | PRINT_VERBOSE)) | PRINT_NAMEVAL | PRINT_QUOTED | PRINT_SKIP; break; case 'v': pflags = (pflags & ~(PRINT_HEADER | PRINT_NAMEVAL | PRINT_SKIP)) | PRINT_VERBOSE; break; default: xo_errx(1, "usage: jls [-dhNnqv] [-j jail] [param ...]"); } #ifdef INET6 ip6_ok = feature_present("inet6"); #endif #ifdef INET ip4_ok = feature_present("inet"); #endif /* Add the parameters to print. */ if (optind == argc) { if (pflags & (PRINT_HEADER | PRINT_NAMEVAL)) add_param("all", NULL, (size_t)0, NULL, JP_USER); else if (pflags & PRINT_VERBOSE) { add_param("jid", NULL, (size_t)0, NULL, JP_USER); add_param("host.hostname", NULL, (size_t)0, NULL, JP_USER); add_param("path", NULL, (size_t)0, NULL, JP_USER); add_param("name", NULL, (size_t)0, NULL, JP_USER); add_param("dying", NULL, (size_t)0, NULL, JP_USER); add_param("cpuset.id", NULL, (size_t)0, NULL, JP_USER); #ifdef INET if (ip4_ok) add_param("ip4.addr", NULL, (size_t)0, NULL, JP_USER); #endif #ifdef INET6 if (ip6_ok) add_param("ip6.addr", NULL, (size_t)0, NULL, JP_USER | JP_OPT); #endif } else { pflags |= PRINT_DEFAULT; if (pflags & PRINT_JAIL_NAME) add_param("name", NULL, (size_t)0, NULL, JP_USER); else add_param("jid", NULL, (size_t)0, NULL, JP_USER); #ifdef INET if (ip4_ok) add_param("ip4.addr", NULL, (size_t)0, NULL, JP_USER); #endif add_param("host.hostname", NULL, (size_t)0, NULL, JP_USER); add_param("path", NULL, (size_t)0, NULL, JP_USER); } } else { pflags &= ~PRINT_VERBOSE; while (optind < argc) add_param(argv[optind++], NULL, (size_t)0, NULL, JP_USER); } if (pflags & PRINT_SKIP) { /* Check for parameters with jailsys parents. */ for (i = 0; i < nparams; i++) { if ((params[i].jp_flags & JP_USER) && (dot = strchr(params[i].jp_name, '.'))) { pname = alloca((dot - params[i].jp_name) + 1); strlcpy(pname, params[i].jp_name, (dot - params[i].jp_name) + 1); param_parent[i] = add_param(pname, NULL, (size_t)0, NULL, JP_OPT); } } } /* Add the index key parameters. */ if (jid != 0) add_param("jid", &jid, sizeof(jid), NULL, 0); else if (jname != NULL) add_param("name", jname, strlen(jname), NULL, 0); else add_param("lastjid", &lastjid, sizeof(lastjid), NULL, 0); /* Print a header line if requested. */ if (pflags & PRINT_VERBOSE) { xo_emit("{T:/%3s}{T:JID}{P: }{T:Hostname}{Pd:/%22s}{T:Path}\n", "", ""); xo_emit("{P:/%8s}{T:Name}{Pd:/%26s}{T:State}\n", "", ""); xo_emit("{P:/%8s}{T:CPUSetID}\n", ""); xo_emit("{P:/%8s}{T:IP Address(es)}\n", ""); } else if (pflags & PRINT_DEFAULT) if (pflags & PRINT_JAIL_NAME) xo_emit("{P: }{T:JID/%-15s}{P: }{T:IP Address/%-15s}" "{P: }{T:Hostname/%-29s}{P: }{T:Path}\n"); else xo_emit("{T:JID/%6s}{P: }{T:IP Address}{P:/%6s}" "{T:Hostname}{P:/%22s}{T:Path}\n", "", ""); else if (pflags & PRINT_HEADER) { for (i = spc = 0; i < nparams; i++) if (params[i].jp_flags & JP_USER) { if (spc) xo_emit("{P: }"); else spc = 1; xo_emit(params[i].jp_name); } xo_emit("{P:\n}"); } xo_open_container("jail-information"); xo_open_list("jail"); /* Fetch the jail(s) and print the parameters. */ if (jid != 0 || jname != NULL) { if (print_jail(pflags, jflags) < 0) xo_errx(1, "%s", jail_errmsg); } else { for (lastjid = 0; (lastjid = print_jail(pflags, jflags)) >= 0; ) ; if (errno != 0 && errno != ENOENT) xo_errx(1, "%s", jail_errmsg); } xo_close_list("jail"); xo_close_container("jail-information"); xo_finish(); return (0); }
int main(int argc, char *argv[]) { struct protox *tp = NULL; /* for printing cblocks & stats */ int ch; int fib = -1; char *endptr; bool first = true; af = AF_UNSPEC; argc = xo_parse_args(argc, argv); while ((ch = getopt(argc, argv, "46AaBbdF:f:ghI:iLlM:mN:np:Qq:RrSTsuWw:xz")) != -1) switch(ch) { case '4': #ifdef INET af = AF_INET; #else errx(1, "IPv4 support is not compiled in"); #endif break; case '6': #ifdef INET6 af = AF_INET6; #else errx(1, "IPv6 support is not compiled in"); #endif break; case 'A': Aflag = 1; break; case 'a': aflag = 1; break; case 'B': Bflag = 1; break; case 'b': bflag = 1; break; case 'd': dflag = 1; break; case 'F': fib = strtol(optarg, &endptr, 0); if (*endptr != '\0' || (fib == 0 && (errno == EINVAL || errno == ERANGE))) xo_errx(1, "%s: invalid fib", optarg); break; case 'f': if (strcmp(optarg, "inet") == 0) af = AF_INET; #ifdef INET6 else if (strcmp(optarg, "inet6") == 0) af = AF_INET6; #endif #ifdef IPSEC else if (strcmp(optarg, "pfkey") == 0) af = PF_KEY; #endif else if (strcmp(optarg, "unix") == 0 || strcmp(optarg, "local") == 0) af = AF_UNIX; #ifdef NETGRAPH else if (strcmp(optarg, "ng") == 0 || strcmp(optarg, "netgraph") == 0) af = AF_NETGRAPH; #endif else if (strcmp(optarg, "link") == 0) af = AF_LINK; else { xo_errx(1, "%s: unknown address family", optarg); } break; case 'g': gflag = 1; break; case 'h': hflag = 1; break; case 'I': { char *cp; iflag = 1; for (cp = interface = optarg; isalpha(*cp); cp++) continue; unit = atoi(cp); break; } case 'i': iflag = 1; break; case 'L': Lflag = 1; break; case 'M': memf = optarg; break; case 'm': mflag = 1; break; case 'N': nlistf = optarg; break; case 'n': numeric_addr = numeric_port = 1; break; case 'p': if ((tp = name2protox(optarg)) == NULL) { xo_errx(1, "%s: unknown or uninstrumented " "protocol", optarg); } pflag = 1; break; case 'Q': Qflag = 1; break; case 'q': noutputs = atoi(optarg); if (noutputs != 0) noutputs++; break; case 'r': rflag = 1; break; case 'R': Rflag = 1; break; case 's': ++sflag; break; case 'S': numeric_addr = 1; break; case 'u': af = AF_UNIX; break; case 'W': case 'l': Wflag = 1; break; case 'w': interval = atoi(optarg); iflag = 1; break; case 'T': Tflag = 1; break; case 'x': xflag = 1; break; case 'z': zflag = 1; break; case '?': default: usage(); } argv += optind; argc -= optind; #define BACKWARD_COMPATIBILITY #ifdef BACKWARD_COMPATIBILITY if (*argv) { if (isdigit(**argv)) { interval = atoi(*argv); if (interval <= 0) usage(); ++argv; iflag = 1; } if (*argv) { nlistf = *argv; if (*++argv) memf = *argv; } } #endif /* * Discard setgid privileges if not the running kernel so that bad * guys can't print interesting stuff from kernel memory. */ live = (nlistf == NULL && memf == NULL); if (!live) { if (setgid(getgid()) != 0) xo_err(-1, "setgid"); } if (xflag && Tflag) xo_errx(1, "-x and -T are incompatible, pick one."); if (Bflag) { if (!live) usage(); bpf_stats(interface); xo_finish(); exit(0); } if (mflag) { if (!live) { if (kread(0, NULL, 0) == 0) mbpr(kvmd, nl[N_SFSTAT].n_value); } else mbpr(NULL, 0); xo_finish(); exit(0); } if (Qflag) { if (!live) { if (kread(0, NULL, 0) == 0) netisr_stats(); } else netisr_stats(); xo_finish(); exit(0); } #if 0 /* * Keep file descriptors open to avoid overhead * of open/close on each call to get* routines. */ sethostent(1); setnetent(1); #else /* * This does not make sense any more with DNS being default over * the files. Doing a setXXXXent(1) causes a tcp connection to be * used for the queries, which is slower. */ #endif if (iflag && !sflag) { xo_open_container("statistics"); intpr(NULL, af); xo_close_container("statistics"); xo_finish(); exit(0); } if (rflag) { xo_open_container("statistics"); if (sflag) { rt_stats(); flowtable_stats(); } else routepr(fib, af); xo_close_container("statistics"); xo_finish(); exit(0); } if (gflag) { xo_open_container("statistics"); if (sflag) { if (af == AF_INET || af == AF_UNSPEC) mrt_stats(); #ifdef INET6 if (af == AF_INET6 || af == AF_UNSPEC) mrt6_stats(); #endif } else { if (af == AF_INET || af == AF_UNSPEC) mroutepr(); #ifdef INET6 if (af == AF_INET6 || af == AF_UNSPEC) mroute6pr(); #endif } xo_close_container("statistics"); xo_finish(); exit(0); } /* Load all necessary kvm symbols */ kresolve_list(nl); if (tp) { xo_open_container("statistics"); printproto(tp, tp->pr_name, &first); if (!first) xo_close_list("socket"); xo_close_container("statistics"); xo_finish(); exit(0); } xo_open_container("statistics"); if (af == AF_INET || af == AF_UNSPEC) for (tp = protox; tp->pr_name; tp++) printproto(tp, tp->pr_name, &first); #ifdef INET6 if (af == AF_INET6 || af == AF_UNSPEC) for (tp = ip6protox; tp->pr_name; tp++) printproto(tp, tp->pr_name, &first); #endif /*INET6*/ #ifdef IPSEC if (af == PF_KEY || af == AF_UNSPEC) for (tp = pfkeyprotox; tp->pr_name; tp++) printproto(tp, tp->pr_name, &first); #endif /*IPSEC*/ #ifdef NETGRAPH if (af == AF_NETGRAPH || af == AF_UNSPEC) for (tp = netgraphprotox; tp->pr_name; tp++) printproto(tp, tp->pr_name, &first); #endif /* NETGRAPH */ if ((af == AF_UNIX || af == AF_UNSPEC) && !sflag) unixpr(nl[N_UNP_COUNT].n_value, nl[N_UNP_GENCNT].n_value, nl[N_UNP_DHEAD].n_value, nl[N_UNP_SHEAD].n_value, nl[N_UNP_SPHEAD].n_value, &first); if (!first) xo_close_list("socket"); xo_close_container("statistics"); xo_finish(); exit(0); }
void bpf_stats(char *ifname) { struct xbpf_d *d, *bd, zerostat; char *pname, flagbuf[12]; size_t size; if (zflag) { bzero(&zerostat, sizeof(zerostat)); if (sysctlbyname("net.bpf.stats", NULL, NULL, &zerostat, sizeof(zerostat)) < 0) xo_warn("failed to zero bpf counters"); return; } if (sysctlbyname("net.bpf.stats", NULL, &size, NULL, 0) < 0) { xo_warn("net.bpf.stats"); return; } if (size == 0) return; bd = malloc(size); if (bd == NULL) { xo_warn("malloc failed"); return; } if (sysctlbyname("net.bpf.stats", bd, &size, NULL, 0) < 0) { xo_warn("net.bpf.stats"); free(bd); return; } xo_emit("{T:/%5s} {T:/%6s} {T:/%7s} {T:/%9s} {T:/%9s} {T:/%9s} " "{T:/%5s} {T:/%5s} {T:/%s}\n", "Pid", "Netif", "Flags", "Recv", "Drop", "Match", "Sblen", "Hblen", "Command"); xo_open_container("bpf-statistics"); xo_open_list("bpf-entry"); for (d = &bd[0]; d < &bd[size / sizeof(*d)]; d++) { if (d->bd_structsize != sizeof(*d)) { xo_warnx("bpf_stats_extended: version mismatch"); return; } if (ifname && strcmp(ifname, d->bd_ifname) != 0) continue; xo_open_instance("bpf-entry"); pname = bpf_pidname(d->bd_pid); xo_emit("{k:pid/%5d} {k:interface-name/%6s} ", d->bd_pid, d->bd_ifname); bpf_flags(d, flagbuf); xo_emit("{d:flags/%7s} {:received-packets/%9ju} " "{:dropped-packets/%9ju} {:filter-packets/%9ju} " "{:store-buffer-length/%5d} {:hold-buffer-length/%5d} " "{:process/%s}\n", flagbuf, (uintmax_t)d->bd_rcount, (uintmax_t)d->bd_dcount, (uintmax_t)d->bd_fcount, d->bd_slen, d->bd_hlen, pname); free(pname); xo_close_instance("bpf-entry"); } xo_close_list("bpf-entry"); xo_close_container("bpf-statistics"); free(bd); }
int main(int argc, char *argv[]) { int ch, interval, tmp; int i; struct kinfo_proc *p; struct procstat *prstat, *cprstat; long l; pid_t pid; char *dummy; char *nlistf, *memf; const char *xocontainer; int cnt; interval = 0; memf = nlistf = NULL; argc = xo_parse_args(argc, argv); xocontainer = "basic"; while ((ch = getopt(argc, argv, "CHN:M:abcefijklhrsStvw:x")) != -1) { switch (ch) { case 'C': Cflag++; break; case 'H': Hflag++; break; case 'M': memf = optarg; break; case 'N': nlistf = optarg; break; case 'S': Sflag++; xocontainer = "cs"; break; case 'a': aflag++; break; case 'b': bflag++; xocontainer = "binary"; break; case 'c': cflag++; xocontainer = "arguments"; break; case 'e': eflag++; xocontainer = "environment"; break; case 'f': fflag++; xocontainer = "files"; break; case 'i': iflag++; xocontainer = "signals"; break; case 'j': jflag++; xocontainer = "thread_signals"; break; case 'k': kflag++; xocontainer = "kstack"; break; case 'l': lflag++; xocontainer = "rlimit"; break; case 'n': nflag++; break; case 'h': hflag++; break; case 'r': rflag++; xocontainer = "rusage"; break; case 's': sflag++; xocontainer = "credentials"; break; case 't': tflag++; xocontainer = "threads"; break; case 'v': vflag++; xocontainer = "vm"; break; case 'w': l = strtol(optarg, &dummy, 10); if (*dummy != '\0') usage(); if (l < 1 || l > INT_MAX) usage(); interval = l; break; case 'x': xflag++; xocontainer = "auxv"; break; case '?': default: usage(); } } argc -= optind; argv += optind; /* We require that either 0 or 1 mode flags be set. */ tmp = bflag + cflag + eflag + fflag + iflag + jflag + (kflag ? 1 : 0) + lflag + rflag + sflag + tflag + vflag + xflag + Sflag; if (!(tmp == 0 || tmp == 1)) usage(); /* We allow -k to be specified up to twice, but not more. */ if (kflag > 2) usage(); /* Must specify either the -a flag or a list of pids. */ if (!(aflag == 1 && argc == 0) && !(aflag == 0 && argc > 0)) usage(); /* Only allow -C with -f. */ if (Cflag && !fflag) usage(); if (memf != NULL) prstat = procstat_open_kvm(nlistf, memf); else prstat = procstat_open_sysctl(); if (prstat == NULL) xo_errx(1, "procstat_open()"); do { xo_set_version(PROCSTAT_XO_VERSION); xo_open_container("procstat"); xo_open_container(xocontainer); if (aflag) { p = procstat_getprocs(prstat, KERN_PROC_PROC, 0, &cnt); if (p == NULL) xo_errx(1, "procstat_getprocs()"); kinfo_proc_sort(p, cnt); for (i = 0; i < cnt; i++) { procstat(prstat, &p[i]); /* Suppress header after first process. */ hflag = 1; xo_flush(); } procstat_freeprocs(prstat, p); } for (i = 0; i < argc; i++) { l = strtol(argv[i], &dummy, 10); if (*dummy == '\0') { if (l < 0) usage(); pid = l; p = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt); if (p == NULL) xo_errx(1, "procstat_getprocs()"); if (cnt != 0) procstat(prstat, p); procstat_freeprocs(prstat, p); } else { cprstat = procstat_open_core(argv[i]); if (cprstat == NULL) { warnx("procstat_open()"); continue; } p = procstat_getprocs(cprstat, KERN_PROC_PID, -1, &cnt); if (p == NULL) xo_errx(1, "procstat_getprocs()"); if (cnt != 0) procstat(cprstat, p); procstat_freeprocs(cprstat, p); procstat_close(cprstat); } /* Suppress header after first process. */ hflag = 1; } xo_close_container(xocontainer); xo_close_container("procstat"); xo_finish(); if (interval) sleep(interval); } while (interval); procstat_close(prstat); exit(0); }
int main(int argc, char *argv[]) { int ch, func = 0; int rtn = 0; int aflag = 0; /* do it for all entries */ argc = xo_parse_args(argc, argv); if (argc < 0) exit(1); while ((ch = getopt(argc, argv, "andfsSi:")) != -1) switch(ch) { case 'a': aflag = 1; break; case 'd': SETFUNC(F_DELETE); break; case 'n': nflag = 1; break; case 'S': SETFUNC(F_REPLACE); break; case 's': SETFUNC(F_SET); break; case 'f' : SETFUNC(F_FILESET); break; case 'i': rifname = optarg; break; case '?': default: usage(); } argc -= optind; argv += optind; if (!func) func = F_GET; if (rifname) { if (func != F_GET && !(func == F_DELETE && aflag)) xo_errx(1, "-i not applicable to this operation"); if (if_nametoindex(rifname) == 0) { if (errno == ENXIO) xo_errx(1, "interface %s does not exist", rifname); else xo_err(1, "if_nametoindex(%s)", rifname); } } switch (func) { case F_GET: if (aflag) { if (argc != 0) usage(); xo_set_version(ARP_XO_VERSION); xo_open_container("arp"); xo_open_list("arp-cache"); search(0, print_entry); xo_close_list("arp-cache"); xo_close_container("arp"); xo_finish(); } else { if (argc != 1) usage(); rtn = get(argv[0]); } break; case F_SET: case F_REPLACE: if (argc < 2 || argc > 6) usage(); if (func == F_REPLACE) (void)delete(argv[0]); rtn = set(argc, argv) ? 1 : 0; break; case F_DELETE: if (aflag) { if (argc != 0) usage(); search(0, nuke_entry); } else { if (argc != 1) usage(); rtn = delete(argv[0]); } break; case F_FILESET: if (argc != 1) usage(); rtn = file(argv[0]); break; } if (ifnameindex != NULL) if_freenameindex(ifnameindex); return (rtn); }
int main (int argc, char **argv) { static char domainname[] = "gt_01"; static char path[MAXPATHLEN]; const char *tzone = "EST"; const char *lang = "pig_latin"; argc = xo_parse_args(argc, argv); if (argc < 0) return 1; for (argc = 1; argv[argc]; argc++) { if (strcmp(argv[argc], "tz") == 0) tzone = argv[++argc]; else if (strcmp(argv[argc], "lang") == 0) lang = argv[++argc]; else if (strcmp(argv[argc], "po") == 0) strlcpy(path, argv[++argc], sizeof(path)); } setenv("LANG", lang, 1); setenv("TZ", tzone, 1); if (path[0] == 0) { getcwd(path, sizeof(path)); strlcat(path, "/po", sizeof(path)); } setlocale(LC_ALL, ""); bindtextdomain(domainname, path); bindtextdomain("ldns", path); bindtextdomain("strerror", path); textdomain(domainname); tzset(); xo_open_container("top"); xo_emit("{G:}Your {qg:adjective} {g:noun} is {g:verb} {qg:owner} {g:target}\n", "flaming", "sword", "burning", "my", "couch"); xo_emit("{G:}The {qg:adjective} {g:noun} was {g:verb} {qg:owner} {g:target}\n", "flaming", "sword", "burning", "my", "couch"); int i; for (i = 0; i < 5; i++) xo_emit("{lw:bytes/%d}{Ngp:byte,bytes}\n", i); xo_emit("{G:}{L:total} {:total/%u}\n", 1234); xo_emit("{G:ldns}Received {:received/%zu} {Ngp:byte,bytes} " "from {:from/%s}#{:port/%d} in {:time/%d} ms\n", (size_t) 1234, "foop", 4321, 32); xo_emit("{G:}Received {:received/%zu} {Ngp:byte,bytes} " "from {:from/%s}#{:port/%d} in {:time/%d} ms\n", (size_t) 1234, "foop", 4321, 32); xo_emit("{G:/%s}Received {:received/%zu} {Ngp:byte,bytes} " "from {:from/%s}#{:port/%d} in {:time/%d} ms\n", "ldns", (size_t) 1234, "foop", 4321, 32); struct timeval tv; tv.tv_sec = 1435085229; tv.tv_usec = 123456; struct tm tm; (void) gmtime_r(&tv.tv_sec, &tm); char date[64]; strftime(date, sizeof(date), "%+", &tm); xo_emit("{G:}Only {:marzlevanes/%d} {Ngp:marzlevane,marzlevanes} " "are functioning correctly\n", 3); xo_emit("{G:}Version {:version} {:date}\n", "1.2.3", date); errno = EACCES; xo_emit_warn("{G:}Unable to {g:verb/objectulate} forward velociping"); xo_emit_warn("{G:}{g:style/automatic} synchronization of {g:type/cardinal} " "{g:target/grammeters} failed"); xo_emit("{G:}{Lwcg:hydrocoptic marzlevanes}{:marzlevanes/%d}\n", 6); xo_emit("{G:}{Lwcg:Windings}{g:windings}\n", "lotus-o-delta"); xo_close_container("top"); xo_finish(); return 0; }
int main(int argc, char *argv[]) { int ch, errors, total; (void) setlocale(LC_CTYPE, ""); argc = xo_parse_args(argc, argv); if (argc < 0) return (argc); while ((ch = getopt(argc, argv, "clmwL")) != -1) switch((char)ch) { case 'l': doline = 1; break; case 'w': doword = 1; break; case 'c': dochar = 1; domulti = 0; break; case 'L': dolongline = 1; break; case 'm': domulti = 1; dochar = 0; break; case '?': default: usage(); } argv += optind; argc -= optind; (void)signal(SIGINFO, siginfo_handler); /* Wc's flags are on by default. */ if (doline + doword + dochar + domulti + dolongline == 0) doline = doword = dochar = 1; stderr_handle = xo_create_to_file(stderr, XO_STYLE_TEXT, 0); xo_open_container("wc"); xo_open_list("file"); errors = 0; total = 0; if (!*argv) { xo_open_instance("file"); if (cnt((char *)NULL) != 0) ++errors; xo_close_instance("file"); } else { do { xo_open_instance("file"); if (cnt(*argv) != 0) ++errors; xo_close_instance("file"); ++total; } while(*++argv); } xo_close_list("file"); if (total > 1) { xo_open_container("total"); show_cnt("total", tlinect, twordct, tcharct, tlongline); xo_close_container("total"); } xo_close_container("wc"); xo_finish(); exit(errors == 0 ? 0 : 1); }
int main (int argc, char **argv) { static char base_grocery[] = "GRO"; static char base_hardware[] = "HRD"; struct item { const char *i_title; int i_sold; int i_instock; int i_onorder; const char *i_sku_base; int i_sku_num; }; struct item list[] = { { "gum", 1412, 54, 10, base_grocery, 415 }, { "rope", 85, 4, 2, base_hardware, 212 }, { "ladder", 0, 2, 1, base_hardware, 517 }, { "bolt", 4123, 144, 42, base_hardware, 632 }, { "water", 17, 14, 2, base_grocery, 2331 }, { NULL, 0, 0, 0, NULL, 0 } }; struct item list2[] = { { "fish", 1321, 45, 1, base_grocery, 533 }, { NULL, 0, 0, 0, NULL, 0 } }; struct item *ip; xo_info_t info[] = { { "in-stock", "number", "Number of items in stock" }, { "name", "string", "Name of the item" }, { "on-order", "number", "Number of items on order" }, { "sku", "string", "Stock Keeping Unit" }, { "sold", "number", "Number of items sold" }, { NULL, NULL, NULL }, }; int info_count = (sizeof(info) / sizeof(info[0])) - 1; argc = xo_parse_args(argc, argv); if (argc < 0) return 1; for (argc = 1; argv[argc]; argc++) { if (strcmp(argv[argc], "xml") == 0) xo_set_style(NULL, XO_STYLE_XML); else if (strcmp(argv[argc], "json") == 0) xo_set_style(NULL, XO_STYLE_JSON); else if (strcmp(argv[argc], "text") == 0) xo_set_style(NULL, XO_STYLE_TEXT); else if (strcmp(argv[argc], "html") == 0) xo_set_style(NULL, XO_STYLE_HTML); else if (strcmp(argv[argc], "pretty") == 0) xo_set_flags(NULL, XOF_PRETTY); else if (strcmp(argv[argc], "xpath") == 0) xo_set_flags(NULL, XOF_XPATH); else if (strcmp(argv[argc], "info") == 0) xo_set_flags(NULL, XOF_INFO); else if (strcmp(argv[argc], "error") == 0) { close(-1); xo_err(1, "error detected"); } } xo_set_info(NULL, info, info_count); xo_set_flags(NULL, XOF_KEYS); xo_open_container_h(NULL, "top"); xo_attr("test", "value"); xo_open_container("data"); xo_open_list("item"); xo_attr("test2", "value2"); xo_emit("{T:Item/%-10s}{T:Total Sold/%12s}{T:In Stock/%12s}" "{T:On Order/%12s}{T:SKU/%5s}\n"); for (ip = list; ip->i_title; ip++) { xo_open_instance("item"); xo_attr("test3", "value3"); xo_emit("{keq:sku/%s-%u/%s-000-%u}" "{k:name/%-10s/%s}{n:sold/%12u/%u}{:in-stock/%12u/%u}" "{:on-order/%12u/%u}{qkd:sku/%5s-000-%u/%s-000-%u}\n", ip->i_sku_base, ip->i_sku_num, ip->i_title, ip->i_sold, ip->i_instock, ip->i_onorder, ip->i_sku_base, ip->i_sku_num); xo_close_instance("item"); } xo_close_list("item"); xo_close_container("data"); xo_emit("\n\n"); xo_open_container("data"); xo_open_list("item"); for (ip = list; ip->i_title; ip++) { xo_open_instance("item"); xo_emit("{keq:sku/%s-%u/%s-000-%u}", ip->i_sku_base, ip->i_sku_num); xo_emit("{L:Item} '{k:name/%s}':\n", ip->i_title); xo_emit("{P: }{L:Total sold}: {n:sold/%u%s}\n", ip->i_sold, ip->i_sold ? ".0" : ""); xo_emit("{P: }{Lcw:In stock}{:in-stock/%u}\n", ip->i_instock); xo_emit("{P: }{Lcw:On order}{:on-order/%u}\n", ip->i_onorder); xo_emit("{P: }{L:SKU}: {qkd:sku/%s-000-%u}\n", ip->i_sku_base, ip->i_sku_num); xo_close_instance("item"); } xo_close_list("item"); xo_close_container("data"); xo_open_container("data"); xo_open_list("item"); for (ip = list2; ip->i_title; ip++) { xo_open_instance("item"); xo_emit("{keq:sku/%s-%u/%s-000-%u}", ip->i_sku_base, ip->i_sku_num); xo_emit("{L:Item} '{k:name/%s}':\n", ip->i_title); xo_emit("{P: }{L:Total sold}: {n:sold/%u%s}\n", ip->i_sold, ip->i_sold ? ".0" : ""); xo_emit("{P: }{Lcw:In stock}{:in-stock/%u}\n", ip->i_instock); xo_emit("{P: }{Lcw:On order}{:on-order/%u}\n", ip->i_onorder); xo_emit("{P: }{L:SKU}: {qkd:sku/%s-000-%u}\n", ip->i_sku_base, ip->i_sku_num); xo_close_instance("item"); } xo_close_list("item"); xo_close_container("data"); xo_open_container("data"); xo_open_list("item"); for (ip = list; ip->i_title; ip++) { xo_attr("test4", "value4"); xo_emit("{Lwc:Item}{l:item}\n", ip->i_title); } xo_close_list("item"); xo_close_container("data"); xo_emit("X{P:}X", "epic fail"); xo_emit("X{T:}X", "epic fail"); xo_emit("X{N:}X", "epic fail"); xo_emit("X{L:}X\n", "epic fail"); xo_emit("X{P: }X{Lwc:Cost}{:cost/%u}\n", 425); xo_emit("X{P:/%30s}X{Lwc:Cost}{:cost/%u}\n", "", 455); xo_close_container_h(NULL, "top"); xo_finish(); return 0; }
/* * Dump ICMP statistics. */ void icmp_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct icmpstat icmpstat; size_t len; int i, first; if (fetch_stats("net.inet.icmp.stats", off, &icmpstat, sizeof(icmpstat), kread_counters) != 0) return; xo_open_container(name); xo_emit("{T:/%s}:\n", name); #define p(f, m) if (icmpstat.f || sflag <= 1) \ xo_emit(m, icmpstat.f, plural(icmpstat.f)) #define p1a(f, m) if (icmpstat.f || sflag <= 1) \ xo_emit(m, icmpstat.f) #define p2(f, m) if (icmpstat.f || sflag <= 1) \ xo_emit(m, icmpstat.f, plurales(icmpstat.f)) p(icps_error, "\t{:icmp-calls/%lu} " "{N:/call%s to icmp_error}\n"); p(icps_oldicmp, "\t{:errors-not-from-message/%lu} " "{N:/error%s not generated in response to an icmp message}\n"); for (first = 1, i = 0; i < ICMP_MAXTYPE + 1; i++) { if (icmpstat.icps_outhist[i] != 0) { if (first) { xo_open_list("output-histogram"); xo_emit("\tOutput histogram:\n"); first = 0; } xo_open_instance("output-histogram"); if (icmpnames[i] != NULL) xo_emit("\t\t{k:name/%s}: {:count/%lu}\n", icmpnames[i], icmpstat.icps_outhist[i]); else xo_emit("\t\tunknown ICMP #{k:name/%d}: " "{:count/%lu}\n", i, icmpstat.icps_outhist[i]); xo_close_instance("output-histogram"); } } if (!first) xo_close_list("output-histogram"); p(icps_badcode, "\t{:dropped-bad-code/%lu} " "{N:/message%s with bad code fields}\n"); p(icps_tooshort, "\t{:dropped-too-short/%lu} " "{N:/message%s less than the minimum length}\n"); p(icps_checksum, "\t{:dropped-bad-checksum/%lu} " "{N:/message%s with bad checksum}\n"); p(icps_badlen, "\t{:dropped-bad-length/%lu} " "{N:/message%s with bad length}\n"); p1a(icps_bmcastecho, "\t{:dropped-multicast-echo/%lu} " "{N:/multicast echo requests ignored}\n"); p1a(icps_bmcasttstamp, "\t{:dropped-multicast-timestamp/%lu} " "{N:/multicast timestamp requests ignored}\n"); for (first = 1, i = 0; i < ICMP_MAXTYPE + 1; i++) { if (icmpstat.icps_inhist[i] != 0) { if (first) { xo_open_list("input-histogram"); xo_emit("\tInput histogram:\n"); first = 0; } xo_open_instance("input-histogram"); if (icmpnames[i] != NULL) xo_emit("\t\t{k:name/%s}: {:count/%lu}\n", icmpnames[i], icmpstat.icps_inhist[i]); else xo_emit( "\t\tunknown ICMP #{k:name/%d}: {:count/%lu}\n", i, icmpstat.icps_inhist[i]); xo_close_instance("input-histogram"); } } if (!first) xo_close_list("input-histogram"); p(icps_reflect, "\t{:sent-packets/%lu} " "{N:/message response%s generated}\n"); p2(icps_badaddr, "\t{:discard-invalid-return-address/%lu} " "{N:/invalid return address%s}\n"); p(icps_noroute, "\t{:discard-no-route/%lu} " "{N:/no return route%s}\n"); #undef p #undef p1a #undef p2 if (live) { len = sizeof i; if (sysctlbyname("net.inet.icmp.maskrepl", &i, &len, NULL, 0) < 0) return; xo_emit("\tICMP address mask responses are " "{q:icmp-address-responses/%sabled}\n", i ? "en" : "dis"); } xo_close_container(name); }
int main (int argc, char **argv) { struct employee { const char *e_first; const char *e_nic; const char *e_last; unsigned e_dept; unsigned e_percent; } employees[] = { { "Jim", "რეგტ", "გთხოვთ ახ", 431, 90 }, { "Terry", "<one", "Οὐχὶ ταὐτὰ παρίσταταί μοι Jones", 660, 90 }, { "Leslie", "Les", "Patterson", 341,60 }, { "Ashley", "Ash", "Meter & Smith", 1440, 40 }, { "0123456789", "0123456789", "012345678901234567890", 1440, 40 }, { "ახლა", "გაიარო", "საერთაშორისო", 123, 90 }, { "෴ණ්ණ෴෴ණ්ණ෴", "Mick", "෴ණ්ණ෴෴ණ්ණ෴෴ණ්ණ෴෴෴", 110, 20 }, { NULL, NULL } }, *ep = employees; int rc; argc = xo_parse_args(argc, argv); if (argc < 0) return 1; xo_set_info(NULL, info, info_count); xo_set_flags(NULL, XOF_COLUMNS); xo_open_container("employees"); xo_emit("Οὐχὶ ταὐτὰ παρίσταταί μοι {:v1/%s}, {:v2/%s}\n", "γιγνώσκειν", "ὦ ἄνδρες ᾿Αθηναῖοι"); rc = xo_emit("გთხოვთ {:v1/%s} {:v2/%s}\n", "ახლავე გაიაროთ რეგისტრაცია", "Unicode-ის მეათე საერთაშორისო"); xo_emit("{Twc:Width}{:width/%d}\n", rc); /* Okay, Sinhala is uber cool ... */ rc = xo_emit("[{:sinhala}]\n", "෴ණ්ණ෴"); xo_emit("{Twc:Width}{:width/%d}\n", rc); rc = xo_emit("[{:sinhala}]\n", "෴"); xo_emit("{Twc:Width}{:width/%d}\n", rc); rc = xo_emit("[{:sinhala/%-4..4s/%s}]\n", "෴ණ්ණ෴෴ණ්ණ෴"); xo_emit("[{:not-sinhala/%-4..4s/%s}]\n", "123456"); rc = xo_emit("[{:tag/%s}]\n", "ර්ඝ"); xo_emit("{Twc:Width}{:width/%d}\n", rc); xo_open_list("employee"); xo_emit("{T:First Name/%-25s}{T:Last Name/%-14s}" "{T:/%-12s}{T:Time (%)}\n", "Department"); for ( ; ep->e_first; ep++) { xo_open_instance("employee"); xo_emit("{[:-25}{:first-name/%s} ({:nic-name/\"%s\"}){]:}" "{:last-name/%-14..14s/%s}" "{:department/%8u/%u}{:percent-time/%8u/%u}\n", ep->e_first, ep->e_nic, ep->e_last, ep->e_dept, ep->e_percent); if (ep->e_percent > 50) { xo_attr("full-time", "%s", "honest & for true"); xo_emit("{e:benefits/%s}", "full"); } xo_close_instance("employee"); } xo_close_list("employee"); xo_close_container("employees"); xo_finish(); return 0; }