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