summaryrefslogtreecommitdiffhomepage
path: root/whoson.c
diff options
context:
space:
mode:
authorSean Kurtz <seankurtz75@gmail.com>2026-11-28 18:57:06 -0600
committerSean Kurtz <seankurtz75@gmail.com>2026-11-28 18:57:06 -0600
commit7ecdc5efc90cd0f983764997fb17da6928b908fa (patch)
tree582a776ea6445a69aa2a9524244e567a86a60c6a /whoson.c
parent0922e0b31b3a476c250d8677fb76fdf2d542723e (diff)
downloadwhoson-fix/c-programming-standards.tar.gz
Follow C-PROGRAMMING-STANDARDS.md throughoutfix/c-programming-standards
The standards document that merged as PR #25 is now the reference for the language level, the diagnostics, the names and the comments. What the audit found and this commit settles: - C23 in full: nullptr instead of NULL, static_assert for every offset the walk reads, constexpr for the buffer and column widths, and the one compiler attribute wrapped in PRINTFLIKE so call sites stay C23. - -Wstrict-prototypes and -Wmissing-prototypes, which the document requires and the Makefile did not carry. - Lower-case constexpr names, and static so each stays internal. - A Doxygen block on every function, type, global and macro, and /**< */ on every member, as section 3.3 asks. - -D_OPEN_SYS_FILE_EXT=1, the value the document names, in the Makefile and in .clangd. - make format and make tidy, the two target names the document gives. - The eye-catcher hex, the CHTRKID value and the EBCDIC reasoning now carry the why in a comment rather than standing bare. Where the document and this program disagree, the program keeps its reason and CONTRIBUTING.md records the agreement where it is not obvious. Also fixes the wall of undecodable bytes after `make check`: the runtime's own storage report, and the one the ps child inherits, are EBCDIC text written to an ASCII log. An untagged stdout or stderr is now tagged ISO8859-1 before anything writes to it, so both reports arrive as text.
Diffstat (limited to 'whoson.c')
-rw-r--r--whoson.c544
1 files changed, 390 insertions, 154 deletions
diff --git a/whoson.c b/whoson.c
index 62a213c..9aead3c 100644
--- a/whoson.c
+++ b/whoson.c
@@ -1,13 +1,14 @@
-/*
+/**
+ * @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
*
- * whoson - who is logged on to this z/OS system, and how (TSO/E, z/OSMF, SSH).
- *
- * 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.
+ * @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.
@@ -59,74 +60,109 @@
#include <sys/wait.h>
#include <unistd.h>
-#define MSG_LEN 512
-#define NAME_LEN 16
-#define JOB_LEN 9
-#define ASID_LEN 8
-#define PID_LEN 12
-#define CPU_LEN 16
-#define PATH_LEN 64
-#define OUT_LEN 8192
-#define CMD_BUF 2048
-#define TTY_BUF 2048
+/* 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
-#define PS_PATH_BUF 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
-#define PS_PATH_BUF 1027
+/** @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). */
#define CVT_ASVT_OFF 0x22Cu
+/** @brief ASVT field: the eye-catcher "ASVT". */
#define ASVT_ACRONYM_OFF 0x200u
+/** @brief ASVT field: highest ASID in use (ASVTMXU). */
#define ASVT_MAXU_OFF 0x204u
+/** @brief ASVT field: first entry of ASVTENTY, four bytes each. */
#define ASVT_ENTY_OFF 0x210u
-#define ASVT_ACRONYM 0xC1E2E5E3u /* "ASVT" in EBCDIC */
-#define ASCB_ACRONYM 0xC1E2C3C2u /* "ASCB" in EBCDIC */
-#define CSCB_ACRONYM 0xC3E2C3C2u /* "CSCB" in EBCDIC */
-#define ASSB_ACRONYM 0xC1E2E2C2u /* "ASSB" in EBCDIC */
+
+/* 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. */
+#define ASVT_ACRONYM 0xC1E2E5E3u
+/** @brief "ASCB" as it appears in the ASCB. */
+#define ASCB_ACRONYM 0xC1E2C3C2u
+/** @brief "CSCB" as it appears in the CSCB. */
+#define CSCB_ACRONYM 0xC3E2C3C2u
+/** @brief "ASSB" as it appears in the ASSB. */
+#define 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];
- uint16_t ascbasid; /* X'24' */
- unsigned char ascbresv1[0x38 - 0x26];
- uint32_t ascbcscb; /* X'38' */
- uint32_t ascbtsb; /* X'3C' */
- uint64_t ascbejst; /* X'40' TCB CPU in TOD units */
- unsigned char ascbresv2[0xAC - 0x48];
- uint32_t ascbjbni; /* X'AC' */
- uint32_t ascbjbns; /* X'B0' */
- unsigned char ascbresv3[0xC8 - 0xB4];
- uint64_t ascbsrbt; /* X'C8' SRB CPU in TOD units */
- unsigned char ascbresv4[0x150 - 0xD0];
- uint32_t ascbassb; /* X'150' */
+ 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' */
- unsigned char chvcd; /* X'04' */
- unsigned char chsze; /* X'05' */
- unsigned char chresv0[0x08 - 0x06];
- char chkey[8]; /* X'08' userid */
- char chcls[8]; /* X'10' logon procedure */
- uint32_t chunit; /* X'18' */
- unsigned char chtrkid; /* X'1C' X'01' is a TSO/E session */
- unsigned char chresv1; /* X'1D' */
- uint16_t chasid; /* X'1E' address space id */
- unsigned char chresv2[0xD8 - 0x20];
- char chcscbid[4]; /* X'D8' eye-catcher */
+ 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];
- uint64_t assbasst; /* X'160' preemptable SRB CPU in TOD units */
+ 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);
@@ -150,38 +186,44 @@ static_assert(offsetof(cscb, chasid) == 0x1E, "CHASID");
static_assert(offsetof(cscb, chcscbid) == 0xD8, "CHCSCBID");
static_assert(offsetof(assb, assbasst) == 0x160, "ASSBASST");
-/* One address space, as read from its ASCB, indexed by ASID - 1. */
+/** @brief What the ASCB walk keeps per address space, indexed by ASID - 1. */
typedef struct space {
- bool tso;
- uint64_t us; /* microseconds of CPU */
- char job[JOB_LEN];
- char user[NAME_LEN];
- char logon[JOB_LEN];
+ 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;
-/* One output row. TSO rows are built from a space; SSH rows from a process. */
+/** @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;
- uint64_t us;
- pid_t pid;
- const char *type;
- char job[JOB_LEN];
- char logon[JOB_LEN];
- char user[NAME_LEN];
+ 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;
- pid_t ppid;
- uid_t euid;
- char name[PATH_LEN];
+ 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;
- unsigned 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"
@@ -198,18 +240,27 @@ static const char usage_text[] =
"(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
-/* A control-block read that faults is caught here and turned into a skipped
- * row. */
+/** @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;
-/* Only fcntl(), which is safe in a signal handler. */
+/** @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);
@@ -217,18 +268,21 @@ static void on_fault(int sig) {
_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, NULL);
+ sigaction(SIGSEGV, &sa, nullptr);
#ifdef SIGBUS
- sigaction(SIGBUS, &sa, NULL);
+ 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
@@ -236,25 +290,39 @@ static void unguard(void) {
#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;
}
-/* Set by a failed write, so main can exit nonzero on truncated output. */
+/** @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);
@@ -271,8 +339,12 @@ static int write_all(int fd, const char *buf, size_t len) {
return 0;
}
-/* Tag fd with ccsid as text. zopen's setccsid(): an untagged file created by
- * the shell becomes ISO8859-1 rather than an anonymous EBCDIC file. */
+/**
+ * @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;
@@ -283,6 +355,13 @@ static int tag_fd(int fd, unsigned ccsid) {
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;
@@ -292,17 +371,25 @@ static int set_cvt(int fd, int cmd, int pccsid, int fccsid) {
return fcntl(fd, F_CONTROL_CVT, &c);
}
-/* The conversion setting belongs to the open file description, which the
- * calling shell keeps after whoson exits. Save it and put it back, or the
- * shell's own output would inherit ours. */
+/** @brief A descriptor's starting conversion setting, kept for restore_cvt().
+ */
typedef struct cvt_saved {
- int fd;
- struct f_cnvrt v;
+ 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;
@@ -310,6 +397,7 @@ static void restore_cvt(void) {
(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;
@@ -324,16 +412,25 @@ static void save_cvt(int fd) {
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);
}
-/* 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. */
+/**
+ * @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;
@@ -368,8 +465,9 @@ static void emit(int fd, char *buf, size_t 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];
+ char buf[msg_len];
size_t len = strlen(text);
if (len >= sizeof(buf))
@@ -378,8 +476,10 @@ static void emit_str(int fd, const char *text) {
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];
+ char text[msg_len];
vsnprintf(text, sizeof(text), fmt, ap);
emit_str(STDERR_FILENO, text);
@@ -389,6 +489,7 @@ static void vmessage(bool usage, const char *fmt, va_list ap) {
}
}
+/** @brief Report an error on stderr, in the destination's character set. */
static void error_msg(const char *fmt, ...) {
va_list ap;
@@ -397,6 +498,7 @@ static void error_msg(const char *fmt, ...) {
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;
@@ -405,8 +507,16 @@ static void usage_error(const char *fmt, ...) {
va_end(ap);
}
-/* Copy the 8-byte EBCDIC name a control block points at. These pointers
- * address common storage, so no cross-memory services are needed. */
+/**
+ * @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;
@@ -430,7 +540,18 @@ static void read_name(uint32_t ptr, char *dst, size_t dstlen) {
dst[n] = '\0';
}
-/* Read one ASCB. Returns 0 and fills *out on success; -1 skips it. */
+/**
+ * @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};
@@ -439,8 +560,8 @@ static int scan_one(unsigned idx, uint32_t entry, uint32_t entries,
uint32_t cscb_addr;
uint64_t tod;
bool tso;
- char key[NAME_LEN] = {0};
- char cls[JOB_LEN] = {0};
+ char key[name_len] = {0};
+ char cls[job_len] = {0};
fault_armed = 1;
if (sigsetjmp(fault_env, 1) != 0) {
@@ -474,7 +595,8 @@ static int scan_one(unsigned idx, uint32_t entry, uint32_t entries,
sizeof(key));
read_name(cscb_addr + (uint32_t)offsetof(cscb, chcls), cls,
sizeof(cls));
- if (read_u8(cscb_addr + (uint32_t)offsetof(cscb, chtrkid)) == 0x01)
+ 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,
@@ -505,6 +627,12 @@ fail:
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;
@@ -533,6 +661,13 @@ fail:
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;
@@ -548,16 +683,42 @@ static void ascb_scan(uint32_t entries, unsigned maxu, space *snap,
}
}
+/** @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 == NULL)
+ if (buf == nullptr)
return -1;
for (;;) {
ssize_t n;
@@ -571,7 +732,7 @@ static int read_all(int fd, char **out, size_t *outlen) {
return -1;
}
grown = realloc(buf, cap * 2 + 1);
- if (grown == NULL) {
+ if (grown == nullptr) {
free(buf);
return -1;
}
@@ -595,9 +756,13 @@ static int read_all(int fd, char **out, size_t *outlen) {
return 0;
}
-/* ps on a pipe is ASCII when the 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. */
+/**
+ * @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;
@@ -609,9 +774,11 @@ static void text_to_ascii(char *buf, size_t len) {
}
}
-/* Tell read() what the pipe carries, using its tag: 1 = valid ASCII, 2 =
- * the runtime was told to convert (read returns ASCII), 0 = untagged, so the
- * bytes must be sniffed after the read. */
+/**
+ * @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;
@@ -630,13 +797,14 @@ static int read_setup(int fd) {
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 == NULL)
+ if (grown == nullptr)
return -1;
*map = grown;
*cap = ncap;
@@ -647,19 +815,29 @@ static int add_pid_asid(pid_asid **map, size_t *n, size_t *cap, pid_t pid,
return 0;
}
-/* ps prints one header line ("PID ASID" on current releases); anything else
- * that does not parse is an error, not a line to drop. */
+/**
+ * @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") != NULL;
+ 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 = NULL;
+ char *buf = nullptr;
size_t len = 0;
size_t n = 0;
size_t cap = 0;
@@ -668,10 +846,10 @@ static int ps_scan(pid_asid **map, size_t *count) {
int status;
int mode;
- *map = NULL;
+ *map = nullptr;
*count = 0;
fp = ps_open();
- if (fp == NULL) {
+ if (fp == nullptr) {
error_msg("whoson: cannot run /bin/ps: %s\n", strerror(errno));
return -1;
}
@@ -710,7 +888,7 @@ static int ps_scan(pid_asid **map, size_t *count) {
} else if (!is_header(&buf[start])) {
error_msg("whoson: cannot parse ps line: %s\n", &buf[start]);
free(*map);
- *map = NULL;
+ *map = nullptr;
free(buf);
return -1;
}
@@ -721,13 +899,14 @@ static int ps_scan(pid_asid **map, size_t *count) {
if (n == 0) {
error_msg("whoson: ps returned no processes\n");
free(*map);
- *map = NULL;
+ *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;
@@ -737,6 +916,7 @@ static int cmp_pid_asid(const void *a, const void *b) {
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;
@@ -745,6 +925,7 @@ static const pid_asid *find_asid(const pid_asid *map, size_t n, pid_t pid) {
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;
@@ -754,26 +935,33 @@ static int cmp_proc(const void *a, const void *b) {
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 != NULL ? base + 1 : path;
+ base = base != nullptr ? base + 1 : path;
return strcmp(base, "sshd") == 0 || strcmp(base, "sshd-session") == 0;
}
-/* The sftp subsystem also runs as a child of sshd-session, but it is a file
- * transfer, not a login. */
+/**
+ * @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;
@@ -783,13 +971,13 @@ static int append_proc(proc **procs, size_t *n, size_t *cap, const W_PSPROC *ps,
size_t ncap = *cap ? *cap * 2 : 64;
proc *grown = realloc(*procs, ncap * sizeof(**procs));
- if (grown == NULL)
+ if (grown == nullptr)
return -1;
*procs = grown;
*cap = ncap;
}
base = strrchr(path, '/');
- base = base != NULL ? base + 1 : path;
+ base = base != nullptr ? base + 1 : path;
len = strlen(base);
if (len >= sizeof((*procs)[*n].name))
len = sizeof((*procs)[*n].name) - 1;
@@ -802,6 +990,12 @@ static int append_proc(proc **procs, size_t *n, size_t *cap, const W_PSPROC *ps,
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;
@@ -811,12 +1005,12 @@ static int proc_scan(proc **procs, size_t *count) {
size_t cap = 0;
int token = 0;
- *procs = NULL;
+ *procs = nullptr;
*count = 0;
- path = malloc(PS_PATH_BUF);
- cmd = malloc(CMD_BUF);
- tty = malloc(TTY_BUF);
- if (path == NULL || cmd == NULL || tty == NULL) {
+ 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);
@@ -827,18 +1021,18 @@ static int proc_scan(proc **procs, size_t *count) {
int next;
memset(&ps, 0, sizeof(ps));
- ps.ps_pathlen = PS_PATH_BUF;
+ ps.ps_pathlen = (int)ps_path_buf;
ps.ps_pathptr = path;
- ps.ps_cmdlen = CMD_BUF;
+ ps.ps_cmdlen = (int)cmd_buf;
ps.ps_cmdptr = cmd;
- ps.ps_conttylen = TTY_BUF;
+ 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 = NULL;
+ *procs = nullptr;
free(path);
free(cmd);
free(tty);
@@ -847,11 +1041,11 @@ static int proc_scan(proc **procs, size_t *count) {
if (next == 0)
break;
token = next;
- path[PS_PATH_BUF - 1] = '\0';
+ 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 = NULL;
+ *procs = nullptr;
free(path);
free(cmd);
free(tty);
@@ -864,7 +1058,7 @@ static int proc_scan(proc **procs, size_t *count) {
if (n == 0) {
error_msg("whoson: the process table is empty\n");
free(*procs);
- *procs = NULL;
+ *procs = nullptr;
return -1;
}
qsort(*procs, n, sizeof(**procs), cmp_proc);
@@ -872,18 +1066,24 @@ static int proc_scan(proc **procs, size_t *count) {
return 0;
}
-/* 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. */
+/**
+ * @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 == NULL || logon[0] == '\0')
+ if (logon == nullptr || logon[0] == '\0')
return false;
- p = list != NULL && list[0] != '\0' ? list : "IZUFPROC";
+ p = list != nullptr && list[0] != '\0' ? list : "IZUFPROC";
for (;;) {
const char *comma = strchr(p, ',');
- const char *end = comma != NULL ? comma : p + strlen(p);
+ const char *end = comma != nullptr ? comma : p + strlen(p);
const char *s = p;
size_t len;
@@ -894,17 +1094,22 @@ static bool logon_is_zosmf(const char *logon) {
len = (size_t)(end - s);
if (len != 0 && len == strlen(logon) && strncmp(s, logon, len) == 0)
return true;
- if (comma == NULL)
+ 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;
- char name[NAME_LEN];
+ uid_t uid; /**< cached uid */
+ char name[name_len]; /**< its userid */
} cache[16];
static size_t used;
size_t i;
@@ -917,7 +1122,7 @@ static void user_name(uid_t uid, char *out, size_t outlen) {
}
}
pw = getpwuid(uid);
- if (pw != NULL)
+ 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",
@@ -928,6 +1133,7 @@ static void user_name(uid_t uid, char *out, size_t outlen) {
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;
@@ -942,9 +1148,16 @@ static int cmp_rows(const void *a, const void *b) {
return 0;
}
-/* TOD units are 2^-12 microseconds. Print a duration in the largest unit
- * that keeps it short: hundredths of a second under a minute, then whole
- * minutes, hours and days. A long session could otherwise read 1947:50:11. */
+/**
+ * @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;
@@ -963,19 +1176,24 @@ static void fmt_cpu(uint64_t us, char *out, size_t outlen) {
secs % 86400u / 3600u);
}
+/** @brief The table as it is built, so one write carries every row. */
typedef struct outbuf {
- char buf[OUT_LEN];
- size_t len;
+ 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];
+ char line[msg_len];
va_list ap;
int n;
@@ -992,11 +1210,12 @@ static void out_add(outbuf *o, const char *fmt, ...) {
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];
+ char cpu[cpu_len];
+ char asid[asid_len];
+ char pid[pid_len];
size_t i;
out.len = 0;
@@ -1019,6 +1238,18 @@ static void print_rows(row *rows, size_t n) {
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) {
@@ -1048,11 +1279,11 @@ static int collect(row *rows, size_t maxrows, const space *snap, unsigned maxu,
const char *job = "-";
parent = find_proc(procs, nprocs, procs[k].ppid);
- if (parent == NULL || !is_sshd(parent->name) ||
+ 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 != NULL && pa->asid >= 1 && pa->asid <= maxu) {
+ if (pa != nullptr && pa->asid >= 1 && pa->asid <= maxu) {
asid = pa->asid;
us = snap[asid - 1].us;
if (snap[asid - 1].job[0] != '\0')
@@ -1070,6 +1301,9 @@ static int collect(row *rows, size_t maxrows, const space *snap, unsigned maxu,
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;
@@ -1083,6 +1317,8 @@ int main(int argc, char **argv) {
int nrows;
int arg;
+ tag_untagged(STDOUT_FILENO);
+ tag_untagged(STDERR_FILENO);
save_cvt(STDOUT_FILENO);
save_cvt(STDERR_FILENO);
(void)atexit(restore_cvt);
@@ -1106,7 +1342,7 @@ int main(int argc, char **argv) {
return 1;
}
snap = calloc((size_t)maxu, sizeof(*snap));
- if (snap == NULL) {
+ if (snap == nullptr) {
unguard();
error_msg("whoson: out of memory for %u address spaces\n", maxu);
return 1;
@@ -1132,7 +1368,7 @@ int main(int argc, char **argv) {
* 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 == NULL) {
+ if (rows == nullptr) {
error_msg("whoson: out of memory for the session table\n");
free(procs);
free(map);