xref: /freebsd/usr.bin/w/w.c (revision 307625842b02ee4c898751dbeaa16eb370bbb7f7)
19b50d902SRodney W. Grimes /*-
28a16b7a1SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
38a16b7a1SPedro F. Giffuni  *
49b50d902SRodney W. Grimes  * Copyright (c) 1980, 1991, 1993, 1994
59b50d902SRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
69b50d902SRodney W. Grimes  *
79b50d902SRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
89b50d902SRodney W. Grimes  * modification, are permitted provided that the following conditions
99b50d902SRodney W. Grimes  * are met:
109b50d902SRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
119b50d902SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
129b50d902SRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
139b50d902SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
149b50d902SRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
15fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
169b50d902SRodney W. Grimes  *    may be used to endorse or promote products derived from this software
179b50d902SRodney W. Grimes  *    without specific prior written permission.
189b50d902SRodney W. Grimes  *
199b50d902SRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
209b50d902SRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
219b50d902SRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
229b50d902SRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
239b50d902SRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
249b50d902SRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
259b50d902SRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
269b50d902SRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
279b50d902SRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
289b50d902SRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
299b50d902SRodney W. Grimes  * SUCH DAMAGE.
309b50d902SRodney W. Grimes  */
319b50d902SRodney W. Grimes 
328b56c58bSMark Murray #include <sys/cdefs.h>
338b56c58bSMark Murray 
348b56c58bSMark Murray __FBSDID("$FreeBSD$");
358b56c58bSMark Murray 
369b50d902SRodney W. Grimes #ifndef lint
3790389da9SPhilippe Charnier static const char copyright[] =
389b50d902SRodney W. Grimes "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
399b50d902SRodney W. Grimes 	The Regents of the University of California.  All rights reserved.\n";
408b56c58bSMark Murray #endif
419b50d902SRodney W. Grimes 
429b50d902SRodney W. Grimes #ifndef lint
438b56c58bSMark Murray static const char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
4490389da9SPhilippe Charnier #endif
459b50d902SRodney W. Grimes 
469b50d902SRodney W. Grimes /*
479b50d902SRodney W. Grimes  * w - print system status (who and what)
489b50d902SRodney W. Grimes  *
499b50d902SRodney W. Grimes  * This program is similar to the systat command on Tenex/Tops 10/20
509b50d902SRodney W. Grimes  *
519b50d902SRodney W. Grimes  */
529b50d902SRodney W. Grimes #include <sys/param.h>
539b50d902SRodney W. Grimes #include <sys/time.h>
549b50d902SRodney W. Grimes #include <sys/stat.h>
559b50d902SRodney W. Grimes #include <sys/sysctl.h>
569b50d902SRodney W. Grimes #include <sys/proc.h>
579b50d902SRodney W. Grimes #include <sys/user.h>
589b50d902SRodney W. Grimes #include <sys/ioctl.h>
59630a02daSAllan Jude #include <sys/sbuf.h>
609b50d902SRodney W. Grimes #include <sys/socket.h>
619b50d902SRodney W. Grimes #include <sys/tty.h>
62630a02daSAllan Jude #include <sys/types.h>
639b50d902SRodney W. Grimes 
64a29cc9a3SAndriy Gapon #include <machine/cpu.h>
659b50d902SRodney W. Grimes #include <netinet/in.h>
669b50d902SRodney W. Grimes #include <arpa/inet.h>
678b56c58bSMark Murray #include <arpa/nameser.h>
689b50d902SRodney W. Grimes 
69821df508SXin LI #include <ctype.h>
709b50d902SRodney W. Grimes #include <err.h>
719b50d902SRodney W. Grimes #include <errno.h>
729b50d902SRodney W. Grimes #include <fcntl.h>
739b50d902SRodney W. Grimes #include <kvm.h>
7400034645SAndrey A. Chernov #include <langinfo.h>
75920aa23dSEitan Adler #include <libgen.h>
765b718312SBrian Somers #include <libutil.h>
77af943f55SThomas Moestl #include <limits.h>
7800034645SAndrey A. Chernov #include <locale.h>
799b50d902SRodney W. Grimes #include <netdb.h>
809b50d902SRodney W. Grimes #include <nlist.h>
819b50d902SRodney W. Grimes #include <paths.h>
828b56c58bSMark Murray #include <resolv.h>
839b50d902SRodney W. Grimes #include <stdio.h>
849b50d902SRodney W. Grimes #include <stdlib.h>
859b50d902SRodney W. Grimes #include <string.h>
86821df508SXin LI #include <timeconv.h>
879b50d902SRodney W. Grimes #include <unistd.h>
881131779fSEd Schouten #include <utmpx.h>
89821df508SXin LI #include <vis.h>
9076c0abf1SMarcel Moolenaar #include <libxo/xo.h>
919b50d902SRodney W. Grimes 
929b50d902SRodney W. Grimes #include "extern.h"
939b50d902SRodney W. Grimes 
94d11cba9cSEd Schouten static struct utmpx *utmp;
95d11cba9cSEd Schouten static struct winsize ws;
96d11cba9cSEd Schouten static kvm_t   *kd;
97d11cba9cSEd Schouten static time_t	now;		/* the current time of day */
98d11cba9cSEd Schouten static int	ttywidth;	/* width of tty */
99ec9801deSMike Karels static int	fromwidth = 0;	/* max width of "from" field */
100ec9801deSMike Karels static int	argwidth;	/* width of arguments */
101d11cba9cSEd Schouten static int	header = 1;	/* true if -h flag: don't print heading */
102d11cba9cSEd Schouten static int	nflag;		/* true if -n flag: don't convert addrs */
103d11cba9cSEd Schouten static int	dflag;		/* true if -d flag: output debug info */
104d11cba9cSEd Schouten static int	sortidle;	/* sort by idle time */
10500034645SAndrey A. Chernov int		use_ampm;	/* use AM/PM time */
106d11cba9cSEd Schouten static int	use_comma;      /* use comma as floats separator */
107d11cba9cSEd Schouten static char   **sel_users;	/* login array of particular users selected */
1089b50d902SRodney W. Grimes 
1099b50d902SRodney W. Grimes /*
1109b50d902SRodney W. Grimes  * One of these per active utmp entry.
1119b50d902SRodney W. Grimes  */
112d11cba9cSEd Schouten static struct entry {
1139b50d902SRodney W. Grimes 	struct	entry *next;
114dc65bcacSEd Schouten 	struct	utmpx utmp;
1159b50d902SRodney W. Grimes 	dev_t	tdev;			/* dev_t of terminal */
1169b50d902SRodney W. Grimes 	time_t	idle;			/* idle time of terminal in seconds */
1179b50d902SRodney W. Grimes 	struct	kinfo_proc *kp;		/* `most interesting' proc */
1189b50d902SRodney W. Grimes 	char	*args;			/* arg list of interesting process */
1191bb32253SAndrey A. Chernov 	struct	kinfo_proc *dkp;	/* debug option proc list */
120ec9801deSMike Karels 	char	*from;			/* "from": name or addr */
121ae335351SMike Karels 	char	*save_from;		/* original "from": name or addr */
1229b50d902SRodney W. Grimes } *ep, *ehead = NULL, **nextp = &ehead;
1239b50d902SRodney W. Grimes 
12402f56376SDavid Malone #define	debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata)
125ac3cd520SBrian Feldman 
126dc65bcacSEd Schouten #define	W_DISPUSERSIZE	10
127dc65bcacSEd Schouten #define	W_DISPLINESIZE	8
128ec9801deSMike Karels #define	W_MAXHOSTSIZE	40
1295b718312SBrian Somers 
1303f330d7dSWarner Losh static void		 pr_header(time_t *, int);
131dc65bcacSEd Schouten static struct stat	*ttystat(char *);
1323f330d7dSWarner Losh static void		 usage(int);
1339b50d902SRodney W. Grimes 
1349f0b6e5eSJohn Baldwin char *fmt_argv(char **, char *, char *, size_t);	/* ../../bin/ps/fmt.c */
1359b50d902SRodney W. Grimes 
1369b50d902SRodney W. Grimes int
137e8e649ccSJuli Mallett main(int argc, char *argv[])
1389b50d902SRodney W. Grimes {
1399b50d902SRodney W. Grimes 	struct kinfo_proc *kp;
1401bb32253SAndrey A. Chernov 	struct kinfo_proc *dkp;
1419b50d902SRodney W. Grimes 	struct stat *stp;
1423bebe991SBrian Somers 	time_t touched;
143ab9cee11SXin LI 	int ch, i, nentries, nusers, wcmd, longidle, longattime;
14476c0abf1SMarcel Moolenaar 	const char *memf, *nlistf, *p, *save_p;
1458b56c58bSMark Murray 	char *x_suffix;
146af943f55SThomas Moestl 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
1475b718312SBrian Somers 	char fn[MAXHOSTNAMELEN];
1485b718312SBrian Somers 	char *dot;
1499b50d902SRodney W. Grimes 
150d1b2ad1aSAndrey A. Chernov 	(void)setlocale(LC_ALL, "");
15100034645SAndrey A. Chernov 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
1522742fc8eSAndrey A. Chernov 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
153baf72ec1SAndrey A. Chernov 
15476c0abf1SMarcel Moolenaar 	argc = xo_parse_args(argc, argv);
15576c0abf1SMarcel Moolenaar 	if (argc < 0)
15676c0abf1SMarcel Moolenaar 		exit(1);
15776c0abf1SMarcel Moolenaar 
1589b50d902SRodney W. Grimes 	/* Are we w(1) or uptime(1)? */
159920aa23dSEitan Adler 	if (strcmp(basename(argv[0]), "uptime") == 0) {
1609b50d902SRodney W. Grimes 		wcmd = 0;
1619b50d902SRodney W. Grimes 		p = "";
1629b50d902SRodney W. Grimes 	} else {
1639b50d902SRodney W. Grimes 		wcmd = 1;
1641bb32253SAndrey A. Chernov 		p = "dhiflM:N:nsuw";
1659b50d902SRodney W. Grimes 	}
1669b50d902SRodney W. Grimes 
167c08dcaf1SRebecca Cran 	memf = _PATH_DEVNULL;
168c08dcaf1SRebecca Cran 	nlistf = NULL;
1691c8af878SWarner Losh 	while ((ch = getopt(argc, argv, p)) != -1)
1709b50d902SRodney W. Grimes 		switch (ch) {
1711bb32253SAndrey A. Chernov 		case 'd':
1721bb32253SAndrey A. Chernov 			dflag = 1;
1731bb32253SAndrey A. Chernov 			break;
1749b50d902SRodney W. Grimes 		case 'h':
1759b50d902SRodney W. Grimes 			header = 0;
1769b50d902SRodney W. Grimes 			break;
1779b50d902SRodney W. Grimes 		case 'i':
1789b50d902SRodney W. Grimes 			sortidle = 1;
1799b50d902SRodney W. Grimes 			break;
1809b50d902SRodney W. Grimes 		case 'M':
1819b50d902SRodney W. Grimes 			header = 0;
1829b50d902SRodney W. Grimes 			memf = optarg;
1839b50d902SRodney W. Grimes 			break;
1849b50d902SRodney W. Grimes 		case 'N':
1859b50d902SRodney W. Grimes 			nlistf = optarg;
1869b50d902SRodney W. Grimes 			break;
1879b50d902SRodney W. Grimes 		case 'n':
1882279a9a4SHajimu UMEMOTO 			nflag += 1;
1899b50d902SRodney W. Grimes 			break;
1909b50d902SRodney W. Grimes 		case 'f': case 'l': case 's': case 'u': case 'w':
1919b50d902SRodney W. Grimes 			warnx("[-flsuw] no longer supported");
1929b50d902SRodney W. Grimes 			/* FALLTHROUGH */
1939b50d902SRodney W. Grimes 		case '?':
1949b50d902SRodney W. Grimes 		default:
1959b50d902SRodney W. Grimes 			usage(wcmd);
1969b50d902SRodney W. Grimes 		}
1979b50d902SRodney W. Grimes 	argc -= optind;
1989b50d902SRodney W. Grimes 	argv += optind;
1999b50d902SRodney W. Grimes 
2006367cd09SPeter Wemm 	if (!(_res.options & RES_INIT))
2016367cd09SPeter Wemm 		res_init();
2026367cd09SPeter Wemm 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
2036367cd09SPeter Wemm 	_res.retry = 1;		/* only try once.. */
2046367cd09SPeter Wemm 
2059b50d902SRodney W. Grimes 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
2069b50d902SRodney W. Grimes 		errx(1, "%s", errbuf);
2079b50d902SRodney W. Grimes 
2089b50d902SRodney W. Grimes 	(void)time(&now);
2099b50d902SRodney W. Grimes 
2109b50d902SRodney W. Grimes 	if (*argv)
211ac3cd520SBrian Feldman 		sel_users = argv;
2129b50d902SRodney W. Grimes 
213dc65bcacSEd Schouten 	setutxent();
214dc65bcacSEd Schouten 	for (nusers = 0; (utmp = getutxent()) != NULL;) {
215ec9801deSMike Karels 		struct addrinfo hints, *res;
216ec9801deSMike Karels 		struct sockaddr_storage ss;
217ec9801deSMike Karels 		struct sockaddr *sa = (struct sockaddr *)&ss;
218ec9801deSMike Karels 		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
219ec9801deSMike Karels 		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
220ec9801deSMike Karels 		int isaddr;
221ec9801deSMike Karels 
222dc65bcacSEd Schouten 		if (utmp->ut_type != USER_PROCESS)
2239b50d902SRodney W. Grimes 			continue;
224dc65bcacSEd Schouten 		if (!(stp = ttystat(utmp->ut_line)))
2250cadb9caSBrian Somers 			continue;	/* corrupted record */
2269b50d902SRodney W. Grimes 		++nusers;
227ac3cd520SBrian Feldman 		if (wcmd == 0)
2289b50d902SRodney W. Grimes 			continue;
229ac3cd520SBrian Feldman 		if (sel_users) {
230ac3cd520SBrian Feldman 			int usermatch;
231ac3cd520SBrian Feldman 			char **user;
232ac3cd520SBrian Feldman 
233ac3cd520SBrian Feldman 			usermatch = 0;
234ac3cd520SBrian Feldman 			for (user = sel_users; !usermatch && *user; user++)
235dc65bcacSEd Schouten 				if (!strcmp(utmp->ut_user, *user))
236ac3cd520SBrian Feldman 					usermatch = 1;
237ac3cd520SBrian Feldman 			if (!usermatch)
238ac3cd520SBrian Feldman 				continue;
239ac3cd520SBrian Feldman 		}
2409b50d902SRodney W. Grimes 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
24190389da9SPhilippe Charnier 			errx(1, "calloc");
2429b50d902SRodney W. Grimes 		*nextp = ep;
243ac3cd520SBrian Feldman 		nextp = &ep->next;
244dc65bcacSEd Schouten 		memmove(&ep->utmp, utmp, sizeof *utmp);
2459b50d902SRodney W. Grimes 		ep->tdev = stp->st_rdev;
2469b50d902SRodney W. Grimes 		/*
2479b50d902SRodney W. Grimes 		 * If this is the console device, attempt to ascertain
2489b50d902SRodney W. Grimes 		 * the true console device dev_t.
2499b50d902SRodney W. Grimes 		 */
2509b50d902SRodney W. Grimes 		if (ep->tdev == 0) {
2519b50d902SRodney W. Grimes 			size_t size;
2529b50d902SRodney W. Grimes 
2539b50d902SRodney W. Grimes 			size = sizeof(dev_t);
254bec1fa86SPoul-Henning Kamp 			(void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
2559b50d902SRodney W. Grimes 		}
2563bebe991SBrian Somers 		touched = stp->st_atime;
257dc65bcacSEd Schouten 		if (touched < ep->utmp.ut_tv.tv_sec) {
2583bebe991SBrian Somers 			/* tty untouched since before login */
259dc65bcacSEd Schouten 			touched = ep->utmp.ut_tv.tv_sec;
2603bebe991SBrian Somers 		}
2613bebe991SBrian Somers 		if ((ep->idle = now - touched) < 0)
2629b50d902SRodney W. Grimes 			ep->idle = 0;
263ec9801deSMike Karels 
264ec9801deSMike Karels 		save_p = p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
265ec9801deSMike Karels 		if ((x_suffix = strrchr(p, ':')) != NULL) {
266ec9801deSMike Karels 			if ((dot = strchr(x_suffix, '.')) != NULL &&
267ec9801deSMike Karels 			    strchr(dot+1, '.') == NULL)
268ec9801deSMike Karels 				*x_suffix++ = '\0';
269ec9801deSMike Karels 			else
270ec9801deSMike Karels 				x_suffix = NULL;
271ec9801deSMike Karels 		}
272ec9801deSMike Karels 
273ec9801deSMike Karels 		isaddr = 0;
274ec9801deSMike Karels 		memset(&ss, '\0', sizeof(ss));
275ec9801deSMike Karels 		if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
276ec9801deSMike Karels 			lsin6->sin6_len = sizeof(*lsin6);
277ec9801deSMike Karels 			lsin6->sin6_family = AF_INET6;
278ec9801deSMike Karels 			isaddr = 1;
279ec9801deSMike Karels 		} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
280ec9801deSMike Karels 			lsin->sin_len = sizeof(*lsin);
281ec9801deSMike Karels 			lsin->sin_family = AF_INET;
282ec9801deSMike Karels 			isaddr = 1;
283ec9801deSMike Karels 		}
284ec9801deSMike Karels 		if (nflag == 0) {
285ec9801deSMike Karels 			/* Attempt to change an IP address into a name */
286ec9801deSMike Karels 			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
287ec9801deSMike Karels 			    sa->sa_len) == HOSTNAME_FOUND)
288ec9801deSMike Karels 				p = fn;
289ec9801deSMike Karels 		} else if (!isaddr && nflag > 1) {
290ec9801deSMike Karels 			/*
291ec9801deSMike Karels 			 * If a host has only one A/AAAA RR, change a
292ec9801deSMike Karels 			 * name into an IP address
293ec9801deSMike Karels 			 */
294ec9801deSMike Karels 			memset(&hints, 0, sizeof(hints));
295ec9801deSMike Karels 			hints.ai_flags = AI_PASSIVE;
296ec9801deSMike Karels 			hints.ai_family = AF_UNSPEC;
297ec9801deSMike Karels 			hints.ai_socktype = SOCK_STREAM;
298ec9801deSMike Karels 			if (getaddrinfo(p, NULL, &hints, &res) == 0) {
299ec9801deSMike Karels 				if (res->ai_next == NULL &&
300ec9801deSMike Karels 				    getnameinfo(res->ai_addr, res->ai_addrlen,
301ec9801deSMike Karels 					fn, sizeof(fn), NULL, 0,
302ec9801deSMike Karels 					NI_NUMERICHOST) == 0)
303ec9801deSMike Karels 					p = fn;
304ec9801deSMike Karels 				freeaddrinfo(res);
305ec9801deSMike Karels 			}
306ec9801deSMike Karels 		}
307ec9801deSMike Karels 
308ec9801deSMike Karels 		if (x_suffix) {
309ec9801deSMike Karels 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
310ec9801deSMike Karels 			p = buf;
311ec9801deSMike Karels 		}
312ec9801deSMike Karels 		ep->from = strdup(p);
313ec9801deSMike Karels 		if ((i = strlen(p)) > fromwidth)
314ec9801deSMike Karels 			fromwidth = i;
315ae335351SMike Karels 		if (save_p != p)
316ae335351SMike Karels 			ep->save_from = strdup(save_p);
3179b50d902SRodney W. Grimes 	}
318dc65bcacSEd Schouten 	endutxent();
3199b50d902SRodney W. Grimes 
320ec9801deSMike Karels #define HEADER_USER		"USER"
321ec9801deSMike Karels #define HEADER_TTY		"TTY"
322ec9801deSMike Karels #define HEADER_FROM		"FROM"
323ec9801deSMike Karels #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
324ec9801deSMike Karels #define HEADER_WHAT		"WHAT\n"
325ec9801deSMike Karels #define WUSED  (W_DISPUSERSIZE + W_DISPLINESIZE + fromwidth + \
326ec9801deSMike Karels 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
327ec9801deSMike Karels 
328ec9801deSMike Karels 
329ec9801deSMike Karels 	if ((int) sizeof(HEADER_FROM) > fromwidth)
330ec9801deSMike Karels 		fromwidth = sizeof(HEADER_FROM);
331ec9801deSMike Karels 	fromwidth++;
332ec9801deSMike Karels 	if (fromwidth > W_MAXHOSTSIZE)
333ec9801deSMike Karels 		fromwidth = W_MAXHOSTSIZE;
334ec9801deSMike Karels 
33576c0abf1SMarcel Moolenaar 	xo_open_container("uptime-information");
33676c0abf1SMarcel Moolenaar 
3379b50d902SRodney W. Grimes 	if (header || wcmd == 0) {
3389b50d902SRodney W. Grimes 		pr_header(&now, nusers);
339c59c7f97SPoul-Henning Kamp 		if (wcmd == 0) {
34076c0abf1SMarcel Moolenaar 			xo_close_container("uptime-information");
341441ee032SMichael Gmelin 			xo_finish();
342441ee032SMichael Gmelin 
343c59c7f97SPoul-Henning Kamp 			(void)kvm_close(kd);
3449b50d902SRodney W. Grimes 			exit(0);
345c59c7f97SPoul-Henning Kamp 		}
3469b50d902SRodney W. Grimes 
34776c0abf1SMarcel Moolenaar 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s}  {T:/%s}",
348dc65bcacSEd Schouten 				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
349dc65bcacSEd Schouten 				W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
350ec9801deSMike Karels 				fromwidth, fromwidth, HEADER_FROM,
351a88d7a82SJoseph Koshy 				HEADER_LOGIN_IDLE HEADER_WHAT);
3520812a2b4SPeter Wemm 	}
3539b50d902SRodney W. Grimes 
3549b50d902SRodney W. Grimes 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
3559b50d902SRodney W. Grimes 		err(1, "%s", kvm_geterr(kd));
3569b50d902SRodney W. Grimes 	for (i = 0; i < nentries; i++, kp++) {
3571131779fSEd Schouten 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
3581131779fSEd Schouten 		    kp->ki_tdev == NODEV)
3599b50d902SRodney W. Grimes 			continue;
3609b50d902SRodney W. Grimes 		for (ep = ehead; ep != NULL; ep = ep->next) {
3611f7d2501SKirk McKusick 			if (ep->tdev == kp->ki_tdev) {
3629b50d902SRodney W. Grimes 				/*
3631bb32253SAndrey A. Chernov 				 * proc is associated with this terminal
3641bb32253SAndrey A. Chernov 				 */
3651f7d2501SKirk McKusick 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
3661bb32253SAndrey A. Chernov 					/*
3671bb32253SAndrey A. Chernov 					 * Proc is 'most interesting'
3689b50d902SRodney W. Grimes 					 */
3691f7d2501SKirk McKusick 					if (proc_compare(ep->kp, kp))
3709b50d902SRodney W. Grimes 						ep->kp = kp;
3711bb32253SAndrey A. Chernov 				}
3721bb32253SAndrey A. Chernov 				/*
3731bb32253SAndrey A. Chernov 				 * Proc debug option info; add to debug
3741f7d2501SKirk McKusick 				 * list using kinfo_proc ki_spare[0]
3751bb32253SAndrey A. Chernov 				 * as next pointer; ptr to ptr avoids the
3761bb32253SAndrey A. Chernov 				 * ptr = long assumption.
3771bb32253SAndrey A. Chernov 				 */
3781bb32253SAndrey A. Chernov 				dkp = ep->dkp;
3791bb32253SAndrey A. Chernov 				ep->dkp = kp;
380ac3cd520SBrian Feldman 				debugproc(kp) = dkp;
3819b50d902SRodney W. Grimes 			}
3829b50d902SRodney W. Grimes 		}
3839b50d902SRodney W. Grimes 	}
3849b50d902SRodney W. Grimes 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
3859b50d902SRodney W. Grimes 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
3869b50d902SRodney W. Grimes 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
3879b50d902SRodney W. Grimes 	       ttywidth = 79;
3889b50d902SRodney W. Grimes         else
3899b50d902SRodney W. Grimes 	       ttywidth = ws.ws_col - 1;
3909b50d902SRodney W. Grimes 	argwidth = ttywidth - WUSED;
3919b50d902SRodney W. Grimes 	if (argwidth < 4)
3929b50d902SRodney W. Grimes 		argwidth = 8;
393*30762584SKristof Provost 	/* Don't truncate if we're outputting json or XML. */
394*30762584SKristof Provost 	if (xo_get_style(NULL) != XO_STYLE_TEXT)
395*30762584SKristof Provost 		argwidth = ARG_MAX;
3969b50d902SRodney W. Grimes 	for (ep = ehead; ep != NULL; ep = ep->next) {
3979b50d902SRodney W. Grimes 		if (ep->kp == NULL) {
3988b56c58bSMark Murray 			ep->args = strdup("-");
3999b50d902SRodney W. Grimes 			continue;
4009b50d902SRodney W. Grimes 		}
4019b50d902SRodney W. Grimes 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
4029f0b6e5eSJohn Baldwin 		    ep->kp->ki_comm, NULL, MAXCOMLEN);
4039b50d902SRodney W. Grimes 		if (ep->args == NULL)
4049b50d902SRodney W. Grimes 			err(1, NULL);
4059b50d902SRodney W. Grimes 	}
4069b50d902SRodney W. Grimes 	/* sort by idle time */
4079b50d902SRodney W. Grimes 	if (sortidle && ehead != NULL) {
408ac3cd520SBrian Feldman 		struct entry *from, *save;
4099b50d902SRodney W. Grimes 
410ac3cd520SBrian Feldman 		from = ehead;
4119b50d902SRodney W. Grimes 		ehead = NULL;
4129b50d902SRodney W. Grimes 		while (from != NULL) {
4139b50d902SRodney W. Grimes 			for (nextp = &ehead;
4149b50d902SRodney W. Grimes 			    (*nextp) && from->idle >= (*nextp)->idle;
4159b50d902SRodney W. Grimes 			    nextp = &(*nextp)->next)
4169b50d902SRodney W. Grimes 				continue;
4179b50d902SRodney W. Grimes 			save = from;
4189b50d902SRodney W. Grimes 			from = from->next;
4199b50d902SRodney W. Grimes 			save->next = *nextp;
4209b50d902SRodney W. Grimes 			*nextp = save;
4219b50d902SRodney W. Grimes 		}
4229b50d902SRodney W. Grimes 	}
4239b50d902SRodney W. Grimes 
42476c0abf1SMarcel Moolenaar 	xo_open_container("user-table");
42576c0abf1SMarcel Moolenaar 	xo_open_list("user-entry");
42676c0abf1SMarcel Moolenaar 
4279b50d902SRodney W. Grimes 	for (ep = ehead; ep != NULL; ep = ep->next) {
428c76b41b7SPeter Wemm 		time_t t;
4299587fac0SAndrey A. Chernov 
43076c0abf1SMarcel Moolenaar 		xo_open_instance("user-entry");
43176c0abf1SMarcel Moolenaar 
4321bb32253SAndrey A. Chernov 		if (dflag) {
43376c0abf1SMarcel Moolenaar 		        xo_open_container("process-table");
43476c0abf1SMarcel Moolenaar 		        xo_open_list("process-entry");
43576c0abf1SMarcel Moolenaar 
436ac3cd520SBrian Feldman 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
4378b56c58bSMark Murray 				const char *ptr;
438ac3cd520SBrian Feldman 
4390cadb9caSBrian Somers 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
4409f0b6e5eSJohn Baldwin 				    dkp->ki_comm, NULL, MAXCOMLEN);
4410cadb9caSBrian Somers 				if (ptr == NULL)
4420cadb9caSBrian Somers 					ptr = "-";
44376c0abf1SMarcel Moolenaar 				xo_open_instance("process-entry");
4442d3725d6SYuri Pankov 				xo_emit("\t\t{:process-id/%-9d/%d} "
4452d3725d6SYuri Pankov 				    "{:command/%hs}\n", dkp->ki_pid, ptr);
44676c0abf1SMarcel Moolenaar 				xo_close_instance("process-entry");
4471bb32253SAndrey A. Chernov 			}
44876c0abf1SMarcel Moolenaar 		        xo_close_list("process-entry");
44976c0abf1SMarcel Moolenaar 		        xo_close_container("process-table");
4501bb32253SAndrey A. Chernov 		}
45176c0abf1SMarcel Moolenaar 		xo_emit("{:user/%-*.*s/%@**@s} {:tty/%-*.*s/%@**@s} ",
452dc65bcacSEd Schouten 			W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
453dc65bcacSEd Schouten 			W_DISPLINESIZE, W_DISPLINESIZE,
4541131779fSEd Schouten 			*ep->utmp.ut_line ?
4551131779fSEd Schouten 			(strncmp(ep->utmp.ut_line, "tty", 3) &&
456255318a8SAndrey A. Chernov 			 strncmp(ep->utmp.ut_line, "cua", 3) ?
45776c0abf1SMarcel Moolenaar 			 ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-");
45876c0abf1SMarcel Moolenaar 
459ae335351SMike Karels 		if (ep->save_from)
460ae335351SMike Karels 		    xo_attr("address", "%s", ep->save_from);
46176c0abf1SMarcel Moolenaar 		xo_emit("{:from/%-*.*s/%@**@s} ",
462ec9801deSMike Karels 		    fromwidth, fromwidth, ep->from);
463dc65bcacSEd Schouten 		t = ep->utmp.ut_tv.tv_sec;
46434903a55SHajimu UMEMOTO 		longattime = pr_attime(&t, &now);
46570498d5aSDaniel O'Callaghan 		longidle = pr_idle(ep->idle);
4662d3725d6SYuri Pankov 		xo_emit("{:command/%.*hs/%@*@hs}\n",
46776c0abf1SMarcel Moolenaar 		    argwidth - longidle - longattime,
46834903a55SHajimu UMEMOTO 		    ep->args);
46976c0abf1SMarcel Moolenaar 
47076c0abf1SMarcel Moolenaar 		xo_close_instance("user-entry");
4719b50d902SRodney W. Grimes 	}
47276c0abf1SMarcel Moolenaar 
47376c0abf1SMarcel Moolenaar 	xo_close_list("user-entry");
47476c0abf1SMarcel Moolenaar 	xo_close_container("user-table");
47576c0abf1SMarcel Moolenaar 	xo_close_container("uptime-information");
47676c0abf1SMarcel Moolenaar 	xo_finish();
47776c0abf1SMarcel Moolenaar 
478c59c7f97SPoul-Henning Kamp 	(void)kvm_close(kd);
4799b50d902SRodney W. Grimes 	exit(0);
4809b50d902SRodney W. Grimes }
4819b50d902SRodney W. Grimes 
4829b50d902SRodney W. Grimes static void
483e8e649ccSJuli Mallett pr_header(time_t *nowp, int nusers)
4849b50d902SRodney W. Grimes {
4859b50d902SRodney W. Grimes 	double avenrun[3];
486716ced0bSDavid E. O'Brien 	time_t uptime;
487a21cbcb8SAndre Oppermann 	struct timespec tp;
4889d8c91b7SAndrey A. Chernov 	int days, hrs, i, mins, secs;
4899b50d902SRodney W. Grimes 	char buf[256];
490630a02daSAllan Jude 	struct sbuf *upbuf;
4919b50d902SRodney W. Grimes 
492630a02daSAllan Jude 	upbuf = sbuf_new_auto();
4939b50d902SRodney W. Grimes 	/*
4949b50d902SRodney W. Grimes 	 * Print time of day.
4959b50d902SRodney W. Grimes 	 */
49669fe77ceSPhilippe Charnier 	if (strftime(buf, sizeof(buf),
49769fe77ceSPhilippe Charnier 	    use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
49876c0abf1SMarcel Moolenaar 		xo_emit("{:time-of-day/%s} ", buf);
4999b50d902SRodney W. Grimes 	/*
5009b50d902SRodney W. Grimes 	 * Print how long system has been up.
5019b50d902SRodney W. Grimes 	 */
502b6eec535SEd Maste 	if (clock_gettime(CLOCK_UPTIME, &tp) != -1) {
503a21cbcb8SAndre Oppermann 		uptime = tp.tv_sec;
504716ced0bSDavid E. O'Brien 		if (uptime > 60)
505716ced0bSDavid E. O'Brien 			uptime += 30;
506716ced0bSDavid E. O'Brien 		days = uptime / 86400;
507716ced0bSDavid E. O'Brien 		uptime %= 86400;
508716ced0bSDavid E. O'Brien 		hrs = uptime / 3600;
509716ced0bSDavid E. O'Brien 		uptime %= 3600;
510716ced0bSDavid E. O'Brien 		mins = uptime / 60;
511716ced0bSDavid E. O'Brien 		secs = uptime % 60;
51276c0abf1SMarcel Moolenaar 		xo_emit(" up");
513630a02daSAllan Jude 		xo_emit("{e:uptime/%lu}", (unsigned long) tp.tv_sec);
514630a02daSAllan Jude 		xo_emit("{e:days/%d}{e:hours/%d}{e:minutes/%d}{e:seconds/%d}", days, hrs, mins, secs);
515630a02daSAllan Jude 
5169b50d902SRodney W. Grimes 		if (days > 0)
517630a02daSAllan Jude 			sbuf_printf(upbuf, " %d day%s,",
51876c0abf1SMarcel Moolenaar 				days, days > 1 ? "s" : "");
5199b50d902SRodney W. Grimes 		if (hrs > 0 && mins > 0)
520630a02daSAllan Jude 			sbuf_printf(upbuf, " %2d:%02d,", hrs, mins);
5219d8c91b7SAndrey A. Chernov 		else if (hrs > 0)
522630a02daSAllan Jude 			sbuf_printf(upbuf, " %d hr%s,",
52376c0abf1SMarcel Moolenaar 				hrs, hrs > 1 ? "s" : "");
5249d8c91b7SAndrey A. Chernov 		else if (mins > 0)
525630a02daSAllan Jude 			sbuf_printf(upbuf, " %d min%s,",
52676c0abf1SMarcel Moolenaar 				mins, mins > 1 ? "s" : "");
5279d8c91b7SAndrey A. Chernov 		else
528630a02daSAllan Jude 			sbuf_printf(upbuf, " %d sec%s,",
52976c0abf1SMarcel Moolenaar 				secs, secs > 1 ? "s" : "");
530630a02daSAllan Jude 		if (sbuf_finish(upbuf) != 0)
531630a02daSAllan Jude 			xo_err(1, "Could not generate output");
532630a02daSAllan Jude 		xo_emit("{:uptime-human/%s}", sbuf_data(upbuf));
533630a02daSAllan Jude 		sbuf_delete(upbuf);
5349b50d902SRodney W. Grimes 	}
5359b50d902SRodney W. Grimes 
5369b50d902SRodney W. Grimes 	/* Print number of users logged in to system */
537ba86ca7cSAlexander Motin 	xo_emit(" {:users/%d} {Np:user,users}", nusers);
5389b50d902SRodney W. Grimes 
5399b50d902SRodney W. Grimes 	/*
5409b50d902SRodney W. Grimes 	 * Print 1, 5, and 15 minute load averages.
5419b50d902SRodney W. Grimes 	 */
542807bd0d9SMarcelo Araujo 	if (getloadavg(avenrun, nitems(avenrun)) == -1)
54376c0abf1SMarcel Moolenaar 		xo_emit(", no load average information available\n");
5449b50d902SRodney W. Grimes 	else {
54576c0abf1SMarcel Moolenaar 	        static const char *format[] = {
54676c0abf1SMarcel Moolenaar 		    " {:load-average-1/%.2f}",
54776c0abf1SMarcel Moolenaar 		    " {:load-average-5/%.2f}",
54876c0abf1SMarcel Moolenaar 		    " {:load-average-15/%.2f}",
54976c0abf1SMarcel Moolenaar 		};
55076c0abf1SMarcel Moolenaar 		xo_emit(", load averages:");
551807bd0d9SMarcelo Araujo 		for (i = 0; i < (int)(nitems(avenrun)); i++) {
5522742fc8eSAndrey A. Chernov 			if (use_comma && i > 0)
55376c0abf1SMarcel Moolenaar 				xo_emit(",");
55476c0abf1SMarcel Moolenaar 			xo_emit(format[i], avenrun[i]);
5552742fc8eSAndrey A. Chernov 		}
55676c0abf1SMarcel Moolenaar 		xo_emit("\n");
5579b50d902SRodney W. Grimes 	}
5589b50d902SRodney W. Grimes }
5599b50d902SRodney W. Grimes 
5609b50d902SRodney W. Grimes static struct stat *
561dc65bcacSEd Schouten ttystat(char *line)
5629b50d902SRodney W. Grimes {
5639b50d902SRodney W. Grimes 	static struct stat sb;
5649b50d902SRodney W. Grimes 	char ttybuf[MAXPATHLEN];
5659b50d902SRodney W. Grimes 
566dc65bcacSEd Schouten 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
56721632754SEd Schouten 	if (stat(ttybuf, &sb) == 0 && S_ISCHR(sb.st_mode)) {
5689b50d902SRodney W. Grimes 		return (&sb);
569d0d0355eSSean Chittenden 	} else
570d0d0355eSSean Chittenden 		return (NULL);
5719b50d902SRodney W. Grimes }
5729b50d902SRodney W. Grimes 
5739b50d902SRodney W. Grimes static void
574e8e649ccSJuli Mallett usage(int wcmd)
5759b50d902SRodney W. Grimes {
5769b50d902SRodney W. Grimes 	if (wcmd)
57776c0abf1SMarcel Moolenaar 		xo_error("usage: w [-dhin] [-M core] [-N system] [user ...]\n");
5789b50d902SRodney W. Grimes 	else
57976c0abf1SMarcel Moolenaar 		xo_error("usage: uptime\n");
58010b92369SMark Johnston 	xo_finish();
5819b50d902SRodney W. Grimes 	exit(1);
5829b50d902SRodney W. Grimes }
583