w.c revision 73365
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. All advertising materials mentioning features or use of this software 14 * must display the following acknowledgement: 15 * This product includes software developed by the University of 16 * California, Berkeley and its contributors. 17 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 */ 33 34#ifndef lint 35static 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 /* not lint */ 39 40#ifndef lint 41#if 0 42static char sccsid[] = "@(#)w.c 8.4 (Berkeley) 4/16/94"; 43#endif 44static const char rcsid[] = 45 "$FreeBSD: head/usr.bin/w/w.c 73365 2001-03-02 23:11:38Z ache $"; 46#endif /* not lint */ 47 48/* 49 * w - print system status (who and what) 50 * 51 * This program is similar to the systat command on Tenex/Tops 10/20 52 * 53 */ 54#include <sys/param.h> 55#include <sys/time.h> 56#include <sys/stat.h> 57#include <sys/sysctl.h> 58#include <sys/proc.h> 59#include <sys/user.h> 60#include <sys/ioctl.h> 61#include <sys/socket.h> 62#include <sys/tty.h> 63 64#include <machine/cpu.h> 65#include <netinet/in.h> 66#include <arpa/inet.h> 67 68#include <ctype.h> 69#include <err.h> 70#include <errno.h> 71#include <fcntl.h> 72#include <kvm.h> 73#include <langinfo.h> 74#include <locale.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 <unistd.h> 82#include <utmp.h> 83#include <vis.h> 84 85#include <arpa/nameser.h> 86#include <resolv.h> 87 88#include "extern.h" 89 90struct timeval boottime; 91struct utmp utmp; 92struct winsize ws; 93kvm_t *kd; 94time_t now; /* the current time of day */ 95time_t uptime; /* time of last reboot & elapsed time since */ 96int ttywidth; /* width of tty */ 97int argwidth; /* width of tty */ 98int header = 1; /* true if -h flag: don't print heading */ 99int nflag; /* true if -n flag: don't convert addrs */ 100int dflag; /* true if -d flag: output debug info */ 101int sortidle; /* sort by idle time */ 102int use_ampm; /* use AM/PM time */ 103char **sel_users; /* login array of particular users selected */ 104char domain[MAXHOSTNAMELEN]; 105 106/* 107 * One of these per active utmp entry. 108 */ 109struct 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 char *args; /* arg list of interesting process */ 116 struct kinfo_proc *dkp; /* debug option proc list */ 117} *ep, *ehead = NULL, **nextp = &ehead; 118 119#define debugproc(p) *((struct kinfo_proc **)&(p)->ki_spare[0]) 120 121static void pr_header __P((time_t *, int)); 122static struct stat *ttystat __P((char *, int)); 123static void usage __P((int)); 124static int this_is_uptime __P((const char *s)); 125 126char *fmt_argv __P((char **, char *, int)); /* ../../bin/ps/fmt.c */ 127 128int 129main(argc, argv) 130 int argc; 131 char **argv; 132{ 133 struct kinfo_proc *kp; 134 struct kinfo_proc *dkp; 135 struct hostent *hp; 136 struct stat *stp; 137 FILE *ut; 138 u_long l; 139 time_t touched; 140 int ch, i, nentries, nusers, wcmd, longidle, dropgid; 141 char *memf, *nlistf, *p, *x; 142 char buf[MAXHOSTNAMELEN], errbuf[256]; 143 144 (void)setlocale(LC_ALL, ""); 145 use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0'); 146 147 /* Are we w(1) or uptime(1)? */ 148 if (this_is_uptime(argv[0]) == 0) { 149 wcmd = 0; 150 p = ""; 151 } else { 152 wcmd = 1; 153 p = "dhiflM:N:nsuw"; 154 } 155 156 dropgid = 0; 157 memf = nlistf = _PATH_DEVNULL; 158 while ((ch = getopt(argc, argv, p)) != -1) 159 switch (ch) { 160 case 'd': 161 dflag = 1; 162 break; 163 case 'h': 164 header = 0; 165 break; 166 case 'i': 167 sortidle = 1; 168 break; 169 case 'M': 170 header = 0; 171 memf = optarg; 172 dropgid = 1; 173 break; 174 case 'N': 175 nlistf = optarg; 176 dropgid = 1; 177 break; 178 case 'n': 179 nflag = 1; 180 break; 181 case 'f': case 'l': case 's': case 'u': case 'w': 182 warnx("[-flsuw] no longer supported"); 183 /* FALLTHROUGH */ 184 case '?': 185 default: 186 usage(wcmd); 187 } 188 argc -= optind; 189 argv += optind; 190 191 if (!(_res.options & RES_INIT)) 192 res_init(); 193 _res.retrans = 2; /* resolver timeout to 2 seconds per try */ 194 _res.retry = 1; /* only try once.. */ 195 196 /* 197 * Discard setgid privileges if not the running kernel so that bad 198 * guys can't print interesting stuff from kernel memory. 199 */ 200 if (dropgid) 201 setgid(getgid()); 202 203 if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL) 204 errx(1, "%s", errbuf); 205 206 (void)time(&now); 207 if ((ut = fopen(_PATH_UTMP, "r")) == NULL) 208 err(1, "%s", _PATH_UTMP); 209 210 if (*argv) 211 sel_users = argv; 212 213 for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) { 214 if (utmp.ut_name[0] == '\0') 215 continue; 216 if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE))) 217 continue; /* corrupted record */ 218 ++nusers; 219 if (wcmd == 0) 220 continue; 221 if (sel_users) { 222 int usermatch; 223 char **user; 224 225 usermatch = 0; 226 for (user = sel_users; !usermatch && *user; user++) 227 if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE)) 228 usermatch = 1; 229 if (!usermatch) 230 continue; 231 } 232 if ((ep = calloc(1, sizeof(struct entry))) == NULL) 233 errx(1, "calloc"); 234 *nextp = ep; 235 nextp = &ep->next; 236 memmove(&ep->utmp, &utmp, sizeof(struct utmp)); 237 ep->tdev = stp->st_rdev; 238#ifdef CPU_CONSDEV 239 /* 240 * If this is the console device, attempt to ascertain 241 * the true console device dev_t. 242 */ 243 if (ep->tdev == 0) { 244 int mib[2]; 245 size_t size; 246 247 mib[0] = CTL_MACHDEP; 248 mib[1] = CPU_CONSDEV; 249 size = sizeof(dev_t); 250 (void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0); 251 } 252#endif 253 touched = stp->st_atime; 254 if (touched < ep->utmp.ut_time) { 255 /* tty untouched since before login */ 256 touched = ep->utmp.ut_time; 257 } 258 if ((ep->idle = now - touched) < 0) 259 ep->idle = 0; 260 } 261 (void)fclose(ut); 262 263 if (header || wcmd == 0) { 264 pr_header(&now, nusers); 265 if (wcmd == 0) 266 exit(0); 267 268#define HEADER_USER "USER" 269#define HEADER_TTY "TTY" 270#define HEADER_FROM "FROM" 271#define HEADER_LOGIN_IDLE "LOGIN@ IDLE " 272#define HEADER_WHAT "WHAT\n" 273#define WUSED (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \ 274 sizeof(HEADER_LOGIN_IDLE) + 3) /* header width incl. spaces */ 275 (void)printf("%-*.*s %-*.*s %-*.*s %s", 276 UT_NAMESIZE, UT_NAMESIZE, HEADER_USER, 277 UT_LINESIZE, UT_LINESIZE, HEADER_TTY, 278 UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM, 279 HEADER_LOGIN_IDLE HEADER_WHAT); 280 } 281 282 if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL) 283 err(1, "%s", kvm_geterr(kd)); 284 for (i = 0; i < nentries; i++, kp++) { 285 if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB) 286 continue; 287 for (ep = ehead; ep != NULL; ep = ep->next) { 288 if (ep->tdev == kp->ki_tdev) { 289 /* 290 * proc is associated with this terminal 291 */ 292 if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) { 293 /* 294 * Proc is 'most interesting' 295 */ 296 if (proc_compare(ep->kp, kp)) 297 ep->kp = kp; 298 } 299 /* 300 * Proc debug option info; add to debug 301 * list using kinfo_proc ki_spare[0] 302 * as next pointer; ptr to ptr avoids the 303 * ptr = long assumption. 304 */ 305 dkp = ep->dkp; 306 ep->dkp = kp; 307 debugproc(kp) = dkp; 308 } 309 } 310 } 311 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 && 312 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 && 313 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0) 314 ttywidth = 79; 315 else 316 ttywidth = ws.ws_col - 1; 317 argwidth = ttywidth - WUSED; 318 if (argwidth < 4) 319 argwidth = 8; 320 for (ep = ehead; ep != NULL; ep = ep->next) { 321 if (ep->kp == NULL) { 322 ep->args = "-"; 323 continue; 324 } 325 ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth), 326 ep->kp->ki_comm, MAXCOMLEN); 327 if (ep->args == NULL) 328 err(1, NULL); 329 } 330 /* sort by idle time */ 331 if (sortidle && ehead != NULL) { 332 struct entry *from, *save; 333 334 from = ehead; 335 ehead = NULL; 336 while (from != NULL) { 337 for (nextp = &ehead; 338 (*nextp) && from->idle >= (*nextp)->idle; 339 nextp = &(*nextp)->next) 340 continue; 341 save = from; 342 from = from->next; 343 save->next = *nextp; 344 *nextp = save; 345 } 346 } 347 348 if (!nflag) { 349 if (gethostname(domain, sizeof(domain) - 1) < 0 || 350 (p = strchr(domain, '.')) == NULL) 351 domain[0] = '\0'; 352 else { 353 domain[sizeof(domain) - 1] = '\0'; 354 memmove(domain, p, strlen(p) + 1); 355 } 356 } 357 358 for (ep = ehead; ep != NULL; ep = ep->next) { 359 char host_buf[UT_HOSTSIZE + 1]; 360 361 host_buf[UT_HOSTSIZE] = '\0'; 362 strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE); 363 p = *host_buf ? host_buf : "-"; 364 if ((x = strchr(p, ':')) != NULL) 365 *x++ = '\0'; 366 if (!nflag && isdigit(*p) && (l = inet_addr(p)) != -1 && 367 (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) { 368 if (domain[0] != '\0') { 369 p = hp->h_name; 370 p += strlen(hp->h_name); 371 p -= strlen(domain); 372 if (p > hp->h_name && 373 strcasecmp(p, domain) == 0) 374 *p = '\0'; 375 } 376 p = hp->h_name; 377 } 378 if (nflag && *p && strcmp(p, "-") && 379 inet_addr(p) == INADDR_NONE) { 380 hp = gethostbyname(p); 381 382 if (hp != NULL) { 383 struct in_addr in; 384 385 memmove(&in, hp->h_addr, sizeof(in)); 386 p = inet_ntoa(in); 387 } 388 } 389 if (x) { 390 (void)snprintf(buf, sizeof(buf), "%s:%s", p, x); 391 p = buf; 392 } 393 if (dflag) { 394 for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) { 395 char *ptr; 396 397 ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth), 398 dkp->ki_comm, MAXCOMLEN); 399 if (ptr == NULL) 400 ptr = "-"; 401 (void)printf("\t\t%-9d %s\n", 402 dkp->ki_pid, ptr); 403 } 404 } 405 (void)printf("%-*.*s %-*.*s %-*.*s ", 406 UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name, 407 UT_LINESIZE, UT_LINESIZE, 408 strncmp(ep->utmp.ut_line, "tty", 3) && 409 strncmp(ep->utmp.ut_line, "cua", 3) ? 410 ep->utmp.ut_line : ep->utmp.ut_line + 3, 411 UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-"); 412 pr_attime(&ep->utmp.ut_time, &now); 413 longidle = pr_idle(ep->idle); 414 (void)printf("%.*s\n", argwidth - longidle, ep->args); 415 } 416 exit(0); 417} 418 419static void 420pr_header(nowp, nusers) 421 time_t *nowp; 422 int nusers; 423{ 424 double avenrun[3]; 425 time_t uptime; 426 int days, hrs, i, mins, secs; 427 int mib[2]; 428 size_t size; 429 char buf[256]; 430 431 /* 432 * Print time of day. 433 */ 434 (void)strftime(buf, sizeof(buf) - 1, 435 use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)); 436 buf[sizeof(buf) - 1] = '\0'; 437 (void)printf("%s ", buf); 438 439 /* 440 * Print how long system has been up. 441 * (Found by looking getting "boottime" from the kernel) 442 */ 443 mib[0] = CTL_KERN; 444 mib[1] = KERN_BOOTTIME; 445 size = sizeof(boottime); 446 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && 447 boottime.tv_sec != 0) { 448 uptime = now - boottime.tv_sec; 449 uptime += 30; 450 days = uptime / 86400; 451 uptime %= 86400; 452 hrs = uptime / 3600; 453 uptime %= 3600; 454 mins = uptime / 60; 455 secs = uptime % 60; 456 (void)printf(" up"); 457 if (days > 0) 458 (void)printf(" %d day%s,", days, days > 1 ? "s" : ""); 459 if (hrs > 0 && mins > 0) 460 (void)printf(" %2d:%02d,", hrs, mins); 461 else if (hrs > 0) 462 (void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : ""); 463 else if (mins > 0) 464 (void)printf(" %d min%s,", mins, mins > 1 ? "s" : ""); 465 else 466 (void)printf(" %d sec%s,", secs, secs > 1 ? "s" : ""); 467 } 468 469 /* Print number of users logged in to system */ 470 (void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s"); 471 472 /* 473 * Print 1, 5, and 15 minute load averages. 474 */ 475 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1) 476 (void)printf(", no load average information available\n"); 477 else { 478 (void)printf(", load averages:"); 479 for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) 480 (void)printf("%s %.2f", i > 0 ? "," : "", avenrun[i]); 481 (void)printf("\n"); 482 } 483} 484 485static struct stat * 486ttystat(line, sz) 487 char *line; 488 int sz; 489{ 490 static struct stat sb; 491 char ttybuf[MAXPATHLEN]; 492 493 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line); 494 if (stat(ttybuf, &sb)) { 495 warn("%s", ttybuf); 496 return (NULL); 497 } 498 return (&sb); 499} 500 501static void 502usage(wcmd) 503 int wcmd; 504{ 505 if (wcmd) 506 (void)fprintf(stderr, 507 "usage: w [-dhin] [-M core] [-N system] [user ...]\n"); 508 else 509 (void)fprintf(stderr, "usage: uptime\n"); 510 exit(1); 511} 512 513static int 514this_is_uptime(s) 515 const char *s; 516{ 517 const char *u; 518 519 if ((u = strrchr(s, '/')) != NULL) 520 ++u; 521 else 522 u = s; 523 if (strcmp(u, "uptime") == 0) 524 return (0); 525 return (-1); 526} 527