2 * w - show what logged in users are doing.
4 * Almost entirely rewritten from scratch by Charles Blake circa
5 * June 1996. Some vestigal traces of the original may exist.
6 * That was done in 1993 by Larry Greenfield with some fixes by
9 * Changes by Albert Cahalan, 2002.
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "fileutils.h"
29 #include "proc/devname.h"
30 #include "proc/escape.h"
31 #include "proc/procps.h"
32 #include "proc/readproc.h"
33 #include "proc/sysinfo.h"
34 #include "proc/version.h"
35 #include "proc/whattime.h"
50 #include <sys/ioctl.h>
53 #include <sys/types.h>
58 #include <arpa/inet.h>
60 static int ignoreuser = 0; /* for '-u' */
61 static int oldstyle = 0; /* for '-o' */
62 static proc_t **procs; /* our snapshot of the process table */
64 typedef struct utmp utmp_t;
67 # define FROM_STRING "on"
69 # define FROM_STRING "off"
72 #define MAX_CMD_WIDTH 512
73 #define MIN_CMD_WIDTH 7
76 * This routine is careful since some programs leave utmp strings
77 * unprintable. Always outputs at least 16 chars padded with
78 * spaces on the right if necessary.
80 static void print_host(const char *restrict host, int len, const int fromlen)
88 for (; host < last; host++) {
89 if (*host == '\0') break;
90 if (isprint(*host) && *host != ' ') {
101 * space-fill, and a '-' too if needed to ensure the
108 while (width++ < fromlen)
113 /* This routine prints the display part of the host or IPv6 link address interface */
114 static void print_display_or_interface(const char *restrict host, int len, int restlen)
118 if (restlen <= 0) return; /* not enough space for printing anything */
120 /* search for a collon (might be a display) */
122 while ( (disp < (host + len)) && (*disp != ':') && isprint(*disp) ) disp++;
126 /* detect multiple colons -> IPv6 in the host (not a display) */
128 while ( (tmp < (host + len)) && (*tmp != ':') && isprint(*tmp) ) tmp++;
130 if (*tmp != ':') { /* multiple colons not found - it's a display */
132 /* number of chars till the end of the input field */
133 len -= (disp - host);
135 /* if it is still longer than the rest of the output field, then cut it */
136 if (len > restlen) len = restlen;
138 /* print the display */
139 while ((len > 0) && isprint(*disp) && (*disp != ' ')) {
141 fputc(*disp, stdout);
145 if ((len > 0) && (*disp != '\0')) { /* space or nonprintable found - replace with dash and stop printing */
149 } else { /* multiple colons found - it's an IPv6 address */
151 /* search for % (interface separator in case of IPv6 link address) */
152 while ( (tmp < (host + len)) && (*tmp != '%') && isprint(*tmp) ) tmp++;
154 if (*tmp == '%') { /* interface separator found */
156 /* number of chars till the end of the input field */
159 /* if it is still longer than the rest of the output field, then cut it */
160 if (len > restlen) len = restlen;
162 /* print the interface */
163 while ((len > 0) && isprint(*tmp) && (*tmp != ' ')) {
168 if ((len > 0) && (*tmp != '\0')) { /* space or nonprintable found - replace with dash and stop printing */
177 /* padding with spaces */
178 while (restlen > 0) {
185 /* This routine prints either the hostname or the IP address of the remote */
186 static void print_from(const utmp_t *restrict const u, const int ip_addresses, const int fromlen) {
187 char buf[fromlen + 1];
188 char buf_ipv6[INET6_ADDRSTRLEN];
190 int32_t ut_addr_v6[4]; /* IP address of the remote host */
192 if (ip_addresses) { /* -i switch used */
193 memcpy(&ut_addr_v6, &u->ut_addr_v6, sizeof(ut_addr_v6));
194 if (IN6_IS_ADDR_V4MAPPED(&ut_addr_v6)) {
196 ut_addr_v6[0] = ut_addr_v6[3];
201 if (ut_addr_v6[1] || ut_addr_v6[2] || ut_addr_v6[3]) {
203 if (!inet_ntop(AF_INET6, &ut_addr_v6, buf_ipv6, sizeof(buf_ipv6))) {
204 strcpy(buf, ""); /* invalid address, clean the buffer */
206 strncpy(buf, buf_ipv6, fromlen); /* address valid, copy to buffer */
210 if (!(ut_addr_v6[0] && inet_ntop(AF_INET, &ut_addr_v6[0], buf, sizeof(buf)))) {
211 strcpy(buf, ""); /* invalid address, clean the buffer */
217 if (len) { /* IP address is non-empty, print it (and concatenate with display, if present) */
219 /* show the display part of the host or IPv6 link addr. interface, if present */
220 print_display_or_interface(u->ut_host, UT_HOSTSIZE, fromlen - len);
221 } else { /* IP address is empty, print the host instead */
222 print_host(u->ut_host, UT_HOSTSIZE, fromlen);
224 } else { /* -i switch NOT used */
225 print_host(u->ut_host, UT_HOSTSIZE, fromlen);
230 /* compact 7 char format for time intervals (belongs in libproc?) */
231 static void print_time_ival7(time_t t, int centi_sec, FILE * fout)
233 if ((long)t < (long)0) {
234 /* system clock changed? */
239 if (t >= 48 * 60 * 60)
241 fprintf(fout, _(" %2ludays"), t / (24 * 60 * 60));
242 else if (t >= 60 * 60)
244 /* Translation Hint: Hours:Minutes */
245 fprintf(fout, " %2lu:%02u ", t / (60 * 60),
246 (unsigned)((t / 60) % 60));
249 /* Translation Hint: Minutes:Seconds */
250 fprintf(fout, _(" %2lu:%02um"), t / 60, (unsigned)t % 60);
254 if (t >= 48 * 60 * 60)
256 fprintf(fout, _(" %2ludays"), t / (24 * 60 * 60));
257 else if (t >= 60 * 60)
259 /* Translation Hint: Hours:Minutes */
260 fprintf(fout, _(" %2lu:%02um"), t / (60 * 60),
261 (unsigned)((t / 60) % 60));
263 /* 1 minute or more */
264 /* Translation Hint: Minutes:Seconds */
265 fprintf(fout, " %2lu:%02u ", t / 60, (unsigned)t % 60);
267 /* Translation Hint: Seconds:Centiseconds */
268 fprintf(fout, _(" %2lu.%02us"), t, centi_sec);
272 /* stat the device file to get an idle time */
273 static time_t idletime(const char *restrict const tty)
276 if (stat(tty, &sbuf) != 0)
278 return time(NULL) - sbuf.st_atime;
281 /* 7 character formatted login time */
283 static void print_logintime(time_t logt, FILE * fout)
286 /* Abbreviated of weekday can be longer than 3 characters,
287 * see for instance hu_HU. Using 16 is few bytes more than
291 struct tm *logtm, *curtm;
295 curtm = localtime(&curt);
296 /* localtime returns a pointer to static memory */
297 today = curtm->tm_yday;
298 logtm = localtime(&logt);
299 if (curt - logt > 12 * 60 * 60 && logtm->tm_yday != today) {
300 if (curt - logt > 6 * 24 * 60 * 60) {
301 strftime(time_str, sizeof(time_str), "%b", logtm);
302 fprintf(fout, " %02d%3s%02d", logtm->tm_mday,
303 time_str, logtm->tm_year % 100);
305 strftime(time_str, sizeof(time_str), "%a", logtm);
306 fprintf(fout, " %3s%02d ", time_str,
310 fprintf(fout, " %02d:%02d ", logtm->tm_hour, logtm->tm_min);
315 * This function scans the process table accumulating total cpu
316 * times for any processes "associated" with this login session.
317 * It also searches for the "best" process to report as "(w)hat"
318 * the user for that login session is doing currently. This the
319 * essential core of 'w'.
321 static const proc_t *getproc(const utmp_t * restrict const u,
322 const char *restrict const tty,
323 unsigned long long *restrict const jcpu,
324 int *restrict const found_utpid)
327 proc_t **pptr = procs;
328 const proc_t *best = NULL;
329 const proc_t *secondbest = NULL;
334 char buf[UT_NAMESIZE + 1];
335 /* pointer to static data */
336 struct passwd *passwd_data;
337 strncpy(buf, u->ut_user, UT_NAMESIZE);
338 buf[UT_NAMESIZE] = '\0';
339 passwd_data = getpwnam(buf);
342 uid = passwd_data->pw_uid;
343 /* OK to have passwd_data go out of scope here */
345 line = tty_to_dev(tty);
347 for (; *pptr; pptr++) {
348 const proc_t *restrict const tmp = *pptr;
349 if (unlikely(tmp->tgid == u->ut_pid)) {
354 if (tmp->tty != line)
356 (*jcpu) += tmp->utime + tmp->stime;
358 /* same time-logic here as for "best" below */
359 if (!(secondbest && tmp->start_time <= secondbest->start_time)) {
362 if (!ignoreuser && uid != tmp->euid && uid != tmp->ruid)
364 if (tmp->pgrp != tmp->tpgid)
366 if (best && tmp->start_time <= best->start_time)
370 return best ? best : secondbest;
373 static void showinfo(utmp_t * u, int formtype, int maxcmd, int from,
374 const int userlen, const int fromlen, const int ip_addresses)
376 unsigned long long jcpu;
379 char uname[UT_NAMESIZE + 1] = "", tty[5 + UT_LINESIZE + 1] = "/dev/";
382 for (i = 0; i < UT_LINESIZE; i++)
383 /* clean up tty if garbled */
384 if (isalnum(u->ut_line[i]) || (u->ut_line[i] == '/'))
385 tty[i + 5] = u->ut_line[i];
389 best = getproc(u, tty + 5, &jcpu, &ut_pid_found);
392 * just skip if stale utmp entry (i.e. login proc doesn't
393 * exist). If there is a desire a cmdline flag could be
394 * added to optionally show it with a prefix of (stale)
395 * in front of cmd or something like that.
400 /* force NUL term for printf */
401 strncpy(uname, u->ut_user, UT_NAMESIZE);
404 printf("%-*.*s%-9.8s", userlen + 1, userlen, uname, u->ut_line);
406 print_from(u, ip_addresses, fromlen);
407 print_logintime(u->ut_time, stdout);
408 if (*u->ut_line == ':')
409 /* idle unknown for xdm logins */
412 print_time_ival7(idletime(tty), 0, stdout);
413 print_time_ival7(jcpu / Hertz, (jcpu % Hertz) * (100. / Hertz),
416 unsigned long long pcpu = best->utime + best->stime;
417 print_time_ival7(pcpu / Hertz,
418 (pcpu % Hertz) * (100. / Hertz),
423 printf("%-*.*s%-9.8s", userlen + 1, userlen, u->ut_user,
426 print_from(u, ip_addresses, fromlen);
427 if (*u->ut_line == ':')
428 /* idle unknown for xdm logins */
431 print_time_ival7(idletime(tty), 0, stdout);
435 char cmdbuf[MAX_CMD_WIDTH];
436 escape_command(cmdbuf, best, sizeof cmdbuf, &maxcmd, ESC_ARGS);
437 fputs(cmdbuf, stdout);
444 static void __attribute__ ((__noreturn__))
447 fputs(USAGE_HEADER, out);
449 _(" %s [options]\n"), program_invocation_short_name);
450 fputs(USAGE_OPTIONS, out);
451 fputs(_(" -h, --no-header do not print header\n"),out);
452 fputs(_(" -u, --no-current ignore current process username\n"),out);
453 fputs(_(" -s, --short short format\n"),out);
454 fputs(_(" -f, --from show remote hostname field\n"),out);
455 fputs(_(" -o, --old-style old style output\n"),out);
456 fputs(_(" -i, --ip-addr display IP address instead of hostname (if possible)\n"), out);
457 fputs(USAGE_SEPARATOR, out);
458 fputs(_(" --help display this help and exit\n"), out);
459 fputs(USAGE_VERSION, out);
460 fprintf(out, USAGE_MAN_TAIL("w(1)"));
462 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
465 int main(int argc, char **argv)
467 char *user = NULL, *p;
476 /* switches (defaults) */
480 int ip_addresses = 0;
483 HELP_OPTION = CHAR_MAX + 1
486 static const struct option longopts[] = {
487 {"no-header", no_argument, NULL, 'h'},
488 {"no-current", no_argument, NULL, 'u'},
489 {"short", no_argument, NULL, 's'},
490 {"from", no_argument, NULL, 'f'},
491 {"old-style", no_argument, NULL, 'o'},
492 {"ip-addr", no_argument, NULL, 'i'},
493 {"help", no_argument, NULL, HELP_OPTION},
494 {"version", no_argument, NULL, 'V'},
498 #ifdef HAVE_PROGRAM_INVOCATION_NAME
499 program_invocation_name = program_invocation_short_name;
501 setlocale (LC_ALL, "");
502 bindtextdomain(PACKAGE, LOCALEDIR);
504 atexit(close_stdout);
511 getopt_long(argc, argv, "husfoVi", longopts, NULL)) != -1)
526 printf(PROCPS_NG_VERSION);
545 user = (argv[optind]);
547 /* Get user field length from environment */
548 if ((env_var = getenv("PROCPS_USERLEN")) != NULL) {
549 int ut_namesize = UT_NAMESIZE;
550 userlen = atoi(env_var);
551 if (userlen < 8 || ut_namesize < userlen) {
553 (_("User length environment PROCPS_USERLEN must be between 8 and %i, ignoring.\n"),
558 /* Get from field length from environment */
559 if ((env_var = getenv("PROCPS_FROMLEN")) != NULL) {
560 fromlen = atoi(env_var);
561 if (fromlen < 8 || UT_HOSTSIZE < fromlen) {
563 (_("from length environment PROCPS_FROMLEN must be between 8 and %d, ignoring\n"),
568 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_col > 0)
570 else if ((p = getenv("COLUMNS")))
573 maxcmd = MAX_CMD_WIDTH;
574 if (MAX_CMD_WIDTH < maxcmd)
575 maxcmd = MAX_CMD_WIDTH;
576 maxcmd -= 21 + userlen + (from ? fromlen : 0) + (longform ? 20 : 0);
577 if (maxcmd < MIN_CMD_WIDTH)
578 maxcmd = MIN_CMD_WIDTH;
580 procs = readproctab(PROC_FILLCOM | PROC_FILLUSR | PROC_FILLSTAT);
583 /* print uptime and headers */
585 /* Translation Hint: Following five uppercase messages are
586 * headers. Try to keep alignment intact. */
587 printf(_("%-*s TTY "), userlen, _("USER"));
589 printf("%-*s", fromlen - 1, _("FROM"));
591 printf(_(" LOGIN@ IDLE JCPU PCPU WHAT\n"));
593 printf(_(" IDLE WHAT\n"));
603 if (u->ut_type != USER_PROCESS)
605 if (!strncmp(u->ut_user, user, UT_NAMESIZE))
606 showinfo(u, longform, maxcmd, from, userlen,
607 fromlen, ip_addresses);
614 if (u->ut_type != USER_PROCESS)
617 showinfo(u, longform, maxcmd, from, userlen,
618 fromlen, ip_addresses);