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