id: fix infinite loop on some systems
[coreutils/ericb.git] / src / pinky.c
blob9575923023ddfe55266ba161d8e5d7645bdef35d
1 /* GNU's pinky.
2 Copyright (C) 1992-1997, 1999-2006, 2008 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 "readutmp.h"
31 /* The official name of this program (e.g., no `g' prefix). */
32 #define PROGRAM_NAME "pinky"
34 #define AUTHORS \
35 proper_name ("Joseph Arceneaux"), \
36 proper_name ("David MacKenzie"), \
37 proper_name ("Kaveh Ghazi")
39 #ifndef MAXHOSTNAMELEN
40 # define MAXHOSTNAMELEN 64
41 #endif
43 char *ttyname (int);
45 /* If true, display the hours:minutes since each user has touched
46 the keyboard, or blank if within the last minute, or days followed
47 by a 'd' if not within the last day. */
48 static bool include_idle = true;
50 /* If true, display a line at the top describing each field. */
51 static bool include_heading = true;
53 /* if true, display the user's full name from pw_gecos. */
54 static bool include_fullname = true;
56 /* if true, display the user's ~/.project file when doing long format. */
57 static bool include_project = true;
59 /* if true, display the user's ~/.plan file when doing long format. */
60 static bool include_plan = true;
62 /* if true, display the user's home directory and shell
63 when doing long format. */
64 static bool include_home_and_shell = true;
66 /* if true, use the "short" output format. */
67 static bool do_short_format = true;
69 /* if true, display the ut_host field. */
70 #ifdef HAVE_UT_HOST
71 static bool include_where = true;
72 #endif
74 /* The strftime format to use for login times, and its expected
75 output width. */
76 static char const *time_format;
77 static int time_format_width;
79 static struct option const longopts[] =
81 {GETOPT_HELP_OPTION_DECL},
82 {GETOPT_VERSION_OPTION_DECL},
83 {NULL, 0, NULL, 0}
86 /* Count and return the number of ampersands in STR. */
88 static size_t
89 count_ampersands (const char *str)
91 size_t count = 0;
94 if (*str == '&')
95 count++;
96 } while (*str++);
97 return count;
100 /* Create a string (via xmalloc) which contains a full name by substituting
101 for each ampersand in GECOS_NAME the USER_NAME string with its first
102 character capitalized. The caller must ensure that GECOS_NAME contains
103 no `,'s. The caller also is responsible for free'ing the return value of
104 this function. */
106 static char *
107 create_fullname (const char *gecos_name, const char *user_name)
109 size_t rsize = strlen (gecos_name) + 1;
110 char *result;
111 char *r;
112 size_t ampersands = count_ampersands (gecos_name);
114 if (ampersands != 0)
116 size_t ulen = strlen (user_name);
117 size_t product = ampersands * ulen;
118 rsize += product - ampersands;
119 if (xalloc_oversized (ulen, ampersands) || rsize < product)
120 xalloc_die ();
123 r = result = xmalloc (rsize);
125 while (*gecos_name)
127 if (*gecos_name == '&')
129 const char *uname = user_name;
130 if (islower (to_uchar (*uname)))
131 *r++ = toupper (to_uchar (*uname++));
132 while (*uname)
133 *r++ = *uname++;
135 else
137 *r++ = *gecos_name;
140 gecos_name++;
142 *r = 0;
144 return result;
147 /* Return a string representing the time between WHEN and the time
148 that this function is first run. */
150 static const char *
151 idle_string (time_t when)
153 static time_t now = 0;
154 static char buf[INT_STRLEN_BOUND (long int) + 2];
155 time_t seconds_idle;
157 if (now == 0)
158 time (&now);
160 seconds_idle = now - when;
161 if (seconds_idle < 60) /* One minute. */
162 return " ";
163 if (seconds_idle < (24 * 60 * 60)) /* One day. */
165 int hours = seconds_idle / (60 * 60);
166 int minutes = (seconds_idle % (60 * 60)) / 60;
167 sprintf (buf, "%02d:%02d", hours, minutes);
169 else
171 unsigned long int days = seconds_idle / (24 * 60 * 60);
172 sprintf (buf, "%lud", days);
174 return buf;
177 /* Return a time string. */
178 static const char *
179 time_string (const STRUCT_UTMP *utmp_ent)
181 static char buf[INT_STRLEN_BOUND (intmax_t) + sizeof "-%m-%d %H:%M"];
183 /* Don't take the address of UT_TIME_MEMBER directly.
184 Ulrich Drepper wrote:
185 ``... GNU libc (and perhaps other libcs as well) have extended
186 utmp file formats which do not use a simple time_t ut_time field.
187 In glibc, ut_time is a macro which selects for backward compatibility
188 the tv_sec member of a struct timeval value.'' */
189 time_t t = UT_TIME_MEMBER (utmp_ent);
190 struct tm *tmp = localtime (&t);
192 if (tmp)
194 strftime (buf, sizeof buf, time_format, tmp);
195 return buf;
197 else
198 return timetostr (t, buf);
201 /* Display a line of information about UTMP_ENT. */
203 static void
204 print_entry (const STRUCT_UTMP *utmp_ent)
206 struct stat stats;
207 time_t last_change;
208 char mesg;
210 #define DEV_DIR_WITH_TRAILING_SLASH "/dev/"
211 #define DEV_DIR_LEN (sizeof (DEV_DIR_WITH_TRAILING_SLASH) - 1)
213 char line[sizeof (utmp_ent->ut_line) + DEV_DIR_LEN + 1];
215 /* Copy ut_line into LINE, prepending `/dev/' if ut_line is not
216 already an absolute file name. Some system may put the full,
217 absolute file name in ut_line. */
218 if (utmp_ent->ut_line[0] == '/')
220 strncpy (line, utmp_ent->ut_line, sizeof (utmp_ent->ut_line));
221 line[sizeof (utmp_ent->ut_line)] = '\0';
223 else
225 strcpy (line, DEV_DIR_WITH_TRAILING_SLASH);
226 strncpy (line + DEV_DIR_LEN, utmp_ent->ut_line, sizeof (utmp_ent->ut_line));
227 line[DEV_DIR_LEN + sizeof (utmp_ent->ut_line)] = '\0';
230 if (stat (line, &stats) == 0)
232 mesg = (stats.st_mode & S_IWGRP) ? ' ' : '*';
233 last_change = stats.st_atime;
235 else
237 mesg = '?';
238 last_change = 0;
241 printf ("%-8.*s", UT_USER_SIZE, UT_USER (utmp_ent));
243 if (include_fullname)
245 struct passwd *pw;
246 char name[UT_USER_SIZE + 1];
248 strncpy (name, UT_USER (utmp_ent), UT_USER_SIZE);
249 name[UT_USER_SIZE] = '\0';
250 pw = getpwnam (name);
251 if (pw == NULL)
252 /* TRANSLATORS: Real name is unknown; at most 19 characters. */
253 printf (" %19s", _(" ???"));
254 else
256 char *const comma = strchr (pw->pw_gecos, ',');
257 char *result;
259 if (comma)
260 *comma = '\0';
262 result = create_fullname (pw->pw_gecos, pw->pw_name);
263 printf (" %-19.19s", result);
264 free (result);
268 printf (" %c%-8.*s",
269 mesg, (int) sizeof (utmp_ent->ut_line), utmp_ent->ut_line);
271 if (include_idle)
273 if (last_change)
274 printf (" %-6s", idle_string (last_change));
275 else
276 /* TRANSLATORS: Idle time is unknown; at most 5 characters. */
277 printf (" %-6s", _("?????"));
280 printf (" %s", time_string (utmp_ent));
282 #ifdef HAVE_UT_HOST
283 if (include_where && utmp_ent->ut_host[0])
285 char ut_host[sizeof (utmp_ent->ut_host) + 1];
286 char *host = NULL;
287 char *display = NULL;
289 /* Copy the host name into UT_HOST, and ensure it's nul terminated. */
290 strncpy (ut_host, utmp_ent->ut_host, (int) sizeof (utmp_ent->ut_host));
291 ut_host[sizeof (utmp_ent->ut_host)] = '\0';
293 /* Look for an X display. */
294 display = strchr (ut_host, ':');
295 if (display)
296 *display++ = '\0';
298 if (*ut_host)
299 /* See if we can canonicalize it. */
300 host = canon_host (ut_host);
301 if ( ! host)
302 host = ut_host;
304 if (display)
305 printf (" %s:%s", host, display);
306 else
307 printf (" %s", host);
309 if (host != ut_host)
310 free (host);
312 #endif
314 putchar ('\n');
317 /* Display a verbose line of information about UTMP_ENT. */
319 static void
320 print_long_entry (const char name[])
322 struct passwd *pw;
324 pw = getpwnam (name);
326 printf (_("Login name: "));
327 printf ("%-28s", name);
329 printf (_("In real life: "));
330 if (pw == NULL)
332 /* TRANSLATORS: Real name is unknown; no hard limit. */
333 printf (" %s", _("???\n"));
334 return;
336 else
338 char *const comma = strchr (pw->pw_gecos, ',');
339 char *result;
341 if (comma)
342 *comma = '\0';
344 result = create_fullname (pw->pw_gecos, pw->pw_name);
345 printf (" %s", result);
346 free (result);
349 putchar ('\n');
351 if (include_home_and_shell)
353 printf (_("Directory: "));
354 printf ("%-29s", pw->pw_dir);
355 printf (_("Shell: "));
356 printf (" %s", pw->pw_shell);
357 putchar ('\n');
360 if (include_project)
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);
368 strcpy (project, pw->pw_dir);
369 strcat (project, baseproject);
371 stream = fopen (project, "r");
372 if (stream)
374 size_t bytes;
376 printf (_("Project: "));
378 while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0)
379 fwrite (buf, 1, bytes, stdout);
380 fclose (stream);
383 free (project);
386 if (include_plan)
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);
394 strcpy (plan, pw->pw_dir);
395 strcat (plan, baseplan);
397 stream = fopen (plan, "r");
398 if (stream)
400 size_t bytes;
402 printf (_("Plan:\n"));
404 while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0)
405 fwrite (buf, 1, bytes, stdout);
406 fclose (stream);
409 free (plan);
412 putchar ('\n');
415 /* Print the username of each valid entry and the number of valid entries
416 in UTMP_BUF, which should have N elements. */
418 static void
419 print_heading (void)
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');
435 /* Display UTMP_BUF, which should have N entries. */
437 static void
438 scan_entries (size_t n, const STRUCT_UTMP *utmp_buf,
439 const int argc_names, char *const argv_names[])
441 if (hard_locale (LC_TIME))
443 time_format = "%Y-%m-%d %H:%M";
444 time_format_width = 4 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2;
446 else
448 time_format = "%b %e %H:%M";
449 time_format_width = 3 + 1 + 2 + 1 + 2 + 1 + 2;
452 if (include_heading)
453 print_heading ();
455 while (n--)
457 if (IS_USER_PROCESS (utmp_buf))
459 if (argc_names)
461 int i;
463 for (i = 0; i < argc_names; i++)
464 if (strncmp (UT_USER (utmp_buf), argv_names[i], UT_USER_SIZE)
465 == 0)
467 print_entry (utmp_buf);
468 break;
471 else
472 print_entry (utmp_buf);
474 utmp_buf++;
478 /* Display a list of who is on the system, according to utmp file FILENAME. */
480 static void
481 short_pinky (const char *filename,
482 const int argc_names, char *const argv_names[])
484 size_t n_users;
485 STRUCT_UTMP *utmp_buf;
487 if (read_utmp (filename, &n_users, &utmp_buf, 0) != 0)
488 error (EXIT_FAILURE, errno, "%s", filename);
490 scan_entries (n_users, utmp_buf, argc_names, argv_names);
493 static void
494 long_pinky (const int argc_names, char *const argv_names[])
496 int i;
498 for (i = 0; i < argc_names; i++)
499 print_long_entry (argv_names[i]);
502 void
503 usage (int status)
505 if (status != EXIT_SUCCESS)
506 fprintf (stderr, _("Try `%s --help' for more information.\n"),
507 program_name);
508 else
510 printf (_("Usage: %s [OPTION]... [USER]...\n"), program_name);
511 fputs (_("\
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 (_("\
530 A lightweight `finger' program; print user information.\n\
531 The utmp file will be %s.\n\
532 "), UTMP_FILE);
533 emit_bug_reporting_address ();
535 exit (status);
539 main (int argc, char **argv)
541 int optc;
542 int n_users;
544 initialize_main (&argc, &argv);
545 set_program_name (argv[0]);
546 setlocale (LC_ALL, "");
547 bindtextdomain (PACKAGE, LOCALEDIR);
548 textdomain (PACKAGE);
550 atexit (close_stdout);
552 while ((optc = getopt_long (argc, argv, "sfwiqbhlp", longopts, NULL)) != -1)
554 switch (optc)
556 case 's':
557 do_short_format = true;
558 break;
560 case 'l':
561 do_short_format = false;
562 break;
564 case 'f':
565 include_heading = false;
566 break;
568 case 'w':
569 include_fullname = false;
570 break;
572 case 'i':
573 include_fullname = false;
574 #ifdef HAVE_UT_HOST
575 include_where = false;
576 #endif
577 break;
579 case 'q':
580 include_fullname = false;
581 #ifdef HAVE_UT_HOST
582 include_where = false;
583 #endif
584 include_idle = false;
585 break;
587 case 'h':
588 include_project = false;
589 break;
591 case 'p':
592 include_plan = false;
593 break;
595 case 'b':
596 include_home_and_shell = false;
597 break;
599 case_GETOPT_HELP_CHAR;
601 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
603 default:
604 usage (EXIT_FAILURE);
608 n_users = argc - optind;
610 if (!do_short_format && n_users == 0)
612 error (0, 0, _("no username specified; at least one must be\
613 specified when using -l"));
614 usage (EXIT_FAILURE);
617 if (do_short_format)
618 short_pinky (UTMP_FILE, n_users, argv + optind);
619 else
620 long_pinky (n_users, argv + optind);
622 exit (EXIT_SUCCESS);