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