Annotation of embedaddon/sudo/plugins/sudoers/visudo.c, revision 1.1.1.2

1.1       misho       1: /*
1.1.1.2 ! misho       2:  * Copyright (c) 1996, 1998-2005, 2007-2012
1.1       misho       3:  *     Todd C. Miller <Todd.Miller@courtesan.com>
                      4:  *
                      5:  * Permission to use, copy, modify, and distribute this software for any
                      6:  * purpose with or without fee is hereby granted, provided that the above
                      7:  * copyright notice and this permission notice appear in all copies.
                      8:  *
                      9:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     10:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     11:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     12:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     13:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     14:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     15:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     16:  *
                     17:  * Sponsored in part by the Defense Advanced Research Projects
                     18:  * Agency (DARPA) and Air Force Research Laboratory, Air Force
                     19:  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
                     20:  */
                     21: 
                     22: /*
                     23:  * Lock the sudoers file for safe editing (ala vipw) and check for parse errors.
                     24:  */
                     25: 
                     26: #define _SUDO_MAIN
                     27: 
                     28: #ifdef __TANDEM
                     29: # include <floss.h>
                     30: #endif
                     31: 
                     32: #include <config.h>
                     33: 
                     34: #include <sys/types.h>
                     35: #include <sys/param.h>
                     36: #include <sys/stat.h>
                     37: #include <sys/socket.h>
                     38: #include <sys/time.h>
                     39: #ifndef __TANDEM
                     40: # include <sys/file.h>
                     41: #endif
                     42: #include <sys/wait.h>
                     43: #include <stdio.h>
                     44: #ifdef STDC_HEADERS
                     45: # include <stdlib.h>
                     46: # include <stddef.h>
                     47: #else
                     48: # ifdef HAVE_STDLIB_H
                     49: #  include <stdlib.h>
                     50: # endif
                     51: #endif /* STDC_HEADERS */
                     52: #ifdef HAVE_STRING_H
                     53: # include <string.h>
                     54: #endif /* HAVE_STRING_H */
                     55: #ifdef HAVE_STRINGS_H
                     56: # include <strings.h>
                     57: #endif /* HAVE_STRINGS_H */
                     58: #ifdef HAVE_UNISTD_H
                     59: #include <unistd.h>
                     60: #endif /* HAVE_UNISTD_H */
                     61: #include <stdarg.h>
                     62: #include <ctype.h>
                     63: #include <pwd.h>
                     64: #include <grp.h>
                     65: #include <signal.h>
                     66: #include <errno.h>
                     67: #include <fcntl.h>
                     68: #include <netinet/in.h>
                     69: #include <arpa/inet.h>
                     70: #include <netdb.h>
                     71: #if TIME_WITH_SYS_TIME
                     72: # include <time.h>
                     73: #endif
                     74: #ifdef HAVE_SETLOCALE
                     75: # include <locale.h>
                     76: #endif
                     77: 
                     78: #include "sudoers.h"
                     79: #include "interfaces.h"
                     80: #include "parse.h"
                     81: #include "redblack.h"
                     82: #include "gettext.h"
                     83: #include "sudoers_version.h"
1.1.1.2 ! misho      84: #include "sudo_conf.h"
1.1       misho      85: #include <gram.h>
                     86: 
                     87: struct sudoersfile {
                     88:     struct sudoersfile *prev, *next;
                     89:     char *path;
                     90:     char *tpath;
                     91:     int fd;
                     92:     int modified;
                     93:     int doedit;
                     94: };
                     95: TQ_DECLARE(sudoersfile)
                     96: 
1.1.1.2 ! misho      97: sudo_conv_t sudo_conv; /* NULL in non-plugin */
        !            98: 
1.1       misho      99: /*
                    100:  * Function prototypes
                    101:  */
                    102: static void quit(int);
                    103: static char *get_args(char *);
                    104: static char *get_editor(char **);
                    105: static void get_hostname(void);
1.1.1.2 ! misho     106: static int whatnow(void);
        !           107: static int check_aliases(bool, bool);
        !           108: static bool check_syntax(char *, bool, bool, bool);
        !           109: static bool edit_sudoers(struct sudoersfile *, char *, char *, int);
        !           110: static bool install_sudoers(struct sudoersfile *, bool);
1.1       misho     111: static int print_unused(void *, void *);
1.1.1.2 ! misho     112: static void reparse_sudoers(char *, char *, bool, bool);
1.1       misho     113: static int run_command(char *, char **);
                    114: static int visudo_printf(int msg_type, const char *fmt, ...);
                    115: static void setup_signals(void);
                    116: static void help(void) __attribute__((__noreturn__));
                    117: static void usage(int);
                    118: 
                    119: void cleanup(int);
                    120: 
                    121: extern void yyerror(const char *);
                    122: extern void yyrestart(FILE *);
                    123: 
                    124: /*
                    125:  * External globals exported by the parser
                    126:  */
                    127: extern struct rbtree *aliases;
                    128: extern FILE *yyin;
                    129: extern char *sudoers, *errorfile;
1.1.1.2 ! misho     130: extern int errorlineno;
        !           131: extern bool parse_error;
1.1       misho     132: /* For getopt(3) */
                    133: extern char *optarg;
                    134: extern int optind;
                    135: 
                    136: /*
                    137:  * Globals
                    138:  */
                    139: struct interface *interfaces;
                    140: struct sudo_user sudo_user;
                    141: struct passwd *list_pw;
                    142: sudo_printf_t sudo_printf = visudo_printf;
                    143: static struct sudoersfile_list sudoerslist;
                    144: static struct rbtree *alias_freelist;
1.1.1.2 ! misho     145: static bool checkonly;
1.1       misho     146: 
                    147: int
                    148: main(int argc, char *argv[])
                    149: {
                    150:     struct sudoersfile *sp;
                    151:     char *args, *editor, *sudoers_path;
1.1.1.2 ! misho     152:     int ch, exitcode = 0;
        !           153:     bool quiet, strict, oldperms;
        !           154:     debug_decl(main, SUDO_DEBUG_MAIN)
        !           155: 
1.1       misho     156: #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
1.1.1.2 ! misho     157:     {
        !           158:        extern char *malloc_options;
        !           159:        malloc_options = "AFGJPR";
        !           160:     }
1.1       misho     161: #endif
                    162: 
                    163: #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
                    164:     setprogname(argc > 0 ? argv[0] : "visudo");
                    165: #endif
                    166: 
                    167: #ifdef HAVE_SETLOCALE 
                    168:     setlocale(LC_ALL, "");
                    169: #endif
                    170:     bindtextdomain("sudoers", LOCALEDIR); /* XXX - should have visudo domain */
                    171:     textdomain("sudoers");
                    172: 
                    173:     if (argc < 1)
                    174:        usage(1);
                    175: 
1.1.1.2 ! misho     176:     /* Read sudo.conf. */
        !           177:     sudo_conf_read();
        !           178: 
1.1       misho     179:     /*
                    180:      * Arg handling.
                    181:      */
1.1.1.2 ! misho     182:     checkonly = oldperms = quiet = strict = false;
1.1       misho     183:     sudoers_path = _PATH_SUDOERS;
                    184:     while ((ch = getopt(argc, argv, "Vcf:sq")) != -1) {
                    185:        switch (ch) {
                    186:            case 'V':
                    187:                (void) printf(_("%s version %s\n"), getprogname(), PACKAGE_VERSION);
                    188:                (void) printf(_("%s grammar version %d\n"), getprogname(), SUDOERS_GRAMMAR_VERSION);
1.1.1.2 ! misho     189:                goto done;
1.1       misho     190:            case 'c':
                    191:                checkonly++;            /* check mode */
                    192:                break;
                    193:            case 'f':
                    194:                sudoers_path = optarg;  /* sudoers file path */
1.1.1.2 ! misho     195:                oldperms = true;
1.1       misho     196:                break;
                    197:            case 'h':
                    198:                help();
                    199:                break;
                    200:            case 's':
                    201:                strict++;               /* strict mode */
                    202:                break;
                    203:            case 'q':
                    204:                quiet++;                /* quiet mode */
                    205:                break;
                    206:            default:
                    207:                usage(1);
                    208:        }
                    209:     }
1.1.1.2 ! misho     210:     /* There should be no other command line arguments. */
        !           211:     if (argc - optind != 0)
1.1       misho     212:        usage(1);
                    213: 
                    214:     sudo_setpwent();
                    215:     sudo_setgrent();
                    216: 
                    217:     /* Mock up a fake sudo_user struct. */
                    218:     user_cmnd = "";
                    219:     if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
                    220:        errorx(1, _("you do not exist in the %s database"), "passwd");
                    221:     get_hostname();
                    222: 
                    223:     /* Setup defaults data structures. */
                    224:     init_defaults();
                    225: 
1.1.1.2 ! misho     226:     if (checkonly) {
        !           227:        exitcode = check_syntax(sudoers_path, quiet, strict, oldperms) ? 0 : 1;
        !           228:        goto done;
        !           229:     }
1.1       misho     230: 
                    231:     /*
                    232:      * Parse the existing sudoers file(s) in quiet mode to highlight any
                    233:      * existing errors and to pull in editor and env_editor conf values.
                    234:      */
1.1.1.2 ! misho     235:     if ((yyin = open_sudoers(sudoers_path, true, NULL)) == NULL) {
1.1       misho     236:        error(1, "%s", sudoers_path);
                    237:     }
                    238:     init_parser(sudoers_path, 0);
                    239:     yyparse();
                    240:     (void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
                    241: 
                    242:     editor = get_editor(&args);
                    243: 
                    244:     /* Install signal handlers to clean up temp files if we are killed. */
                    245:     setup_signals();
                    246: 
                    247:     /* Edit the sudoers file(s) */
                    248:     tq_foreach_fwd(&sudoerslist, sp) {
                    249:        if (!sp->doedit)
                    250:            continue;
                    251:        if (sp != tq_first(&sudoerslist)) {
                    252:            printf(_("press return to edit %s: "), sp->path);
                    253:            while ((ch = getchar()) != EOF && ch != '\n')
                    254:                    continue;
                    255:        }
                    256:        edit_sudoers(sp, editor, args, -1);
                    257:     }
                    258: 
                    259:     /* Check edited files for a parse error and re-edit any that fail. */
                    260:     reparse_sudoers(editor, args, strict, quiet);
                    261: 
1.1.1.2 ! misho     262:     /* Install the sudoers temp files as needed. */
1.1       misho     263:     tq_foreach_fwd(&sudoerslist, sp) {
1.1.1.2 ! misho     264:        (void) install_sudoers(sp, oldperms);
1.1       misho     265:     }
                    266: 
1.1.1.2 ! misho     267: done:
        !           268:     sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, exitcode);                
        !           269:     exit(exitcode);
1.1       misho     270: }
                    271: 
                    272: /*
                    273:  * List of editors that support the "+lineno" command line syntax.
                    274:  * If an entry starts with '*' the tail end of the string is matched.
                    275:  * No other wild cards are supported.
                    276:  */
                    277: static char *lineno_editors[] = {
                    278:     "ex",
                    279:     "nex",
                    280:     "vi",
                    281:     "nvi",
                    282:     "vim",
                    283:     "elvis",
                    284:     "*macs",
                    285:     "mg",
                    286:     "vile",
                    287:     "jove",
                    288:     "pico",
                    289:     "nano",
                    290:     "ee",
                    291:     "joe",
                    292:     "zile",
                    293:     NULL
                    294: };
                    295: 
                    296: /*
                    297:  * Edit each sudoers file.
1.1.1.2 ! misho     298:  * Returns true on success, else false.
1.1       misho     299:  */
1.1.1.2 ! misho     300: static bool
1.1       misho     301: edit_sudoers(struct sudoersfile *sp, char *editor, char *args, int lineno)
                    302: {
                    303:     int tfd;                           /* sudoers temp file descriptor */
1.1.1.2 ! misho     304:     bool modified;                     /* was the file modified? */
1.1       misho     305:     int ac;                            /* argument count */
                    306:     char **av;                         /* argument vector for run_command */
                    307:     char *cp;                          /* scratch char pointer */
                    308:     char buf[PATH_MAX*2];              /* buffer used for copying files */
                    309:     char linestr[64];                  /* string version of lineno */
                    310:     struct timeval tv, tv1, tv2;       /* time before and after edit */
                    311:     struct timeval orig_mtim;          /* starting mtime of sudoers file */
                    312:     off_t orig_size;                   /* starting size of sudoers file */
                    313:     ssize_t nread;                     /* number of bytes read */
                    314:     struct stat sb;                    /* stat buffer */
1.1.1.2 ! misho     315:     bool rval = false;                 /* return value */
        !           316:     debug_decl(edit_sudoers, SUDO_DEBUG_UTIL)
1.1       misho     317: 
                    318:     if (fstat(sp->fd, &sb) == -1)
                    319:        error(1, _("unable to stat %s"), sp->path);
                    320:     orig_size = sb.st_size;
                    321:     mtim_get(&sb, &orig_mtim);
                    322: 
                    323:     /* Create the temp file if needed and set timestamp. */
                    324:     if (sp->tpath == NULL) {
                    325:        easprintf(&sp->tpath, "%s.tmp", sp->path);
                    326:        tfd = open(sp->tpath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
                    327:        if (tfd < 0)
                    328:            error(1, "%s", sp->tpath);
                    329: 
                    330:        /* Copy sp->path -> sp->tpath and reset the mtime. */
                    331:        if (orig_size != 0) {
                    332:            (void) lseek(sp->fd, (off_t)0, SEEK_SET);
                    333:            while ((nread = read(sp->fd, buf, sizeof(buf))) > 0)
                    334:                if (write(tfd, buf, nread) != nread)
                    335:                    error(1, _("write error"));
                    336: 
                    337:            /* Add missing newline at EOF if needed. */
                    338:            if (nread > 0 && buf[nread - 1] != '\n') {
                    339:                buf[0] = '\n';
                    340:                if (write(tfd, buf, 1) != 1)
                    341:                    error(1, _("write error"));
                    342:            }
                    343:        }
                    344:        (void) close(tfd);
                    345:     }
                    346:     (void) touch(-1, sp->tpath, &orig_mtim);
                    347: 
                    348:     /* Does the editor support +lineno? */
                    349:     if (lineno > 0)
                    350:     {
                    351:        char *editor_base = strrchr(editor, '/');
                    352:        if (editor_base != NULL)
                    353:            editor_base++;
                    354:        else
                    355:            editor_base = editor;
                    356:        if (*editor_base == 'r')
                    357:            editor_base++;
                    358: 
                    359:        for (av = lineno_editors; (cp = *av) != NULL; av++) {
                    360:            /* We only handle a leading '*' wildcard. */
                    361:            if (*cp == '*') {
                    362:                size_t blen = strlen(editor_base);
                    363:                size_t clen = strlen(++cp);
                    364:                if (blen >= clen) {
                    365:                    if (strcmp(cp, editor_base + blen - clen) == 0)
                    366:                        break;
                    367:                }
                    368:            } else if (strcmp(cp, editor_base) == 0)
                    369:                break;
                    370:        }
                    371:        /* Disable +lineno if editor doesn't support it. */
                    372:        if (cp == NULL)
                    373:            lineno = -1;
                    374:     }
                    375: 
                    376:     /* Find the length of the argument vector */
                    377:     ac = 3 + (lineno > 0);
                    378:     if (args) {
1.1.1.2 ! misho     379:         bool wasblank;
1.1       misho     380: 
                    381:         ac++;
1.1.1.2 ! misho     382:         for (wasblank = false, cp = args; *cp; cp++) {
1.1       misho     383:             if (isblank((unsigned char) *cp))
1.1.1.2 ! misho     384:                 wasblank = true;
1.1       misho     385:             else if (wasblank) {
1.1.1.2 ! misho     386:                 wasblank = false;
1.1       misho     387:                 ac++;
                    388:             }
                    389:         }
                    390:     }
                    391: 
                    392:     /* Build up argument vector for the command */
                    393:     av = emalloc2(ac, sizeof(char *));
                    394:     if ((av[0] = strrchr(editor, '/')) != NULL)
                    395:        av[0]++;
                    396:     else
                    397:        av[0] = editor;
                    398:     ac = 1;
                    399:     if (lineno > 0) {
                    400:        (void) snprintf(linestr, sizeof(linestr), "+%d", lineno);
                    401:        av[ac++] = linestr;
                    402:     }
                    403:     if (args) {
                    404:        for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t")))
                    405:            av[ac++] = cp;
                    406:     }
                    407:     av[ac++] = sp->tpath;
                    408:     av[ac++] = NULL;
                    409: 
                    410:     /*
                    411:      * Do the edit:
                    412:      *  We cannot check the editor's exit value against 0 since
                    413:      *  XPG4 specifies that vi's exit value is a function of the
                    414:      *  number of errors during editing (?!?!).
                    415:      */
                    416:     gettimeofday(&tv1, NULL);
                    417:     if (run_command(editor, av) != -1) {
                    418:        gettimeofday(&tv2, NULL);
                    419:        /*
                    420:         * Sanity checks.
                    421:         */
                    422:        if (stat(sp->tpath, &sb) < 0) {
                    423:            warningx(_("unable to stat temporary file (%s), %s unchanged"),
                    424:                sp->tpath, sp->path);
1.1.1.2 ! misho     425:            goto done;
1.1       misho     426:        }
                    427:        if (sb.st_size == 0 && orig_size != 0) {
                    428:            warningx(_("zero length temporary file (%s), %s unchanged"),
                    429:                sp->tpath, sp->path);
1.1.1.2 ! misho     430:            sp->modified = true;
        !           431:            goto done;
1.1       misho     432:        }
                    433:     } else {
                    434:        warningx(_("editor (%s) failed, %s unchanged"), editor, sp->path);
1.1.1.2 ! misho     435:        goto done;
1.1       misho     436:     }
                    437: 
                    438:     /* Set modified bit if use changed the file. */
1.1.1.2 ! misho     439:     modified = true;
1.1       misho     440:     mtim_get(&sb, &tv);
                    441:     if (orig_size == sb.st_size && timevalcmp(&orig_mtim, &tv, ==)) {
                    442:        /*
                    443:         * If mtime and size match but the user spent no measurable
                    444:         * time in the editor we can't tell if the file was changed.
                    445:         */
                    446:        timevalsub(&tv1, &tv2);
                    447:        if (timevalisset(&tv2))
1.1.1.2 ! misho     448:            modified = false;
1.1       misho     449:     }
                    450: 
                    451:     /*
                    452:      * If modified in this edit session, mark as modified.
                    453:      */
                    454:     if (modified)
                    455:        sp->modified = modified;
                    456:     else
                    457:        warningx(_("%s unchanged"), sp->tpath);
                    458: 
1.1.1.2 ! misho     459:     rval = true;
        !           460: done:
        !           461:     debug_return_bool(rval);
1.1       misho     462: }
                    463: 
                    464: /*
                    465:  * Parse sudoers after editing and re-edit any ones that caused a parse error.
                    466:  */
1.1.1.2 ! misho     467: static void
        !           468: reparse_sudoers(char *editor, char *args, bool strict, bool quiet)
1.1       misho     469: {
                    470:     struct sudoersfile *sp, *last;
                    471:     FILE *fp;
                    472:     int ch;
1.1.1.2 ! misho     473:     debug_decl(reparse_sudoers, SUDO_DEBUG_UTIL)
1.1       misho     474: 
                    475:     /*
                    476:      * Parse the edited sudoers files and do sanity checking
                    477:      */
                    478:     do {
                    479:        sp = tq_first(&sudoerslist);
                    480:        last = tq_last(&sudoerslist);
                    481:        fp = fopen(sp->tpath, "r+");
                    482:        if (fp == NULL)
                    483:            errorx(1, _("unable to re-open temporary file (%s), %s unchanged."),
                    484:                sp->tpath, sp->path);
                    485: 
                    486:        /* Clean slate for each parse */
                    487:        init_defaults();
                    488:        init_parser(sp->path, quiet);
                    489: 
                    490:        /* Parse the sudoers temp file */
                    491:        yyrestart(fp);
                    492:        if (yyparse() && !parse_error) {
                    493:            warningx(_("unabled to parse temporary file (%s), unknown error"),
                    494:                sp->tpath);
1.1.1.2 ! misho     495:            parse_error = true;
1.1       misho     496:            errorfile = sp->path;
                    497:        }
                    498:        fclose(yyin);
                    499:        if (!parse_error) {
                    500:            if (!update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER) ||
                    501:                check_aliases(strict, quiet) != 0) {
1.1.1.2 ! misho     502:                parse_error = true;
1.1       misho     503:                errorfile = sp->path;
                    504:            }
                    505:        }
                    506: 
                    507:        /*
                    508:         * Got an error, prompt the user for what to do now
                    509:         */
                    510:        if (parse_error) {
                    511:            switch (whatnow()) {
1.1.1.2 ! misho     512:                case 'Q' :      parse_error = false;    /* ignore parse error */
1.1       misho     513:                                break;
1.1.1.2 ! misho     514:                case 'x' :      /* XXX - should return instead of exiting */
        !           515:                                cleanup(0);
        !           516:                                sudo_debug_exit_int(__func__, __FILE__,
        !           517:                                    __LINE__, sudo_debug_subsys, 0);
1.1       misho     518:                                exit(0);
                    519:                                break;
                    520:            }
                    521:        }
                    522:        if (parse_error) {
                    523:            /* Edit file with the parse error */
                    524:            tq_foreach_fwd(&sudoerslist, sp) {
                    525:                if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
                    526:                    edit_sudoers(sp, editor, args, errorlineno);
                    527:                    break;
                    528:                }
                    529:            }
                    530:            if (sp == NULL) {
                    531:                errorx(1, _("internal error, unable to find %s in list!"),
                    532:                    sudoers);
                    533:            }
                    534:        }
                    535: 
                    536:        /* If any new #include directives were added, edit them too. */
                    537:        for (sp = last->next; sp != NULL; sp = sp->next) {
                    538:            printf(_("press return to edit %s: "), sp->path);
                    539:            while ((ch = getchar()) != EOF && ch != '\n')
                    540:                    continue;
                    541:            edit_sudoers(sp, editor, args, errorlineno);
                    542:        }
                    543:     } while (parse_error);
                    544: 
1.1.1.2 ! misho     545:     debug_return;
1.1       misho     546: }
                    547: 
                    548: /*
                    549:  * Set the owner and mode on a sudoers temp file and
1.1.1.2 ! misho     550:  * move it into place.  Returns true on success, else false.
1.1       misho     551:  */
1.1.1.2 ! misho     552: static bool
        !           553: install_sudoers(struct sudoersfile *sp, bool oldperms)
1.1       misho     554: {
                    555:     struct stat sb;
1.1.1.2 ! misho     556:     bool rval = false;
        !           557:     debug_decl(install_sudoers, SUDO_DEBUG_UTIL)
        !           558: 
        !           559:     if (!sp->modified) {
        !           560:        /*
        !           561:         * No changes but fix owner/mode if needed.
        !           562:         */
        !           563:        (void) unlink(sp->tpath);
        !           564:        if (!oldperms && fstat(sp->fd, &sb) != -1) {
        !           565:            if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID)
        !           566:                ignore_result(chown(sp->path, SUDOERS_UID, SUDOERS_GID));
        !           567:            if ((sb.st_mode & 0777) != SUDOERS_MODE)
        !           568:                ignore_result(chmod(sp->path, SUDOERS_MODE));
        !           569:        }
        !           570:        rval = true;
        !           571:        goto done;
        !           572:     }
1.1       misho     573: 
                    574:     /*
                    575:      * Change mode and ownership of temp file so when
                    576:      * we move it to sp->path things are kosher.
                    577:      */
                    578:     if (oldperms) {
                    579:        /* Use perms of the existing file.  */
                    580:        if (fstat(sp->fd, &sb) == -1)
                    581:            error(1, _("unable to stat %s"), sp->path);
                    582:        if (chown(sp->tpath, sb.st_uid, sb.st_gid) != 0) {
                    583:            warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
                    584:                sp->tpath, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid);
                    585:        }
                    586:        if (chmod(sp->tpath, sb.st_mode & 0777) != 0) {
                    587:            warning(_("unable to change mode of %s to 0%o"), sp->tpath,
                    588:                (unsigned int)(sb.st_mode & 0777));
                    589:        }
                    590:     } else {
                    591:        if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
                    592:            warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
                    593:                sp->tpath, SUDOERS_UID, SUDOERS_GID);
1.1.1.2 ! misho     594:            goto done;
1.1       misho     595:        }
                    596:        if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
                    597:            warning(_("unable to change mode of %s to 0%o"), sp->tpath,
                    598:                SUDOERS_MODE);
1.1.1.2 ! misho     599:            goto done;
1.1       misho     600:        }
                    601:     }
                    602: 
                    603:     /*
                    604:      * Now that sp->tpath is sane (parses ok) it needs to be
                    605:      * rename(2)'d to sp->path.  If the rename(2) fails we try using
                    606:      * mv(1) in case sp->tpath and sp->path are on different file systems.
                    607:      */
                    608:     if (rename(sp->tpath, sp->path) == 0) {
                    609:        efree(sp->tpath);
                    610:        sp->tpath = NULL;
                    611:     } else {
                    612:        if (errno == EXDEV) {
                    613:            char *av[4];
                    614:            warningx(_("%s and %s not on the same file system, using mv to rename"),
                    615:              sp->tpath, sp->path);
                    616: 
                    617:            /* Build up argument vector for the command */
                    618:            if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
                    619:                av[0]++;
                    620:            else
                    621:                av[0] = _PATH_MV;
                    622:            av[1] = sp->tpath;
                    623:            av[2] = sp->path;
                    624:            av[3] = NULL;
                    625: 
                    626:            /* And run it... */
                    627:            if (run_command(_PATH_MV, av)) {
                    628:                warningx(_("command failed: '%s %s %s', %s unchanged"),
                    629:                    _PATH_MV, sp->tpath, sp->path, sp->path);
                    630:                (void) unlink(sp->tpath);
                    631:                efree(sp->tpath);
                    632:                sp->tpath = NULL;
1.1.1.2 ! misho     633:                goto done;
1.1       misho     634:            }
                    635:            efree(sp->tpath);
                    636:            sp->tpath = NULL;
                    637:        } else {
                    638:            warning(_("error renaming %s, %s unchanged"), sp->tpath, sp->path);
                    639:            (void) unlink(sp->tpath);
1.1.1.2 ! misho     640:            goto done;
1.1       misho     641:        }
                    642:     }
1.1.1.2 ! misho     643:     rval = true;
        !           644: done:
        !           645:     debug_return_bool(rval);
1.1       misho     646: }
                    647: 
                    648: /* STUB */
                    649: void
                    650: set_fqdn(void)
                    651: {
                    652:     return;
                    653: }
                    654: 
                    655: /* STUB */
                    656: void
                    657: init_envtables(void)
                    658: {
                    659:     return;
                    660: }
                    661: 
                    662: /* STUB */
1.1.1.2 ! misho     663: bool
1.1       misho     664: user_is_exempt(void)
                    665: {
1.1.1.2 ! misho     666:     return false;
1.1       misho     667: }
                    668: 
                    669: /* STUB */
                    670: void
                    671: sudo_setspent(void)
                    672: {
                    673:     return;
                    674: }
                    675: 
                    676: /* STUB */
                    677: void
                    678: sudo_endspent(void)
                    679: {
                    680:     return;
                    681: }
                    682: 
                    683: /* STUB */
                    684: int
                    685: group_plugin_query(const char *user, const char *group, const struct passwd *pw)
                    686: {
1.1.1.2 ! misho     687:     return false;
1.1       misho     688: }
                    689: 
                    690: /*
                    691:  * Assuming a parse error occurred, prompt the user for what they want
                    692:  * to do now.  Returns the first letter of their choice.
                    693:  */
1.1.1.2 ! misho     694: static int
1.1       misho     695: whatnow(void)
                    696: {
                    697:     int choice, c;
1.1.1.2 ! misho     698:     debug_decl(whatnow, SUDO_DEBUG_UTIL)
1.1       misho     699: 
                    700:     for (;;) {
                    701:        (void) fputs(_("What now? "), stdout);
                    702:        choice = getchar();
                    703:        for (c = choice; c != '\n' && c != EOF;)
                    704:            c = getchar();
                    705: 
                    706:        switch (choice) {
                    707:            case EOF:
                    708:                choice = 'x';
                    709:                /* FALLTHROUGH */
                    710:            case 'e':
                    711:            case 'x':
                    712:            case 'Q':
1.1.1.2 ! misho     713:                debug_return_int(choice);
1.1       misho     714:            default:
                    715:                (void) puts(_("Options are:\n"
                    716:                    "  (e)dit sudoers file again\n"
                    717:                    "  e(x)it without saving changes to sudoers file\n"
                    718:                    "  (Q)uit and save changes to sudoers file (DANGER!)\n"));
                    719:        }
                    720:     }
                    721: }
                    722: 
                    723: /*
                    724:  * Install signal handlers for visudo.
                    725:  */
                    726: static void
                    727: setup_signals(void)
                    728: {
1.1.1.2 ! misho     729:     sigaction_t sa;
        !           730:     debug_decl(setup_signals, SUDO_DEBUG_UTIL)
1.1       misho     731: 
1.1.1.2 ! misho     732:     /*
        !           733:      * Setup signal handlers to cleanup nicely.
        !           734:      */
        !           735:     zero_bytes(&sa, sizeof(sa));
        !           736:     sigemptyset(&sa.sa_mask);
        !           737:     sa.sa_flags = SA_RESTART;
        !           738:     sa.sa_handler = quit;
        !           739:     (void) sigaction(SIGTERM, &sa, NULL);
        !           740:     (void) sigaction(SIGHUP, &sa, NULL);
        !           741:     (void) sigaction(SIGINT, &sa, NULL);
        !           742:     (void) sigaction(SIGQUIT, &sa, NULL);
        !           743: 
        !           744:     debug_return;
1.1       misho     745: }
                    746: 
                    747: static int
                    748: run_command(char *path, char **argv)
                    749: {
                    750:     int status;
                    751:     pid_t pid, rv;
1.1.1.2 ! misho     752:     debug_decl(run_command, SUDO_DEBUG_UTIL)
1.1       misho     753: 
1.1.1.2 ! misho     754:     switch (pid = sudo_debug_fork()) {
1.1       misho     755:        case -1:
                    756:            error(1, _("unable to execute %s"), path);
                    757:            break;      /* NOTREACHED */
                    758:        case 0:
                    759:            sudo_endpwent();
                    760:            sudo_endgrent();
                    761:            closefrom(STDERR_FILENO + 1);
                    762:            execv(path, argv);
                    763:            warning(_("unable to run %s"), path);
                    764:            _exit(127);
                    765:            break;      /* NOTREACHED */
                    766:     }
                    767: 
                    768:     do {
                    769:        rv = waitpid(pid, &status, 0);
                    770:     } while (rv == -1 && errno == EINTR);
                    771: 
1.1.1.2 ! misho     772:     if (rv != -1)
        !           773:        rv = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
        !           774:     debug_return_int(rv);
1.1       misho     775: }
                    776: 
1.1.1.2 ! misho     777: static bool
        !           778: check_owner(const char *path, bool quiet)
1.1       misho     779: {
                    780:     struct stat sb;
1.1.1.2 ! misho     781:     bool ok = true;
        !           782:     debug_decl(check_owner, SUDO_DEBUG_UTIL)
        !           783: 
        !           784:     if (stat(path, &sb) == 0) {
        !           785:        if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
        !           786:            ok = false;
        !           787:            if (!quiet) {
        !           788:                fprintf(stderr,
        !           789:                    _("%s: wrong owner (uid, gid) should be (%u, %u)\n"),
        !           790:                    path, SUDOERS_UID, SUDOERS_GID);
        !           791:                }
        !           792:        }
        !           793:        if ((sb.st_mode & 07777) != SUDOERS_MODE) {
        !           794:            ok = false;
        !           795:            if (!quiet) {
        !           796:                fprintf(stderr, _("%s: bad permissions, should be mode 0%o\n"),
        !           797:                    path, SUDOERS_MODE);
        !           798:            }
        !           799:        }
        !           800:     }
        !           801:     debug_return_bool(ok);
        !           802: }
        !           803: 
        !           804: static bool
        !           805: check_syntax(char *sudoers_path, bool quiet, bool strict, bool oldperms)
        !           806: {
        !           807:     bool ok = false;
        !           808:     debug_decl(check_syntax, SUDO_DEBUG_UTIL)
1.1       misho     809: 
                    810:     if (strcmp(sudoers_path, "-") == 0) {
                    811:        yyin = stdin;
                    812:        sudoers_path = "stdin";
                    813:     } else if ((yyin = fopen(sudoers_path, "r")) == NULL) {
                    814:        if (!quiet)
                    815:            warning(_("unable to open %s"), sudoers_path);
1.1.1.2 ! misho     816:        goto done;
1.1       misho     817:     }
                    818:     init_parser(sudoers_path, quiet);
                    819:     if (yyparse() && !parse_error) {
                    820:        if (!quiet)
                    821:            warningx(_("failed to parse %s file, unknown error"), sudoers_path);
1.1.1.2 ! misho     822:        parse_error = true;
1.1       misho     823:        errorfile = sudoers_path;
                    824:     }
                    825:     if (!parse_error && check_aliases(strict, quiet) != 0) {
1.1.1.2 ! misho     826:        parse_error = true;
1.1       misho     827:        errorfile = sudoers_path;
                    828:     }
1.1.1.2 ! misho     829:     ok = !parse_error;
        !           830: 
        !           831:     if (parse_error) {
        !           832:        if (!quiet) {
1.1       misho     833:            if (errorlineno != -1)
                    834:                (void) printf(_("parse error in %s near line %d\n"),
                    835:                    errorfile, errorlineno);
                    836:            else
                    837:                (void) printf(_("parse error in %s\n"), errorfile);
                    838:        }
1.1.1.2 ! misho     839:     } else {
        !           840:        struct sudoersfile *sp;
        !           841: 
        !           842:        /* Parsed OK, check mode and owner. */
        !           843:        if (oldperms || check_owner(sudoers_path, quiet))
        !           844:            (void) printf(_("%s: parsed OK\n"), sudoers_path);
        !           845:        else
        !           846:            ok = false;
        !           847:        tq_foreach_fwd(&sudoerslist, sp) {
        !           848:            if (oldperms || check_owner(sp->path, quiet))
        !           849:                (void) printf(_("%s: parsed OK\n"), sp->path);
        !           850:            else
        !           851:                ok = false;
1.1       misho     852:        }
                    853:     }
                    854: 
1.1.1.2 ! misho     855: done:
        !           856:     debug_return_bool(ok);
1.1       misho     857: }
                    858: 
                    859: /*
                    860:  * Used to open (and lock) the initial sudoers file and to also open
                    861:  * any subsequent files #included via a callback from the parser.
                    862:  */
                    863: FILE *
1.1.1.2 ! misho     864: open_sudoers(const char *path, bool doedit, bool *keepopen)
1.1       misho     865: {
                    866:     struct sudoersfile *entry;
                    867:     FILE *fp;
1.1.1.2 ! misho     868:     int open_flags;
        !           869:     debug_decl(open_sudoers, SUDO_DEBUG_UTIL)
        !           870: 
        !           871:     if (checkonly)
        !           872:        open_flags = O_RDONLY;
        !           873:     else
        !           874:        open_flags = O_RDWR | O_CREAT;
1.1       misho     875: 
                    876:     /* Check for existing entry */
                    877:     tq_foreach_fwd(&sudoerslist, entry) {
                    878:        if (strcmp(path, entry->path) == 0)
                    879:            break;
                    880:     }
                    881:     if (entry == NULL) {
1.1.1.2 ! misho     882:        entry = ecalloc(1, sizeof(*entry));
1.1       misho     883:        entry->path = estrdup(path);
1.1.1.2 ! misho     884:        /* entry->modified = 0; */
1.1       misho     885:        entry->prev = entry;
1.1.1.2 ! misho     886:        /* entry->next = NULL; */
        !           887:        entry->fd = open(entry->path, open_flags, SUDOERS_MODE);
        !           888:        /* entry->tpath = NULL; */
1.1       misho     889:        entry->doedit = doedit;
                    890:        if (entry->fd == -1) {
                    891:            warning("%s", entry->path);
                    892:            efree(entry);
1.1.1.2 ! misho     893:            debug_return_ptr(NULL);
1.1       misho     894:        }
1.1.1.2 ! misho     895:        if (!checkonly && !lock_file(entry->fd, SUDO_TLOCK))
1.1       misho     896:            errorx(1, _("%s busy, try again later"), entry->path);
                    897:        if ((fp = fdopen(entry->fd, "r")) == NULL)
                    898:            error(1, "%s", entry->path);
                    899:        tq_append(&sudoerslist, entry);
                    900:     } else {
                    901:        /* Already exists, open .tmp version if there is one. */
                    902:        if (entry->tpath != NULL) {
                    903:            if ((fp = fopen(entry->tpath, "r")) == NULL)
                    904:                error(1, "%s", entry->tpath);
                    905:        } else {
                    906:            if ((fp = fdopen(entry->fd, "r")) == NULL)
                    907:                error(1, "%s", entry->path);
                    908:            rewind(fp);
                    909:        }
                    910:     }
                    911:     if (keepopen != NULL)
1.1.1.2 ! misho     912:        *keepopen = true;
        !           913:     debug_return_ptr(fp);
1.1       misho     914: }
                    915: 
                    916: static char *
                    917: get_editor(char **args)
                    918: {
                    919:     char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
1.1.1.2 ! misho     920:     debug_decl(get_editor, SUDO_DEBUG_UTIL)
1.1       misho     921: 
                    922:     /*
                    923:      * Check VISUAL and EDITOR environment variables to see which editor
                    924:      * the user wants to use (we may not end up using it though).
                    925:      * If the path is not fully-qualified, make it so and check that
                    926:      * the specified executable actually exists.
                    927:      */
                    928:     UserEditorArgs = NULL;
                    929:     if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
                    930:        UserEditor = getenv("EDITOR");
                    931:     if (UserEditor && *UserEditor == '\0')
                    932:        UserEditor = NULL;
                    933:     else if (UserEditor) {
                    934:        UserEditorArgs = get_args(UserEditor);
                    935:        if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
                    936:            UserEditor = Editor;
                    937:        } else {
                    938:            if (def_env_editor) {
                    939:                /* If we are honoring $EDITOR this is a fatal error. */
                    940:                errorx(1, _("specified editor (%s) doesn't exist"), UserEditor);
                    941:            } else {
                    942:                /* Otherwise, just ignore $EDITOR. */
                    943:                UserEditor = NULL;
                    944:            }
                    945:        }
                    946:     }
                    947: 
                    948:     /*
                    949:      * See if we can use the user's choice of editors either because
                    950:      * we allow any $EDITOR or because $EDITOR is in the allowable list.
                    951:      */
                    952:     Editor = EditorArgs = EditorPath = NULL;
                    953:     if (def_env_editor && UserEditor) {
                    954:        Editor = UserEditor;
                    955:        EditorArgs = UserEditorArgs;
                    956:     } else if (UserEditor) {
                    957:        struct stat editor_sb;
                    958:        struct stat user_editor_sb;
                    959:        char *base, *userbase;
                    960: 
                    961:        if (stat(UserEditor, &user_editor_sb) != 0) {
                    962:            /* Should never happen since we already checked above. */
                    963:            error(1, _("unable to stat editor (%s)"), UserEditor);
                    964:        }
                    965:        EditorPath = estrdup(def_editor);
                    966:        Editor = strtok(EditorPath, ":");
                    967:        do {
                    968:            EditorArgs = get_args(Editor);
                    969:            /*
                    970:             * Both Editor and UserEditor should be fully qualified but
                    971:             * check anyway...
                    972:             */
                    973:            if ((base = strrchr(Editor, '/')) == NULL)
                    974:                continue;
                    975:            if ((userbase = strrchr(UserEditor, '/')) == NULL) {
                    976:                Editor = NULL;
                    977:                break;
                    978:            }
                    979:            base++, userbase++;
                    980: 
                    981:            /*
                    982:             * We compare the basenames first and then use stat to match
                    983:             * for sure.
                    984:             */
                    985:            if (strcmp(base, userbase) == 0) {
                    986:                if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
                    987:                    && (editor_sb.st_mode & 0000111) &&
                    988:                    editor_sb.st_dev == user_editor_sb.st_dev &&
                    989:                    editor_sb.st_ino == user_editor_sb.st_ino)
                    990:                    break;
                    991:            }
                    992:        } while ((Editor = strtok(NULL, ":")));
                    993:     }
                    994: 
                    995:     /*
                    996:      * Can't use $EDITOR, try each element of def_editor until we
                    997:      * find one that exists, is regular, and is executable.
                    998:      */
                    999:     if (Editor == NULL || *Editor == '\0') {
                   1000:        efree(EditorPath);
                   1001:        EditorPath = estrdup(def_editor);
                   1002:        Editor = strtok(EditorPath, ":");
                   1003:        do {
                   1004:            EditorArgs = get_args(Editor);
                   1005:            if (sudo_goodpath(Editor, NULL))
                   1006:                break;
                   1007:        } while ((Editor = strtok(NULL, ":")));
                   1008: 
                   1009:        /* Bleah, none of the editors existed! */
                   1010:        if (Editor == NULL || *Editor == '\0')
                   1011:            errorx(1, _("no editor found (editor path = %s)"), def_editor);
                   1012:     }
                   1013:     *args = EditorArgs;
1.1.1.2 ! misho    1014:     debug_return_str(Editor);
1.1       misho    1015: }
                   1016: 
                   1017: /*
                   1018:  * Split out any command line arguments and return them.
                   1019:  */
                   1020: static char *
                   1021: get_args(char *cmnd)
                   1022: {
                   1023:     char *args;
1.1.1.2 ! misho    1024:     debug_decl(get_args, SUDO_DEBUG_UTIL)
1.1       misho    1025: 
                   1026:     args = cmnd;
                   1027:     while (*args && !isblank((unsigned char) *args))
                   1028:        args++;
                   1029:     if (*args) {
                   1030:        *args++ = '\0';
                   1031:        while (*args && isblank((unsigned char) *args))
                   1032:            args++;
                   1033:     }
1.1.1.2 ! misho    1034:     debug_return_str(*args ? args : NULL);
1.1       misho    1035: }
                   1036: 
                   1037: /*
                   1038:  * Look up the hostname and set user_host and user_shost.
                   1039:  */
                   1040: static void
                   1041: get_hostname(void)
                   1042: {
                   1043:     char *p, thost[MAXHOSTNAMELEN + 1];
1.1.1.2 ! misho    1044:     debug_decl(get_hostname, SUDO_DEBUG_UTIL)
1.1       misho    1045: 
1.1.1.2 ! misho    1046:     if (gethostname(thost, sizeof(thost)) != -1) {
        !          1047:        thost[sizeof(thost) - 1] = '\0';
        !          1048:        user_host = estrdup(thost);
        !          1049: 
        !          1050:        if ((p = strchr(user_host, '.'))) {
        !          1051:            *p = '\0';
        !          1052:            user_shost = estrdup(user_host);
        !          1053:            *p = '.';
        !          1054:        } else {
        !          1055:            user_shost = user_host;
        !          1056:        }
1.1       misho    1057:     } else {
1.1.1.2 ! misho    1058:        user_host = user_shost = "localhost";
1.1       misho    1059:     }
1.1.1.2 ! misho    1060:     debug_return;
1.1       misho    1061: }
                   1062: 
1.1.1.2 ! misho    1063: static bool
        !          1064: alias_remove_recursive(char *name, int type)
1.1       misho    1065: {
                   1066:     struct member *m;
                   1067:     struct alias *a;
1.1.1.2 ! misho    1068:     bool rval = true;
        !          1069:     debug_decl(alias_remove_recursive, SUDO_DEBUG_ALIAS)
1.1       misho    1070: 
                   1071:     if ((a = alias_find(name, type)) != NULL) {
                   1072:        tq_foreach_fwd(&a->members, m) {
                   1073:            if (m->type == ALIAS) {
1.1.1.2 ! misho    1074:                if (!alias_remove_recursive(m->name, type))
        !          1075:                    rval = false;
1.1       misho    1076:            }
                   1077:        }
                   1078:     }
                   1079:     alias_seqno++;
                   1080:     a = alias_remove(name, type);
                   1081:     if (a)
                   1082:        rbinsert(alias_freelist, a);
1.1.1.2 ! misho    1083:     debug_return_bool(rval);
1.1       misho    1084: }
                   1085: 
                   1086: static int
                   1087: check_alias(char *name, int type, int strict, int quiet)
                   1088: {
                   1089:     struct member *m;
                   1090:     struct alias *a;
1.1.1.2 ! misho    1091:     int errors = 0;
        !          1092:     debug_decl(check_alias, SUDO_DEBUG_ALIAS)
1.1       misho    1093: 
                   1094:     if ((a = alias_find(name, type)) != NULL) {
                   1095:        /* check alias contents */
                   1096:        tq_foreach_fwd(&a->members, m) {
                   1097:            if (m->type == ALIAS)
1.1.1.2 ! misho    1098:                errors += check_alias(m->name, type, strict, quiet);
1.1       misho    1099:        }
                   1100:     } else {
                   1101:        if (!quiet) {
                   1102:            char *fmt;
                   1103:            if (errno == ELOOP) {
                   1104:                fmt = strict ?
                   1105:                    _("Error: cycle in %s_Alias `%s'") :
                   1106:                    _("Warning: cycle in %s_Alias `%s'");
                   1107:            } else {
                   1108:                fmt = strict ?
                   1109:                    _("Error: %s_Alias `%s' referenced but not defined") :
                   1110:                    _("Warning: %s_Alias `%s' referenced but not defined");
                   1111:            }
                   1112:            warningx(fmt,
                   1113:                type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
                   1114:                type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
                   1115:                "Unknown", name);
                   1116:        }
1.1.1.2 ! misho    1117:        errors++;
1.1       misho    1118:     }
                   1119: 
1.1.1.2 ! misho    1120:     debug_return_int(errors);
1.1       misho    1121: }
                   1122: 
                   1123: /*
                   1124:  * Iterate through the sudoers datastructures looking for undefined
                   1125:  * aliases or unused aliases.
                   1126:  */
                   1127: static int
1.1.1.2 ! misho    1128: check_aliases(bool strict, bool quiet)
1.1       misho    1129: {
                   1130:     struct cmndspec *cs;
                   1131:     struct member *m, *binding;
                   1132:     struct privilege *priv;
                   1133:     struct userspec *us;
                   1134:     struct defaults *d;
1.1.1.2 ! misho    1135:     int atype, errors = 0;
        !          1136:     debug_decl(check_aliases, SUDO_DEBUG_ALIAS)
1.1       misho    1137: 
                   1138:     alias_freelist = rbcreate(alias_compare);
                   1139: 
                   1140:     /* Forward check. */
                   1141:     tq_foreach_fwd(&userspecs, us) {
                   1142:        tq_foreach_fwd(&us->users, m) {
                   1143:            if (m->type == ALIAS) {
                   1144:                alias_seqno++;
1.1.1.2 ! misho    1145:                errors += check_alias(m->name, USERALIAS, strict, quiet);
1.1       misho    1146:            }
                   1147:        }
                   1148:        tq_foreach_fwd(&us->privileges, priv) {
                   1149:            tq_foreach_fwd(&priv->hostlist, m) {
                   1150:                if (m->type == ALIAS) {
                   1151:                    alias_seqno++;
1.1.1.2 ! misho    1152:                    errors += check_alias(m->name, HOSTALIAS, strict, quiet);
1.1       misho    1153:                }
                   1154:            }
                   1155:            tq_foreach_fwd(&priv->cmndlist, cs) {
                   1156:                tq_foreach_fwd(&cs->runasuserlist, m) {
                   1157:                    if (m->type == ALIAS) {
                   1158:                        alias_seqno++;
1.1.1.2 ! misho    1159:                        errors += check_alias(m->name, RUNASALIAS, strict, quiet);
1.1       misho    1160:                    }
                   1161:                }
                   1162:                if ((m = cs->cmnd)->type == ALIAS) {
                   1163:                    alias_seqno++;
1.1.1.2 ! misho    1164:                    errors += check_alias(m->name, CMNDALIAS, strict, quiet);
1.1       misho    1165:                }
                   1166:            }
                   1167:        }
                   1168:     }
                   1169: 
                   1170:     /* Reverse check (destructive) */
                   1171:     tq_foreach_fwd(&userspecs, us) {
                   1172:        tq_foreach_fwd(&us->users, m) {
                   1173:            if (m->type == ALIAS) {
                   1174:                alias_seqno++;
1.1.1.2 ! misho    1175:                if (!alias_remove_recursive(m->name, USERALIAS))
        !          1176:                    errors++;
1.1       misho    1177:            }
                   1178:        }
                   1179:        tq_foreach_fwd(&us->privileges, priv) {
                   1180:            tq_foreach_fwd(&priv->hostlist, m) {
                   1181:                if (m->type == ALIAS) {
                   1182:                    alias_seqno++;
1.1.1.2 ! misho    1183:                    if (!alias_remove_recursive(m->name, HOSTALIAS))
        !          1184:                        errors++;
1.1       misho    1185:                }
                   1186:            }
                   1187:            tq_foreach_fwd(&priv->cmndlist, cs) {
                   1188:                tq_foreach_fwd(&cs->runasuserlist, m) {
                   1189:                    if (m->type == ALIAS) {
                   1190:                        alias_seqno++;
1.1.1.2 ! misho    1191:                        if (!alias_remove_recursive(m->name, RUNASALIAS))
        !          1192:                            errors++;
1.1       misho    1193:                    }
                   1194:                }
                   1195:                if ((m = cs->cmnd)->type == ALIAS) {
                   1196:                    alias_seqno++;
1.1.1.2 ! misho    1197:                    if (!alias_remove_recursive(m->name, CMNDALIAS))
        !          1198:                        errors++;
1.1       misho    1199:                }
                   1200:            }
                   1201:        }
                   1202:     }
                   1203:     tq_foreach_fwd(&defaults, d) {
                   1204:        switch (d->type) {
                   1205:            case DEFAULTS_HOST:
                   1206:                atype = HOSTALIAS;
                   1207:                break;
                   1208:            case DEFAULTS_USER:
                   1209:                atype = USERALIAS;
                   1210:                break;
                   1211:            case DEFAULTS_RUNAS:
                   1212:                atype = RUNASALIAS;
                   1213:                break;
                   1214:            case DEFAULTS_CMND:
                   1215:                atype = CMNDALIAS;
                   1216:                break;
                   1217:            default:
                   1218:                continue; /* not an alias */
                   1219:        }
                   1220:        tq_foreach_fwd(&d->binding, binding) {
                   1221:            for (m = binding; m != NULL; m = m->next) {
                   1222:                if (m->type == ALIAS) {
                   1223:                    alias_seqno++;
1.1.1.2 ! misho    1224:                    if (!alias_remove_recursive(m->name, atype))
        !          1225:                        errors++;
1.1       misho    1226:                }
                   1227:            }
                   1228:        }
                   1229:     }
                   1230:     rbdestroy(alias_freelist, alias_free);
                   1231: 
                   1232:     /* If all aliases were referenced we will have an empty tree. */
                   1233:     if (!no_aliases() && !quiet)
                   1234:        alias_apply(print_unused, strict ? "Error" : "Warning");
                   1235: 
1.1.1.2 ! misho    1236:     debug_return_int(strict ? errors : 0);
1.1       misho    1237: }
                   1238: 
                   1239: static int
                   1240: print_unused(void *v1, void *v2)
                   1241: {
                   1242:     struct alias *a = (struct alias *)v1;
                   1243:     char *prefix = (char *)v2;
                   1244: 
1.1.1.2 ! misho    1245:     warningx2(_("%s: unused %s_Alias %s"), prefix,
1.1       misho    1246:        a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
                   1247:        a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
                   1248:        "Unknown", a->name);
                   1249:     return 0;
                   1250: }
                   1251: 
                   1252: /*
                   1253:  * Unlink any sudoers temp files that remain.
                   1254:  */
                   1255: void
                   1256: cleanup(int gotsignal)
                   1257: {
                   1258:     struct sudoersfile *sp;
                   1259: 
                   1260:     tq_foreach_fwd(&sudoerslist, sp) {
                   1261:        if (sp->tpath != NULL)
                   1262:            (void) unlink(sp->tpath);
                   1263:     }
                   1264:     if (!gotsignal) {
                   1265:        sudo_endpwent();
                   1266:        sudo_endgrent();
                   1267:     }
                   1268: }
                   1269: 
                   1270: /*
                   1271:  * Unlink sudoers temp files (if any) and exit.
                   1272:  */
                   1273: static void
                   1274: quit(int signo)
                   1275: {
                   1276:     const char *signame, *myname;
                   1277: 
                   1278:     cleanup(signo);
                   1279: #define        emsg     " exiting due to signal: "
                   1280:     myname = getprogname();
                   1281:     signame = strsignal(signo);
1.1.1.2 ! misho    1282:     ignore_result(write(STDERR_FILENO, myname, strlen(myname)));
        !          1283:     ignore_result(write(STDERR_FILENO, emsg, sizeof(emsg) - 1));
        !          1284:     ignore_result(write(STDERR_FILENO, signame, strlen(signame)));
        !          1285:     ignore_result(write(STDERR_FILENO, "\n", 1));
1.1       misho    1286:     _exit(signo);
                   1287: }
                   1288: 
                   1289: static void
                   1290: usage(int fatal)
                   1291: {
                   1292:     (void) fprintf(fatal ? stderr : stdout,
                   1293:        "usage: %s [-chqsV] [-f sudoers]\n", getprogname());
                   1294:     if (fatal)
                   1295:        exit(1);
                   1296: }
                   1297: 
                   1298: static void
                   1299: help(void)
                   1300: {
                   1301:     (void) printf(_("%s - safely edit the sudoers file\n\n"), getprogname());
                   1302:     usage(0);
                   1303:     (void) puts(_("\nOptions:\n"
                   1304:        "  -c          check-only mode\n"
                   1305:        "  -f sudoers  specify sudoers file location\n"
                   1306:        "  -h          display help message and exit\n"
                   1307:        "  -q          less verbose (quiet) syntax error messages\n"
                   1308:        "  -s          strict syntax checking\n"
                   1309:        "  -V          display version information and exit"));
                   1310:     exit(0);
                   1311: }
                   1312: 
                   1313: static int
                   1314: visudo_printf(int msg_type, const char *fmt, ...)
                   1315: {
                   1316:     va_list ap;
                   1317:     FILE *fp;
                   1318:             
                   1319:     switch (msg_type) {
                   1320:     case SUDO_CONV_INFO_MSG:
                   1321:        fp = stdout;
                   1322:        break;
                   1323:     case SUDO_CONV_ERROR_MSG:
                   1324:        fp = stderr;
                   1325:        break;
                   1326:     default:
                   1327:        errno = EINVAL;
                   1328:        return -1;
                   1329:     }
                   1330:    
                   1331:     va_start(ap, fmt);
                   1332:     vfprintf(fp, fmt, ap);
                   1333:     va_end(ap);
                   1334:    
                   1335:     return 0;
                   1336: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>