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