Merge from vendor branch FILE:
[dragonfly.git] / usr.bin / w / w.c
1 /*-
2  * Copyright (c) 1980, 1991, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1980, 1991, 1993, 1994 The Regents of the University of California.  All rights reserved.
34  * @(#)w.c      8.4 (Berkeley) 4/16/94
35  * $FreeBSD: src/usr.bin/w/w.c,v 1.38.2.6 2002/03/12 19:51:51 phantom Exp $
36  * $DragonFly: src/usr.bin/w/w.c,v 1.7 2005/03/25 14:15:23 liamfoy Exp $
37  */
38
39 /*
40  * w - print system status (who and what)
41  *
42  * This program is similar to the systat command on Tenex/Tops 10/20
43  *
44  */
45 #include <sys/param.h>
46 #include <sys/time.h>
47 #include <sys/stat.h>
48 #include <sys/sysctl.h>
49 #include <sys/user.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #include <sys/tty.h>
53
54 #include <machine/cpu.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
57
58 #include <ctype.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <kvm.h>
63 #include <limits.h>
64 #include <langinfo.h>
65 #include <locale.h>
66 #include <netdb.h>
67 #include <nlist.h>
68 #include <paths.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 #include <utmp.h>
74 #include <vis.h>
75
76 #include <arpa/nameser.h>
77 #include <resolv.h>
78
79 #include "extern.h"
80
81 struct timeval  boottime;
82 struct utmp     utmp;
83 struct winsize  ws;
84 kvm_t          *kd;
85 time_t          now;            /* the current time of day */
86 time_t          uptime;         /* time of last reboot & elapsed time since */
87 int             ttywidth;       /* width of tty */
88 int             argwidth;       /* width of tty */
89 int             header = 1;     /* true if -h flag: don't print heading */
90 int             nflag;          /* true if -n flag: don't convert addrs */
91 int             dflag;          /* true if -d flag: output debug info */
92 int             sortidle;       /* sort by idle time */
93 int             use_ampm;       /* use AM/PM time */
94 int             use_comma;      /* use comma as floats separator */
95 char          **sel_users;      /* login array of particular users selected */
96 char            domain[MAXHOSTNAMELEN];
97
98 /*
99  * One of these per active utmp entry.
100  */
101 struct  entry {
102         struct  entry *next;
103         struct  utmp utmp;
104         dev_t   tdev;                   /* dev_t of terminal */
105         time_t  idle;                   /* idle time of terminal in seconds */
106         struct  kinfo_proc *kp;         /* `most interesting' proc */
107         char    *args;                  /* arg list of interesting process */
108         struct  kinfo_proc *dkp;        /* debug option proc list */
109 } *ep, *ehead = NULL, **nextp = &ehead;
110
111 #define debugproc(p) *((struct kinfo_proc **)&(p)->kp_eproc.e_spare[0])
112
113 static void              pr_header(time_t *, int);
114 static struct stat      *ttystat(char *, int);
115 static void              usage(int);
116 static int               this_is_uptime(const char *s);
117
118 char *fmt_argv(char **, char *, int);   /* ../../bin/ps/fmt.c */
119
120 int
121 main(int argc, char **argv)
122 {
123         struct kinfo_proc *kp;
124         struct kinfo_proc *dkp;
125         struct hostent *hp;
126         struct stat *stp;
127         FILE *ut;
128         in_addr_t l;
129         time_t touched;
130         int ch, i, nentries, nusers, wcmd, longidle, dropgid;
131         char *memf, *nlistf, *p, *x;
132         char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
133
134         (void)setlocale(LC_ALL, "");
135         use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
136         use_comma = (*nl_langinfo(RADIXCHAR) != ',');
137
138         /* Are we w(1) or uptime(1)? */
139         if (this_is_uptime(argv[0]) == 0) {
140                 wcmd = 0;
141                 p = "";
142         } else {
143                 wcmd = 1;
144                 p = "dhiflM:N:nsuw";
145         }
146
147         dropgid = 0;
148         memf = nlistf = _PATH_DEVNULL;
149         while ((ch = getopt(argc, argv, p)) != -1)
150                 switch (ch) {
151                 case 'd':
152                         dflag = 1;
153                         break;
154                 case 'h':
155                         header = 0;
156                         break;
157                 case 'i':
158                         sortidle = 1;
159                         break;
160                 case 'M':
161                         header = 0;
162                         memf = optarg;
163                         dropgid = 1;
164                         break;
165                 case 'N':
166                         nlistf = optarg;
167                         dropgid = 1;
168                         break;
169                 case 'n':
170                         nflag = 1;
171                         break;
172                 case 'f': case 'l': case 's': case 'u': case 'w':
173                         warnx("[-flsuw] no longer supported");
174                         /* FALLTHROUGH */
175                 case '?':
176                 default:
177                         usage(wcmd);
178                 }
179         argc -= optind;
180         argv += optind;
181
182         if (!(_res.options & RES_INIT))
183                 res_init();
184         _res.retrans = 2;       /* resolver timeout to 2 seconds per try */
185         _res.retry = 1;         /* only try once.. */
186
187         /*
188          * Discard setgid privileges if not the running kernel so that bad
189          * guys can't print interesting stuff from kernel memory.
190          */
191         if (dropgid)
192                 setgid(getgid());
193
194         if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
195                 errx(1, "%s", errbuf);
196
197         (void)time(&now);
198         if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
199                 err(1, "%s", _PATH_UTMP);
200
201         if (*argv)
202                 sel_users = argv;
203
204         for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
205                 if (utmp.ut_name[0] == '\0')
206                         continue;
207                 if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
208                         continue;       /* corrupted record */
209                 ++nusers;
210                 if (wcmd == 0)
211                         continue;
212                 if (sel_users) {
213                         int usermatch;
214                         char **user;
215
216                         usermatch = 0;
217                         for (user = sel_users; !usermatch && *user; user++)
218                                 if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
219                                         usermatch = 1;
220                         if (!usermatch)
221                                 continue;
222                 }
223                 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
224                         errx(1, "calloc");
225                 *nextp = ep;
226                 nextp = &ep->next;
227                 memmove(&ep->utmp, &utmp, sizeof(struct utmp));
228                 ep->tdev = stp->st_rdev;
229 #ifdef CPU_CONSDEV
230                 /*
231                  * If this is the console device, attempt to ascertain
232                  * the true console device dev_t.
233                  */
234                 if (ep->tdev == 0) {
235                         int mib[2];
236                         size_t size;
237
238                         mib[0] = CTL_MACHDEP;
239                         mib[1] = CPU_CONSDEV;
240                         size = sizeof(dev_t);
241                         (void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
242                 }
243 #endif
244                 touched = stp->st_atime;
245                 if (touched < ep->utmp.ut_time) {
246                         /* tty untouched since before login */
247                         touched = ep->utmp.ut_time;
248                 }
249                 if ((ep->idle = now - touched) < 0)
250                         ep->idle = 0;
251         }
252         (void)fclose(ut);
253
254         if (header || wcmd == 0) {
255                 pr_header(&now, nusers);
256                 if (wcmd == 0) {
257                         (void)kvm_close(kd);
258                         exit(0);
259                 }
260
261 #define HEADER_USER             "USER"
262 #define HEADER_TTY              "TTY"
263 #define HEADER_FROM             "FROM"
264 #define HEADER_LOGIN_IDLE       "LOGIN@  IDLE "
265 #define HEADER_WHAT             "WHAT\n"
266 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \
267                 sizeof(HEADER_LOGIN_IDLE) + 3)  /* header width incl. spaces */ 
268                 (void)printf("%-*.*s %-*.*s %-*.*s  %s", 
269                                 UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
270                                 UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
271                                 UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM,
272                                 HEADER_LOGIN_IDLE HEADER_WHAT);
273         }
274
275         if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
276                 err(1, "%s", kvm_geterr(kd));
277         for (i = 0; i < nentries; i++, kp++) {
278                 struct proc *pr = &kp->kp_proc;
279                 struct eproc *e;
280
281                 if (pr->p_stat == SIDL || pr->p_stat == SZOMB)
282                         continue;
283                 e = &kp->kp_eproc;
284                 for (ep = ehead; ep != NULL; ep = ep->next) {
285                         if (ep->tdev == e->e_tdev) {
286                                 /*
287                                  * proc is associated with this terminal
288                                  */
289                                 if (ep->kp == NULL && e->e_pgid == e->e_tpgid) {
290                                         /*
291                                          * Proc is 'most interesting'
292                                          */
293                                         if (proc_compare(&ep->kp->kp_proc, pr))
294                                                 ep->kp = kp;
295                                 }
296                                 /*
297                                  * Proc debug option info; add to debug
298                                  * list using kinfo_proc kp_eproc.e_spare
299                                  * as next pointer; ptr to ptr avoids the
300                                  * ptr = long assumption.
301                                  */
302                                 dkp = ep->dkp;
303                                 ep->dkp = kp;
304                                 debugproc(kp) = dkp;
305                         }
306                 }
307         }
308         if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
309              ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
310              ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
311                ttywidth = 79;
312         else
313                ttywidth = ws.ws_col - 1;
314         argwidth = ttywidth - WUSED;
315         if (argwidth < 4)
316                 argwidth = 8;
317         for (ep = ehead; ep != NULL; ep = ep->next) {
318                 if (ep->kp == NULL) {
319                         ep->args = "-";
320                         continue;
321                 }
322                 ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
323                     ep->kp->kp_thread.td_comm, MAXCOMLEN);
324                 if (ep->args == NULL)
325                         err(1, NULL);
326         }
327         /* sort by idle time */
328         if (sortidle && ehead != NULL) {
329                 struct entry *from, *save;
330
331                 from = ehead;
332                 ehead = NULL;
333                 while (from != NULL) {
334                         for (nextp = &ehead;
335                             (*nextp) && from->idle >= (*nextp)->idle;
336                             nextp = &(*nextp)->next)
337                                 continue;
338                         save = from;
339                         from = from->next;
340                         save->next = *nextp;
341                         *nextp = save;
342                 }
343         }
344
345         if (!nflag) {
346                 if (gethostname(domain, sizeof(domain)) < 0 ||
347                     (p = strchr(domain, '.')) == NULL)
348                         domain[0] = '\0';
349                 else {
350                         domain[sizeof(domain) - 1] = '\0';
351                         memmove(domain, p, strlen(p) + 1);
352                 }
353         }
354
355         for (ep = ehead; ep != NULL; ep = ep->next) {
356                 char host_buf[UT_HOSTSIZE + 1];
357
358                 host_buf[UT_HOSTSIZE] = '\0';
359                 strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
360                 p = *host_buf ? host_buf : "-";
361                 if ((x = strchr(p, ':')) != NULL)
362                         *x++ = '\0';
363                 if (!nflag && isdigit(*p) && (l = inet_addr(p)) != -1 &&
364                     (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
365                         if (domain[0] != '\0') {
366                                 p = hp->h_name;
367                                 p += strlen(hp->h_name);
368                                 p -= strlen(domain);
369                                 if (p > hp->h_name &&
370                                     strcasecmp(p, domain) == 0)
371                                         *p = '\0';
372                         }
373                         p = hp->h_name;
374                 }
375                 if (nflag && *p && strcmp(p, "-") &&
376                     inet_addr(p) == INADDR_NONE) {
377                         hp = gethostbyname(p);
378
379                         if (hp != NULL) {
380                                 struct in_addr in;
381
382                                 memmove(&in, hp->h_addr, sizeof(in));
383                                 p = inet_ntoa(in);
384                         }
385                 }
386                 if (x) {
387                         (void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
388                         p = buf;
389                 }
390                 if (dflag) {
391                         for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
392                                 char *ptr;
393
394                                 ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
395                                     dkp->kp_thread.td_comm, MAXCOMLEN);
396                                 if (ptr == NULL)
397                                         ptr = "-";
398                                 (void)printf("\t\t%-9d %s\n",
399                                     dkp->kp_proc.p_pid, ptr);
400                         }
401                 }
402                 (void)printf("%-*.*s %-*.*s %-*.*s ",
403                     UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
404                     UT_LINESIZE, UT_LINESIZE,
405                     strncmp(ep->utmp.ut_line, "tty", 3) &&
406                     strncmp(ep->utmp.ut_line, "cua", 3) ?
407                     ep->utmp.ut_line : ep->utmp.ut_line + 3,
408                     UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
409                 pr_attime(&ep->utmp.ut_time, &now);
410                 longidle = pr_idle(ep->idle);
411                 (void)printf("%.*s\n", argwidth - longidle, ep->args);
412         }
413         (void)kvm_close(kd);
414         exit(0);
415 }
416
417 static void
418 pr_header(time_t *nowp, int nusers)
419 {
420         double avenrun[3];
421         time_t uptime;
422         int days, hrs, i, mins, secs;
423         int mib[2];
424         size_t size;
425         char buf[256];
426
427         /*
428          * Print time of day.
429          */
430         (void)strftime(buf, sizeof(buf) - 1,
431                        use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp));
432         buf[sizeof(buf) - 1] = '\0';
433         (void)printf("%s ", buf);
434
435         /*
436          * Print how long system has been up.
437          * (Found by looking at "boottime" from the kernel)
438          */
439         mib[0] = CTL_KERN;
440         mib[1] = KERN_BOOTTIME;
441         size = sizeof(boottime);
442         if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
443             boottime.tv_sec != 0) {
444                 uptime = now - boottime.tv_sec;
445                 if (uptime > 60)
446                         uptime += 30;
447                 days = uptime / 86400;
448                 uptime %= 86400;
449                 hrs = uptime / 3600;
450                 uptime %= 3600;
451                 mins = uptime / 60;
452                 secs = uptime % 60;
453                 (void)printf(" up");
454                 if (days > 0)
455                         (void)printf(" %d day%s,", days, days > 1 ? "s" : "");
456                 if (hrs > 0 && mins > 0)
457                         (void)printf(" %2d:%02d,", hrs, mins);
458                 else if (hrs > 0)
459                         (void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
460                 else if (mins > 0)
461                         (void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
462                 else
463                         (void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
464         }
465
466         /* Print number of users logged in on system */
467         (void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
468
469         /*
470          * Print 1, 5, and 15 minute load averages.
471          */
472         if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
473                 (void)printf(", no load average information available\n");
474         else {
475                 (void)printf(", load averages:");
476                 for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
477                         if (use_comma && i > 0)
478                                 (void)printf(",");
479                         (void)printf(" %.2f", avenrun[i]);
480                 }
481                 (void)printf("\n");
482         }
483 }
484
485 static struct stat *
486 ttystat(char *line, int sz)
487 {
488         static struct stat sb;
489         char ttybuf[MAXPATHLEN];
490
491         (void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
492         if (stat(ttybuf, &sb)) {
493                 warn("%s", ttybuf);
494                 return (NULL);
495         }
496         return (&sb);
497 }
498
499 static void
500 usage(int wcmd)
501 {
502         if (wcmd)
503                 (void)fprintf(stderr,
504                     "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
505         else
506                 (void)fprintf(stderr, "usage: uptime\n");
507         exit(1);
508 }
509
510 static int 
511 this_is_uptime(const char *s)
512 {
513         const char *u;
514
515         if ((u = strrchr(s, '/')) != NULL)
516                 ++u;
517         else
518                 u = s;
519         if (strcmp(u, "uptime") == 0)
520                 return (0);
521         return (-1);
522 }