xref: /freebsd/usr.bin/w/w.c (revision bd490be57438a82c22d1274bc58d51142b63f4a0)
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 
329b50d902SRodney W. Grimes /*
339b50d902SRodney W. Grimes  * w - print system status (who and what)
349b50d902SRodney W. Grimes  *
359b50d902SRodney W. Grimes  * This program is similar to the systat command on Tenex/Tops 10/20
369b50d902SRodney W. Grimes  *
379b50d902SRodney W. Grimes  */
389b50d902SRodney W. Grimes #include <sys/param.h>
399b50d902SRodney W. Grimes #include <sys/time.h>
409b50d902SRodney W. Grimes #include <sys/stat.h>
419b50d902SRodney W. Grimes #include <sys/sysctl.h>
429b50d902SRodney W. Grimes #include <sys/proc.h>
439b50d902SRodney W. Grimes #include <sys/user.h>
449b50d902SRodney W. Grimes #include <sys/ioctl.h>
45630a02daSAllan Jude #include <sys/sbuf.h>
469b50d902SRodney W. Grimes #include <sys/socket.h>
479b50d902SRodney W. Grimes #include <sys/tty.h>
48630a02daSAllan Jude #include <sys/types.h>
499b50d902SRodney W. Grimes 
50a29cc9a3SAndriy Gapon #include <machine/cpu.h>
519b50d902SRodney W. Grimes #include <netinet/in.h>
529b50d902SRodney W. Grimes #include <arpa/inet.h>
538b56c58bSMark Murray #include <arpa/nameser.h>
549b50d902SRodney W. Grimes 
55821df508SXin LI #include <ctype.h>
569b50d902SRodney W. Grimes #include <errno.h>
579b50d902SRodney W. Grimes #include <fcntl.h>
589b50d902SRodney W. Grimes #include <kvm.h>
5900034645SAndrey A. Chernov #include <langinfo.h>
60920aa23dSEitan Adler #include <libgen.h>
615b718312SBrian Somers #include <libutil.h>
62af943f55SThomas Moestl #include <limits.h>
6300034645SAndrey A. Chernov #include <locale.h>
649b50d902SRodney W. Grimes #include <netdb.h>
659b50d902SRodney W. Grimes #include <nlist.h>
669b50d902SRodney W. Grimes #include <paths.h>
678b56c58bSMark Murray #include <resolv.h>
689b50d902SRodney W. Grimes #include <stdio.h>
699b50d902SRodney W. Grimes #include <stdlib.h>
709b50d902SRodney W. Grimes #include <string.h>
71821df508SXin LI #include <timeconv.h>
729b50d902SRodney W. Grimes #include <unistd.h>
731131779fSEd Schouten #include <utmpx.h>
74821df508SXin LI #include <vis.h>
7576c0abf1SMarcel Moolenaar #include <libxo/xo.h>
769b50d902SRodney W. Grimes 
779b50d902SRodney W. Grimes #include "extern.h"
789b50d902SRodney W. Grimes 
79d11cba9cSEd Schouten static struct utmpx *utmp;
80d11cba9cSEd Schouten static struct winsize ws;
81d11cba9cSEd Schouten static kvm_t   *kd;
82d11cba9cSEd Schouten static time_t	now;		/* the current time of day */
8304f6b9cbSDag-Erling Smørgrav static size_t	ttywidth;	/* width of tty */
8404f6b9cbSDag-Erling Smørgrav static size_t	fromwidth = 0;	/* max width of "from" field */
8504f6b9cbSDag-Erling Smørgrav static size_t	argwidth;	/* width of arguments */
86d11cba9cSEd Schouten static int	header = 1;	/* true if -h flag: don't print heading */
87d11cba9cSEd Schouten static int	nflag;		/* true if -n flag: don't convert addrs */
88d11cba9cSEd Schouten static int	dflag;		/* true if -d flag: output debug info */
89d11cba9cSEd Schouten static int	sortidle;	/* sort by idle time */
9000034645SAndrey A. Chernov int		use_ampm;	/* use AM/PM time */
91d11cba9cSEd Schouten static int	use_comma;      /* use comma as floats separator */
92d11cba9cSEd Schouten static char   **sel_users;	/* login array of particular users selected */
939b50d902SRodney W. Grimes 
949b50d902SRodney W. Grimes /*
959b50d902SRodney W. Grimes  * One of these per active utmp entry.
969b50d902SRodney W. Grimes  */
97d11cba9cSEd Schouten static struct entry {
989b50d902SRodney W. Grimes 	struct	entry *next;
99dc65bcacSEd Schouten 	struct	utmpx utmp;
1009b50d902SRodney W. Grimes 	dev_t	tdev;			/* dev_t of terminal */
1019b50d902SRodney W. Grimes 	time_t	idle;			/* idle time of terminal in seconds */
1029b50d902SRodney W. Grimes 	struct	kinfo_proc *kp;		/* `most interesting' proc */
1039b50d902SRodney W. Grimes 	char	*args;			/* arg list of interesting process */
1041bb32253SAndrey A. Chernov 	struct	kinfo_proc *dkp;	/* debug option proc list */
105ec9801deSMike Karels 	char	*from;			/* "from": name or addr */
106ae335351SMike Karels 	char	*save_from;		/* original "from": name or addr */
1079b50d902SRodney W. Grimes } *ep, *ehead = NULL, **nextp = &ehead;
1089b50d902SRodney W. Grimes 
10902f56376SDavid Malone #define	debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata)
110ac3cd520SBrian Feldman 
1115321a354SBram #define	W_XO_VERSION	"1"
1125321a354SBram 
113dc65bcacSEd Schouten #define	W_DISPUSERSIZE	10
114dc65bcacSEd Schouten #define	W_DISPLINESIZE	8
115ec9801deSMike Karels #define	W_MAXHOSTSIZE	40
1165b718312SBrian Somers 
1173f330d7dSWarner Losh static void		 pr_header(time_t *, int);
118dc65bcacSEd Schouten static struct stat	*ttystat(char *);
1193f330d7dSWarner Losh static void		 usage(int);
1209b50d902SRodney W. Grimes 
1219f0b6e5eSJohn Baldwin char *fmt_argv(char **, char *, char *, size_t);	/* ../../bin/ps/fmt.c */
1229b50d902SRodney W. Grimes 
1239b50d902SRodney W. Grimes int
main(int argc,char * argv[])124e8e649ccSJuli Mallett main(int argc, char *argv[])
1259b50d902SRodney W. Grimes {
1269b50d902SRodney W. Grimes 	struct kinfo_proc *kp;
1271bb32253SAndrey A. Chernov 	struct kinfo_proc *dkp;
1289b50d902SRodney W. Grimes 	struct stat *stp;
1293bebe991SBrian Somers 	time_t touched;
13004f6b9cbSDag-Erling Smørgrav 	size_t width;
131ab9cee11SXin LI 	int ch, i, nentries, nusers, wcmd, longidle, longattime;
13276c0abf1SMarcel Moolenaar 	const char *memf, *nlistf, *p, *save_p;
1338b56c58bSMark Murray 	char *x_suffix;
13404f6b9cbSDag-Erling Smørgrav 	char errbuf[_POSIX2_LINE_MAX];
13504f6b9cbSDag-Erling Smørgrav 	char buf[MAXHOSTNAMELEN], fn[MAXHOSTNAMELEN];
1365b718312SBrian Somers 	char *dot;
1379b50d902SRodney W. Grimes 
138baf72ec1SAndrey A. Chernov 
13976c0abf1SMarcel Moolenaar 	argc = xo_parse_args(argc, argv);
14076c0abf1SMarcel Moolenaar 	if (argc < 0)
14176c0abf1SMarcel Moolenaar 		exit(1);
14276c0abf1SMarcel Moolenaar 
143*bd490be5SBaptiste Daroussin 	if (xo_get_style(NULL) == XO_STYLE_TEXT) {
144*bd490be5SBaptiste Daroussin 		setlocale(LC_ALL, "");
145*bd490be5SBaptiste Daroussin 	}
146*bd490be5SBaptiste Daroussin 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
147*bd490be5SBaptiste Daroussin 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
1489b50d902SRodney W. Grimes 	/* Are we w(1) or uptime(1)? */
149920aa23dSEitan Adler 	if (strcmp(basename(argv[0]), "uptime") == 0) {
1509b50d902SRodney W. Grimes 		wcmd = 0;
1519b50d902SRodney W. Grimes 		p = "";
1529b50d902SRodney W. Grimes 	} else {
1539b50d902SRodney W. Grimes 		wcmd = 1;
1541bb32253SAndrey A. Chernov 		p = "dhiflM:N:nsuw";
1559b50d902SRodney W. Grimes 	}
1569b50d902SRodney W. Grimes 
157c08dcaf1SRebecca Cran 	memf = _PATH_DEVNULL;
158c08dcaf1SRebecca Cran 	nlistf = NULL;
1591c8af878SWarner Losh 	while ((ch = getopt(argc, argv, p)) != -1)
1609b50d902SRodney W. Grimes 		switch (ch) {
1611bb32253SAndrey A. Chernov 		case 'd':
1621bb32253SAndrey A. Chernov 			dflag = 1;
1631bb32253SAndrey A. Chernov 			break;
1649b50d902SRodney W. Grimes 		case 'h':
1659b50d902SRodney W. Grimes 			header = 0;
1669b50d902SRodney W. Grimes 			break;
1679b50d902SRodney W. Grimes 		case 'i':
1689b50d902SRodney W. Grimes 			sortidle = 1;
1699b50d902SRodney W. Grimes 			break;
1709b50d902SRodney W. Grimes 		case 'M':
1719b50d902SRodney W. Grimes 			header = 0;
1729b50d902SRodney W. Grimes 			memf = optarg;
1739b50d902SRodney W. Grimes 			break;
1749b50d902SRodney W. Grimes 		case 'N':
1759b50d902SRodney W. Grimes 			nlistf = optarg;
1769b50d902SRodney W. Grimes 			break;
1779b50d902SRodney W. Grimes 		case 'n':
1782279a9a4SHajimu UMEMOTO 			nflag += 1;
1799b50d902SRodney W. Grimes 			break;
1809b50d902SRodney W. Grimes 		case 'f': case 'l': case 's': case 'u': case 'w':
181d90ff31aSDag-Erling Smørgrav 			xo_warnx("-%c no longer supported", ch);
1829b50d902SRodney W. Grimes 			/* FALLTHROUGH */
1839b50d902SRodney W. Grimes 		case '?':
1849b50d902SRodney W. Grimes 		default:
1859b50d902SRodney W. Grimes 			usage(wcmd);
1869b50d902SRodney W. Grimes 		}
1879b50d902SRodney W. Grimes 	argc -= optind;
1889b50d902SRodney W. Grimes 	argv += optind;
1899b50d902SRodney W. Grimes 
1906367cd09SPeter Wemm 	if (!(_res.options & RES_INIT))
1916367cd09SPeter Wemm 		res_init();
1926367cd09SPeter Wemm 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
1936367cd09SPeter Wemm 	_res.retry = 1;		/* only try once.. */
1946367cd09SPeter Wemm 
1959b50d902SRodney W. Grimes 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
196d90ff31aSDag-Erling Smørgrav 		xo_errx(1, "%s", errbuf);
1979b50d902SRodney W. Grimes 
1989b50d902SRodney W. Grimes 	(void)time(&now);
1999b50d902SRodney W. Grimes 
2009b50d902SRodney W. Grimes 	if (*argv)
201ac3cd520SBrian Feldman 		sel_users = argv;
2029b50d902SRodney W. Grimes 
203dc65bcacSEd Schouten 	setutxent();
204dc65bcacSEd Schouten 	for (nusers = 0; (utmp = getutxent()) != NULL;) {
205ec9801deSMike Karels 		struct addrinfo hints, *res;
206ec9801deSMike Karels 		struct sockaddr_storage ss;
207ec9801deSMike Karels 		struct sockaddr *sa = (struct sockaddr *)&ss;
208ec9801deSMike Karels 		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
209ec9801deSMike Karels 		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
210ec9801deSMike Karels 		int isaddr;
211ec9801deSMike Karels 
212dc65bcacSEd Schouten 		if (utmp->ut_type != USER_PROCESS)
2139b50d902SRodney W. Grimes 			continue;
214dc65bcacSEd Schouten 		if (!(stp = ttystat(utmp->ut_line)))
2150cadb9caSBrian Somers 			continue;	/* corrupted record */
2169b50d902SRodney W. Grimes 		++nusers;
217ac3cd520SBrian Feldman 		if (wcmd == 0)
2189b50d902SRodney W. Grimes 			continue;
219ac3cd520SBrian Feldman 		if (sel_users) {
220ac3cd520SBrian Feldman 			int usermatch;
221ac3cd520SBrian Feldman 			char **user;
222ac3cd520SBrian Feldman 
223ac3cd520SBrian Feldman 			usermatch = 0;
224ac3cd520SBrian Feldman 			for (user = sel_users; !usermatch && *user; user++)
225dc65bcacSEd Schouten 				if (!strcmp(utmp->ut_user, *user))
226ac3cd520SBrian Feldman 					usermatch = 1;
227ac3cd520SBrian Feldman 			if (!usermatch)
228ac3cd520SBrian Feldman 				continue;
229ac3cd520SBrian Feldman 		}
2309b50d902SRodney W. Grimes 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
231d90ff31aSDag-Erling Smørgrav 			xo_errx(1, "calloc");
2329b50d902SRodney W. Grimes 		*nextp = ep;
233ac3cd520SBrian Feldman 		nextp = &ep->next;
234dc65bcacSEd Schouten 		memmove(&ep->utmp, utmp, sizeof *utmp);
2359b50d902SRodney W. Grimes 		ep->tdev = stp->st_rdev;
2369b50d902SRodney W. Grimes 		/*
2379b50d902SRodney W. Grimes 		 * If this is the console device, attempt to ascertain
2389b50d902SRodney W. Grimes 		 * the true console device dev_t.
2399b50d902SRodney W. Grimes 		 */
2409b50d902SRodney W. Grimes 		if (ep->tdev == 0) {
2419b50d902SRodney W. Grimes 			size_t size;
2429b50d902SRodney W. Grimes 
2439b50d902SRodney W. Grimes 			size = sizeof(dev_t);
244bec1fa86SPoul-Henning Kamp 			(void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
2459b50d902SRodney W. Grimes 		}
2463bebe991SBrian Somers 		touched = stp->st_atime;
247dc65bcacSEd Schouten 		if (touched < ep->utmp.ut_tv.tv_sec) {
2483bebe991SBrian Somers 			/* tty untouched since before login */
249dc65bcacSEd Schouten 			touched = ep->utmp.ut_tv.tv_sec;
2503bebe991SBrian Somers 		}
2513bebe991SBrian Somers 		if ((ep->idle = now - touched) < 0)
2529b50d902SRodney W. Grimes 			ep->idle = 0;
253ec9801deSMike Karels 
254ec9801deSMike Karels 		save_p = p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
255ec9801deSMike Karels 		if ((x_suffix = strrchr(p, ':')) != NULL) {
256ec9801deSMike Karels 			if ((dot = strchr(x_suffix, '.')) != NULL &&
257ec9801deSMike Karels 			    strchr(dot+1, '.') == NULL)
258ec9801deSMike Karels 				*x_suffix++ = '\0';
259ec9801deSMike Karels 			else
260ec9801deSMike Karels 				x_suffix = NULL;
261ec9801deSMike Karels 		}
262ec9801deSMike Karels 
263ec9801deSMike Karels 		isaddr = 0;
264ec9801deSMike Karels 		memset(&ss, '\0', sizeof(ss));
265ec9801deSMike Karels 		if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
266ec9801deSMike Karels 			lsin6->sin6_len = sizeof(*lsin6);
267ec9801deSMike Karels 			lsin6->sin6_family = AF_INET6;
268ec9801deSMike Karels 			isaddr = 1;
269ec9801deSMike Karels 		} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
270ec9801deSMike Karels 			lsin->sin_len = sizeof(*lsin);
271ec9801deSMike Karels 			lsin->sin_family = AF_INET;
272ec9801deSMike Karels 			isaddr = 1;
273ec9801deSMike Karels 		}
274ec9801deSMike Karels 		if (nflag == 0) {
275ec9801deSMike Karels 			/* Attempt to change an IP address into a name */
276ec9801deSMike Karels 			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
277ec9801deSMike Karels 			    sa->sa_len) == HOSTNAME_FOUND)
278ec9801deSMike Karels 				p = fn;
279ec9801deSMike Karels 		} else if (!isaddr && nflag > 1) {
280ec9801deSMike Karels 			/*
281ec9801deSMike Karels 			 * If a host has only one A/AAAA RR, change a
282ec9801deSMike Karels 			 * name into an IP address
283ec9801deSMike Karels 			 */
284ec9801deSMike Karels 			memset(&hints, 0, sizeof(hints));
285ec9801deSMike Karels 			hints.ai_flags = AI_PASSIVE;
286ec9801deSMike Karels 			hints.ai_family = AF_UNSPEC;
287ec9801deSMike Karels 			hints.ai_socktype = SOCK_STREAM;
288ec9801deSMike Karels 			if (getaddrinfo(p, NULL, &hints, &res) == 0) {
289ec9801deSMike Karels 				if (res->ai_next == NULL &&
290ec9801deSMike Karels 				    getnameinfo(res->ai_addr, res->ai_addrlen,
291ec9801deSMike Karels 					fn, sizeof(fn), NULL, 0,
292ec9801deSMike Karels 					NI_NUMERICHOST) == 0)
293ec9801deSMike Karels 					p = fn;
294ec9801deSMike Karels 				freeaddrinfo(res);
295ec9801deSMike Karels 			}
296ec9801deSMike Karels 		}
297ec9801deSMike Karels 
298ec9801deSMike Karels 		if (x_suffix) {
299ec9801deSMike Karels 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
300ec9801deSMike Karels 			p = buf;
301ec9801deSMike Karels 		}
302ec9801deSMike Karels 		ep->from = strdup(p);
30304f6b9cbSDag-Erling Smørgrav 		if ((width = strlen(p)) > fromwidth)
30404f6b9cbSDag-Erling Smørgrav 			fromwidth = width;
305ae335351SMike Karels 		if (save_p != p)
306ae335351SMike Karels 			ep->save_from = strdup(save_p);
3079b50d902SRodney W. Grimes 	}
308dc65bcacSEd Schouten 	endutxent();
3099b50d902SRodney W. Grimes 
310ec9801deSMike Karels #define HEADER_USER		"USER"
311ec9801deSMike Karels #define HEADER_TTY		"TTY"
312ec9801deSMike Karels #define HEADER_FROM		"FROM"
313ec9801deSMike Karels #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
314ec9801deSMike Karels #define HEADER_WHAT		"WHAT\n"
315ec9801deSMike Karels #define WUSED  (W_DISPUSERSIZE + W_DISPLINESIZE + fromwidth + \
316ec9801deSMike Karels 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
317ec9801deSMike Karels 
31804f6b9cbSDag-Erling Smørgrav 	if (sizeof(HEADER_FROM) > fromwidth)
319ec9801deSMike Karels 		fromwidth = sizeof(HEADER_FROM);
320ec9801deSMike Karels 	fromwidth++;
321ec9801deSMike Karels 	if (fromwidth > W_MAXHOSTSIZE)
322ec9801deSMike Karels 		fromwidth = W_MAXHOSTSIZE;
323ec9801deSMike Karels 
3245321a354SBram 	xo_set_version(W_XO_VERSION);
32576c0abf1SMarcel Moolenaar 	xo_open_container("uptime-information");
32676c0abf1SMarcel Moolenaar 
3279b50d902SRodney W. Grimes 	if (header || wcmd == 0) {
3289b50d902SRodney W. Grimes 		pr_header(&now, nusers);
329c59c7f97SPoul-Henning Kamp 		if (wcmd == 0) {
33076c0abf1SMarcel Moolenaar 			xo_close_container("uptime-information");
331d90ff31aSDag-Erling Smørgrav 			if (xo_finish() < 0)
332d90ff31aSDag-Erling Smørgrav 				xo_err(1, "stdout");
333c59c7f97SPoul-Henning Kamp 			(void)kvm_close(kd);
3349b50d902SRodney W. Grimes 			exit(0);
335c59c7f97SPoul-Henning Kamp 		}
3369b50d902SRodney W. Grimes 
33776c0abf1SMarcel Moolenaar 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s}  {T:/%s}",
338dc65bcacSEd Schouten 				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
339dc65bcacSEd Schouten 				W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
340ec9801deSMike Karels 				fromwidth, fromwidth, HEADER_FROM,
341a88d7a82SJoseph Koshy 				HEADER_LOGIN_IDLE HEADER_WHAT);
3420812a2b4SPeter Wemm 	}
3439b50d902SRodney W. Grimes 
3449b50d902SRodney W. Grimes 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
345d90ff31aSDag-Erling Smørgrav 		xo_err(1, "%s", kvm_geterr(kd));
3469b50d902SRodney W. Grimes 	for (i = 0; i < nentries; i++, kp++) {
3471131779fSEd Schouten 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
3481131779fSEd Schouten 		    kp->ki_tdev == NODEV)
3499b50d902SRodney W. Grimes 			continue;
3509b50d902SRodney W. Grimes 		for (ep = ehead; ep != NULL; ep = ep->next) {
3511f7d2501SKirk McKusick 			if (ep->tdev == kp->ki_tdev) {
3529b50d902SRodney W. Grimes 				/*
3531bb32253SAndrey A. Chernov 				 * proc is associated with this terminal
3541bb32253SAndrey A. Chernov 				 */
3551f7d2501SKirk McKusick 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
3561bb32253SAndrey A. Chernov 					/*
3571bb32253SAndrey A. Chernov 					 * Proc is 'most interesting'
3589b50d902SRodney W. Grimes 					 */
3591f7d2501SKirk McKusick 					if (proc_compare(ep->kp, kp))
3609b50d902SRodney W. Grimes 						ep->kp = kp;
3611bb32253SAndrey A. Chernov 				}
3621bb32253SAndrey A. Chernov 				/*
3631bb32253SAndrey A. Chernov 				 * Proc debug option info; add to debug
3641f7d2501SKirk McKusick 				 * list using kinfo_proc ki_spare[0]
3651bb32253SAndrey A. Chernov 				 * as next pointer; ptr to ptr avoids the
3661bb32253SAndrey A. Chernov 				 * ptr = long assumption.
3671bb32253SAndrey A. Chernov 				 */
3681bb32253SAndrey A. Chernov 				dkp = ep->dkp;
3691bb32253SAndrey A. Chernov 				ep->dkp = kp;
370ac3cd520SBrian Feldman 				debugproc(kp) = dkp;
3719b50d902SRodney W. Grimes 			}
3729b50d902SRodney W. Grimes 		}
3739b50d902SRodney W. Grimes 	}
3749b50d902SRodney W. Grimes 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
3759b50d902SRodney W. Grimes 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
3769b50d902SRodney W. Grimes 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
3779b50d902SRodney W. Grimes 	       ttywidth = 79;
3789b50d902SRodney W. Grimes         else
3799b50d902SRodney W. Grimes 	       ttywidth = ws.ws_col - 1;
3809b50d902SRodney W. Grimes 	argwidth = ttywidth - WUSED;
3819b50d902SRodney W. Grimes 	if (argwidth < 4)
3829b50d902SRodney W. Grimes 		argwidth = 8;
38330762584SKristof Provost 	/* Don't truncate if we're outputting json or XML. */
38430762584SKristof Provost 	if (xo_get_style(NULL) != XO_STYLE_TEXT)
38530762584SKristof Provost 		argwidth = ARG_MAX;
3869b50d902SRodney W. Grimes 	for (ep = ehead; ep != NULL; ep = ep->next) {
3879b50d902SRodney W. Grimes 		if (ep->kp == NULL) {
3888b56c58bSMark Murray 			ep->args = strdup("-");
3899b50d902SRodney W. Grimes 			continue;
3909b50d902SRodney W. Grimes 		}
3919b50d902SRodney W. Grimes 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
3929f0b6e5eSJohn Baldwin 		    ep->kp->ki_comm, NULL, MAXCOMLEN);
3939b50d902SRodney W. Grimes 		if (ep->args == NULL)
3946fc1bbbfSDag-Erling Smørgrav 			xo_err(1, "fmt_argv");
3959b50d902SRodney W. Grimes 	}
3969b50d902SRodney W. Grimes 	/* sort by idle time */
3979b50d902SRodney W. Grimes 	if (sortidle && ehead != NULL) {
398ac3cd520SBrian Feldman 		struct entry *from, *save;
3999b50d902SRodney W. Grimes 
400ac3cd520SBrian Feldman 		from = ehead;
4019b50d902SRodney W. Grimes 		ehead = NULL;
4029b50d902SRodney W. Grimes 		while (from != NULL) {
4039b50d902SRodney W. Grimes 			for (nextp = &ehead;
4049b50d902SRodney W. Grimes 			    (*nextp) && from->idle >= (*nextp)->idle;
4059b50d902SRodney W. Grimes 			    nextp = &(*nextp)->next)
4069b50d902SRodney W. Grimes 				continue;
4079b50d902SRodney W. Grimes 			save = from;
4089b50d902SRodney W. Grimes 			from = from->next;
4099b50d902SRodney W. Grimes 			save->next = *nextp;
4109b50d902SRodney W. Grimes 			*nextp = save;
4119b50d902SRodney W. Grimes 		}
4129b50d902SRodney W. Grimes 	}
4139b50d902SRodney W. Grimes 
41476c0abf1SMarcel Moolenaar 	xo_open_container("user-table");
41576c0abf1SMarcel Moolenaar 	xo_open_list("user-entry");
41676c0abf1SMarcel Moolenaar 
4179b50d902SRodney W. Grimes 	for (ep = ehead; ep != NULL; ep = ep->next) {
418c76b41b7SPeter Wemm 		time_t t;
4199587fac0SAndrey A. Chernov 
42076c0abf1SMarcel Moolenaar 		xo_open_instance("user-entry");
42176c0abf1SMarcel Moolenaar 
4221bb32253SAndrey A. Chernov 		if (dflag) {
42376c0abf1SMarcel Moolenaar 			xo_open_container("process-table");
42476c0abf1SMarcel Moolenaar 			xo_open_list("process-entry");
42576c0abf1SMarcel Moolenaar 
426ac3cd520SBrian Feldman 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
4278b56c58bSMark Murray 				const char *ptr;
428ac3cd520SBrian Feldman 
4290cadb9caSBrian Somers 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
4309f0b6e5eSJohn Baldwin 				    dkp->ki_comm, NULL, MAXCOMLEN);
4310cadb9caSBrian Somers 				if (ptr == NULL)
4320cadb9caSBrian Somers 					ptr = "-";
43376c0abf1SMarcel Moolenaar 				xo_open_instance("process-entry");
4342d3725d6SYuri Pankov 				xo_emit("\t\t{:process-id/%-9d/%d} "
4352d3725d6SYuri Pankov 				    "{:command/%hs}\n", dkp->ki_pid, ptr);
43676c0abf1SMarcel Moolenaar 				xo_close_instance("process-entry");
4371bb32253SAndrey A. Chernov 			}
43876c0abf1SMarcel Moolenaar 			xo_close_list("process-entry");
43976c0abf1SMarcel Moolenaar 			xo_close_container("process-table");
4401bb32253SAndrey A. Chernov 		}
44176c0abf1SMarcel Moolenaar 		xo_emit("{:user/%-*.*s/%@**@s} {:tty/%-*.*s/%@**@s} ",
442dc65bcacSEd Schouten 			W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
443dc65bcacSEd Schouten 			W_DISPLINESIZE, W_DISPLINESIZE,
4441131779fSEd Schouten 			*ep->utmp.ut_line ?
4451131779fSEd Schouten 			(strncmp(ep->utmp.ut_line, "tty", 3) &&
446255318a8SAndrey A. Chernov 			 strncmp(ep->utmp.ut_line, "cua", 3) ?
44776c0abf1SMarcel Moolenaar 			 ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-");
44876c0abf1SMarcel Moolenaar 
449ae335351SMike Karels 		if (ep->save_from)
450ae335351SMike Karels 		    xo_attr("address", "%s", ep->save_from);
45176c0abf1SMarcel Moolenaar 		xo_emit("{:from/%-*.*s/%@**@s} ",
45204f6b9cbSDag-Erling Smørgrav 		    (int)fromwidth, (int)fromwidth, ep->from);
453dc65bcacSEd Schouten 		t = ep->utmp.ut_tv.tv_sec;
45434903a55SHajimu UMEMOTO 		longattime = pr_attime(&t, &now);
45570498d5aSDaniel O'Callaghan 		longidle = pr_idle(ep->idle);
4562d3725d6SYuri Pankov 		xo_emit("{:command/%.*hs/%@*@hs}\n",
45704f6b9cbSDag-Erling Smørgrav 		    (int)argwidth - longidle - longattime,
45834903a55SHajimu UMEMOTO 		    ep->args);
45976c0abf1SMarcel Moolenaar 
46076c0abf1SMarcel Moolenaar 		xo_close_instance("user-entry");
4619b50d902SRodney W. Grimes 	}
46276c0abf1SMarcel Moolenaar 
46376c0abf1SMarcel Moolenaar 	xo_close_list("user-entry");
46476c0abf1SMarcel Moolenaar 	xo_close_container("user-table");
46576c0abf1SMarcel Moolenaar 	xo_close_container("uptime-information");
466d90ff31aSDag-Erling Smørgrav 	if (xo_finish() < 0)
467d90ff31aSDag-Erling Smørgrav 		xo_err(1, "stdout");
46876c0abf1SMarcel Moolenaar 
469c59c7f97SPoul-Henning Kamp 	(void)kvm_close(kd);
4709b50d902SRodney W. Grimes 	exit(0);
4719b50d902SRodney W. Grimes }
4729b50d902SRodney W. Grimes 
4739b50d902SRodney W. Grimes static void
pr_header(time_t * nowp,int nusers)474e8e649ccSJuli Mallett pr_header(time_t *nowp, int nusers)
4759b50d902SRodney W. Grimes {
476deb2f1b6SDag-Erling Smørgrav 	char buf[64];
477deb2f1b6SDag-Erling Smørgrav 	struct sbuf upbuf;
4789b50d902SRodney W. Grimes 	double avenrun[3];
479a21cbcb8SAndre Oppermann 	struct timespec tp;
480deb2f1b6SDag-Erling Smørgrav 	unsigned long days, hrs, mins, secs;
481deb2f1b6SDag-Erling Smørgrav 	unsigned int i;
4829b50d902SRodney W. Grimes 
4839b50d902SRodney W. Grimes 	/*
4849b50d902SRodney W. Grimes 	 * Print time of day.
4859b50d902SRodney W. Grimes 	 */
48669fe77ceSPhilippe Charnier 	if (strftime(buf, sizeof(buf),
48769fe77ceSPhilippe Charnier 	    use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
48876c0abf1SMarcel Moolenaar 		xo_emit("{:time-of-day/%s} ", buf);
4899b50d902SRodney W. Grimes 	/*
4909b50d902SRodney W. Grimes 	 * Print how long system has been up.
4919b50d902SRodney W. Grimes 	 */
492deb2f1b6SDag-Erling Smørgrav 	(void)sbuf_new(&upbuf, buf, sizeof(buf), SBUF_FIXEDLEN);
493b6eec535SEd Maste 	if (clock_gettime(CLOCK_UPTIME, &tp) != -1) {
49476c0abf1SMarcel Moolenaar 		xo_emit(" up");
495deb2f1b6SDag-Erling Smørgrav 		secs = tp.tv_sec;
496deb2f1b6SDag-Erling Smørgrav 		xo_emit("{e:uptime/%lu}", secs);
497deb2f1b6SDag-Erling Smørgrav 		mins = secs / 60;
498deb2f1b6SDag-Erling Smørgrav 		secs %= 60;
499deb2f1b6SDag-Erling Smørgrav 		hrs = mins / 60;
500deb2f1b6SDag-Erling Smørgrav 		mins %= 60;
501deb2f1b6SDag-Erling Smørgrav 		days = hrs / 24;
502deb2f1b6SDag-Erling Smørgrav 		hrs %= 24;
503deb2f1b6SDag-Erling Smørgrav 		xo_emit("{e:days/%ld}{e:hours/%ld}{e:minutes/%ld}{e:seconds/%ld}",
50404f6b9cbSDag-Erling Smørgrav 		    days, hrs, mins, secs);
505630a02daSAllan Jude 
506deb2f1b6SDag-Erling Smørgrav 		/* If we've been up longer than 60 s, round to nearest min */
507deb2f1b6SDag-Erling Smørgrav 		if (tp.tv_sec > 60) {
508deb2f1b6SDag-Erling Smørgrav 			secs = tp.tv_sec + 30;
509deb2f1b6SDag-Erling Smørgrav 			mins = secs / 60;
510deb2f1b6SDag-Erling Smørgrav 			secs = 0;
511deb2f1b6SDag-Erling Smørgrav 			hrs = mins / 60;
512deb2f1b6SDag-Erling Smørgrav 			mins %= 60;
513deb2f1b6SDag-Erling Smørgrav 			days = hrs / 24;
514deb2f1b6SDag-Erling Smørgrav 			hrs %= 24;
515deb2f1b6SDag-Erling Smørgrav 		}
516deb2f1b6SDag-Erling Smørgrav 
5179b50d902SRodney W. Grimes 		if (days > 0)
518deb2f1b6SDag-Erling Smørgrav 			sbuf_printf(&upbuf, " %ld day%s,",
51976c0abf1SMarcel Moolenaar 				days, days > 1 ? "s" : "");
5209b50d902SRodney W. Grimes 		if (hrs > 0 && mins > 0)
521deb2f1b6SDag-Erling Smørgrav 			sbuf_printf(&upbuf, " %2ld:%02ld,", hrs, mins);
5229d8c91b7SAndrey A. Chernov 		else if (hrs > 0)
523deb2f1b6SDag-Erling Smørgrav 			sbuf_printf(&upbuf, " %ld hr%s,",
52476c0abf1SMarcel Moolenaar 				hrs, hrs > 1 ? "s" : "");
5259d8c91b7SAndrey A. Chernov 		else if (mins > 0)
526deb2f1b6SDag-Erling Smørgrav 			sbuf_printf(&upbuf, " %ld min%s,",
52776c0abf1SMarcel Moolenaar 				mins, mins > 1 ? "s" : "");
5289d8c91b7SAndrey A. Chernov 		else
529deb2f1b6SDag-Erling Smørgrav 			sbuf_printf(&upbuf, " %ld sec%s,",
53076c0abf1SMarcel Moolenaar 				secs, secs > 1 ? "s" : "");
531deb2f1b6SDag-Erling Smørgrav 		if (sbuf_finish(&upbuf) != 0)
532630a02daSAllan Jude 			xo_err(1, "Could not generate output");
533deb2f1b6SDag-Erling Smørgrav 		xo_emit("{:uptime-human/%s}", sbuf_data(&upbuf));
534deb2f1b6SDag-Erling Smørgrav 		sbuf_delete(&upbuf);
5359b50d902SRodney W. Grimes 	}
5369b50d902SRodney W. Grimes 
5379b50d902SRodney W. Grimes 	/* Print number of users logged in to system */
538ba86ca7cSAlexander Motin 	xo_emit(" {:users/%d} {Np:user,users}", nusers);
5399b50d902SRodney W. Grimes 
5409b50d902SRodney W. Grimes 	/*
5419b50d902SRodney W. Grimes 	 * Print 1, 5, and 15 minute load averages.
5429b50d902SRodney W. Grimes 	 */
543807bd0d9SMarcelo Araujo 	if (getloadavg(avenrun, nitems(avenrun)) == -1)
54476c0abf1SMarcel Moolenaar 		xo_emit(", no load average information available\n");
5459b50d902SRodney W. Grimes 	else {
54676c0abf1SMarcel Moolenaar 		static const char *format[] = {
54776c0abf1SMarcel Moolenaar 		    " {:load-average-1/%.2f}",
54876c0abf1SMarcel Moolenaar 		    " {:load-average-5/%.2f}",
54976c0abf1SMarcel Moolenaar 		    " {:load-average-15/%.2f}",
55076c0abf1SMarcel Moolenaar 		};
55176c0abf1SMarcel Moolenaar 		xo_emit(", load averages:");
552deb2f1b6SDag-Erling Smørgrav 		for (i = 0; i < nitems(avenrun); i++) {
5532742fc8eSAndrey A. Chernov 			if (use_comma && i > 0)
55476c0abf1SMarcel Moolenaar 				xo_emit(",");
55576c0abf1SMarcel Moolenaar 			xo_emit(format[i], avenrun[i]);
5562742fc8eSAndrey A. Chernov 		}
55776c0abf1SMarcel Moolenaar 		xo_emit("\n");
5589b50d902SRodney W. Grimes 	}
5599b50d902SRodney W. Grimes }
5609b50d902SRodney W. Grimes 
5619b50d902SRodney W. Grimes static struct stat *
ttystat(char * line)562dc65bcacSEd Schouten ttystat(char *line)
5639b50d902SRodney W. Grimes {
5649b50d902SRodney W. Grimes 	static struct stat sb;
5659b50d902SRodney W. Grimes 	char ttybuf[MAXPATHLEN];
5669b50d902SRodney W. Grimes 
567dc65bcacSEd Schouten 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
56804f6b9cbSDag-Erling Smørgrav 	if (stat(ttybuf, &sb) == 0 && S_ISCHR(sb.st_mode))
5699b50d902SRodney W. Grimes 		return (&sb);
570d0d0355eSSean Chittenden 	return (NULL);
5719b50d902SRodney W. Grimes }
5729b50d902SRodney W. Grimes 
5739b50d902SRodney W. Grimes static void
usage(int wcmd)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