w.c revision 48566
1219561Savg/*-
2219561Savg * Copyright (c) 1980, 1991, 1993, 1994
3262818Smarcel *	The Regents of the University of California.  All rights reserved.
4219561Savg *
5262818Smarcel * Redistribution and use in source and binary forms, with or without
6262818Smarcel * modification, are permitted provided that the following conditions
7219561Savg * are met:
8220437Sart * 1. Redistributions of source code must retain the above copyright
9219561Savg *    notice, this list of conditions and the following disclaimer.
10219561Savg * 2. Redistributions in binary form must reproduce the above copyright
11219561Savg *    notice, this list of conditions and the following disclaimer in the
12262818Smarcel *    documentation and/or other materials provided with the distribution.
13262818Smarcel * 3. All advertising materials mentioning features or use of this software
14289769Sjhb *    must display the following acknowledgement:
15219561Savg *	This product includes software developed by the University of
16219561Savg *	California, Berkeley and its contributors.
17253996Savg * 4. Neither the name of the University nor the names of its contributors
18262818Smarcel *    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
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
43#endif
44static const char rcsid[] =
45	"$Id: w.c,v 1.34 1999/04/22 23:40:56 ache Exp $";
46#endif /* not lint */
47
48/*
49 * w - print system status (who and what)
50 *
51 * This program is similar to the systat command on Tenex/Tops 10/20
52 *
53 */
54#include <sys/param.h>
55#include <sys/time.h>
56#include <sys/stat.h>
57#include <sys/sysctl.h>
58#include <sys/proc.h>
59#include <sys/user.h>
60#include <sys/ioctl.h>
61#include <sys/socket.h>
62#include <sys/tty.h>
63
64#include <machine/cpu.h>
65#include <netinet/in.h>
66#include <arpa/inet.h>
67
68#include <ctype.h>
69#include <err.h>
70#include <errno.h>
71#include <fcntl.h>
72#include <kvm.h>
73#include <netdb.h>
74#include <nlist.h>
75#include <paths.h>
76#include <stdio.h>
77#include <stdlib.h>
78#include <string.h>
79#include <unistd.h>
80#include <utmp.h>
81#include <vis.h>
82#include <locale.h>
83
84#include <arpa/nameser.h>
85#include <resolv.h>
86
87#include "extern.h"
88
89struct timeval	boottime;
90struct utmp	utmp;
91struct winsize	ws;
92kvm_t	       *kd;
93time_t		now;		/* the current time of day */
94time_t		uptime;		/* time of last reboot & elapsed time since */
95int		ttywidth;	/* width of tty */
96int		argwidth;	/* width of tty */
97int		header = 1;	/* true if -h flag: don't print heading */
98int		nflag;		/* true if -n flag: don't convert addrs */
99int		dflag;		/* true if -d flag: output debug info */
100int		sortidle;	/* sort by idle time */
101char	       *sel_user;	/* login of particular user selected */
102char		domain[MAXHOSTNAMELEN];
103
104/*
105 * One of these per active utmp entry.
106 */
107struct	entry {
108	struct	entry *next;
109	struct	utmp utmp;
110	dev_t	tdev;			/* dev_t of terminal */
111	time_t	idle;			/* idle time of terminal in seconds */
112	struct	kinfo_proc *kp;		/* `most interesting' proc */
113	char	*args;			/* arg list of interesting process */
114	struct	kinfo_proc *dkp;	/* debug option proc list */
115} *ep, *ehead = NULL, **nextp = &ehead;
116
117static void	pr_header __P((time_t *, int));
118static struct stat
119		*ttystat __P((char *, int));
120static void	usage __P((int));
121static int	this_is_uptime __P((const char *s));
122
123char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
124
125int
126main(argc, argv)
127	int argc;
128	char **argv;
129{
130	struct kinfo_proc *kp;
131	struct kinfo_proc *dkp;
132	struct hostent *hp;
133	struct stat *stp;
134	FILE *ut;
135	u_long l;
136	int ch, i, nentries, nusers, wcmd, longidle;
137	char *memf, *nlistf, *p, *x;
138	char buf[MAXHOSTNAMELEN], errbuf[256];
139
140	(void) setlocale(LC_ALL, "");
141
142	/* Are we w(1) or uptime(1)? */
143	if (this_is_uptime(argv[0]) == 0) {
144		wcmd = 0;
145		p = "";
146	} else {
147		wcmd = 1;
148		p = "dhiflM:N:nsuw";
149	}
150
151	memf = nlistf = NULL;
152	while ((ch = getopt(argc, argv, p)) != -1)
153		switch (ch) {
154		case 'd':
155			dflag = 1;
156			break;
157		case 'h':
158			header = 0;
159			break;
160		case 'i':
161			sortidle = 1;
162			break;
163		case 'M':
164			header = 0;
165			memf = optarg;
166			break;
167		case 'N':
168			nlistf = optarg;
169			break;
170		case 'n':
171			nflag = 1;
172			break;
173		case 'f': case 'l': case 's': case 'u': case 'w':
174			warnx("[-flsuw] no longer supported");
175			/* FALLTHROUGH */
176		case '?':
177		default:
178			usage(wcmd);
179		}
180	argc -= optind;
181	argv += optind;
182
183	if (!(_res.options & RES_INIT))
184		res_init();
185	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
186	_res.retry = 1;		/* only try once.. */
187
188	/*
189	 * Discard setgid privileges if not the running kernel so that bad
190	 * guys can't print interesting stuff from kernel memory.
191	 */
192	if (nlistf != NULL || memf != NULL)
193		setgid(getgid());
194
195	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
196		errx(1, "%s", errbuf);
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		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
209			continue;	/* corrupted record */
210		++nusers;
211		if (wcmd == 0 || (sel_user &&
212		    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
213			continue;
214		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
215			errx(1, "calloc");
216		*nextp = ep;
217		nextp = &(ep->next);
218		memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
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#define HEADER_USER		"USER"
246#define HEADER_TTY		"TTY"
247#define HEADER_FROM		"FROM"
248#define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
249#define HEADER_WHAT		"WHAT\n"
250#define WUSED  (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \
251		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
252		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
253				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
254				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
255				UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM,
256				HEADER_LOGIN_IDLE HEADER_WHAT);
257	}
258
259	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
260		err(1, "%s", kvm_geterr(kd));
261	for (i = 0; i < nentries; i++, kp++) {
262		struct proc *pr = &kp->kp_proc;
263		struct eproc *e;
264
265		if (pr->p_stat == SIDL || pr->p_stat == SZOMB)
266			continue;
267		e = &kp->kp_eproc;
268		for (ep = ehead; ep != NULL; ep = ep->next) {
269			if (ep->tdev == e->e_tdev) {
270				/*
271				 * proc is associated with this terminal
272				 */
273				if (ep->kp == NULL && e->e_pgid == e->e_tpgid) {
274					/*
275					 * Proc is 'most interesting'
276					 */
277					if (proc_compare(&ep->kp->kp_proc, pr))
278						ep->kp = kp;
279				}
280				/*
281				 * Proc debug option info; add to debug
282				 * list using kinfo_proc kp_eproc.e_spare
283				 * as next pointer; ptr to ptr avoids the
284				 * ptr = long assumption.
285				 */
286				dkp = ep->dkp;
287				ep->dkp = kp;
288				*((struct kinfo_proc **)(&kp->kp_eproc.e_spare[0])) = dkp;
289			}
290		}
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 - WUSED;
299	if (argwidth < 4)
300		argwidth = 8;
301	for (ep = ehead; ep != NULL; ep = ep->next) {
302		if (ep->kp == NULL) {
303			ep->args = "-";
304			continue;
305		}
306		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
307		    ep->kp->kp_proc.p_comm, MAXCOMLEN);
308		if (ep->args == NULL)
309			err(1, NULL);
310	}
311	/* sort by idle time */
312	if (sortidle && ehead != NULL) {
313		struct entry *from = ehead, *save;
314
315		ehead = NULL;
316		while (from != NULL) {
317			for (nextp = &ehead;
318			    (*nextp) && from->idle >= (*nextp)->idle;
319			    nextp = &(*nextp)->next)
320				continue;
321			save = from;
322			from = from->next;
323			save->next = *nextp;
324			*nextp = save;
325		}
326	}
327
328	if (!nflag) {
329		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
330		    (p = strchr(domain, '.')) == 0)
331			domain[0] = '\0';
332		else {
333			domain[sizeof(domain) - 1] = '\0';
334			memmove(domain, p, strlen(p) + 1);
335		}
336	}
337
338	for (ep = ehead; ep != NULL; ep = ep->next) {
339		char host_buf[UT_HOSTSIZE + 1];
340
341		host_buf[UT_HOSTSIZE] = '\0';
342		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
343		p = *host_buf ? host_buf : "-";
344		if ((x = strchr(p, ':')) != NULL)
345			*x++ = '\0';
346		if (!nflag && isdigit(*p) &&
347		    (long)(l = inet_addr(p)) != -1 &&
348		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
349			if (domain[0] != '\0') {
350				p = hp->h_name;
351				p += strlen(hp->h_name);
352				p -= strlen(domain);
353				if (p > hp->h_name && strcmp(p, domain) == 0)
354					*p = '\0';
355			}
356			p = hp->h_name;
357		}
358		if (nflag && *p && strcmp(p, "-") &&
359		    inet_addr(p) == INADDR_NONE) {
360			hp = gethostbyname(p);
361
362			if (hp != NULL) {
363				struct in_addr in;
364
365				memmove(&in, hp->h_addr, sizeof(in));
366				p = inet_ntoa(in);
367			}
368		}
369		if (x) {
370			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
371			p = buf;
372		}
373		if (dflag) {
374			for (dkp = ep->dkp; dkp != NULL; dkp = *((struct kinfo_proc **)(&dkp->kp_eproc.e_spare[0]))) {
375				char *ptr;
376				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
377					    dkp->kp_proc.p_comm, MAXCOMLEN);
378				if (ptr == NULL)
379					ptr = "-";
380				(void)printf( "\t\t%-9d %s\n", dkp->kp_proc.p_pid, ptr);
381			}
382		}
383		(void)printf("%-*.*s %-*.*s %-*.*s ",
384		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
385		    UT_LINESIZE, UT_LINESIZE,
386		    strncmp(ep->utmp.ut_line, "tty", 3) &&
387		    strncmp(ep->utmp.ut_line, "cua", 3) ?
388		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
389		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
390		pr_attime(&ep->utmp.ut_time, &now);
391		longidle = pr_idle(ep->idle);
392		(void)printf("%.*s\n", argwidth - longidle, ep->args);
393	}
394	exit(0);
395}
396
397static void
398pr_header(nowp, nusers)
399	time_t *nowp;
400	int nusers;
401{
402	double avenrun[3];
403	time_t uptime;
404	int days, hrs, i, mins, secs;
405	int mib[2];
406	size_t size;
407	char buf[256];
408
409	/*
410	 * Print time of day.
411	 *
412	 * SCCS forces the string manipulation below, as it replaces
413	 * %, M, and % in a character string with the file name.
414	 */
415	(void)strftime(buf, sizeof(buf) - 1,
416	    __CONCAT("%l:%","M%p"), localtime(nowp));
417	buf[sizeof(buf) - 1] = '\0';
418	(void)printf("%s ", buf);
419
420	/*
421	 * Print how long system has been up.
422	 * (Found by looking getting "boottime" from the kernel)
423	 */
424	mib[0] = CTL_KERN;
425	mib[1] = KERN_BOOTTIME;
426	size = sizeof(boottime);
427	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
428	    boottime.tv_sec != 0) {
429		uptime = now - boottime.tv_sec;
430		uptime += 30;
431		days = uptime / 86400;
432		uptime %= 86400;
433		hrs = uptime / 3600;
434		uptime %= 3600;
435		mins = uptime / 60;
436		secs = uptime % 60;
437		(void)printf(" up");
438		if (days > 0)
439			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
440		if (hrs > 0 && mins > 0)
441			(void)printf(" %2d:%02d,", hrs, mins);
442		else if (hrs > 0)
443			(void)printf(" %d hr%s,",
444				     hrs, hrs > 1 ? "s" : "");
445		else if (mins > 0)
446			(void)printf(" %d min%s,",
447				     mins, mins > 1 ? "s" : "");
448		else
449			(void)printf(" %d sec%s,",
450				     secs, secs > 1 ? "s" : "");
451	}
452
453	/* Print number of users logged in to system */
454	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
455
456	/*
457	 * Print 1, 5, and 15 minute load averages.
458	 */
459	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
460		(void)printf(", no load average information available\n");
461	else {
462		(void)printf(", load averages:");
463		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
464			if (i > 0)
465				(void)printf(",");
466			(void)printf(" %.2f", avenrun[i]);
467		}
468		(void)printf("\n");
469	}
470}
471
472static struct stat *
473ttystat(line, sz)
474	char *line;
475	int sz;
476{
477	static struct stat sb;
478	char ttybuf[MAXPATHLEN];
479
480	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
481	if (stat(ttybuf, &sb)) {
482		warn("%s", ttybuf);
483		return NULL;
484	}
485	return (&sb);
486}
487
488static void
489usage(wcmd)
490	int wcmd;
491{
492	if (wcmd)
493		(void)fprintf(stderr,
494		    "usage: w [-dhin] [-M core] [-N system] [user]\n");
495	else
496		(void)fprintf(stderr,
497			"usage: uptime\n");
498	exit (1);
499}
500
501static int
502this_is_uptime(s)
503	const char *s;
504{
505	const char *u;
506
507	if ((u = strrchr(s, '/')) != NULL)
508		++u;
509	else
510		u = s;
511	if (strcmp(u, "uptime") == 0)
512		return(0);
513	return(-1);
514}
515
516