w.c revision 1.48 1 /* $NetBSD: w.c,v 1.48 2002/07/27 23:58:40 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.48 2002/07/27 23:58:40 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 #ifdef SUPPORT_FTPD_UTMP
123 pid_t ftpd_pid; /* pid as extracted from ftpd's entry */
124 #endif
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 if (wcmd) {
201 #ifdef SUPPORT_UTMP
202 setutent();
203 #endif
204 #ifdef SUPPORT_UTMP
205 setutxent();
206 #endif
207 }
208
209 if (*argv)
210 sel_user = *argv;
211
212 nusers = 0;
213 #ifdef SUPPORT_UTMPX
214 while ((utx = getutxent()) != NULL) {
215 if (utx->ut_type != USER_PROCESS)
216 continue;
217 ++nusers;
218 if (wcmd == 0 || (sel_user &&
219 strncmp(utx->ut_name, sel_user, sizeof(utx->ut_name) != 0)))
220 continue;
221 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
222 err(1, NULL);
223 (void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
224 (void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
225 (void)memcpy(ep->host, utx->ut_host, sizeof(utx->ut_host));
226 ep->name[sizeof(utx->ut_name)] = '\0';
227 ep->line[sizeof(utx->ut_line)] = '\0';
228 ep->host[sizeof(utx->ut_host)] = '\0';
229 ep->tv = utx->ut_tv;
230 *nextp = ep;
231 nextp = &(ep->next);
232 process(ep);
233 }
234 #endif
235
236 #ifdef SUPPORT_UTMP
237 while ((ut = getutent()) != NULL) {
238 ++nusers;
239 if (wcmd == 0 || (sel_user &&
240 strncmp(ut->ut_name, sel_user, sizeof(ut->ut_name) != 0)))
241 continue;
242
243 /* Don't process entries that we have utmpx for */
244 for (ep = ehead; ep != NULL; ep = ep->next) {
245 if (strncmp(ep->line, ut->ut_line,
246 sizeof(ut->ut_line)) == 0)
247 break;
248 }
249 if (ep != NULL)
250 continue;
251
252 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
253 err(1, NULL);
254 (void)memcpy(ep->name, ut->ut_name, sizeof(ut->ut_name));
255 (void)memcpy(ep->line, ut->ut_line, sizeof(ut->ut_line));
256 (void)memcpy(ep->host, ut->ut_host, sizeof(ut->ut_host));
257 ep->name[sizeof(ut->ut_name)] = '\0';
258 ep->line[sizeof(ut->ut_line)] = '\0';
259 ep->host[sizeof(ut->ut_host)] = '\0';
260 ep->tv.tv_sec = ut->ut_time;
261 ep->tv.tv_usec = 0;
262 *nextp = ep;
263 nextp = &(ep->next);
264 process(ep);
265 }
266 #endif
267
268 if (wcmd) {
269 #ifdef SUPPORT_UTMPX
270 endutxent();
271 #endif
272 #ifdef SUPPORT_UTMP
273 endutent();
274 #endif
275 } else
276 nusers = 1;
277
278 if (header || wcmd == 0) {
279 pr_header(&now, nusers);
280 if (wcmd == 0)
281 exit (0);
282 }
283
284 if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
285 sizeof(struct kinfo_proc2), &nentries)) == NULL)
286 errx(1, "%s", kvm_geterr(kd));
287
288 /* Include trailing space because TTY header starts one column early. */
289 for (i = 0; i < nentries; i++, kp++) {
290
291 if (kp->p_stat == SIDL || kp->p_stat == SZOMB)
292 continue;
293
294 for (ep = ehead; ep != NULL; ep = ep->next) {
295 if (ep->tdev == kp->p_tdev &&
296 kp->p__pgid == kp->p_tpgid) {
297 /*
298 * Proc is in foreground of this terminal
299 */
300 if (proc_compare(ep->kp, kp)) {
301 ep->kp = kp;
302 }
303 break;
304 }
305 #ifdef SUPPORT_FTPD_UTMP
306 /*
307 * Hack to match process to ftp utmp entry.
308 */
309 else if (ep->tdev == 0 && kp->p_tdev == NODEV &&
310 ep->ftpd_pid == kp->p_pid) {
311 ep->kp = kp;
312 }
313 #endif /* SUPPORT_FTPD_UTMP */
314 }
315 }
316
317 argwidth = printf("%-*sTTY %-*s %*s IDLE WHAT\n",
318 maxname, "USER", maxhost, "FROM",
319 7 /* "dddhhXm" */, "LOGIN@");
320 argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
321
322 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
323 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
324 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
325 ttywidth = 79;
326 else
327 ttywidth = ws.ws_col - 1;
328 argwidth = ttywidth - argwidth;
329 if (argwidth < 4)
330 argwidth = 8;
331 /* sort by idle time */
332 if (sortidle && ehead != NULL) {
333 struct entry *from = ehead, *save;
334
335 ehead = NULL;
336 while (from != NULL) {
337 for (nextp = &ehead;
338 (*nextp) && from->idle >= (*nextp)->idle;
339 nextp = &(*nextp)->next)
340 continue;
341 save = from;
342 from = from->next;
343 save->next = *nextp;
344 *nextp = save;
345 }
346 }
347 #if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
348 else if (ehead != NULL) {
349 struct entry *from = ehead, *save;
350
351 ehead = NULL;
352 while (from != NULL) {
353 for (nextp = &ehead;
354 (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
355 nextp = &(*nextp)->next)
356 continue;
357 save = from;
358 from = from->next;
359 save->next = *nextp;
360 *nextp = save;
361 }
362 }
363 #endif
364
365 if (!nflag) {
366 int rv;
367
368 rv = gethostname(domain, sizeof(domain));
369 domain[sizeof(domain) - 1] = '\0';
370 if (rv < 0 || (p = strchr(domain, '.')) == 0)
371 domain[0] = '\0';
372 else
373 memmove(domain, p, strlen(p) + 1);
374 }
375
376 for (ep = ehead; ep != NULL; ep = ep->next) {
377 char host_buf[MAXHOSTNAMELEN + 1];
378
379 host_buf[MAXHOSTNAMELEN] = '\0';
380 strncpy(host_buf, ep->host, MAXHOSTNAMELEN);
381 p = *host_buf ? host_buf : "-";
382
383 for (x = p; x < p + MAXHOSTNAMELEN; x++)
384 if (*x == '\0' || *x == ':')
385 break;
386 if (x == p + MAXHOSTNAMELEN || *x != ':')
387 x = NULL;
388 else
389 *x++ = '\0';
390
391 if (!nflag && inet_aton(p, &l) &&
392 (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
393 if (domain[0] != '\0') {
394 p = hp->h_name;
395 p += strlen(hp->h_name);
396 p -= strlen(domain);
397 if (p > hp->h_name &&
398 strcasecmp(p, domain) == 0)
399 *p = '\0';
400 }
401 p = hp->h_name;
402 }
403 if (x) {
404 (void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
405 p = buf;
406 }
407 if (ep->kp == NULL) {
408 warnx("Stale utmp entry: %s %s %s",
409 ep->name, ep->line, ep->host);
410 continue;
411 }
412 (void)printf("%-*s %-2.2s %-*.*s ",
413 maxname, ep->kp->p_login,
414 (strncmp(ep->line, "tty", 3) &&
415 strncmp(ep->line, "dty", 3)) ?
416 ep->line : ep->line + 3,
417 maxhost, maxhost, *p ? p : "-");
418 then = (time_t)ep->tv.tv_sec;
419 pr_attime(&then, &now);
420 pr_idle(ep->idle);
421 pr_args(ep->kp);
422 (void)printf("\n");
423 }
424 exit(0);
425 }
426
427 static void
428 pr_args(struct kinfo_proc2 *kp)
429 {
430 char **argv;
431 int left;
432
433 if (kp == 0)
434 goto nothing;
435 left = argwidth;
436 argv = kvm_getargv2(kd, kp, argwidth);
437 if (argv == 0)
438 goto nothing;
439 while (*argv) {
440 fmt_puts(*argv, &left);
441 argv++;
442 fmt_putc(' ', &left);
443 }
444 return;
445 nothing:
446 putchar('-');
447 }
448
449 static void
450 pr_header(time_t *nowp, int nusers)
451 {
452 double avenrun[3];
453 time_t uptime;
454 int days, hrs, i, mins;
455 int mib[2];
456 size_t size;
457 char buf[256];
458
459 /*
460 * Print time of day.
461 *
462 * SCCS forces the string manipulation below, as it replaces
463 * %, M, and % in a character string with the file name.
464 */
465 (void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
466 buf[sizeof(buf) - 1] = '\0';
467 (void)printf("%s ", buf);
468
469 /*
470 * Print how long system has been up.
471 * (Found by looking getting "boottime" from the kernel)
472 */
473 mib[0] = CTL_KERN;
474 mib[1] = KERN_BOOTTIME;
475 size = sizeof(boottime);
476 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
477 boottime.tv_sec != 0) {
478 uptime = now - boottime.tv_sec;
479 uptime += 30;
480 if (uptime > SECSPERMIN) {
481 days = uptime / SECSPERDAY;
482 uptime %= SECSPERDAY;
483 hrs = uptime / SECSPERHOUR;
484 uptime %= SECSPERHOUR;
485 mins = uptime / SECSPERMIN;
486 (void)printf(" up");
487 if (days > 0)
488 (void)printf(" %d day%s,", days,
489 days > 1 ? "s" : "");
490 if (hrs > 0 && mins > 0)
491 (void)printf(" %2d:%02d,", hrs, mins);
492 else {
493 if (hrs > 0)
494 (void)printf(" %d hr%s,",
495 hrs, hrs > 1 ? "s" : "");
496 if (mins > 0)
497 (void)printf(" %d min%s,",
498 mins, mins > 1 ? "s" : "");
499 }
500 }
501 }
502
503 /* Print number of users logged in to system */
504 (void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
505
506 /*
507 * Print 1, 5, and 15 minute load averages.
508 */
509 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
510 (void)printf(", no load average information available\n");
511 else {
512 (void)printf(", load averages:");
513 for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
514 if (i > 0)
515 (void)printf(",");
516 (void)printf(" %.2f", avenrun[i]);
517 }
518 (void)printf("\n");
519 }
520 }
521
522 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
523 static struct stat *
524 ttystat(char *line)
525 {
526 static struct stat sb;
527 char ttybuf[MAXPATHLEN];
528
529 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
530 if (stat(ttybuf, &sb))
531 return (NULL);
532 return (&sb);
533 }
534
535 static void
536 process(struct entry *ep)
537 {
538 struct stat *stp;
539 time_t touched;
540 int max;
541
542 if ((max = strlen(ep->name)) > maxname)
543 maxname = max;
544 if ((max = strlen(ep->line)) > maxline)
545 maxline = max;
546 if ((max = strlen(ep->host)) > maxhost)
547 maxhost = max;
548
549 if ((stp = ttystat(ep->line)) == NULL)
550 return;
551
552 #ifdef SUPPORT_FTPD_UTMP
553 /*
554 * Hack to recognize and correctly parse
555 * ut entry made by ftpd. The "tty" used
556 * by ftpd is not a real tty, just identifier in
557 * form ftpSUPPORT_ID. Pid parsed from the "tty name"
558 * is used later to match corresponding process.
559 */
560 if (strncmp(ep->line, "ftp", 3) == 0) {
561 ep->ftpd_pid = strtol(ep->line + 3, NULL, 10);
562
563 return;
564 }
565 #endif /* SUPPORT_FTPD_UTMP */
566
567 ep->tdev = stp->st_rdev;
568 /*
569 * If this is the console device, attempt to ascertain
570 * the true console device dev_t.
571 */
572 if (ep->tdev == 0) {
573 int mib[2];
574 size_t size;
575
576 mib[0] = CTL_KERN;
577 mib[1] = KERN_CONSDEV;
578 size = sizeof(dev_t);
579 (void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
580 }
581
582 touched = stp->st_atime;
583 if (touched < ep->tv.tv_sec) {
584 /* tty untouched since before login */
585 touched = ep->tv.tv_sec;
586 }
587 if ((ep->idle = now - touched) < 0)
588 ep->idle = 0;
589 }
590 #endif
591
592 static void
593 usage(int wcmd)
594 {
595
596 if (wcmd)
597 (void)fprintf(stderr,
598 "usage: w: [-hin] [-M core] [-N system] [user]\n");
599 else
600 (void)fprintf(stderr, "uptime\n");
601 exit(1);
602 }
603