xref: /freebsd/usr.bin/last/last.c (revision e627b39baccd1ec9129690167cf5e6d860509655)
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 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 char sccsid[] = "@(#)last.c	8.2 (Berkeley) 4/2/94";
42 #endif /* not lint */
43 
44 #include <sys/param.h>
45 #include <sys/stat.h>
46 
47 #include <err.h>
48 #include <fcntl.h>
49 #include <locale.h>
50 #include <paths.h>
51 #include <signal.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <time.h>
56 #include <unistd.h>
57 #include <utmp.h>
58 #include <sys/queue.h>
59 
60 #define	NO	0				/* false/no */
61 #define	YES	1				/* true/yes */
62 
63 static struct utmp	buf[1024];		/* utmp read buffer */
64 
65 typedef struct arg {
66 	char	*name;				/* argument */
67 #define	HOST_TYPE	-2
68 #define	TTY_TYPE	-3
69 #define	USER_TYPE	-4
70 	int	type;				/* type of arg */
71 	struct arg	*next;			/* linked list pointer */
72 } ARG;
73 ARG	*arglist;				/* head of linked list */
74 
75 LIST_HEAD(ttylisthead, ttytab) ttylist;
76 
77 struct ttytab {
78 	long	logout;				/* log out time */
79 	char	tty[UT_LINESIZE + 1];		/* terminal name */
80 	LIST_ENTRY(ttytab) list;
81 };
82 
83 static long	currentout,			/* current logout value */
84 		maxrec;				/* records to display */
85 static char	*file = _PATH_WTMP;		/* wtmp file */
86 
87 void	 addarg __P((int, char *));
88 void	 hostconv __P((char *));
89 void	 onintr __P((int));
90 char	*ttyconv __P((char *));
91 int	 want __P((struct utmp *));
92 void	 wtmp __P((void));
93 
94 int
95 main(argc, argv)
96 	int argc;
97 	char *argv[];
98 {
99 	extern int optind;
100 	extern char *optarg;
101 	int ch;
102 	char *p;
103 
104 	(void) setlocale(LC_TIME, "");
105 
106 	maxrec = -1;
107 	while ((ch = getopt(argc, argv, "0123456789f:h:t:")) != EOF)
108 		switch (ch) {
109 		case '0': case '1': case '2': case '3': case '4':
110 		case '5': case '6': case '7': case '8': case '9':
111 			/*
112 			 * kludge: last was originally designed to take
113 			 * a number after a dash.
114 			 */
115 			if (maxrec == -1) {
116 				p = argv[optind - 1];
117 				if (p[0] == '-' && p[1] == ch && !p[2])
118 					maxrec = atol(++p);
119 				else
120 					maxrec = atol(argv[optind] + 1);
121 				if (!maxrec)
122 					exit(0);
123 			}
124 			break;
125 		case 'f':
126 			file = optarg;
127 			break;
128 		case 'h':
129 			hostconv(optarg);
130 			addarg(HOST_TYPE, optarg);
131 			break;
132 		case 't':
133 			addarg(TTY_TYPE, ttyconv(optarg));
134 			break;
135 		case '?':
136 		default:
137 			(void)fprintf(stderr,
138 	"usage: last [-#] [-f file] [-t tty] [-h hostname] [user ...]\n");
139 			exit(1);
140 		}
141 
142 	if (argc) {
143 		setlinebuf(stdout);
144 		for (argv += optind; *argv; ++argv) {
145 #define	COMPATIBILITY
146 #ifdef	COMPATIBILITY
147 			/* code to allow "last p5" to work */
148 			addarg(TTY_TYPE, ttyconv(*argv));
149 #endif
150 			addarg(USER_TYPE, *argv);
151 		}
152 	}
153 	wtmp();
154 	exit(0);
155 }
156 
157 /*
158  * wtmp --
159  *	read through the wtmp file
160  */
161 void
162 wtmp()
163 {
164 	struct utmp	*bp;			/* current structure */
165 	struct ttytab	*tt;				/* ttylist entry */
166 	struct stat	stb;			/* stat of file for size */
167 	long	bl, delta;			/* time difference */
168 	int	bytes, wfd;
169 	char    *crmsg;
170 	char ct[80];
171 	struct tm *tm;
172 
173 	LIST_INIT(&ttylist);
174 
175 	if ((wfd = open(file, O_RDONLY, 0)) < 0 || fstat(wfd, &stb) == -1)
176 		err(1, "%s", file);
177 	bl = (stb.st_size + sizeof(buf) - 1) / sizeof(buf);
178 
179 	(void)time(&buf[0].ut_time);
180 	(void)signal(SIGINT, onintr);
181 	(void)signal(SIGQUIT, onintr);
182 
183 	while (--bl >= 0) {
184 		if (lseek(wfd, (off_t)(bl * sizeof(buf)), L_SET) == -1 ||
185 		    (bytes = read(wfd, buf, sizeof(buf))) == -1)
186 			err(1, "%s", file);
187 		for (bp = &buf[bytes / sizeof(buf[0]) - 1]; bp >= buf; --bp) {
188 			/*
189 			 * if the terminal line is '~', the machine stopped.
190 			 * see utmp(5) for more info.
191 			 */
192 			if (bp->ut_line[0] == '~' && !bp->ut_line[1]) {
193 				/* everybody just logged out */
194 				for (tt = ttylist.lh_first; tt; tt = tt->list.le_next) {
195 					LIST_REMOVE(tt, list);
196 					free(tt);
197 				}
198 				currentout = -bp->ut_time;
199 				crmsg = strncmp(bp->ut_name, "shutdown",
200 				    UT_NAMESIZE) ? "crash" : "shutdown";
201 				if (want(bp)) {
202 					tm = localtime(&bp->ut_time);
203 					(void) strftime(ct, sizeof(ct), "%c", tm);
204 					printf("%-*.*s  %-*.*s %-*.*s %10.10s %5.5s \n",
205 					    UT_NAMESIZE, UT_NAMESIZE,
206 					    bp->ut_name, UT_LINESIZE,
207 					    UT_LINESIZE, bp->ut_line,
208 					    UT_HOSTSIZE, UT_HOSTSIZE,
209 					    bp->ut_host, ct, ct + 11);
210 					if (maxrec != -1 && !--maxrec)
211 						return;
212 				}
213 				continue;
214 			}
215 			/*
216 			 * if the line is '{' or '|', date got set; see
217 			 * utmp(5) for more info.
218 			 */
219 			if ((bp->ut_line[0] == '{' || bp->ut_line[0] == '|')
220 			    && !bp->ut_line[1]) {
221 				if (want(bp)) {
222 					tm = localtime(&bp->ut_time);
223 					(void) strftime(ct, sizeof(ct), "%c", tm);
224 					printf("%-*.*s  %-*.*s %-*.*s %10.10s %5.5s \n",
225 					    UT_NAMESIZE, UT_NAMESIZE, bp->ut_name,
226 					    UT_LINESIZE, UT_LINESIZE, bp->ut_line,
227 					    UT_HOSTSIZE, UT_HOSTSIZE, bp->ut_host,
228 					    ct, ct + 11);
229 					if (maxrec && !--maxrec)
230 						return;
231 				}
232 				continue;
233 			}
234 			if (bp->ut_name[0] == '\0' || want(bp)) {
235 				/* find associated tty */
236 				for (tt = ttylist.lh_first; ; tt = tt->list.le_next) {
237 					if (tt == NULL) {
238 						/* add new one */
239 						tt = malloc(sizeof(struct ttytab));
240 						if (tt == NULL)
241 							err(1, "malloc failure");
242 						tt->logout = currentout;
243 						strncpy(tt->tty, bp->ut_line, UT_LINESIZE);
244 						LIST_INSERT_HEAD(&ttylist, tt, list);
245 						break;
246 					}
247 					if (!strncmp(tt->tty, bp->ut_line, UT_LINESIZE))
248 						break;
249 				}
250 				if (bp->ut_name[0]) {
251 					/*
252 					 * when uucp and ftp log in over a network, the entry in
253 					 * the utmp file is the name plus their process id.  See
254 					 * etc/ftpd.c and usr.bin/uucp/uucpd.c for more information.
255 					 */
256 					if (!strncmp(bp->ut_line, "ftp", sizeof("ftp") - 1))
257 						bp->ut_line[3] = '\0';
258 					else if (!strncmp(bp->ut_line, "uucp", sizeof("uucp") - 1))
259 						bp->ut_line[4] = '\0';
260 					tm = localtime(&bp->ut_time);
261 					(void) strftime(ct, sizeof(ct), "%c", tm);
262 					printf("%-*.*s  %-*.*s %-*.*s %10.10s %5.5s ",
263 					    UT_NAMESIZE, UT_NAMESIZE, bp->ut_name,
264 					    UT_LINESIZE, UT_LINESIZE, bp->ut_line,
265 					    UT_HOSTSIZE, UT_HOSTSIZE, bp->ut_host,
266 					    ct, ct + 11);
267 					if (!tt->logout)
268 						puts("  still logged in");
269 					else {
270 						if (tt->logout < 0) {
271 							tt->logout = -tt->logout;
272 							printf("- %s", crmsg);
273 						}
274 						else {
275 							tm = localtime(&tt->logout);
276 							(void) strftime(ct, sizeof(ct), "%c", tm);
277 							printf("- %5.5s", ct + 11);
278 						}
279 						delta = tt->logout - bp->ut_time;
280 						tm = gmtime(&delta);
281 						(void) strftime(ct, sizeof(ct), "%c", tm);
282 						if (delta < 86400)
283 							printf("  (%5.5s)\n", ct + 11);
284 						else
285 							printf(" (%ld+%5.5s)\n",
286 							    delta / 86400, ct + 11);
287 					}
288 					LIST_REMOVE(tt, list);
289 					free(tt);
290 					if (maxrec != -1 && !--maxrec)
291 						return;
292 				} else {
293 					tt->logout = bp->ut_time;
294 				}
295 			}
296 		}
297 	}
298 	tm = localtime(&buf[0].ut_time);
299 	(void) strftime(ct, sizeof(ct), "%c", tm);
300 	printf("\nwtmp begins %10.10s %5.5s \n", ct, ct + 11);
301 }
302 
303 /*
304  * want --
305  *	see if want this entry
306  */
307 int
308 want(bp)
309 	struct utmp *bp;
310 {
311 	ARG *step;
312 
313 	if (!arglist)
314 		return (YES);
315 
316 	for (step = arglist; step; step = step->next)
317 		switch(step->type) {
318 		case HOST_TYPE:
319 			if (!strncasecmp(step->name, bp->ut_host, UT_HOSTSIZE))
320 				return (YES);
321 			break;
322 		case TTY_TYPE:
323 			if (!strncmp(step->name, bp->ut_line, UT_LINESIZE))
324 				return (YES);
325 			break;
326 		case USER_TYPE:
327 			if (!strncmp(step->name, bp->ut_name, UT_NAMESIZE))
328 				return (YES);
329 			break;
330 	}
331 	return (NO);
332 }
333 
334 /*
335  * addarg --
336  *	add an entry to a linked list of arguments
337  */
338 void
339 addarg(type, arg)
340 	int type;
341 	char *arg;
342 {
343 	ARG *cur;
344 
345 	if (!(cur = (ARG *)malloc((u_int)sizeof(ARG))))
346 		err(1, "malloc failure");
347 	cur->next = arglist;
348 	cur->type = type;
349 	cur->name = arg;
350 	arglist = cur;
351 }
352 
353 /*
354  * hostconv --
355  *	convert the hostname to search pattern; if the supplied host name
356  *	has a domain attached that is the same as the current domain, rip
357  *	off the domain suffix since that's what login(1) does.
358  */
359 void
360 hostconv(arg)
361 	char *arg;
362 {
363 	static int first = 1;
364 	static char *hostdot, name[MAXHOSTNAMELEN];
365 	char *argdot;
366 
367 	if (!(argdot = strchr(arg, '.')))
368 		return;
369 	if (first) {
370 		first = 0;
371 		if (gethostname(name, sizeof(name)))
372 			err(1, "gethostname");
373 		hostdot = strchr(name, '.');
374 	}
375 	if (hostdot && !strcasecmp(hostdot, argdot))
376 		*argdot = '\0';
377 }
378 
379 /*
380  * ttyconv --
381  *	convert tty to correct name.
382  */
383 char *
384 ttyconv(arg)
385 	char *arg;
386 {
387 	char *mval;
388 
389 	/*
390 	 * kludge -- we assume that all tty's end with
391 	 * a two character suffix.
392 	 */
393 	if (strlen(arg) == 2) {
394 		/* either 6 for "ttyxx" or 8 for "console" */
395 		if (!(mval = malloc((u_int)8)))
396 			err(1, "malloc failure");
397 		if (!strcmp(arg, "co"))
398 			(void)strcpy(mval, "console");
399 		else {
400 			(void)strcpy(mval, "tty");
401 			(void)strcpy(mval + 3, arg);
402 		}
403 		return (mval);
404 	}
405 	if (!strncmp(arg, _PATH_DEV, sizeof(_PATH_DEV) - 1))
406 		return (arg + 5);
407 	return (arg);
408 }
409 
410 /*
411  * onintr --
412  *	on interrupt, we inform the user how far we've gotten
413  */
414 void
415 onintr(signo)
416 	int signo;
417 {
418 	char ct[80];
419 	struct tm *tm;
420 
421 	tm = localtime(&buf[0].ut_time);
422 	(void) strftime(ct, sizeof(ct), "%c", tm);
423 	printf("\ninterrupted %10.10s %5.5s \n", ct, ct + 11);
424 	if (signo == SIGINT)
425 		exit(1);
426 	(void)fflush(stdout);			/* fix required for rsh */
427 }
428