ac.c revision 126750
1/*
2 *      Copyright (c) 1994 Christopher G. Demetriou.
3 *      @(#)Copyright (c) 1994, Simon J. Gerraty.
4 *
5 *      This is free software.  It comes with NO WARRANTY.
6 *      Permission to use, modify and distribute this source code
7 *      is granted subject to the following conditions.
8 *      1/ that the above copyright notice and this notice
9 *      are preserved in all copies and that due credit be given
10 *      to the author.
11 *      2/ that any changes to this code are clearly commented
12 *      as such so that the author does not get blamed for bugs
13 *      other than his own.
14 */
15
16#include <sys/cdefs.h>
17__FBSDID("$FreeBSD: head/usr.sbin/ac/ac.c 126750 2004-03-08 19:20:06Z gad $");
18
19#include <sys/types.h>
20#include <sys/time.h>
21#include <err.h>
22#include <errno.h>
23#include <langinfo.h>
24#include <locale.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <timeconv.h>
29#include <unistd.h>
30#include <utmp.h>
31
32/*
33 * this is for our list of currently logged in sessions
34 */
35struct utmp_list {
36	struct utmp_list *next;
37	struct utmp usr;
38};
39
40/*
41 * this is for our list of users that are accumulating time.
42 */
43struct user_list {
44	struct user_list *next;
45	char	name[UT_NAMESIZE+1];
46	time_t	secs;
47};
48
49/*
50 * this is for chosing whether to ignore a login
51 */
52struct tty_list {
53	struct tty_list *next;
54	char	name[UT_LINESIZE+3];
55	size_t	len;
56	int	ret;
57};
58
59/*
60 * globals - yes yuk
61 */
62#ifdef CONSOLE_TTY
63static char 	*Console = CONSOLE_TTY;
64#endif
65static time_t	Total = 0;
66static time_t	FirstTime = 0;
67static int	Flags = 0;
68static struct user_list *Users = NULL;
69static struct tty_list *Ttys = NULL;
70
71#define NEW(type) (type *)malloc(sizeof (type))
72
73#define	AC_W	1				/* not _PATH_WTMP */
74#define	AC_D	2				/* daily totals (ignore -p) */
75#define	AC_P	4				/* per-user totals */
76#define	AC_U	8				/* specified users only */
77#define	AC_T	16				/* specified ttys only */
78
79#ifdef DEBUG
80static int Debug = 0;
81#endif
82
83int			main(int, char **);
84int			ac(FILE *);
85struct tty_list		*add_tty(char *);
86#ifdef DEBUG
87const char		*debug_pfx(const struct utmp *, const struct utmp *);
88#endif
89int			do_tty(char *);
90FILE			*file(const char *);
91struct utmp_list	*log_in(struct utmp_list *, struct utmp *);
92struct utmp_list	*log_out(struct utmp_list *, struct utmp *);
93int			on_console(struct utmp_list *);
94void			show(const char *, time_t);
95void			show_today(struct user_list *, struct utmp_list *,
96			    time_t);
97void			show_users(struct user_list *);
98struct user_list	*update_user(struct user_list *, char *, time_t);
99void			usage(void);
100
101/*
102 * open wtmp or die
103 */
104FILE *
105file(const char *name)
106{
107	FILE *fp;
108
109	if ((fp = fopen(name, "r")) == NULL)
110		err(1, "%s", name);
111	/* in case we want to discriminate */
112	if (strcmp(_PATH_WTMP, name))
113		Flags |= AC_W;
114	return fp;
115}
116
117struct tty_list *
118add_tty(char *name)
119{
120	struct tty_list *tp;
121	char *rcp;
122
123	Flags |= AC_T;
124
125	if ((tp = NEW(struct tty_list)) == NULL)
126		errx(1, "malloc failed");
127	tp->len = 0;				/* full match */
128	tp->ret = 1;				/* do if match */
129	if (*name == '!') {			/* don't do if match */
130		tp->ret = 0;
131		name++;
132	}
133	strlcpy(tp->name, name, sizeof (tp->name));
134	if ((rcp = strchr(tp->name, '*')) != NULL) {	/* wild card */
135		*rcp = '\0';
136		tp->len = strlen(tp->name);	/* match len bytes only */
137	}
138	tp->next = Ttys;
139	Ttys = tp;
140	return Ttys;
141}
142
143/*
144 * should we process the named tty?
145 */
146int
147do_tty(char *name)
148{
149	struct tty_list *tp;
150	int def_ret = 0;
151
152	for (tp = Ttys; tp != NULL; tp = tp->next) {
153		if (tp->ret == 0)		/* specific don't */
154			def_ret = 1;		/* default do */
155		if (tp->len != 0) {
156			if (strncmp(name, tp->name, tp->len) == 0)
157				return tp->ret;
158		} else {
159			if (strncmp(name, tp->name, sizeof (tp->name)) == 0)
160				return tp->ret;
161		}
162	}
163	return def_ret;
164}
165
166#ifdef CONSOLE_TTY
167/*
168 * is someone logged in on Console?
169 */
170int
171on_console(struct utmp_list *head)
172{
173	struct utmp_list *up;
174
175	for (up = head; up; up = up->next) {
176		if (strncmp(up->usr.ut_line, Console,
177		    sizeof (up->usr.ut_line)) == 0)
178			return 1;
179	}
180	return 0;
181}
182#endif
183
184/*
185 * update user's login time
186 */
187struct user_list *
188update_user(struct user_list *head, char *name, time_t secs)
189{
190	struct user_list *up;
191
192	for (up = head; up != NULL; up = up->next) {
193		if (strncmp(up->name, name, UT_NAMESIZE) == 0) {
194			up->secs += secs;
195			Total += secs;
196			return head;
197		}
198	}
199	/*
200	 * not found so add new user unless specified users only
201	 */
202	if (Flags & AC_U)
203		return head;
204
205	if ((up = NEW(struct user_list)) == NULL)
206		errx(1, "malloc failed");
207	up->next = head;
208	strlcpy(up->name, name, sizeof (up->name));
209	up->secs = secs;
210	Total += secs;
211	return up;
212}
213
214#ifdef DEBUG
215/*
216 * Create a string which is the standard prefix for a debug line.  It
217 * includes a timestamp (perhaps with year), device-name, and user-name.
218 */
219const char *
220debug_pfx(const struct utmp *event_up, const struct utmp *userinf_up)
221{
222	static char str_result[40+UT_LINESIZE+UT_NAMESIZE];
223	static char thisyear[5];
224	size_t maxcopy;
225	time_t ut_timecopy;
226
227	if (thisyear[0] == '\0') {
228		/* Figure out what "this year" is. */
229		time(&ut_timecopy);
230		strlcpy(str_result, ctime(&ut_timecopy), sizeof(str_result));
231		strlcpy(thisyear, &str_result[20], sizeof(thisyear));
232	}
233
234	if (event_up->ut_time == 0)
235		strlcpy(str_result, "*ZeroTime* --:--:-- ", sizeof(str_result));
236	else {
237		/*
238		* The type of utmp.ut_time is not necessary type time_t, as
239		* it is explicitly defined as type int32_t.  Copy the value
240		* for platforms where sizeof(time_t) != sizeof(int32_t).
241		*/
242		ut_timecopy = _time32_to_time(event_up->ut_time);
243		strlcpy(str_result, ctime(&ut_timecopy), sizeof(str_result));
244		/*
245		 * Include the year, if it is not the same year as "now".
246		 */
247		if (strncmp(&str_result[20], thisyear, 4) == 0)
248			str_result[20] = '\0';
249		else {
250			str_result[24] = ' ';		/* Replace a '\n' */
251			str_result[25] = '\0';
252		}
253	}
254
255	if (userinf_up->ut_line[0] == '\0')
256		strlcat(str_result, "NoDev", sizeof(str_result));
257	else {
258		/* ut_line is not necessarily null-terminated. */
259		maxcopy = strlen(str_result) + UT_LINESIZE + 1;
260		if (maxcopy > sizeof(str_result))
261			maxcopy = sizeof(str_result);
262		strlcat(str_result, userinf_up->ut_line, maxcopy);
263	}
264	strlcat(str_result, ": ", sizeof(str_result));
265
266	if (userinf_up->ut_name[0] == '\0')
267		strlcat(str_result, "LogOff", sizeof(str_result));
268	else {
269		/* ut_name is not necessarily null-terminated. */
270		maxcopy = strlen(str_result) + UT_NAMESIZE + 1;
271		if (maxcopy > sizeof(str_result))
272			maxcopy = sizeof(str_result);
273		strlcat(str_result, userinf_up->ut_name, maxcopy);
274	}
275
276	return (str_result);
277}
278#endif
279
280int
281main(int argc, char *argv[])
282{
283	FILE *fp;
284	int c;
285
286	(void) setlocale(LC_TIME, "");
287
288	fp = NULL;
289	while ((c = getopt(argc, argv, "Dc:dpt:w:")) != -1) {
290		switch (c) {
291#ifdef DEBUG
292		case 'D':
293			Debug++;
294			break;
295#endif
296		case 'c':
297#ifdef CONSOLE_TTY
298			Console = optarg;
299#else
300			usage();		/* XXX */
301#endif
302			break;
303		case 'd':
304			Flags |= AC_D;
305			break;
306		case 'p':
307			Flags |= AC_P;
308			break;
309		case 't':			/* only do specified ttys */
310			add_tty(optarg);
311			break;
312		case 'w':
313			fp = file(optarg);
314			break;
315		case '?':
316		default:
317			usage();
318			break;
319		}
320	}
321	if (optind < argc) {
322		/*
323		 * initialize user list
324		 */
325		for (; optind < argc; optind++) {
326			Users = update_user(Users, argv[optind], (time_t)0);
327		}
328		Flags |= AC_U;			/* freeze user list */
329	}
330	if (Flags & AC_D)
331		Flags &= ~AC_P;
332	if (fp == NULL) {
333		/*
334		 * if _PATH_WTMP does not exist, exit quietly
335		 */
336		if (access(_PATH_WTMP, 0) != 0 && errno == ENOENT)
337			return 0;
338
339		fp = file(_PATH_WTMP);
340	}
341	ac(fp);
342
343	return 0;
344}
345
346/*
347 * print login time in decimal hours
348 */
349void
350show(const char *name, time_t secs)
351{
352	(void)printf("\t%-*s %8.2f\n", UT_NAMESIZE, name,
353	    ((double)secs / 3600));
354}
355
356void
357show_users(struct user_list *list)
358{
359	struct user_list *lp;
360
361	for (lp = list; lp; lp = lp->next)
362		show(lp->name, lp->secs);
363}
364
365/*
366 * print total login time for 24hr period in decimal hours
367 */
368void
369show_today(struct user_list *users, struct utmp_list *logins, time_t secs)
370{
371	struct user_list *up;
372	struct utmp_list *lp;
373	char date[64];
374	time_t yesterday = secs - 1;
375	static int d_first = -1;
376
377	if (d_first < 0)
378		d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
379	(void)strftime(date, sizeof (date),
380		       d_first ? "%e %b  total" : "%b %e  total",
381		       localtime(&yesterday));
382
383	/* restore the missing second */
384	yesterday++;
385
386	for (lp = logins; lp != NULL; lp = lp->next) {
387		secs = yesterday - lp->usr.ut_time;
388		Users = update_user(Users, lp->usr.ut_name, secs);
389		lp->usr.ut_time = yesterday;	/* as if they just logged in */
390	}
391	secs = 0;
392	for (up = users; up != NULL; up = up->next) {
393		secs += up->secs;
394		up->secs = 0;			/* for next day */
395	}
396	if (secs)
397		(void)printf("%s %11.2f\n", date, ((double)secs / 3600));
398}
399
400/*
401 * log a user out and update their times.
402 * if ut_line is "~", we log all users out as the system has
403 * been shut down.
404 */
405struct utmp_list *
406log_out(struct utmp_list *head, struct utmp *up)
407{
408	struct utmp_list *lp, *lp2, *tlp;
409	time_t secs;
410
411	for (lp = head, lp2 = NULL; lp != NULL; )
412		if (*up->ut_line == '~' || strncmp(lp->usr.ut_line, up->ut_line,
413		    sizeof (up->ut_line)) == 0) {
414			secs = up->ut_time - lp->usr.ut_time;
415			Users = update_user(Users, lp->usr.ut_name, secs);
416#ifdef DEBUG
417			if (Debug)
418				printf("%s logged out (%2d:%02d:%02d)\n",
419				    debug_pfx(up, &lp->usr), (int)(secs / 3600),
420				    (int)((secs % 3600) / 60),
421				    (int)(secs % 60));
422#endif
423			/*
424			 * now lose it
425			 */
426			tlp = lp;
427			lp = lp->next;
428			if (tlp == head)
429				head = lp;
430			else if (lp2 != NULL)
431				lp2->next = lp;
432			free(tlp);
433		} else {
434			lp2 = lp;
435			lp = lp->next;
436		}
437	return head;
438}
439
440
441/*
442 * if do_tty says ok, login a user
443 */
444struct utmp_list *
445log_in(struct utmp_list *head, struct utmp *up)
446{
447	struct utmp_list *lp;
448
449	/*
450	 * this could be a login. if we're not dealing with
451	 * the console name, say it is.
452	 *
453	 * If we are, and if ut_host==":0.0" we know that it
454	 * isn't a real login. _But_ if we have not yet recorded
455	 * someone being logged in on Console - due to the wtmp
456	 * file starting after they logged in, we'll pretend they
457	 * logged in, at the start of the wtmp file.
458	 */
459
460#ifdef CONSOLE_TTY
461	if (up->ut_host[0] == ':') {
462		/*
463		 * SunOS 4.0.2 does not treat ":0.0" as special but we
464		 * do.
465		 */
466		if (on_console(head))
467			return head;
468		/*
469		 * ok, no recorded login, so they were here when wtmp
470		 * started!  Adjust ut_time!
471		 */
472		up->ut_time = FirstTime;
473		/*
474		 * this allows us to pick the right logout
475		 */
476		strlcpy(up->ut_line, Console, sizeof (up->ut_line));
477	}
478#endif
479	/*
480	 * If we are doing specified ttys only, we ignore
481	 * anything else.
482	 */
483	if (Flags & AC_T)
484		if (!do_tty(up->ut_line))
485			return head;
486
487	/*
488	 * go ahead and log them in
489	 */
490	if ((lp = NEW(struct utmp_list)) == NULL)
491		errx(1, "malloc failed");
492	lp->next = head;
493	head = lp;
494	memmove((char *)&lp->usr, (char *)up, sizeof (struct utmp));
495#ifdef DEBUG
496	if (Debug) {
497		printf("%s logged in", debug_pfx(&lp->usr, up));
498		if (*up->ut_host)
499			printf(" (%-.*s)", (int)sizeof(up->ut_host),
500			    up->ut_host);
501		putchar('\n');
502	}
503#endif
504	return head;
505}
506
507int
508ac(FILE	*fp)
509{
510	struct utmp_list *lp, *head = NULL;
511	struct utmp usr;
512	struct tm *ltm;
513	time_t secs;
514	int day = -1;
515
516	while (fread((char *)&usr, sizeof(usr), 1, fp) == 1) {
517		if (!FirstTime)
518			FirstTime = usr.ut_time;
519		if (Flags & AC_D) {
520			time_t t = _int_to_time(usr.ut_time);
521			ltm = localtime(&t);
522			if (day >= 0 && day != ltm->tm_yday) {
523				day = ltm->tm_yday;
524				/*
525				 * print yesterday's total
526				 */
527				secs = usr.ut_time;
528				secs -= ltm->tm_sec;
529				secs -= 60 * ltm->tm_min;
530				secs -= 3600 * ltm->tm_hour;
531				show_today(Users, head, secs);
532			} else
533				day = ltm->tm_yday;
534		}
535		switch(*usr.ut_line) {
536		case '|':
537			secs = usr.ut_time;
538			break;
539		case '{':
540			secs -= usr.ut_time;
541			/*
542			 * adjust time for those logged in
543			 */
544			for (lp = head; lp != NULL; lp = lp->next)
545				lp->usr.ut_time -= secs;
546			break;
547		case '~':			/* reboot or shutdown */
548			head = log_out(head, &usr);
549			FirstTime = usr.ut_time; /* shouldn't be needed */
550			break;
551		default:
552			/*
553			 * if they came in on tty[p-sP-S]*, then it is only
554			 * a login session if the ut_host field is non-empty
555			 */
556			if (*usr.ut_name) {
557				if (strncmp(usr.ut_line, "tty", 3) == 0 ||
558				    strchr("pqrsPQRS", usr.ut_line[3]) != 0 ||
559				    *usr.ut_host != '\0')
560					head = log_in(head, &usr);
561#ifdef DEBUG
562				else if (Debug > 1)
563					/* Things such as 'screen' sessions. */
564					printf("%s - record ignored\n",
565					    debug_pfx(&usr, &usr));
566#endif
567			} else
568				head = log_out(head, &usr);
569			break;
570		}
571	}
572	(void)fclose(fp);
573	if (!(Flags & AC_W))
574		usr.ut_time = time((time_t *)0);
575	(void)strcpy(usr.ut_line, "~");
576
577	if (Flags & AC_D) {
578		time_t t = _int_to_time(usr.ut_time);
579		ltm = localtime(&t);
580		if (day >= 0 && day != ltm->tm_yday) {
581			/*
582			 * print yesterday's total
583			 */
584			secs = usr.ut_time;
585			secs -= ltm->tm_sec;
586			secs -= 60 * ltm->tm_min;
587			secs -= 3600 * ltm->tm_hour;
588			show_today(Users, head, secs);
589		}
590	}
591	/*
592	 * anyone still logged in gets time up to now
593	 */
594	head = log_out(head, &usr);
595
596	if (Flags & AC_D)
597		show_today(Users, head, time((time_t *)0));
598	else {
599		if (Flags & AC_P)
600			show_users(Users);
601		show("total", Total);
602	}
603	return 0;
604}
605
606void
607usage(void)
608{
609	(void)fprintf(stderr,
610#ifdef CONSOLE_TTY
611	    "ac [-dp] [-c console] [-t tty] [-w wtmp] [users ...]\n");
612#else
613	    "ac [-dp] [-t tty] [-w wtmp] [users ...]\n");
614#endif
615	exit(1);
616}
617