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 * 3. 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 * @(#) Copyright (c) 1980, 1991, 1993, 1994 The Regents of the University of California. All rights reserved. 30 * @(#)w.c 8.4 (Berkeley) 4/16/94 31 * $FreeBSD: src/usr.bin/w/w.c,v 1.38.2.6 2002/03/12 19:51:51 phantom Exp $ 32 */ 33 34 /* 35 * w - print system status (who and what) 36 * 37 * This program is similar to the systat command on Tenex/Tops 10/20 38 * 39 */ 40 #include <sys/user.h> 41 #include <sys/param.h> 42 #include <sys/time.h> 43 #include <sys/stat.h> 44 #include <sys/sysctl.h> 45 #include <sys/ioctl.h> 46 #include <sys/socket.h> 47 #include <sys/tty.h> 48 49 #include <machine/cpu.h> 50 #include <netinet/in.h> 51 #include <arpa/inet.h> 52 53 #include <ctype.h> 54 #include <err.h> 55 #include <errno.h> 56 #include <fcntl.h> 57 #include <kvm.h> 58 #include <limits.h> 59 #include <langinfo.h> 60 #include <locale.h> 61 #include <netdb.h> 62 #include <nlist.h> 63 #include <paths.h> 64 #include <stdio.h> 65 #include <stdlib.h> 66 #include <string.h> 67 #include <unistd.h> 68 #include <utmpx.h> 69 #include <vis.h> 70 71 #include <arpa/nameser.h> 72 #include <resolv.h> 73 74 #include "extern.h" 75 76 static struct winsize ws; 77 static kvm_t *kd; 78 static time_t now; /* the current time of day */ 79 static time_t then; 80 static int ttywidth; /* width of tty */ 81 static int argwidth; /* width of tty */ 82 static int header = 1; /* true if -h flag: don't print heading */ 83 static int nflag; /* true if -n flag: don't convert addrs */ 84 static int dflag; /* true if -d flag: output debug info */ 85 static int sortidle; /* sort by idle time */ 86 int use_ampm; /* use AM/PM time */ 87 static int use_comma; /* use comma as floats separator */ 88 static char **sel_users; /* login array of particular users selected */ 89 static char domain[MAXHOSTNAMELEN]; 90 static int maxname = 8, maxline = 3, maxhost = 16; 91 92 /* 93 * One of these per active utmpx entry. 94 */ 95 static struct entry { 96 struct entry *next; 97 char name[UTX_USERSIZE + 1]; 98 char line[UTX_LINESIZE + 1]; 99 char host[UTX_HOSTSIZE + 1]; 100 char type[2]; 101 struct timeval tv; 102 dev_t tdev; /* dev_t of terminal */ 103 time_t idle; /* idle time of terminal in seconds */ 104 struct kinfo_proc *kp; /* `most interesting' proc */ 105 char *args; /* arg list of interesting process */ 106 struct kinfo_proc *dkp; /* debug option proc list */ 107 pid_t pid; /* pid or ~0 if not known */ 108 } *ep, *ehead = NULL, **nextp = &ehead; 109 110 #define debugproc(p) *((struct kinfo_proc **)&(p)->kp_spare[0]) 111 112 static void pr_header(time_t *, int); 113 static struct stat *ttystat(char *, int); 114 static void process(struct entry *); 115 static void usage(int); 116 static int this_is_uptime(const char *s); 117 118 char *fmt_argv(char **, char *, int); /* ../../bin/ps/fmt.c */ 119 120 int 121 main(int argc, char **argv) 122 { 123 struct kinfo_proc *kp; 124 struct kinfo_proc *dkp; 125 struct hostent *hp; 126 in_addr_t l; 127 int ch, i, nentries, nusers, wcmd, longidle, dropgid; 128 char *memf, *nlistf, *p, *x; 129 struct utmpx *utx; 130 char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX]; 131 132 (void)setlocale(LC_ALL, ""); 133 use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0'); 134 use_comma = (*nl_langinfo(RADIXCHAR) != ','); 135 136 /* Are we w(1) or uptime(1)? */ 137 if (this_is_uptime(argv[0]) == 0) { 138 wcmd = 0; 139 p = ""; 140 } else { 141 wcmd = 1; 142 p = "dhiflM:N:nsuw"; 143 } 144 145 dropgid = 0; 146 memf = nlistf = _PATH_DEVNULL; 147 while ((ch = getopt(argc, argv, p)) != -1) 148 switch (ch) { 149 case 'd': 150 dflag = 1; 151 break; 152 case 'h': 153 header = 0; 154 break; 155 case 'i': 156 sortidle = 1; 157 break; 158 case 'M': 159 header = 0; 160 memf = optarg; 161 dropgid = 1; 162 break; 163 case 'N': 164 nlistf = optarg; 165 dropgid = 1; 166 break; 167 case 'n': 168 nflag = 1; 169 break; 170 case 'f': case 'l': case 's': case 'u': case 'w': 171 warnx("[-flsuw] no longer supported"); 172 /* FALLTHROUGH */ 173 case '?': 174 default: 175 usage(wcmd); 176 } 177 argc -= optind; 178 argv += optind; 179 180 if (!(_res.options & RES_INIT)) 181 res_init(); 182 _res.retrans = 2; /* resolver timeout to 2 seconds per try */ 183 _res.retry = 1; /* only try once.. */ 184 185 /* 186 * Discard setgid privileges if not the running kernel so that bad 187 * guys can't print interesting stuff from kernel memory. 188 */ 189 if (dropgid) 190 setgid(getgid()); 191 192 if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL) 193 errx(1, "%s", errbuf); 194 195 (void)time(&now); 196 setutxent(); 197 198 if (*argv) 199 sel_users = argv; 200 201 nusers = 0; 202 while ((utx = getutxent()) != NULL) { 203 if (utx->ut_type != USER_PROCESS) 204 continue; 205 ++nusers; 206 207 if (sel_users) { 208 int usermatch; 209 char **user; 210 211 usermatch = 0; 212 for (user = sel_users; !usermatch && *user; user++) 213 if (!strncmp(utx->ut_name, *user, UTX_USERSIZE)) 214 usermatch = 1; 215 if (!usermatch) 216 continue; 217 } 218 219 if ((ep = calloc(1, sizeof(struct entry))) == NULL) 220 err(1, NULL); 221 (void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name)); 222 (void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line)); 223 (void)memcpy(ep->host, utx->ut_host, sizeof(utx->ut_host)); 224 ep->name[sizeof(utx->ut_name)] = '\0'; 225 ep->line[sizeof(utx->ut_line)] = '\0'; 226 ep->host[sizeof(utx->ut_host)] = '\0'; 227 #if 1 228 /* XXX: Actually we don't support the utx->ut_ss stuff yet */ 229 if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss, 230 utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0, 231 NI_NUMERICHOST) != 0) { 232 (void)memcpy(ep->host, utx->ut_host, 233 sizeof(utx->ut_host)); 234 ep->host[sizeof(utx->ut_host)] = '\0'; 235 } 236 #endif 237 ep->type[0] = 'x'; 238 ep->tv = utx->ut_tv; 239 ep->pid = utx->ut_pid; 240 241 *nextp = ep; 242 nextp = &(ep->next); 243 if (wcmd != 0) 244 process(ep); 245 } 246 endutxent(); 247 248 if (header || wcmd == 0) { 249 pr_header(&now, nusers); 250 if (wcmd == 0) { 251 (void)kvm_close(kd); 252 exit(0); 253 } 254 255 #define HEADER_USER "USER" 256 #define HEADER_TTY "TTY" 257 #define HEADER_FROM "FROM" 258 #define HEADER_LOGIN_IDLE "LOGIN@ IDLE " 259 #define HEADER_WHAT "WHAT\n" 260 #define WUSED (maxname + maxline + maxhost + \ 261 sizeof(HEADER_LOGIN_IDLE) + 3) /* header width incl. spaces */ 262 (void)printf("%-*.*s %-*.*s %-*.*s %s", 263 maxname, maxname, HEADER_USER, 264 maxline, maxline, HEADER_TTY, 265 maxhost, maxhost, HEADER_FROM, 266 HEADER_LOGIN_IDLE HEADER_WHAT); 267 } 268 269 if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL) 270 err(1, "%s", kvm_geterr(kd)); 271 for (i = 0; i < nentries; i++, kp++) { 272 if (kp->kp_stat == SIDL || kp->kp_stat == SZOMB) 273 continue; 274 for (ep = ehead; ep != NULL; ep = ep->next) { 275 if (ep->tdev == kp->kp_tdev) { 276 /* 277 * proc is associated with this terminal 278 */ 279 if (ep->kp == NULL && kp->kp_pgid == kp->kp_tpgid) { 280 /* 281 * Proc is 'most interesting' 282 */ 283 if (proc_compare(ep->kp, kp)) 284 ep->kp = kp; 285 } 286 /* 287 * Proc debug option info; add to debug 288 * list using kinfo_proc kp_eproc.e_spare 289 * as next pointer; ptr to ptr avoids the 290 * ptr = long assumption. 291 */ 292 dkp = ep->dkp; 293 ep->dkp = kp; 294 debugproc(kp) = dkp; 295 } 296 if (ep->pid != 0 && ep->pid == kp->kp_pid) { 297 ep->kp = kp; 298 break; 299 } 300 } 301 } 302 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 && 303 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 && 304 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0) 305 ttywidth = 79; 306 else 307 ttywidth = ws.ws_col - 1; 308 argwidth = ttywidth - WUSED; 309 if (argwidth < 4) 310 argwidth = 8; 311 for (ep = ehead; ep != NULL; ep = ep->next) { 312 if (ep->kp == NULL) { 313 ep->args = "-"; 314 continue; 315 } 316 ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth), 317 ep->kp->kp_comm, MAXCOMLEN); 318 if (ep->args == NULL) 319 err(1, NULL); 320 } 321 /* sort by idle time */ 322 if (sortidle && ehead != NULL) { 323 struct entry *from, *save; 324 325 from = ehead; 326 ehead = NULL; 327 while (from != NULL) { 328 for (nextp = &ehead; 329 (*nextp) && from->idle >= (*nextp)->idle; 330 nextp = &(*nextp)->next) 331 continue; 332 save = from; 333 from = from->next; 334 save->next = *nextp; 335 *nextp = save; 336 } 337 } else if (ehead != NULL) { 338 struct entry *from = ehead, *save; 339 340 ehead = NULL; 341 while (from != NULL) { 342 for (nextp = &ehead; 343 (*nextp) && strcmp(from->line, (*nextp)->line) > 0; 344 nextp = &(*nextp)->next) 345 continue; 346 save = from; 347 from = from->next; 348 save->next = *nextp; 349 *nextp = save; 350 } 351 } 352 353 if (!nflag) { 354 if (gethostname(domain, sizeof(domain)) < 0 || 355 (p = strchr(domain, '.')) == NULL) 356 domain[0] = '\0'; 357 else { 358 domain[sizeof(domain) - 1] = '\0'; 359 memmove(domain, p, strlen(p) + 1); 360 } 361 } 362 363 for (ep = ehead; ep != NULL; ep = ep->next) { 364 char host_buf[UTX_HOSTSIZE + 1]; 365 366 host_buf[UTX_HOSTSIZE] = '\0'; 367 strncpy(host_buf, ep->host, maxhost); 368 p = *host_buf ? host_buf : "-"; 369 if ((x = strchr(p, ':')) != NULL) 370 *x++ = '\0'; 371 if (!nflag && isdigit(*p) && 372 (l = inet_addr(p)) != INADDR_NONE && 373 (hp = gethostbyaddr(&l, sizeof(l), AF_INET))) { 374 if (domain[0] != '\0') { 375 p = hp->h_name; 376 p += strlen(hp->h_name); 377 p -= strlen(domain); 378 if (p > hp->h_name && 379 strcasecmp(p, domain) == 0) 380 *p = '\0'; 381 } 382 p = hp->h_name; 383 } 384 if (nflag && *p && strcmp(p, "-") && 385 inet_addr(p) == INADDR_NONE) { 386 hp = gethostbyname(p); 387 388 if (hp != NULL) { 389 struct in_addr in; 390 391 memmove(&in, hp->h_addr, sizeof(in)); 392 p = inet_ntoa(in); 393 } 394 } 395 if (x) { 396 (void)snprintf(buf, sizeof(buf), "%s:%s", p, x); 397 p = buf; 398 } 399 if (dflag) { 400 for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) { 401 char *ptr; 402 403 ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth), 404 dkp->kp_comm, MAXCOMLEN); 405 if (ptr == NULL) 406 ptr = "-"; 407 (void)printf("\t\t%-9d %s\n", 408 dkp->kp_pid, ptr); 409 } 410 } 411 (void)printf("%-*.*s %-*.*s %-*.*s ", 412 maxname, maxname, ep->name, 413 maxline, maxline, 414 strncmp(ep->line, "tty", 3) && 415 strncmp(ep->line, "cua", 3) ? 416 ep->line : ep->line + 3, 417 maxhost, maxhost, *p ? p : "-"); 418 then = (time_t)ep->tv.tv_sec; 419 pr_attime(&then, &now); 420 longidle = pr_idle(ep->idle); 421 (void)printf("%.*s\n", argwidth - longidle, ep->args); 422 } 423 (void)kvm_close(kd); 424 exit(0); 425 } 426 427 static void 428 pr_header(time_t *nowp, int nusers) 429 { 430 struct timespec boot_ts; 431 double avenrun[3]; 432 time_t uptime; 433 int days, hrs, i, mins, secs; 434 char buf[256]; 435 436 /* 437 * Print time of day. (use "AM"/"PM" for all locales) 438 */ 439 (void)strftime_l(buf, sizeof(buf) - 1, 440 use_ampm ? "%l:%M%p" : "%k:%M", 441 localtime(nowp), NULL); 442 buf[sizeof(buf) - 1] = '\0'; 443 (void)printf("%s ", buf); 444 445 /* 446 * Print how long system has been up. 447 * 448 * Use clock_gettime() rather than trying to calculate 449 * a realtime delta that would be subject to time and date 450 * changes. 451 */ 452 if (clock_gettime(CLOCK_UPTIME, &boot_ts) == 0) { 453 uptime = boot_ts.tv_sec; 454 if (uptime > 60) 455 uptime += 30; 456 days = uptime / 86400; 457 uptime %= 86400; 458 hrs = uptime / 3600; 459 uptime %= 3600; 460 mins = uptime / 60; 461 secs = uptime % 60; 462 (void)printf(" up"); 463 if (days > 0) 464 (void)printf(" %d day%s,", days, days > 1 ? "s" : ""); 465 if (hrs > 0 && mins > 0) 466 (void)printf(" %2d:%02d,", hrs, mins); 467 else if (hrs > 0) 468 (void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : ""); 469 else if (mins > 0) 470 (void)printf(" %d min%s,", mins, mins > 1 ? "s" : ""); 471 else 472 (void)printf(" %d sec%s,", secs, secs > 1 ? "s" : ""); 473 } 474 475 /* Print number of users logged in on system */ 476 (void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s"); 477 478 /* 479 * Print 1, 5, and 15 minute load averages. 480 */ 481 if (getloadavg(avenrun, NELEM(avenrun)) == -1) 482 (void)printf(", no load average information available\n"); 483 else { 484 (void)printf(", load averages:"); 485 for (i = 0; i < (int)NELEM(avenrun); i++) { 486 if (use_comma && i > 0) 487 (void)printf(","); 488 (void)printf(" %.2f", avenrun[i]); 489 } 490 (void)printf("\n"); 491 } 492 } 493 494 static struct stat * 495 ttystat(char *line, int sz) 496 { 497 static struct stat sb; 498 char ttybuf[MAXPATHLEN]; 499 500 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line); 501 if (stat(ttybuf, &sb)) { 502 warn("%s", ttybuf); 503 return (NULL); 504 } 505 return (&sb); 506 } 507 508 static void 509 usage(int wcmd) 510 { 511 if (wcmd) 512 (void)fprintf(stderr, 513 "usage: w [-dhin] [-M core] [-N system] [user ...]\n"); 514 else 515 (void)fprintf(stderr, "usage: uptime\n"); 516 exit(1); 517 } 518 519 static int 520 this_is_uptime(const char *s) 521 { 522 const char *u; 523 524 if ((u = strrchr(s, '/')) != NULL) 525 ++u; 526 else 527 u = s; 528 if (strcmp(u, "uptime") == 0) 529 return (0); 530 return (-1); 531 } 532 533 static void 534 process(struct entry *ep) 535 { 536 struct stat *stp; 537 time_t touched; 538 int max; 539 540 if ((max = strlen(ep->name)) > maxname) 541 maxname = max; 542 if ((max = strlen(ep->line)) > maxline) 543 maxline = max; 544 if ((max = strlen(ep->host)) > maxhost) 545 maxhost = max; 546 547 ep->tdev = 0; 548 ep->idle = (time_t)-1; 549 550 if (!(stp = ttystat(ep->line, maxline))) 551 return; /* corrupted record */ 552 553 ep->tdev = stp->st_rdev; 554 #ifdef CPU_CONSDEV 555 /* 556 * If this is the console device, attempt to ascertain 557 * the true console device dev_t. 558 */ 559 if (ep->tdev == 0) { 560 int mib[2]; 561 size_t size; 562 563 mib[0] = CTL_MACHDEP; 564 mib[1] = CPU_CONSDEV; 565 size = sizeof(dev_t); 566 (void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0); 567 } 568 #endif 569 570 touched = stp->st_atime; 571 if (touched < ep->tv.tv_sec) { 572 /* tty untouched since before login */ 573 touched = ep->tv.tv_sec; 574 } 575 if ((ep->idle = now - touched) < 0) 576 ep->idle = 0; 577 } 578