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