1/* See LICENSE file for copyright and license details. */
2
3#include <errno.h>
4#include <libgen.h>
5#include <pwd.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include <string.h>
9#include <time.h>
10#include <unistd.h>
11#include <utmp.h>
12
13#include "config.h"
14#include "paths.h"
15#include "util.h"
16
17static void
18usage(void)
19{
20 eprintf("usage: %s [user]\n", argv0);
21}
22
23// ?man last: show last logged in users
24// ?man arguments: user
25// ?man display a list of recent user logins
26int
27main(int argc, char **argv)
28{
29 FILE *fp;
30 struct utmp ut;
31 char *user, *file, *prog;
32 char ut_name_buf[UT_NAMESIZE + 1];
33 time_t t;
34
35 ARGBEGIN
36 {
37 default:
38 usage();
39 }
40 ARGEND;
41
42 switch (argc) {
43 case 0:
44 user = NULL;
45 break;
46 case 1:
47 user = argv[0];
48 break;
49 default:
50 usage();
51 }
52
53 prog = basename(argv0);
54 file = (!strcmp(prog, "last")) ? WTMP_PATH : BTMP_PATH;
55 if ((fp = fopen(file, "r")) == NULL)
56 eprintf("fopen %s:", file);
57
58 while (fread(&ut, sizeof(ut), 1, fp) == 1) {
59 memcpy(ut_name_buf, ut.ut_name, UT_NAMESIZE);
60 ut_name_buf[UT_NAMESIZE] = '\0';
61 if (ut.ut_type != USER_PROCESS || (user && strcmp(user, ut_name_buf))) {
62 continue;
63 }
64
65 t = ut.ut_time;
66 printf("%-8.8s %-8.8s %-16.16s %s", ut.ut_user, ut.ut_line, ut.ut_host, ctime(&t));
67 }
68 if (fclose(fp))
69 eprintf("fclose %s:", file);
70 return 0;
71}