1 /* $NetBSD: w.c,v 1.93 2022/05/26 06:48:36 wiz Exp $ */
2
3 /*-
4 * Copyright (c) 1980, 1991, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1980, 1991, 1993, 1994\
35 The Regents of the University of California. All rights reserved.");
36 #endif /* not lint */
37
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)w.c 8.6 (Berkeley) 6/30/94";
41 #else
42 __RCSID("$NetBSD: w.c,v 1.93 2022/05/26 06:48:36 wiz Exp $");
43 #endif
44 #endif /* not lint */
45
46 /*
47 * w - print system status (who and what)
48 *
49 * This program is similar to the systat command on Tenex/Tops 10/20
50 *
51 */
52 #include <sys/param.h>
53 #include <sys/types.h>
54 #include <sys/time.h>
55 #include <sys/stat.h>
56 #include <sys/sysctl.h>
57 #include <sys/proc.h>
58 #include <sys/ioctl.h>
59 #include <sys/socket.h>
60
61 #include <netinet/in.h>
62 #include <arpa/inet.h>
63
64 #include <ctype.h>
65 #include <err.h>
66 #include <errno.h>
67 #include <fcntl.h>
68 #include <kvm.h>
69 #include <limits.h>
70 #include <netdb.h>
71 #include <nlist.h>
72 #include <paths.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <time.h>
77 #include <tzfile.h>
78 #include <unistd.h>
79 #ifdef SUPPORT_UTMP
80 #include <utmp.h>
81 #endif
82 #ifdef SUPPORT_UTMPX
83 #include <utmpx.h>
84 #endif
85 #include <vis.h>
86
87 #include "extern.h"
88
89 struct timespec boottime;
90 struct winsize ws;
91 kvm_t *kd;
92 time_t now; /* the current time of day */
93 int ttywidth; /* width of tty */
94 int argwidth; /* width of tty left to print process args */
95 int header = 1; /* true if -h flag: don't print heading */
96 int nflag; /* true if -n flag: don't convert addrs */
97 int wflag; /* true if -w flag: wide printout */
98 int sortidle; /* sort by idle time */
99 int alphasort; /* sort by tty alphabeta, not numeric */
100 char *sel_user; /* login of particular user selected */
101 char domain[MAXHOSTNAMELEN + 1];
102 int maxname = 8, maxline = 3, maxhost = 16;
103
104 /*
105 * One of these per active utmp entry.
106 */
107 struct entry {
108 struct entry *next;
109 char name[UTX_USERSIZE + 1];
110 char line[UTX_LINESIZE + 1];
111 char host[UTX_HOSTSIZE + 1];
112 char type[2];
113 struct timeval tv;
114 dev_t tdev; /* dev_t of terminal */
115 time_t idle; /* idle time of terminal in seconds */
116 struct kinfo_proc2 *tp; /* `most interesting' tty proc */
117 struct kinfo_proc2 *pp; /* pid proc */
118 pid_t pid; /* pid or ~0 if not known */
119 } *ehead = NULL, **nextp = &ehead;
120
121 static void pr_args(struct kinfo_proc2 *);
122 static void pr_header(time_t *, int);
123 static int proc_compare_wrapper(const struct kinfo_proc2 *,
124 const struct kinfo_proc2 *);
125 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
126 static int ttystat(const char *, struct stat *);
127 static void process(struct entry *);
128 #endif
129 static void fixhost(struct entry *ep);
130 __dead static void usage(int);
131
132 int
main(int argc,char ** argv)133 main(int argc, char **argv)
134 {
135 struct kinfo_proc2 *kp;
136 struct entry *ep;
137 int ch, i, nentries, nusers, wcmd, curtain, use_sysctl;
138 char *memf, *nlistf, *usrnp;
139 const char *options;
140 time_t then;
141 size_t len;
142 #ifdef SUPPORT_UTMP
143 struct utmp *ut;
144 #endif
145 #ifdef SUPPORT_UTMPX
146 struct utmpx *utx;
147 #endif
148 const char *progname;
149 char errbuf[_POSIX2_LINE_MAX];
150
151 setprogname(argv[0]);
152
153 /* Are we w(1) or uptime(1)? */
154 progname = getprogname();
155 if (*progname == '-')
156 progname++;
157 if (*progname == 'u') {
158 wcmd = 0;
159 options = "";
160 } else {
161 wcmd = 1;
162 options = "AhiM:N:nw";
163 }
164
165 memf = nlistf = NULL;
166 while ((ch = getopt(argc, argv, options)) != -1)
167 switch (ch) {
168 case 'A':
169 alphasort = 1;
170 break;
171 case 'h':
172 header = 0;
173 break;
174 case 'i':
175 sortidle = 1;
176 break;
177 case 'M':
178 header = 0;
179 memf = optarg;
180 break;
181 case 'N':
182 nlistf = optarg;
183 break;
184 case 'n':
185 nflag = 1;
186 break;
187 case 'w':
188 wflag = 1;
189 break;
190 case '?':
191 default:
192 usage(wcmd);
193 }
194 argc -= optind;
195 argv += optind;
196
197 use_sysctl = (memf == NULL && nlistf == NULL);
198
199 if ((kd = kvm_openfiles(nlistf, memf, NULL,
200 memf == NULL ? KVM_NO_FILES : O_RDONLY, errbuf)) == NULL)
201 errx(1, "%s", errbuf);
202
203 (void)time(&now);
204
205 if (use_sysctl) {
206 len = sizeof(curtain);
207 if (sysctlbyname("security.curtain", &curtain, &len,
208 NULL, 0) == -1)
209 curtain = 0;
210 }
211
212 if (!nflag) {
213 int rv;
214 char *p;
215
216 rv = gethostname(domain, sizeof(domain));
217 domain[sizeof(domain) - 1] = '\0';
218 if (rv < 0 || (p = strchr(domain, '.')) == 0)
219 domain[0] = '\0';
220 else
221 memmove(domain, p, strlen(p) + 1);
222 }
223
224 #ifdef SUPPORT_UTMPX
225 setutxent();
226 #endif
227 #ifdef SUPPORT_UTMP
228 setutent();
229 #endif
230
231 if (*argv)
232 sel_user = *argv;
233
234 nusers = 0;
235 #ifdef SUPPORT_UTMPX
236 while ((utx = getutxent()) != NULL) {
237 if (utx->ut_type != USER_PROCESS)
238 continue;
239 ++nusers;
240
241 #ifndef SUPPORT_UTMP
242 if (wcmd == 0)
243 continue;
244 #endif /* !SUPPORT_UTMP */
245
246 if (sel_user &&
247 strncmp(utx->ut_name, sel_user, sizeof(utx->ut_name)) != 0)
248 continue;
249 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
250 err(1, NULL);
251 (void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
252 ep->line[sizeof(utx->ut_line)] = '\0';
253 *nextp = ep;
254 nextp = &(ep->next);
255
256 if (wcmd == 0)
257 continue;
258
259 (void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
260 ep->name[sizeof(utx->ut_name)] = '\0';
261 if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
262 utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
263 NI_NUMERICHOST) != 0) {
264 (void)memcpy(ep->host, utx->ut_host,
265 sizeof(utx->ut_host));
266 ep->host[sizeof(utx->ut_host)] = '\0';
267 }
268 fixhost(ep);
269 ep->type[0] = 'x';
270 ep->tv = utx->ut_tv;
271 ep->pid = utx->ut_pid;
272 process(ep);
273 }
274 #endif
275
276 #ifdef SUPPORT_UTMP
277 while ((ut = getutent()) != NULL) {
278 if (ut->ut_name[0] == '\0')
279 continue;
280
281 if (sel_user &&
282 strncmp(ut->ut_name, sel_user, sizeof(ut->ut_name)) != 0)
283 continue;
284
285 /* Don't process entries that we have utmpx for */
286 for (ep = ehead; ep != NULL; ep = ep->next) {
287 if (strncmp(ep->line, ut->ut_line,
288 sizeof(ut->ut_line)) == 0)
289 break;
290 }
291 if (ep != NULL)
292 continue;
293
294 ++nusers;
295
296 if (wcmd == 0)
297 continue;
298
299 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
300 err(1, NULL);
301 (void)memcpy(ep->name, ut->ut_name, sizeof(ut->ut_name));
302 (void)memcpy(ep->line, ut->ut_line, sizeof(ut->ut_line));
303 (void)memcpy(ep->host, ut->ut_host, sizeof(ut->ut_host));
304 ep->name[sizeof(ut->ut_name)] = '\0';
305 ep->line[sizeof(ut->ut_line)] = '\0';
306 ep->host[sizeof(ut->ut_host)] = '\0';
307 fixhost(ep);
308 ep->tv.tv_sec = ut->ut_time;
309 *nextp = ep;
310 nextp = &(ep->next);
311 process(ep);
312 }
313 #endif
314
315 #ifdef SUPPORT_UTMPX
316 endutxent();
317 #endif
318 #ifdef SUPPORT_UTMP
319 endutent();
320 #endif
321
322 if (header || wcmd == 0) {
323 pr_header(&now, nusers);
324 if (wcmd == 0)
325 exit (0);
326 }
327
328 if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
329 sizeof(struct kinfo_proc2), &nentries)) == NULL)
330 errx(1, "%s", kvm_geterr(kd));
331
332 /* Include trailing space because TTY header starts one column early. */
333 for (i = 0; i < nentries; i++, kp++) {
334
335 for (ep = ehead; ep != NULL; ep = ep->next) {
336 if (ep->tdev != 0 && ep->tdev == kp->p_tdev &&
337 kp->p__pgid == kp->p_tpgid) {
338 /*
339 * Proc is in foreground of this
340 * terminal
341 */
342 if (proc_compare_wrapper(ep->tp, kp))
343 ep->tp = kp;
344 break;
345 }
346 if (ep->pid != 0 && ep->pid == kp->p_pid) {
347 ep->pp = kp;
348 break;
349 }
350 }
351 }
352
353 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
354 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
355 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
356 ttywidth = 79;
357 else
358 ttywidth = ws.ws_col - 1;
359
360 if (!wflag && maxhost > (ttywidth / 3))
361 maxhost = ttywidth / 3;
362
363 argwidth = printf("%-*s TTY %-*s %*s IDLE WHAT\n",
364 maxname, "USER", maxhost, "FROM",
365 7 /* "dddhhXm" */, "LOGIN@");
366 argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
367 argwidth = ttywidth - argwidth;
368 if (argwidth < 4)
369 argwidth = 8;
370 if (wflag)
371 argwidth = -1;
372
373 /* sort by idle time */
374 if (sortidle && ehead != NULL) {
375 struct entry *from = ehead, *save;
376
377 ehead = NULL;
378 while (from != NULL) {
379 for (nextp = &ehead;
380 (*nextp) && from->idle >= (*nextp)->idle;
381 nextp = &(*nextp)->next)
382 continue;
383 save = from;
384 from = from->next;
385 save->next = *nextp;
386 *nextp = save;
387 }
388 }
389 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
390 else if (ehead != NULL && alphasort) {
391 struct entry *from = ehead, *save;
392
393 ehead = NULL;
394 while (from != NULL) {
395 for (nextp = &ehead;
396 (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
397 nextp = &(*nextp)->next)
398 continue;
399 save = from;
400 from = from->next;
401 save->next = *nextp;
402 *nextp = save;
403 }
404 }
405 #endif
406
407 for (ep = ehead; ep != NULL; ep = ep->next) {
408 if (ep->tp != NULL)
409 kp = ep->tp;
410 else if (ep->pp != NULL)
411 kp = ep->pp;
412 else if (ep->pid != 0) {
413 if (curtain)
414 kp = NULL;
415 else {
416 warnx("Stale utmp%s entry: %s %s %s",
417 ep->type, ep->name, ep->line, ep->host);
418 continue;
419 }
420 }
421 usrnp = (kp == NULL) ? ep->name : kp->p_login;
422 (void)printf("%-*s %-7.7s %-*.*s ",
423 maxname, usrnp, ep->line,
424 maxhost, maxhost, ep->host);
425 then = (time_t)ep->tv.tv_sec;
426 pr_attime(&then, &now);
427 pr_idle(ep->idle);
428 pr_args(kp);
429 (void)printf("\n");
430 }
431 exit(0);
432 }
433
434 static void
pr_args(struct kinfo_proc2 * kp)435 pr_args(struct kinfo_proc2 *kp)
436 {
437 char **argv;
438 int left;
439
440 if (kp == 0)
441 goto nothing;
442 left = argwidth;
443 argv = kvm_getargv2(kd, kp, (argwidth < 0) ? 0 : argwidth);
444 if (argv == 0) {
445 fmt_putc('(', &left);
446 fmt_puts((char *)kp->p_comm, &left);
447 fmt_putc(')', &left);
448 return;
449 }
450 while (*argv) {
451 fmt_puts(*argv, &left);
452 argv++;
453 fmt_putc(' ', &left);
454 }
455 return;
456 nothing:
457 putchar('-');
458 }
459
460 static void
pr_header(time_t * nowp,int nusers)461 pr_header(time_t *nowp, int nusers)
462 {
463 double avenrun[3];
464 time_t uptime;
465 int days, hrs, mins;
466 int mib[2];
467 size_t size, i;
468 char buf[256];
469
470 /*
471 * Print time of day.
472 */
473 (void)strftime(buf, sizeof(buf), "%l:%M%p", localtime(nowp));
474 buf[sizeof(buf) - 1] = '\0';
475 (void)printf("%s ", buf);
476
477 /*
478 * Print how long system has been up.
479 * (Found by looking getting "boottime" from the kernel)
480 */
481 mib[0] = CTL_KERN;
482 mib[1] = KERN_BOOTTIME;
483 size = sizeof(boottime);
484 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
485 boottime.tv_sec != 0) {
486 uptime = now - boottime.tv_sec;
487 uptime += 30;
488 if (uptime > SECSPERMIN) {
489 days = uptime / SECSPERDAY;
490 uptime %= SECSPERDAY;
491 hrs = uptime / SECSPERHOUR;
492 uptime %= SECSPERHOUR;
493 mins = uptime / SECSPERMIN;
494 (void)printf(" up");
495 if (days > 0)
496 (void)printf(" %d day%s,", days,
497 days > 1 ? "s" : "");
498 if (hrs > 0 && mins > 0)
499 (void)printf(" %2d:%02d,", hrs, mins);
500 else {
501 if (hrs > 0)
502 (void)printf(" %d hr%s,",
503 hrs, hrs > 1 ? "s" : "");
504 if (mins > 0)
505 (void)printf(" %d min%s,",
506 mins, mins > 1 ? "s" : "");
507 }
508 }
509 }
510
511 /* Print number of users logged in to system */
512 (void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
513
514 /*
515 * Print 1, 5, and 15 minute load averages.
516 */
517 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
518 (void)printf(", no load average information available\n");
519 else {
520 (void)printf(", load averages:");
521 for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
522 if (i > 0)
523 (void)printf(",");
524 (void)printf(" %.2f", avenrun[i]);
525 }
526 (void)printf("\n");
527 }
528 }
529
530 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
531 static int
ttystat(const char * line,struct stat * st)532 ttystat(const char *line, struct stat *st)
533 {
534 char ttybuf[MAXPATHLEN];
535
536 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
537 return stat(ttybuf, st);
538 }
539
540 static void
process(struct entry * ep)541 process(struct entry *ep)
542 {
543 struct stat st;
544 time_t touched;
545 int max;
546
547 if ((max = strlen(ep->name)) > maxname)
548 maxname = max;
549 if ((max = strlen(ep->line)) > maxline)
550 maxline = max;
551 if ((max = strlen(ep->host)) > maxhost)
552 maxhost = max;
553
554 ep->tdev = 0;
555 ep->idle = (time_t)-1;
556
557 #ifdef SUPPORT_UTMP
558 /*
559 * Hack to recognize and correctly parse
560 * ut entry made by ftpd. The "tty" used
561 * by ftpd is not a real tty, just identifier in
562 * form ftpPID. Pid parsed from the "tty name"
563 * is used later to match corresponding process.
564 * NB: This is only used for utmp entries. For utmpx,
565 * we already have the pid.
566 */
567 if (ep->pid == 0 && strncmp(ep->line, "ftp", 3) == 0) {
568 ep->pid = strtol(ep->line + 3, NULL, 10);
569 return;
570 }
571 #endif
572 if (ttystat(ep->line, &st) == -1)
573 return;
574
575 ep->tdev = st.st_rdev;
576 /*
577 * If this is the console device, attempt to ascertain
578 * the true console device dev_t.
579 */
580 if (ep->tdev == 0) {
581 int mib[2];
582 size_t size;
583
584 mib[0] = CTL_KERN;
585 mib[1] = KERN_CONSDEV;
586 size = sizeof(dev_t);
587 (void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
588 }
589
590 touched = st.st_atime;
591 if (touched < ep->tv.tv_sec) {
592 /* tty untouched since before login */
593 touched = ep->tv.tv_sec;
594 }
595 if ((ep->idle = now - touched) < 0)
596 ep->idle = 0;
597 }
598 #endif
599
600 static int
proc_compare_wrapper(const struct kinfo_proc2 * p1,const struct kinfo_proc2 * p2)601 proc_compare_wrapper(const struct kinfo_proc2 *p1,
602 const struct kinfo_proc2 *p2)
603 {
604 struct kinfo_lwp *l1, *l2;
605 int cnt;
606
607 if (p1 == NULL)
608 return 1;
609
610 l1 = kvm_getlwps(kd, p1->p_pid, 0, sizeof(*l1), &cnt);
611 if (l1 == NULL || cnt == 0)
612 return 1;
613
614 l2 = kvm_getlwps(kd, p2->p_pid, 0, sizeof(*l1), &cnt);
615 if (l2 == NULL || cnt == 0)
616 return 0;
617
618 return proc_compare(p1, l1, p2, l2);
619 }
620
621 static void
fixhost(struct entry * ep)622 fixhost(struct entry *ep)
623 {
624 char host_buf[sizeof(ep->host)];
625 char *b, *m, *p, *r, *x;
626 struct hostent *hp;
627 union {
628 struct in_addr l4;
629 struct in6_addr l6;
630 } l;
631
632 strlcpy(host_buf, *ep->host ? ep->host : "-", sizeof(host_buf));
633 p = host_buf;
634
635 /*
636 * One ':' in hostname means X display number, more is IPv6.
637 */
638 for (x = p; x < &host_buf[sizeof(host_buf)]; x++)
639 if (*x == '\0' || *x == ':')
640 break;
641 if (x == p + sizeof(host_buf) || *x != ':')
642 m = x = NULL;
643 else {
644 for (m = x + 1; m < &host_buf[sizeof(host_buf)]; m++)
645 if (*m == '\0' || *m == ':')
646 break;
647 if (m == p + sizeof(host_buf) || *m != ':') {
648 *x++ = '\0';
649 m = NULL;
650 } else
651 x = NULL;
652 }
653
654 /*
655 * Leading '[' indicates an IP address inside brackets.
656 */
657 b = NULL;
658 if (!nflag && (*p == '[')) {
659 for (b = p++; b < &host_buf[sizeof(host_buf)]; b++)
660 if (*b == '\0' || *b == ']')
661 break;
662 if (b < &host_buf[sizeof(host_buf)] && *b == ']') {
663 *b = '\0';
664 for (x = b + 1; x < &host_buf[sizeof(host_buf)]; x++)
665 if (*x == '\0' || *x == ':')
666 break;
667 if (x < &host_buf[sizeof(host_buf)] && *x == ':')
668 *x++ = '\0';
669 } else
670 b = NULL;
671 }
672
673 int af = m ? AF_INET6 : AF_INET;
674 size_t alen = m ? sizeof(l.l6) : sizeof(l.l4);
675 if (!nflag && inet_pton(af, p, &l) &&
676 (hp = gethostbyaddr((char *)&l, alen, af)))
677 r = hp->h_name;
678 else {
679 if (b)
680 *b = ']';
681 r = host_buf;
682 }
683
684 if (domain[0] != '\0') {
685 p = r;
686 p += strlen(r);
687 p -= strlen(domain);
688 if (p > r &&
689 strcasecmp(p, domain) == 0)
690 *p = '\0';
691 }
692
693 if (x)
694 (void)snprintf(ep->host, sizeof(ep->host), "%s:%s", r, x);
695 else
696 strlcpy(ep->host, r, sizeof(ep->host));
697 }
698
699 static void
usage(int wcmd)700 usage(int wcmd)
701 {
702
703 if (wcmd)
704 (void)fprintf(stderr,
705 "Usage: %s [-Ahinw] [-M core] [-N system] [user]\n",
706 getprogname());
707 else
708 (void)fprintf(stderr, "Usage: %s\n", getprogname());
709 exit(1);
710 }
711