the WHATSNEW file is gone
[debian/sudo] / visudo.c
index c3a1c59584d2695d5874adfc12d5226d10e27186..ab8d58744e258899cf59ee97631d6f2ada935e6d 100644 (file)
--- a/visudo.c
+++ b/visudo.c
@@ -1,47 +1,44 @@
 /*
- * Copyright (c) 1996, 1998-2001 Todd C. Miller <Todd.Miller@courtesan.com>
- * All rights reserved.
+ * Copyright (c) 1996, 1998-2005, 2007-2010
+ *     Todd C. Miller <Todd.Miller@courtesan.com>
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
  *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * 4. Products derived from this software may not be called "Sudo" nor
- *    may "Sudo" appear in their names without specific prior written
- *    permission from the author.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
- * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Sponsored in part by the Defense Advanced Research Projects
+ * Agency (DARPA) and Air Force Research Laboratory, Air Force
+ * Materiel Command, USAF, under agreement number F39502-99-1-0512.
  */
 
 /*
  * Lock the sudoers file for safe editing (ala vipw) and check for parse errors.
  */
 
-#include "config.h"
+#define _SUDO_MAIN
+
+#ifdef __TANDEM
+# include <floss.h>
+#endif
+
+#include <config.h>
 
 #include <sys/types.h>
 #include <sys/param.h>
 #include <sys/stat.h>
-#include <sys/file.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#ifndef __TANDEM
+# include <sys/file.h>
+#endif
 #include <sys/wait.h>
 #include <stdio.h>
 #ifdef STDC_HEADERS
 #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 */
 #include <ctype.h>
 #include <pwd.h>
-#include <time.h>
+#include <grp.h>
 #include <signal.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#if TIME_WITH_SYS_TIME
+# include <time.h>
+#endif
+#ifdef __STDC__
+# include <stdarg.h>
+#else
+# include <varargs.h>
+#endif
 
 #include "sudo.h"
-#include "version.h"
+#include "interfaces.h"
+#include "parse.h"
+#include "redblack.h"
+#include <gram.h>
 
-#ifndef lint
-static const char rcsid[] = "$Sudo: visudo.c,v 1.146 2002/01/17 15:35:54 millert Exp $";
-#endif /* lint */
+struct sudoersfile {
+    struct sudoersfile *prev, *next;
+    char *path;
+    char *tpath;
+    int fd;
+    int modified;
+    int doedit;
+};
+TQ_DECLARE(sudoersfile);
 
 /*
  * Function prototypes
  */
-static void usage              __P((void));
+static RETSIGTYPE quit         __P((int));
+static char *get_args          __P((char *));
+static char *get_editor                __P((char **));
+static void get_hostname       __P((void));
 static char whatnow            __P((void));
-static RETSIGTYPE Exit         __P((int));
-static void setup_signals      __P((void));
+static int check_aliases       __P((int, int));
+static int check_syntax                __P((char *, int, int));
+static int edit_sudoers                __P((struct sudoersfile *, char *, char *, int));
+static int install_sudoers     __P((struct sudoersfile *, int));
+static int print_unused                __P((void *, void *));
+static int reparse_sudoers     __P((char *, char *, int, int));
 static int run_command         __P((char *, char **));
-static int check_syntax                __P((int));
-int command_matches            __P((char *, char *, char *, char *));
-int addr_matches               __P((char *));
-int hostname_matches           __P((char *, char *, char *));
-int netgr_matches              __P((char *, char *, char *, char *));
-int usergr_matches             __P((char *, char *));
-void init_parser               __P((void));
-void yyrestart                 __P((FILE *));
+static void print_selfref      __P((char *, int, int, int));
+static void print_undefined    __P((char *, int, int, int));
+static void setup_signals      __P((void));
+static void usage              __P((void)) __attribute__((__noreturn__));
+
+extern void yyerror            __P((const char *));
+extern void yyrestart          __P((FILE *));
 
 /*
  * External globals exported by the parser
  */
-extern FILE *yyin, *yyout;
-extern int errorlineno;
-extern int pedantic;
-extern int quiet;
-
+extern struct rbtree *aliases;
+extern FILE *yyin;
+extern char *sudoers, *errorfile;
+extern int errorlineno, parse_error;
 /* For getopt(3) */
 extern char *optarg;
 extern int optind;
@@ -108,56 +129,51 @@ extern int optind;
 /*
  * Globals
  */
+int Argc;
 char **Argv;
-char *sudoers = _PATH_SUDOERS;
-char *stmp = _PATH_SUDOERS_TMP;
+int num_interfaces;
+struct interface *interfaces;
 struct sudo_user sudo_user;
-int parse_error = FALSE;
+struct passwd *list_pw;
+static struct sudoersfile_list sudoerslist;
+static struct rbtree *alias_freelist;
 
 int
 main(argc, argv)
     int argc;
     char **argv;
 {
-    char buf[MAXPATHLEN*2];            /* buffer used for copying files */
-    char *Editor;                      /* editor to use */
-    char *UserEditor;                  /* editor user wants to use */
-    char *EditorPath;                  /* colon-separated list of editors */
-    char *av[4];                       /* argument vector for run_command */
-    int checkonly;                     /* only check existing file? */
-    int sudoers_fd;                    /* sudoers file descriptor */
-    int stmp_fd;                       /* stmp file descriptor */
-    int n;                             /* length parameter */
-    int ch;                            /* getopt char */
-    time_t now;                                /* time now */
-    struct stat stmp_sb, sudoers_sb;   /* to check for changes */
-
-    /* Warn about aliases that are used before being defined. */
-    pedantic = 1;
+    struct sudoersfile *sp;
+    char *args, *editor, *sudoers_path;
+    int ch, checkonly, quiet, strict, oldperms;
+#if defined(SUDO_DEVEL) && defined(__OpenBSD__)
+    extern char *malloc_options;
+    malloc_options = "AFGJPR";
+#endif
 
-    /*
-     * Parse command line options
-     */
     Argv = argv;
+    if ((Argc = argc) < 1)
+       usage();
 
     /*
      * Arg handling.
      */
-    checkonly = 0;
+    checkonly = oldperms = quiet = strict = FALSE;
+    sudoers_path = _PATH_SUDOERS;
     while ((ch = getopt(argc, argv, "Vcf:sq")) != -1) {
        switch (ch) {
            case 'V':
-               (void) printf("visudo version %s\n", version);
+               (void) printf("%s version %s\n", getprogname(), PACKAGE_VERSION);
                exit(0);
            case 'c':
                checkonly++;            /* check mode */
                break;
            case 'f':
-               sudoers = optarg;       /* sudoers file path */
-               easprintf(&stmp, "%s.tmp", optarg);
+               sudoers_path = optarg;  /* sudoers file path */
+               oldperms = TRUE;
                break;
            case 's':
-               pedantic++;             /* strict mode */
+               strict++;               /* strict mode */
                break;
            case 'q':
                quiet++;                /* quiet mode */
@@ -171,392 +187,407 @@ main(argc, argv)
     if (argc)
        usage();
 
+    sudo_setpwent();
+    sudo_setgrent();
+
     /* Mock up a fake sudo_user struct. */
-    user_host = user_shost = user_cmnd = "";
-    if ((sudo_user.pw = getpwuid(getuid())) == NULL) {
-       (void) fprintf(stderr, "%s: Can't find you in the passwd database.\n",
-           Argv[0]);
-       exit(1);
-    }
+    user_cmnd = "";
+    if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
+       errorx(1, "you don't exist in the passwd database");
+    get_hostname();
 
     /* Setup defaults data structures. */
     init_defaults();
 
     if (checkonly)
-       exit(check_syntax(quiet));
+       exit(check_syntax(sudoers_path, quiet, strict));
 
     /*
-     * Open sudoers, lock it and stat it.  
-     * sudoers_fd must remain open throughout in order to hold the lock.
+     * Parse the existing sudoers file(s) in quiet mode to highlight any
+     * existing errors and to pull in editor and env_editor conf values.
      */
-    sudoers_fd = open(sudoers, O_RDWR | O_CREAT, SUDOERS_MODE);
-    if (sudoers_fd == -1) {
-       (void) fprintf(stderr, "%s: %s: %s\n", Argv[0], sudoers,
-           strerror(errno));
-       exit(1);
-    }
-    if (!lock_file(sudoers_fd, SUDO_TLOCK)) {
-       (void) fprintf(stderr, "%s: sudoers file busy, try again later.\n",
-           Argv[0]);
-       exit(1);
-    }
-#ifdef HAVE_FSTAT
-    if (fstat(sudoers_fd, &sudoers_sb) == -1) {
-#else
-    if (stat(sudoers, &sudoers_sb) == -1) {
-#endif
-       (void) fprintf(stderr, "%s: can't stat %s: %s\n",
-           Argv[0], sudoers, strerror(errno));
-       exit(1);
+    if ((yyin = open_sudoers(sudoers_path, TRUE, NULL)) == NULL) {
+       error(1, "%s", sudoers_path);
     }
+    init_parser(sudoers_path, 0);
+    yyparse();
+    (void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
 
-    /*
-     * Open sudoers temp file.
-     */
-    stmp_fd = open(stmp, O_WRONLY | O_CREAT | O_TRUNC, 0600);
-    if (stmp_fd < 0) {
-       (void) fprintf(stderr, "%s: %s: %s\n", Argv[0], stmp, strerror(errno));
-       exit(1);
-    }
+    editor = get_editor(&args);
 
-    /* Install signal handlers to clean up stmp if we are killed. */
+    /* Install signal handlers to clean up temp files if we are killed. */
     setup_signals();
 
-    /* Copy sudoers -> stmp and reset the mtime */
-    if (sudoers_sb.st_size) {
-       while ((n = read(sudoers_fd, buf, sizeof(buf))) > 0)
-           if (write(stmp_fd, buf, n) != n) {
-               (void) fprintf(stderr, "%s: Write failed: %s\n", Argv[0],
-               strerror(errno));
-               Exit(-1);
-           }
-
-       (void) close(stmp_fd);
-       (void) touch(stmp, sudoers_sb.st_mtime);
-
-       /* Parse sudoers to pull in editor and env_editor conf values. */
-       if ((yyin = fopen(stmp, "r"))) {
-           yyout = stdout;
-           init_parser();
-           yyparse();
-           parse_error = FALSE;
-           yyrestart(yyin);
-           fclose(yyin);
+    /* Edit the sudoers file(s) */
+    tq_foreach_fwd(&sudoerslist, sp) {
+       if (!sp->doedit)
+           continue;
+       if (sp != tq_first(&sudoerslist)) {
+           printf("press return to edit %s: ", sp->path);
+           while ((ch = getchar()) != EOF && ch != '\n')
+                   continue;
        }
-    } else
-       (void) close(stmp_fd);
+       edit_sudoers(sp, editor, args, -1);
+    }
 
-    /*
-     * Check EDITOR and VISUAL environment variables to see which editor
-     * the user wants to use (we may not end up using it though).
-     * If the path is not fully-qualified, make it so and check that
-     * the specified executable actually exists.
-     */
-    if ((UserEditor = getenv("EDITOR")) == NULL || *UserEditor == '\0')
-       UserEditor = getenv("VISUAL");
-    if (UserEditor && *UserEditor == '\0')
-       UserEditor = NULL;
-    else if (UserEditor) {
-       if (find_path(UserEditor, &Editor, getenv("PATH")) == FOUND) {
-           UserEditor = Editor;
-       } else {
-           if (def_flag(I_ENV_EDITOR)) {
-               /* If we are honoring $EDITOR this is a fatal error. */
-               (void) fprintf(stderr,
-                   "%s: specified editor (%s) doesn't exist!\n",
-                   Argv[0], UserEditor);
-               Exit(-1);
-           } else {
-               /* Otherwise, just ignore $EDITOR. */
-               UserEditor = NULL;
-           }
-       }
+    /* Check edited files for a parse error and re-edit any that fail. */
+    reparse_sudoers(editor, args, strict, quiet);
+
+    /* Install the sudoers temp files. */
+    tq_foreach_fwd(&sudoerslist, sp) {
+       if (!sp->modified)
+           (void) unlink(sp->tpath);
+       else
+           (void) install_sudoers(sp, oldperms);
     }
 
-    /*
-     * See if we can use the user's choice of editors either because
-     * we allow any $EDITOR or because $EDITOR is in the allowable list.
-     */
-    Editor = EditorPath = NULL;
-    if (def_flag(I_ENV_EDITOR) && UserEditor)
-       Editor = UserEditor;
-    else if (UserEditor) {
-       struct stat editor_sb;
-       struct stat user_editor_sb;
-       char *base, *userbase;
+    exit(0);
+}
 
-       if (stat(UserEditor, &user_editor_sb) != 0) {
-           /* Should never happen since we already checked above. */
-           (void) fprintf(stderr, "%s: unable to stat editor (%s): %s\n",
-               Argv[0], UserEditor, strerror(errno));
-           Exit(-1);
-       }
-       EditorPath = estrdup(def_str(I_EDITOR));
-       Editor = strtok(EditorPath, ":");
-       do {
-           /*
-            * Both Editor and UserEditor should be fully qualified but
-            * check anyway...
-            */
-           if ((base = strrchr(Editor, '/')) == NULL)
-               continue;
-           if ((userbase = strrchr(UserEditor, '/')) == NULL) {
-               Editor = NULL;
-               break;
-           }
-           base++, userbase++;
+/*
+ * Edit each sudoers file.
+ * Returns TRUE on success, else FALSE.
+ */
+static int
+edit_sudoers(sp, editor, args, lineno)
+    struct sudoersfile *sp;
+    char *editor, *args;
+    int lineno;
+{
+    int tfd;                           /* sudoers temp file descriptor */
+    int modified;                      /* was the file modified? */
+    int ac;                            /* argument count */
+    char **av;                         /* argument vector for run_command */
+    char *cp;                          /* scratch char pointer */
+    char buf[PATH_MAX*2];              /* buffer used for copying files */
+    char linestr[64];                  /* string version of lineno */
+    struct timeval tv, tv1, tv2;       /* time before and after edit */
+    struct timeval orig_mtim;          /* starting mtime of sudoers file */
+    off_t orig_size;                   /* starting size of sudoers file */
+    ssize_t nread;                     /* number of bytes read */
+    struct stat sb;                    /* stat buffer */
 
-           /*
-            * We compare the basenames first and then use stat to match
-            * for sure.
-            */
-           if (strcmp(base, userbase) == 0) {
-               if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
-                   && (editor_sb.st_mode & 0000111) &&
-                   editor_sb.st_dev == user_editor_sb.st_dev &&
-                   editor_sb.st_ino == user_editor_sb.st_ino)
-                   break;
+#ifdef HAVE_FSTAT
+    if (fstat(sp->fd, &sb) == -1)
+#else
+    if (stat(sp->path, &sb) == -1)
+#endif
+       error(1, "can't stat %s", sp->path);
+    orig_size = sb.st_size;
+    mtim_get(&sb, &orig_mtim);
+
+    /* Create the temp file if needed and set timestamp. */
+    if (sp->tpath == NULL) {
+       easprintf(&sp->tpath, "%s.tmp", sp->path);
+       tfd = open(sp->tpath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
+       if (tfd < 0)
+           error(1, "%s", sp->tpath);
+
+       /* Copy sp->path -> sp->tpath and reset the mtime. */
+       if (orig_size != 0) {
+           (void) lseek(sp->fd, (off_t)0, SEEK_SET);
+           while ((nread = read(sp->fd, buf, sizeof(buf))) > 0)
+               if (write(tfd, buf, nread) != nread)
+                   error(1, "write error");
+
+           /* Add missing newline at EOF if needed. */
+           if (nread > 0 && buf[nread - 1] != '\n') {
+               buf[0] = '\n';
+               write(tfd, buf, 1);
            }
-       } while ((Editor = strtok(NULL, ":")));
+       }
+       (void) close(tfd);
+    }
+    (void) touch(-1, sp->tpath, &orig_mtim);
+
+    /* Find the length of the argument vector */
+    ac = 3 + (lineno > 0);
+    if (args) {
+        int wasblank;
+
+        ac++;
+        for (wasblank = FALSE, cp = args; *cp; cp++) {
+            if (isblank((unsigned char) *cp))
+                wasblank = TRUE;
+            else if (wasblank) {
+                wasblank = FALSE;
+                ac++;
+            }
+        }
     }
 
-    /*
-     * Can't use $EDITOR, try each element of I_EDITOR until we
-     * find one that exists, is regular, and is executable.
-     */
-    if (Editor == NULL || *Editor == '\0') {
-       if (EditorPath != NULL)
-           free(EditorPath);
-       EditorPath = estrdup(def_str(I_EDITOR));
-       Editor = strtok(EditorPath, ":");
-       do {
-           if (sudo_goodpath(Editor))
-               break;
-       } while ((Editor = strtok(NULL, ":")));
-
-       /* Bleah, none of the editors existed! */
-       if (Editor == NULL || *Editor == '\0') {
-           (void) fprintf(stderr, "%s: no editor found (editor path = %s)\n",
-               Argv[0], def_str(I_EDITOR));
-           Exit(-1);
-       }
+    /* Build up argument vector for the command */
+    av = emalloc2(ac, sizeof(char *));
+    if ((av[0] = strrchr(editor, '/')) != NULL)
+       av[0]++;
+    else
+       av[0] = editor;
+    ac = 1;
+    if (lineno > 0) {
+       (void) snprintf(linestr, sizeof(linestr), "+%d", lineno);
+       av[ac++] = linestr;
+    }
+    if (args) {
+       for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t")))
+           av[ac++] = cp;
     }
+    av[ac++] = sp->tpath;
+    av[ac++] = NULL;
 
     /*
-     * Edit the temp file and parse it (for sanity checking)
+     * Do the edit:
+     *  We cannot check the editor's exit value against 0 since
+     *  XPG4 specifies that vi's exit value is a function of the
+     *  number of errors during editing (?!?!).
      */
-    do {
-       char linestr[64];
-
-       /* Build up argument vector for the command */
-       if ((av[0] = strrchr(Editor, '/')) != NULL)
-           av[0]++;
-       else
-           av[0] = Editor;
-       n = 1;
-       if (parse_error == TRUE) {
-           (void) snprintf(linestr, sizeof(linestr), "+%d", errorlineno);
-           av[n++] = linestr;
+    gettime(&tv1);
+    if (run_command(editor, av) != -1) {
+       gettime(&tv2);
+       /*
+        * Sanity checks.
+        */
+       if (stat(sp->tpath, &sb) < 0) {
+           warningx("cannot stat temporary file (%s), %s unchanged",
+               sp->tpath, sp->path);
+           return(FALSE);
+       }
+       if (sb.st_size == 0 && orig_size != 0) {
+           warningx("zero length temporary file (%s), %s unchanged",
+               sp->tpath, sp->path);
+           sp->modified = TRUE;
+           return(FALSE);
        }
-       av[n++] = stmp;
-       av[n++] = NULL;
+    } else {
+       warningx("editor (%s) failed, %s unchanged", editor, sp->path);
+       return(FALSE);
+    }
 
+    /* Set modified bit if use changed the file. */
+    modified = TRUE;
+    mtim_get(&sb, &tv);
+    if (orig_size == sb.st_size && timevalcmp(&orig_mtim, &tv, ==)) {
        /*
-        * Do the edit:
-        *  We cannot check the editor's exit value against 0 since
-        *  XPG4 specifies that vi's exit value is a function of the
-        *  number of errors during editing (?!?!).
+        * If mtime and size match but the user spent no measurable
+        * time in the editor we can't tell if the file was changed.
         */
-       now = time(NULL);
-       if (run_command(Editor, av) != -1) {
-           /*
-            * Sanity checks.
-            */
-           if (stat(stmp, &stmp_sb) < 0) {
-               (void) fprintf(stderr,
-                   "%s: Can't stat temporary file (%s), %s unchanged.\n",
-                   Argv[0], stmp, sudoers);
-               Exit(-1);
-           }
-           if (stmp_sb.st_size == 0) {
-               (void) fprintf(stderr,
-                   "%s: Zero length temporary file (%s), %s unchanged.\n",
-                   Argv[0], stmp, sudoers);
-               Exit(-1);
-           }
+       timevalsub(&tv1, &tv2);
+       if (timevalisset(&tv2))
+           modified = FALSE;
+    }
 
-           /*
-            * Passed sanity checks so reopen stmp file and check
-            * for parse errors.
-            */
-           yyout = stdout;
-           if (parse_error)
-               yyin = freopen(stmp, "r", yyin);
-           else
-               yyin = fopen(stmp, "r");
-           if (yyin == NULL) {
-               (void) fprintf(stderr,
-                   "%s: Can't re-open temporary file (%s), %s unchanged.\n",
-                   Argv[0], stmp, sudoers);
-               Exit(-1);
-           }
+    /*
+     * If modified in this edit session, mark as modified.
+     */
+    if (modified)
+       sp->modified = modified;
+    else
+       warningx("%s unchanged", sp->tpath);
+
+    return(TRUE);
+}
 
-           /* Clean slate for each parse */
-           user_runas = NULL;
-           init_defaults();
-           init_parser();
+/*
+ * Parse sudoers after editing and re-edit any ones that caused a parse error.
+ * Returns TRUE on success, else FALSE.
+ */
+static int
+reparse_sudoers(editor, args, strict, quiet)
+    char *editor, *args;
+    int strict, quiet;
+{
+    struct sudoersfile *sp, *last;
+    FILE *fp;
+    int ch;
 
-           /* Parse the sudoers file */
-           if (yyparse() && parse_error != TRUE) {
-               (void) fprintf(stderr,
-                   "%s: Failed to parse temporary file (%s), unknown error.\n",
-                   Argv[0], stmp);
+    /*
+     * Parse the edited sudoers files and do sanity checking
+     */
+    do {
+       sp = tq_first(&sudoerslist);
+       last = tq_last(&sudoerslist);
+       fp = fopen(sp->tpath, "r+");
+       if (fp == NULL)
+           errorx(1, "can't re-open temporary file (%s), %s unchanged.",
+               sp->tpath, sp->path);
+
+       /* Clean slate for each parse */
+       init_defaults();
+       init_parser(sp->path, quiet);
+
+       /* Parse the sudoers temp file */
+       yyrestart(fp);
+       if (yyparse() && !parse_error) {
+           warningx("unabled to parse temporary file (%s), unknown error",
+               sp->tpath);
+           parse_error = TRUE;
+           errorfile = sp->path;
+       }
+       fclose(yyin);
+       if (!parse_error) {
+           if (!update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER) ||
+               check_aliases(strict, quiet) != 0) {
                parse_error = TRUE;
+               errorfile = sp->path;
            }
-       } else {
-           (void) fprintf(stderr,
-               "%s: Editor (%s) failed, %s unchanged.\n", Argv[0],
-                   Editor, sudoers);
-           Exit(-1);
        }
 
        /*
         * Got an error, prompt the user for what to do now
         */
-       if (parse_error == TRUE) {
+       if (parse_error) {
            switch (whatnow()) {
                case 'Q' :      parse_error = FALSE;    /* ignore parse error */
                                break;
-               case 'x' :      if (sudoers_sb.st_size == 0)
-                                   unlink(sudoers);
-                               Exit(0);
+               case 'x' :      cleanup(0);
+                               exit(0);
                                break;
            }
-           yyrestart(yyin);    /* reset lexer */
        }
-    } while (parse_error == TRUE);
+       if (parse_error) {
+           /* Edit file with the parse error */
+           tq_foreach_fwd(&sudoerslist, sp) {
+               if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
+                   edit_sudoers(sp, editor, args, errorlineno);
+                   break;
+               }
+           }
+           if (sp == NULL)
+               errorx(1, "internal error, can't find %s in list!", sudoers);
+       }
 
-    /*
-     * If the user didn't change the temp file, just unlink it.
-     */
-    if (sudoers_sb.st_mtime != now && sudoers_sb.st_mtime == stmp_sb.st_mtime &&
-       sudoers_sb.st_size == stmp_sb.st_size) {
-       (void) fprintf(stderr, "%s: sudoers file unchanged.\n", Argv[0]);
-       Exit(0);
-    }
+       /* If any new #include directives were added, edit them too. */
+       for (sp = last->next; sp != NULL; sp = sp->next) {
+           printf("press return to edit %s: ", sp->path);
+           while ((ch = getchar()) != EOF && ch != '\n')
+                   continue;
+           edit_sudoers(sp, editor, args, errorlineno);
+       }
+    } while (parse_error);
+
+    return(TRUE);
+}
+
+/*
+ * Set the owner and mode on a sudoers temp file and
+ * move it into place.  Returns TRUE on success, else FALSE.
+ */
+static int
+install_sudoers(sp, oldperms)
+    struct sudoersfile *sp;
+    int oldperms;
+{
+    struct stat sb;
 
     /*
      * Change mode and ownership of temp file so when
-     * we move it to sudoers things are kosher.
+     * we move it to sp->path things are kosher.
      */
-    if (chown(stmp, SUDOERS_UID, SUDOERS_GID)) {
-       (void) fprintf(stderr,
-           "%s: Unable to set (uid, gid) of %s to (%d, %d): %s\n",
-           Argv[0], stmp, SUDOERS_UID, SUDOERS_GID, strerror(errno));
-       Exit(-1);
-    }
-    if (chmod(stmp, SUDOERS_MODE)) {
-       (void) fprintf(stderr,
-           "%s: Unable to change mode of %s to %o: %s\n",
-           Argv[0], stmp, SUDOERS_MODE, strerror(errno));
-       Exit(-1);
+    if (oldperms) {
+       /* Use perms of the existing file.  */
+#ifdef HAVE_FSTAT
+       if (fstat(sp->fd, &sb) == -1)
+#else
+       if (stat(sp->path, &sb) == -1)
+#endif
+           error(1, "can't stat %s", sp->path);
+       (void) chown(sp->tpath, sb.st_uid, sb.st_gid);
+       (void) chmod(sp->tpath, sb.st_mode & 0777);
+    } else {
+       if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
+           warning("unable to set (uid, gid) of %s to (%d, %d)",
+               sp->tpath, SUDOERS_UID, SUDOERS_GID);
+           return(FALSE);
+       }
+       if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
+           warning("unable to change mode of %s to 0%o", sp->tpath,
+               SUDOERS_MODE);
+           return(FALSE);
+       }
     }
 
     /*
-     * Now that we have a sane stmp file (parses ok) it needs to be
-     * rename(2)'d to sudoers.  If the rename(2) fails we try using
-     * mv(1) in case stmp and sudoers are on different filesystems.
+     * Now that sp->tpath is sane (parses ok) it needs to be
+     * rename(2)'d to sp->path.  If the rename(2) fails we try using
+     * mv(1) in case sp->tpath and sp->path are on different file systems.
      */
-    if (rename(stmp, sudoers)) {
+    if (rename(sp->tpath, sp->path) == 0) {
+       efree(sp->tpath);
+       sp->tpath = NULL;
+    } else {
        if (errno == EXDEV) {
-           (void) fprintf(stderr,
-             "%s: %s and %s not on the same filesystem, using mv to rename.\n",
-             Argv[0], stmp, sudoers);
+           char *av[4];
+           warningx("%s and %s not on the same file system, using mv to rename",
+             sp->tpath, sp->path);
 
            /* Build up argument vector for the command */
            if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
                av[0]++;
            else
                av[0] = _PATH_MV;
-           av[1] = stmp;
-           av[2] = sudoers;
+           av[1] = sp->tpath;
+           av[2] = sp->path;
            av[3] = NULL;
 
            /* And run it... */
            if (run_command(_PATH_MV, av)) {
-               (void) fprintf(stderr,
-                              "%s: Command failed: '%s %s %s', %s unchanged.\n",
-                              Argv[0], _PATH_MV, stmp, sudoers, sudoers);
-               Exit(-1);
+               warningx("command failed: '%s %s %s', %s unchanged",
+                   _PATH_MV, sp->tpath, sp->path, sp->path);
+               (void) unlink(sp->tpath);
+               efree(sp->tpath);
+               sp->tpath = NULL;
+               return(FALSE);
            }
+           efree(sp->tpath);
+           sp->tpath = NULL;
        } else {
-           (void) fprintf(stderr, "%s: Error renaming %s, %s unchanged: %s\n",
-                                  Argv[0], stmp, sudoers, strerror(errno));
-           Exit(-1);
+           warning("error renaming %s, %s unchanged", sp->tpath, sp->path);
+           (void) unlink(sp->tpath);
+           return(FALSE);
        }
     }
-
-    exit(0);
-}
-
-/*
- * Dummy *_matches routines.
- * These exist to allow us to use the same parser as sudo(8).
- */
-int
-command_matches(cmnd, cmnd_args, path, sudoers_args)
-    char *cmnd;
-    char *cmnd_args;
-    char *path;
-    char *sudoers_args;
-{
     return(TRUE);
 }
 
-int
-addr_matches(n)
-    char *n;
-{
-    return(TRUE);
-}
-
-int
-hostname_matches(s, l, p)
-    char *s, *l, *p;
+/* STUB */
+void
+set_fqdn()
 {
-    return(TRUE);
+    return;
 }
 
-int
-usergr_matches(g, u)
-    char *g, *u;
+/* STUB */
+void
+init_envtables()
 {
-    return(TRUE);
+    return;
 }
 
+/* STUB */
 int
-netgr_matches(n, h, sh, u)
-    char *n, *h, *sh, *u;
+user_is_exempt()
 {
-    return(TRUE);
+    return(FALSE);
 }
 
+/* STUB */
 void
-set_fqdn()
+sudo_setspent()
 {
     return;
 }
 
-int
-user_is_exempt()
+/* STUB */
+void
+sudo_endspent()
 {
-    return(TRUE);
+    return;
 }
 
-void
-init_envtables()
+char *
+sudo_getepw(pw)
+    const struct passwd *pw;
 {
-    return;
+    return (pw->pw_passwd);
 }
 
 /*
@@ -602,9 +633,10 @@ setup_signals()
        /*
         * Setup signal handlers to cleanup nicely.
         */
+       zero_bytes(&sa, sizeof(sa));
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = SA_RESTART;
-       sa.sa_handler = Exit;
+       sa.sa_handler = quit;
        (void) sigaction(SIGTERM, &sa, NULL);
        (void) sigaction(SIGHUP, &sa, NULL);
        (void) sigaction(SIGINT, &sa, NULL);
@@ -617,96 +649,534 @@ run_command(path, argv)
     char **argv;
 {
     int status;
-    pid_t pid;
-    sigset_t set, oset;
-
-    (void) sigemptyset(&set);
-    (void) sigaddset(&set, SIGCHLD);
-    (void) sigprocmask(SIG_BLOCK, &set, &oset);
+    pid_t pid, rv;
 
     switch (pid = fork()) {
        case -1:
-           (void) fprintf(stderr,
-               "%s: unable to run %s: %s\n", Argv[0], path, strerror(errno));
-           Exit(-1);
+           error(1, "unable to run %s", path);
            break;      /* NOTREACHED */
        case 0:
-           (void) sigprocmask(SIG_SETMASK, &oset, NULL);
+           sudo_endpwent();
+           sudo_endgrent();
+           closefrom(STDERR_FILENO + 1);
            execv(path, argv);
-           (void) fprintf(stderr,
-               "%s: unable to run %s: %s\n", Argv[0], path, strerror(errno));
+           warning("unable to run %s", path);
            _exit(127);
            break;      /* NOTREACHED */
     }
 
+    do {
 #ifdef sudo_waitpid
-    pid = sudo_waitpid(pid, &status, 0);
+       rv = sudo_waitpid(pid, &status, 0);
 #else
-    pid = wait(&status);
+       rv = wait(&status);
 #endif
+    } while (rv == -1 && errno == EINTR);
 
-    (void) sigprocmask(SIG_SETMASK, &oset, NULL);
-
-    /* XXX - should use WEXITSTATUS() */
-    return(pid == -1 ? -1 : (status >> 8));
+    if (rv == -1 || !WIFEXITED(status))
+       return(-1);
+    return(WEXITSTATUS(status));
 }
 
 static int
-check_syntax(quiet)
+check_syntax(sudoers_path, quiet, strict)
+    char *sudoers_path;
     int quiet;
+    int strict;
 {
+    struct stat sb;
+    int error;
 
-    if ((yyin = fopen(sudoers, "r")) == NULL) {
+    if ((yyin = fopen(sudoers_path, "r")) == NULL) {
        if (!quiet)
-           (void) fprintf(stderr, "%s: unable to open %s: %s\n", Argv[0],
-               sudoers, strerror(errno));
+           warning("unable to open %s", sudoers_path);
        exit(1);
     }
-    yyout = stdout;
-    init_parser();
-    if (yyparse() && parse_error != TRUE) {
+    init_parser(sudoers_path, quiet);
+    if (yyparse() && !parse_error) {
        if (!quiet)
-           (void) fprintf(stderr,
-               "%s: failed to parse %s file, unknown error.\n",
-               Argv[0], sudoers);
+           warningx("failed to parse %s file, unknown error", sudoers_path);
        parse_error = TRUE;
+       errorfile = sudoers_path;
     }
-    if (!quiet){
-       if (parse_error)
-           (void) printf("parse error in %s near line %d\n", sudoers,
-               errorlineno);
-       else
-           (void) printf("%s file parsed OK\n", sudoers);
+    if (!parse_error && check_aliases(strict, quiet) != 0) {
+       parse_error = TRUE;
+       errorfile = sudoers_path;
+    }
+    error = parse_error;
+    if (!quiet) {
+       if (parse_error) {
+           if (errorlineno != -1)
+               (void) printf("parse error in %s near line %d\n", errorfile,
+                   errorlineno);
+           else
+               (void) printf("parse error in %s\n", errorfile);
+       } else {
+           (void) printf("%s: parsed OK\n", sudoers_path);
+       }
+    }
+    /* Check mode and owner in strict mode. */
+#ifdef HAVE_FSTAT
+    if (strict && fstat(fileno(yyin), &sb) == 0)
+#else
+    if (strict && stat(sudoers_path, &sb) == 0)
+#endif
+    {
+       if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
+           error = TRUE;
+           if (!quiet) {
+               fprintf(stderr, "%s: wrong owner (uid, gid) should be (%d, %d)\n",
+                   sudoers_path, SUDOERS_UID, SUDOERS_GID);
+               }
+       }
+       if ((sb.st_mode & 07777) != SUDOERS_MODE) {
+           error = TRUE;
+           if (!quiet) {
+               fprintf(stderr, "%s: bad permissions, should be mode 0%o\n",
+                   sudoers_path, SUDOERS_MODE);
+           }
+       }
     }
 
-    return(parse_error == TRUE);
+    return(error);
 }
 
 /*
- * Unlink the sudoers temp file (if it exists) and exit.
- * Used in place of a normal exit() and as a signal handler.
- * A positive parameter indicates we were called as a signal handler.
+ * Used to open (and lock) the initial sudoers file and to also open
+ * any subsequent files #included via a callback from the parser.
  */
-static RETSIGTYPE
-Exit(sig)
-    int sig;
+FILE *
+open_sudoers(path, doedit, keepopen)
+    const char *path;
+    int doedit;
+    int *keepopen;
+{
+    struct sudoersfile *entry;
+    FILE *fp;
+
+    /* Check for existing entry */
+    tq_foreach_fwd(&sudoerslist, entry) {
+       if (strcmp(path, entry->path) == 0)
+           break;
+    }
+    if (entry == NULL) {
+       entry = emalloc(sizeof(*entry));
+       entry->path = estrdup(path);
+       entry->modified = 0;
+       entry->prev = entry;
+       entry->next = NULL;
+       entry->fd = open(entry->path, O_RDWR | O_CREAT, SUDOERS_MODE);
+       entry->tpath = NULL;
+       entry->doedit = doedit;
+       if (entry->fd == -1) {
+           warning("%s", entry->path);
+           efree(entry);
+           return(NULL);
+       }
+       if (!lock_file(entry->fd, SUDO_TLOCK))
+           errorx(1, "%s busy, try again later", entry->path);
+       if ((fp = fdopen(entry->fd, "r")) == NULL)
+           error(1, "%s", entry->path);
+       tq_append(&sudoerslist, entry);
+    } else {
+       /* Already exists, open .tmp version if there is one. */
+       if (entry->tpath != NULL) {
+           if ((fp = fopen(entry->tpath, "r")) == NULL)
+               error(1, "%s", entry->tpath);
+       } else {
+           if ((fp = fdopen(entry->fd, "r")) == NULL)
+               error(1, "%s", entry->path);
+           rewind(fp);
+       }
+    }
+    if (keepopen != NULL)
+       *keepopen = TRUE;
+    return(fp);
+}
+
+static char *
+get_editor(args)
+    char **args;
 {
-    char *emsg = " exiting due to signal.\n";
+    char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
+
+    /*
+     * Check VISUAL and EDITOR environment variables to see which editor
+     * the user wants to use (we may not end up using it though).
+     * If the path is not fully-qualified, make it so and check that
+     * the specified executable actually exists.
+     */
+    UserEditorArgs = NULL;
+    if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
+       UserEditor = getenv("EDITOR");
+    if (UserEditor && *UserEditor == '\0')
+       UserEditor = NULL;
+    else if (UserEditor) {
+       UserEditorArgs = get_args(UserEditor);
+       if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
+           UserEditor = Editor;
+       } else {
+           if (def_env_editor) {
+               /* If we are honoring $EDITOR this is a fatal error. */
+               errorx(1, "specified editor (%s) doesn't exist!", UserEditor);
+           } else {
+               /* Otherwise, just ignore $EDITOR. */
+               UserEditor = NULL;
+           }
+       }
+    }
+
+    /*
+     * See if we can use the user's choice of editors either because
+     * we allow any $EDITOR or because $EDITOR is in the allowable list.
+     */
+    Editor = EditorArgs = EditorPath = NULL;
+    if (def_env_editor && UserEditor) {
+       Editor = UserEditor;
+       EditorArgs = UserEditorArgs;
+    } else if (UserEditor) {
+       struct stat editor_sb;
+       struct stat user_editor_sb;
+       char *base, *userbase;
 
-    (void) unlink(stmp);
+       if (stat(UserEditor, &user_editor_sb) != 0) {
+           /* Should never happen since we already checked above. */
+           error(1, "unable to stat editor (%s)", UserEditor);
+       }
+       EditorPath = estrdup(def_editor);
+       Editor = strtok(EditorPath, ":");
+       do {
+           EditorArgs = get_args(Editor);
+           /*
+            * Both Editor and UserEditor should be fully qualified but
+            * check anyway...
+            */
+           if ((base = strrchr(Editor, '/')) == NULL)
+               continue;
+           if ((userbase = strrchr(UserEditor, '/')) == NULL) {
+               Editor = NULL;
+               break;
+           }
+           base++, userbase++;
 
-    if (sig > 0) {
-       write(STDERR_FILENO, Argv[0], strlen(Argv[0]));
-       write(STDERR_FILENO, emsg, sizeof(emsg) - 1);
-       _exit(-sig);
+           /*
+            * We compare the basenames first and then use stat to match
+            * for sure.
+            */
+           if (strcmp(base, userbase) == 0) {
+               if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
+                   && (editor_sb.st_mode & 0000111) &&
+                   editor_sb.st_dev == user_editor_sb.st_dev &&
+                   editor_sb.st_ino == user_editor_sb.st_ino)
+                   break;
+           }
+       } while ((Editor = strtok(NULL, ":")));
     }
-    exit(-sig);
+
+    /*
+     * Can't use $EDITOR, try each element of def_editor until we
+     * find one that exists, is regular, and is executable.
+     */
+    if (Editor == NULL || *Editor == '\0') {
+       efree(EditorPath);
+       EditorPath = estrdup(def_editor);
+       Editor = strtok(EditorPath, ":");
+       do {
+           EditorArgs = get_args(Editor);
+           if (sudo_goodpath(Editor, NULL))
+               break;
+       } while ((Editor = strtok(NULL, ":")));
+
+       /* Bleah, none of the editors existed! */
+       if (Editor == NULL || *Editor == '\0')
+           errorx(1, "no editor found (editor path = %s)", def_editor);
+    }
+    *args = EditorArgs;
+    return(Editor);
+}
+
+/*
+ * Split out any command line arguments and return them.
+ */
+static char *
+get_args(cmnd)
+    char *cmnd;
+{
+    char *args;
+
+    args = cmnd;
+    while (*args && !isblank((unsigned char) *args))
+       args++;
+    if (*args) {
+       *args++ = '\0';
+       while (*args && isblank((unsigned char) *args))
+           args++;
+    }
+    return(*args ? args : NULL);
+}
+
+/*
+ * Look up the hostname and set user_host and user_shost.
+ */
+static void
+get_hostname()
+{
+    char *p, thost[MAXHOSTNAMELEN + 1];
+
+    if (gethostname(thost, sizeof(thost)) != 0) {
+       user_host = user_shost = "localhost";
+       return;
+    }
+    thost[sizeof(thost) - 1] = '\0';
+    user_host = estrdup(thost);
+
+    if ((p = strchr(user_host, '.'))) {
+       *p = '\0';
+       user_shost = estrdup(user_host);
+       *p = '.';
+    } else {
+       user_shost = user_host;
+    }
+}
+
+static int
+alias_remove_recursive(name, type, strict, quiet)
+    char *name;
+    int type;
+    int strict;
+    int quiet;
+{
+    struct member *m;
+    struct alias *a;
+    int error = 0;
+
+    if ((a = alias_find(name, type)) != NULL) {
+       tq_foreach_fwd(&a->members, m) {
+           if (m->type == ALIAS) {
+               if (strcmp(name, m->name) == 0) {
+                   print_selfref(m->name, type, strict, quiet);
+                   error = 1;
+               } else {
+                   if (!alias_remove_recursive(m->name, type, strict, quiet))
+                       error = 1;
+               }
+           }
+       }
+    }
+    alias_seqno++;
+    a = alias_remove(name, type);
+    if (a)
+       rbinsert(alias_freelist, a);
+    return(error);
+}
+
+/*
+ * Iterate through the sudoers datastructures looking for undefined
+ * aliases or unused aliases.
+ */
+static int
+check_aliases(strict, quiet)
+    int strict;
+    int quiet;
+{
+    struct cmndspec *cs;
+    struct member *m, *binding;
+    struct privilege *priv;
+    struct userspec *us;
+    struct defaults *d;
+    int atype, error = 0;
+
+    alias_freelist = rbcreate(alias_compare);
+
+    /* Forward check. */
+    tq_foreach_fwd(&userspecs, us) {
+       tq_foreach_fwd(&us->users, m) {
+           if (m->type == ALIAS) {
+               alias_seqno++;
+               if (alias_find(m->name, USERALIAS) == NULL) {
+                   print_undefined(m->name, USERALIAS, strict, quiet);
+                   error++;
+               }
+           }
+       }
+       tq_foreach_fwd(&us->privileges, priv) {
+           tq_foreach_fwd(&priv->hostlist, m) {
+               if (m->type == ALIAS) {
+                   alias_seqno++;
+                   if (alias_find(m->name, HOSTALIAS) == NULL) {
+                       print_undefined(m->name, HOSTALIAS, strict, quiet);
+                       error++;
+                   }
+               }
+           }
+           tq_foreach_fwd(&priv->cmndlist, cs) {
+               tq_foreach_fwd(&cs->runasuserlist, m) {
+                   if (m->type == ALIAS) {
+                       alias_seqno++;
+                       if (alias_find(m->name, RUNASALIAS) == NULL) {
+                           print_undefined(m->name, RUNASALIAS, strict, quiet);
+                           error++;
+                       }
+                   }
+               }
+               if ((m = cs->cmnd)->type == ALIAS) {
+                   alias_seqno++;
+                   if (alias_find(m->name, CMNDALIAS) == NULL) {
+                       print_undefined(m->name, CMNDALIAS, strict, quiet);
+                       error++;
+                   }
+               }
+           }
+       }
+    }
+
+    /* Reverse check (destructive) */
+    tq_foreach_fwd(&userspecs, us) {
+       tq_foreach_fwd(&us->users, m) {
+           if (m->type == ALIAS) {
+               if (!alias_remove_recursive(m->name, USERALIAS, strict, quiet))
+                   error++;
+           }
+       }
+       tq_foreach_fwd(&us->privileges, priv) {
+           tq_foreach_fwd(&priv->hostlist, m) {
+               if (m->type == ALIAS)
+                   if (!alias_remove_recursive(m->name, HOSTALIAS, strict, 
+                       quiet))
+                       error++;
+           }
+           tq_foreach_fwd(&priv->cmndlist, cs) {
+               tq_foreach_fwd(&cs->runasuserlist, m) {
+                   if (m->type == ALIAS)
+                       if (!alias_remove_recursive(m->name, RUNASALIAS,
+                           strict, quiet))
+                           error++;
+               }
+               if ((m = cs->cmnd)->type == ALIAS)
+                   if (!alias_remove_recursive(m->name, CMNDALIAS, strict,
+                       quiet))
+                       error++;
+           }
+       }
+    }
+    tq_foreach_fwd(&defaults, d) {
+       switch (d->type) {
+           case DEFAULTS_HOST:
+               atype = HOSTALIAS;
+               break;
+           case DEFAULTS_USER:
+               atype = USERALIAS;
+               break;
+           case DEFAULTS_RUNAS:
+               atype = RUNASALIAS;
+               break;
+           case DEFAULTS_CMND:
+               atype = CMNDALIAS;
+               break;
+           default:
+               continue; /* not an alias */
+       }
+       tq_foreach_fwd(&d->binding, binding) {
+           for (m = binding; m != NULL; m = m->next) {
+               if (m->type == ALIAS)
+                   if (!alias_remove_recursive(m->name, atype, strict, quiet))
+                       error++;
+           }
+       }
+    }
+    rbdestroy(alias_freelist, alias_free);
+
+    /* If all aliases were referenced we will have an empty tree. */
+    if (!no_aliases() && !quiet)
+       alias_apply(print_unused, strict ? "Error" : "Warning");
+
+    return (strict ? error : 0);
+}
+
+static void
+print_undefined(name, type, strict, quiet)
+    char *name;
+    int type;
+    int strict;
+    int quiet;
+{
+    if (!quiet) {
+       warningx("%s: %s_Alias `%s' referenced but not defined",
+           strict ? "Error" : "Warning",
+           type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
+           type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
+           "Unknown", name);
+    }
+}
+
+static void
+print_selfref(name, type, strict, quiet)
+    char *name;
+    int type;
+    int strict;
+    int quiet;
+{
+    if (!quiet) {
+       warningx("%s: %s_Alias `%s' references self",
+           strict ? "Error" : "Warning",
+           type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
+           type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
+           "Unknown", name);
+    }
+}
+
+static int
+print_unused(v1, v2)
+    void *v1;
+    void *v2;
+{
+    struct alias *a = (struct alias *)v1;
+    char *prefix = (char *)v2;
+
+    warningx("%s: unused %s_Alias %s", prefix,
+       a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
+       a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
+       "Unknown", a->name);
+    return(0);
+}
+
+/*
+ * Unlink any sudoers temp files that remain.
+ */
+void
+cleanup(gotsignal)
+    int gotsignal;
+{
+    struct sudoersfile *sp;
+
+    tq_foreach_fwd(&sudoerslist, sp) {
+       if (sp->tpath != NULL)
+           (void) unlink(sp->tpath);
+    }
+    if (!gotsignal) {
+       sudo_endpwent();
+       sudo_endgrent();
+    }
+}
+
+/*
+ * Unlink sudoers temp files (if any) and exit.
+ */
+static RETSIGTYPE
+quit(signo)
+    int signo;
+{
+    cleanup(signo);
+#define        emsg     " exiting due to signal.\n"
+    write(STDERR_FILENO, getprogname(), strlen(getprogname()));
+    write(STDERR_FILENO, emsg, sizeof(emsg) - 1);
+    _exit(signo);
 }
 
 static void
 usage()
 {
-    (void) fprintf(stderr, "usage: %s [-c] [-f sudoers] [-q] [-s] [-V]\n",
-       Argv[0]);
+    (void) fprintf(stderr, "usage: %s [-c] [-q] [-s] [-V] [-f sudoers]\n",
+       getprogname());
     exit(1);
 }