w.c revision 253749
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: head/usr.bin/w/w.c 253749 2013-07-28 18:35:43Z avg $"); 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 39 40#ifndef lint 41static 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 <netinet/in.h> 61#include <arpa/inet.h> 62#include <arpa/nameser.h> 63 64#include <ctype.h> 65#include <err.h> 66#include <errno.h> 67#include <fcntl.h> 68#include <kvm.h> 69#include <langinfo.h> 70#include <libutil.h> 71#include <limits.h> 72#include <locale.h> 73#include <netdb.h> 74#include <nlist.h> 75#include <paths.h> 76#include <resolv.h> 77#include <stdio.h> 78#include <stdlib.h> 79#include <string.h> 80#include <timeconv.h> 81#include <unistd.h> 82#include <utmpx.h> 83#include <vis.h> 84 85#include "extern.h" 86 87static struct utmpx *utmp; 88static struct winsize ws; 89static kvm_t *kd; 90static time_t now; /* the current time of day */ 91static int ttywidth; /* width of tty */ 92static int argwidth; /* width of tty */ 93static int header = 1; /* true if -h flag: don't print heading */ 94static int nflag; /* true if -n flag: don't convert addrs */ 95static int dflag; /* true if -d flag: output debug info */ 96static int sortidle; /* sort by idle time */ 97int use_ampm; /* use AM/PM time */ 98static int use_comma; /* use comma as floats separator */ 99static char **sel_users; /* login array of particular users selected */ 100 101/* 102 * One of these per active utmp entry. 103 */ 104static struct entry { 105 struct entry *next; 106 struct utmpx utmp; 107 dev_t tdev; /* dev_t of terminal */ 108 time_t idle; /* idle time of terminal in seconds */ 109 struct kinfo_proc *kp; /* `most interesting' proc */ 110 char *args; /* arg list of interesting process */ 111 struct kinfo_proc *dkp; /* debug option proc list */ 112} *ep, *ehead = NULL, **nextp = &ehead; 113 114#define debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata) 115 116#define W_DISPUSERSIZE 10 117#define W_DISPLINESIZE 8 118#define W_DISPHOSTSIZE 24 119 120static void pr_header(time_t *, int); 121static struct stat *ttystat(char *); 122static void usage(int); 123static int this_is_uptime(const char *s); 124 125char *fmt_argv(char **, char *, char *, size_t); /* ../../bin/ps/fmt.c */ 126 127int 128main(int argc, char *argv[]) 129{ 130 struct kinfo_proc *kp; 131 struct kinfo_proc *dkp; 132 struct stat *stp; 133 time_t touched; 134 int ch, i, nentries, nusers, wcmd, longidle, longattime, dropgid; 135 const char *memf, *nlistf, *p; 136 char *x_suffix; 137 char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX]; 138 char fn[MAXHOSTNAMELEN]; 139 char *dot; 140 141 (void)setlocale(LC_ALL, ""); 142 use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0'); 143 use_comma = (*nl_langinfo(RADIXCHAR) != ','); 144 145 /* Are we w(1) or uptime(1)? */ 146 if (this_is_uptime(argv[0]) == 0) { 147 wcmd = 0; 148 p = ""; 149 } else { 150 wcmd = 1; 151 p = "dhiflM:N:nsuw"; 152 } 153 154 dropgid = 0; 155 memf = _PATH_DEVNULL; 156 nlistf = NULL; 157 while ((ch = getopt(argc, argv, p)) != -1) 158 switch (ch) { 159 case 'd': 160 dflag = 1; 161 break; 162 case 'h': 163 header = 0; 164 break; 165 case 'i': 166 sortidle = 1; 167 break; 168 case 'M': 169 header = 0; 170 memf = optarg; 171 dropgid = 1; 172 break; 173 case 'N': 174 nlistf = optarg; 175 dropgid = 1; 176 break; 177 case 'n': 178 nflag = 1; 179 break; 180 case 'f': case 'l': case 's': case 'u': case 'w': 181 warnx("[-flsuw] no longer supported"); 182 /* FALLTHROUGH */ 183 case '?': 184 default: 185 usage(wcmd); 186 } 187 argc -= optind; 188 argv += optind; 189 190 if (!(_res.options & RES_INIT)) 191 res_init(); 192 _res.retrans = 2; /* resolver timeout to 2 seconds per try */ 193 _res.retry = 1; /* only try once.. */ 194 195 /* 196 * Discard setgid privileges if not the running kernel so that bad 197 * guys can't print interesting stuff from kernel memory. 198 */ 199 if (dropgid) 200 setgid(getgid()); 201 202 if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL) 203 errx(1, "%s", errbuf); 204 205 (void)time(&now); 206 207 if (*argv) 208 sel_users = argv; 209 210 setutxent(); 211 for (nusers = 0; (utmp = getutxent()) != NULL;) { 212 if (utmp->ut_type != USER_PROCESS) 213 continue; 214 if (!(stp = ttystat(utmp->ut_line))) 215 continue; /* corrupted record */ 216 ++nusers; 217 if (wcmd == 0) 218 continue; 219 if (sel_users) { 220 int usermatch; 221 char **user; 222 223 usermatch = 0; 224 for (user = sel_users; !usermatch && *user; user++) 225 if (!strcmp(utmp->ut_user, *user)) 226 usermatch = 1; 227 if (!usermatch) 228 continue; 229 } 230 if ((ep = calloc(1, sizeof(struct entry))) == NULL) 231 errx(1, "calloc"); 232 *nextp = ep; 233 nextp = &ep->next; 234 memmove(&ep->utmp, utmp, sizeof *utmp); 235 ep->tdev = stp->st_rdev; 236 /* 237 * If this is the console device, attempt to ascertain 238 * the true console device dev_t. 239 */ 240 if (ep->tdev == 0) { 241 size_t size; 242 243 size = sizeof(dev_t); 244 (void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0); 245 } 246 touched = stp->st_atime; 247 if (touched < ep->utmp.ut_tv.tv_sec) { 248 /* tty untouched since before login */ 249 touched = ep->utmp.ut_tv.tv_sec; 250 } 251 if ((ep->idle = now - touched) < 0) 252 ep->idle = 0; 253 } 254 endutxent(); 255 256 if (header || wcmd == 0) { 257 pr_header(&now, nusers); 258 if (wcmd == 0) { 259 (void)kvm_close(kd); 260 exit(0); 261 } 262 263#define HEADER_USER "USER" 264#define HEADER_TTY "TTY" 265#define HEADER_FROM "FROM" 266#define HEADER_LOGIN_IDLE "LOGIN@ IDLE " 267#define HEADER_WHAT "WHAT\n" 268#define WUSED (W_DISPUSERSIZE + W_DISPLINESIZE + W_DISPHOSTSIZE + \ 269 sizeof(HEADER_LOGIN_IDLE) + 3) /* header width incl. spaces */ 270 (void)printf("%-*.*s %-*.*s %-*.*s %s", 271 W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER, 272 W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY, 273 W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM, 274 HEADER_LOGIN_IDLE HEADER_WHAT); 275 } 276 277 if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL) 278 err(1, "%s", kvm_geterr(kd)); 279 for (i = 0; i < nentries; i++, kp++) { 280 if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB || 281 kp->ki_tdev == NODEV) 282 continue; 283 for (ep = ehead; ep != NULL; ep = ep->next) { 284 if (ep->tdev == kp->ki_tdev) { 285 /* 286 * proc is associated with this terminal 287 */ 288 if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) { 289 /* 290 * Proc is 'most interesting' 291 */ 292 if (proc_compare(ep->kp, kp)) 293 ep->kp = kp; 294 } 295 /* 296 * Proc debug option info; add to debug 297 * list using kinfo_proc ki_spare[0] 298 * as next pointer; ptr to ptr avoids the 299 * ptr = long assumption. 300 */ 301 dkp = ep->dkp; 302 ep->dkp = kp; 303 debugproc(kp) = dkp; 304 } 305 } 306 } 307 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 && 308 ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 && 309 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0) 310 ttywidth = 79; 311 else 312 ttywidth = ws.ws_col - 1; 313 argwidth = ttywidth - WUSED; 314 if (argwidth < 4) 315 argwidth = 8; 316 for (ep = ehead; ep != NULL; ep = ep->next) { 317 if (ep->kp == NULL) { 318 ep->args = strdup("-"); 319 continue; 320 } 321 ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth), 322 ep->kp->ki_comm, NULL, MAXCOMLEN); 323 if (ep->args == NULL) 324 err(1, NULL); 325 } 326 /* sort by idle time */ 327 if (sortidle && ehead != NULL) { 328 struct entry *from, *save; 329 330 from = ehead; 331 ehead = NULL; 332 while (from != NULL) { 333 for (nextp = &ehead; 334 (*nextp) && from->idle >= (*nextp)->idle; 335 nextp = &(*nextp)->next) 336 continue; 337 save = from; 338 from = from->next; 339 save->next = *nextp; 340 *nextp = save; 341 } 342 } 343 344 for (ep = ehead; ep != NULL; ep = ep->next) { 345 struct addrinfo hints, *res; 346 struct sockaddr_storage ss; 347 struct sockaddr *sa = (struct sockaddr *)&ss; 348 struct sockaddr_in *lsin = (struct sockaddr_in *)&ss; 349 struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss; 350 time_t t; 351 int isaddr; 352 353 p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-"; 354 if ((x_suffix = strrchr(p, ':')) != NULL) { 355 if ((dot = strchr(x_suffix, '.')) != NULL && 356 strchr(dot+1, '.') == NULL) 357 *x_suffix++ = '\0'; 358 else 359 x_suffix = NULL; 360 } 361 362 isaddr = 0; 363 memset(&ss, '\0', sizeof(ss)); 364 if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) { 365 lsin6->sin6_len = sizeof(*lsin6); 366 lsin6->sin6_family = AF_INET6; 367 isaddr = 1; 368 } else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) { 369 lsin->sin_len = sizeof(*lsin); 370 lsin->sin_family = AF_INET; 371 isaddr = 1; 372 } 373 if (!nflag) { 374 /* Attempt to change an IP address into a name */ 375 if (isaddr && realhostname_sa(fn, sizeof(fn), sa, 376 sa->sa_len) == HOSTNAME_FOUND) 377 p = fn; 378 } else if (!isaddr) { 379 /* 380 * If a host has only one A/AAAA RR, change a 381 * name into an IP address 382 */ 383 memset(&hints, 0, sizeof(hints)); 384 hints.ai_flags = AI_PASSIVE; 385 hints.ai_family = AF_UNSPEC; 386 hints.ai_socktype = SOCK_STREAM; 387 if (getaddrinfo(p, NULL, &hints, &res) == 0) { 388 if (res->ai_next == NULL && 389 getnameinfo(res->ai_addr, res->ai_addrlen, 390 fn, sizeof(fn), NULL, 0, 391 NI_NUMERICHOST) == 0) 392 p = fn; 393 freeaddrinfo(res); 394 } 395 } 396 397 if (x_suffix) { 398 (void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix); 399 p = buf; 400 } 401 if (dflag) { 402 for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) { 403 const char *ptr; 404 405 ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth), 406 dkp->ki_comm, NULL, MAXCOMLEN); 407 if (ptr == NULL) 408 ptr = "-"; 409 (void)printf("\t\t%-9d %s\n", 410 dkp->ki_pid, ptr); 411 } 412 } 413 (void)printf("%-*.*s %-*.*s %-*.*s ", 414 W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user, 415 W_DISPLINESIZE, W_DISPLINESIZE, 416 *ep->utmp.ut_line ? 417 (strncmp(ep->utmp.ut_line, "tty", 3) && 418 strncmp(ep->utmp.ut_line, "cua", 3) ? 419 ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-", 420 W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-"); 421 t = ep->utmp.ut_tv.tv_sec; 422 longattime = pr_attime(&t, &now); 423 longidle = pr_idle(ep->idle); 424 (void)printf("%.*s\n", argwidth - longidle - longattime, 425 ep->args); 426 } 427 (void)kvm_close(kd); 428 exit(0); 429} 430 431static void 432pr_header(time_t *nowp, int nusers) 433{ 434 double avenrun[3]; 435 time_t uptime; 436 struct timespec tp; 437 int days, hrs, i, mins, secs; 438 char buf[256]; 439 440 /* 441 * Print time of day. 442 */ 443 if (strftime(buf, sizeof(buf), 444 use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0) 445 (void)printf("%s ", buf); 446 /* 447 * Print how long system has been up. 448 */ 449 if (clock_gettime(CLOCK_UPTIME, &tp) != -1) { 450 uptime = tp.tv_sec; 451 if (uptime > 60) 452 uptime += 30; 453 days = uptime / 86400; 454 uptime %= 86400; 455 hrs = uptime / 3600; 456 uptime %= 3600; 457 mins = uptime / 60; 458 secs = uptime % 60; 459 (void)printf(" up"); 460 if (days > 0) 461 (void)printf(" %d day%s,", days, days > 1 ? "s" : ""); 462 if (hrs > 0 && mins > 0) 463 (void)printf(" %2d:%02d,", hrs, mins); 464 else if (hrs > 0) 465 (void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : ""); 466 else if (mins > 0) 467 (void)printf(" %d min%s,", mins, mins > 1 ? "s" : ""); 468 else 469 (void)printf(" %d sec%s,", secs, secs > 1 ? "s" : ""); 470 } 471 472 /* Print number of users logged in to system */ 473 (void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s"); 474 475 /* 476 * Print 1, 5, and 15 minute load averages. 477 */ 478 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1) 479 (void)printf(", no load average information available\n"); 480 else { 481 (void)printf(", load averages:"); 482 for (i = 0; i < (int)(sizeof(avenrun) / sizeof(avenrun[0])); i++) { 483 if (use_comma && i > 0) 484 (void)printf(","); 485 (void)printf(" %.2f", avenrun[i]); 486 } 487 (void)printf("\n"); 488 } 489} 490 491static struct stat * 492ttystat(char *line) 493{ 494 static struct stat sb; 495 char ttybuf[MAXPATHLEN]; 496 497 (void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line); 498 if (stat(ttybuf, &sb) == 0 && S_ISCHR(sb.st_mode)) { 499 return (&sb); 500 } else 501 return (NULL); 502} 503 504static void 505usage(int wcmd) 506{ 507 if (wcmd) 508 (void)fprintf(stderr, 509 "usage: w [-dhin] [-M core] [-N system] [user ...]\n"); 510 else 511 (void)fprintf(stderr, "usage: uptime\n"); 512 exit(1); 513} 514 515static int 516this_is_uptime(const char *s) 517{ 518 const char *u; 519 520 if ((u = strrchr(s, '/')) != NULL) 521 ++u; 522 else 523 u = s; 524 if (strcmp(u, "uptime") == 0) 525 return (0); 526 return (-1); 527} 528