w.c revision 1.60 1 /* $NetBSD: w.c,v 1.60 2003/08/07 11:17:13 agc 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.60 2003/08/07 11:17:13 agc 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 #define max(a,b) (((a)>(b))?(a):(b))
91
92 struct timeval boottime;
93 struct winsize ws;
94 kvm_t *kd;
95 time_t now; /* the current time of day */
96 time_t uptime; /* time of last reboot & elapsed time since */
97 int ttywidth; /* width of tty */
98 int argwidth; /* width of tty left to print process args */
99 int header = 1; /* true if -h flag: don't print heading */
100 int nflag; /* true if -n flag: don't convert addrs */
101 int sortidle; /* sort bu idle time */
102 char *sel_user; /* login of particular user selected */
103 char domain[MAXHOSTNAMELEN + 1];
104 int maxname = 8, maxline = 3, maxhost = 16;
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 struct stat *ttystat(char *);
127 static void process(struct entry *);
128 #endif
129 static void usage(int);
130 int main(int, char **);
131
132 int
133 main(int argc, char **argv)
134 {
135 struct kinfo_proc2 *kp;
136 struct hostent *hp;
137 struct in_addr l;
138 int ch, i, nentries, nusers, wcmd;
139 char *memf, *nlistf, *p, *x;
140 time_t then;
141 #ifdef SUPPORT_UTMP
142 struct utmp *ut;
143 #endif
144 #ifdef SUPPORT_UTMPX
145 struct utmpx *utx;
146 #endif
147 const char *progname;
148 char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
149
150 /* Are we w(1) or uptime(1)? */
151 progname = getprogname();
152 if (*progname == '-')
153 progname++;
154 if (*progname == 'u') {
155 wcmd = 0;
156 p = "";
157 } else {
158 wcmd = 1;
159 p = "hiflM:N:nsuw";
160 }
161
162 memf = nlistf = NULL;
163 while ((ch = getopt(argc, argv, p)) != -1)
164 switch (ch) {
165 case 'h':
166 header = 0;
167 break;
168 case 'i':
169 sortidle = 1;
170 break;
171 case 'M':
172 header = 0;
173 memf = optarg;
174 break;
175 case 'N':
176 nlistf = optarg;
177 break;
178 case 'n':
179 nflag = 1;
180 break;
181 case 'f': case 'l': case 's': case 'u': case 'w':
182 warnx("[-flsuw] no longer supported");
183 /* FALLTHROUGH */
184 case '?':
185 default:
186 usage(wcmd);
187 }
188 argc -= optind;
189 argv += optind;
190
191 if ((kd = kvm_openfiles(nlistf, memf, NULL,
192 memf == NULL ? KVM_NO_FILES : O_RDONLY, errbuf)) == NULL)
193 errx(1, "%s", errbuf);
194
195 (void)time(&now);
196
197 #ifdef SUPPORT_UTMPX
198 setutxent();
199 #endif
200 #ifdef SUPPORT_UTMP
201 setutent();
202 #endif
203
204 if (*argv)
205 sel_user = *argv;
206
207 nusers = 0;
208 #ifdef SUPPORT_UTMPX
209 while ((utx = getutxent()) != NULL) {
210 if (utx->ut_type != USER_PROCESS)
211 continue;
212 ++nusers;
213 if (sel_user &&
214 strncmp(utx->ut_name, sel_user, sizeof(utx->ut_name) != 0))
215 continue;
216 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
217 err(1, NULL);
218 (void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
219 (void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
220 ep->name[sizeof(utx->ut_name)] = '\0';
221 ep->line[sizeof(utx->ut_line)] = '\0';
222 if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
223 utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
224 NI_NUMERICHOST) != 0) {
225 (void)memcpy(ep->host, utx->ut_host,
226 sizeof(utx->ut_host));
227 ep->host[sizeof(utx->ut_host)] = '\0';
228 }
229 ep->type[0] = 'x';
230 ep->tv = utx->ut_tv;
231 ep->pid = utx->ut_pid;
232 *nextp = ep;
233 nextp = &(ep->next);
234 if (wcmd != 0)
235 process(ep);
236 }
237 #endif
238
239 #ifdef SUPPORT_UTMP
240 while ((ut = getutent()) != NULL) {
241 if (ut->ut_name[0] == '\0')
242 continue;
243
244 if (sel_user &&
245 strncmp(ut->ut_name, sel_user, sizeof(ut->ut_name) != 0))
246 continue;
247
248 /* Don't process entries that we have utmpx for */
249 for (ep = ehead; ep != NULL; ep = ep->next) {
250 if (strncmp(ep->line, ut->ut_line,
251 sizeof(ut->ut_line)) == 0)
252 break;
253 }
254 if (ep != NULL)
255 continue;
256
257 ++nusers;
258 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
259 err(1, NULL);
260 (void)memcpy(ep->name, ut->ut_name, sizeof(ut->ut_name));
261 (void)memcpy(ep->line, ut->ut_line, sizeof(ut->ut_line));
262 (void)memcpy(ep->host, ut->ut_host, sizeof(ut->ut_host));
263 ep->name[sizeof(ut->ut_name)] = '\0';
264 ep->line[sizeof(ut->ut_line)] = '\0';
265 ep->host[sizeof(ut->ut_host)] = '\0';
266 ep->tv.tv_sec = ut->ut_time;
267 *nextp = ep;
268 nextp = &(ep->next);
269 if (wcmd != 0)
270 process(ep);
271 }
272 #endif
273
274 #ifdef SUPPORT_UTMPX
275 endutxent();
276 #endif
277 #ifdef SUPPORT_UTMP
278 endutent();
279 #endif
280
281 if (header || wcmd == 0) {
282 pr_header(&now, nusers);
283 if (wcmd == 0)
284 exit (0);
285 }
286
287 if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
288 sizeof(struct kinfo_proc2), &nentries)) == NULL)
289 errx(1, "%s", kvm_geterr(kd));
290
291 /* Include trailing space because TTY header starts one column early. */
292 for (i = 0; i < nentries; i++, kp++) {
293
294 if (kp->p_stat == SIDL || kp->p_stat == SZOMB)
295 continue;
296
297 for (ep = ehead; ep != NULL; ep = ep->next) {
298 if (ep->tdev != 0 && ep->tdev == kp->p_tdev &&
299 kp->p__pgid == kp->p_tpgid) {
300 /*
301 * Proc is in foreground of this
302 * terminal
303 */
304 if (proc_compare(ep->tp, kp))
305 ep->tp = kp;
306 break;
307 }
308 if (ep->pid != 0 && ep->pid == kp->p_pid) {
309 ep->pp = kp;
310 break;
311 }
312 }
313 }
314
315 argwidth = printf("%-*sTTY %-*s %*s IDLE WHAT\n",
316 maxname, "USER", maxhost, "FROM",
317 7 /* "dddhhXm" */, "LOGIN@");
318 argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
319
320 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
321 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
322 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
323 ttywidth = 79;
324 else
325 ttywidth = ws.ws_col - 1;
326 argwidth = ttywidth - argwidth;
327 if (argwidth < 4)
328 argwidth = 8;
329 /* sort by idle time */
330 if (sortidle && ehead != NULL) {
331 struct entry *from = ehead, *save;
332
333 ehead = NULL;
334 while (from != NULL) {
335 for (nextp = &ehead;
336 (*nextp) && from->idle >= (*nextp)->idle;
337 nextp = &(*nextp)->next)
338 continue;
339 save = from;
340 from = from->next;
341 save->next = *nextp;
342 *nextp = save;
343 }
344 }
345 #if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
346 else if (ehead != NULL) {
347 struct entry *from = ehead, *save;
348
349 ehead = NULL;
350 while (from != NULL) {
351 for (nextp = &ehead;
352 (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
353 nextp = &(*nextp)->next)
354 continue;
355 save = from;
356 from = from->next;
357 save->next = *nextp;
358 *nextp = save;
359 }
360 }
361 #endif
362
363 if (!nflag) {
364 int rv;
365
366 rv = gethostname(domain, sizeof(domain));
367 domain[sizeof(domain) - 1] = '\0';
368 if (rv < 0 || (p = strchr(domain, '.')) == 0)
369 domain[0] = '\0';
370 else
371 memmove(domain, p, strlen(p) + 1);
372 }
373
374 for (ep = ehead; ep != NULL; ep = ep->next) {
375 char host_buf[MAXHOSTNAMELEN + 1];
376
377 strlcpy(host_buf, ep->host, sizeof(host_buf));
378 p = *host_buf ? host_buf : "-";
379
380 for (x = p; x < p + MAXHOSTNAMELEN; x++)
381 if (*x == '\0' || *x == ':')
382 break;
383 if (x == p + MAXHOSTNAMELEN || *x != ':')
384 x = NULL;
385 else
386 *x++ = '\0';
387
388 if (!nflag && inet_aton(p, &l) &&
389 (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
390 if (domain[0] != '\0') {
391 p = hp->h_name;
392 p += strlen(hp->h_name);
393 p -= strlen(domain);
394 if (p > hp->h_name &&
395 strcasecmp(p, domain) == 0)
396 *p = '\0';
397 }
398 p = hp->h_name;
399 }
400 if (x) {
401 (void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
402 p = buf;
403 }
404 if (ep->tp != NULL)
405 kp = ep->tp;
406 else if (ep->pp != NULL)
407 kp = ep->pp;
408 else {
409 warnx("Stale utmp%s entry: %s %s %s",
410 ep->type, ep->name, ep->line, ep->host);
411 continue;
412 }
413 (void)printf("%-*s %-2.2s %-*.*s ",
414 maxname, kp->p_login,
415 (strncmp(ep->line, "tty", 3) &&
416 strncmp(ep->line, "dty", 3)) ?
417 ep->line : ep->line + 3,
418 maxhost, maxhost, *p ? p : "-");
419 then = (time_t)ep->tv.tv_sec;
420 pr_attime(&then, &now);
421 pr_idle(ep->idle);
422 pr_args(kp);
423 (void)printf("\n");
424 }
425 exit(0);
426 }
427
428 static void
429 pr_args(struct kinfo_proc2 *kp)
430 {
431 char **argv;
432 int left;
433
434 if (kp == 0)
435 goto nothing;
436 left = argwidth;
437 argv = kvm_getargv2(kd, kp, argwidth);
438 if (argv == 0) {
439 if (kp->p_comm == 0) {
440 goto nothing;
441 } else {
442 fmt_putc('(', &left);
443 fmt_puts((char *)kp->p_comm, &left);
444 fmt_putc(')', &left);
445 return;
446 }
447 }
448 while (*argv) {
449 fmt_puts(*argv, &left);
450 argv++;
451 fmt_putc(' ', &left);
452 }
453 return;
454 nothing:
455 putchar('-');
456 }
457
458 static void
459 pr_header(time_t *nowp, int nusers)
460 {
461 double avenrun[3];
462 time_t uptime;
463 int days, hrs, i, mins;
464 int mib[2];
465 size_t size;
466 char buf[256];
467
468 /*
469 * Print time of day.
470 *
471 * SCCS forces the string manipulation below, as it replaces
472 * %, M, and % in a character string with the file name.
473 */
474 (void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
475 buf[sizeof(buf) - 1] = '\0';
476 (void)printf("%s ", buf);
477
478 /*
479 * Print how long system has been up.
480 * (Found by looking getting "boottime" from the kernel)
481 */
482 mib[0] = CTL_KERN;
483 mib[1] = KERN_BOOTTIME;
484 size = sizeof(boottime);
485 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
486 boottime.tv_sec != 0) {
487 uptime = now - boottime.tv_sec;
488 uptime += 30;
489 if (uptime > SECSPERMIN) {
490 days = uptime / SECSPERDAY;
491 uptime %= SECSPERDAY;
492 hrs = uptime / SECSPERHOUR;
493 uptime %= SECSPERHOUR;
494 mins = uptime / SECSPERMIN;
495 (void)printf(" up");
496 if (days > 0)
497 (void)printf(" %d day%s,", days,
498 days > 1 ? "s" : "");
499 if (hrs > 0 && mins > 0)
500 (void)printf(" %2d:%02d,", hrs, mins);
501 else {
502 if (hrs > 0)
503 (void)printf(" %d hr%s,",
504 hrs, hrs > 1 ? "s" : "");
505 if (mins > 0)
506 (void)printf(" %d min%s,",
507 mins, mins > 1 ? "s" : "");
508 }
509 }
510 }
511
512 /* Print number of users logged in to system */
513 (void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
514
515 /*
516 * Print 1, 5, and 15 minute load averages.
517 */
518 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
519 (void)printf(", no load average information available\n");
520 else {
521 (void)printf(", load averages:");
522 for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
523 if (i > 0)
524 (void)printf(",");
525 (void)printf(" %.2f", avenrun[i]);
526 }
527 (void)printf("\n");
528 }
529 }
530
531 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
532 static struct stat *
533 ttystat(char *line)
534 {
535 static struct stat sb;
536 char ttybuf[MAXPATHLEN];
537
538 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
539 if (stat(ttybuf, &sb))
540 return (NULL);
541 return (&sb);
542 }
543
544 static void
545 process(struct entry *ep)
546 {
547 struct stat *stp;
548 time_t touched;
549 int max;
550
551 if ((max = strlen(ep->name)) > maxname)
552 maxname = max;
553 if ((max = strlen(ep->line)) > maxline)
554 maxline = max;
555 if ((max = strlen(ep->host)) > maxhost)
556 maxhost = max;
557
558
559 #ifdef SUPPORT_UTMP
560 /*
561 * Hack to recognize and correctly parse
562 * ut entry made by ftpd. The "tty" used
563 * by ftpd is not a real tty, just identifier in
564 * form ftpSUPPORT_ID. Pid parsed from the "tty name"
565 * is used later to match corresponding process.
566 * NB: This is only used for utmp entries. For utmpx,
567 * we already have the pid.
568 */
569 if (ep->pid == 0 && strncmp(ep->line, "ftp", 3) == 0) {
570 ep->pid = strtol(ep->line + 3, NULL, 10);
571 return;
572 }
573 #endif
574 if ((stp = ttystat(ep->line)) == NULL)
575 return;
576
577 ep->tdev = stp->st_rdev;
578 /*
579 * If this is the console device, attempt to ascertain
580 * the true console device dev_t.
581 */
582 if (ep->tdev == 0) {
583 int mib[2];
584 size_t size;
585
586 mib[0] = CTL_KERN;
587 mib[1] = KERN_CONSDEV;
588 size = sizeof(dev_t);
589 (void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
590 }
591
592 touched = stp->st_atime;
593 if (touched < ep->tv.tv_sec) {
594 /* tty untouched since before login */
595 touched = ep->tv.tv_sec;
596 }
597 if ((ep->idle = now - touched) < 0)
598 ep->idle = 0;
599 }
600 #endif
601
602 static void
603 usage(int wcmd)
604 {
605
606 if (wcmd)
607 (void)fprintf(stderr,
608 "usage: w: [-hin] [-M core] [-N system] [user]\n");
609 else
610 (void)fprintf(stderr, "uptime\n");
611 exit(1);
612 }
613