pinky: fix string size calculation
[coreutils.git] / src / pinky.c
blob82b2d842e5d7ffe19c8bc420969d0a05c8cc07c6
1 /* GNU's pinky.
2 Copyright (C) 1992-2023 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 <https://www.gnu.org/licenses/>. */
17 /* Created by hacking who.c by Kaveh Ghazi ghazi@caip.rutgers.edu */
19 #include <config.h>
20 #include <ctype.h>
21 #include <getopt.h>
22 #include <pwd.h>
23 #include <stdckdint.h>
24 #include <stdio.h>
26 #include <sys/types.h>
27 #include "system.h"
29 #include "canon-host.h"
30 #include "hard-locale.h"
31 #include "readutmp.h"
33 /* The official name of this program (e.g., no 'g' prefix). */
34 #define PROGRAM_NAME "pinky"
36 #define AUTHORS \
37 proper_name ("Joseph Arceneaux"), \
38 proper_name ("David MacKenzie"), \
39 proper_name ("Kaveh Ghazi")
41 /* If true, display the hours:minutes since each user has touched
42 the keyboard, or blank if within the last minute, or days followed
43 by a 'd' if not within the last day. */
44 static bool include_idle = true;
46 /* If true, display a line at the top describing each field. */
47 static bool include_heading = true;
49 /* if true, display the user's full name from pw_gecos. */
50 static bool include_fullname = true;
52 /* if true, display the user's ~/.project file when doing long format. */
53 static bool include_project = true;
55 /* if true, display the user's ~/.plan file when doing long format. */
56 static bool include_plan = true;
58 /* if true, display the user's home directory and shell
59 when doing long format. */
60 static bool include_home_and_shell = true;
62 /* if true, use the "short" output format. */
63 static bool do_short_format = true;
65 /* if true, display the ut_host field. */
66 #if HAVE_STRUCT_XTMP_UT_HOST
67 static bool include_where = true;
68 #endif
70 /* The strftime format to use for login times, and its expected
71 output width. */
72 static char const *time_format;
73 static int time_format_width;
75 static struct option const longopts[] =
77 {GETOPT_HELP_OPTION_DECL},
78 {GETOPT_VERSION_OPTION_DECL},
79 {nullptr, 0, nullptr, 0}
82 /* Count and return the number of ampersands in STR. */
84 ATTRIBUTE_PURE
85 static idx_t
86 count_ampersands (char const *str)
88 idx_t count = 0;
89 for (; *str; str++)
90 count += *str == '&';
91 return count;
94 /* Create a string (via xmalloc) which contains a full name by substituting
95 for each ampersand in GECOS_NAME the USER_NAME string with its first
96 character capitalized. The caller must ensure that GECOS_NAME contains
97 no ','s. The caller also is responsible for free'ing the return value of
98 this function. */
100 static char *
101 create_fullname (char const *gecos_name, char const *user_name)
103 idx_t rsize = strlen (gecos_name) + 1;
104 char *result;
105 char *r;
106 idx_t ampersands = count_ampersands (gecos_name);
108 if (ampersands != 0)
110 idx_t ulen = strlen (user_name);
111 ptrdiff_t product;
112 if (ckd_mul (&product, ulen - 1, ampersands)
113 || ckd_add (&rsize, rsize, product))
114 xalloc_die ();
117 r = result = xmalloc (rsize);
119 while (*gecos_name)
121 if (*gecos_name == '&')
123 char const *uname = user_name;
124 if (islower (to_uchar (*uname)))
125 *r++ = toupper (to_uchar (*uname++));
126 while (*uname)
127 *r++ = *uname++;
129 else
131 *r++ = *gecos_name;
134 gecos_name++;
136 *r = 0;
138 return result;
141 /* Return a string representing the time between WHEN and the time
142 that this function is first run. */
144 static char const *
145 idle_string (time_t when)
147 static time_t now = 0;
148 static char buf[INT_STRLEN_BOUND (intmax_t) + sizeof "d"];
149 time_t seconds_idle;
151 if (now == 0)
152 time (&now);
154 seconds_idle = now - when;
155 if (seconds_idle < 60) /* One minute. */
156 return " ";
157 if (seconds_idle < (24 * 60 * 60)) /* One day. */
159 int hours = seconds_idle / (60 * 60);
160 int minutes = (seconds_idle % (60 * 60)) / 60;
161 sprintf (buf, "%02d:%02d", hours, minutes);
163 else
165 intmax_t days = seconds_idle / (24 * 60 * 60);
166 sprintf (buf, "%jdd", days);
168 return buf;
171 /* Return a time string. */
172 static char const *
173 time_string (struct gl_utmp const *utmp_ent)
175 static char buf[INT_STRLEN_BOUND (intmax_t) + sizeof "-%m-%d %H:%M"];
176 struct tm *tmp = localtime (&utmp_ent->ut_ts.tv_sec);
178 if (tmp)
180 strftime (buf, sizeof buf, time_format, tmp);
181 return buf;
183 else
184 return timetostr (utmp_ent->ut_ts.tv_sec, buf);
187 /* Display a line of information about UTMP_ENT. */
189 static void
190 print_entry (struct gl_utmp const *utmp_ent)
192 struct stat stats;
193 time_t last_change;
194 char mesg;
196 /* If ut_line contains a space, the device name starts after the space. */
197 char *line = utmp_ent->ut_line;
198 char *space = strchr (line, ' ');
199 line = space ? space + 1 : line;
201 int dirfd;
202 if (IS_ABSOLUTE_FILE_NAME (line))
203 dirfd = AT_FDCWD;
204 else
206 static int dev_dirfd;
207 if (!dev_dirfd)
209 dev_dirfd = open ("/dev", O_PATHSEARCH | O_DIRECTORY);
210 if (dev_dirfd < 0)
211 dev_dirfd = AT_FDCWD - 1;
213 dirfd = dev_dirfd;
216 if (AT_FDCWD <= dirfd && fstatat (dirfd, line, &stats, 0) == 0)
218 mesg = (stats.st_mode & S_IWGRP) ? ' ' : '*';
219 last_change = stats.st_atime;
221 else
223 mesg = '?';
224 last_change = 0;
227 char *ut_user = utmp_ent->ut_user;
228 if (strnlen (ut_user, 8) < 8)
229 printf ("%-8s", ut_user);
230 else
231 fputs (ut_user, stdout);
233 if (include_fullname)
235 struct passwd *pw = getpwnam (ut_user);
236 if (pw == nullptr)
237 /* TRANSLATORS: Real name is unknown; at most 19 characters. */
238 printf (" %19s", _(" ???"));
239 else
241 char *const comma = strchr (pw->pw_gecos, ',');
242 char *result;
244 if (comma)
245 *comma = '\0';
247 result = create_fullname (pw->pw_gecos, pw->pw_name);
248 printf (" %-19.19s", result);
249 free (result);
253 fputc (' ', stdout);
254 fputc (mesg, stdout);
255 if (strnlen (utmp_ent->ut_line, 8) < 8)
256 printf ("%-8s", utmp_ent->ut_line);
257 else
258 fputs (utmp_ent->ut_line, stdout);
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_STRUCT_XTMP_UT_HOST
272 if (include_where && utmp_ent->ut_host[0])
274 char *host = nullptr;
275 char *display = nullptr;
276 char *ut_host = utmp_ent->ut_host;
278 /* Look for an X display. */
279 display = strchr (ut_host, ':');
280 if (display)
281 *display++ = '\0';
283 if (*ut_host)
284 /* See if we can canonicalize it. */
285 host = canon_host (ut_host);
286 if ( ! host)
287 host = ut_host;
289 fputc (' ', stdout);
290 fputs (host, stdout);
291 if (display)
293 fputc (':', stdout);
294 fputs (display, stdout);
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 == nullptr)
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 char const *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 char const *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_STRUCT_XTMP_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 (idx_t n, struct gl_utmp const *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 for (int i = 0; i < argc_names; i++)
446 if (STREQ (utmp_buf->ut_user, argv_names[i]))
448 print_entry (utmp_buf);
449 break;
452 else
453 print_entry (utmp_buf);
455 utmp_buf++;
459 /* Display a list of who is on the system, according to utmp file FILENAME. */
461 static void
462 short_pinky (char const *filename,
463 const int argc_names, char *const argv_names[])
465 idx_t n_users;
466 struct gl_utmp *utmp_buf;
467 if (read_utmp (filename, &n_users, &utmp_buf, READ_UTMP_USER_PROCESS) != 0)
468 error (EXIT_FAILURE, errno, "%s", quotef (filename));
470 scan_entries (n_users, utmp_buf, argc_names, argv_names);
471 exit (EXIT_SUCCESS);
474 static void
475 long_pinky (const int argc_names, char *const argv_names[])
477 for (int i = 0; i < argc_names; i++)
478 print_long_entry (argv_names[i]);
481 void
482 usage (int status)
484 if (status != EXIT_SUCCESS)
485 emit_try_help ();
486 else
488 printf (_("Usage: %s [OPTION]... [USER]...\n"), program_name);
489 fputs (_("\
491 -l produce long format output for the specified USERs\n\
492 -b omit the user's home directory and shell in long format\n\
493 -h omit the user's project file in long format\n\
494 -p omit the user's plan file in long format\n\
495 -s do short format output, this is the default\n\
496 "), stdout);
497 fputs (_("\
498 -f omit the line of column headings in short format\n\
499 -w omit the user's full name in short format\n\
500 -i omit the user's full name and remote host in short format\n\
501 -q omit the user's full name, remote host and idle time\n\
502 in short format\n\
503 "), stdout);
504 fputs (HELP_OPTION_DESCRIPTION, stdout);
505 fputs (VERSION_OPTION_DESCRIPTION, stdout);
506 printf (_("\
508 A lightweight 'finger' program; print user information.\n\
509 The utmp file will be %s.\n\
510 "), UTMP_FILE);
511 emit_ancillary_info (PROGRAM_NAME);
513 exit (status);
517 main (int argc, char **argv)
519 int optc;
520 int n_users;
522 initialize_main (&argc, &argv);
523 set_program_name (argv[0]);
524 setlocale (LC_ALL, "");
525 bindtextdomain (PACKAGE, LOCALEDIR);
526 textdomain (PACKAGE);
528 atexit (close_stdout);
530 while ((optc = getopt_long (argc, argv, "sfwiqbhlp", longopts, nullptr))
531 != -1)
533 switch (optc)
535 case 's':
536 do_short_format = true;
537 break;
539 case 'l':
540 do_short_format = false;
541 break;
543 case 'f':
544 include_heading = false;
545 break;
547 case 'w':
548 include_fullname = false;
549 break;
551 case 'i':
552 include_fullname = false;
553 #ifdef HAVE_STRUCT_XTMP_UT_HOST
554 include_where = false;
555 #endif
556 break;
558 case 'q':
559 include_fullname = false;
560 #ifdef HAVE_STRUCT_XTMP_UT_HOST
561 include_where = false;
562 #endif
563 include_idle = false;
564 break;
566 case 'h':
567 include_project = false;
568 break;
570 case 'p':
571 include_plan = false;
572 break;
574 case 'b':
575 include_home_and_shell = false;
576 break;
578 case_GETOPT_HELP_CHAR;
580 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
582 default:
583 usage (EXIT_FAILURE);
587 n_users = argc - optind;
589 if (!do_short_format && n_users == 0)
591 error (0, 0, _("no username specified; at least one must be\
592 specified when using -l"));
593 usage (EXIT_FAILURE);
596 if (do_short_format)
597 short_pinky (UTMP_FILE, n_users, argv + optind);
598 else
599 long_pinky (n_users, argv + optind);
601 return EXIT_SUCCESS;