w.c revision 1.32 1 /* $NetBSD: w.c,v 1.32 1999/10/11 12:00:19 mrg 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.32 1999/10/11 12:00:19 mrg 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/time.h>
58 #include <sys/stat.h>
59 #include <sys/sysctl.h>
60 #include <sys/proc.h>
61 #include <sys/user.h>
62 #include <sys/ioctl.h>
63 #include <sys/socket.h>
64
65 #include <machine/cpu.h>
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 struct timeval boottime;
90 struct utmp utmp;
91 struct winsize ws;
92 kvm_t *kd;
93 time_t now; /* the current time of day */
94 time_t uptime; /* time of last reboot & elapsed time since */
95 int ttywidth; /* width of tty */
96 int argwidth; /* width of tty */
97 int header = 1; /* true if -h flag: don't print heading */
98 int nflag; /* true if -n flag: don't convert addrs */
99 int sortidle; /* sort bu idle time */
100 char *sel_user; /* login of particular user selected */
101 char domain[MAXHOSTNAMELEN + 1];
102
103 /*
104 * One of these per active utmp entry.
105 */
106 struct entry {
107 struct entry *next;
108 struct utmp utmp;
109 dev_t tdev; /* dev_t of terminal */
110 time_t idle; /* idle time of terminal in seconds */
111 struct kinfo_proc *kp; /* `most interesting' proc */
112 } *ep, *ehead = NULL, **nextp = &ehead;
113
114 static void pr_args __P((struct kinfo_proc *));
115 static void pr_header __P((time_t *, int));
116 static struct stat
117 *ttystat __P((char *));
118 static void usage __P((int));
119 int main __P((int, char **));
120
121 int
122 main(argc, argv)
123 int argc;
124 char **argv;
125 {
126 extern char *__progname;
127 struct kinfo_proc *kp;
128 struct hostent *hp;
129 struct stat *stp;
130 FILE *ut;
131 struct in_addr l;
132 int ch, i, nentries, nusers, wcmd;
133 gid_t egid = getegid();
134 char *memf, *nlistf, *p, *x;
135 char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
136
137 (void)setegid(getgid());
138
139 /* Are we w(1) or uptime(1)? */
140 p = __progname;
141 if (*p == '-')
142 p++;
143 if (*p == 'u') {
144 wcmd = 0;
145 p = "";
146 } else {
147 wcmd = 1;
148 p = "hiflM:N:nsuw";
149 }
150
151 memf = nlistf = NULL;
152 while ((ch = getopt(argc, argv, p)) != -1)
153 switch (ch) {
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 break;
164 case 'N':
165 nlistf = optarg;
166 break;
167 case 'n':
168 nflag = 1;
169 break;
170 case 'f': case 'l': case 's': case 'u': case 'w':
171 warnx("[-flsuw] no longer supported");
172 /* FALLTHROUGH */
173 case '?':
174 default:
175 usage(wcmd);
176 }
177 argc -= optind;
178 argv += optind;
179
180 /*
181 * Discard setgid privileges. If not the running kernel, we toss
182 * them away totally so that bad guys can't print interesting stuff
183 * from kernel memory, otherwise switch back to kmem for the
184 * duration of the kvm_openfiles() call.
185 */
186 if (nlistf != NULL || memf != NULL)
187 (void)setgid(getgid());
188 else
189 (void)setegid(egid);
190
191 if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
192 errx(1, "%s", errbuf);
193
194 /* get rid of it now anyway */
195 if (nlistf == NULL && memf == NULL)
196 (void)setgid(getgid());
197
198 (void)time(&now);
199 if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
200 err(1, "%s", _PATH_UTMP);
201
202 if (*argv)
203 sel_user = *argv;
204
205 for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
206 if (utmp.ut_name[0] == '\0')
207 continue;
208 ++nusers;
209 if (wcmd == 0 || (sel_user &&
210 strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
211 continue;
212 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
213 err(1, "%s", "");
214 *nextp = ep;
215 nextp = &(ep->next);
216 memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
217 if (!(stp = ttystat(ep->utmp.ut_line)))
218 continue;
219 ep->tdev = stp->st_rdev;
220 #ifdef CPU_CONSDEV
221 /*
222 * If this is the console device, attempt to ascertain
223 * the true console device dev_t.
224 */
225 if (ep->tdev == 0) {
226 int mib[2];
227 size_t size;
228
229 mib[0] = CTL_MACHDEP;
230 mib[1] = CPU_CONSDEV;
231 size = sizeof(dev_t);
232 (void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
233 }
234 #endif
235 if ((ep->idle = now - stp->st_atime) < 0)
236 ep->idle = 0;
237 }
238 (void)fclose(ut);
239
240 if (header || wcmd == 0) {
241 pr_header(&now, nusers);
242 if (wcmd == 0)
243 exit (0);
244 }
245
246 #define HEADER "USER TTY FROM LOGIN@ IDLE WHAT\n"
247 #define WUSED (sizeof (HEADER) - sizeof ("WHAT\n"))
248 (void)printf(HEADER);
249
250 if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
251 errx(1, "%s", kvm_geterr(kd));
252 for (i = 0; i < nentries; i++, kp++) {
253 struct proc *p = &kp->kp_proc;
254 struct eproc *e;
255
256 if (p->p_stat == SIDL || p->p_stat == SZOMB)
257 continue;
258 e = &kp->kp_eproc;
259 for (ep = ehead; ep != NULL; ep = ep->next) {
260 if (ep->tdev == e->e_tdev && e->e_pgid == e->e_tpgid) {
261 /*
262 * Proc is in foreground of this terminal
263 */
264 if (proc_compare(&ep->kp->kp_proc, p))
265 ep->kp = kp;
266 break;
267 }
268 }
269 }
270 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
271 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
272 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
273 ttywidth = 79;
274 else
275 ttywidth = ws.ws_col - 1;
276 argwidth = ttywidth - WUSED;
277 if (argwidth < 4)
278 argwidth = 8;
279 /* sort by idle time */
280 if (sortidle && ehead != NULL) {
281 struct entry *from = ehead, *save;
282
283 ehead = NULL;
284 while (from != NULL) {
285 for (nextp = &ehead;
286 (*nextp) && from->idle >= (*nextp)->idle;
287 nextp = &(*nextp)->next)
288 continue;
289 save = from;
290 from = from->next;
291 save->next = *nextp;
292 *nextp = save;
293 }
294 }
295
296 if (!nflag) {
297 int rv;
298
299 rv = gethostname(domain, sizeof(domain));
300 domain[sizeof(domain) - 1] = '\0';
301 if (rv < 0 || (p = strchr(domain, '.')) == 0)
302 domain[0] = '\0';
303 else
304 memmove(domain, p, strlen(p) + 1);
305 }
306
307 for (ep = ehead; ep != NULL; ep = ep->next) {
308 p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
309 for (x = p; x < p + UT_HOSTSIZE; x++)
310 if (*x == '\0' || *x == ':')
311 break;
312 if (x == p + UT_HOSTSIZE || *x != ':')
313 x = NULL;
314 else
315 *x++ = '\0';
316
317 if (!nflag && inet_aton(p, &l) &&
318 (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
319 if (domain[0] != '\0') {
320 p = hp->h_name;
321 p += strlen(hp->h_name);
322 p -= strlen(domain);
323 if (p > hp->h_name && strcmp(p, domain) == 0)
324 *p = '\0';
325 }
326 p = hp->h_name;
327 }
328 if (x) {
329 (void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
330 (int)(ep->utmp.ut_host + UT_HOSTSIZE - x), x);
331 p = buf;
332 }
333 (void)printf("%-*.*s %-2.2s %-*.*s ",
334 UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
335 (strncmp(ep->utmp.ut_line, "tty", 3) &&
336 strncmp(ep->utmp.ut_line, "dty", 3)) ?
337 ep->utmp.ut_line : ep->utmp.ut_line + 3,
338 UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
339 pr_attime(&ep->utmp.ut_time, &now);
340 pr_idle(ep->idle);
341 pr_args(ep->kp);
342 printf("\n");
343 }
344 exit(0);
345 }
346
347 static void
348 pr_args(kp)
349 struct kinfo_proc *kp;
350 {
351 char **argv;
352 int left;
353
354 if (kp == 0)
355 goto nothing;
356 left = argwidth;
357 argv = kvm_getargv(kd, kp, argwidth);
358 if (argv == 0)
359 goto nothing;
360 while (*argv) {
361 fmt_puts(*argv, &left);
362 argv++;
363 fmt_putc(' ', &left);
364 }
365 return;
366 nothing:
367 putchar('-');
368 }
369
370 static void
371 pr_header(nowp, nusers)
372 time_t *nowp;
373 int nusers;
374 {
375 double avenrun[3];
376 time_t uptime;
377 int days, hrs, i, mins;
378 int mib[2];
379 size_t size;
380 char buf[256];
381
382 /*
383 * Print time of day.
384 *
385 * SCCS forces the string manipulation below, as it replaces
386 * %, M, and % in a character string with the file name.
387 */
388 (void)strftime(buf, sizeof(buf),
389 __CONCAT("%l:%","M%p"), localtime(nowp));
390 buf[sizeof(buf) - 1] = '\0';
391 (void)printf("%s ", buf);
392
393 /*
394 * Print how long system has been up.
395 * (Found by looking getting "boottime" from the kernel)
396 */
397 mib[0] = CTL_KERN;
398 mib[1] = KERN_BOOTTIME;
399 size = sizeof(boottime);
400 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
401 boottime.tv_sec != 0) {
402 uptime = now - boottime.tv_sec;
403 uptime += 30;
404 if (uptime > SECSPERMIN) {
405 days = uptime / SECSPERDAY;
406 uptime %= SECSPERDAY;
407 hrs = uptime / SECSPERHOUR;
408 uptime %= SECSPERHOUR;
409 mins = uptime / SECSPERMIN;
410 (void)printf(" up");
411 if (days > 0)
412 (void)printf(" %d day%s,", days,
413 days > 1 ? "s" : "");
414 if (hrs > 0 && mins > 0)
415 (void)printf(" %2d:%02d,", hrs, mins);
416 else {
417 if (hrs > 0)
418 (void)printf(" %d hr%s,",
419 hrs, hrs > 1 ? "s" : "");
420 if (mins > 0)
421 (void)printf(" %d min%s,",
422 mins, mins > 1 ? "s" : "");
423 }
424 }
425 }
426
427 /* Print number of users logged in to system */
428 (void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
429
430 /*
431 * Print 1, 5, and 15 minute load averages.
432 */
433 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
434 (void)printf(", no load average information available\n");
435 else {
436 (void)printf(", load averages:");
437 for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
438 if (i > 0)
439 (void)printf(",");
440 (void)printf(" %.2f", avenrun[i]);
441 }
442 (void)printf("\n");
443 }
444 }
445
446 static struct stat *
447 ttystat(line)
448 char *line;
449 {
450 static struct stat sb;
451 char ttybuf[MAXPATHLEN];
452
453 (void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
454 if (stat(ttybuf, &sb))
455 return (NULL);
456 return (&sb);
457 }
458
459 static void
460 usage(wcmd)
461 int wcmd;
462 {
463 if (wcmd)
464 (void)fprintf(stderr,
465 "usage: w: [-hin] [-M core] [-N system] [user]\n");
466 else
467 (void)fprintf(stderr, "uptime\n");
468 exit(1);
469 }
470