]> granicus.if.org Git - apache/blob - server/util_script.c
fr doc rebuild.
[apache] / server / util_script.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "apr.h"
18 #include "apr_lib.h"
19 #include "apr_strings.h"
20
21 #define APR_WANT_STRFUNC
22 #include "apr_want.h"
23
24 #if APR_HAVE_STDLIB_H
25 #include <stdlib.h>
26 #endif
27
28 #include "ap_config.h"
29 #include "httpd.h"
30 #include "http_config.h"
31 #include "http_main.h"
32 #include "http_log.h"
33 #include "http_core.h"
34 #include "http_protocol.h"
35 #include "http_request.h"       /* for sub_req_lookup_uri() */
36 #include "util_script.h"
37 #include "apr_date.h"           /* For apr_date_parse_http() */
38 #include "util_ebcdic.h"
39
40 #ifdef OS2
41 #define INCL_DOS
42 #include <os2.h>
43 #endif
44
45 /*
46  * Various utility functions which are common to a whole lot of
47  * script-type extensions mechanisms, and might as well be gathered
48  * in one place (if only to avoid creating inter-module dependancies
49  * where there don't have to be).
50  */
51
52 /* we know core's module_index is 0 */
53 #undef APLOG_MODULE_INDEX
54 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
55
56 static char *http2env(request_rec *r, const char *w)
57 {
58     char *res = (char *)apr_palloc(r->pool, sizeof("HTTP_") + strlen(w));
59     char *cp = res;
60     char c;
61
62     *cp++ = 'H';
63     *cp++ = 'T';
64     *cp++ = 'T';
65     *cp++ = 'P';
66     *cp++ = '_';
67
68     while ((c = *w++) != 0) {
69         if (apr_isalnum(c)) {
70             *cp++ = apr_toupper(c);
71         }
72         else if (c == '-') {
73             *cp++ = '_';
74         }
75         else {
76             if (APLOGrtrace1(r))
77                 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
78                             "Not exporting header with invalid name as envvar: %s",
79                             ap_escape_logitem(r->pool, w));
80             return NULL;
81         }
82     }
83     *cp = 0;
84
85     return res;
86 }
87
88 static void add_unless_null(apr_table_t *table, const char *name, const char *val)
89 {
90     if (name && val) {
91         apr_table_addn(table, name, val);
92     }
93 }
94
95 /* Sets variable @name in table @dest from r->subprocess_env if
96  * available, else from the environment, else from @fallback if
97  * non-NULL. */
98 static void env2env(apr_table_t *dest, request_rec *r,
99                     const char *name, const char *fallback)
100 {
101     const char *val;
102
103     val = apr_table_get(r->subprocess_env, name);
104     if (!val)
105         val = apr_pstrdup(r->pool, getenv(name));
106     if (!val)
107         val = apr_pstrdup(r->pool, fallback);
108     if (val)
109         apr_table_addn(dest, name, val);
110 }
111
112 AP_DECLARE(char **) ap_create_environment(apr_pool_t *p, apr_table_t *t)
113 {
114     const apr_array_header_t *env_arr = apr_table_elts(t);
115     const apr_table_entry_t *elts = (const apr_table_entry_t *) env_arr->elts;
116     char **env = (char **) apr_palloc(p, (env_arr->nelts + 2) * sizeof(char *));
117     int i, j;
118     char *tz;
119     char *whack;
120
121     j = 0;
122     if (!apr_table_get(t, "TZ")) {
123         tz = getenv("TZ");
124         if (tz != NULL) {
125             env[j++] = apr_pstrcat(p, "TZ=", tz, NULL);
126         }
127     }
128     for (i = 0; i < env_arr->nelts; ++i) {
129         if (!elts[i].key) {
130             continue;
131         }
132         env[j] = apr_pstrcat(p, elts[i].key, "=", elts[i].val, NULL);
133         whack = env[j];
134         if (apr_isdigit(*whack)) {
135             *whack++ = '_';
136         }
137         while (*whack != '=') {
138 #ifdef WIN32
139             if (!apr_isalnum(*whack) && *whack != '(' && *whack != ')') {
140 #else
141             if (!apr_isalnum(*whack)) {
142 #endif
143                 *whack = '_';
144             }
145             ++whack;
146         }
147         ++j;
148     }
149
150     env[j] = NULL;
151     return env;
152 }
153
154 AP_DECLARE(void) ap_add_common_vars(request_rec *r)
155 {
156     apr_table_t *e;
157     server_rec *s = r->server;
158     conn_rec *c = r->connection;
159     core_dir_config *conf =
160         (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
161     const char *env_temp;
162     const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
163     const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
164     int i;
165     apr_port_t rport;
166     char *q;
167
168     /* use a temporary apr_table_t which we'll overlap onto
169      * r->subprocess_env later
170      * (exception: if r->subprocess_env is empty at the start,
171      * write directly into it)
172      */
173     if (apr_is_empty_table(r->subprocess_env)) {
174         e = r->subprocess_env;
175     }
176     else {
177         e = apr_table_make(r->pool, 25 + hdrs_arr->nelts);
178     }
179
180     /* First, add environment vars from headers... this is as per
181      * CGI specs, though other sorts of scripting interfaces see
182      * the same vars...
183      */
184
185     for (i = 0; i < hdrs_arr->nelts; ++i) {
186         if (!hdrs[i].key) {
187             continue;
188         }
189
190         /* A few headers are special cased --- Authorization to prevent
191          * rogue scripts from capturing passwords; content-type and -length
192          * for no particular reason.
193          */
194
195         if (!ap_cstr_casecmp(hdrs[i].key, "Content-type")) {
196             apr_table_addn(e, "CONTENT_TYPE", hdrs[i].val);
197         }
198         else if (!ap_cstr_casecmp(hdrs[i].key, "Content-length")) {
199             apr_table_addn(e, "CONTENT_LENGTH", hdrs[i].val);
200         }
201         /* HTTP_PROXY collides with a popular envvar used to configure
202          * proxies, don't let clients set/override it.  But, if you must...
203          */
204 #ifndef SECURITY_HOLE_PASS_PROXY
205         else if (!ap_cstr_casecmp(hdrs[i].key, "Proxy")) {
206             ;
207         }
208 #endif
209         /*
210          * You really don't want to disable this check, since it leaves you
211          * wide open to CGIs stealing passwords and people viewing them
212          * in the environment with "ps -e".  But, if you must...
213          */
214 #ifndef SECURITY_HOLE_PASS_AUTHORIZATION
215         else if (!ap_cstr_casecmp(hdrs[i].key, "Authorization")
216                  || !ap_cstr_casecmp(hdrs[i].key, "Proxy-Authorization")) {
217             if (conf->cgi_pass_auth == AP_CGI_PASS_AUTH_ON) {
218                 add_unless_null(e, http2env(r, hdrs[i].key), hdrs[i].val);
219             }
220         }
221 #endif
222         else
223             add_unless_null(e, http2env(r, hdrs[i].key), hdrs[i].val);
224     }
225
226     env2env(e, r, "PATH", DEFAULT_PATH);
227 #if defined(WIN32)
228     env2env(e, r, "SystemRoot", NULL);
229     env2env(e, r, "COMSPEC", NULL);
230     env2env(e, r, "PATHEXT", NULL);
231     env2env(e, r, "WINDIR", NULL);
232 #elif defined(OS2)
233     env2env(e, r, "COMSPEC", NULL);
234     env2env(e, r, "ETC", NULL);
235     env2env(e, r, "DPATH", NULL);
236     env2env(e, r, "PERLLIB_PREFIX", NULL);
237 #elif defined(BEOS)
238     env2env(e, r, "LIBRARY_PATH", NULL);
239 #elif defined(DARWIN)
240     env2env(e, r, "DYLD_LIBRARY_PATH", NULL);
241 #elif defined(_AIX)
242     env2env(e, r, "LIBPATH", NULL);
243 #elif defined(__HPUX__)
244     /* HPUX PARISC 2.0W knows both, otherwise redundancy is harmless */
245     env2env(e, r, "SHLIB_PATH", NULL);
246     env2env(e, r, "LD_LIBRARY_PATH", NULL);
247 #else /* Some Unix */
248     env2env(e, r, "LD_LIBRARY_PATH", NULL);
249 #endif
250
251     apr_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r));
252     apr_table_addn(e, "SERVER_SOFTWARE", ap_get_server_banner());
253     apr_table_addn(e, "SERVER_NAME",
254                    ap_escape_html(r->pool, ap_get_server_name_for_url(r)));
255     apr_table_addn(e, "SERVER_ADDR", r->connection->local_ip);  /* Apache */
256     apr_table_addn(e, "SERVER_PORT",
257                   apr_psprintf(r->pool, "%u", ap_get_server_port(r)));
258     add_unless_null(e, "REMOTE_HOST",
259                     ap_get_useragent_host(r, REMOTE_HOST, NULL));
260     apr_table_addn(e, "REMOTE_ADDR", r->useragent_ip);
261     apr_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r));    /* Apache */
262     apr_table_setn(e, "REQUEST_SCHEME", ap_http_scheme(r));
263     apr_table_addn(e, "CONTEXT_PREFIX", ap_context_prefix(r));
264     apr_table_addn(e, "CONTEXT_DOCUMENT_ROOT", ap_context_document_root(r));
265     apr_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */
266     if (apr_table_get(r->notes, "proxy-noquery") && (q = ap_strchr(r->filename, '?'))) {
267         char *script_filename = apr_pstrmemdup(r->pool, r->filename, q - r->filename);
268         apr_table_addn(e, "SCRIPT_FILENAME", script_filename);
269     }
270     else {
271         apr_table_addn(e, "SCRIPT_FILENAME", r->filename);  /* Apache */
272     }
273
274     rport = c->client_addr->port;
275     apr_table_addn(e, "REMOTE_PORT", apr_itoa(r->pool, rport));
276
277     if (r->user) {
278         apr_table_addn(e, "REMOTE_USER", r->user);
279     }
280     else if (r->prev) {
281         request_rec *back = r->prev;
282
283         while (back) {
284             if (back->user) {
285                 apr_table_addn(e, "REDIRECT_REMOTE_USER", back->user);
286                 break;
287             }
288             back = back->prev;
289         }
290     }
291     add_unless_null(e, "AUTH_TYPE", r->ap_auth_type);
292     env_temp = ap_get_remote_logname(r);
293     if (env_temp) {
294         apr_table_addn(e, "REMOTE_IDENT", apr_pstrdup(r->pool, env_temp));
295     }
296
297     /* Apache custom error responses. If we have redirected set two new vars */
298
299     if (r->prev) {
300         if (conf->qualify_redirect_url != AP_CORE_CONFIG_ON) { 
301             add_unless_null(e, "REDIRECT_URL", r->prev->uri);
302         }
303         else { 
304             /* PR#57785: reconstruct full URL here */
305             apr_uri_t *uri = &r->prev->parsed_uri;
306             if (!uri->scheme) {
307                 uri->scheme = (char*)ap_http_scheme(r->prev);
308             }
309             if (!uri->port) {
310                 uri->port = ap_get_server_port(r->prev);
311                 uri->port_str = apr_psprintf(r->pool, "%u", uri->port);
312             }
313             if (!uri->hostname) {
314                 uri->hostname = (char*)ap_get_server_name_for_url(r->prev);
315             }
316             add_unless_null(e, "REDIRECT_URL",
317                             apr_uri_unparse(r->pool, uri, 0));
318         }
319         add_unless_null(e, "REDIRECT_QUERY_STRING", r->prev->args);
320     }
321
322     if (e != r->subprocess_env) {
323         apr_table_overlap(r->subprocess_env, e, APR_OVERLAP_TABLES_SET);
324     }
325 }
326
327 /* This "cute" little function comes about because the path info on
328  * filenames and URLs aren't always the same. So we take the two,
329  * and find as much of the two that match as possible.
330  */
331
332 AP_DECLARE(int) ap_find_path_info(const char *uri, const char *path_info)
333 {
334     int lu = strlen(uri);
335     int lp = strlen(path_info);
336
337     while (lu-- && lp-- && uri[lu] == path_info[lp]) {
338         if (path_info[lp] == '/') {
339             while (lu && uri[lu-1] == '/') lu--;
340         }
341     }
342
343     if (lu == -1) {
344         lu = 0;
345     }
346
347     while (uri[lu] != '\0' && uri[lu] != '/') {
348         lu++;
349     }
350     return lu;
351 }
352
353 /* Obtain the Request-URI from the original request-line, returning
354  * a new string from the request pool containing the URI or "".
355  */
356 static char *original_uri(request_rec *r)
357 {
358     char *first, *last;
359
360     if (r->the_request == NULL) {
361         return (char *) apr_pcalloc(r->pool, 1);
362     }
363
364     first = r->the_request;     /* use the request-line */
365
366     while (*first && !apr_isspace(*first)) {
367         ++first;                /* skip over the method */
368     }
369     while (apr_isspace(*first)) {
370         ++first;                /*   and the space(s)   */
371     }
372
373     last = first;
374     while (*last && !apr_isspace(*last)) {
375         ++last;                 /* end at next whitespace */
376     }
377
378     return apr_pstrmemdup(r->pool, first, last - first);
379 }
380
381 AP_DECLARE(void) ap_add_cgi_vars(request_rec *r)
382 {
383     apr_table_t *e = r->subprocess_env;
384     core_dir_config *conf =
385         (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
386     int request_uri_from_original = 1;
387     const char *request_uri_rule;
388
389     apr_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
390     apr_table_setn(e, "SERVER_PROTOCOL", r->protocol);
391     apr_table_setn(e, "REQUEST_METHOD", r->method);
392     apr_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
393
394     if (conf->cgi_var_rules) {
395         request_uri_rule = apr_hash_get(conf->cgi_var_rules, "REQUEST_URI",
396                                         APR_HASH_KEY_STRING);
397         if (request_uri_rule && !strcmp(request_uri_rule, "current-uri")) {
398             request_uri_from_original = 0;
399         }
400     }
401     apr_table_setn(e, "REQUEST_URI",
402                    request_uri_from_original ? original_uri(r) : r->uri);
403
404     /* Note that the code below special-cases scripts run from includes,
405      * because it "knows" that the sub_request has been hacked to have the
406      * args and path_info of the original request, and not any that may have
407      * come with the script URI in the include command.  Ugh.
408      */
409
410     if (!strcmp(r->protocol, "INCLUDED")) {
411         apr_table_setn(e, "SCRIPT_NAME", r->uri);
412         if (r->path_info && *r->path_info) {
413             apr_table_setn(e, "PATH_INFO", r->path_info);
414         }
415     }
416     else if (!r->path_info || !*r->path_info) {
417         apr_table_setn(e, "SCRIPT_NAME", r->uri);
418     }
419     else {
420         int path_info_start = ap_find_path_info(r->uri, r->path_info);
421
422         apr_table_setn(e, "SCRIPT_NAME",
423                       apr_pstrndup(r->pool, r->uri, path_info_start));
424
425         apr_table_setn(e, "PATH_INFO", r->path_info);
426     }
427
428     if (r->path_info && r->path_info[0]) {
429         /*
430          * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
431          * Need to re-escape it for this, since the entire URI was
432          * un-escaped before we determined where the PATH_INFO began.
433          */
434         request_rec *pa_req;
435
436         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r,
437                                        NULL);
438
439         if (pa_req->filename) {
440             char *pt = apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
441                                   NULL);
442 #ifdef WIN32
443             /* We need to make this a real Windows path name */
444             apr_filepath_merge(&pt, "", pt, APR_FILEPATH_NATIVE, r->pool);
445 #endif
446             apr_table_setn(e, "PATH_TRANSLATED", pt);
447         }
448         ap_destroy_sub_req(pa_req);
449     }
450 }
451
452
453 static int set_cookie_doo_doo(void *v, const char *key, const char *val)
454 {
455     apr_table_addn(v, key, val);
456     return 1;
457 }
458
459 #define HTTP_UNSET (-HTTP_OK)
460 #define SCRIPT_LOG_MARK  __FILE__,__LINE__,module_index
461
462 AP_DECLARE(int) ap_scan_script_header_err_core_ex(request_rec *r, char *buffer,
463                                        int (*getsfunc) (char *, int, void *),
464                                        void *getsfunc_data,
465                                        int module_index)
466 {
467     char x[MAX_STRING_LEN];
468     char *w, *l;
469     int p;
470     int cgi_status = HTTP_UNSET;
471     apr_table_t *merge;
472     apr_table_t *cookie_table;
473     int trace_log = APLOG_R_MODULE_IS_LEVEL(r, module_index, APLOG_TRACE1);
474     int first_header = 1;
475
476     if (buffer) {
477         *buffer = '\0';
478     }
479     w = buffer ? buffer : x;
480
481     /* temporary place to hold headers to merge in later */
482     merge = apr_table_make(r->pool, 10);
483
484     /* The HTTP specification says that it is legal to merge duplicate
485      * headers into one.  Some browsers that support Cookies don't like
486      * merged headers and prefer that each Set-Cookie header is sent
487      * separately.  Lets humour those browsers by not merging.
488      * Oh what a pain it is.
489      */
490     cookie_table = apr_table_make(r->pool, 2);
491     apr_table_do(set_cookie_doo_doo, cookie_table, r->err_headers_out, "Set-Cookie", NULL);
492
493     while (1) {
494
495         int rv = (*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data);
496         if (rv == 0) {
497             const char *msg = "Premature end of script headers";
498             if (first_header)
499                 msg = "End of script output before headers";
500             /* Intentional no APLOGNO */
501             ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
502                           "%s: %s", msg,
503                           apr_filepath_name_get(r->filename));
504             return HTTP_INTERNAL_SERVER_ERROR;
505         }
506         else if (rv == -1) {
507             /* Intentional no APLOGNO */
508             ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
509                           "Script timed out before returning headers: %s",
510                           apr_filepath_name_get(r->filename));
511             return HTTP_GATEWAY_TIME_OUT;
512         }
513
514         /* Delete terminal (CR?)LF */
515
516         p = strlen(w);
517              /* Indeed, the host's '\n':
518                 '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
519                  -- whatever the script generates.
520              */
521         if (p > 0 && w[p - 1] == '\n') {
522             if (p > 1 && w[p - 2] == CR) {
523                 w[p - 2] = '\0';
524             }
525             else {
526                 w[p - 1] = '\0';
527             }
528         }
529
530         /*
531          * If we've finished reading the headers, check to make sure any
532          * HTTP/1.1 conditions are met.  If so, we're done; normal processing
533          * will handle the script's output.  If not, just return the error.
534          * The appropriate thing to do would be to send the script process a
535          * SIGPIPE to let it know we're ignoring it, close the channel to the
536          * script process, and *then* return the failed-to-meet-condition
537          * error.  Otherwise we'd be waiting for the script to finish
538          * blithering before telling the client the output was no good.
539          * However, we don't have the information to do that, so we have to
540          * leave it to an upper layer.
541          */
542         if (w[0] == '\0') {
543             int cond_status = OK;
544
545             /* PR#38070: This fails because it gets confused when a
546              * CGI Status header overrides ap_meets_conditions.
547              *
548              * We can fix that by dropping ap_meets_conditions when
549              * Status has been set.  Since this is the only place
550              * cgi_status gets used, let's test it explicitly.
551              *
552              * The alternative would be to ignore CGI Status when
553              * ap_meets_conditions returns anything interesting.
554              * That would be safer wrt HTTP, but would break CGI.
555              */
556             if ((cgi_status == HTTP_UNSET) && (r->method_number == M_GET)) {
557                 cond_status = ap_meets_conditions(r);
558             }
559             apr_table_overlap(r->err_headers_out, merge,
560                 APR_OVERLAP_TABLES_MERGE);
561             if (!apr_is_empty_table(cookie_table)) {
562                 /* the cookies have already been copied to the cookie_table */
563                 apr_table_unset(r->err_headers_out, "Set-Cookie");
564                 r->err_headers_out = apr_table_overlay(r->pool,
565                     r->err_headers_out, cookie_table);
566             }
567             return cond_status;
568         }
569
570         if (trace_log) {
571             if (first_header)
572                 ap_log_rerror(SCRIPT_LOG_MARK, APLOG_TRACE4, 0, r,
573                               "Headers from script '%s':",
574                               apr_filepath_name_get(r->filename));
575             ap_log_rerror(SCRIPT_LOG_MARK, APLOG_TRACE4, 0, r, "  %s", w);
576         }
577
578         /* if we see a bogus header don't ignore it. Shout and scream */
579
580 #if APR_CHARSET_EBCDIC
581             /* Chances are that we received an ASCII header text instead of
582              * the expected EBCDIC header lines. Try to auto-detect:
583              */
584         if (!(l = strchr(w, ':'))) {
585             int maybeASCII = 0, maybeEBCDIC = 0;
586             unsigned char *cp, native;
587             apr_size_t inbytes_left, outbytes_left;
588
589             for (cp = w; *cp != '\0'; ++cp) {
590                 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
591                 if (apr_isprint(*cp) && !apr_isprint(native))
592                     ++maybeEBCDIC;
593                 if (!apr_isprint(*cp) && apr_isprint(native))
594                     ++maybeASCII;
595             }
596             if (maybeASCII > maybeEBCDIC) {
597                 ap_log_error(SCRIPT_LOG_MARK, APLOG_ERR, 0, r->server,
598                              APLOGNO(02660) "CGI Interface Error: "
599                              "Script headers apparently ASCII: (CGI = %s)",
600                              r->filename);
601                 inbytes_left = outbytes_left = cp - w;
602                 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
603                                       w, &inbytes_left, w, &outbytes_left);
604             }
605         }
606 #endif /*APR_CHARSET_EBCDIC*/
607         if (!(l = strchr(w, ':'))) {
608             if (!buffer) {
609                 /* Soak up all the script output - may save an outright kill */
610                 while ((*getsfunc)(w, MAX_STRING_LEN - 1, getsfunc_data) > 0) {
611                     continue;
612                 }
613             }
614
615             /* Intentional no APLOGNO */
616             ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
617                           "malformed header from script '%s': Bad header: %.30s",
618                           apr_filepath_name_get(r->filename), w);
619             return HTTP_INTERNAL_SERVER_ERROR;
620         }
621
622         *l++ = '\0';
623         while (apr_isspace(*l)) {
624             ++l;
625         }
626
627         if (!ap_cstr_casecmp(w, "Content-type")) {
628             char *tmp;
629
630             /* Nuke trailing whitespace */
631
632             char *endp = l + strlen(l) - 1;
633             while (endp > l && apr_isspace(*endp)) {
634                 *endp-- = '\0';
635             }
636
637             tmp = apr_pstrdup(r->pool, l);
638             ap_content_type_tolower(tmp);
639             ap_set_content_type(r, tmp);
640         }
641         /*
642          * If the script returned a specific status, that's what
643          * we'll use - otherwise we assume 200 OK.
644          */
645         else if (!ap_cstr_casecmp(w, "Status")) {
646             r->status = cgi_status = atoi(l);
647             if (!ap_is_HTTP_VALID_RESPONSE(cgi_status))
648                 /* Intentional no APLOGNO */
649                 ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
650                               "Invalid status line from script '%s': %.30s",
651                               apr_filepath_name_get(r->filename), l);
652             else
653                 if (APLOGrtrace1(r))
654                    ap_log_rerror(SCRIPT_LOG_MARK, APLOG_TRACE1, 0, r,
655                                  "Status line from script '%s': %.30s",
656                                  apr_filepath_name_get(r->filename), l);
657             r->status_line = apr_pstrdup(r->pool, l);
658         }
659         else if (!ap_cstr_casecmp(w, "Location")) {
660             apr_table_set(r->headers_out, w, l);
661         }
662         else if (!ap_cstr_casecmp(w, "Content-Length")) {
663             apr_table_set(r->headers_out, w, l);
664         }
665         else if (!ap_cstr_casecmp(w, "Content-Range")) {
666             apr_table_set(r->headers_out, w, l);
667         }
668         else if (!ap_cstr_casecmp(w, "Transfer-Encoding")) {
669             apr_table_set(r->headers_out, w, l);
670         }
671         else if (!ap_cstr_casecmp(w, "ETag")) {
672             apr_table_set(r->headers_out, w, l);
673         }
674         /*
675          * If the script gave us a Last-Modified header, we can't just
676          * pass it on blindly because of restrictions on future or invalid values.
677          */
678         else if (!ap_cstr_casecmp(w, "Last-Modified")) {
679             apr_time_t parsed_date = apr_date_parse_http(l);
680             if (parsed_date != APR_DATE_BAD) {
681                 ap_update_mtime(r, parsed_date);
682                 ap_set_last_modified(r);
683                 if (APLOGrtrace1(r)) {
684                     apr_time_t last_modified_date = apr_date_parse_http(apr_table_get(r->headers_out,
685                                                                                       "Last-Modified"));
686                     /*
687                      * A Last-Modified header value coming from a (F)CGI source
688                      * is considered HTTP input so we assume the GMT timezone.
689                      * The following logs should inform the admin about violations
690                      * and related actions taken by httpd.
691                      * The apr_date_parse_rfc function is 'timezone aware'
692                      * and it will be used to generate a more informative set of logs
693                      * (we don't use it as a replacement of apr_date_parse_http
694                      * for the aforementioned reason).
695                      */
696                     apr_time_t parsed_date_tz_aware = apr_date_parse_rfc(l);
697
698                     /* 
699                      * The parsed Last-Modified header datestring has been replaced by httpd.
700                      */
701                     if (parsed_date > last_modified_date) {
702                         ap_log_rerror(SCRIPT_LOG_MARK, APLOG_TRACE1, 0, r,
703                                       "The Last-Modified header value %s (%s) "
704                                       "has been replaced with '%s'", l,
705                                       parsed_date != parsed_date_tz_aware ? "not in GMT"
706                                                                           : "in the future",
707                                       apr_table_get(r->headers_out, "Last-Modified"));
708                     /* 
709                      * Last-Modified header datestring not in GMT and not considered in the future
710                      * by httpd (like now() + 1 hour in the PST timezone). No action is taken but
711                      * the admin is warned about the violation.
712                      */
713                     } else if (parsed_date != parsed_date_tz_aware) {
714                         ap_log_rerror(SCRIPT_LOG_MARK, APLOG_TRACE1, 0, r,
715                                       "The Last-Modified header value is not set "
716                                       "within the GMT timezone (as required)");
717                     }
718                 }
719             }
720             else {
721                 if (APLOGrtrace1(r))
722                    ap_log_rerror(SCRIPT_LOG_MARK, APLOG_TRACE1, 0, r,
723                                  "Ignored invalid header value: Last-Modified: '%s'", l);
724             }
725         }
726         else if (!ap_cstr_casecmp(w, "Set-Cookie")) {
727             apr_table_add(cookie_table, w, l);
728         }
729         else {
730             apr_table_add(merge, w, l);
731         }
732         first_header = 0;
733     }
734     /* never reached - we leave this function within the while loop above */
735     return OK;
736 }
737
738 AP_DECLARE(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
739                                        int (*getsfunc) (char *, int, void *),
740                                        void *getsfunc_data)
741 {
742     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc,
743                                              getsfunc_data,
744                                              APLOG_MODULE_INDEX);
745 }
746
747 static int getsfunc_FILE(char *buf, int len, void *f)
748 {
749     return apr_file_gets(buf, len, (apr_file_t *) f) == APR_SUCCESS;
750 }
751
752 AP_DECLARE(int) ap_scan_script_header_err(request_rec *r, apr_file_t *f,
753                                           char *buffer)
754 {
755     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc_FILE, f,
756                                              APLOG_MODULE_INDEX);
757 }
758
759 AP_DECLARE(int) ap_scan_script_header_err_ex(request_rec *r, apr_file_t *f,
760                                           char *buffer, int module_index)
761 {
762     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc_FILE, f,
763                                              module_index);
764 }
765
766
767 static int getsfunc_BRIGADE(char *buf, int len, void *arg)
768 {
769     apr_bucket_brigade *bb = (apr_bucket_brigade *)arg;
770     const char *dst_end = buf + len - 1; /* leave room for terminating null */
771     char *dst = buf;
772     apr_bucket *e = APR_BRIGADE_FIRST(bb);
773     apr_status_t rv;
774     int done = 0;
775
776     while ((dst < dst_end) && !done && e != APR_BRIGADE_SENTINEL(bb)
777            && !APR_BUCKET_IS_EOS(e)) {
778         const char *bucket_data;
779         apr_size_t bucket_data_len;
780         const char *src;
781         const char *src_end;
782         apr_bucket * next;
783
784         rv = apr_bucket_read(e, &bucket_data, &bucket_data_len,
785                              APR_BLOCK_READ);
786         if (rv != APR_SUCCESS || (bucket_data_len == 0)) {
787             *dst = '\0';
788             return APR_STATUS_IS_TIMEUP(rv) ? -1 : 0;
789         }
790         src = bucket_data;
791         src_end = bucket_data + bucket_data_len;
792         while ((src < src_end) && (dst < dst_end) && !done) {
793             if (*src == '\n') {
794                 done = 1;
795             }
796             else if (*src != '\r') {
797                 *dst++ = *src;
798             }
799             src++;
800         }
801
802         if (src < src_end) {
803             apr_bucket_split(e, src - bucket_data);
804         }
805         next = APR_BUCKET_NEXT(e);
806         apr_bucket_delete(e);
807         e = next;
808     }
809     *dst = 0;
810     return done;
811 }
812
813 AP_DECLARE(int) ap_scan_script_header_err_brigade(request_rec *r,
814                                                   apr_bucket_brigade *bb,
815                                                   char *buffer)
816 {
817     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc_BRIGADE, bb,
818                                              APLOG_MODULE_INDEX);
819 }
820
821 AP_DECLARE(int) ap_scan_script_header_err_brigade_ex(request_rec *r,
822                                                      apr_bucket_brigade *bb,
823                                                      char *buffer,
824                                                      int module_index)
825 {
826     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc_BRIGADE, bb,
827                                              module_index);
828 }
829
830
831 struct vastrs {
832     va_list args;
833     int arg;
834     const char *curpos;
835 };
836
837 static int getsfunc_STRING(char *w, int len, void *pvastrs)
838 {
839     struct vastrs *strs = (struct vastrs*) pvastrs;
840     const char *p;
841     int t;
842
843     if (!strs->curpos || !*strs->curpos) {
844         w[0] = '\0';
845         return 0;
846     }
847     p = ap_strchr_c(strs->curpos, '\n');
848     if (p)
849         ++p;
850     else
851         p = ap_strchr_c(strs->curpos, '\0');
852     t = p - strs->curpos;
853     if (t > len)
854         t = len;
855     strncpy (w, strs->curpos, t);
856     w[t] = '\0';
857     if (!strs->curpos[t]) {
858         ++strs->arg;
859         strs->curpos = va_arg(strs->args, const char *);
860     }
861     else
862         strs->curpos += t;
863     return t;
864 }
865
866 /* ap_scan_script_header_err_strs() accepts additional const char* args...
867  * each is treated as one or more header lines, and the first non-header
868  * character is returned to **arg, **data.  (The first optional arg is
869  * counted as 0.)
870  */
871 AP_DECLARE_NONSTD(int) ap_scan_script_header_err_strs_ex(request_rec *r,
872                                                          char *buffer,
873                                                          int module_index,
874                                                          const char **termch,
875                                                          int *termarg, ...)
876 {
877     struct vastrs strs;
878     int res;
879
880     va_start(strs.args, termarg);
881     strs.arg = 0;
882     strs.curpos = va_arg(strs.args, char*);
883     res = ap_scan_script_header_err_core_ex(r, buffer, getsfunc_STRING,
884                                             (void *) &strs, module_index);
885     if (termch)
886         *termch = strs.curpos;
887     if (termarg)
888         *termarg = strs.arg;
889     va_end(strs.args);
890     return res;
891 }
892
893 AP_DECLARE_NONSTD(int) ap_scan_script_header_err_strs(request_rec *r,
894                                                       char *buffer,
895                                                       const char **termch,
896                                                       int *termarg, ...)
897 {
898     struct vastrs strs;
899     int res;
900
901     va_start(strs.args, termarg);
902     strs.arg = 0;
903     strs.curpos = va_arg(strs.args, char*);
904     res = ap_scan_script_header_err_core_ex(r, buffer, getsfunc_STRING,
905                                             (void *) &strs, APLOG_MODULE_INDEX);
906     if (termch)
907         *termch = strs.curpos;
908     if (termarg)
909         *termarg = strs.arg;
910     va_end(strs.args);
911     return res;
912 }
913
914 static void
915 argstr_to_table(char *str, apr_table_t *parms)
916 {
917     char *key;
918     char *value;
919     char *strtok_state;
920
921     if (str == NULL) {
922         return;
923     }
924
925     key = apr_strtok(str, "&", &strtok_state);
926     while (key) {
927         value = strchr(key, '=');
928         if (value) {
929             *value = '\0';      /* Split the string in two */
930             value++;            /* Skip passed the = */
931         }
932         else {
933             value = "1";
934         }
935         ap_unescape_url(key);
936         ap_unescape_url(value);
937         apr_table_set(parms, key, value);
938         key = apr_strtok(NULL, "&", &strtok_state);
939     }
940 }
941
942 AP_DECLARE(void) ap_args_to_table(request_rec *r, apr_table_t **table)
943 {
944     apr_table_t *t = apr_table_make(r->pool, 10);
945     argstr_to_table(apr_pstrdup(r->pool, r->args), t);
946     *table = t;
947 }