]> granicus.if.org Git - apache/blob - server/util_script.c
Merge r1741310, r1741461 from trunk:
[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_useragent_host(r, 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         if (conf->qualify_redirect_url != AP_CORE_CONFIG_ON) { 
290             add_unless_null(e, "REDIRECT_URL", r->prev->uri);
291         }
292         else { 
293             /* PR#57785: reconstruct full URL here */
294             apr_uri_t *uri = &r->prev->parsed_uri;
295             if (!uri->scheme) {
296                 uri->scheme = (char*)ap_http_scheme(r->prev);
297             }
298             if (!uri->port) {
299                 uri->port = ap_get_server_port(r->prev);
300                 uri->port_str = apr_psprintf(r->pool, "%u", uri->port);
301             }
302             if (!uri->hostname) {
303                 uri->hostname = (char*)ap_get_server_name_for_url(r->prev);
304             }
305             add_unless_null(e, "REDIRECT_URL",
306                             apr_uri_unparse(r->pool, uri, 0));
307         }
308         add_unless_null(e, "REDIRECT_QUERY_STRING", r->prev->args);
309     }
310
311     if (e != r->subprocess_env) {
312         apr_table_overlap(r->subprocess_env, e, APR_OVERLAP_TABLES_SET);
313     }
314 }
315
316 /* This "cute" little function comes about because the path info on
317  * filenames and URLs aren't always the same. So we take the two,
318  * and find as much of the two that match as possible.
319  */
320
321 AP_DECLARE(int) ap_find_path_info(const char *uri, const char *path_info)
322 {
323     int lu = strlen(uri);
324     int lp = strlen(path_info);
325
326     while (lu-- && lp-- && uri[lu] == path_info[lp]) {
327         if (path_info[lp] == '/') {
328             while (lu && uri[lu-1] == '/') lu--;
329         }
330     }
331
332     if (lu == -1) {
333         lu = 0;
334     }
335
336     while (uri[lu] != '\0' && uri[lu] != '/') {
337         lu++;
338     }
339     return lu;
340 }
341
342 /* Obtain the Request-URI from the original request-line, returning
343  * a new string from the request pool containing the URI or "".
344  */
345 static char *original_uri(request_rec *r)
346 {
347     char *first, *last;
348
349     if (r->the_request == NULL) {
350         return (char *) apr_pcalloc(r->pool, 1);
351     }
352
353     first = r->the_request;     /* use the request-line */
354
355     while (*first && !apr_isspace(*first)) {
356         ++first;                /* skip over the method */
357     }
358     while (apr_isspace(*first)) {
359         ++first;                /*   and the space(s)   */
360     }
361
362     last = first;
363     while (*last && !apr_isspace(*last)) {
364         ++last;                 /* end at next whitespace */
365     }
366
367     return apr_pstrmemdup(r->pool, first, last - first);
368 }
369
370 AP_DECLARE(void) ap_add_cgi_vars(request_rec *r)
371 {
372     apr_table_t *e = r->subprocess_env;
373     core_dir_config *conf =
374         (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
375     int request_uri_from_original = 1;
376     const char *request_uri_rule;
377
378     apr_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
379     apr_table_setn(e, "SERVER_PROTOCOL", r->protocol);
380     apr_table_setn(e, "REQUEST_METHOD", r->method);
381     apr_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
382
383     if (conf->cgi_var_rules) {
384         request_uri_rule = apr_hash_get(conf->cgi_var_rules, "REQUEST_URI",
385                                         APR_HASH_KEY_STRING);
386         if (request_uri_rule && !strcmp(request_uri_rule, "current-uri")) {
387             request_uri_from_original = 0;
388         }
389     }
390     apr_table_setn(e, "REQUEST_URI",
391                    request_uri_from_original ? original_uri(r) : r->uri);
392
393     /* Note that the code below special-cases scripts run from includes,
394      * because it "knows" that the sub_request has been hacked to have the
395      * args and path_info of the original request, and not any that may have
396      * come with the script URI in the include command.  Ugh.
397      */
398
399     if (!strcmp(r->protocol, "INCLUDED")) {
400         apr_table_setn(e, "SCRIPT_NAME", r->uri);
401         if (r->path_info && *r->path_info) {
402             apr_table_setn(e, "PATH_INFO", r->path_info);
403         }
404     }
405     else if (!r->path_info || !*r->path_info) {
406         apr_table_setn(e, "SCRIPT_NAME", r->uri);
407     }
408     else {
409         int path_info_start = ap_find_path_info(r->uri, r->path_info);
410
411         apr_table_setn(e, "SCRIPT_NAME",
412                       apr_pstrndup(r->pool, r->uri, path_info_start));
413
414         apr_table_setn(e, "PATH_INFO", r->path_info);
415     }
416
417     if (r->path_info && r->path_info[0]) {
418         /*
419          * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
420          * Need to re-escape it for this, since the entire URI was
421          * un-escaped before we determined where the PATH_INFO began.
422          */
423         request_rec *pa_req;
424
425         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r,
426                                        NULL);
427
428         if (pa_req->filename) {
429             char *pt = apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
430                                   NULL);
431 #ifdef WIN32
432             /* We need to make this a real Windows path name */
433             apr_filepath_merge(&pt, "", pt, APR_FILEPATH_NATIVE, r->pool);
434 #endif
435             apr_table_setn(e, "PATH_TRANSLATED", pt);
436         }
437         ap_destroy_sub_req(pa_req);
438     }
439 }
440
441
442 static int set_cookie_doo_doo(void *v, const char *key, const char *val)
443 {
444     apr_table_addn(v, key, val);
445     return 1;
446 }
447
448 #define HTTP_UNSET (-HTTP_OK)
449 #define SCRIPT_LOG_MARK  __FILE__,__LINE__,module_index
450
451 AP_DECLARE(int) ap_scan_script_header_err_core_ex(request_rec *r, char *buffer,
452                                        int (*getsfunc) (char *, int, void *),
453                                        void *getsfunc_data,
454                                        int module_index)
455 {
456     char x[MAX_STRING_LEN];
457     char *w, *l;
458     int p;
459     int cgi_status = HTTP_UNSET;
460     apr_table_t *merge;
461     apr_table_t *cookie_table;
462     int trace_log = APLOG_R_MODULE_IS_LEVEL(r, module_index, APLOG_TRACE1);
463     int first_header = 1;
464
465     if (buffer) {
466         *buffer = '\0';
467     }
468     w = buffer ? buffer : x;
469
470     /* temporary place to hold headers to merge in later */
471     merge = apr_table_make(r->pool, 10);
472
473     /* The HTTP specification says that it is legal to merge duplicate
474      * headers into one.  Some browsers that support Cookies don't like
475      * merged headers and prefer that each Set-Cookie header is sent
476      * separately.  Lets humour those browsers by not merging.
477      * Oh what a pain it is.
478      */
479     cookie_table = apr_table_make(r->pool, 2);
480     apr_table_do(set_cookie_doo_doo, cookie_table, r->err_headers_out, "Set-Cookie", NULL);
481
482     while (1) {
483
484         int rv = (*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data);
485         if (rv == 0) {
486             const char *msg = "Premature end of script headers";
487             if (first_header)
488                 msg = "End of script output before headers";
489             /* Intentional no APLOGNO */
490             ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
491                           "%s: %s", msg,
492                           apr_filepath_name_get(r->filename));
493             return HTTP_INTERNAL_SERVER_ERROR;
494         }
495         else if (rv == -1) {
496             /* Intentional no APLOGNO */
497             ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
498                           "Script timed out before returning headers: %s",
499                           apr_filepath_name_get(r->filename));
500             return HTTP_GATEWAY_TIME_OUT;
501         }
502
503         /* Delete terminal (CR?)LF */
504
505         p = strlen(w);
506              /* Indeed, the host's '\n':
507                 '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
508                  -- whatever the script generates.
509              */
510         if (p > 0 && w[p - 1] == '\n') {
511             if (p > 1 && w[p - 2] == CR) {
512                 w[p - 2] = '\0';
513             }
514             else {
515                 w[p - 1] = '\0';
516             }
517         }
518
519         /*
520          * If we've finished reading the headers, check to make sure any
521          * HTTP/1.1 conditions are met.  If so, we're done; normal processing
522          * will handle the script's output.  If not, just return the error.
523          * The appropriate thing to do would be to send the script process a
524          * SIGPIPE to let it know we're ignoring it, close the channel to the
525          * script process, and *then* return the failed-to-meet-condition
526          * error.  Otherwise we'd be waiting for the script to finish
527          * blithering before telling the client the output was no good.
528          * However, we don't have the information to do that, so we have to
529          * leave it to an upper layer.
530          */
531         if (w[0] == '\0') {
532             int cond_status = OK;
533
534             /* PR#38070: This fails because it gets confused when a
535              * CGI Status header overrides ap_meets_conditions.
536              *
537              * We can fix that by dropping ap_meets_conditions when
538              * Status has been set.  Since this is the only place
539              * cgi_status gets used, let's test it explicitly.
540              *
541              * The alternative would be to ignore CGI Status when
542              * ap_meets_conditions returns anything interesting.
543              * That would be safer wrt HTTP, but would break CGI.
544              */
545             if ((cgi_status == HTTP_UNSET) && (r->method_number == M_GET)) {
546                 cond_status = ap_meets_conditions(r);
547             }
548             apr_table_overlap(r->err_headers_out, merge,
549                 APR_OVERLAP_TABLES_MERGE);
550             if (!apr_is_empty_table(cookie_table)) {
551                 /* the cookies have already been copied to the cookie_table */
552                 apr_table_unset(r->err_headers_out, "Set-Cookie");
553                 r->err_headers_out = apr_table_overlay(r->pool,
554                     r->err_headers_out, cookie_table);
555             }
556             return cond_status;
557         }
558
559         if (trace_log) {
560             if (first_header)
561                 ap_log_rerror(SCRIPT_LOG_MARK, APLOG_TRACE4, 0, r,
562                               "Headers from script '%s':",
563                               apr_filepath_name_get(r->filename));
564             ap_log_rerror(SCRIPT_LOG_MARK, APLOG_TRACE4, 0, r, "  %s", w);
565         }
566
567         /* if we see a bogus header don't ignore it. Shout and scream */
568
569 #if APR_CHARSET_EBCDIC
570             /* Chances are that we received an ASCII header text instead of
571              * the expected EBCDIC header lines. Try to auto-detect:
572              */
573         if (!(l = strchr(w, ':'))) {
574             int maybeASCII = 0, maybeEBCDIC = 0;
575             unsigned char *cp, native;
576             apr_size_t inbytes_left, outbytes_left;
577
578             for (cp = w; *cp != '\0'; ++cp) {
579                 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
580                 if (apr_isprint(*cp) && !apr_isprint(native))
581                     ++maybeEBCDIC;
582                 if (!apr_isprint(*cp) && apr_isprint(native))
583                     ++maybeASCII;
584             }
585             if (maybeASCII > maybeEBCDIC) {
586                 ap_log_error(SCRIPT_LOG_MARK, APLOG_ERR, 0, r->server,
587                              APLOGNO(02660) "CGI Interface Error: "
588                              "Script headers apparently ASCII: (CGI = %s)",
589                              r->filename);
590                 inbytes_left = outbytes_left = cp - w;
591                 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
592                                       w, &inbytes_left, w, &outbytes_left);
593             }
594         }
595 #endif /*APR_CHARSET_EBCDIC*/
596         if (!(l = strchr(w, ':'))) {
597             if (!buffer) {
598                 /* Soak up all the script output - may save an outright kill */
599                 while ((*getsfunc)(w, MAX_STRING_LEN - 1, getsfunc_data) > 0) {
600                     continue;
601                 }
602             }
603
604             /* Intentional no APLOGNO */
605             ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
606                           "malformed header from script '%s': Bad header: %.30s",
607                           apr_filepath_name_get(r->filename), w);
608             return HTTP_INTERNAL_SERVER_ERROR;
609         }
610
611         *l++ = '\0';
612         while (apr_isspace(*l)) {
613             ++l;
614         }
615
616         if (!strcasecmp(w, "Content-type")) {
617             char *tmp;
618
619             /* Nuke trailing whitespace */
620
621             char *endp = l + strlen(l) - 1;
622             while (endp > l && apr_isspace(*endp)) {
623                 *endp-- = '\0';
624             }
625
626             tmp = apr_pstrdup(r->pool, l);
627             ap_content_type_tolower(tmp);
628             ap_set_content_type(r, tmp);
629         }
630         /*
631          * If the script returned a specific status, that's what
632          * we'll use - otherwise we assume 200 OK.
633          */
634         else if (!strcasecmp(w, "Status")) {
635             r->status = cgi_status = atoi(l);
636             if (!ap_is_HTTP_VALID_RESPONSE(cgi_status))
637                 /* Intentional no APLOGNO */
638                 ap_log_rerror(SCRIPT_LOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
639                               "Invalid status line from script '%s': %.30s",
640                               apr_filepath_name_get(r->filename), l);
641             else
642                 if (APLOGrtrace1(r))
643                    ap_log_rerror(SCRIPT_LOG_MARK, APLOG_TRACE1, 0, r,
644                                  "Status line from script '%s': %.30s",
645                                  apr_filepath_name_get(r->filename), l);
646             r->status_line = apr_pstrdup(r->pool, l);
647         }
648         else if (!strcasecmp(w, "Location")) {
649             apr_table_set(r->headers_out, w, l);
650         }
651         else if (!strcasecmp(w, "Content-Length")) {
652             apr_table_set(r->headers_out, w, l);
653         }
654         else if (!strcasecmp(w, "Content-Range")) {
655             apr_table_set(r->headers_out, w, l);
656         }
657         else if (!strcasecmp(w, "Transfer-Encoding")) {
658             apr_table_set(r->headers_out, w, l);
659         }
660         else if (!strcasecmp(w, "ETag")) {
661             apr_table_set(r->headers_out, w, l);
662         }
663         /*
664          * If the script gave us a Last-Modified header, we can't just
665          * pass it on blindly because of restrictions on future values.
666          */
667         else if (!strcasecmp(w, "Last-Modified")) {
668             ap_update_mtime(r, apr_date_parse_http(l));
669             ap_set_last_modified(r);
670         }
671         else if (!strcasecmp(w, "Set-Cookie")) {
672             apr_table_add(cookie_table, w, l);
673         }
674         else {
675             apr_table_add(merge, w, l);
676         }
677         first_header = 0;
678     }
679     /* never reached - we leave this function within the while loop above */
680     return OK;
681 }
682
683 AP_DECLARE(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
684                                        int (*getsfunc) (char *, int, void *),
685                                        void *getsfunc_data)
686 {
687     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc,
688                                              getsfunc_data,
689                                              APLOG_MODULE_INDEX);
690 }
691
692 static int getsfunc_FILE(char *buf, int len, void *f)
693 {
694     return apr_file_gets(buf, len, (apr_file_t *) f) == APR_SUCCESS;
695 }
696
697 AP_DECLARE(int) ap_scan_script_header_err(request_rec *r, apr_file_t *f,
698                                           char *buffer)
699 {
700     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc_FILE, f,
701                                              APLOG_MODULE_INDEX);
702 }
703
704 AP_DECLARE(int) ap_scan_script_header_err_ex(request_rec *r, apr_file_t *f,
705                                           char *buffer, int module_index)
706 {
707     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc_FILE, f,
708                                              module_index);
709 }
710
711
712 static int getsfunc_BRIGADE(char *buf, int len, void *arg)
713 {
714     apr_bucket_brigade *bb = (apr_bucket_brigade *)arg;
715     const char *dst_end = buf + len - 1; /* leave room for terminating null */
716     char *dst = buf;
717     apr_bucket *e = APR_BRIGADE_FIRST(bb);
718     apr_status_t rv;
719     int done = 0;
720
721     while ((dst < dst_end) && !done && e != APR_BRIGADE_SENTINEL(bb)
722            && !APR_BUCKET_IS_EOS(e)) {
723         const char *bucket_data;
724         apr_size_t bucket_data_len;
725         const char *src;
726         const char *src_end;
727         apr_bucket * next;
728
729         rv = apr_bucket_read(e, &bucket_data, &bucket_data_len,
730                              APR_BLOCK_READ);
731         if (rv != APR_SUCCESS || (bucket_data_len == 0)) {
732             *dst = '\0';
733             return APR_STATUS_IS_TIMEUP(rv) ? -1 : 0;
734         }
735         src = bucket_data;
736         src_end = bucket_data + bucket_data_len;
737         while ((src < src_end) && (dst < dst_end) && !done) {
738             if (*src == '\n') {
739                 done = 1;
740             }
741             else if (*src != '\r') {
742                 *dst++ = *src;
743             }
744             src++;
745         }
746
747         if (src < src_end) {
748             apr_bucket_split(e, src - bucket_data);
749         }
750         next = APR_BUCKET_NEXT(e);
751         apr_bucket_delete(e);
752         e = next;
753     }
754     *dst = 0;
755     return done;
756 }
757
758 AP_DECLARE(int) ap_scan_script_header_err_brigade(request_rec *r,
759                                                   apr_bucket_brigade *bb,
760                                                   char *buffer)
761 {
762     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc_BRIGADE, bb,
763                                              APLOG_MODULE_INDEX);
764 }
765
766 AP_DECLARE(int) ap_scan_script_header_err_brigade_ex(request_rec *r,
767                                                      apr_bucket_brigade *bb,
768                                                      char *buffer,
769                                                      int module_index)
770 {
771     return ap_scan_script_header_err_core_ex(r, buffer, getsfunc_BRIGADE, bb,
772                                              module_index);
773 }
774
775
776 struct vastrs {
777     va_list args;
778     int arg;
779     const char *curpos;
780 };
781
782 static int getsfunc_STRING(char *w, int len, void *pvastrs)
783 {
784     struct vastrs *strs = (struct vastrs*) pvastrs;
785     const char *p;
786     int t;
787
788     if (!strs->curpos || !*strs->curpos) {
789         w[0] = '\0';
790         return 0;
791     }
792     p = ap_strchr_c(strs->curpos, '\n');
793     if (p)
794         ++p;
795     else
796         p = ap_strchr_c(strs->curpos, '\0');
797     t = p - strs->curpos;
798     if (t > len)
799         t = len;
800     strncpy (w, strs->curpos, t);
801     w[t] = '\0';
802     if (!strs->curpos[t]) {
803         ++strs->arg;
804         strs->curpos = va_arg(strs->args, const char *);
805     }
806     else
807         strs->curpos += t;
808     return t;
809 }
810
811 /* ap_scan_script_header_err_strs() accepts additional const char* args...
812  * each is treated as one or more header lines, and the first non-header
813  * character is returned to **arg, **data.  (The first optional arg is
814  * counted as 0.)
815  */
816 AP_DECLARE_NONSTD(int) ap_scan_script_header_err_strs_ex(request_rec *r,
817                                                          char *buffer,
818                                                          int module_index,
819                                                          const char **termch,
820                                                          int *termarg, ...)
821 {
822     struct vastrs strs;
823     int res;
824
825     va_start(strs.args, termarg);
826     strs.arg = 0;
827     strs.curpos = va_arg(strs.args, char*);
828     res = ap_scan_script_header_err_core_ex(r, buffer, getsfunc_STRING,
829                                             (void *) &strs, module_index);
830     if (termch)
831         *termch = strs.curpos;
832     if (termarg)
833         *termarg = strs.arg;
834     va_end(strs.args);
835     return res;
836 }
837
838 AP_DECLARE_NONSTD(int) ap_scan_script_header_err_strs(request_rec *r,
839                                                       char *buffer,
840                                                       const char **termch,
841                                                       int *termarg, ...)
842 {
843     struct vastrs strs;
844     int res;
845
846     va_start(strs.args, termarg);
847     strs.arg = 0;
848     strs.curpos = va_arg(strs.args, char*);
849     res = ap_scan_script_header_err_core_ex(r, buffer, getsfunc_STRING,
850                                             (void *) &strs, APLOG_MODULE_INDEX);
851     if (termch)
852         *termch = strs.curpos;
853     if (termarg)
854         *termarg = strs.arg;
855     va_end(strs.args);
856     return res;
857 }
858
859 static void
860 argstr_to_table(char *str, apr_table_t *parms)
861 {
862     char *key;
863     char *value;
864     char *strtok_state;
865
866     if (str == NULL) {
867         return;
868     }
869
870     key = apr_strtok(str, "&", &strtok_state);
871     while (key) {
872         value = strchr(key, '=');
873         if (value) {
874             *value = '\0';      /* Split the string in two */
875             value++;            /* Skip passed the = */
876         }
877         else {
878             value = "1";
879         }
880         ap_unescape_url(key);
881         ap_unescape_url(value);
882         apr_table_set(parms, key, value);
883         key = apr_strtok(NULL, "&", &strtok_state);
884     }
885 }
886
887 AP_DECLARE(void) ap_args_to_table(request_rec *r, apr_table_t **table)
888 {
889     apr_table_t *t = apr_table_make(r->pool, 10);
890     argstr_to_table(apr_pstrdup(r->pool, r->args), t);
891     *table = t;
892 }