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