xref: /freebsd/usr.sbin/ac/ac.c (revision 7bd6fde3)
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$");
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  */
35 struct 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  */
43 struct 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  */
52 struct 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
63 static char 	*Console = CONSOLE_TTY;
64 #endif
65 static time_t	Total = 0;
66 static time_t	FirstTime = 0;
67 static int	Flags = 0;
68 static struct user_list *Users = NULL;
69 static 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
80 static int Debug = 0;
81 #endif
82 
83 int			main(int, char **);
84 int			ac(FILE *);
85 struct tty_list		*add_tty(char *);
86 #ifdef DEBUG
87 const char		*debug_pfx(const struct utmp *, const struct utmp *);
88 #endif
89 int			do_tty(char *);
90 FILE			*file(const char *);
91 struct utmp_list	*log_in(struct utmp_list *, struct utmp *);
92 struct utmp_list	*log_out(struct utmp_list *, struct utmp *);
93 int			on_console(struct utmp_list *);
94 void			show(const char *, time_t);
95 void			show_today(struct user_list *, struct utmp_list *,
96 			    time_t);
97 void			show_users(struct user_list *);
98 struct user_list	*update_user(struct user_list *, char *, time_t);
99 void			usage(void);
100 
101 /*
102  * open wtmp or die
103  */
104 FILE *
105 file(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 
117 struct tty_list *
118 add_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  */
146 int
147 do_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  */
170 int
171 on_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  */
187 struct user_list *
188 update_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  */
219 const char *
220 debug_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 
280 int
281 main(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  */
349 void
350 show(const char *name, time_t secs)
351 {
352 	(void)printf("\t%-*s %8.2f\n", UT_NAMESIZE, name,
353 	    ((double)secs / 3600));
354 }
355 
356 void
357 show_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  */
368 void
369 show_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  */
405 struct utmp_list *
406 log_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  */
444 struct utmp_list *
445 log_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 
507 int
508 ac(FILE	*fp)
509 {
510 	struct utmp_list *lp, *head = NULL;
511 	struct utmp usr;
512 	struct tm *ltm;
513 	time_t prev_secs, secs, ut_timecopy;
514 	int day, rfound, tchanged, tskipped;
515 
516 	day = -1;
517 	prev_secs = 1;			/* Minimum acceptable date == 1970 */
518 	rfound = tchanged = tskipped = 0;
519 	secs = 0;
520 	while (fread((char *)&usr, sizeof(usr), 1, fp) == 1) {
521 		rfound++;
522 		/*
523 		 * The type of utmp.ut_time is not necessary type time_t, as
524 		 * it is explicitly defined as type int32_t.  Copy the value
525 		 * for platforms where sizeof(time_t) != size(int32_t).
526 		 */
527 		ut_timecopy = _time32_to_time(usr.ut_time);
528 		/*
529 		 * With sparc64 using 64-bit time_t's, there is some system
530 		 * routine which sets ut_time==0 (the high-order word of a
531 		 * 64-bit time) instead of a 32-bit time value.  For those
532 		 * wtmp files, it is "more-accurate" to substitute the most-
533 		 * recent time found, instead of throwing away the entire
534 		 * record.  While it is still just a guess, it is a better
535 		 * guess than throwing away a log-off record and therefore
536 		 * counting a session as if it continued to the end of the
537 		 * month, or the next system-reboot.
538 		 */
539 		if (ut_timecopy == 0 && prev_secs > 1) {
540 #ifdef DEBUG
541 			if (Debug)
542 				printf("%s - date changed to: %s",
543 				    debug_pfx(&usr, &usr), ctime(&prev_secs));
544 #endif
545 			tchanged++;
546 			usr.ut_time = ut_timecopy = prev_secs;
547 		}
548 		/*
549 		 * Skip records where the time goes backwards.
550 		 */
551 		if (ut_timecopy < prev_secs) {
552 #ifdef DEBUG
553 			if (Debug)
554 				printf("%s - bad date, record skipped\n",
555 				    debug_pfx(&usr, &usr));
556 #endif
557 			tskipped++;
558 			continue;	/* Skip this invalid record. */
559 		}
560 		prev_secs = ut_timecopy;
561 
562 		if (!FirstTime)
563 			FirstTime = ut_timecopy;
564 		if (Flags & AC_D) {
565 			ltm = localtime(&ut_timecopy);
566 			if (day >= 0 && day != ltm->tm_yday) {
567 				day = ltm->tm_yday;
568 				/*
569 				 * print yesterday's total
570 				 */
571 				secs = ut_timecopy;
572 				secs -= ltm->tm_sec;
573 				secs -= 60 * ltm->tm_min;
574 				secs -= 3600 * ltm->tm_hour;
575 				show_today(Users, head, secs);
576 			} else
577 				day = ltm->tm_yday;
578 		}
579 		switch(*usr.ut_line) {
580 		case '|':
581 			secs = ut_timecopy;
582 			break;
583 		case '{':
584 			secs -= ut_timecopy;
585 			/*
586 			 * adjust time for those logged in
587 			 */
588 			for (lp = head; lp != NULL; lp = lp->next)
589 				lp->usr.ut_time -= secs;
590 			break;
591 		case '~':			/* reboot or shutdown */
592 			head = log_out(head, &usr);
593 			FirstTime = ut_timecopy; /* shouldn't be needed */
594 			break;
595 		default:
596 			/*
597 			 * if they came in on tty[p-sP-S]*, then it is only
598 			 * a login session if the ut_host field is non-empty
599 			 */
600 			if (*usr.ut_name) {
601 				if (strncmp(usr.ut_line, "tty", 3) == 0 ||
602 				    strchr("pqrsPQRS", usr.ut_line[3]) != 0 ||
603 				    *usr.ut_host != '\0')
604 					head = log_in(head, &usr);
605 #ifdef DEBUG
606 				else if (Debug > 1)
607 					/* Things such as 'screen' sessions. */
608 					printf("%s - record ignored\n",
609 					    debug_pfx(&usr, &usr));
610 #endif
611 			} else
612 				head = log_out(head, &usr);
613 			break;
614 		}
615 	}
616 	(void)fclose(fp);
617 	if (!(Flags & AC_W))
618 		usr.ut_time = time((time_t *)0);
619 	(void)strcpy(usr.ut_line, "~");
620 
621 	if (Flags & AC_D) {
622 		ut_timecopy = _time32_to_time(usr.ut_time);
623 		ltm = localtime(&ut_timecopy);
624 		if (day >= 0 && day != ltm->tm_yday) {
625 			/*
626 			 * print yesterday's total
627 			 */
628 			secs = ut_timecopy;
629 			secs -= ltm->tm_sec;
630 			secs -= 60 * ltm->tm_min;
631 			secs -= 3600 * ltm->tm_hour;
632 			show_today(Users, head, secs);
633 		}
634 	}
635 	/*
636 	 * anyone still logged in gets time up to now
637 	 */
638 	head = log_out(head, &usr);
639 
640 	if (Flags & AC_D)
641 		show_today(Users, head, time((time_t *)0));
642 	else {
643 		if (Flags & AC_P)
644 			show_users(Users);
645 		show("total", Total);
646 	}
647 
648 	if (tskipped > 0)
649 		printf("(Skipped %d of %d records due to invalid time values)\n",
650 		    tskipped, rfound);
651 	if (tchanged > 0)
652 		printf("(Changed %d of %d records to have a more likely time value)\n",
653 		    tchanged, rfound);
654 
655 	return 0;
656 }
657 
658 void
659 usage(void)
660 {
661 	(void)fprintf(stderr,
662 #ifdef CONSOLE_TTY
663 	    "ac [-dp] [-c console] [-t tty] [-w wtmp] [users ...]\n");
664 #else
665 	    "ac [-dp] [-t tty] [-w wtmp] [users ...]\n");
666 #endif
667 	exit(1);
668 }
669