w.c revision 1.43 1 /* $NetBSD: w.c,v 1.43 2000/12/20 01:20:38 cgd 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.43 2000/12/20 01:20:38 cgd 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 #include <utmp.h>
85 #include <vis.h>
86
87 #include "extern.h"
88
89 #define max(a,b) (((a)>(b))?(a):(b))
90
91 struct timeval boottime;
92 struct utmp utmp;
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
105 /*
106 * One of these per active utmp entry.
107 */
108 struct entry {
109 struct entry *next;
110 struct utmp utmp;
111 dev_t tdev; /* dev_t of terminal */
112 time_t idle; /* idle time of terminal in seconds */
113 struct kinfo_proc2 *kp; /* `most interesting' proc */
114 #ifdef SUPPORT_FTPD_UTMP
115 pid_t ftpd_pid; /* pid as extracted from ftpd's entry */
116 #endif
117 } *ep, *ehead = NULL, **nextp = &ehead;
118
119 static void pr_args __P((struct kinfo_proc2 *));
120 static void pr_header __P((time_t *, int));
121 static struct stat
122 *ttystat __P((char *));
123 static void usage __P((int));
124 int main __P((int, char **));
125
126 int
127 main(argc, argv)
128 int argc;
129 char **argv;
130 {
131 extern char *__progname;
132 struct kinfo_proc2 *kp;
133 struct hostent *hp;
134 struct stat *stp;
135 FILE *ut;
136 struct in_addr l;
137 int ch, i, nentries, nusers, wcmd, lognamelen;
138 char *memf, *nlistf, *p, *x;
139 char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
140
141 /* Are we w(1) or uptime(1)? */
142 p = __progname;
143 if (*p == '-')
144 p++;
145 if (*p == 'u') {
146 wcmd = 0;
147 p = "";
148 } else {
149 wcmd = 1;
150 p = "hiflM:N:nsuw";
151 }
152
153 memf = nlistf = NULL;
154 while ((ch = getopt(argc, argv, p)) != -1)
155 switch (ch) {
156 case 'h':
157 header = 0;
158 break;
159 case 'i':
160 sortidle = 1;
161 break;
162 case 'M':
163 header = 0;
164 memf = optarg;
165 break;
166 case 'N':
167 nlistf = optarg;
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 ((kd = kvm_openfiles(nlistf, memf, NULL,
183 memf == NULL ? KVM_NO_FILES : O_RDONLY, errbuf)) == NULL)
184 errx(1, "%s", errbuf);
185
186 (void)time(&now);
187 if ((ut = fopen(_PATH_UTMP, "r")) == NULL && wcmd)
188 err(1, "%s", _PATH_UTMP);
189
190 if (*argv)
191 sel_user = *argv;
192
193 for (nusers = 0; ut && fread(&utmp, sizeof(utmp), 1, ut);) {
194 if (utmp.ut_name[0] == '\0')
195 continue;
196 ++nusers;
197 if (wcmd == 0 || (sel_user &&
198 strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
199 continue;
200 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
201 err(1, NULL);
202 *nextp = ep;
203 nextp = &(ep->next);
204 memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
205 if (!(stp = ttystat(ep->utmp.ut_line))) {
206 #ifdef SUPPORT_FTPD_UTMP
207 /*
208 * Hack to recognize and correctly parse
209 * utmp entry made by ftpd. The "tty" used
210 * by ftpd is not a real tty, just identifier in
211 * form ftpPROCESS_ID. Pid parsed from the "tty name"
212 * is used later to match corresponding process.
213 */
214 if (strncmp(ep->utmp.ut_line, "ftp", 3) == 0)
215 ep->ftpd_pid =
216 strtol(ep->utmp.ut_line + 3, NULL, 10);
217 #endif /* SUPPORT_FTPD_UTMP */
218
219 continue;
220 }
221 ep->tdev = stp->st_rdev;
222 /*
223 * If this is the console device, attempt to ascertain
224 * the true console device dev_t.
225 */
226 if (ep->tdev == 0) {
227 int mib[2];
228 size_t size;
229
230 mib[0] = CTL_KERN;
231 mib[1] = KERN_CONSDEV;
232 size = sizeof(dev_t);
233 (void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
234 }
235 if ((ep->idle = now - stp->st_atime) < 0)
236 ep->idle = 0;
237 }
238 if (ut)
239 (void)fclose(ut);
240 else
241 nusers = 1;
242
243 if (header || wcmd == 0) {
244 pr_header(&now, nusers);
245 if (wcmd == 0)
246 exit (0);
247 }
248
249 if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
250 sizeof(struct kinfo_proc2), &nentries)) == NULL)
251 errx(1, "%s", kvm_geterr(kd));
252
253 /* Include trailing space because TTY header starts one column early. */
254 lognamelen = sizeof("USER ") - 1 /* NUL */;
255 for (i = 0; i < nentries; i++, kp++) {
256
257 if (kp->p_stat == SIDL || kp->p_stat == SZOMB)
258 continue;
259
260 for (ep = ehead; ep != NULL; ep = ep->next) {
261 if (ep->tdev == kp->p_tdev
262 && kp->p__pgid == kp->p_tpgid) {
263 /*
264 * Proc is in foreground of this terminal
265 */
266 if (proc_compare(ep->kp, kp)) {
267 ep->kp = kp;
268 lognamelen = max(lognamelen,
269 strlen(kp->p_login));
270 }
271 break;
272 }
273 #ifdef SUPPORT_FTPD_UTMP
274 /*
275 * Hack to match process to ftp utmp entry.
276 */
277 else if (ep->tdev == 0 && kp->p_tdev == NODEV
278 && ep->ftpd_pid == kp->p_pid) {
279 ep->kp = kp;
280 lognamelen = max(lognamelen,
281 strlen(kp->p_login));
282 }
283 #endif /* SUPPORT_FTPD_UTMP */
284 }
285 }
286
287 argwidth = printf("%-*sTTY %-*s %*s IDLE WHAT\n",
288 lognamelen, "USER", UT_HOSTSIZE, "FROM",
289 7 /* "dddhhXm" */, "LOGIN@");
290 argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
291
292 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
293 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
294 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
295 ttywidth = 79;
296 else
297 ttywidth = ws.ws_col - 1;
298 argwidth = ttywidth - argwidth;
299 if (argwidth < 4)
300 argwidth = 8;
301 /* sort by idle time */
302 if (sortidle && ehead != NULL) {
303 struct entry *from = ehead, *save;
304
305 ehead = NULL;
306 while (from != NULL) {
307 for (nextp = &ehead;
308 (*nextp) && from->idle >= (*nextp)->idle;
309 nextp = &(*nextp)->next)
310 continue;
311 save = from;
312 from = from->next;
313 save->next = *nextp;
314 *nextp = save;
315 }
316 }
317
318 if (!nflag) {
319 int rv;
320
321 rv = gethostname(domain, sizeof(domain));
322 domain[sizeof(domain) - 1] = '\0';
323 if (rv < 0 || (p = strchr(domain, '.')) == 0)
324 domain[0] = '\0';
325 else
326 memmove(domain, p, strlen(p) + 1);
327 }
328
329 for (ep = ehead; ep != NULL; ep = ep->next) {
330 p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
331 for (x = p; x < p + UT_HOSTSIZE; x++)
332 if (*x == '\0' || *x == ':')
333 break;
334 if (x == p + UT_HOSTSIZE || *x != ':')
335 x = NULL;
336 else
337 *x++ = '\0';
338
339 if (!nflag && inet_aton(p, &l) &&
340 (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
341 if (domain[0] != '\0') {
342 p = hp->h_name;
343 p += strlen(hp->h_name);
344 p -= strlen(domain);
345 if (p > hp->h_name && strcmp(p, domain) == 0)
346 *p = '\0';
347 }
348 p = hp->h_name;
349 }
350 if (x) {
351 (void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
352 (int)(ep->utmp.ut_host + UT_HOSTSIZE - x), x);
353 p = buf;
354 }
355 if (ep->kp == NULL) {
356 warnx("Stale utmp entry: %.*s %.*s %.*s",
357 UT_NAMESIZE, ep->utmp.ut_name,
358 UT_LINESIZE, ep->utmp.ut_line,
359 UT_HOSTSIZE, ep->utmp.ut_host);
360 continue;
361 }
362 (void)printf("%-*s %-2.2s %-*.*s ",
363 lognamelen, ep->kp->p_login,
364 (strncmp(ep->utmp.ut_line, "tty", 3) &&
365 strncmp(ep->utmp.ut_line, "dty", 3)) ?
366 ep->utmp.ut_line : ep->utmp.ut_line + 3,
367 UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
368 pr_attime(&ep->utmp.ut_time, &now);
369 pr_idle(ep->idle);
370 pr_args(ep->kp);
371 (void)printf("\n");
372 }
373 exit(0);
374 }
375
376 static void
377 pr_args(kp)
378 struct kinfo_proc2 *kp;
379 {
380 char **argv;
381 int left;
382
383 if (kp == 0)
384 goto nothing;
385 left = argwidth;
386 argv = kvm_getargv2(kd, kp, argwidth);
387 if (argv == 0)
388 goto nothing;
389 while (*argv) {
390 fmt_puts(*argv, &left);
391 argv++;
392 fmt_putc(' ', &left);
393 }
394 return;
395 nothing:
396 putchar('-');
397 }
398
399 static void
400 pr_header(nowp, nusers)
401 time_t *nowp;
402 int nusers;
403 {
404 double avenrun[3];
405 time_t uptime;
406 int days, hrs, i, mins;
407 int mib[2];
408 size_t size;
409 char buf[256];
410
411 /*
412 * Print time of day.
413 *
414 * SCCS forces the string manipulation below, as it replaces
415 * %, M, and % in a character string with the file name.
416 */
417 (void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
418 buf[sizeof(buf) - 1] = '\0';
419 (void)printf("%s ", buf);
420
421 /*
422 * Print how long system has been up.
423 * (Found by looking getting "boottime" from the kernel)
424 */
425 mib[0] = CTL_KERN;
426 mib[1] = KERN_BOOTTIME;
427 size = sizeof(boottime);
428 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
429 boottime.tv_sec != 0) {
430 uptime = now - boottime.tv_sec;
431 uptime += 30;
432 if (uptime > SECSPERMIN) {
433 days = uptime / SECSPERDAY;
434 uptime %= SECSPERDAY;
435 hrs = uptime / SECSPERHOUR;
436 uptime %= SECSPERHOUR;
437 mins = uptime / SECSPERMIN;
438 (void)printf(" up");
439 if (days > 0)
440 (void)printf(" %d day%s,", days,
441 days > 1 ? "s" : "");
442 if (hrs > 0 && mins > 0)
443 (void)printf(" %2d:%02d,", hrs, mins);
444 else {
445 if (hrs > 0)
446 (void)printf(" %d hr%s,",
447 hrs, hrs > 1 ? "s" : "");
448 if (mins > 0)
449 (void)printf(" %d min%s,",
450 mins, mins > 1 ? "s" : "");
451 }
452 }
453 }
454
455 /* Print number of users logged in to system */
456 (void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
457
458 /*
459 * Print 1, 5, and 15 minute load averages.
460 */
461 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
462 (void)printf(", no load average information available\n");
463 else {
464 (void)printf(", load averages:");
465 for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
466 if (i > 0)
467 (void)printf(",");
468 (void)printf(" %.2f", avenrun[i]);
469 }
470 (void)printf("\n");
471 }
472 }
473
474 static struct stat *
475 ttystat(line)
476 char *line;
477 {
478 static struct stat sb;
479 char ttybuf[MAXPATHLEN];
480
481 (void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
482 if (stat(ttybuf, &sb))
483 return (NULL);
484 return (&sb);
485 }
486
487 static void
488 usage(wcmd)
489 int wcmd;
490 {
491 if (wcmd)
492 (void)fprintf(stderr,
493 "usage: w: [-hin] [-M core] [-N system] [user]\n");
494 else
495 (void)fprintf(stderr, "uptime\n");
496 exit(1);
497 }
498