2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1980, 1991, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * w - print system status (who and what)
35 * This program is similar to the systat command on Tenex/Tops 10/20
38 #include <sys/param.h>
41 #include <sys/sysctl.h>
44 #include <sys/ioctl.h>
46 #include <sys/socket.h>
48 #include <sys/types.h>
50 #include <machine/cpu.h>
51 #include <netinet/in.h>
52 #include <arpa/inet.h>
53 #include <arpa/nameser.h>
79 static struct utmpx *utmp;
80 static struct winsize ws;
82 static time_t now; /* the current time of day */
83 static size_t ttywidth; /* width of tty */
84 static size_t fromwidth = 0; /* max width of "from" field */
85 static size_t argwidth; /* width of arguments */
86 static int header = 1; /* true if -h flag: don't print heading */
87 static int nflag; /* true if -n flag: don't convert addrs */
88 static int dflag; /* true if -d flag: output debug info */
89 static int sortidle; /* sort by idle time */
90 int use_ampm; /* use AM/PM time */
91 static int use_comma; /* use comma as floats separator */
92 static char **sel_users; /* login array of particular users selected */
95 * One of these per active utmp entry.
100 dev_t tdev; /* dev_t of terminal */
101 time_t idle; /* idle time of terminal in seconds */
102 struct kinfo_proc *kp; /* `most interesting' proc */
103 char *args; /* arg list of interesting process */
104 struct kinfo_proc *dkp; /* debug option proc list */
105 char *from; /* "from": name or addr */
106 char *save_from; /* original "from": name or addr */
107 } *ep, *ehead = NULL, **nextp = &ehead;
109 #define debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata)
111 #define W_DISPUSERSIZE 10
112 #define W_DISPLINESIZE 8
113 #define W_MAXHOSTSIZE 40
115 static void pr_header(time_t *, int);
116 static struct stat *ttystat(char *);
117 static void usage(int);
119 char *fmt_argv(char **, char *, char *, size_t); /* ../../bin/ps/fmt.c */
122 main(int argc, char *argv[])
124 struct kinfo_proc *kp;
125 struct kinfo_proc *dkp;
129 int ch, i, nentries, nusers, wcmd, longidle, longattime;
130 const char *memf, *nlistf, *p, *save_p;
132 char errbuf[_POSIX2_LINE_MAX];
133 char buf[MAXHOSTNAMELEN], fn[MAXHOSTNAMELEN];
136 (void)setlocale(LC_ALL, "");
137 use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
138 use_comma = (*nl_langinfo(RADIXCHAR) != ',');
140 argc = xo_parse_args(argc, argv);
144 /* Are we w(1) or uptime(1)? */
145 if (strcmp(basename(argv[0]), "uptime") == 0) {
153 memf = _PATH_DEVNULL;
155 while ((ch = getopt(argc, argv, p)) != -1)
176 case 'f': case 'l': case 's': case 'u': case 'w':
177 xo_warnx("-%c no longer supported", ch);
186 if (!(_res.options & RES_INIT))
188 _res.retrans = 2; /* resolver timeout to 2 seconds per try */
189 _res.retry = 1; /* only try once.. */
191 if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
192 xo_errx(1, "%s", errbuf);
200 for (nusers = 0; (utmp = getutxent()) != NULL;) {
201 struct addrinfo hints, *res;
202 struct sockaddr_storage ss;
203 struct sockaddr *sa = (struct sockaddr *)&ss;
204 struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
205 struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
208 if (utmp->ut_type != USER_PROCESS)
210 if (!(stp = ttystat(utmp->ut_line)))
211 continue; /* corrupted record */
220 for (user = sel_users; !usermatch && *user; user++)
221 if (!strcmp(utmp->ut_user, *user))
226 if ((ep = calloc(1, sizeof(struct entry))) == NULL)
227 xo_errx(1, "calloc");
230 memmove(&ep->utmp, utmp, sizeof *utmp);
231 ep->tdev = stp->st_rdev;
233 * If this is the console device, attempt to ascertain
234 * the true console device dev_t.
239 size = sizeof(dev_t);
240 (void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
242 touched = stp->st_atime;
243 if (touched < ep->utmp.ut_tv.tv_sec) {
244 /* tty untouched since before login */
245 touched = ep->utmp.ut_tv.tv_sec;
247 if ((ep->idle = now - touched) < 0)
250 save_p = p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
251 if ((x_suffix = strrchr(p, ':')) != NULL) {
252 if ((dot = strchr(x_suffix, '.')) != NULL &&
253 strchr(dot+1, '.') == NULL)
260 memset(&ss, '\0', sizeof(ss));
261 if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
262 lsin6->sin6_len = sizeof(*lsin6);
263 lsin6->sin6_family = AF_INET6;
265 } else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
266 lsin->sin_len = sizeof(*lsin);
267 lsin->sin_family = AF_INET;
271 /* Attempt to change an IP address into a name */
272 if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
273 sa->sa_len) == HOSTNAME_FOUND)
275 } else if (!isaddr && nflag > 1) {
277 * If a host has only one A/AAAA RR, change a
278 * name into an IP address
280 memset(&hints, 0, sizeof(hints));
281 hints.ai_flags = AI_PASSIVE;
282 hints.ai_family = AF_UNSPEC;
283 hints.ai_socktype = SOCK_STREAM;
284 if (getaddrinfo(p, NULL, &hints, &res) == 0) {
285 if (res->ai_next == NULL &&
286 getnameinfo(res->ai_addr, res->ai_addrlen,
287 fn, sizeof(fn), NULL, 0,
288 NI_NUMERICHOST) == 0)
295 (void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
298 ep->from = strdup(p);
299 if ((width = strlen(p)) > fromwidth)
302 ep->save_from = strdup(save_p);
306 #define HEADER_USER "USER"
307 #define HEADER_TTY "TTY"
308 #define HEADER_FROM "FROM"
309 #define HEADER_LOGIN_IDLE "LOGIN@ IDLE "
310 #define HEADER_WHAT "WHAT\n"
311 #define WUSED (W_DISPUSERSIZE + W_DISPLINESIZE + fromwidth + \
312 sizeof(HEADER_LOGIN_IDLE) + 3) /* header width incl. spaces */
314 if (sizeof(HEADER_FROM) > fromwidth)
315 fromwidth = sizeof(HEADER_FROM);
317 if (fromwidth > W_MAXHOSTSIZE)
318 fromwidth = W_MAXHOSTSIZE;
320 xo_open_container("uptime-information");
322 if (header || wcmd == 0) {
323 pr_header(&now, nusers);
325 xo_close_container("uptime-information");
332 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%s}",
333 W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
334 W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
335 fromwidth, fromwidth, HEADER_FROM,
336 HEADER_LOGIN_IDLE HEADER_WHAT);
339 if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
340 xo_err(1, "%s", kvm_geterr(kd));
341 for (i = 0; i < nentries; i++, kp++) {
342 if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
343 kp->ki_tdev == NODEV)
345 for (ep = ehead; ep != NULL; ep = ep->next) {
346 if (ep->tdev == kp->ki_tdev) {
348 * proc is associated with this terminal
350 if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
352 * Proc is 'most interesting'
354 if (proc_compare(ep->kp, kp))
358 * Proc debug option info; add to debug
359 * list using kinfo_proc ki_spare[0]
360 * as next pointer; ptr to ptr avoids the
361 * ptr = long assumption.
369 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
370 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
371 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
374 ttywidth = ws.ws_col - 1;
375 argwidth = ttywidth - WUSED;
378 /* Don't truncate if we're outputting json or XML. */
379 if (xo_get_style(NULL) != XO_STYLE_TEXT)
381 for (ep = ehead; ep != NULL; ep = ep->next) {
382 if (ep->kp == NULL) {
383 ep->args = strdup("-");
386 ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
387 ep->kp->ki_comm, NULL, MAXCOMLEN);
388 if (ep->args == NULL)
389 xo_err(1, "fmt_argv");
391 /* sort by idle time */
392 if (sortidle && ehead != NULL) {
393 struct entry *from, *save;
397 while (from != NULL) {
399 (*nextp) && from->idle >= (*nextp)->idle;
400 nextp = &(*nextp)->next)
409 xo_open_container("user-table");
410 xo_open_list("user-entry");
412 for (ep = ehead; ep != NULL; ep = ep->next) {
415 xo_open_instance("user-entry");
418 xo_open_container("process-table");
419 xo_open_list("process-entry");
421 for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
424 ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
425 dkp->ki_comm, NULL, MAXCOMLEN);
428 xo_open_instance("process-entry");
429 xo_emit("\t\t{:process-id/%-9d/%d} "
430 "{:command/%hs}\n", dkp->ki_pid, ptr);
431 xo_close_instance("process-entry");
433 xo_close_list("process-entry");
434 xo_close_container("process-table");
436 xo_emit("{:user/%-*.*s/%@**@s} {:tty/%-*.*s/%@**@s} ",
437 W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
438 W_DISPLINESIZE, W_DISPLINESIZE,
440 (strncmp(ep->utmp.ut_line, "tty", 3) &&
441 strncmp(ep->utmp.ut_line, "cua", 3) ?
442 ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-");
445 xo_attr("address", "%s", ep->save_from);
446 xo_emit("{:from/%-*.*s/%@**@s} ",
447 (int)fromwidth, (int)fromwidth, ep->from);
448 t = ep->utmp.ut_tv.tv_sec;
449 longattime = pr_attime(&t, &now);
450 longidle = pr_idle(ep->idle);
451 xo_emit("{:command/%.*hs/%@*@hs}\n",
452 (int)argwidth - longidle - longattime,
455 xo_close_instance("user-entry");
458 xo_close_list("user-entry");
459 xo_close_container("user-table");
460 xo_close_container("uptime-information");
469 pr_header(time_t *nowp, int nusers)
475 unsigned long days, hrs, mins, secs;
481 if (strftime(buf, sizeof(buf),
482 use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
483 xo_emit("{:time-of-day/%s} ", buf);
485 * Print how long system has been up.
487 (void)sbuf_new(&upbuf, buf, sizeof(buf), SBUF_FIXEDLEN);
488 if (clock_gettime(CLOCK_UPTIME, &tp) != -1) {
491 xo_emit("{e:uptime/%lu}", secs);
498 xo_emit("{e:days/%ld}{e:hours/%ld}{e:minutes/%ld}{e:seconds/%ld}",
499 days, hrs, mins, secs);
501 /* If we've been up longer than 60 s, round to nearest min */
502 if (tp.tv_sec > 60) {
503 secs = tp.tv_sec + 30;
513 sbuf_printf(&upbuf, " %ld day%s,",
514 days, days > 1 ? "s" : "");
515 if (hrs > 0 && mins > 0)
516 sbuf_printf(&upbuf, " %2ld:%02ld,", hrs, mins);
518 sbuf_printf(&upbuf, " %ld hr%s,",
519 hrs, hrs > 1 ? "s" : "");
521 sbuf_printf(&upbuf, " %ld min%s,",
522 mins, mins > 1 ? "s" : "");
524 sbuf_printf(&upbuf, " %ld sec%s,",
525 secs, secs > 1 ? "s" : "");
526 if (sbuf_finish(&upbuf) != 0)
527 xo_err(1, "Could not generate output");
528 xo_emit("{:uptime-human/%s}", sbuf_data(&upbuf));
532 /* Print number of users logged in to system */
533 xo_emit(" {:users/%d} {Np:user,users}", nusers);
536 * Print 1, 5, and 15 minute load averages.
538 if (getloadavg(avenrun, nitems(avenrun)) == -1)
539 xo_emit(", no load average information available\n");
541 static const char *format[] = {
542 " {:load-average-1/%.2f}",
543 " {:load-average-5/%.2f}",
544 " {:load-average-15/%.2f}",
546 xo_emit(", load averages:");
547 for (i = 0; i < nitems(avenrun); i++) {
548 if (use_comma && i > 0)
550 xo_emit(format[i], avenrun[i]);
559 static struct stat sb;
560 char ttybuf[MAXPATHLEN];
562 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
563 if (stat(ttybuf, &sb) == 0 && S_ISCHR(sb.st_mode))
572 xo_error("usage: w [-dhin] [-M core] [-N system] [user ...]\n");
574 xo_error("usage: uptime\n");