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