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