1 /* $OpenBSD: w.c,v 1.34 2001/07/12 05:17:31 deraadt Exp $ */ 2 3 /*- 4 * Copyright (c) 1980, 1991, 1993, 1994 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 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. All advertising materials mentioning features or use of this software 16 * must display the following acknowledgement: 17 * This product includes software developed by the University of 18 * California, Berkeley and its contributors. 19 * 4. Neither the name of the University nor the names of its contributors 20 * may be used to endorse or promote products derived from this software 21 * without specific prior written permission. 22 * 23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 33 * SUCH DAMAGE. 34 */ 35 36 #ifndef lint 37 static char copyright[] = 38 "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\ 39 The Regents of the University of California. All rights reserved.\n"; 40 #endif /* not lint */ 41 42 #ifndef lint 43 #if 0 44 static char sccsid[] = "@(#)w.c 8.4 (Berkeley) 4/16/94"; 45 #else 46 static char *rcsid = "$OpenBSD: w.c,v 1.34 2001/07/12 05:17:31 deraadt Exp $"; 47 #endif 48 #endif /* not lint */ 49 50 /* 51 * w - print system status (who and what) 52 * 53 * This program is similar to the systat command on Tenex/Tops 10/20 54 * 55 */ 56 #include <sys/param.h> 57 #include <sys/time.h> 58 #include <sys/stat.h> 59 #include <sys/sysctl.h> 60 #include <sys/proc.h> 61 #include <sys/user.h> 62 #include <sys/ioctl.h> 63 #include <sys/socket.h> 64 #include <sys/tty.h> 65 66 #include <machine/cpu.h> 67 #include <netinet/in.h> 68 #include <arpa/inet.h> 69 70 #include <ctype.h> 71 #include <err.h> 72 #include <errno.h> 73 #include <fcntl.h> 74 #include <kvm.h> 75 #include <netdb.h> 76 #include <nlist.h> 77 #include <paths.h> 78 #include <stdio.h> 79 #include <stdlib.h> 80 #include <string.h> 81 #include <tzfile.h> 82 #include <unistd.h> 83 #include <limits.h> 84 #include <utmp.h> 85 #include <vis.h> 86 87 #include "extern.h" 88 89 struct timeval boottime; 90 struct utmp utmp; 91 struct winsize ws; 92 kvm_t *kd; 93 time_t now; /* the current time of day */ 94 time_t uptime; /* time of last reboot & elapsed time since */ 95 int ttywidth; /* width of tty */ 96 int argwidth; /* width of tty */ 97 int header = 1; /* true if -h flag: don't print heading */ 98 int nflag = 1; /* true if -n flag: don't convert addrs */ 99 int sortidle; /* sort bu idle time */ 100 char *sel_user; /* login of particular user selected */ 101 char domain[MAXHOSTNAMELEN]; 102 103 #define NAME_WIDTH 8 104 #define HOST_WIDTH 16 105 106 /* 107 * One of these per active utmp entry. 108 */ 109 struct entry { 110 struct entry *next; 111 struct utmp utmp; 112 dev_t tdev; /* dev_t of terminal */ 113 time_t idle; /* idle time of terminal in seconds */ 114 struct kinfo_proc *kp; /* `most interesting' proc */ 115 } *ep, *ehead = NULL, **nextp = &ehead; 116 117 static void pr_args __P((struct kinfo_proc *)); 118 static void pr_header __P((time_t *, int)); 119 static struct stat 120 *ttystat __P((char *)); 121 static void usage __P((int)); 122 123 int 124 main(argc, argv) 125 int argc; 126 char **argv; 127 { 128 extern char *__progname; 129 struct kinfo_proc *kp; 130 struct hostent *hp; 131 struct stat *stp; 132 FILE *ut; 133 struct in_addr addr; 134 int ch, i, nentries, nusers, wcmd; 135 char *memf, *nlistf, *p, *x; 136 char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX]; 137 138 /* Are we w(1) or uptime(1)? */ 139 p = __progname; 140 if (*p == '-') 141 p++; 142 if (p[0] == 'w' && p[1] == '\0') { 143 wcmd = 1; 144 p = "hiflM:N:asuw"; 145 } else if (!strcmp(p, "uptime")) { 146 wcmd = 0; 147 p = "M:N:"; 148 } else 149 errx(1, 150 "this program should be invoked only as \"w\" or \"uptime\""); 151 152 memf = nlistf = NULL; 153 while ((ch = getopt(argc, argv, p)) != -1) 154 switch (ch) { 155 case 'h': 156 header = 0; 157 break; 158 case 'i': 159 sortidle = 1; 160 break; 161 case 'M': 162 header = 0; 163 memf = optarg; 164 break; 165 case 'N': 166 nlistf = optarg; 167 break; 168 case 'a': 169 nflag = 0; 170 break; 171 case 'f': case 'l': case 's': case 'u': case 'w': 172 warnx("[-flsuw] no longer supported"); 173 /* FALLTHROUGH */ 174 case '?': 175 default: 176 usage(wcmd); 177 } 178 argc -= optind; 179 argv += optind; 180 181 /* 182 * Discard setgid privileges if not the running kernel so that bad 183 * guys can't print interesting stuff from kernel memory. 184 */ 185 if (nlistf != NULL || memf != NULL) { 186 setegid(getgid()); 187 setgid(getgid()); 188 } 189 190 if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL) 191 errx(1, "%s", errbuf); 192 193 setegid(getgid()); 194 setgid(getgid()); 195 196 (void)time(&now); 197 if ((ut = fopen(_PATH_UTMP, "r")) == NULL) 198 err(1, "%s", _PATH_UTMP); 199 200 if (*argv) 201 sel_user = *argv; 202 203 for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) { 204 if (utmp.ut_name[0] == '\0') 205 continue; 206 ++nusers; 207 if (wcmd == 0 || (sel_user && 208 strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0)) 209 continue; 210 if ((ep = calloc(1, sizeof(*ep))) == NULL) 211 err(1, NULL); 212 *nextp = ep; 213 nextp = &(ep->next); 214 memcpy(&(ep->utmp), &utmp, sizeof(utmp)); 215 if (!(stp = ttystat(ep->utmp.ut_line))) 216 continue; 217 ep->tdev = stp->st_rdev; 218 #ifdef CPU_CONSDEV 219 /* 220 * If this is the console device, attempt to ascertain 221 * the true console device dev_t. 222 */ 223 if (ep->tdev == 0) { 224 int mib[2]; 225 size_t size; 226 227 mib[0] = CTL_MACHDEP; 228 mib[1] = CPU_CONSDEV; 229 size = sizeof(dev_t); 230 (void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0); 231 } 232 #endif 233 if ((ep->idle = now - stp->st_atime) < 0) 234 ep->idle = 0; 235 } 236 (void)fclose(ut); 237 238 if (header || wcmd == 0) { 239 pr_header(&now, nusers); 240 if (wcmd == 0) 241 exit (0); 242 } 243 244 #define HEADER "USER TTY FROM LOGIN@ IDLE WHAT" 245 #define WUSED (sizeof(HEADER) - sizeof("WHAT")) 246 (void)puts(HEADER); 247 248 if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL) 249 errx(1, "%s", kvm_geterr(kd)); 250 for (i = 0; i < nentries; i++, kp++) { 251 struct proc *p = &kp->kp_proc; 252 struct eproc *e; 253 254 if (p->p_stat == SIDL || p->p_stat == SZOMB) 255 continue; 256 e = &kp->kp_eproc; 257 for (ep = ehead; ep != NULL; ep = ep->next) { 258 /* ftp is a special case. */ 259 if (strncmp(ep->utmp.ut_line, "ftp", 3) == 0) { 260 char pidstr[UT_LINESIZE-2]; 261 pid_t fp; 262 263 (void)strncpy(pidstr, &ep->utmp.ut_line[3], 264 sizeof(pidstr) - 1); 265 pidstr[sizeof(pidstr) - 1] = '\0'; 266 fp = (pid_t)strtol(pidstr, NULL, 10); 267 if (p->p_pid == fp) { 268 ep->kp = kp; 269 break; 270 } 271 } else if (ep->tdev == e->e_tdev && 272 e->e_pgid == e->e_tpgid) { 273 /* 274 * Proc is in foreground of this terminal 275 */ 276 if (proc_compare(&ep->kp->kp_proc, p)) 277 ep->kp = kp; 278 break; 279 } 280 } 281 } 282 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 && 283 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 && 284 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0) 285 ttywidth = 79; 286 else 287 ttywidth = ws.ws_col - 1; 288 argwidth = ttywidth - WUSED; 289 if (argwidth < 4) 290 argwidth = 8; 291 /* sort by idle time */ 292 if (sortidle && ehead != NULL) { 293 struct entry *from = ehead, *save; 294 295 ehead = NULL; 296 while (from != NULL) { 297 for (nextp = &ehead; 298 (*nextp) && from->idle >= (*nextp)->idle; 299 nextp = &(*nextp)->next) 300 continue; 301 save = from; 302 from = from->next; 303 save->next = *nextp; 304 *nextp = save; 305 } 306 } 307 308 if (!nflag) { 309 if (gethostname(domain, sizeof(domain) - 1) < 0 || 310 (p = strchr(domain, '.')) == 0) 311 domain[0] = '\0'; 312 else { 313 domain[sizeof(domain) - 1] = '\0'; 314 memmove(domain, p, strlen(p) + 1); 315 } 316 } 317 318 for (ep = ehead; ep != NULL; ep = ep->next) { 319 p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-"; 320 for (x = NULL, i = 0; p[i] != '\0' && i < UT_HOSTSIZE; i++) 321 if (p[i] == ':') { 322 x = &p[i]; 323 *x++ = '\0'; 324 break; 325 } 326 if (!nflag && inet_aton(p, &addr) && 327 (hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET))) { 328 if (domain[0] != '\0') { 329 p = hp->h_name; 330 p += strlen(hp->h_name); 331 p -= strlen(domain); 332 if (p > hp->h_name && 333 strcasecmp(p, domain) == 0) 334 *p = '\0'; 335 } 336 p = hp->h_name; 337 } 338 if (x) { 339 (void)snprintf(buf, sizeof(buf), "%s:%.*s", p, 340 (int)(ep->utmp.ut_host + UT_HOSTSIZE - x), x); 341 p = buf; 342 } 343 (void)printf("%-*.*s %-2.2s %-*.*s ", 344 NAME_WIDTH, UT_NAMESIZE, ep->utmp.ut_name, 345 strncmp(ep->utmp.ut_line, "tty", 3) ? 346 ep->utmp.ut_line : ep->utmp.ut_line + 3, 347 HOST_WIDTH, HOST_WIDTH, *p ? p : "-"); 348 pr_attime(&ep->utmp.ut_time, &now); 349 pr_idle(ep->idle); 350 pr_args(ep->kp); 351 printf("\n"); 352 } 353 exit(0); 354 } 355 356 static void 357 pr_args(kp) 358 struct kinfo_proc *kp; 359 { 360 char **argv, *str; 361 int left; 362 363 if (kp == NULL) 364 goto nothing; 365 left = argwidth; 366 argv = kvm_getargv(kd, kp, argwidth+60); /* +60 for ftpd snip */ 367 if (argv == NULL) 368 goto nothing; 369 370 if (*argv == NULL || **argv == '\0') { 371 /* Process has zeroed argv[0], display executable name. */ 372 fmt_putc('(', &left); 373 fmt_puts(kp->kp_proc.p_comm, &left); 374 fmt_putc(')', &left); 375 } 376 while (*argv) { 377 /* ftp is a special case... */ 378 if (strncmp(*argv, "ftpd:", 5) == 0) { 379 str = strrchr(*argv, ':'); 380 if (str != (char *)NULL) { 381 if ((str[0] == ':') && isspace(str[1])) 382 str += 2; 383 fmt_puts(str, &left); 384 } else 385 fmt_puts(*argv, &left); 386 } else 387 fmt_puts(*argv, &left); 388 argv++; 389 fmt_putc(' ', &left); 390 } 391 return; 392 nothing: 393 putchar('-'); 394 } 395 396 static void 397 pr_header(nowp, nusers) 398 time_t *nowp; 399 int nusers; 400 { 401 double avenrun[3]; 402 time_t uptime; 403 int days, hrs, i, mins; 404 int mib[2]; 405 size_t size; 406 char buf[256]; 407 408 /* 409 * Print time of day. 410 * 411 * SCCS forces the string manipulation below, as it replaces 412 * %, M, and % in a character string with the file name. 413 */ 414 (void)strftime(buf, sizeof(buf) - 1, 415 __CONCAT("%l:%","M%p"), localtime(nowp)); 416 buf[sizeof(buf) - 1] = '\0'; 417 (void)printf("%s ", buf); 418 419 /* 420 * Print how long system has been up. 421 * (Found by looking getting "boottime" from the kernel) 422 */ 423 mib[0] = CTL_KERN; 424 mib[1] = KERN_BOOTTIME; 425 size = sizeof(boottime); 426 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1) { 427 uptime = now - boottime.tv_sec; 428 if (uptime > 59) { 429 uptime += 30; 430 days = uptime / SECSPERDAY; 431 uptime %= SECSPERDAY; 432 hrs = uptime / SECSPERHOUR; 433 uptime %= SECSPERHOUR; 434 mins = uptime / SECSPERMIN; 435 (void)printf(" up"); 436 if (days > 0) 437 (void)printf(" %d day%s,", days, 438 days > 1 ? "s" : ""); 439 if (hrs > 0 && mins > 0) 440 (void)printf(" %2d:%02d,", hrs, mins); 441 else { 442 if (hrs > 0) 443 (void)printf(" %d hr%s,", 444 hrs, hrs > 1 ? "s" : ""); 445 if (mins > 0 || (days == 0 && hrs == 0)) 446 (void)printf(" %d min%s,", 447 mins, mins != 1 ? "s" : ""); 448 } 449 } else 450 printf(" %d secs,", uptime); 451 } 452 453 /* Print number of users logged in to system */ 454 (void)printf(" %d user%s", nusers, nusers != 1 ? "s" : ""); 455 456 /* 457 * Print 1, 5, and 15 minute load averages. 458 */ 459 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1) 460 (void)printf(", no load average information available\n"); 461 else { 462 (void)printf(", load averages:"); 463 for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) { 464 if (i > 0) 465 (void)printf(","); 466 (void)printf(" %.2f", avenrun[i]); 467 } 468 (void)printf("\n"); 469 } 470 } 471 472 static struct stat * 473 ttystat(line) 474 char *line; 475 { 476 static struct stat sb; 477 char ttybuf[sizeof(_PATH_DEV) + UT_LINESIZE]; 478 479 /* Note, line may not be NUL-terminated */ 480 (void)strlcpy(ttybuf, _PATH_DEV, sizeof(ttybuf)); 481 (void)strncat(ttybuf, line, sizeof(ttybuf) - 1 - strlen(ttybuf)); 482 if (stat(ttybuf, &sb)) 483 return (NULL); 484 return (&sb); 485 } 486 487 static void 488 usage(wcmd) 489 int wcmd; 490 { 491 if (wcmd) 492 (void)fprintf(stderr, 493 "usage: w [-hia] [-M core] [-N system] [user]\n"); 494 else 495 (void)fprintf(stderr, 496 "usage: uptime [-M core] [-N system]\n"); 497 exit (1); 498 } 499