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