maint: avoid sc_tight_scope failure in sort.c
[coreutils.git] / src / pinky.c
blob0843efd5537eb8bb570776b18c435be7723150c5
1 /* GNU's pinky.
2 Copyright (C) 1992-2024 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 <stdio.h>
25 #include <sys/types.h>
26 #include "system.h"
28 #include "canon-host.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 /* If true, display the hours:minutes since each user has touched
41 the keyboard, or blank if within the last minute, or days followed
42 by a 'd' if not within the last day. */
43 static bool include_idle = true;
45 /* If true, display a line at the top describing each field. */
46 static bool include_heading = true;
48 /* if true, display the user's full name from pw_gecos. */
49 static bool include_fullname = true;
51 /* if true, display the user's ~/.project file when doing long format. */
52 static bool include_project = true;
54 /* if true, display the user's ~/.plan file when doing long format. */
55 static bool include_plan = true;
57 /* if true, display the user's home directory and shell
58 when doing long format. */
59 static bool include_home_and_shell = true;
61 /* if true, use the "short" output format. */
62 static bool do_short_format = true;
64 /* if true, display the ut_host field. */
65 #if HAVE_STRUCT_XTMP_UT_HOST
66 static bool include_where = true;
67 #endif
69 /* The strftime format to use for login times, and its expected
70 output width. */
71 static char const *time_format;
72 static int time_format_width;
74 static struct option const longopts[] =
76 {GETOPT_HELP_OPTION_DECL},
77 {GETOPT_VERSION_OPTION_DECL},
78 {nullptr, 0, nullptr, 0}
81 /* Count and return the number of ampersands in STR. */
83 ATTRIBUTE_PURE
84 static idx_t
85 count_ampersands (char const *str)
87 idx_t count = 0;
88 for (; *str; str++)
89 count += *str == '&';
90 return count;
93 /* Create a string (via xmalloc) which contains a full name by substituting
94 for each ampersand in GECOS_NAME the USER_NAME string with its first
95 character capitalized. The caller must ensure that GECOS_NAME contains
96 no ','s. The caller also is responsible for free'ing the return value of
97 this function. */
99 static char *
100 create_fullname (char const *gecos_name, char const *user_name)
102 idx_t rsize = strlen (gecos_name) + 1;
103 char *result;
104 char *r;
105 idx_t ampersands = count_ampersands (gecos_name);
107 if (ampersands != 0)
109 idx_t ulen = strlen (user_name);
110 ptrdiff_t product;
111 if (ckd_mul (&product, ulen - 1, ampersands)
112 || ckd_add (&rsize, rsize, product))
113 xalloc_die ();
116 r = result = xmalloc (rsize);
118 while (*gecos_name)
120 if (*gecos_name == '&')
122 char const *uname = user_name;
123 if (islower (to_uchar (*uname)))
124 *r++ = toupper (to_uchar (*uname++));
125 while (*uname)
126 *r++ = *uname++;
128 else
130 *r++ = *gecos_name;
133 gecos_name++;
135 *r = 0;
137 return result;
140 /* Return a string representing the time between WHEN and the time
141 that this function is first run. */
143 static char const *
144 idle_string (time_t when)
146 static time_t now = 0;
147 static char buf[INT_STRLEN_BOUND (intmax_t) + sizeof "d"];
148 time_t seconds_idle;
150 if (now == 0)
151 time (&now);
153 seconds_idle = now - when;
154 if (seconds_idle < 60) /* One minute. */
155 return " ";
156 if (seconds_idle < (24 * 60 * 60)) /* One day. */
158 int hours = seconds_idle / (60 * 60);
159 int minutes = (seconds_idle % (60 * 60)) / 60;
160 sprintf (buf, "%02d:%02d", hours, minutes);
162 else
164 intmax_t days = seconds_idle / (24 * 60 * 60);
165 sprintf (buf, "%jdd", days);
167 return buf;
170 /* Return a time string. */
171 static char const *
172 time_string (struct gl_utmp const *utmp_ent)
174 static char buf[INT_STRLEN_BOUND (intmax_t) + sizeof "-%m-%d %H:%M"];
175 struct tm *tmp = localtime (&utmp_ent->ut_ts.tv_sec);
177 if (tmp)
179 strftime (buf, sizeof buf, time_format, tmp);
180 return buf;
182 else
183 return timetostr (utmp_ent->ut_ts.tv_sec, buf);
186 /* Display a line of information about UTMP_ENT. */
188 static void
189 print_entry (struct gl_utmp const *utmp_ent)
191 struct stat stats;
192 time_t last_change;
193 char mesg;
195 /* If ut_line contains a space, the device name starts after the space. */
196 char *line = utmp_ent->ut_line;
197 char *space = strchr (line, ' ');
198 line = space ? space + 1 : line;
200 int dirfd;
201 if (IS_ABSOLUTE_FILE_NAME (line))
202 dirfd = AT_FDCWD;
203 else
205 static int dev_dirfd;
206 if (!dev_dirfd)
208 dev_dirfd = open ("/dev", O_PATHSEARCH | O_DIRECTORY);
209 if (dev_dirfd < 0)
210 dev_dirfd = AT_FDCWD - 1;
212 dirfd = dev_dirfd;
215 if (AT_FDCWD <= dirfd && fstatat (dirfd, line, &stats, 0) == 0)
217 mesg = (stats.st_mode & S_IWGRP) ? ' ' : '*';
218 last_change = stats.st_atime;
220 else
222 mesg = '?';
223 last_change = 0;
226 char *ut_user = utmp_ent->ut_user;
227 if (strnlen (ut_user, 8) < 8)
228 printf ("%-8s", ut_user);
229 else
230 fputs (ut_user, stdout);
232 if (include_fullname)
234 struct passwd *pw = getpwnam (ut_user);
235 if (pw == nullptr)
236 /* TRANSLATORS: Real name is unknown; at most 19 characters. */
237 printf (" %19s", _(" ???"));
238 else
240 char *const comma = strchr (pw->pw_gecos, ',');
241 char *result;
243 if (comma)
244 *comma = '\0';
246 result = create_fullname (pw->pw_gecos, pw->pw_name);
247 printf (" %-19.19s", result);
248 free (result);
252 fputc (' ', stdout);
253 fputc (mesg, stdout);
254 if (strnlen (utmp_ent->ut_line, 8) < 8)
255 printf ("%-8s", utmp_ent->ut_line);
256 else
257 fputs (utmp_ent->ut_line, stdout);
259 if (include_idle)
261 if (last_change)
262 printf (" %-6s", idle_string (last_change));
263 else
264 /* TRANSLATORS: Idle time is unknown; at most 5 characters. */
265 printf (" %-6s", _("?????"));
268 printf (" %s", time_string (utmp_ent));
270 #ifdef HAVE_STRUCT_XTMP_UT_HOST
271 if (include_where && utmp_ent->ut_host[0])
273 char *host = nullptr;
274 char *display = nullptr;
275 char *ut_host = utmp_ent->ut_host;
277 /* Look for an X display. */
278 display = strchr (ut_host, ':');
279 if (display)
280 *display++ = '\0';
282 if (*ut_host)
283 /* See if we can canonicalize it. */
284 host = canon_host (ut_host);
285 if ( ! host)
286 host = ut_host;
288 fputc (' ', stdout);
289 fputs (host, stdout);
290 if (display)
292 fputc (':', stdout);
293 fputs (display, stdout);
296 if (host != ut_host)
297 free (host);
299 #endif
301 putchar ('\n');
304 /* Display a verbose line of information about UTMP_ENT. */
306 static void
307 print_long_entry (const char name[])
309 struct passwd *pw;
311 pw = getpwnam (name);
313 printf (_("Login name: "));
314 printf ("%-28s", name);
316 printf (_("In real life: "));
317 if (pw == nullptr)
319 /* TRANSLATORS: Real name is unknown; no hard limit. */
320 printf (" %s", _("???\n"));
321 return;
323 else
325 char *const comma = strchr (pw->pw_gecos, ',');
326 char *result;
328 if (comma)
329 *comma = '\0';
331 result = create_fullname (pw->pw_gecos, pw->pw_name);
332 printf (" %s", result);
333 free (result);
336 putchar ('\n');
338 if (include_home_and_shell)
340 printf (_("Directory: "));
341 printf ("%-29s", pw->pw_dir);
342 printf (_("Shell: "));
343 printf (" %s", pw->pw_shell);
344 putchar ('\n');
347 if (include_project)
349 FILE *stream;
350 char buf[1024];
351 char const *const baseproject = "/.project";
352 char *const project =
353 xmalloc (strlen (pw->pw_dir) + strlen (baseproject) + 1);
354 stpcpy (stpcpy (project, pw->pw_dir), baseproject);
356 stream = fopen (project, "r");
357 if (stream)
359 size_t bytes;
361 printf (_("Project: "));
363 while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0)
364 fwrite (buf, 1, bytes, stdout);
365 fclose (stream);
368 free (project);
371 if (include_plan)
373 FILE *stream;
374 char buf[1024];
375 char const *const baseplan = "/.plan";
376 char *const plan =
377 xmalloc (strlen (pw->pw_dir) + strlen (baseplan) + 1);
378 stpcpy (stpcpy (plan, pw->pw_dir), baseplan);
380 stream = fopen (plan, "r");
381 if (stream)
383 size_t bytes;
385 printf (_("Plan:\n"));
387 while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0)
388 fwrite (buf, 1, bytes, stdout);
389 fclose (stream);
392 free (plan);
395 putchar ('\n');
398 /* Print the username of each valid entry and the number of valid entries
399 in UTMP_BUF, which should have N elements. */
401 static void
402 print_heading (void)
404 printf ("%-8s", _("Login"));
405 if (include_fullname)
406 printf (" %-19s", _("Name"));
407 printf (" %-9s", _(" TTY"));
408 if (include_idle)
409 printf (" %-6s", _("Idle"));
410 printf (" %-*s", time_format_width, _("When"));
411 #ifdef HAVE_STRUCT_XTMP_UT_HOST
412 if (include_where)
413 printf (" %s", _("Where"));
414 #endif
415 putchar ('\n');
418 /* Display UTMP_BUF, which should have N entries. */
420 static void
421 scan_entries (idx_t n, struct gl_utmp const *utmp_buf,
422 const int argc_names, char *const argv_names[])
424 if (hard_locale (LC_TIME))
426 time_format = "%Y-%m-%d %H:%M";
427 time_format_width = 4 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2;
429 else
431 time_format = "%b %e %H:%M";
432 time_format_width = 3 + 1 + 2 + 1 + 2 + 1 + 2;
435 if (include_heading)
436 print_heading ();
438 while (n--)
440 if (IS_USER_PROCESS (utmp_buf))
442 if (argc_names)
444 for (int i = 0; i < argc_names; i++)
445 if (STREQ (utmp_buf->ut_user, argv_names[i]))
447 print_entry (utmp_buf);
448 break;
451 else
452 print_entry (utmp_buf);
454 utmp_buf++;
458 /* Display a list of who is on the system, according to utmp file FILENAME. */
460 static void
461 short_pinky (char const *filename,
462 const int argc_names, char *const argv_names[])
464 idx_t n_users;
465 struct gl_utmp *utmp_buf;
466 if (read_utmp (filename, &n_users, &utmp_buf, READ_UTMP_USER_PROCESS) != 0)
467 error (EXIT_FAILURE, errno, "%s", quotef (filename));
469 scan_entries (n_users, utmp_buf, argc_names, argv_names);
470 exit (EXIT_SUCCESS);
473 static void
474 long_pinky (const int argc_names, char *const argv_names[])
476 for (int i = 0; i < argc_names; i++)
477 print_long_entry (argv_names[i]);
480 void
481 usage (int status)
483 if (status != EXIT_SUCCESS)
484 emit_try_help ();
485 else
487 printf (_("Usage: %s [OPTION]... [USER]...\n"), program_name);
488 fputs (_("\
490 -l produce long format output for the specified USERs\n\
491 -b omit the user's home directory and shell in long format\n\
492 -h omit the user's project file in long format\n\
493 -p omit the user's plan file in long format\n\
494 -s do short format output, this is the default\n\
495 "), stdout);
496 fputs (_("\
497 -f omit the line of column headings in short format\n\
498 -w omit the user's full name in short format\n\
499 -i omit the user's full name and remote host in short format\n\
500 -q omit the user's full name, remote host and idle time\n\
501 in short format\n\
502 "), stdout);
503 fputs (HELP_OPTION_DESCRIPTION, stdout);
504 fputs (VERSION_OPTION_DESCRIPTION, stdout);
505 printf (_("\
507 A lightweight 'finger' program; print user information.\n\
508 The utmp file will be %s.\n\
509 "), UTMP_FILE);
510 emit_ancillary_info (PROGRAM_NAME);
512 exit (status);
516 main (int argc, char **argv)
518 int optc;
519 int n_users;
521 initialize_main (&argc, &argv);
522 set_program_name (argv[0]);
523 setlocale (LC_ALL, "");
524 bindtextdomain (PACKAGE, LOCALEDIR);
525 textdomain (PACKAGE);
527 atexit (close_stdout);
529 while ((optc = getopt_long (argc, argv, "sfwiqbhlp", longopts, nullptr))
530 != -1)
532 switch (optc)
534 case 's':
535 do_short_format = true;
536 break;
538 case 'l':
539 do_short_format = false;
540 break;
542 case 'f':
543 include_heading = false;
544 break;
546 case 'w':
547 include_fullname = false;
548 break;
550 case 'i':
551 include_fullname = false;
552 #ifdef HAVE_STRUCT_XTMP_UT_HOST
553 include_where = false;
554 #endif
555 break;
557 case 'q':
558 include_fullname = false;
559 #ifdef HAVE_STRUCT_XTMP_UT_HOST
560 include_where = false;
561 #endif
562 include_idle = false;
563 break;
565 case 'h':
566 include_project = false;
567 break;
569 case 'p':
570 include_plan = false;
571 break;
573 case 'b':
574 include_home_and_shell = false;
575 break;
577 case_GETOPT_HELP_CHAR;
579 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
581 default:
582 usage (EXIT_FAILURE);
586 n_users = argc - optind;
588 if (!do_short_format && n_users == 0)
590 error (0, 0, _("no username specified; at least one must be\
591 specified when using -l"));
592 usage (EXIT_FAILURE);
595 if (do_short_format)
596 short_pinky (UTMP_FILE, n_users, argv + optind);
597 else
598 long_pinky (n_users, argv + optind);
600 return EXIT_SUCCESS;