xref: /original-bsd/usr.bin/w/w.c (revision ab6c2785)
1 /*-
2  * Copyright (c) 1980, 1991 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1980, 1991 The Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)w.c	5.37 (Berkeley) 05/21/93";
16 #endif /* not lint */
17 
18 /*
19  * w - print system status (who and what)
20  *
21  * This program is similar to the systat command on Tenex/Tops 10/20
22  *
23  */
24 #include <sys/param.h>
25 #include <sys/time.h>
26 #include <sys/stat.h>
27 #include <sys/sysctl.h>
28 #include <sys/proc.h>
29 #include <sys/user.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
32 #include <sys/tty.h>
33 
34 #include <machine/cpu.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
37 
38 #include <ctype.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <kvm.h>
43 #include <netdb.h>
44 #include <nlist.h>
45 #include <paths.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <tzfile.h>
50 #include <unistd.h>
51 #include <utmp.h>
52 
53 #include "extern.h"
54 
55 struct timeval boottime;
56 struct utmp utmp;
57 struct winsize ws;
58 kvm_t *kd;
59 time_t now;			/* the current time of day */
60 time_t uptime;			/* time of last reboot & elapsed time since */
61 int ttywidth;			/* width of tty */
62 int argwidth;			/* width of tty */
63 int header = 1;			/* true if -h flag: don't print heading */
64 int nflag;			/* true if -n flag: don't convert addrs */
65 int sortidle;			/* sort bu idle time */
66 char *sel_user;			/* login of particular user selected */
67 char *program;
68 char domain[MAXHOSTNAMELEN];
69 
70 /*
71  * One of these per active utmp entry.
72  */
73 struct	entry {
74 	struct	entry *next;
75 	struct	utmp utmp;
76 	dev_t	tdev;		/* dev_t of terminal */
77 	time_t	idle;		/* idle time of terminal in seconds */
78 	struct	kinfo_proc *kp;	/* `most interesting' proc */
79 	char	*args;		/* arg list of interesting process */
80 } *ep, *ehead = NULL, **nextp = &ehead;
81 
82 static void	 pr_header __P((time_t *, int));
83 static struct stat
84 		*ttystat __P((char *));
85 static void	 usage __P((int));
86 
87 char *fmt_argv __P((char **, char *, int));
88 
89 int
90 main(argc, argv)
91 	int argc;
92 	char **argv;
93 {
94 	extern char *optarg;
95 	extern int optind;
96 	struct kinfo_proc *kp;
97 	struct hostent *hp;
98 	struct stat *stp;
99 	FILE *ut;
100 	u_long l;
101 	int ch, i, nentries, nusers, wcmd;
102 	char *memf, *nlistf, *p, *x;
103 	char buf[MAXHOSTNAMELEN], errbuf[256];
104 
105 	/* Are we w(1) or uptime(1)? */
106 	program = argv[0];
107 	if ((p = rindex(program, '/')) || *(p = program) == '-')
108 		p++;
109 	if (*p == 'u') {
110 		wcmd = 0;
111 		p = "";
112 	} else {
113 		wcmd = 1;
114 		p = "hiflM:N:nsuw";
115 	}
116 
117 	memf = nlistf = NULL;
118 	while ((ch = getopt(argc, argv, p)) != EOF)
119 		switch (ch) {
120 		case 'h':
121 			header = 0;
122 			break;
123 		case 'i':
124 			sortidle = 1;
125 			break;
126 		case 'M':
127 			header = 0;
128 			memf = optarg;
129 			break;
130 		case 'N':
131 			nlistf = optarg;
132 			break;
133 		case 'n':
134 			nflag = 1;
135 			break;
136 		case 'f': case 'l': case 's': case 'u': case 'w':
137 			warnx("[-flsuw] no longer supported");
138 			/* FALLTHROUGH */
139 		case '?':
140 		default:
141 			usage(wcmd);
142 		}
143 	argc -= optind;
144 	argv += optind;
145 
146 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
147 		err(1, "%s", errbuf);
148 
149 	(void)time(&now);
150 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
151 		err(1, "%s", _PATH_UTMP);
152 
153 	if (*argv)
154 		sel_user = *argv;
155 
156 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
157 		if (utmp.ut_name[0] == '\0')
158 			continue;
159 		++nusers;
160 		if (wcmd == 0 || (sel_user &&
161 		    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
162 			continue;
163 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
164 			err(1, NULL);
165 		*nextp = ep;
166 		nextp = &(ep->next);
167 		bcopy(&utmp, &(ep->utmp), sizeof (struct utmp));
168 		stp = ttystat(ep->utmp.ut_line);
169 		ep->tdev = stp->st_rdev;
170 #ifdef CPU_CONSDEV
171 		/*
172 		 * If this is the console device, attempt to ascertain
173 		 * the true console device dev_t.
174 		 */
175 		if (ep->tdev == 0) {
176 			int mib[2], size;
177 
178 			mib[0] = CTL_MACHDEP;
179 			mib[1] = CPU_CONSDEV;
180 			size = sizeof(dev_t);
181 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
182 		}
183 #endif
184 		if ((ep->idle = now - stp->st_atime) < 0)
185 			ep->idle = 0;
186 	}
187 	(void)fclose(ut);
188 
189 	if (header || wcmd == 0) {
190 		pr_header(&now, nusers);
191 		if (wcmd == 0)
192 			exit (0);
193 	}
194 
195 #define HEADER	"USER    TTY FROM              LOGIN@  IDLE WHAT\n"
196 #define WUSED	(sizeof (HEADER) - sizeof ("WHAT\n"))
197 	(void)printf(HEADER);
198 
199 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
200 		err(1, "%s", kvm_geterr(kd));
201 	for (i = 0; i < nentries; i++, kp++) {
202 		register struct proc *p = &kp->kp_proc;
203 		register struct eproc *e;
204 
205 		if (p->p_stat == SIDL || p->p_stat == SZOMB)
206 			continue;
207 		e = &kp->kp_eproc;
208 		for (ep = ehead; ep != NULL; ep = ep->next) {
209 			if (ep->tdev == e->e_tdev && e->e_pgid == e->e_tpgid) {
210 				/*
211 				 * Proc is in foreground of this terminal
212 				 */
213 				if (proc_compare(&ep->kp->kp_proc, p))
214 					ep->kp = kp;
215 				break;
216 			}
217 		}
218 	}
219 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
220 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
221 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
222 	       ttywidth = 79;
223         else
224 	       ttywidth = ws.ws_col - 1;
225 	argwidth = ttywidth - WUSED;
226 	if (argwidth < 4)
227 		argwidth = 8;
228 	for (ep = ehead; ep != NULL; ep = ep->next) {
229 		if (ep->kp == NULL) {
230 			ep->args = "-";
231 			continue;
232 		}
233 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
234 		    ep->kp->kp_proc.p_comm, MAXCOMLEN);
235 		if (ep->args == NULL)
236 			err(1, NULL);
237 	}
238 	/* sort by idle time */
239 	if (sortidle && ehead != NULL) {
240 		struct entry *from = ehead, *save;
241 
242 		ehead = NULL;
243 		while (from != NULL) {
244 			for (nextp = &ehead;
245 			    (*nextp) && from->idle >= (*nextp)->idle;
246 			    nextp = &(*nextp)->next)
247 				continue;
248 			save = from;
249 			from = from->next;
250 			save->next = *nextp;
251 			*nextp = save;
252 		}
253 	}
254 
255 	if (!nflag)
256 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
257 		    (p = index(domain, '.')) == 0)
258 			domain[0] = '\0';
259 		else {
260 			domain[sizeof(domain) - 1] = '\0';
261 			bcopy(p, domain, strlen(p) + 1);
262 		}
263 
264 	for (ep = ehead; ep != NULL; ep = ep->next) {
265 		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
266 		if (x = index(p, ':'))
267 			*x++ = '\0';
268 		if (!nflag && isdigit(*p) &&
269 		    (long)(l = inet_addr(p)) != -1 &&
270 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
271 			if (domain[0] != '\0') {
272 				p = hp->h_name;
273 				p += strlen(hp->h_name);
274 				p -= strlen(domain);
275 				if (p > hp->h_name && !strcmp(p, domain))
276 					*p = '\0';
277 			}
278 			p = hp->h_name;
279 		}
280 		if (x) {
281 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
282 			p = buf;
283 		}
284 		(void)printf("%-*.*s %-2.2s %-*.*s ",
285 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
286 		    strncmp(ep->utmp.ut_line, "tty", 3) ?
287 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
288 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
289 		pr_attime(&ep->utmp.ut_time, &now);
290 		pr_idle(ep->idle);
291 		(void)printf("%.*s\n", argwidth, ep->args);
292 	}
293 	exit(0);
294 }
295 
296 static void
297 pr_header(nowp, nusers)
298 	time_t *nowp;
299 	int nusers;
300 {
301 	double avenrun[3];
302 	time_t uptime;
303 	int days, hrs, i, mins;
304 	int mib[2], size;
305 	char buf[256], fmt[10];
306 
307 	/*
308 	 * Print time of day.
309 	 *
310 	 * Note, SCCS forces the string manipulation below, as it
311 	 * replaces w.c with file information.
312 	 */
313 	(void)strcpy(fmt, "%l:%%%p");
314 	fmt[4] = 'M';
315 	(void)strftime(buf, sizeof(buf), fmt, localtime(nowp));
316 	(void)printf("%s ", buf);
317 
318 	/*
319 	 * Print how long system has been up.
320 	 * (Found by looking getting "boottime" from the kernel)
321 	 */
322 	mib[0] = CTL_KERN;
323 	mib[1] = KERN_BOOTTIME;
324 	size = sizeof(boottime);
325 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) == -1)
326 		err(1, "cannot get kernel bootime");
327 
328 	uptime = now - boottime.tv_sec;
329 	uptime += 30;
330 	days = uptime / SECSPERDAY;
331 	uptime %= SECSPERDAY;
332 	hrs = uptime / SECSPERHOUR;
333 	uptime %= SECSPERHOUR;
334 	mins = uptime / SECSPERMIN;
335 	(void)printf(" up");
336 	if (days > 0)
337 		(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
338 	if (hrs > 0 && mins > 0)
339 		(void)printf(" %2d:%02d,", hrs, mins);
340 	else {
341 		if (hrs > 0)
342 			(void)printf(" %d hr%s,",
343 			    hrs, hrs > 1 ? "s" : "");
344 		if (mins > 0)
345 			(void)printf(" %d min%s,",
346 			    mins, mins > 1 ? "s" : "");
347 	}
348 
349 	/* Print number of users logged in to system */
350 	(void)printf(" %d user%s", nusers, nusers > 1 ? "s" : "");
351 
352 	/*
353 	 * Print 1, 5, and 15 minute load averages.
354 	 */
355 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
356 		(void)printf(", no load average information available\n");
357 	else {
358 		(void)printf(", load averages:");
359 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
360 			if (i > 0)
361 				(void)printf(",");
362 			(void)printf(" %.2f", avenrun[i]);
363 		}
364 		(void)printf("\n");
365 	}
366 }
367 
368 static struct stat *
369 ttystat(line)
370 	char *line;
371 {
372 	static struct stat sb;
373 	char ttybuf[MAXPATHLEN];
374 
375 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
376 	if (stat(ttybuf, &sb))
377 		err(1, "%s", ttybuf);
378 	return (&sb);
379 }
380 
381 static void
382 usage(wcmd)
383 	int wcmd;
384 {
385 	if (wcmd)
386 		(void)fprintf(stderr,
387 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
388 	else
389 		(void)fprintf(stderr, "uptime\n");
390 	exit (1);
391 }
392