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