]> git.ipfire.org Git - thirdparty/util-linux.git/blob - login-utils/last.c
Merge branch 'PR/ipcs-fix-counters' of github.com:karelzak/util-linux-work
[thirdparty/util-linux.git] / login-utils / last.c
1 /*
2 * last(1) from sysvinit project, merged into util-linux in Aug 2013.
3 *
4 * Copyright (C) 1991-2004 Miquel van Smoorenburg.
5 * Copyright (C) 2013 Ondrej Oprala <ooprala@redhat.com>
6 * Karel Zak <kzak@redhat.com>
7 *
8 * Re-implementation of the 'last' command, this time for Linux. Yes I know
9 * there is BSD last, but I just felt like writing this. No thanks :-). Also,
10 * this version gives lots more info (especially with -x)
11 *
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 */
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <time.h>
31 #include <stdio.h>
32 #include <ctype.h>
33 #include <utmpx.h>
34 #include <pwd.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <string.h>
38 #include <signal.h>
39 #include <getopt.h>
40 #include <netinet/in.h>
41 #include <netdb.h>
42 #include <arpa/inet.h>
43 #include <libgen.h>
44
45 #include "c.h"
46 #include "nls.h"
47 #include "optutils.h"
48 #include "pathnames.h"
49 #include "xalloc.h"
50 #include "closestream.h"
51 #include "carefulputc.h"
52 #include "strutils.h"
53 #include "timeutils.h"
54 #include "monotonic.h"
55 #include "fileutils.h"
56
57 #ifdef FUZZ_TARGET
58 #include "fuzz.h"
59 #endif
60
61 #ifndef SHUTDOWN_TIME
62 # define SHUTDOWN_TIME 254
63 #endif
64
65 #ifndef LAST_LOGIN_LEN
66 # define LAST_LOGIN_LEN 8
67 #endif
68
69 #ifndef LAST_DOMAIN_LEN
70 # define LAST_DOMAIN_LEN 16
71 #endif
72
73 #ifndef LAST_TIMESTAMP_LEN
74 # define LAST_TIMESTAMP_LEN 32
75 #endif
76
77 #define UCHUNKSIZE 16384 /* How much we read at once. */
78
79 struct last_control {
80 unsigned int lastb :1, /* Is this command 'lastb' */
81 extended :1, /* Lots of info */
82 showhost :1, /* Show hostname */
83 altlist :1, /* Hostname at the end */
84 usedns :1, /* Use DNS to lookup the hostname */
85 useip :1; /* Print IP address in number format */
86
87 unsigned int name_len; /* Number of login name characters to print */
88 unsigned int domain_len; /* Number of domain name characters to print */
89 unsigned int maxrecs; /* Maximum number of records to list */
90
91 char **show; /* Match search list */
92
93 struct timeval boot_time; /* system boot time */
94 time_t since; /* at what time to start displaying the file */
95 time_t until; /* at what time to stop displaying the file */
96 time_t present; /* who where present at time_t */
97 unsigned int time_fmt; /* time format */
98 char separator; /* output separator */
99 };
100
101 /* Double linked list of struct utmp's */
102 struct utmplist {
103 struct utmpx ut;
104 struct utmplist *next;
105 struct utmplist *prev;
106 };
107
108 /* Types of listing */
109 enum {
110 R_CRASH = 1, /* No logout record, system boot in between */
111 R_DOWN, /* System brought down in decent way */
112 R_NORMAL, /* Normal */
113 R_NOW, /* Still logged in */
114 R_REBOOT, /* Reboot record. */
115 R_REBOOT_CRASH, /* Reboot record without matching shutdown */
116 R_PHANTOM, /* No logout record but session is stale. */
117 R_TIMECHANGE /* NEW_TIME or OLD_TIME */
118 };
119
120 enum {
121 LAST_TIMEFTM_NONE = 0,
122 LAST_TIMEFTM_SHORT,
123 LAST_TIMEFTM_CTIME,
124 LAST_TIMEFTM_ISO8601,
125
126 LAST_TIMEFTM_HHMM, /* non-public */
127 };
128
129 struct last_timefmt {
130 const char *name;
131 int in_len; /* log-in */
132 int in_fmt;
133 int out_len; /* log-out */
134 int out_fmt;
135 };
136
137 static struct last_timefmt timefmts[] = {
138 [LAST_TIMEFTM_NONE] = { .name = "notime" },
139 [LAST_TIMEFTM_SHORT] = {
140 .name = "short",
141 .in_len = 16,
142 .out_len = 7,
143 .in_fmt = LAST_TIMEFTM_CTIME,
144 .out_fmt = LAST_TIMEFTM_HHMM
145 },
146 [LAST_TIMEFTM_CTIME] = {
147 .name = "full",
148 .in_len = 24,
149 .out_len = 26,
150 .in_fmt = LAST_TIMEFTM_CTIME,
151 .out_fmt = LAST_TIMEFTM_CTIME
152 },
153 [LAST_TIMEFTM_ISO8601] = {
154 .name = "iso",
155 .in_len = 25,
156 .out_len = 27,
157 .in_fmt = LAST_TIMEFTM_ISO8601,
158 .out_fmt = LAST_TIMEFTM_ISO8601
159 }
160 };
161
162 /* Global variables */
163 static unsigned int recsdone; /* Number of records listed */
164 static time_t lastdate; /* Last date we've seen */
165 static time_t currentdate; /* date when we started processing the file */
166
167 #ifndef FUZZ_TARGET
168 /* --time-format=option parser */
169 static int which_time_format(const char *s)
170 {
171 size_t i;
172
173 for (i = 0; i < ARRAY_SIZE(timefmts); i++) {
174 if (strcmp(timefmts[i].name, s) == 0)
175 return i;
176 }
177 errx(EXIT_FAILURE, _("unknown time format: %s"), s);
178 }
179 #endif
180
181 /*
182 * Read one utmp entry, return in new format.
183 * Automatically reposition file pointer.
184 */
185 static int uread(FILE *fp, struct utmpx *u, int *quit, const char *filename)
186 {
187 static int utsize;
188 static char buf[UCHUNKSIZE];
189 char tmp[1024];
190 static off_t fpos;
191 static int bpos;
192 off_t o;
193
194 if (quit == NULL && u != NULL) {
195 /*
196 * Normal read.
197 */
198 return fread(u, sizeof(struct utmpx), 1, fp);
199 }
200
201 if (u == NULL) {
202 /*
203 * Initialize and position.
204 */
205 utsize = sizeof(struct utmpx);
206 fseeko(fp, 0, SEEK_END);
207 fpos = ftello(fp);
208 if (fpos == 0)
209 return 0;
210 o = ((fpos - 1) / UCHUNKSIZE) * UCHUNKSIZE;
211 if (fseeko(fp, o, SEEK_SET) < 0) {
212 warn(_("seek on %s failed"), filename);
213 return 0;
214 }
215 bpos = (int)(fpos - o);
216 if (fread(buf, bpos, 1, fp) != 1) {
217 warn(_("cannot read %s"), filename);
218 return 0;
219 }
220 fpos = o;
221 return 1;
222 }
223
224 /*
225 * Read one struct. From the buffer if possible.
226 */
227 bpos -= utsize;
228 if (bpos >= 0) {
229 memcpy(u, buf + bpos, sizeof(struct utmpx));
230 return 1;
231 }
232
233 /*
234 * Oops we went "below" the buffer. We should be able to
235 * seek back UCHUNKSIZE bytes.
236 */
237 fpos -= UCHUNKSIZE;
238 if (fpos < 0)
239 return 0;
240
241 /*
242 * Copy whatever is left in the buffer.
243 */
244 memcpy(tmp + (-bpos), buf, utsize + bpos);
245 if (fseeko(fp, fpos, SEEK_SET) < 0) {
246 warn(_("seek on %s failed"), filename);
247 return 0;
248 }
249
250 /*
251 * Read another UCHUNKSIZE bytes.
252 */
253 if (fread(buf, UCHUNKSIZE, 1, fp) != 1) {
254 warn(_("cannot read %s"), filename);
255 return 0;
256 }
257
258 /*
259 * The end of the UCHUNKSIZE byte buffer should be the first
260 * few bytes of the current struct utmp.
261 */
262 memcpy(tmp, buf + UCHUNKSIZE + bpos, -bpos);
263 bpos += UCHUNKSIZE;
264
265 memcpy(u, tmp, sizeof(struct utmpx));
266
267 return 1;
268 }
269
270 #ifndef FUZZ_TARGET
271 /*
272 * SIGINT handler
273 */
274 static void int_handler(int sig __attribute__((unused)))
275 {
276 ul_sig_err(EXIT_FAILURE, "Interrupted");
277 }
278
279 /*
280 * SIGQUIT handler
281 */
282 static void quit_handler(int sig __attribute__((unused)))
283 {
284 ul_sig_warn("Interrupted");
285 signal(SIGQUIT, quit_handler);
286 }
287 #endif
288
289 /*
290 * Lookup a host with DNS.
291 */
292 static int dns_lookup(char *result, int size, int useip, int32_t *a)
293 {
294 struct sockaddr_in sin;
295 struct sockaddr_in6 sin6;
296 struct sockaddr *sa;
297 int salen, flags;
298 int mapped = 0;
299
300 flags = useip ? NI_NUMERICHOST : 0;
301
302 /*
303 * IPv4 or IPv6 ?
304 * 1. If last 3 4bytes are 0, must be IPv4
305 * 2. If IPv6 in IPv4, handle as IPv4
306 * 3. Anything else is IPv6
307 *
308 * Ugly.
309 */
310 if (a[0] == 0 && a[1] == 0 && a[2] == (int32_t)htonl (0xffff))
311 mapped = 1;
312
313 if (mapped || (a[1] == 0 && a[2] == 0 && a[3] == 0)) {
314 /* IPv4 */
315 sin.sin_family = AF_INET;
316 sin.sin_port = 0;
317 sin.sin_addr.s_addr = mapped ? a[3] : a[0];
318 sa = (struct sockaddr *)&sin;
319 salen = sizeof(sin);
320 } else {
321 /* IPv6 */
322 memset(&sin6, 0, sizeof(sin6));
323 sin6.sin6_family = AF_INET6;
324 sin6.sin6_port = 0;
325 memcpy(sin6.sin6_addr.s6_addr, a, 16);
326 sa = (struct sockaddr *)&sin6;
327 salen = sizeof(sin6);
328 }
329
330 return getnameinfo(sa, salen, result, size, NULL, 0, flags);
331 }
332
333 static int time_formatter(int fmt, char *dst, size_t dlen, time_t *when)
334 {
335 int ret = 0;
336
337 switch (fmt) {
338 case LAST_TIMEFTM_NONE:
339 *dst = 0;
340 break;
341 case LAST_TIMEFTM_HHMM:
342 {
343 struct tm tm;
344
345 localtime_r(when, &tm);
346 if (!snprintf(dst, dlen, "%02d:%02d", tm.tm_hour, tm.tm_min))
347 ret = -1;
348 break;
349 }
350 case LAST_TIMEFTM_CTIME:
351 {
352 char buf[CTIME_BUFSIZ];
353
354 if (!ctime_r(when, buf)) {
355 ret = -1;
356 break;
357 }
358 snprintf(dst, dlen, "%s", buf);
359 ret = rtrim_whitespace((unsigned char *) dst);
360 break;
361 }
362 case LAST_TIMEFTM_ISO8601:
363 ret = strtime_iso(when, ISO_TIMESTAMP_T, dst, dlen);
364 break;
365 default:
366 abort();
367 }
368 return ret;
369 }
370
371 /*
372 * Remove trailing spaces from a string.
373 */
374 static void trim_trailing_spaces(char *s)
375 {
376 char *p;
377
378 for (p = s; *p; ++p)
379 continue;
380 while (p > s && isspace(*--p))
381 continue;
382 if (p > s)
383 ++p;
384 *p++ = '\n';
385 *p = '\0';
386 }
387
388 /*
389 * Show one line of information on screen
390 */
391 static int list(const struct last_control *ctl, struct utmpx *p, time_t logout_time, int what)
392 {
393 time_t secs, utmp_time;
394 char logintime[LAST_TIMESTAMP_LEN];
395 char logouttime[LAST_TIMESTAMP_LEN];
396 char length[LAST_TIMESTAMP_LEN];
397 char final[512];
398 char utline[sizeof(p->ut_line) + 1];
399 char domain[256];
400 int mins, hours, days;
401 int r, len;
402 struct last_timefmt *fmt;
403
404 /*
405 * uucp and ftp have special-type entries
406 */
407 mem2strcpy(utline, p->ut_line, sizeof(p->ut_line), sizeof(utline));
408 if (strncmp(utline, "ftp", 3) == 0 && isdigit(utline[3]))
409 utline[3] = 0;
410 if (strncmp(utline, "uucp", 4) == 0 && isdigit(utline[4]))
411 utline[4] = 0;
412
413 /*
414 * Is this something we want to show?
415 */
416 if (ctl->show) {
417 char **walk;
418 for (walk = ctl->show; *walk; walk++) {
419 if (strncmp(p->ut_user, *walk, sizeof(p->ut_user)) == 0 ||
420 strcmp(utline, *walk) == 0 ||
421 (strncmp(utline, "tty", 3) == 0 &&
422 strcmp(utline + 3, *walk) == 0)) break;
423 }
424 if (*walk == NULL) return 0;
425 }
426
427 /*
428 * Calculate times
429 */
430 fmt = &timefmts[ctl->time_fmt];
431
432 utmp_time = p->ut_tv.tv_sec;
433
434 if (ctl->present) {
435 if (ctl->present < utmp_time)
436 return 0;
437 if (0 < logout_time && logout_time < ctl->present)
438 return 0;
439 }
440
441 /* log-in time */
442 if (time_formatter(fmt->in_fmt, logintime,
443 sizeof(logintime), &utmp_time) < 0)
444 errx(EXIT_FAILURE, _("preallocation size exceeded"));
445
446 /* log-out time */
447 secs = logout_time - utmp_time; /* Under strange circumstances, secs < 0 can happen */
448 mins = (secs / 60) % 60;
449 hours = (secs / 3600) % 24;
450 days = secs / 86400;
451
452 strcpy(logouttime, "- ");
453 if (time_formatter(fmt->out_fmt, logouttime + 2,
454 sizeof(logouttime) - 2, &logout_time) < 0)
455 errx(EXIT_FAILURE, _("preallocation size exceeded"));
456
457 if (logout_time == currentdate) {
458 if (ctl->time_fmt > LAST_TIMEFTM_SHORT) {
459 snprintf(logouttime, sizeof(logouttime), " still running");
460 length[0] = 0;
461 } else {
462 snprintf(logouttime, sizeof(logouttime), " still");
463 snprintf(length, sizeof(length), "running");
464 }
465 } else if (days) {
466 snprintf(length, sizeof(length), "(%d+%02d:%02d)", days, abs(hours), abs(mins)); /* hours and mins always shown as positive (w/o minus sign!) even if secs < 0 */
467 } else if (hours) {
468 snprintf(length, sizeof(length), " (%02d:%02d)", hours, abs(mins)); /* mins always shown as positive (w/o minus sign!) even if secs < 0 */
469 } else if (secs >= 0) {
470 snprintf(length, sizeof(length), " (%02d:%02d)", hours, mins);
471 } else {
472 snprintf(length, sizeof(length), " (-00:%02d)", abs(mins)); /* mins always shown as positive (w/o minus sign!) even if secs < 0 */
473 }
474
475 switch(what) {
476 case R_CRASH:
477 case R_REBOOT_CRASH:
478 snprintf(logouttime, sizeof(logouttime), "- crash");
479 break;
480 case R_DOWN:
481 snprintf(logouttime, sizeof(logouttime), "- down ");
482 break;
483 case R_NOW:
484 if (ctl->time_fmt > LAST_TIMEFTM_SHORT) {
485 snprintf(logouttime, sizeof(logouttime), " still logged in");
486 length[0] = 0;
487 } else {
488 snprintf(logouttime, sizeof(logouttime), " still");
489 snprintf(length, sizeof(length), "logged in");
490 }
491 break;
492 case R_PHANTOM:
493 if (ctl->time_fmt > LAST_TIMEFTM_SHORT) {
494 snprintf(logouttime, sizeof(logouttime), " gone - no logout");
495 length[0] = 0;
496 } else if (ctl->time_fmt == LAST_TIMEFTM_SHORT) {
497 snprintf(logouttime, sizeof(logouttime), " gone");
498 snprintf(length, sizeof(length), "- no logout");
499 } else {
500 logouttime[0] = 0;
501 snprintf(length, sizeof(length), "no logout");
502 }
503 break;
504 case R_TIMECHANGE:
505 logouttime[0] = 0;
506 length[0] = 0;
507 break;
508 case R_NORMAL:
509 case R_REBOOT:
510 break;
511 default:
512 abort();
513 }
514
515 /*
516 * Look up host with DNS if needed.
517 */
518 r = -1;
519 if (ctl->usedns || ctl->useip)
520 r = dns_lookup(domain, sizeof(domain), ctl->useip, (int32_t*)p->ut_addr_v6);
521 if (r < 0)
522 mem2strcpy(domain, p->ut_host, sizeof(p->ut_host), sizeof(domain));
523
524 if (ctl->showhost) {
525 if (!ctl->altlist) {
526 len = snprintf(final, sizeof(final),
527 "%-8.*s%c%-12.12s%c%-16.*s%c%-*.*s%c%-*.*s%c%s\n",
528 ctl->name_len, p->ut_user, ctl->separator, utline, ctl->separator,
529 ctl->domain_len, domain, ctl->separator,
530 fmt->in_len, fmt->in_len, logintime, ctl->separator, fmt->out_len, fmt->out_len,
531 logouttime, ctl->separator, length);
532 } else {
533 len = snprintf(final, sizeof(final),
534 "%-8.*s%c%-12.12s%c%-*.*s%c%-*.*s%c%-12.12s%c%s\n",
535 ctl->name_len, p->ut_user, ctl->separator, utline, ctl->separator,
536 fmt->in_len, fmt->in_len, logintime, ctl->separator, fmt->out_len, fmt->out_len,
537 logouttime, ctl->separator, length, ctl->separator, domain);
538 }
539 } else
540 len = snprintf(final, sizeof(final),
541 "%-8.*s%c%-12.12s%c%-*.*s%c%-*.*s%c%s\n",
542 ctl->name_len, p->ut_user, ctl->separator, utline, ctl->separator,
543 fmt->in_len, fmt->in_len, logintime, ctl->separator, fmt->out_len, fmt->out_len,
544 logouttime, ctl->separator, length);
545
546 #if defined(__GLIBC__)
547 # if (__GLIBC__ == 2) && (__GLIBC_MINOR__ == 0)
548 final[sizeof(final)-1] = '\0';
549 # endif
550 #endif
551
552 trim_trailing_spaces(final);
553 /*
554 * Print out "final" string safely.
555 */
556 fputs_careful(final, stdout, '*', false, 0);
557
558 if (len < 0 || (size_t)len >= sizeof(final))
559 putchar('\n');
560
561 recsdone++;
562 if (ctl->maxrecs && ctl->maxrecs <= recsdone)
563 return 1;
564
565 return 0;
566 }
567
568 #ifndef FUZZ_TARGET
569 static void __attribute__((__noreturn__)) usage(const struct last_control *ctl)
570 {
571 FILE *out = stdout;
572 fputs(USAGE_HEADER, out);
573 fprintf(out, _(
574 " %s [options] [<username>...] [<tty>...]\n"), program_invocation_short_name);
575
576 fputs(USAGE_SEPARATOR, out);
577 fputs(_("Show a listing of last logged in users.\n"), out);
578
579 fputs(USAGE_OPTIONS, out);
580 fputs(_(" -<number> how many lines to show\n"), out);
581 fputs(_(" -a, --hostlast display hostnames in the last column\n"), out);
582 fputs(_(" -d, --dns translate the IP number back into a hostname\n"), out);
583 fprintf(out,
584 _(" -f, --file <file> use a specific file instead of %s\n"), ctl->lastb ? _PATH_BTMP : _PATH_WTMP);
585 fputs(_(" -F, --fulltimes print full login and logout times and dates\n"), out);
586 fputs(_(" -i, --ip display IP numbers in numbers-and-dots notation\n"), out);
587 fputs(_(" -n, --limit <number> how many lines to show\n"), out);
588 fputs(_(" -R, --nohostname don't display the hostname field\n"), out);
589 fputs(_(" -s, --since <time> display the lines since the specified time\n"), out);
590 fputs(_(" -t, --until <time> display the lines until the specified time\n"), out);
591 fputs(_(" -T, --tab-separated use tabs as delimiters\n"), out);
592 fputs(_(" -p, --present <time> display who were present at the specified time\n"), out);
593 fputs(_(" -w, --fullnames display full user and domain names\n"), out);
594 fputs(_(" -x, --system display system shutdown entries and run level changes\n"), out);
595 fputs(_(" --time-format <format> show timestamps in the specified <format>:\n"
596 " notime|short|full|iso\n"), out);
597
598 fputs(USAGE_SEPARATOR, out);
599 fprintf(out, USAGE_HELP_OPTIONS(22));
600 fprintf(out, USAGE_MAN_TAIL("last(1)"));
601
602 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
603 }
604 #endif
605
606 static int is_phantom(const struct last_control *ctl, struct utmpx *ut)
607 {
608 struct passwd *pw;
609 char path[sizeof(ut->ut_line) + 16];
610 char user[sizeof(ut->ut_user) + 1];
611 int ret = 0;
612
613 if (ut->ut_tv.tv_sec < ctl->boot_time.tv_sec)
614 return 1;
615
616 mem2strcpy(user, ut->ut_user, sizeof(ut->ut_user), sizeof(user));
617 pw = getpwnam(user);
618 if (!pw)
619 return 1;
620 snprintf(path, sizeof(path), "/proc/%u/loginuid", ut->ut_pid);
621 if (access(path, R_OK) == 0) {
622 unsigned int loginuid;
623 FILE *f = NULL;
624
625 if (!(f = fopen(path, "r")))
626 return 1;
627 if (fscanf(f, "%u", &loginuid) != 1)
628 ret = 1;
629 fclose(f);
630 if (!ret && pw->pw_uid != loginuid)
631 return 1;
632 } else {
633 struct stat st;
634 char utline[sizeof(ut->ut_line) + 1];
635
636 mem2strcpy(utline, ut->ut_line, sizeof(ut->ut_line), sizeof(utline));
637
638 snprintf(path, sizeof(path), "/dev/%s", utline);
639 if (stat(path, &st))
640 return 1;
641 if (pw->pw_uid != st.st_uid)
642 return 1;
643 }
644 return ret;
645 }
646
647 static void process_wtmp_file(const struct last_control *ctl,
648 const char *filename)
649 {
650 FILE *fp; /* File pointer of wtmp file */
651
652 struct utmpx ut; /* Current utmp entry */
653 struct utmplist *ulist = NULL; /* All entries */
654 struct utmplist *p; /* Pointer into utmplist */
655 struct utmplist *next; /* Pointer into utmplist */
656
657 time_t lastboot = 0; /* Last boottime */
658 time_t lastrch = 0; /* Last run level change */
659 time_t lastdown; /* Last downtime */
660 time_t begintime; /* When wtmp begins */
661 int whydown = 0; /* Why we went down: crash or shutdown */
662
663 int c, x; /* Scratch */
664 struct stat st; /* To stat the [uw]tmp file */
665 int quit = 0; /* Flag */
666 int down = 0; /* Down flag */
667
668 #ifndef FUZZ_TARGET
669 time(&lastdown);
670 #else
671 lastdown = 1596001948;
672 #endif
673 /*
674 * Fill in 'lastdate'
675 */
676 lastdate = currentdate = lastrch = lastdown;
677
678 #ifndef FUZZ_TARGET
679 /*
680 * Install signal handlers
681 */
682 signal(SIGINT, int_handler);
683 signal(SIGQUIT, quit_handler);
684 #endif
685
686 /*
687 * Open the utmp file
688 */
689 if ((fp = fopen(filename, "r")) == NULL)
690 err(EXIT_FAILURE, _("cannot open %s"), filename);
691
692 /*
693 * Optimize the buffer size.
694 */
695 setvbuf(fp, NULL, _IOFBF, UCHUNKSIZE);
696
697 /*
698 * Read first structure to capture the time field
699 */
700 if (uread(fp, &ut, NULL, filename) == 1)
701 begintime = ut.ut_tv.tv_sec;
702 else {
703 if (fstat(fileno(fp), &st) != 0)
704 err(EXIT_FAILURE, _("stat of %s failed"), filename);
705 begintime = st.st_ctime;
706 quit = 1;
707 }
708
709 /*
710 * Go to end of file minus one structure
711 * and/or initialize utmp reading code.
712 */
713 uread(fp, NULL, NULL, filename);
714
715 /*
716 * Read struct after struct backwards from the file.
717 */
718 while (!quit) {
719
720 if (uread(fp, &ut, &quit, filename) != 1)
721 break;
722
723 if (ctl->since && ut.ut_tv.tv_sec < ctl->since)
724 continue;
725
726 if (ctl->until && ctl->until < ut.ut_tv.tv_sec)
727 continue;
728
729 lastdate = ut.ut_tv.tv_sec;
730
731 if (ctl->lastb) {
732 quit = list(ctl, &ut, ut.ut_tv.tv_sec, R_NORMAL);
733 continue;
734 }
735
736 /*
737 * Set ut_type to the correct type.
738 */
739 if (strncmp(ut.ut_line, "~", 1) == 0) {
740 if (strncmp(ut.ut_user, "shutdown", 8) == 0)
741 ut.ut_type = SHUTDOWN_TIME;
742 else if (strncmp(ut.ut_user, "reboot", 6) == 0)
743 ut.ut_type = BOOT_TIME;
744 else if (strncmp(ut.ut_user, "runlevel", 8) == 0)
745 ut.ut_type = RUN_LVL;
746 }
747 #if 1 /*def COMPAT*/
748 /*
749 * For stupid old applications that don't fill in
750 * ut_type correctly.
751 */
752 else {
753 if (ut.ut_type != DEAD_PROCESS &&
754 ut.ut_user[0] && ut.ut_line[0] &&
755 strncmp(ut.ut_user, "LOGIN", 5) != 0)
756 ut.ut_type = USER_PROCESS;
757 /*
758 * Even worse, applications that write ghost
759 * entries: ut_type set to USER_PROCESS but
760 * empty ut_user...
761 */
762 if (ut.ut_user[0] == 0)
763 ut.ut_type = DEAD_PROCESS;
764
765 /*
766 * Clock changes.
767 */
768 if (strncmp(ut.ut_user, "date", 4) == 0) {
769 if (ut.ut_line[0] == '|')
770 ut.ut_type = OLD_TIME;
771 if (ut.ut_line[0] == '{')
772 ut.ut_type = NEW_TIME;
773 }
774 }
775 #endif
776 switch (ut.ut_type) {
777 case SHUTDOWN_TIME:
778 if (ctl->extended) {
779 strcpy(ut.ut_line, "system down");
780 quit = list(ctl, &ut, lastboot, R_NORMAL);
781 }
782 lastdown = lastrch = ut.ut_tv.tv_sec;
783 down = 1;
784 break;
785 case OLD_TIME:
786 case NEW_TIME:
787 if (ctl->extended) {
788 strcpy(ut.ut_line,
789 ut.ut_type == NEW_TIME ? "new time" :
790 "old time");
791 quit = list(ctl, &ut, lastdown, R_TIMECHANGE);
792 }
793 break;
794 case BOOT_TIME:
795 strcpy(ut.ut_line, "system boot");
796 if (lastdown > lastboot && lastdown != currentdate)
797 quit = list(ctl, &ut, lastboot, R_REBOOT_CRASH);
798 else
799 quit = list(ctl, &ut, lastdown, R_REBOOT);
800 lastboot = ut.ut_tv.tv_sec;
801 down = 1;
802 break;
803 case RUN_LVL:
804 x = ut.ut_pid & 255;
805 if (ctl->extended) {
806 snprintf(ut.ut_line, sizeof(ut.ut_line), "(to lvl %c)", x);
807 quit = list(ctl, &ut, lastrch, R_NORMAL);
808 }
809 if (x == '0' || x == '6') {
810 lastdown = ut.ut_tv.tv_sec;
811 down = 1;
812 ut.ut_type = SHUTDOWN_TIME;
813 }
814 lastrch = ut.ut_tv.tv_sec;
815 break;
816
817 case USER_PROCESS:
818 /*
819 * This was a login - show the first matching
820 * logout record and delete all records with
821 * the same ut_line.
822 */
823 c = 0;
824 for (p = ulist; p; p = next) {
825 next = p->next;
826 if (strncmp(p->ut.ut_line, ut.ut_line,
827 sizeof(ut.ut_line)) == 0) {
828 /* Show it */
829 if (c == 0) {
830 quit = list(ctl, &ut, p->ut.ut_tv.tv_sec, R_NORMAL);
831 c = 1;
832 }
833 if (p->next)
834 p->next->prev = p->prev;
835 if (p->prev)
836 p->prev->next = p->next;
837 else
838 ulist = p->next;
839 free(p);
840 }
841 }
842 /*
843 * Not found? Then crashed, down, still
844 * logged in, or missing logout record.
845 */
846 if (c == 0) {
847 if (!lastboot) {
848 c = R_NOW;
849 /* Is process still alive? */
850 if (is_phantom(ctl, &ut))
851 c = R_PHANTOM;
852 } else
853 c = whydown;
854 quit = list(ctl, &ut, lastboot, c);
855 }
856 /* fallthrough */
857
858 case DEAD_PROCESS:
859 /*
860 * Just store the data if it is
861 * interesting enough.
862 */
863 if (ut.ut_line[0] == 0)
864 break;
865 p = xmalloc(sizeof(struct utmplist));
866 memcpy(&p->ut, &ut, sizeof(struct utmpx));
867 p->next = ulist;
868 p->prev = NULL;
869 if (ulist)
870 ulist->prev = p;
871 ulist = p;
872 break;
873
874 case EMPTY:
875 case INIT_PROCESS:
876 case LOGIN_PROCESS:
877 #ifdef ACCOUNTING
878 case ACCOUNTING:
879 #endif
880 /* ignored ut_types */
881 break;
882
883 default:
884 warnx("unrecognized ut_type: %d", ut.ut_type);
885 }
886
887 /*
888 * If we saw a shutdown/reboot record we can remove
889 * the entire current ulist.
890 */
891 if (down) {
892 lastboot = ut.ut_tv.tv_sec;
893 whydown = (ut.ut_type == SHUTDOWN_TIME) ? R_DOWN : R_CRASH;
894 for (p = ulist; p; p = next) {
895 next = p->next;
896 free(p);
897 }
898 ulist = NULL;
899 down = 0;
900 }
901 }
902
903 if (ctl->time_fmt != LAST_TIMEFTM_NONE) {
904 struct last_timefmt *fmt;
905 char timestr[LAST_TIMESTAMP_LEN];
906 char *tmp = xstrdup(filename);
907
908 fmt = &timefmts[ctl->time_fmt];
909 if (time_formatter(fmt->in_fmt, timestr,
910 sizeof(timestr), &begintime) < 0)
911 errx(EXIT_FAILURE, _("preallocation size exceeded"));
912 printf(_("\n%s begins %s\n"), basename(tmp), timestr);
913 free(tmp);
914 }
915
916 fclose(fp);
917
918 for (p = ulist; p; p = next) {
919 next = p->next;
920 free(p);
921 }
922 }
923
924 #ifdef FUZZ_TARGET
925 # include "all-io.h"
926
927 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
928 struct last_control ctl = {
929 .showhost = TRUE,
930 .name_len = LAST_LOGIN_LEN,
931 .time_fmt = LAST_TIMEFTM_SHORT,
932 .domain_len = LAST_DOMAIN_LEN,
933 .boot_time = {
934 .tv_sec = 1595978419,
935 .tv_usec = 816074
936 }
937 };
938 char name[] = "/tmp/test-last-fuzz.XXXXXX";
939 int fd;
940
941 fd = mkstemp_cloexec(name);
942 if (fd < 0)
943 err(EXIT_FAILURE, "mkstemp() failed");
944 if (write_all(fd, data, size) != 0)
945 err(EXIT_FAILURE, "write() failed");
946
947 process_wtmp_file(&ctl, name);
948
949 close(fd);
950 unlink(name);
951
952 return 0;
953 }
954 #else
955 int main(int argc, char **argv)
956 {
957 struct last_control ctl = {
958 .showhost = TRUE,
959 .name_len = LAST_LOGIN_LEN,
960 .time_fmt = LAST_TIMEFTM_SHORT,
961 .domain_len = LAST_DOMAIN_LEN
962 };
963 char **files = NULL;
964 size_t i, nfiles = 0;
965 int c;
966 usec_t p;
967
968 enum {
969 OPT_TIME_FORMAT = CHAR_MAX + 1
970 };
971 static const struct option long_opts[] = {
972 { "limit", required_argument, NULL, 'n' },
973 { "help", no_argument, NULL, 'h' },
974 { "file", required_argument, NULL, 'f' },
975 { "nohostname", no_argument, NULL, 'R' },
976 { "version", no_argument, NULL, 'V' },
977 { "hostlast", no_argument, NULL, 'a' },
978 { "since", required_argument, NULL, 's' },
979 { "until", required_argument, NULL, 't' },
980 { "present", required_argument, NULL, 'p' },
981 { "system", no_argument, NULL, 'x' },
982 { "dns", no_argument, NULL, 'd' },
983 { "ip", no_argument, NULL, 'i' },
984 { "fulltimes", no_argument, NULL, 'F' },
985 { "fullnames", no_argument, NULL, 'w' },
986 { "tab-separated", no_argument, NULL, 'T' },
987 { "time-format", required_argument, NULL, OPT_TIME_FORMAT },
988 { NULL, 0, NULL, 0 }
989 };
990 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
991 { 'F', OPT_TIME_FORMAT }, /* fulltime, time-format */
992 { 0 }
993 };
994 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
995
996 setlocale(LC_ALL, "");
997 bindtextdomain(PACKAGE, LOCALEDIR);
998 textdomain(PACKAGE);
999 close_stdout_atexit();
1000 /*
1001 * Which file do we want to read?
1002 */
1003 ctl.lastb = strcmp(program_invocation_short_name, "lastb") == 0 ? 1 : 0;
1004 ctl.separator = ' ';
1005 while ((c = getopt_long(argc, argv,
1006 "hVf:n:RxadFit:p:s:T0123456789w", long_opts, NULL)) != -1) {
1007
1008 err_exclusive_options(c, long_opts, excl, excl_st);
1009
1010 switch(c) {
1011 case 'h':
1012 usage(&ctl);
1013 break;
1014 case 'V':
1015 print_version(EXIT_SUCCESS);
1016 case 'R':
1017 ctl.showhost = 0;
1018 break;
1019 case 'x':
1020 ctl.extended = 1;
1021 break;
1022 case 'n':
1023 ctl.maxrecs = strtos32_or_err(optarg, _("failed to parse number"));
1024 break;
1025 case 'f':
1026 if (!files)
1027 files = xmalloc(sizeof(char *) * argc);
1028 files[nfiles++] = xstrdup(optarg);
1029 break;
1030 case 'd':
1031 ctl.usedns = 1;
1032 break;
1033 case 'i':
1034 ctl.useip = 1;
1035 break;
1036 case 'a':
1037 ctl.altlist = 1;
1038 break;
1039 case 'F':
1040 ctl.time_fmt = LAST_TIMEFTM_CTIME;
1041 break;
1042 case 'p':
1043 if (parse_timestamp(optarg, &p) < 0)
1044 errx(EXIT_FAILURE, _("invalid time value \"%s\""), optarg);
1045 ctl.present = (time_t) (p / 1000000);
1046 break;
1047 case 's':
1048 if (parse_timestamp(optarg, &p) < 0)
1049 errx(EXIT_FAILURE, _("invalid time value \"%s\""), optarg);
1050 ctl.since = (time_t) (p / 1000000);
1051 break;
1052 case 't':
1053 if (parse_timestamp(optarg, &p) < 0)
1054 errx(EXIT_FAILURE, _("invalid time value \"%s\""), optarg);
1055 ctl.until = (time_t) (p / 1000000);
1056 break;
1057 case 'w':
1058 if (ctl.name_len < sizeof_member(struct utmpx, ut_user))
1059 ctl.name_len = sizeof_member(struct utmpx, ut_user);
1060 if (ctl.domain_len < sizeof_member(struct utmpx, ut_host))
1061 ctl.domain_len = sizeof_member(struct utmpx, ut_host);
1062 break;
1063 case '0': case '1': case '2': case '3': case '4':
1064 case '5': case '6': case '7': case '8': case '9':
1065 ctl.maxrecs = 10 * ctl.maxrecs + c - '0';
1066 break;
1067 case OPT_TIME_FORMAT:
1068 ctl.time_fmt = which_time_format(optarg);
1069 break;
1070 case 'T':
1071 ctl.separator = '\t';
1072 break;
1073 default:
1074 errtryhelp(EXIT_FAILURE);
1075 }
1076 }
1077
1078 if (optind < argc)
1079 ctl.show = argv + optind;
1080
1081 if (!files) {
1082 files = xmalloc(sizeof(char *));
1083 files[nfiles++] = xstrdup(ctl.lastb ? _PATH_BTMP : _PATH_WTMP);
1084 }
1085
1086 for (i = 0; i < nfiles; i++) {
1087 get_boot_time(&ctl.boot_time);
1088 process_wtmp_file(&ctl, files[i]);
1089 free(files[i]);
1090 }
1091 free(files);
1092 return EXIT_SUCCESS;
1093 }
1094 #endif