add Vcs entries to the control file
[debian/sudo] / visudo.c
1 /*
2  * Copyright (c) 1996, 1998-2005, 2007-2010
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 <ctype.h>
62 #include <pwd.h>
63 #include <grp.h>
64 #include <signal.h>
65 #include <errno.h>
66 #include <fcntl.h>
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69 #include <netdb.h>
70 #if TIME_WITH_SYS_TIME
71 # include <time.h>
72 #endif
73 #ifdef __STDC__
74 # include <stdarg.h>
75 #else
76 # include <varargs.h>
77 #endif
78
79 #include "sudo.h"
80 #include "interfaces.h"
81 #include "parse.h"
82 #include "redblack.h"
83 #include <gram.h>
84
85 struct sudoersfile {
86     struct sudoersfile *prev, *next;
87     char *path;
88     char *tpath;
89     int fd;
90     int modified;
91     int doedit;
92 };
93 TQ_DECLARE(sudoersfile);
94
95 /*
96  * Function prototypes
97  */
98 static RETSIGTYPE quit          __P((int));
99 static char *get_args           __P((char *));
100 static char *get_editor         __P((char **));
101 static void get_hostname        __P((void));
102 static char whatnow             __P((void));
103 static int check_aliases        __P((int, int));
104 static int check_syntax         __P((char *, int, int));
105 static int edit_sudoers         __P((struct sudoersfile *, char *, char *, int));
106 static int install_sudoers      __P((struct sudoersfile *, int));
107 static int print_unused         __P((void *, void *));
108 static int reparse_sudoers      __P((char *, char *, int, int));
109 static int run_command          __P((char *, char **));
110 static void print_selfref       __P((char *, int, int, int));
111 static void print_undefined     __P((char *, int, int, int));
112 static void setup_signals       __P((void));
113 static void usage               __P((void)) __attribute__((__noreturn__));
114
115 extern void yyerror             __P((const char *));
116 extern void yyrestart           __P((FILE *));
117
118 /*
119  * External globals exported by the parser
120  */
121 extern struct rbtree *aliases;
122 extern FILE *yyin;
123 extern char *sudoers, *errorfile;
124 extern int errorlineno, parse_error;
125 /* For getopt(3) */
126 extern char *optarg;
127 extern int optind;
128
129 /*
130  * Globals
131  */
132 int Argc;
133 char **Argv;
134 int num_interfaces;
135 struct interface *interfaces;
136 struct sudo_user sudo_user;
137 struct passwd *list_pw;
138 static struct sudoersfile_list sudoerslist;
139 static struct rbtree *alias_freelist;
140
141 int
142 main(argc, argv)
143     int argc;
144     char **argv;
145 {
146     struct sudoersfile *sp;
147     char *args, *editor, *sudoers_path;
148     int ch, checkonly, quiet, strict, oldperms;
149 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
150     extern char *malloc_options;
151     malloc_options = "AFGJPR";
152 #endif
153
154     Argv = argv;
155     if ((Argc = argc) < 1)
156         usage();
157
158     /*
159      * Arg handling.
160      */
161     checkonly = oldperms = quiet = strict = FALSE;
162     sudoers_path = _PATH_SUDOERS;
163     while ((ch = getopt(argc, argv, "Vcf:sq")) != -1) {
164         switch (ch) {
165             case 'V':
166                 (void) printf("%s version %s\n", getprogname(), PACKAGE_VERSION);
167                 exit(0);
168             case 'c':
169                 checkonly++;            /* check mode */
170                 break;
171             case 'f':
172                 sudoers_path = optarg;  /* sudoers file path */
173                 oldperms = TRUE;
174                 break;
175             case 's':
176                 strict++;               /* strict mode */
177                 break;
178             case 'q':
179                 quiet++;                /* quiet mode */
180                 break;
181             default:
182                 usage();
183         }
184     }
185     argc -= optind;
186     argv += optind;
187     if (argc)
188         usage();
189
190     sudo_setpwent();
191     sudo_setgrent();
192
193     /* Mock up a fake sudo_user struct. */
194     user_cmnd = "";
195     if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
196         errorx(1, "you don't exist in the passwd database");
197     get_hostname();
198
199     /* Setup defaults data structures. */
200     init_defaults();
201
202     if (checkonly)
203         exit(check_syntax(sudoers_path, quiet, strict));
204
205     /*
206      * Parse the existing sudoers file(s) in quiet mode to highlight any
207      * existing errors and to pull in editor and env_editor conf values.
208      */
209     if ((yyin = open_sudoers(sudoers_path, TRUE, NULL)) == NULL) {
210         error(1, "%s", sudoers_path);
211     }
212     init_parser(sudoers_path, 0);
213     yyparse();
214     (void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
215
216     editor = get_editor(&args);
217
218     /* Install signal handlers to clean up temp files if we are killed. */
219     setup_signals();
220
221     /* Edit the sudoers file(s) */
222     tq_foreach_fwd(&sudoerslist, sp) {
223         if (!sp->doedit)
224             continue;
225         if (sp != tq_first(&sudoerslist)) {
226             printf("press return to edit %s: ", sp->path);
227             while ((ch = getchar()) != EOF && ch != '\n')
228                     continue;
229         }
230         edit_sudoers(sp, editor, args, -1);
231     }
232
233     /* Check edited files for a parse error and re-edit any that fail. */
234     reparse_sudoers(editor, args, strict, quiet);
235
236     /* Install the sudoers temp files. */
237     tq_foreach_fwd(&sudoerslist, sp) {
238         if (!sp->modified)
239             (void) unlink(sp->tpath);
240         else
241             (void) install_sudoers(sp, oldperms);
242     }
243
244     exit(0);
245 }
246
247 /*
248  * Edit each sudoers file.
249  * Returns TRUE on success, else FALSE.
250  */
251 static int
252 edit_sudoers(sp, editor, args, lineno)
253     struct sudoersfile *sp;
254     char *editor, *args;
255     int lineno;
256 {
257     int tfd;                            /* sudoers temp file descriptor */
258     int modified;                       /* was the file modified? */
259     int ac;                             /* argument count */
260     char **av;                          /* argument vector for run_command */
261     char *cp;                           /* scratch char pointer */
262     char buf[PATH_MAX*2];               /* buffer used for copying files */
263     char linestr[64];                   /* string version of lineno */
264     struct timeval tv, tv1, tv2;        /* time before and after edit */
265     struct timeval orig_mtim;           /* starting mtime of sudoers file */
266     off_t orig_size;                    /* starting size of sudoers file */
267     ssize_t nread;                      /* number of bytes read */
268     struct stat sb;                     /* stat buffer */
269
270 #ifdef HAVE_FSTAT
271     if (fstat(sp->fd, &sb) == -1)
272 #else
273     if (stat(sp->path, &sb) == -1)
274 #endif
275         error(1, "can't stat %s", sp->path);
276     orig_size = sb.st_size;
277     mtim_get(&sb, &orig_mtim);
278
279     /* Create the temp file if needed and set timestamp. */
280     if (sp->tpath == NULL) {
281         easprintf(&sp->tpath, "%s.tmp", sp->path);
282         tfd = open(sp->tpath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
283         if (tfd < 0)
284             error(1, "%s", sp->tpath);
285
286         /* Copy sp->path -> sp->tpath and reset the mtime. */
287         if (orig_size != 0) {
288             (void) lseek(sp->fd, (off_t)0, SEEK_SET);
289             while ((nread = read(sp->fd, buf, sizeof(buf))) > 0)
290                 if (write(tfd, buf, nread) != nread)
291                     error(1, "write error");
292
293             /* Add missing newline at EOF if needed. */
294             if (nread > 0 && buf[nread - 1] != '\n') {
295                 buf[0] = '\n';
296                 write(tfd, buf, 1);
297             }
298         }
299         (void) close(tfd);
300     }
301     (void) touch(-1, sp->tpath, &orig_mtim);
302
303     /* Find the length of the argument vector */
304     ac = 3 + (lineno > 0);
305     if (args) {
306         int wasblank;
307
308         ac++;
309         for (wasblank = FALSE, cp = args; *cp; cp++) {
310             if (isblank((unsigned char) *cp))
311                 wasblank = TRUE;
312             else if (wasblank) {
313                 wasblank = FALSE;
314                 ac++;
315             }
316         }
317     }
318
319     /* Build up argument vector for the command */
320     av = emalloc2(ac, sizeof(char *));
321     if ((av[0] = strrchr(editor, '/')) != NULL)
322         av[0]++;
323     else
324         av[0] = editor;
325     ac = 1;
326     if (lineno > 0) {
327         (void) snprintf(linestr, sizeof(linestr), "+%d", lineno);
328         av[ac++] = linestr;
329     }
330     if (args) {
331         for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t")))
332             av[ac++] = cp;
333     }
334     av[ac++] = sp->tpath;
335     av[ac++] = NULL;
336
337     /*
338      * Do the edit:
339      *  We cannot check the editor's exit value against 0 since
340      *  XPG4 specifies that vi's exit value is a function of the
341      *  number of errors during editing (?!?!).
342      */
343     gettime(&tv1);
344     if (run_command(editor, av) != -1) {
345         gettime(&tv2);
346         /*
347          * Sanity checks.
348          */
349         if (stat(sp->tpath, &sb) < 0) {
350             warningx("cannot stat temporary file (%s), %s unchanged",
351                 sp->tpath, sp->path);
352             return(FALSE);
353         }
354         if (sb.st_size == 0 && orig_size != 0) {
355             warningx("zero length temporary file (%s), %s unchanged",
356                 sp->tpath, sp->path);
357             sp->modified = TRUE;
358             return(FALSE);
359         }
360     } else {
361         warningx("editor (%s) failed, %s unchanged", editor, sp->path);
362         return(FALSE);
363     }
364
365     /* Set modified bit if use changed the file. */
366     modified = TRUE;
367     mtim_get(&sb, &tv);
368     if (orig_size == sb.st_size && timevalcmp(&orig_mtim, &tv, ==)) {
369         /*
370          * If mtime and size match but the user spent no measurable
371          * time in the editor we can't tell if the file was changed.
372          */
373         timevalsub(&tv1, &tv2);
374         if (timevalisset(&tv2))
375             modified = FALSE;
376     }
377
378     /*
379      * If modified in this edit session, mark as modified.
380      */
381     if (modified)
382         sp->modified = modified;
383     else
384         warningx("%s unchanged", sp->tpath);
385
386     return(TRUE);
387 }
388
389 /*
390  * Parse sudoers after editing and re-edit any ones that caused a parse error.
391  * Returns TRUE on success, else FALSE.
392  */
393 static int
394 reparse_sudoers(editor, args, strict, quiet)
395     char *editor, *args;
396     int strict, quiet;
397 {
398     struct sudoersfile *sp, *last;
399     FILE *fp;
400     int ch;
401
402     /*
403      * Parse the edited sudoers files and do sanity checking
404      */
405     do {
406         sp = tq_first(&sudoerslist);
407         last = tq_last(&sudoerslist);
408         fp = fopen(sp->tpath, "r+");
409         if (fp == NULL)
410             errorx(1, "can't re-open temporary file (%s), %s unchanged.",
411                 sp->tpath, sp->path);
412
413         /* Clean slate for each parse */
414         init_defaults();
415         init_parser(sp->path, quiet);
416
417         /* Parse the sudoers temp file */
418         yyrestart(fp);
419         if (yyparse() && !parse_error) {
420             warningx("unabled to parse temporary file (%s), unknown error",
421                 sp->tpath);
422             parse_error = TRUE;
423             errorfile = sp->path;
424         }
425         fclose(yyin);
426         if (!parse_error) {
427             if (!update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER) ||
428                 check_aliases(strict, quiet) != 0) {
429                 parse_error = TRUE;
430                 errorfile = sp->path;
431             }
432         }
433
434         /*
435          * Got an error, prompt the user for what to do now
436          */
437         if (parse_error) {
438             switch (whatnow()) {
439                 case 'Q' :      parse_error = FALSE;    /* ignore parse error */
440                                 break;
441                 case 'x' :      cleanup(0);
442                                 exit(0);
443                                 break;
444             }
445         }
446         if (parse_error) {
447             /* Edit file with the parse error */
448             tq_foreach_fwd(&sudoerslist, sp) {
449                 if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
450                     edit_sudoers(sp, editor, args, errorlineno);
451                     break;
452                 }
453             }
454             if (sp == NULL)
455                 errorx(1, "internal error, can't find %s in list!", sudoers);
456         }
457
458         /* If any new #include directives were added, edit them too. */
459         for (sp = last->next; sp != NULL; sp = sp->next) {
460             printf("press return to edit %s: ", sp->path);
461             while ((ch = getchar()) != EOF && ch != '\n')
462                     continue;
463             edit_sudoers(sp, editor, args, errorlineno);
464         }
465     } while (parse_error);
466
467     return(TRUE);
468 }
469
470 /*
471  * Set the owner and mode on a sudoers temp file and
472  * move it into place.  Returns TRUE on success, else FALSE.
473  */
474 static int
475 install_sudoers(sp, oldperms)
476     struct sudoersfile *sp;
477     int oldperms;
478 {
479     struct stat sb;
480
481     /*
482      * Change mode and ownership of temp file so when
483      * we move it to sp->path things are kosher.
484      */
485     if (oldperms) {
486         /* Use perms of the existing file.  */
487 #ifdef HAVE_FSTAT
488         if (fstat(sp->fd, &sb) == -1)
489 #else
490         if (stat(sp->path, &sb) == -1)
491 #endif
492             error(1, "can't stat %s", sp->path);
493         (void) chown(sp->tpath, sb.st_uid, sb.st_gid);
494         (void) chmod(sp->tpath, sb.st_mode & 0777);
495     } else {
496         if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
497             warning("unable to set (uid, gid) of %s to (%d, %d)",
498                 sp->tpath, SUDOERS_UID, SUDOERS_GID);
499             return(FALSE);
500         }
501         if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
502             warning("unable to change mode of %s to 0%o", sp->tpath,
503                 SUDOERS_MODE);
504             return(FALSE);
505         }
506     }
507
508     /*
509      * Now that sp->tpath is sane (parses ok) it needs to be
510      * rename(2)'d to sp->path.  If the rename(2) fails we try using
511      * mv(1) in case sp->tpath and sp->path are on different file systems.
512      */
513     if (rename(sp->tpath, sp->path) == 0) {
514         efree(sp->tpath);
515         sp->tpath = NULL;
516     } else {
517         if (errno == EXDEV) {
518             char *av[4];
519             warningx("%s and %s not on the same file system, using mv to rename",
520               sp->tpath, sp->path);
521
522             /* Build up argument vector for the command */
523             if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
524                 av[0]++;
525             else
526                 av[0] = _PATH_MV;
527             av[1] = sp->tpath;
528             av[2] = sp->path;
529             av[3] = NULL;
530
531             /* And run it... */
532             if (run_command(_PATH_MV, av)) {
533                 warningx("command failed: '%s %s %s', %s unchanged",
534                     _PATH_MV, sp->tpath, sp->path, sp->path);
535                 (void) unlink(sp->tpath);
536                 efree(sp->tpath);
537                 sp->tpath = NULL;
538                 return(FALSE);
539             }
540             efree(sp->tpath);
541             sp->tpath = NULL;
542         } else {
543             warning("error renaming %s, %s unchanged", sp->tpath, sp->path);
544             (void) unlink(sp->tpath);
545             return(FALSE);
546         }
547     }
548     return(TRUE);
549 }
550
551 /* STUB */
552 void
553 set_fqdn()
554 {
555     return;
556 }
557
558 /* STUB */
559 void
560 init_envtables()
561 {
562     return;
563 }
564
565 /* STUB */
566 int
567 user_is_exempt()
568 {
569     return(FALSE);
570 }
571
572 /* STUB */
573 void
574 sudo_setspent()
575 {
576     return;
577 }
578
579 /* STUB */
580 void
581 sudo_endspent()
582 {
583     return;
584 }
585
586 char *
587 sudo_getepw(pw)
588     const struct passwd *pw;
589 {
590     return (pw->pw_passwd);
591 }
592
593 /*
594  * Assuming a parse error occurred, prompt the user for what they want
595  * to do now.  Returns the first letter of their choice.
596  */
597 static char
598 whatnow()
599 {
600     int choice, c;
601
602     for (;;) {
603         (void) fputs("What now? ", stdout);
604         choice = getchar();
605         for (c = choice; c != '\n' && c != EOF;)
606             c = getchar();
607
608         switch (choice) {
609             case EOF:
610                 choice = 'x';
611                 /* FALLTHROUGH */
612             case 'e':
613             case 'x':
614             case 'Q':
615                 return(choice);
616             default:
617                 (void) puts("Options are:");
618                 (void) puts("  (e)dit sudoers file again");
619                 (void) puts("  e(x)it without saving changes to sudoers file");
620                 (void) puts("  (Q)uit and save changes to sudoers file (DANGER!)\n");
621         }
622     }
623 }
624
625 /*
626  * Install signal handlers for visudo.
627  */
628 static void
629 setup_signals()
630 {
631         sigaction_t sa;
632
633         /*
634          * Setup signal handlers to cleanup nicely.
635          */
636         zero_bytes(&sa, sizeof(sa));
637         sigemptyset(&sa.sa_mask);
638         sa.sa_flags = SA_RESTART;
639         sa.sa_handler = quit;
640         (void) sigaction(SIGTERM, &sa, NULL);
641         (void) sigaction(SIGHUP, &sa, NULL);
642         (void) sigaction(SIGINT, &sa, NULL);
643         (void) sigaction(SIGQUIT, &sa, NULL);
644 }
645
646 static int
647 run_command(path, argv)
648     char *path;
649     char **argv;
650 {
651     int status;
652     pid_t pid, rv;
653
654     switch (pid = fork()) {
655         case -1:
656             error(1, "unable to run %s", path);
657             break;      /* NOTREACHED */
658         case 0:
659             sudo_endpwent();
660             sudo_endgrent();
661             closefrom(STDERR_FILENO + 1);
662             execv(path, argv);
663             warning("unable to run %s", path);
664             _exit(127);
665             break;      /* NOTREACHED */
666     }
667
668     do {
669 #ifdef sudo_waitpid
670         rv = sudo_waitpid(pid, &status, 0);
671 #else
672         rv = wait(&status);
673 #endif
674     } while (rv == -1 && errno == EINTR);
675
676     if (rv == -1 || !WIFEXITED(status))
677         return(-1);
678     return(WEXITSTATUS(status));
679 }
680
681 static int
682 check_syntax(sudoers_path, quiet, strict)
683     char *sudoers_path;
684     int quiet;
685     int strict;
686 {
687     struct stat sb;
688     int error;
689
690     if ((yyin = fopen(sudoers_path, "r")) == NULL) {
691         if (!quiet)
692             warning("unable to open %s", sudoers_path);
693         exit(1);
694     }
695     init_parser(sudoers_path, quiet);
696     if (yyparse() && !parse_error) {
697         if (!quiet)
698             warningx("failed to parse %s file, unknown error", sudoers_path);
699         parse_error = TRUE;
700         errorfile = sudoers_path;
701     }
702     if (!parse_error && check_aliases(strict, quiet) != 0) {
703         parse_error = TRUE;
704         errorfile = sudoers_path;
705     }
706     error = parse_error;
707     if (!quiet) {
708         if (parse_error) {
709             if (errorlineno != -1)
710                 (void) printf("parse error in %s near line %d\n", errorfile,
711                     errorlineno);
712             else
713                 (void) printf("parse error in %s\n", errorfile);
714         } else {
715             (void) printf("%s: parsed OK\n", sudoers_path);
716         }
717     }
718     /* Check mode and owner in strict mode. */
719 #ifdef HAVE_FSTAT
720     if (strict && fstat(fileno(yyin), &sb) == 0)
721 #else
722     if (strict && stat(sudoers_path, &sb) == 0)
723 #endif
724     {
725         if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
726             error = TRUE;
727             if (!quiet) {
728                 fprintf(stderr, "%s: wrong owner (uid, gid) should be (%d, %d)\n",
729                     sudoers_path, SUDOERS_UID, SUDOERS_GID);
730                 }
731         }
732         if ((sb.st_mode & 07777) != SUDOERS_MODE) {
733             error = TRUE;
734             if (!quiet) {
735                 fprintf(stderr, "%s: bad permissions, should be mode 0%o\n",
736                     sudoers_path, SUDOERS_MODE);
737             }
738         }
739     }
740
741     return(error);
742 }
743
744 /*
745  * Used to open (and lock) the initial sudoers file and to also open
746  * any subsequent files #included via a callback from the parser.
747  */
748 FILE *
749 open_sudoers(path, doedit, keepopen)
750     const char *path;
751     int doedit;
752     int *keepopen;
753 {
754     struct sudoersfile *entry;
755     FILE *fp;
756
757     /* Check for existing entry */
758     tq_foreach_fwd(&sudoerslist, entry) {
759         if (strcmp(path, entry->path) == 0)
760             break;
761     }
762     if (entry == NULL) {
763         entry = emalloc(sizeof(*entry));
764         entry->path = estrdup(path);
765         entry->modified = 0;
766         entry->prev = entry;
767         entry->next = NULL;
768         entry->fd = open(entry->path, O_RDWR | O_CREAT, SUDOERS_MODE);
769         entry->tpath = NULL;
770         entry->doedit = doedit;
771         if (entry->fd == -1) {
772             warning("%s", entry->path);
773             efree(entry);
774             return(NULL);
775         }
776         if (!lock_file(entry->fd, SUDO_TLOCK))
777             errorx(1, "%s busy, try again later", entry->path);
778         if ((fp = fdopen(entry->fd, "r")) == NULL)
779             error(1, "%s", entry->path);
780         tq_append(&sudoerslist, entry);
781     } else {
782         /* Already exists, open .tmp version if there is one. */
783         if (entry->tpath != NULL) {
784             if ((fp = fopen(entry->tpath, "r")) == NULL)
785                 error(1, "%s", entry->tpath);
786         } else {
787             if ((fp = fdopen(entry->fd, "r")) == NULL)
788                 error(1, "%s", entry->path);
789             rewind(fp);
790         }
791     }
792     if (keepopen != NULL)
793         *keepopen = TRUE;
794     return(fp);
795 }
796
797 static char *
798 get_editor(args)
799     char **args;
800 {
801     char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
802
803     /*
804      * Check VISUAL and EDITOR environment variables to see which editor
805      * the user wants to use (we may not end up using it though).
806      * If the path is not fully-qualified, make it so and check that
807      * the specified executable actually exists.
808      */
809     UserEditorArgs = NULL;
810     if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
811         UserEditor = getenv("EDITOR");
812     if (UserEditor && *UserEditor == '\0')
813         UserEditor = NULL;
814     else if (UserEditor) {
815         UserEditorArgs = get_args(UserEditor);
816         if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
817             UserEditor = Editor;
818         } else {
819             if (def_env_editor) {
820                 /* If we are honoring $EDITOR this is a fatal error. */
821                 errorx(1, "specified editor (%s) doesn't exist!", UserEditor);
822             } else {
823                 /* Otherwise, just ignore $EDITOR. */
824                 UserEditor = NULL;
825             }
826         }
827     }
828
829     /*
830      * See if we can use the user's choice of editors either because
831      * we allow any $EDITOR or because $EDITOR is in the allowable list.
832      */
833     Editor = EditorArgs = EditorPath = NULL;
834     if (def_env_editor && UserEditor) {
835         Editor = UserEditor;
836         EditorArgs = UserEditorArgs;
837     } else if (UserEditor) {
838         struct stat editor_sb;
839         struct stat user_editor_sb;
840         char *base, *userbase;
841
842         if (stat(UserEditor, &user_editor_sb) != 0) {
843             /* Should never happen since we already checked above. */
844             error(1, "unable to stat editor (%s)", UserEditor);
845         }
846         EditorPath = estrdup(def_editor);
847         Editor = strtok(EditorPath, ":");
848         do {
849             EditorArgs = get_args(Editor);
850             /*
851              * Both Editor and UserEditor should be fully qualified but
852              * check anyway...
853              */
854             if ((base = strrchr(Editor, '/')) == NULL)
855                 continue;
856             if ((userbase = strrchr(UserEditor, '/')) == NULL) {
857                 Editor = NULL;
858                 break;
859             }
860             base++, userbase++;
861
862             /*
863              * We compare the basenames first and then use stat to match
864              * for sure.
865              */
866             if (strcmp(base, userbase) == 0) {
867                 if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
868                     && (editor_sb.st_mode & 0000111) &&
869                     editor_sb.st_dev == user_editor_sb.st_dev &&
870                     editor_sb.st_ino == user_editor_sb.st_ino)
871                     break;
872             }
873         } while ((Editor = strtok(NULL, ":")));
874     }
875
876     /*
877      * Can't use $EDITOR, try each element of def_editor until we
878      * find one that exists, is regular, and is executable.
879      */
880     if (Editor == NULL || *Editor == '\0') {
881         efree(EditorPath);
882         EditorPath = estrdup(def_editor);
883         Editor = strtok(EditorPath, ":");
884         do {
885             EditorArgs = get_args(Editor);
886             if (sudo_goodpath(Editor, NULL))
887                 break;
888         } while ((Editor = strtok(NULL, ":")));
889
890         /* Bleah, none of the editors existed! */
891         if (Editor == NULL || *Editor == '\0')
892             errorx(1, "no editor found (editor path = %s)", def_editor);
893     }
894     *args = EditorArgs;
895     return(Editor);
896 }
897
898 /*
899  * Split out any command line arguments and return them.
900  */
901 static char *
902 get_args(cmnd)
903     char *cmnd;
904 {
905     char *args;
906
907     args = cmnd;
908     while (*args && !isblank((unsigned char) *args))
909         args++;
910     if (*args) {
911         *args++ = '\0';
912         while (*args && isblank((unsigned char) *args))
913             args++;
914     }
915     return(*args ? args : NULL);
916 }
917
918 /*
919  * Look up the hostname and set user_host and user_shost.
920  */
921 static void
922 get_hostname()
923 {
924     char *p, thost[MAXHOSTNAMELEN + 1];
925
926     if (gethostname(thost, sizeof(thost)) != 0) {
927         user_host = user_shost = "localhost";
928         return;
929     }
930     thost[sizeof(thost) - 1] = '\0';
931     user_host = estrdup(thost);
932
933     if ((p = strchr(user_host, '.'))) {
934         *p = '\0';
935         user_shost = estrdup(user_host);
936         *p = '.';
937     } else {
938         user_shost = user_host;
939     }
940 }
941
942 static int
943 alias_remove_recursive(name, type, strict, quiet)
944     char *name;
945     int type;
946     int strict;
947     int quiet;
948 {
949     struct member *m;
950     struct alias *a;
951     int error = 0;
952
953     if ((a = alias_find(name, type)) != NULL) {
954         tq_foreach_fwd(&a->members, m) {
955             if (m->type == ALIAS) {
956                 if (strcmp(name, m->name) == 0) {
957                     print_selfref(m->name, type, strict, quiet);
958                     error = 1;
959                 } else {
960                     if (!alias_remove_recursive(m->name, type, strict, quiet))
961                         error = 1;
962                 }
963             }
964         }
965     }
966     alias_seqno++;
967     a = alias_remove(name, type);
968     if (a)
969         rbinsert(alias_freelist, a);
970     return(error);
971 }
972
973 /*
974  * Iterate through the sudoers datastructures looking for undefined
975  * aliases or unused aliases.
976  */
977 static int
978 check_aliases(strict, quiet)
979     int strict;
980     int quiet;
981 {
982     struct cmndspec *cs;
983     struct member *m, *binding;
984     struct privilege *priv;
985     struct userspec *us;
986     struct defaults *d;
987     int atype, error = 0;
988
989     alias_freelist = rbcreate(alias_compare);
990
991     /* Forward check. */
992     tq_foreach_fwd(&userspecs, us) {
993         tq_foreach_fwd(&us->users, m) {
994             if (m->type == ALIAS) {
995                 alias_seqno++;
996                 if (alias_find(m->name, USERALIAS) == NULL) {
997                     print_undefined(m->name, USERALIAS, strict, quiet);
998                     error++;
999                 }
1000             }
1001         }
1002         tq_foreach_fwd(&us->privileges, priv) {
1003             tq_foreach_fwd(&priv->hostlist, m) {
1004                 if (m->type == ALIAS) {
1005                     alias_seqno++;
1006                     if (alias_find(m->name, HOSTALIAS) == NULL) {
1007                         print_undefined(m->name, HOSTALIAS, strict, quiet);
1008                         error++;
1009                     }
1010                 }
1011             }
1012             tq_foreach_fwd(&priv->cmndlist, cs) {
1013                 tq_foreach_fwd(&cs->runasuserlist, m) {
1014                     if (m->type == ALIAS) {
1015                         alias_seqno++;
1016                         if (alias_find(m->name, RUNASALIAS) == NULL) {
1017                             print_undefined(m->name, RUNASALIAS, strict, quiet);
1018                             error++;
1019                         }
1020                     }
1021                 }
1022                 if ((m = cs->cmnd)->type == ALIAS) {
1023                     alias_seqno++;
1024                     if (alias_find(m->name, CMNDALIAS) == NULL) {
1025                         print_undefined(m->name, CMNDALIAS, strict, quiet);
1026                         error++;
1027                     }
1028                 }
1029             }
1030         }
1031     }
1032
1033     /* Reverse check (destructive) */
1034     tq_foreach_fwd(&userspecs, us) {
1035         tq_foreach_fwd(&us->users, m) {
1036             if (m->type == ALIAS) {
1037                 if (!alias_remove_recursive(m->name, USERALIAS, strict, quiet))
1038                     error++;
1039             }
1040         }
1041         tq_foreach_fwd(&us->privileges, priv) {
1042             tq_foreach_fwd(&priv->hostlist, m) {
1043                 if (m->type == ALIAS)
1044                     if (!alias_remove_recursive(m->name, HOSTALIAS, strict, 
1045                         quiet))
1046                         error++;
1047             }
1048             tq_foreach_fwd(&priv->cmndlist, cs) {
1049                 tq_foreach_fwd(&cs->runasuserlist, m) {
1050                     if (m->type == ALIAS)
1051                         if (!alias_remove_recursive(m->name, RUNASALIAS,
1052                             strict, quiet))
1053                             error++;
1054                 }
1055                 if ((m = cs->cmnd)->type == ALIAS)
1056                     if (!alias_remove_recursive(m->name, CMNDALIAS, strict,
1057                         quiet))
1058                         error++;
1059             }
1060         }
1061     }
1062     tq_foreach_fwd(&defaults, d) {
1063         switch (d->type) {
1064             case DEFAULTS_HOST:
1065                 atype = HOSTALIAS;
1066                 break;
1067             case DEFAULTS_USER:
1068                 atype = USERALIAS;
1069                 break;
1070             case DEFAULTS_RUNAS:
1071                 atype = RUNASALIAS;
1072                 break;
1073             case DEFAULTS_CMND:
1074                 atype = CMNDALIAS;
1075                 break;
1076             default:
1077                 continue; /* not an alias */
1078         }
1079         tq_foreach_fwd(&d->binding, binding) {
1080             for (m = binding; m != NULL; m = m->next) {
1081                 if (m->type == ALIAS)
1082                     if (!alias_remove_recursive(m->name, atype, strict, quiet))
1083                         error++;
1084             }
1085         }
1086     }
1087     rbdestroy(alias_freelist, alias_free);
1088
1089     /* If all aliases were referenced we will have an empty tree. */
1090     if (!no_aliases() && !quiet)
1091         alias_apply(print_unused, strict ? "Error" : "Warning");
1092
1093     return (strict ? error : 0);
1094 }
1095
1096 static void
1097 print_undefined(name, type, strict, quiet)
1098     char *name;
1099     int type;
1100     int strict;
1101     int quiet;
1102 {
1103     if (!quiet) {
1104         warningx("%s: %s_Alias `%s' referenced but not defined",
1105             strict ? "Error" : "Warning",
1106             type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
1107             type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
1108             "Unknown", name);
1109     }
1110 }
1111
1112 static void
1113 print_selfref(name, type, strict, quiet)
1114     char *name;
1115     int type;
1116     int strict;
1117     int quiet;
1118 {
1119     if (!quiet) {
1120         warningx("%s: %s_Alias `%s' references self",
1121             strict ? "Error" : "Warning",
1122             type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
1123             type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
1124             "Unknown", name);
1125     }
1126 }
1127
1128 static int
1129 print_unused(v1, v2)
1130     void *v1;
1131     void *v2;
1132 {
1133     struct alias *a = (struct alias *)v1;
1134     char *prefix = (char *)v2;
1135
1136     warningx("%s: unused %s_Alias %s", prefix,
1137         a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
1138         a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
1139         "Unknown", a->name);
1140     return(0);
1141 }
1142
1143 /*
1144  * Unlink any sudoers temp files that remain.
1145  */
1146 void
1147 cleanup(gotsignal)
1148     int gotsignal;
1149 {
1150     struct sudoersfile *sp;
1151
1152     tq_foreach_fwd(&sudoerslist, sp) {
1153         if (sp->tpath != NULL)
1154             (void) unlink(sp->tpath);
1155     }
1156     if (!gotsignal) {
1157         sudo_endpwent();
1158         sudo_endgrent();
1159     }
1160 }
1161
1162 /*
1163  * Unlink sudoers temp files (if any) and exit.
1164  */
1165 static RETSIGTYPE
1166 quit(signo)
1167     int signo;
1168 {
1169     cleanup(signo);
1170 #define emsg     " exiting due to signal.\n"
1171     write(STDERR_FILENO, getprogname(), strlen(getprogname()));
1172     write(STDERR_FILENO, emsg, sizeof(emsg) - 1);
1173     _exit(signo);
1174 }
1175
1176 static void
1177 usage()
1178 {
1179     (void) fprintf(stderr, "usage: %s [-c] [-q] [-s] [-V] [-f sudoers]\n",
1180         getprogname());
1181     exit(1);
1182 }