]> granicus.if.org Git - apache/blob - server/util_script.c
stop using apr_sockaddr_port_get() accessor function, as it will
[apache] / server / util_script.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 #include "apr.h"
60 #include "apr_lib.h"
61 #include "apr_strings.h"
62
63 #define APR_WANT_STRFUNC
64 #include "apr_want.h"
65
66 #if APR_HAVE_STDLIB_H
67 #include <stdlib.h>
68 #endif
69
70 #define CORE_PRIVATE
71 #include "ap_config.h"
72 #include "httpd.h"
73 #include "http_config.h"
74 #include "http_main.h"
75 #include "http_log.h"
76 #include "http_core.h"
77 #include "http_protocol.h"
78 #include "http_request.h"       /* for sub_req_lookup_uri() */
79 #include "util_script.h"
80 #include "apr_date.h"           /* For apr_date_parse_http() */
81 #include "util_ebcdic.h"
82
83 #ifdef OS2
84 #define INCL_DOS
85 #include <os2.h>
86 #endif
87
88 /*
89  * Various utility functions which are common to a whole lot of
90  * script-type extensions mechanisms, and might as well be gathered
91  * in one place (if only to avoid creating inter-module dependancies
92  * where there don't have to be).
93  */
94
95 #define MALFORMED_MESSAGE "malformed header from script. Bad header="
96 #define MALFORMED_HEADER_LENGTH_TO_SHOW 30
97
98 static char *http2env(apr_pool_t *a, const char *w)
99 {
100     char *res = (char *)apr_palloc(a, sizeof("HTTP_") + strlen(w));
101     char *cp = res;
102     char c;
103
104     *cp++ = 'H';
105     *cp++ = 'T';
106     *cp++ = 'T';
107     *cp++ = 'P';
108     *cp++ = '_';
109
110     while ((c = *w++) != 0) {
111         if (!apr_isalnum(c)) {
112             *cp++ = '_';
113         }
114         else {
115             *cp++ = apr_toupper(c);
116         }
117     }
118     *cp = 0;
119  
120     return res;
121 }
122
123 AP_DECLARE(char **) ap_create_environment(apr_pool_t *p, apr_table_t *t)
124 {
125     const apr_array_header_t *env_arr = apr_table_elts(t);
126     const apr_table_entry_t *elts = (const apr_table_entry_t *) env_arr->elts;
127     char **env = (char **) apr_palloc(p, (env_arr->nelts + 2) * sizeof(char *));
128     int i, j;
129     char *tz;
130     char *whack;
131
132     j = 0;
133     if (!apr_table_get(t, "TZ")) {
134         tz = getenv("TZ");
135         if (tz != NULL) {
136             env[j++] = apr_pstrcat(p, "TZ=", tz, NULL);
137         }
138     }
139     for (i = 0; i < env_arr->nelts; ++i) {
140         if (!elts[i].key) {
141             continue;
142         }
143         env[j] = apr_pstrcat(p, elts[i].key, "=", elts[i].val, NULL);
144         whack = env[j];
145         if (apr_isdigit(*whack)) {
146             *whack++ = '_';
147         }
148         while (*whack != '=') {
149             if (!apr_isalnum(*whack) && *whack != '_') {
150                 *whack = '_';
151             }
152             ++whack;
153         }
154         ++j;
155     }
156
157     env[j] = NULL;
158     return env;
159 }
160
161 AP_DECLARE(void) ap_add_common_vars(request_rec *r)
162 {
163     apr_table_t *e;
164     server_rec *s = r->server;
165     conn_rec *c = r->connection;
166     const char *rem_logname;
167     char *env_path;
168 #if defined(WIN32) || defined(OS2) || defined(BEOS)
169     char *env_temp;
170 #endif
171     const char *host;
172     const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
173     const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
174     int i;
175     apr_port_t rport;
176
177     /* use a temporary apr_table_t which we'll overlap onto
178      * r->subprocess_env later
179      * (exception: if r->subprocess_env is empty at the start,
180      * write directly into it)
181      */
182     if (apr_is_empty_table(r->subprocess_env)) {
183       e = r->subprocess_env;
184     }
185     else {
186       e = apr_table_make(r->pool, 25 + hdrs_arr->nelts);
187     }
188
189     /* First, add environment vars from headers... this is as per
190      * CGI specs, though other sorts of scripting interfaces see
191      * the same vars...
192      */
193
194     for (i = 0; i < hdrs_arr->nelts; ++i) {
195         if (!hdrs[i].key) {
196             continue;
197         }
198
199         /* A few headers are special cased --- Authorization to prevent
200          * rogue scripts from capturing passwords; content-type and -length
201          * for no particular reason.
202          */
203
204         if (!strcasecmp(hdrs[i].key, "Content-type")) {
205             apr_table_addn(e, "CONTENT_TYPE", hdrs[i].val);
206         }
207         else if (!strcasecmp(hdrs[i].key, "Content-length")) {
208             apr_table_addn(e, "CONTENT_LENGTH", hdrs[i].val);
209         }
210         /*
211          * You really don't want to disable this check, since it leaves you
212          * wide open to CGIs stealing passwords and people viewing them
213          * in the environment with "ps -e".  But, if you must...
214          */
215 #ifndef SECURITY_HOLE_PASS_AUTHORIZATION
216         else if (!strcasecmp(hdrs[i].key, "Authorization") 
217                  || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) {
218             continue;
219         }
220 #endif
221         else {
222             apr_table_addn(e, http2env(r->pool, hdrs[i].key), hdrs[i].val);
223         }
224     }
225
226     if (!(env_path = getenv("PATH"))) {
227         env_path = DEFAULT_PATH;
228     }
229     apr_table_addn(e, "PATH", apr_pstrdup(r->pool, env_path));
230
231 #ifdef WIN32
232     if (env_temp = getenv("SystemRoot")) {
233         apr_table_addn(e, "SystemRoot", env_temp);         
234     }
235     if (env_temp = getenv("COMSPEC")) {
236         apr_table_addn(e, "COMSPEC", env_temp);            
237     }
238     if (env_temp = getenv("PATHEXT")) {
239         apr_table_addn(e, "PATHEXT", env_temp);            
240     }
241     if (env_temp = getenv("WINDIR")) {
242         apr_table_addn(e, "WINDIR", env_temp);
243     }
244 #endif
245
246 #ifdef OS2
247     if ((env_temp = getenv("COMSPEC")) != NULL) {
248         apr_table_addn(e, "COMSPEC", env_temp);            
249     }
250     if ((env_temp = getenv("ETC")) != NULL) {
251         apr_table_addn(e, "ETC", env_temp);            
252     }
253     if ((env_temp = getenv("DPATH")) != NULL) {
254         apr_table_addn(e, "DPATH", env_temp);            
255     }
256     if ((env_temp = getenv("PERLLIB_PREFIX")) != NULL) {
257         apr_table_addn(e, "PERLLIB_PREFIX", env_temp);            
258     }
259 #endif
260
261 #ifdef BEOS
262     if ((env_temp = getenv("LIBRARY_PATH")) != NULL) {
263         apr_table_addn(e, "LIBRARY_PATH", env_temp);            
264     }
265 #endif
266
267     apr_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r));
268     apr_table_addn(e, "SERVER_SOFTWARE", ap_get_server_version());
269     apr_table_addn(e, "SERVER_NAME",
270                    ap_escape_html(r->pool, ap_get_server_name(r)));
271     apr_table_addn(e, "SERVER_ADDR", r->connection->local_ip);  /* Apache */
272     apr_table_addn(e, "SERVER_PORT",
273                   apr_psprintf(r->pool, "%u", ap_get_server_port(r)));
274     host = ap_get_remote_host(c, r->per_dir_config, REMOTE_HOST, NULL);
275     if (host) {
276         apr_table_addn(e, "REMOTE_HOST", host);
277     }
278     apr_table_addn(e, "REMOTE_ADDR", c->remote_ip);
279     apr_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r));    /* Apache */
280     apr_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */
281     apr_table_addn(e, "SCRIPT_FILENAME", r->filename);  /* Apache */
282
283     rport = c->remote_addr->port;
284     apr_table_addn(e, "REMOTE_PORT", apr_itoa(r->pool, rport));
285
286     if (r->user) {
287         apr_table_addn(e, "REMOTE_USER", r->user);
288     }
289     else if (r->prev) {
290         request_rec *back = r->prev;
291
292         while (back) {
293             if (back->user) {
294                 apr_table_addn(e, "REDIRECT_REMOTE_USER", back->user);
295                 break;
296             }
297             back = back->prev;
298         }
299     }
300     if (r->ap_auth_type) {
301         apr_table_addn(e, "AUTH_TYPE", r->ap_auth_type);
302     }
303     rem_logname = ap_get_remote_logname(r);
304     if (rem_logname) {
305         apr_table_addn(e, "REMOTE_IDENT", apr_pstrdup(r->pool, rem_logname));
306     }
307
308     /* Apache custom error responses. If we have redirected set two new vars */
309
310     if (r->prev) {
311         if (r->prev->args) {
312             apr_table_addn(e, "REDIRECT_QUERY_STRING", r->prev->args);
313         }
314         if (r->prev->uri) {
315             apr_table_addn(e, "REDIRECT_URL", r->prev->uri);
316         }
317     }
318
319     if (e != r->subprocess_env) {
320       apr_table_overlap(r->subprocess_env, e, APR_OVERLAP_TABLES_SET);
321     }
322 }
323
324 /* This "cute" little function comes about because the path info on
325  * filenames and URLs aren't always the same. So we take the two,
326  * and find as much of the two that match as possible.
327  */
328
329 AP_DECLARE(int) ap_find_path_info(const char *uri, const char *path_info)
330 {
331     int lu = strlen(uri);
332     int lp = strlen(path_info);
333
334     while (lu-- && lp-- && uri[lu] == path_info[lp]);
335
336     if (lu == -1) {
337         lu = 0;
338     }
339
340     while (uri[lu] != '\0' && uri[lu] != '/') {
341         lu++;
342     }
343     return lu;
344 }
345
346 /* Obtain the Request-URI from the original request-line, returning
347  * a new string from the request pool containing the URI or "".
348  */
349 static char *original_uri(request_rec *r)
350 {
351     char *first, *last;
352
353     if (r->the_request == NULL) {
354         return (char *) apr_pcalloc(r->pool, 1);
355     }
356
357     first = r->the_request;     /* use the request-line */
358
359     while (*first && !apr_isspace(*first)) {
360         ++first;                /* skip over the method */
361     }
362     while (apr_isspace(*first)) {
363         ++first;                /*   and the space(s)   */
364     }
365
366     last = first;
367     while (*last && !apr_isspace(*last)) {
368         ++last;                 /* end at next whitespace */
369     }
370
371     return apr_pstrmemdup(r->pool, first, last - first);
372 }
373
374 AP_DECLARE(void) ap_add_cgi_vars(request_rec *r)
375 {
376     apr_table_t *e = r->subprocess_env;
377
378     apr_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
379     apr_table_setn(e, "SERVER_PROTOCOL", r->protocol);
380     apr_table_setn(e, "REQUEST_METHOD", r->method);
381     apr_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
382     apr_table_setn(e, "REQUEST_URI", original_uri(r)); 
383
384     /* Note that the code below special-cases scripts run from includes,
385      * because it "knows" that the sub_request has been hacked to have the
386      * args and path_info of the original request, and not any that may have
387      * come with the script URI in the include command.  Ugh.
388      */
389
390     if (!strcmp(r->protocol, "INCLUDED")) {
391         apr_table_setn(e, "SCRIPT_NAME", r->uri);
392         if (r->path_info && *r->path_info) {
393             apr_table_setn(e, "PATH_INFO", r->path_info);
394         }
395     }
396     else if (!r->path_info || !*r->path_info) {
397         apr_table_setn(e, "SCRIPT_NAME", r->uri);
398     }
399     else {
400         int path_info_start = ap_find_path_info(r->uri, r->path_info);
401
402         apr_table_setn(e, "SCRIPT_NAME",
403                       apr_pstrndup(r->pool, r->uri, path_info_start));
404
405         apr_table_setn(e, "PATH_INFO", r->path_info);
406     }
407
408     if (r->path_info && r->path_info[0]) {
409         /*
410          * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
411          * Need to re-escape it for this, since the entire URI was
412          * un-escaped before we determined where the PATH_INFO began.
413          */
414         request_rec *pa_req;
415
416         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r,
417                                        NULL);
418
419         if (pa_req->filename) {
420             char *pt = apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
421                                   NULL);
422 #ifdef WIN32
423             /* We need to make this a real Windows path name */
424             apr_filepath_merge(&pt, "", pt, APR_FILEPATH_NATIVE, r->pool);
425 #endif
426             apr_table_setn(e, "PATH_TRANSLATED", pt);
427         }
428         ap_destroy_sub_req(pa_req);
429     }
430 }
431
432
433 static int set_cookie_doo_doo(void *v, const char *key, const char *val)
434 {
435     apr_table_addn(v, key, val);
436     return 1;
437 }
438
439 AP_DECLARE(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
440                                        int (*getsfunc) (char *, int, void *),
441                                        void *getsfunc_data)
442 {
443     char x[MAX_STRING_LEN];
444     char *w, *l;
445     int p;
446     int cgi_status = HTTP_OK;
447     apr_table_t *merge;
448     apr_table_t *cookie_table;
449
450     if (buffer) {
451         *buffer = '\0';
452     }
453     w = buffer ? buffer : x;
454
455     /* temporary place to hold headers to merge in later */
456     merge = apr_table_make(r->pool, 10);
457
458     /* The HTTP specification says that it is legal to merge duplicate
459      * headers into one.  Some browsers that support Cookies don't like
460      * merged headers and prefer that each Set-Cookie header is sent
461      * separately.  Lets humour those browsers by not merging.
462      * Oh what a pain it is.
463      */
464     cookie_table = apr_table_make(r->pool, 2);
465     apr_table_do(set_cookie_doo_doo, cookie_table, r->err_headers_out, "Set-Cookie", NULL);
466
467     while (1) {
468
469         if ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data) == 0) {
470             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
471                           "Premature end of script headers: %s", 
472                           apr_filepath_name_get(r->filename));
473             return HTTP_INTERNAL_SERVER_ERROR;
474         }
475
476         /* Delete terminal (CR?)LF */
477
478         p = strlen(w);
479              /* Indeed, the host's '\n':
480                 '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
481                  -- whatever the script generates.
482              */                                  
483         if (p > 0 && w[p - 1] == '\n') {
484             if (p > 1 && w[p - 2] == CR) {
485                 w[p - 2] = '\0';
486             }
487             else {
488                 w[p - 1] = '\0';
489             }
490         }
491
492         /*
493          * If we've finished reading the headers, check to make sure any
494          * HTTP/1.1 conditions are met.  If so, we're done; normal processing
495          * will handle the script's output.  If not, just return the error.
496          * The appropriate thing to do would be to send the script process a
497          * SIGPIPE to let it know we're ignoring it, close the channel to the
498          * script process, and *then* return the failed-to-meet-condition
499          * error.  Otherwise we'd be waiting for the script to finish
500          * blithering before telling the client the output was no good.
501          * However, we don't have the information to do that, so we have to
502          * leave it to an upper layer.
503          */
504         if (w[0] == '\0') {
505             int cond_status = OK;
506
507             if ((cgi_status == HTTP_OK) && (r->method_number == M_GET)) {
508                 cond_status = ap_meets_conditions(r);
509             }
510             apr_table_overlap(r->err_headers_out, merge,
511                 APR_OVERLAP_TABLES_MERGE);
512             if (!apr_is_empty_table(cookie_table)) {
513                 /* the cookies have already been copied to the cookie_table */
514                 apr_table_unset(r->err_headers_out, "Set-Cookie");
515                 r->err_headers_out = apr_table_overlay(r->pool,
516                     r->err_headers_out, cookie_table);
517             }
518             return cond_status;
519         }
520
521         /* if we see a bogus header don't ignore it. Shout and scream */
522
523 #if APR_CHARSET_EBCDIC
524             /* Chances are that we received an ASCII header text instead of
525              * the expected EBCDIC header lines. Try to auto-detect:
526              */
527         if (!(l = strchr(w, ':'))) {
528             int maybeASCII = 0, maybeEBCDIC = 0;
529             unsigned char *cp, native;
530             apr_size_t inbytes_left, outbytes_left;
531
532             for (cp = w; *cp != '\0'; ++cp) {
533                 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
534                 if (apr_isprint(*cp) && !apr_isprint(native))
535                     ++maybeEBCDIC;
536                 if (!apr_isprint(*cp) && apr_isprint(native))
537                     ++maybeASCII;
538             }
539             if (maybeASCII > maybeEBCDIC) {
540                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
541                              "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)",
542                              r->filename);
543                 inbytes_left = outbytes_left = cp - w;
544                 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
545                                       w, &inbytes_left, w, &outbytes_left);
546             }
547         }
548 #endif /*APR_CHARSET_EBCDIC*/
549         if (!(l = strchr(w, ':'))) {
550             char malformed[(sizeof MALFORMED_MESSAGE) + 1
551                            + MALFORMED_HEADER_LENGTH_TO_SHOW];
552
553             strcpy(malformed, MALFORMED_MESSAGE);
554             strncat(malformed, w, MALFORMED_HEADER_LENGTH_TO_SHOW);
555
556             if (!buffer) {
557                 /* Soak up all the script output - may save an outright kill */
558                 while ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data)) {
559                     continue;
560                 }
561             }
562
563             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
564                           "%s: %s", malformed, 
565                           apr_filepath_name_get(r->filename));
566             return HTTP_INTERNAL_SERVER_ERROR;
567         }
568
569         *l++ = '\0';
570         while (*l && apr_isspace(*l)) {
571             ++l;
572         }
573
574         if (!strcasecmp(w, "Content-type")) {
575             char *tmp;
576
577             /* Nuke trailing whitespace */
578
579             char *endp = l + strlen(l) - 1;
580             while (endp > l && apr_isspace(*endp)) {
581                 *endp-- = '\0';
582             }
583
584             tmp = apr_pstrdup(r->pool, l);
585             ap_content_type_tolower(tmp);
586             ap_set_content_type(r, tmp);
587         }
588         /*
589          * If the script returned a specific status, that's what
590          * we'll use - otherwise we assume 200 OK.
591          */
592         else if (!strcasecmp(w, "Status")) {
593             r->status = cgi_status = atoi(l);
594             r->status_line = apr_pstrdup(r->pool, l);
595         }
596         else if (!strcasecmp(w, "Location")) {
597             apr_table_set(r->headers_out, w, l);
598         }
599         else if (!strcasecmp(w, "Content-Length")) {
600             apr_table_set(r->headers_out, w, l);
601         }
602         else if (!strcasecmp(w, "Transfer-Encoding")) {
603             apr_table_set(r->headers_out, w, l);
604         }
605         /*
606          * If the script gave us a Last-Modified header, we can't just
607          * pass it on blindly because of restrictions on future values.
608          */
609         else if (!strcasecmp(w, "Last-Modified")) {
610             ap_update_mtime(r, apr_date_parse_http(l));
611             ap_set_last_modified(r);
612         }
613         else if (!strcasecmp(w, "Set-Cookie")) {
614             apr_table_add(cookie_table, w, l);
615         }
616         else {
617             apr_table_add(merge, w, l);
618         }
619     }
620
621     return OK;
622 }
623
624 static int getsfunc_FILE(char *buf, int len, void *f)
625 {
626     return apr_file_gets(buf, len, (apr_file_t *) f) == APR_SUCCESS;
627 }
628
629 AP_DECLARE(int) ap_scan_script_header_err(request_rec *r, apr_file_t *f,
630                                           char *buffer)
631 {
632     return ap_scan_script_header_err_core(r, buffer, getsfunc_FILE, f);
633 }
634
635 static int getsfunc_BRIGADE(char *buf, int len, void *arg)
636 {
637     apr_bucket_brigade *bb = (apr_bucket_brigade *)arg;
638     const char *dst_end = buf + len - 1; /* leave room for terminating null */
639     char *dst = buf;
640     apr_bucket *e = APR_BRIGADE_FIRST(bb);
641     apr_status_t rv;
642     int done = 0;
643
644     while ((dst < dst_end) && !done && !APR_BUCKET_IS_EOS(e)) {
645         const char *bucket_data;
646         apr_size_t bucket_data_len;
647         const char *src;
648         const char *src_end;
649         apr_bucket * next;
650
651         rv = apr_bucket_read(e, &bucket_data, &bucket_data_len,
652                              APR_BLOCK_READ);
653         if (!APR_STATUS_IS_SUCCESS(rv) || (bucket_data_len == 0)) {
654             return 0;
655         }
656         src = bucket_data;
657         src_end = bucket_data + bucket_data_len;
658         while ((src < src_end) && (dst < dst_end) && !done) {
659             if (*src == '\n') {
660                 done = 1;
661             }
662             else if (*src != '\r') {
663                 *dst++ = *src;
664             }
665             src++;
666         }
667
668         if (src < src_end) {
669             apr_bucket_split(e, src - bucket_data);
670         }
671         next = APR_BUCKET_NEXT(e);
672         APR_BUCKET_REMOVE(e);
673         apr_bucket_destroy(e);
674         e = next;
675     }
676     *dst = 0;
677     return 1;
678 }
679
680 AP_DECLARE(int) ap_scan_script_header_err_brigade(request_rec *r,
681                                                   apr_bucket_brigade *bb,
682                                                   char *buffer)
683 {
684     return ap_scan_script_header_err_core(r, buffer, getsfunc_BRIGADE, bb);
685 }
686
687 struct vastrs {
688     va_list args;
689     int arg;
690     const char *curpos;
691 };
692
693 static int getsfunc_STRING(char *w, int len, void *pvastrs)
694 {
695     struct vastrs *strs = (struct vastrs*) pvastrs;
696     const char *p;
697     int t;
698     
699     if (!strs->curpos || !*strs->curpos) 
700         return 0;
701     p = ap_strchr_c(strs->curpos, '\n');
702     if (p)
703         ++p;
704     else
705         p = ap_strchr_c(strs->curpos, '\0');
706     t = p - strs->curpos;
707     if (t > len)
708         t = len;
709     strncpy (w, strs->curpos, t);
710     w[t] = '\0';
711     if (!strs->curpos[t]) {
712         ++strs->arg;
713         strs->curpos = va_arg(strs->args, const char *);
714     }
715     else
716         strs->curpos += t;
717     return t;    
718 }
719
720 /* ap_scan_script_header_err_strs() accepts additional const char* args...
721  * each is treated as one or more header lines, and the first non-header
722  * character is returned to **arg, **data.  (The first optional arg is
723  * counted as 0.)
724  */
725 AP_DECLARE_NONSTD(int) ap_scan_script_header_err_strs(request_rec *r, 
726                                                       char *buffer, 
727                                                       const char **termch,
728                                                       int *termarg, ...)
729 {
730     struct vastrs strs;
731     int res;
732
733     va_start(strs.args, termarg);
734     strs.arg = 0;
735     strs.curpos = va_arg(strs.args, char*);
736     res = ap_scan_script_header_err_core(r, buffer, getsfunc_STRING, (void *) &strs);
737     if (termch)
738         *termch = strs.curpos;
739     if (termarg)
740         *termarg = strs.arg;
741     va_end(strs.args);
742     return res;
743 }