last.c revision 89572
1238384Sjkim/*
2238384Sjkim * Copyright (c) 1987, 1993, 1994
3238384Sjkim *	The Regents of the University of California.  All rights reserved.
4238384Sjkim *
5238384Sjkim * Redistribution and use in source and binary forms, with or without
6238384Sjkim * modification, are permitted provided that the following conditions
7238384Sjkim * are met:
8238384Sjkim * 1. Redistributions of source code must retain the above copyright
9280304Sjkim *    notice, this list of conditions and the following disclaimer.
10238384Sjkim * 2. Redistributions in binary form must reproduce the above copyright
11238384Sjkim *    notice, this list of conditions and the following disclaimer in the
12238384Sjkim *    documentation and/or other materials provided with the distribution.
13238384Sjkim * 3. All advertising materials mentioning features or use of this software
14238384Sjkim *    must display the following acknowledgement:
15238384Sjkim *	This product includes software developed by the University of
16238384Sjkim *	California, Berkeley and its contributors.
17238384Sjkim * 4. Neither the name of the University nor the names of its contributors
18238384Sjkim *    may be used to endorse or promote products derived from this software
19238384Sjkim *    without specific prior written permission.
20238384Sjkim *
21238384Sjkim * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22238384Sjkim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23238384Sjkim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24238384Sjkim * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25238384Sjkim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26238384Sjkim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27238384Sjkim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28238384Sjkim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29238384Sjkim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30238384Sjkim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31238384Sjkim * SUCH DAMAGE.
32238384Sjkim *
33238384Sjkim * $FreeBSD: head/usr.bin/last/last.c 89572 2002-01-19 23:20:02Z dillon $
34238384Sjkim */
35238384Sjkim
36238384Sjkim#ifndef lint
37238384Sjkimstatic const char copyright[] =
38238384Sjkim"@(#) Copyright (c) 1987, 1993, 1994\n\
39238384Sjkim	The Regents of the University of California.  All rights reserved.\n";
40238384Sjkim#endif /* not lint */
41238384Sjkim
42238384Sjkim#ifndef lint
43238384Sjkimstatic const char sccsid[] = "@(#)last.c	8.2 (Berkeley) 4/2/94";
44238384Sjkim#endif /* not lint */
45238384Sjkim
46238384Sjkim#include <sys/param.h>
47238384Sjkim#include <sys/stat.h>
48238384Sjkim
49238384Sjkim#include <err.h>
50238384Sjkim#include <fcntl.h>
51238384Sjkim#include <langinfo.h>
52238384Sjkim#include <locale.h>
53238384Sjkim#include <paths.h>
54238384Sjkim#include <signal.h>
55238384Sjkim#include <stdio.h>
56280304Sjkim#include <stdlib.h>
57238384Sjkim#include <string.h>
58238384Sjkim#include <time.h>
59238384Sjkim#include <unistd.h>
60238384Sjkim#include <utmp.h>
61238384Sjkim#include <sys/queue.h>
62238384Sjkim
63280304Sjkim#define	NO	0				/* false/no */
64280304Sjkim#define	YES	1				/* true/yes */
65238384Sjkim#define	ATOI2(ar)	((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
66238384Sjkim
67238384Sjkimstatic struct utmp	buf[1024];		/* utmp read buffer */
68238384Sjkim
69238384Sjkimtypedef struct arg {
70280304Sjkim	char	*name;				/* argument */
71238384Sjkim#define	HOST_TYPE	-2
72238384Sjkim#define	TTY_TYPE	-3
73238384Sjkim#define	USER_TYPE	-4
74238384Sjkim	int	type;				/* type of arg */
75280304Sjkim	struct arg	*next;			/* linked list pointer */
76280304Sjkim} ARG;
77280304SjkimARG	*arglist;				/* head of linked list */
78280304Sjkim
79280304SjkimLIST_HEAD(ttylisthead, ttytab) ttylist;
80280304Sjkim
81280304Sjkimstruct ttytab {
82280304Sjkim	time_t	logout;				/* log out time */
83280304Sjkim	char	tty[UT_LINESIZE + 1];		/* terminal name */
84280304Sjkim	LIST_ENTRY(ttytab) list;
85280304Sjkim};
86280304Sjkim
87280304Sjkimstatic long	currentout,			/* current logout value */
88280304Sjkim		maxrec;				/* records to display */
89280304Sjkimstatic const	char *file = _PATH_WTMP;		/* wtmp file */
90280304Sjkimstatic int	sflag = 0;			/* show delta in seconds */
91280304Sjkimstatic int	width = 5;			/* show seconds in delta */
92280304Sjkimstatic int      d_first;
93284285Sjkimstatic time_t	snaptime;			/* if != 0, we will only
94280304Sjkim						 * report users logged in
95280304Sjkim						 * at this snapshot time
96280304Sjkim						 */
97280304Sjkim
98280304Sjkimvoid	 addarg __P((int, char *));
99280304Sjkimtime_t	 dateconv __P((char *));
100280304Sjkimvoid	 hostconv __P((char *));
101280304Sjkimvoid	 onintr __P((int));
102280304Sjkimchar	*ttyconv __P((char *));
103280304Sjkimint	 want __P((struct utmp *));
104280304Sjkimvoid	 usage __P((void));
105280304Sjkimvoid	 wtmp __P((void));
106280304Sjkim
107280304Sjkimvoid
108280304Sjkimusage(void)
109280304Sjkim{
110280304Sjkim	(void)fprintf(stderr,
111280304Sjkim"usage: last [-#] [-d [[CC]YY][MMDD]hhmm[.SS]] [-f file] [-h hostname]\n"
112280304Sjkim"\t[-t tty] [-s|w] [user ...]\n");
113280304Sjkim	exit(1);
114280304Sjkim}
115280304Sjkim
116280304Sjkimint
117280304Sjkimmain(argc, argv)
118238384Sjkim	int argc;
119238384Sjkim	char *argv[];
120280304Sjkim{
121280304Sjkim	int ch;
122280304Sjkim	char *p;
123280304Sjkim
124280304Sjkim	(void) setlocale(LC_TIME, "");
125280304Sjkim	d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
126280304Sjkim
127280304Sjkim	maxrec = -1;
128280304Sjkim	snaptime = 0;
129280304Sjkim	while ((ch = getopt(argc, argv, "0123456789d:f:h:st:w")) != -1)
130280304Sjkim		switch (ch) {
131280304Sjkim		case '0': case '1': case '2': case '3': case '4':
132280304Sjkim		case '5': case '6': case '7': case '8': case '9':
133280304Sjkim			/*
134280304Sjkim			 * kludge: last was originally designed to take
135280304Sjkim			 * a number after a dash.
136280304Sjkim			 */
137280304Sjkim			if (maxrec == -1) {
138280304Sjkim				p = argv[optind - 1];
139280304Sjkim				if (p[0] == '-' && p[1] == ch && !p[2])
140280304Sjkim					maxrec = atol(++p);
141280304Sjkim				else
142280304Sjkim					maxrec = atol(argv[optind] + 1);
143280304Sjkim				if (!maxrec)
144280304Sjkim					exit(0);
145280304Sjkim			}
146280304Sjkim			break;
147280304Sjkim		case 'd':
148280304Sjkim			snaptime = dateconv(optarg);
149280304Sjkim			break;
150280304Sjkim		case 'f':
151280304Sjkim			file = optarg;
152280304Sjkim			break;
153280304Sjkim		case 'h':
154238384Sjkim			hostconv(optarg);
155238384Sjkim			addarg(HOST_TYPE, optarg);
156238384Sjkim			break;
157238384Sjkim		case 's':
158238384Sjkim			sflag++;	/* Show delta as seconds */
159			break;
160		case 't':
161			addarg(TTY_TYPE, ttyconv(optarg));
162			break;
163		case 'w':
164			width = 8;
165			break;
166		case '?':
167		default:
168			usage();
169		}
170
171	if (sflag && width == 8) usage();
172
173	if (argc) {
174		setlinebuf(stdout);
175		for (argv += optind; *argv; ++argv) {
176#define	COMPATIBILITY
177#ifdef	COMPATIBILITY
178			/* code to allow "last p5" to work */
179			addarg(TTY_TYPE, ttyconv(*argv));
180#endif
181			addarg(USER_TYPE, *argv);
182		}
183	}
184	wtmp();
185	exit(0);
186}
187
188/*
189 * wtmp --
190 *	read through the wtmp file
191 */
192void
193wtmp()
194{
195	struct utmp	*bp;			/* current structure */
196	struct ttytab	*tt, *ttx;		/* ttylist entry */
197	struct stat	stb;			/* stat of file for size */
198	long	bl;
199	time_t	delta;				/* time difference */
200	int	bytes, wfd;
201	const	char *crmsg;
202	char ct[80];
203	struct tm *tm;
204	int	 snapfound = 0;			/* found snapshot entry? */
205	time_t	t;
206
207	LIST_INIT(&ttylist);
208
209	if ((wfd = open(file, O_RDONLY, 0)) < 0 || fstat(wfd, &stb) == -1)
210		err(1, "%s", file);
211	bl = (stb.st_size + sizeof(buf) - 1) / sizeof(buf);
212
213	(void)time(&t);
214	buf[0].ut_time = _time_to_int(t);
215	(void)signal(SIGINT, onintr);
216	(void)signal(SIGQUIT, onintr);
217
218	while (--bl >= 0) {
219		if (lseek(wfd, (off_t)(bl * sizeof(buf)), L_SET) == -1 ||
220		    (bytes = read(wfd, buf, sizeof(buf))) == -1)
221			err(1, "%s", file);
222		for (bp = &buf[bytes / sizeof(buf[0]) - 1]; bp >= buf; --bp) {
223			/*
224			 * if the terminal line is '~', the machine stopped.
225			 * see utmp(5) for more info.
226			 */
227			if (bp->ut_line[0] == '~' && !bp->ut_line[1]) {
228				/* everybody just logged out */
229				for (tt = LIST_FIRST(&ttylist); tt;) {
230					LIST_REMOVE(tt, list);
231					ttx = tt;
232					tt = LIST_NEXT(tt, list);
233					free(ttx);
234				}
235				currentout = -bp->ut_time;
236				crmsg = strncmp(bp->ut_name, "shutdown",
237				    UT_NAMESIZE) ? "crash" : "shutdown";
238				/*
239				 * if we're in snapshot mode, we want to
240				 * exit if this shutdown/reboot appears
241				 * while we we are tracking the active
242				 * range
243				 */
244				if (snaptime && snapfound)
245					return;
246				/*
247				 * don't print shutdown/reboot entries
248				 * unless flagged for
249				 */
250				if (!snaptime && want(bp)) {
251					t = _int_to_time(bp->ut_time);
252					tm = localtime(&t);
253					(void) strftime(ct, sizeof(ct),
254						     d_first ? "%a %e %b %R" :
255							       "%a %b %e %R",
256						     tm);
257					printf("%-*.*s %-*.*s %-*.*s %s\n",
258					    UT_NAMESIZE, UT_NAMESIZE,
259					    bp->ut_name, UT_LINESIZE,
260					    UT_LINESIZE, bp->ut_line,
261					    UT_HOSTSIZE, UT_HOSTSIZE,
262					    bp->ut_host, ct);
263					if (maxrec != -1 && !--maxrec)
264						return;
265				}
266				continue;
267			}
268			/*
269			 * if the line is '{' or '|', date got set; see
270			 * utmp(5) for more info.
271			 */
272			if ((bp->ut_line[0] == '{' || bp->ut_line[0] == '|')
273			    && !bp->ut_line[1]) {
274				if (want(bp) && !snaptime) {
275					t = _int_to_time(bp->ut_time);
276					tm = localtime(&t);
277					(void) strftime(ct, sizeof(ct),
278						     d_first ? "%a %e %b %R" :
279							       "%a %b %e %R",
280						     tm);
281					printf("%-*.*s %-*.*s %-*.*s %s\n",
282					    UT_NAMESIZE, UT_NAMESIZE, bp->ut_name,
283					    UT_LINESIZE, UT_LINESIZE, bp->ut_line,
284					    UT_HOSTSIZE, UT_HOSTSIZE, bp->ut_host,
285					    ct);
286					if (maxrec && !--maxrec)
287						return;
288				}
289				continue;
290			}
291			/* find associated tty */
292			LIST_FOREACH(tt, &ttylist, list)
293			    if (!strncmp(tt->tty, bp->ut_line, UT_LINESIZE))
294				    break;
295
296			if (tt == NULL) {
297				/* add new one */
298				tt = malloc(sizeof(struct ttytab));
299				if (tt == NULL)
300					err(1, "malloc failure");
301				tt->logout = currentout;
302				strncpy(tt->tty, bp->ut_line, UT_LINESIZE);
303				LIST_INSERT_HEAD(&ttylist, tt, list);
304			}
305
306			/*
307			 * print record if not in snapshot mode and wanted
308			 * or in snapshot mode and in snapshot range
309			 */
310			if (bp->ut_name[0] && (want(bp) ||
311			    (bp->ut_time < snaptime &&
312				(tt->logout > snaptime || tt->logout < 1)))) {
313				snapfound = 1;
314				/*
315				 * when uucp and ftp log in over a network, the entry in
316				 * the utmp file is the name plus their process id.  See
317				 * etc/ftpd.c and usr.bin/uucp/uucpd.c for more information.
318				 */
319				if (!strncmp(bp->ut_line, "ftp", sizeof("ftp") - 1))
320					bp->ut_line[3] = '\0';
321				else if (!strncmp(bp->ut_line, "uucp", sizeof("uucp") - 1))
322					bp->ut_line[4] = '\0';
323				t = _int_to_time(bp->ut_time);
324				tm = localtime(&t);
325				(void) strftime(ct, sizeof(ct),
326				    d_first ? "%a %e %b %R" :
327				    "%a %b %e %R",
328				    tm);
329				printf("%-*.*s %-*.*s %-*.*s %s ",
330				    UT_NAMESIZE, UT_NAMESIZE, bp->ut_name,
331				    UT_LINESIZE, UT_LINESIZE, bp->ut_line,
332				    UT_HOSTSIZE, UT_HOSTSIZE, bp->ut_host,
333				    ct);
334				if (!tt->logout)
335					puts("  still logged in");
336				else {
337					if (tt->logout < 0) {
338						tt->logout = -tt->logout;
339						printf("- %s", crmsg);
340					}
341					else {
342						tm = localtime(&tt->logout);
343						(void) strftime(ct, sizeof(ct), "%R", tm);
344						printf("- %s", ct);
345					}
346					delta = tt->logout - bp->ut_time;
347					if ( sflag ) {
348						printf("  (%8ld)\n",
349						    (long)delta);
350					} else {
351						tm = gmtime(&delta);
352						(void) strftime(ct, sizeof(ct),
353						    width >= 8 ? "%T" : "%R",
354						    tm);
355						if (delta < 86400)
356							printf("  (%s)\n", ct);
357						else
358							printf(" (%ld+%s)\n",
359							    (long)delta /
360							    86400, ct);
361					}
362				}
363				if (maxrec != -1 && !--maxrec)
364					return;
365			}
366			tt->logout = bp->ut_time;
367		}
368	}
369	t = _int_to_time(buf[0].ut_time);
370	tm = localtime(&t);
371	(void) strftime(ct, sizeof(ct), "\nwtmp begins %+\n", tm);
372	printf("%s", ct);
373}
374
375/*
376 * want --
377 *	see if want this entry
378 */
379int
380want(bp)
381	struct utmp *bp;
382{
383	ARG *step;
384
385	if (snaptime)
386		return (NO);
387
388	if (!arglist)
389		return (YES);
390
391	for (step = arglist; step; step = step->next)
392		switch(step->type) {
393		case HOST_TYPE:
394			if (!strncasecmp(step->name, bp->ut_host, UT_HOSTSIZE))
395				return (YES);
396			break;
397		case TTY_TYPE:
398			if (!strncmp(step->name, bp->ut_line, UT_LINESIZE))
399				return (YES);
400			break;
401		case USER_TYPE:
402			if (!strncmp(step->name, bp->ut_name, UT_NAMESIZE))
403				return (YES);
404			break;
405	}
406	return (NO);
407}
408
409/*
410 * addarg --
411 *	add an entry to a linked list of arguments
412 */
413void
414addarg(type, arg)
415	int type;
416	char *arg;
417{
418	ARG *cur;
419
420	if (!(cur = (ARG *)malloc((u_int)sizeof(ARG))))
421		err(1, "malloc failure");
422	cur->next = arglist;
423	cur->type = type;
424	cur->name = arg;
425	arglist = cur;
426}
427
428/*
429 * hostconv --
430 *	convert the hostname to search pattern; if the supplied host name
431 *	has a domain attached that is the same as the current domain, rip
432 *	off the domain suffix since that's what login(1) does.
433 */
434void
435hostconv(arg)
436	char *arg;
437{
438	static int first = 1;
439	static char *hostdot, name[MAXHOSTNAMELEN];
440	char *argdot;
441
442	if (!(argdot = strchr(arg, '.')))
443		return;
444	if (first) {
445		first = 0;
446		if (gethostname(name, sizeof(name)))
447			err(1, "gethostname");
448		hostdot = strchr(name, '.');
449	}
450	if (hostdot && !strcasecmp(hostdot, argdot))
451		*argdot = '\0';
452}
453
454/*
455 * ttyconv --
456 *	convert tty to correct name.
457 */
458char *
459ttyconv(arg)
460	char *arg;
461{
462	char *mval;
463
464	/*
465	 * kludge -- we assume that all tty's end with
466	 * a two character suffix.
467	 */
468	if (strlen(arg) == 2) {
469		/* either 6 for "ttyxx" or 8 for "console" */
470		if (!(mval = malloc((u_int)8)))
471			err(1, "malloc failure");
472		if (!strcmp(arg, "co"))
473			(void)strcpy(mval, "console");
474		else {
475			(void)strcpy(mval, "tty");
476			(void)strcpy(mval + 3, arg);
477		}
478		return (mval);
479	}
480	if (!strncmp(arg, _PATH_DEV, sizeof(_PATH_DEV) - 1))
481		return (arg + 5);
482	return (arg);
483}
484
485/*
486 * dateconv --
487 * 	Convert the snapshot time in command line given in the format
488 * 	[[CC]YY]MMDDhhmm[.SS]] to a time_t.
489 * 	Derived from atime_arg1() in usr.bin/touch/touch.c
490 */
491time_t
492dateconv(arg)
493        char *arg;
494{
495        time_t timet;
496        struct tm *t;
497        int yearset;
498        char *p;
499
500        /* Start with the current time. */
501        if (time(&timet) < 0)
502                err(1, "time");
503        if ((t = localtime(&timet)) == NULL)
504                err(1, "localtime");
505
506        /* [[CC]YY]MMDDhhmm[.SS] */
507        if ((p = strchr(arg, '.')) == NULL)
508                t->tm_sec = 0; 		/* Seconds defaults to 0. */
509        else {
510                if (strlen(p + 1) != 2)
511                        goto terr;
512                *p++ = '\0';
513                t->tm_sec = ATOI2(p);
514        }
515
516        yearset = 0;
517        switch (strlen(arg)) {
518        case 12:                	/* CCYYMMDDhhmm */
519                t->tm_year = ATOI2(arg);
520                t->tm_year *= 100;
521                yearset = 1;
522                /* FALLTHOUGH */
523        case 10:                	/* YYMMDDhhmm */
524                if (yearset) {
525                        yearset = ATOI2(arg);
526                        t->tm_year += yearset;
527                } else {
528                        yearset = ATOI2(arg);
529                        if (yearset < 69)
530                                t->tm_year = yearset + 2000;
531                        else
532                                t->tm_year = yearset + 1900;
533                }
534                t->tm_year -= 1900;     /* Convert to UNIX time. */
535                /* FALLTHROUGH */
536        case 8:				/* MMDDhhmm */
537                t->tm_mon = ATOI2(arg);
538                --t->tm_mon;    	/* Convert from 01-12 to 00-11 */
539                t->tm_mday = ATOI2(arg);
540                t->tm_hour = ATOI2(arg);
541                t->tm_min = ATOI2(arg);
542                break;
543        case 4:				/* hhmm */
544                t->tm_hour = ATOI2(arg);
545                t->tm_min = ATOI2(arg);
546                break;
547        default:
548                goto terr;
549        }
550        t->tm_isdst = -1;       	/* Figure out DST. */
551        timet = mktime(t);
552        if (timet == -1)
553terr:           errx(1,
554        "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
555        return timet;
556}
557
558
559/*
560 * onintr --
561 *	on interrupt, we inform the user how far we've gotten
562 */
563void
564onintr(signo)
565	int signo;
566{
567	char ct[80];
568	struct tm *tm;
569	time_t t = _int_to_time(buf[0].ut_time);
570
571	tm = localtime(&t);
572	(void) strftime(ct, sizeof(ct),
573			d_first ? "%a %e %b %R" : "%a %b %e %R",
574			tm);
575	printf("\ninterrupted %s\n", ct);
576	if (signo == SIGINT)
577		exit(1);
578	(void)fflush(stdout);			/* fix required for rsh */
579}
580