w.c revision 1.69 1 /* $NetBSD: w.c,v 1.69 2005/09/04 19:02:08 elad 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\n\
35 The Regents of the University of California. All rights reserved.\n");
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.69 2005/09/04 19:02:08 elad 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/user.h>
59 #include <sys/ioctl.h>
60 #include <sys/socket.h>
61
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64
65 #include <ctype.h>
66 #include <err.h>
67 #include <errno.h>
68 #include <fcntl.h>
69 #include <kvm.h>
70 #include <limits.h>
71 #include <netdb.h>
72 #include <nlist.h>
73 #include <paths.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <time.h>
78 #include <tzfile.h>
79 #include <unistd.h>
80 #ifdef SUPPORT_UTMP
81 #include <utmp.h>
82 #endif
83 #ifdef SUPPORT_UTMPX
84 #include <utmpx.h>
85 #endif
86 #include <vis.h>
87
88 #include "extern.h"
89
90 struct timeval boottime;
91 struct winsize ws;
92 kvm_t *kd;
93 time_t now; /* the current time of day */
94 time_t uptime; /* time of last reboot & elapsed time since */
95 int ttywidth; /* width of tty */
96 int argwidth; /* width of tty left to print process args */
97 int header = 1; /* true if -h flag: don't print heading */
98 int nflag; /* true if -n flag: don't convert addrs */
99 int wflag; /* true if -w flag: wide printout */
100 int sortidle; /* sort bu idle time */
101 char *sel_user; /* login of particular user selected */
102 char domain[MAXHOSTNAMELEN + 1];
103 int maxname = 8, maxline = 3, maxhost = 16;
104 int use_sysctl;
105
106 /*
107 * One of these per active utmp entry.
108 */
109 struct entry {
110 struct entry *next;
111 char name[65];
112 char line[65];
113 char host[257];
114 char type[2];
115 struct timeval tv;
116 dev_t tdev; /* dev_t of terminal */
117 time_t idle; /* idle time of terminal in seconds */
118 struct kinfo_proc2 *tp; /* `most interesting' tty proc */
119 struct kinfo_proc2 *pp; /* pid proc */
120 pid_t pid; /* pid or ~0 if not known */
121 } *ep, *ehead = NULL, **nextp = &ehead;
122
123 static void pr_args(struct kinfo_proc2 *);
124 static void pr_header(time_t *, int);
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 usage(int);
130
131 int main(int, char **);
132
133 int
134 main(int argc, char **argv)
135 {
136 struct kinfo_proc2 *kp;
137 struct hostent *hp;
138 struct in_addr l;
139 int ch, i, nentries, nusers, wcmd;
140 char *memf, *nlistf, *p, *x;
141 time_t then;
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 buf[MAXHOSTNAMELEN], 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 p = "";
160 } else {
161 wcmd = 1;
162 p = "hiM:N:nw";
163 }
164
165 memf = nlistf = NULL;
166 while ((ch = getopt(argc, argv, p)) != -1)
167 switch (ch) {
168 case 'h':
169 header = 0;
170 break;
171 case 'i':
172 sortidle = 1;
173 break;
174 case 'M':
175 header = 0;
176 memf = optarg;
177 break;
178 case 'N':
179 nlistf = optarg;
180 break;
181 case 'n':
182 nflag = 1;
183 break;
184 case 'w':
185 wflag = 1;
186 break;
187 case '?':
188 default:
189 usage(wcmd);
190 }
191 argc -= optind;
192 argv += optind;
193
194 use_sysctl = (memf == NULL && nlistf == NULL);
195
196 if (!use_sysctl) {
197 if ((kd = kvm_openfiles(nlistf, memf, NULL,
198 memf == NULL ? KVM_NO_FILES : O_RDONLY, errbuf)) == NULL)
199 errx(1, "%s", errbuf);
200 }
201
202 (void)time(&now);
203
204 #ifdef SUPPORT_UTMPX
205 setutxent();
206 #endif
207 #ifdef SUPPORT_UTMP
208 setutent();
209 #endif
210
211 if (*argv)
212 sel_user = *argv;
213
214 nusers = 0;
215 #ifdef SUPPORT_UTMPX
216 while ((utx = getutxent()) != NULL) {
217 if (utx->ut_type != USER_PROCESS)
218 continue;
219 ++nusers;
220 if (sel_user &&
221 strncmp(utx->ut_name, sel_user, sizeof(utx->ut_name)) != 0)
222 continue;
223 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
224 err(1, NULL);
225 (void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
226 (void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
227 ep->name[sizeof(utx->ut_name)] = '\0';
228 ep->line[sizeof(utx->ut_line)] = '\0';
229 if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
230 utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
231 NI_NUMERICHOST) != 0) {
232 (void)memcpy(ep->host, utx->ut_host,
233 sizeof(utx->ut_host));
234 ep->host[sizeof(utx->ut_host)] = '\0';
235 }
236 ep->type[0] = 'x';
237 ep->tv = utx->ut_tv;
238 ep->pid = utx->ut_pid;
239 *nextp = ep;
240 nextp = &(ep->next);
241 if (wcmd != 0)
242 process(ep);
243 }
244 #endif
245
246 #ifdef SUPPORT_UTMP
247 while ((ut = getutent()) != NULL) {
248 if (ut->ut_name[0] == '\0')
249 continue;
250
251 if (sel_user &&
252 strncmp(ut->ut_name, sel_user, sizeof(ut->ut_name)) != 0)
253 continue;
254
255 /* Don't process entries that we have utmpx for */
256 for (ep = ehead; ep != NULL; ep = ep->next) {
257 if (strncmp(ep->line, ut->ut_line,
258 sizeof(ut->ut_line)) == 0)
259 break;
260 }
261 if (ep != NULL)
262 continue;
263
264 ++nusers;
265 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
266 err(1, NULL);
267 (void)memcpy(ep->name, ut->ut_name, sizeof(ut->ut_name));
268 (void)memcpy(ep->line, ut->ut_line, sizeof(ut->ut_line));
269 (void)memcpy(ep->host, ut->ut_host, sizeof(ut->ut_host));
270 ep->name[sizeof(ut->ut_name)] = '\0';
271 ep->line[sizeof(ut->ut_line)] = '\0';
272 ep->host[sizeof(ut->ut_host)] = '\0';
273 ep->tv.tv_sec = ut->ut_time;
274 *nextp = ep;
275 nextp = &(ep->next);
276 if (wcmd != 0)
277 process(ep);
278 }
279 #endif
280
281 #ifdef SUPPORT_UTMPX
282 endutxent();
283 #endif
284 #ifdef SUPPORT_UTMP
285 endutent();
286 #endif
287
288 if (header || wcmd == 0) {
289 pr_header(&now, nusers);
290 if (wcmd == 0)
291 exit (0);
292 }
293
294 if (use_sysctl) {
295 int mib[6] = { CTL_KERN, KERN_PROC2, KERN_PROC_ALL, 0, sizeof(*kp), 0 };
296 size_t size;
297
298 if (sysctl(mib, 6, NULL, &size, NULL, 0) == -1)
299 err(1, "sysctl (query)");
300
301 if ((kp = malloc(size)) == NULL)
302 err(1, "malloc");
303 memset(kp, 0, size);
304
305 mib[5] = size / sizeof(*kp);
306
307 if (sysctl(mib, 6, kp, &size, NULL, 0) == -1)
308 err(1, "sysctl (copy)");
309
310 nentries = size / sizeof(*kp);
311 } else {
312 if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
313 sizeof(struct kinfo_proc2), &nentries)) == NULL)
314 errx(1, "%s", kvm_geterr(kd));
315 }
316
317 /* Include trailing space because TTY header starts one column early. */
318 for (i = 0; i < nentries; i++, kp++) {
319
320 if (kp->p_stat == SIDL || kp->p_stat == SZOMB)
321 continue;
322
323 for (ep = ehead; ep != NULL; ep = ep->next) {
324 if (ep->tdev != 0 && ep->tdev == kp->p_tdev &&
325 kp->p__pgid == kp->p_tpgid) {
326 /*
327 * Proc is in foreground of this
328 * terminal
329 */
330 if (proc_compare(ep->tp, kp))
331 ep->tp = kp;
332 break;
333 }
334 if (ep->pid != 0 && ep->pid == kp->p_pid) {
335 ep->pp = kp;
336 break;
337 }
338 }
339 }
340
341 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
342 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
343 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
344 ttywidth = 79;
345 else
346 ttywidth = ws.ws_col - 1;
347
348 if (!wflag && maxhost > (ttywidth / 3))
349 maxhost = ttywidth / 3;
350
351 argwidth = printf("%-*s TTY %-*s %*s IDLE WHAT\n",
352 maxname, "USER", maxhost, "FROM",
353 7 /* "dddhhXm" */, "LOGIN@");
354 argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
355 argwidth = ttywidth - argwidth;
356 if (argwidth < 4)
357 argwidth = 8;
358 if (wflag)
359 argwidth = -1;
360
361 /* sort by idle time */
362 if (sortidle && ehead != NULL) {
363 struct entry *from = ehead, *save;
364
365 ehead = NULL;
366 while (from != NULL) {
367 for (nextp = &ehead;
368 (*nextp) && from->idle >= (*nextp)->idle;
369 nextp = &(*nextp)->next)
370 continue;
371 save = from;
372 from = from->next;
373 save->next = *nextp;
374 *nextp = save;
375 }
376 }
377 #if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
378 else if (ehead != NULL) {
379 struct entry *from = ehead, *save;
380
381 ehead = NULL;
382 while (from != NULL) {
383 for (nextp = &ehead;
384 (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
385 nextp = &(*nextp)->next)
386 continue;
387 save = from;
388 from = from->next;
389 save->next = *nextp;
390 *nextp = save;
391 }
392 }
393 #endif
394
395 if (!nflag) {
396 int rv;
397
398 rv = gethostname(domain, sizeof(domain));
399 domain[sizeof(domain) - 1] = '\0';
400 if (rv < 0 || (p = strchr(domain, '.')) == 0)
401 domain[0] = '\0';
402 else
403 memmove(domain, p, strlen(p) + 1);
404 }
405
406 for (ep = ehead; ep != NULL; ep = ep->next) {
407 char host_buf[MAXHOSTNAMELEN + 1];
408
409 strlcpy(host_buf, ep->host, sizeof(host_buf));
410 p = *host_buf ? host_buf : "-";
411
412 for (x = p; x < p + MAXHOSTNAMELEN; x++)
413 if (*x == '\0' || *x == ':')
414 break;
415 if (x == p + MAXHOSTNAMELEN || *x != ':')
416 x = NULL;
417 else
418 *x++ = '\0';
419
420 if (!nflag && inet_aton(p, &l) &&
421 (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
422 if (domain[0] != '\0') {
423 p = hp->h_name;
424 p += strlen(hp->h_name);
425 p -= strlen(domain);
426 if (p > hp->h_name &&
427 strcasecmp(p, domain) == 0)
428 *p = '\0';
429 }
430 p = hp->h_name;
431 }
432 if (x) {
433 (void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
434 p = buf;
435 }
436 if (ep->tp != NULL)
437 kp = ep->tp;
438 else if (ep->pp != NULL)
439 kp = ep->pp;
440 else {
441 warnx("Stale utmp%s entry: %s %s %s",
442 ep->type, ep->name, ep->line, ep->host);
443 continue;
444 }
445 (void)printf("%-*s %-7.7s %-*.*s ",
446 maxname, kp->p_login, ep->line,
447 maxhost, maxhost, *p ? p : "-");
448 then = (time_t)ep->tv.tv_sec;
449 pr_attime(&then, &now);
450 pr_idle(ep->idle);
451 pr_args(kp);
452 (void)printf("\n");
453 }
454 exit(0);
455 }
456
457 static void
458 pr_args(struct kinfo_proc2 *kp)
459 {
460 char **argv;
461 int left;
462
463 if (kp == 0)
464 goto nothing;
465 left = argwidth;
466
467 if (use_sysctl) {
468 char *a = NULL;
469 size_t size;
470 int mib[4] = { CTL_KERN, KERN_PROC_ARGS, kp->p_pid, KERN_PROC_NARGV };
471 int nargv;
472
473 size = sizeof(nargv);
474 if (sysctl(mib, 4, &nargv, &size, NULL, 0) == -1)
475 err(1, "sysctl (nargv)");
476
477 size = ARG_MAX;
478
479 argv = malloc(size);
480 memset(argv, 0, size);
481
482 mib[3] = KERN_PROC_ARGV;
483
484 if (sysctl(mib, 4, argv, &size, NULL, 0) == -1)
485 err(1, "sysctl (argv copy)");
486
487 if (size == 0) {
488 free(argv);
489 argv = NULL;
490 }
491
492 if (nargv != 1 && argv != NULL) {
493 a = (char *)argv;
494 while (nargv > 1) {
495 if (*a == '\0') {
496 *a = ' ';
497 nargv--;
498 }
499 a++;
500 }
501 }
502 if (a != NULL && argwidth)
503 argv[argwidth] = '\0';
504 } else {
505 argv = kvm_getargv2(kd, kp, (argwidth < 0) ? 0 : argwidth);
506 }
507
508 if (argv == 0) {
509 if (kp->p_comm == 0) {
510 goto nothing;
511 } else {
512 fmt_putc('(', &left);
513 fmt_puts((char *)kp->p_comm, &left);
514 fmt_putc(')', &left);
515 return;
516 }
517 }
518
519 if (use_sysctl) {
520 printf("%s", (char *)argv);
521 } else {
522 while (*argv) {
523 fmt_puts(*argv, &left);
524 argv++;
525 fmt_putc(' ', &left);
526 }
527 }
528
529 return;
530 nothing:
531 putchar('-');
532 }
533
534 static void
535 pr_header(time_t *nowp, int nusers)
536 {
537 double avenrun[3];
538 time_t uptime;
539 int days, hrs, i, mins;
540 int mib[2];
541 size_t size;
542 char buf[256];
543
544 /*
545 * Print time of day.
546 *
547 * SCCS forces the string manipulation below, as it replaces
548 * %, M, and % in a character string with the file name.
549 */
550 (void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
551 buf[sizeof(buf) - 1] = '\0';
552 (void)printf("%s ", buf);
553
554 /*
555 * Print how long system has been up.
556 * (Found by looking getting "boottime" from the kernel)
557 */
558 mib[0] = CTL_KERN;
559 mib[1] = KERN_BOOTTIME;
560 size = sizeof(boottime);
561 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
562 boottime.tv_sec != 0) {
563 uptime = now - boottime.tv_sec;
564 uptime += 30;
565 if (uptime > SECSPERMIN) {
566 days = uptime / SECSPERDAY;
567 uptime %= SECSPERDAY;
568 hrs = uptime / SECSPERHOUR;
569 uptime %= SECSPERHOUR;
570 mins = uptime / SECSPERMIN;
571 (void)printf(" up");
572 if (days > 0)
573 (void)printf(" %d day%s,", days,
574 days > 1 ? "s" : "");
575 if (hrs > 0 && mins > 0)
576 (void)printf(" %2d:%02d,", hrs, mins);
577 else {
578 if (hrs > 0)
579 (void)printf(" %d hr%s,",
580 hrs, hrs > 1 ? "s" : "");
581 if (mins > 0)
582 (void)printf(" %d min%s,",
583 mins, mins > 1 ? "s" : "");
584 }
585 }
586 }
587
588 /* Print number of users logged in to system */
589 (void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
590
591 /*
592 * Print 1, 5, and 15 minute load averages.
593 */
594 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
595 (void)printf(", no load average information available\n");
596 else {
597 (void)printf(", load averages:");
598 for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
599 if (i > 0)
600 (void)printf(",");
601 (void)printf(" %.2f", avenrun[i]);
602 }
603 (void)printf("\n");
604 }
605 }
606
607 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
608 static int
609 ttystat(const char *line, struct stat *st)
610 {
611 char ttybuf[MAXPATHLEN];
612
613 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
614 return stat(ttybuf, st);
615 }
616
617 static void
618 process(struct entry *ep)
619 {
620 struct stat st;
621 time_t touched;
622 int max;
623
624 if ((max = strlen(ep->name)) > maxname)
625 maxname = max;
626 if ((max = strlen(ep->line)) > maxline)
627 maxline = max;
628 if ((max = strlen(ep->host)) > maxhost)
629 maxhost = max;
630
631 ep->tdev = 0;
632 ep->idle = (time_t)-1;
633
634 #ifdef SUPPORT_UTMP
635 /*
636 * Hack to recognize and correctly parse
637 * ut entry made by ftpd. The "tty" used
638 * by ftpd is not a real tty, just identifier in
639 * form ftpPID. Pid parsed from the "tty name"
640 * is used later to match corresponding process.
641 * NB: This is only used for utmp entries. For utmpx,
642 * we already have the pid.
643 */
644 if (ep->pid == 0 && strncmp(ep->line, "ftp", 3) == 0) {
645 ep->pid = strtol(ep->line + 3, NULL, 10);
646 return;
647 }
648 #endif
649 if (ttystat(ep->line, &st) == -1)
650 return;
651
652 ep->tdev = st.st_rdev;
653 /*
654 * If this is the console device, attempt to ascertain
655 * the true console device dev_t.
656 */
657 if (ep->tdev == 0) {
658 int mib[2];
659 size_t size;
660
661 mib[0] = CTL_KERN;
662 mib[1] = KERN_CONSDEV;
663 size = sizeof(dev_t);
664 (void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
665 }
666
667 touched = st.st_atime;
668 if (touched < ep->tv.tv_sec) {
669 /* tty untouched since before login */
670 touched = ep->tv.tv_sec;
671 }
672 if ((ep->idle = now - touched) < 0)
673 ep->idle = 0;
674 }
675 #endif
676
677 static void
678 usage(int wcmd)
679 {
680
681 if (wcmd)
682 (void)fprintf(stderr,
683 "Usage: %s [-hinw] [-M core] [-N system] [user]\n",
684 getprogname());
685 else
686 (void)fprintf(stderr, "Usage: %s\n", getprogname());
687 exit(1);
688 }
689