2 * Copyright (c) 2009-2012 Todd C. Miller <Todd.Miller@courtesan.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/types.h>
20 #include <sys/param.h>
22 #ifdef HAVE_SYS_SYSMACROS_H
23 # include <sys/sysmacros.h>
28 #include <sys/ioctl.h>
29 #ifdef HAVE_SYS_SELECT_H
30 #include <sys/select.h>
31 #endif /* HAVE_SYS_SELECT_H */
40 #endif /* STDC_HEADERS */
42 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
46 #endif /* HAVE_STRING_H */
49 #endif /* HAVE_STRINGS_H */
52 #endif /* HAVE_UNISTD_H */
53 #if TIME_WITH_SYS_TIME
56 #ifndef HAVE_STRUCT_TIMESPEC
57 # include "compat/timespec.h"
65 # define NAMLEN(dirent) strlen((dirent)->d_name)
67 # define dirent direct
68 # define NAMLEN(dirent) (dirent)->d_namlen
69 # ifdef HAVE_SYS_NDIR_H
70 # include <sys/ndir.h>
72 # ifdef HAVE_SYS_DIR_H
92 # include "compat/stdbool.h"
93 #endif /* HAVE_STDBOOL_H */
95 #include <pathnames.h>
101 #include "sudo_plugin.h"
102 #include "sudo_conf.h"
103 #include "sudo_debug.h"
106 # define LINE_MAX 2048
109 /* Must match the defines in iolog.c */
111 #define IOFD_STDOUT 1
112 #define IOFD_STDERR 2
114 #define IOFD_TTYOUT 4
115 #define IOFD_TIMING 5
118 /* Bitmap of iofds to be replayed */
119 unsigned int replay_filter = (1 << IOFD_STDOUT) | (1 << IOFD_STDERR) |
135 * Info present in the I/O log file
150 * Handle expressions like:
151 * ( user millert or user root ) and tty console and command /bin/sh
154 struct search_node *next;
159 #define ST_RUNASUSER 5
160 #define ST_RUNASGROUP 6
161 #define ST_FROMDATE 7
179 struct search_node *expr;
184 sudo_conv_t sudo_conv; /* NULL in non-plugin */
186 #define STACK_NODE_SIZE 32
187 static struct search_node *node_stack[32];
188 static int stack_top;
190 static const char *session_dir = _PATH_SUDO_IO_LOGDIR;
192 static union io_fd io_fds[IOFD_MAX];
193 static const char *io_fnames[IOFD_MAX] = {
202 extern time_t get_date(char *);
203 extern char *get_timestr(time_t, int);
204 extern int term_raw(int, int);
205 extern int term_restore(int, int);
206 extern void get_ttysize(int *rowp, int *colp);
209 static int list_sessions(int, char **, const char *, const char *, const char *);
210 static int parse_expr(struct search_node **, char **);
211 static void check_input(int, double *);
212 static void delay(double);
213 static void help(void) __attribute__((__noreturn__));
214 static void usage(int);
215 static int open_io_fd(char *pathbuf, int len, const char *suffix, union io_fd *fdp);
216 static int parse_timing(const char *buf, const char *decimal, int *idx, double *seconds, size_t *nbytes);
217 static struct log_info *parse_logfile(char *logfile);
218 static void free_log_info(struct log_info *li);
219 static size_t atomic_writev(int fd, struct iovec *iov, int iovcnt);
222 # define REGEX_T regex_t
224 # define REGEX_T char
227 #define VALID_ID(s) (isalnum((unsigned char)(s)[0]) && \
228 isalnum((unsigned char)(s)[1]) && isalnum((unsigned char)(s)[2]) && \
229 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
230 isalnum((unsigned char)(s)[5]) && (s)[6] == '\0')
232 #define IS_IDLOG(s) ( \
233 isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
235 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
237 isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
238 (s)[8] == '/' && (s)[9] == 'l' && (s)[10] == 'o' && (s)[11] == 'g' && \
242 main(int argc, char *argv[])
244 int ch, idx, plen, exitcode = 0, rows = 0, cols = 0;
245 bool interactive = false, listonly = false, need_nlcr = false;
246 const char *id, *user = NULL, *pattern = NULL, *tty = NULL, *decimal = ".";
247 char path[PATH_MAX], buf[LINE_MAX], *cp, *ep;
248 double seconds, to_wait, speed = 1.0, max_wait = 0;
250 size_t len, nbytes, nread;
252 struct iovec *iov = NULL;
253 int iovcnt = 0, iovmax = 0;
254 debug_decl(main, SUDO_DEBUG_MAIN)
256 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
258 extern char *malloc_options;
259 malloc_options = "AFGJPR";
263 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
264 setprogname(argc > 0 ? argv[0] : "sudoreplay");
267 #ifdef HAVE_SETLOCALE
268 setlocale(LC_ALL, "");
269 decimal = localeconv()->decimal_point;
271 bindtextdomain("sudoers", LOCALEDIR); /* XXX - should have sudoreplay domain */
272 textdomain("sudoers");
274 /* Read sudo.conf. */
277 while ((ch = getopt(argc, argv, "d:f:hlm:s:V")) != -1) {
280 session_dir = optarg;
283 /* Set the replay filter. */
285 for (cp = strtok(optarg, ","); cp; cp = strtok(NULL, ",")) {
286 if (strcmp(cp, "stdout") == 0)
287 SET(replay_filter, 1 << IOFD_STDOUT);
288 else if (strcmp(cp, "stderr") == 0)
289 SET(replay_filter, 1 << IOFD_STDERR);
290 else if (strcmp(cp, "ttyout") == 0)
291 SET(replay_filter, 1 << IOFD_TTYOUT);
293 errorx(1, _("invalid filter option: %s"), optarg);
304 max_wait = strtod(optarg, &ep);
305 if (*ep != '\0' || errno != 0)
306 errorx(1, _("invalid max wait: %s"), optarg);
310 speed = strtod(optarg, &ep);
311 if (*ep != '\0' || errno != 0)
312 errorx(1, _("invalid speed factor: %s"), optarg);
315 (void) printf(_("%s version %s\n"), getprogname(), PACKAGE_VERSION);
327 exitcode = list_sessions(argc, argv, pattern, user, tty);
334 /* 6 digit ID in base 36, e.g. 01G712AB or free-form name */
337 plen = snprintf(path, sizeof(path), "%s/%.2s/%.2s/%.2s/timing",
338 session_dir, id, &id[2], &id[4]);
339 if (plen <= 0 || plen >= sizeof(path))
340 errorx(1, _("%s/%.2s/%.2s/%.2s/timing: %s"), session_dir,
341 id, &id[2], &id[4], strerror(ENAMETOOLONG));
343 plen = snprintf(path, sizeof(path), "%s/%s/timing",
345 if (plen <= 0 || plen >= sizeof(path))
346 errorx(1, _("%s/%s/timing: %s"), session_dir,
347 id, strerror(ENAMETOOLONG));
351 /* Open files for replay, applying replay filter for the -f flag. */
352 for (idx = 0; idx < IOFD_MAX; idx++) {
353 if (ISSET(replay_filter, 1 << idx) || idx == IOFD_TIMING) {
354 if (open_io_fd(path, plen, io_fnames[idx], &io_fds[idx]) == -1)
355 error(1, _("unable to open %s"), path);
359 /* Parse log file. */
361 strlcat(path, "/log", sizeof(path));
362 if ((li = parse_logfile(path)) == NULL)
364 printf(_("Replaying sudo session: %s\n"), li->cmd);
366 /* Make sure the terminal is large enough. */
367 get_ttysize(&rows, &cols);
368 if (li->rows != 0 && li->cols != 0) {
369 if (li->rows > rows) {
370 printf(_("Warning: your terminal is too small to properly replay the log.\n"));
371 printf(_("Log geometry is %d x %d, your terminal's geometry is %d x %d."), li->rows, li->cols, rows, cols);
375 /* Done with parsed log file. */
380 memset(&sa, 0, sizeof(sa));
381 sigemptyset(&sa.sa_mask);
382 sa.sa_flags = SA_RESETHAND;
383 sa.sa_handler = cleanup;
384 (void) sigaction(SIGINT, &sa, NULL);
385 (void) sigaction(SIGKILL, &sa, NULL);
386 (void) sigaction(SIGTERM, &sa, NULL);
387 (void) sigaction(SIGHUP, &sa, NULL);
388 sa.sa_flags = SA_RESTART;
389 sa.sa_handler = SIG_IGN;
390 (void) sigaction(SIGTSTP, &sa, NULL);
391 (void) sigaction(SIGQUIT, &sa, NULL);
393 /* XXX - read user input from /dev/tty and set STDOUT to raw if not a pipe */
394 /* Set stdin to raw mode if it is a tty */
395 interactive = isatty(STDIN_FILENO);
397 ch = fcntl(STDIN_FILENO, F_GETFL, 0);
399 (void) fcntl(STDIN_FILENO, F_SETFL, ch | O_NONBLOCK);
400 if (!term_raw(STDIN_FILENO, 1))
401 error(1, _("unable to set tty to raw mode"));
404 iov = ecalloc(iovmax, sizeof(*iov));
408 * Timing file consists of line of the format: "%f %d\n"
411 while (gzgets(io_fds[IOFD_TIMING].g, buf, sizeof(buf)) != NULL) {
413 while (fgets(buf, sizeof(buf), io_fds[IOFD_TIMING].f) != NULL) {
415 char last_char = '\0';
417 if (!parse_timing(buf, decimal, &idx, &seconds, &nbytes))
418 errorx(1, _("invalid timing file line: %s"), buf);
421 check_input(STDIN_FILENO, &speed);
423 /* Adjust delay using speed factor and clamp to max_wait */
424 to_wait = seconds / speed;
425 if (max_wait && to_wait > max_wait)
429 /* Even if we are not relaying, we still have to delay. */
430 if (io_fds[idx].v == NULL)
433 /* Check whether we need to convert newline to CR LF pairs. */
435 need_nlcr = (idx == IOFD_STDOUT || idx == IOFD_STDERR);
437 /* All output is sent to stdout. */
438 while (nbytes != 0) {
439 if (nbytes > sizeof(buf))
444 nread = gzread(io_fds[idx].g, buf, len);
446 nread = fread(buf, 1, len, io_fds[idx].f);
450 /* Convert newline to carriage return + linefeed if needed. */
452 size_t remainder = nread;
457 /* Handle a "\r\n" pair that spans a buffer. */
458 if (last_char == '\r' && buf[0] == '\n') {
462 while ((ep = memchr(ep + 1, '\n', remainder)) != NULL) {
463 /* Is there already a carriage return? */
464 if (cp != ep && ep[-1] == '\r') {
465 remainder = (size_t)(&buf[nread - 1] - ep);
469 /* Store the line in iov followed by \r\n pair. */
470 if (iovcnt + 3 > iovmax) {
472 iov = erealloc3(iov, iovmax, sizeof(*iov));
474 linelen = (size_t)(ep - cp) + 1;
475 iov[iovcnt].iov_base = cp;
476 iov[iovcnt].iov_len = linelen - 1; /* not including \n */
478 iov[iovcnt].iov_base = "\r\n";
479 iov[iovcnt].iov_len = 2;
482 remainder -= linelen;
484 if (cp - buf != nread) {
486 * Partial line without a linefeed or multiple lines
489 iov[iovcnt].iov_base = cp;
490 iov[iovcnt].iov_len = nread - (cp - buf);
493 last_char = buf[nread - 1]; /* stash last char of old buffer */
495 /* No conversion needed. */
496 iov[0].iov_base = buf;
497 iov[0].iov_len = nread;
500 if (atomic_writev(STDOUT_FILENO, iov, iovcnt) == -1)
501 error(1, _("writing to standard output"));
504 term_restore(STDIN_FILENO, 1);
506 sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, exitcode);
513 struct timespec ts, rts;
517 * Typical max resolution is 1/HZ but we can't portably check that.
518 * If the interval is small enough, just ignore it.
524 rts.tv_nsec = (secs - (double) rts.tv_sec) * 1000000000.0;
526 memcpy(&ts, &rts, sizeof(ts));
527 rval = nanosleep(&ts, &rts);
528 } while (rval == -1 && errno == EINTR);
530 error2(1, _("nanosleep: tv_sec %ld, tv_nsec %ld"),
531 (long)ts.tv_sec, (long)ts.tv_nsec);
536 open_io_fd(char *path, int len, const char *suffix, union io_fd *fdp)
538 debug_decl(open_io_fd, SUDO_DEBUG_UTIL)
541 strlcat(path, suffix, PATH_MAX);
544 fdp->g = gzopen(path, "r");
546 fdp->f = fopen(path, "r");
548 debug_return_int(fdp->v ? 0 : -1);
552 * Call writev(), restarting as needed and handling EAGAIN since
553 * fd may be in non-blocking mode.
556 atomic_writev(int fd, struct iovec *iov, int iovcnt)
558 ssize_t n, nwritten = 0;
559 size_t count, remainder, nbytes = 0;
561 debug_decl(atomic_writev, SUDO_DEBUG_UTIL)
563 for (i = 0; i < iovcnt; i++)
564 nbytes += iov[i].iov_len;
567 n = writev(STDOUT_FILENO, iov, iovcnt);
570 remainder = nbytes - nwritten;
573 /* short writev, adjust iov and do the rest. */
577 count += iov[i].iov_len;
578 if (count == remainder) {
583 if (count > remainder) {
584 size_t off = (count - remainder);
585 /* XXX - side effect prevents iov from being const */
586 iov[i].iov_base = (char *)iov[i].iov_base + off;
587 iov[i].iov_len -= off;
595 if (n == 0 || errno == EAGAIN) {
599 FD_SET(STDOUT_FILENO, &fdsw);
601 nready = select(STDOUT_FILENO + 1, NULL, &fdsw, NULL, NULL);
602 } while (nready == -1 && errno == EINTR);
611 debug_return_size_t(nwritten);
615 * Build expression list from search args
618 parse_expr(struct search_node **headp, char *argv[])
620 struct search_node *sn, *newsn;
621 char or = 0, not = 0, type, **av;
622 debug_decl(parse_expr, SUDO_DEBUG_UTIL)
625 for (av = argv; *av; av++) {
627 case 'a': /* and (ignore) */
628 if (strncmp(*av, "and", strlen(*av)) != 0)
632 if (strncmp(*av, "or", strlen(*av)) != 0)
636 case '!': /* negate */
637 if (av[0][1] != '\0')
641 case 'c': /* command */
642 if (av[0][1] == '\0')
643 errorx(1, _("ambiguous expression \"%s\""), *av);
644 if (strncmp(*av, "cwd", strlen(*av)) == 0)
646 else if (strncmp(*av, "command", strlen(*av)) == 0)
651 case 'f': /* from date */
652 if (strncmp(*av, "fromdate", strlen(*av)) != 0)
656 case 'g': /* runas group */
657 if (strncmp(*av, "group", strlen(*av)) != 0)
659 type = ST_RUNASGROUP;
661 case 'r': /* runas user */
662 if (strncmp(*av, "runas", strlen(*av)) != 0)
666 case 't': /* tty or to date */
667 if (av[0][1] == '\0')
668 errorx(1, _("ambiguous expression \"%s\""), *av);
669 if (strncmp(*av, "todate", strlen(*av)) == 0)
671 else if (strncmp(*av, "tty", strlen(*av)) == 0)
677 if (strncmp(*av, "user", strlen(*av)) != 0)
681 case '(': /* start sub-expression */
682 if (av[0][1] != '\0')
684 if (stack_top + 1 == STACK_NODE_SIZE) {
685 errorx(1, _("too many parenthesized expressions, max %d"),
688 node_stack[stack_top++] = sn;
691 case ')': /* end sub-expression */
692 if (av[0][1] != '\0')
696 errorx(1, _("unmatched ')' in expression"));
697 if (node_stack[stack_top])
698 sn->next = node_stack[stack_top]->next;
699 debug_return_int(av - argv + 1);
702 errorx(1, _("unknown search term \"%s\""), *av);
706 /* Allocate new search node */
707 newsn = ecalloc(1, sizeof(*newsn));
710 newsn->negated = not;
711 /* newsn->next = NULL; */
712 if (type == ST_EXPR) {
713 av += parse_expr(&newsn->u.expr, av + 1);
716 errorx(1, _("%s requires an argument"), av[-1]);
718 if (type == ST_PATTERN) {
719 if (regcomp(&newsn->u.cmdre, *av, REG_EXTENDED|REG_NOSUB) != 0)
720 errorx(1, _("invalid regular expression: %s"), *av);
723 if (type == ST_TODATE || type == ST_FROMDATE) {
724 newsn->u.tstamp = get_date(*av);
725 if (newsn->u.tstamp == -1)
726 errorx(1, _("could not parse date \"%s\""), *av);
731 not = or = 0; /* reset state */
739 errorx(1, _("unmatched '(' in expression"));
741 errorx(1, _("illegal trailing \"or\""));
743 errorx(1, _("illegal trailing \"!\""));
745 debug_return_int(av - argv);
749 match_expr(struct search_node *head, struct log_info *log)
751 struct search_node *sn;
754 debug_decl(match_expr, SUDO_DEBUG_UTIL)
756 for (sn = head; sn; sn = sn->next) {
757 /* If we have no match, skip ahead to the next OR entry. */
758 if (!matched && !sn->or)
763 matched = match_expr(sn->u.expr, log);
766 matched = strcmp(sn->u.cwd, log->cwd) == 0;
769 matched = strcmp(sn->u.tty, log->tty) == 0;
772 matched = strcmp(sn->u.runas_group, log->runas_group) == 0;
775 matched = strcmp(sn->u.runas_user, log->runas_user) == 0;
778 matched = strcmp(sn->u.user, log->user) == 0;
782 rc = regexec(&sn->u.cmdre, log->cmd, 0, NULL, 0);
783 if (rc && rc != REG_NOMATCH) {
785 regerror(rc, &sn->u.cmdre, buf, sizeof(buf));
786 errorx(1, "%s", buf);
788 matched = rc == REG_NOMATCH ? 0 : 1;
790 matched = strstr(log.cmd, sn->u.pattern) != NULL;
794 matched = log->tstamp >= sn->u.tstamp;
797 matched = log->tstamp <= sn->u.tstamp;
803 debug_return_bool(matched);
806 static struct log_info *
807 parse_logfile(char *logfile)
810 char *buf = NULL, *cp, *ep;
811 size_t bufsize = 0, cwdsize = 0, cmdsize = 0;
812 struct log_info *li = NULL;
813 debug_decl(list_session, SUDO_DEBUG_UTIL)
815 fp = fopen(logfile, "r");
817 warning(_("unable to open %s"), logfile);
822 * ID file has three lines:
825 * 3) command with args
827 li = ecalloc(1, sizeof(*li));
828 if (getline(&buf, &bufsize, fp) == -1 ||
829 getline(&li->cwd, &cwdsize, fp) == -1 ||
830 getline(&li->cmd, &cmdsize, fp) == -1) {
834 /* Strip the newline from the cwd and command. */
835 li->cwd[strcspn(li->cwd, "\n")] = '\0';
836 li->cmd[strcspn(li->cmd, "\n")] = '\0';
839 * Crack the log line (rows and cols not present in old versions).
840 * timestamp:user:runas_user:runas_group:tty:rows:cols
842 buf[strcspn(buf, "\n")] = '\0';
845 if ((ep = strchr(buf, ':')) == NULL)
847 if ((li->tstamp = atoi(buf)) == 0)
852 if ((ep = strchr(cp, ':')) == NULL)
854 li->user = estrndup(cp, (size_t)(ep - cp));
858 if ((ep = strchr(cp, ':')) == NULL)
860 li->runas_user = estrndup(cp, (size_t)(ep - cp));
864 if ((ep = strchr(cp, ':')) == NULL)
867 li->runas_group = estrndup(cp, (size_t)(ep - cp));
869 /* tty, followed by optional rows + columns */
871 if ((ep = strchr(cp, ':')) == NULL) {
872 li->tty = estrdup(cp);
874 li->tty = estrndup(cp, (size_t)(ep - cp));
877 if ((ep = strchr(cp, ':')) != NULL) {
884 debug_return_ptr(li);
891 debug_return_ptr(NULL);
895 free_log_info(struct log_info *li)
900 efree(li->runas_user);
901 efree(li->runas_group);
909 list_session(char *logfile, REGEX_T *re, const char *user, const char *tty)
911 char idbuf[7], *idstr, *cp;
914 debug_decl(list_session, SUDO_DEBUG_UTIL)
916 if ((li = parse_logfile(logfile)) == NULL)
919 /* Match on search expression if there is one. */
920 if (search_expr && !match_expr(search_expr, li))
923 /* Convert from /var/log/sudo-sessions/00/00/01/log to 000001 */
924 cp = logfile + strlen(session_dir) + 1;
935 /* Not an id, just use the iolog_file portion. */
936 cp[strlen(cp) - 4] = '\0';
939 /* XXX - print rows + cols? */
940 printf("%s : %s : TTY=%s ; CWD=%s ; USER=%s ; ",
941 get_timestr(li->tstamp, 1), li->user, li->tty, li->cwd, li->runas_user);
943 printf("GROUP=%s ; ", li->runas_group);
944 printf("TSID=%s ; COMMAND=%s\n", idstr, li->cmd);
950 debug_return_int(rval);
954 session_compare(const void *v1, const void *v2)
956 const char *s1 = *(const char **)v1;
957 const char *s2 = *(const char **)v2;
958 return strcmp(s1, s2);
961 /* XXX - always returns 0, calls error() on failure */
963 find_sessions(const char *dir, REGEX_T *re, const char *user, const char *tty)
968 size_t sdlen, sessions_len = 0, sessions_size = 36*36;
970 char pathbuf[PATH_MAX], **sessions = NULL;
971 #ifdef HAVE_STRUCT_DIRENT_D_TYPE
972 bool checked_type = true;
974 const bool checked_type = false;
976 debug_decl(find_sessions, SUDO_DEBUG_UTIL)
980 error(1, _("unable to open %s"), dir);
982 /* XXX - would be faster to chdir and use relative names */
983 sdlen = strlcpy(pathbuf, dir, sizeof(pathbuf));
984 if (sdlen + 1 >= sizeof(pathbuf)) {
985 errno = ENAMETOOLONG;
986 error(1, "%s/", dir);
988 pathbuf[sdlen++] = '/';
989 pathbuf[sdlen] = '\0';
991 /* Store potential session dirs for sorting. */
992 sessions = emalloc2(sessions_size, sizeof(char *));
993 while ((dp = readdir(d)) != NULL) {
994 /* Skip "." and ".." */
995 if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
996 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
998 #ifdef HAVE_STRUCT_DIRENT_D_TYPE
1000 if (dp->d_type != DT_DIR) {
1001 /* Not all file systems support d_type. */
1002 if (dp->d_type != DT_UNKNOWN)
1004 checked_type = false;
1009 /* Add name to session list. */
1010 if (sessions_len + 1 > sessions_size) {
1011 sessions_size <<= 1;
1012 sessions = erealloc3(sessions, sessions_size, sizeof(char *));
1014 sessions[sessions_len++] = estrdup(dp->d_name);
1018 /* Sort and list the sessions. */
1019 qsort(sessions, sessions_len, sizeof(char *), session_compare);
1020 for (i = 0; i < sessions_len; i++) {
1021 len = snprintf(&pathbuf[sdlen], sizeof(pathbuf) - sdlen,
1022 "%s/log", sessions[i]);
1023 if (len <= 0 || len >= sizeof(pathbuf) - sdlen) {
1024 errno = ENAMETOOLONG;
1025 error(1, "%s/%s/log", dir, sessions[i]);
1029 /* Check for dir with a log file. */
1030 if (lstat(pathbuf, &sb) == 0 && S_ISREG(sb.st_mode)) {
1031 list_session(pathbuf, re, user, tty);
1033 /* Strip off "/log" and recurse if a dir. */
1034 pathbuf[sdlen + len - 4] = '\0';
1035 if (checked_type || (lstat(pathbuf, &sb) == 0 && S_ISDIR(sb.st_mode)))
1036 find_sessions(pathbuf, re, user, tty);
1041 debug_return_int(0);
1044 /* XXX - always returns 0, calls error() on failure */
1046 list_sessions(int argc, char **argv, const char *pattern, const char *user,
1049 REGEX_T rebuf, *re = NULL;
1050 debug_decl(list_sessions, SUDO_DEBUG_UTIL)
1052 /* Parse search expression if present */
1053 parse_expr(&search_expr, argv);
1056 /* optional regex */
1059 if (regcomp(re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
1060 errorx(1, _("invalid regex: %s"), pattern);
1063 re = (char *) pattern;
1064 #endif /* HAVE_REGCOMP */
1066 debug_return_int(find_sessions(session_dir, re, user, tty));
1070 * Check input for ' ', '<', '>'
1074 check_input(int ttyfd, double *speed)
1077 int nready, paused = 0;
1081 debug_decl(check_input, SUDO_DEBUG_UTIL)
1083 fdsr = ecalloc(howmany(ttyfd + 1, NFDBITS), sizeof(fd_mask));
1085 FD_SET(ttyfd, fdsr);
1089 nready = select(ttyfd + 1, fdsr, NULL, NULL, paused ? NULL : &tv);
1092 n = read(ttyfd, &ch, 1);
1116 * Parse a timing line, which is formatted as:
1117 * index sleep_time num_bytes
1118 * Where index is IOFD_*, sleep_time is the number of seconds to sleep
1119 * before writing the data and num_bytes is the number of bytes to output.
1120 * Returns 1 on success and 0 on failure.
1123 parse_timing(buf, decimal, idx, seconds, nbytes)
1125 const char *decimal;
1132 double d, fract = 0;
1134 debug_decl(parse_timing, SUDO_DEBUG_UTIL)
1137 ul = strtoul(buf, &ep, 10);
1141 for (cp = ep + 1; isspace((unsigned char) *cp); cp++)
1145 * Parse number of seconds. Sudo logs timing data in the C locale
1146 * but this may not match the current locale so we cannot use strtod().
1147 * Furthermore, sudo < 1.7.4 logged with the user's locale so we need
1148 * to be able to parse those logs too.
1151 l = strtol(cp, &ep, 10);
1152 if ((errno == ERANGE && (l == LONG_MAX || l == LONG_MIN)) ||
1153 l < 0 || l > INT_MAX ||
1154 (*ep != '.' && strncmp(ep, decimal, strlen(decimal)) != 0)) {
1157 *seconds = (double)l;
1158 cp = ep + (*ep == '.' ? 1 : strlen(decimal));
1160 while (isdigit((unsigned char) *cp)) {
1161 fract += (*cp - '0') / d;
1166 while (isspace((unsigned char) *cp))
1170 ul = strtoul(cp, &ep, 10);
1171 if (errno == ERANGE && ul == ULONG_MAX)
1173 *nbytes = (size_t)ul;
1175 debug_return_int(1);
1177 debug_return_int(0);
1183 fprintf(fatal ? stderr : stdout,
1184 _("usage: %s [-h] [-d directory] [-m max_wait] [-s speed_factor] ID\n"),
1186 fprintf(fatal ? stderr : stdout,
1187 _("usage: %s [-h] [-d directory] -l [search expression]\n"),
1196 (void) printf(_("%s - replay sudo session logs\n\n"), getprogname());
1198 (void) puts(_("\nOptions:\n"
1199 " -d directory specify directory for session logs\n"
1200 " -f filter specify which I/O type to display\n"
1201 " -h display help message and exit\n"
1202 " -l [expression] list available session IDs that match expression\n"
1203 " -m max_wait max number of seconds to wait between events\n"
1204 " -s speed_factor speed up or slow down output\n"
1205 " -V display version information and exit"));
1210 * Cleanup hook for error()/errorx()
1215 term_restore(STDIN_FILENO, 0);
1217 kill(getpid(), signo);