/** * @file whoson.c * @brief Who is logged on to this z/OS system, and how: TSO/E, z/OSMF, SSH. * * SPDX-License-Identifier: MIT OR Apache-2.0 OR BSD-2-Clause * SPDX-FileCopyrightText: 2026 Sean Kurtz * * @details Sessions come from the address space control blocks, not from a * subsystem or a console command: CVT (PSA+X'10') -> ASVT -> every allocated * ASCB. That walk reads only common storage, which is mapped into every address * space, so it needs no APF authorization, no supervisor state and no key zero. * ASCBJBNI holds the job name; the logon procedure comes from the session's * CSCB (CHCLS), not from ASCBJBNS, which only names how the address space was * started. A non-zero ASCBTSB, or a CSCB track id of X'01', marks TSO/E. * * The CPU column is the address space's TCB time (ASCBEJST), SRB time * (ASCBSRBT) and preemptable SRB time (the ASSB's ASSBASST). All three are * TOD-clock accumulators: the low 12 bits are the fraction, so >> 12 is * microseconds. * * SSH sessions come from the process table: sshd forks one worker per * connection, so a process whose parent is an sshd (and which is not itself * an sshd) is a login. w_getpsent supplies that tree; ps supplies the * address-space id (BPXYPGPS has one, the C W_PSPROC does not). The join to * the ASCB is by ASID, not by job name: sshd's fork job names repeat. * * Control blocks are read through volatile pointers on purpose: nothing in * this file may be cached across the walk, because the blocks change under * it. Every read of a control block is guarded: an address space can end * between the ASVT read and the ASCB read, and a stale pointer must skip one * row, not abend the program. The handler assumes z/OS raises SIGSEGV * synchronously for an unmapped common-storage read; ISO C leaves that * implementation-defined, but the platform does it. * * Character conversion follows the zopen conventions: source and output are * ISO8859-1 (CCSID 819) and the descriptor's tag says what the destination * expects. A text file with no tag (or a non-EBCDIC tag) is tagged 819 and * receives ASCII; an EBCDIC file, terminal or pipe is tagged IBM-1047 and * the C runtime converts the ASCII writes (fcntl F_CONTROL_CVT). Nothing is * decided from isatty(), and no byte is converted twice. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* Attributes without C23 spelling wrap here, so call sites stay readable. */ #ifdef __clang__ /** @brief printf-format checking for a wrapper that forwards a va_list. */ #define PRINTFLIKE(fmt_index, va_index) \ __attribute__((format(printf, fmt_index, va_index))) #else #define PRINTFLIKE(fmt_index, va_index) #endif /* Buffer and column widths. */ static constexpr size_t msg_len = 512; /**< one formatted message or table line */ static constexpr size_t name_len = 16; /**< a userid from CHKEY or getpwuid */ static constexpr size_t job_len = 9; /**< an 8-byte job name, plus the nul */ static constexpr size_t asid_len = 8; /**< "%04X" of an ASID, plus the nul */ static constexpr size_t pid_len = 12; /**< a 32-bit pid in decimal, plus the nul */ static constexpr size_t cpu_len = 16; /**< a formatted CPU duration */ static constexpr size_t path_len = 64; /**< basename of a process path */ static constexpr size_t out_len = 8192; /**< the whole table, then one write */ static constexpr size_t cmd_buf = 2048; /**< W_PSPROC command buffer */ static constexpr size_t tty_buf = 2048; /**< W_PSPROC controlling-TTY buffer */ #ifdef PS_PATHBLEN /** @brief W_PSPROC path buffer: the header's own limit when it has one. */ static constexpr size_t ps_path_buf = PS_PATHBLEN; #else /** @brief W_PSPROC path buffer, for headers that do not name a limit. */ static constexpr size_t ps_path_buf = 1027; #endif /* CVTASVT. The ASVT's own head, then ASVTENTY, the array of ASCB addresses; * a set high bit marks an ASID that is free or non-reusable. */ /** @brief CVT field holding the ASVT address (CVTASVT). */ static constexpr uint32_t cvt_asvt_off = 0x22CU; /** @brief ASVT field: the eye-catcher "ASVT". */ static constexpr uint32_t asvt_acronym_off = 0x200U; /** @brief ASVT field: highest ASID in use (ASVTMXU). */ static constexpr uint32_t asvt_maxu_off = 0x204U; /** @brief ASVT field: first entry of ASVTENTY, four bytes each. */ static constexpr uint32_t asvt_enty_off = 0x210U; /* An eye-catcher is a four-byte word that spells its block name in EBCDIC, * and these blocks are filled in while the system runs in EBCDIC, even when * whoson is built in ASCII mode. The value therefore cannot be a character * literal: 'ASCB' would be the ASCII bytes B0 09 34 7E. */ /** @brief "ASVT" as it appears in the ASVT. */ static constexpr uint32_t asvt_acronym = 0xC1E2E5E3U; /** @brief "ASCB" as it appears in the ASCB. */ static constexpr uint32_t ascb_acronym = 0xC1E2C3C2U; /** @brief "CSCB" as it appears in the CSCB. */ static constexpr uint32_t cscb_acronym = 0xC3E2C3C2U; /** @brief "ASSB" as it appears in the ASSB. */ static constexpr uint32_t assb_acronym = 0xC1E2E2C2U; /** @brief CSCB CHTRKID value that marks a TSO/E session. */ enum { CSCB_TRKID_TSO = 0x01 }; /* Packed so the compiler adds no padding of its own: every offset is the sum * of the field widths, and the static asserts pin the fields the walk reads. * The overlays describe layout only; every read goes through the accessors, * so the compiler never assumes the block is stable. */ /** * @brief Address space control block, as far as the walk needs it (ASCB). */ typedef struct __attribute__((packed)) ascb { uint32_t ascbascb; /**< X'00' eye-catcher */ unsigned char ascbresv0[0x24 - 0x04]; /**< X'04' unused here */ uint16_t ascbasid; /**< X'24' address space id */ unsigned char ascbresv1[0x38 - 0x26]; /**< X'26' unused here */ uint32_t ascbcscb; /**< X'38' CSCB address */ uint32_t ascbtsb; /**< X'3C' TSB address, zero if none */ uint64_t ascbejst; /**< X'40' TCB CPU in TOD units */ unsigned char ascbresv2[0xAC - 0x48]; /**< X'48' unused here */ uint32_t ascbjbni; /**< X'AC' job name, for a batch job */ uint32_t ascbjbns; /**< X'B0' procedure name, or job */ unsigned char ascbresv3[0xC8 - 0xB4]; /**< X'B4' unused here */ uint64_t ascbsrbt; /**< X'C8' SRB CPU in TOD units */ unsigned char ascbresv4[0x150 - 0xD0]; /**< X'D0' unused here */ uint32_t ascbassb; /**< X'150' ASSB address */ } ascb; /** @brief Command scheduling control block (CSCB), the session's identity. */ typedef struct __attribute__((packed)) cscb { uint32_t chptr; /**< X'00' chain pointer */ unsigned char chvcd; /**< X'04' VCD */ unsigned char chsze; /**< X'05' block size */ unsigned char chresv0[0x08 - 0x06]; /**< X'06' unused here */ char chkey[8]; /**< X'08' userid */ char chcls[8]; /**< X'10' logon procedure name */ uint32_t chunit; /**< X'18' unit */ unsigned char chtrkid; /**< X'1C' X'01' is a TSO/E session */ unsigned char chresv1; /**< X'1D' unused here */ uint16_t chasid; /**< X'1E' address space id */ unsigned char chresv2[0xD8 - 0x20]; /**< X'20' unused here */ char chcscbid[4]; /**< X'D8' eye-catcher */ } cscb; /** @brief Address space secondary block: preemptible SRB time (ASSB). */ typedef struct __attribute__((packed)) assb { char assbassb[4]; /**< X'000' eye-catcher */ unsigned char assbresv[0x160 - 0x04]; /**< X'004' unused here */ uint64_t assbasst; /**< X'160' SRB CPU in TOD units */ } assb; static_assert(alignof(ascb) == 1); static_assert(alignof(cscb) == 1); static_assert(alignof(assb) == 1); static_assert(sizeof(ascb) == 0x154); static_assert(sizeof(cscb) == 0xDC); static_assert(sizeof(assb) == 0x168); static_assert(offsetof(ascb, ascbasid) == 0x24, "ASCBASID"); static_assert(offsetof(ascb, ascbcscb) == 0x38, "ASCBCSCB"); static_assert(offsetof(ascb, ascbtsb) == 0x3C, "ASCBTSB"); static_assert(offsetof(ascb, ascbejst) == 0x40, "ASCBEJST"); static_assert(offsetof(ascb, ascbjbni) == 0xAC, "ASCBJBNI"); static_assert(offsetof(ascb, ascbjbns) == 0xB0, "ASCBJBNS"); static_assert(offsetof(ascb, ascbsrbt) == 0xC8, "ASCBSRBT"); static_assert(offsetof(ascb, ascbassb) == 0x150, "ASCBASSB"); static_assert(offsetof(cscb, chkey) == 0x08, "CHKEY"); static_assert(offsetof(cscb, chcls) == 0x10, "CHCLS"); static_assert(offsetof(cscb, chtrkid) == 0x1C, "CHTRKID"); static_assert(offsetof(cscb, chasid) == 0x1E, "CHASID"); static_assert(offsetof(cscb, chcscbid) == 0xD8, "CHCSCBID"); static_assert(offsetof(assb, assbasst) == 0x160, "ASSBASST"); /** @brief What the ASCB walk keeps per address space, indexed by ASID - 1. */ typedef struct space { bool tso; /**< the session is TSO/E */ uint64_t us; /**< microseconds of CPU */ char job[job_len]; /**< job name, or the procedure name */ char user[name_len]; /**< CHKEY userid, else the job name */ char logon[job_len]; /**< CHCLS procedure, else empty */ } space; /** @brief One line of the table, before it is sorted and formatted: a TSO/E * row comes from a space, an SSH row from a process. */ typedef struct row { unsigned asid; /**< ASID, or 0 when no address space is known */ uint64_t us; /**< microseconds of CPU */ pid_t pid; /**< POSIX pid, or 0 for a TSO/E session */ const char *type; /**< "TSO/E", "z/OSMF" or "SSH" */ char job[job_len]; /**< job name, or "-" */ char logon[job_len]; /**< logon procedure, or "-" */ char user[name_len]; /**< userid */ } row; /** @brief One process from the table, reduced to what the SSH rule needs. */ typedef struct proc { pid_t pid; /**< process id */ pid_t ppid; /**< parent process id */ uid_t euid; /**< effective uid, the userid for SSH */ char name[path_len]; /**< basename of the executable */ } proc; /** @brief One pid-to-ASID pair, as printed by ps -o pid,xasid. */ typedef struct pid_asid { pid_t pid; /**< process id */ unsigned asid; /**< address space id from the xasid column */ } pid_asid; /** @brief The --help text, kept as a plain array: Open XL 2.2 generates * bad code for a string-literal `constexpr` (negative character * representation). */ static const char usage_text[] = "usage: whoson [--help | --version]\n" "\n" "List the interactive sessions on this system: TSO/E, z/OSMF (a TSO/E\n" "session started by the z/OSMF logon procedure) and SSH. Started tasks,\n" "OMVS daemons and the processes inside a session are not listed.\n" "\n" "Options:\n" " -h, --help show this help and exit\n" " -V, --version show the version and exit\n" "\n" "z/OSMF is recognised by its logon procedure name. Set\n" "WHOSON_ZOSMF_PROCS to a comma-separated list to match other names\n" "(default: IZUFPROC).\n"; /* Set by the Makefile from its VERSION, so the binary and the tag agree. */ /** @brief Version string, or "unknown" when the Makefile did not set one. */ #ifndef WHOSON_VERSION #define WHOSON_VERSION "unknown" #endif /** @brief Where a faulting control-block read resumes: set by scan_one() and * read_asvt(), and only valid while a guarded read is in progress. */ static sigjmp_buf fault_env; /** @brief Non-zero while a guarded read is in progress. */ static volatile sig_atomic_t fault_armed; /** @brief Put back the descriptor's conversion setting, from a signal handler. */ static void restore_cvt(void); static void vmessage(bool usage, const char *fmt, va_list ap) PRINTFLIKE(2, 0); static void error_msg(const char *fmt, ...) PRINTFLIKE(1, 2); static void usage_error(const char *fmt, ...) PRINTFLIKE(1, 2); /** @brief Turn a faulting read of an address space that went away into a * skipped row; otherwise restore the conversion setting and die. */ static void on_fault(int sig) { if (fault_armed) siglongjmp(fault_env, 1); restore_cvt(); _exit(128 + sig); } /** @brief Catch SIGSEGV and SIGBUS: a read of an ended address space must * skip one row, not abend the program. */ static void guard(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = on_fault; sigemptyset(&sa.sa_mask); sigaction(SIGSEGV, &sa, nullptr); #ifdef SIGBUS sigaction(SIGBUS, &sa, nullptr); #endif } /** @brief Put the default fault handling back once the walk is over. */ static void unguard(void) { signal(SIGSEGV, SIG_DFL); #ifdef SIGBUS signal(SIGBUS, SIG_DFL); #endif } /* The accessors below read a live control block. volatile is load-bearing: * the compiler may not fold two reads of a block the system is changing, and * it may not assume the value it read once still holds. The pointer cast is * the MVS control-block interface: the address came out of another block. */ /** @brief Read one byte of common storage at addr. */ static uint8_t read_u8(uint32_t addr) { return *(const volatile uint8_t *)(uintptr_t)addr; } /** @brief Read a big-endian 16-bit field of common storage at addr. */ static uint16_t read_u16(uint32_t addr) { return *(const volatile uint16_t *)(uintptr_t)addr; } /** @brief Read a big-endian 32-bit field of common storage at addr. */ static uint32_t read_u32(uint32_t addr) { return *(const volatile uint32_t *)(uintptr_t)addr; } /** @brief Read a big-endian 64-bit field of common storage at addr. */ static uint64_t read_u64(uint32_t addr) { return *(const volatile uint64_t *)(uintptr_t)addr; } /** @brief Set by a failed write, so main can exit nonzero on truncated * output. */ static bool output_failed; /** @brief Write the whole buffer, retrying short writes and EINTR. * @param fd descriptor * @param buf bytes to write * @param len byte count * @return 0 on success, -1 with output_failed set on failure. */ static int write_all(int fd, const char *buf, size_t len) { while (len > 0) { ssize_t n = write(fd, buf, len); if (n < 0 && errno == EINTR) continue; if (n <= 0) { output_failed = true; return -1; } buf += n; len -= (size_t)n; } return 0; } /** * @brief Tag fd as text in ccsid; zopen's setccsid(), through __fchattr(). * @param fd descriptor to tag * @param ccsid CCSID to record, 819 for ASCII * @return 0 on success, -1 with errno set */ static int tag_fd(int fd, unsigned ccsid) { attrib_t a; memset(&a, 0, sizeof(a)); a.att_filetagchg = 1; a.att_filetag.ft_ccsid = (unsigned short)ccsid; a.att_filetag.ft_txtflag = 1; return __fchattr(fd, &a, sizeof(a)); } /** @brief Set the descriptor's character conversion (F_CONTROL_CVT). * @param fd descriptor * @param cmd SETCVTON, SETCVTOFF or QUERYCVT * @param pccsid source CCSID of a write * @param fccsid destination CCSID of a write * @return what fcntl() returns */ static int set_cvt(int fd, int cmd, int pccsid, int fccsid) { struct f_cnvrt c; c.cvtcmd = cmd; c.pccsid = (short)pccsid; c.fccsid = (short)fccsid; return fcntl(fd, F_CONTROL_CVT, &c); } /** @brief A descriptor's starting conversion setting, kept for restore_cvt(). */ typedef struct cvt_saved { int fd; /**< descriptor */ struct f_cnvrt v; /**< the setting to put back */ } cvt_saved; /** @brief Conversion settings saved before whoson changed them. */ static cvt_saved saved_cvt[2]; /** @brief How many entries of saved_cvt are in use (stdout and stderr). */ static size_t nsaved; /** * @brief Put back every saved conversion setting. * * The setting belongs to the open file description, which the calling shell * keeps after whoson exits, so leaving ours behind would change the shell's * own output. Only fcntl(), which is async-signal-safe, is used here. */ static void restore_cvt(void) { size_t i; for (i = 0; i < nsaved; i++) (void)fcntl(saved_cvt[i].fd, F_CONTROL_CVT, &saved_cvt[i].v); } /** @brief Save fd's conversion setting for restore_cvt(). */ static void save_cvt(int fd) { struct f_cnvrt q; memset(&q, 0, sizeof(q)); q.cvtcmd = QUERYCVT; if (fcntl(fd, F_CONTROL_CVT, &q) != 0) return; if (nsaved >= sizeof(saved_cvt) / sizeof(saved_cvt[0])) return; /* main saves stdout and stderr only */ saved_cvt[nsaved].fd = fd; saved_cvt[nsaved].v = q; nsaved++; } /** @brief Whether a stat structure says the file is EBCDIC text. */ static bool ebcdic_tag(const struct stat *st) { return st->st_tag.ft_txtflag && (st->st_tag.ft_ccsid == 37 || st->st_tag.ft_ccsid == 1047); } /** * @brief Write buf in the character set fd expects. * * Files are the ASCII half of the zopen rule; terminals, pipes and * EBCDIC-tagged files are IBM-1047. Only a file's tag is changed (an untagged * file becomes ISO8859-1); a pipe or pty keeps its tag and just gets the * conversion, so the runtime's own output to the same descriptor is not * relabelled. * @param fd descriptor * @param buf ASCII bytes; converted in place when the destination wants * EBCDIC * @param len byte count */ static void emit(int fd, char *buf, size_t len) { struct stat st; bool ascii = false; int fccsid = 1047; if (fstat(fd, &st) == 0) { if (S_ISREG(st.st_mode)) { ascii = !ebcdic_tag(&st); if (ascii && (!st.st_tag.ft_txtflag || st.st_tag.ft_ccsid == 0)) (void)tag_fd(fd, 819); } else if (S_ISSOCK(st.st_mode)) { ascii = true; } else if (st.st_tag.ft_txtflag && st.st_tag.ft_ccsid != 0 && !ebcdic_tag(&st)) { ascii = true; /* a pipe or pty that asked for ASCII */ } else if (ebcdic_tag(&st)) { fccsid = (int)st.st_tag.ft_ccsid; } } if (ascii) { (void)set_cvt(fd, SETCVTOFF, 0, 0); write_all(fd, buf, len); return; } if (set_cvt(fd, SETCVTON, 819, fccsid) == 0) { write_all(fd, buf, len); return; } /* No fcntl support (fstat failed): convert by hand. */ (void)set_cvt(fd, SETCVTOFF, 0, 0); __a2e_l(buf, len); write_all(fd, buf, len); } /** @brief emit() a nul-terminated string, copied into a bounded buffer. */ static void emit_str(int fd, const char *text) { char buf[msg_len]; size_t len = strlen(text); if (len >= sizeof(buf)) len = sizeof(buf) - 1; memcpy(buf, text, len); emit(fd, buf, len); } /** @brief Format into a bounded buffer and emit() it, with the usage text * when the message is a usage error. */ static void vmessage(bool usage, const char *fmt, va_list ap) { char text[msg_len]; vsnprintf(text, sizeof(text), fmt, ap); emit_str(STDERR_FILENO, text); if (usage) { emit_str(STDERR_FILENO, "\n"); emit_str(STDERR_FILENO, usage_text); } } /** @brief Report an error on stderr, in the destination's character set. */ static void error_msg(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vmessage(false, fmt, ap); va_end(ap); } /** @brief Report a usage error on stderr, followed by the usage text. */ static void usage_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vmessage(true, fmt, ap); va_end(ap); } /** * @brief Copy the 8-byte EBCDIC name a control block points at, as ASCII. * * These pointers address common storage, so no cross-memory services are * needed, and the name is decoded with __e2a_l() because the block holds * EBCDIC even in an ASCII build. * @param ptr address of the name in common storage, 0 for none * @param dst output buffer, always nul-terminated * @param dstlen size of dst */ static void read_name(uint32_t ptr, char *dst, size_t dstlen) { unsigned char raw[8]; size_t i; size_t n = 0; if (dstlen == 0) return; dst[0] = '\0'; if (ptr == 0) return; for (i = 0; i < sizeof(raw); i++) raw[i] = read_u8(ptr + (uint32_t)i); __e2a_l((char *)raw, sizeof(raw)); for (i = 0; i < sizeof(raw) && n + 1 < dstlen; i++) { if (raw[i] == ' ' || raw[i] == '\0') break; if (raw[i] < 0x20 || raw[i] > 0x7E) break; dst[n++] = (char)raw[i]; } dst[n] = '\0'; } /** * @brief Read one ASCB into *out, with its CSCB and ASSB. * * Every read is guarded: the address space can end between the ASVT read and * the ASCB read, and the block can be reused while it is being read, so the * ASVT entry is re-checked at the end. * @param idx index into ASVTENTY, so the ASID must be idx + 1 * @param entry the raw ASVT entry, high bit included * @param entries address of ASVTENTY * @param out receives the address space on success * @return 0 on success, -1 when the address space is gone or unreadable */ static int scan_one(unsigned idx, uint32_t entry, uint32_t entries, space *out) { space tmp = {0}; uint32_t ascb_addr = entry & 0x7FFFFFFFu; uint16_t asid; uint32_t cscb_addr; uint64_t tod; bool tso; char key[name_len] = {0}; char cls[job_len] = {0}; fault_armed = 1; if (sigsetjmp(fault_env, 1) != 0) { fault_armed = 0; return -1; } if (read_u32(ascb_addr) != ascb_acronym) goto fail; asid = read_u16(ascb_addr + (uint32_t)offsetof(ascb, ascbasid)); if (asid != idx + 1) goto fail; tod = read_u64(ascb_addr + (uint32_t)offsetof(ascb, ascbejst)) + read_u64(ascb_addr + (uint32_t)offsetof(ascb, ascbsrbt)); cscb_addr = read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbcscb)); tso = read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbtsb)) != 0; { uint32_t assb_addr = read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbassb)); if (assb_addr != 0 && read_u32(assb_addr) == assb_acronym) tod += read_u64(assb_addr + (uint32_t)offsetof(assb, assbasst)); } /* A CSCB that has already been released can still be reachable through a * stale ASCB pointer; its eye-catcher and CHASID say whether the block * still belongs to this address space. */ if (cscb_addr != 0 && read_u32(cscb_addr + (uint32_t)offsetof(cscb, chcscbid)) == cscb_acronym && read_u16(cscb_addr + (uint32_t)offsetof(cscb, chasid)) == asid) { read_name(cscb_addr + (uint32_t)offsetof(cscb, chkey), key, sizeof(key)); read_name(cscb_addr + (uint32_t)offsetof(cscb, chcls), cls, sizeof(cls)); if (read_u8(cscb_addr + (uint32_t)offsetof(cscb, chtrkid)) == CSCB_TRKID_TSO) tso = true; } read_name(read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbjbni)), tmp.job, sizeof(tmp.job)); read_name(read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbjbns)), tmp.logon, sizeof(tmp.logon)); /* The ASVT entry must still name the same ASCB: if the address space * ended while we were reading it, the block may already be reused. */ if (read_u32(entries + 4u * idx) != entry) goto fail; tmp.tso = tso; tmp.us = tod >> 12; if (tmp.job[0] == '\0') snprintf(tmp.job, sizeof(tmp.job), "%s", tmp.logon); if (key[0] != '\0') snprintf(tmp.user, sizeof(tmp.user), "%s", key); else snprintf(tmp.user, sizeof(tmp.user), "%s", tmp.job); if (cls[0] != '\0') snprintf(tmp.logon, sizeof(tmp.logon), "%s", cls); else tmp.logon[0] = '\0'; *out = tmp; fault_armed = 0; return 0; fail: fault_armed = 0; return -1; } /** * @brief Find the ASVT through the CVT and validate it. * @param maxu receives ASVTMXU, the highest ASID in use * @param entries receives the address of ASVTENTY * @return 0 on success, -1 when the PSA, CVT or ASVT cannot be used */ static int read_asvt(unsigned *maxu, uint32_t *entries) { uint32_t cvt; uint32_t asvt; fault_armed = 1; if (sigsetjmp(fault_env, 1) != 0) { fault_armed = 0; return -1; } cvt = read_u32(16); if (cvt == 0) goto fail; asvt = read_u32(cvt + cvt_asvt_off); if (asvt == 0) goto fail; if (read_u32(asvt + asvt_acronym_off) != asvt_acronym) goto fail; *maxu = read_u32(asvt + asvt_maxu_off) & 0xFFFFu; if (*maxu == 0) goto fail; *entries = asvt + asvt_enty_off; fault_armed = 0; return 0; fail: fault_armed = 0; return -1; } /** * @brief Walk ASVTENTY and fill one space per live address space. * @param entries address of ASVTENTY * @param maxu number of entries to examine * @param snap output array, indexed by ASID - 1 * @param found receives the number of address spaces that were read */ static void ascb_scan(uint32_t entries, unsigned maxu, space *snap, unsigned *found) { unsigned i; *found = 0; for (i = 0; i < maxu; i++) { uint32_t entry = read_u32(entries + 4u * i); if ((entry & 0x80000000u) != 0 || (entry & 0x7FFFFFFFu) == 0) continue; if (scan_one(i, entry, entries, &snap[i]) == 0) (*found)++; } } /** @brief Tag an untagged pipe or file ISO8859-1 before anything writes. * * The runtime prints its own diagnostics -- and the ps child prints its * storage report -- as EBCDIC text, which reaches an ASCII terminal or log * as a wall of undecodable bytes unless the descriptor says it is text. * A terminal carries its own tag and is left alone. * @param fd descriptor to tag when it has no text tag yet */ static void tag_untagged(int fd) { struct stat st; if (fstat(fd, &st) != 0 || S_ISCHR(st.st_mode)) return; if (st.st_tag.ft_txtflag && st.st_tag.ft_ccsid != 0) return; (void)tag_fd(fd, 819); } /** @brief Start ps, which supplies the ASID the process table lacks. */ static FILE *ps_open(void) { /* NOLINTNEXTLINE(cert-env33-c): ps is the only source of pid-to-ASID. */ return popen("/bin/ps -A -o pid,xasid", "r"); } /** @brief Read a whole descriptor into a growing buffer. * @param fd descriptor * @param out receives the malloc'd, nul-terminated buffer * @param outlen receives the byte count * @return 0 on success, -1 on error or out of memory */ static int read_all(int fd, char **out, size_t *outlen) { size_t cap = 16384; size_t len = 0; char *buf = malloc(cap + 1); if (buf == nullptr) return -1; for (;;) { ssize_t n; if (len == cap) { char *grown; if (cap >= (8u << 20)) { free(buf); errno = EFBIG; return -1; } grown = realloc(buf, cap * 2 + 1); if (grown == nullptr) { free(buf); return -1; } buf = grown; cap *= 2; } n = read(fd, buf + len, cap - len); if (n < 0) { if (errno == EINTR) continue; free(buf); return -1; } if (n == 0) break; len += (size_t)n; } buf[len] = '\0'; *out = buf; *outlen = len; return 0; } /** * @brief Convert a buffer of untagged ps output to ASCII, in place. * * ps writes ASCII when its pipe is tagged ASCII and EBCDIC when it is not; * the content decides, not the environment. A line ends at LF, NL or the * EBCDIC 0x25/0x15 code points, which __e2a_l() turns into '\n'. */ static void text_to_ascii(char *buf, size_t len) { size_t i; for (i = 0; i < len; i++) { if ((unsigned char)buf[i] >= 0x80) { __e2a_l(buf, len); return; } } } /** * @brief Tell read() what the pipe carries, using its tag. * @return 1 = valid ASCII, 2 = the runtime converts (read returns ASCII), * 0 = untagged, so the bytes must be sniffed after the read */ static int read_setup(int fd) { struct stat st; if (fstat(fd, &st) == 0 && st.st_tag.ft_txtflag) { unsigned ccsid = st.st_tag.ft_ccsid; if (ccsid == 37 || ccsid == 1047) { if (set_cvt(fd, SETCVTON, 819, (int)ccsid) == 0) return 2; } else if (ccsid != 0) { (void)set_cvt(fd, SETCVTOFF, 0, 0); return 1; } } (void)set_cvt(fd, SETCVTOFF, 0, 0); return 0; } /** @brief Append one pid-to-ASID pair, growing the map when it is full. */ static int add_pid_asid(pid_asid **map, size_t *n, size_t *cap, pid_t pid, unsigned asid) { if (*n == *cap) { size_t ncap = *cap ? *cap * 2 : 64; pid_asid *grown = realloc(*map, ncap * sizeof(**map)); if (grown == nullptr) return -1; *map = grown; *cap = ncap; } (*map)[*n].pid = pid; (*map)[*n].asid = asid; (*n)++; return 0; } /** * @brief Whether a ps line is the header rather than a process. * * ps prints one header line ("PID ASID" on current releases); anything else * that does not parse is an error, not a line to drop. */ static bool is_header(const char *s) { while (isspace((unsigned char)*s)) s++; return strncmp(s, "PID", 3) == 0 && (s[3] == '\0' || isspace((unsigned char)s[3])) && strstr(s, "ASID") != nullptr; } /** * @brief Read /bin/ps -A -o pid,xasid into a sorted pid-to-ASID map. * @param map receives the malloc'd array * @param count receives the number of pairs * @return 0 on success, -1 when ps cannot run or its output does not parse */ static int ps_scan(pid_asid **map, size_t *count) { FILE *fp; char *buf = nullptr; size_t len = 0; size_t n = 0; size_t cap = 0; size_t i; size_t start = 0; int status; int mode; *map = nullptr; *count = 0; fp = ps_open(); if (fp == nullptr) { error_msg("whoson: cannot run /bin/ps: %s\n", strerror(errno)); return -1; } mode = read_setup(fileno(fp)); if (read_all(fileno(fp), &buf, &len) != 0) { error_msg("whoson: cannot read ps output: %s\n", strerror(errno)); pclose(fp); return -1; } status = pclose(fp); if (status == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { error_msg("whoson: ps failed\n"); free(buf); return -1; } if (mode == 0) text_to_ascii(buf, len); /* The buffer is ASCII by now: mode 1 and 2 were read as ASCII, and mode 0 * was converted above, which also turns EBCDIC NL into '\n'. */ for (i = 0; i <= len; i++) { char c = i < len ? buf[i] : '\n'; if (c != '\n' && c != '\r') continue; buf[i < len ? i : len] = '\0'; if (buf[start] != '\0') { int pid; unsigned asid; if (sscanf(&buf[start], "%d %x", &pid, &asid) == 2) { if (add_pid_asid(map, &n, &cap, (pid_t)pid, asid) != 0) { error_msg("whoson: out of memory\n"); free(buf); return -1; } } else if (!is_header(&buf[start])) { error_msg("whoson: cannot parse ps line: %s\n", &buf[start]); free(*map); *map = nullptr; free(buf); return -1; } } start = i + 1; } free(buf); if (n == 0) { error_msg("whoson: ps returned no processes\n"); free(*map); *map = nullptr; return -1; } *count = n; return 0; } /** @brief qsort() order for pid_asid: by pid, then ASID. */ static int cmp_pid_asid(const void *a, const void *b) { const pid_asid *x = a; const pid_asid *y = b; if (x->pid != y->pid) return x->pid < y->pid ? -1 : 1; return 0; } /** @brief Binary-search a sorted pid_asid map for pid; 0 copies use ASID 0. */ static const pid_asid *find_asid(const pid_asid *map, size_t n, pid_t pid) { pid_asid key; key.pid = pid; key.asid = 0; return bsearch(&key, map, n, sizeof(*map), cmp_pid_asid); } /** @brief qsort() order for proc: by pid. */ static int cmp_proc(const void *a, const void *b) { const proc *x = a; const proc *y = b; if (x->pid != y->pid) return x->pid < y->pid ? -1 : 1; return 0; } /** @brief Binary-search a sorted process list for pid. */ static const proc *find_proc(const proc *procs, size_t n, pid_t pid) { proc key = {.pid = pid}; return bsearch(&key, procs, n, sizeof(*procs), cmp_proc); } /** @brief Whether a process path is sshd or sshd-session. */ static bool is_sshd(const char *path) { const char *base = strrchr(path, '/'); base = base != nullptr ? base + 1 : path; return strcmp(base, "sshd") == 0 || strcmp(base, "sshd-session") == 0; } /** * @brief Whether a process is the sftp subsystem. * * It also runs as a child of sshd-session, but it is a file transfer, not a * login. */ static bool is_sftp_server(const char *name) { return strcmp(name, "sftp-server") == 0 || strcmp(name, "internal-sftp") == 0; } /** @brief Append one process, keeping only the basename of its path. */ static int append_proc(proc **procs, size_t *n, size_t *cap, const W_PSPROC *ps, const char *path) { const char *base; size_t len; if (*n == *cap) { size_t ncap = *cap ? *cap * 2 : 64; proc *grown = realloc(*procs, ncap * sizeof(**procs)); if (grown == nullptr) return -1; *procs = grown; *cap = ncap; } base = strrchr(path, '/'); base = base != nullptr ? base + 1 : path; len = strlen(base); if (len >= sizeof((*procs)[*n].name)) len = sizeof((*procs)[*n].name) - 1; memcpy((*procs)[*n].name, base, len); (*procs)[*n].name[len] = '\0'; (*procs)[*n].pid = ps->ps_pid; (*procs)[*n].ppid = ps->ps_ppid; (*procs)[*n].euid = ps->ps_euid; (*n)++; return 0; } /** * @brief Read the process table with w_getpsent into a sorted list. * @param procs receives the malloc'd array * @param count receives the number of processes * @return 0 on success, -1 on a table that cannot be read */ static int proc_scan(proc **procs, size_t *count) { W_PSPROC ps; char *path; char *cmd; char *tty; size_t n = 0; size_t cap = 0; int token = 0; *procs = nullptr; *count = 0; path = malloc(ps_path_buf); cmd = malloc(cmd_buf); tty = malloc(tty_buf); if (path == nullptr || cmd == nullptr || tty == nullptr) { error_msg("whoson: out of memory\n"); free(path); free(cmd); free(tty); return -1; } for (;;) { int next; memset(&ps, 0, sizeof(ps)); ps.ps_pathlen = (int)ps_path_buf; ps.ps_pathptr = path; ps.ps_cmdlen = (int)cmd_buf; ps.ps_cmdptr = cmd; ps.ps_conttylen = (int)tty_buf; ps.ps_conttyptr = tty; next = w_getpsent(token, &ps, sizeof(ps)); if (next < 0) { error_msg("whoson: cannot read the process table: %s\n", strerror(errno)); free(*procs); *procs = nullptr; free(path); free(cmd); free(tty); return -1; } if (next == 0) break; token = next; path[ps_path_buf - 1] = '\0'; if (append_proc(procs, &n, &cap, &ps, path) != 0) { error_msg("whoson: out of memory\n"); free(*procs); *procs = nullptr; free(path); free(cmd); free(tty); return -1; } } free(path); free(cmd); free(tty); if (n == 0) { error_msg("whoson: the process table is empty\n"); free(*procs); *procs = nullptr; return -1; } qsort(*procs, n, sizeof(**procs), cmp_proc); *count = n; return 0; } /** * @brief Whether a logon procedure is one z/OSMF uses. * * A logon procedure name from WHOSON_ZOSMF_PROCS; z/OSMF passes the * procedure it was started with, so the name is the only clue common storage * has. An unset or empty variable means IZUFPROC, the default in the z/OSMF * configuration. */ static bool logon_is_zosmf(const char *logon) { const char *list = getenv("WHOSON_ZOSMF_PROCS"); const char *p; if (logon == nullptr || logon[0] == '\0') return false; p = list != nullptr && list[0] != '\0' ? list : "IZUFPROC"; for (;;) { const char *comma = strchr(p, ','); const char *end = comma != nullptr ? comma : p + strlen(p); const char *s = p; size_t len; while (s < end && (*s == ' ' || *s == '\t')) s++; while (end > s && (end[-1] == ' ' || end[-1] == '\t')) end--; len = (size_t)(end - s); if (len != 0 && len == strlen(logon) && strncmp(s, logon, len) == 0) return true; if (comma == nullptr) break; p = comma + 1; } return false; } /** @brief Map a uid to a userid, caching getpwuid() for the rows. * @param uid effective uid of an SSH process * @param out output buffer * @param outlen size of out */ static void user_name(uid_t uid, char *out, size_t outlen) { static struct { uid_t uid; /**< cached uid */ char name[name_len]; /**< its userid */ } cache[16]; static size_t used; size_t i; struct passwd *pw; for (i = 0; i < used; i++) { if (cache[i].uid == uid) { snprintf(out, outlen, "%s", cache[i].name); return; } } pw = getpwuid(uid); if (pw != nullptr) snprintf(cache[used].name, sizeof(cache[used].name), "%s", pw->pw_name); else snprintf(cache[used].name, sizeof(cache[used].name), "%u", (unsigned)uid); cache[used].uid = uid; snprintf(out, outlen, "%s", cache[used].name); if (used + 1 < sizeof(cache) / sizeof(cache[0])) used++; } /** @brief qsort() order for the table: userid, then ASID, then pid. */ static int cmp_rows(const void *a, const void *b) { const row *x = a; const row *y = b; int cmp = strcmp(x->user, y->user); if (cmp != 0) return cmp; if (x->asid != y->asid) return x->asid < y->asid ? -1 : 1; if (x->pid != y->pid) return x->pid < y->pid ? -1 : 1; return 0; } /** * @brief Format a CPU time as a compact duration. * * TOD units are 2^-12 microseconds. The largest unit that keeps it short * wins: hundredths of a second under a minute, then whole minutes, hours and * days. A long session could otherwise read 1947:50:11. * @param us microseconds of CPU * @param out output buffer * @param outlen size of out */ static void fmt_cpu(uint64_t us, char *out, size_t outlen) { uint64_t hundredths = (us + 5000u) / 10000u; uint64_t secs = hundredths / 100u; if (secs < 60u) snprintf(out, outlen, "%" PRIu64 ".%02" PRIu64 "s", secs, hundredths % 100u); else if (secs < 3600u) snprintf(out, outlen, "%" PRIu64 "m%02" PRIu64 "s", secs / 60u, secs % 60u); else if (secs < 86400u) snprintf(out, outlen, "%" PRIu64 "h%02" PRIu64 "m", secs / 3600u, secs % 3600u / 60u); else snprintf(out, outlen, "%" PRIu64 "d%02" PRIu64 "h", secs / 86400u, secs % 86400u / 3600u); } /** @brief The table as it is built, so one write carries every row. */ typedef struct outbuf { char buf[out_len]; /**< formatted rows, not yet written */ size_t len; /**< bytes in buf */ } outbuf; static void out_add(outbuf *o, const char *fmt, ...) PRINTFLIKE(2, 3); /** @brief emit() whatever the table has accumulated and reset it. */ static void out_flush(outbuf *o) { if (o->len != 0) emit(STDOUT_FILENO, o->buf, o->len); o->len = 0; } /** @brief Append one formatted line to the table, flushing it when full. */ static void out_add(outbuf *o, const char *fmt, ...) { char line[msg_len]; va_list ap; int n; va_start(ap, fmt); n = vsnprintf(line, sizeof(line), fmt, ap); va_end(ap); if (n < 0) return; if ((size_t)n >= sizeof(line)) n = (int)sizeof(line) - 1; if (o->len + (size_t)n > sizeof(o->buf)) out_flush(o); memcpy(o->buf + o->len, line, (size_t)n); o->len += (size_t)n; } /** @brief Format the header and the rows, one row at a time, and write them. */ static void print_rows(row *rows, size_t n) { outbuf out; char cpu[cpu_len]; char asid[asid_len]; char pid[pid_len]; size_t i; out.len = 0; out_add(&out, "%-8.8s %-6.6s %-4.4s %-8.8s %-10.10s %-8.8s %s\n", "USER", "TYPE", "ASID", "JOBNAME", "LOGONPROC", "PID", "CPU"); for (i = 0; i < n; i++) { fmt_cpu(rows[i].us, cpu, sizeof(cpu)); if (rows[i].asid != 0) snprintf(asid, sizeof(asid), "%04X", rows[i].asid); else snprintf(asid, sizeof(asid), "%s", "-"); if (rows[i].pid > 0) snprintf(pid, sizeof(pid), "%" PRId32, rows[i].pid); else snprintf(pid, sizeof(pid), "%s", "-"); out_add(&out, "%-8.8s %-6.6s %-4.4s %-8.8s %-10.10s %-8.8s %s\n", rows[i].user, rows[i].type, asid, rows[i].job, rows[i].logon, pid, cpu); } out_flush(&out); } /** * @brief Build the table: one row per TSO/E space, then one per SSH login. * @param rows output array * @param maxrows capacity of rows * @param snap per-ASID state from the ASCB walk * @param maxu number of entries in snap * @param procs the process table, sorted by pid * @param nprocs number of processes * @param map pid-to-ASID map, sorted by pid * @param nmap number of pairs * @return the number of rows written */ static int collect(row *rows, size_t maxrows, const space *snap, unsigned maxu, const proc *procs, size_t nprocs, const pid_asid *map, size_t nmap) { size_t n = 0; unsigned i; size_t k; for (i = 0; i < maxu && n < maxrows; i++) { if (!snap[i].tso) continue; rows[n].asid = i + 1; rows[n].us = snap[i].us; rows[n].pid = 0; rows[n].type = logon_is_zosmf(snap[i].logon) ? "z/OSMF" : "TSO/E"; snprintf(rows[n].user, sizeof(rows[n].user), "%s", snap[i].user[0] != '\0' ? snap[i].user : snap[i].job); snprintf(rows[n].job, sizeof(rows[n].job), "%s", snap[i].job); snprintf(rows[n].logon, sizeof(rows[n].logon), "%s", snap[i].logon[0] != '\0' ? snap[i].logon : "-"); n++; } for (k = 0; k < nprocs && n < maxrows; k++) { const proc *parent; const pid_asid *pa; unsigned asid = 0; uint64_t us = 0; const char *job = "-"; parent = find_proc(procs, nprocs, procs[k].ppid); if (parent == nullptr || !is_sshd(parent->name) || is_sshd(procs[k].name) || is_sftp_server(procs[k].name)) continue; pa = find_asid(map, nmap, procs[k].pid); if (pa != nullptr && pa->asid >= 1 && pa->asid <= maxu) { asid = pa->asid; us = snap[asid - 1].us; if (snap[asid - 1].job[0] != '\0') job = snap[asid - 1].job; } rows[n].asid = asid; rows[n].us = us; rows[n].pid = procs[k].pid; rows[n].type = "SSH"; snprintf(rows[n].job, sizeof(rows[n].job), "%s", job); snprintf(rows[n].logon, sizeof(rows[n].logon), "%s", "-"); user_name(procs[k].euid, rows[n].user, sizeof(rows[n].user)); n++; } return (int)n; } /** @brief Walk common storage and the process table, and print the sessions. * @return 0 on success, 1 on a read, memory or output failure */ int main(int argc, char **argv) { space *snap; row *rows; proc *procs; pid_asid *map; size_t nmap; size_t nprocs; unsigned maxu; unsigned found; uint32_t entries; int nrows; int arg; tag_untagged(STDOUT_FILENO); tag_untagged(STDERR_FILENO); save_cvt(STDOUT_FILENO); save_cvt(STDERR_FILENO); (void)atexit(restore_cvt); for (arg = 1; arg < argc; arg++) { if (strcmp(argv[arg], "-h") == 0 || strcmp(argv[arg], "--help") == 0) { emit_str(STDOUT_FILENO, usage_text); return output_failed ? 1 : 0; } else if (strcmp(argv[arg], "-V") == 0 || strcmp(argv[arg], "--version") == 0) { emit_str(STDOUT_FILENO, "whoson " WHOSON_VERSION "\n"); return output_failed ? 1 : 0; } else { usage_error("whoson: unknown argument: %s", argv[arg]); return 1; } } guard(); if (read_asvt(&maxu, &entries) != 0) { unguard(); error_msg("whoson: cannot read the ASVT\n"); return 1; } snap = calloc((size_t)maxu, sizeof(*snap)); if (snap == nullptr) { unguard(); error_msg("whoson: out of memory for %u address spaces\n", maxu); return 1; } ascb_scan(entries, maxu, snap, &found); unguard(); if (found == 0) { free(snap); error_msg("whoson: no address spaces found\n"); return 1; } if (ps_scan(&map, &nmap) != 0) { free(snap); return 1; } if (proc_scan(&procs, &nprocs) != 0) { free(map); free(snap); return 1; } qsort(map, nmap, sizeof(*map), cmp_pid_asid); /* At most one TSO row per address space and one SSH row per process, so * the table can hold both lists; maxu alone would drop SSH sessions on a * system that shares address spaces (_BPX_SHAREAS). */ rows = calloc((size_t)maxu + nprocs, sizeof(*rows)); if (rows == nullptr) { error_msg("whoson: out of memory for the session table\n"); free(procs); free(map); free(snap); return 1; } nrows = collect(rows, (size_t)maxu + nprocs, snap, maxu, procs, nprocs, map, nmap); qsort(rows, (size_t)nrows, sizeof(*rows), cmp_rows); print_rows(rows, (size_t)nrows); free(rows); free(procs); free(map); free(snap); return output_failed ? 1 : 0; }