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