Merge commit 'upstream/1.7.6p1'
[debian/sudo] / logging.c
index 80d0f5a37d12a728b3027debf9428b93ecf5f3c7..d0aeab9906f3836f972a55b23a1e2608171e0e06 100644 (file)
--- a/logging.c
+++ b/logging.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994-1996,1998-2007 Todd C. Miller <Todd.Miller@courtesan.com>
+ * Copyright (c) 1994-1996, 1998-2010 Todd C. Miller <Todd.Miller@courtesan.com>
  *
  * Permission to use, copy, modify, and distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
 #endif /* STDC_HEADERS */
 #ifdef HAVE_STRING_H
 # include <string.h>
-#else
-# ifdef HAVE_STRINGS_H
-#  include <strings.h>
-# endif
 #endif /* HAVE_STRING_H */
+#ifdef HAVE_STRINGS_H
+# include <strings.h>
+#endif /* HAVE_STRINGS_H */
 #ifdef HAVE_UNISTD_H
 # include <unistd.h>
 #endif /* HAVE_UNISTD_H */
-#ifdef HAVE_ERR_H
-# include <err.h>
-#else
-# include "emul/err.h"
-#endif /* HAVE_ERR_H */
+#ifdef HAVE_SETLOCALE
+# include <locale.h>
+#endif /* HAVE_SETLOCALE */
+#ifdef HAVE_NL_LANGINFO
+# include <langinfo.h>
+#endif /* HAVE_NL_LANGINFO */
 #include <pwd.h>
+#include <grp.h>
 #include <signal.h>
 #include <time.h>
 #include <errno.h>
 
 #include "sudo.h"
 
-#ifndef lint
-__unused static const char rcsid[] = "$Sudo: logging.c,v 1.168.2.16 2008/06/22 20:23:57 millert Exp $";
-#endif /* lint */
-
 static void do_syslog          __P((int, char *));
 static void do_logfile         __P((char *));
-static void send_mail          __P((char *));
-static void mail_auth          __P((int, char *));
-static char *get_timestr       __P((void));
+static void send_mail          __P((const char *fmt, ...));
+static int should_mail         __P((int));
 static void mysyslog           __P((int, const char *, ...));
+static char *new_logline       __P((const char *, int));
 
 #define MAXSYSLOGTRIES 16      /* num of retries for broken syslogs */
 
@@ -125,6 +122,9 @@ mysyslog(pri, fmt, va_alist)
     closelog();
 }
 
+#define FMT_FIRST "%8s : %s"
+#define FMT_CONTD "%8s : (command continued) %s"
+
 /*
  * Log a message to syslog, pre-pending the username and splitting the
  * message into parts if it is longer than MAXSYSLOGLEN.
@@ -137,14 +137,18 @@ do_syslog(pri, msg)
     size_t len, maxlen;
     char *p, *tmp, save;
     const char *fmt;
-    const char *fmt_first = "%8s : %s";
-    const char *fmt_contd = "%8s : (command continued) %s";
+
+#ifdef HAVE_SETLOCALE
+    const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
+    if (!setlocale(LC_ALL, def_sudoers_locale))
+       setlocale(LC_ALL, "C");
+#endif /* HAVE_SETLOCALE */
 
     /*
      * Log the full line, breaking into multiple syslog(3) calls if necessary
      */
-    fmt = fmt_first;
-    maxlen = MAXSYSLOGLEN - (sizeof(fmt_first) - 6 + strlen(user_name));
+    fmt = FMT_FIRST;
+    maxlen = MAXSYSLOGLEN - (sizeof(FMT_FIRST) - 6 + strlen(user_name));
     for (p = msg; *p != '\0'; ) {
        len = strlen(p);
        if (len > maxlen) {
@@ -171,9 +175,14 @@ do_syslog(pri, msg)
            mysyslog(pri, fmt, user_name, p);
            p += len;
        }
-       fmt = fmt_contd;
-       maxlen = MAXSYSLOGLEN - (sizeof(fmt_contd) - 6 + strlen(user_name));
+       fmt = FMT_CONTD;
+       maxlen = MAXSYSLOGLEN - (sizeof(FMT_CONTD) - 6 + strlen(user_name));
     }
+
+#ifdef HAVE_SETLOCALE
+    setlocale(LC_ALL, old_locale);
+    efree((void *)old_locale);
+#endif /* HAVE_SETLOCALE */
 }
 
 static void
@@ -191,31 +200,34 @@ do_logfile(msg)
     fp = fopen(def_logfile, "a");
     (void) umask(oldmask);
     if (fp == NULL) {
-       easprintf(&full_line, "Can't open log file: %s: %s",
-           def_logfile, strerror(errno));
-       send_mail(full_line);
-       efree(full_line);
+       send_mail("Can't open log file: %s: %s", def_logfile, strerror(errno));
     } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
-       easprintf(&full_line, "Can't lock log file: %s: %s",
-           def_logfile, strerror(errno));
-       send_mail(full_line);
-       efree(full_line);
+       send_mail("Can't lock log file: %s: %s", def_logfile, strerror(errno));
     } else {
+       time_t now;
+
+#ifdef HAVE_SETLOCALE
+       const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
+       if (!setlocale(LC_ALL, def_sudoers_locale))
+           setlocale(LC_ALL, "C");
+#endif /* HAVE_SETLOCALE */
+
+       now = time(NULL);
        if (def_loglinelen == 0) {
            /* Don't pretty-print long log file lines (hard to grep) */
            if (def_log_host)
-               (void) fprintf(fp, "%s : %s : HOST=%s : %s\n", get_timestr(),
-                   user_name, user_shost, msg);
+               (void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
+                   get_timestr(now, def_log_year), user_name, user_shost, msg);
            else
-               (void) fprintf(fp, "%s : %s : %s\n", get_timestr(),
-                   user_name, msg);
+               (void) fprintf(fp, "%s : %s : %s\n",
+                   get_timestr(now, def_log_year), user_name, msg);
        } else {
            if (def_log_host)
-               easprintf(&full_line, "%s : %s : HOST=%s : %s", get_timestr(),
-                   user_name, user_shost, msg);
+               easprintf(&full_line, "%s : %s : HOST=%s : %s",
+                   get_timestr(now, def_log_year), user_name, user_shost, msg);
            else
-               easprintf(&full_line, "%s : %s : %s", get_timestr(),
-                   user_name, msg);
+               easprintf(&full_line, "%s : %s : %s",
+                   get_timestr(now, def_log_year), user_name, msg);
 
            /*
             * Print out full_line with word wrap
@@ -269,60 +281,40 @@ do_logfile(msg)
        (void) fflush(fp);
        (void) lock_file(fileno(fp), SUDO_UNLOCK);
        (void) fclose(fp);
+
+#ifdef HAVE_SETLOCALE
+       setlocale(LC_ALL, old_locale);
+       efree((void *)old_locale);
+#endif /* HAVE_SETLOCALE */
     }
 }
 
 /*
- * Two main functions, log_error() to log errors and log_auth() to
- * log allow/deny messages.
+ * Log and mail the denial message, optionally informing the user.
  */
 void
-log_auth(status, inform_user)
+log_denial(status, inform_user)
     int status;
     int inform_user;
 {
-    char *evstr = NULL;
     char *message;
     char *logline;
-    int pri;
 
-    if (ISSET(status, VALIDATE_OK))
-       pri = def_syslog_goodpri;
-    else
-       pri = def_syslog_badpri;
-
-    /* Set error message, if any. */
-    if (ISSET(status, VALIDATE_OK))
-       message = "";
-    else if (ISSET(status, FLAG_NO_USER))
-       message = "user NOT in sudoers ; ";
+    /* Set error message. */
+    if (ISSET(status, FLAG_NO_USER))
+       message = "user NOT in sudoers";
     else if (ISSET(status, FLAG_NO_HOST))
-       message = "user NOT authorized on host ; ";
-    else if (ISSET(status, VALIDATE_NOT_OK))
-       message = "command not allowed ; ";
+       message = "user NOT authorized on host";
     else
-       message = "unknown error ; ";
+       message = "command not allowed";
 
-    if (sudo_user.env_vars != NULL) {
-       size_t len = 7; /* " ; ENV=" */
-       struct list_member *cur;
-       for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
-           len += strlen(cur->value) + 1;
-       evstr = emalloc(len);
-       strlcpy(evstr, " ; ENV=", len);
-       for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
-           strlcat(evstr, cur->value, len);
-           strlcat(evstr, " ", len);           /* NOTE: last one will fail */
-       }
-    }
-    easprintf(&logline, "%sTTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s%s%s",
-       message, user_tty, user_cwd, *user_runas, evstr ? evstr : "",
-       user_cmnd, user_args ? " " : "", user_args ? user_args : "");
+    logline = new_logline(message, 0);
 
-    mail_auth(status, logline);                /* send mail based on status */
+    if (should_mail(status))
+       send_mail("%s", logline);       /* send mail based on status */
 
     /* Inform the user if they failed to authenticate.  */
-    if (inform_user && ISSET(status, VALIDATE_NOT_OK)) {
+    if (inform_user) {
        if (ISSET(status, FLAG_NO_USER))
            (void) fprintf(stderr, "%s is not in the sudoers file.  %s",
                user_name, "This incident will be reported.\n");
@@ -334,20 +326,47 @@ log_auth(status, inform_user)
                user_name, user_shost);
        else
            (void) fprintf(stderr,
-               "Sorry, user %s is not allowed to execute '%s%s%s' as %s on %s.\n",
+               "Sorry, user %s is not allowed to execute '%s%s%s' as %s%s%s on %s.\n",
                user_name, user_cmnd, user_args ? " " : "",
-               user_args ? user_args : "", *user_runas, user_host);
+               user_args ? user_args : "",
+               list_pw ? list_pw->pw_name : runas_pw ?
+               runas_pw->pw_name : user_name, runas_gr ? ":" : "",
+               runas_gr ? runas_gr->gr_name : "", user_host);
     }
 
     /*
      * Log via syslog and/or a file.
      */
     if (def_syslog)
-       do_syslog(pri, logline);
+       do_syslog(def_syslog_badpri, logline);
+    if (def_logfile)
+       do_logfile(logline);
+
+    efree(logline);
+}
+
+/*
+ * Log and potentially mail the allowed command.
+ */
+void
+log_allowed(status)
+    int status;
+{
+    char *logline;
+
+    logline = new_logline(NULL, 0);
+
+    if (should_mail(status))
+       send_mail("%s", logline);       /* send mail based on status */
+
+    /*
+     * Log via syslog and/or a file.
+     */
+    if (def_syslog)
+       do_syslog(def_syslog_goodpri, logline);
     if (def_logfile)
        do_logfile(logline);
 
-    efree(evstr);
     efree(logline);
 }
 
@@ -364,7 +383,6 @@ log_error(flags, fmt, va_alist)
     int serrno = errno;
     char *message;
     char *logline;
-    char *evstr = NULL;
     va_list ap;
 #ifdef __STDC__
     va_start(ap, fmt);
@@ -373,65 +391,34 @@ log_error(flags, fmt, va_alist)
 #endif
 
     /* Become root if we are not already to avoid user interference */
-    set_perms(PERM_ROOT);
+    set_perms(PERM_ROOT|PERM_NOEXIT);
 
     /* Expand printf-style format + args. */
     evasprintf(&message, fmt, ap);
     va_end(ap);
 
-    if (sudo_user.env_vars != NULL) {
-       size_t len = 7; /* " ; ENV=" */
-       struct list_member *cur;
-       for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
-           len += strlen(cur->value) + 1;
-       evstr = emalloc(len);
-       strlcpy(evstr, " ; ENV=", len);
-       for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
-           strlcat(evstr, cur->value, len);
-           strlcat(evstr, " ", len);           /* NOTE: last one will fail */
-       }
-    }
-
     if (ISSET(flags, MSG_ONLY))
        logline = message;
-    else if (ISSET(flags, USE_ERRNO)) {
-       if (user_args) {
-           easprintf(&logline,
-               "%s: %s ; TTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s %s",
-               message, strerror(serrno), user_tty, user_cwd, *user_runas,
-               evstr ? evstr : "", user_cmnd, user_args);
-       } else {
-           easprintf(&logline,
-               "%s: %s ; TTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s", message,
-               strerror(serrno), user_tty, user_cwd, *user_runas,
-               evstr ? evstr : "", user_cmnd);
-       }
-    } else {
-       if (user_args) {
-           easprintf(&logline,
-               "%s ; TTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s %s", message,
-               user_tty, user_cwd, *user_runas, evstr ? evstr : "",
-               user_cmnd, user_args);
-       } else {
-           easprintf(&logline,
-               "%s ; TTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s", message,
-               user_tty, user_cwd, *user_runas, evstr ? evstr : "", user_cmnd);
-       }
-    }
+    else
+       logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
 
     /*
      * Tell the user.
      */
-    if (ISSET(flags, USE_ERRNO))
-       warn("%s", message);
-    else
-       warnx("%s", message);
+    if (!ISSET(flags, NO_STDERR)) {
+       if (ISSET(flags, USE_ERRNO))
+           warning("%s", message);
+       else
+           warningx("%s", message);
+    }
+    if (logline != message)
+        efree(message);
 
     /*
      * Send a copy of the error via mail.
      */
     if (!ISSET(flags, NO_MAIL))
-       send_mail(logline);
+       send_mail("%s", logline);
 
     /*
      * Log to syslog and/or a file.
@@ -441,12 +428,12 @@ log_error(flags, fmt, va_alist)
     if (def_logfile)
        do_logfile(logline);
 
-    efree(message);
-    if (logline != message)
-       efree(logline);
+    efree(logline);
 
-    if (!ISSET(flags, NO_EXIT))
+    if (!ISSET(flags, NO_EXIT)) {
+       cleanup(0);
        exit(1);
+    }
 }
 
 #define MAX_MAILFLAGS  63
@@ -455,24 +442,30 @@ log_error(flags, fmt, va_alist)
  * Send a message to MAILTO user
  */
 static void
-send_mail(line)
-    char *line;
+#ifdef __STDC__
+send_mail(const char *fmt, ...)
+#else
+send_mail(fmt, va_alist)
+    const char *fmt;
+    va_dcl
+#endif
 {
     FILE *mail;
     char *p;
     int fd, pfd[2], status;
     pid_t pid, rv;
     sigaction_t sa;
+    va_list ap;
 #ifndef NO_ROOT_MAILER
     static char *root_envp[] = {
        "HOME=/",
-       "PATH=/usr/bin:/bin",
+       "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
        "LOGNAME=root",
        "USERNAME=root",
        "USER=root",
        NULL
     };
-#endif
+#endif /* NO_ROOT_MAILER */
 
     /* Just return if mailer is disabled. */
     if (!def_mailerpath || !def_mailto)
@@ -481,11 +474,11 @@ send_mail(line)
     /* Fork and return, child will daemonize. */
     switch (pid = fork()) {
        case -1:
-           /* Error */
-           err(1, "cannot fork");
+           /* Error. */
+           error(1, "cannot fork");
            break;
        case 0:
-           /* Child */
+           /* Child. */
            switch (pid = fork()) {
                case -1:
                    /* Error. */
@@ -500,7 +493,7 @@ send_mail(line)
            }
            break;
        default:
-           /* Parent */
+           /* Parent. */
            do {
 #ifdef HAVE_WAITPID
                rv = waitpid(pid, &status, 0);
@@ -512,32 +505,33 @@ send_mail(line)
     }
 
     /* Daemonize - disassociate from session/tty. */
-#ifdef HAVE_SETSID
     if (setsid() == -1)
-      warn("setsid");
-#else
-    setpgrp(0, 0);
-# ifdef TIOCNOTTY
-    if ((fd = open(_PATH_TTY, O_RDWR, 0644)) != -1) {
-       ioctl(fd, TIOCNOTTY, NULL);
-       close(fd);
-    }
-# endif
-#endif
-    chdir("/");
+      warning("setsid");
+    if (chdir("/") == -1)
+      warning("chdir(/)");
     if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
        (void) dup2(fd, STDIN_FILENO);
        (void) dup2(fd, STDOUT_FILENO);
        (void) dup2(fd, STDERR_FILENO);
     }
 
-    /* Close password and other fds so we don't leak. */
-    endpwent();
+#ifdef HAVE_SETLOCALE
+    if (!setlocale(LC_ALL, def_sudoers_locale)) {
+       setlocale(LC_ALL, "C");
+       efree(def_sudoers_locale);
+       def_sudoers_locale = estrdup("C");
+    }
+#endif /* HAVE_SETLOCALE */
+
+    /* Close password, group and other fds so we don't leak. */
+    sudo_endpwent();
+    sudo_endgrent();
     closefrom(STDERR_FILENO + 1);
 
     /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
+    zero_bytes(&sa, sizeof(sa));
     sigemptyset(&sa.sa_mask);
-    sa.sa_flags = 0;
+    sa.sa_flags = SA_INTERRUPT;
     sa.sa_handler = SIG_IGN;
     (void) sigaction(SIGPIPE, &sa, NULL);
 
@@ -560,12 +554,15 @@ send_mail(line)
 
                /* Child, set stdin to output side of the pipe */
                if (pfd[0] != STDIN_FILENO) {
-                   (void) dup2(pfd[0], STDIN_FILENO);
+                   if (dup2(pfd[0], STDIN_FILENO) == -1) {
+                       mysyslog(LOG_ERR, "cannot dup stdin: %m");
+                       _exit(127);
+                   }
                    (void) close(pfd[0]);
                }
                (void) close(pfd[1]);
 
-               /* Build up an argv based the mailer path and flags */
+               /* Build up an argv based on the mailer path and flags */
                mflags = estrdup(def_mailerflags);
                mpath = estrdup(def_mailerpath);
                if ((argv[0] = strrchr(mpath, ' ')))
@@ -586,10 +583,10 @@ send_mail(line)
                 * (so user cannot kill it) or as the user (for the paranoid).
                 */
 #ifndef NO_ROOT_MAILER
-               set_perms(PERM_ROOT);
+               set_perms(PERM_ROOT|PERM_NOEXIT);
                execve(mpath, argv, root_envp);
 #else
-               set_perms(PERM_FULL_USER);
+               set_perms(PERM_FULL_USER|PERM_NOEXIT);
                execv(mpath, argv);
 #endif /* NO_ROOT_MAILER */
                mysyslog(LOG_ERR, "cannot execute %s: %m", mpath);
@@ -601,9 +598,9 @@ send_mail(line)
     (void) close(pfd[0]);
     mail = fdopen(pfd[1], "w");
 
-    /* Pipes are all setup, send message via sendmail. */
+    /* Pipes are all setup, send message. */
     (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
-       def_mailto, user_name, "auto-generated");
+       def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
     for (p = def_mailsub; *p; p++) {
        /* Expand escapes in the subject */
        if (*p == '%' && *(p+1) != '%') {
@@ -621,78 +618,168 @@ send_mail(line)
        } else
            (void) fputc(*p, mail);
     }
-    (void) fprintf(mail, "\n\n%s : %s : %s : %s\n\n", user_host,
-       get_timestr(), user_name, line);
+
+#ifdef HAVE_NL_LANGINFO
+    if (strcmp(def_sudoers_locale, "C") != 0)
+       (void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET));
+#endif /* HAVE_NL_LANGINFO */
+
+    (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
+       get_timestr(time(NULL), def_log_year), user_name);
+#ifdef __STDC__
+    va_start(ap, fmt);
+#else
+    va_start(ap);
+#endif
+    (void) vfprintf(mail, fmt, ap);
+    va_end(ap);
+    fputs("\n\n", mail);
+
     fclose(mail);
     do {
 #ifdef HAVE_WAITPID
-       rv = waitpid(pid, &status, 0);
+        rv = waitpid(pid, &status, 0);
 #else
-       rv = wait(&status);
+        rv = wait(&status);
 #endif
     } while (rv == -1 && errno == EINTR);
     _exit(0);
 }
 
 /*
- * Send mail based on the value of "status" and compile-time options.
+ * Determine whether we should send mail based on "status" and defaults options.
  */
-static void
-mail_auth(status, line)
+static int
+should_mail(status)
     int status;
-    char *line;
 {
-    int mail_mask;
-
-    /* If any of these bits are set in status, we send mail. */
-    if (def_mail_always)
-       mail_mask =
-           VALIDATE_ERROR|VALIDATE_OK|FLAG_NO_USER|FLAG_NO_HOST|VALIDATE_NOT_OK;
-    else {
-       mail_mask = VALIDATE_ERROR;
-       if (def_mail_no_user)
-           SET(mail_mask, FLAG_NO_USER);
-       if (def_mail_no_host)
-           SET(mail_mask, FLAG_NO_HOST);
-       if (def_mail_no_perms)
-           SET(mail_mask, VALIDATE_NOT_OK);
-    }
 
-    if ((status & mail_mask) != 0)
-       send_mail(line);
+    return def_mail_always || ISSET(status, VALIDATE_ERROR) ||
+       (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
+       (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
+       (def_mail_no_perms && !ISSET(status, VALIDATE_OK));
 }
 
+#define        LL_TTY_STR      "TTY="
+#define        LL_CWD_STR      "PWD="          /* XXX - should be CWD= */
+#define        LL_USER_STR     "USER="
+#define        LL_GROUP_STR    "GROUP="
+#define        LL_ENV_STR      "ENV="
+#define        LL_CMND_STR     "COMMAND="
+#define        LL_TSID_STR     "TSID="
+
 /*
- * Return an ascii string with the current date + time
- * Uses strftime() if available, else falls back to ctime().
+ * Allocate and fill in a new logline.
  */
 static char *
-get_timestr()
+new_logline(message, serrno)
+    const char *message;
+    int serrno;
 {
-    char *s;
-    time_t now = time((time_t) 0);
-#ifdef HAVE_STRFTIME
-    static char buf[128];
-    struct tm *timeptr;
-
-    timeptr = localtime(&now);
-    if (def_log_year)
-       s = "%h %e %T %Y";
-    else
-       s = "%h %e %T";
+    size_t len = 0;
+    char *evstr = NULL;
+    char *errstr = NULL;
+    char *line;
 
-    /* strftime() does not guarantee to NUL-terminate so we must check. */
-    buf[sizeof(buf) - 1] = '\0';
-    if (strftime(buf, sizeof(buf), s, timeptr) && buf[sizeof(buf) - 1] == '\0')
-       return(buf);
+    /*
+     * Compute line length
+     */
+    if (message != NULL)
+       len += strlen(message) + 3;
+    if (serrno) {
+       errstr = strerror(serrno);
+       len += strlen(errstr) + 3;
+    }
+    len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
+    len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
+    if (runas_pw != NULL)
+       len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
+    if (runas_gr != NULL)
+       len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
+    if (sudo_user.sessid[0] != '\0')
+       len += sizeof(LL_TSID_STR) + 2 + strlen(sudo_user.sessid);
+    if (sudo_user.env_vars != NULL) {
+       size_t evlen = 0;
+       struct list_member *cur;
+       for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
+           evlen += strlen(cur->value) + 1;
+       evstr = emalloc(evlen);
+       evstr[0] = '\0';
+       for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
+           strlcat(evstr, cur->value, evlen);
+           strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
+       }
+       len += sizeof(LL_ENV_STR) + 2 + evlen;
+    }
+    /* Note: we log "sudo -l command arg ..." as "list command arg ..." */
+    len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
+    if (ISSET(sudo_mode, MODE_CHECK))
+       len += sizeof("list ") - 1;
+    if (user_args != NULL)
+       len += strlen(user_args) + 1;
 
-#endif /* HAVE_STRFTIME */
+    /*
+     * Allocate and build up the line.
+     */
+    line = emalloc(++len);
+    line[0] = '\0';
 
-    s = ctime(&now) + 4;               /* skip day of the week */
-    if (def_log_year)
-       s[20] = '\0';                   /* avoid the newline */
-    else
-       s[15] = '\0';                   /* don't care about year */
+    if (message != NULL) {
+       if (strlcat(line, message, len) >= len ||
+           strlcat(line, errstr ? " : " : " ; ", len) >= len)
+           goto toobig;
+    }
+    if (serrno) {
+       if (strlcat(line, errstr, len) >= len ||
+           strlcat(line, " ; ", len) >= len)
+           goto toobig;
+    }
+    if (strlcat(line, LL_TTY_STR, len) >= len ||
+       strlcat(line, user_tty, len) >= len ||
+       strlcat(line, " ; ", len) >= len)
+       goto toobig;
+    if (strlcat(line, LL_CWD_STR, len) >= len ||
+       strlcat(line, user_cwd, len) >= len ||
+       strlcat(line, " ; ", len) >= len)
+       goto toobig;
+    if (runas_pw != NULL) {
+       if (strlcat(line, LL_USER_STR, len) >= len ||
+           strlcat(line, runas_pw->pw_name, len) >= len ||
+           strlcat(line, " ; ", len) >= len)
+           goto toobig;
+    }
+    if (runas_gr != NULL) {
+       if (strlcat(line, LL_GROUP_STR, len) >= len ||
+           strlcat(line, runas_gr->gr_name, len) >= len ||
+           strlcat(line, " ; ", len) >= len)
+           goto toobig;
+    }
+    if (sudo_user.sessid[0] != '\0') {
+       if (strlcat(line, LL_TSID_STR, len) >= len ||
+           strlcat(line, sudo_user.sessid, len) >= len ||
+           strlcat(line, " ; ", len) >= len)
+           goto toobig;
+    }
+    if (evstr != NULL) {
+       if (strlcat(line, LL_ENV_STR, len) >= len ||
+           strlcat(line, evstr, len) >= len ||
+           strlcat(line, " ; ", len) >= len)
+           goto toobig;
+       efree(evstr);
+    }
+    if (strlcat(line, LL_CMND_STR, len) >= len)
+       goto toobig;
+    if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
+       goto toobig;
+    if (strlcat(line, user_cmnd, len) >= len)
+       goto toobig;
+    if (user_args != NULL) {
+       if (strlcat(line, " ", len) >= len ||
+           strlcat(line, user_args, len) >= len)
+           goto toobig;
+    }
 
-    return(s);
+    return line;
+toobig:
+    errorx(1, "internal error: insufficient space for log line");
 }