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