1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
|
/**
* @file whoson.c
* @brief Who is logged on to this z/OS system, and how: TSO/E, z/OSMF, SSH.
*
* SPDX-License-Identifier: MIT OR Apache-2.0 OR BSD-2-Clause
* SPDX-FileCopyrightText: 2026 Sean Kurtz
*
* @details Sessions come from the address space control blocks, not from a
* subsystem or a console command: CVT (PSA+X'10') -> ASVT -> every allocated
* ASCB. That walk reads only common storage, which is mapped into every address
* space, so it needs no APF authorization, no supervisor state and no key zero.
* ASCBJBNI holds the job name; the logon procedure comes from the session's
* CSCB (CHCLS), not from ASCBJBNS, which only names how the address space was
* started. A non-zero ASCBTSB, or a CSCB track id of X'01', marks TSO/E.
*
* The CPU column is the address space's TCB time (ASCBEJST), SRB time
* (ASCBSRBT) and preemptable SRB time (the ASSB's ASSBASST). All three are
* TOD-clock accumulators: the low 12 bits are the fraction, so >> 12 is
* microseconds.
*
* SSH sessions come from the process table: sshd forks one worker per
* connection, so a process whose parent is an sshd (and which is not itself
* an sshd) is a login. w_getpsent supplies that tree; ps supplies the
* address-space id (BPXYPGPS has one, the C W_PSPROC does not). The join to
* the ASCB is by ASID, not by job name: sshd's fork job names repeat.
*
* Control blocks are read through volatile pointers on purpose: nothing in
* this file may be cached across the walk, because the blocks change under
* it. Every read of a control block is guarded: an address space can end
* between the ASVT read and the ASCB read, and a stale pointer must skip one
* row, not abend the program. The handler assumes z/OS raises SIGSEGV
* synchronously for an unmapped common-storage read; ISO C leaves that
* implementation-defined, but the platform does it.
*
* Character conversion follows the zopen conventions: source and output are
* ISO8859-1 (CCSID 819) and the descriptor's tag says what the destination
* expects. A text file with no tag (or a non-EBCDIC tag) is tagged 819 and
* receives ASCII; an EBCDIC file, terminal or pipe is tagged IBM-1047 and
* the C runtime converts the ASCII writes (fcntl F_CONTROL_CVT). Nothing is
* decided from isatty(), and no byte is converted twice.
*/
#include <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>
/* Attributes without C23 spelling wrap here, so call sites stay readable. */
#ifdef __clang__
/** @brief printf-format checking for a wrapper that forwards a va_list. */
#define PRINTFLIKE(fmt_index, va_index) \
__attribute__((format(printf, fmt_index, va_index)))
#else
#define PRINTFLIKE(fmt_index, va_index)
#endif
/* Buffer and column widths. */
static constexpr size_t msg_len =
512; /**< one formatted message or table line */
static constexpr size_t name_len = 16; /**< a userid from CHKEY or getpwuid */
static constexpr size_t job_len = 9; /**< an 8-byte job name, plus the nul */
static constexpr size_t asid_len = 8; /**< "%04X" of an ASID, plus the nul */
static constexpr size_t pid_len =
12; /**< a 32-bit pid in decimal, plus the nul */
static constexpr size_t cpu_len = 16; /**< a formatted CPU duration */
static constexpr size_t path_len = 64; /**< basename of a process path */
static constexpr size_t out_len = 8192; /**< the whole table, then one write */
static constexpr size_t cmd_buf = 2048; /**< W_PSPROC command buffer */
static constexpr size_t tty_buf = 2048; /**< W_PSPROC controlling-TTY buffer */
#ifdef PS_PATHBLEN
/** @brief W_PSPROC path buffer: the header's own limit when it has one. */
static constexpr size_t ps_path_buf = PS_PATHBLEN;
#else
/** @brief W_PSPROC path buffer, for headers that do not name a limit. */
static constexpr size_t ps_path_buf = 1027;
#endif
/* CVTASVT. The ASVT's own head, then ASVTENTY, the array of ASCB addresses;
* a set high bit marks an ASID that is free or non-reusable. */
/** @brief CVT field holding the ASVT address (CVTASVT). */
static constexpr uint32_t cvt_asvt_off = 0x22CU;
/** @brief ASVT field: the eye-catcher "ASVT". */
static constexpr uint32_t asvt_acronym_off = 0x200U;
/** @brief ASVT field: highest ASID in use (ASVTMXU). */
static constexpr uint32_t asvt_maxu_off = 0x204U;
/** @brief ASVT field: first entry of ASVTENTY, four bytes each. */
static constexpr uint32_t asvt_enty_off = 0x210U;
/* An eye-catcher is a four-byte word that spells its block name in EBCDIC,
* and these blocks are filled in while the system runs in EBCDIC, even when
* whoson is built in ASCII mode. The value therefore cannot be a character
* literal: 'ASCB' would be the ASCII bytes B0 09 34 7E. */
/** @brief "ASVT" as it appears in the ASVT. */
static constexpr uint32_t asvt_acronym = 0xC1E2E5E3U;
/** @brief "ASCB" as it appears in the ASCB. */
static constexpr uint32_t ascb_acronym = 0xC1E2C3C2U;
/** @brief "CSCB" as it appears in the CSCB. */
static constexpr uint32_t cscb_acronym = 0xC3E2C3C2U;
/** @brief "ASSB" as it appears in the ASSB. */
static constexpr uint32_t assb_acronym = 0xC1E2E2C2U;
/** @brief CSCB CHTRKID value that marks a TSO/E session. */
enum { CSCB_TRKID_TSO = 0x01 };
/* Packed so the compiler adds no padding of its own: every offset is the sum
* of the field widths, and the static asserts pin the fields the walk reads.
* The overlays describe layout only; every read goes through the accessors,
* so the compiler never assumes the block is stable. */
/**
* @brief Address space control block, as far as the walk needs it (ASCB).
*/
typedef struct __attribute__((packed)) ascb {
uint32_t ascbascb; /**< X'00' eye-catcher */
unsigned char ascbresv0[0x24 - 0x04]; /**< X'04' unused here */
uint16_t ascbasid; /**< X'24' address space id */
unsigned char ascbresv1[0x38 - 0x26]; /**< X'26' unused here */
uint32_t ascbcscb; /**< X'38' CSCB address */
uint32_t ascbtsb; /**< X'3C' TSB address, zero if none */
uint64_t ascbejst; /**< X'40' TCB CPU in TOD units */
unsigned char ascbresv2[0xAC - 0x48]; /**< X'48' unused here */
uint32_t ascbjbni; /**< X'AC' job name, for a batch job */
uint32_t ascbjbns; /**< X'B0' procedure name, or job */
unsigned char ascbresv3[0xC8 - 0xB4]; /**< X'B4' unused here */
uint64_t ascbsrbt; /**< X'C8' SRB CPU in TOD units */
unsigned char ascbresv4[0x150 - 0xD0]; /**< X'D0' unused here */
uint32_t ascbassb; /**< X'150' ASSB address */
} ascb;
/** @brief Command scheduling control block (CSCB), the session's identity. */
typedef struct __attribute__((packed)) cscb {
uint32_t chptr; /**< X'00' chain pointer */
unsigned char chvcd; /**< X'04' VCD */
unsigned char chsze; /**< X'05' block size */
unsigned char chresv0[0x08 - 0x06]; /**< X'06' unused here */
char chkey[8]; /**< X'08' userid */
char chcls[8]; /**< X'10' logon procedure name */
uint32_t chunit; /**< X'18' unit */
unsigned char chtrkid; /**< X'1C' X'01' is a TSO/E session */
unsigned char chresv1; /**< X'1D' unused here */
uint16_t chasid; /**< X'1E' address space id */
unsigned char chresv2[0xD8 - 0x20]; /**< X'20' unused here */
char chcscbid[4]; /**< X'D8' eye-catcher */
} cscb;
/** @brief Address space secondary block: preemptible SRB time (ASSB). */
typedef struct __attribute__((packed)) assb {
char assbassb[4]; /**< X'000' eye-catcher */
unsigned char assbresv[0x160 - 0x04]; /**< X'004' unused here */
uint64_t assbasst; /**< X'160' SRB CPU in TOD units */
} assb;
static_assert(alignof(ascb) == 1);
static_assert(alignof(cscb) == 1);
static_assert(alignof(assb) == 1);
static_assert(sizeof(ascb) == 0x154);
static_assert(sizeof(cscb) == 0xDC);
static_assert(sizeof(assb) == 0x168);
static_assert(offsetof(ascb, ascbasid) == 0x24, "ASCBASID");
static_assert(offsetof(ascb, ascbcscb) == 0x38, "ASCBCSCB");
static_assert(offsetof(ascb, ascbtsb) == 0x3C, "ASCBTSB");
static_assert(offsetof(ascb, ascbejst) == 0x40, "ASCBEJST");
static_assert(offsetof(ascb, ascbjbni) == 0xAC, "ASCBJBNI");
static_assert(offsetof(ascb, ascbjbns) == 0xB0, "ASCBJBNS");
static_assert(offsetof(ascb, ascbsrbt) == 0xC8, "ASCBSRBT");
static_assert(offsetof(ascb, ascbassb) == 0x150, "ASCBASSB");
static_assert(offsetof(cscb, chkey) == 0x08, "CHKEY");
static_assert(offsetof(cscb, chcls) == 0x10, "CHCLS");
static_assert(offsetof(cscb, chtrkid) == 0x1C, "CHTRKID");
static_assert(offsetof(cscb, chasid) == 0x1E, "CHASID");
static_assert(offsetof(cscb, chcscbid) == 0xD8, "CHCSCBID");
static_assert(offsetof(assb, assbasst) == 0x160, "ASSBASST");
/** @brief What the ASCB walk keeps per address space, indexed by ASID - 1. */
typedef struct space {
bool tso; /**< the session is TSO/E */
uint64_t us; /**< microseconds of CPU */
char job[job_len]; /**< job name, or the procedure name */
char user[name_len]; /**< CHKEY userid, else the job name */
char logon[job_len]; /**< CHCLS procedure, else empty */
} space;
/** @brief One line of the table, before it is sorted and formatted: a TSO/E
* row comes from a space, an SSH row from a process. */
typedef struct row {
unsigned asid; /**< ASID, or 0 when no address space is known */
uint64_t us; /**< microseconds of CPU */
pid_t pid; /**< POSIX pid, or 0 for a TSO/E session */
const char *type; /**< "TSO/E", "z/OSMF" or "SSH" */
char job[job_len]; /**< job name, or "-" */
char logon[job_len]; /**< logon procedure, or "-" */
char user[name_len]; /**< userid */
} row;
/** @brief One process from the table, reduced to what the SSH rule needs. */
typedef struct proc {
pid_t pid; /**< process id */
pid_t ppid; /**< parent process id */
uid_t euid; /**< effective uid, the userid for SSH */
char name[path_len]; /**< basename of the executable */
} proc;
/** @brief One pid-to-ASID pair, as printed by ps -o pid,xasid. */
typedef struct pid_asid {
pid_t pid; /**< process id */
unsigned asid; /**< address space id from the xasid column */
} pid_asid;
/** @brief The --help text, kept as a plain array: Open XL 2.2 generates
* bad code for a string-literal `constexpr` (negative character
* representation). */
static const char usage_text[] =
"usage: whoson [--help | --version]\n"
"\n"
"List the interactive sessions on this system: TSO/E, z/OSMF (a TSO/E\n"
"session started by the z/OSMF logon procedure) and SSH. Started tasks,\n"
"OMVS daemons and the processes inside a session are not listed.\n"
"\n"
"Options:\n"
" -h, --help show this help and exit\n"
" -V, --version show the version and exit\n"
"\n"
"z/OSMF is recognised by its logon procedure name. Set\n"
"WHOSON_ZOSMF_PROCS to a comma-separated list to match other names\n"
"(default: IZUFPROC).\n";
/* Set by the Makefile from its VERSION, so the binary and the tag agree. */
/** @brief Version string, or "unknown" when the Makefile did not set one. */
#ifndef WHOSON_VERSION
#define WHOSON_VERSION "unknown"
#endif
/** @brief Where a faulting control-block read resumes: set by scan_one() and
* read_asvt(), and only valid while a guarded read is in progress. */
static sigjmp_buf fault_env;
/** @brief Non-zero while a guarded read is in progress. */
static volatile sig_atomic_t fault_armed;
/** @brief Put back the descriptor's conversion setting, from a signal handler.
*/
static void restore_cvt(void);
static void vmessage(bool usage, const char *fmt, va_list ap) PRINTFLIKE(2, 0);
static void error_msg(const char *fmt, ...) PRINTFLIKE(1, 2);
static void usage_error(const char *fmt, ...) PRINTFLIKE(1, 2);
/** @brief Turn a faulting read of an address space that went away into a
* skipped row; otherwise restore the conversion setting and die. */
static void on_fault(int sig) {
if (fault_armed)
siglongjmp(fault_env, 1);
restore_cvt();
_exit(128 + sig);
}
/** @brief Catch SIGSEGV and SIGBUS: a read of an ended address space must
* skip one row, not abend the program. */
static void guard(void) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = on_fault;
sigemptyset(&sa.sa_mask);
sigaction(SIGSEGV, &sa, nullptr);
#ifdef SIGBUS
sigaction(SIGBUS, &sa, nullptr);
#endif
}
/** @brief Put the default fault handling back once the walk is over. */
static void unguard(void) {
signal(SIGSEGV, SIG_DFL);
#ifdef SIGBUS
signal(SIGBUS, SIG_DFL);
#endif
}
/* The accessors below read a live control block. volatile is load-bearing:
* the compiler may not fold two reads of a block the system is changing, and
* it may not assume the value it read once still holds. The pointer cast is
* the MVS control-block interface: the address came out of another block. */
/** @brief Read one byte of common storage at addr. */
static uint8_t read_u8(uint32_t addr) {
return *(const volatile uint8_t *)(uintptr_t)addr;
}
/** @brief Read a big-endian 16-bit field of common storage at addr. */
static uint16_t read_u16(uint32_t addr) {
return *(const volatile uint16_t *)(uintptr_t)addr;
}
/** @brief Read a big-endian 32-bit field of common storage at addr. */
static uint32_t read_u32(uint32_t addr) {
return *(const volatile uint32_t *)(uintptr_t)addr;
}
/** @brief Read a big-endian 64-bit field of common storage at addr. */
static uint64_t read_u64(uint32_t addr) {
return *(const volatile uint64_t *)(uintptr_t)addr;
}
/** @brief Set by a failed write, so main can exit nonzero on truncated
* output. */
static bool output_failed;
/** @brief Write the whole buffer, retrying short writes and EINTR.
* @param fd descriptor
* @param buf bytes to write
* @param len byte count
* @return 0 on success, -1 with output_failed set on failure. */
static int write_all(int fd, const char *buf, size_t len) {
while (len > 0) {
ssize_t n = write(fd, buf, len);
if (n < 0 && errno == EINTR)
continue;
if (n <= 0) {
output_failed = true;
return -1;
}
buf += n;
len -= (size_t)n;
}
return 0;
}
/**
* @brief Tag fd as text in ccsid; zopen's setccsid(), through __fchattr().
* @param fd descriptor to tag
* @param ccsid CCSID to record, 819 for ASCII
* @return 0 on success, -1 with errno set
*/
static int tag_fd(int fd, unsigned ccsid) {
attrib_t a;
memset(&a, 0, sizeof(a));
a.att_filetagchg = 1;
a.att_filetag.ft_ccsid = (unsigned short)ccsid;
a.att_filetag.ft_txtflag = 1;
return __fchattr(fd, &a, sizeof(a));
}
/** @brief Set the descriptor's character conversion (F_CONTROL_CVT).
* @param fd descriptor
* @param cmd SETCVTON, SETCVTOFF or QUERYCVT
* @param pccsid source CCSID of a write
* @param fccsid destination CCSID of a write
* @return what fcntl() returns
*/
static int set_cvt(int fd, int cmd, int pccsid, int fccsid) {
struct f_cnvrt c;
c.cvtcmd = cmd;
c.pccsid = (short)pccsid;
c.fccsid = (short)fccsid;
return fcntl(fd, F_CONTROL_CVT, &c);
}
/** @brief A descriptor's starting conversion setting, kept for restore_cvt().
*/
typedef struct cvt_saved {
int fd; /**< descriptor */
struct f_cnvrt v; /**< the setting to put back */
} cvt_saved;
/** @brief Conversion settings saved before whoson changed them. */
static cvt_saved saved_cvt[2];
/** @brief How many entries of saved_cvt are in use (stdout and stderr). */
static size_t nsaved;
/**
* @brief Put back every saved conversion setting.
*
* The setting belongs to the open file description, which the calling shell
* keeps after whoson exits, so leaving ours behind would change the shell's
* own output. Only fcntl(), which is async-signal-safe, is used here.
*/
static void restore_cvt(void) {
size_t i;
for (i = 0; i < nsaved; i++)
(void)fcntl(saved_cvt[i].fd, F_CONTROL_CVT, &saved_cvt[i].v);
}
/** @brief Save fd's conversion setting for restore_cvt(). */
static void save_cvt(int fd) {
struct f_cnvrt q;
memset(&q, 0, sizeof(q));
q.cvtcmd = QUERYCVT;
if (fcntl(fd, F_CONTROL_CVT, &q) != 0)
return;
if (nsaved >= sizeof(saved_cvt) / sizeof(saved_cvt[0]))
return; /* main saves stdout and stderr only */
saved_cvt[nsaved].fd = fd;
saved_cvt[nsaved].v = q;
nsaved++;
}
/** @brief Whether a stat structure says the file is EBCDIC text. */
static bool ebcdic_tag(const struct stat *st) {
return st->st_tag.ft_txtflag &&
(st->st_tag.ft_ccsid == 37 || st->st_tag.ft_ccsid == 1047);
}
/**
* @brief Write buf in the character set fd expects.
*
* Files are the ASCII half of the zopen rule; terminals, pipes and
* EBCDIC-tagged files are IBM-1047. Only a file's tag is changed (an untagged
* file becomes ISO8859-1); a pipe or pty keeps its tag and just gets the
* conversion, so the runtime's own output to the same descriptor is not
* relabelled.
* @param fd descriptor
* @param buf ASCII bytes; converted in place when the destination wants
* EBCDIC
* @param len byte count
*/
static void emit(int fd, char *buf, size_t len) {
struct stat st;
bool ascii = false;
int fccsid = 1047;
if (fstat(fd, &st) == 0) {
if (S_ISREG(st.st_mode)) {
ascii = !ebcdic_tag(&st);
if (ascii && (!st.st_tag.ft_txtflag || st.st_tag.ft_ccsid == 0))
(void)tag_fd(fd, 819);
} else if (S_ISSOCK(st.st_mode)) {
ascii = true;
} else if (st.st_tag.ft_txtflag && st.st_tag.ft_ccsid != 0 &&
!ebcdic_tag(&st)) {
ascii = true; /* a pipe or pty that asked for ASCII */
} else if (ebcdic_tag(&st)) {
fccsid = (int)st.st_tag.ft_ccsid;
}
}
if (ascii) {
(void)set_cvt(fd, SETCVTOFF, 0, 0);
write_all(fd, buf, len);
return;
}
if (set_cvt(fd, SETCVTON, 819, fccsid) == 0) {
write_all(fd, buf, len);
return;
}
/* No fcntl support (fstat failed): convert by hand. */
(void)set_cvt(fd, SETCVTOFF, 0, 0);
__a2e_l(buf, len);
write_all(fd, buf, len);
}
/** @brief emit() a nul-terminated string, copied into a bounded buffer. */
static void emit_str(int fd, const char *text) {
char buf[msg_len];
size_t len = strlen(text);
if (len >= sizeof(buf))
len = sizeof(buf) - 1;
memcpy(buf, text, len);
emit(fd, buf, len);
}
/** @brief Format into a bounded buffer and emit() it, with the usage text
* when the message is a usage error. */
static void vmessage(bool usage, const char *fmt, va_list ap) {
char text[msg_len];
vsnprintf(text, sizeof(text), fmt, ap);
emit_str(STDERR_FILENO, text);
if (usage) {
emit_str(STDERR_FILENO, "\n");
emit_str(STDERR_FILENO, usage_text);
}
}
/** @brief Report an error on stderr, in the destination's character set. */
static void error_msg(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vmessage(false, fmt, ap);
va_end(ap);
}
/** @brief Report a usage error on stderr, followed by the usage text. */
static void usage_error(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vmessage(true, fmt, ap);
va_end(ap);
}
/**
* @brief Copy the 8-byte EBCDIC name a control block points at, as ASCII.
*
* These pointers address common storage, so no cross-memory services are
* needed, and the name is decoded with __e2a_l() because the block holds
* EBCDIC even in an ASCII build.
* @param ptr address of the name in common storage, 0 for none
* @param dst output buffer, always nul-terminated
* @param dstlen size of dst
*/
static void read_name(uint32_t ptr, char *dst, size_t dstlen) {
unsigned char raw[8];
size_t i;
size_t n = 0;
if (dstlen == 0)
return;
dst[0] = '\0';
if (ptr == 0)
return;
for (i = 0; i < sizeof(raw); i++)
raw[i] = read_u8(ptr + (uint32_t)i);
__e2a_l((char *)raw, sizeof(raw));
for (i = 0; i < sizeof(raw) && n + 1 < dstlen; i++) {
if (raw[i] == ' ' || raw[i] == '\0')
break;
if (raw[i] < 0x20 || raw[i] > 0x7E)
break;
dst[n++] = (char)raw[i];
}
dst[n] = '\0';
}
/**
* @brief Read one ASCB into *out, with its CSCB and ASSB.
*
* Every read is guarded: the address space can end between the ASVT read and
* the ASCB read, and the block can be reused while it is being read, so the
* ASVT entry is re-checked at the end.
* @param idx index into ASVTENTY, so the ASID must be idx + 1
* @param entry the raw ASVT entry, high bit included
* @param entries address of ASVTENTY
* @param out receives the address space on success
* @return 0 on success, -1 when the address space is gone or unreadable
*/
static int scan_one(unsigned idx, uint32_t entry, uint32_t entries,
space *out) {
space tmp = {0};
uint32_t ascb_addr = entry & 0x7FFFFFFFu;
uint16_t asid;
uint32_t cscb_addr;
uint64_t tod;
bool tso;
char key[name_len] = {0};
char cls[job_len] = {0};
fault_armed = 1;
if (sigsetjmp(fault_env, 1) != 0) {
fault_armed = 0;
return -1;
}
if (read_u32(ascb_addr) != ascb_acronym)
goto fail;
asid = read_u16(ascb_addr + (uint32_t)offsetof(ascb, ascbasid));
if (asid != idx + 1)
goto fail;
tod = read_u64(ascb_addr + (uint32_t)offsetof(ascb, ascbejst)) +
read_u64(ascb_addr + (uint32_t)offsetof(ascb, ascbsrbt));
cscb_addr = read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbcscb));
tso = read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbtsb)) != 0;
{
uint32_t assb_addr =
read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbassb));
if (assb_addr != 0 && read_u32(assb_addr) == assb_acronym)
tod += read_u64(assb_addr + (uint32_t)offsetof(assb, assbasst));
}
/* A CSCB that has already been released can still be reachable through a
* stale ASCB pointer; its eye-catcher and CHASID say whether the block
* still belongs to this address space. */
if (cscb_addr != 0 &&
read_u32(cscb_addr + (uint32_t)offsetof(cscb, chcscbid)) ==
cscb_acronym &&
read_u16(cscb_addr + (uint32_t)offsetof(cscb, chasid)) == asid) {
read_name(cscb_addr + (uint32_t)offsetof(cscb, chkey), key,
sizeof(key));
read_name(cscb_addr + (uint32_t)offsetof(cscb, chcls), cls,
sizeof(cls));
if (read_u8(cscb_addr + (uint32_t)offsetof(cscb, chtrkid)) ==
CSCB_TRKID_TSO)
tso = true;
}
read_name(read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbjbni)), tmp.job,
sizeof(tmp.job));
read_name(read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbjbns)),
tmp.logon, sizeof(tmp.logon));
/* The ASVT entry must still name the same ASCB: if the address space
* ended while we were reading it, the block may already be reused. */
if (read_u32(entries + 4u * idx) != entry)
goto fail;
tmp.tso = tso;
tmp.us = tod >> 12;
if (tmp.job[0] == '\0')
snprintf(tmp.job, sizeof(tmp.job), "%s", tmp.logon);
if (key[0] != '\0')
snprintf(tmp.user, sizeof(tmp.user), "%s", key);
else
snprintf(tmp.user, sizeof(tmp.user), "%s", tmp.job);
if (cls[0] != '\0')
snprintf(tmp.logon, sizeof(tmp.logon), "%s", cls);
else
tmp.logon[0] = '\0';
*out = tmp;
fault_armed = 0;
return 0;
fail:
fault_armed = 0;
return -1;
}
/**
* @brief Find the ASVT through the CVT and validate it.
* @param maxu receives ASVTMXU, the highest ASID in use
* @param entries receives the address of ASVTENTY
* @return 0 on success, -1 when the PSA, CVT or ASVT cannot be used
*/
static int read_asvt(unsigned *maxu, uint32_t *entries) {
uint32_t cvt;
uint32_t asvt;
fault_armed = 1;
if (sigsetjmp(fault_env, 1) != 0) {
fault_armed = 0;
return -1;
}
cvt = read_u32(16);
if (cvt == 0)
goto fail;
asvt = read_u32(cvt + cvt_asvt_off);
if (asvt == 0)
goto fail;
if (read_u32(asvt + asvt_acronym_off) != asvt_acronym)
goto fail;
*maxu = read_u32(asvt + asvt_maxu_off) & 0xFFFFu;
if (*maxu == 0)
goto fail;
*entries = asvt + asvt_enty_off;
fault_armed = 0;
return 0;
fail:
fault_armed = 0;
return -1;
}
/**
* @brief Walk ASVTENTY and fill one space per live address space.
* @param entries address of ASVTENTY
* @param maxu number of entries to examine
* @param snap output array, indexed by ASID - 1
* @param found receives the number of address spaces that were read
*/
static void ascb_scan(uint32_t entries, unsigned maxu, space *snap,
unsigned *found) {
unsigned i;
*found = 0;
for (i = 0; i < maxu; i++) {
uint32_t entry = read_u32(entries + 4u * i);
if ((entry & 0x80000000u) != 0 || (entry & 0x7FFFFFFFu) == 0)
continue;
if (scan_one(i, entry, entries, &snap[i]) == 0)
(*found)++;
}
}
/** @brief Tag an untagged pipe or file ISO8859-1 before anything writes.
*
* The runtime prints its own diagnostics -- and the ps child prints its
* storage report -- as EBCDIC text, which reaches an ASCII terminal or log
* as a wall of undecodable bytes unless the descriptor says it is text.
* A terminal carries its own tag and is left alone.
* @param fd descriptor to tag when it has no text tag yet
*/
static void tag_untagged(int fd) {
struct stat st;
if (fstat(fd, &st) != 0 || S_ISCHR(st.st_mode))
return;
if (st.st_tag.ft_txtflag && st.st_tag.ft_ccsid != 0)
return;
(void)tag_fd(fd, 819);
}
/** @brief Start ps, which supplies the ASID the process table lacks. */
static FILE *ps_open(void) {
/* NOLINTNEXTLINE(cert-env33-c): ps is the only source of pid-to-ASID. */
return popen("/bin/ps -A -o pid,xasid", "r");
}
/** @brief Read a whole descriptor into a growing buffer.
* @param fd descriptor
* @param out receives the malloc'd, nul-terminated buffer
* @param outlen receives the byte count
* @return 0 on success, -1 on error or out of memory
*/
static int read_all(int fd, char **out, size_t *outlen) {
size_t cap = 16384;
size_t len = 0;
char *buf = malloc(cap + 1);
if (buf == nullptr)
return -1;
for (;;) {
ssize_t n;
if (len == cap) {
char *grown;
if (cap >= (8u << 20)) {
free(buf);
errno = EFBIG;
return -1;
}
grown = realloc(buf, cap * 2 + 1);
if (grown == nullptr) {
free(buf);
return -1;
}
buf = grown;
cap *= 2;
}
n = read(fd, buf + len, cap - len);
if (n < 0) {
if (errno == EINTR)
continue;
free(buf);
return -1;
}
if (n == 0)
break;
len += (size_t)n;
}
buf[len] = '\0';
*out = buf;
*outlen = len;
return 0;
}
/**
* @brief Convert a buffer of untagged ps output to ASCII, in place.
*
* ps writes ASCII when its pipe is tagged ASCII and EBCDIC when it is not;
* the content decides, not the environment. A line ends at LF, NL or the
* EBCDIC 0x25/0x15 code points, which __e2a_l() turns into '\n'.
*/
static void text_to_ascii(char *buf, size_t len) {
size_t i;
for (i = 0; i < len; i++) {
if ((unsigned char)buf[i] >= 0x80) {
__e2a_l(buf, len);
return;
}
}
}
/**
* @brief Tell read() what the pipe carries, using its tag.
* @return 1 = valid ASCII, 2 = the runtime converts (read returns ASCII),
* 0 = untagged, so the bytes must be sniffed after the read
*/
static int read_setup(int fd) {
struct stat st;
if (fstat(fd, &st) == 0 && st.st_tag.ft_txtflag) {
unsigned ccsid = st.st_tag.ft_ccsid;
if (ccsid == 37 || ccsid == 1047) {
if (set_cvt(fd, SETCVTON, 819, (int)ccsid) == 0)
return 2;
} else if (ccsid != 0) {
(void)set_cvt(fd, SETCVTOFF, 0, 0);
return 1;
}
}
(void)set_cvt(fd, SETCVTOFF, 0, 0);
return 0;
}
/** @brief Append one pid-to-ASID pair, growing the map when it is full. */
static int add_pid_asid(pid_asid **map, size_t *n, size_t *cap, pid_t pid,
unsigned asid) {
if (*n == *cap) {
size_t ncap = *cap ? *cap * 2 : 64;
pid_asid *grown = realloc(*map, ncap * sizeof(**map));
if (grown == nullptr)
return -1;
*map = grown;
*cap = ncap;
}
(*map)[*n].pid = pid;
(*map)[*n].asid = asid;
(*n)++;
return 0;
}
/**
* @brief Whether a ps line is the header rather than a process.
*
* ps prints one header line ("PID ASID" on current releases); anything else
* that does not parse is an error, not a line to drop.
*/
static bool is_header(const char *s) {
while (isspace((unsigned char)*s))
s++;
return strncmp(s, "PID", 3) == 0 &&
(s[3] == '\0' || isspace((unsigned char)s[3])) &&
strstr(s, "ASID") != nullptr;
}
/**
* @brief Read /bin/ps -A -o pid,xasid into a sorted pid-to-ASID map.
* @param map receives the malloc'd array
* @param count receives the number of pairs
* @return 0 on success, -1 when ps cannot run or its output does not parse
*/
static int ps_scan(pid_asid **map, size_t *count) {
FILE *fp;
char *buf = nullptr;
size_t len = 0;
size_t n = 0;
size_t cap = 0;
size_t i;
size_t start = 0;
int status;
int mode;
*map = nullptr;
*count = 0;
fp = ps_open();
if (fp == nullptr) {
error_msg("whoson: cannot run /bin/ps: %s\n", strerror(errno));
return -1;
}
mode = read_setup(fileno(fp));
if (read_all(fileno(fp), &buf, &len) != 0) {
error_msg("whoson: cannot read ps output: %s\n", strerror(errno));
pclose(fp);
return -1;
}
status = pclose(fp);
if (status == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
error_msg("whoson: ps failed\n");
free(buf);
return -1;
}
if (mode == 0)
text_to_ascii(buf, len);
/* The buffer is ASCII by now: mode 1 and 2 were read as ASCII, and mode 0
* was converted above, which also turns EBCDIC NL into '\n'. */
for (i = 0; i <= len; i++) {
char c = i < len ? buf[i] : '\n';
if (c != '\n' && c != '\r')
continue;
buf[i < len ? i : len] = '\0';
if (buf[start] != '\0') {
int pid;
unsigned asid;
if (sscanf(&buf[start], "%d %x", &pid, &asid) == 2) {
if (add_pid_asid(map, &n, &cap, (pid_t)pid, asid) != 0) {
error_msg("whoson: out of memory\n");
free(buf);
return -1;
}
} else if (!is_header(&buf[start])) {
error_msg("whoson: cannot parse ps line: %s\n", &buf[start]);
free(*map);
*map = nullptr;
free(buf);
return -1;
}
}
start = i + 1;
}
free(buf);
if (n == 0) {
error_msg("whoson: ps returned no processes\n");
free(*map);
*map = nullptr;
return -1;
}
*count = n;
return 0;
}
/** @brief qsort() order for pid_asid: by pid, then ASID. */
static int cmp_pid_asid(const void *a, const void *b) {
const pid_asid *x = a;
const pid_asid *y = b;
if (x->pid != y->pid)
return x->pid < y->pid ? -1 : 1;
return 0;
}
/** @brief Binary-search a sorted pid_asid map for pid; 0 copies use ASID 0. */
static const pid_asid *find_asid(const pid_asid *map, size_t n, pid_t pid) {
pid_asid key;
key.pid = pid;
key.asid = 0;
return bsearch(&key, map, n, sizeof(*map), cmp_pid_asid);
}
/** @brief qsort() order for proc: by pid. */
static int cmp_proc(const void *a, const void *b) {
const proc *x = a;
const proc *y = b;
if (x->pid != y->pid)
return x->pid < y->pid ? -1 : 1;
return 0;
}
/** @brief Binary-search a sorted process list for pid. */
static const proc *find_proc(const proc *procs, size_t n, pid_t pid) {
proc key = {.pid = pid};
return bsearch(&key, procs, n, sizeof(*procs), cmp_proc);
}
/** @brief Whether a process path is sshd or sshd-session. */
static bool is_sshd(const char *path) {
const char *base = strrchr(path, '/');
base = base != nullptr ? base + 1 : path;
return strcmp(base, "sshd") == 0 || strcmp(base, "sshd-session") == 0;
}
/**
* @brief Whether a process is the sftp subsystem.
*
* It also runs as a child of sshd-session, but it is a file transfer, not a
* login.
*/
static bool is_sftp_server(const char *name) {
return strcmp(name, "sftp-server") == 0 ||
strcmp(name, "internal-sftp") == 0;
}
/** @brief Append one process, keeping only the basename of its path. */
static int append_proc(proc **procs, size_t *n, size_t *cap, const W_PSPROC *ps,
const char *path) {
const char *base;
size_t len;
if (*n == *cap) {
size_t ncap = *cap ? *cap * 2 : 64;
proc *grown = realloc(*procs, ncap * sizeof(**procs));
if (grown == nullptr)
return -1;
*procs = grown;
*cap = ncap;
}
base = strrchr(path, '/');
base = base != nullptr ? base + 1 : path;
len = strlen(base);
if (len >= sizeof((*procs)[*n].name))
len = sizeof((*procs)[*n].name) - 1;
memcpy((*procs)[*n].name, base, len);
(*procs)[*n].name[len] = '\0';
(*procs)[*n].pid = ps->ps_pid;
(*procs)[*n].ppid = ps->ps_ppid;
(*procs)[*n].euid = ps->ps_euid;
(*n)++;
return 0;
}
/**
* @brief Read the process table with w_getpsent into a sorted list.
* @param procs receives the malloc'd array
* @param count receives the number of processes
* @return 0 on success, -1 on a table that cannot be read
*/
static int proc_scan(proc **procs, size_t *count) {
W_PSPROC ps;
char *path;
char *cmd;
char *tty;
size_t n = 0;
size_t cap = 0;
int token = 0;
*procs = nullptr;
*count = 0;
path = malloc(ps_path_buf);
cmd = malloc(cmd_buf);
tty = malloc(tty_buf);
if (path == nullptr || cmd == nullptr || tty == nullptr) {
error_msg("whoson: out of memory\n");
free(path);
free(cmd);
free(tty);
return -1;
}
for (;;) {
int next;
memset(&ps, 0, sizeof(ps));
ps.ps_pathlen = (int)ps_path_buf;
ps.ps_pathptr = path;
ps.ps_cmdlen = (int)cmd_buf;
ps.ps_cmdptr = cmd;
ps.ps_conttylen = (int)tty_buf;
ps.ps_conttyptr = tty;
next = w_getpsent(token, &ps, sizeof(ps));
if (next < 0) {
error_msg("whoson: cannot read the process table: %s\n",
strerror(errno));
free(*procs);
*procs = nullptr;
free(path);
free(cmd);
free(tty);
return -1;
}
if (next == 0)
break;
token = next;
path[ps_path_buf - 1] = '\0';
if (append_proc(procs, &n, &cap, &ps, path) != 0) {
error_msg("whoson: out of memory\n");
free(*procs);
*procs = nullptr;
free(path);
free(cmd);
free(tty);
return -1;
}
}
free(path);
free(cmd);
free(tty);
if (n == 0) {
error_msg("whoson: the process table is empty\n");
free(*procs);
*procs = nullptr;
return -1;
}
qsort(*procs, n, sizeof(**procs), cmp_proc);
*count = n;
return 0;
}
/**
* @brief Whether a logon procedure is one z/OSMF uses.
*
* A logon procedure name from WHOSON_ZOSMF_PROCS; z/OSMF passes the
* procedure it was started with, so the name is the only clue common storage
* has. An unset or empty variable means IZUFPROC, the default in the z/OSMF
* configuration.
*/
static bool logon_is_zosmf(const char *logon) {
const char *list = getenv("WHOSON_ZOSMF_PROCS");
const char *p;
if (logon == nullptr || logon[0] == '\0')
return false;
p = list != nullptr && list[0] != '\0' ? list : "IZUFPROC";
for (;;) {
const char *comma = strchr(p, ',');
const char *end = comma != nullptr ? comma : p + strlen(p);
const char *s = p;
size_t len;
while (s < end && (*s == ' ' || *s == '\t'))
s++;
while (end > s && (end[-1] == ' ' || end[-1] == '\t'))
end--;
len = (size_t)(end - s);
if (len != 0 && len == strlen(logon) && strncmp(s, logon, len) == 0)
return true;
if (comma == nullptr)
break;
p = comma + 1;
}
return false;
}
/** @brief Map a uid to a userid, caching getpwuid() for the rows.
* @param uid effective uid of an SSH process
* @param out output buffer
* @param outlen size of out
*/
static void user_name(uid_t uid, char *out, size_t outlen) {
static struct {
uid_t uid; /**< cached uid */
char name[name_len]; /**< its userid */
} cache[16];
static size_t used;
size_t i;
struct passwd *pw;
for (i = 0; i < used; i++) {
if (cache[i].uid == uid) {
snprintf(out, outlen, "%s", cache[i].name);
return;
}
}
pw = getpwuid(uid);
if (pw != nullptr)
snprintf(cache[used].name, sizeof(cache[used].name), "%s", pw->pw_name);
else
snprintf(cache[used].name, sizeof(cache[used].name), "%u",
(unsigned)uid);
cache[used].uid = uid;
snprintf(out, outlen, "%s", cache[used].name);
if (used + 1 < sizeof(cache) / sizeof(cache[0]))
used++;
}
/** @brief qsort() order for the table: userid, then ASID, then pid. */
static int cmp_rows(const void *a, const void *b) {
const row *x = a;
const row *y = b;
int cmp = strcmp(x->user, y->user);
if (cmp != 0)
return cmp;
if (x->asid != y->asid)
return x->asid < y->asid ? -1 : 1;
if (x->pid != y->pid)
return x->pid < y->pid ? -1 : 1;
return 0;
}
/**
* @brief Format a CPU time as a compact duration.
*
* TOD units are 2^-12 microseconds. The largest unit that keeps it short
* wins: hundredths of a second under a minute, then whole minutes, hours and
* days. A long session could otherwise read 1947:50:11.
* @param us microseconds of CPU
* @param out output buffer
* @param outlen size of out
*/
static void fmt_cpu(uint64_t us, char *out, size_t outlen) {
uint64_t hundredths = (us + 5000u) / 10000u;
uint64_t secs = hundredths / 100u;
if (secs < 60u)
snprintf(out, outlen, "%" PRIu64 ".%02" PRIu64 "s", secs,
hundredths % 100u);
else if (secs < 3600u)
snprintf(out, outlen, "%" PRIu64 "m%02" PRIu64 "s", secs / 60u,
secs % 60u);
else if (secs < 86400u)
snprintf(out, outlen, "%" PRIu64 "h%02" PRIu64 "m", secs / 3600u,
secs % 3600u / 60u);
else
snprintf(out, outlen, "%" PRIu64 "d%02" PRIu64 "h", secs / 86400u,
secs % 86400u / 3600u);
}
/** @brief The table as it is built, so one write carries every row. */
typedef struct outbuf {
char buf[out_len]; /**< formatted rows, not yet written */
size_t len; /**< bytes in buf */
} outbuf;
static void out_add(outbuf *o, const char *fmt, ...) PRINTFLIKE(2, 3);
/** @brief emit() whatever the table has accumulated and reset it. */
static void out_flush(outbuf *o) {
if (o->len != 0)
emit(STDOUT_FILENO, o->buf, o->len);
o->len = 0;
}
/** @brief Append one formatted line to the table, flushing it when full. */
static void out_add(outbuf *o, const char *fmt, ...) {
char line[msg_len];
va_list ap;
int n;
va_start(ap, fmt);
n = vsnprintf(line, sizeof(line), fmt, ap);
va_end(ap);
if (n < 0)
return;
if ((size_t)n >= sizeof(line))
n = (int)sizeof(line) - 1;
if (o->len + (size_t)n > sizeof(o->buf))
out_flush(o);
memcpy(o->buf + o->len, line, (size_t)n);
o->len += (size_t)n;
}
/** @brief Format the header and the rows, one row at a time, and write them. */
static void print_rows(row *rows, size_t n) {
outbuf out;
char cpu[cpu_len];
char asid[asid_len];
char pid[pid_len];
size_t i;
out.len = 0;
out_add(&out, "%-8.8s %-6.6s %-4.4s %-8.8s %-10.10s %-8.8s %s\n", "USER",
"TYPE", "ASID", "JOBNAME", "LOGONPROC", "PID", "CPU");
for (i = 0; i < n; i++) {
fmt_cpu(rows[i].us, cpu, sizeof(cpu));
if (rows[i].asid != 0)
snprintf(asid, sizeof(asid), "%04X", rows[i].asid);
else
snprintf(asid, sizeof(asid), "%s", "-");
if (rows[i].pid > 0)
snprintf(pid, sizeof(pid), "%" PRId32, rows[i].pid);
else
snprintf(pid, sizeof(pid), "%s", "-");
out_add(&out, "%-8.8s %-6.6s %-4.4s %-8.8s %-10.10s %-8.8s %s\n",
rows[i].user, rows[i].type, asid, rows[i].job, rows[i].logon,
pid, cpu);
}
out_flush(&out);
}
/**
* @brief Build the table: one row per TSO/E space, then one per SSH login.
* @param rows output array
* @param maxrows capacity of rows
* @param snap per-ASID state from the ASCB walk
* @param maxu number of entries in snap
* @param procs the process table, sorted by pid
* @param nprocs number of processes
* @param map pid-to-ASID map, sorted by pid
* @param nmap number of pairs
* @return the number of rows written
*/
static int collect(row *rows, size_t maxrows, const space *snap, unsigned maxu,
const proc *procs, size_t nprocs, const pid_asid *map,
size_t nmap) {
size_t n = 0;
unsigned i;
size_t k;
for (i = 0; i < maxu && n < maxrows; i++) {
if (!snap[i].tso)
continue;
rows[n].asid = i + 1;
rows[n].us = snap[i].us;
rows[n].pid = 0;
rows[n].type = logon_is_zosmf(snap[i].logon) ? "z/OSMF" : "TSO/E";
snprintf(rows[n].user, sizeof(rows[n].user), "%s",
snap[i].user[0] != '\0' ? snap[i].user : snap[i].job);
snprintf(rows[n].job, sizeof(rows[n].job), "%s", snap[i].job);
snprintf(rows[n].logon, sizeof(rows[n].logon), "%s",
snap[i].logon[0] != '\0' ? snap[i].logon : "-");
n++;
}
for (k = 0; k < nprocs && n < maxrows; k++) {
const proc *parent;
const pid_asid *pa;
unsigned asid = 0;
uint64_t us = 0;
const char *job = "-";
parent = find_proc(procs, nprocs, procs[k].ppid);
if (parent == nullptr || !is_sshd(parent->name) ||
is_sshd(procs[k].name) || is_sftp_server(procs[k].name))
continue;
pa = find_asid(map, nmap, procs[k].pid);
if (pa != nullptr && pa->asid >= 1 && pa->asid <= maxu) {
asid = pa->asid;
us = snap[asid - 1].us;
if (snap[asid - 1].job[0] != '\0')
job = snap[asid - 1].job;
}
rows[n].asid = asid;
rows[n].us = us;
rows[n].pid = procs[k].pid;
rows[n].type = "SSH";
snprintf(rows[n].job, sizeof(rows[n].job), "%s", job);
snprintf(rows[n].logon, sizeof(rows[n].logon), "%s", "-");
user_name(procs[k].euid, rows[n].user, sizeof(rows[n].user));
n++;
}
return (int)n;
}
/** @brief Walk common storage and the process table, and print the sessions.
* @return 0 on success, 1 on a read, memory or output failure
*/
int main(int argc, char **argv) {
space *snap;
row *rows;
proc *procs;
pid_asid *map;
size_t nmap;
size_t nprocs;
unsigned maxu;
unsigned found;
uint32_t entries;
int nrows;
int arg;
tag_untagged(STDOUT_FILENO);
tag_untagged(STDERR_FILENO);
save_cvt(STDOUT_FILENO);
save_cvt(STDERR_FILENO);
(void)atexit(restore_cvt);
for (arg = 1; arg < argc; arg++) {
if (strcmp(argv[arg], "-h") == 0 || strcmp(argv[arg], "--help") == 0) {
emit_str(STDOUT_FILENO, usage_text);
return output_failed ? 1 : 0;
} else if (strcmp(argv[arg], "-V") == 0 ||
strcmp(argv[arg], "--version") == 0) {
emit_str(STDOUT_FILENO, "whoson " WHOSON_VERSION "\n");
return output_failed ? 1 : 0;
} else {
usage_error("whoson: unknown argument: %s", argv[arg]);
return 1;
}
}
guard();
if (read_asvt(&maxu, &entries) != 0) {
unguard();
error_msg("whoson: cannot read the ASVT\n");
return 1;
}
snap = calloc((size_t)maxu, sizeof(*snap));
if (snap == nullptr) {
unguard();
error_msg("whoson: out of memory for %u address spaces\n", maxu);
return 1;
}
ascb_scan(entries, maxu, snap, &found);
unguard();
if (found == 0) {
free(snap);
error_msg("whoson: no address spaces found\n");
return 1;
}
if (ps_scan(&map, &nmap) != 0) {
free(snap);
return 1;
}
if (proc_scan(&procs, &nprocs) != 0) {
free(map);
free(snap);
return 1;
}
qsort(map, nmap, sizeof(*map), cmp_pid_asid);
/* At most one TSO row per address space and one SSH row per process, so
* the table can hold both lists; maxu alone would drop SSH sessions on a
* system that shares address spaces (_BPX_SHAREAS). */
rows = calloc((size_t)maxu + nprocs, sizeof(*rows));
if (rows == nullptr) {
error_msg("whoson: out of memory for the session table\n");
free(procs);
free(map);
free(snap);
return 1;
}
nrows = collect(rows, (size_t)maxu + nprocs, snap, maxu, procs, nprocs, map,
nmap);
qsort(rows, (size_t)nrows, sizeof(*rows), cmp_rows);
print_rows(rows, (size_t)nrows);
free(rows);
free(procs);
free(map);
free(snap);
return output_failed ? 1 : 0;
}
|