]> granicus.if.org Git - apache/blob - modules/filters/mod_include.c
Do printf formatting properly.
[apache] / modules / filters / mod_include.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /*
60  * http_include.c: Handles the server-parsed HTML documents
61  * 
62  * Original by Rob McCool; substantial fixups by David Robinson;
63  * incorporated into the Apache module framework by rst.
64  * 
65  */
66 /* 
67  * sub key may be anything a Perl*Handler can be:
68  * subroutine name, package name (defaults to package::handler),
69  * Class->method call or anoymous sub {}
70  *
71  * Child <!--#perl sub="sub {print $$}" --> accessed
72  * <!--#perl sub="sub {print ++$Access::Cnt }" --> times. <br>
73  *
74  * <!--#perl arg="one" sub="mymod::includer" -->
75  *
76  * -Doug MacEachern
77  */
78
79 #define CORE_PRIVATE
80
81 #ifdef USE_PERL_SSI
82 #include "config.h"
83 #undef VOIDUSED
84 #ifdef USE_SFIO
85 #undef USE_SFIO
86 #define USE_STDIO
87 #endif
88 #include "modules/perl/mod_perl.h"
89 #else
90 #include "ap_config.h"
91 #include "httpd.h"
92 #include "http_config.h"
93 #include "http_request.h"
94 #include "http_core.h"
95 #include "http_protocol.h"
96 #include "http_log.h"
97 #include "http_main.h"
98 #include "util_script.h"
99 #include "http_core.h"
100 #include <string.h>
101 #ifdef HAVE_PWD_H
102 #include <pwd.h>
103 #endif
104 #endif
105 #include "util_ebcdic.h"
106
107 #define STARTING_SEQUENCE "<!--#"
108 #define ENDING_SEQUENCE "-->"
109 #define DEFAULT_ERROR_MSG "[an error occurred while processing this directive]"
110 #define DEFAULT_TIME_FORMAT "%A, %d-%b-%Y %H:%M:%S %Z"
111 #define SIZEFMT_BYTES 0
112 #define SIZEFMT_KMG 1
113 #ifdef CHARSET_EBCDIC
114 #define RAW_ASCII_CHAR(ch)  ap_xlate_conv_byte(ap_hdrs_from_ascii, (unsigned char)ch)
115 #else /*CHARSET_EBCDIC*/
116 #define RAW_ASCII_CHAR(ch)  (ch)
117 #endif /*CHARSET_EBCDIC*/
118
119 module MODULE_VAR_EXPORT includes_module;
120
121 /* just need some arbitrary non-NULL pointer which can't also be a request_rec */
122 #define NESTED_INCLUDE_MAGIC    (&includes_module)
123
124 /* TODO: changing directory should be handled by CreateProcess */
125 #define ap_chdir_file(x) do {} while(0)
126
127 /* ------------------------ Environment function -------------------------- */
128
129 /* XXX: could use ap_table_overlap here */
130 static void add_include_vars(request_rec *r, char *timefmt)
131 {
132 #ifndef WIN32
133     struct passwd *pw;
134 #endif /* ndef WIN32 */
135     ap_table_t *e = r->subprocess_env;
136     char *t;
137     ap_time_t date = r->request_time;
138
139     ap_table_setn(e, "DATE_LOCAL", ap_ht_time(r->pool, date, timefmt, 0));
140     ap_table_setn(e, "DATE_GMT", ap_ht_time(r->pool, date, timefmt, 1));
141     ap_table_setn(e, "LAST_MODIFIED",
142               ap_ht_time(r->pool, r->finfo.mtime, timefmt, 0));
143     ap_table_setn(e, "DOCUMENT_URI", r->uri);
144     ap_table_setn(e, "DOCUMENT_PATH_INFO", r->path_info);
145 #ifndef WIN32
146     pw = getpwuid(r->finfo.user);
147     if (pw) {
148         ap_table_setn(e, "USER_NAME", ap_pstrdup(r->pool, pw->pw_name));
149     }
150     else {
151         ap_table_setn(e, "USER_NAME", ap_psprintf(r->pool, "user#%lu",
152                     (unsigned long) r->finfo.user));
153     }
154 #endif /* ndef WIN32 */
155
156     if ((t = strrchr(r->filename, '/'))) {
157         ap_table_setn(e, "DOCUMENT_NAME", ++t);
158     }
159     else {
160         ap_table_setn(e, "DOCUMENT_NAME", r->uri);
161     }
162     if (r->args) {
163         char *arg_copy = ap_pstrdup(r->pool, r->args);
164
165         ap_unescape_url(arg_copy);
166         ap_table_setn(e, "QUERY_STRING_UNESCAPED",
167                   ap_escape_shell_cmd(r->pool, arg_copy));
168     }
169 }
170
171
172
173 /* --------------------------- Parser functions --------------------------- */
174
175 #define OUTBUFSIZE 4096
176 /* PUT_CHAR and FLUSH_BUF currently only work within the scope of 
177  * find_string(); they are hacks to avoid calling rputc for each and
178  * every character output.  A common set of buffering calls for this 
179  * type of output SHOULD be implemented.
180  */
181 #define PUT_CHAR(c,r) \
182  { \
183     outbuf[outind++] = c; \
184     if (outind == OUTBUFSIZE) { \
185         FLUSH_BUF(r) \
186     }; \
187  }
188
189 /* there SHOULD be some error checking on the return value of
190  * rwrite, however it is unclear what the API for rwrite returning
191  * errors is and little can really be done to help the error in 
192  * any case.
193  */
194 #define FLUSH_BUF(r) \
195  { \
196    ap_rwrite(outbuf, outind, r); \
197    outind = 0; \
198  }
199
200 /*
201  * f: file handle being read from
202  * c: character to read into
203  * ret: return value to use if input fails
204  * r: current request_rec
205  *
206  * This macro is redefined after find_string() for historical reasons
207  * to avoid too many code changes.  This is one of the many things
208  * that should be fixed.
209  */
210 #define GET_CHAR(f,c,ret,r) \
211  { \
212    ap_status_t status = ap_getc(&c, f); \
213    if (status != APR_SUCCESS) { /* either EOF or error -- needs error handling if latter */ \
214        if (status != APR_EOF) { \
215            ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, \
216                         "encountered error in GET_CHAR macro, " \
217                         "mod_include."); \
218        } \
219        FLUSH_BUF(r); \
220        ap_close(f); \
221        return ret; \
222    } \
223  }
224
225 static int find_string(ap_file_t *in, const char *str, request_rec *r, int printing)
226 {
227     int x, l = strlen(str), p;
228     char outbuf[OUTBUFSIZE];
229     int outind = 0;
230     char c;
231
232     p = 0;
233     while (1) {
234         GET_CHAR(in, c, 1, r);
235         if (c == str[p]) {
236             if ((++p) == l) {
237                 FLUSH_BUF(r);
238                 return 0;
239             }
240         }
241         else {
242             if (printing) {
243                 for (x = 0; x < p; x++) {
244                     PUT_CHAR(str[x], r);
245                 }
246                 PUT_CHAR(c, r);
247             }
248             p = 0;
249         }
250     }
251 }
252
253 #undef FLUSH_BUF
254 #undef PUT_CHAR
255 #undef GET_CHAR
256 #define GET_CHAR(f,c,r,p) \
257  { \
258    ap_status_t status = ap_getc(&c, f); \
259    if (status != APR_SUCCESS) { /* either EOF or error -- needs error handling if latter */ \
260        if (status != APR_EOF) { \
261            ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, \
262                         "encountered error in GET_CHAR macro, " \
263                         "mod_include."); \
264        } \
265        ap_close(f); \
266        return r; \
267    } \
268  }
269
270 /*
271  * decodes a string containing html entities or numeric character references.
272  * 's' is overwritten with the decoded string.
273  * If 's' is syntatically incorrect, then the followed fixups will be made:
274  *   unknown entities will be left undecoded;
275  *   references to unused numeric characters will be deleted.
276  *   In particular, &#00; will not be decoded, but will be deleted.
277  *
278  * drtr
279  */
280
281 /* maximum length of any ISO-LATIN-1 HTML entity name. */
282 #define MAXENTLEN (6)
283
284 /* The following is a shrinking transformation, therefore safe. */
285
286 static void decodehtml(char *s)
287 {
288     int val, i, j;
289     char *p = s;
290     const char *ents;
291     static const char * const entlist[MAXENTLEN + 1] =
292     {
293         NULL,                   /* 0 */
294         NULL,                   /* 1 */
295         "lt\074gt\076",         /* 2 */
296         "amp\046ETH\320eth\360",        /* 3 */
297         "quot\042Auml\304Euml\313Iuml\317Ouml\326Uuml\334auml\344euml\353\
298 iuml\357ouml\366uuml\374yuml\377",      /* 4 */
299         "Acirc\302Aring\305AElig\306Ecirc\312Icirc\316Ocirc\324Ucirc\333\
300 THORN\336szlig\337acirc\342aring\345aelig\346ecirc\352icirc\356ocirc\364\
301 ucirc\373thorn\376",            /* 5 */
302         "Agrave\300Aacute\301Atilde\303Ccedil\307Egrave\310Eacute\311\
303 Igrave\314Iacute\315Ntilde\321Ograve\322Oacute\323Otilde\325Oslash\330\
304 Ugrave\331Uacute\332Yacute\335agrave\340aacute\341atilde\343ccedil\347\
305 egrave\350eacute\351igrave\354iacute\355ntilde\361ograve\362oacute\363\
306 otilde\365oslash\370ugrave\371uacute\372yacute\375"     /* 6 */
307     };
308
309     for (; *s != '\0'; s++, p++) {
310         if (*s != '&') {
311             *p = *s;
312             continue;
313         }
314         /* find end of entity */
315         for (i = 1; s[i] != ';' && s[i] != '\0'; i++) {
316             continue;
317         }
318
319         if (s[i] == '\0') {     /* treat as normal data */
320             *p = *s;
321             continue;
322         }
323
324         /* is it numeric ? */
325         if (s[1] == '#') {
326             for (j = 2, val = 0; j < i && ap_isdigit(s[j]); j++) {
327                 val = val * 10 + s[j] - '0';
328             }
329             s += i;
330             if (j < i || val <= 8 || (val >= 11 && val <= 31) ||
331                 (val >= 127 && val <= 160) || val >= 256) {
332                 p--;            /* no data to output */
333             }
334             else {
335                 *p = RAW_ASCII_CHAR(val);
336             }
337         }
338         else {
339             j = i - 1;
340             if (j > MAXENTLEN || entlist[j] == NULL) {
341                 /* wrong length */
342                 *p = '&';
343                 continue;       /* skip it */
344             }
345             for (ents = entlist[j]; *ents != '\0'; ents += i) {
346                 if (strncmp(s + 1, ents, j) == 0) {
347                     break;
348                 }
349             }
350
351             if (*ents == '\0') {
352                 *p = '&';       /* unknown */
353             }
354             else {
355                 *p = RAW_ASCII_CHAR(((const unsigned char *) ents)[j]);
356                 s += i;
357             }
358         }
359     }
360
361     *p = '\0';
362 }
363
364 /*
365  * extract the next tag name and value.
366  * if there are no more tags, set the tag name to 'done'
367  * the tag value is html decoded if dodecode is non-zero
368  */
369
370 static char *get_tag(ap_pool_t *p, ap_file_t *in, char *tag, int tagbuf_len, int dodecode)
371 {
372     char *t = tag, *tag_val, c, term;
373
374     /* makes code below a little less cluttered */
375     --tagbuf_len;
376
377     do {                        /* skip whitespace */
378         GET_CHAR(in, c, NULL, p);
379     } while (ap_isspace(c));
380
381     /* tags can't start with - */
382     if (c == '-') {
383         GET_CHAR(in, c, NULL, p);
384         if (c == '-') {
385             do {
386                 GET_CHAR(in, c, NULL, p);
387             } while (ap_isspace(c));
388             if (c == '>') {
389                 ap_cpystrn(tag, "done", tagbuf_len);
390                 return tag;
391             }
392         }
393         return NULL;            /* failed */
394     }
395
396     /* find end of tag name */
397     while (1) {
398         if (t - tag == tagbuf_len) {
399             *t = '\0';
400             return NULL;
401         }
402         if (c == '=' || ap_isspace(c)) {
403             break;
404         }
405         *(t++) = ap_tolower(c);
406         GET_CHAR(in, c, NULL, p);
407     }
408
409     *t++ = '\0';
410     tag_val = t;
411
412     while (ap_isspace(c)) {
413         GET_CHAR(in, c, NULL, p);       /* space before = */
414     }
415     if (c != '=') {
416         ap_ungetc(c, in);
417         return NULL;
418     }
419
420     do {
421         GET_CHAR(in, c, NULL, p);       /* space after = */
422     } while (ap_isspace(c));
423
424     /* we should allow a 'name' as a value */
425
426     if (c != '"' && c != '\'') {
427         return NULL;
428     }
429     term = c;
430     while (1) {
431         GET_CHAR(in, c, NULL, p);
432         if (t - tag == tagbuf_len) {
433             *t = '\0';
434             return NULL;
435         }
436 /* Want to accept \" as a valid character within a string. */
437         if (c == '\\') {
438             *(t++) = c;         /* Add backslash */
439             GET_CHAR(in, c, NULL, p);
440             if (c == term) {    /* Only if */
441                 *(--t) = c;     /* Replace backslash ONLY for terminator */
442             }
443         }
444         else if (c == term) {
445             break;
446         }
447         *(t++) = c;
448     }
449     *t = '\0';
450     if (dodecode) {
451         decodehtml(tag_val);
452     }
453     return ap_pstrdup(p, tag_val);
454 }
455
456 static int get_directive(ap_file_t *in, char *dest, size_t len, ap_pool_t *p)
457 {
458     char *d = dest;
459     char c;
460
461     /* make room for nul terminator */
462     --len;
463
464     /* skip initial whitespace */
465     while (1) {
466         GET_CHAR(in, c, 1, p);
467         if (!ap_isspace(c)) {
468             break;
469         }
470     }
471     /* now get directive */
472     while (1) {
473         if (d - dest == len) {
474             return 1;
475         }
476         *d++ = ap_tolower(c);
477         GET_CHAR(in, c, 1, p);
478         if (ap_isspace(c)) {
479             break;
480         }
481     }
482     *d = '\0';
483     return 0;
484 }
485
486 /*
487  * Do variable substitution on strings
488  */
489 static void parse_string(request_rec *r, const char *in, char *out,
490                         size_t length, int leave_name)
491 {
492     char ch;
493     char *next = out;
494     char *end_out;
495
496     /* leave room for nul terminator */
497     end_out = out + length - 1;
498
499     while ((ch = *in++) != '\0') {
500         switch (ch) {
501         case '\\':
502             if (next == end_out) {
503                 /* truncated */
504                 *next = '\0';
505                 return;
506             }
507             if (*in == '$') {
508                 *next++ = *in++;
509             }
510             else {
511                 *next++ = ch;
512             }
513             break;
514         case '$':
515             {
516                 char var[MAX_STRING_LEN];
517                 const char *start_of_var_name;
518                 const char *end_of_var_name;    /* end of var name + 1 */
519                 const char *expansion;
520                 const char *val;
521                 size_t l;
522
523                 /* guess that the expansion won't happen */
524                 expansion = in - 1;
525                 if (*in == '{') {
526                     ++in;
527                     start_of_var_name = in;
528                     in = strchr(in, '}');
529                     if (in == NULL) {
530                         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
531                                     0, r, "Missing '}' on variable \"%s\"",
532                                     expansion);
533                         *next = '\0';
534                         return;
535                     }
536                     end_of_var_name = in;
537                     ++in;
538                 }
539                 else {
540                     start_of_var_name = in;
541                     while (ap_isalnum(*in) || *in == '_') {
542                         ++in;
543                     }
544                     end_of_var_name = in;
545                 }
546                 /* what a pain, too bad there's no table_getn where you can
547                  * pass a non-nul terminated string */
548                 l = end_of_var_name - start_of_var_name;
549                 if (l != 0) {
550                     l = (l > sizeof(var) - 1) ? (sizeof(var) - 1) : l;
551                     memcpy(var, start_of_var_name, l);
552                     var[l] = '\0';
553
554                     val = ap_table_get(r->subprocess_env, var);
555                     if (val) {
556                         expansion = val;
557                         l = strlen(expansion);
558                     }
559                     else if (leave_name) {
560                         l = in - expansion;
561                     }
562                     else {
563                         break;  /* no expansion to be done */
564                     }
565                 }
566                 else {
567                     /* zero-length variable name causes just the $ to be copied */
568                     l = 1;
569                 }
570                 l = (l > end_out - next) ? (end_out - next) : l;
571                 memcpy(next, expansion, l);
572                 next += l;
573                 break;
574             }
575         default:
576             if (next == end_out) {
577                 /* truncated */
578                 *next = '\0';
579                 return;
580             }
581             *next++ = ch;
582             break;
583         }
584     }
585     *next = '\0';
586     return;
587 }
588
589 /* --------------------------- Action handlers ---------------------------- */
590
591 static int include_cgi(char *s, request_rec *r)
592 {
593     request_rec *rr = ap_sub_req_lookup_uri(s, r);
594     int rr_status;
595
596     if (rr->status != HTTP_OK) {
597         return -1;
598     }
599
600     /* No hardwired path info or query allowed */
601
602     if ((rr->path_info && rr->path_info[0]) || rr->args) {
603         return -1;
604     }
605     if (rr->finfo.protection == 0) {
606         return -1;
607     }
608
609     /* Script gets parameters of the *document*, for back compatibility */
610
611     rr->path_info = r->path_info;       /* hard to get right; see mod_cgi.c */
612     rr->args = r->args;
613
614     /* Force sub_req to be treated as a CGI request, even if ordinary
615      * typing rules would have called it something else.
616      */
617
618     rr->content_type = CGI_MAGIC_TYPE;
619
620     /* Run it. */
621
622     rr_status = ap_run_sub_req(rr);
623     if (ap_is_HTTP_REDIRECT(rr_status)) {
624         const char *location = ap_table_get(rr->headers_out, "Location");
625         location = ap_escape_html(rr->pool, location);
626         ap_rvputs(r, "<A HREF=\"", location, "\">", location, "</A>", NULL);
627     }
628
629     ap_destroy_sub_req(rr);
630     ap_chdir_file(r->filename);
631
632     return 0;
633 }
634
635 /* ensure that path is relative, and does not contain ".." elements
636  * ensentially ensure that it does not match the regex:
637  * (^/|(^|/)\.\.(/|$))
638  * XXX: this needs os abstraction... consider c:..\foo in win32
639  */
640 static int is_only_below(const char *path)
641 {
642 #ifdef HAVE_DRIVE_LETTERS
643     if (path[1] == ':')
644         return 0;
645 #endif
646     if (path[0] == '/') {
647         return 0;
648     }
649     if (path[0] == '.' && path[1] == '.'
650         && (path[2] == '\0' || path[2] == '/')) {
651         return 0;
652     }
653     while (*path) {
654         if (*path == '/' && path[1] == '.' && path[2] == '.'
655             && (path[3] == '\0' || path[3] == '/')) {
656             return 0;
657         }
658         ++path;
659     }
660     return 1;
661 }
662
663 static int handle_include(ap_file_t *in, request_rec *r, const char *error, int noexec)
664 {
665     char tag[MAX_STRING_LEN];
666     char parsed_string[MAX_STRING_LEN];
667     char *tag_val;
668
669     while (1) {
670         if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
671             return 1;
672         }
673         if (!strcmp(tag, "file") || !strcmp(tag, "virtual")) {
674             request_rec *rr = NULL;
675             char *error_fmt = NULL;
676
677             parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
678             if (tag[0] == 'f') {
679                 /* be safe; only files in this directory or below allowed */
680                 if (!is_only_below(parsed_string)) {
681                     error_fmt = "unable to include file \"%s\" "
682                                 "in parsed file %s";
683                 }
684                 else {
685                     rr = ap_sub_req_lookup_file(parsed_string, r);
686                 }
687             }
688             else {
689                 rr = ap_sub_req_lookup_uri(parsed_string, r);
690             }
691
692             if (!error_fmt && rr->status != HTTP_OK) {
693                 error_fmt = "unable to include \"%s\" in parsed file %s";
694             }
695
696             if (!error_fmt && noexec && rr->content_type
697                 && (strncmp(rr->content_type, "text/", 5))) {
698                 error_fmt = "unable to include potential exec \"%s\" "
699                     "in parsed file %s";
700             }
701             if (error_fmt == NULL) {
702                 /* try to avoid recursive includes.  We do this by walking
703                  * up the r->main list of subrequests, and at each level
704                  * walking back through any internal redirects.  At each
705                  * step, we compare the filenames and the URIs.  
706                  *
707                  * The filename comparison catches a recursive include
708                  * with an ever-changing URL, eg.
709                  * <!--#include virtual=
710                  *      "$REQUEST_URI/$QUERY_STRING?$QUERY_STRING/x"-->
711                  * which, although they would eventually be caught because
712                  * we have a limit on the length of files, etc., can 
713                  * recurse for a while.
714                  *
715                  * The URI comparison catches the case where the filename
716                  * is changed while processing the request, so the 
717                  * current name is never the same as any previous one.
718                  * This can happen with "DocumentRoot /foo" when you
719                  * request "/" on the server and it includes "/".
720                  * This only applies to modules such as mod_dir that 
721                  * (somewhat improperly) mess with r->filename outside 
722                  * of a filename translation phase.
723                  */
724                 int founddupe = 0;
725                 request_rec *p;
726                 for (p = r; p != NULL && !founddupe; p = p->main) {
727                     request_rec *q;
728                     for (q = p; q != NULL; q = q->prev) {
729                         if ( (strcmp(q->filename, rr->filename) == 0) ||
730                              (strcmp(q->uri, rr->uri) == 0) ){
731                             founddupe = 1;
732                             break;
733                         }
734                     }
735                 }
736
737                 if (p != NULL) {
738                     error_fmt = "Recursive include of \"%s\" "
739                         "in parsed file %s";
740                 }
741             }
742
743             /* see the Kludge in send_parsed_file for why */
744             if (rr) 
745                 ap_set_module_config(rr->request_config, &includes_module, r);
746
747             if (!error_fmt && ap_run_sub_req(rr)) {
748                 error_fmt = "unable to include \"%s\" in parsed file %s";
749             }
750             ap_chdir_file(r->filename);
751             if (error_fmt) {
752                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
753                             0, r, error_fmt, tag_val, r->filename);
754                 ap_rputs(error, r);
755             }
756
757             /* destroy the sub request if it's not a nested include */
758             if (rr != NULL
759                 && ap_get_module_config(rr->request_config, &includes_module)
760                     != NESTED_INCLUDE_MAGIC) {
761                 ap_destroy_sub_req(rr);
762             }
763         }
764         else if (!strcmp(tag, "done")) {
765             return 0;
766         }
767         else {
768             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
769                         "unknown parameter \"%s\" to tag include in %s",
770                         tag, r->filename);
771             ap_rputs(error, r);
772         }
773     }
774 }
775
776 typedef struct {
777 #ifdef TPF
778     TPF_FORK_CHILD t;
779 #endif
780     request_rec *r;
781     char *s;
782 } include_cmd_arg;
783
784
785
786 static ap_status_t build_argv_list(char ***argv, request_rec *r, ap_pool_t *p)
787 {
788     int numwords, x, idx;
789     char *w;
790     const char *args = r->args;
791
792     if (!args || !args[0] || strchr(args, '=')) {
793        numwords = 1;
794     }
795     else {
796         /* count the number of keywords */
797         for (x = 0, numwords = 1; args[x]; x++) {
798             if (args[x] == '+') {
799                 ++numwords;
800             }
801         }
802     }
803     /* Everything is - 1 to account for the first parameter which is the
804      * program name.  We didn't used to have to do this, but APR wants it.
805      */
806     if (numwords > APACHE_ARG_MAX - 1) {
807         numwords = APACHE_ARG_MAX - 1;  /* Truncate args to prevent overrun */
808     }
809     *argv = (char **) ap_palloc(p, (numwords + 2) * sizeof(char *));
810  
811     for (x = 1, idx = 1; x < numwords; x++) {
812         w = ap_getword_nulls(p, &args, '+');
813         ap_unescape_url(w);
814         (*argv)[idx++] = ap_escape_shell_cmd(p, w);
815     }
816     (*argv)[idx] = NULL;
817
818     return APR_SUCCESS;
819 }
820
821
822
823 static int include_cmd(char *s, request_rec *r)
824 {
825     include_cmd_arg arg;
826     BUFF *script_in;
827     ap_procattr_t *procattr;
828     ap_proc_t procnew;
829     ap_status_t rc;
830     ap_table_t *env = r->subprocess_env;
831     char **argv;
832     ap_file_t *file = NULL;
833     ap_iol *iol;
834 #if defined(RLIMIT_CPU)  || defined(RLIMIT_NPROC) || \
835     defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined (RLIMIT_AS)
836     core_dir_config *conf; 
837     conf = (core_dir_config *) ap_get_module_config(r->per_dir_config,
838                                                     &core_module);
839 #endif
840
841     arg.r = r;
842     arg.s = s;
843 #ifdef TPF
844     arg.t.filename = r->filename;
845     arg.t.subprocess_env = r->subprocess_env;
846     arg.t.prog_type = FORK_FILE;
847 #endif
848
849     if (r->path_info && r->path_info[0] != '\0') {
850         request_rec *pa_req;
851
852         ap_table_setn(env, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
853
854         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r);
855         if (pa_req->filename) {
856             ap_table_setn(env, "PATH_TRANSLATED",
857                       ap_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
858                               NULL));
859         }
860     }
861
862     if (r->args) {
863         char *arg_copy = ap_pstrdup(r->pool, r->args);
864
865         ap_table_setn(env, "QUERY_STRING", r->args);
866         ap_unescape_url(arg_copy);
867         ap_table_setn(env, "QUERY_STRING_UNESCAPED",
868                   ap_escape_shell_cmd(r->pool, arg_copy));
869     }
870
871     if ((ap_createprocattr_init(&procattr, r->pool) != APR_SUCCESS) ||
872         (ap_setprocattr_io(procattr, APR_NO_PIPE, 
873                            APR_FULL_BLOCK, APR_NO_PIPE) != APR_SUCCESS) ||
874         (ap_setprocattr_dir(procattr, ap_make_dirstr_parent(r->pool, r->filename)) != APR_SUCCESS) ||
875 #ifdef RLIMIT_CPU
876         ((rc = ap_setprocattr_limit(procattr, APR_LIMIT_CPU, conf->limit_cpu)) != APR_SUCCESS) ||
877 #endif
878 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
879         ((rc = ap_setprocattr_limit(procattr, APR_LIMIT_MEM, conf->limit_mem)) != APR_SUCCESS) ||
880 #endif
881 #ifdef RLIMIT_NPROC
882         ((rc = ap_setprocattr_limit(procattr, APR_LIMIT_NPROC, conf->limit_nproc)) != APR_SUCCESS) ||
883 #endif
884         (ap_setprocattr_cmdtype(procattr, APR_SHELLCMD) != APR_SUCCESS)) {
885         /* Something bad happened, tell the world. */
886         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
887             "couldn't initialize proc attributes: %s %s", r->filename, s);
888         rc = !APR_SUCCESS;
889     }
890     else {
891         build_argv_list(&argv, r, r->pool);
892         argv[0] = ap_pstrdup(r->pool, s);
893         rc = ap_create_process(&procnew, s, argv, ap_create_environment(r->pool, env), procattr, r->pool);
894
895         if (rc != APR_SUCCESS) {
896             /* Bad things happened. Everyone should have cleaned up. */
897             ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
898                         "couldn't create child process: %d: %s", rc, s);
899         }
900         else {
901             ap_note_subprocess(r->pool, &procnew, kill_after_timeout);
902             /* Fill in BUFF structure for parents pipe to child's stdout */
903             file = procnew.out;
904             iol = ap_create_file_iol(file);
905             if (!iol)
906                 return APR_EBADF;
907             script_in = ap_bcreate(r->pool, B_RD);
908             ap_bpush_iol(script_in, iol);
909             ap_send_fb(script_in, r);
910             ap_bclose(script_in);
911         }
912     }
913
914     return 0;
915 }
916
917 static int handle_exec(ap_file_t *in, request_rec *r, const char *error)
918 {
919     char tag[MAX_STRING_LEN];
920     char *tag_val;
921     char *file = r->filename;
922     char parsed_string[MAX_STRING_LEN];
923
924     while (1) {
925         if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
926             return 1;
927         }
928         if (!strcmp(tag, "cmd")) {
929             parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 1);
930             if (include_cmd(parsed_string, r) == -1) {
931                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
932                             "execution failure for parameter \"%s\" "
933                             "to tag exec in file %s",
934                             tag, r->filename);
935                 ap_rputs(error, r);
936             }
937             /* just in case some stooge changed directories */
938             ap_chdir_file(r->filename);
939         }
940         else if (!strcmp(tag, "cgi")) {
941             parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
942             if (include_cgi(parsed_string, r) == -1) {
943                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
944                             "invalid CGI ref \"%s\" in %s", tag_val, file);
945                 ap_rputs(error, r);
946             }
947             ap_chdir_file(r->filename);
948         }
949         else if (!strcmp(tag, "done")) {
950             return 0;
951         }
952         else {
953             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
954                         "unknown parameter \"%s\" to tag exec in %s",
955                         tag, file);
956             ap_rputs(error, r);
957         }
958     }
959
960 }
961
962 static int handle_echo(ap_file_t *in, request_rec *r, const char *error)
963 {
964     char tag[MAX_STRING_LEN];
965     char *tag_val;
966     enum {E_NONE, E_URL, E_ENTITY} encode;
967
968     encode = E_ENTITY;
969
970     while (1) {
971         if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
972             return 1;
973         }
974         if (!strcmp(tag, "var")) {
975             const char *val = ap_table_get(r->subprocess_env, tag_val);
976
977             if (val) {
978                 if (encode == E_NONE) {
979                     ap_rputs(val, r);
980                 }
981                 else if (encode == E_URL) {
982                     ap_rputs(ap_escape_uri(r->pool, val), r);
983                 }
984                 else if (encode == E_ENTITY) {
985                     ap_rputs(ap_escape_html(r->pool, val), r);
986                 }
987             }
988             else {
989                 ap_rputs("(none)", r);
990             }
991         }
992         else if (!strcmp(tag, "done")) {
993             return 0;
994         }
995         else if (!strcmp(tag, "encoding")) {
996             if (!strcasecmp(tag_val, "none")) encode = E_NONE;
997             else if (!strcasecmp(tag_val, "url")) encode = E_URL;
998             else if (!strcasecmp(tag_val, "entity")) encode = E_ENTITY;
999             else {
1000                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1001                             "unknown value \"%s\" to parameter \"encoding\" of "
1002                             "tag echo in %s",
1003                             tag_val, r->filename);
1004                 ap_rputs(error, r);
1005             }
1006         }
1007
1008         else {
1009             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1010                         "unknown parameter \"%s\" to tag echo in %s",
1011                         tag, r->filename);
1012             ap_rputs(error, r);
1013         }
1014     }
1015 }
1016
1017 #ifdef USE_PERL_SSI
1018 static int handle_perl(ap_file_t *in, request_rec *r, const char *error)
1019 {
1020     char tag[MAX_STRING_LEN];
1021     char parsed_string[MAX_STRING_LEN];
1022     char *tag_val;
1023     SV *sub = Nullsv;
1024     AV *av = newAV();
1025
1026     if (ap_allow_options(r) & OPT_INCNOEXEC) {
1027         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1028                       "#perl SSI disallowed by IncludesNoExec in %s",
1029                       r->filename);
1030         return DECLINED;
1031     }
1032     while (1) {
1033         if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
1034             break;
1035         }
1036         if (strnEQ(tag, "sub", 3)) {
1037             sub = newSVpv(tag_val, 0);
1038         }
1039         else if (strnEQ(tag, "arg", 3)) {
1040             parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
1041             av_push(av, newSVpv(parsed_string, 0));
1042         }
1043         else if (strnEQ(tag, "done", 4)) {
1044             break;
1045         }
1046     }
1047     perl_stdout2client(r);
1048     perl_setup_env(r);
1049     perl_call_handler(sub, r, av);
1050     return OK;
1051 }
1052 #endif
1053
1054 /* error and tf must point to a string with room for at 
1055  * least MAX_STRING_LEN characters 
1056  */
1057 static int handle_config(ap_file_t *in, request_rec *r, char *error, char *tf,
1058                          int *sizefmt)
1059 {
1060     char tag[MAX_STRING_LEN];
1061     char *tag_val;
1062     char parsed_string[MAX_STRING_LEN];
1063     ap_table_t *env = r->subprocess_env;
1064
1065     while (1) {
1066         if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 0))) {
1067             return 1;
1068         }
1069         if (!strcmp(tag, "errmsg")) {
1070             parse_string(r, tag_val, error, MAX_STRING_LEN, 0);
1071         }
1072         else if (!strcmp(tag, "timefmt")) {
1073             ap_time_t date = r->request_time;
1074
1075             parse_string(r, tag_val, tf, MAX_STRING_LEN, 0);
1076             ap_table_setn(env, "DATE_LOCAL", ap_ht_time(r->pool, date, tf, 0));
1077             ap_table_setn(env, "DATE_GMT", ap_ht_time(r->pool, date, tf, 1));
1078             ap_table_setn(env, "LAST_MODIFIED",
1079                       ap_ht_time(r->pool, r->finfo.mtime, tf, 0));
1080         }
1081         else if (!strcmp(tag, "sizefmt")) {
1082             parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
1083             decodehtml(parsed_string);
1084             if (!strcmp(parsed_string, "bytes")) {
1085                 *sizefmt = SIZEFMT_BYTES;
1086             }
1087             else if (!strcmp(parsed_string, "abbrev")) {
1088                 *sizefmt = SIZEFMT_KMG;
1089             }
1090         }
1091         else if (!strcmp(tag, "done")) {
1092             return 0;
1093         }
1094         else {
1095             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1096                         "unknown parameter \"%s\" to tag config in %s",
1097                         tag, r->filename);
1098             ap_rputs(error, r);
1099         }
1100     }
1101 }
1102
1103
1104 static int find_file(request_rec *r, const char *directive, const char *tag,
1105                      char *tag_val, ap_finfo_t *finfo, const char *error)
1106 {
1107     char *to_send = tag_val;
1108     request_rec *rr = NULL;
1109     int ret=0;
1110     char *error_fmt = NULL;
1111
1112     if (!strcmp(tag, "file")) {
1113         /* be safe; only files in this directory or below allowed */
1114         if (!is_only_below(tag_val)) {
1115             error_fmt = "unable to access file \"%s\" "
1116                         "in parsed file %s";
1117         }
1118         else {
1119             ap_getparents(tag_val);    /* get rid of any nasties */
1120             rr = ap_sub_req_lookup_file(tag_val, r);
1121
1122             if (rr->status == HTTP_OK && rr->finfo.protection != 0) {
1123                 to_send = rr->filename;
1124                 if (ap_stat(finfo, to_send, rr->pool) != APR_SUCCESS) {
1125                     error_fmt = "unable to get information about \"%s\" "
1126                         "in parsed file %s";
1127                 }
1128             }
1129             else {
1130                 error_fmt = "unable to lookup information about \"%s\" "
1131                             "in parsed file %s";
1132             }
1133         }
1134
1135         if (error_fmt) {
1136             ret = -1;
1137             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error_fmt, to_send, r->filename);
1138             ap_rputs(error, r);
1139         }
1140
1141         if (rr) ap_destroy_sub_req(rr);
1142         
1143         return ret;
1144     }
1145     else if (!strcmp(tag, "virtual")) {
1146         rr = ap_sub_req_lookup_uri(tag_val, r);
1147
1148         if (rr->status == HTTP_OK && rr->finfo.protection != 0) {
1149             memcpy((char *) finfo, (const char *) &rr->finfo,
1150                    sizeof(rr->finfo));
1151             ap_destroy_sub_req(rr);
1152             return 0;
1153         }
1154         else {
1155             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1156                         "unable to get information about \"%s\" "
1157                         "in parsed file %s",
1158                         tag_val, r->filename);
1159             ap_rputs(error, r);
1160             ap_destroy_sub_req(rr);
1161             return -1;
1162         }
1163     }
1164     else {
1165         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1166                     "unknown parameter \"%s\" to tag %s in %s",
1167                     tag, directive, r->filename);
1168         ap_rputs(error, r);
1169         return -1;
1170     }
1171 }
1172
1173
1174 static int handle_fsize(ap_file_t *in, request_rec *r, const char *error, int sizefmt)
1175 {
1176     char tag[MAX_STRING_LEN];
1177     char *tag_val;
1178     ap_finfo_t finfo;
1179     char parsed_string[MAX_STRING_LEN];
1180
1181     while (1) {
1182         if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
1183             return 1;
1184         }
1185         else if (!strcmp(tag, "done")) {
1186             return 0;
1187         }
1188         else {
1189             parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
1190             if (!find_file(r, "fsize", tag, parsed_string, &finfo, error)) {
1191                 if (sizefmt == SIZEFMT_KMG) {
1192                     ap_send_size(finfo.size, r);
1193                 }
1194                 else {
1195                     int l, x;
1196                     ap_snprintf(tag, sizeof(tag), "%" APR_OFF_T_FMT, finfo.size);
1197                     l = strlen(tag);    /* grrr */
1198                     for (x = 0; x < l; x++) {
1199                         if (x && (!((l - x) % 3))) {
1200                             ap_rputc(',', r);
1201                         }
1202                         ap_rputc(tag[x], r);
1203                     }
1204                 }
1205             }
1206         }
1207     }
1208 }
1209
1210 static int handle_flastmod(ap_file_t *in, request_rec *r, const char *error, const char *tf)
1211 {
1212     char tag[MAX_STRING_LEN];
1213     char *tag_val;
1214     ap_finfo_t finfo;
1215     char parsed_string[MAX_STRING_LEN];
1216
1217     while (1) {
1218         if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
1219             return 1;
1220         }
1221         else if (!strcmp(tag, "done")) {
1222             return 0;
1223         }
1224         else {
1225             parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
1226             if (!find_file(r, "flastmod", tag, parsed_string, &finfo, error)) {
1227                 ap_rputs(ap_ht_time(r->pool, finfo.mtime, tf, 0), r);
1228             }
1229         }
1230     }
1231 }
1232
1233 static int re_check(request_rec *r, char *string, char *rexp)
1234 {
1235     regex_t *compiled;
1236     int regex_error;
1237
1238     compiled = ap_pregcomp(r->pool, rexp, REG_EXTENDED | REG_NOSUB);
1239     if (compiled == NULL) {
1240         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1241                     "unable to compile pattern \"%s\"", rexp);
1242         return -1;
1243     }
1244     regex_error = ap_regexec(compiled, string, 0, (regmatch_t *) NULL, 0);
1245     ap_pregfree(r->pool, compiled);
1246     return (!regex_error);
1247 }
1248
1249 enum token_type {
1250     token_string,
1251     token_and, token_or, token_not, token_eq, token_ne,
1252     token_rbrace, token_lbrace, token_group,
1253     token_ge, token_le, token_gt, token_lt
1254 };
1255 struct token {
1256     enum token_type type;
1257     char value[MAX_STRING_LEN];
1258 };
1259
1260 /* there is an implicit assumption here that string is at most MAX_STRING_LEN-1
1261  * characters long...
1262  */
1263 static const char *get_ptoken(request_rec *r, const char *string, struct token *token)
1264 {
1265     char ch;
1266     int next = 0;
1267     int qs = 0;
1268
1269     /* Skip leading white space */
1270     if (string == (char *) NULL) {
1271         return (char *) NULL;
1272     }
1273     while ((ch = *string++)) {
1274         if (!ap_isspace(ch)) {
1275             break;
1276         }
1277     }
1278     if (ch == '\0') {
1279         return (char *) NULL;
1280     }
1281
1282     token->type = token_string; /* the default type */
1283     switch (ch) {
1284     case '(':
1285         token->type = token_lbrace;
1286         return (string);
1287     case ')':
1288         token->type = token_rbrace;
1289         return (string);
1290     case '=':
1291         token->type = token_eq;
1292         return (string);
1293     case '!':
1294         if (*string == '=') {
1295             token->type = token_ne;
1296             return (string + 1);
1297         }
1298         else {
1299             token->type = token_not;
1300             return (string);
1301         }
1302     case '\'':
1303         token->type = token_string;
1304         qs = 1;
1305         break;
1306     case '|':
1307         if (*string == '|') {
1308             token->type = token_or;
1309             return (string + 1);
1310         }
1311         break;
1312     case '&':
1313         if (*string == '&') {
1314             token->type = token_and;
1315             return (string + 1);
1316         }
1317         break;
1318     case '>':
1319         if (*string == '=') {
1320             token->type = token_ge;
1321             return (string + 1);
1322         }
1323         else {
1324             token->type = token_gt;
1325             return (string);
1326         }
1327     case '<':
1328         if (*string == '=') {
1329             token->type = token_le;
1330             return (string + 1);
1331         }
1332         else {
1333             token->type = token_lt;
1334             return (string);
1335         }
1336     default:
1337         token->type = token_string;
1338         break;
1339     }
1340     /* We should only be here if we are in a string */
1341     if (!qs) {
1342         token->value[next++] = ch;
1343     }
1344
1345     /* 
1346      * Yes I know that goto's are BAD.  But, c doesn't allow me to
1347      * exit a loop from a switch statement.  Yes, I could use a flag,
1348      * but that is (IMHO) even less readable/maintainable than the goto.
1349      */
1350     /* 
1351      * I used the ++string throughout this section so that string
1352      * ends up pointing to the next token and I can just return it
1353      */
1354     for (ch = *string; ch != '\0'; ch = *++string) {
1355         if (ch == '\\') {
1356             if ((ch = *++string) == '\0') {
1357                 goto TOKEN_DONE;
1358             }
1359             token->value[next++] = ch;
1360             continue;
1361         }
1362         if (!qs) {
1363             if (ap_isspace(ch)) {
1364                 goto TOKEN_DONE;
1365             }
1366             switch (ch) {
1367             case '(':
1368                 goto TOKEN_DONE;
1369             case ')':
1370                 goto TOKEN_DONE;
1371             case '=':
1372                 goto TOKEN_DONE;
1373             case '!':
1374                 goto TOKEN_DONE;
1375             case '|':
1376                 if (*(string + 1) == '|') {
1377                     goto TOKEN_DONE;
1378                 }
1379                 break;
1380             case '&':
1381                 if (*(string + 1) == '&') {
1382                     goto TOKEN_DONE;
1383                 }
1384                 break;
1385             case '<':
1386                 goto TOKEN_DONE;
1387             case '>':
1388                 goto TOKEN_DONE;
1389             }
1390             token->value[next++] = ch;
1391         }
1392         else {
1393             if (ch == '\'') {
1394                 qs = 0;
1395                 ++string;
1396                 goto TOKEN_DONE;
1397             }
1398             token->value[next++] = ch;
1399         }
1400     }
1401   TOKEN_DONE:
1402     /* If qs is still set, I have an unmatched ' */
1403     if (qs) {
1404         ap_rputs("\nUnmatched '\n", r);
1405         next = 0;
1406     }
1407     token->value[next] = '\0';
1408     return (string);
1409 }
1410
1411
1412 /*
1413  * Hey I still know that goto's are BAD.  I don't think that I've ever
1414  * used two in the same project, let alone the same file before.  But,
1415  * I absolutely want to make sure that I clean up the memory in all
1416  * cases.  And, without rewriting this completely, the easiest way
1417  * is to just branch to the return code which cleans it up.
1418  */
1419 /* there is an implicit assumption here that expr is at most MAX_STRING_LEN-1
1420  * characters long...
1421  */
1422 static int parse_expr(request_rec *r, const char *expr, const char *error)
1423 {
1424     struct parse_node {
1425         struct parse_node *left, *right, *parent;
1426         struct token token;
1427         int value, done;
1428     }         *root, *current, *new;
1429     const char *parse;
1430     char buffer[MAX_STRING_LEN];
1431     ap_pool_t *expr_pool;
1432     int retval = 0;
1433
1434     if ((parse = expr) == (char *) NULL) {
1435         return (0);
1436     }
1437     root = current = (struct parse_node *) NULL;
1438     if (ap_create_pool(&expr_pool, r->pool) != APR_SUCCESS)
1439                 return 0;
1440
1441     /* Create Parse Tree */
1442     while (1) {
1443         new = (struct parse_node *) ap_palloc(expr_pool,
1444                                            sizeof(struct parse_node));
1445         new->parent = new->left = new->right = (struct parse_node *) NULL;
1446         new->done = 0;
1447         if ((parse = get_ptoken(r, parse, &new->token)) == (char *) NULL) {
1448             break;
1449         }
1450         switch (new->token.type) {
1451
1452         case token_string:
1453 #ifdef DEBUG_INCLUDE
1454             ap_rvputs(r, "     Token: string (", new->token.value, ")\n", NULL);
1455 #endif
1456             if (current == (struct parse_node *) NULL) {
1457                 root = current = new;
1458                 break;
1459             }
1460             switch (current->token.type) {
1461             case token_string:
1462                 if (current->token.value[0] != '\0') {
1463                     strncat(current->token.value, " ",
1464                          sizeof(current->token.value)
1465                             - strlen(current->token.value) - 1);
1466                 }
1467                 strncat(current->token.value, new->token.value,
1468                          sizeof(current->token.value)
1469                             - strlen(current->token.value) - 1);
1470                 current->token.value[sizeof(current->token.value) - 1] = '\0';
1471                 break;
1472             case token_eq:
1473             case token_ne:
1474             case token_and:
1475             case token_or:
1476             case token_lbrace:
1477             case token_not:
1478             case token_ge:
1479             case token_gt:
1480             case token_le:
1481             case token_lt:
1482                 new->parent = current;
1483                 current = current->right = new;
1484                 break;
1485             default:
1486                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1487                             "Invalid expression \"%s\" in file %s",
1488                             expr, r->filename);
1489                 ap_rputs(error, r);
1490                 goto RETURN;
1491             }
1492             break;
1493
1494         case token_and:
1495         case token_or:
1496 #ifdef DEBUG_INCLUDE
1497             ap_rputs("     Token: and/or\n", r);
1498 #endif
1499             if (current == (struct parse_node *) NULL) {
1500                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1501                             "Invalid expression \"%s\" in file %s",
1502                             expr, r->filename);
1503                 ap_rputs(error, r);
1504                 goto RETURN;
1505             }
1506             /* Percolate upwards */
1507             while (current != (struct parse_node *) NULL) {
1508                 switch (current->token.type) {
1509                 case token_string:
1510                 case token_group:
1511                 case token_not:
1512                 case token_eq:
1513                 case token_ne:
1514                 case token_and:
1515                 case token_or:
1516                 case token_ge:
1517                 case token_gt:
1518                 case token_le:
1519                 case token_lt:
1520                     current = current->parent;
1521                     continue;
1522                 case token_lbrace:
1523                     break;
1524                 default:
1525                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1526                                 "Invalid expression \"%s\" in file %s",
1527                                 expr, r->filename);
1528                     ap_rputs(error, r);
1529                     goto RETURN;
1530                 }
1531                 break;
1532             }
1533             if (current == (struct parse_node *) NULL) {
1534                 new->left = root;
1535                 new->left->parent = new;
1536                 new->parent = (struct parse_node *) NULL;
1537                 root = new;
1538             }
1539             else {
1540                 new->left = current->right;
1541                 current->right = new;
1542                 new->parent = current;
1543             }
1544             current = new;
1545             break;
1546
1547         case token_not:
1548 #ifdef DEBUG_INCLUDE
1549             ap_rputs("     Token: not\n", r);
1550 #endif
1551             if (current == (struct parse_node *) NULL) {
1552                 root = current = new;
1553                 break;
1554             }
1555             /* Percolate upwards */
1556             while (current != (struct parse_node *) NULL) {
1557                 switch (current->token.type) {
1558                 case token_not:
1559                 case token_eq:
1560                 case token_ne:
1561                 case token_and:
1562                 case token_or:
1563                 case token_lbrace:
1564                 case token_ge:
1565                 case token_gt:
1566                 case token_le:
1567                 case token_lt:
1568                     break;
1569                 default:
1570                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1571                                 "Invalid expression \"%s\" in file %s",
1572                                 expr, r->filename);
1573                     ap_rputs(error, r);
1574                     goto RETURN;
1575                 }
1576                 break;
1577             }
1578             if (current == (struct parse_node *) NULL) {
1579                 new->left = root;
1580                 new->left->parent = new;
1581                 new->parent = (struct parse_node *) NULL;
1582                 root = new;
1583             }
1584             else {
1585                 new->left = current->right;
1586                 current->right = new;
1587                 new->parent = current;
1588             }
1589             current = new;
1590             break;
1591
1592         case token_eq:
1593         case token_ne:
1594         case token_ge:
1595         case token_gt:
1596         case token_le:
1597         case token_lt:
1598 #ifdef DEBUG_INCLUDE
1599             ap_rputs("     Token: eq/ne/ge/gt/le/lt\n", r);
1600 #endif
1601             if (current == (struct parse_node *) NULL) {
1602                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1603                             "Invalid expression \"%s\" in file %s",
1604                             expr, r->filename);
1605                 ap_rputs(error, r);
1606                 goto RETURN;
1607             }
1608             /* Percolate upwards */
1609             while (current != (struct parse_node *) NULL) {
1610                 switch (current->token.type) {
1611                 case token_string:
1612                 case token_group:
1613                     current = current->parent;
1614                     continue;
1615                 case token_lbrace:
1616                 case token_and:
1617                 case token_or:
1618                     break;
1619                 case token_not:
1620                 case token_eq:
1621                 case token_ne:
1622                 case token_ge:
1623                 case token_gt:
1624                 case token_le:
1625                 case token_lt:
1626                 default:
1627                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1628                                 "Invalid expression \"%s\" in file %s",
1629                                 expr, r->filename);
1630                     ap_rputs(error, r);
1631                     goto RETURN;
1632                 }
1633                 break;
1634             }
1635             if (current == (struct parse_node *) NULL) {
1636                 new->left = root;
1637                 new->left->parent = new;
1638                 new->parent = (struct parse_node *) NULL;
1639                 root = new;
1640             }
1641             else {
1642                 new->left = current->right;
1643                 current->right = new;
1644                 new->parent = current;
1645             }
1646             current = new;
1647             break;
1648
1649         case token_rbrace:
1650 #ifdef DEBUG_INCLUDE
1651             ap_rputs("     Token: rbrace\n", r);
1652 #endif
1653             while (current != (struct parse_node *) NULL) {
1654                 if (current->token.type == token_lbrace) {
1655                     current->token.type = token_group;
1656                     break;
1657                 }
1658                 current = current->parent;
1659             }
1660             if (current == (struct parse_node *) NULL) {
1661                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1662                             "Unmatched ')' in \"%s\" in file %s",
1663                             expr, r->filename);
1664                 ap_rputs(error, r);
1665                 goto RETURN;
1666             }
1667             break;
1668
1669         case token_lbrace:
1670 #ifdef DEBUG_INCLUDE
1671             ap_rputs("     Token: lbrace\n", r);
1672 #endif
1673             if (current == (struct parse_node *) NULL) {
1674                 root = current = new;
1675                 break;
1676             }
1677             /* Percolate upwards */
1678             while (current != (struct parse_node *) NULL) {
1679                 switch (current->token.type) {
1680                 case token_not:
1681                 case token_eq:
1682                 case token_ne:
1683                 case token_and:
1684                 case token_or:
1685                 case token_lbrace:
1686                 case token_ge:
1687                 case token_gt:
1688                 case token_le:
1689                 case token_lt:
1690                     break;
1691                 case token_string:
1692                 case token_group:
1693                 default:
1694                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1695                                 "Invalid expression \"%s\" in file %s",
1696                                 expr, r->filename);
1697                     ap_rputs(error, r);
1698                     goto RETURN;
1699                 }
1700                 break;
1701             }
1702             if (current == (struct parse_node *) NULL) {
1703                 new->left = root;
1704                 new->left->parent = new;
1705                 new->parent = (struct parse_node *) NULL;
1706                 root = new;
1707             }
1708             else {
1709                 new->left = current->right;
1710                 current->right = new;
1711                 new->parent = current;
1712             }
1713             current = new;
1714             break;
1715         default:
1716             break;
1717         }
1718     }
1719
1720     /* Evaluate Parse Tree */
1721     current = root;
1722     while (current != (struct parse_node *) NULL) {
1723         switch (current->token.type) {
1724         case token_string:
1725 #ifdef DEBUG_INCLUDE
1726             ap_rputs("     Evaluate string\n", r);
1727 #endif
1728             parse_string(r, current->token.value, buffer, sizeof(buffer), 0);
1729             ap_cpystrn(current->token.value, buffer, sizeof(current->token.value));
1730             current->value = (current->token.value[0] != '\0');
1731             current->done = 1;
1732             current = current->parent;
1733             break;
1734
1735         case token_and:
1736         case token_or:
1737 #ifdef DEBUG_INCLUDE
1738             ap_rputs("     Evaluate and/or\n", r);
1739 #endif
1740             if (current->left == (struct parse_node *) NULL ||
1741                 current->right == (struct parse_node *) NULL) {
1742                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1743                             "Invalid expression \"%s\" in file %s",
1744                             expr, r->filename);
1745                 ap_rputs(error, r);
1746                 goto RETURN;
1747             }
1748             if (!current->left->done) {
1749                 switch (current->left->token.type) {
1750                 case token_string:
1751                     parse_string(r, current->left->token.value,
1752                                  buffer, sizeof(buffer), 0);
1753                     ap_cpystrn(current->left->token.value, buffer,
1754                             sizeof(current->left->token.value));
1755                     current->left->value = (current->left->token.value[0] != '\0');
1756                     current->left->done = 1;
1757                     break;
1758                 default:
1759                     current = current->left;
1760                     continue;
1761                 }
1762             }
1763             if (!current->right->done) {
1764                 switch (current->right->token.type) {
1765                 case token_string:
1766                     parse_string(r, current->right->token.value,
1767                                  buffer, sizeof(buffer), 0);
1768                     ap_cpystrn(current->right->token.value, buffer,
1769                             sizeof(current->right->token.value));
1770                     current->right->value = (current->right->token.value[0] != '\0');
1771                     current->right->done = 1;
1772                     break;
1773                 default:
1774                     current = current->right;
1775                     continue;
1776                 }
1777             }
1778 #ifdef DEBUG_INCLUDE
1779             ap_rvputs(r, "     Left: ", current->left->value ? "1" : "0",
1780                    "\n", NULL);
1781             ap_rvputs(r, "     Right: ", current->right->value ? "1" : "0",
1782                    "\n", NULL);
1783 #endif
1784             if (current->token.type == token_and) {
1785                 current->value = current->left->value && current->right->value;
1786             }
1787             else {
1788                 current->value = current->left->value || current->right->value;
1789             }
1790 #ifdef DEBUG_INCLUDE
1791             ap_rvputs(r, "     Returning ", current->value ? "1" : "0",
1792                    "\n", NULL);
1793 #endif
1794             current->done = 1;
1795             current = current->parent;
1796             break;
1797
1798         case token_eq:
1799         case token_ne:
1800 #ifdef DEBUG_INCLUDE
1801             ap_rputs("     Evaluate eq/ne\n", r);
1802 #endif
1803             if ((current->left == (struct parse_node *) NULL) ||
1804                 (current->right == (struct parse_node *) NULL) ||
1805                 (current->left->token.type != token_string) ||
1806                 (current->right->token.type != token_string)) {
1807                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1808                             "Invalid expression \"%s\" in file %s",
1809                             expr, r->filename);
1810                 ap_rputs(error, r);
1811                 goto RETURN;
1812             }
1813             parse_string(r, current->left->token.value,
1814                          buffer, sizeof(buffer), 0);
1815             ap_cpystrn(current->left->token.value, buffer,
1816                         sizeof(current->left->token.value));
1817             parse_string(r, current->right->token.value,
1818                          buffer, sizeof(buffer), 0);
1819             ap_cpystrn(current->right->token.value, buffer,
1820                         sizeof(current->right->token.value));
1821             if (current->right->token.value[0] == '/') {
1822                 int len;
1823                 len = strlen(current->right->token.value);
1824                 if (current->right->token.value[len - 1] == '/') {
1825                     current->right->token.value[len - 1] = '\0';
1826                 }
1827                 else {
1828                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1829                                 "Invalid rexp \"%s\" in file %s",
1830                                 current->right->token.value, r->filename);
1831                     ap_rputs(error, r);
1832                     goto RETURN;
1833                 }
1834 #ifdef DEBUG_INCLUDE
1835                 ap_rvputs(r, "     Re Compare (", current->left->token.value,
1836                   ") with /", &current->right->token.value[1], "/\n", NULL);
1837 #endif
1838                 current->value =
1839                     re_check(r, current->left->token.value,
1840                              &current->right->token.value[1]);
1841             }
1842             else {
1843 #ifdef DEBUG_INCLUDE
1844                 ap_rvputs(r, "     Compare (", current->left->token.value,
1845                        ") with (", current->right->token.value, ")\n", NULL);
1846 #endif
1847                 current->value =
1848                     (strcmp(current->left->token.value,
1849                             current->right->token.value) == 0);
1850             }
1851             if (current->token.type == token_ne) {
1852                 current->value = !current->value;
1853             }
1854 #ifdef DEBUG_INCLUDE
1855             ap_rvputs(r, "     Returning ", current->value ? "1" : "0",
1856                    "\n", NULL);
1857 #endif
1858             current->done = 1;
1859             current = current->parent;
1860             break;
1861         case token_ge:
1862         case token_gt:
1863         case token_le:
1864         case token_lt:
1865 #ifdef DEBUG_INCLUDE
1866             ap_rputs("     Evaluate ge/gt/le/lt\n", r);
1867 #endif
1868             if ((current->left == (struct parse_node *) NULL) ||
1869                 (current->right == (struct parse_node *) NULL) ||
1870                 (current->left->token.type != token_string) ||
1871                 (current->right->token.type != token_string)) {
1872                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1873                             "Invalid expression \"%s\" in file %s",
1874                             expr, r->filename);
1875                 ap_rputs(error, r);
1876                 goto RETURN;
1877             }
1878             parse_string(r, current->left->token.value,
1879                          buffer, sizeof(buffer), 0);
1880             ap_cpystrn(current->left->token.value, buffer,
1881                         sizeof(current->left->token.value));
1882             parse_string(r, current->right->token.value,
1883                          buffer, sizeof(buffer), 0);
1884             ap_cpystrn(current->right->token.value, buffer,
1885                         sizeof(current->right->token.value));
1886 #ifdef DEBUG_INCLUDE
1887             ap_rvputs(r, "     Compare (", current->left->token.value,
1888                    ") with (", current->right->token.value, ")\n", NULL);
1889 #endif
1890             current->value =
1891                 strcmp(current->left->token.value,
1892                        current->right->token.value);
1893             if (current->token.type == token_ge) {
1894                 current->value = current->value >= 0;
1895             }
1896             else if (current->token.type == token_gt) {
1897                 current->value = current->value > 0;
1898             }
1899             else if (current->token.type == token_le) {
1900                 current->value = current->value <= 0;
1901             }
1902             else if (current->token.type == token_lt) {
1903                 current->value = current->value < 0;
1904             }
1905             else {
1906                 current->value = 0;     /* Don't return -1 if unknown token */
1907             }
1908 #ifdef DEBUG_INCLUDE
1909             ap_rvputs(r, "     Returning ", current->value ? "1" : "0",
1910                    "\n", NULL);
1911 #endif
1912             current->done = 1;
1913             current = current->parent;
1914             break;
1915
1916         case token_not:
1917             if (current->right != (struct parse_node *) NULL) {
1918                 if (!current->right->done) {
1919                     current = current->right;
1920                     continue;
1921                 }
1922                 current->value = !current->right->value;
1923             }
1924             else {
1925                 current->value = 0;
1926             }
1927 #ifdef DEBUG_INCLUDE
1928             ap_rvputs(r, "     Evaluate !: ", current->value ? "1" : "0",
1929                    "\n", NULL);
1930 #endif
1931             current->done = 1;
1932             current = current->parent;
1933             break;
1934
1935         case token_group:
1936             if (current->right != (struct parse_node *) NULL) {
1937                 if (!current->right->done) {
1938                     current = current->right;
1939                     continue;
1940                 }
1941                 current->value = current->right->value;
1942             }
1943             else {
1944                 current->value = 1;
1945             }
1946 #ifdef DEBUG_INCLUDE
1947             ap_rvputs(r, "     Evaluate (): ", current->value ? "1" : "0",
1948                    "\n", NULL);
1949 #endif
1950             current->done = 1;
1951             current = current->parent;
1952             break;
1953
1954         case token_lbrace:
1955             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1956                         "Unmatched '(' in \"%s\" in file %s",
1957                         expr, r->filename);
1958             ap_rputs(error, r);
1959             goto RETURN;
1960
1961         case token_rbrace:
1962             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1963                         "Unmatched ')' in \"%s\" in file %s",
1964                         expr, r->filename);
1965             ap_rputs(error, r);
1966             goto RETURN;
1967
1968         default:
1969             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1970                         "bad token type");
1971             ap_rputs(error, r);
1972             goto RETURN;
1973         }
1974     }
1975
1976     retval = (root == (struct parse_node *) NULL) ? 0 : root->value;
1977   RETURN:
1978     ap_destroy_pool(expr_pool);
1979     return (retval);
1980 }
1981
1982 static int handle_if(ap_file_t *in, request_rec *r, const char *error,
1983                      int *conditional_status, int *printing)
1984 {
1985     char tag[MAX_STRING_LEN];
1986     char *tag_val;
1987     char *expr;
1988
1989     expr = NULL;
1990     while (1) {
1991         tag_val = get_tag(r->pool, in, tag, sizeof(tag), 0);
1992         if (*tag == '\0') {
1993             return 1;
1994         }
1995         else if (!strcmp(tag, "done")) {
1996             if (expr == NULL) {
1997                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1998                             "missing expr in if statement: %s",
1999                             r->filename);
2000                 ap_rputs(error, r);
2001                 return 1;
2002             }
2003             *printing = *conditional_status = parse_expr(r, expr, error);
2004 #ifdef DEBUG_INCLUDE
2005             ap_rvputs(r, "**** if conditional_status=\"",
2006                    *conditional_status ? "1" : "0", "\"\n", NULL);
2007 #endif
2008             return 0;
2009         }
2010         else if (!strcmp(tag, "expr")) {
2011             expr = tag_val;
2012 #ifdef DEBUG_INCLUDE
2013             ap_rvputs(r, "**** if expr=\"", expr, "\"\n", NULL);
2014 #endif
2015         }
2016         else {
2017             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2018                         "unknown parameter \"%s\" to tag if in %s",
2019                         tag, r->filename);
2020             ap_rputs(error, r);
2021         }
2022     }
2023 }
2024
2025 static int handle_elif(ap_file_t *in, request_rec *r, const char *error,
2026                        int *conditional_status, int *printing)
2027 {
2028     char tag[MAX_STRING_LEN];
2029     char *tag_val;
2030     char *expr;
2031
2032     expr = NULL;
2033     while (1) {
2034         tag_val = get_tag(r->pool, in, tag, sizeof(tag), 0);
2035         if (*tag == '\0') {
2036             return 1;
2037         }
2038         else if (!strcmp(tag, "done")) {
2039 #ifdef DEBUG_INCLUDE
2040             ap_rvputs(r, "**** elif conditional_status=\"",
2041                    *conditional_status ? "1" : "0", "\"\n", NULL);
2042 #endif
2043             if (*conditional_status) {
2044                 *printing = 0;
2045                 return (0);
2046             }
2047             if (expr == NULL) {
2048                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2049                             "missing expr in elif statement: %s",
2050                             r->filename);
2051                 ap_rputs(error, r);
2052                 return 1;
2053             }
2054             *printing = *conditional_status = parse_expr(r, expr, error);
2055 #ifdef DEBUG_INCLUDE
2056             ap_rvputs(r, "**** elif conditional_status=\"",
2057                    *conditional_status ? "1" : "0", "\"\n", NULL);
2058 #endif
2059             return 0;
2060         }
2061         else if (!strcmp(tag, "expr")) {
2062             expr = tag_val;
2063 #ifdef DEBUG_INCLUDE
2064             ap_rvputs(r, "**** if expr=\"", expr, "\"\n", NULL);
2065 #endif
2066         }
2067         else {
2068             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2069                         "unknown parameter \"%s\" to tag if in %s",
2070                         tag, r->filename);
2071             ap_rputs(error, r);
2072         }
2073     }
2074 }
2075
2076 static int handle_else(ap_file_t *in, request_rec *r, const char *error,
2077                        int *conditional_status, int *printing)
2078 {
2079     char tag[MAX_STRING_LEN];
2080
2081     if (!get_tag(r->pool, in, tag, sizeof(tag), 1)) {
2082         return 1;
2083     }
2084     else if (!strcmp(tag, "done")) {
2085 #ifdef DEBUG_INCLUDE
2086         ap_rvputs(r, "**** else conditional_status=\"",
2087                *conditional_status ? "1" : "0", "\"\n", NULL);
2088 #endif
2089         *printing = !(*conditional_status);
2090         *conditional_status = 1;
2091         return 0;
2092     }
2093     else {
2094         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2095                     "else directive does not take tags in %s",
2096                     r->filename);
2097         if (*printing) {
2098             ap_rputs(error, r);
2099         }
2100         return -1;
2101     }
2102 }
2103
2104 static int handle_endif(ap_file_t *in, request_rec *r, const char *error,
2105                         int *conditional_status, int *printing)
2106 {
2107     char tag[MAX_STRING_LEN];
2108
2109     if (!get_tag(r->pool, in, tag, sizeof(tag), 1)) {
2110         return 1;
2111     }
2112     else if (!strcmp(tag, "done")) {
2113 #ifdef DEBUG_INCLUDE
2114         ap_rvputs(r, "**** endif conditional_status=\"",
2115                *conditional_status ? "1" : "0", "\"\n", NULL);
2116 #endif
2117         *printing = 1;
2118         *conditional_status = 1;
2119         return 0;
2120     }
2121     else {
2122         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2123                     "endif directive does not take tags in %s",
2124                     r->filename);
2125         ap_rputs(error, r);
2126         return -1;
2127     }
2128 }
2129
2130 static int handle_set(ap_file_t *in, request_rec *r, const char *error)
2131 {
2132     char tag[MAX_STRING_LEN];
2133     char parsed_string[MAX_STRING_LEN];
2134     char *tag_val;
2135     char *var;
2136
2137     var = (char *) NULL;
2138     while (1) {
2139         if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
2140             return 1;
2141         }
2142         else if (!strcmp(tag, "done")) {
2143             return 0;
2144         }
2145         else if (!strcmp(tag, "var")) {
2146             var = tag_val;
2147         }
2148         else if (!strcmp(tag, "value")) {
2149             if (var == (char *) NULL) {
2150                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2151                             "variable must precede value in set directive in %s",
2152                             r->filename);
2153                 ap_rputs(error, r);
2154                 return -1;
2155             }
2156             parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
2157             ap_table_setn(r->subprocess_env, var, ap_pstrdup(r->pool, parsed_string));
2158         }
2159         else {
2160             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2161                         "Invalid tag for set directive in %s", r->filename);
2162             ap_rputs(error, r);
2163             return -1;
2164         }
2165     }
2166 }
2167
2168 static int handle_printenv(ap_file_t *in, request_rec *r, const char *error)
2169 {
2170     char tag[MAX_STRING_LEN];
2171     char *tag_val;
2172     ap_array_header_t *arr = ap_table_elts(r->subprocess_env);
2173     ap_table_entry_t *elts = (ap_table_entry_t *)arr->elts;
2174     int i;
2175
2176     if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
2177         return 1;
2178     }
2179     else if (!strcmp(tag, "done")) {
2180         for (i = 0; i < arr->nelts; ++i) {
2181             ap_rvputs(r, ap_escape_html(r->pool, elts[i].key), "=", 
2182                 ap_escape_html(r->pool, elts[i].val), "\n", NULL);
2183         }
2184         return 0;
2185     }
2186     else {
2187         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2188                     "printenv directive does not take tags in %s",
2189                     r->filename);
2190         ap_rputs(error, r);
2191         return -1;
2192     }
2193 }
2194
2195
2196
2197 /* -------------------------- The main function --------------------------- */
2198
2199 /* This is a stub which parses a file descriptor. */
2200
2201 static void send_parsed_content(ap_file_t *f, request_rec *r)
2202 {
2203     char directive[MAX_STRING_LEN], error[MAX_STRING_LEN];
2204     char timefmt[MAX_STRING_LEN];
2205     int noexec = ap_allow_options(r) & OPT_INCNOEXEC;
2206     int ret, sizefmt;
2207     int if_nesting;
2208     int printing;
2209     int conditional_status;
2210
2211     ap_cpystrn(error, DEFAULT_ERROR_MSG, sizeof(error));
2212     ap_cpystrn(timefmt, DEFAULT_TIME_FORMAT, sizeof(timefmt));
2213     sizefmt = SIZEFMT_KMG;
2214
2215 /*  Turn printing on */
2216     printing = conditional_status = 1;
2217     if_nesting = 0;
2218
2219     ap_chdir_file(r->filename);
2220     if (r->args) {              /* add QUERY stuff to env cause it ain't yet */
2221         char *arg_copy = ap_pstrdup(r->pool, r->args);
2222
2223         ap_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
2224         ap_unescape_url(arg_copy);
2225         ap_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
2226                   ap_escape_shell_cmd(r->pool, arg_copy));
2227     }
2228
2229     while (1) {
2230         if (!find_string(f, STARTING_SEQUENCE, r, printing)) {
2231             if (get_directive(f, directive, sizeof(directive), r->pool)) {
2232                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2233                             "mod_include: error reading directive in %s",
2234                             r->filename);
2235                 ap_rputs(error, r);
2236                 return;
2237             }
2238             if (!strcmp(directive, "if")) {
2239                 if (!printing) {
2240                     if_nesting++;
2241                 }
2242                 else {
2243                     ret = handle_if(f, r, error, &conditional_status,
2244                                     &printing);
2245                     if_nesting = 0;
2246                 }
2247                 continue;
2248             }
2249             else if (!strcmp(directive, "else")) {
2250                 if (!if_nesting) {
2251                     ret = handle_else(f, r, error, &conditional_status,
2252                                       &printing);
2253                 }
2254                 continue;
2255             }
2256             else if (!strcmp(directive, "elif")) {
2257                 if (!if_nesting) {
2258                     ret = handle_elif(f, r, error, &conditional_status,
2259                                       &printing);
2260                 }
2261                 continue;
2262             }
2263             else if (!strcmp(directive, "endif")) {
2264                 if (!if_nesting) {
2265                     ret = handle_endif(f, r, error, &conditional_status,
2266                                        &printing);
2267                 }
2268                 else {
2269                     if_nesting--;
2270                 }
2271                 continue;
2272             }
2273             if (!printing) {
2274                 continue;
2275             }
2276             if (!strcmp(directive, "exec")) {
2277                 if (noexec) {
2278                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2279                                   "exec used but not allowed in %s",
2280                                   r->filename);
2281                     if (printing) {
2282                         ap_rputs(error, r);
2283                     }
2284                     ret = find_string(f, ENDING_SEQUENCE, r, 0);
2285                 }
2286                 else {
2287                     ret = handle_exec(f, r, error);
2288                 }
2289             }
2290             else if (!strcmp(directive, "config")) {
2291                 ret = handle_config(f, r, error, timefmt, &sizefmt);
2292             }
2293             else if (!strcmp(directive, "set")) {
2294                 ret = handle_set(f, r, error);
2295             }
2296             else if (!strcmp(directive, "include")) {
2297                 ret = handle_include(f, r, error, noexec);
2298             }
2299             else if (!strcmp(directive, "echo")) {
2300                 ret = handle_echo(f, r, error);
2301             }
2302             else if (!strcmp(directive, "fsize")) {
2303                 ret = handle_fsize(f, r, error, sizefmt);
2304             }
2305             else if (!strcmp(directive, "flastmod")) {
2306                 ret = handle_flastmod(f, r, error, timefmt);
2307             }
2308             else if (!strcmp(directive, "printenv")) {
2309                 ret = handle_printenv(f, r, error);
2310             }
2311 #ifdef USE_PERL_SSI
2312             else if (!strcmp(directive, "perl")) {
2313                 ret = handle_perl(f, r, error);
2314             }
2315 #endif
2316             else {
2317                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2318                               "unknown directive \"%s\" "
2319                               "in parsed doc %s",
2320                               directive, r->filename);
2321                 if (printing) {
2322                     ap_rputs(error, r);
2323                 }
2324                 ret = find_string(f, ENDING_SEQUENCE, r, 0);
2325             }
2326             if (ret) {
2327                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2328                               "premature EOF in parsed file %s",
2329                               r->filename);
2330                 return;
2331             }
2332         }
2333         else {
2334             return;
2335         }
2336     }
2337 }
2338
2339 /*****************************************************************
2340  *
2341  * XBITHACK.  Sigh...  NB it's configurable per-directory; the compile-time
2342  * option only changes the default.
2343  */
2344
2345 module includes_module;
2346 enum xbithack {
2347     xbithack_off, xbithack_on, xbithack_full
2348 };
2349
2350 #ifdef XBITHACK
2351 #define DEFAULT_XBITHACK xbithack_full
2352 #else
2353 #define DEFAULT_XBITHACK xbithack_off
2354 #endif
2355
2356 static void *create_includes_dir_config(ap_pool_t *p, char *dummy)
2357 {
2358     enum xbithack *result = (enum xbithack *) ap_palloc(p, sizeof(enum xbithack));
2359     *result = DEFAULT_XBITHACK;
2360     return result;
2361 }
2362
2363 static const char *set_xbithack(cmd_parms *cmd, void *xbp, char *arg)
2364 {
2365     enum xbithack *state = (enum xbithack *) xbp;
2366
2367     if (!strcasecmp(arg, "off")) {
2368         *state = xbithack_off;
2369     }
2370     else if (!strcasecmp(arg, "on")) {
2371         *state = xbithack_on;
2372     }
2373     else if (!strcasecmp(arg, "full")) {
2374         *state = xbithack_full;
2375     }
2376     else {
2377         return "XBitHack must be set to Off, On, or Full";
2378     }
2379
2380     return NULL;
2381 }
2382
2383 static int send_parsed_file(request_rec *r)
2384 {
2385     ap_file_t *f = NULL;
2386     enum xbithack *state =
2387     (enum xbithack *) ap_get_module_config(r->per_dir_config, &includes_module);
2388     int errstatus;
2389     request_rec *parent;
2390
2391     if (!(ap_allow_options(r) & OPT_INCLUDES)) {
2392         return DECLINED;
2393     }
2394     r->allowed |= (1 << M_GET);
2395     if (r->method_number != M_GET) {
2396         return DECLINED;
2397     }
2398     if (r->finfo.protection == 0) {
2399         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2400                     "File does not exist: %s",
2401                     (r->path_info
2402                      ? ap_pstrcat(r->pool, r->filename, r->path_info, NULL)
2403                      : r->filename));
2404         return HTTP_NOT_FOUND;
2405     }
2406
2407     errstatus = ap_open(&f, r->filename, APR_READ|APR_BUFFERED, 0, r->pool);
2408
2409     if (errstatus != APR_SUCCESS) {
2410         ap_log_rerror(APLOG_MARK, APLOG_ERR, errstatus, r,
2411                     "file permissions deny server access: %s", r->filename);
2412         return HTTP_FORBIDDEN;
2413     }
2414
2415     if ((*state == xbithack_full)
2416 #if !defined(OS2) && !defined(WIN32)
2417     /*  OS/2 dosen't support Groups. */
2418         && (r->finfo.protection & S_IXGRP)
2419 #endif
2420         ) {
2421         ap_update_mtime(r, r->finfo.mtime);
2422         ap_set_last_modified(r);
2423     }
2424     if ((errstatus = ap_meets_conditions(r)) != OK) {
2425         return errstatus;
2426     }
2427
2428     ap_send_http_header(r);
2429
2430     if (r->header_only) {
2431         ap_close(f);
2432         return OK;
2433     }
2434
2435     if ((parent = ap_get_module_config(r->request_config, &includes_module))) {
2436         /* Kludge --- for nested includes, we want to keep the subprocess
2437          * environment of the base document (for compatibility); that means
2438          * torquing our own last_modified date as well so that the
2439          * LAST_MODIFIED variable gets reset to the proper value if the
2440          * nested document resets <!--#config timefmt-->.
2441          * We also insist that the memory for this subrequest not be
2442          * destroyed, that's dealt with in handle_include().
2443          */
2444         r->subprocess_env = parent->subprocess_env;
2445         ap_pool_join(parent->pool, r->pool);
2446         r->finfo.mtime = parent->finfo.mtime;
2447     }
2448     else {
2449         /* we're not a nested include, so we create an initial
2450          * environment */
2451         ap_add_common_vars(r);
2452         ap_add_cgi_vars(r);
2453         add_include_vars(r, DEFAULT_TIME_FORMAT);
2454     }
2455     /* XXX: this is bogus, at some point we're going to do a subrequest,
2456      * and when we do it we're going to be subjecting code that doesn't
2457      * expect to be signal-ready to SIGALRM.  There is no clean way to
2458      * fix this, except to put alarm support into BUFF. -djg
2459      */
2460 #ifdef CHARSET_EBCDIC
2461     /* XXX:@@@ Is the generated/included output ALWAYS in text/ebcdic format? */
2462     ap_bsetopt(r->connection->client, BO_WXLATE, &ap_hdrs_to_ascii);
2463 #endif
2464
2465     send_parsed_content(f, r);
2466
2467     if (parent) {
2468         /* signify that the sub request should not be killed */
2469         ap_set_module_config(r->request_config, &includes_module,
2470             NESTED_INCLUDE_MAGIC);
2471     }
2472
2473     return OK;
2474 }
2475
2476 static int send_shtml_file(request_rec *r)
2477 {
2478     r->content_type = "text/html";
2479     return send_parsed_file(r);
2480 }
2481
2482 static int xbithack_handler(request_rec *r)
2483 {
2484 #if defined(OS2) || defined(WIN32)
2485     /* OS/2 dosen't currently support the xbithack. This is being worked on. */
2486     return DECLINED;
2487 #else
2488     enum xbithack *state;
2489
2490     if (!(r->finfo.protection & S_IXUSR)) {
2491         return DECLINED;
2492     }
2493
2494     state = (enum xbithack *) ap_get_module_config(r->per_dir_config,
2495                                                 &includes_module);
2496
2497     if (*state == xbithack_off) {
2498         return DECLINED;
2499     }
2500     return send_parsed_file(r);
2501 #endif
2502 }
2503
2504 static const command_rec includes_cmds[] =
2505 {
2506     {"XBitHack", set_xbithack, NULL, OR_OPTIONS, TAKE1, "Off, On, or Full"},
2507     {NULL}
2508 };
2509
2510 static const handler_rec includes_handlers[] =
2511 {
2512     {INCLUDES_MAGIC_TYPE, send_shtml_file},
2513     {INCLUDES_MAGIC_TYPE3, send_shtml_file},
2514     {"server-parsed", send_parsed_file},
2515     {"text/html", xbithack_handler},
2516     {NULL}
2517 };
2518
2519 module MODULE_VAR_EXPORT includes_module =
2520 {
2521     STANDARD20_MODULE_STUFF,
2522     create_includes_dir_config, /* dir config creater */
2523     NULL,                       /* dir merger --- default is to override */
2524     NULL,                       /* server config */
2525     NULL,                       /* merge server config */
2526     includes_cmds,              /* command ap_table_t */
2527     includes_handlers,          /* handlers */
2528     NULL                        /* register hooks */
2529 };