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