xref: /freebsd/usr.bin/last/last.c (revision 99e8005137088aafb1350e23b113d69b01b0820f)
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 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 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 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 void	 hostconv __P((char *));
100 void	 onintr __P((int));
101 char	*ttyconv __P((char *));
102 time_t	 dateconv __P((char *));
103 int	 want __P((struct utmp *));
104 void	 wtmp __P((void));
105 
106 void
107 usage(void)
108 {
109 	(void)fprintf(stderr,
110 	"usage: last [-#] [-f file] [-h hostname] [-t tty] [-s|w] [user ...]\n");
111 	exit(1);
112 }
113 
114 int
115 main(argc, argv)
116 	int argc;
117 	char *argv[];
118 {
119 	int ch;
120 	char *p;
121 
122 	(void) setlocale(LC_TIME, "");
123 	d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
124 
125 	maxrec = -1;
126 	snaptime = 0;
127 	while ((ch = getopt(argc, argv, "0123456789d:f:h:st:w")) != -1)
128 		switch (ch) {
129 		case '0': case '1': case '2': case '3': case '4':
130 		case '5': case '6': case '7': case '8': case '9':
131 			/*
132 			 * kludge: last was originally designed to take
133 			 * a number after a dash.
134 			 */
135 			if (maxrec == -1) {
136 				p = argv[optind - 1];
137 				if (p[0] == '-' && p[1] == ch && !p[2])
138 					maxrec = atol(++p);
139 				else
140 					maxrec = atol(argv[optind] + 1);
141 				if (!maxrec)
142 					exit(0);
143 			}
144 			break;
145 		case 'd':
146 			snaptime = dateconv(optarg);
147 			break;
148 		case 'f':
149 			file = optarg;
150 			break;
151 		case 'h':
152 			hostconv(optarg);
153 			addarg(HOST_TYPE, optarg);
154 			break;
155 		case 's':
156 			sflag++;	/* Show delta as seconds */
157 			break;
158 		case 't':
159 			addarg(TTY_TYPE, ttyconv(optarg));
160 			break;
161 		case 'w':
162 			width = 8;
163 			break;
164 		case '?':
165 		default:
166 			usage();
167 		}
168 
169 	if (sflag && width == 8) usage();
170 
171 	if (argc) {
172 		setlinebuf(stdout);
173 		for (argv += optind; *argv; ++argv) {
174 #define	COMPATIBILITY
175 #ifdef	COMPATIBILITY
176 			/* code to allow "last p5" to work */
177 			addarg(TTY_TYPE, ttyconv(*argv));
178 #endif
179 			addarg(USER_TYPE, *argv);
180 		}
181 	}
182 	wtmp();
183 	exit(0);
184 }
185 
186 /*
187  * wtmp --
188  *	read through the wtmp file
189  */
190 void
191 wtmp()
192 {
193 	struct utmp	*bp;			/* current structure */
194 	struct ttytab	*tt, *ttx;		/* ttylist entry */
195 	struct stat	stb;			/* stat of file for size */
196 	long	bl;
197 	time_t	delta;				/* time difference */
198 	int	bytes, wfd;
199 	char    *crmsg;
200 	char ct[80];
201 	struct tm *tm;
202 	int	 snapfound = 0;			/* found snapshot entry? */
203 
204 	LIST_INIT(&ttylist);
205 
206 	if ((wfd = open(file, O_RDONLY, 0)) < 0 || fstat(wfd, &stb) == -1)
207 		err(1, "%s", file);
208 	bl = (stb.st_size + sizeof(buf) - 1) / sizeof(buf);
209 
210 	(void)time(&buf[0].ut_time);
211 	(void)signal(SIGINT, onintr);
212 	(void)signal(SIGQUIT, onintr);
213 
214 	while (--bl >= 0) {
215 		if (lseek(wfd, (off_t)(bl * sizeof(buf)), L_SET) == -1 ||
216 		    (bytes = read(wfd, buf, sizeof(buf))) == -1)
217 			err(1, "%s", file);
218 		for (bp = &buf[bytes / sizeof(buf[0]) - 1]; bp >= buf; --bp) {
219 			/*
220 			 * if the terminal line is '~', the machine stopped.
221 			 * see utmp(5) for more info.
222 			 */
223 			if (bp->ut_line[0] == '~' && !bp->ut_line[1]) {
224 				/* everybody just logged out */
225 				for (tt = LIST_FIRST(&ttylist); tt;) {
226 					LIST_REMOVE(tt, list);
227 					ttx = tt;
228 					tt = LIST_NEXT(tt, list);
229 					free(ttx);
230 				}
231 				currentout = -bp->ut_time;
232 				crmsg = strncmp(bp->ut_name, "shutdown",
233 				    UT_NAMESIZE) ? "crash" : "shutdown";
234 				/*
235 				 * if we're in snapshot mode, we want to
236 				 * exit if this shutdown/reboot appears
237 				 * while we we are tracking the active
238 				 * range
239 				 */
240 				if (snaptime && snapfound)
241 					return;
242 				/*
243 				 * don't print shutdown/reboot entries
244 				 * unless flagged for
245 				 */
246 				if (!snaptime && want(bp)) {
247 					tm = localtime(&bp->ut_time);
248 					(void) strftime(ct, sizeof(ct),
249 						     d_first ? "%a %e %b %R" :
250 							       "%a %b %e %R",
251 						     tm);
252 					printf("%-*.*s %-*.*s %-*.*s %s\n",
253 					    UT_NAMESIZE, UT_NAMESIZE,
254 					    bp->ut_name, UT_LINESIZE,
255 					    UT_LINESIZE, bp->ut_line,
256 					    UT_HOSTSIZE, UT_HOSTSIZE,
257 					    bp->ut_host, ct);
258 					if (maxrec != -1 && !--maxrec)
259 						return;
260 				}
261 				continue;
262 			}
263 			/*
264 			 * if the line is '{' or '|', date got set; see
265 			 * utmp(5) for more info.
266 			 */
267 			if ((bp->ut_line[0] == '{' || bp->ut_line[0] == '|')
268 			    && !bp->ut_line[1]) {
269 				if (want(bp) && !snaptime) {
270 					tm = localtime(&bp->ut_time);
271 					(void) strftime(ct, sizeof(ct),
272 						     d_first ? "%a %e %b %R" :
273 							       "%a %b %e %R",
274 						     tm);
275 					printf("%-*.*s %-*.*s %-*.*s %s\n",
276 					    UT_NAMESIZE, UT_NAMESIZE, bp->ut_name,
277 					    UT_LINESIZE, UT_LINESIZE, bp->ut_line,
278 					    UT_HOSTSIZE, UT_HOSTSIZE, bp->ut_host,
279 					    ct);
280 					if (maxrec && !--maxrec)
281 						return;
282 				}
283 				continue;
284 			}
285 			/* find associated tty */
286 			LIST_FOREACH(tt, &ttylist, list)
287 			    if (!strncmp(tt->tty, bp->ut_line, UT_LINESIZE))
288 				    break;
289 
290 			if (tt == NULL) {
291 				/* add new one */
292 				tt = malloc(sizeof(struct ttytab));
293 				if (tt == NULL)
294 					err(1, "malloc failure");
295 				tt->logout = currentout;
296 				strncpy(tt->tty, bp->ut_line, UT_LINESIZE);
297 				LIST_INSERT_HEAD(&ttylist, tt, list);
298 			}
299 
300 			/*
301 			 * print record if not in snapshot mode and wanted
302 			 * or in snapshot mode and in snapshot range
303 			 */
304 			if (bp->ut_name[0] && (want(bp) ||
305 			    (bp->ut_time < snaptime &&
306 				(tt->logout > snaptime || tt->logout < 1)))) {
307 				snapfound = 1;
308 				/*
309 				 * when uucp and ftp log in over a network, the entry in
310 				 * the utmp file is the name plus their process id.  See
311 				 * etc/ftpd.c and usr.bin/uucp/uucpd.c for more information.
312 				 */
313 				if (!strncmp(bp->ut_line, "ftp", sizeof("ftp") - 1))
314 					bp->ut_line[3] = '\0';
315 				else if (!strncmp(bp->ut_line, "uucp", sizeof("uucp") - 1))
316 					bp->ut_line[4] = '\0';
317 				tm = localtime(&bp->ut_time);
318 				(void) strftime(ct, sizeof(ct),
319 				    d_first ? "%a %e %b %R" :
320 				    "%a %b %e %R",
321 				    tm);
322 				printf("%-*.*s %-*.*s %-*.*s %s ",
323 				    UT_NAMESIZE, UT_NAMESIZE, bp->ut_name,
324 				    UT_LINESIZE, UT_LINESIZE, bp->ut_line,
325 				    UT_HOSTSIZE, UT_HOSTSIZE, bp->ut_host,
326 				    ct);
327 				if (!tt->logout)
328 					puts("  still logged in");
329 				else {
330 					if (tt->logout < 0) {
331 						tt->logout = -tt->logout;
332 						printf("- %s", crmsg);
333 					}
334 					else {
335 						tm = localtime(&tt->logout);
336 						(void) strftime(ct, sizeof(ct), "%R", tm);
337 						printf("- %s", ct);
338 					}
339 					delta = tt->logout - bp->ut_time;
340 					if ( sflag ) {
341 						printf("  (%8lu)\n",
342 						    delta);
343 					} else {
344 						tm = gmtime(&delta);
345 						(void) strftime(ct, sizeof(ct),
346 						    width >= 8 ? "%T" : "%R",
347 						    tm);
348 						if (delta < 86400)
349 							printf("  (%s)\n", ct);
350 						else
351 							printf(" (%ld+%s)\n",
352 							    delta / 86400,  ct);
353 					}
354 				}
355 				if (maxrec != -1 && !--maxrec)
356 					return;
357 			}
358 			tt->logout = bp->ut_time;
359 		}
360 	}
361 	tm = localtime(&buf[0].ut_time);
362 	(void) strftime(ct, sizeof(ct), "\nwtmp begins %c\n", tm);
363 	printf("%s", ct);
364 }
365 
366 /*
367  * want --
368  *	see if want this entry
369  */
370 int
371 want(bp)
372 	struct utmp *bp;
373 {
374 	ARG *step;
375 
376 	if (snaptime)
377 		return (NO);
378 
379 	if (!arglist)
380 		return (YES);
381 
382 	for (step = arglist; step; step = step->next)
383 		switch(step->type) {
384 		case HOST_TYPE:
385 			if (!strncasecmp(step->name, bp->ut_host, UT_HOSTSIZE))
386 				return (YES);
387 			break;
388 		case TTY_TYPE:
389 			if (!strncmp(step->name, bp->ut_line, UT_LINESIZE))
390 				return (YES);
391 			break;
392 		case USER_TYPE:
393 			if (!strncmp(step->name, bp->ut_name, UT_NAMESIZE))
394 				return (YES);
395 			break;
396 	}
397 	return (NO);
398 }
399 
400 /*
401  * addarg --
402  *	add an entry to a linked list of arguments
403  */
404 void
405 addarg(type, arg)
406 	int type;
407 	char *arg;
408 {
409 	ARG *cur;
410 
411 	if (!(cur = (ARG *)malloc((u_int)sizeof(ARG))))
412 		err(1, "malloc failure");
413 	cur->next = arglist;
414 	cur->type = type;
415 	cur->name = arg;
416 	arglist = cur;
417 }
418 
419 /*
420  * hostconv --
421  *	convert the hostname to search pattern; if the supplied host name
422  *	has a domain attached that is the same as the current domain, rip
423  *	off the domain suffix since that's what login(1) does.
424  */
425 void
426 hostconv(arg)
427 	char *arg;
428 {
429 	static int first = 1;
430 	static char *hostdot, name[MAXHOSTNAMELEN];
431 	char *argdot;
432 
433 	if (!(argdot = strchr(arg, '.')))
434 		return;
435 	if (first) {
436 		first = 0;
437 		if (gethostname(name, sizeof(name)))
438 			err(1, "gethostname");
439 		hostdot = strchr(name, '.');
440 	}
441 	if (hostdot && !strcasecmp(hostdot, argdot))
442 		*argdot = '\0';
443 }
444 
445 /*
446  * ttyconv --
447  *	convert tty to correct name.
448  */
449 char *
450 ttyconv(arg)
451 	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((u_int)8)))
462 			err(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  */
482 time_t
483 dateconv(arg)
484         char *arg;
485 {
486         time_t timet;
487         struct tm *t;
488         int yearset;
489         char *p;
490 
491         /* Start with the current time. */
492         if (time(&timet) < 0)
493                 err(1, "time");
494         if ((t = localtime(&timet)) == NULL)
495                 err(1, "localtime");
496 
497         /* [[CC]YY]MMDDhhmm[.SS] */
498         if ((p = strchr(arg, '.')) == NULL)
499                 t->tm_sec = 0; 		/* Seconds defaults to 0. */
500         else {
501                 if (strlen(p + 1) != 2)
502                         goto terr;
503                 *p++ = '\0';
504                 t->tm_sec = ATOI2(p);
505         }
506 
507         yearset = 0;
508         switch (strlen(arg)) {
509         case 12:                	/* CCYYMMDDhhmm */
510                 t->tm_year = ATOI2(arg);
511                 t->tm_year *= 100;
512                 yearset = 1;
513                 /* FALLTHOUGH */
514         case 10:                	/* YYMMDDhhmm */
515                 if (yearset) {
516                         yearset = ATOI2(arg);
517                         t->tm_year += yearset;
518                 } else {
519                         yearset = ATOI2(arg);
520                         if (yearset < 69)
521                                 t->tm_year = yearset + 2000;
522                         else
523                                 t->tm_year = yearset + 1900;
524                 }
525                 t->tm_year -= 1900;     /* Convert to UNIX time. */
526                 /* FALLTHROUGH */
527         case 8:				/* MMDDhhmm */
528                 t->tm_mon = ATOI2(arg);
529                 --t->tm_mon;    	/* Convert from 01-12 to 00-11 */
530                 t->tm_mday = ATOI2(arg);
531                 t->tm_hour = ATOI2(arg);
532                 t->tm_min = ATOI2(arg);
533                 break;
534         case 4:				/* hhmm */
535                 t->tm_hour = ATOI2(arg);
536                 t->tm_min = ATOI2(arg);
537                 break;
538         default:
539                 goto terr;
540         }
541         t->tm_isdst = -1;       	/* Figure out DST. */
542         timet = mktime(t);
543         if (timet == -1)
544 terr:           errx(1,
545         "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
546         return timet;
547 }
548 
549 
550 /*
551  * onintr --
552  *	on interrupt, we inform the user how far we've gotten
553  */
554 void
555 onintr(signo)
556 	int signo;
557 {
558 	char ct[80];
559 	struct tm *tm;
560 
561 	tm = localtime(&buf[0].ut_time);
562 	(void) strftime(ct, sizeof(ct),
563 			d_first ? "%a %e %b %R" : "%a %b %e %R",
564 			tm);
565 	printf("\ninterrupted %s\n", ct);
566 	if (signo == SIGINT)
567 		exit(1);
568 	(void)fflush(stdout);			/* fix required for rsh */
569 }
570