1 /*- 2 * Copyright (c) 1980, 1991, 1993, 1994 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 4. Neither the name of the University nor the names of its contributors 14 * may be used to endorse or promote products derived from this software 15 * without specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27 * SUCH DAMAGE. 28 */ 29 30 #include <sys/cdefs.h> 31 32 __FBSDID("$FreeBSD$"); 33 34 #ifndef lint 35 static 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 39 40 #ifndef lint 41 static const char sccsid[] = "@(#)w.c 8.4 (Berkeley) 4/16/94"; 42 #endif 43 44 /* 45 * w - print system status (who and what) 46 * 47 * This program is similar to the systat command on Tenex/Tops 10/20 48 * 49 */ 50 #include <sys/param.h> 51 #include <sys/time.h> 52 #include <sys/stat.h> 53 #include <sys/sysctl.h> 54 #include <sys/proc.h> 55 #include <sys/user.h> 56 #include <sys/ioctl.h> 57 #include <sys/socket.h> 58 #include <sys/tty.h> 59 60 #include <machine/cpu.h> 61 #include <netinet/in.h> 62 #include <arpa/inet.h> 63 #include <arpa/nameser.h> 64 65 #include <ctype.h> 66 #include <err.h> 67 #include <errno.h> 68 #include <fcntl.h> 69 #include <kvm.h> 70 #include <langinfo.h> 71 #include <libgen.h> 72 #include <libutil.h> 73 #include <limits.h> 74 #include <locale.h> 75 #include <netdb.h> 76 #include <nlist.h> 77 #include <paths.h> 78 #include <resolv.h> 79 #include <stdio.h> 80 #include <stdlib.h> 81 #include <string.h> 82 #include <timeconv.h> 83 #include <unistd.h> 84 #include <utmpx.h> 85 #include <vis.h> 86 #include <libxo/xo.h> 87 88 #include "extern.h" 89 90 static struct utmpx *utmp; 91 static struct winsize ws; 92 static kvm_t *kd; 93 static time_t now; /* the current time of day */ 94 static int ttywidth; /* width of tty */ 95 static int argwidth; /* width of tty */ 96 static int header = 1; /* true if -h flag: don't print heading */ 97 static int nflag; /* true if -n flag: don't convert addrs */ 98 static int dflag; /* true if -d flag: output debug info */ 99 static int sortidle; /* sort by idle time */ 100 int use_ampm; /* use AM/PM time */ 101 static int use_comma; /* use comma as floats separator */ 102 static char **sel_users; /* login array of particular users selected */ 103 104 /* 105 * One of these per active utmp entry. 106 */ 107 static struct entry { 108 struct entry *next; 109 struct utmpx 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 117 #define debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata) 118 119 #define W_DISPUSERSIZE 10 120 #define W_DISPLINESIZE 8 121 #define W_DISPHOSTSIZE 24 122 123 static void pr_header(time_t *, int); 124 static struct stat *ttystat(char *); 125 static void usage(int); 126 127 char *fmt_argv(char **, char *, char *, size_t); /* ../../bin/ps/fmt.c */ 128 129 int 130 main(int argc, char *argv[]) 131 { 132 struct kinfo_proc *kp; 133 struct kinfo_proc *dkp; 134 struct stat *stp; 135 time_t touched; 136 int ch, i, nentries, nusers, wcmd, longidle, longattime, dropgid; 137 const char *memf, *nlistf, *p, *save_p; 138 char *x_suffix; 139 char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX]; 140 char fn[MAXHOSTNAMELEN]; 141 char *dot; 142 143 (void)setlocale(LC_ALL, ""); 144 use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0'); 145 use_comma = (*nl_langinfo(RADIXCHAR) != ','); 146 147 argc = xo_parse_args(argc, argv); 148 if (argc < 0) 149 exit(1); 150 151 /* Are we w(1) or uptime(1)? */ 152 if (strcmp(basename(argv[0]), "uptime") == 0) { 153 wcmd = 0; 154 p = ""; 155 } else { 156 wcmd = 1; 157 p = "dhiflM:N:nsuw"; 158 } 159 160 dropgid = 0; 161 memf = _PATH_DEVNULL; 162 nlistf = NULL; 163 while ((ch = getopt(argc, argv, p)) != -1) 164 switch (ch) { 165 case 'd': 166 dflag = 1; 167 break; 168 case 'h': 169 header = 0; 170 break; 171 case 'i': 172 sortidle = 1; 173 break; 174 case 'M': 175 header = 0; 176 memf = optarg; 177 dropgid = 1; 178 break; 179 case 'N': 180 nlistf = optarg; 181 dropgid = 1; 182 break; 183 case 'n': 184 nflag = 1; 185 break; 186 case 'f': case 'l': case 's': case 'u': case 'w': 187 warnx("[-flsuw] no longer supported"); 188 /* FALLTHROUGH */ 189 case '?': 190 default: 191 usage(wcmd); 192 } 193 argc -= optind; 194 argv += optind; 195 196 if (!(_res.options & RES_INIT)) 197 res_init(); 198 _res.retrans = 2; /* resolver timeout to 2 seconds per try */ 199 _res.retry = 1; /* only try once.. */ 200 201 /* 202 * Discard setgid privileges if not the running kernel so that bad 203 * guys can't print interesting stuff from kernel memory. 204 */ 205 if (dropgid) 206 setgid(getgid()); 207 208 if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL) 209 errx(1, "%s", errbuf); 210 211 (void)time(&now); 212 213 if (*argv) 214 sel_users = argv; 215 216 setutxent(); 217 for (nusers = 0; (utmp = getutxent()) != NULL;) { 218 if (utmp->ut_type != USER_PROCESS) 219 continue; 220 if (!(stp = ttystat(utmp->ut_line))) 221 continue; /* corrupted record */ 222 ++nusers; 223 if (wcmd == 0) 224 continue; 225 if (sel_users) { 226 int usermatch; 227 char **user; 228 229 usermatch = 0; 230 for (user = sel_users; !usermatch && *user; user++) 231 if (!strcmp(utmp->ut_user, *user)) 232 usermatch = 1; 233 if (!usermatch) 234 continue; 235 } 236 if ((ep = calloc(1, sizeof(struct entry))) == NULL) 237 errx(1, "calloc"); 238 *nextp = ep; 239 nextp = &ep->next; 240 memmove(&ep->utmp, utmp, sizeof *utmp); 241 ep->tdev = stp->st_rdev; 242 /* 243 * If this is the console device, attempt to ascertain 244 * the true console device dev_t. 245 */ 246 if (ep->tdev == 0) { 247 size_t size; 248 249 size = sizeof(dev_t); 250 (void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0); 251 } 252 touched = stp->st_atime; 253 if (touched < ep->utmp.ut_tv.tv_sec) { 254 /* tty untouched since before login */ 255 touched = ep->utmp.ut_tv.tv_sec; 256 } 257 if ((ep->idle = now - touched) < 0) 258 ep->idle = 0; 259 } 260 endutxent(); 261 262 xo_open_container("uptime-information"); 263 264 if (header || wcmd == 0) { 265 pr_header(&now, nusers); 266 if (wcmd == 0) { 267 xo_close_container("uptime-information"); 268 xo_finish(); 269 270 (void)kvm_close(kd); 271 exit(0); 272 } 273 274 #define HEADER_USER "USER" 275 #define HEADER_TTY "TTY" 276 #define HEADER_FROM "FROM" 277 #define HEADER_LOGIN_IDLE "LOGIN@ IDLE " 278 #define HEADER_WHAT "WHAT\n" 279 #define WUSED (W_DISPUSERSIZE + W_DISPLINESIZE + W_DISPHOSTSIZE + \ 280 sizeof(HEADER_LOGIN_IDLE) + 3) /* header width incl. spaces */ 281 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%s}", 282 W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER, 283 W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY, 284 W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM, 285 HEADER_LOGIN_IDLE HEADER_WHAT); 286 } 287 288 if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL) 289 err(1, "%s", kvm_geterr(kd)); 290 for (i = 0; i < nentries; i++, kp++) { 291 if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB || 292 kp->ki_tdev == NODEV) 293 continue; 294 for (ep = ehead; ep != NULL; ep = ep->next) { 295 if (ep->tdev == kp->ki_tdev) { 296 /* 297 * proc is associated with this terminal 298 */ 299 if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) { 300 /* 301 * Proc is 'most interesting' 302 */ 303 if (proc_compare(ep->kp, kp)) 304 ep->kp = kp; 305 } 306 /* 307 * Proc debug option info; add to debug 308 * list using kinfo_proc ki_spare[0] 309 * as next pointer; ptr to ptr avoids the 310 * ptr = long assumption. 311 */ 312 dkp = ep->dkp; 313 ep->dkp = kp; 314 debugproc(kp) = dkp; 315 } 316 } 317 } 318 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 && 319 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 && 320 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0) 321 ttywidth = 79; 322 else 323 ttywidth = ws.ws_col - 1; 324 argwidth = ttywidth - WUSED; 325 if (argwidth < 4) 326 argwidth = 8; 327 for (ep = ehead; ep != NULL; ep = ep->next) { 328 if (ep->kp == NULL) { 329 ep->args = strdup("-"); 330 continue; 331 } 332 ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth), 333 ep->kp->ki_comm, NULL, MAXCOMLEN); 334 if (ep->args == NULL) 335 err(1, NULL); 336 } 337 /* sort by idle time */ 338 if (sortidle && ehead != NULL) { 339 struct entry *from, *save; 340 341 from = ehead; 342 ehead = NULL; 343 while (from != NULL) { 344 for (nextp = &ehead; 345 (*nextp) && from->idle >= (*nextp)->idle; 346 nextp = &(*nextp)->next) 347 continue; 348 save = from; 349 from = from->next; 350 save->next = *nextp; 351 *nextp = save; 352 } 353 } 354 355 xo_open_container("user-table"); 356 xo_open_list("user-entry"); 357 358 for (ep = ehead; ep != NULL; ep = ep->next) { 359 struct addrinfo hints, *res; 360 struct sockaddr_storage ss; 361 struct sockaddr *sa = (struct sockaddr *)&ss; 362 struct sockaddr_in *lsin = (struct sockaddr_in *)&ss; 363 struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss; 364 time_t t; 365 int isaddr; 366 367 xo_open_instance("user-entry"); 368 369 save_p = p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-"; 370 if ((x_suffix = strrchr(p, ':')) != NULL) { 371 if ((dot = strchr(x_suffix, '.')) != NULL && 372 strchr(dot+1, '.') == NULL) 373 *x_suffix++ = '\0'; 374 else 375 x_suffix = NULL; 376 } 377 378 isaddr = 0; 379 memset(&ss, '\0', sizeof(ss)); 380 if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) { 381 lsin6->sin6_len = sizeof(*lsin6); 382 lsin6->sin6_family = AF_INET6; 383 isaddr = 1; 384 } else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) { 385 lsin->sin_len = sizeof(*lsin); 386 lsin->sin_family = AF_INET; 387 isaddr = 1; 388 } 389 if (!nflag) { 390 /* Attempt to change an IP address into a name */ 391 if (isaddr && realhostname_sa(fn, sizeof(fn), sa, 392 sa->sa_len) == HOSTNAME_FOUND) 393 p = fn; 394 } else if (!isaddr) { 395 /* 396 * If a host has only one A/AAAA RR, change a 397 * name into an IP address 398 */ 399 memset(&hints, 0, sizeof(hints)); 400 hints.ai_flags = AI_PASSIVE; 401 hints.ai_family = AF_UNSPEC; 402 hints.ai_socktype = SOCK_STREAM; 403 if (getaddrinfo(p, NULL, &hints, &res) == 0) { 404 if (res->ai_next == NULL && 405 getnameinfo(res->ai_addr, res->ai_addrlen, 406 fn, sizeof(fn), NULL, 0, 407 NI_NUMERICHOST) == 0) 408 p = fn; 409 freeaddrinfo(res); 410 } 411 } 412 413 if (x_suffix) { 414 (void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix); 415 p = buf; 416 } 417 if (dflag) { 418 xo_open_container("process-table"); 419 xo_open_list("process-entry"); 420 421 for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) { 422 const char *ptr; 423 424 ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth), 425 dkp->ki_comm, NULL, MAXCOMLEN); 426 if (ptr == NULL) 427 ptr = "-"; 428 xo_open_instance("process-entry"); 429 xo_emit("\t\t{:process-id/%-9d/%d} {:command/%s}\n", 430 dkp->ki_pid, ptr); 431 xo_close_instance("process-entry"); 432 } 433 xo_close_list("process-entry"); 434 xo_close_container("process-table"); 435 } 436 xo_emit("{:user/%-*.*s/%@**@s} {:tty/%-*.*s/%@**@s} ", 437 W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user, 438 W_DISPLINESIZE, W_DISPLINESIZE, 439 *ep->utmp.ut_line ? 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) : "-"); 443 444 if (save_p && save_p != p) 445 xo_attr("address", "%s", save_p); 446 xo_emit("{:from/%-*.*s/%@**@s} ", 447 W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-"); 448 t = ep->utmp.ut_tv.tv_sec; 449 longattime = pr_attime(&t, &now); 450 longidle = pr_idle(ep->idle); 451 xo_emit("{:command/%.*s/%@*@s}\n", 452 argwidth - longidle - longattime, 453 ep->args); 454 455 xo_close_instance("user-entry"); 456 } 457 458 xo_close_list("user-entry"); 459 xo_close_container("user-table"); 460 xo_close_container("uptime-information"); 461 xo_finish(); 462 463 (void)kvm_close(kd); 464 exit(0); 465 } 466 467 static void 468 pr_header(time_t *nowp, int nusers) 469 { 470 double avenrun[3]; 471 time_t uptime; 472 struct timespec tp; 473 int days, hrs, i, mins, secs; 474 char buf[256]; 475 476 /* 477 * Print time of day. 478 */ 479 if (strftime(buf, sizeof(buf), 480 use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0) 481 xo_emit("{:time-of-day/%s} ", buf); 482 /* 483 * Print how long system has been up. 484 */ 485 if (clock_gettime(CLOCK_UPTIME, &tp) != -1) { 486 uptime = tp.tv_sec; 487 if (uptime > 60) 488 uptime += 30; 489 days = uptime / 86400; 490 uptime %= 86400; 491 hrs = uptime / 3600; 492 uptime %= 3600; 493 mins = uptime / 60; 494 secs = uptime % 60; 495 xo_emit(" up"); 496 xo_attr("seconds", "%lu", (unsigned long) tp.tv_sec); 497 if (days > 0) 498 xo_emit(" {:uptime/%d day%s},", 499 days, days > 1 ? "s" : ""); 500 if (hrs > 0 && mins > 0) 501 xo_emit(" {:uptime/%2d:%02d},", hrs, mins); 502 else if (hrs > 0) 503 xo_emit(" {:uptime/%d hr%s},", 504 hrs, hrs > 1 ? "s" : ""); 505 else if (mins > 0) 506 xo_emit(" {:uptime/%d min%s},", 507 mins, mins > 1 ? "s" : ""); 508 else 509 xo_emit(" {:uptime/%d sec%s},", 510 secs, secs > 1 ? "s" : ""); 511 } 512 513 /* Print number of users logged in to system */ 514 xo_emit(" {:users/%d} {N:user%s}", nusers, nusers == 1 ? "" : "s"); 515 516 /* 517 * Print 1, 5, and 15 minute load averages. 518 */ 519 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1) 520 xo_emit(", no load average information available\n"); 521 else { 522 static const char *format[] = { 523 " {:load-average-1/%.2f}", 524 " {:load-average-5/%.2f}", 525 " {:load-average-15/%.2f}", 526 }; 527 xo_emit(", load averages:"); 528 for (i = 0; i < (int)(sizeof(avenrun) / sizeof(avenrun[0])); i++) { 529 if (use_comma && i > 0) 530 xo_emit(","); 531 xo_emit(format[i], avenrun[i]); 532 } 533 xo_emit("\n"); 534 } 535 } 536 537 static struct stat * 538 ttystat(char *line) 539 { 540 static struct stat sb; 541 char ttybuf[MAXPATHLEN]; 542 543 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line); 544 if (stat(ttybuf, &sb) == 0 && S_ISCHR(sb.st_mode)) { 545 return (&sb); 546 } else 547 return (NULL); 548 } 549 550 static void 551 usage(int wcmd) 552 { 553 if (wcmd) 554 xo_error("usage: w [-dhin] [-M core] [-N system] [user ...]\n"); 555 else 556 xo_error("usage: uptime\n"); 557 xo_finish(); 558 exit(1); 559 } 560