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