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