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