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

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':
1.1.1.3 ! misho     191:                checkonly = true;       /* check mode */
1.1       misho     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':
1.1.1.3 ! misho     201:                strict = true;          /* strict mode */
1.1       misho     202:                break;
                    203:            case 'q':
1.1.1.3 ! misho     204:                quiet = false;          /* quiet mode */
1.1       misho     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:     }
1.1.1.3 ! misho     238:     init_parser(sudoers_path, false);
1.1       misho     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: 
1.1.1.3 ! misho     475:     if (tq_empty(&sudoerslist))
        !           476:        debug_return;
        !           477: 
1.1       misho     478:     /*
                    479:      * Parse the edited sudoers files and do sanity checking
                    480:      */
                    481:     do {
                    482:        sp = tq_first(&sudoerslist);
                    483:        last = tq_last(&sudoerslist);
                    484:        fp = fopen(sp->tpath, "r+");
                    485:        if (fp == NULL)
                    486:            errorx(1, _("unable to re-open temporary file (%s), %s unchanged."),
                    487:                sp->tpath, sp->path);
                    488: 
                    489:        /* Clean slate for each parse */
                    490:        init_defaults();
                    491:        init_parser(sp->path, quiet);
                    492: 
                    493:        /* Parse the sudoers temp file */
                    494:        yyrestart(fp);
                    495:        if (yyparse() && !parse_error) {
                    496:            warningx(_("unabled to parse temporary file (%s), unknown error"),
                    497:                sp->tpath);
1.1.1.2   misho     498:            parse_error = true;
1.1       misho     499:            errorfile = sp->path;
                    500:        }
                    501:        fclose(yyin);
                    502:        if (!parse_error) {
1.1.1.3 ! misho     503:            if (!check_defaults(SETDEF_ALL, quiet) ||
1.1       misho     504:                check_aliases(strict, quiet) != 0) {
1.1.1.2   misho     505:                parse_error = true;
1.1.1.3 ! misho     506:                errorfile = NULL;
1.1       misho     507:            }
                    508:        }
                    509: 
                    510:        /*
                    511:         * Got an error, prompt the user for what to do now
                    512:         */
                    513:        if (parse_error) {
                    514:            switch (whatnow()) {
1.1.1.2   misho     515:                case 'Q' :      parse_error = false;    /* ignore parse error */
1.1       misho     516:                                break;
1.1.1.2   misho     517:                case 'x' :      /* XXX - should return instead of exiting */
                    518:                                cleanup(0);
                    519:                                sudo_debug_exit_int(__func__, __FILE__,
                    520:                                    __LINE__, sudo_debug_subsys, 0);
1.1       misho     521:                                exit(0);
                    522:                                break;
                    523:            }
                    524:        }
                    525:        if (parse_error) {
                    526:            /* Edit file with the parse error */
                    527:            tq_foreach_fwd(&sudoerslist, sp) {
                    528:                if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
                    529:                    edit_sudoers(sp, editor, args, errorlineno);
1.1.1.3 ! misho     530:                    if (errorfile != NULL)
        !           531:                        break;
1.1       misho     532:                }
                    533:            }
1.1.1.3 ! misho     534:            if (errorfile != NULL && sp == NULL) {
1.1       misho     535:                errorx(1, _("internal error, unable to find %s in list!"),
                    536:                    sudoers);
                    537:            }
                    538:        }
                    539: 
                    540:        /* If any new #include directives were added, edit them too. */
                    541:        for (sp = last->next; sp != NULL; sp = sp->next) {
                    542:            printf(_("press return to edit %s: "), sp->path);
                    543:            while ((ch = getchar()) != EOF && ch != '\n')
                    544:                    continue;
                    545:            edit_sudoers(sp, editor, args, errorlineno);
                    546:        }
                    547:     } while (parse_error);
                    548: 
1.1.1.2   misho     549:     debug_return;
1.1       misho     550: }
                    551: 
                    552: /*
                    553:  * Set the owner and mode on a sudoers temp file and
1.1.1.2   misho     554:  * move it into place.  Returns true on success, else false.
1.1       misho     555:  */
1.1.1.2   misho     556: static bool
                    557: install_sudoers(struct sudoersfile *sp, bool oldperms)
1.1       misho     558: {
                    559:     struct stat sb;
1.1.1.2   misho     560:     bool rval = false;
                    561:     debug_decl(install_sudoers, SUDO_DEBUG_UTIL)
                    562: 
                    563:     if (!sp->modified) {
                    564:        /*
                    565:         * No changes but fix owner/mode if needed.
                    566:         */
                    567:        (void) unlink(sp->tpath);
                    568:        if (!oldperms && fstat(sp->fd, &sb) != -1) {
                    569:            if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID)
                    570:                ignore_result(chown(sp->path, SUDOERS_UID, SUDOERS_GID));
                    571:            if ((sb.st_mode & 0777) != SUDOERS_MODE)
                    572:                ignore_result(chmod(sp->path, SUDOERS_MODE));
                    573:        }
                    574:        rval = true;
                    575:        goto done;
                    576:     }
1.1       misho     577: 
                    578:     /*
                    579:      * Change mode and ownership of temp file so when
                    580:      * we move it to sp->path things are kosher.
                    581:      */
                    582:     if (oldperms) {
                    583:        /* Use perms of the existing file.  */
                    584:        if (fstat(sp->fd, &sb) == -1)
                    585:            error(1, _("unable to stat %s"), sp->path);
                    586:        if (chown(sp->tpath, sb.st_uid, sb.st_gid) != 0) {
                    587:            warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
                    588:                sp->tpath, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid);
                    589:        }
                    590:        if (chmod(sp->tpath, sb.st_mode & 0777) != 0) {
                    591:            warning(_("unable to change mode of %s to 0%o"), sp->tpath,
                    592:                (unsigned int)(sb.st_mode & 0777));
                    593:        }
                    594:     } else {
                    595:        if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
                    596:            warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
                    597:                sp->tpath, SUDOERS_UID, SUDOERS_GID);
1.1.1.2   misho     598:            goto done;
1.1       misho     599:        }
                    600:        if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
                    601:            warning(_("unable to change mode of %s to 0%o"), sp->tpath,
                    602:                SUDOERS_MODE);
1.1.1.2   misho     603:            goto done;
1.1       misho     604:        }
                    605:     }
                    606: 
                    607:     /*
                    608:      * Now that sp->tpath is sane (parses ok) it needs to be
                    609:      * rename(2)'d to sp->path.  If the rename(2) fails we try using
                    610:      * mv(1) in case sp->tpath and sp->path are on different file systems.
                    611:      */
                    612:     if (rename(sp->tpath, sp->path) == 0) {
                    613:        efree(sp->tpath);
                    614:        sp->tpath = NULL;
                    615:     } else {
                    616:        if (errno == EXDEV) {
                    617:            char *av[4];
                    618:            warningx(_("%s and %s not on the same file system, using mv to rename"),
                    619:              sp->tpath, sp->path);
                    620: 
                    621:            /* Build up argument vector for the command */
                    622:            if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
                    623:                av[0]++;
                    624:            else
                    625:                av[0] = _PATH_MV;
                    626:            av[1] = sp->tpath;
                    627:            av[2] = sp->path;
                    628:            av[3] = NULL;
                    629: 
                    630:            /* And run it... */
                    631:            if (run_command(_PATH_MV, av)) {
                    632:                warningx(_("command failed: '%s %s %s', %s unchanged"),
                    633:                    _PATH_MV, sp->tpath, sp->path, sp->path);
                    634:                (void) unlink(sp->tpath);
                    635:                efree(sp->tpath);
                    636:                sp->tpath = NULL;
1.1.1.2   misho     637:                goto done;
1.1       misho     638:            }
                    639:            efree(sp->tpath);
                    640:            sp->tpath = NULL;
                    641:        } else {
                    642:            warning(_("error renaming %s, %s unchanged"), sp->tpath, sp->path);
                    643:            (void) unlink(sp->tpath);
1.1.1.2   misho     644:            goto done;
1.1       misho     645:        }
                    646:     }
1.1.1.2   misho     647:     rval = true;
                    648: done:
                    649:     debug_return_bool(rval);
1.1       misho     650: }
                    651: 
                    652: /* STUB */
                    653: void
                    654: set_fqdn(void)
                    655: {
                    656:     return;
                    657: }
                    658: 
                    659: /* STUB */
                    660: void
                    661: init_envtables(void)
                    662: {
                    663:     return;
                    664: }
                    665: 
                    666: /* STUB */
1.1.1.2   misho     667: bool
1.1       misho     668: user_is_exempt(void)
                    669: {
1.1.1.2   misho     670:     return false;
1.1       misho     671: }
                    672: 
                    673: /* STUB */
                    674: void
                    675: sudo_setspent(void)
                    676: {
                    677:     return;
                    678: }
                    679: 
                    680: /* STUB */
                    681: void
                    682: sudo_endspent(void)
                    683: {
                    684:     return;
                    685: }
                    686: 
                    687: /* STUB */
                    688: int
                    689: group_plugin_query(const char *user, const char *group, const struct passwd *pw)
                    690: {
1.1.1.2   misho     691:     return false;
1.1       misho     692: }
                    693: 
                    694: /*
                    695:  * Assuming a parse error occurred, prompt the user for what they want
                    696:  * to do now.  Returns the first letter of their choice.
                    697:  */
1.1.1.2   misho     698: static int
1.1       misho     699: whatnow(void)
                    700: {
                    701:     int choice, c;
1.1.1.2   misho     702:     debug_decl(whatnow, SUDO_DEBUG_UTIL)
1.1       misho     703: 
                    704:     for (;;) {
                    705:        (void) fputs(_("What now? "), stdout);
                    706:        choice = getchar();
                    707:        for (c = choice; c != '\n' && c != EOF;)
                    708:            c = getchar();
                    709: 
                    710:        switch (choice) {
                    711:            case EOF:
                    712:                choice = 'x';
                    713:                /* FALLTHROUGH */
                    714:            case 'e':
                    715:            case 'x':
                    716:            case 'Q':
1.1.1.2   misho     717:                debug_return_int(choice);
1.1       misho     718:            default:
                    719:                (void) puts(_("Options are:\n"
                    720:                    "  (e)dit sudoers file again\n"
                    721:                    "  e(x)it without saving changes to sudoers file\n"
                    722:                    "  (Q)uit and save changes to sudoers file (DANGER!)\n"));
                    723:        }
                    724:     }
                    725: }
                    726: 
                    727: /*
                    728:  * Install signal handlers for visudo.
                    729:  */
                    730: static void
                    731: setup_signals(void)
                    732: {
1.1.1.2   misho     733:     sigaction_t sa;
                    734:     debug_decl(setup_signals, SUDO_DEBUG_UTIL)
1.1       misho     735: 
1.1.1.2   misho     736:     /*
                    737:      * Setup signal handlers to cleanup nicely.
                    738:      */
                    739:     zero_bytes(&sa, sizeof(sa));
                    740:     sigemptyset(&sa.sa_mask);
                    741:     sa.sa_flags = SA_RESTART;
                    742:     sa.sa_handler = quit;
                    743:     (void) sigaction(SIGTERM, &sa, NULL);
                    744:     (void) sigaction(SIGHUP, &sa, NULL);
                    745:     (void) sigaction(SIGINT, &sa, NULL);
                    746:     (void) sigaction(SIGQUIT, &sa, NULL);
                    747: 
                    748:     debug_return;
1.1       misho     749: }
                    750: 
                    751: static int
                    752: run_command(char *path, char **argv)
                    753: {
                    754:     int status;
                    755:     pid_t pid, rv;
1.1.1.2   misho     756:     debug_decl(run_command, SUDO_DEBUG_UTIL)
1.1       misho     757: 
1.1.1.2   misho     758:     switch (pid = sudo_debug_fork()) {
1.1       misho     759:        case -1:
                    760:            error(1, _("unable to execute %s"), path);
                    761:            break;      /* NOTREACHED */
                    762:        case 0:
                    763:            sudo_endpwent();
                    764:            sudo_endgrent();
                    765:            closefrom(STDERR_FILENO + 1);
                    766:            execv(path, argv);
                    767:            warning(_("unable to run %s"), path);
                    768:            _exit(127);
                    769:            break;      /* NOTREACHED */
                    770:     }
                    771: 
                    772:     do {
                    773:        rv = waitpid(pid, &status, 0);
                    774:     } while (rv == -1 && errno == EINTR);
                    775: 
1.1.1.2   misho     776:     if (rv != -1)
                    777:        rv = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
                    778:     debug_return_int(rv);
1.1       misho     779: }
                    780: 
1.1.1.2   misho     781: static bool
                    782: check_owner(const char *path, bool quiet)
1.1       misho     783: {
                    784:     struct stat sb;
1.1.1.2   misho     785:     bool ok = true;
                    786:     debug_decl(check_owner, SUDO_DEBUG_UTIL)
                    787: 
                    788:     if (stat(path, &sb) == 0) {
                    789:        if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
                    790:            ok = false;
                    791:            if (!quiet) {
                    792:                fprintf(stderr,
                    793:                    _("%s: wrong owner (uid, gid) should be (%u, %u)\n"),
                    794:                    path, SUDOERS_UID, SUDOERS_GID);
                    795:                }
                    796:        }
                    797:        if ((sb.st_mode & 07777) != SUDOERS_MODE) {
                    798:            ok = false;
                    799:            if (!quiet) {
                    800:                fprintf(stderr, _("%s: bad permissions, should be mode 0%o\n"),
                    801:                    path, SUDOERS_MODE);
                    802:            }
                    803:        }
                    804:     }
                    805:     debug_return_bool(ok);
                    806: }
                    807: 
                    808: static bool
                    809: check_syntax(char *sudoers_path, bool quiet, bool strict, bool oldperms)
                    810: {
                    811:     bool ok = false;
                    812:     debug_decl(check_syntax, SUDO_DEBUG_UTIL)
1.1       misho     813: 
                    814:     if (strcmp(sudoers_path, "-") == 0) {
                    815:        yyin = stdin;
                    816:        sudoers_path = "stdin";
                    817:     } else if ((yyin = fopen(sudoers_path, "r")) == NULL) {
                    818:        if (!quiet)
                    819:            warning(_("unable to open %s"), sudoers_path);
1.1.1.2   misho     820:        goto done;
1.1       misho     821:     }
                    822:     init_parser(sudoers_path, quiet);
                    823:     if (yyparse() && !parse_error) {
                    824:        if (!quiet)
                    825:            warningx(_("failed to parse %s file, unknown error"), sudoers_path);
1.1.1.2   misho     826:        parse_error = true;
1.1       misho     827:        errorfile = sudoers_path;
                    828:     }
1.1.1.3 ! misho     829:     if (!parse_error) {
        !           830:        if (!check_defaults(SETDEF_ALL, quiet) ||
        !           831:            check_aliases(strict, quiet) != 0) {
        !           832:            parse_error = true;
        !           833:            errorfile = NULL;
        !           834:        }
1.1       misho     835:     }
1.1.1.2   misho     836:     ok = !parse_error;
                    837: 
                    838:     if (parse_error) {
                    839:        if (!quiet) {
1.1       misho     840:            if (errorlineno != -1)
                    841:                (void) printf(_("parse error in %s near line %d\n"),
                    842:                    errorfile, errorlineno);
                    843:            else
                    844:                (void) printf(_("parse error in %s\n"), errorfile);
                    845:        }
1.1.1.2   misho     846:     } else {
                    847:        struct sudoersfile *sp;
                    848: 
                    849:        /* Parsed OK, check mode and owner. */
                    850:        if (oldperms || check_owner(sudoers_path, quiet))
                    851:            (void) printf(_("%s: parsed OK\n"), sudoers_path);
                    852:        else
                    853:            ok = false;
                    854:        tq_foreach_fwd(&sudoerslist, sp) {
                    855:            if (oldperms || check_owner(sp->path, quiet))
                    856:                (void) printf(_("%s: parsed OK\n"), sp->path);
                    857:            else
                    858:                ok = false;
1.1       misho     859:        }
                    860:     }
                    861: 
1.1.1.2   misho     862: done:
                    863:     debug_return_bool(ok);
1.1       misho     864: }
                    865: 
                    866: /*
                    867:  * Used to open (and lock) the initial sudoers file and to also open
                    868:  * any subsequent files #included via a callback from the parser.
                    869:  */
                    870: FILE *
1.1.1.2   misho     871: open_sudoers(const char *path, bool doedit, bool *keepopen)
1.1       misho     872: {
                    873:     struct sudoersfile *entry;
                    874:     FILE *fp;
1.1.1.2   misho     875:     int open_flags;
                    876:     debug_decl(open_sudoers, SUDO_DEBUG_UTIL)
                    877: 
                    878:     if (checkonly)
                    879:        open_flags = O_RDONLY;
                    880:     else
                    881:        open_flags = O_RDWR | O_CREAT;
1.1       misho     882: 
                    883:     /* Check for existing entry */
                    884:     tq_foreach_fwd(&sudoerslist, entry) {
                    885:        if (strcmp(path, entry->path) == 0)
                    886:            break;
                    887:     }
                    888:     if (entry == NULL) {
1.1.1.2   misho     889:        entry = ecalloc(1, sizeof(*entry));
1.1       misho     890:        entry->path = estrdup(path);
1.1.1.2   misho     891:        /* entry->modified = 0; */
1.1       misho     892:        entry->prev = entry;
1.1.1.2   misho     893:        /* entry->next = NULL; */
                    894:        entry->fd = open(entry->path, open_flags, SUDOERS_MODE);
                    895:        /* entry->tpath = NULL; */
1.1       misho     896:        entry->doedit = doedit;
                    897:        if (entry->fd == -1) {
                    898:            warning("%s", entry->path);
                    899:            efree(entry);
1.1.1.2   misho     900:            debug_return_ptr(NULL);
1.1       misho     901:        }
1.1.1.2   misho     902:        if (!checkonly && !lock_file(entry->fd, SUDO_TLOCK))
1.1       misho     903:            errorx(1, _("%s busy, try again later"), entry->path);
                    904:        if ((fp = fdopen(entry->fd, "r")) == NULL)
                    905:            error(1, "%s", entry->path);
                    906:        tq_append(&sudoerslist, entry);
                    907:     } else {
                    908:        /* Already exists, open .tmp version if there is one. */
                    909:        if (entry->tpath != NULL) {
                    910:            if ((fp = fopen(entry->tpath, "r")) == NULL)
                    911:                error(1, "%s", entry->tpath);
                    912:        } else {
                    913:            if ((fp = fdopen(entry->fd, "r")) == NULL)
                    914:                error(1, "%s", entry->path);
                    915:            rewind(fp);
                    916:        }
                    917:     }
                    918:     if (keepopen != NULL)
1.1.1.2   misho     919:        *keepopen = true;
                    920:     debug_return_ptr(fp);
1.1       misho     921: }
                    922: 
                    923: static char *
                    924: get_editor(char **args)
                    925: {
                    926:     char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
1.1.1.2   misho     927:     debug_decl(get_editor, SUDO_DEBUG_UTIL)
1.1       misho     928: 
                    929:     /*
                    930:      * Check VISUAL and EDITOR environment variables to see which editor
                    931:      * the user wants to use (we may not end up using it though).
                    932:      * If the path is not fully-qualified, make it so and check that
                    933:      * the specified executable actually exists.
                    934:      */
                    935:     UserEditorArgs = NULL;
                    936:     if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
                    937:        UserEditor = getenv("EDITOR");
                    938:     if (UserEditor && *UserEditor == '\0')
                    939:        UserEditor = NULL;
                    940:     else if (UserEditor) {
                    941:        UserEditorArgs = get_args(UserEditor);
                    942:        if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
                    943:            UserEditor = Editor;
                    944:        } else {
                    945:            if (def_env_editor) {
                    946:                /* If we are honoring $EDITOR this is a fatal error. */
                    947:                errorx(1, _("specified editor (%s) doesn't exist"), UserEditor);
                    948:            } else {
                    949:                /* Otherwise, just ignore $EDITOR. */
                    950:                UserEditor = NULL;
                    951:            }
                    952:        }
                    953:     }
                    954: 
                    955:     /*
                    956:      * See if we can use the user's choice of editors either because
                    957:      * we allow any $EDITOR or because $EDITOR is in the allowable list.
                    958:      */
                    959:     Editor = EditorArgs = EditorPath = NULL;
                    960:     if (def_env_editor && UserEditor) {
                    961:        Editor = UserEditor;
                    962:        EditorArgs = UserEditorArgs;
                    963:     } else if (UserEditor) {
                    964:        struct stat editor_sb;
                    965:        struct stat user_editor_sb;
                    966:        char *base, *userbase;
                    967: 
                    968:        if (stat(UserEditor, &user_editor_sb) != 0) {
                    969:            /* Should never happen since we already checked above. */
                    970:            error(1, _("unable to stat editor (%s)"), UserEditor);
                    971:        }
                    972:        EditorPath = estrdup(def_editor);
                    973:        Editor = strtok(EditorPath, ":");
                    974:        do {
                    975:            EditorArgs = get_args(Editor);
                    976:            /*
                    977:             * Both Editor and UserEditor should be fully qualified but
                    978:             * check anyway...
                    979:             */
                    980:            if ((base = strrchr(Editor, '/')) == NULL)
                    981:                continue;
                    982:            if ((userbase = strrchr(UserEditor, '/')) == NULL) {
                    983:                Editor = NULL;
                    984:                break;
                    985:            }
                    986:            base++, userbase++;
                    987: 
                    988:            /*
                    989:             * We compare the basenames first and then use stat to match
                    990:             * for sure.
                    991:             */
                    992:            if (strcmp(base, userbase) == 0) {
                    993:                if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
                    994:                    && (editor_sb.st_mode & 0000111) &&
                    995:                    editor_sb.st_dev == user_editor_sb.st_dev &&
                    996:                    editor_sb.st_ino == user_editor_sb.st_ino)
                    997:                    break;
                    998:            }
                    999:        } while ((Editor = strtok(NULL, ":")));
                   1000:     }
                   1001: 
                   1002:     /*
                   1003:      * Can't use $EDITOR, try each element of def_editor until we
                   1004:      * find one that exists, is regular, and is executable.
                   1005:      */
                   1006:     if (Editor == NULL || *Editor == '\0') {
                   1007:        efree(EditorPath);
                   1008:        EditorPath = estrdup(def_editor);
                   1009:        Editor = strtok(EditorPath, ":");
                   1010:        do {
                   1011:            EditorArgs = get_args(Editor);
                   1012:            if (sudo_goodpath(Editor, NULL))
                   1013:                break;
                   1014:        } while ((Editor = strtok(NULL, ":")));
                   1015: 
                   1016:        /* Bleah, none of the editors existed! */
                   1017:        if (Editor == NULL || *Editor == '\0')
                   1018:            errorx(1, _("no editor found (editor path = %s)"), def_editor);
                   1019:     }
                   1020:     *args = EditorArgs;
1.1.1.2   misho    1021:     debug_return_str(Editor);
1.1       misho    1022: }
                   1023: 
                   1024: /*
                   1025:  * Split out any command line arguments and return them.
                   1026:  */
                   1027: static char *
                   1028: get_args(char *cmnd)
                   1029: {
                   1030:     char *args;
1.1.1.2   misho    1031:     debug_decl(get_args, SUDO_DEBUG_UTIL)
1.1       misho    1032: 
                   1033:     args = cmnd;
                   1034:     while (*args && !isblank((unsigned char) *args))
                   1035:        args++;
                   1036:     if (*args) {
                   1037:        *args++ = '\0';
                   1038:        while (*args && isblank((unsigned char) *args))
                   1039:            args++;
                   1040:     }
1.1.1.2   misho    1041:     debug_return_str(*args ? args : NULL);
1.1       misho    1042: }
                   1043: 
                   1044: /*
                   1045:  * Look up the hostname and set user_host and user_shost.
                   1046:  */
                   1047: static void
                   1048: get_hostname(void)
                   1049: {
                   1050:     char *p, thost[MAXHOSTNAMELEN + 1];
1.1.1.2   misho    1051:     debug_decl(get_hostname, SUDO_DEBUG_UTIL)
1.1       misho    1052: 
1.1.1.2   misho    1053:     if (gethostname(thost, sizeof(thost)) != -1) {
                   1054:        thost[sizeof(thost) - 1] = '\0';
                   1055:        user_host = estrdup(thost);
                   1056: 
                   1057:        if ((p = strchr(user_host, '.'))) {
                   1058:            *p = '\0';
                   1059:            user_shost = estrdup(user_host);
                   1060:            *p = '.';
                   1061:        } else {
                   1062:            user_shost = user_host;
                   1063:        }
1.1       misho    1064:     } else {
1.1.1.2   misho    1065:        user_host = user_shost = "localhost";
1.1       misho    1066:     }
1.1.1.2   misho    1067:     debug_return;
1.1       misho    1068: }
                   1069: 
1.1.1.2   misho    1070: static bool
                   1071: alias_remove_recursive(char *name, int type)
1.1       misho    1072: {
                   1073:     struct member *m;
                   1074:     struct alias *a;
1.1.1.2   misho    1075:     bool rval = true;
                   1076:     debug_decl(alias_remove_recursive, SUDO_DEBUG_ALIAS)
1.1       misho    1077: 
                   1078:     if ((a = alias_find(name, type)) != NULL) {
                   1079:        tq_foreach_fwd(&a->members, m) {
                   1080:            if (m->type == ALIAS) {
1.1.1.2   misho    1081:                if (!alias_remove_recursive(m->name, type))
                   1082:                    rval = false;
1.1       misho    1083:            }
                   1084:        }
                   1085:     }
                   1086:     alias_seqno++;
                   1087:     a = alias_remove(name, type);
                   1088:     if (a)
                   1089:        rbinsert(alias_freelist, a);
1.1.1.2   misho    1090:     debug_return_bool(rval);
1.1       misho    1091: }
                   1092: 
                   1093: static int
                   1094: check_alias(char *name, int type, int strict, int quiet)
                   1095: {
                   1096:     struct member *m;
                   1097:     struct alias *a;
1.1.1.2   misho    1098:     int errors = 0;
                   1099:     debug_decl(check_alias, SUDO_DEBUG_ALIAS)
1.1       misho    1100: 
                   1101:     if ((a = alias_find(name, type)) != NULL) {
                   1102:        /* check alias contents */
                   1103:        tq_foreach_fwd(&a->members, m) {
                   1104:            if (m->type == ALIAS)
1.1.1.2   misho    1105:                errors += check_alias(m->name, type, strict, quiet);
1.1       misho    1106:        }
                   1107:     } else {
                   1108:        if (!quiet) {
                   1109:            char *fmt;
                   1110:            if (errno == ELOOP) {
                   1111:                fmt = strict ?
                   1112:                    _("Error: cycle in %s_Alias `%s'") :
                   1113:                    _("Warning: cycle in %s_Alias `%s'");
                   1114:            } else {
                   1115:                fmt = strict ?
                   1116:                    _("Error: %s_Alias `%s' referenced but not defined") :
                   1117:                    _("Warning: %s_Alias `%s' referenced but not defined");
                   1118:            }
                   1119:            warningx(fmt,
                   1120:                type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
                   1121:                type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
                   1122:                "Unknown", name);
                   1123:        }
1.1.1.2   misho    1124:        errors++;
1.1       misho    1125:     }
                   1126: 
1.1.1.2   misho    1127:     debug_return_int(errors);
1.1       misho    1128: }
                   1129: 
                   1130: /*
                   1131:  * Iterate through the sudoers datastructures looking for undefined
                   1132:  * aliases or unused aliases.
                   1133:  */
                   1134: static int
1.1.1.2   misho    1135: check_aliases(bool strict, bool quiet)
1.1       misho    1136: {
                   1137:     struct cmndspec *cs;
                   1138:     struct member *m, *binding;
                   1139:     struct privilege *priv;
                   1140:     struct userspec *us;
                   1141:     struct defaults *d;
1.1.1.2   misho    1142:     int atype, errors = 0;
                   1143:     debug_decl(check_aliases, SUDO_DEBUG_ALIAS)
1.1       misho    1144: 
                   1145:     alias_freelist = rbcreate(alias_compare);
                   1146: 
                   1147:     /* Forward check. */
                   1148:     tq_foreach_fwd(&userspecs, us) {
                   1149:        tq_foreach_fwd(&us->users, m) {
                   1150:            if (m->type == ALIAS) {
                   1151:                alias_seqno++;
1.1.1.2   misho    1152:                errors += check_alias(m->name, USERALIAS, strict, quiet);
1.1       misho    1153:            }
                   1154:        }
                   1155:        tq_foreach_fwd(&us->privileges, priv) {
                   1156:            tq_foreach_fwd(&priv->hostlist, m) {
                   1157:                if (m->type == ALIAS) {
                   1158:                    alias_seqno++;
1.1.1.2   misho    1159:                    errors += check_alias(m->name, HOSTALIAS, strict, quiet);
1.1       misho    1160:                }
                   1161:            }
                   1162:            tq_foreach_fwd(&priv->cmndlist, cs) {
                   1163:                tq_foreach_fwd(&cs->runasuserlist, m) {
                   1164:                    if (m->type == ALIAS) {
                   1165:                        alias_seqno++;
1.1.1.2   misho    1166:                        errors += check_alias(m->name, RUNASALIAS, strict, quiet);
1.1       misho    1167:                    }
                   1168:                }
                   1169:                if ((m = cs->cmnd)->type == ALIAS) {
                   1170:                    alias_seqno++;
1.1.1.2   misho    1171:                    errors += check_alias(m->name, CMNDALIAS, strict, quiet);
1.1       misho    1172:                }
                   1173:            }
                   1174:        }
                   1175:     }
                   1176: 
                   1177:     /* Reverse check (destructive) */
                   1178:     tq_foreach_fwd(&userspecs, us) {
                   1179:        tq_foreach_fwd(&us->users, m) {
                   1180:            if (m->type == ALIAS) {
                   1181:                alias_seqno++;
1.1.1.2   misho    1182:                if (!alias_remove_recursive(m->name, USERALIAS))
                   1183:                    errors++;
1.1       misho    1184:            }
                   1185:        }
                   1186:        tq_foreach_fwd(&us->privileges, priv) {
                   1187:            tq_foreach_fwd(&priv->hostlist, m) {
                   1188:                if (m->type == ALIAS) {
                   1189:                    alias_seqno++;
1.1.1.2   misho    1190:                    if (!alias_remove_recursive(m->name, HOSTALIAS))
                   1191:                        errors++;
1.1       misho    1192:                }
                   1193:            }
                   1194:            tq_foreach_fwd(&priv->cmndlist, cs) {
                   1195:                tq_foreach_fwd(&cs->runasuserlist, m) {
                   1196:                    if (m->type == ALIAS) {
                   1197:                        alias_seqno++;
1.1.1.2   misho    1198:                        if (!alias_remove_recursive(m->name, RUNASALIAS))
                   1199:                            errors++;
1.1       misho    1200:                    }
                   1201:                }
                   1202:                if ((m = cs->cmnd)->type == ALIAS) {
                   1203:                    alias_seqno++;
1.1.1.2   misho    1204:                    if (!alias_remove_recursive(m->name, CMNDALIAS))
                   1205:                        errors++;
1.1       misho    1206:                }
                   1207:            }
                   1208:        }
                   1209:     }
                   1210:     tq_foreach_fwd(&defaults, d) {
                   1211:        switch (d->type) {
                   1212:            case DEFAULTS_HOST:
                   1213:                atype = HOSTALIAS;
                   1214:                break;
                   1215:            case DEFAULTS_USER:
                   1216:                atype = USERALIAS;
                   1217:                break;
                   1218:            case DEFAULTS_RUNAS:
                   1219:                atype = RUNASALIAS;
                   1220:                break;
                   1221:            case DEFAULTS_CMND:
                   1222:                atype = CMNDALIAS;
                   1223:                break;
                   1224:            default:
                   1225:                continue; /* not an alias */
                   1226:        }
                   1227:        tq_foreach_fwd(&d->binding, binding) {
                   1228:            for (m = binding; m != NULL; m = m->next) {
                   1229:                if (m->type == ALIAS) {
                   1230:                    alias_seqno++;
1.1.1.2   misho    1231:                    if (!alias_remove_recursive(m->name, atype))
                   1232:                        errors++;
1.1       misho    1233:                }
                   1234:            }
                   1235:        }
                   1236:     }
                   1237:     rbdestroy(alias_freelist, alias_free);
                   1238: 
                   1239:     /* If all aliases were referenced we will have an empty tree. */
                   1240:     if (!no_aliases() && !quiet)
                   1241:        alias_apply(print_unused, strict ? "Error" : "Warning");
                   1242: 
1.1.1.2   misho    1243:     debug_return_int(strict ? errors : 0);
1.1       misho    1244: }
                   1245: 
                   1246: static int
                   1247: print_unused(void *v1, void *v2)
                   1248: {
                   1249:     struct alias *a = (struct alias *)v1;
                   1250:     char *prefix = (char *)v2;
                   1251: 
1.1.1.2   misho    1252:     warningx2(_("%s: unused %s_Alias %s"), prefix,
1.1       misho    1253:        a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
                   1254:        a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
                   1255:        "Unknown", a->name);
                   1256:     return 0;
                   1257: }
                   1258: 
                   1259: /*
                   1260:  * Unlink any sudoers temp files that remain.
                   1261:  */
                   1262: void
                   1263: cleanup(int gotsignal)
                   1264: {
                   1265:     struct sudoersfile *sp;
                   1266: 
                   1267:     tq_foreach_fwd(&sudoerslist, sp) {
                   1268:        if (sp->tpath != NULL)
                   1269:            (void) unlink(sp->tpath);
                   1270:     }
                   1271:     if (!gotsignal) {
                   1272:        sudo_endpwent();
                   1273:        sudo_endgrent();
                   1274:     }
                   1275: }
                   1276: 
                   1277: /*
                   1278:  * Unlink sudoers temp files (if any) and exit.
                   1279:  */
                   1280: static void
                   1281: quit(int signo)
                   1282: {
                   1283:     const char *signame, *myname;
                   1284: 
                   1285:     cleanup(signo);
                   1286: #define        emsg     " exiting due to signal: "
                   1287:     myname = getprogname();
                   1288:     signame = strsignal(signo);
1.1.1.2   misho    1289:     ignore_result(write(STDERR_FILENO, myname, strlen(myname)));
                   1290:     ignore_result(write(STDERR_FILENO, emsg, sizeof(emsg) - 1));
                   1291:     ignore_result(write(STDERR_FILENO, signame, strlen(signame)));
                   1292:     ignore_result(write(STDERR_FILENO, "\n", 1));
1.1       misho    1293:     _exit(signo);
                   1294: }
                   1295: 
                   1296: static void
                   1297: usage(int fatal)
                   1298: {
                   1299:     (void) fprintf(fatal ? stderr : stdout,
                   1300:        "usage: %s [-chqsV] [-f sudoers]\n", getprogname());
                   1301:     if (fatal)
                   1302:        exit(1);
                   1303: }
                   1304: 
                   1305: static void
                   1306: help(void)
                   1307: {
                   1308:     (void) printf(_("%s - safely edit the sudoers file\n\n"), getprogname());
                   1309:     usage(0);
                   1310:     (void) puts(_("\nOptions:\n"
                   1311:        "  -c          check-only mode\n"
                   1312:        "  -f sudoers  specify sudoers file location\n"
                   1313:        "  -h          display help message and exit\n"
                   1314:        "  -q          less verbose (quiet) syntax error messages\n"
                   1315:        "  -s          strict syntax checking\n"
                   1316:        "  -V          display version information and exit"));
                   1317:     exit(0);
                   1318: }
                   1319: 
                   1320: static int
                   1321: visudo_printf(int msg_type, const char *fmt, ...)
                   1322: {
                   1323:     va_list ap;
                   1324:     FILE *fp;
                   1325:             
                   1326:     switch (msg_type) {
                   1327:     case SUDO_CONV_INFO_MSG:
                   1328:        fp = stdout;
                   1329:        break;
                   1330:     case SUDO_CONV_ERROR_MSG:
                   1331:        fp = stderr;
                   1332:        break;
                   1333:     default:
                   1334:        errno = EINVAL;
                   1335:        return -1;
                   1336:     }
                   1337:    
                   1338:     va_start(ap, fmt);
                   1339:     vfprintf(fp, fmt, ap);
                   1340:     va_end(ap);
                   1341:    
                   1342:     return 0;
                   1343: }

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