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