adjust copyright dates
[platform/upstream/coreutils.git] / src / pinky.c
1 /* GNU's pinky.
2    Copyright (C) 1992-1997, 1999-2006, 2008 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>.  */
16
17 /* Created by hacking who.c by Kaveh Ghazi ghazi@caip.rutgers.edu */
18
19 #include <config.h>
20 #include <getopt.h>
21 #include <pwd.h>
22 #include <stdio.h>
23
24 #include <sys/types.h>
25 #include "system.h"
26
27 #include "canon-host.h"
28 #include "error.h"
29 #include "hard-locale.h"
30 #include "inttostr.h"
31 #include "readutmp.h"
32
33 /* The official name of this program (e.g., no `g' prefix).  */
34 #define PROGRAM_NAME "pinky"
35
36 #define AUTHORS \
37   proper_name ("Joseph Arceneaux"), \
38   proper_name ("David MacKenzie"), \
39   proper_name ("Kaveh Ghazi")
40
41 #ifndef MAXHOSTNAMELEN
42 # define MAXHOSTNAMELEN 64
43 #endif
44
45 char *ttyname ();
46
47 /* The name this program was run with. */
48 const char *program_name;
49
50 /* If true, display the hours:minutes since each user has touched
51    the keyboard, or blank if within the last minute, or days followed
52    by a 'd' if not within the last day. */
53 static bool include_idle = true;
54
55 /* If true, display a line at the top describing each field. */
56 static bool include_heading = true;
57
58 /* if true, display the user's full name from pw_gecos. */
59 static bool include_fullname = true;
60
61 /* if true, display the user's ~/.project file when doing long format. */
62 static bool include_project = true;
63
64 /* if true, display the user's ~/.plan file when doing long format. */
65 static bool include_plan = true;
66
67 /* if true, display the user's home directory and shell
68    when doing long format. */
69 static bool include_home_and_shell = true;
70
71 /* if true, use the "short" output format. */
72 static bool do_short_format = true;
73
74 /* if true, display the ut_host field. */
75 #ifdef HAVE_UT_HOST
76 static bool include_where = true;
77 #endif
78
79 /* The strftime format to use for login times, and its expected
80    output width.  */
81 static char const *time_format;
82 static int time_format_width;
83
84 static struct option const longopts[] =
85 {
86   {GETOPT_HELP_OPTION_DECL},
87   {GETOPT_VERSION_OPTION_DECL},
88   {NULL, 0, NULL, 0}
89 };
90
91 /* Count and return the number of ampersands in STR.  */
92
93 static size_t
94 count_ampersands (const char *str)
95 {
96   size_t count = 0;
97   do
98     {
99       if (*str == '&')
100         count++;
101     } while (*str++);
102   return count;
103 }
104
105 /* Create a string (via xmalloc) which contains a full name by substituting
106    for each ampersand in GECOS_NAME the USER_NAME string with its first
107    character capitalized.  The caller must ensure that GECOS_NAME contains
108    no `,'s.  The caller also is responsible for free'ing the return value of
109    this function.  */
110
111 static char *
112 create_fullname (const char *gecos_name, const char *user_name)
113 {
114   size_t rsize = strlen (gecos_name) + 1;
115   char *result;
116   char *r;
117   size_t ampersands = count_ampersands (gecos_name);
118
119   if (ampersands != 0)
120     {
121       size_t ulen = strlen (user_name);
122       size_t product = ampersands * ulen;
123       rsize += product - ampersands;
124       if (xalloc_oversized (ulen, ampersands) || rsize < product)
125         xalloc_die ();
126     }
127
128   r = result = xmalloc (rsize);
129
130   while (*gecos_name)
131     {
132       if (*gecos_name == '&')
133         {
134           const char *uname = user_name;
135           if (islower (to_uchar (*uname)))
136             *r++ = toupper (to_uchar (*uname++));
137           while (*uname)
138             *r++ = *uname++;
139         }
140       else
141         {
142           *r++ = *gecos_name;
143         }
144
145       gecos_name++;
146     }
147   *r = 0;
148
149   return result;
150 }
151
152 /* Return a string representing the time between WHEN and the time
153    that this function is first run. */
154
155 static const char *
156 idle_string (time_t when)
157 {
158   static time_t now = 0;
159   static char buf[INT_STRLEN_BOUND (long int) + 2];
160   time_t seconds_idle;
161
162   if (now == 0)
163     time (&now);
164
165   seconds_idle = now - when;
166   if (seconds_idle < 60)        /* One minute. */
167     return "     ";
168   if (seconds_idle < (24 * 60 * 60))    /* One day. */
169     {
170       int hours = seconds_idle / (60 * 60);
171       int minutes = (seconds_idle % (60 * 60)) / 60;
172       sprintf (buf, "%02d:%02d", hours, minutes);
173     }
174   else
175     {
176       unsigned long int days = seconds_idle / (24 * 60 * 60);
177       sprintf (buf, "%lud", days);
178     }
179   return buf;
180 }
181
182 /* Return a time string.  */
183 static const char *
184 time_string (const STRUCT_UTMP *utmp_ent)
185 {
186   static char buf[INT_STRLEN_BOUND (intmax_t) + sizeof "-%m-%d %H:%M"];
187
188   /* Don't take the address of UT_TIME_MEMBER directly.
189      Ulrich Drepper wrote:
190      ``... GNU libc (and perhaps other libcs as well) have extended
191      utmp file formats which do not use a simple time_t ut_time field.
192      In glibc, ut_time is a macro which selects for backward compatibility
193      the tv_sec member of a struct timeval value.''  */
194   time_t t = UT_TIME_MEMBER (utmp_ent);
195   struct tm *tmp = localtime (&t);
196
197   if (tmp)
198     {
199       strftime (buf, sizeof buf, time_format, tmp);
200       return buf;
201     }
202   else
203     return TYPE_SIGNED (time_t) ? imaxtostr (t, buf) : umaxtostr (t, buf);
204 }
205
206 /* Display a line of information about UTMP_ENT. */
207
208 static void
209 print_entry (const STRUCT_UTMP *utmp_ent)
210 {
211   struct stat stats;
212   time_t last_change;
213   char mesg;
214
215 #define DEV_DIR_WITH_TRAILING_SLASH "/dev/"
216 #define DEV_DIR_LEN (sizeof (DEV_DIR_WITH_TRAILING_SLASH) - 1)
217
218   char line[sizeof (utmp_ent->ut_line) + DEV_DIR_LEN + 1];
219
220   /* Copy ut_line into LINE, prepending `/dev/' if ut_line is not
221      already an absolute file name.  Some system may put the full,
222      absolute file name in ut_line.  */
223   if (utmp_ent->ut_line[0] == '/')
224     {
225       strncpy (line, utmp_ent->ut_line, sizeof (utmp_ent->ut_line));
226       line[sizeof (utmp_ent->ut_line)] = '\0';
227     }
228   else
229     {
230       strcpy (line, DEV_DIR_WITH_TRAILING_SLASH);
231       strncpy (line + DEV_DIR_LEN, utmp_ent->ut_line, sizeof (utmp_ent->ut_line));
232       line[DEV_DIR_LEN + sizeof (utmp_ent->ut_line)] = '\0';
233     }
234
235   if (stat (line, &stats) == 0)
236     {
237       mesg = (stats.st_mode & S_IWGRP) ? ' ' : '*';
238       last_change = stats.st_atime;
239     }
240   else
241     {
242       mesg = '?';
243       last_change = 0;
244     }
245
246   printf ("%-8.*s", UT_USER_SIZE, UT_USER (utmp_ent));
247
248   if (include_fullname)
249     {
250       struct passwd *pw;
251       char name[UT_USER_SIZE + 1];
252
253       strncpy (name, UT_USER (utmp_ent), UT_USER_SIZE);
254       name[UT_USER_SIZE] = '\0';
255       pw = getpwnam (name);
256       if (pw == NULL)
257         printf (" %19s", "        ???");
258       else
259         {
260           char *const comma = strchr (pw->pw_gecos, ',');
261           char *result;
262
263           if (comma)
264             *comma = '\0';
265
266           result = create_fullname (pw->pw_gecos, pw->pw_name);
267           printf (" %-19.19s", result);
268           free (result);
269         }
270     }
271
272   printf (" %c%-8.*s",
273           mesg, (int) sizeof (utmp_ent->ut_line), utmp_ent->ut_line);
274
275   if (include_idle)
276     {
277       if (last_change)
278         printf (" %-6s", idle_string (last_change));
279       else
280         printf (" %-6s", "???");
281     }
282
283   printf (" %s", time_string (utmp_ent));
284
285 #ifdef HAVE_UT_HOST
286   if (include_where && utmp_ent->ut_host[0])
287     {
288       char ut_host[sizeof (utmp_ent->ut_host) + 1];
289       char *host = NULL;
290       char *display = NULL;
291
292       /* Copy the host name into UT_HOST, and ensure it's nul terminated. */
293       strncpy (ut_host, utmp_ent->ut_host, (int) sizeof (utmp_ent->ut_host));
294       ut_host[sizeof (utmp_ent->ut_host)] = '\0';
295
296       /* Look for an X display.  */
297       display = strchr (ut_host, ':');
298       if (display)
299         *display++ = '\0';
300
301       if (*ut_host)
302         /* See if we can canonicalize it.  */
303         host = canon_host (ut_host);
304       if ( ! host)
305         host = ut_host;
306
307       if (display)
308         printf (" %s:%s", host, display);
309       else
310         printf (" %s", host);
311
312       if (host != ut_host)
313         free (host);
314     }
315 #endif
316
317   putchar ('\n');
318 }
319
320 /* Display a verbose line of information about UTMP_ENT. */
321
322 static void
323 print_long_entry (const char name[])
324 {
325   struct passwd *pw;
326
327   pw = getpwnam (name);
328
329   printf (_("Login name: "));
330   printf ("%-28s", name);
331
332   printf (_("In real life: "));
333   if (pw == NULL)
334     {
335       printf (" %s", _("???\n"));
336       return;
337     }
338   else
339     {
340       char *const comma = strchr (pw->pw_gecos, ',');
341       char *result;
342
343       if (comma)
344         *comma = '\0';
345
346       result = create_fullname (pw->pw_gecos, pw->pw_name);
347       printf (" %s", result);
348       free (result);
349     }
350
351   putchar ('\n');
352
353   if (include_home_and_shell)
354     {
355       printf (_("Directory: "));
356       printf ("%-29s", pw->pw_dir);
357       printf (_("Shell: "));
358       printf (" %s", pw->pw_shell);
359       putchar ('\n');
360     }
361
362   if (include_project)
363     {
364       FILE *stream;
365       char buf[1024];
366       const char *const baseproject = "/.project";
367       char *const project =
368       xmalloc (strlen (pw->pw_dir) + strlen (baseproject) + 1);
369
370       strcpy (project, pw->pw_dir);
371       strcat (project, baseproject);
372
373       stream = fopen (project, "r");
374       if (stream)
375         {
376           size_t bytes;
377
378           printf (_("Project: "));
379
380           while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0)
381             fwrite (buf, 1, bytes, stdout);
382           fclose (stream);
383         }
384
385       free (project);
386     }
387
388   if (include_plan)
389     {
390       FILE *stream;
391       char buf[1024];
392       const char *const baseplan = "/.plan";
393       char *const plan =
394       xmalloc (strlen (pw->pw_dir) + strlen (baseplan) + 1);
395
396       strcpy (plan, pw->pw_dir);
397       strcat (plan, baseplan);
398
399       stream = fopen (plan, "r");
400       if (stream)
401         {
402           size_t bytes;
403
404           printf (_("Plan:\n"));
405
406           while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0)
407             fwrite (buf, 1, bytes, stdout);
408           fclose (stream);
409         }
410
411       free (plan);
412     }
413
414   putchar ('\n');
415 }
416
417 /* Print the username of each valid entry and the number of valid entries
418    in UTMP_BUF, which should have N elements. */
419
420 static void
421 print_heading (void)
422 {
423   printf ("%-8s", _("Login"));
424   if (include_fullname)
425     printf (" %-19s", _("Name"));
426   printf (" %-9s", _(" TTY"));
427   if (include_idle)
428     printf (" %-6s", _("Idle"));
429   printf (" %-*s", time_format_width, _("When"));
430 #ifdef HAVE_UT_HOST
431   if (include_where)
432     printf (" %s", _("Where"));
433 #endif
434   putchar ('\n');
435 }
436
437 /* Display UTMP_BUF, which should have N entries. */
438
439 static void
440 scan_entries (size_t n, const STRUCT_UTMP *utmp_buf,
441               const int argc_names, char *const argv_names[])
442 {
443   if (hard_locale (LC_TIME))
444     {
445       time_format = "%Y-%m-%d %H:%M";
446       time_format_width = 4 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2;
447     }
448   else
449     {
450       time_format = "%b %e %H:%M";
451       time_format_width = 3 + 1 + 2 + 1 + 2 + 1 + 2;
452     }
453
454   if (include_heading)
455     print_heading ();
456
457   while (n--)
458     {
459       if (IS_USER_PROCESS (utmp_buf))
460         {
461           if (argc_names)
462             {
463               int i;
464
465               for (i = 0; i < argc_names; i++)
466                 if (strncmp (UT_USER (utmp_buf), argv_names[i], UT_USER_SIZE)
467                     == 0)
468                   {
469                     print_entry (utmp_buf);
470                     break;
471                   }
472             }
473           else
474             print_entry (utmp_buf);
475         }
476       utmp_buf++;
477     }
478 }
479
480 /* Display a list of who is on the system, according to utmp file FILENAME. */
481
482 static void
483 short_pinky (const char *filename,
484              const int argc_names, char *const argv_names[])
485 {
486   size_t n_users;
487   STRUCT_UTMP *utmp_buf;
488
489   if (read_utmp (filename, &n_users, &utmp_buf, 0) != 0)
490     error (EXIT_FAILURE, errno, "%s", filename);
491
492   scan_entries (n_users, utmp_buf, argc_names, argv_names);
493 }
494
495 static void
496 long_pinky (const int argc_names, char *const argv_names[])
497 {
498   int i;
499
500   for (i = 0; i < argc_names; i++)
501     print_long_entry (argv_names[i]);
502 }
503
504 void
505 usage (int status)
506 {
507   if (status != EXIT_SUCCESS)
508     fprintf (stderr, _("Try `%s --help' for more information.\n"),
509              program_name);
510   else
511     {
512       printf (_("Usage: %s [OPTION]... [USER]...\n"), program_name);
513       fputs (_("\
514 \n\
515   -l              produce long format output for the specified USERs\n\
516   -b              omit the user's home directory and shell in long format\n\
517   -h              omit the user's project file in long format\n\
518   -p              omit the user's plan file in long format\n\
519   -s              do short format output, this is the default\n\
520 "), stdout);
521       fputs (_("\
522   -f              omit the line of column headings in short format\n\
523   -w              omit the user's full name in short format\n\
524   -i              omit the user's full name and remote host in short format\n\
525   -q              omit the user's full name, remote host and idle time\n\
526                   in short format\n\
527 "), stdout);
528       fputs (HELP_OPTION_DESCRIPTION, stdout);
529       fputs (VERSION_OPTION_DESCRIPTION, stdout);
530       printf (_("\
531 \n\
532 A lightweight `finger' program;  print user information.\n\
533 The utmp file will be %s.\n\
534 "), UTMP_FILE);
535       emit_bug_reporting_address ();
536     }
537   exit (status);
538 }
539
540 int
541 main (int argc, char **argv)
542 {
543   int optc;
544   int n_users;
545
546   initialize_main (&argc, &argv);
547   program_name = argv[0];
548   setlocale (LC_ALL, "");
549   bindtextdomain (PACKAGE, LOCALEDIR);
550   textdomain (PACKAGE);
551
552   atexit (close_stdout);
553
554   while ((optc = getopt_long (argc, argv, "sfwiqbhlp", longopts, NULL)) != -1)
555     {
556       switch (optc)
557         {
558         case 's':
559           do_short_format = true;
560           break;
561
562         case 'l':
563           do_short_format = false;
564           break;
565
566         case 'f':
567           include_heading = false;
568           break;
569
570         case 'w':
571           include_fullname = false;
572           break;
573
574         case 'i':
575           include_fullname = false;
576 #ifdef HAVE_UT_HOST
577           include_where = false;
578 #endif
579           break;
580
581         case 'q':
582           include_fullname = false;
583 #ifdef HAVE_UT_HOST
584           include_where = false;
585 #endif
586           include_idle = false;
587           break;
588
589         case 'h':
590           include_project = false;
591           break;
592
593         case 'p':
594           include_plan = false;
595           break;
596
597         case 'b':
598           include_home_and_shell = false;
599           break;
600
601         case_GETOPT_HELP_CHAR;
602
603         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
604
605         default:
606           usage (EXIT_FAILURE);
607         }
608     }
609
610   n_users = argc - optind;
611
612   if (!do_short_format && n_users == 0)
613     {
614       error (0, 0, _("no username specified; at least one must be\
615  specified when using -l"));
616       usage (EXIT_FAILURE);
617     }
618
619   if (do_short_format)
620     short_pinky (UTMP_FILE, n_users, argv + optind);
621   else
622     long_pinky (n_users, argv + optind);
623
624   exit (EXIT_SUCCESS);
625 }