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