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