maint: avoid a valgrind memory leak warning from pinky
[coreutils.git] / src / pinky.c
blob500f70a8b557c2fe25cfc92c68e9b6770cfe8222
1 /* GNU's pinky.
2 Copyright (C) 1992-2013 Free Software Foundation, Inc.
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.
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.
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/>. */
17 /* Created by hacking who.c by Kaveh Ghazi ghazi@caip.rutgers.edu */
19 #include <config.h>
20 #include <getopt.h>
21 #include <pwd.h>
22 #include <stdio.h>
24 #include <sys/types.h>
25 #include "system.h"
27 #include "canon-host.h"
28 #include "error.h"
29 #include "hard-locale.h"
30 #include "readutmp.h"
32 /* The official name of this program (e.g., no 'g' prefix). */
33 #define PROGRAM_NAME "pinky"
35 #define AUTHORS \
36 proper_name ("Joseph Arceneaux"), \
37 proper_name ("David MacKenzie"), \
38 proper_name ("Kaveh Ghazi")
40 char *ttyname (int);
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;
47 /* If true, display a line at the top describing each field. */
48 static bool include_heading = true;
50 /* if true, display the user's full name from pw_gecos. */
51 static bool include_fullname = true;
53 /* if true, display the user's ~/.project file when doing long format. */
54 static bool include_project = true;
56 /* if true, display the user's ~/.plan file when doing long format. */
57 static bool include_plan = true;
59 /* if true, display the user's home directory and shell
60 when doing long format. */
61 static bool include_home_and_shell = true;
63 /* if true, use the "short" output format. */
64 static bool do_short_format = true;
66 /* if true, display the ut_host field. */
67 #ifdef HAVE_UT_HOST
68 static bool include_where = true;
69 #endif
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;
76 static struct option const longopts[] =
78 {GETOPT_HELP_OPTION_DECL},
79 {GETOPT_VERSION_OPTION_DECL},
80 {NULL, 0, NULL, 0}
83 /* Count and return the number of ampersands in STR. */
85 static size_t _GL_ATTRIBUTE_PURE
86 count_ampersands (const char *str)
88 size_t count = 0;
91 if (*str == '&')
92 count++;
93 } while (*str++);
94 return count;
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. */
103 static char *
104 create_fullname (const char *gecos_name, const char *user_name)
106 size_t rsize = strlen (gecos_name) + 1;
107 char *result;
108 char *r;
109 size_t ampersands = count_ampersands (gecos_name);
111 if (ampersands != 0)
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 ();
120 r = result = xmalloc (rsize);
122 while (*gecos_name)
124 if (*gecos_name == '&')
126 const char *uname = user_name;
127 if (islower (to_uchar (*uname)))
128 *r++ = toupper (to_uchar (*uname++));
129 while (*uname)
130 *r++ = *uname++;
132 else
134 *r++ = *gecos_name;
137 gecos_name++;
139 *r = 0;
141 return result;
144 /* Return a string representing the time between WHEN and the time
145 that this function is first run. */
147 static const char *
148 idle_string (time_t when)
150 static time_t now = 0;
151 static char buf[INT_STRLEN_BOUND (long int) + 2];
152 time_t seconds_idle;
154 if (now == 0)
155 time (&now);
157 seconds_idle = now - when;
158 if (seconds_idle < 60) /* One minute. */
159 return " ";
160 if (seconds_idle < (24 * 60 * 60)) /* One day. */
162 int hours = seconds_idle / (60 * 60);
163 int minutes = (seconds_idle % (60 * 60)) / 60;
164 sprintf (buf, "%02d:%02d", hours, minutes);
166 else
168 unsigned long int days = seconds_idle / (24 * 60 * 60);
169 sprintf (buf, "%lud", days);
171 return buf;
174 /* Return a time string. */
175 static const char *
176 time_string (const STRUCT_UTMP *utmp_ent)
178 static char buf[INT_STRLEN_BOUND (intmax_t) + sizeof "-%m-%d %H:%M"];
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);
189 if (tmp)
191 strftime (buf, sizeof buf, time_format, tmp);
192 return buf;
194 else
195 return timetostr (t, buf);
198 /* Display a line of information about UTMP_ENT. */
200 static void
201 print_entry (const STRUCT_UTMP *utmp_ent)
203 struct stat stats;
204 time_t last_change;
205 char mesg;
207 #define DEV_DIR_WITH_TRAILING_SLASH "/dev/"
208 #define DEV_DIR_LEN (sizeof (DEV_DIR_WITH_TRAILING_SLASH) - 1)
210 char line[sizeof (utmp_ent->ut_line) + DEV_DIR_LEN + 1];
211 char *p = line;
213 /* Copy ut_line into LINE, prepending '/dev/' if ut_line is not
214 already an absolute file name. Some system may put the full,
215 absolute file name in ut_line. */
216 if ( ! IS_ABSOLUTE_FILE_NAME (utmp_ent->ut_line))
217 p = stpcpy (p, DEV_DIR_WITH_TRAILING_SLASH);
218 stzncpy (p, utmp_ent->ut_line, sizeof (utmp_ent->ut_line));
220 if (stat (line, &stats) == 0)
222 mesg = (stats.st_mode & S_IWGRP) ? ' ' : '*';
223 last_change = stats.st_atime;
225 else
227 mesg = '?';
228 last_change = 0;
231 printf ("%-8.*s", UT_USER_SIZE, UT_USER (utmp_ent));
233 if (include_fullname)
235 struct passwd *pw;
236 char name[UT_USER_SIZE + 1];
238 stzncpy (name, UT_USER (utmp_ent), UT_USER_SIZE);
239 pw = getpwnam (name);
240 if (pw == NULL)
241 /* TRANSLATORS: Real name is unknown; at most 19 characters. */
242 printf (" %19s", _(" ???"));
243 else
245 char *const comma = strchr (pw->pw_gecos, ',');
246 char *result;
248 if (comma)
249 *comma = '\0';
251 result = create_fullname (pw->pw_gecos, pw->pw_name);
252 printf (" %-19.19s", result);
253 free (result);
257 printf (" %c%-8.*s",
258 mesg, (int) sizeof (utmp_ent->ut_line), utmp_ent->ut_line);
260 if (include_idle)
262 if (last_change)
263 printf (" %-6s", idle_string (last_change));
264 else
265 /* TRANSLATORS: Idle time is unknown; at most 5 characters. */
266 printf (" %-6s", _("?????"));
269 printf (" %s", time_string (utmp_ent));
271 #ifdef HAVE_UT_HOST
272 if (include_where && utmp_ent->ut_host[0])
274 char ut_host[sizeof (utmp_ent->ut_host) + 1];
275 char *host = NULL;
276 char *display = NULL;
278 /* Copy the host name into UT_HOST, and ensure it's nul terminated. */
279 stzncpy (ut_host, utmp_ent->ut_host, sizeof (utmp_ent->ut_host));
281 /* Look for an X display. */
282 display = strchr (ut_host, ':');
283 if (display)
284 *display++ = '\0';
286 if (*ut_host)
287 /* See if we can canonicalize it. */
288 host = canon_host (ut_host);
289 if ( ! host)
290 host = ut_host;
292 if (display)
293 printf (" %s:%s", host, display);
294 else
295 printf (" %s", host);
297 if (host != ut_host)
298 free (host);
300 #endif
302 putchar ('\n');
305 /* Display a verbose line of information about UTMP_ENT. */
307 static void
308 print_long_entry (const char name[])
310 struct passwd *pw;
312 pw = getpwnam (name);
314 printf (_("Login name: "));
315 printf ("%-28s", name);
317 printf (_("In real life: "));
318 if (pw == NULL)
320 /* TRANSLATORS: Real name is unknown; no hard limit. */
321 printf (" %s", _("???\n"));
322 return;
324 else
326 char *const comma = strchr (pw->pw_gecos, ',');
327 char *result;
329 if (comma)
330 *comma = '\0';
332 result = create_fullname (pw->pw_gecos, pw->pw_name);
333 printf (" %s", result);
334 free (result);
337 putchar ('\n');
339 if (include_home_and_shell)
341 printf (_("Directory: "));
342 printf ("%-29s", pw->pw_dir);
343 printf (_("Shell: "));
344 printf (" %s", pw->pw_shell);
345 putchar ('\n');
348 if (include_project)
350 FILE *stream;
351 char buf[1024];
352 const char *const baseproject = "/.project";
353 char *const project =
354 xmalloc (strlen (pw->pw_dir) + strlen (baseproject) + 1);
355 stpcpy (stpcpy (project, pw->pw_dir), baseproject);
357 stream = fopen (project, "r");
358 if (stream)
360 size_t bytes;
362 printf (_("Project: "));
364 while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0)
365 fwrite (buf, 1, bytes, stdout);
366 fclose (stream);
369 free (project);
372 if (include_plan)
374 FILE *stream;
375 char buf[1024];
376 const char *const baseplan = "/.plan";
377 char *const plan =
378 xmalloc (strlen (pw->pw_dir) + strlen (baseplan) + 1);
379 stpcpy (stpcpy (plan, pw->pw_dir), baseplan);
381 stream = fopen (plan, "r");
382 if (stream)
384 size_t bytes;
386 printf (_("Plan:\n"));
388 while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0)
389 fwrite (buf, 1, bytes, stdout);
390 fclose (stream);
393 free (plan);
396 putchar ('\n');
399 /* Print the username of each valid entry and the number of valid entries
400 in UTMP_BUF, which should have N elements. */
402 static void
403 print_heading (void)
405 printf ("%-8s", _("Login"));
406 if (include_fullname)
407 printf (" %-19s", _("Name"));
408 printf (" %-9s", _(" TTY"));
409 if (include_idle)
410 printf (" %-6s", _("Idle"));
411 printf (" %-*s", time_format_width, _("When"));
412 #ifdef HAVE_UT_HOST
413 if (include_where)
414 printf (" %s", _("Where"));
415 #endif
416 putchar ('\n');
419 /* Display UTMP_BUF, which should have N entries. */
421 static void
422 scan_entries (size_t n, const STRUCT_UTMP *utmp_buf,
423 const int argc_names, char *const argv_names[])
425 if (hard_locale (LC_TIME))
427 time_format = "%Y-%m-%d %H:%M";
428 time_format_width = 4 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2;
430 else
432 time_format = "%b %e %H:%M";
433 time_format_width = 3 + 1 + 2 + 1 + 2 + 1 + 2;
436 if (include_heading)
437 print_heading ();
439 while (n--)
441 if (IS_USER_PROCESS (utmp_buf))
443 if (argc_names)
445 int i;
447 for (i = 0; i < argc_names; i++)
448 if (strncmp (UT_USER (utmp_buf), argv_names[i], UT_USER_SIZE)
449 == 0)
451 print_entry (utmp_buf);
452 break;
455 else
456 print_entry (utmp_buf);
458 utmp_buf++;
462 /* Display a list of who is on the system, according to utmp file FILENAME. */
464 static void
465 short_pinky (const char *filename,
466 const int argc_names, char *const argv_names[])
468 size_t n_users;
469 STRUCT_UTMP *utmp_buf = NULL;
471 if (read_utmp (filename, &n_users, &utmp_buf, 0) != 0)
472 error (EXIT_FAILURE, errno, "%s", filename);
474 scan_entries (n_users, utmp_buf, argc_names, argv_names);
476 IF_LINT (free (utmp_buf));
479 static void
480 long_pinky (const int argc_names, char *const argv_names[])
482 int i;
484 for (i = 0; i < argc_names; i++)
485 print_long_entry (argv_names[i]);
488 void
489 usage (int status)
491 if (status != EXIT_SUCCESS)
492 emit_try_help ();
493 else
495 printf (_("Usage: %s [OPTION]... [USER]...\n"), program_name);
496 fputs (_("\
498 -l produce long format output for the specified USERs\n\
499 -b omit the user's home directory and shell in long format\n\
500 -h omit the user's project file in long format\n\
501 -p omit the user's plan file in long format\n\
502 -s do short format output, this is the default\n\
503 "), stdout);
504 fputs (_("\
505 -f omit the line of column headings in short format\n\
506 -w omit the user's full name in short format\n\
507 -i omit the user's full name and remote host in short format\n\
508 -q omit the user's full name, remote host and idle time\n\
509 in short format\n\
510 "), stdout);
511 fputs (HELP_OPTION_DESCRIPTION, stdout);
512 fputs (VERSION_OPTION_DESCRIPTION, stdout);
513 printf (_("\
515 A lightweight 'finger' program; print user information.\n\
516 The utmp file will be %s.\n\
517 "), UTMP_FILE);
518 emit_ancillary_info ();
520 exit (status);
524 main (int argc, char **argv)
526 int optc;
527 int n_users;
529 initialize_main (&argc, &argv);
530 set_program_name (argv[0]);
531 setlocale (LC_ALL, "");
532 bindtextdomain (PACKAGE, LOCALEDIR);
533 textdomain (PACKAGE);
535 atexit (close_stdout);
537 while ((optc = getopt_long (argc, argv, "sfwiqbhlp", longopts, NULL)) != -1)
539 switch (optc)
541 case 's':
542 do_short_format = true;
543 break;
545 case 'l':
546 do_short_format = false;
547 break;
549 case 'f':
550 include_heading = false;
551 break;
553 case 'w':
554 include_fullname = false;
555 break;
557 case 'i':
558 include_fullname = false;
559 #ifdef HAVE_UT_HOST
560 include_where = false;
561 #endif
562 break;
564 case 'q':
565 include_fullname = false;
566 #ifdef HAVE_UT_HOST
567 include_where = false;
568 #endif
569 include_idle = false;
570 break;
572 case 'h':
573 include_project = false;
574 break;
576 case 'p':
577 include_plan = false;
578 break;
580 case 'b':
581 include_home_and_shell = false;
582 break;
584 case_GETOPT_HELP_CHAR;
586 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
588 default:
589 usage (EXIT_FAILURE);
593 n_users = argc - optind;
595 if (!do_short_format && n_users == 0)
597 error (0, 0, _("no username specified; at least one must be\
598 specified when using -l"));
599 usage (EXIT_FAILURE);
602 if (do_short_format)
603 short_pinky (UTMP_FILE, n_users, argv + optind);
604 else
605 long_pinky (n_users, argv + optind);
607 exit (EXIT_SUCCESS);