last.c revision 102944
1/*
2 * Copyright (c) 1987, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1987, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41static const char sccsid[] = "@(#)last.c	8.2 (Berkeley) 4/2/94";
42#endif /* not lint */
43#include <sys/cdefs.h>
44__FBSDID("$FreeBSD: head/usr.bin/last/last.c 102944 2002-09-04 23:29:10Z dwmalone $");
45
46#include <sys/param.h>
47#include <sys/stat.h>
48
49#include <err.h>
50#include <fcntl.h>
51#include <langinfo.h>
52#include <locale.h>
53#include <paths.h>
54#include <signal.h>
55#include <stdio.h>
56#include <stdlib.h>
57#include <string.h>
58#include <time.h>
59#include <unistd.h>
60#include <utmp.h>
61#include <sys/queue.h>
62
63#define	NO	0				/* false/no */
64#define	YES	1				/* true/yes */
65#define	ATOI2(ar)	((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
66
67static struct utmp	buf[1024];		/* utmp read buffer */
68
69typedef struct arg {
70	char	*name;				/* argument */
71#define	HOST_TYPE	-2
72#define	TTY_TYPE	-3
73#define	USER_TYPE	-4
74	int	type;				/* type of arg */
75	struct arg	*next;			/* linked list pointer */
76} ARG;
77ARG	*arglist;				/* head of linked list */
78
79LIST_HEAD(ttylisthead, ttytab) ttylist;
80
81struct ttytab {
82	time_t	logout;				/* log out time */
83	char	tty[UT_LINESIZE + 1];		/* terminal name */
84	LIST_ENTRY(ttytab) list;
85};
86
87static const	char *crmsg;			/* cause of last reboot */
88static long	currentout,			/* current logout value */
89		maxrec;				/* records to display */
90static const	char *file = _PATH_WTMP;		/* wtmp file */
91static int	sflag = 0;			/* show delta in seconds */
92static int	width = 5;			/* show seconds in delta */
93static int	yflag;				/* show year */
94static int      d_first;
95static int	snapfound = 0;			/* found snapshot entry? */
96static time_t	snaptime;			/* if != 0, we will only
97						 * report users logged in
98						 * at this snapshot time
99						 */
100
101void	 addarg(int, char *);
102time_t	 dateconv(char *);
103void	 doentry(struct utmp *);
104void	 hostconv(char *);
105void	 onintr(int);
106void	 printentry(struct utmp *, struct ttytab *);
107char	*ttyconv(char *);
108int	 want(struct utmp *);
109void	 usage(void);
110void	 wtmp(void);
111
112void
113usage(void)
114{
115	(void)fprintf(stderr,
116"usage: last [-#] [-y] [-d [[CC]YY][MMDD]hhmm[.SS]] [-f file] [-h host]\n"
117"\t[-t tty] [-s|w] [user ...]\n");
118	exit(1);
119}
120
121int
122main(int argc, char *argv[])
123{
124	int ch;
125	char *p;
126
127	(void) setlocale(LC_TIME, "");
128	d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
129
130	maxrec = -1;
131	snaptime = 0;
132	while ((ch = getopt(argc, argv, "0123456789d:f:h:st:wy")) != -1)
133		switch (ch) {
134		case '0': case '1': case '2': case '3': case '4':
135		case '5': case '6': case '7': case '8': case '9':
136			/*
137			 * kludge: last was originally designed to take
138			 * a number after a dash.
139			 */
140			if (maxrec == -1) {
141				p = argv[optind - 1];
142				if (p[0] == '-' && p[1] == ch && !p[2])
143					maxrec = atol(++p);
144				else
145					maxrec = atol(argv[optind] + 1);
146				if (!maxrec)
147					exit(0);
148			}
149			break;
150		case 'd':
151			snaptime = dateconv(optarg);
152			break;
153		case 'f':
154			file = optarg;
155			break;
156		case 'h':
157			hostconv(optarg);
158			addarg(HOST_TYPE, optarg);
159			break;
160		case 's':
161			sflag++;	/* Show delta as seconds */
162			break;
163		case 't':
164			addarg(TTY_TYPE, ttyconv(optarg));
165			break;
166		case 'w':
167			width = 8;
168			break;
169		case 'y':
170			yflag++;
171			break;
172		case '?':
173		default:
174			usage();
175		}
176
177	if (sflag && width == 8) usage();
178
179	if (argc) {
180		setlinebuf(stdout);
181		for (argv += optind; *argv; ++argv) {
182#define	COMPATIBILITY
183#ifdef	COMPATIBILITY
184			/* code to allow "last p5" to work */
185			addarg(TTY_TYPE, ttyconv(*argv));
186#endif
187			addarg(USER_TYPE, *argv);
188		}
189	}
190	wtmp();
191	exit(0);
192}
193
194/*
195 * wtmp --
196 *	read through the wtmp file
197 */
198void
199wtmp(void)
200{
201	struct utmp	*bp;			/* current structure */
202	struct stat	stb;			/* stat of file for size */
203	long	bl;
204	int	bytes, wfd;
205	char ct[80];
206	struct tm *tm;
207	time_t	t;
208
209	LIST_INIT(&ttylist);
210
211	if ((wfd = open(file, O_RDONLY, 0)) < 0 || fstat(wfd, &stb) == -1)
212		err(1, "%s", file);
213	bl = (stb.st_size + sizeof(buf) - 1) / sizeof(buf);
214
215	(void)time(&t);
216	buf[0].ut_time = _time_to_int(t);
217	(void)signal(SIGINT, onintr);
218	(void)signal(SIGQUIT, onintr);
219
220	while (--bl >= 0) {
221		if (lseek(wfd, (off_t)(bl * sizeof(buf)), L_SET) == -1 ||
222		    (bytes = read(wfd, buf, sizeof(buf))) == -1)
223			err(1, "%s", file);
224		for (bp = &buf[bytes / sizeof(buf[0]) - 1]; bp >= buf; --bp)
225			doentry(bp);
226	}
227	t = _int_to_time(buf[0].ut_time);
228	tm = localtime(&t);
229	(void) strftime(ct, sizeof(ct), "\nwtmp begins %+\n", tm);
230	printf("%s", ct);
231}
232
233/*
234 * doentry --
235 *	process a single wtmp entry
236 */
237void
238doentry(struct utmp *bp)
239{
240	struct ttytab	*tt, *ttx;		/* ttylist entry */
241
242	/*
243	 * if the terminal line is '~', the machine stopped.
244	 * see utmp(5) for more info.
245	 */
246	if (bp->ut_line[0] == '~' && !bp->ut_line[1]) {
247		/* everybody just logged out */
248		for (tt = LIST_FIRST(&ttylist); tt;) {
249			LIST_REMOVE(tt, list);
250			ttx = tt;
251			tt = LIST_NEXT(tt, list);
252			free(ttx);
253		}
254		currentout = -bp->ut_time;
255		crmsg = strncmp(bp->ut_name, "shutdown", UT_NAMESIZE) ?
256		    "crash" : "shutdown";
257		/*
258		 * if we're in snapshot mode, we want to exit if this
259		 * shutdown/reboot appears while we we are tracking the
260		 * active range
261		 */
262		if (snaptime && snapfound)
263			exit(0);
264		/*
265		 * don't print shutdown/reboot entries unless flagged for
266		 */
267		if (!snaptime && want(bp))
268			printentry(bp, NULL);
269		return;
270	}
271	/*
272	 * if the line is '{' or '|', date got set; see
273	 * utmp(5) for more info.
274	 */
275	if ((bp->ut_line[0] == '{' || bp->ut_line[0] == '|') &&
276	    !bp->ut_line[1]) {
277		if (want(bp) && !snaptime)
278			printentry(bp, NULL);
279		return;
280	}
281	/* find associated tty */
282	LIST_FOREACH(tt, &ttylist, list)
283	    if (!strncmp(tt->tty, bp->ut_line, UT_LINESIZE))
284		    break;
285
286	if (tt == NULL) {
287		/* add new one */
288		tt = malloc(sizeof(struct ttytab));
289		if (tt == NULL)
290			errx(1, "malloc failure");
291		tt->logout = currentout;
292		strncpy(tt->tty, bp->ut_line, UT_LINESIZE);
293		LIST_INSERT_HEAD(&ttylist, tt, list);
294	}
295
296	/*
297	 * print record if not in snapshot mode and wanted
298	 * or in snapshot mode and in snapshot range
299	 */
300	if (bp->ut_name[0] && (want(bp) || (bp->ut_time < snaptime &&
301	    (tt->logout > snaptime || tt->logout < 1)))) {
302		snapfound = 1;
303		/*
304		 * when uucp and ftp log in over a network, the entry in
305		 * the utmp file is the name plus their process id.  See
306		 * etc/ftpd.c and usr.bin/uucp/uucpd.c for more information.
307		 */
308		if (!strncmp(bp->ut_line, "ftp", sizeof("ftp") - 1))
309			bp->ut_line[3] = '\0';
310		else if (!strncmp(bp->ut_line, "uucp", sizeof("uucp") - 1))
311			bp->ut_line[4] = '\0';
312		printentry(bp, tt);
313	}
314	tt->logout = bp->ut_time;
315}
316
317/*
318 * printentry --
319 *	output an entry
320 *
321 * If `tt' is non-NULL, use it and `crmsg' to print the logout time or
322 * logout type (crash/shutdown) as appropriate.
323 */
324void
325printentry(struct utmp *bp, struct ttytab *tt)
326{
327	char ct[80];
328	struct tm *tm;
329	time_t	delta;				/* time difference */
330	time_t	t;
331
332	if (maxrec != -1 && !maxrec--)
333		exit(0);
334	t = _int_to_time(bp->ut_time);
335	tm = localtime(&t);
336	(void) strftime(ct, sizeof(ct), d_first ?
337	    (yflag ? "%a %e %b %Y %R" : "%a %e %b %R") :
338	    (yflag ? "%a %b %e %Y %R" : "%a %b %e %R"), tm);
339	printf("%-*.*s %-*.*s %-*.*s %s%c",
340	    UT_NAMESIZE, UT_NAMESIZE, bp->ut_name,
341	    UT_LINESIZE, UT_LINESIZE, bp->ut_line,
342	    UT_HOSTSIZE, UT_HOSTSIZE, bp->ut_host,
343	    ct, tt == NULL ? '\n' : ' ');
344	if (tt == NULL)
345		return;
346	if (!tt->logout) {
347		puts("  still logged in");
348		return;
349	}
350	if (tt->logout < 0) {
351		tt->logout = -tt->logout;
352		printf("- %s", crmsg);
353	} else {
354		tm = localtime(&tt->logout);
355		(void) strftime(ct, sizeof(ct), "%R", tm);
356		printf("- %s", ct);
357	}
358	delta = tt->logout - bp->ut_time;
359	if (sflag) {
360		printf("  (%8ld)\n", (long)delta);
361	} else {
362		tm = gmtime(&delta);
363		(void) strftime(ct, sizeof(ct), width >= 8 ? "%T" : "%R", tm);
364		if (delta < 86400)
365			printf("  (%s)\n", ct);
366		else
367			printf(" (%ld+%s)\n", (long)delta / 86400, ct);
368	}
369}
370
371/*
372 * want --
373 *	see if want this entry
374 */
375int
376want(struct utmp *bp)
377{
378	ARG *step;
379
380	if (snaptime)
381		return (NO);
382
383	if (!arglist)
384		return (YES);
385
386	for (step = arglist; step; step = step->next)
387		switch(step->type) {
388		case HOST_TYPE:
389			if (!strncasecmp(step->name, bp->ut_host, UT_HOSTSIZE))
390				return (YES);
391			break;
392		case TTY_TYPE:
393			if (!strncmp(step->name, bp->ut_line, UT_LINESIZE))
394				return (YES);
395			break;
396		case USER_TYPE:
397			if (!strncmp(step->name, bp->ut_name, UT_NAMESIZE))
398				return (YES);
399			break;
400		}
401	return (NO);
402}
403
404/*
405 * addarg --
406 *	add an entry to a linked list of arguments
407 */
408void
409addarg(int type, char *arg)
410{
411	ARG *cur;
412
413	if ((cur = malloc(sizeof(ARG))) == NULL)
414		errx(1, "malloc failure");
415	cur->next = arglist;
416	cur->type = type;
417	cur->name = arg;
418	arglist = cur;
419}
420
421/*
422 * hostconv --
423 *	convert the hostname to search pattern; if the supplied host name
424 *	has a domain attached that is the same as the current domain, rip
425 *	off the domain suffix since that's what login(1) does.
426 */
427void
428hostconv(char *arg)
429{
430	static int first = 1;
431	static char *hostdot, name[MAXHOSTNAMELEN];
432	char *argdot;
433
434	if (!(argdot = strchr(arg, '.')))
435		return;
436	if (first) {
437		first = 0;
438		if (gethostname(name, sizeof(name)))
439			err(1, "gethostname");
440		hostdot = strchr(name, '.');
441	}
442	if (hostdot && !strcasecmp(hostdot, argdot))
443		*argdot = '\0';
444}
445
446/*
447 * ttyconv --
448 *	convert tty to correct name.
449 */
450char *
451ttyconv(char *arg)
452{
453	char *mval;
454
455	/*
456	 * kludge -- we assume that all tty's end with
457	 * a two character suffix.
458	 */
459	if (strlen(arg) == 2) {
460		/* either 6 for "ttyxx" or 8 for "console" */
461		if ((mval = malloc(8)) == NULL)
462			errx(1, "malloc failure");
463		if (!strcmp(arg, "co"))
464			(void)strcpy(mval, "console");
465		else {
466			(void)strcpy(mval, "tty");
467			(void)strcpy(mval + 3, arg);
468		}
469		return (mval);
470	}
471	if (!strncmp(arg, _PATH_DEV, sizeof(_PATH_DEV) - 1))
472		return (arg + 5);
473	return (arg);
474}
475
476/*
477 * dateconv --
478 * 	Convert the snapshot time in command line given in the format
479 * 	[[CC]YY]MMDDhhmm[.SS]] to a time_t.
480 * 	Derived from atime_arg1() in usr.bin/touch/touch.c
481 */
482time_t
483dateconv(char *arg)
484{
485        time_t timet;
486        struct tm *t;
487        int yearset;
488        char *p;
489
490        /* Start with the current time. */
491        if (time(&timet) < 0)
492                err(1, "time");
493        if ((t = localtime(&timet)) == NULL)
494                err(1, "localtime");
495
496        /* [[CC]YY]MMDDhhmm[.SS] */
497        if ((p = strchr(arg, '.')) == NULL)
498                t->tm_sec = 0; 		/* Seconds defaults to 0. */
499        else {
500                if (strlen(p + 1) != 2)
501                        goto terr;
502                *p++ = '\0';
503                t->tm_sec = ATOI2(p);
504        }
505
506        yearset = 0;
507        switch (strlen(arg)) {
508        case 12:                	/* CCYYMMDDhhmm */
509                t->tm_year = ATOI2(arg);
510                t->tm_year *= 100;
511                yearset = 1;
512                /* FALLTHOUGH */
513        case 10:                	/* YYMMDDhhmm */
514                if (yearset) {
515                        yearset = ATOI2(arg);
516                        t->tm_year += yearset;
517                } else {
518                        yearset = ATOI2(arg);
519                        if (yearset < 69)
520                                t->tm_year = yearset + 2000;
521                        else
522                                t->tm_year = yearset + 1900;
523                }
524                t->tm_year -= 1900;     /* Convert to UNIX time. */
525                /* FALLTHROUGH */
526        case 8:				/* MMDDhhmm */
527                t->tm_mon = ATOI2(arg);
528                --t->tm_mon;    	/* Convert from 01-12 to 00-11 */
529                t->tm_mday = ATOI2(arg);
530                t->tm_hour = ATOI2(arg);
531                t->tm_min = ATOI2(arg);
532                break;
533        case 4:				/* hhmm */
534                t->tm_hour = ATOI2(arg);
535                t->tm_min = ATOI2(arg);
536                break;
537        default:
538                goto terr;
539        }
540        t->tm_isdst = -1;       	/* Figure out DST. */
541        timet = mktime(t);
542        if (timet == -1)
543terr:           errx(1,
544        "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
545        return timet;
546}
547
548
549/*
550 * onintr --
551 *	on interrupt, we inform the user how far we've gotten
552 */
553void
554onintr(int signo)
555{
556	char ct[80];
557	struct tm *tm;
558	time_t t = _int_to_time(buf[0].ut_time);
559
560	tm = localtime(&t);
561	(void) strftime(ct, sizeof(ct),
562			d_first ? "%a %e %b %R" : "%a %b %e %R",
563			tm);
564	printf("\ninterrupted %s\n", ct);
565	if (signo == SIGINT)
566		exit(1);
567	(void)fflush(stdout);			/* fix required for rsh */
568}
569