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