xref: /freebsd/usr.bin/last/last.c (revision eacee0ff7ec955b32e09515246bd97b6edcd2b0f)
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  * $FreeBSD$
34  */
35 
36 #ifndef lint
37 static const char copyright[] =
38 "@(#) Copyright (c) 1987, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif /* not lint */
41 
42 #ifndef lint
43 static const char sccsid[] = "@(#)last.c	8.2 (Berkeley) 4/2/94";
44 #endif /* not lint */
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 
67 static struct utmp	buf[1024];		/* utmp read buffer */
68 
69 typedef 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;
77 ARG	*arglist;				/* head of linked list */
78 
79 LIST_HEAD(ttylisthead, ttytab) ttylist;
80 
81 struct ttytab {
82 	time_t	logout;				/* log out time */
83 	char	tty[UT_LINESIZE + 1];		/* terminal name */
84 	LIST_ENTRY(ttytab) list;
85 };
86 
87 static long	currentout,			/* current logout value */
88 		maxrec;				/* records to display */
89 static const	char *file = _PATH_WTMP;		/* wtmp file */
90 static int	sflag = 0;			/* show delta in seconds */
91 static int	width = 5;			/* show seconds in delta */
92 static int      d_first;
93 static time_t	snaptime;			/* if != 0, we will only
94 						 * report users logged in
95 						 * at this snapshot time
96 						 */
97 
98 void	 addarg __P((int, char *));
99 time_t	 dateconv __P((char *));
100 void	 hostconv __P((char *));
101 void	 onintr __P((int));
102 char	*ttyconv __P((char *));
103 int	 want __P((struct utmp *));
104 void	 usage __P((void));
105 void	 wtmp __P((void));
106 
107 void
108 usage(void)
109 {
110 	(void)fprintf(stderr,
111 "usage: last [-#] [-d [[CC]YY][MMDD]hhmm[.SS]] [-f file] [-h hostname]\n"
112 "\t[-t tty] [-s|w] [user ...]\n");
113 	exit(1);
114 }
115 
116 int
117 main(argc, argv)
118 	int argc;
119 	char *argv[];
120 {
121 	int ch;
122 	char *p;
123 
124 	(void) setlocale(LC_TIME, "");
125 	d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
126 
127 	maxrec = -1;
128 	snaptime = 0;
129 	while ((ch = getopt(argc, argv, "0123456789d:f:h:st:w")) != -1)
130 		switch (ch) {
131 		case '0': case '1': case '2': case '3': case '4':
132 		case '5': case '6': case '7': case '8': case '9':
133 			/*
134 			 * kludge: last was originally designed to take
135 			 * a number after a dash.
136 			 */
137 			if (maxrec == -1) {
138 				p = argv[optind - 1];
139 				if (p[0] == '-' && p[1] == ch && !p[2])
140 					maxrec = atol(++p);
141 				else
142 					maxrec = atol(argv[optind] + 1);
143 				if (!maxrec)
144 					exit(0);
145 			}
146 			break;
147 		case 'd':
148 			snaptime = dateconv(optarg);
149 			break;
150 		case 'f':
151 			file = optarg;
152 			break;
153 		case 'h':
154 			hostconv(optarg);
155 			addarg(HOST_TYPE, optarg);
156 			break;
157 		case 's':
158 			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  */
192 void
193 wtmp()
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  */
379 int
380 want(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  */
413 void
414 addarg(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  */
434 void
435 hostconv(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  */
458 char *
459 ttyconv(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  */
491 time_t
492 dateconv(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)
553 terr:           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  */
563 void
564 onintr(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