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