diff options
| author | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-27 21:36:31 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-27 21:36:31 -0600 |
| commit | d84b4b8a3139e69cb6f27bb3223442c50b96290c (patch) | |
| tree | c56774d86c7e902f8547f766ddffbe968c5bdcec | |
| parent | 552c76c32f217b08268f1b2c75f832ed96e4d4d8 (diff) | |
| parent | 2d57ddfcc32e62a74305b7e6bf5fb4df8d64709e (diff) | |
| download | whoson-d84b4b8a3139e69cb6f27bb3223442c50b96290c.tar.gz | |
Merge pull request #18 from skurtz97/fix/review-552c76c
Fix the code review findings on 552c76c
| -rw-r--r-- | .clangd | 13 | ||||
| -rw-r--r-- | .github/ISSUE_TEMPLATE/bug_report.yml | 17 | ||||
| -rw-r--r-- | .github/PULL_REQUEST_TEMPLATE.md | 4 | ||||
| -rw-r--r-- | .github/workflows/ci.yml | 2 | ||||
| -rw-r--r-- | .github/workflows/release.yml | 2 | ||||
| -rw-r--r-- | CHANGELOG.md | 36 | ||||
| -rw-r--r-- | CONTRIBUTING.md | 22 | ||||
| -rw-r--r-- | Makefile | 15 | ||||
| -rw-r--r-- | README.md | 114 | ||||
| -rw-r--r-- | whoson.c | 1178 |
10 files changed, 1089 insertions, 314 deletions
@@ -3,7 +3,8 @@ # macros here. CompileFlags: Add: [-std=c17, -D_XOPEN_SOURCE=600, -D_POSIX_C_SOURCE=200809L, - -D_ALL_SOURCE, -D_EXT, -Wall, -Wextra, -Wshadow, -Wconversion] + -D_ALL_SOURCE, -D_EXT, -D_OPEN_SYS, -D_OPEN_SYS_FILE_EXT, + -Wall, -Wextra, -Wshadow, -Wconversion] # IBM Open XL only: the editor is not that compiler. Remove: [-fzos-le-char-mode=*, -m64] @@ -11,6 +12,16 @@ CompileFlags: Diagnostics: UnusedIncludes: Strict MissingIncludes: None + # The tree only builds on z/OS with IBM Open XL: Linux clangd has no + # <sys/ps.h>, no attrib_t/st_tag, no F_CONTROL_CVT and no __fchattr, so its + # cascade from the missing z/OS headers is noise. The build on z/OS is the + # authority; these are the diagnostics that cascade from those headers. + Suppress: + - pp_file_not_found + - undeclared_var_use + - unknown_typename + - incomplete_type + - implicit_function_declaration ClangTidy: # Use .clang-tidy; do not duplicate its checks here. FastCheckFilter: Strict diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 48c07e1..c32923f 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -5,15 +5,16 @@ body: - type: markdown attributes: value: | - whoson only reads two console displays, so the most useful thing you - can attach is what those displays said. On an operator console: - `D TS,A` for TSO/E sessions, `D OMVS,A=ALL` for processes. + whoson reads common storage and the process table, so the most useful + thing you can attach is the output of `ps -A -o pid,xasid` and, for a + TSO/E row, what `D TS,A` says about that address space. - type: textarea id: happened attributes: label: What happened - description: Paste the whoson output, and the display it disagrees with. + description: Paste the whoson output, and the `ps`/`D TS,A` + output it disagrees with. render: text validations: required: true @@ -36,10 +37,10 @@ body: - type: input id: system attributes: - label: z/OS release and ZOAU level - description: The `uname -a` output, and the ZOAU level (`pkglist`, - or the install directory). - placeholder: z/OS 3.1, ZOAU 1.3.4 + label: z/OS release and Open XL level + description: The `uname -a` output, and the compiler level + (`ibm-clang --version`). + placeholder: z/OS 3.1, Open XL 2.2.0 validations: required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 6b87a5b..ef578fc 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -7,6 +7,6 @@ - [ ] `make` is warning-free on z/OS with IBM Open XL - [ ] `make check` (heap checker, storage report) passes - [ ] `clang-format --dry-run -Werror whoson.c` passes -- [ ] ran on this system and compared with `D TS,A` / `D OMVS,A=ALL` +- [ ] ran on this system and compared with `D TS,A` and `ps -A -o pid,xasid` -If a display field or column changed, say what the console showed. +If a control-block field or column changed, say what the probe or `ps` showed. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index de6ccb1..0b30bfe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: persist-credentials: false - # The build itself needs z/OS and the ZOAU headers, so this job only + # The build itself needs z/OS and IBM Open XL, so this job only # proves that the Makefile parses under GNU make and that each recipe is # well formed. -n runs nothing. - run: make -n all diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3ce4386..9f80cba 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,7 +1,7 @@ name: release # Pushing v1.2.3 creates the release and attaches the source archive. There is -# no binary: whoson links against the ZOAU 64-bit DLL and only builds on z/OS, +# no binary: whoson only builds on z/OS, # which no hosted runner provides. on: push: diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e769ef..ac390e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,8 @@ - Rewritten without ZOAU and without a console display. Sessions are read straight out of common storage, walking CVT -> ASVT -> ASCB, which needs no - APF authorization, no supervisor state and no key zero; process details come - from `ps -A -o pid,jobname,user,time,args`, joined on the job name. The + APF authorization, no supervisor state and no key zero; SSH sessions come + from `w_getpsent()` and their address space id from `ps -o pid,xasid`. The ZOAU shared library, `LIBPATH` and the `AC=1`/`extattr +a` install are gone. - Only sessions are listed. Started tasks, OMVS daemons and the processes inside a session no longer appear as rows, so the table answers "who is @@ -14,22 +14,22 @@ session whose logon procedure is the z/OSMF one (`IZUFPROC` by default, per the z/OSMF Configuration Guide's `COMMONPROC`/`FILEPROC`), which is how z/OSMF actually logs a user on; it is not a separate kind of session. -- `JOBNAME` and `LOGONPROC` are separate columns: `ASCBJBNI` is the job name, - `ASCBJBNS` the name the address space was started with, which for TSO/E is - the logon procedure. - -## Unreleased - -- `TYPE` says which kind of TSO/E logon a row is: `TSO/E ISPF` when the - address space has no OMVS process, `TSO/E z/OSMF` when that process is a - z/OSMF program (`IZUGDSPT`, a load module from the z/OSMF load library, in - the `IZUFPROC` session z/OSMF logs on with) or when the CEA session table - records a z/OSMF `APPID` for the session, and `TSO/E OMVS` for any other - logon that has one. The z/OSMF session used to be reported as - `TSO/E OMVS`. -- `F CEA,DIAG,SESSTABLE` is read as a third display, so a z/OSMF session is - named even when it has no z/OSMF process left running. Losing that display - costs the label, not the table, and is not reported. +- `JOBNAME` and `LOGONPROC` are separate columns: `ASCBJBNI` is the job name + (falling back to `ASCBJBNS` when it is blank), and the logon procedure comes + from the session's CSCB (`CHCLS`), not from `ASCBJBNS`. +- `CPU` adds `ASSBASST` to `ASCBEJST` + `ASCBSRBT` and converts TOD units with + `>> 12`; the old rewrite multiplied by 1024, overstating CPU time by 2^22. +- `SSH` rows come from the process tree (parent `sshd`, child not `sshd`), not + from `-R`, so OpenSSH 9.8's `sshd-session` and unauthenticated preauth + children are handled. Rows join to the ASCB by ASID. +- The ASVT walk sizes itself from `ASVTMAXU`, validates each ASCB, and a fault + while reading a terminated address space skips that row instead of abending. +- Output follows the zopen character-set convention: files are tagged + ISO8859-1 (CCSID 819) and receive ASCII; terminals, pipes and EBCDIC files + are IBM-1047 with the runtime converting from ASCII (`F_CONTROL_CVT`). The + same tag drives how `ps` output is read. +- Requires z/OS 2.5 or later. Revises the tooling docs, CI comment and issue + templates to drop ZOAU and the old console displays. ## 1.0.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d6adecf..4bc6455 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,8 +4,8 @@ Small tool, small rules. ## Building -whoson is a single C17 file linked against the ZOAU shared library, so it -builds on z/OS and nowhere else: +whoson is a single C17 file with no external library, so it builds on z/OS +and nowhere else: ```sh make # -> ./whoson @@ -13,9 +13,8 @@ make check # under the CEE heap checker and storage report make install # -> ~/.local/bin/whoson ``` -Needs IBM Open XL C/C++ (`ibm-clang`, pinned by absolute path in the -`Makefile`), ZOAU 1.3 or later, and `LIBPATH` containing -`/usr/lpp/IBM/zoautil/lib`. +Needs IBM Open XL C/C++ 2.2 (`ibm-clang`, pinned by absolute path in the +`Makefile`) and z/OS 2.5 or later, the oldest target that compiler accepts. GNU make and IBM's make both have to parse the Makefile: keep it to POSIX make syntax (`?=` is out), and let `make -n` stay free of side effects. @@ -27,14 +26,15 @@ syntax (`?=` is out), and let `make -n` stay free of side effects. `.clang-tidy`, gets fixed rather than silenced. - `clang-format -i whoson.c` before committing; `.clang-format` is the authority, and CI checks the result against clang-format 23.1.5. -- Comments say why, not what, and the file header says what the two displays - give and what they do not. +- Comments say why, not what, and the file header says what the control-block + walk and the process table give and what they do not. ## Changes - One PR per change, branched from `main`, merged through the PR. -- Touching how a display is parsed means saying which field was wrong and what - the console showed. Do not adjust a test or an example to make a claim true. +- Touching how a control block or a `ps` row is parsed means saying which field + was wrong and what the probe or `ps` showed. Do not adjust an example to make + a claim true. - No binaries in the tree, and nothing generated (`.clangd` indexes, `whoson.json`) gets committed. @@ -46,5 +46,5 @@ syntax (`?=` is out), and let `make -n` stay free of side effects. `VERSION`, takes the release notes from that `CHANGELOG.md` section, and attaches the source archive with its sha256. -There is no binary in a release: it links the ZOAU 64-bit DLL and only builds -on z/OS, so a release ships the sources and the build instructions. +There is no binary in a release: whoson only builds on z/OS, so a release +ships the sources and the build instructions. @@ -16,9 +16,11 @@ # the source needs 64 bits - the control block pointers are 32-bit - so if # the ASCII mode is ever dropped, -m64 goes with it. # -# ASCII character mode is deliberate: ps output and the ssh channel are -# ASCII, so literals stay ASCII and the names copied out of EBCDIC storage -# are converted once, in copy_name(). Source stays ASCII-tagged. +# ASCII character mode is deliberate: the source is tagged ISO8859-1, so +# literals stay ASCII. Output is converted by the C runtime from the +# descriptor's tag (emit()): a file becomes ISO8859-1 (CCSID 819), a terminal +# or pipe IBM-1047, and the tag also tells read() what ps wrote. _OPEN_SYS and +# _OPEN_SYS_FILE_EXT expose __fchattr(), attrib_t and F_CONTROL_CVT. # # Every build is the release build: -O3, no -g, and a z/OS program object has # no symbol table to remove. @@ -37,9 +39,10 @@ CCDIR = /usr/lpp/IBM/cnw/v2r2/openxl/bin CC = $(CCDIR)/ibm-clang LISTFMT = $(CCDIR)/ibm-clang-listing-formatter CPPFLAGS = -D_XOPEN_SOURCE=600 -D_POSIX_C_SOURCE=200809L -D_ALL_SOURCE \ - -D_EXT -DWHOSON_VERSION=\"$(VERSION)\" -CFLAGS = -std=c17 -O3 -m64 -fzos-le-char-mode=ascii -Wall -Wextra \ - -Wpedantic -Wshadow -Wconversion + -D_EXT -D_OPEN_SYS -D_OPEN_SYS_FILE_EXT \ + -DWHOSON_VERSION=\"$(VERSION)\" +CFLAGS = -std=c17 -O3 -m64 -mzos-target=zosv2r5 -fzos-le-char-mode=ascii \ + -Wall -Wextra -Wpedantic -Wshadow -Wconversion CEEOPTS = HEAPCHK(ON,1,32),RPTSTG(ON),FILETAG(AUTOCVT,AUTOTAG),POSIX(ON) .PHONY: all install check list clean @@ -5,44 +5,51 @@ [](LICENSE) Who is logged on to this z/OS system: the interactive sessions, one row each, -with the address space, the job name, the name the address space was started -with and its CPU time. +with the address space, the job name, the logon procedure and its CPU time. ```text $ whoson USER TYPE ASID JOBNAME LOGONPROC PID CPU -CBT002 TSO/E 0046 CBT002 CBT002 - 499:34:54 -SKURTZ SSH 002B SSHD16 - 83886753 4:53:34 -SKURTZ TSO/E 0060 SKURTZ SKURTZ - 68:54:38 +CBT002 TSO/E 0046 CBT002 CBT002 - 0:12:31 +SKURTZ z/OSMF 003D SKURTZ IZUFPROC - 0:03:41 +SKURTZ SSH 004C SKURTZ - 33555303 0:00:02 ``` Three types of session are listed, and nothing else: - `TSO/E` — an address space with a TSO/E session control block (`ASCBTSB` is - not zero). That covers a logon at a terminal, under ISPF or not, and it - covers a z/OSMF user too, because z/OSMF logs its users on with a TSO/E - logon procedure. + not zero) or a CSCB track id of X'01'. That covers a logon at a terminal, + under ISPF or not, and it covers a z/OSMF user too, because z/OSMF logs its + users on with a TSO/E logon procedure. - `z/OSMF` — a `TSO/E` session whose logon procedure is the one z/OSMF is configured with. The z/OSMF Configuration Guide names it twice: `FILEPROC` for the data set and file REST services and `COMMONPROC` for the common TSO services, both defaulting to `IZUFPROC`, the procedure IBM ships in `SYS1.PROCLIB`. That is what separates a user who came in through the z/OSMF web interface from one who logged on at a terminal: same TSO/E - machinery, different logon procedure. -- `SSH` — an `sshd` started with `-R`, which is the process sshd forks per - connection (the listener runs without the flag). A connection that has not - authenticated yet still runs under the daemon account and is not listed. + machinery, different logon procedure. Any other procedure z/OSMF is + configured with can be added to `WHOSON_ZOSMF_PROCS`. +- `SSH` — a process whose parent is an `sshd` (or `sshd-session`) and which is + not itself an `sshd`. sshd forks that worker per connection; the listener + has no `sshd` parent. A connection that has not authenticated yet is + excluded by the same rule, and a port-forward-only connection has no such + child, so neither is listed. Started tasks, OMVS daemons and the processes inside a session are not sessions and are not listed: `TCPIP`, `CEA`, `IZUSVR` and the shells behind an `sshd` are all absent from the table by design. -`JOBNAME` is `ASCBJBNI`, the job name, and `LOGONPROC` is `ASCBJBNS`, the name -the address space was started with — for a TSO/E session that is the logon -procedure. `ASID` is the address space id, `PID` the POSIX process id where -one exists (`-` for a session that has none), and `CPU` is the sum of the -address space's TCB and SRB accumulator (`ASCBEJST` + `ASCBSRBT`, in -1024-microsecond units) as `hours:minutes:seconds`. +`JOBNAME` is `ASCBJBNI` when it is set and `ASCBJBNS` otherwise — for a TSO/E +session `ASCBJBNI` is empty and `ASCBJBNS` holds the userid. `LOGONPROC` is +the session's CSCB class (`CHCLS`), which is the logon procedure for a TSO/E +user; `ASCBJBNS` only says how the address space was started. `USER` is the +CSCB key (`CHKEY`), the userid for a TSO/E session, and the POSIX effective +uid for an SSH session. `ASID` is the address space id, `PID` the POSIX +process id where one exists (`-` for a session that has none), and `CPU` is +TCB time (`ASCBEJST`) plus SRB time (`ASCBSRBT`) plus additional preemptable +SRB time (`ASSBASST`) as `hours:minutes:seconds`. All three are TOD-clock +accumulators, so the low 12 bits are the fraction, not 1024-microsecond +units. ```sh whoson # the table @@ -52,12 +59,15 @@ whoson --help ## Requirements -- z/OS 2.1 or later. +- z/OS 2.5 or later (the oldest target Open XL 2.2 accepts). - IBM Open XL C/C++ (`ibm-clang`) to build it. -There is nothing else: no ZOAU, no console access, no `LIBPATH`, and no -authorization. The program reads only common storage, which is mapped into -every address space. +There is nothing else: no ZOAU, no console access, no `LIBPATH`, and no APF +authorization. The TSO/E half reads only common storage, which is mapped into +every address space. The SSH half calls `w_getpsent()`, which is filtered by +the caller's authority: without READ on `SUPERUSER.PROCESS.GETPSENT` (or an +equivalent uid match) other users' processes are invisible, so their SSH +sessions are missing from the table. TSO/E rows are unaffected. ## Install @@ -100,14 +110,20 @@ The sources are ASCII and stay that way; the build is in ASCII character mode accept. Names read out of control blocks arrive in EBCDIC and are converted once, as they are copied. -Output does not go through `printf`. `emit()` writes every message and the -table itself with `write(2)`, in the character set the destination expects: -plain ASCII when the descriptor is a terminal, EBCDIC when it is a pipe, a -socket or a file. CEE converts stdio output from ASCII to EBCDIC on a terminal, -and this system's sshd converts the other way for a command it runs without a -tty, so neither `printf` nor a raw `write()` is right on both paths. Help and -error text go through the same `emit()`, so `whoson -h` and the usage message -are readable whichever way they are run. +Output does not go through `printf`, and it does not guess from `isatty()`. +The source and the program are ISO8859-1 (CCSID 819). `emit()` looks at the +destination's tag and sets the descriptor up the way [zopen][zopen] does: +a text file is tagged ISO8859-1 and receives ASCII (an untagged file is +tagged 819 first, so `whoson > out` produces a tagged ASCII file); a terminal, +a pipe or an EBCDIC-tagged file is written as IBM-1047 and the C runtime +converts the ASCII writes to EBCDIC through `fcntl(F_CONTROL_CVT)`. The +descriptor's saved setting is restored before exit, so the shell's own output +is not affected. That works the +same whether `_BPXK_AUTOCVT` is on or off, and on both a tty and a pipe, +where `printf` and a raw `write()` each get one of the two wrong. Help and +error text go through the same `emit()`. + +[zopen]: https://zopen.community/Guides/CommonSolutions ## How the data is produced @@ -117,17 +133,35 @@ No display command and no subsystem interface is involved: `ASVTMAXU` at `+X'204'` and the array of ASCB pointers at `+X'210'`; an entry with the high bit set is a free ASID, and `ASCB` at offset 0 proves the rest point at an address space control block. -- From each ASCB: `ASCBASID` (`X'24'`), `ASCBTSB` (`X'3C'`, the TSO/E test), - `ASCBEJST` (`X'40'`) and `ASCBSRBT` (`X'C8'`) for CPU, `ASCBJBNI` (`X'AC'`) - and `ASCBJBNS` (`X'B0'`) for the two names. The name pointers address common - storage, so no cross-memory services are needed to follow them. -- `ps -A -o pid,jobname,user,time,args` supplies the pid, the user and the - command. The job name joins a process to an address space; the command is - what tells an `sshd` session (`-R`) from its listener. +- From each ASCB: `ASCBASID` (`X'24'`), `ASCBTSB` (`X'3C'`), `ASCBEJST` + (`X'40'`) and `ASCBSRBT` (`X'C8'`) for CPU, `ASCBJBNI` (`X'AC'`) and + `ASCBJBNS` (`X'B0'`) for the names. The name pointers address common + storage, so no cross-memory services are needed to follow them. The ASCB's + ACB eye-catcher and `ASCBASID == ASID` validate the block; a fault while + reading any of it skips that row instead of ending the program. +- The session's CSCB is at `ASCB+X'38'`: `CHKEY` (`X'08'`, the userid), + `CHCLS` (`X'10'`, the logon procedure) and `CHTRKID` (`X'1C'`, X'01' for a + TSO/E user). `ASSBASST` (`X'160'` from `ASCBASSB`, `X'150'`) adds + preemptable SRB time to the CPU column. +- `w_getpsent()` supplies the process tree, its parent and the executable + path; a process whose parent is `sshd` and which is not `sshd` itself is an + SSH session. `ps -A -o pid,xasid` supplies the address space id (the + `W_PSPROC` interface has no ASID field), and the join to the ASCB is by + ASID because sshd's per-connection job names repeat. + +## Limits + +- A z/OSMF login that never starts a TSO/E address space (some REST-only + flows live entirely inside `IZUSVR1`) is not a TSO/E session and is not + listed. A TSO/E session started by another CEA application can only be + recognised by its procedure name, so it may be reported as `TSO/E`. +- SSH rows need `w_getpsent()` visibility, as described under Requirements. + Only pty logins have a `/etc/utmpx` record; whoson does not read it, so a + session's tty and remote address are not shown. -The offsets above are the ones the ASCB and ASVT macros on the system -generate, and they are the ones the fields were read at when the walk was -checked against `DISPLAY TS`. +The offsets above are the ones the ASVT, ASCB, CSCB and ASSB macros on the +system generate, and they were checked against a probe that read all 355 +address spaces on CBT. ## Contributing @@ -2,108 +2,238 @@ * 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 or SSH). + * 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 the program needs no APF authorization, no supervisor state and no key - * zero. ASCBJBNI holds the job name, ASCBJBNS the name the address space was - * started with - for a TSO/E session that is the logon procedure - and a - * non-zero ASCBTSB marks a TSO/E session. + * 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. * - * Process details (pid, user, command, elapsed time) come from - * "ps -A -o pid,jobname,user,time,args", joined on the job name. That join is - * what tells an SSH login from a started task: sshd forks one address space - * per connection and the fork inherits the job name of the connection. + * 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. * - * The ASCB CPU accumulators, ASCBEJST and ASCBSRBT, count in 1024-microsecond - * units, so the CPU column is printed as seconds. + * 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. * - * Ctrl blocks are read through volatile pointers on purpose: nothing in this - * file may be cached across the walk, because the blocks change under it. + * 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. + * + * 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 <ctype.h> +#include <errno.h> +#include <fcntl.h> #include <inttypes.h> +#include <pwd.h> +#include <setjmp.h> +#include <signal.h> #include <stdarg.h> +#include <stdbool.h> +#include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <sys/ps.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <sys/wait.h> #include <unistd.h> -#define MAX_SPACES 1024 -#define MAX_PROCS 8192 -#define MAX_TOKENS 16 #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 CMD_LEN 256 -#define TIME_LEN 16 +#define PATH_LEN 64 +#define OUT_LEN 8192 +#define CMD_BUF 2048 +#define TTY_BUF 2048 -/* ASCB field offsets: mvs-data-areas, checked against IHAASCB here. */ -#define ASCB_ASID 0x24u -#define ASCB_TSB 0x3Cu -#define ASCB_EJST 0x40u -#define ASCB_JBNI 0xACu -#define ASCB_JBNS 0xB0u -#define ASCB_SRBT 0xC8u +#ifdef PS_PATHBLEN +#define PS_PATH_BUF PS_PATHBLEN +#else +#define PS_PATH_BUF 1027 +#endif -/* CVTASVT, and the ASVT's own layout: the array of ASCB pointers starts well - * past the head of the block, and a set high bit marks a free ASID. */ -#define CVT_ASVT 556u -#define ASVT_MAXU 0x204u -#define ASVT_ENTY 0x210u +/* 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. */ +#define CVT_ASVT_OFF 0x22Cu +#define ASVT_ACRONYM_OFF 0x200u +#define ASVT_MAXU_OFF 0x204u +#define ASVT_ENTY_OFF 0x210u +#define ASVT_ACRONYM 0xC1E2E5E3u /* "ASVT" in EBCDIC */ #define ASCB_ACRONYM 0xC1E2C3C2u /* "ASCB" in EBCDIC */ +/* Field offsets are checked against these overlays (static_assert below). + * The overlays describe layout only; every read goes through the accessors, + * so the compiler never assumes the block is stable. */ +struct ascb { + uint32_t ascbascb; + unsigned char pad0[0x24 - 0x04]; + uint16_t ascbasid; + unsigned char pad1[0x38 - 0x26]; + uint32_t ascbcscb; + uint32_t ascbtsb; + uint64_t ascbejst; + unsigned char pad2[0xAC - 0x48]; + uint32_t ascbjbni; + uint32_t ascbjbns; + unsigned char pad3[0xC8 - 0xB4]; + uint64_t ascbsrbt; + unsigned char pad4[0x150 - 0xD0]; + uint32_t ascbassb; +}; + +struct cscb { + unsigned char pad0[0x08]; + char chkey[8]; + char chcls[8]; + unsigned char pad1[0x1C - 0x18]; + unsigned char chtrkid; +}; + +struct assb { + unsigned char pad[0x160]; + uint64_t assbasst; +}; + +_Static_assert(offsetof(struct ascb, ascbasid) == 0x24, "ASCBASID"); +_Static_assert(offsetof(struct ascb, ascbcscb) == 0x38, "ASCBCSCB"); +_Static_assert(offsetof(struct ascb, ascbtsb) == 0x3C, "ASCBTSB"); +_Static_assert(offsetof(struct ascb, ascbejst) == 0x40, "ASCBEJST"); +_Static_assert(offsetof(struct ascb, ascbjbni) == 0xAC, "ASCBJBNI"); +_Static_assert(offsetof(struct ascb, ascbjbns) == 0xB0, "ASCBJBNS"); +_Static_assert(offsetof(struct ascb, ascbsrbt) == 0xC8, "ASCBSRBT"); +_Static_assert(offsetof(struct ascb, ascbassb) == 0x150, "ASCBASSB"); +_Static_assert(offsetof(struct cscb, chkey) == 0x08, "CHKEY"); +_Static_assert(offsetof(struct cscb, chcls) == 0x10, "CHCLS"); +_Static_assert(offsetof(struct cscb, chtrkid) == 0x1C, "CHTRKID"); +_Static_assert(offsetof(struct assb, assbasst) == 0x160, "ASSBASST"); + +/* One address space, as read from its ASCB, indexed by ASID - 1. */ struct space { + bool tso; + uint64_t us; /* microseconds of CPU */ + char job[JOB_LEN]; + char user[NAME_LEN]; + char logon[JOB_LEN]; +}; + +/* One output row. TSO rows are built from a space; SSH rows from a process. */ +struct row { unsigned asid; - int tso; - unsigned long long cpu; + bool tso; + uint64_t us; + pid_t pid; + const char *type; char job[JOB_LEN]; char logon[JOB_LEN]; char user[NAME_LEN]; - char type[NAME_LEN]; - int32_t pid; }; struct proc { - int32_t pid; - char job[JOB_LEN]; - char user[NAME_LEN]; - char time[TIME_LEN]; - char cmd[CMD_LEN]; + pid_t pid; + pid_t ppid; + uid_t euid; + char name[PATH_LEN]; +}; + +struct pid_asid { + pid_t pid; + unsigned asid; }; static const char usage_text[] = "usage: whoson [--help | --version]\n" "\n" - "List the interactive sessions on this system: TSO/E, z/OSMF (which is a\n" - "TSO/E session started by the z/OSMF logon procedure) and SSH. Started\n" - "tasks, OMVS daemons and the processes inside a session are not listed.\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"; + " -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. */ #ifndef WHOSON_VERSION #define WHOSON_VERSION "unknown" #endif -/* Write a message in the character set its destination expects. CEE converts - * stdio output from ASCII to EBCDIC when the stream is a terminal, and sshd - * converts a pipe, socket or file the other way, so neither printf nor a raw - * write() is right on both: a terminal gets ASCII, everything else EBCDIC. */ -static void emit(int fd, char *buf, size_t len) { - if (!isatty(fd)) - __a2e_l(buf, len); +/* A control-block read that faults is caught here and turned into a skipped + * row. */ +static sigjmp_buf fault_env; +static volatile sig_atomic_t fault_armed; + +static void on_fault(int sig) { + if (fault_armed) + siglongjmp(fault_env, 1); + _exit(128 + sig); +} + +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); +#ifdef SIGBUS + sigaction(SIGBUS, &sa, NULL); +#endif +} + +static void unguard(void) { + signal(SIGSEGV, SIG_DFL); +#ifdef SIGBUS + signal(SIGBUS, SIG_DFL); +#endif +} + +static uint8_t read_u8(uint32_t addr) { + return *(const volatile uint8_t *)(uintptr_t)addr; +} + +static uint16_t read_u16(uint32_t addr) { + return *(const volatile uint16_t *)(uintptr_t)addr; +} + +static uint32_t read_u32(uint32_t addr) { + return *(const volatile uint32_t *)(uintptr_t)addr; +} + +static uint64_t read_u64(uint32_t addr) { + return *(const volatile uint64_t *)(uintptr_t)addr; +} + +static void 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) return; buf += n; @@ -111,6 +241,101 @@ static void emit(int fd, char *buf, size_t len) { } } +/* 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. */ +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)); +} + +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); +} + +/* 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. */ +struct cvt_saved { + int fd; + struct f_cnvrt v; +}; + +static struct cvt_saved saved_cvt[2]; +static size_t nsaved; + +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); +} + +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; + saved_cvt[nsaved].fd = fd; + saved_cvt[nsaved].v = q; + nsaved++; +} + +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. */ +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); +} + static void emit_str(int fd, const char *text) { char buf[MSG_LEN]; size_t len = strlen(text); @@ -121,250 +346,722 @@ static void emit_str(int fd, const char *text) { emit(fd, buf, len); } -/* Report an error on stderr; messages are short enough for one line buffer. */ -static void error_msg(const char *fmt, ...) { +static void vmessage(bool usage, const char *fmt, va_list ap) { char text[MSG_LEN]; - va_list ap; - va_start(ap, fmt); vsnprintf(text, sizeof(text), fmt, ap); - va_end(ap); emit_str(STDERR_FILENO, text); + if (usage) { + emit_str(STDERR_FILENO, "\n"); + emit_str(STDERR_FILENO, usage_text); + } } -static void usage_error(const char *fmt, ...) { - char text[MSG_LEN]; +static void error_msg(const char *fmt, ...) { va_list ap; va_start(ap, fmt); - vsnprintf(text, sizeof(text), fmt, ap); + vmessage(false, fmt, ap); va_end(ap); - emit_str(STDERR_FILENO, text); - emit_str(STDERR_FILENO, "\n"); - emit_str(STDERR_FILENO, usage_text); } -static void copy_field(char *dst, size_t dstlen, const char *src) { - snprintf(dst, dstlen, "%s", src); +static void usage_error(const char *fmt, ...) { + va_list ap; + + va_start(ap, fmt); + vmessage(true, fmt, ap); + va_end(ap); } -/* Copy the 8-byte name a control block points at. These pointers address - * common storage, so no cross-memory services are needed to read them. */ -static void copy_name(char *dst, uint32_t ptr) { - char raw[JOB_LEN]; - int i; +/* Copy the 8-byte EBCDIC name a control block points at. These pointers + * address common storage, so no cross-memory services are needed. */ +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 < JOB_LEN - 1; i++) - raw[i] = ((const volatile char *)(uintptr_t)ptr)[i]; - __e2a_l(raw, JOB_LEN - 1); /* names sit in storage as EBCDIC */ - for (i = 0; i < JOB_LEN - 1; i++) { - if (raw[i] == '\0' || raw[i] == ' ') + 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'; +} + +static void read_tagged_name(uint32_t addr, char *dst, size_t dstlen) { + unsigned char raw[8]; + size_t i; + size_t n = 0; + + if (dstlen == 0) + return; + dst[0] = '\0'; + for (i = 0; i < sizeof(raw); i++) + raw[i] = read_u8(addr + (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[i] = raw[i]; + dst[n++] = (char)raw[i]; } - dst[i] = '\0'; + dst[n] = '\0'; } -/* Walk the ASVT and describe every allocated address space. */ -static int ascb_scan(struct space *sp, int max) { - uint32_t cvt = *(volatile uint32_t *)(uintptr_t)16; +/* Read one ASCB. Returns 0 and fills *out on success; -1 skips it. */ +static int scan_one(unsigned idx, uint32_t entry, uint32_t entries, + struct space *out) { + struct space tmp; + uint32_t ascb = entry & 0x7FFFFFFFu; + uint16_t asid; + uint32_t cscb; + uint64_t tod; + bool tso; + char key[NAME_LEN]; + char cls[JOB_LEN]; + + memset(&tmp, 0, sizeof(tmp)); + memset(key, 0, sizeof(key)); + memset(cls, 0, sizeof(cls)); + fault_armed = 1; + if (sigsetjmp(fault_env, 1) != 0) { + fault_armed = 0; + return -1; + } + if (read_u32(ascb) != ASCB_ACRONYM) + goto fail; + asid = read_u16(ascb + (uint32_t)offsetof(struct ascb, ascbasid)); + if (asid != idx + 1) + goto fail; + tod = read_u64(ascb + (uint32_t)offsetof(struct ascb, ascbejst)) + + read_u64(ascb + (uint32_t)offsetof(struct ascb, ascbsrbt)); + cscb = read_u32(ascb + (uint32_t)offsetof(struct ascb, ascbcscb)); + tso = read_u32(ascb + (uint32_t)offsetof(struct ascb, ascbtsb)) != 0; + if (cscb != 0) { + uint32_t assb; + + read_tagged_name(cscb + (uint32_t)offsetof(struct cscb, chkey), key, + sizeof(key)); + read_tagged_name(cscb + (uint32_t)offsetof(struct cscb, chcls), cls, + sizeof(cls)); + if (read_u8(cscb + (uint32_t)offsetof(struct cscb, chtrkid)) == 0x01) + tso = true; + assb = read_u32(ascb + (uint32_t)offsetof(struct ascb, ascbassb)); + if (assb != 0) + tod += read_u64(assb + (uint32_t)offsetof(struct assb, assbasst)); + } + read_name(read_u32(ascb + (uint32_t)offsetof(struct ascb, ascbjbni)), + tmp.job, sizeof(tmp.job)); + read_name(read_u32(ascb + (uint32_t)offsetof(struct 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; +} + +static int read_asvt(unsigned *maxu, uint32_t *entries) { + uint32_t cvt; uint32_t asvt; - uint32_t entries; - unsigned maxu; - unsigned i; - int n = 0; + fault_armed = 1; + if (sigsetjmp(fault_env, 1) != 0) { + fault_armed = 0; + return -1; + } + cvt = read_u32(16); if (cvt == 0) - return 0; - asvt = *(volatile uint32_t *)(uintptr_t)(cvt + CVT_ASVT); + goto fail; + asvt = read_u32(cvt + CVT_ASVT_OFF); if (asvt == 0) - return 0; - maxu = *(volatile uint32_t *)(uintptr_t)(asvt + ASVT_MAXU) & 0xFFFFu; - entries = asvt + ASVT_ENTY; - for (i = 0; i < maxu && n < max; i++) { - uint32_t ent = *(volatile uint32_t *)(uintptr_t)(entries + 4u * i); - uint32_t ascb; + 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; +} - if ((ent & 0x80000000u) != 0) - continue; - ascb = ent & 0x7FFFFFFFu; - if (*(volatile uint32_t *)(uintptr_t)ascb != ASCB_ACRONYM) +static int ascb_scan(uint32_t entries, unsigned maxu, struct 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; - sp[n].asid = *(volatile uint16_t *)(uintptr_t)(ascb + ASCB_ASID); - sp[n].tso = *(volatile uint32_t *)(uintptr_t)(ascb + ASCB_TSB) != 0; - sp[n].cpu = - *(volatile unsigned long long *)(uintptr_t)(ascb + ASCB_EJST) + - *(volatile unsigned long long *)(uintptr_t)(ascb + ASCB_SRBT); - copy_name(sp[n].job, - *(volatile uint32_t *)(uintptr_t)(ascb + ASCB_JBNI)); - copy_name(sp[n].logon, - *(volatile uint32_t *)(uintptr_t)(ascb + ASCB_JBNS)); - if (sp[n].job[0] == '\0') - copy_field(sp[n].job, JOB_LEN, sp[n].logon); - sp[n].user[0] = '\0'; - sp[n].type[0] = '\0'; - sp[n].pid = 0; - n++; + if (scan_one(i, entry, entries, &snap[i]) == 0) + (*found)++; } - return n; + return 0; } -/* Read the process table. ps prints one line per process as - * "pid jobname user time command", so the job name joins to an address - * space by name and the command tells an sshd session from the listener. */ -static int ps_scan(struct proc *pr, int max) { - FILE *fp; - char line[512]; - int n = 0; +static FILE *ps_open(void) { + return popen("/bin/ps -A -o pid,xasid", "r"); +} - fp = popen("ps -A -o pid,jobname,user,time,args", "r"); - if (fp == NULL) - return 0; - while (fgets(line, sizeof(line), fp) != NULL && n < max) { - int32_t pid; - char job[JOB_LEN]; - char user[NAME_LEN]; - char tm[TIME_LEN]; +static int read_all(int fd, char **out, size_t *outlen) { + size_t cap = 16384; + size_t len = 0; + char *buf = malloc(cap + 1); - job[0] = '\0'; - user[0] = '\0'; - tm[0] = '\0'; - pr[n].cmd[0] = '\0'; - if (sscanf(line, "%" SCNd32 " %8s %15s %15s %255[^\n]", &pid, job, user, - tm, pr[n].cmd) < 4) - continue; - if (strcmp(job, "JOBNAME") == 0) - continue; - pr[n].pid = pid; - copy_field(pr[n].job, JOB_LEN, job); - copy_field(pr[n].user, NAME_LEN, user); - copy_field(pr[n].time, TIME_LEN, tm); - n++; + if (buf == NULL) + 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 == NULL) { + 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; } - pclose(fp); - return n; + buf[len] = '\0'; + *out = buf; + *outlen = len; + return 0; } -/* An sshd started with -R serves one connection; the listener runs without - * it, so the flag is what separates a session from the daemon. */ -static int is_ssh_session(const struct proc *p) { - if (strstr(p->cmd, "sshd") == NULL || strstr(p->cmd, " -R") == NULL) - return 0; - /* An unauthenticated connection runs as a daemon account; it is not a - * session until someone has logged on. */ - return strcmp(p->user, "BPXROOT") != 0 && strcmp(p->user, "root") != 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. */ +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; + } + } } -/* TSO/E sessions come from the ASCB walk, SSH sessions from the process - * table. Everything else - started tasks, OMVS daemons, fork children of a - * shell - is not a session and stays out of the list. */ -static int collect(struct space *rows, int max, const struct space *sp, int nsp, - const struct proc *pr, int npr) { - int n = 0; - int i; +/* 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. */ +static int read_setup(int fd) { + struct stat st; - for (i = 0; i < nsp && n < max; i++) { - if (!sp[i].tso) - continue; - rows[n] = sp[i]; - copy_field(rows[n].type, NAME_LEN, - strncmp(sp[i].logon, "IZU", 3) == 0 ? "z/OSMF" : "TSO/E"); - copy_field(rows[n].user, NAME_LEN, sp[i].job); - rows[n].pid = -1; - n++; + 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; + } } - for (i = 0; i < npr && n < max; i++) { - unsigned asid = 0; - unsigned long long cpu = 0; - int k; - int dup = 0; + (void)set_cvt(fd, SETCVTOFF, 0, 0); + return 0; +} + +static int add_pid_asid(struct pid_asid **map, size_t *n, size_t *cap, + pid_t pid, unsigned asid) { + if (*n == *cap) { + size_t ncap = *cap ? *cap * 2 : 64; + struct pid_asid *grown = realloc(*map, ncap * sizeof(**map)); + + if (grown == NULL) + return -1; + *map = grown; + *cap = ncap; + } + (*map)[*n].pid = pid; + (*map)[*n].asid = asid; + (*n)++; + return 0; +} + +static bool is_header(const char *s) { + return !isdigit((unsigned char)s[0]); +} - if (!is_ssh_session(&pr[i])) +static int ps_scan(struct pid_asid **map, size_t *count) { + FILE *fp; + char *buf = NULL; + size_t len = 0; + size_t n = 0; + size_t cap = 0; + size_t i; + size_t start = 0; + int status; + int mode; + + *map = NULL; + *count = 0; + fp = ps_open(); + if (fp == NULL) { + 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); + for (i = 0; i <= len; i++) { + char c = i < len ? buf[i] : '\n'; + + if (c != '\n' && c != 0x15 && c != 0x25) continue; - for (k = 0; k < nsp; k++) { - if (strcmp(sp[k].job, pr[i].job) == 0) { - asid = sp[k].asid; - cpu = sp[k].cpu; - break; + 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 = NULL; + free(buf); + return -1; } } - for (k = 0; k < n; k++) { - if (asid != 0 && rows[k].asid == asid) - dup = 1; + start = i + 1; + } + free(buf); + if (n == 0) { + error_msg("whoson: ps returned no processes\n"); + free(*map); + *map = NULL; + return -1; + } + *count = n; + return 0; +} + +static int cmp_pid_asid(const void *a, const void *b) { + const struct pid_asid *x = a; + const struct pid_asid *y = b; + + if (x->pid != y->pid) + return x->pid < y->pid ? -1 : 1; + return 0; +} + +static const struct pid_asid *find_asid(const struct pid_asid *map, size_t n, + pid_t pid) { + struct pid_asid key; + + key.pid = pid; + key.asid = 0; + return bsearch(&key, map, n, sizeof(*map), cmp_pid_asid); +} + +static int cmp_proc(const void *a, const void *b) { + const struct proc *x = a; + const struct proc *y = b; + + if (x->pid != y->pid) + return x->pid < y->pid ? -1 : 1; + return 0; +} + +static const struct proc *find_proc(const struct proc *procs, size_t n, + pid_t pid) { + struct proc key; + + memset(&key, 0, sizeof(key)); + key.pid = pid; + return bsearch(&key, procs, n, sizeof(*procs), cmp_proc); +} + +static bool is_sshd(const char *path) { + const char *base = strrchr(path, '/'); + + base = base != NULL ? base + 1 : path; + return strcmp(base, "sshd") == 0 || strcmp(base, "sshd-session") == 0; +} + +static int append_proc(struct 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; + struct proc *grown = realloc(*procs, ncap * sizeof(**procs)); + + if (grown == NULL) + return -1; + *procs = grown; + *cap = ncap; + } + base = strrchr(path, '/'); + base = base != NULL ? 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; +} + +static int proc_scan(struct 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 = NULL; + *count = 0; + path = malloc(PS_PATH_BUF); + cmd = malloc(CMD_BUF); + tty = malloc(TTY_BUF); + if (path == NULL || cmd == NULL || tty == NULL) { + 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 = PS_PATH_BUF; + ps.ps_pathptr = path; + ps.ps_cmdlen = CMD_BUF; + ps.ps_cmdptr = cmd; + ps.ps_conttylen = 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; + 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 = NULL; + free(path); + free(cmd); + free(tty); + return -1; } - if (dup) - continue; - rows[n].asid = asid; - rows[n].cpu = cpu; - rows[n].pid = pr[i].pid; - copy_field(rows[n].type, NAME_LEN, "SSH"); - copy_field(rows[n].job, JOB_LEN, pr[i].job); - copy_field(rows[n].user, NAME_LEN, pr[i].user); - copy_field(rows[n].logon, JOB_LEN, "-"); - n++; } - return n; + free(path); + free(cmd); + free(tty); + if (n == 0) { + error_msg("whoson: the process table is empty\n"); + free(*procs); + *procs = NULL; + return -1; + } + qsort(*procs, n, sizeof(**procs), cmp_proc); + *count = n; + 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. */ +static bool logon_is_zosmf(const char *logon) { + const char *list = getenv("WHOSON_ZOSMF_PROCS"); + const char *p; + + if (logon == NULL || logon[0] == '\0') + return false; + p = list != NULL && list[0] != '\0' ? list : "IZUFPROC"; + for (;;) { + const char *comma = strchr(p, ','); + const char *end = comma != NULL ? 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 == NULL) + break; + p = comma + 1; + } + return false; } -static int compare_rows(const void *a, const void *b) { - const struct space *x = a; - const struct space *y = b; +static void user_name(uid_t uid, char *out, size_t outlen) { + static struct { + uid_t uid; + char name[NAME_LEN]; + } 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 != NULL) + 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++; +} + +static int cmp_rows(const void *a, const void *b) { + const struct row *x = a; + const struct 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; } -/* CPU counters arrive in 1024-microsecond units; print them as h:mm:ss. */ -static void fmt_cpu(unsigned long long units, char *out, size_t outlen) { - unsigned long long secs = (units * 1024ULL + 500000ULL) / 1000000ULL; +/* TOD units are 2^-12 microseconds; print the total as h:mm:ss. */ +static void fmt_cpu(uint64_t us, char *out, size_t outlen) { + uint64_t secs = (us + 500000u) / 1000000u; - snprintf(out, outlen, "%llu:%02llu:%02llu", secs / 3600ULL, - secs % 3600ULL / 60ULL, secs % 60ULL); + snprintf(out, outlen, "%" PRIu64 ":%02" PRIu64 ":%02" PRIu64, secs / 3600u, + secs % 3600u / 60u, secs % 60u); } -static void print_rows(const struct space *sp, int n) { +struct outbuf { + char buf[OUT_LEN]; + size_t len; +}; + +static void out_flush(struct outbuf *o) { + if (o->len != 0) + emit(STDOUT_FILENO, o->buf, o->len); + o->len = 0; +} + +static void out_add(struct 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; +} + +static void print_rows(struct row *rows, size_t n) { + struct outbuf out; char cpu[CPU_LEN]; char asid[ASID_LEN]; char pid[PID_LEN]; - int i; + size_t i; - snprintf(line, sizeof(line), - "%-8.8s %-6.6s %-4.4s %-8.8s %-10.10s %-8.8s %s\n", "USER", "TYPE", - "ASID", "JOBNAME", "LOGONPROC", "PID", "CPU"); - emit_str(STDOUT_FILENO, line); + 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(sp[i].cpu, cpu, sizeof(cpu)); - if (sp[i].asid != 0) - snprintf(asid, sizeof(asid), "%04X", sp[i].asid); + fmt_cpu(rows[i].us, cpu, sizeof(cpu)); + if (rows[i].asid != 0) + snprintf(asid, sizeof(asid), "%04X", rows[i].asid); else - copy_field(asid, sizeof(asid), "-"); - if (sp[i].pid > 0) - snprintf(pid, sizeof(pid), "%" PRId32, sp[i].pid); + snprintf(asid, sizeof(asid), "%s", "-"); + if (rows[i].pid > 0) + snprintf(pid, sizeof(pid), "%" PRId32, rows[i].pid); else - copy_field(pid, sizeof(pid), "-"); - snprintf(line, sizeof(line), - "%-8.8s %-6.6s %-4.4s %-8.8s %-10.10s %-8.8s %s\n", sp[i].user, - sp[i].type, asid, sp[i].job, sp[i].logon, pid, cpu); - emit_str(STDOUT_FILENO, line); + 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); +} + +static int collect(struct row *rows, size_t maxrows, const struct space *snap, + unsigned maxu, const struct proc *procs, size_t nprocs, + const struct pid_asid *map, size_t nmap) { + size_t n = 0; + size_t ssh_start; + 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].tso = true; + 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++; + } + ssh_start = n; + for (k = 0; k < nprocs && n < maxrows; k++) { + const struct proc *parent; + const struct pid_asid *pa; + unsigned asid = 0; + uint64_t us = 0; + const char *job = "-"; + size_t r; + bool dup = false; + + parent = find_proc(procs, nprocs, procs[k].ppid); + if (parent == NULL || !is_sshd(parent->name) || is_sshd(procs[k].name)) + continue; + pa = find_asid(map, nmap, procs[k].pid); + if (pa != NULL && 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; + } + if (asid != 0) { + for (r = ssh_start; r < n; r++) { + if (rows[r].asid == asid) + dup = true; + } + } + if (dup) + continue; + rows[n].asid = asid; + rows[n].tso = false; + 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; } int main(int argc, char **argv) { - static struct space spaces[MAX_SPACES]; - static struct space rows[MAX_SPACES]; - static struct proc procs[MAX_PROCS]; - int nsp; - int npr; + struct space *snap; + struct row *rows; + struct proc *procs; + struct pid_asid *map; + size_t nmap; + size_t nprocs; + unsigned maxu; + unsigned found; + uint32_t entries; + int nrows; int arg; + size_t bytes; + size_t space_bytes; + 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); @@ -378,14 +1075,43 @@ int main(int argc, char **argv) { return 1; } } - nsp = ascb_scan(spaces, MAX_SPACES); - if (nsp == 0) { + guard(); + if (read_asvt(&maxu, &entries) != 0) { + unguard(); + error_msg("whoson: cannot read the ASVT\n"); + return 1; + } + space_bytes = (sizeof(struct space) + 15u) & ~(size_t)15u; + bytes = (size_t)maxu * (space_bytes + sizeof(struct row)); + snap = calloc(1, bytes); + if (snap == NULL) { + unguard(); + error_msg("whoson: out of memory for %u address spaces\n", maxu); + return 1; + } + rows = (struct row *)(void *)((char *)snap + (size_t)maxu * space_bytes); + ascb_scan(entries, maxu, snap, &found); + unguard(); + if (found == 0) { + free(snap); error_msg("whoson: no address spaces found\n"); return 1; } - npr = ps_scan(procs, MAX_PROCS); - nsp = collect(rows, MAX_SPACES, spaces, nsp, procs, npr); - qsort(rows, (size_t)nsp, sizeof(rows[0]), compare_rows); - print_rows(rows, nsp); + 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); + nrows = collect(rows, maxu, snap, maxu, procs, nprocs, map, nmap); + qsort(rows, (size_t)nrows, sizeof(*rows), cmp_rows); + print_rows(rows, (size_t)nrows); + free(procs); + free(map); + free(snap); return 0; } |
