*** empty log message ***
[coreutils.git] / src / who.c
blob95db2d5f7cbec889e15f215bb8d02be29ae8ce83
1 /* GNU's who.
2 Copyright (C) 1992-2002 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 2, or (at your option)
7 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, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by jla; revised by djm; revised again by mstone */
20 /* Output format:
21 name [state] line time [activity] [pid] [comment] [exit]
22 state: -T
23 name, line, time: not -q
24 idle: -u
27 #include <config.h>
28 #include <getopt.h>
29 #include <stdio.h>
31 #include <sys/types.h>
32 #include "system.h"
34 #include "readutmp.h"
35 #include "error.h"
36 #include "closeout.h"
38 /* The official name of this program (e.g., no `g' prefix). */
39 #define PROGRAM_NAME "who"
41 #define AUTHORS N_ ("Joseph Arceneaux, David MacKenzie, and Michael Stone")
43 #ifndef MAXHOSTNAMELEN
44 # define MAXHOSTNAMELEN 64
45 #endif
47 #ifndef S_IWGRP
48 # define S_IWGRP 020
49 #endif
51 #ifndef USER_PROCESS
52 # define USER_PROCESS INT_MAX
53 #endif
55 #ifndef RUN_LVL
56 # define RUN_LVL INT_MAX
57 #endif
59 #ifndef INIT_PROCESS
60 # define INIT_PROCESS INT_MAX
61 #endif
63 #ifndef LOGIN_PROCESS
64 # define LOGIN_PROCESS INT_MAX
65 #endif
67 #ifndef DEAD_PROCESS
68 # define DEAD_PROCESS INT_MAX
69 #endif
71 #ifndef BOOT_TIME
72 # define BOOT_TIME 0
73 #endif
75 #ifndef NEW_TIME
76 # define NEW_TIME 0
77 #endif
79 #define IDLESTR_LEN 6
81 #if HAVE_STRUCT_XTMP_UT_PID
82 # define UT_PID(U) ((U)->ut_pid)
83 # define PIDSTR_DECL_AND_INIT(Var, Utmp_ent) \
84 char Var[INT_STRLEN_BOUND (Utmp_ent->ut_pid) + 1]; \
85 sprintf (Var, "%d", (int) (Utmp_ent->ut_pid))
86 #else
87 # define UT_PID(U) 0
88 # define PIDSTR_DECL_AND_INIT(Var, Utmp_ent) \
89 const char *Var = ""
90 #endif
92 #if HAVE_STRUCT_XTMP_UT_ID
93 # define UT_ID(U) ((U)->ut_id)
94 #else
95 /* Of course, sizeof "whatever" is the size of a pointer (often 4),
96 but that's ok, since the actual string has a length of only 2. */
97 # define UT_ID(U) "??"
98 #endif
100 #define UT_TYPE_UNDEF 255
102 #if HAVE_STRUCT_XTMP_UT_TYPE
103 # define UT_TYPE(U) ((U)->ut_type)
104 #else
105 # define UT_TYPE(U) UT_TYPE_UNDEF
106 #endif
108 #define IS_USER_PROCESS(U) \
109 (UT_USER (utmp_buf)[0] \
110 && (UT_TYPE (utmp_buf) == USER_PROCESS \
111 || (UT_TYPE (utmp_buf) == UT_TYPE_UNDEF \
112 && UT_TIME_MEMBER (utmp_buf) != 0)))
114 int gethostname ();
115 char *ttyname ();
116 char *canon_host ();
118 /* The name this program was run with. */
119 char *program_name;
121 /* If nonzero, attempt to canonicalize hostnames via a DNS lookup. */
122 static int do_lookup;
124 /* If nonzero, display only a list of usernames and count of
125 the users logged on.
126 Ignored for `who am i'. */
127 static int short_list;
129 /* If nonzero, display only name, line, and time fields */
130 static int short_output;
132 /* If nonzero, display the hours:minutes since each user has touched
133 the keyboard, or "." if within the last minute, or "old" if
134 not within the last day. */
135 static int include_idle;
137 /* If nonzero, display a line at the top describing each field. */
138 static int include_heading;
140 /* If nonzero, display a `+' for each user if mesg y, a `-' if mesg n,
141 or a `?' if their tty cannot be statted. */
142 static int include_mesg;
144 /* If nonzero, display process termination & exit status */
145 static int include_exit;
147 /* If nonzero, display the last boot time */
148 static int need_boottime;
150 /* If nonzero, display dead processes */
151 static int need_deadprocs;
153 /* If nonzero, display processes waiting for user login */
154 static int need_login;
156 /* If nonzero, display processes started by init */
157 static int need_initspawn;
159 /* If nonzero, display the last clock change */
160 static int need_clockchange;
162 /* If nonzero, display the current runlevel */
163 static int need_runlevel;
165 /* If nonzero, display user processes */
166 static int need_users;
168 /* If nonzero, display info only for the controlling tty */
169 static int my_line_only;
171 /* for long options with no corresponding short option, use enum */
172 enum
174 LOOKUP_OPTION = CHAR_MAX + 1,
175 LOGIN_OPTION
178 static struct option const longopts[] = {
179 {"all", no_argument, NULL, 'a'},
180 {"boot", no_argument, NULL, 'b'},
181 {"count", no_argument, NULL, 'q'},
182 {"dead", no_argument, NULL, 'd'},
183 {"heading", no_argument, NULL, 'H'},
184 {"idle", no_argument, NULL, 'i'},
185 {"login", no_argument, NULL, LOGIN_OPTION},
186 {"lookup", no_argument, NULL, LOOKUP_OPTION},
187 {"message", no_argument, NULL, 'T'},
188 {"mesg", no_argument, NULL, 'T'},
189 {"process", no_argument, NULL, 'p'},
190 {"runlevel", no_argument, NULL, 'r'},
191 {"short", no_argument, NULL, 's'},
192 {"time", no_argument, NULL, 't'},
193 {"users", no_argument, NULL, 'u'},
194 {"writable", no_argument, NULL, 'T'},
195 {GETOPT_HELP_OPTION_DECL},
196 {GETOPT_VERSION_OPTION_DECL},
197 {NULL, 0, NULL, 0}
200 /* Return a string representing the time between WHEN and the time
201 that this function is first run.
202 FIXME: locale? */
203 static const char *
204 idle_string (time_t when)
206 static time_t now = 0;
207 static char idle_hhmm[IDLESTR_LEN];
208 time_t seconds_idle;
210 if (now == 0)
211 time (&now);
213 seconds_idle = now - when;
214 if (seconds_idle < 60) /* One minute. */
215 return " . ";
216 if (seconds_idle < (24 * 60 * 60)) /* One day. */
218 sprintf (idle_hhmm, "%02d:%02d",
219 (int) (seconds_idle / (60 * 60)),
220 (int) ((seconds_idle % (60 * 60)) / 60));
221 return (const char *) idle_hhmm;
223 return _(" old ");
226 /* Return a standard time string, "mon dd hh:mm"
227 FIXME: handle localization */
228 static const char *
229 time_string (const STRUCT_UTMP *utmp_ent)
231 /* Don't take the address of UT_TIME_MEMBER directly.
232 Ulrich Drepper wrote:
233 ``... GNU libc (and perhaps other libcs as well) have extended
234 utmp file formats which do not use a simple time_t ut_time field.
235 In glibc, ut_time is a macro which selects for backward compatibility
236 the tv_sec member of a struct timeval value.'' */
237 time_t tm = UT_TIME_MEMBER (utmp_ent);
239 char *ptr = ctime (&tm) + 4;
240 ptr[12] = '\0';
241 return ptr;
244 /* Print formatted output line. Uses mostly arbitrary field sizes, probably
245 will need tweaking if any of the localization stuff is done, or for 64 bit
246 pids, etc. */
247 static void
248 print_line (const char *user, const char state, const char *line,
249 const char *time_str, const char *idle, const char *pid,
250 const char *comment, const char *exitstr)
252 printf ("%-8.8s", user ? user : " .");
253 if (include_mesg)
254 printf (" %c", state);
255 printf (" %-12s", line);
256 printf (" %-12s", time_str);
257 if (include_idle && !short_output)
258 printf (" %-6s", idle);
259 if (!short_output)
260 printf (" %10s", pid);
261 /* FIXME: it's not really clear whether the following should be in short_output.
262 a strict reading of SUSv2 would suggest not, but I haven't seen any
263 implementations that actually work that way... */
264 printf (" %-8s", comment);
265 if (include_exit && exitstr && *exitstr)
266 printf (" %-12s", exitstr);
267 putchar ('\n');
270 /* Send properly parsed USER_PROCESS info to print_line */
271 static void
272 print_user (const STRUCT_UTMP *utmp_ent)
274 struct stat stats;
275 time_t last_change;
276 char mesg;
277 char idlestr[IDLESTR_LEN];
278 static char *hoststr;
279 static int hostlen;
281 #define DEV_DIR_WITH_TRAILING_SLASH "/dev/"
282 #define DEV_DIR_LEN (sizeof (DEV_DIR_WITH_TRAILING_SLASH) - 1)
284 char line[sizeof (utmp_ent->ut_line) + DEV_DIR_LEN + 1];
285 PIDSTR_DECL_AND_INIT (pidstr, utmp_ent);
287 /* Copy ut_line into LINE, prepending `/dev/' if ut_line is not
288 already an absolute pathname. Some system may put the full,
289 absolute pathname in ut_line. */
290 if (utmp_ent->ut_line[0] == '/')
292 strncpy (line, utmp_ent->ut_line, sizeof (utmp_ent->ut_line));
293 line[sizeof (utmp_ent->ut_line)] = '\0';
295 else
297 strcpy (line, DEV_DIR_WITH_TRAILING_SLASH);
298 strncpy (line + DEV_DIR_LEN, utmp_ent->ut_line,
299 sizeof (utmp_ent->ut_line));
300 line[DEV_DIR_LEN + sizeof (utmp_ent->ut_line)] = '\0';
303 if (stat (line, &stats) == 0)
305 mesg = (stats.st_mode & S_IWGRP) ? '+' : '-';
306 last_change = stats.st_atime;
308 else
310 mesg = '?';
311 last_change = 0;
314 if (last_change)
315 sprintf (idlestr, "%.6s", idle_string (last_change));
316 else
317 sprintf (idlestr, " ?");
319 #if HAVE_UT_HOST
320 if (utmp_ent->ut_host[0])
322 char ut_host[sizeof (utmp_ent->ut_host) + 1];
323 char *host = 0, *display = 0;
325 /* Copy the host name into UT_HOST, and ensure it's nul terminated. */
326 strncpy (ut_host, utmp_ent->ut_host, (int) sizeof (utmp_ent->ut_host));
327 ut_host[sizeof (utmp_ent->ut_host)] = '\0';
329 /* Look for an X display. */
330 display = strrchr (ut_host, ':');
331 if (display)
332 *display++ = '\0';
334 if (*ut_host && do_lookup)
336 /* See if we can canonicalize it. */
337 host = canon_host (ut_host);
340 if (! host)
341 host = ut_host;
343 if (display)
345 if (hostlen < strlen (host) + strlen (display) + 4)
347 hostlen = strlen (host) + strlen (display) + 4;
348 hoststr = (char *) realloc (hoststr, hostlen);
350 sprintf (hoststr, "(%s:%s)", host, display);
352 else
354 if (hostlen < strlen (host) + 3)
356 hostlen = strlen (host) + 3;
357 hoststr = (char *) realloc (hoststr, hostlen);
359 sprintf (hoststr, "(%s)", host);
362 else
364 if (hostlen < 1)
366 hostlen = 1;
367 hoststr = (char *) realloc (hoststr, hostlen);
369 stpcpy (hoststr, "");
371 #endif
373 print_line (UT_USER (utmp_ent), mesg, utmp_ent->ut_line,
374 time_string (utmp_ent), idlestr, pidstr,
375 hoststr ? hoststr : "", "");
378 static void
379 print_boottime (const STRUCT_UTMP *utmp_ent)
381 print_line ("", ' ', "system boot", time_string (utmp_ent), "", "", "", "");
384 static char *
385 make_id_equals_comment (STRUCT_UTMP const *utmp_ent)
387 char *comment = xmalloc (sizeof (_("id=")) + sizeof UT_ID (utmp_ent) + 1);
389 /* Cast field width argument to `int' to avoid warning from gcc. */
390 sprintf (comment, "%s%.*s", _("id="), (int) sizeof UT_ID (utmp_ent),
391 UT_ID (utmp_ent));
392 return comment;
395 static void
396 print_deadprocs (const STRUCT_UTMP *utmp_ent)
398 static char *exitstr;
399 char *comment = make_id_equals_comment (utmp_ent);
400 PIDSTR_DECL_AND_INIT (pidstr, utmp_ent);
402 if (!exitstr)
403 exitstr = xmalloc (sizeof (_("term="))
404 + INT_STRLEN_BOUND (UT_EXIT_E_TERMINATION (utmp_ent)) + 1
405 + sizeof (_("exit="))
406 + INT_STRLEN_BOUND (UT_EXIT_E_EXIT (utmp_ent))
407 + 1);
408 sprintf (exitstr, "%s%d %s%d", _("term="), UT_EXIT_E_TERMINATION (utmp_ent),
409 _("exit="), UT_EXIT_E_EXIT (utmp_ent));
411 /* FIXME: add idle time? */
413 print_line ("", ' ', utmp_ent->ut_line,
414 time_string (utmp_ent), "", pidstr, comment, exitstr);
415 free (comment);
418 static void
419 print_login (const STRUCT_UTMP *utmp_ent)
421 char *comment = make_id_equals_comment (utmp_ent);
422 PIDSTR_DECL_AND_INIT (pidstr, utmp_ent);
424 /* FIXME: add idle time? */
426 print_line ("LOGIN", ' ', utmp_ent->ut_line,
427 time_string (utmp_ent), "", pidstr, comment, "");
428 free (comment);
431 static void
432 print_initspawn (const STRUCT_UTMP *utmp_ent)
434 char *comment = make_id_equals_comment (utmp_ent);
435 PIDSTR_DECL_AND_INIT (pidstr, utmp_ent);
437 print_line ("", ' ', utmp_ent->ut_line,
438 time_string (utmp_ent), "", pidstr, comment, "");
439 free (comment);
442 static void
443 print_clockchange (const STRUCT_UTMP *utmp_ent)
445 /* FIXME: handle NEW_TIME & OLD_TIME both */
446 print_line ("", ' ', _("clock change"),
447 time_string (utmp_ent), "", "", "", "");
450 static void
451 print_runlevel (const STRUCT_UTMP *utmp_ent)
453 static char *runlevline, *comment;
454 int last = UT_PID (utmp_ent) / 256;
455 int curr = UT_PID (utmp_ent) % 256;
457 if (!runlevline)
458 runlevline = xmalloc (sizeof (_("run-level")) + 3);
459 sprintf (runlevline, "%s %c", _("run-level"), curr);
461 if (!comment)
462 comment = xmalloc (sizeof (_("last=")) + 2);
463 sprintf (comment, "%s%c", _("last="), (last == 'N') ? 'S' : last);
465 print_line ("", ' ', runlevline, time_string (utmp_ent),
466 "", "", comment, "");
468 return;
471 /* Print the username of each valid entry and the number of valid entries
472 in UTMP_BUF, which should have N elements. */
473 static void
474 list_entries_who (int n, const STRUCT_UTMP *utmp_buf)
476 int entries = 0;
478 while (n--)
480 if (UT_USER (utmp_buf)[0] && UT_TYPE (utmp_buf) == USER_PROCESS)
482 char *trimmed_name;
484 trimmed_name = extract_trimmed_name (utmp_buf);
486 printf ("%s ", trimmed_name);
487 free (trimmed_name);
488 entries++;
490 utmp_buf++;
492 printf (_("\n# users=%u\n"), entries);
495 static void
496 print_heading (void)
498 print_line (_("NAME"), ' ', _("LINE"), _("TIME"), _("IDLE"), _("PID"),
499 _("COMMENT"), _("EXIT"));
502 /* Display UTMP_BUF, which should have N entries. */
503 static void
504 scan_entries (int n, const STRUCT_UTMP *utmp_buf)
506 char *ttyname_b IF_LINT ( = NULL);
508 if (include_heading)
509 print_heading ();
511 if (my_line_only)
513 ttyname_b = ttyname (0);
514 if (!ttyname_b)
515 return;
516 if (strncmp (ttyname_b, DEV_DIR_WITH_TRAILING_SLASH, DEV_DIR_LEN) == 0)
517 ttyname_b += DEV_DIR_LEN; /* Discard /dev/ prefix. */
520 while (n--)
522 if (!my_line_only ||
523 strncmp (ttyname_b, utmp_buf->ut_line,
524 sizeof (utmp_buf->ut_line)) == 0)
526 if (need_users && IS_USER_PROCESS (utmp_buf))
527 print_user (utmp_buf);
528 else if (need_runlevel && UT_TYPE (utmp_buf) == RUN_LVL)
529 print_runlevel (utmp_buf);
530 else if (need_boottime && UT_TYPE (utmp_buf) == BOOT_TIME)
531 print_boottime (utmp_buf);
532 /* I've never seen one of these, so I don't know what it should
533 look like :^)
534 FIXME: handle OLD_TIME also, perhaps show the delta? */
535 else if (need_clockchange && UT_TYPE (utmp_buf) == NEW_TIME)
536 print_clockchange (utmp_buf);
537 else if (need_initspawn && UT_TYPE (utmp_buf) == INIT_PROCESS)
538 print_initspawn (utmp_buf);
539 else if (need_login && UT_TYPE (utmp_buf) == LOGIN_PROCESS)
540 print_login (utmp_buf);
541 else if (need_deadprocs && UT_TYPE (utmp_buf) == DEAD_PROCESS)
542 print_deadprocs (utmp_buf);
545 utmp_buf++;
549 /* Display a list of who is on the system, according to utmp file filename. */
550 static void
551 who (const char *filename)
553 int n_users;
554 STRUCT_UTMP *utmp_buf;
555 int fail = read_utmp (filename, &n_users, &utmp_buf);
557 if (fail)
558 error (1, errno, "%s", filename);
560 if (short_list)
561 list_entries_who (n_users, utmp_buf);
562 else
563 scan_entries (n_users, utmp_buf);
566 void
567 usage (int status)
569 if (status != 0)
570 fprintf (stderr, _("Try `%s --help' for more information.\n"),
571 program_name);
572 else
574 printf (_("Usage: %s [OPTION]... [ FILE | ARG1 ARG2 ]\n"), program_name);
575 fputs (_("\
577 -a, --all same as -b -d --login -p -r -t -T -u\n\
578 -b, --boot time of last system boot\n\
579 -d, --dead print dead processes\n\
580 -H, --heading print line of column headings\n\
581 "), stdout);
582 fputs (_("\
583 -i, --idle add idle time as HOURS:MINUTES, . or old\n\
584 (deprecated, use -u)\n\
585 --login print system login processes\n\
586 (equivalent to SUS -l)\n\
587 "), stdout);
588 fputs (_("\
589 -l, --lookup attempt to canonicalize hostnames via DNS\n\
590 (-l is deprecated, use --lookup)\n\
591 -m only hostname and user associated with stdin\n\
592 -p, --process print active processes spawned by init\n\
593 "), stdout);
594 fputs (_("\
595 -q, --count all login names and number of users logged on\n\
596 -r, --runlevel print current runlevel\n\
597 -s, --short print only name, line, and time (default)\n\
598 -t, --time print last system clock change\n\
599 "), stdout);
600 fputs (_("\
601 -T, -w, --mesg add user's message status as +, - or ?\n\
602 -u, --users list users logged in\n\
603 --message same as -T\n\
604 --writable same as -T\n\
605 "), stdout);
606 fputs (HELP_OPTION_DESCRIPTION, stdout);
607 fputs (VERSION_OPTION_DESCRIPTION, stdout);
608 printf (_("\
610 If FILE is not specified, use %s. %s as FILE is common.\n\
611 If ARG1 ARG2 given, -m presumed: `am i' or `mom likes' are usual.\n\
612 "), UTMP_FILE, WTMP_FILE);
613 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
615 exit (status);
619 main (int argc, char **argv)
621 int optc, longind;
622 int assumptions = 1;
624 program_name = argv[0];
625 setlocale (LC_ALL, "");
626 bindtextdomain (PACKAGE, LOCALEDIR);
627 textdomain (PACKAGE);
629 atexit (close_stdout);
631 while ((optc = getopt_long (argc, argv, "abdilmpqrstuwHT", longopts,
632 &longind)) != -1)
634 switch (optc)
636 case 0:
637 break;
639 case 'a':
640 need_boottime = 1;
641 need_deadprocs = 1;
642 need_login = 1;
643 need_initspawn = 1;
644 need_runlevel = 1;
645 need_clockchange = 1;
646 need_users = 1;
647 include_mesg = 1;
648 include_idle = 1;
649 include_exit = 1;
650 assumptions = 0;
651 break;
653 case 'b':
654 need_boottime = 1;
655 assumptions = 0;
656 break;
658 case 'd':
659 need_deadprocs = 1;
660 include_idle = 1;
661 include_exit = 1;
662 assumptions = 0;
663 break;
665 case 'H':
666 include_heading = 1;
667 break;
669 /* FIXME: This should be -l in a future version */
670 case LOGIN_OPTION:
671 need_login = 1;
672 include_idle = 1;
673 assumptions = 0;
674 break;
676 case 'm':
677 my_line_only = 1;
678 break;
680 case 'p':
681 need_initspawn = 1;
682 assumptions = 0;
683 break;
685 case 'q':
686 short_list = 1;
687 break;
689 case 'r':
690 need_runlevel = 1;
691 include_idle = 1;
692 assumptions = 0;
693 break;
695 case 's':
696 short_output = 1;
697 break;
699 case 't':
700 need_clockchange = 1;
701 assumptions = 0;
702 break;
704 case 'T':
705 case 'w':
706 include_mesg = 1;
707 break;
709 case 'i':
710 error (0, 0,
711 _("Warning: -i will be removed in a future release; \
712 use -u instead"));
713 /* Fall through. */
714 case 'u':
715 need_users = 1;
716 include_idle = 1;
717 assumptions = 0;
718 break;
720 case 'l':
721 error (0, 0,
722 _("Warning: the meaning of '-l' will change in a future\
723 release to conform to POSIX"));
724 case LOOKUP_OPTION:
725 do_lookup = 1;
726 break;
728 case_GETOPT_HELP_CHAR;
730 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
732 default:
733 usage (1);
737 if (assumptions)
739 need_users = 1;
740 short_output = 1;
743 if (include_exit)
745 short_output = 0;
748 switch (argc - optind)
750 case 0: /* who */
751 who (UTMP_FILE);
752 break;
754 case 1: /* who <utmp file> */
755 who (argv[optind]);
756 break;
758 case 2: /* who <blurf> <glop> */
759 my_line_only = 1;
760 who (UTMP_FILE);
761 break;
763 default: /* lose */
764 error (0, 0, _("too many arguments"));
765 usage (1);
768 exit (0);