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