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