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