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