]> granicus.if.org Git - apache/blob - modules/filters/mod_include.c
Add config directives to override the DEFAULT_ERROR_MSG and
[apache] / modules / filters / mod_include.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 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 #include "apr.h"
68 #include "apr_strings.h"
69 #include "apr_thread_proc.h"
70 #include "apr_hash.h"
71 #include "apr_user.h"
72 #include "apr_lib.h"
73 #include "apr_optional.h"
74
75 #define APR_WANT_STRFUNC
76 #include "apr_want.h"
77
78 #define CORE_PRIVATE
79
80 #include "ap_config.h"
81 #include "util_filter.h"
82 #include "httpd.h"
83 #include "http_config.h"
84 #include "http_request.h"
85 #include "http_core.h"
86 #include "http_protocol.h"
87 #include "http_log.h"
88 #include "http_main.h"
89 #include "util_script.h"
90 #include "http_core.h"
91 #include "mod_include.h"
92 #include "util_ebcdic.h"
93
94 module AP_MODULE_DECLARE_DATA include_module;
95 static apr_hash_t *include_hash;
96 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *ssi_pfn_register;
97
98
99 /* ------------------------ Environment function -------------------------- */
100
101 /* XXX: could use ap_table_overlap here */
102 static void add_include_vars(request_rec *r, char *timefmt)
103 {
104     char *pwname;
105     apr_table_t *e = r->subprocess_env;
106     char *t;
107     apr_time_t date = r->request_time;
108
109     apr_table_setn(e, "DATE_LOCAL", ap_ht_time(r->pool, date, timefmt, 0));
110     apr_table_setn(e, "DATE_GMT", ap_ht_time(r->pool, date, timefmt, 1));
111     apr_table_setn(e, "LAST_MODIFIED",
112               ap_ht_time(r->pool, r->finfo.mtime, timefmt, 0));
113     apr_table_setn(e, "DOCUMENT_URI", r->uri);
114     apr_table_setn(e, "DOCUMENT_PATH_INFO", r->path_info);
115     if (apr_get_username(&pwname, r->finfo.user, r->pool) == APR_SUCCESS) {
116         apr_table_setn(e, "USER_NAME", pwname);
117     }
118     else {
119         apr_table_setn(e, "USER_NAME", "<unknown>");
120     }
121     if ((t = strrchr(r->filename, '/'))) {
122         apr_table_setn(e, "DOCUMENT_NAME", ++t);
123     }
124     else {
125         apr_table_setn(e, "DOCUMENT_NAME", r->uri);
126     }
127     if (r->args) {
128         char *arg_copy = apr_pstrdup(r->pool, r->args);
129
130         ap_unescape_url(arg_copy);
131         apr_table_setn(e, "QUERY_STRING_UNESCAPED",
132                   ap_escape_shell_cmd(r->pool, arg_copy));
133     }
134 }
135
136
137
138 /* --------------------------- Parser functions --------------------------- */
139
140 /* This function returns either a pointer to the split bucket containing the
141  * first byte of the BEGINNING_SEQUENCE (after finding a complete match) or it
142  * returns NULL if no match found.
143  */
144 static apr_bucket *find_start_sequence(apr_bucket *dptr, include_ctx_t *ctx,
145                                       apr_bucket_brigade *bb, int *do_cleanup)
146 {
147     apr_size_t len;
148     const char *c;
149     const char *buf;
150     const char *str = STARTING_SEQUENCE;
151
152     *do_cleanup = 0;
153
154     do {
155         if (APR_BUCKET_IS_EOS(dptr)) {
156             break;
157         }
158         apr_bucket_read(dptr, &buf, &len, 0);
159         /* XXX handle retcodes */
160         if (len == 0) { /* end of pipe? */
161             break;
162         }
163         c = buf;
164         while (c - buf != len) {
165             if (*c == str[ctx->parse_pos]) {
166                 if (ctx->state == PRE_HEAD) {
167                     ctx->state             = PARSE_HEAD;
168                     ctx->head_start_bucket = dptr;
169                     ctx->head_start_index  = c - buf;
170                 }
171                 ctx->parse_pos++;
172             }
173             else {
174                 if (str[ctx->parse_pos] == '\0') {
175                     apr_bucket   *tmp_bkt;
176                     apr_size_t  start_index;
177
178                     /* We want to split the bucket at the '<'. */
179                     ctx->state            = PARSE_DIRECTIVE;
180                     ctx->tag_length       = 0;
181                     ctx->parse_pos        = 0;
182                     ctx->tag_start_bucket = dptr;
183                     ctx->tag_start_index  = c - buf;
184                     if (ctx->head_start_index > 0) {
185                         start_index = (c - buf) - ctx->head_start_index;
186                         apr_bucket_split(ctx->head_start_bucket, ctx->head_start_index);
187                         tmp_bkt = APR_BUCKET_NEXT(ctx->head_start_bucket);
188                         if (dptr == ctx->head_start_bucket) {
189                             ctx->tag_start_bucket = tmp_bkt;
190                             ctx->tag_start_index  = start_index;
191                         }
192                         ctx->head_start_bucket = tmp_bkt;
193                         ctx->head_start_index  = 0;
194                     }
195                     return ctx->head_start_bucket;
196                 }
197                 else if (ctx->parse_pos != 0) {
198                     /* The reason for this, is that we need to make sure 
199                      * that we catch cases like <<!--#.  This makes the 
200                      * second check after the original check fails.
201                      * If parse_pos was already 0 then we already checked this.
202                      */
203                     *do_cleanup = 1;
204                     if (*c == str[0]) {
205                         ctx->parse_pos         = 1;
206                         ctx->state             = PARSE_HEAD;
207                         ctx->head_start_bucket = dptr;
208                         ctx->head_start_index  = c - buf;
209                     }
210                     else {
211                         ctx->parse_pos         = 0;
212                         ctx->state             = PRE_HEAD;
213                         ctx->head_start_bucket = NULL;
214                         ctx->head_start_index  = 0;
215                     }
216                 }
217             }
218             c++;
219         }
220         dptr = APR_BUCKET_NEXT(dptr);
221     } while (dptr != APR_BRIGADE_SENTINEL(bb));
222     return NULL;
223 }
224
225 static apr_bucket *find_end_sequence(apr_bucket *dptr, include_ctx_t *ctx, apr_bucket_brigade *bb)
226 {
227     apr_size_t len;
228     const char *c;
229     const char *buf;
230     const char *str = ENDING_SEQUENCE;
231
232     do {
233         if (APR_BUCKET_IS_EOS(dptr)) {
234             break;
235         }
236         apr_bucket_read(dptr, &buf, &len, 0);
237         /* XXX handle retcodes */
238         if (len == 0) { /* end of pipe? */
239             break;
240         }
241         if (dptr == ctx->tag_start_bucket) {
242             c = buf + ctx->tag_start_index;
243         }
244         else {
245             c = buf;
246         }
247         while (c - buf != len) {
248             if (*c == str[ctx->parse_pos]) {
249                 if (ctx->state != PARSE_TAIL) {
250                     ctx->state             = PARSE_TAIL;
251                     ctx->tail_start_bucket = dptr;
252                     ctx->tail_start_index  = c - buf;
253                 }
254                 ctx->parse_pos++;
255             }
256             else {
257                 if (ctx->state == PARSE_DIRECTIVE) {
258                     if (ctx->tag_length == 0) {
259                         if (!apr_isspace(*c)) {
260                             ctx->tag_start_bucket = dptr;
261                             ctx->tag_start_index  = c - buf;
262                             ctx->tag_length       = 1;
263                             ctx->directive_length = 1;
264                         }
265                     }
266                     else {
267                         if (!apr_isspace(*c)) {
268                             ctx->directive_length++;
269                         }
270                         else {
271                             ctx->state = PARSE_TAG;
272                         }
273                         ctx->tag_length++;
274                     }
275                 }
276                 else if (ctx->state == PARSE_TAG) {
277                     ctx->tag_length++;
278                 }
279                 else {
280                     if (str[ctx->parse_pos] == '\0') {
281                         apr_bucket *tmp_buck = dptr;
282
283                         /* We want to split the bucket at the '>'. The
284                          * end of the END_SEQUENCE is in the current bucket.
285                          * The beginning might be in a previous bucket.
286                          */
287                         ctx->state = PARSED;
288                         if ((c - buf) > 0) {
289                             apr_bucket_split(dptr, c - buf);
290                             tmp_buck = APR_BUCKET_NEXT(dptr);
291                         }
292                         return (tmp_buck);
293                     }
294                     else if (ctx->parse_pos != 0) {
295                         /* The reason for this, is that we need to make sure 
296                          * that we catch cases like --->.  This makes the 
297                          * second check after the original check fails.
298                          * If parse_pos was already 0 then we already checked this.
299                          */
300                          ctx->tag_length += ctx->parse_pos;
301
302                          if (*c == str[0]) {
303                              ctx->state             = PARSE_TAIL;
304                              ctx->tail_start_bucket = dptr;
305                              ctx->tail_start_index  = c - buf;
306                              ctx->tag_length       += ctx->parse_pos;
307                              ctx->parse_pos         = 1;
308                          }
309                          else {
310                              if (ctx->tag_length > ctx->directive_length) {
311                                  ctx->state = PARSE_TAG;
312                              }
313                              else {
314                                  ctx->state = PARSE_DIRECTIVE;
315                                  ctx->directive_length += ctx->parse_pos;
316                              }
317                              ctx->tail_start_bucket = NULL;
318                              ctx->tail_start_index  = 0;
319                              ctx->tag_length       += ctx->parse_pos;
320                              ctx->parse_pos         = 0;
321                          }
322                     }
323                 }
324             }
325             c++;
326         }
327         dptr = APR_BUCKET_NEXT(dptr);
328     } while (dptr != APR_BRIGADE_SENTINEL(bb));
329     return NULL;
330 }
331
332 /* This function culls through the buckets that have been set aside in the 
333  * ssi_tag_brigade and copies just the directive part of the SSI tag (none
334  * of the start and end delimiter bytes are copied).
335  */
336 static apr_status_t get_combined_directive (include_ctx_t *ctx,
337                                             request_rec *r,
338                                             apr_bucket_brigade *bb,
339                                             char *tmp_buf, int tmp_buf_size)
340 {
341     int         done = 0;
342     apr_bucket  *dptr;
343     const char *tmp_from;
344     apr_size_t tmp_from_len;
345
346     /* If the tag length is longer than the tmp buffer, allocate space. */
347     if (ctx->tag_length > tmp_buf_size-1) {
348         if ((ctx->combined_tag = apr_pcalloc(r->pool, ctx->tag_length + 1)) == NULL) {
349             return (APR_ENOMEM);
350         }
351     }     /* Else, just use the temp buffer. */
352     else {
353         ctx->combined_tag = tmp_buf;
354     }
355
356     /* Prime the pump. Start at the beginning of the tag... */
357     dptr = ctx->tag_start_bucket;
358     apr_bucket_read (dptr, &tmp_from, &tmp_from_len, 0);  /* Read the bucket... */
359
360     /* Adjust the pointer to start at the tag within the bucket... */
361     if (dptr == ctx->tail_start_bucket) {
362         tmp_from_len -= (tmp_from_len - ctx->tail_start_index);
363     }
364     tmp_from          = &tmp_from[ctx->tag_start_index];
365     tmp_from_len     -= ctx->tag_start_index;
366     ctx->curr_tag_pos = ctx->combined_tag;
367
368     /* Loop through the buckets from the tag_start_bucket until before
369      * the tail_start_bucket copying the contents into the buffer.
370      */
371     do {
372         memcpy (ctx->curr_tag_pos, tmp_from, tmp_from_len);
373         ctx->curr_tag_pos += tmp_from_len;
374
375         if (dptr == ctx->tail_start_bucket) {
376             done = 1;
377         }
378         else {
379             dptr = APR_BUCKET_NEXT (dptr);
380             apr_bucket_read (dptr, &tmp_from, &tmp_from_len, 0);
381             /* Adjust the count to stop at the beginning of the tail. */
382             if (dptr == ctx->tail_start_bucket) {
383                 tmp_from_len -= (tmp_from_len - ctx->tail_start_index);
384             }
385         }
386     } while ((!done) &&
387              ((ctx->curr_tag_pos - ctx->combined_tag) < ctx->tag_length));
388
389     ctx->combined_tag[ctx->tag_length] = '\0';
390     ctx->curr_tag_pos = ctx->combined_tag;
391
392     return (APR_SUCCESS);
393 }
394
395 /*
396  * decodes a string containing html entities or numeric character references.
397  * 's' is overwritten with the decoded string.
398  * If 's' is syntatically incorrect, then the followed fixups will be made:
399  *   unknown entities will be left undecoded;
400  *   references to unused numeric characters will be deleted.
401  *   In particular, &#00; will not be decoded, but will be deleted.
402  *
403  * drtr
404  */
405
406 /* maximum length of any ISO-LATIN-1 HTML entity name. */
407 #define MAXENTLEN (6)
408
409 /* The following is a shrinking transformation, therefore safe. */
410
411 static void decodehtml(char *s)
412 {
413     int val, i, j;
414     char *p = s;
415     const char *ents;
416     static const char * const entlist[MAXENTLEN + 1] =
417     {
418         NULL,                   /* 0 */
419         NULL,                   /* 1 */
420         "lt\074gt\076",         /* 2 */
421         "amp\046ETH\320eth\360",        /* 3 */
422         "quot\042Auml\304Euml\313Iuml\317Ouml\326Uuml\334auml\344euml\353\
423 iuml\357ouml\366uuml\374yuml\377",      /* 4 */
424         "Acirc\302Aring\305AElig\306Ecirc\312Icirc\316Ocirc\324Ucirc\333\
425 THORN\336szlig\337acirc\342aring\345aelig\346ecirc\352icirc\356ocirc\364\
426 ucirc\373thorn\376",            /* 5 */
427         "Agrave\300Aacute\301Atilde\303Ccedil\307Egrave\310Eacute\311\
428 Igrave\314Iacute\315Ntilde\321Ograve\322Oacute\323Otilde\325Oslash\330\
429 Ugrave\331Uacute\332Yacute\335agrave\340aacute\341atilde\343ccedil\347\
430 egrave\350eacute\351igrave\354iacute\355ntilde\361ograve\362oacute\363\
431 otilde\365oslash\370ugrave\371uacute\372yacute\375"     /* 6 */
432     };
433
434     for (; *s != '\0'; s++, p++) {
435         if (*s != '&') {
436             *p = *s;
437             continue;
438         }
439         /* find end of entity */
440         for (i = 1; s[i] != ';' && s[i] != '\0'; i++) {
441             continue;
442         }
443
444         if (s[i] == '\0') {     /* treat as normal data */
445             *p = *s;
446             continue;
447         }
448
449         /* is it numeric ? */
450         if (s[1] == '#') {
451             for (j = 2, val = 0; j < i && apr_isdigit(s[j]); j++) {
452                 val = val * 10 + s[j] - '0';
453             }
454             s += i;
455             if (j < i || val <= 8 || (val >= 11 && val <= 31) ||
456                 (val >= 127 && val <= 160) || val >= 256) {
457                 p--;            /* no data to output */
458             }
459             else {
460                 *p = RAW_ASCII_CHAR(val);
461             }
462         }
463         else {
464             j = i - 1;
465             if (j > MAXENTLEN || entlist[j] == NULL) {
466                 /* wrong length */
467                 *p = '&';
468                 continue;       /* skip it */
469             }
470             for (ents = entlist[j]; *ents != '\0'; ents += i) {
471                 if (strncmp(s + 1, ents, j) == 0) {
472                     break;
473                 }
474             }
475
476             if (*ents == '\0') {
477                 *p = '&';       /* unknown */
478             }
479             else {
480                 *p = RAW_ASCII_CHAR(((const unsigned char *) ents)[j]);
481                 s += i;
482             }
483         }
484     }
485
486     *p = '\0';
487 }
488
489 /*
490  * Extract the next tag name and value.
491  * If there are no more tags, set the tag name to NULL.
492  * The tag value is html decoded if dodecode is non-zero.
493  * The tag value may be NULL if there is no tag value..
494  *    format:
495  *        [WS]<Tag>[WS]=[WS]['|"]<Value>['|"|WS]
496  */
497
498 #define SKIP_TAG_WHITESPACE(ptr) while ((*ptr != '\0') && (apr_isspace (*ptr))) ptr++
499
500 static void ap_ssi_get_tag_and_value(include_ctx_t *ctx, char **tag,
501                               char **tag_val, int dodecode)
502 {
503     char *c = ctx->curr_tag_pos;
504     int   shift_val = 0; 
505     char  term = '\0';
506
507     *tag_val = NULL;
508     SKIP_TAG_WHITESPACE(c);
509     *tag = c;             /* First non-whitespace character (could be NULL). */
510
511     while ((*c != '\0') && (*c != '=') && (!apr_isspace(*c))) {
512         *c = apr_tolower(*c);    /* find end of tag, lowercasing as we go... */
513         c++;
514     }
515
516     if ((*c == '\0') || (**tag == '=')) {
517         if ((**tag == '\0') || (**tag == '=')) {
518             *tag = NULL;
519         }
520         ctx->curr_tag_pos = c;
521         return;      /* We have found the end of the buffer. */
522     }                /* We might have a tag, but definitely no value. */
523
524     if (*c == '=') {
525         *c++ = '\0';     /* Overwrite the '=' with a terminating byte after tag. */
526     }
527     else {               /* Try skipping WS to find the '='. */
528         *c++ = '\0';     /* Terminate the tag... */
529         SKIP_TAG_WHITESPACE(c);
530         
531         if (*c != '=') {     /* There needs to be an equal sign if there's a value. */
532             ctx->curr_tag_pos = c;
533             return;       /* There apparently was no value. */
534         }
535         else {
536             c++; /* Skip the equals sign. */
537         }
538     }
539
540     SKIP_TAG_WHITESPACE(c);
541     if (*c == '"' || *c == '\'') {    /* Allow quoted values for space inclusion. */
542         term = *c++;     /* NOTE: This does not pass the quotes on return. */
543     }
544     
545     *tag_val = c;
546     while ((*c != '\0') &&
547            (((term != '\0') && (*c != term)) ||
548             ((term == '\0') && (!apr_isspace(*c))))) {
549         if (*c == '\\') {  /* Accept \" and \' as valid char in string. */
550             c++;
551             if (*c == term) { /* Overwrite the "\" during the embedded  */
552                 shift_val++;  /* escape sequence of '\"' or "\'". Shift */
553             }                 /* bytes from here to next delimiter.     */
554             if (shift_val > 0) {
555                 *(c-shift_val) = *c;
556             }
557         }
558
559         c++;
560         if (shift_val > 0) {
561             *(c-shift_val) = *c;
562         }
563     }
564     
565     *c++ = '\0'; /* Overwrites delimiter (term or WS) with NULL. */
566     ctx->curr_tag_pos = c;
567     if (dodecode) {
568         decodehtml(*tag_val);
569     }
570
571     return;
572 }
573
574
575 /*
576  * Do variable substitution on strings
577  */
578 static void ap_ssi_parse_string(request_rec *r, const char *in, char *out,
579                          size_t length, int leave_name)
580 {
581     char ch;
582     char *next = out;
583     char *end_out;
584
585     /* leave room for nul terminator */
586     end_out = out + length - 1;
587
588     while ((ch = *in++) != '\0') {
589         switch (ch) {
590         case '\\':
591             if (next == end_out) {
592                 /* truncated */
593                 *next = '\0';
594                 return;
595             }
596             if (*in == '$') {
597                 *next++ = *in++;
598             }
599             else {
600                 *next++ = ch;
601             }
602             break;
603         case '$':
604             {
605                 const char *start_of_var_name;
606                 char *end_of_var_name;  /* end of var name + 1 */
607                 const char *expansion, *temp_end, *val;
608                 char        tmp_store;
609                 size_t l;
610
611                 /* guess that the expansion won't happen */
612                 expansion = in - 1;
613                 if (*in == '{') {
614                     ++in;
615                     start_of_var_name = in;
616                     in = ap_strchr_c(in, '}');
617                     if (in == NULL) {
618                         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
619                                     0, r, "Missing '}' on variable \"%s\"",
620                                     expansion);
621                         *next = '\0';
622                         return;
623                     }
624                     temp_end = in;
625                     end_of_var_name = (char *)temp_end;
626                     ++in;
627                 }
628                 else {
629                     start_of_var_name = in;
630                     while (apr_isalnum(*in) || *in == '_') {
631                         ++in;
632                     }
633                     temp_end = in;
634                     end_of_var_name = (char *)temp_end;
635                 }
636                 /* what a pain, too bad there's no table_getn where you can
637                  * pass a non-nul terminated string */
638                 l = end_of_var_name - start_of_var_name;
639                 if (l != 0) {
640                     tmp_store        = *end_of_var_name;
641                     *end_of_var_name = '\0';
642                     val = apr_table_get(r->subprocess_env, start_of_var_name);
643                     *end_of_var_name = tmp_store;
644
645                     if (val) {
646                         expansion = val;
647                         l = strlen(expansion);
648                     }
649                     else if (leave_name) {
650                         l = in - expansion;
651                     }
652                     else {
653                         break;  /* no expansion to be done */
654                     }
655                 }
656                 else {
657                     /* zero-length variable name causes just the $ to be copied */
658                     l = 1;
659                 }
660                 l = ((int)l > end_out - next) ? (end_out - next) : l;
661                 memcpy(next, expansion, l);
662                 next += l;
663                 break;
664             }
665         default:
666             if (next == end_out) {
667                 /* truncated */
668                 *next = '\0';
669                 return;
670             }
671             *next++ = ch;
672             break;
673         }
674     }
675     *next = '\0';
676     return;
677 }
678
679 /* --------------------------- Action handlers ---------------------------- */
680
681 /* ensure that path is relative, and does not contain ".." elements
682  * ensentially ensure that it does not match the regex:
683  * (^/|(^|/)\.\.(/|$))
684  * XXX: Needs to become apr_is_path_relative() test
685  */
686 static int is_only_below(const char *path)
687 {
688 #ifdef HAVE_DRIVE_LETTERS
689     if (path[1] == ':') 
690         return 0;
691 #endif
692 #ifdef NETWARE
693     if (strchr(path, ':')
694         return 0;
695 #endif
696     if (path[0] == '/') {
697         return 0;
698     }
699     while (*path) {
700         int dots = 0;
701         while (path[dots] == '.')
702             ++dots;
703 #if defined(WIN32) 
704         /* If the name is canonical this is redundant
705          * but in security, redundancy is worthwhile.
706          * Does OS2 belong here (accepts ... for ..)?
707          */
708         if (dots > 1 && (!path[dots] || path[dots] == '/'))
709             return 0;
710 #else
711         if (dots == 2 && (!path[dots] || path[dots] == '/'))
712             return 0;
713 #endif
714         path += dots;
715         while (*path && *(path++) != '/')
716             ++path;
717     }
718     return 1;
719 }
720
721 static int handle_include(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
722                           ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
723 {
724     char *tag     = NULL;
725     char *tag_val = NULL;
726     apr_bucket  *tmp_buck;
727     char parsed_string[MAX_STRING_LEN];
728
729     *inserted_head = NULL;
730     if (ctx->flags & FLAG_PRINTING) {
731         while (1) {
732             ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 1);
733             if (tag_val == NULL) {
734                 if (tag == NULL) {
735                     return (0);
736                 }
737                 else {
738                     return (1);
739                 }
740             }
741             if (!strcmp(tag, "file") || !strcmp(tag, "virtual")) {
742                 request_rec *rr = NULL;
743                 char *error_fmt = NULL;
744
745                 ap_ssi_parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
746                 if (tag[0] == 'f') {
747                     /* be safe; only files in this directory or below allowed */
748                 if (!is_only_below(parsed_string)) {
749                         error_fmt = "unable to include file \"%s\" "
750                                     "in parsed file %s";
751                     }
752                     else {
753                         rr = ap_sub_req_lookup_file(parsed_string, r, f->next);
754                     }
755                 }
756                 else {
757                     rr = ap_sub_req_lookup_uri(parsed_string, r, f->next);
758                 }
759
760                 if (!error_fmt && rr->status != HTTP_OK) {
761                     error_fmt = "unable to include \"%s\" in parsed file %s";
762                 }
763
764                 if (!error_fmt && (ctx->flags & FLAG_NO_EXEC) && rr->content_type
765                     && (strncmp(rr->content_type, "text/", 5))) {
766                     error_fmt = "unable to include potential exec \"%s\" "
767                         "in parsed file %s";
768                 }
769                 if (error_fmt == NULL) {
770                 /* try to avoid recursive includes.  We do this by walking
771                  * up the r->main list of subrequests, and at each level
772                  * walking back through any internal redirects.  At each
773                  * step, we compare the filenames and the URIs.  
774                  *
775                  * The filename comparison catches a recursive include
776                  * with an ever-changing URL, eg.
777                  * <!--#include virtual=
778                  *      "$REQUEST_URI/$QUERY_STRING?$QUERY_STRING/x"-->
779                  * which, although they would eventually be caught because
780                  * we have a limit on the length of files, etc., can 
781                  * recurse for a while.
782                  *
783                  * The URI comparison catches the case where the filename
784                  * is changed while processing the request, so the 
785                  * current name is never the same as any previous one.
786                  * This can happen with "DocumentRoot /foo" when you
787                  * request "/" on the server and it includes "/".
788                  * This only applies to modules such as mod_dir that 
789                  * (somewhat improperly) mess with r->filename outside 
790                  * of a filename translation phase.
791                  */
792                 int founddupe = 0;
793                     request_rec *p;
794                     for (p = r; p != NULL && !founddupe; p = p->main) {
795                     request_rec *q;
796                     for (q = p; q != NULL; q = q->prev) {
797                         if ( (strcmp(q->filename, rr->filename) == 0) ||
798                              (strcmp(q->uri, rr->uri) == 0) ){
799                             founddupe = 1;
800                             break;
801                         }
802                     }
803                 }
804
805                     if (p != NULL) {
806                         error_fmt = "Recursive include of \"%s\" "
807                             "in parsed file %s";
808                     }
809                 }
810
811             /* See the Kludge in send_parsed_file for why */
812                 /* Basically, it puts a bread crumb in here, then looks */
813                 /*   for the crumb later to see if its been here.       */
814             if (rr) 
815                 ap_set_module_config(rr->request_config, &include_module, r);
816
817                 if (!error_fmt) {
818                     SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next);
819                     
820                     if (ap_run_sub_req(rr)) {
821                         error_fmt = "unable to include \"%s\" in parsed file %s";
822                     }
823                 }
824                 if (error_fmt) {
825                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
826                             0, r, error_fmt, tag_val, r->filename);
827                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
828                 }
829
830             /* destroy the sub request if it's not a nested include (crumb) */
831                 if (rr != NULL
832                 && ap_get_module_config(rr->request_config, &include_module)
833                     != NESTED_INCLUDE_MAGIC) {
834                 ap_destroy_sub_req(rr);
835                 }
836             }
837             else {
838                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
839                             "unknown parameter \"%s\" to tag include in %s",
840                             tag, r->filename);
841                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
842             }
843         }
844     }
845     return 0;
846 }
847
848
849 static int handle_echo(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
850                        ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
851 {
852     char       *tag       = NULL;
853     char       *tag_val   = NULL;
854     const char *echo_text = NULL;
855     apr_bucket  *tmp_buck;
856     apr_size_t e_len, e_wrt;
857     enum {E_NONE, E_URL, E_ENTITY} encode;
858
859     encode = E_ENTITY;
860
861     *inserted_head = NULL;
862     if (ctx->flags & FLAG_PRINTING) {
863         while (1) {
864             ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 1);
865             if (tag_val == NULL) {
866                 if (tag != NULL) {
867                     return 1;
868                 }
869                 else {
870                     return 0;
871                 }
872             }
873             if (!strcmp(tag, "var")) {
874                 const char *val = apr_table_get(r->subprocess_env, tag_val);
875                 int b_copy = 0;
876
877                 if (val) {
878                     switch(encode) {
879                     case E_NONE:   echo_text = val;  b_copy = 1;             break;
880                     case E_URL:    echo_text = ap_escape_uri(r->pool, val);  break;
881                     case E_ENTITY: echo_text = ap_escape_html(r->pool, val); break;
882                 }
883
884                     e_len = strlen(echo_text);
885                     tmp_buck = apr_bucket_heap_create(echo_text, e_len, 1, &e_wrt);
886                 }
887                 else {
888                     tmp_buck = apr_bucket_immortal_create("(none)", sizeof("none"));
889                 }
890                 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
891                 if (*inserted_head == NULL) {
892                     *inserted_head = tmp_buck;
893                 }
894             }
895             else if (!strcmp(tag, "encoding")) {
896                 if (!strcasecmp(tag_val, "none")) encode = E_NONE;
897                 else if (!strcasecmp(tag_val, "url")) encode = E_URL;
898                 else if (!strcasecmp(tag_val, "entity")) encode = E_ENTITY;
899                 else {
900                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
901                                   "unknown value \"%s\" to parameter \"encoding\" of "
902                                   "tag echo in %s", tag_val, r->filename);
903                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
904                 }
905             }
906             else {
907                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
908                             "unknown parameter \"%s\" in tag echo of %s",
909                             tag, r->filename);
910                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
911             }
912
913         }
914     }
915     return 0;
916 }
917
918 /* error and tf must point to a string with room for at 
919  * least MAX_STRING_LEN characters 
920  */
921 static int handle_config(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
922                          ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
923 {
924     char *tag     = NULL;
925     char *tag_val = NULL;
926     char parsed_string[MAX_STRING_LEN];
927     apr_table_t *env = r->subprocess_env;
928
929     *inserted_head = NULL;
930     if (ctx->flags & FLAG_PRINTING) {
931         while (1) {
932             ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 0);
933             if (tag_val == NULL) {
934                 if (tag == NULL) {
935                     return 0;  /* Reached the end of the string. */
936                 }
937                 else {
938                     return 1;  /* tags must have values. */
939                 }
940             }
941             if (!strcmp(tag, "errmsg")) {
942                 ap_ssi_parse_string(r, tag_val, ctx->error_str, MAX_STRING_LEN, 0);
943                 ctx->error_length = strlen(ctx->error_str);
944             }
945             else if (!strcmp(tag, "timefmt")) {
946                 apr_time_t date = r->request_time;
947
948                 ap_ssi_parse_string(r, tag_val, ctx->time_str, MAX_STRING_LEN, 0);
949                 apr_table_setn(env, "DATE_LOCAL", ap_ht_time(r->pool, date, ctx->time_str, 0));
950                 apr_table_setn(env, "DATE_GMT", ap_ht_time(r->pool, date, ctx->time_str, 1));
951                 apr_table_setn(env, "LAST_MODIFIED",
952                                ap_ht_time(r->pool, r->finfo.mtime, ctx->time_str, 0));
953             }
954             else if (!strcmp(tag, "sizefmt")) {
955                 ap_ssi_parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
956                 decodehtml(parsed_string);
957                 if (!strcmp(parsed_string, "bytes")) {
958                     ctx->flags |= FLAG_SIZE_IN_BYTES;
959                 }
960                 else if (!strcmp(parsed_string, "abbrev")) {
961                     ctx->flags &= FLAG_SIZE_ABBREV;
962                 }
963             }
964             else {
965                 apr_bucket  *tmp_buck;
966
967                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
968                             "unknown parameter \"%s\" to tag config in %s",
969                             tag, r->filename);
970                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
971             }
972         }
973     }
974     return 0;
975 }
976
977
978 static int find_file(request_rec *r, const char *directive, const char *tag,
979                      char *tag_val, apr_finfo_t *finfo)
980 {
981     char *to_send = tag_val;
982     request_rec *rr = NULL;
983     int ret=0;
984     char *error_fmt = NULL;
985     apr_status_t rv = APR_SUCCESS;
986
987     if (!strcmp(tag, "file")) {
988         /* be safe; only files in this directory or below allowed */
989         if (!is_only_below(tag_val)) {
990             error_fmt = "unable to access file \"%s\" "
991                         "in parsed file %s";
992         }
993         else {
994             ap_getparents(tag_val);    /* get rid of any nasties */
995
996             /* note: it is okay to pass NULL for the "next filter" since
997                we never attempt to "run" this sub request. */
998             rr = ap_sub_req_lookup_file(tag_val, r, NULL);
999
1000             if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
1001                 to_send = rr->filename;
1002                 if ((rv = apr_stat(finfo, to_send, APR_FINFO_GPROT 
1003                                 | APR_FINFO_MIN, rr->pool)) != APR_SUCCESS
1004                                                      && rv != APR_INCOMPLETE) {
1005                     error_fmt = "unable to get information about \"%s\" "
1006                         "in parsed file %s";
1007                 }
1008             }
1009             else {
1010                 error_fmt = "unable to lookup information about \"%s\" "
1011                             "in parsed file %s";
1012             }
1013         }
1014
1015         if (error_fmt) {
1016             ret = -1;
1017             ap_log_rerror(APLOG_MARK, APLOG_ERR | (rv ? 0 : APLOG_NOERRNO),
1018                           rv, r, error_fmt, to_send, r->filename);
1019         }
1020
1021         if (rr) ap_destroy_sub_req(rr);
1022         
1023         return ret;
1024     }
1025     else if (!strcmp(tag, "virtual")) {
1026         /* note: it is okay to pass NULL for the "next filter" since
1027            we never attempt to "run" this sub request. */
1028         rr = ap_sub_req_lookup_uri(tag_val, r, NULL);
1029
1030         if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
1031             memcpy((char *) finfo, (const char *) &rr->finfo,
1032                    sizeof(rr->finfo));
1033             ap_destroy_sub_req(rr);
1034             return 0;
1035         }
1036         else {
1037             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1038                         "unable to get information about \"%s\" "
1039                         "in parsed file %s",
1040                         tag_val, r->filename);
1041             ap_destroy_sub_req(rr);
1042             return -1;
1043         }
1044     }
1045     else {
1046         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1047                     "unknown parameter \"%s\" to tag %s in %s",
1048                     tag, directive, r->filename);
1049         return -1;
1050     }
1051 }
1052
1053 #define NEG_SIGN  "    -"
1054 #define ZERO_K    "   0k"
1055 #define ONE_K     "   1k"
1056
1057 static void generate_size(apr_ssize_t size, char *buff, apr_size_t buff_size)
1058 {
1059     /* XXX: this -1 thing is a gross hack */
1060     if (size == (apr_ssize_t)-1) {
1061         memcpy (buff, NEG_SIGN, sizeof(NEG_SIGN)+1);
1062     }
1063     else if (!size) {
1064         memcpy (buff, ZERO_K, sizeof(ZERO_K)+1);
1065     }
1066     else if (size < 1024) {
1067         memcpy (buff, ONE_K, sizeof(ONE_K)+1);
1068     }
1069     else if (size < 1048576) {
1070         apr_snprintf(buff, buff_size, "%4" APR_SSIZE_T_FMT "k", (size + 512) / 1024);
1071     }
1072     else if (size < 103809024) {
1073         apr_snprintf(buff, buff_size, "%4.1fM", size / 1048576.0);
1074     }
1075     else {
1076         apr_snprintf(buff, buff_size, "%4" APR_SSIZE_T_FMT "M", (size + 524288) / 1048576);
1077     }
1078 }
1079
1080 static int handle_fsize(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
1081                         ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
1082 {
1083     char *tag     = NULL;
1084     char *tag_val = NULL;
1085     apr_finfo_t  finfo;
1086     apr_size_t  s_len, s_wrt;
1087     apr_bucket   *tmp_buck;
1088     char parsed_string[MAX_STRING_LEN];
1089
1090     *inserted_head = NULL;
1091     if (ctx->flags & FLAG_PRINTING) {
1092         while (1) {
1093             ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 1);
1094             if (tag_val == NULL) {
1095                 if (tag == NULL) {
1096                     return 0;
1097                 }
1098                 else {
1099                     return 1;
1100                 }
1101             }
1102             else {
1103                 ap_ssi_parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
1104                 if (!find_file(r, "fsize", tag, parsed_string, &finfo)) {
1105                     char buff[50];
1106
1107                     if (!(ctx->flags & FLAG_SIZE_IN_BYTES)) {
1108                         generate_size(finfo.size, buff, sizeof(buff));
1109                         s_len = strlen (buff);
1110                     }
1111                     else {
1112                         int l, x, pos = 0;
1113                         char tmp_buff[50];
1114
1115                         apr_snprintf(tmp_buff, sizeof(tmp_buff), "%" APR_OFF_T_FMT, finfo.size);
1116                         l = strlen(tmp_buff);    /* grrr */
1117                         for (x = 0; x < l; x++) {
1118                             if (x && (!((l - x) % 3))) {
1119                                 buff[pos++] = ',';
1120                             }
1121                             buff[pos++] = tmp_buff[x];
1122                         }
1123                         buff[pos] = '\0';
1124                         s_len = pos;
1125                     }
1126
1127                     tmp_buck = apr_bucket_heap_create(buff, s_len, 1, &s_wrt);
1128                     APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
1129                     if (*inserted_head == NULL) {
1130                         *inserted_head = tmp_buck;
1131                     }
1132                 }
1133                 else {
1134                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1135                 }
1136             }
1137         }
1138     }
1139     return 0;
1140 }
1141
1142 static int handle_flastmod(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
1143                            ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
1144 {
1145     char *tag     = NULL;
1146     char *tag_val = NULL;
1147     apr_finfo_t  finfo;
1148     apr_size_t  t_len, t_wrt;
1149     apr_bucket   *tmp_buck;
1150     char parsed_string[MAX_STRING_LEN];
1151
1152     *inserted_head = NULL;
1153     if (ctx->flags & FLAG_PRINTING) {
1154         while (1) {
1155             ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 1);
1156             if (tag_val == NULL) {
1157                 if (tag == NULL) {
1158                     return 0;
1159                 }
1160                 else {
1161                     return 1;
1162                 }
1163             }
1164             else {
1165                 ap_ssi_parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
1166                 if (!find_file(r, "flastmod", tag, parsed_string, &finfo)) {
1167                     char *t_val;
1168
1169                     t_val = ap_ht_time(r->pool, finfo.mtime, ctx->time_str, 0);
1170                     t_len = strlen(t_val);
1171
1172                     tmp_buck = apr_bucket_heap_create(t_val, t_len, 1, &t_wrt);
1173                     APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
1174                     if (*inserted_head == NULL) {
1175                         *inserted_head = tmp_buck;
1176                     }
1177                 }
1178                 else {
1179                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1180                 }
1181             }
1182         }
1183     }
1184     return 0;
1185 }
1186
1187 static int re_check(request_rec *r, char *string, char *rexp)
1188 {
1189     regex_t *compiled;
1190     int regex_error;
1191
1192     compiled = ap_pregcomp(r->pool, rexp, REG_EXTENDED | REG_NOSUB);
1193     if (compiled == NULL) {
1194         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1195                     "unable to compile pattern \"%s\"", rexp);
1196         return -1;
1197     }
1198     regex_error = ap_regexec(compiled, string, 0, (regmatch_t *) NULL, 0);
1199     ap_pregfree(r->pool, compiled);
1200     return (!regex_error);
1201 }
1202
1203 enum token_type {
1204     token_string,
1205     token_and, token_or, token_not, token_eq, token_ne,
1206     token_rbrace, token_lbrace, token_group,
1207     token_ge, token_le, token_gt, token_lt
1208 };
1209 struct token {
1210     enum token_type type;
1211     char value[MAX_STRING_LEN];
1212 };
1213
1214 /* there is an implicit assumption here that string is at most MAX_STRING_LEN-1
1215  * characters long...
1216  */
1217 static const char *get_ptoken(request_rec *r, const char *string, struct token *token,
1218                               int *unmatched)
1219 {
1220     char ch;
1221     int next = 0;
1222     int qs = 0;
1223     int tkn_fnd = 0;
1224
1225     /* Skip leading white space */
1226     if (string == (char *) NULL) {
1227         return (char *) NULL;
1228     }
1229     while ((ch = *string++)) {
1230         if (!apr_isspace(ch)) {
1231             break;
1232         }
1233     }
1234     if (ch == '\0') {
1235         return (char *) NULL;
1236     }
1237
1238     token->type = token_string; /* the default type */
1239     switch (ch) {
1240     case '(':
1241         token->type = token_lbrace;
1242         return (string);
1243     case ')':
1244         token->type = token_rbrace;
1245         return (string);
1246     case '=':
1247         token->type = token_eq;
1248         return (string);
1249     case '!':
1250         if (*string == '=') {
1251             token->type = token_ne;
1252             return (string + 1);
1253         }
1254         else {
1255             token->type = token_not;
1256             return (string);
1257         }
1258     case '\'':
1259         token->type = token_string;
1260         qs = 1;
1261         break;
1262     case '|':
1263         if (*string == '|') {
1264             token->type = token_or;
1265             return (string + 1);
1266         }
1267         break;
1268     case '&':
1269         if (*string == '&') {
1270             token->type = token_and;
1271             return (string + 1);
1272         }
1273         break;
1274     case '>':
1275         if (*string == '=') {
1276             token->type = token_ge;
1277             return (string + 1);
1278         }
1279         else {
1280             token->type = token_gt;
1281             return (string);
1282         }
1283     case '<':
1284         if (*string == '=') {
1285             token->type = token_le;
1286             return (string + 1);
1287         }
1288         else {
1289             token->type = token_lt;
1290             return (string);
1291         }
1292     default:
1293         token->type = token_string;
1294         break;
1295     }
1296     /* We should only be here if we are in a string */
1297     if (!qs) {
1298         token->value[next++] = ch;
1299     }
1300
1301     /* 
1302      * Yes I know that goto's are BAD.  But, c doesn't allow me to
1303      * exit a loop from a switch statement.  Yes, I could use a flag,
1304      * but that is (IMHO) even less readable/maintainable than the goto.
1305      */
1306     /* 
1307      * I used the ++string throughout this section so that string
1308      * ends up pointing to the next token and I can just return it
1309      */
1310     for (ch = *string; ((ch != '\0') && (!tkn_fnd)); ch = *++string) {
1311         if (ch == '\\') {
1312             if ((ch = *++string) == '\0') {
1313                 tkn_fnd = 1;
1314             }
1315             else {
1316                 token->value[next++] = ch;
1317             }
1318         }
1319         else {
1320             if (!qs) {
1321                 if (apr_isspace(ch)) {
1322                     tkn_fnd = 1;
1323                 }
1324                 else {
1325                     switch (ch) {
1326                     case '(':
1327                     case ')':
1328                     case '=':
1329                     case '!':
1330                     case '<':
1331                     case '>':
1332                         tkn_fnd = 1;
1333                         break;
1334                     case '|':
1335                         if (*(string + 1) == '|') {
1336                             tkn_fnd = 1;
1337                         }
1338                         break;
1339                     case '&':
1340                         if (*(string + 1) == '&') {
1341                             tkn_fnd = 1;
1342                         }
1343                         break;
1344                     }
1345                     if (!tkn_fnd) {
1346                         token->value[next++] = ch;
1347                     }
1348                 }
1349             }
1350             else {
1351                 if (ch == '\'') {
1352                     qs = 0;
1353                     ++string;
1354                     tkn_fnd = 1;
1355                 }
1356                 else {
1357                     token->value[next++] = ch;
1358                 }
1359             }
1360         }
1361     }
1362
1363     /* If qs is still set, I have an unmatched ' */
1364     if (qs) {
1365         *unmatched = 1;
1366         next = 0;
1367     }
1368     token->value[next] = '\0';
1369     return (string);
1370 }
1371
1372
1373 /*
1374  * Hey I still know that goto's are BAD.  I don't think that I've ever
1375  * used two in the same project, let alone the same file before.  But,
1376  * I absolutely want to make sure that I clean up the memory in all
1377  * cases.  And, without rewriting this completely, the easiest way
1378  * is to just branch to the return code which cleans it up.
1379  */
1380 /* there is an implicit assumption here that expr is at most MAX_STRING_LEN-1
1381  * characters long...
1382  */
1383 static int parse_expr(request_rec *r, const char *expr, int *was_error, 
1384                       int *was_unmatched, char *debug)
1385 {
1386     struct parse_node {
1387         struct parse_node *left, *right, *parent;
1388         struct token token;
1389         int value, done;
1390     }         *root, *current, *new;
1391     const char *parse;
1392     char buffer[MAX_STRING_LEN];
1393     apr_pool_t *expr_pool;
1394     int retval = 0;
1395     apr_size_t debug_pos = 0;
1396
1397     debug[debug_pos] = '\0';
1398     *was_error       = 0;
1399     *was_unmatched   = 0;
1400     if ((parse = expr) == (char *) NULL) {
1401         return (0);
1402     }
1403     root = current = (struct parse_node *) NULL;
1404     if (apr_pool_create(&expr_pool, r->pool) != APR_SUCCESS)
1405                 return 0;
1406
1407     /* Create Parse Tree */
1408     while (1) {
1409         new = (struct parse_node *) apr_palloc(expr_pool,
1410                                            sizeof(struct parse_node));
1411         new->parent = new->left = new->right = (struct parse_node *) NULL;
1412         new->done = 0;
1413         if ((parse = get_ptoken(r, parse, &new->token, was_unmatched)) == (char *) NULL) {
1414             break;
1415         }
1416         switch (new->token.type) {
1417
1418         case token_string:
1419 #ifdef DEBUG_INCLUDE
1420             debug_pos += sprintf (&debug[debug_pos], "     Token: string (%s)\n",
1421                                   new->token.value);
1422 #endif
1423             if (current == (struct parse_node *) NULL) {
1424                 root = current = new;
1425                 break;
1426             }
1427             switch (current->token.type) {
1428             case token_string:
1429                 if (current->token.value[0] != '\0') {
1430                     strncat(current->token.value, " ",
1431                          sizeof(current->token.value)
1432                             - strlen(current->token.value) - 1);
1433                 }
1434                 strncat(current->token.value, new->token.value,
1435                          sizeof(current->token.value)
1436                             - strlen(current->token.value) - 1);
1437                 current->token.value[sizeof(current->token.value) - 1] = '\0';
1438                 break;
1439             case token_eq:
1440             case token_ne:
1441             case token_and:
1442             case token_or:
1443             case token_lbrace:
1444             case token_not:
1445             case token_ge:
1446             case token_gt:
1447             case token_le:
1448             case token_lt:
1449                 new->parent = current;
1450                 current = current->right = new;
1451                 break;
1452             default:
1453                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1454                             "Invalid expression \"%s\" in file %s",
1455                             expr, r->filename);
1456                 *was_error = 1;
1457                 goto RETURN;
1458             }
1459             break;
1460
1461         case token_and:
1462         case token_or:
1463 #ifdef DEBUG_INCLUDE
1464             memcpy (&debug[debug_pos], "     Token: and/or\n",
1465                     sizeof ("     Token: and/or\n"));
1466             debug_pos += sizeof ("     Token: and/or\n");
1467 #endif
1468             if (current == (struct parse_node *) NULL) {
1469                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1470                             "Invalid expression \"%s\" in file %s",
1471                             expr, r->filename);
1472                 *was_error = 1;
1473                 goto RETURN;
1474             }
1475             /* Percolate upwards */
1476             while (current != (struct parse_node *) NULL) {
1477                 switch (current->token.type) {
1478                 case token_string:
1479                 case token_group:
1480                 case token_not:
1481                 case token_eq:
1482                 case token_ne:
1483                 case token_and:
1484                 case token_or:
1485                 case token_ge:
1486                 case token_gt:
1487                 case token_le:
1488                 case token_lt:
1489                     current = current->parent;
1490                     continue;
1491                 case token_lbrace:
1492                     break;
1493                 default:
1494                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1495                                 "Invalid expression \"%s\" in file %s",
1496                                 expr, r->filename);
1497                     *was_error = 1;
1498                     goto RETURN;
1499                 }
1500                 break;
1501             }
1502             if (current == (struct parse_node *) NULL) {
1503                 new->left = root;
1504                 new->left->parent = new;
1505                 new->parent = (struct parse_node *) NULL;
1506                 root = new;
1507             }
1508             else {
1509                 new->left = current->right;
1510                 current->right = new;
1511                 new->parent = current;
1512             }
1513             current = new;
1514             break;
1515
1516         case token_not:
1517 #ifdef DEBUG_INCLUDE
1518             memcpy (&debug[debug_pos], "     Token: not\n",
1519                     sizeof ("     Token: not\n"));
1520             debug_pos += sizeof ("     Token: not\n");
1521 #endif
1522             if (current == (struct parse_node *) NULL) {
1523                 root = current = new;
1524                 break;
1525             }
1526             /* Percolate upwards */
1527             while (current != (struct parse_node *) NULL) {
1528                 switch (current->token.type) {
1529                 case token_not:
1530                 case token_eq:
1531                 case token_ne:
1532                 case token_and:
1533                 case token_or:
1534                 case token_lbrace:
1535                 case token_ge:
1536                 case token_gt:
1537                 case token_le:
1538                 case token_lt:
1539                     break;
1540                 default:
1541                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1542                                 "Invalid expression \"%s\" in file %s",
1543                                 expr, r->filename);
1544                     *was_error = 1;
1545                     goto RETURN;
1546                 }
1547                 break;
1548             }
1549             if (current == (struct parse_node *) NULL) {
1550                 new->left = root;
1551                 new->left->parent = new;
1552                 new->parent = (struct parse_node *) NULL;
1553                 root = new;
1554             }
1555             else {
1556                 new->left = current->right;
1557                 current->right = new;
1558                 new->parent = current;
1559             }
1560             current = new;
1561             break;
1562
1563         case token_eq:
1564         case token_ne:
1565         case token_ge:
1566         case token_gt:
1567         case token_le:
1568         case token_lt:
1569 #ifdef DEBUG_INCLUDE
1570             memcpy (&debug[debug_pos], "     Token: eq/ne/ge/gt/le/lt\n",
1571                     sizeof ("     Token: eq/ne/ge/gt/le/lt\n"));
1572             debug_pos += sizeof ("     Token: eq/ne/ge/gt/le/lt\n");
1573 #endif
1574             if (current == (struct parse_node *) NULL) {
1575                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1576                             "Invalid expression \"%s\" in file %s",
1577                             expr, r->filename);
1578                 *was_error = 1;
1579                 goto RETURN;
1580             }
1581             /* Percolate upwards */
1582             while (current != (struct parse_node *) NULL) {
1583                 switch (current->token.type) {
1584                 case token_string:
1585                 case token_group:
1586                     current = current->parent;
1587                     continue;
1588                 case token_lbrace:
1589                 case token_and:
1590                 case token_or:
1591                     break;
1592                 case token_not:
1593                 case token_eq:
1594                 case token_ne:
1595                 case token_ge:
1596                 case token_gt:
1597                 case token_le:
1598                 case token_lt:
1599                 default:
1600                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1601                                 "Invalid expression \"%s\" in file %s",
1602                                 expr, r->filename);
1603                     *was_error = 1;
1604                     goto RETURN;
1605                 }
1606                 break;
1607             }
1608             if (current == (struct parse_node *) NULL) {
1609                 new->left = root;
1610                 new->left->parent = new;
1611                 new->parent = (struct parse_node *) NULL;
1612                 root = new;
1613             }
1614             else {
1615                 new->left = current->right;
1616                 current->right = new;
1617                 new->parent = current;
1618             }
1619             current = new;
1620             break;
1621
1622         case token_rbrace:
1623 #ifdef DEBUG_INCLUDE
1624             memcpy (&debug[debug_pos], "     Token: rbrace\n",
1625                     sizeof ("     Token: rbrace\n"));
1626             debug_pos += sizeof ("     Token: rbrace\n");
1627 #endif
1628             while (current != (struct parse_node *) NULL) {
1629                 if (current->token.type == token_lbrace) {
1630                     current->token.type = token_group;
1631                     break;
1632                 }
1633                 current = current->parent;
1634             }
1635             if (current == (struct parse_node *) NULL) {
1636                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1637                             "Unmatched ')' in \"%s\" in file %s",
1638                             expr, r->filename);
1639                 *was_error = 1;
1640                 goto RETURN;
1641             }
1642             break;
1643
1644         case token_lbrace:
1645 #ifdef DEBUG_INCLUDE
1646             memcpy (&debug[debug_pos], "     Token: lbrace\n",
1647                     sizeof ("     Token: lbrace\n"));
1648             debug_pos += sizeof ("     Token: lbrace\n");
1649 #endif
1650             if (current == (struct parse_node *) NULL) {
1651                 root = current = new;
1652                 break;
1653             }
1654             /* Percolate upwards */
1655             while (current != (struct parse_node *) NULL) {
1656                 switch (current->token.type) {
1657                 case token_not:
1658                 case token_eq:
1659                 case token_ne:
1660                 case token_and:
1661                 case token_or:
1662                 case token_lbrace:
1663                 case token_ge:
1664                 case token_gt:
1665                 case token_le:
1666                 case token_lt:
1667                     break;
1668                 case token_string:
1669                 case token_group:
1670                 default:
1671                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1672                                 "Invalid expression \"%s\" in file %s",
1673                                 expr, r->filename);
1674                     *was_error = 1;
1675                     goto RETURN;
1676                 }
1677                 break;
1678             }
1679             if (current == (struct parse_node *) NULL) {
1680                 new->left = root;
1681                 new->left->parent = new;
1682                 new->parent = (struct parse_node *) NULL;
1683                 root = new;
1684             }
1685             else {
1686                 new->left = current->right;
1687                 current->right = new;
1688                 new->parent = current;
1689             }
1690             current = new;
1691             break;
1692         default:
1693             break;
1694         }
1695     }
1696
1697     /* Evaluate Parse Tree */
1698     current = root;
1699     while (current != (struct parse_node *) NULL) {
1700         switch (current->token.type) {
1701         case token_string:
1702 #ifdef DEBUG_INCLUDE
1703             memcpy (&debug[debug_pos], "     Evaluate string\n",
1704                     sizeof ("     Evaluate string\n"));
1705             debug_pos += sizeof ("     Evaluate string\n");
1706 #endif
1707             ap_ssi_parse_string(r, current->token.value, buffer, sizeof(buffer), 0);
1708             apr_cpystrn(current->token.value, buffer, sizeof(current->token.value));
1709             current->value = (current->token.value[0] != '\0');
1710             current->done = 1;
1711             current = current->parent;
1712             break;
1713
1714         case token_and:
1715         case token_or:
1716 #ifdef DEBUG_INCLUDE
1717             memcpy (&debug[debug_pos], "     Evaluate and/or\n",
1718                     sizeof ("     Evaluate and/or\n"));
1719             debug_pos += sizeof ("     Evaluate and/or\n");
1720 #endif
1721             if (current->left == (struct parse_node *) NULL ||
1722                 current->right == (struct parse_node *) NULL) {
1723                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1724                             "Invalid expression \"%s\" in file %s",
1725                             expr, r->filename);
1726                 *was_error = 1;
1727                 goto RETURN;
1728             }
1729             if (!current->left->done) {
1730                 switch (current->left->token.type) {
1731                 case token_string:
1732                     ap_ssi_parse_string(r, current->left->token.value,
1733                                  buffer, sizeof(buffer), 0);
1734                     apr_cpystrn(current->left->token.value, buffer,
1735                             sizeof(current->left->token.value));
1736                     current->left->value = (current->left->token.value[0] != '\0');
1737                     current->left->done = 1;
1738                     break;
1739                 default:
1740                     current = current->left;
1741                     continue;
1742                 }
1743             }
1744             if (!current->right->done) {
1745                 switch (current->right->token.type) {
1746                 case token_string:
1747                     ap_ssi_parse_string(r, current->right->token.value,
1748                                  buffer, sizeof(buffer), 0);
1749                     apr_cpystrn(current->right->token.value, buffer,
1750                             sizeof(current->right->token.value));
1751                     current->right->value = (current->right->token.value[0] != '\0');
1752                     current->right->done = 1;
1753                     break;
1754                 default:
1755                     current = current->right;
1756                     continue;
1757                 }
1758             }
1759 #ifdef DEBUG_INCLUDE
1760             debug_pos += sprintf (&debug[debug_pos], "     Left: %c\n",
1761                                   current->left->value ? '1' : '0');
1762             debug_pos += sprintf (&debug[debug_pos], "     Right: %c\n",
1763                                   current->right->value ? '1' : '0');
1764 #endif
1765             if (current->token.type == token_and) {
1766                 current->value = current->left->value && current->right->value;
1767             }
1768             else {
1769                 current->value = current->left->value || current->right->value;
1770             }
1771 #ifdef DEBUG_INCLUDE
1772             debug_pos += sprintf (&debug[debug_pos], "     Returning %c\n",
1773                                   current->value ? '1' : '0');
1774 #endif
1775             current->done = 1;
1776             current = current->parent;
1777             break;
1778
1779         case token_eq:
1780         case token_ne:
1781 #ifdef DEBUG_INCLUDE
1782             memcpy (&debug[debug_pos], "     Evaluate eq/ne\n",
1783                     sizeof ("     Evaluate eq/ne\n"));
1784             debug_pos += sizeof ("     Evaluate eq/ne\n");
1785 #endif
1786             if ((current->left == (struct parse_node *) NULL) ||
1787                 (current->right == (struct parse_node *) NULL) ||
1788                 (current->left->token.type != token_string) ||
1789                 (current->right->token.type != token_string)) {
1790                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1791                             "Invalid expression \"%s\" in file %s",
1792                             expr, r->filename);
1793                 *was_error = 1;
1794                 goto RETURN;
1795             }
1796             ap_ssi_parse_string(r, current->left->token.value,
1797                          buffer, sizeof(buffer), 0);
1798             apr_cpystrn(current->left->token.value, buffer,
1799                         sizeof(current->left->token.value));
1800             ap_ssi_parse_string(r, current->right->token.value,
1801                          buffer, sizeof(buffer), 0);
1802             apr_cpystrn(current->right->token.value, buffer,
1803                         sizeof(current->right->token.value));
1804             if (current->right->token.value[0] == '/') {
1805                 int len;
1806                 len = strlen(current->right->token.value);
1807                 if (current->right->token.value[len - 1] == '/') {
1808                     current->right->token.value[len - 1] = '\0';
1809                 }
1810                 else {
1811                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1812                                 "Invalid rexp \"%s\" in file %s",
1813                                 current->right->token.value, r->filename);
1814                     *was_error = 1;
1815                     goto RETURN;
1816                 }
1817 #ifdef DEBUG_INCLUDE
1818                 debug_pos += sprintf (&debug[debug_pos],
1819                                       "     Re Compare (%s) with /%s/\n",
1820                                       current->left->token.value,
1821                                       &current->right->token.value[1]);
1822 #endif
1823                 current->value =
1824                     re_check(r, current->left->token.value,
1825                              &current->right->token.value[1]);
1826             }
1827             else {
1828 #ifdef DEBUG_INCLUDE
1829                 debug_pos += sprintf (&debug[debug_pos],
1830                                       "     Compare (%s) with (%s)\n",
1831                                       current->left->token.value,
1832                                       current->right->token.value);
1833 #endif
1834                 current->value =
1835                     (strcmp(current->left->token.value,
1836                             current->right->token.value) == 0);
1837             }
1838             if (current->token.type == token_ne) {
1839                 current->value = !current->value;
1840             }
1841 #ifdef DEBUG_INCLUDE
1842             debug_pos += sprintf (&debug[debug_pos], "     Returning %c\n",
1843                                   current->value ? '1' : '0');
1844 #endif
1845             current->done = 1;
1846             current = current->parent;
1847             break;
1848         case token_ge:
1849         case token_gt:
1850         case token_le:
1851         case token_lt:
1852 #ifdef DEBUG_INCLUDE
1853             memcpy (&debug[debug_pos], "     Evaluate ge/gt/le/lt\n",
1854                     sizeof ("     Evaluate ge/gt/le/lt\n"));
1855             debug_pos += sizeof ("     Evaluate ge/gt/le/lt\n");
1856 #endif
1857             if ((current->left == (struct parse_node *) NULL) ||
1858                 (current->right == (struct parse_node *) NULL) ||
1859                 (current->left->token.type != token_string) ||
1860                 (current->right->token.type != token_string)) {
1861                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1862                             "Invalid expression \"%s\" in file %s",
1863                             expr, r->filename);
1864                 *was_error = 1;
1865                 goto RETURN;
1866             }
1867             ap_ssi_parse_string(r, current->left->token.value,
1868                          buffer, sizeof(buffer), 0);
1869             apr_cpystrn(current->left->token.value, buffer,
1870                         sizeof(current->left->token.value));
1871             ap_ssi_parse_string(r, current->right->token.value,
1872                          buffer, sizeof(buffer), 0);
1873             apr_cpystrn(current->right->token.value, buffer,
1874                         sizeof(current->right->token.value));
1875 #ifdef DEBUG_INCLUDE
1876             debug_pos += sprintf (&debug[debug_pos],
1877                                   "     Compare (%s) with (%s)\n",
1878                                   current->left->token.value,
1879                                   current->right->token.value);
1880 #endif
1881             current->value =
1882                 strcmp(current->left->token.value,
1883                        current->right->token.value);
1884             if (current->token.type == token_ge) {
1885                 current->value = current->value >= 0;
1886             }
1887             else if (current->token.type == token_gt) {
1888                 current->value = current->value > 0;
1889             }
1890             else if (current->token.type == token_le) {
1891                 current->value = current->value <= 0;
1892             }
1893             else if (current->token.type == token_lt) {
1894                 current->value = current->value < 0;
1895             }
1896             else {
1897                 current->value = 0;     /* Don't return -1 if unknown token */
1898             }
1899 #ifdef DEBUG_INCLUDE
1900             debug_pos += sprintf (&debug[debug_pos], "     Returning %c\n",
1901                                   current->value ? '1' : '0');
1902 #endif
1903             current->done = 1;
1904             current = current->parent;
1905             break;
1906
1907         case token_not:
1908             if (current->right != (struct parse_node *) NULL) {
1909                 if (!current->right->done) {
1910                     current = current->right;
1911                     continue;
1912                 }
1913                 current->value = !current->right->value;
1914             }
1915             else {
1916                 current->value = 0;
1917             }
1918 #ifdef DEBUG_INCLUDE
1919             debug_pos += sprintf (&debug[debug_pos], "     Evaluate !: %c\n",
1920                                   current->value ? '1' : '0');
1921 #endif
1922             current->done = 1;
1923             current = current->parent;
1924             break;
1925
1926         case token_group:
1927             if (current->right != (struct parse_node *) NULL) {
1928                 if (!current->right->done) {
1929                     current = current->right;
1930                     continue;
1931                 }
1932                 current->value = current->right->value;
1933             }
1934             else {
1935                 current->value = 1;
1936             }
1937 #ifdef DEBUG_INCLUDE
1938             debug_pos += sprintf (&debug[debug_pos], "     Evaluate (): %c\n",
1939                                   current->value ? '1' : '0');
1940 #endif
1941             current->done = 1;
1942             current = current->parent;
1943             break;
1944
1945         case token_lbrace:
1946             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1947                         "Unmatched '(' in \"%s\" in file %s",
1948                         expr, r->filename);
1949             *was_error = 1;
1950             goto RETURN;
1951
1952         case token_rbrace:
1953             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1954                         "Unmatched ')' in \"%s\" in file %s",
1955                         expr, r->filename);
1956             *was_error = 1;
1957             goto RETURN;
1958
1959         default:
1960             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1961                           "bad token type");
1962             *was_error = 1;
1963             goto RETURN;
1964         }
1965     }
1966
1967     retval = (root == (struct parse_node *) NULL) ? 0 : root->value;
1968   RETURN:
1969     apr_pool_destroy(expr_pool);
1970     return (retval);
1971 }
1972
1973 /*-------------------------------------------------------------------------*/
1974 #ifdef DEBUG_INCLUDE
1975
1976 /* XXX overlaying the static string pointed to by cond_txt isn't cool */
1977
1978 #define MAX_DEBUG_SIZE MAX_STRING_LEN
1979 #define LOG_COND_STATUS(cntx, t_buck, h_ptr, ins_head, tag_text)           \
1980 {                                                                          \
1981     char *cond_txt = "**** X     conditional_status=\"0\"\n";              \
1982     apr_size_t c_wrt;                                                      \
1983                                                                            \
1984     if (cntx->flags & FLAG_COND_TRUE) {                                    \
1985         cond_txt[31] = '1';                                                \
1986     }                                                                      \
1987     memcpy(&cond_txt[5], tag_text, sizeof(tag_text));                      \
1988     t_buck = apr_bucket_heap_create(cond_txt, sizeof(cond_txt), 1, &c_wrt); \
1989     APR_BUCKET_INSERT_BEFORE(h_ptr, t_buck);                                \
1990                                                                            \
1991     if (ins_head == NULL) {                                                \
1992         ins_head = t_buck;                                                 \
1993     }                                                                      \
1994 }
1995 #define DUMP_PARSE_EXPR_DEBUG(t_buck, h_ptr, d_buf, ins_head)            \
1996 {                                                                        \
1997     apr_size_t b_wrt;                                                    \
1998     if (d_buf[0] != '\0') {                                              \
1999         t_buck = apr_bucket_heap_create(d_buf, strlen(d_buf), 1, &b_wrt); \
2000         APR_BUCKET_INSERT_BEFORE(h_ptr, t_buck);                          \
2001                                                                          \
2002         if (ins_head == NULL) {                                          \
2003             ins_head = t_buck;                                           \
2004         }                                                                \
2005     }                                                                    \
2006 }
2007 #else
2008
2009 #define MAX_DEBUG_SIZE 10
2010 #define LOG_COND_STATUS(cntx, t_buck, h_ptr, ins_head, tag_text)
2011 #define DUMP_PARSE_EXPR_DEBUG(t_buck, h_ptr, d_buf, ins_head)
2012
2013 #endif
2014 /*-------------------------------------------------------------------------*/
2015
2016 /* pjr - These seem to allow expr="fred" expr="joe" where joe overwrites fred. */
2017 static int handle_if(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
2018                      ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
2019 {
2020     char *tag     = NULL;
2021     char *tag_val = NULL;
2022     char *expr    = NULL;
2023     int   expr_ret, was_error, was_unmatched;
2024     apr_bucket *tmp_buck;
2025     char debug_buf[MAX_DEBUG_SIZE];
2026
2027     *inserted_head = NULL;
2028     if (!ctx->flags & FLAG_PRINTING) {
2029         ctx->if_nesting_level++;
2030     }
2031     else {
2032         while (1) {
2033             ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 0);
2034             if (tag == NULL) {
2035                 if (expr == NULL) {
2036                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2037                                   "missing expr in if statement: %s", r->filename);
2038                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2039                     return 1;
2040                 }
2041                 expr_ret = parse_expr(r, expr, &was_error, &was_unmatched, debug_buf);
2042                 if (was_error) {
2043                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2044                     return 1;
2045                 }
2046                 if (was_unmatched) {
2047                     DUMP_PARSE_EXPR_DEBUG(tmp_buck, head_ptr, "\nUnmatched '\n",
2048                                           *inserted_head);
2049                 }
2050                 DUMP_PARSE_EXPR_DEBUG(tmp_buck, head_ptr, debug_buf, *inserted_head);
2051                 
2052                 if (expr_ret) {
2053                     ctx->flags |= (FLAG_PRINTING | FLAG_COND_TRUE);
2054                 }
2055                 else {
2056                     ctx->flags &= FLAG_CLEAR_PRINT_COND;
2057                 }
2058                 LOG_COND_STATUS(ctx, tmp_buck, head_ptr, *inserted_head, "   if");
2059                 ctx->if_nesting_level = 0;
2060                 return 0;
2061             }
2062             else if (!strcmp(tag, "expr")) {
2063                 expr = tag_val;
2064 #ifdef DEBUG_INCLUDE
2065                 if (1) {
2066                     apr_size_t d_len = 0, d_wrt = 0;
2067                     d_len = sprintf(debug_buf, "**** if expr=\"%s\"\n", expr);
2068                     tmp_buck = apr_bucket_heap_create(debug_buf, d_len, 1, &d_wrt);
2069                     APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
2070
2071                     if (*inserted_head == NULL) {
2072                         *inserted_head = tmp_buck;
2073                     }
2074                 }
2075 #endif
2076             }
2077             else {
2078                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2079                             "unknown parameter \"%s\" to tag if in %s", tag, r->filename);
2080                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2081             }
2082
2083         }
2084     }
2085     return 0;
2086 }
2087
2088 static int handle_elif(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
2089                        ap_filter_t *f,  apr_bucket *head_ptr, apr_bucket **inserted_head)
2090 {
2091     char *tag     = NULL;
2092     char *tag_val = NULL;
2093     char *expr    = NULL;
2094     int   expr_ret, was_error, was_unmatched;
2095     apr_bucket *tmp_buck;
2096     char debug_buf[MAX_DEBUG_SIZE];
2097
2098     *inserted_head = NULL;
2099     if (!ctx->if_nesting_level) {
2100         while (1) {
2101             ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 0);
2102             if (tag == '\0') {
2103                 LOG_COND_STATUS(ctx, tmp_buck, head_ptr, *inserted_head, " elif");
2104                 
2105                 if (ctx->flags & FLAG_COND_TRUE) {
2106                     ctx->flags &= FLAG_CLEAR_PRINTING;
2107                     return (0);
2108                 }
2109                 if (expr == NULL) {
2110                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2111                                   "missing expr in elif statement: %s", r->filename);
2112                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2113                     return (1);
2114                 }
2115                 expr_ret = parse_expr(r, expr, &was_error, &was_unmatched, debug_buf);
2116                 if (was_error) {
2117                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2118                     return 1;
2119                 }
2120                 if (was_unmatched) {
2121                     DUMP_PARSE_EXPR_DEBUG(tmp_buck, head_ptr, "\nUnmatched '\n",
2122                                           *inserted_head);
2123                 }
2124                 DUMP_PARSE_EXPR_DEBUG(tmp_buck, head_ptr, debug_buf, *inserted_head);
2125                 
2126                 if (expr_ret) {
2127                     ctx->flags |= (FLAG_PRINTING | FLAG_COND_TRUE);
2128                 }
2129                 else {
2130                     ctx->flags &= FLAG_CLEAR_PRINT_COND;
2131                 }
2132                 LOG_COND_STATUS(ctx, tmp_buck, head_ptr, *inserted_head, " elif");
2133                 return (0);
2134             }
2135             else if (!strcmp(tag, "expr")) {
2136                 expr = tag_val;
2137 #ifdef DEBUG_INCLUDE
2138                 if (1) {
2139                     apr_size_t d_len = 0, d_wrt = 0;
2140                     d_len = sprintf(debug_buf, "**** elif expr=\"%s\"\n", expr);
2141                     tmp_buck = apr_bucket_heap_create(debug_buf, d_len, 1, &d_wrt);
2142                     APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
2143
2144                     if (*inserted_head == NULL) {
2145                         *inserted_head = tmp_buck;
2146                     }
2147                 }
2148 #endif
2149             }
2150             else {
2151                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2152                             "unknown parameter \"%s\" to tag if in %s", tag, r->filename);
2153                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2154             }
2155         }
2156     }
2157     return 0;
2158 }
2159
2160 static int handle_else(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
2161                        ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
2162 {
2163     char *tag = NULL;
2164     char *tag_val = NULL;
2165     apr_bucket *tmp_buck;
2166
2167     *inserted_head = NULL;
2168     if (!ctx->if_nesting_level) {
2169         ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 1);
2170         if ((tag != NULL) || (tag_val != NULL)) {
2171             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2172                         "else directive does not take tags in %s", r->filename);
2173             if (ctx->flags & FLAG_PRINTING) {
2174                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2175             }
2176             return -1;
2177         }
2178         else {
2179             LOG_COND_STATUS(ctx, tmp_buck, head_ptr, *inserted_head, " else");
2180             
2181             if (ctx->flags & FLAG_COND_TRUE) {
2182                 ctx->flags &= FLAG_CLEAR_PRINTING;
2183             }
2184             else {
2185                 ctx->flags |= (FLAG_PRINTING | FLAG_COND_TRUE);
2186             }
2187             return 0;
2188         }
2189     }
2190     return 0;
2191 }
2192
2193 static int handle_endif(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
2194                         ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
2195 {
2196     char *tag     = NULL;
2197     char *tag_val = NULL;
2198     apr_bucket *tmp_buck;
2199
2200     *inserted_head = NULL;
2201     if (!ctx->if_nesting_level) {
2202         ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 1);
2203         if ((tag != NULL) || (tag_val != NULL)) {
2204             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2205                         "endif directive does not take tags in %s", r->filename);
2206             CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2207             return -1;
2208         }
2209         else {
2210             LOG_COND_STATUS(ctx, tmp_buck, head_ptr, *inserted_head, "endif");
2211             ctx->flags |= (FLAG_PRINTING | FLAG_COND_TRUE);
2212             return 0;
2213         }
2214     }
2215     else {
2216         ctx->if_nesting_level--;
2217         return 0;
2218     }
2219 }
2220
2221 static int handle_set(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
2222                       ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
2223 {
2224     char *tag     = NULL;
2225     char *tag_val = NULL;
2226     char *var     = NULL;
2227     apr_bucket *tmp_buck;
2228     char parsed_string[MAX_STRING_LEN];
2229
2230     *inserted_head = NULL;
2231     if (ctx->flags & FLAG_PRINTING) {
2232         while (1) {
2233             ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 1);
2234             if ((tag == NULL) && (tag_val == NULL)) {
2235                 return 0;
2236             }
2237             else if (tag_val == NULL) {
2238                 return 1;
2239             }
2240             else if (!strcmp(tag, "var")) {
2241                 var = tag_val;
2242             }
2243             else if (!strcmp(tag, "value")) {
2244                 if (var == (char *) NULL) {
2245                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2246                                 "variable must precede value in set directive in %s",
2247                             r->filename);
2248                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2249                     return (-1);
2250                 }
2251                 ap_ssi_parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
2252                 apr_table_setn(r->subprocess_env, apr_pstrdup(r->pool, var),
2253                                apr_pstrdup(r->pool, parsed_string));
2254             }
2255             else {
2256                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2257                             "Invalid tag for set directive in %s", r->filename);
2258                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2259                 return -1;
2260             }
2261         }
2262     }
2263     return 0;
2264 }
2265
2266 static int handle_printenv(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
2267                            ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
2268 {
2269     char *tag     = NULL;
2270     char *tag_val = NULL;
2271     apr_bucket *tmp_buck;
2272
2273     if (ctx->flags & FLAG_PRINTING) {
2274         ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, 1);
2275         if ((tag == NULL) && (tag_val == NULL)) {
2276             apr_array_header_t *arr = apr_table_elts(r->subprocess_env);
2277             apr_table_entry_t *elts = (apr_table_entry_t *)arr->elts;
2278             int i;
2279             char *key_text, *val_text;
2280             apr_size_t   k_len, v_len, t_wrt;
2281
2282             *inserted_head = NULL;
2283             for (i = 0; i < arr->nelts; ++i) {
2284                 key_text = ap_escape_html(r->pool, elts[i].key);
2285                 val_text = ap_escape_html(r->pool, elts[i].val);
2286                 k_len = strlen(key_text);
2287                 v_len = strlen(val_text);
2288
2289                 /*  Key_text                                               */
2290                 tmp_buck = apr_bucket_heap_create(key_text, k_len, 1, &t_wrt);
2291                 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
2292                 if (*inserted_head == NULL) {
2293                     *inserted_head = tmp_buck;
2294                 }
2295                 /*            =                                            */
2296                 tmp_buck = apr_bucket_immortal_create("=", 1);
2297                 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
2298                 /*              Value_text                                 */
2299                 tmp_buck = apr_bucket_heap_create(val_text, v_len, 1, &t_wrt);
2300                 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
2301                 /*                        newline...                       */
2302                 tmp_buck = apr_bucket_immortal_create("\n", 1);
2303                 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
2304             }
2305             return 0;
2306         }
2307         else {
2308             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2309                         "printenv directive does not take tags in %s", r->filename);
2310             CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
2311             return -1;
2312         }
2313     }
2314     return 0;
2315 }
2316
2317 /* -------------------------- The main function --------------------------- */
2318
2319 static void send_parsed_content(apr_bucket_brigade **bb, request_rec *r, 
2320                                 ap_filter_t *f)
2321 {
2322     include_ctx_t *ctx = f->ctx;
2323     apr_bucket *dptr = APR_BRIGADE_FIRST(*bb);
2324     apr_bucket *tmp_dptr;
2325     apr_bucket_brigade *tag_and_after;
2326     int ret;
2327
2328     if (r->args) {              /* add QUERY stuff to env cause it ain't yet */
2329         char *arg_copy = apr_pstrdup(r->pool, r->args);
2330
2331         apr_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
2332         ap_unescape_url(arg_copy);
2333         apr_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
2334                   ap_escape_shell_cmd(r->pool, arg_copy));
2335     }
2336
2337     while (dptr != APR_BRIGADE_SENTINEL(*bb)) {
2338         /* State to check for the STARTING_SEQUENCE. */
2339         if ((ctx->state == PRE_HEAD) || (ctx->state == PARSE_HEAD)) {
2340             int do_cleanup = 0;
2341             apr_size_t cleanup_bytes = ctx->parse_pos;
2342
2343             tmp_dptr = find_start_sequence(dptr, ctx, *bb, &do_cleanup);
2344
2345             /* The few bytes stored in the ssi_tag_brigade turned out not to
2346              * be a tag after all. This can only happen if the starting
2347              * tag actually spans brigades. This should be very rare.
2348              */
2349             if ((do_cleanup) && (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade))) {
2350                 apr_bucket *tmp_bkt;
2351
2352                 tmp_bkt = apr_bucket_immortal_create(STARTING_SEQUENCE, cleanup_bytes);
2353                 APR_BRIGADE_INSERT_HEAD(*bb, tmp_bkt);
2354
2355                 while (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
2356                     tmp_bkt = APR_BRIGADE_FIRST(ctx->ssi_tag_brigade);
2357                     apr_bucket_delete(tmp_bkt);
2358                 }
2359             }
2360
2361             /* If I am inside a conditional (if, elif, else) that is false
2362              *   then I need to throw away anything contained in it.
2363              */
2364             if ((!(ctx->flags & FLAG_PRINTING)) && (tmp_dptr != NULL) &&
2365                 (dptr != APR_BRIGADE_SENTINEL(*bb))) {
2366                 while ((dptr != APR_BRIGADE_SENTINEL(*bb)) &&
2367                        (dptr != tmp_dptr)) {
2368                     apr_bucket *free_bucket = dptr;
2369
2370                     dptr = APR_BUCKET_NEXT (dptr);
2371                     apr_bucket_delete(free_bucket);
2372                 }
2373             }
2374
2375             /* Adjust the current bucket position based on what was found... */
2376             if ((tmp_dptr != NULL) && (ctx->state == PARSE_DIRECTIVE)) {
2377                 if (ctx->tag_start_bucket != NULL) {
2378                     dptr = ctx->tag_start_bucket;
2379                 }
2380                 else {
2381                     dptr = APR_BRIGADE_SENTINEL(*bb);
2382                 }
2383             }
2384             else if (tmp_dptr == NULL) { /* There was no possible SSI tag in the */
2385                 dptr = APR_BRIGADE_SENTINEL(*bb);  /* remainder of this brigade...    */
2386             }
2387         }
2388
2389         /* State to check for the ENDING_SEQUENCE. */
2390         if (((ctx->state == PARSE_DIRECTIVE) ||
2391              (ctx->state == PARSE_TAG)       ||
2392              (ctx->state == PARSE_TAIL))       &&
2393             (dptr != APR_BRIGADE_SENTINEL(*bb))) {
2394             tmp_dptr = find_end_sequence(dptr, ctx, *bb);
2395
2396             if (tmp_dptr != NULL) {
2397                 dptr = tmp_dptr;  /* Adjust bucket pos... */
2398                 
2399                 /* If some of the tag has already been set aside then set
2400                  * aside remainder of tag. Now the full tag is in ssi_tag_brigade.
2401                  * If none has yet been set aside, then leave it all where it is.
2402                  * In any event after this the entire set of tag buckets will be
2403                  * in one place or another.
2404                  */
2405                 if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
2406                     tag_and_after = apr_brigade_split(*bb, dptr);
2407                     APR_BRIGADE_CONCAT(ctx->ssi_tag_brigade, *bb);
2408                     *bb = tag_and_after;
2409                 }
2410             }
2411             else {
2412                 dptr = APR_BRIGADE_SENTINEL(*bb);  /* remainder of this brigade...    */
2413             }
2414         }
2415
2416         /* State to processed the directive... */
2417         if (ctx->state == PARSED) {
2418             apr_bucket    *content_head = NULL, *tmp_bkt;
2419             apr_size_t    tmp_i;
2420             char          tmp_buf[TMP_BUF_SIZE];
2421             int (*handle_func)(include_ctx_t *, apr_bucket_brigade **, request_rec *,
2422                            ap_filter_t *, apr_bucket *, apr_bucket **);
2423
2424             /* By now the full tag (all buckets) should either be set aside into
2425              *  ssi_tag_brigade or contained within the current bb. All tag
2426              *  processing from here on can assume that.
2427              */
2428
2429             /* At this point, everything between ctx->head_start_bucket and
2430              * ctx->tail_start_bucket is an SSI
2431              * directive, we just have to deal with it now.
2432              */
2433             if (get_combined_directive(ctx, r, *bb, tmp_buf,
2434                                         TMP_BUF_SIZE) != APR_SUCCESS) {
2435                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2436                             "mod_include: error copying directive in %s",
2437                             r->filename);
2438                 CREATE_ERROR_BUCKET(ctx, tmp_bkt, dptr, content_head);
2439
2440                 /* DO CLEANUP HERE!!!!! */
2441                 tmp_dptr = ctx->head_start_bucket;
2442                 if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
2443                     while (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
2444                         tmp_bkt = APR_BRIGADE_FIRST(ctx->ssi_tag_brigade);
2445                         apr_bucket_delete(tmp_bkt);
2446                     }
2447                 }
2448                 else {
2449                     do {
2450                         tmp_bkt  = tmp_dptr;
2451                         tmp_dptr = APR_BUCKET_NEXT (tmp_dptr);
2452                         apr_bucket_delete(tmp_bkt);
2453                     } while ((tmp_dptr != dptr) &&
2454                              (tmp_dptr != APR_BRIGADE_SENTINEL(*bb)));
2455                 }
2456
2457                 return;
2458             }
2459
2460             /* Even if I don't generate any content, I know at this point that
2461              *   I will at least remove the discovered SSI tag, thereby making
2462              *   the content shorter than it was. This is the safest point I can
2463              *   find to unset this field.
2464              */
2465             apr_table_unset(f->r->headers_out, "Content-Length");
2466
2467             /* Can't destroy the tag buckets until I'm done processing
2468              *  because the combined_tag might just be pointing to
2469              *  the contents of a single bucket!
2470              */
2471
2472             /* Retrieve the handler function to be called for this directive from the
2473              *  functions registered in the hash table.
2474              * Need to lower case the directive for proper matching. Also need to have
2475              *  it NULL terminated (and include the NULL in the length) for proper
2476              *  hash matching.
2477              */
2478             for (tmp_i = 0; tmp_i < ctx->directive_length; tmp_i++) {
2479                 ctx->combined_tag[tmp_i] = apr_tolower(ctx->combined_tag[tmp_i]);
2480             }
2481             ctx->combined_tag[ctx->directive_length] = '\0';
2482             ctx->curr_tag_pos = &ctx->combined_tag[ctx->directive_length+1];
2483
2484             handle_func = 
2485                 (int (*)(include_ctx_t *, apr_bucket_brigade **, request_rec *,
2486                     ap_filter_t *, apr_bucket *, apr_bucket **))
2487                 apr_hash_get(include_hash, ctx->combined_tag, ctx->directive_length+1);
2488             if (handle_func != NULL) {
2489                 ret = (*handle_func)(ctx, bb, r, f, dptr, &content_head);
2490             }
2491             else {
2492                 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2493                               "unknown directive \"%s\" in parsed doc %s",
2494                               ctx->combined_tag, r->filename);
2495                 CREATE_ERROR_BUCKET(ctx, tmp_bkt, dptr, content_head);
2496             }
2497
2498             /* This chunk of code starts at the first bucket in the chain
2499              * of tag buckets (assuming that by this point the bucket for
2500              * the STARTING_SEQUENCE has been split) and loops through to
2501              * the end of the tag buckets freeing them all.
2502              *
2503              * Remember that some part of this may have been set aside
2504              * into the ssi_tag_brigade and the remainder (possibly as
2505              * little as one byte) will be in the current brigade.
2506              *
2507              * The value of dptr should have been set during the
2508              * PARSE_TAIL state to the first bucket after the
2509              * ENDING_SEQUENCE.
2510              *
2511              * The value of content_head may have been set during processing
2512              * of the directive. If so, the content was inserted in front
2513              * of the dptr bucket. The inserted buckets should not be thrown
2514              * away here, but they should also not be parsed later.
2515              */
2516             if (content_head == NULL) {
2517                 content_head = dptr;
2518             }
2519             tmp_dptr = ctx->head_start_bucket;
2520             if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
2521                 while (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
2522                     tmp_bkt = APR_BRIGADE_FIRST(ctx->ssi_tag_brigade);
2523                     apr_bucket_delete(tmp_bkt);
2524                 }
2525             }
2526             else {
2527                 do {
2528                     tmp_bkt  = tmp_dptr;
2529                     tmp_dptr = APR_BUCKET_NEXT (tmp_dptr);
2530                     apr_bucket_delete(tmp_bkt);
2531                 } while ((tmp_dptr != content_head) &&
2532                          (tmp_dptr != APR_BRIGADE_SENTINEL(*bb)));
2533             }
2534             if (ctx->combined_tag == tmp_buf) {
2535                 memset (ctx->combined_tag, '\0', ctx->tag_length);
2536                 ctx->combined_tag = NULL;
2537             }
2538
2539             /* Don't reset the flags or the nesting level!!! */
2540             ctx->parse_pos         = 0;
2541             ctx->head_start_bucket = NULL;
2542             ctx->head_start_index  = 0;
2543             ctx->tag_start_bucket  = NULL;
2544             ctx->tag_start_index   = 0;
2545             ctx->tail_start_bucket = NULL;
2546             ctx->tail_start_index  = 0;
2547             ctx->curr_tag_pos      = NULL;
2548             ctx->tag_length        = 0;
2549             ctx->directive_length  = 0;
2550
2551             if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
2552                 while (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
2553                     tmp_bkt = APR_BRIGADE_FIRST(ctx->ssi_tag_brigade);
2554                     apr_bucket_delete(tmp_bkt);
2555                 }
2556             }
2557
2558             ctx->state     = PRE_HEAD;
2559         }
2560     }
2561
2562     /* If I am in the middle of parsing an SSI tag then I need to set aside
2563      *   the pertinent trailing buckets and pass on the initial part of the
2564      *   brigade. The pertinent parts of the next brigades will be added to
2565      *   these set aside buckets to form the whole tag and will be processed
2566      *   once the whole tag has been found.
2567      */
2568     if (ctx->state == PRE_HEAD) {
2569         /* Inside a false conditional (if, elif, else), so toss it all... */
2570         if ((dptr != APR_BRIGADE_SENTINEL(*bb)) &&
2571             (!(ctx->flags & FLAG_PRINTING))) {
2572             apr_bucket *free_bucket;
2573             do {
2574                 free_bucket = dptr;
2575                 dptr = APR_BUCKET_NEXT (dptr);
2576                 apr_bucket_delete(free_bucket);
2577             } while (dptr != APR_BRIGADE_SENTINEL(*bb));
2578         }
2579         else { /* Otherwise pass it along... */
2580             ap_pass_brigade(f->next, *bb);  /* No SSI tags in this brigade... */
2581         }
2582     }
2583     else if (ctx->state == PARSED) {     /* Invalid internal condition... */
2584         apr_bucket *content_head = NULL, *tmp_bkt;
2585         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2586                       "Invalid mod_include state during file %s", r->filename);
2587         CREATE_ERROR_BUCKET(ctx, tmp_bkt, APR_BRIGADE_FIRST(*bb), content_head);
2588     }
2589     else {                 /* Entire brigade is middle chunk of SSI tag... */
2590         if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
2591             APR_BRIGADE_CONCAT(ctx->ssi_tag_brigade, *bb);
2592         }
2593         else {             /* End of brigade contains part of SSI tag... */
2594             if (ctx->head_start_index > 0) {
2595                 apr_bucket_split(ctx->head_start_bucket, ctx->head_start_index);
2596                 ctx->head_start_bucket = APR_BUCKET_NEXT(ctx->head_start_bucket);
2597                 ctx->head_start_index  = 0;
2598             }
2599                            /* Set aside tag, pass pre-tag... */
2600             tag_and_after = apr_brigade_split(*bb, ctx->head_start_bucket);
2601             ap_save_brigade(f, &ctx->ssi_tag_brigade, &tag_and_after);
2602             ap_pass_brigade(f->next, *bb);
2603         }
2604     }
2605 }
2606
2607 /*****************************************************************
2608  *
2609  * XBITHACK.  Sigh...  NB it's configurable per-directory; the compile-time
2610  * option only changes the default.
2611  */
2612
2613 module include_module;
2614 enum xbithack {
2615     xbithack_off, xbithack_on, xbithack_full
2616 };
2617
2618 typedef struct {
2619     char *default_error_msg;
2620     char *default_time_fmt;
2621     enum xbithack *xbithack;
2622 } include_dir_config;
2623
2624 #ifdef XBITHACK
2625 #define DEFAULT_XBITHACK xbithack_full
2626 #else
2627 #define DEFAULT_XBITHACK xbithack_off
2628 #endif
2629
2630 static void *create_includes_dir_config(apr_pool_t *p, char *dummy)
2631 {
2632     include_dir_config *result =
2633         (include_dir_config *)apr_palloc(p, sizeof(include_dir_config));
2634     enum xbithack *xbh = (enum xbithack *) apr_palloc(p, sizeof(enum xbithack));
2635     *xbh = DEFAULT_XBITHACK;
2636     result->default_error_msg = DEFAULT_ERROR_MSG;
2637     result->default_time_fmt = DEFAULT_TIME_FORMAT;
2638     result->xbithack = xbh;
2639     return result;
2640     return result;
2641 }
2642
2643 static const char *set_xbithack(cmd_parms *cmd, void *xbp, const char *arg)
2644 {
2645     include_dir_config *conf = (include_dir_config *)xbp;
2646
2647     if (!strcasecmp(arg, "off")) {
2648         *conf->xbithack = xbithack_off;
2649     }
2650     else if (!strcasecmp(arg, "on")) {
2651         *conf->xbithack = xbithack_on;
2652     }
2653     else if (!strcasecmp(arg, "full")) {
2654         *conf->xbithack = xbithack_full;
2655     }
2656     else {
2657         return "XBitHack must be set to Off, On, or Full";
2658     }
2659
2660     return NULL;
2661 }
2662
2663 static int includes_filter(ap_filter_t *f, apr_bucket_brigade *b)
2664 {
2665     request_rec *r = f->r;
2666     include_ctx_t *ctx = f->ctx;
2667     request_rec *parent;
2668     include_dir_config *conf = 
2669                    (include_dir_config *)ap_get_module_config(r->per_dir_config,
2670                                                               &include_module);
2671
2672     if (!(ap_allow_options(r) & OPT_INCLUDES)) {
2673         return ap_pass_brigade(f->next, b);
2674     }
2675     r->allowed |= (1 << M_GET);
2676     if (r->method_number != M_GET) {
2677         return ap_pass_brigade(f->next, b);
2678     }
2679
2680     if (!f->ctx) {
2681         f->ctx    = ctx      = apr_pcalloc(f->c->pool, sizeof(*ctx));
2682         if (ctx != NULL) {
2683             ctx->state           = PRE_HEAD;
2684             ctx->flags           = (FLAG_PRINTING | FLAG_COND_TRUE);
2685             if (ap_allow_options(r) & OPT_INCNOEXEC) {
2686                 ctx->flags |= FLAG_NO_EXEC;
2687             }
2688             ctx->ssi_tag_brigade = apr_brigade_create(f->c->pool);
2689
2690             apr_cpystrn(ctx->error_str, conf->default_error_msg, sizeof(ctx->error_str));
2691             apr_cpystrn(ctx->time_str, conf->default_time_fmt, sizeof(ctx->time_str));
2692             ctx->error_length = strlen(ctx->error_str);
2693         }
2694         else {
2695             ap_pass_brigade(f->next, b);
2696             return APR_ENOMEM;
2697         }
2698     }
2699
2700     /* Assure the platform supports Group protections */
2701     if ((*conf->xbithack == xbithack_full)
2702         && (r->finfo.valid & APR_FINFO_GPROT)
2703         && (r->finfo.protection & APR_GEXECUTE)) {
2704         ap_update_mtime(r, r->finfo.mtime);
2705         ap_set_last_modified(r);
2706     }
2707
2708     if ((parent = ap_get_module_config(r->request_config, &include_module))) {
2709         /* Kludge --- for nested includes, we want to keep the subprocess
2710          * environment of the base document (for compatibility); that means
2711          * torquing our own last_modified date as well so that the
2712          * LAST_MODIFIED variable gets reset to the proper value if the
2713          * nested document resets <!--#config timefmt-->.
2714          * We also insist that the memory for this subrequest not be
2715          * destroyed, that's dealt with in handle_include().
2716          */
2717         r->subprocess_env = r->main->subprocess_env;
2718         apr_pool_join(r->main->pool, r->pool);
2719         r->finfo.mtime = r->main->finfo.mtime;
2720     }
2721     else {
2722         /* we're not a nested include, so we create an initial
2723          * environment */
2724         ap_add_common_vars(r);
2725         ap_add_cgi_vars(r);
2726         add_include_vars(r, conf->default_time_fmt);
2727     }
2728     /* XXX: this is bogus, at some point we're going to do a subrequest,
2729      * and when we do it we're going to be subjecting code that doesn't
2730      * expect to be signal-ready to SIGALRM.  There is no clean way to
2731      * fix this, except to put alarm support into BUFF. -djg
2732      */
2733
2734
2735     send_parsed_content(&b, r, f);
2736
2737     if (parent) {
2738         /* signify that the sub request should not be killed */
2739         ap_set_module_config(r->request_config, &include_module,
2740             NESTED_INCLUDE_MAGIC);
2741     }
2742
2743     return OK;
2744 }
2745
2746 static void ap_register_include_handler(char *tag, include_handler func)
2747 {
2748     apr_hash_set(include_hash, tag, strlen(tag) + 1, (const void *)func);
2749 }
2750
2751 static void include_post_config(apr_pool_t *p, apr_pool_t *plog,
2752                                 apr_pool_t *ptemp, server_rec *s)
2753 {
2754     include_hash = apr_hash_make(p);
2755
2756     ssi_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
2757
2758     if(ssi_pfn_register) {
2759         ssi_pfn_register("if", handle_if);
2760         ssi_pfn_register("set", handle_set);
2761         ssi_pfn_register("else", handle_else);
2762         ssi_pfn_register("elif", handle_elif);
2763         ssi_pfn_register("echo", handle_echo);
2764         ssi_pfn_register("endif", handle_endif);
2765         ssi_pfn_register("fsize", handle_fsize);
2766         ssi_pfn_register("config", handle_config);
2767         ssi_pfn_register("include", handle_include);
2768         ssi_pfn_register("flastmod", handle_flastmod);
2769         ssi_pfn_register("printenv", handle_printenv);
2770     }
2771 }
2772
2773 static const char *set_default_error_msg(cmd_parms *cmd, void *mconfig, const char *msg)
2774 {
2775     include_dir_config *conf = (include_dir_config *)mconfig;
2776     conf->default_error_msg = apr_pstrdup(cmd->pool, msg);
2777     return NULL;
2778 }
2779
2780 static const char *set_default_time_fmt(cmd_parms *cmd, void *mconfig, const char *fmt)
2781 {
2782     include_dir_config *conf = (include_dir_config *)mconfig;
2783     conf->default_time_fmt = apr_pstrdup(cmd->pool, fmt);
2784     return NULL;
2785 }
2786
2787 /*
2788  * Module definition and configuration data structs...
2789  */
2790 static const command_rec includes_cmds[] =
2791 {
2792     AP_INIT_TAKE1("XBitHack", set_xbithack, NULL, OR_OPTIONS, 
2793                   "Off, On, or Full"),
2794     AP_INIT_TAKE1("SSIErrorMsg", set_default_error_msg, NULL, OR_ALL, 
2795                   "a string"),
2796     AP_INIT_TAKE1("SSITimeFormat", set_default_time_fmt, NULL, OR_ALL,
2797                   "a strftime(3) formatted string"),
2798     {NULL}
2799 };
2800
2801 static void register_hooks(apr_pool_t *p)
2802 {
2803     APR_REGISTER_OPTIONAL_FN(ap_ssi_get_tag_and_value);
2804     APR_REGISTER_OPTIONAL_FN(ap_ssi_parse_string);
2805     APR_REGISTER_OPTIONAL_FN(ap_register_include_handler);
2806     ap_hook_post_config(include_post_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
2807     ap_register_output_filter("INCLUDES", includes_filter, AP_FTYPE_CONTENT);
2808 }
2809
2810 module AP_MODULE_DECLARE_DATA include_module =
2811 {
2812     STANDARD20_MODULE_STUFF,
2813     create_includes_dir_config, /* dir config creater */
2814     NULL,                       /* dir merger --- default is to override */
2815     NULL,                       /* server config */
2816     NULL,                       /* merge server config */
2817     includes_cmds,              /* command apr_table_t */
2818     register_hooks              /* register hooks */
2819 };