ced224876baccdc036a7e89f6d3aaa3a039f4500
[debian/sudo] / plugins / sudoers / toke.l
1 %{
2 /*
3  * Copyright (c) 1996, 1998-2005, 2007-2011
4  *      Todd C. Miller <Todd.Miller@courtesan.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
18  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
19  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
20  *
21  * Sponsored in part by the Defense Advanced Research Projects
22  * Agency (DARPA) and Air Force Research Laboratory, Air Force
23  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
24  */
25
26 #include <config.h>
27
28 #include <sys/types.h>
29 #include <sys/param.h>
30 #include <sys/stat.h>
31 #include <stdio.h>
32 #ifdef STDC_HEADERS
33 # include <stdlib.h>
34 # include <stddef.h>
35 #else
36 # ifdef HAVE_STDLIB_H
37 #  include <stdlib.h>
38 # endif
39 #endif /* STDC_HEADERS */
40 #ifdef HAVE_STRING_H
41 # include <string.h>
42 #endif /* HAVE_STRING_H */
43 #ifdef HAVE_STRINGS_H
44 # include <strings.h>
45 #endif /* HAVE_STRINGS_H */
46 #ifdef HAVE_UNISTD_H
47 # include <unistd.h>
48 #endif /* HAVE_UNISTD_H */
49 #if defined(HAVE_MALLOC_H) && !defined(STDC_HEADERS)
50 # include <malloc.h>
51 #endif /* HAVE_MALLOC_H && !STDC_HEADERS */
52 #ifdef HAVE_DIRENT_H
53 # include <dirent.h>
54 # define NAMLEN(dirent) strlen((dirent)->d_name)
55 #else
56 # define dirent direct
57 # define NAMLEN(dirent) (dirent)->d_namlen
58 # ifdef HAVE_SYS_NDIR_H
59 #  include <sys/ndir.h>
60 # endif
61 # ifdef HAVE_SYS_DIR_H
62 #  include <sys/dir.h>
63 # endif
64 # ifdef HAVE_NDIR_H
65 #  include <ndir.h>
66 # endif
67 #endif
68 #include <errno.h>
69 #include <ctype.h>
70 #include "sudoers.h"
71 #include "parse.h"
72 #include "toke.h"
73 #include <gram.h>
74 #include "lbuf.h"
75
76 extern YYSTYPE yylval;
77 extern bool parse_error;
78 int sudolineno;
79 int last_token;
80 char *sudoers;
81
82 static bool continued, sawspace;
83 static int prev_state;
84
85 static bool _push_include(char *, bool);
86 static bool pop_include(void);
87 static char *parse_include(char *);
88
89 static int sudoers_trace_print(const char *msg);
90 int (*trace_print)(const char *msg) = sudoers_trace_print;
91
92 #define LEXRETURN(n)    do {    \
93         last_token = (n);       \
94         return (n);             \
95 } while (0)
96
97 #define push_include(_p)        (_push_include((_p), false))
98 #define push_includedir(_p)     (_push_include((_p), true))
99 %}
100
101 HEX16                   [0-9A-Fa-f]{1,4}
102 OCTET                   (1?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5])
103 IPV4ADDR                {OCTET}(\.{OCTET}){3}
104 IPV6ADDR                ({HEX16}?:){2,7}{HEX16}?|({HEX16}?:){2,6}:{IPV4ADDR}
105
106 HOSTNAME                [[:alnum:]_-]+
107 WORD                    ([^#>!=:,\(\) \t\n\\\"]|\\[^\n])+
108 ID                      #-?[0-9]+
109 PATH                    \/(\\[\,:= \t#]|[^\,:=\\ \t\n#])+
110 ENVAR                   ([^#!=, \t\n\\\"]|\\[^\n])([^#=, \t\n\\\"]|\\[^\n])*
111 DEFVAR                  [a-z_]+
112
113 %option noinput
114 %option nounput
115 %option noyywrap
116
117 %s      GOTDEFS
118 %x      GOTCMND
119 %x      STARTDEFS
120 %x      INDEFS
121 %x      INSTR
122
123 %%
124 <GOTDEFS>[[:blank:]]*,[[:blank:]]* {
125                             LEXTRACE(", ");
126                             LEXRETURN(',');
127                         }                       /* return ',' */
128
129 <GOTDEFS>[[:blank:]]+   BEGIN STARTDEFS;
130
131 <STARTDEFS>{DEFVAR}     {
132                             BEGIN INDEFS;
133                             LEXTRACE("DEFVAR ");
134                             if (!fill(yytext, yyleng))
135                                 yyterminate();
136                             LEXRETURN(DEFVAR);
137                         }
138
139 <INDEFS>{
140     ,                   {
141                             BEGIN STARTDEFS;
142                             LEXTRACE(", ");
143                             LEXRETURN(',');
144                         }                       /* return ',' */
145
146     =                   {
147                             LEXTRACE("= ");
148                             LEXRETURN('=');
149                         }                       /* return '=' */
150
151     \+=                 {
152                             LEXTRACE("+= ");
153                             LEXRETURN('+');
154                         }                       /* return '+' */
155
156     -=                  {
157                             LEXTRACE("-= ");
158                             LEXRETURN('-');
159                         }                       /* return '-' */
160
161     \"                  {
162                             LEXTRACE("BEGINSTR ");
163                             yylval.string = NULL;
164                             prev_state = YY_START;
165                             BEGIN INSTR;
166                         }
167
168     {ENVAR}             {
169                             LEXTRACE("WORD(2) ");
170                             if (!fill(yytext, yyleng))
171                                 yyterminate();
172                             LEXRETURN(WORD);
173                         }
174 }
175
176 <INSTR>{
177     \\[[:blank:]]*\n[[:blank:]]*        {
178                             /* Line continuation char followed by newline. */
179                             sudolineno++;
180                             continued = true;
181                         }
182
183     \"                  {
184                             LEXTRACE("ENDSTR ");
185                             BEGIN prev_state;
186
187                             if (yylval.string == NULL) {
188                                 LEXTRACE("ERROR "); /* empty string */
189                                 LEXRETURN(ERROR);
190                             }
191                             if (prev_state == INITIAL) {
192                                 switch (yylval.string[0]) {
193                                 case '%':
194                                     if (yylval.string[1] == '\0' ||
195                                         (yylval.string[1] == ':' &&
196                                         yylval.string[2] == '\0')) {
197                                         LEXTRACE("ERROR "); /* empty group */
198                                         LEXRETURN(ERROR);
199                                     }
200                                     LEXTRACE("USERGROUP ");
201                                     LEXRETURN(USERGROUP);
202                                 case '+':
203                                     if (yylval.string[1] == '\0') {
204                                         LEXTRACE("ERROR "); /* empty netgroup */
205                                         LEXRETURN(ERROR);
206                                     }
207                                     LEXTRACE("NETGROUP ");
208                                     LEXRETURN(NETGROUP);
209                                 }
210                             }
211                             LEXTRACE("WORD(4) ");
212                             LEXRETURN(WORD);
213                         }
214
215     \\                  {
216                             LEXTRACE("BACKSLASH ");
217                             if (!append(yytext, yyleng))
218                                 yyterminate();
219                         }
220
221     ([^\"\n\\]|\\\")+   {
222                             LEXTRACE("STRBODY ");
223                             if (!append(yytext, yyleng))
224                                 yyterminate();
225                         }
226 }
227
228 <GOTCMND>{
229     \\[\*\?\[\]\!]      {
230                             /* quoted fnmatch glob char, pass verbatim */
231                             LEXTRACE("QUOTEDCHAR ");
232                             if (!fill_args(yytext, 2, sawspace))
233                                 yyterminate();
234                             sawspace = false;
235                         }
236
237     \\[:\\,= \t#]       {
238                             /* quoted sudoers special char, strip backslash */
239                             LEXTRACE("QUOTEDCHAR ");
240                             if (!fill_args(yytext + 1, 1, sawspace))
241                                 yyterminate();
242                             sawspace = false;
243                         }
244
245     [#:\,=\n]           {
246                             BEGIN INITIAL;
247                             yyless(0);
248                             LEXRETURN(COMMAND);
249                         }                       /* end of command line args */
250
251     [^#\\:, \t\n]+      {
252                             LEXTRACE("ARG ");
253                             if (!fill_args(yytext, yyleng, sawspace))
254                                 yyterminate();
255                             sawspace = false;
256                         }                       /* a command line arg */
257 }
258
259 <INITIAL>^#include[[:blank:]]+.*\n {
260                             char *path;
261
262                             if (continued) {
263                                 LEXTRACE("ERROR ");
264                                 LEXRETURN(ERROR);
265                             }
266
267                             if ((path = parse_include(yytext)) == NULL)
268                                 yyterminate();
269
270                             LEXTRACE("INCLUDE\n");
271
272                             /* Push current buffer and switch to include file */
273                             if (!push_include(path))
274                                 yyterminate();
275                         }
276
277 <INITIAL>^#includedir[[:blank:]]+.*\n {
278                             char *path;
279
280                             if (continued) {
281                                 LEXTRACE("ERROR ");
282                                 LEXRETURN(ERROR);
283                             }
284
285                             if ((path = parse_include(yytext)) == NULL)
286                                 yyterminate();
287
288                             LEXTRACE("INCLUDEDIR\n");
289
290                             /*
291                              * Push current buffer and switch to include file.
292                              * We simply ignore empty directories.
293                              */
294                             if (!push_includedir(path) && parse_error)
295                                 yyterminate();
296                         }
297
298 <INITIAL>^[[:blank:]]*Defaults([:@>\!][[:blank:]]*\!*\"?({ID}|{WORD}))? {
299                             char deftype;
300                             int n;
301
302                             if (continued) {
303                                 LEXTRACE("ERROR ");
304                                 LEXRETURN(ERROR);
305                             }
306
307                             for (n = 0; isblank((unsigned char)yytext[n]); n++)
308                                 continue;
309                             n += sizeof("Defaults") - 1;
310                             if ((deftype = yytext[n++]) != '\0') {
311                                 while (isblank((unsigned char)yytext[n]))
312                                     n++;
313                             }
314                             BEGIN GOTDEFS;
315                             switch (deftype) {
316                                 case ':':
317                                     yyless(n);
318                                     LEXTRACE("DEFAULTS_USER ");
319                                     LEXRETURN(DEFAULTS_USER);
320                                 case '>':
321                                     yyless(n);
322                                     LEXTRACE("DEFAULTS_RUNAS ");
323                                     LEXRETURN(DEFAULTS_RUNAS);
324                                 case '@':
325                                     yyless(n);
326                                     LEXTRACE("DEFAULTS_HOST ");
327                                     LEXRETURN(DEFAULTS_HOST);
328                                 case '!':
329                                     yyless(n);
330                                     LEXTRACE("DEFAULTS_CMND ");
331                                     LEXRETURN(DEFAULTS_CMND);
332                                 default:
333                                     LEXTRACE("DEFAULTS ");
334                                     LEXRETURN(DEFAULTS);
335                             }
336                         }
337
338 <INITIAL>^[[:blank:]]*(Host|Cmnd|User|Runas)_Alias      {
339                             int n;
340
341                             if (continued) {
342                                 LEXTRACE("ERROR ");
343                                 LEXRETURN(ERROR);
344                             }
345
346                             for (n = 0; isblank((unsigned char)yytext[n]); n++)
347                                 continue;
348                             switch (yytext[n]) {
349                                 case 'H':
350                                     LEXTRACE("HOSTALIAS ");
351                                     LEXRETURN(HOSTALIAS);
352                                 case 'C':
353                                     LEXTRACE("CMNDALIAS ");
354                                     LEXRETURN(CMNDALIAS);
355                                 case 'U':
356                                     LEXTRACE("USERALIAS ");
357                                     LEXRETURN(USERALIAS);
358                                 case 'R':
359                                     LEXTRACE("RUNASALIAS ");
360                                     LEXRETURN(RUNASALIAS);
361                             }
362                         }
363
364 NOPASSWD[[:blank:]]*:   {
365                                 /* cmnd does not require passwd for this user */
366                                 LEXTRACE("NOPASSWD ");
367                                 LEXRETURN(NOPASSWD);
368                         }
369
370 PASSWD[[:blank:]]*:     {
371                                 /* cmnd requires passwd for this user */
372                                 LEXTRACE("PASSWD ");
373                                 LEXRETURN(PASSWD);
374                         }
375
376 NOEXEC[[:blank:]]*:     {
377                                 LEXTRACE("NOEXEC ");
378                                 LEXRETURN(NOEXEC);
379                         }
380
381 EXEC[[:blank:]]*:       {
382                                 LEXTRACE("EXEC ");
383                                 LEXRETURN(EXEC);
384                         }
385
386 SETENV[[:blank:]]*:     {
387                                 LEXTRACE("SETENV ");
388                                 LEXRETURN(SETENV);
389                         }
390
391 NOSETENV[[:blank:]]*:   {
392                                 LEXTRACE("NOSETENV ");
393                                 LEXRETURN(NOSETENV);
394                         }
395
396 LOG_OUTPUT[[:blank:]]*: {
397                                 LEXTRACE("LOG_OUTPUT ");
398                                 LEXRETURN(LOG_OUTPUT);
399                         }
400
401 NOLOG_OUTPUT[[:blank:]]*:       {
402                                 LEXTRACE("NOLOG_OUTPUT ");
403                                 LEXRETURN(NOLOG_OUTPUT);
404                         }
405
406 LOG_INPUT[[:blank:]]*:  {
407                                 LEXTRACE("LOG_INPUT ");
408                                 LEXRETURN(LOG_INPUT);
409                         }
410
411 NOLOG_INPUT[[:blank:]]*:        {
412                                 LEXTRACE("NOLOG_INPUT ");
413                                 LEXRETURN(NOLOG_INPUT);
414                         }
415
416 <INITIAL,GOTDEFS>(\+|\%|\%:) {
417                             /* empty group or netgroup */
418                             LEXTRACE("ERROR ");
419                             LEXRETURN(ERROR);
420                         }
421
422 \+{WORD}                {
423                             /* netgroup */
424                             if (!fill(yytext, yyleng))
425                                 yyterminate();
426                             LEXTRACE("NETGROUP ");
427                             LEXRETURN(NETGROUP);
428                         }
429
430 \%:?({WORD}|{ID})       {
431                             /* group */
432                             if (!fill(yytext, yyleng))
433                                 yyterminate();
434                             LEXTRACE("USERGROUP ");
435                             LEXRETURN(USERGROUP);
436                         }
437
438 {IPV4ADDR}(\/{IPV4ADDR})? {
439                             if (!fill(yytext, yyleng))
440                                 yyterminate();
441                             LEXTRACE("NTWKADDR ");
442                             LEXRETURN(NTWKADDR);
443                         }
444
445 {IPV4ADDR}\/([12]?[0-9]|3[0-2]) {
446                             if (!fill(yytext, yyleng))
447                                 yyterminate();
448                             LEXTRACE("NTWKADDR ");
449                             LEXRETURN(NTWKADDR);
450                         }
451
452 {IPV6ADDR}(\/{IPV6ADDR})? {
453                             if (!ipv6_valid(yytext)) {
454                                 LEXTRACE("ERROR ");
455                                 LEXRETURN(ERROR);
456                             }
457                             if (!fill(yytext, yyleng))
458                                 yyterminate();
459                             LEXTRACE("NTWKADDR ");
460                             LEXRETURN(NTWKADDR);
461                         }
462
463 {IPV6ADDR}\/([0-9]|[1-9][0-9]|1[01][0-9]|12[0-8]) {
464                             if (!ipv6_valid(yytext)) {
465                                 LEXTRACE("ERROR ");
466                                 LEXRETURN(ERROR);
467                             }
468                             if (!fill(yytext, yyleng))
469                                 yyterminate();
470                             LEXTRACE("NTWKADDR ");
471                             LEXRETURN(NTWKADDR);
472                         }
473
474 ALL {
475                             LEXTRACE("ALL ");
476                             LEXRETURN(ALL);
477
478                         }
479
480 <INITIAL>ROLE {
481 #ifdef HAVE_SELINUX
482                             LEXTRACE("ROLE ");
483                             LEXRETURN(ROLE);
484 #else
485                             goto got_alias;
486 #endif
487                         }
488
489 <INITIAL>TYPE {
490 #ifdef HAVE_SELINUX
491                             LEXTRACE("TYPE ");
492                             LEXRETURN(TYPE);
493 #else
494                             goto got_alias;
495 #endif
496                         }
497
498 [[:upper:]][[:upper:][:digit:]_]* {
499 #ifndef HAVE_SELINUX
500                         got_alias:
501 #endif
502                             if (!fill(yytext, yyleng))
503                                 yyterminate();
504                             LEXTRACE("ALIAS ");
505                             LEXRETURN(ALIAS);
506                         }
507
508 <GOTDEFS>({PATH}|sudoedit) {
509                             /* no command args allowed for Defaults!/path */
510                             if (!fill_cmnd(yytext, yyleng))
511                                 yyterminate();
512                             LEXTRACE("COMMAND ");
513                             LEXRETURN(COMMAND);
514                         }
515
516 sudoedit                {
517                             BEGIN GOTCMND;
518                             LEXTRACE("COMMAND ");
519                             if (!fill_cmnd(yytext, yyleng))
520                                 yyterminate();
521                         }                       /* sudo -e */
522
523 {PATH}                  {
524                             /* directories can't have args... */
525                             if (yytext[yyleng - 1] == '/') {
526                                 LEXTRACE("COMMAND ");
527                                 if (!fill_cmnd(yytext, yyleng))
528                                     yyterminate();
529                                 LEXRETURN(COMMAND);
530                             } else {
531                                 BEGIN GOTCMND;
532                                 LEXTRACE("COMMAND ");
533                                 if (!fill_cmnd(yytext, yyleng))
534                                     yyterminate();
535                             }
536                         }                       /* a pathname */
537
538 <INITIAL,GOTDEFS>\" {
539                             LEXTRACE("BEGINSTR ");
540                             yylval.string = NULL;
541                             prev_state = YY_START;
542                             BEGIN INSTR;
543                         }
544
545 <INITIAL,GOTDEFS>({ID}|{WORD}) {
546                             /* a word */
547                             if (!fill(yytext, yyleng))
548                                 yyterminate();
549                             LEXTRACE("WORD(5) ");
550                             LEXRETURN(WORD);
551                         }
552
553 \(                      {
554                             LEXTRACE("( ");
555                             LEXRETURN('(');
556                         }
557
558 \)                      {
559                             LEXTRACE(") ");
560                             LEXRETURN(')');
561                         }
562
563 ,                       {
564                             LEXTRACE(", ");
565                             LEXRETURN(',');
566                         }                       /* return ',' */
567
568 =                       {
569                             LEXTRACE("= ");
570                             LEXRETURN('=');
571                         }                       /* return '=' */
572
573 :                       {
574                             LEXTRACE(": ");
575                             LEXRETURN(':');
576                         }                       /* return ':' */
577
578 <*>!+                   {
579                             if (yyleng & 1) {
580                                 LEXTRACE("!");
581                                 LEXRETURN('!'); /* return '!' */
582                             }
583                         }
584
585 <*>\n                   {
586                             if (YY_START == INSTR) {
587                                 LEXTRACE("ERROR ");
588                                 LEXRETURN(ERROR);       /* line break in string */
589                             }
590                             BEGIN INITIAL;
591                             sudolineno++;
592                             continued = false;
593                             LEXTRACE("\n");
594                             LEXRETURN(COMMENT);
595                         }                       /* return newline */
596
597 <*>[[:blank:]]+         {                       /* throw away space/tabs */
598                             sawspace = true;    /* but remember for fill_args */
599                         }
600
601 <*>\\[[:blank:]]*\n     {
602                             sawspace = true;    /* remember for fill_args */
603                             sudolineno++;
604                             continued = true;
605                         }                       /* throw away EOL after \ */
606
607 <INITIAL,STARTDEFS,INDEFS>#(-[^\n0-9].*|[^\n0-9-].*)?\n {
608                             BEGIN INITIAL;
609                             sudolineno++;
610                             continued = false;
611                             LEXTRACE("#\n");
612                             LEXRETURN(COMMENT);
613                         }                       /* comment, not uid/gid */
614
615 <*>.                    {
616                             LEXTRACE("ERROR ");
617                             LEXRETURN(ERROR);
618                         }       /* parse error */
619
620 <*><<EOF>>              {
621                             if (YY_START != INITIAL) {
622                                 BEGIN INITIAL;
623                                 LEXTRACE("ERROR ");
624                                 LEXRETURN(ERROR);
625                             }
626                             if (!pop_include())
627                                 yyterminate();
628                         }
629
630 %%
631 struct path_list {
632     char *path;
633     struct path_list *next;
634 };
635
636 struct include_stack {
637     YY_BUFFER_STATE bs;
638     char *path;
639     struct path_list *more; /* more files in case of includedir */
640     int lineno;
641     bool keepopen;
642 };
643
644 static int
645 pl_compare(const void *v1, const void *v2)
646 {
647     const struct path_list * const *p1 = v1;
648     const struct path_list * const *p2 = v2;
649
650     return strcmp((*p1)->path, (*p2)->path);
651 }
652
653 static char *
654 switch_dir(struct include_stack *stack, char *dirpath)
655 {
656     DIR *dir;
657     int i, count = 0;
658     char *path = NULL;
659     struct dirent *dent;
660     struct stat sb;
661     struct path_list *pl, *first = NULL;
662     struct path_list **sorted = NULL;
663     debug_decl(switch_dir, SUDO_DEBUG_PARSER)
664
665     if (!(dir = opendir(dirpath))) {
666         if (errno != ENOENT) {
667             char *errbuf;
668             if (asprintf(&errbuf, _("%s: %s"), dirpath, strerror(errno)) != -1) {
669                 yyerror(errbuf);
670                 free(errbuf);
671             } else {
672                 yyerror(_("unable to allocate memory"));
673             }
674         }
675         goto done;
676     }
677     while ((dent = readdir(dir))) {
678         /* Ignore files that end in '~' or have a '.' in them. */
679         if (dent->d_name[0] == '\0' || dent->d_name[NAMLEN(dent) - 1] == '~'
680             || strchr(dent->d_name, '.') != NULL) {
681             continue;
682         }
683         if (asprintf(&path, "%s/%s", dirpath, dent->d_name) == -1) {
684             closedir(dir);
685             goto bad;
686         }
687         if (stat(path, &sb) != 0 || !S_ISREG(sb.st_mode)) {
688             efree(path);
689             path = NULL;
690             continue;
691         }
692         pl = malloc(sizeof(*pl));
693         if (pl == NULL)
694             goto bad;
695         pl->path = path;
696         pl->next = first;
697         first = pl;
698         count++;
699     }
700     closedir(dir);
701
702     if (count == 0)
703         goto done;
704
705     /* Sort the list as an array. */
706     sorted = malloc(sizeof(*sorted) * count);
707     if (sorted == NULL)
708         goto bad;
709     pl = first;
710     for (i = 0; i < count; i++) {
711         sorted[i] = pl;
712         pl = pl->next;
713     }
714     qsort(sorted, count, sizeof(*sorted), pl_compare);
715
716     /* Apply sorting to the list. */
717     first = sorted[0];
718     sorted[count - 1]->next = NULL;
719     for (i = 1; i < count; i++)
720         sorted[i - 1]->next = sorted[i];
721     efree(sorted);
722
723     /* Pull out the first element for parsing, leave the rest for later. */
724     if (count) {
725         path = first->path;
726         pl = first->next;
727         efree(first);
728         stack->more = pl;
729     } else {
730         path = NULL;
731     }
732 done:
733     efree(dirpath);
734     debug_return_str(path);
735 bad:
736     while (first != NULL) {
737         pl = first;
738         first = pl->next;
739         free(pl->path);
740         free(pl);
741     }
742     efree(sorted);
743     efree(dirpath);
744     efree(path);
745     debug_return_str(NULL);
746 }
747
748 #define MAX_SUDOERS_DEPTH       128
749 #define SUDOERS_STACK_INCREMENT 16
750
751 static size_t istacksize, idepth;
752 static struct include_stack *istack;
753 static bool keepopen;
754
755 void
756 init_lexer(void)
757 {
758     struct path_list *pl;
759     debug_decl(init_lexer, SUDO_DEBUG_PARSER)
760
761     while (idepth) {
762         idepth--;
763         while ((pl = istack[idepth].more) != NULL) {
764             istack[idepth].more = pl->next;
765             efree(pl->path);
766             efree(pl);
767         }
768         efree(istack[idepth].path);
769         if (idepth && !istack[idepth].keepopen)
770             fclose(istack[idepth].bs->yy_input_file);
771         yy_delete_buffer(istack[idepth].bs);
772     }
773     efree(istack);
774     istack = NULL;
775     istacksize = idepth = 0;
776     sudolineno = 1;
777     keepopen = false;
778     sawspace = false;
779     continued = false;
780     prev_state = INITIAL;
781
782     debug_return;
783 }
784
785 static bool
786 _push_include(char *path, bool isdir)
787 {
788     struct path_list *pl;
789     FILE *fp;
790     debug_decl(_push_include, SUDO_DEBUG_PARSER)
791
792     /* push current state onto stack */
793     if (idepth >= istacksize) {
794         if (idepth > MAX_SUDOERS_DEPTH) {
795             yyerror(_("too many levels of includes"));
796             debug_return_bool(false);
797         }
798         istacksize += SUDOERS_STACK_INCREMENT;
799         istack = (struct include_stack *) realloc(istack,
800             sizeof(*istack) * istacksize);
801         if (istack == NULL) {
802             yyerror(_("unable to allocate memory"));
803             debug_return_bool(false);
804         }
805     }
806     if (isdir) {
807         if (!(path = switch_dir(&istack[idepth], path))) {
808             /* switch_dir() called yyerror() for us */
809             debug_return_bool(false);
810         }
811         while ((fp = open_sudoers(path, false, &keepopen)) == NULL) {
812             /* Unable to open path in includedir, go to next one, if any. */
813             efree(path);
814             if ((pl = istack[idepth].more) == NULL)
815                 debug_return_bool(false);
816             path = pl->path;
817             istack[idepth].more = pl->next;
818             efree(pl);
819         }
820     } else {
821         if ((fp = open_sudoers(path, true, &keepopen)) == NULL) {
822             char *errbuf;
823             if (asprintf(&errbuf, _("%s: %s"), path, strerror(errno)) != -1) {
824                 yyerror(errbuf);
825                 free(errbuf);
826             } else {
827                 yyerror(_("unable to allocate memory"));
828             }
829             debug_return_bool(false);
830         }
831         istack[idepth].more = NULL;
832     }
833     /* Push the old (current) file and open the new one. */
834     istack[idepth].path = sudoers; /* push old path */
835     istack[idepth].bs = YY_CURRENT_BUFFER;
836     istack[idepth].lineno = sudolineno;
837     istack[idepth].keepopen = keepopen;
838     idepth++;
839     sudolineno = 1;
840     sudoers = path;
841     yy_switch_to_buffer(yy_create_buffer(fp, YY_BUF_SIZE));
842
843     debug_return_bool(true);
844 }
845
846 static bool
847 pop_include(void)
848 {
849     struct path_list *pl;
850     FILE *fp;
851     debug_decl(pop_include, SUDO_DEBUG_PARSER)
852
853     if (idepth == 0)
854         debug_return_bool(false);
855
856     if (!keepopen)
857         fclose(YY_CURRENT_BUFFER->yy_input_file);
858     yy_delete_buffer(YY_CURRENT_BUFFER);
859     /* If we are in an include dir, move to the next file. */
860     while ((pl = istack[idepth - 1].more) != NULL) {
861         fp = open_sudoers(pl->path, false, &keepopen);
862         if (fp != NULL) {
863             istack[idepth - 1].more = pl->next;
864             efree(sudoers);
865             sudoers = pl->path;
866             sudolineno = 1;
867             yy_switch_to_buffer(yy_create_buffer(fp, YY_BUF_SIZE));
868             efree(pl);
869             break;
870         }
871         /* Unable to open path in include dir, go to next one. */
872         istack[idepth - 1].more = pl->next;
873         efree(pl->path);
874         efree(pl);
875     }
876     /* If no path list, just pop the last dir on the stack. */
877     if (pl == NULL) {
878         idepth--;
879         yy_switch_to_buffer(istack[idepth].bs);
880         efree(sudoers);
881         sudoers = istack[idepth].path;
882         sudolineno = istack[idepth].lineno;
883         keepopen = istack[idepth].keepopen;
884     }
885     debug_return_bool(true);
886 }
887
888 static char *
889 parse_include(char *base)
890 {
891     char *cp, *ep, *path, *pp;
892     int dirlen = 0, len = 0, subst = 0;
893     size_t shost_len = 0;
894     debug_decl(parse_include, SUDO_DEBUG_PARSER)
895
896     /* Pull out path from #include line. */
897     cp = base + sizeof("#include");
898     if (*cp == 'i')
899         cp += 3; /* includedir */
900     while (isblank((unsigned char) *cp))
901         cp++;
902     ep = cp;
903     while (*ep != '\0' && !isspace((unsigned char) *ep)) {
904         if (ep[0] == '%' && ep[1] == 'h') {
905             shost_len = strlen(user_shost);
906             len += shost_len - 2;
907             subst = 1;
908         }
909         ep++;
910     }
911
912     /* Relative paths are located in the same dir as the sudoers file. */
913     if (*cp != '/') {
914         char *dirend = strrchr(sudoers, '/');
915         if (dirend != NULL)
916             dirlen = (int)(dirend - sudoers) + 1;
917     }
918
919     /* Make a copy of the fully-qualified path and return it. */
920     len += (int)(ep - cp);
921     path = pp = malloc(len + dirlen + 1);
922     if (path == NULL) {
923         yyerror(_("unable to allocate memory"));
924         debug_return_str(NULL);
925     }
926     if (dirlen) {
927         memcpy(path, sudoers, dirlen);
928         pp += dirlen;
929     }
930     if (subst) {
931         /* substitute for %h */
932         while (cp < ep) {
933             if (cp[0] == '%' && cp[1] == 'h') {
934                 memcpy(pp, user_shost, shost_len);
935                 pp += shost_len;
936                 cp += 2;
937                 continue;
938             }
939             *pp++ = *cp++;
940         }
941         *pp = '\0';
942     } else {
943         memcpy(pp, cp, len);
944         pp[len] = '\0';
945     }
946
947     /* Push any excess characters (e.g. comment, newline) back to the lexer */
948     if (*ep != '\0')
949         yyless((int)(ep - base));
950
951     debug_return_str(path);
952 }
953
954 #ifdef TRACELEXER
955 static int
956 sudoers_trace_print(const char *msg)
957 {
958     return fputs(msg, stderr);
959 }
960 #else
961 static int
962 sudoers_trace_print(const char *msg)
963 {
964     static bool initialized;
965     static struct lbuf lbuf;
966
967     if (!initialized) {
968         initialized = true;
969         lbuf_init(&lbuf, NULL, 0, NULL, 0);
970     }
971
972     lbuf_append(&lbuf, "%s", msg);
973     /* XXX - assumes a final newline */
974     if (strchr(msg, '\n') != NULL)
975     {
976         sudo_debug_printf2(SUDO_DEBUG_PARSER|SUDO_DEBUG_DEBUG, "%s:%d %s",
977             sudoers, sudolineno, lbuf.buf);
978         lbuf.len = 0;
979     }
980     return 0;
981 }
982 #endif /* TRACELEXER */