ubase/lastlog.c

75 lines
1.4 KiB
C
Raw Normal View History

/* See LICENSE file for copyright and license details. */
2014-08-18 20:55:38 +00:00
#include <errno.h>
#include <paths.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <utmp.h>
2014-08-18 20:55:38 +00:00
#include "util.h"
#define PASSWD "/etc/passwd"
static FILE *last;
static void
lastlog(char *user)
{
struct passwd *pwd;
struct lastlog ll;
time_t lltime;
2014-08-18 20:55:38 +00:00
errno = 0;
if ((pwd = getpwnam(user)) == NULL) {
2014-08-18 20:55:38 +00:00
if (errno)
weprintf("getpwnam %s:", user);
else
weprintf("unknown user: %s\n", user);
return;
}
fseek(last, pwd->pw_uid * sizeof(struct lastlog), 0);
fread(&ll, sizeof(struct lastlog), 1, last);
2014-08-18 20:55:38 +00:00
if (ferror(last))
eprintf("error reading lastlog\n");
/* on glibc `ll_time' can be an int32_t with compat32
* avoid compiler warning when calling ctime() */
lltime = ll.ll_time;
printf("%-8.8s %-8.8s %-16.16s %s",
user, ll.ll_line, ll.ll_host, ctime(&lltime));
}
int
main(int argc, char **argv)
{
FILE *fp;
char line[512], *p;
2014-08-18 20:55:38 +00:00
if ((last = fopen(_PATH_LASTLOG, "r")) == NULL)
eprintf("fopen %s:", _PATH_LASTLOG);
if (argc > 1) {
while (*++argv)
lastlog(*argv);
} else {
2014-08-18 20:55:38 +00:00
if ((fp = fopen(PASSWD, "r")) == NULL)
eprintf("fopen %s:", PASSWD);
while ((fgets(line, sizeof(line), fp)) != NULL) {
2014-08-18 20:55:38 +00:00
if ((p = strchr(line, ':')) == NULL)
eprintf("invalid passwd entry\n");
*p = '\0';
lastlog(line);
}
if (fclose(fp))
2014-08-18 20:55:38 +00:00
weprintf("fclose %s:", PASSWD);
}
fclose(last);
return EXIT_SUCCESS;
}