2 Copyright (C) 1992-2008 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by jla; revised by djm; revised again by mstone */
20 name [state] line time [activity] [pid] [comment] [exit]
22 name, line, time: not -q
30 #include <sys/types.h>
33 #include "canon-host.h"
36 #include "hard-locale.h"
40 /* The official name of this program (e.g., no `g' prefix). */
41 #define PROGRAM_NAME "who"
44 proper_name ("Joseph Arceneaux"), \
45 proper_name ("David MacKenzie"), \
46 proper_name ("Michael Stone")
48 #ifndef MAXHOSTNAMELEN
49 # define MAXHOSTNAMELEN 64
53 # define UT_TYPE_RUN_LVL(U) UT_TYPE_EQ (U, RUN_LVL)
55 # define UT_TYPE_RUN_LVL(U) false
59 # define UT_TYPE_INIT_PROCESS(U) UT_TYPE_EQ (U, INIT_PROCESS)
61 # define UT_TYPE_INIT_PROCESS(U) false
65 # define UT_TYPE_LOGIN_PROCESS(U) UT_TYPE_EQ (U, LOGIN_PROCESS)
67 # define UT_TYPE_LOGIN_PROCESS(U) false
71 # define UT_TYPE_DEAD_PROCESS(U) UT_TYPE_EQ (U, DEAD_PROCESS)
73 # define UT_TYPE_DEAD_PROCESS(U) false
77 # define UT_TYPE_NEW_TIME(U) UT_TYPE_EQ (U, NEW_TIME)
79 # define UT_TYPE_NEW_TIME(U) false
84 #if HAVE_STRUCT_XTMP_UT_PID
85 # define PIDSTR_DECL_AND_INIT(Var, Utmp_ent) \
86 char Var[INT_STRLEN_BOUND (Utmp_ent->ut_pid) + 1]; \
87 sprintf (Var, "%ld", (long int) (Utmp_ent->ut_pid))
89 # define PIDSTR_DECL_AND_INIT(Var, Utmp_ent) \
93 #if HAVE_STRUCT_XTMP_UT_ID
94 # define UT_ID(U) ((U)->ut_id)
96 # define UT_ID(U) "??"
101 /* The name this program was run with. */
104 /* If true, attempt to canonicalize hostnames via a DNS lookup. */
105 static bool do_lookup;
107 /* If true, display only a list of usernames and count of
109 Ignored for `who am i'. */
110 static bool short_list;
112 /* If true, display only name, line, and time fields. */
113 static bool short_output;
115 /* If true, display the hours:minutes since each user has touched
116 the keyboard, or "." if within the last minute, or "old" if
117 not within the last day. */
118 static bool include_idle;
120 /* If true, display a line at the top describing each field. */
121 static bool include_heading;
123 /* If true, display a `+' for each user if mesg y, a `-' if mesg n,
124 or a `?' if their tty cannot be statted. */
125 static bool include_mesg;
127 /* If true, display process termination & exit status. */
128 static bool include_exit;
130 /* If true, display the last boot time. */
131 static bool need_boottime;
133 /* If true, display dead processes. */
134 static bool need_deadprocs;
136 /* If true, display processes waiting for user login. */
137 static bool need_login;
139 /* If true, display processes started by init. */
140 static bool need_initspawn;
142 /* If true, display the last clock change. */
143 static bool need_clockchange;
145 /* If true, display the current runlevel. */
146 static bool need_runlevel;
148 /* If true, display user processes. */
149 static bool need_users;
151 /* If true, display info only for the controlling tty. */
152 static bool my_line_only;
154 /* The strftime format to use for login times, and its expected
156 static char const *time_format;
157 static int time_format_width;
159 /* for long options with no corresponding short option, use enum */
162 LOOKUP_OPTION = CHAR_MAX + 1
165 static struct option const longopts[] = {
166 {"all", no_argument, NULL, 'a'},
167 {"boot", no_argument, NULL, 'b'},
168 {"count", no_argument, NULL, 'q'},
169 {"dead", no_argument, NULL, 'd'},
170 {"heading", no_argument, NULL, 'H'},
171 {"login", no_argument, NULL, 'l'},
172 {"lookup", no_argument, NULL, LOOKUP_OPTION},
173 {"message", no_argument, NULL, 'T'},
174 {"mesg", no_argument, NULL, 'T'},
175 {"process", no_argument, NULL, 'p'},
176 {"runlevel", no_argument, NULL, 'r'},
177 {"short", no_argument, NULL, 's'},
178 {"time", no_argument, NULL, 't'},
179 {"users", no_argument, NULL, 'u'},
180 {"writable", no_argument, NULL, 'T'},
181 {GETOPT_HELP_OPTION_DECL},
182 {GETOPT_VERSION_OPTION_DECL},
186 /* Return a string representing the time between WHEN and now.
187 BOOTTIME is the time of last reboot.
190 idle_string (time_t when, time_t boottime)
192 static time_t now = TYPE_MINIMUM (time_t);
194 if (now == TYPE_MINIMUM (time_t))
197 if (boottime < when && now - 24 * 60 * 60 < when && when <= now)
199 int seconds_idle = now - when;
200 if (seconds_idle < 60)
204 static char idle_hhmm[IDLESTR_LEN];
205 sprintf (idle_hhmm, "%02d:%02d",
206 seconds_idle / (60 * 60),
207 (seconds_idle % (60 * 60)) / 60);
215 /* Return a time string. */
217 time_string (const STRUCT_UTMP *utmp_ent)
219 static char buf[INT_STRLEN_BOUND (intmax_t) + sizeof "-%m-%d %H:%M"];
221 /* Don't take the address of UT_TIME_MEMBER directly.
222 Ulrich Drepper wrote:
223 ``... GNU libc (and perhaps other libcs as well) have extended
224 utmp file formats which do not use a simple time_t ut_time field.
225 In glibc, ut_time is a macro which selects for backward compatibility
226 the tv_sec member of a struct timeval value.'' */
227 time_t t = UT_TIME_MEMBER (utmp_ent);
228 struct tm *tmp = localtime (&t);
232 strftime (buf, sizeof buf, time_format, tmp);
236 return TYPE_SIGNED (time_t) ? imaxtostr (t, buf) : umaxtostr (t, buf);
239 /* Print formatted output line. Uses mostly arbitrary field sizes, probably
240 will need tweaking if any of the localization stuff is done, or for 64 bit
243 print_line (int userlen, const char *user, const char state,
244 int linelen, const char *line,
245 const char *time_str, const char *idle, const char *pid,
246 const char *comment, const char *exitstr)
248 static char mesg[3] = { ' ', 'x', '\0' };
250 char x_idle[1 + IDLESTR_LEN + 1];
251 char x_pid[1 + INT_STRLEN_BOUND (pid_t) + 1];
257 if (include_idle && !short_output && strlen (idle) < sizeof x_idle - 1)
258 sprintf (x_idle, " %-6s", idle);
262 if (!short_output && strlen (pid) < sizeof x_pid - 1)
263 sprintf (x_pid, " %10s", pid);
267 x_exitstr = xmalloc (include_exit ? 1 + MAX (12, strlen (exitstr)) + 1 : 1);
269 sprintf (x_exitstr, " %-12s", exitstr);
273 err = asprintf (&buf,
283 userlen, user ? user : " .",
284 include_mesg ? mesg : "",
290 /* FIXME: it's not really clear whether the following
291 field should be in the short_output. A strict reading
292 of SUSv2 would suggest not, but I haven't seen any
293 implementations that actually work that way... */
301 /* Remove any trailing spaces. */
302 char *p = buf + strlen (buf);
313 /* Send properly parsed USER_PROCESS info to print_line. The most
314 recent boot time is BOOTTIME. */
316 print_user (const STRUCT_UTMP *utmp_ent, time_t boottime)
321 char idlestr[IDLESTR_LEN + 1];
322 static char *hoststr;
324 static size_t hostlen;
327 #define DEV_DIR_WITH_TRAILING_SLASH "/dev/"
328 #define DEV_DIR_LEN (sizeof (DEV_DIR_WITH_TRAILING_SLASH) - 1)
330 char line[sizeof (utmp_ent->ut_line) + DEV_DIR_LEN + 1];
331 PIDSTR_DECL_AND_INIT (pidstr, utmp_ent);
333 /* Copy ut_line into LINE, prepending `/dev/' if ut_line is not
334 already an absolute file name. Some systems may put the full,
335 absolute file name in ut_line. */
336 if (utmp_ent->ut_line[0] == '/')
338 strncpy (line, utmp_ent->ut_line, sizeof (utmp_ent->ut_line));
339 line[sizeof (utmp_ent->ut_line)] = '\0';
343 strcpy (line, DEV_DIR_WITH_TRAILING_SLASH);
344 strncpy (line + DEV_DIR_LEN, utmp_ent->ut_line,
345 sizeof (utmp_ent->ut_line));
346 line[DEV_DIR_LEN + sizeof (utmp_ent->ut_line)] = '\0';
349 if (stat (line, &stats) == 0)
351 mesg = (stats.st_mode & S_IWGRP) ? '+' : '-';
352 last_change = stats.st_atime;
361 sprintf (idlestr, "%.*s", IDLESTR_LEN, idle_string (last_change, boottime));
363 sprintf (idlestr, " ?");
366 if (utmp_ent->ut_host[0])
368 char ut_host[sizeof (utmp_ent->ut_host) + 1];
370 char *display = NULL;
372 /* Copy the host name into UT_HOST, and ensure it's nul terminated. */
373 strncpy (ut_host, utmp_ent->ut_host, sizeof (utmp_ent->ut_host));
374 ut_host[sizeof (utmp_ent->ut_host)] = '\0';
376 /* Look for an X display. */
377 display = strchr (ut_host, ':');
381 if (*ut_host && do_lookup)
383 /* See if we can canonicalize it. */
384 host = canon_host (ut_host);
392 if (hostlen < strlen (host) + strlen (display) + 4)
394 hostlen = strlen (host) + strlen (display) + 4;
395 hoststr = xrealloc (hoststr, hostlen);
397 sprintf (hoststr, "(%s:%s)", host, display);
401 if (hostlen < strlen (host) + 3)
403 hostlen = strlen (host) + 3;
404 hoststr = xrealloc (hoststr, hostlen);
406 sprintf (hoststr, "(%s)", host);
417 hoststr = xrealloc (hoststr, hostlen);
423 print_line (sizeof UT_USER (utmp_ent), UT_USER (utmp_ent), mesg,
424 sizeof utmp_ent->ut_line, utmp_ent->ut_line,
425 time_string (utmp_ent), idlestr, pidstr,
426 hoststr ? hoststr : "", "");
430 print_boottime (const STRUCT_UTMP *utmp_ent)
432 print_line (-1, "", ' ', -1, "system boot",
433 time_string (utmp_ent), "", "", "", "");
437 make_id_equals_comment (STRUCT_UTMP const *utmp_ent)
439 char *comment = xmalloc (strlen (_("id=")) + sizeof UT_ID (utmp_ent) + 1);
441 strcpy (comment, _("id="));
442 strncat (comment, UT_ID (utmp_ent), sizeof UT_ID (utmp_ent));
447 print_deadprocs (const STRUCT_UTMP *utmp_ent)
449 static char *exitstr;
450 char *comment = make_id_equals_comment (utmp_ent);
451 PIDSTR_DECL_AND_INIT (pidstr, utmp_ent);
454 exitstr = xmalloc (strlen (_("term="))
455 + INT_STRLEN_BOUND (UT_EXIT_E_TERMINATION (utmp_ent)) + 1
456 + strlen (_("exit="))
457 + INT_STRLEN_BOUND (UT_EXIT_E_EXIT (utmp_ent))
459 sprintf (exitstr, "%s%d %s%d", _("term="), UT_EXIT_E_TERMINATION (utmp_ent),
460 _("exit="), UT_EXIT_E_EXIT (utmp_ent));
462 /* FIXME: add idle time? */
464 print_line (-1, "", ' ', sizeof utmp_ent->ut_line, utmp_ent->ut_line,
465 time_string (utmp_ent), "", pidstr, comment, exitstr);
470 print_login (const STRUCT_UTMP *utmp_ent)
472 char *comment = make_id_equals_comment (utmp_ent);
473 PIDSTR_DECL_AND_INIT (pidstr, utmp_ent);
475 /* FIXME: add idle time? */
477 print_line (-1, "LOGIN", ' ', sizeof utmp_ent->ut_line, utmp_ent->ut_line,
478 time_string (utmp_ent), "", pidstr, comment, "");
483 print_initspawn (const STRUCT_UTMP *utmp_ent)
485 char *comment = make_id_equals_comment (utmp_ent);
486 PIDSTR_DECL_AND_INIT (pidstr, utmp_ent);
488 print_line (-1, "", ' ', sizeof utmp_ent->ut_line, utmp_ent->ut_line,
489 time_string (utmp_ent), "", pidstr, comment, "");
494 print_clockchange (const STRUCT_UTMP *utmp_ent)
496 /* FIXME: handle NEW_TIME & OLD_TIME both */
497 print_line (-1, "", ' ', -1, _("clock change"),
498 time_string (utmp_ent), "", "", "", "");
502 print_runlevel (const STRUCT_UTMP *utmp_ent)
504 static char *runlevline, *comment;
505 unsigned char last = UT_PID (utmp_ent) / 256;
506 unsigned char curr = UT_PID (utmp_ent) % 256;
509 runlevline = xmalloc (strlen (_("run-level")) + 3);
510 sprintf (runlevline, "%s %c", _("run-level"), curr);
513 comment = xmalloc (strlen (_("last=")) + 2);
514 sprintf (comment, "%s%c", _("last="), (last == 'N') ? 'S' : last);
516 print_line (-1, "", ' ', -1, runlevline, time_string (utmp_ent),
517 "", "", comment, "");
522 /* Print the username of each valid entry and the number of valid entries
523 in UTMP_BUF, which should have N elements. */
525 list_entries_who (size_t n, const STRUCT_UTMP *utmp_buf)
527 unsigned long int entries = 0;
528 char const *separator = "";
532 if (IS_USER_PROCESS (utmp_buf))
536 trimmed_name = extract_trimmed_name (utmp_buf);
538 printf ("%s%s", separator, trimmed_name);
545 printf (_("\n# users=%lu\n"), entries);
551 print_line (-1, _("NAME"), ' ', -1, _("LINE"), _("TIME"), _("IDLE"),
552 _("PID"), _("COMMENT"), _("EXIT"));
555 /* Display UTMP_BUF, which should have N entries. */
557 scan_entries (size_t n, const STRUCT_UTMP *utmp_buf)
559 char *ttyname_b IF_LINT ( = NULL);
560 time_t boottime = TYPE_MINIMUM (time_t);
567 ttyname_b = ttyname (STDIN_FILENO);
570 if (strncmp (ttyname_b, DEV_DIR_WITH_TRAILING_SLASH, DEV_DIR_LEN) == 0)
571 ttyname_b += DEV_DIR_LEN; /* Discard /dev/ prefix. */
577 strncmp (ttyname_b, utmp_buf->ut_line,
578 sizeof (utmp_buf->ut_line)) == 0)
580 if (need_users && IS_USER_PROCESS (utmp_buf))
581 print_user (utmp_buf, boottime);
582 else if (need_runlevel && UT_TYPE_RUN_LVL (utmp_buf))
583 print_runlevel (utmp_buf);
584 else if (need_boottime && UT_TYPE_BOOT_TIME (utmp_buf))
585 print_boottime (utmp_buf);
586 /* I've never seen one of these, so I don't know what it should
588 FIXME: handle OLD_TIME also, perhaps show the delta? */
589 else if (need_clockchange && UT_TYPE_NEW_TIME (utmp_buf))
590 print_clockchange (utmp_buf);
591 else if (need_initspawn && UT_TYPE_INIT_PROCESS (utmp_buf))
592 print_initspawn (utmp_buf);
593 else if (need_login && UT_TYPE_LOGIN_PROCESS (utmp_buf))
594 print_login (utmp_buf);
595 else if (need_deadprocs && UT_TYPE_DEAD_PROCESS (utmp_buf))
596 print_deadprocs (utmp_buf);
599 if (UT_TYPE_BOOT_TIME (utmp_buf))
600 boottime = UT_TIME_MEMBER (utmp_buf);
606 /* Display a list of who is on the system, according to utmp file FILENAME.
607 Use read_utmp OPTIONS to read the file. */
609 who (const char *filename, int options)
612 STRUCT_UTMP *utmp_buf;
614 if (read_utmp (filename, &n_users, &utmp_buf, options) != 0)
615 error (EXIT_FAILURE, errno, "%s", filename);
618 list_entries_who (n_users, utmp_buf);
620 scan_entries (n_users, utmp_buf);
628 if (status != EXIT_SUCCESS)
629 fprintf (stderr, _("Try `%s --help' for more information.\n"),
633 printf (_("Usage: %s [OPTION]... [ FILE | ARG1 ARG2 ]\n"), program_name);
636 -a, --all same as -b -d --login -p -r -t -T -u\n\
637 -b, --boot time of last system boot\n\
638 -d, --dead print dead processes\n\
639 -H, --heading print line of column headings\n\
642 -l, --login print system login processes\n\
645 --lookup attempt to canonicalize hostnames via DNS\n\
646 -m only hostname and user associated with stdin\n\
647 -p, --process print active processes spawned by init\n\
650 -q, --count all login names and number of users logged on\n\
651 -r, --runlevel print current runlevel\n\
652 -s, --short print only name, line, and time (default)\n\
653 -t, --time print last system clock change\n\
656 -T, -w, --mesg add user's message status as +, - or ?\n\
657 -u, --users list users logged in\n\
658 --message same as -T\n\
659 --writable same as -T\n\
661 fputs (HELP_OPTION_DESCRIPTION, stdout);
662 fputs (VERSION_OPTION_DESCRIPTION, stdout);
665 If FILE is not specified, use %s. %s as FILE is common.\n\
666 If ARG1 ARG2 given, -m presumed: `am i' or `mom likes' are usual.\n\
667 "), UTMP_FILE, WTMP_FILE);
668 emit_bug_reporting_address ();
674 main (int argc, char **argv)
677 bool assumptions = true;
679 initialize_main (&argc, &argv);
680 program_name = argv[0];
681 setlocale (LC_ALL, "");
682 bindtextdomain (PACKAGE, LOCALEDIR);
683 textdomain (PACKAGE);
685 atexit (close_stdout);
687 while ((optc = getopt_long (argc, argv, "abdlmpqrstuwHT", longopts, NULL))
693 need_boottime = true;
694 need_deadprocs = true;
696 need_initspawn = true;
697 need_runlevel = true;
698 need_clockchange = true;
707 need_boottime = true;
712 need_deadprocs = true;
719 include_heading = true;
733 need_initspawn = true;
742 need_runlevel = true;
752 need_clockchange = true;
771 case_GETOPT_HELP_CHAR;
773 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
776 usage (EXIT_FAILURE);
788 short_output = false;
791 if (hard_locale (LC_TIME))
793 time_format = "%Y-%m-%d %H:%M";
794 time_format_width = 4 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2;
798 time_format = "%b %e %H:%M";
799 time_format_width = 3 + 1 + 2 + 1 + 2 + 1 + 2;
802 switch (argc - optind)
804 case 2: /* who <blurf> <glop> */
809 who (UTMP_FILE, READ_UTMP_CHECK_PIDS);
812 case 1: /* who <utmp file> */
813 who (argv[optind], 0);
817 error (0, 0, _("extra operand %s"), quote (argv[optind + 2]));
818 usage (EXIT_FAILURE);