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