<sys/posix4.h>: Clean up a bit.
[dragonfly.git] / usr.bin / w / w.c
blob86c23fbc65c9208d650cc3f0fbdcce916311f840
1 /*-
2 * Copyright (c) 1980, 1991, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
29 * @(#) Copyright (c) 1980, 1991, 1993, 1994 The Regents of the University of California. All rights reserved.
30 * @(#)w.c 8.4 (Berkeley) 4/16/94
31 * $FreeBSD: src/usr.bin/w/w.c,v 1.38.2.6 2002/03/12 19:51:51 phantom Exp $
35 * w - print system status (who and what)
37 * This program is similar to the systat command on Tenex/Tops 10/20
40 #include <sys/user.h>
41 #include <sys/param.h>
42 #include <sys/time.h>
43 #include <sys/stat.h>
44 #include <sys/sysctl.h>
45 #include <sys/ioctl.h>
46 #include <sys/socket.h>
47 #include <sys/tty.h>
49 #include <machine/cpu.h>
50 #include <netinet/in.h>
51 #include <arpa/inet.h>
53 #include <ctype.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <kvm.h>
58 #include <limits.h>
59 #include <langinfo.h>
60 #include <locale.h>
61 #include <netdb.h>
62 #include <nlist.h>
63 #include <paths.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #ifdef SUPPORT_UTMP
69 #include <utmp.h>
70 #endif
71 #ifdef SUPPORT_UTMPX
72 #include <utmpx.h>
73 #endif
74 #include <vis.h>
76 #include <arpa/nameser.h>
77 #include <resolv.h>
79 #include "extern.h"
81 struct timeval boottime;
82 #ifdef SUPPORT_UTMP
83 struct utmp utmp;
84 #endif
85 struct winsize ws;
86 kvm_t *kd;
87 time_t now; /* the current time of day */
88 time_t then;
89 time_t uptime; /* time of last reboot & elapsed time since */
90 int ttywidth; /* width of tty */
91 int argwidth; /* width of tty */
92 int header = 1; /* true if -h flag: don't print heading */
93 int nflag; /* true if -n flag: don't convert addrs */
94 int dflag; /* true if -d flag: output debug info */
95 int sortidle; /* sort by idle time */
96 int use_ampm; /* use AM/PM time */
97 int use_comma; /* use comma as floats separator */
98 char **sel_users; /* login array of particular users selected */
99 char domain[MAXHOSTNAMELEN];
100 int maxname = 8, maxline = 3, maxhost = 16;
103 * One of these per active utmp entry.
105 struct entry {
106 struct entry *next;
107 char name[UTX_USERSIZE + 1];
108 char line[UTX_LINESIZE + 1];
109 char host[UTX_HOSTSIZE + 1];
110 char type[2];
111 struct timeval tv;
112 dev_t tdev; /* dev_t of terminal */
113 time_t idle; /* idle time of terminal in seconds */
114 struct kinfo_proc *kp; /* `most interesting' proc */
115 char *args; /* arg list of interesting process */
116 struct kinfo_proc *dkp; /* debug option proc list */
117 pid_t pid; /* pid or ~0 if not known */
118 } *ep, *ehead = NULL, **nextp = &ehead;
120 #define debugproc(p) *((struct kinfo_proc **)&(p)->kp_spare[0])
122 static void pr_header(time_t *, int);
123 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
124 static struct stat *ttystat(char *, int);
125 static void process(struct entry *);
126 #endif
127 static void usage(int);
128 static int this_is_uptime(const char *s);
130 char *fmt_argv(char **, char *, int); /* ../../bin/ps/fmt.c */
133 main(int argc, char **argv)
135 struct kinfo_proc *kp;
136 struct kinfo_proc *dkp;
137 struct hostent *hp;
138 in_addr_t l;
139 int ch, i, nentries, nusers, wcmd, longidle, dropgid;
140 char *memf, *nlistf, *p, *x;
141 #ifdef SUPPORT_UTMP
142 struct utmp *ut;
143 #endif
144 #ifdef SUPPORT_UTMPX
145 struct utmpx *utx;
146 #endif
147 char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
149 (void)setlocale(LC_ALL, "");
150 use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
151 use_comma = (*nl_langinfo(RADIXCHAR) != ',');
153 /* Are we w(1) or uptime(1)? */
154 if (this_is_uptime(argv[0]) == 0) {
155 wcmd = 0;
156 p = "";
157 } else {
158 wcmd = 1;
159 p = "dhiflM:N:nsuw";
162 dropgid = 0;
163 memf = nlistf = _PATH_DEVNULL;
164 while ((ch = getopt(argc, argv, p)) != -1)
165 switch (ch) {
166 case 'd':
167 dflag = 1;
168 break;
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 dropgid = 1;
179 break;
180 case 'N':
181 nlistf = optarg;
182 dropgid = 1;
183 break;
184 case 'n':
185 nflag = 1;
186 break;
187 case 'f': case 'l': case 's': case 'u': case 'w':
188 warnx("[-flsuw] no longer supported");
189 /* FALLTHROUGH */
190 case '?':
191 default:
192 usage(wcmd);
194 argc -= optind;
195 argv += optind;
197 if (!(_res.options & RES_INIT))
198 res_init();
199 _res.retrans = 2; /* resolver timeout to 2 seconds per try */
200 _res.retry = 1; /* only try once.. */
203 * Discard setgid privileges if not the running kernel so that bad
204 * guys can't print interesting stuff from kernel memory.
206 if (dropgid)
207 setgid(getgid());
209 if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
210 errx(1, "%s", errbuf);
212 (void)time(&now);
213 #ifdef SUPPORT_UTMPX
214 setutxent();
215 #endif
216 #ifdef SUPPORT_UTMP
217 setutent();
218 #endif
220 if (*argv)
221 sel_users = argv;
223 nusers = 0;
224 #ifdef SUPPORT_UTMPX
225 while ((utx = getutxent()) != NULL) {
226 if (utx->ut_type != USER_PROCESS)
227 continue;
228 ++nusers;
230 if (sel_users) {
231 int usermatch;
232 char **user;
234 usermatch = 0;
235 for (user = sel_users; !usermatch && *user; user++)
236 if (!strncmp(utx->ut_name, *user, UTX_USERSIZE))
237 usermatch = 1;
238 if (!usermatch)
239 continue;
242 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
243 err(1, NULL);
244 (void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
245 (void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
246 (void)memcpy(ep->host, utx->ut_host, sizeof(utx->ut_host));
247 ep->name[sizeof(utx->ut_name)] = '\0';
248 ep->line[sizeof(utx->ut_line)] = '\0';
249 ep->host[sizeof(utx->ut_host)] = '\0';
250 #if 1
251 /* XXX: Actually we don't support the utx->ut_ss stuff yet */
252 if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
253 utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
254 NI_NUMERICHOST) != 0) {
255 (void)memcpy(ep->host, utx->ut_host,
256 sizeof(utx->ut_host));
257 ep->host[sizeof(utx->ut_host)] = '\0';
259 #endif
260 ep->type[0] = 'x';
261 ep->tv = utx->ut_tv;
262 ep->pid = utx->ut_pid;
264 *nextp = ep;
265 nextp = &(ep->next);
266 if (wcmd != 0)
267 process(ep);
269 #endif
271 #ifdef SUPPORT_UTMP
272 while ((ut = getutent()) != NULL) {
273 if (ut->ut_name[0] == '\0')
274 continue;
275 ++nusers;
276 if (sel_users) {
277 int usermatch;
278 char **user;
280 usermatch = 0;
281 for (user = sel_users; !usermatch && *user; user++)
282 if (!strncmp(ut->ut_name, *user, UT_NAMESIZE))
283 usermatch = 1;
284 if (!usermatch)
285 continue;
288 /* Don't process entries that we have utmpx for */
289 for (ep = ehead; ep != NULL; ep = ep->next) {
290 if (strncmp(ep->line, ut->ut_line,
291 sizeof(ut->ut_line)) == 0)
292 break;
294 if (ep != NULL) {
295 --nusers; /* Duplicate entry */
296 continue;
299 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
300 err(1, NULL);
301 (void)memcpy(ep->name, ut->ut_name, sizeof(ut->ut_name));
302 (void)memcpy(ep->line, ut->ut_line, sizeof(ut->ut_line));
303 (void)memcpy(ep->host, ut->ut_host, sizeof(ut->ut_host));
304 ep->name[sizeof(ut->ut_name)] = '\0';
305 ep->line[sizeof(ut->ut_line)] = '\0';
306 ep->host[sizeof(ut->ut_host)] = '\0';
307 ep->tv.tv_sec = ut->ut_time;
309 *nextp = ep;
310 nextp = &(ep->next);
311 if (wcmd != 0)
312 process(ep);
314 #endif
316 #ifdef SUPPORT_UTMPX
317 endutxent();
318 #endif
319 #ifdef SUPPORT_UTMP
320 endutent();
321 #endif
323 if (header || wcmd == 0) {
324 pr_header(&now, nusers);
325 if (wcmd == 0) {
326 (void)kvm_close(kd);
327 exit(0);
330 #define HEADER_USER "USER"
331 #define HEADER_TTY "TTY"
332 #define HEADER_FROM "FROM"
333 #define HEADER_LOGIN_IDLE "LOGIN@ IDLE "
334 #define HEADER_WHAT "WHAT\n"
335 #define WUSED (maxname + maxline + maxhost + \
336 sizeof(HEADER_LOGIN_IDLE) + 3) /* header width incl. spaces */
337 (void)printf("%-*.*s %-*.*s %-*.*s %s",
338 maxname, maxname, HEADER_USER,
339 maxline, maxline, HEADER_TTY,
340 maxhost, maxhost, HEADER_FROM,
341 HEADER_LOGIN_IDLE HEADER_WHAT);
344 if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
345 err(1, "%s", kvm_geterr(kd));
346 for (i = 0; i < nentries; i++, kp++) {
347 if (kp->kp_stat == SIDL || kp->kp_stat == SZOMB)
348 continue;
349 for (ep = ehead; ep != NULL; ep = ep->next) {
350 if (ep->tdev == kp->kp_tdev) {
352 * proc is associated with this terminal
354 if (ep->kp == NULL && kp->kp_pgid == kp->kp_tpgid) {
356 * Proc is 'most interesting'
358 if (proc_compare(ep->kp, kp))
359 ep->kp = kp;
362 * Proc debug option info; add to debug
363 * list using kinfo_proc kp_eproc.e_spare
364 * as next pointer; ptr to ptr avoids the
365 * ptr = long assumption.
367 dkp = ep->dkp;
368 ep->dkp = kp;
369 debugproc(kp) = dkp;
371 if (ep->pid != 0 && ep->pid == kp->kp_pid) {
372 ep->kp = kp;
373 break;
377 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
378 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
379 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
380 ttywidth = 79;
381 else
382 ttywidth = ws.ws_col - 1;
383 argwidth = ttywidth - WUSED;
384 if (argwidth < 4)
385 argwidth = 8;
386 for (ep = ehead; ep != NULL; ep = ep->next) {
387 if (ep->kp == NULL) {
388 ep->args = "-";
389 continue;
391 ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
392 ep->kp->kp_comm, MAXCOMLEN);
393 if (ep->args == NULL)
394 err(1, NULL);
396 /* sort by idle time */
397 if (sortidle && ehead != NULL) {
398 struct entry *from, *save;
400 from = ehead;
401 ehead = NULL;
402 while (from != NULL) {
403 for (nextp = &ehead;
404 (*nextp) && from->idle >= (*nextp)->idle;
405 nextp = &(*nextp)->next)
406 continue;
407 save = from;
408 from = from->next;
409 save->next = *nextp;
410 *nextp = save;
413 #if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
414 else if (ehead != NULL) {
415 struct entry *from = ehead, *save;
417 ehead = NULL;
418 while (from != NULL) {
419 for (nextp = &ehead;
420 (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
421 nextp = &(*nextp)->next)
422 continue;
423 save = from;
424 from = from->next;
425 save->next = *nextp;
426 *nextp = save;
429 #endif
431 if (!nflag) {
432 if (gethostname(domain, sizeof(domain)) < 0 ||
433 (p = strchr(domain, '.')) == NULL)
434 domain[0] = '\0';
435 else {
436 domain[sizeof(domain) - 1] = '\0';
437 memmove(domain, p, strlen(p) + 1);
441 for (ep = ehead; ep != NULL; ep = ep->next) {
442 char host_buf[UTX_HOSTSIZE + 1];
444 host_buf[UTX_HOSTSIZE] = '\0';
445 strncpy(host_buf, ep->host, maxhost);
446 p = *host_buf ? host_buf : "-";
447 if ((x = strchr(p, ':')) != NULL)
448 *x++ = '\0';
449 if (!nflag && isdigit(*p) &&
450 (l = inet_addr(p)) != INADDR_NONE &&
451 (hp = gethostbyaddr(&l, sizeof(l), AF_INET))) {
452 if (domain[0] != '\0') {
453 p = hp->h_name;
454 p += strlen(hp->h_name);
455 p -= strlen(domain);
456 if (p > hp->h_name &&
457 strcasecmp(p, domain) == 0)
458 *p = '\0';
460 p = hp->h_name;
462 if (nflag && *p && strcmp(p, "-") &&
463 inet_addr(p) == INADDR_NONE) {
464 hp = gethostbyname(p);
466 if (hp != NULL) {
467 struct in_addr in;
469 memmove(&in, hp->h_addr, sizeof(in));
470 p = inet_ntoa(in);
473 if (x) {
474 (void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
475 p = buf;
477 if (dflag) {
478 for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
479 char *ptr;
481 ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
482 dkp->kp_comm, MAXCOMLEN);
483 if (ptr == NULL)
484 ptr = "-";
485 (void)printf("\t\t%-9d %s\n",
486 dkp->kp_pid, ptr);
489 (void)printf("%-*.*s %-*.*s %-*.*s ",
490 maxname, maxname, ep->name,
491 maxline, maxline,
492 strncmp(ep->line, "tty", 3) &&
493 strncmp(ep->line, "cua", 3) ?
494 ep->line : ep->line + 3,
495 maxhost, maxhost, *p ? p : "-");
496 then = (time_t)ep->tv.tv_sec;
497 pr_attime(&then, &now);
498 longidle = pr_idle(ep->idle);
499 (void)printf("%.*s\n", argwidth - longidle, ep->args);
501 (void)kvm_close(kd);
502 exit(0);
505 static void
506 pr_header(time_t *nowp, int nusers)
508 double avenrun[3];
509 time_t uptime;
510 int days, hrs, i, mins, secs;
511 int mib[2];
512 size_t size;
513 char buf[256];
516 * Print time of day. (use "AM"/"PM" for all locales)
518 (void)strftime_l(buf, sizeof(buf) - 1,
519 use_ampm ? "%l:%M%p" : "%k:%M",
520 localtime(nowp), NULL);
521 buf[sizeof(buf) - 1] = '\0';
522 (void)printf("%s ", buf);
525 * Print how long system has been up.
526 * (Found by looking at "boottime" from the kernel)
528 mib[0] = CTL_KERN;
529 mib[1] = KERN_BOOTTIME;
530 size = sizeof(boottime);
531 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
532 boottime.tv_sec != 0) {
533 uptime = now - boottime.tv_sec;
534 if (uptime > 60)
535 uptime += 30;
536 days = uptime / 86400;
537 uptime %= 86400;
538 hrs = uptime / 3600;
539 uptime %= 3600;
540 mins = uptime / 60;
541 secs = uptime % 60;
542 (void)printf(" up");
543 if (days > 0)
544 (void)printf(" %d day%s,", days, days > 1 ? "s" : "");
545 if (hrs > 0 && mins > 0)
546 (void)printf(" %2d:%02d,", hrs, mins);
547 else if (hrs > 0)
548 (void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
549 else if (mins > 0)
550 (void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
551 else
552 (void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
555 /* Print number of users logged in on system */
556 (void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
559 * Print 1, 5, and 15 minute load averages.
561 if (getloadavg(avenrun, NELEM(avenrun)) == -1)
562 (void)printf(", no load average information available\n");
563 else {
564 (void)printf(", load averages:");
565 for (i = 0; i < (int)NELEM(avenrun); i++) {
566 if (use_comma && i > 0)
567 (void)printf(",");
568 (void)printf(" %.2f", avenrun[i]);
570 (void)printf("\n");
574 static struct stat *
575 ttystat(char *line, int sz)
577 static struct stat sb;
578 char ttybuf[MAXPATHLEN];
580 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
581 if (stat(ttybuf, &sb)) {
582 warn("%s", ttybuf);
583 return (NULL);
585 return (&sb);
588 static void
589 usage(int wcmd)
591 if (wcmd)
592 (void)fprintf(stderr,
593 "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
594 else
595 (void)fprintf(stderr, "usage: uptime\n");
596 exit(1);
599 static int
600 this_is_uptime(const char *s)
602 const char *u;
604 if ((u = strrchr(s, '/')) != NULL)
605 ++u;
606 else
607 u = s;
608 if (strcmp(u, "uptime") == 0)
609 return (0);
610 return (-1);
613 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
614 static void
615 process(struct entry *ep)
617 struct stat *stp;
618 time_t touched;
619 int max;
621 if ((max = strlen(ep->name)) > maxname)
622 maxname = max;
623 if ((max = strlen(ep->line)) > maxline)
624 maxline = max;
625 if ((max = strlen(ep->host)) > maxhost)
626 maxhost = max;
628 ep->tdev = 0;
629 ep->idle = (time_t)-1;
631 if (!(stp = ttystat(ep->line, maxline)))
632 return; /* corrupted record */
634 ep->tdev = stp->st_rdev;
635 #ifdef CPU_CONSDEV
637 * If this is the console device, attempt to ascertain
638 * the true console device dev_t.
640 if (ep->tdev == 0) {
641 int mib[2];
642 size_t size;
644 mib[0] = CTL_MACHDEP;
645 mib[1] = CPU_CONSDEV;
646 size = sizeof(dev_t);
647 (void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
649 #endif
651 touched = stp->st_atime;
652 if (touched < ep->tv.tv_sec) {
653 /* tty untouched since before login */
654 touched = ep->tv.tv_sec;
656 if ((ep->idle = now - touched) < 0)
657 ep->idle = 0;
659 #endif