]> granicus.if.org Git - apache/blob - server/util.c
CVE-2012-3499
[apache] / server / util.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 /*
18  * util.c: string utility things
19  *
20  * 3/21/93 Rob McCool
21  * 1995-96 Many changes by the Apache Software Foundation
22  *
23  */
24
25 /* Debugging aid:
26  * #define DEBUG            to trace all cfg_open*()/cfg_closefile() calls
27  * #define DEBUG_CFG_LINES  to trace every line read from the config files
28  */
29
30 #include "apr.h"
31 #include "apr_strings.h"
32 #include "apr_lib.h"
33
34 #define APR_WANT_STDIO
35 #define APR_WANT_STRFUNC
36 #include "apr_want.h"
37
38 #if APR_HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41 #if APR_HAVE_PROCESS_H
42 #include <process.h>            /* for getpid() on Win32 */
43 #endif
44 #if APR_HAVE_NETDB_H
45 #include <netdb.h>              /* for gethostbyname() */
46 #endif
47
48 #include "ap_config.h"
49 #include "apr_base64.h"
50 #include "httpd.h"
51 #include "http_main.h"
52 #include "http_log.h"
53 #include "http_protocol.h"
54 #include "http_config.h"
55 #include "http_core.h"
56 #include "util_ebcdic.h"
57 #include "util_varbuf.h"
58
59 #ifdef HAVE_PWD_H
60 #include <pwd.h>
61 #endif
62 #ifdef HAVE_GRP_H
63 #include <grp.h>
64 #endif
65 #ifdef HAVE_SYS_LOADAVG_H
66 #include <sys/loadavg.h>
67 #endif
68
69 #include "ap_mpm.h"
70
71 /* A bunch of functions in util.c scan strings looking for certain characters.
72  * To make that more efficient we encode a lookup table.  The test_char_table
73  * is generated automatically by gen_test_char.c.
74  */
75 #include "test_char.h"
76
77 /* we assume the folks using this ensure 0 <= c < 256... which means
78  * you need a cast to (unsigned char) first, you can't just plug a
79  * char in here and get it to work, because if char is signed then it
80  * will first be sign extended.
81  */
82 #define TEST_CHAR(c, f)        (test_char_table[(unsigned)(c)] & (f))
83
84 /* Win32/NetWare/OS2 need to check for both forward and back slashes
85  * in ap_getparents() and ap_escape_url.
86  */
87 #ifdef CASE_BLIND_FILESYSTEM
88 #define IS_SLASH(s) ((s == '/') || (s == '\\'))
89 #define SLASHES "/\\"
90 #else
91 #define IS_SLASH(s) (s == '/')
92 #define SLASHES "/"
93 #endif
94
95 /* we know core's module_index is 0 */
96 #undef APLOG_MODULE_INDEX
97 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
98
99
100 /*
101  * Examine a field value (such as a media-/content-type) string and return
102  * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
103  */
104 AP_DECLARE(char *) ap_field_noparam(apr_pool_t *p, const char *intype)
105 {
106     const char *semi;
107
108     if (intype == NULL) return NULL;
109
110     semi = ap_strchr_c(intype, ';');
111     if (semi == NULL) {
112         return apr_pstrdup(p, intype);
113     }
114     else {
115         while ((semi > intype) && apr_isspace(semi[-1])) {
116             semi--;
117         }
118         return apr_pstrndup(p, intype, semi - intype);
119     }
120 }
121
122 AP_DECLARE(char *) ap_ht_time(apr_pool_t *p, apr_time_t t, const char *fmt,
123                               int gmt)
124 {
125     apr_size_t retcode;
126     char ts[MAX_STRING_LEN];
127     char tf[MAX_STRING_LEN];
128     apr_time_exp_t xt;
129
130     if (gmt) {
131         const char *f;
132         char *strp;
133
134         apr_time_exp_gmt(&xt, t);
135         /* Convert %Z to "GMT" and %z to "+0000";
136          * on hosts that do not have a time zone string in struct tm,
137          * strftime must assume its argument is local time.
138          */
139         for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
140             ; f++, strp++) {
141             if (*f != '%') continue;
142             switch (f[1]) {
143             case '%':
144                 *++strp = *++f;
145                 break;
146             case 'Z':
147                 *strp++ = 'G';
148                 *strp++ = 'M';
149                 *strp = 'T';
150                 f++;
151                 break;
152             case 'z': /* common extension */
153                 *strp++ = '+';
154                 *strp++ = '0';
155                 *strp++ = '0';
156                 *strp++ = '0';
157                 *strp = '0';
158                 f++;
159                 break;
160             }
161         }
162         *strp = '\0';
163         fmt = tf;
164     }
165     else {
166         apr_time_exp_lt(&xt, t);
167     }
168
169     /* check return code? */
170     apr_strftime(ts, &retcode, MAX_STRING_LEN, fmt, &xt);
171     ts[MAX_STRING_LEN - 1] = '\0';
172     return apr_pstrdup(p, ts);
173 }
174
175 /* Roy owes Rob beer. */
176 /* Rob owes Roy dinner. */
177
178 /* These legacy comments would make a lot more sense if Roy hadn't
179  * replaced the old later_than() routine with util_date.c.
180  *
181  * Well, okay, they still wouldn't make any sense.
182  */
183
184 /* Match = 0, NoMatch = 1, Abort = -1
185  * Based loosely on sections of wildmat.c by Rich Salz
186  * Hmmm... shouldn't this really go component by component?
187  */
188 AP_DECLARE(int) ap_strcmp_match(const char *str, const char *expected)
189 {
190     int x, y;
191
192     for (x = 0, y = 0; expected[y]; ++y, ++x) {
193         if ((!str[x]) && (expected[y] != '*'))
194             return -1;
195         if (expected[y] == '*') {
196             while (expected[++y] == '*');
197             if (!expected[y])
198                 return 0;
199             while (str[x]) {
200                 int ret;
201                 if ((ret = ap_strcmp_match(&str[x++], &expected[y])) != 1)
202                     return ret;
203             }
204             return -1;
205         }
206         else if ((expected[y] != '?') && (str[x] != expected[y]))
207             return 1;
208     }
209     return (str[x] != '\0');
210 }
211
212 AP_DECLARE(int) ap_strcasecmp_match(const char *str, const char *expected)
213 {
214     int x, y;
215
216     for (x = 0, y = 0; expected[y]; ++y, ++x) {
217         if (!str[x] && expected[y] != '*')
218             return -1;
219         if (expected[y] == '*') {
220             while (expected[++y] == '*');
221             if (!expected[y])
222                 return 0;
223             while (str[x]) {
224                 int ret;
225                 if ((ret = ap_strcasecmp_match(&str[x++], &expected[y])) != 1)
226                     return ret;
227             }
228             return -1;
229         }
230         else if (expected[y] != '?'
231                  && apr_tolower(str[x]) != apr_tolower(expected[y]))
232             return 1;
233     }
234     return (str[x] != '\0');
235 }
236
237 /* We actually compare the canonical root to this root, (but we don't
238  * waste time checking the case), since every use of this function in
239  * httpd-2.1 tests if the path is 'proper', meaning we've already passed
240  * it through apr_filepath_merge, or we haven't.
241  */
242 AP_DECLARE(int) ap_os_is_path_absolute(apr_pool_t *p, const char *dir)
243 {
244     const char *newpath;
245     const char *ourdir = dir;
246     if (apr_filepath_root(&newpath, &dir, 0, p) != APR_SUCCESS
247             || strncmp(newpath, ourdir, strlen(newpath)) != 0) {
248         return 0;
249     }
250     return 1;
251 }
252
253 AP_DECLARE(int) ap_is_matchexp(const char *str)
254 {
255     register int x;
256
257     for (x = 0; str[x]; x++)
258         if ((str[x] == '*') || (str[x] == '?'))
259             return 1;
260     return 0;
261 }
262
263 /*
264  * Here's a pool-based interface to the POSIX-esque ap_regcomp().
265  * Note that we return ap_regex_t instead of being passed one.
266  * The reason is that if you use an already-used ap_regex_t structure,
267  * the memory that you've already allocated gets forgotten, and
268  * regfree() doesn't clear it. So we don't allow it.
269  */
270
271 static apr_status_t regex_cleanup(void *preg)
272 {
273     ap_regfree((ap_regex_t *) preg);
274     return APR_SUCCESS;
275 }
276
277 AP_DECLARE(ap_regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
278                                      int cflags)
279 {
280     ap_regex_t *preg = apr_palloc(p, sizeof *preg);
281     int err = ap_regcomp(preg, pattern, cflags);
282     if (err) {
283         if (err == AP_REG_ESPACE)
284             ap_abort_on_oom();
285         return NULL;
286     }
287
288     apr_pool_cleanup_register(p, (void *) preg, regex_cleanup,
289                               apr_pool_cleanup_null);
290
291     return preg;
292 }
293
294 AP_DECLARE(void) ap_pregfree(apr_pool_t *p, ap_regex_t *reg)
295 {
296     ap_regfree(reg);
297     apr_pool_cleanup_kill(p, (void *) reg, regex_cleanup);
298 }
299
300 /*
301  * Similar to standard strstr() but we ignore case in this version.
302  * Based on the strstr() implementation further below.
303  */
304 AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
305 {
306     char *p1, *p2;
307     if (*s2 == '\0') {
308         /* an empty s2 */
309         return((char *)s1);
310     }
311     while(1) {
312         for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
313         if (*s1 == '\0') {
314             return(NULL);
315         }
316         /* found first character of s2, see if the rest matches */
317         p1 = (char *)s1;
318         p2 = (char *)s2;
319         for (++p1, ++p2; apr_tolower(*p1) == apr_tolower(*p2); ++p1, ++p2) {
320             if (*p1 == '\0') {
321                 /* both strings ended together */
322                 return((char *)s1);
323             }
324         }
325         if (*p2 == '\0') {
326             /* second string ended, a match */
327             break;
328         }
329         /* didn't find a match here, try starting at next character in s1 */
330         s1++;
331     }
332     return((char *)s1);
333 }
334
335 /*
336  * Returns an offsetted pointer in bigstring immediately after
337  * prefix. Returns bigstring if bigstring doesn't start with
338  * prefix or if prefix is longer than bigstring while still matching.
339  * NOTE: pointer returned is relative to bigstring, so we
340  * can use standard pointer comparisons in the calling function
341  * (eg: test if ap_stripprefix(a,b) == a)
342  */
343 AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
344                                         const char *prefix)
345 {
346     const char *p1;
347
348     if (*prefix == '\0')
349         return bigstring;
350
351     p1 = bigstring;
352     while (*p1 && *prefix) {
353         if (*p1++ != *prefix++)
354             return bigstring;
355     }
356     if (*prefix == '\0')
357         return p1;
358
359     /* hit the end of bigstring! */
360     return bigstring;
361 }
362
363 /* This function substitutes for $0-$9, filling in regular expression
364  * submatches. Pass it the same nmatch and pmatch arguments that you
365  * passed ap_regexec(). pmatch should not be greater than the maximum number
366  * of subexpressions - i.e. one more than the re_nsub member of ap_regex_t.
367  *
368  * nmatch must be <=AP_MAX_REG_MATCH (10).
369  *
370  * input should be the string with the $-expressions, source should be the
371  * string that was matched against.
372  *
373  * It returns the substituted string, or NULL if a vbuf is used.
374  * On errors, returns the orig string.
375  *
376  * Parts of this code are based on Henry Spencer's regsub(), from his
377  * AT&T V8 regexp package.
378  */
379
380 static apr_status_t regsub_core(apr_pool_t *p, char **result,
381                                 struct ap_varbuf *vb, const char *input,
382                                 const char *source, apr_size_t nmatch,
383                                 ap_regmatch_t pmatch[], apr_size_t maxlen)
384 {
385     const char *src = input;
386     char *dst;
387     char c;
388     apr_size_t no;
389     apr_size_t len = 0;
390
391     AP_DEBUG_ASSERT((result && p && !vb) || (vb && !p && !result));
392     if (!source || nmatch>AP_MAX_REG_MATCH)
393         return APR_EINVAL;
394     if (!nmatch) {
395         len = strlen(src);
396         if (maxlen > 0 && len >= maxlen)
397             return APR_ENOMEM;
398         if (!vb) {
399             *result = apr_pstrmemdup(p, src, len);
400             return APR_SUCCESS;
401         }
402         else {
403             ap_varbuf_strmemcat(vb, src, len);
404             return APR_SUCCESS;
405         }
406     }
407
408     /* First pass, find the size */
409     while ((c = *src++) != '\0') {
410         if (c == '$' && apr_isdigit(*src))
411             no = *src++ - '0';
412         else
413             no = AP_MAX_REG_MATCH;
414
415         if (no >= AP_MAX_REG_MATCH) {  /* Ordinary character. */
416             if (c == '\\' && *src)
417                 src++;
418             len++;
419         }
420         else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
421             if (APR_SIZE_MAX - len <= pmatch[no].rm_eo - pmatch[no].rm_so)
422                 return APR_ENOMEM;
423             len += pmatch[no].rm_eo - pmatch[no].rm_so;
424         }
425
426     }
427
428     if (len >= maxlen && maxlen > 0)
429         return APR_ENOMEM;
430
431     if (!vb) {
432         *result = dst = apr_palloc(p, len + 1);
433     }
434     else {
435         if (vb->strlen == AP_VARBUF_UNKNOWN)
436             vb->strlen = strlen(vb->buf);
437         ap_varbuf_grow(vb, vb->strlen + len);
438         dst = vb->buf + vb->strlen;
439         vb->strlen += len;
440     }
441
442     /* Now actually fill in the string */
443
444     src = input;
445
446     while ((c = *src++) != '\0') {
447         if (c == '$' && apr_isdigit(*src))
448             no = *src++ - '0';
449         else
450             no = AP_MAX_REG_MATCH;
451
452         if (no >= AP_MAX_REG_MATCH) {  /* Ordinary character. */
453             if (c == '\\' && *src)
454                 c = *src++;
455             *dst++ = c;
456         }
457         else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
458             len = pmatch[no].rm_eo - pmatch[no].rm_so;
459             memcpy(dst, source + pmatch[no].rm_so, len);
460             dst += len;
461         }
462
463     }
464     *dst = '\0';
465
466     return APR_SUCCESS;
467 }
468
469 #ifndef AP_PREGSUB_MAXLEN
470 #define AP_PREGSUB_MAXLEN   (HUGE_STRING_LEN * 8)
471 #endif
472 AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input,
473                               const char *source, apr_size_t nmatch,
474                               ap_regmatch_t pmatch[])
475 {
476     char *result;
477     apr_status_t rc = regsub_core(p, &result, NULL, input, source, nmatch,
478                                   pmatch, AP_PREGSUB_MAXLEN);
479     if (rc != APR_SUCCESS)
480         result = NULL;
481     return result;
482 }
483
484 AP_DECLARE(apr_status_t) ap_pregsub_ex(apr_pool_t *p, char **result,
485                                        const char *input, const char *source,
486                                        apr_size_t nmatch, ap_regmatch_t pmatch[],
487                                        apr_size_t maxlen)
488 {
489     apr_status_t rc = regsub_core(p, result, NULL, input, source, nmatch,
490                                   pmatch, maxlen);
491     if (rc != APR_SUCCESS)
492         *result = NULL;
493     return rc;
494 }
495
496 /*
497  * Parse .. so we don't compromise security
498  */
499 AP_DECLARE(void) ap_getparents(char *name)
500 {
501     char *next;
502     int l, w, first_dot;
503
504     /* Four paseses, as per RFC 1808 */
505     /* a) remove ./ path segments */
506     for (next = name; *next && (*next != '.'); next++) {
507     }
508
509     l = w = first_dot = next - name;
510     while (name[l] != '\0') {
511         if (name[l] == '.' && IS_SLASH(name[l + 1])
512             && (l == 0 || IS_SLASH(name[l - 1])))
513             l += 2;
514         else
515             name[w++] = name[l++];
516     }
517
518     /* b) remove trailing . path, segment */
519     if (w == 1 && name[0] == '.')
520         w--;
521     else if (w > 1 && name[w - 1] == '.' && IS_SLASH(name[w - 2]))
522         w--;
523     name[w] = '\0';
524
525     /* c) remove all xx/../ segments. (including leading ../ and /../) */
526     l = first_dot;
527
528     while (name[l] != '\0') {
529         if (name[l] == '.' && name[l + 1] == '.' && IS_SLASH(name[l + 2])
530             && (l == 0 || IS_SLASH(name[l - 1]))) {
531             register int m = l + 3, n;
532
533             l = l - 2;
534             if (l >= 0) {
535                 while (l >= 0 && !IS_SLASH(name[l]))
536                     l--;
537                 l++;
538             }
539             else
540                 l = 0;
541             n = l;
542             while ((name[n] = name[m]))
543                 (++n, ++m);
544         }
545         else
546             ++l;
547     }
548
549     /* d) remove trailing xx/.. segment. */
550     if (l == 2 && name[0] == '.' && name[1] == '.')
551         name[0] = '\0';
552     else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.'
553              && IS_SLASH(name[l - 3])) {
554         l = l - 4;
555         if (l >= 0) {
556             while (l >= 0 && !IS_SLASH(name[l]))
557                 l--;
558             l++;
559         }
560         else
561             l = 0;
562         name[l] = '\0';
563     }
564 }
565
566 AP_DECLARE(void) ap_no2slash(char *name)
567 {
568     char *d, *s;
569
570     s = d = name;
571
572 #ifdef HAVE_UNC_PATHS
573     /* Check for UNC names.  Leave leading two slashes. */
574     if (s[0] == '/' && s[1] == '/')
575         *d++ = *s++;
576 #endif
577
578     while (*s) {
579         if ((*d++ = *s) == '/') {
580             do {
581                 ++s;
582             } while (*s == '/');
583         }
584         else {
585             ++s;
586         }
587     }
588     *d = '\0';
589 }
590
591
592 /*
593  * copy at most n leading directories of s into d
594  * d should be at least as large as s plus 1 extra byte
595  * assumes n > 0
596  * the return value is the ever useful pointer to the trailing \0 of d
597  *
598  * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments,
599  * so that if n == 0, "/" is returned in d with n == 1
600  * and s == "e:/test.html", "e:/" is returned in d
601  * *** See also directory_walk in modules/http/http_request.c
602
603  * examples:
604  *    /a/b, 0  ==> /  (true for all platforms)
605  *    /a/b, 1  ==> /
606  *    /a/b, 2  ==> /a/
607  *    /a/b, 3  ==> /a/b/
608  *    /a/b, 4  ==> /a/b/
609  *
610  *    c:/a/b 0 ==> /
611  *    c:/a/b 1 ==> c:/
612  *    c:/a/b 2 ==> c:/a/
613  *    c:/a/b 3 ==> c:/a/b
614  *    c:/a/b 4 ==> c:/a/b
615  */
616 AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
617 {
618     if (n < 1) {
619         *d = '/';
620         *++d = '\0';
621         return (d);
622     }
623
624     for (;;) {
625         if (*s == '\0' || (*s == '/' && (--n) == 0)) {
626             *d = '/';
627             break;
628         }
629         *d++ = *s++;
630     }
631     *++d = 0;
632     return (d);
633 }
634
635
636 /*
637  * return the parent directory name including trailing / of the file s
638  */
639 AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
640 {
641     const char *last_slash = ap_strrchr_c(s, '/');
642     char *d;
643     int l;
644
645     if (last_slash == NULL) {
646         return apr_pstrdup(p, "");
647     }
648     l = (last_slash - s) + 1;
649     d = apr_pstrmemdup(p, s, l);
650
651     return (d);
652 }
653
654
655 AP_DECLARE(int) ap_count_dirs(const char *path)
656 {
657     register int x, n;
658
659     for (x = 0, n = 0; path[x]; x++)
660         if (path[x] == '/')
661             n++;
662     return n;
663 }
664
665 AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
666 {
667     return ap_getword(atrans, (const char **) line, stop);
668 }
669
670 AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
671 {
672     const char *pos = *line;
673     int len;
674     char *res;
675
676     while ((*pos != stop) && *pos) {
677         ++pos;
678     }
679
680     len = pos - *line;
681     res = apr_pstrmemdup(atrans, *line, len);
682
683     if (stop) {
684         while (*pos == stop) {
685             ++pos;
686         }
687     }
688     *line = pos;
689
690     return res;
691 }
692
693 AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
694 {
695     return ap_getword_white(atrans, (const char **) line);
696 }
697
698 AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
699 {
700     const char *pos = *line;
701     int len;
702     char *res;
703
704     while (!apr_isspace(*pos) && *pos) {
705         ++pos;
706     }
707
708     len = pos - *line;
709     res = apr_pstrmemdup(atrans, *line, len);
710
711     while (apr_isspace(*pos)) {
712         ++pos;
713     }
714
715     *line = pos;
716
717     return res;
718 }
719
720 AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line,
721                                        char stop)
722 {
723     return ap_getword_nulls(atrans, (const char **) line, stop);
724 }
725
726 AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line,
727                                     char stop)
728 {
729     const char *pos = ap_strchr_c(*line, stop);
730     char *res;
731
732     if (!pos) {
733         apr_size_t len = strlen(*line);
734         res = apr_pstrmemdup(atrans, *line, len);
735         *line += len;
736         return res;
737     }
738
739     res = apr_pstrndup(atrans, *line, pos - *line);
740
741     ++pos;
742
743     *line = pos;
744
745     return res;
746 }
747
748 /* Get a word, (new) config-file style --- quoted strings and backslashes
749  * all honored
750  */
751
752 static char *substring_conf(apr_pool_t *p, const char *start, int len,
753                             char quote)
754 {
755     char *result = apr_palloc(p, len + 2);
756     char *resp = result;
757     int i;
758
759     for (i = 0; i < len; ++i) {
760         if (start[i] == '\\' && (start[i + 1] == '\\'
761                                  || (quote && start[i + 1] == quote)))
762             *resp++ = start[++i];
763         else
764             *resp++ = start[i];
765     }
766
767     *resp++ = '\0';
768 #if RESOLVE_ENV_PER_TOKEN
769     return (char *)ap_resolve_env(p,result);
770 #else
771     return result;
772 #endif
773 }
774
775 AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
776 {
777     return ap_getword_conf(p, (const char **) line);
778 }
779
780 AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
781 {
782     const char *str = *line, *strend;
783     char *res;
784     char quote;
785
786     while (*str && apr_isspace(*str))
787         ++str;
788
789     if (!*str) {
790         *line = str;
791         return "";
792     }
793
794     if ((quote = *str) == '"' || quote == '\'') {
795         strend = str + 1;
796         while (*strend && *strend != quote) {
797             if (*strend == '\\' && strend[1] &&
798                 (strend[1] == quote || strend[1] == '\\')) {
799                 strend += 2;
800             }
801             else {
802                 ++strend;
803             }
804         }
805         res = substring_conf(p, str + 1, strend - str - 1, quote);
806
807         if (*strend == quote)
808             ++strend;
809     }
810     else {
811         strend = str;
812         while (*strend && !apr_isspace(*strend))
813             ++strend;
814
815         res = substring_conf(p, str, strend - str, 0);
816     }
817
818     while (*strend && apr_isspace(*strend))
819         ++strend;
820     *line = strend;
821     return res;
822 }
823
824 AP_DECLARE(int) ap_cfg_closefile(ap_configfile_t *cfp)
825 {
826 #ifdef DEBUG
827     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(00551)
828         "Done with config file %s", cfp->name);
829 #endif
830     return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
831 }
832
833 /* we can't use apr_file_* directly because of linking issues on Windows */
834 static apr_status_t cfg_close(void *param)
835 {
836     return apr_file_close(param);
837 }
838
839 static apr_status_t cfg_getch(char *ch, void *param)
840 {
841     return apr_file_getc(ch, param);
842 }
843
844 static apr_status_t cfg_getstr(void *buf, apr_size_t bufsiz, void *param)
845 {
846     return apr_file_gets(buf, bufsiz, param);
847 }
848
849 /* Open a ap_configfile_t as FILE, return open ap_configfile_t struct pointer */
850 AP_DECLARE(apr_status_t) ap_pcfg_openfile(ap_configfile_t **ret_cfg,
851                                           apr_pool_t *p, const char *name)
852 {
853     ap_configfile_t *new_cfg;
854     apr_file_t *file = NULL;
855     apr_finfo_t finfo;
856     apr_status_t status;
857 #ifdef DEBUG
858     char buf[120];
859 #endif
860
861     if (name == NULL) {
862         ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00552)
863                "Internal error: pcfg_openfile() called with NULL filename");
864         return APR_EBADF;
865     }
866
867     status = apr_file_open(&file, name, APR_READ | APR_BUFFERED,
868                            APR_OS_DEFAULT, p);
869 #ifdef DEBUG
870     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(00553)
871                 "Opening config file %s (%s)",
872                 name, (status != APR_SUCCESS) ?
873                 apr_strerror(status, buf, sizeof(buf)) : "successful");
874 #endif
875     if (status != APR_SUCCESS)
876         return status;
877
878     status = apr_file_info_get(&finfo, APR_FINFO_TYPE, file);
879     if (status != APR_SUCCESS)
880         return status;
881
882     if (finfo.filetype != APR_REG &&
883 #if defined(WIN32) || defined(OS2) || defined(NETWARE)
884         strcasecmp(apr_filepath_name_get(name), "nul") != 0) {
885 #else
886         strcmp(name, "/dev/null") != 0) {
887 #endif /* WIN32 || OS2 */
888         ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00554)
889                      "Access to file %s denied by server: not a regular file",
890                      name);
891         apr_file_close(file);
892         return APR_EBADF;
893     }
894
895 #ifdef WIN32
896     /* Some twisted character [no pun intended] at MS decided that a
897      * zero width joiner as the lead wide character would be ideal for
898      * describing Unicode text files.  This was further convoluted to
899      * another MSism that the same character mapped into utf-8, EF BB BF
900      * would signify utf-8 text files.
901      *
902      * Since MS configuration files are all protecting utf-8 encoded
903      * Unicode path, file and resource names, we already have the correct
904      * WinNT encoding.  But at least eat the stupid three bytes up front.
905      */
906     {
907         unsigned char buf[4];
908         apr_size_t len = 3;
909         status = apr_file_read(file, buf, &len);
910         if ((status != APR_SUCCESS) || (len < 3)
911               || memcmp(buf, "\xEF\xBB\xBF", 3) != 0) {
912             apr_off_t zero = 0;
913             apr_file_seek(file, APR_SET, &zero);
914         }
915     }
916 #endif
917
918     new_cfg = apr_palloc(p, sizeof(*new_cfg));
919     new_cfg->param = file;
920     new_cfg->name = apr_pstrdup(p, name);
921     new_cfg->getch = cfg_getch;
922     new_cfg->getstr = cfg_getstr;
923     new_cfg->close = cfg_close;
924     new_cfg->line_number = 0;
925     *ret_cfg = new_cfg;
926     return APR_SUCCESS;
927 }
928
929
930 /* Allocate a ap_configfile_t handle with user defined functions and params */
931 AP_DECLARE(ap_configfile_t *) ap_pcfg_open_custom(
932             apr_pool_t *p, const char *descr, void *param,
933             apr_status_t (*getc_func) (char *ch, void *param),
934             apr_status_t (*gets_func) (void *buf, apr_size_t bufsize, void *param),
935             apr_status_t (*close_func) (void *param))
936 {
937     ap_configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
938     new_cfg->param = param;
939     new_cfg->name = descr;
940     new_cfg->getch = getc_func;
941     new_cfg->getstr = gets_func;
942     new_cfg->close = close_func;
943     new_cfg->line_number = 0;
944     return new_cfg;
945 }
946
947 /* Read one character from a configfile_t */
948 AP_DECLARE(apr_status_t) ap_cfg_getc(char *ch, ap_configfile_t *cfp)
949 {
950     apr_status_t rc = cfp->getch(ch, cfp->param);
951     if (rc == APR_SUCCESS && *ch == LF)
952         ++cfp->line_number;
953     return rc;
954 }
955
956 AP_DECLARE(const char *) ap_pcfg_strerror(apr_pool_t *p, ap_configfile_t *cfp,
957                                           apr_status_t rc)
958 {
959     char buf[MAX_STRING_LEN];
960     if (rc == APR_SUCCESS)
961         return NULL;
962     return apr_psprintf(p, "Error reading %s at line %d: %s",
963                         cfp->name, cfp->line_number,
964                         rc == APR_ENOSPC ? "Line too long"
965                                          : apr_strerror(rc, buf, sizeof(buf)));
966 }
967
968 /* Read one line from open ap_configfile_t, strip LF, increase line number */
969 /* If custom handler does not define a getstr() function, read char by char */
970 static apr_status_t ap_cfg_getline_core(char *buf, apr_size_t bufsize,
971                                         ap_configfile_t *cfp)
972 {
973     apr_status_t rc;
974     /* If a "get string" function is defined, use it */
975     if (cfp->getstr != NULL) {
976         char *cp;
977         char *cbuf = buf;
978         apr_size_t cbufsize = bufsize;
979
980         while (1) {
981             ++cfp->line_number;
982             rc = cfp->getstr(cbuf, cbufsize, cfp->param);
983             if (rc == APR_EOF) {
984                 if (cbuf != buf) {
985                     *cbuf = '\0';
986                     break;
987                 }
988                 else {
989                     return APR_EOF;
990                 }
991             }
992             if (rc != APR_SUCCESS) {
993                 return rc;
994             }
995
996             /*
997              *  check for line continuation,
998              *  i.e. match [^\\]\\[\r]\n only
999              */
1000             cp = cbuf;
1001             cp += strlen(cp);
1002             if (cp > cbuf && cp[-1] == LF) {
1003                 cp--;
1004                 if (cp > cbuf && cp[-1] == CR)
1005                     cp--;
1006                 if (cp > cbuf && cp[-1] == '\\') {
1007                     cp--;
1008                     /*
1009                      * line continuation requested -
1010                      * then remove backslash and continue
1011                      */
1012                     cbufsize -= (cp-cbuf);
1013                     cbuf = cp;
1014                     continue;
1015                 }
1016             }
1017             else if (cp - buf >= bufsize - 1) {
1018                 return APR_ENOSPC;
1019             }
1020             break;
1021         }
1022     } else {
1023         /* No "get string" function defined; read character by character */
1024         apr_size_t i = 0;
1025
1026         if (bufsize < 2) {
1027             /* too small, assume caller is crazy */
1028             return APR_EINVAL;
1029         }
1030         buf[0] = '\0';
1031
1032         while (1) {
1033             char c;
1034             rc = cfp->getch(&c, cfp->param);
1035             if (rc == APR_EOF) {
1036                 if (i > 0)
1037                     break;
1038                 else
1039                     return APR_EOF;
1040             }
1041             if (rc != APR_SUCCESS)
1042                 return rc;
1043             if (c == LF) {
1044                 ++cfp->line_number;
1045                 /* check for line continuation */
1046                 if (i > 0 && buf[i-1] == '\\') {
1047                     i--;
1048                     continue;
1049                 }
1050                 else {
1051                     break;
1052                 }
1053             }
1054             else if (i >= bufsize - 2) {
1055                 return APR_ENOSPC;
1056             }
1057             buf[i] = c;
1058             ++i;
1059         }
1060         buf[i] = '\0';
1061     }
1062     return APR_SUCCESS;
1063 }
1064
1065 static int cfg_trim_line(char *buf)
1066 {
1067     char *start, *end;
1068     /*
1069      * Leading and trailing white space is eliminated completely
1070      */
1071     start = buf;
1072     while (apr_isspace(*start))
1073         ++start;
1074     /* blast trailing whitespace */
1075     end = &start[strlen(start)];
1076     while (--end >= start && apr_isspace(*end))
1077         *end = '\0';
1078     /* Zap leading whitespace by shifting */
1079     if (start != buf)
1080         memmove(buf, start, end - start + 2);
1081 #ifdef DEBUG_CFG_LINES
1082     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL, APLOGNO(00555) "Read config: '%s'", buf);
1083 #endif
1084     return end - start + 1;
1085 }
1086
1087 /* Read one line from open ap_configfile_t, strip LF, increase line number */
1088 /* If custom handler does not define a getstr() function, read char by char */
1089 AP_DECLARE(apr_status_t) ap_cfg_getline(char *buf, apr_size_t bufsize,
1090                                         ap_configfile_t *cfp)
1091 {
1092     apr_status_t rc = ap_cfg_getline_core(buf, bufsize, cfp);
1093     if (rc == APR_SUCCESS)
1094         cfg_trim_line(buf);
1095     return rc;
1096 }
1097
1098 AP_DECLARE(apr_status_t) ap_varbuf_cfg_getline(struct ap_varbuf *vb,
1099                                                ap_configfile_t *cfp,
1100                                                apr_size_t max_len)
1101 {
1102     apr_status_t rc;
1103     apr_size_t new_len;
1104     vb->strlen = 0;
1105     *vb->buf = '\0';
1106
1107     if (vb->strlen == AP_VARBUF_UNKNOWN)
1108         vb->strlen = strlen(vb->buf);
1109     if (vb->avail - vb->strlen < 3) {
1110         new_len = vb->avail * 2;
1111         if (new_len > max_len)
1112             new_len = max_len;
1113         else if (new_len < 3)
1114             new_len = 3;
1115         ap_varbuf_grow(vb, new_len);
1116     }
1117
1118     for (;;) {
1119         rc = ap_cfg_getline_core(vb->buf + vb->strlen, vb->avail - vb->strlen, cfp);
1120         if (rc == APR_ENOSPC || rc == APR_SUCCESS)
1121             vb->strlen += strlen(vb->buf + vb->strlen);
1122         if (rc != APR_ENOSPC)
1123             break;
1124         if (vb->avail >= max_len)
1125             return APR_ENOSPC;
1126         new_len = vb->avail * 2;
1127         if (new_len > max_len)
1128             new_len = max_len;
1129         ap_varbuf_grow(vb, new_len);
1130         --cfp->line_number;
1131     }
1132     if (vb->strlen > max_len)
1133         return APR_ENOSPC;
1134     if (rc == APR_SUCCESS)
1135         vb->strlen = cfg_trim_line(vb->buf);
1136     return rc;
1137 }
1138
1139 /* Size an HTTP header field list item, as separated by a comma.
1140  * The return value is a pointer to the beginning of the non-empty list item
1141  * within the original string (or NULL if there is none) and the address
1142  * of field is shifted to the next non-comma, non-whitespace character.
1143  * len is the length of the item excluding any beginning whitespace.
1144  */
1145 AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1146 {
1147     const unsigned char *ptr = (const unsigned char *)*field;
1148     const unsigned char *token;
1149     int in_qpair, in_qstr, in_com;
1150
1151     /* Find first non-comma, non-whitespace byte */
1152
1153     while (*ptr == ',' || apr_isspace(*ptr))
1154         ++ptr;
1155
1156     token = ptr;
1157
1158     /* Find the end of this item, skipping over dead bits */
1159
1160     for (in_qpair = in_qstr = in_com = 0;
1161          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1162          ++ptr) {
1163
1164         if (in_qpair) {
1165             in_qpair = 0;
1166         }
1167         else {
1168             switch (*ptr) {
1169                 case '\\': in_qpair = 1;      /* quoted-pair         */
1170                            break;
1171                 case '"' : if (!in_com)       /* quoted string delim */
1172                                in_qstr = !in_qstr;
1173                            break;
1174                 case '(' : if (!in_qstr)      /* comment (may nest)  */
1175                                ++in_com;
1176                            break;
1177                 case ')' : if (in_com)        /* end comment         */
1178                                --in_com;
1179                            break;
1180                 default  : break;
1181             }
1182         }
1183     }
1184
1185     if ((*len = (ptr - token)) == 0) {
1186         *field = (const char *)ptr;
1187         return NULL;
1188     }
1189
1190     /* Advance field pointer to the next non-comma, non-white byte */
1191
1192     while (*ptr == ',' || apr_isspace(*ptr))
1193         ++ptr;
1194
1195     *field = (const char *)ptr;
1196     return (const char *)token;
1197 }
1198
1199 /* Retrieve an HTTP header field list item, as separated by a comma,
1200  * while stripping insignificant whitespace and lowercasing anything not in
1201  * a quoted string or comment.  The return value is a new string containing
1202  * the converted list item (or NULL if none) and the address pointed to by
1203  * field is shifted to the next non-comma, non-whitespace.
1204  */
1205 AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1206 {
1207     const char *tok_start;
1208     const unsigned char *ptr;
1209     unsigned char *pos;
1210     char *token;
1211     int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1212
1213     /* Find the beginning and maximum length of the list item so that
1214      * we can allocate a buffer for the new string and reset the field.
1215      */
1216     if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1217         return NULL;
1218     }
1219     token = apr_palloc(p, tok_len + 1);
1220
1221     /* Scan the token again, but this time copy only the good bytes.
1222      * We skip extra whitespace and any whitespace around a '=', '/',
1223      * or ';' and lowercase normal characters not within a comment,
1224      * quoted-string or quoted-pair.
1225      */
1226     for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1227          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1228          ++ptr) {
1229
1230         if (in_qpair) {
1231             in_qpair = 0;
1232             *pos++ = *ptr;
1233         }
1234         else {
1235             switch (*ptr) {
1236                 case '\\': in_qpair = 1;
1237                            if (addspace == 1)
1238                                *pos++ = ' ';
1239                            *pos++ = *ptr;
1240                            addspace = 0;
1241                            break;
1242                 case '"' : if (!in_com)
1243                                in_qstr = !in_qstr;
1244                            if (addspace == 1)
1245                                *pos++ = ' ';
1246                            *pos++ = *ptr;
1247                            addspace = 0;
1248                            break;
1249                 case '(' : if (!in_qstr)
1250                                ++in_com;
1251                            if (addspace == 1)
1252                                *pos++ = ' ';
1253                            *pos++ = *ptr;
1254                            addspace = 0;
1255                            break;
1256                 case ')' : if (in_com)
1257                                --in_com;
1258                            *pos++ = *ptr;
1259                            addspace = 0;
1260                            break;
1261                 case ' ' :
1262                 case '\t': if (addspace)
1263                                break;
1264                            if (in_com || in_qstr)
1265                                *pos++ = *ptr;
1266                            else
1267                                addspace = 1;
1268                            break;
1269                 case '=' :
1270                 case '/' :
1271                 case ';' : if (!(in_com || in_qstr))
1272                                addspace = -1;
1273                            *pos++ = *ptr;
1274                            break;
1275                 default  : if (addspace == 1)
1276                                *pos++ = ' ';
1277                            *pos++ = (in_com || in_qstr) ? *ptr
1278                                                         : apr_tolower(*ptr);
1279                            addspace = 0;
1280                            break;
1281             }
1282         }
1283     }
1284     *pos = '\0';
1285
1286     return token;
1287 }
1288
1289 /* Find an item in canonical form (lowercase, no extra spaces) within
1290  * an HTTP field value list.  Returns 1 if found, 0 if not found.
1291  * This would be much more efficient if we stored header fields as
1292  * an array of list items as they are received instead of a plain string.
1293  */
1294 AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line,
1295                                   const char *tok)
1296 {
1297     const unsigned char *pos;
1298     const unsigned char *ptr = (const unsigned char *)line;
1299     int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1300
1301     if (!line || !tok)
1302         return 0;
1303
1304     do {  /* loop for each item in line's list */
1305
1306         /* Find first non-comma, non-whitespace byte */
1307
1308         while (*ptr == ',' || apr_isspace(*ptr))
1309             ++ptr;
1310
1311         if (*ptr)
1312             good = 1;  /* until proven otherwise for this item */
1313         else
1314             break;     /* no items left and nothing good found */
1315
1316         /* We skip extra whitespace and any whitespace around a '=', '/',
1317          * or ';' and lowercase normal characters not within a comment,
1318          * quoted-string or quoted-pair.
1319          */
1320         for (pos = (const unsigned char *)tok;
1321              *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1322              ++ptr) {
1323
1324             if (in_qpair) {
1325                 in_qpair = 0;
1326                 if (good)
1327                     good = (*pos++ == *ptr);
1328             }
1329             else {
1330                 switch (*ptr) {
1331                     case '\\': in_qpair = 1;
1332                                if (addspace == 1)
1333                                    good = good && (*pos++ == ' ');
1334                                good = good && (*pos++ == *ptr);
1335                                addspace = 0;
1336                                break;
1337                     case '"' : if (!in_com)
1338                                    in_qstr = !in_qstr;
1339                                if (addspace == 1)
1340                                    good = good && (*pos++ == ' ');
1341                                good = good && (*pos++ == *ptr);
1342                                addspace = 0;
1343                                break;
1344                     case '(' : if (!in_qstr)
1345                                    ++in_com;
1346                                if (addspace == 1)
1347                                    good = good && (*pos++ == ' ');
1348                                good = good && (*pos++ == *ptr);
1349                                addspace = 0;
1350                                break;
1351                     case ')' : if (in_com)
1352                                    --in_com;
1353                                good = good && (*pos++ == *ptr);
1354                                addspace = 0;
1355                                break;
1356                     case ' ' :
1357                     case '\t': if (addspace || !good)
1358                                    break;
1359                                if (in_com || in_qstr)
1360                                    good = (*pos++ == *ptr);
1361                                else
1362                                    addspace = 1;
1363                                break;
1364                     case '=' :
1365                     case '/' :
1366                     case ';' : if (!(in_com || in_qstr))
1367                                    addspace = -1;
1368                                good = good && (*pos++ == *ptr);
1369                                break;
1370                     default  : if (!good)
1371                                    break;
1372                                if (addspace == 1)
1373                                    good = (*pos++ == ' ');
1374                                if (in_com || in_qstr)
1375                                    good = good && (*pos++ == *ptr);
1376                                else
1377                                    good = good && (*pos++ == apr_tolower(*ptr));
1378                                addspace = 0;
1379                                break;
1380                 }
1381             }
1382         }
1383         if (good && *pos)
1384             good = 0;          /* not good if only a prefix was matched */
1385
1386     } while (*ptr && !good);
1387
1388     return good;
1389 }
1390
1391
1392 /* Retrieve a token, spacing over it and returning a pointer to
1393  * the first non-white byte afterwards.  Note that these tokens
1394  * are delimited by semis and commas; and can also be delimited
1395  * by whitespace at the caller's option.
1396  */
1397
1398 AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line,
1399                                 int accept_white)
1400 {
1401     const char *ptr = *accept_line;
1402     const char *tok_start;
1403     char *token;
1404     int tok_len;
1405
1406     /* Find first non-white byte */
1407
1408     while (*ptr && apr_isspace(*ptr))
1409         ++ptr;
1410
1411     tok_start = ptr;
1412
1413     /* find token end, skipping over quoted strings.
1414      * (comments are already gone).
1415      */
1416
1417     while (*ptr && (accept_white || !apr_isspace(*ptr))
1418            && *ptr != ';' && *ptr != ',') {
1419         if (*ptr++ == '"')
1420             while (*ptr)
1421                 if (*ptr++ == '"')
1422                     break;
1423     }
1424
1425     tok_len = ptr - tok_start;
1426     token = apr_pstrndup(p, tok_start, tok_len);
1427
1428     /* Advance accept_line pointer to the next non-white byte */
1429
1430     while (*ptr && apr_isspace(*ptr))
1431         ++ptr;
1432
1433     *accept_line = ptr;
1434     return token;
1435 }
1436
1437
1438 /* find http tokens, see the definition of token from RFC2068 */
1439 AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1440 {
1441     const unsigned char *start_token;
1442     const unsigned char *s;
1443
1444     if (!line)
1445         return 0;
1446
1447     s = (const unsigned char *)line;
1448     for (;;) {
1449         /* find start of token, skip all stop characters, note NUL
1450          * isn't a token stop, so we don't need to test for it
1451          */
1452         while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1453             ++s;
1454         }
1455         if (!*s) {
1456             return 0;
1457         }
1458         start_token = s;
1459         /* find end of the token */
1460         while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1461             ++s;
1462         }
1463         if (!strncasecmp((const char *)start_token, (const char *)tok,
1464                          s - start_token)) {
1465             return 1;
1466         }
1467         if (!*s) {
1468             return 0;
1469         }
1470     }
1471 }
1472
1473
1474 AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line,
1475                                    const char *tok)
1476 {
1477     int llen, tlen, lidx;
1478
1479     if (!line)
1480         return 0;
1481
1482     llen = strlen(line);
1483     tlen = strlen(tok);
1484     lidx = llen - tlen;
1485
1486     if (lidx < 0 ||
1487         (lidx > 0 && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1488         return 0;
1489
1490     return (strncasecmp(&line[lidx], tok, tlen) == 0);
1491 }
1492
1493 AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1494 {
1495     char *cmd;
1496     unsigned char *d;
1497     const unsigned char *s;
1498
1499     cmd = apr_palloc(p, 2 * strlen(str) + 1);        /* Be safe */
1500     d = (unsigned char *)cmd;
1501     s = (const unsigned char *)str;
1502     for (; *s; ++s) {
1503
1504 #if defined(OS2) || defined(WIN32)
1505         /*
1506          * Newlines to Win32/OS2 CreateProcess() are ill advised.
1507          * Convert them to spaces since they are effectively white
1508          * space to most applications
1509          */
1510         if (*s == '\r' || *s == '\n') {
1511              *d++ = ' ';
1512              continue;
1513          }
1514 #endif
1515
1516         if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1517             *d++ = '\\';
1518         }
1519         *d++ = *s;
1520     }
1521     *d = '\0';
1522
1523     return cmd;
1524 }
1525
1526 static char x2c(const char *what)
1527 {
1528     register char digit;
1529
1530 #if !APR_CHARSET_EBCDIC
1531     digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10
1532              : (what[0] - '0'));
1533     digit *= 16;
1534     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10
1535               : (what[1] - '0'));
1536 #else /*APR_CHARSET_EBCDIC*/
1537     char xstr[5];
1538     xstr[0]='0';
1539     xstr[1]='x';
1540     xstr[2]=what[0];
1541     xstr[3]=what[1];
1542     xstr[4]='\0';
1543     digit = apr_xlate_conv_byte(ap_hdrs_from_ascii,
1544                                 0xFF & strtol(xstr, NULL, 16));
1545 #endif /*APR_CHARSET_EBCDIC*/
1546     return (digit);
1547 }
1548
1549 /*
1550  * Unescapes a URL, leaving reserved characters intact.
1551  * Returns 0 on success, non-zero on error
1552  * Failure is due to
1553  *   bad % escape       returns HTTP_BAD_REQUEST
1554  *
1555  *   decoding %00 or a forbidden character returns HTTP_NOT_FOUND
1556  */
1557
1558 static int unescape_url(char *url, const char *forbid, const char *reserved)
1559 {
1560     register int badesc, badpath;
1561     char *x, *y;
1562
1563     badesc = 0;
1564     badpath = 0;
1565     /* Initial scan for first '%'. Don't bother writing values before
1566      * seeing a '%' */
1567     y = strchr(url, '%');
1568     if (y == NULL) {
1569         return OK;
1570     }
1571     for (x = y; *y; ++x, ++y) {
1572         if (*y != '%') {
1573             *x = *y;
1574         }
1575         else {
1576             if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1577                 badesc = 1;
1578                 *x = '%';
1579             }
1580             else {
1581                 char decoded;
1582                 decoded = x2c(y + 1);
1583                 if ((decoded == '\0')
1584                     || (forbid && ap_strchr_c(forbid, decoded))) {
1585                     badpath = 1;
1586                     *x = decoded;
1587                     y += 2;
1588                 }
1589                 else if (reserved && ap_strchr_c(reserved, decoded)) {
1590                     *x++ = *y++;
1591                     *x++ = *y++;
1592                     *x = *y;
1593                 }
1594                 else {
1595                     *x = decoded;
1596                     y += 2;
1597                 }
1598             }
1599         }
1600     }
1601     *x = '\0';
1602     if (badesc) {
1603         return HTTP_BAD_REQUEST;
1604     }
1605     else if (badpath) {
1606         return HTTP_NOT_FOUND;
1607     }
1608     else {
1609         return OK;
1610     }
1611 }
1612 AP_DECLARE(int) ap_unescape_url(char *url)
1613 {
1614     /* Traditional */
1615     return unescape_url(url, SLASHES, NULL);
1616 }
1617 AP_DECLARE(int) ap_unescape_url_keep2f(char *url, int decode_slashes)
1618 {
1619     /* AllowEncodedSlashes (corrected) */
1620     if (decode_slashes) {
1621         /* no chars reserved */
1622         return unescape_url(url, NULL, NULL);
1623     } else {
1624         /* reserve (do not decode) encoded slashes */
1625         return unescape_url(url, NULL, SLASHES);
1626     }
1627 }
1628 #ifdef NEW_APIS
1629 /* IFDEF these out until they've been thought through.
1630  * Just a germ of an API extension for now
1631  */
1632 AP_DECLARE(int) ap_unescape_url_proxy(char *url)
1633 {
1634     /* leave RFC1738 reserved characters intact, * so proxied URLs
1635      * don't get mangled.  Where does that leave encoded '&' ?
1636      */
1637     return unescape_url(url, NULL, "/;?");
1638 }
1639 AP_DECLARE(int) ap_unescape_url_reserved(char *url, const char *reserved)
1640 {
1641     return unescape_url(url, NULL, reserved);
1642 }
1643 #endif
1644
1645 AP_DECLARE(int) ap_unescape_urlencoded(char *query)
1646 {
1647     char *slider;
1648
1649     /* replace plus with a space */
1650     if (query) {
1651         for (slider = query; *slider; slider++) {
1652             if (*slider == '+') {
1653                 *slider = ' ';
1654             }
1655         }
1656     }
1657
1658     /* unescape everything else */
1659     return unescape_url(query, NULL, NULL);
1660 }
1661
1662 AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
1663                                        apr_port_t port, const request_rec *r)
1664 {
1665     if (ap_is_default_port(port, r)) {
1666         return apr_pstrdup(p, hostname);
1667     }
1668     else {
1669         return apr_psprintf(p, "%s:%u", hostname, port);
1670     }
1671 }
1672
1673 AP_DECLARE(int) ap_unescape_all(char *url)
1674 {
1675     return unescape_url(url, NULL, NULL);
1676 }
1677
1678 /* c2x takes an unsigned, and expects the caller has guaranteed that
1679  * 0 <= what < 256... which usually means that you have to cast to
1680  * unsigned char first, because (unsigned)(char)(x) first goes through
1681  * signed extension to an int before the unsigned cast.
1682  *
1683  * The reason for this assumption is to assist gcc code generation --
1684  * the unsigned char -> unsigned extension is already done earlier in
1685  * both uses of this code, so there's no need to waste time doing it
1686  * again.
1687  */
1688 static const char c2x_table[] = "0123456789abcdef";
1689
1690 static APR_INLINE unsigned char *c2x(unsigned what, unsigned char prefix,
1691                                      unsigned char *where)
1692 {
1693 #if APR_CHARSET_EBCDIC
1694     what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
1695 #endif /*APR_CHARSET_EBCDIC*/
1696     *where++ = prefix;
1697     *where++ = c2x_table[what >> 4];
1698     *where++ = c2x_table[what & 0xf];
1699     return where;
1700 }
1701
1702 /*
1703  * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1704  * routine is (should be) OS independent.
1705  *
1706  * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1707  * cases if a ':' occurs before the first '/' in the URL, the URL should be
1708  * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1709  * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1710  * efficiency reasons, we don't use escape_path_segment(), which is provided for
1711  * reference. Again, RFC 1808 is where this stuff is defined.
1712  *
1713  * If partial is set, os_escape_path() assumes that the path will be appended to
1714  * something with a '/' in it (and thus does not prefix "./").
1715  */
1716
1717 AP_DECLARE(char *) ap_escape_path_segment_buffer(char *copy, const char *segment)
1718 {
1719     const unsigned char *s = (const unsigned char *)segment;
1720     unsigned char *d = (unsigned char *)copy;
1721     unsigned c;
1722
1723     while ((c = *s)) {
1724         if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1725             d = c2x(c, '%', d);
1726         }
1727         else {
1728             *d++ = c;
1729         }
1730         ++s;
1731     }
1732     *d = '\0';
1733     return copy;
1734 }
1735
1736 AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
1737 {
1738     return ap_escape_path_segment_buffer(apr_palloc(p, 3 * strlen(segment) + 1), segment);
1739 }
1740
1741 AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
1742 {
1743     char *copy = apr_palloc(p, 3 * strlen(path) + 3);
1744     const unsigned char *s = (const unsigned char *)path;
1745     unsigned char *d = (unsigned char *)copy;
1746     unsigned c;
1747
1748     if (!partial) {
1749         const char *colon = ap_strchr_c(path, ':');
1750         const char *slash = ap_strchr_c(path, '/');
1751
1752         if (colon && (!slash || colon < slash)) {
1753             *d++ = '.';
1754             *d++ = '/';
1755         }
1756     }
1757     while ((c = *s)) {
1758         if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1759             d = c2x(c, '%', d);
1760         }
1761         else {
1762             *d++ = c;
1763         }
1764         ++s;
1765     }
1766     *d = '\0';
1767     return copy;
1768 }
1769
1770 AP_DECLARE(char *) ap_escape_urlencoded_buffer(char *copy, const char *buffer)
1771 {
1772     const unsigned char *s = (const unsigned char *)buffer;
1773     unsigned char *d = (unsigned char *)copy;
1774     unsigned c;
1775
1776     while ((c = *s)) {
1777         if (TEST_CHAR(c, T_ESCAPE_URLENCODED)) {
1778             d = c2x(c, '%', d);
1779         }
1780         else if (c == ' ') {
1781             *d++ = '+';
1782         }
1783         else {
1784             *d++ = c;
1785         }
1786         ++s;
1787     }
1788     *d = '\0';
1789     return copy;
1790 }
1791
1792 AP_DECLARE(char *) ap_escape_urlencoded(apr_pool_t *p, const char *buffer)
1793 {
1794     return ap_escape_urlencoded_buffer(apr_palloc(p, 3 * strlen(buffer) + 1), buffer);
1795 }
1796
1797 /* ap_escape_uri is now a macro for os_escape_path */
1798
1799 AP_DECLARE(char *) ap_escape_html2(apr_pool_t *p, const char *s, int toasc)
1800 {
1801     int i, j;
1802     char *x;
1803
1804     /* first, count the number of extra characters */
1805     for (i = 0, j = 0; s[i] != '\0'; i++)
1806         if (s[i] == '<' || s[i] == '>')
1807             j += 3;
1808         else if (s[i] == '&')
1809             j += 4;
1810         else if (s[i] == '"')
1811             j += 5;
1812         else if (toasc && !apr_isascii(s[i]))
1813             j += 5;
1814
1815     if (j == 0)
1816         return apr_pstrmemdup(p, s, i);
1817
1818     x = apr_palloc(p, i + j + 1);
1819     for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1820         if (s[i] == '<') {
1821             memcpy(&x[j], "&lt;", 4);
1822             j += 3;
1823         }
1824         else if (s[i] == '>') {
1825             memcpy(&x[j], "&gt;", 4);
1826             j += 3;
1827         }
1828         else if (s[i] == '&') {
1829             memcpy(&x[j], "&amp;", 5);
1830             j += 4;
1831         }
1832         else if (s[i] == '"') {
1833             memcpy(&x[j], "&quot;", 6);
1834             j += 5;
1835         }
1836         else if (toasc && !apr_isascii(s[i])) {
1837             char *esc = apr_psprintf(p, "&#%3.3d;", (unsigned char)s[i]);
1838             memcpy(&x[j], esc, 6);
1839             j += 5;
1840         }
1841         else
1842             x[j] = s[i];
1843
1844     x[j] = '\0';
1845     return x;
1846 }
1847 AP_DECLARE(char *) ap_escape_logitem(apr_pool_t *p, const char *str)
1848 {
1849     char *ret;
1850     unsigned char *d;
1851     const unsigned char *s;
1852
1853     if (!str) {
1854         return NULL;
1855     }
1856
1857     ret = apr_palloc(p, 4 * strlen(str) + 1); /* Be safe */
1858     d = (unsigned char *)ret;
1859     s = (const unsigned char *)str;
1860     for (; *s; ++s) {
1861
1862         if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
1863             *d++ = '\\';
1864             switch(*s) {
1865             case '\b':
1866                 *d++ = 'b';
1867                 break;
1868             case '\n':
1869                 *d++ = 'n';
1870                 break;
1871             case '\r':
1872                 *d++ = 'r';
1873                 break;
1874             case '\t':
1875                 *d++ = 't';
1876                 break;
1877             case '\v':
1878                 *d++ = 'v';
1879                 break;
1880             case '\\':
1881             case '"':
1882                 *d++ = *s;
1883                 break;
1884             default:
1885                 c2x(*s, 'x', d);
1886                 d += 3;
1887             }
1888         }
1889         else {
1890             *d++ = *s;
1891         }
1892     }
1893     *d = '\0';
1894
1895     return ret;
1896 }
1897
1898 AP_DECLARE(apr_size_t) ap_escape_errorlog_item(char *dest, const char *source,
1899                                                apr_size_t buflen)
1900 {
1901     unsigned char *d, *ep;
1902     const unsigned char *s;
1903
1904     if (!source || !buflen) { /* be safe */
1905         return 0;
1906     }
1907
1908     d = (unsigned char *)dest;
1909     s = (const unsigned char *)source;
1910     ep = d + buflen - 1;
1911
1912     for (; d < ep && *s; ++s) {
1913
1914         if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
1915             *d++ = '\\';
1916             if (d >= ep) {
1917                 --d;
1918                 break;
1919             }
1920
1921             switch(*s) {
1922             case '\b':
1923                 *d++ = 'b';
1924                 break;
1925             case '\n':
1926                 *d++ = 'n';
1927                 break;
1928             case '\r':
1929                 *d++ = 'r';
1930                 break;
1931             case '\t':
1932                 *d++ = 't';
1933                 break;
1934             case '\v':
1935                 *d++ = 'v';
1936                 break;
1937             case '\\':
1938                 *d++ = *s;
1939                 break;
1940             case '"': /* no need for this in error log */
1941                 d[-1] = *s;
1942                 break;
1943             default:
1944                 if (d >= ep - 2) {
1945                     ep = --d; /* break the for loop as well */
1946                     break;
1947                 }
1948                 c2x(*s, 'x', d);
1949                 d += 3;
1950             }
1951         }
1952         else {
1953             *d++ = *s;
1954         }
1955     }
1956     *d = '\0';
1957
1958     return (d - (unsigned char *)dest);
1959 }
1960
1961 AP_DECLARE(int) ap_is_directory(apr_pool_t *p, const char *path)
1962 {
1963     apr_finfo_t finfo;
1964
1965     if (apr_stat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
1966         return 0;                /* in error condition, just return no */
1967
1968     return (finfo.filetype == APR_DIR);
1969 }
1970
1971 AP_DECLARE(int) ap_is_rdirectory(apr_pool_t *p, const char *path)
1972 {
1973     apr_finfo_t finfo;
1974
1975     if (apr_stat(&finfo, path, APR_FINFO_LINK | APR_FINFO_TYPE, p) != APR_SUCCESS)
1976         return 0;                /* in error condition, just return no */
1977
1978     return (finfo.filetype == APR_DIR);
1979 }
1980
1981 AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
1982                                   const char *src2)
1983 {
1984     apr_size_t len1, len2;
1985     char *path;
1986
1987     len1 = strlen(src1);
1988     len2 = strlen(src2);
1989      /* allocate +3 for '/' delimiter, trailing NULL and overallocate
1990       * one extra byte to allow the caller to add a trailing '/'
1991       */
1992     path = (char *)apr_palloc(a, len1 + len2 + 3);
1993     if (len1 == 0) {
1994         *path = '/';
1995         memcpy(path + 1, src2, len2 + 1);
1996     }
1997     else {
1998         char *next;
1999         memcpy(path, src1, len1);
2000         next = path + len1;
2001         if (next[-1] != '/') {
2002             *next++ = '/';
2003         }
2004         memcpy(next, src2, len2 + 1);
2005     }
2006     return path;
2007 }
2008
2009 /*
2010  * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
2011  */
2012 AP_DECLARE(int) ap_is_url(const char *u)
2013 {
2014     register int x;
2015
2016     for (x = 0; u[x] != ':'; x++) {
2017         if ((!u[x]) ||
2018             ((!apr_isalpha(u[x])) && (!apr_isdigit(u[x])) &&
2019              (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
2020             return 0;
2021         }
2022     }
2023
2024     return (x ? 1 : 0);                /* If the first character is ':', it's broken, too */
2025 }
2026
2027 AP_DECLARE(int) ap_ind(const char *s, char c)
2028 {
2029     const char *p = ap_strchr_c(s, c);
2030
2031     if (p == NULL)
2032         return -1;
2033     return p - s;
2034 }
2035
2036 AP_DECLARE(int) ap_rind(const char *s, char c)
2037 {
2038     const char *p = ap_strrchr_c(s, c);
2039
2040     if (p == NULL)
2041         return -1;
2042     return p - s;
2043 }
2044
2045 AP_DECLARE(void) ap_str_tolower(char *str)
2046 {
2047     while (*str) {
2048         *str = apr_tolower(*str);
2049         ++str;
2050     }
2051 }
2052
2053 AP_DECLARE(void) ap_str_toupper(char *str)
2054 {
2055     while (*str) {
2056         *str = apr_toupper(*str);
2057         ++str;
2058     }
2059 }
2060
2061 /*
2062  * We must return a FQDN
2063  */
2064 char *ap_get_local_host(apr_pool_t *a)
2065 {
2066 #ifndef MAXHOSTNAMELEN
2067 #define MAXHOSTNAMELEN 256
2068 #endif
2069     char str[MAXHOSTNAMELEN + 1];
2070     char *server_hostname = NULL;
2071     apr_sockaddr_t *sockaddr;
2072     char *hostname;
2073
2074     if (apr_gethostname(str, sizeof(str) - 1, a) != APR_SUCCESS) {
2075         ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a, APLOGNO(00556)
2076                      "%s: apr_gethostname() failed to determine ServerName",
2077                      ap_server_argv0);
2078     } else {
2079         str[sizeof(str) - 1] = '\0';
2080         if (apr_sockaddr_info_get(&sockaddr, str, APR_UNSPEC, 0, 0, a) == APR_SUCCESS) {
2081             if ( (apr_getnameinfo(&hostname, sockaddr, 0) == APR_SUCCESS) &&
2082                 (ap_strchr_c(hostname, '.')) ) {
2083                 server_hostname = apr_pstrdup(a, hostname);
2084                 return server_hostname;
2085             } else if (ap_strchr_c(str, '.')) {
2086                 server_hostname = apr_pstrdup(a, str);
2087             } else {
2088                 apr_sockaddr_ip_get(&hostname, sockaddr);
2089                 server_hostname = apr_pstrdup(a, hostname);
2090             }
2091         } else {
2092             ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a, APLOGNO(00557)
2093                          "%s: apr_sockaddr_info_get() failed for %s",
2094                          ap_server_argv0, str);
2095         }
2096     }
2097
2098     if (!server_hostname)
2099         server_hostname = apr_pstrdup(a, "127.0.0.1");
2100
2101     ap_log_perror(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0, a, APLOGNO(00558)
2102                  "%s: Could not reliably determine the server's fully qualified "
2103                  "domain name, using %s. Set the 'ServerName' directive globally "
2104                  "to suppress this message",
2105                  ap_server_argv0, server_hostname);
2106
2107     return server_hostname;
2108 }
2109
2110 /* simple 'pool' alloc()ing glue to apr_base64.c
2111  */
2112 AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
2113 {
2114     char *decoded;
2115     int l;
2116
2117     decoded = (char *) apr_palloc(p, 1 + apr_base64_decode_len(bufcoded));
2118     l = apr_base64_decode(decoded, bufcoded);
2119     decoded[l] = '\0'; /* make binary sequence into string */
2120
2121     return decoded;
2122 }
2123
2124 AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string)
2125 {
2126     char *encoded;
2127     int l = strlen(string);
2128
2129     encoded = (char *) apr_palloc(p, 1 + apr_base64_encode_len(l));
2130     l = apr_base64_encode(encoded, string, l);
2131     encoded[l] = '\0'; /* make binary sequence into string */
2132
2133     return encoded;
2134 }
2135
2136 /* we want to downcase the type/subtype for comparison purposes
2137  * but nothing else because ;parameter=foo values are case sensitive.
2138  * XXX: in truth we want to downcase parameter names... but really,
2139  * apache has never handled parameters and such correctly.  You
2140  * also need to compress spaces and such to be able to compare
2141  * properly. -djg
2142  */
2143 AP_DECLARE(void) ap_content_type_tolower(char *str)
2144 {
2145     char *semi;
2146
2147     semi = strchr(str, ';');
2148     if (semi) {
2149         *semi = '\0';
2150     }
2151
2152     ap_str_tolower(str);
2153
2154     if (semi) {
2155         *semi = ';';
2156     }
2157 }
2158
2159 /*
2160  * Given a string, replace any bare " with \" .
2161  */
2162 AP_DECLARE(char *) ap_escape_quotes(apr_pool_t *p, const char *instring)
2163 {
2164     int newlen = 0;
2165     const char *inchr = instring;
2166     char *outchr, *outstring;
2167
2168     /*
2169      * Look through the input string, jogging the length of the output
2170      * string up by an extra byte each time we find an unescaped ".
2171      */
2172     while (*inchr != '\0') {
2173         newlen++;
2174         if (*inchr == '"') {
2175             newlen++;
2176         }
2177         /*
2178          * If we find a slosh, and it's not the last byte in the string,
2179          * it's escaping something - advance past both bytes.
2180          */
2181         if ((*inchr == '\\') && (inchr[1] != '\0')) {
2182             inchr++;
2183             newlen++;
2184         }
2185         inchr++;
2186     }
2187     outstring = apr_palloc(p, newlen + 1);
2188     inchr = instring;
2189     outchr = outstring;
2190     /*
2191      * Now copy the input string to the output string, inserting a slosh
2192      * in front of every " that doesn't already have one.
2193      */
2194     while (*inchr != '\0') {
2195         if ((*inchr == '\\') && (inchr[1] != '\0')) {
2196             *outchr++ = *inchr++;
2197             *outchr++ = *inchr++;
2198         }
2199         if (*inchr == '"') {
2200             *outchr++ = '\\';
2201         }
2202         if (*inchr != '\0') {
2203             *outchr++ = *inchr++;
2204         }
2205     }
2206     *outchr = '\0';
2207     return outstring;
2208 }
2209
2210 /*
2211  * Given a string, append the PID deliminated by delim.
2212  * Usually used to create a pid-appended filepath name
2213  * (eg: /a/b/foo -> /a/b/foo.6726). A function, and not
2214  * a macro, to avoid unistd.h dependency
2215  */
2216 AP_DECLARE(char *) ap_append_pid(apr_pool_t *p, const char *string,
2217                                     const char *delim)
2218 {
2219     return apr_psprintf(p, "%s%s%" APR_PID_T_FMT, string,
2220                         delim, getpid());
2221
2222 }
2223
2224 /**
2225  * Parse a given timeout parameter string into an apr_interval_time_t value.
2226  * The unit of the time interval is given as postfix string to the numeric
2227  * string. Currently the following units are understood:
2228  *
2229  * ms    : milliseconds
2230  * s     : seconds
2231  * mi[n] : minutes
2232  * h     : hours
2233  *
2234  * If no unit is contained in the given timeout parameter the default_time_unit
2235  * will be used instead.
2236  * @param timeout_parameter The string containing the timeout parameter.
2237  * @param timeout The timeout value to be returned.
2238  * @param default_time_unit The default time unit to use if none is specified
2239  * in timeout_parameter.
2240  * @return Status value indicating whether the parsing was successful or not.
2241  */
2242 AP_DECLARE(apr_status_t) ap_timeout_parameter_parse(
2243                                                const char *timeout_parameter,
2244                                                apr_interval_time_t *timeout,
2245                                                const char *default_time_unit)
2246 {
2247     char *endp;
2248     const char *time_str;
2249     apr_int64_t tout;
2250
2251     tout = apr_strtoi64(timeout_parameter, &endp, 10);
2252     if (errno) {
2253         return errno;
2254     }
2255     if (!endp || !*endp) {
2256         time_str = default_time_unit;
2257     }
2258     else {
2259         time_str = endp;
2260     }
2261
2262     switch (*time_str) {
2263         /* Time is in seconds */
2264     case 's':
2265         *timeout = (apr_interval_time_t) apr_time_from_sec(tout);
2266         break;
2267     case 'h':
2268         /* Time is in hours */
2269         *timeout = (apr_interval_time_t) apr_time_from_sec(tout * 3600);
2270         break;
2271     case 'm':
2272         switch (*(++time_str)) {
2273         /* Time is in milliseconds */
2274         case 's':
2275             *timeout = (apr_interval_time_t) tout * 1000;
2276             break;
2277         /* Time is in minutes */
2278         case 'i':
2279             *timeout = (apr_interval_time_t) apr_time_from_sec(tout * 60);
2280             break;
2281         default:
2282             return APR_EGENERAL;
2283         }
2284         break;
2285     default:
2286         return APR_EGENERAL;
2287     }
2288     return APR_SUCCESS;
2289 }
2290
2291 /**
2292  * Determine if a request has a request body or not.
2293  *
2294  * @param r the request_rec of the request
2295  * @return truth value
2296  */
2297 AP_DECLARE(int) ap_request_has_body(request_rec *r)
2298 {
2299     apr_off_t cl;
2300     char *estr;
2301     const char *cls;
2302     int has_body;
2303
2304     has_body = (!r->header_only
2305                 && (r->kept_body
2306                     || apr_table_get(r->headers_in, "Transfer-Encoding")
2307                     || ( (cls = apr_table_get(r->headers_in, "Content-Length"))
2308                         && (apr_strtoff(&cl, cls, &estr, 10) == APR_SUCCESS)
2309                         && (!*estr)
2310                         && (cl > 0) )
2311                     )
2312                 );
2313     return has_body;
2314 }
2315
2316 AP_DECLARE_NONSTD(apr_status_t) ap_pool_cleanup_set_null(void *data_)
2317 {
2318     void **ptr = (void **)data_;
2319     *ptr = NULL;
2320     return APR_SUCCESS;
2321 }
2322
2323 AP_DECLARE(apr_status_t) ap_str2_alnum(const char *src, char *dest) {
2324
2325     for ( ; *src; src++, dest++)
2326     {
2327         if (!apr_isprint(*src))
2328             *dest = 'x';
2329         else if (!apr_isalnum(*src))
2330             *dest = '_';
2331         else
2332             *dest = (char)*src;
2333     }
2334     *dest = '\0';
2335     return APR_SUCCESS;
2336
2337 }
2338
2339 AP_DECLARE(apr_status_t) ap_pstr2_alnum(apr_pool_t *p, const char *src,
2340                                         const char **dest)
2341 {
2342     char *new = apr_palloc(p, strlen(src)+1);
2343     if (!new)
2344         return APR_ENOMEM;
2345     *dest = new;
2346     return ap_str2_alnum(src, new);
2347 }
2348
2349 /**
2350  * Read the body and parse any form found, which must be of the
2351  * type application/x-www-form-urlencoded.
2352  *
2353  * Name/value pairs are returned in an array, with the names as
2354  * strings with a maximum length of HUGE_STRING_LEN, and the
2355  * values as bucket brigades. This allows values to be arbitrarily
2356  * large.
2357  *
2358  * All url-encoding is removed from both the names and the values
2359  * on the fly. The names are interpreted as strings, while the
2360  * values are interpreted as blocks of binary data, that may
2361  * contain the 0 character.
2362  *
2363  * In order to ensure that resource limits are not exceeded, a
2364  * maximum size must be provided. If the sum of the lengths of
2365  * the names and the values exceed this size, this function
2366  * will return HTTP_REQUEST_ENTITY_TOO_LARGE.
2367  *
2368  * An optional number of parameters can be provided, if the number
2369  * of parameters provided exceeds this amount, this function will
2370  * return HTTP_REQUEST_ENTITY_TOO_LARGE. If this value is negative,
2371  * no limit is imposed, and the number of parameters is in turn
2372  * constrained by the size parameter above.
2373  *
2374  * This function honours any kept_body configuration, and the
2375  * original raw request body will be saved to the kept_body brigade
2376  * if so configured, just as ap_discard_request_body does.
2377  *
2378  * NOTE: File upload is not yet supported, but can be without change
2379  * to the function call.
2380  */
2381
2382 /* form parsing stuff */
2383 typedef enum {
2384     FORM_NORMAL,
2385     FORM_AMP,
2386     FORM_NAME,
2387     FORM_VALUE,
2388     FORM_PERCENTA,
2389     FORM_PERCENTB,
2390     FORM_ABORT
2391 } ap_form_type_t;
2392
2393 AP_DECLARE(int) ap_parse_form_data(request_rec *r, ap_filter_t *f,
2394                                    apr_array_header_t **ptr,
2395                                    apr_size_t num, apr_size_t usize)
2396 {
2397     apr_bucket_brigade *bb = NULL;
2398     int seen_eos = 0;
2399     char buffer[HUGE_STRING_LEN + 1];
2400     const char *ct;
2401     apr_size_t offset = 0;
2402     apr_ssize_t size;
2403     ap_form_type_t state = FORM_NAME, percent = FORM_NORMAL;
2404     ap_form_pair_t *pair = NULL;
2405     apr_array_header_t *pairs = apr_array_make(r->pool, 4, sizeof(ap_form_pair_t));
2406
2407     char hi = 0;
2408     char low = 0;
2409
2410     *ptr = pairs;
2411
2412     /* sanity check - we only support forms for now */
2413     ct = apr_table_get(r->headers_in, "Content-Type");
2414     if (!ct || strncasecmp("application/x-www-form-urlencoded", ct, 33)) {
2415         return ap_discard_request_body(r);
2416     }
2417
2418     if (usize > APR_SIZE_MAX >> 1)
2419         size = APR_SIZE_MAX >> 1;
2420     else
2421         size = usize;
2422
2423     if (!f) {
2424         f = r->input_filters;
2425     }
2426
2427     bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2428     do {
2429         apr_bucket *bucket = NULL, *last = NULL;
2430
2431         int rv = ap_get_brigade(f, bb, AP_MODE_READBYTES,
2432                                 APR_BLOCK_READ, HUGE_STRING_LEN);
2433         if (rv != APR_SUCCESS) {
2434             apr_brigade_destroy(bb);
2435             return (rv == AP_FILTER_ERROR) ? rv : HTTP_BAD_REQUEST;
2436         }
2437
2438         for (bucket = APR_BRIGADE_FIRST(bb);
2439              bucket != APR_BRIGADE_SENTINEL(bb);
2440              last = bucket, bucket = APR_BUCKET_NEXT(bucket)) {
2441             const char *data;
2442             apr_size_t len, slide;
2443
2444             if (last) {
2445                 apr_bucket_delete(last);
2446             }
2447             if (APR_BUCKET_IS_EOS(bucket)) {
2448                 seen_eos = 1;
2449                 break;
2450             }
2451             if (bucket->length == 0) {
2452                 continue;
2453             }
2454
2455             rv = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
2456             if (rv != APR_SUCCESS) {
2457                 apr_brigade_destroy(bb);
2458                 return HTTP_BAD_REQUEST;
2459             }
2460
2461             slide = len;
2462             while (state != FORM_ABORT && slide-- > 0 && size >= 0 && num != 0) {
2463                 char c = *data++;
2464                 if ('+' == c) {
2465                     c = ' ';
2466                 }
2467                 else if ('&' == c) {
2468                     state = FORM_AMP;
2469                 }
2470                 if ('%' == c) {
2471                     percent = FORM_PERCENTA;
2472                     continue;
2473                 }
2474                 if (FORM_PERCENTA == percent) {
2475                     if (c >= 'a') {
2476                         hi = c - 'a' + 10;
2477                     }
2478                     else if (c >= 'A') {
2479                         hi = c - 'A' + 10;
2480                     }
2481                     else if (c >= '0') {
2482                         hi = c - '0';
2483                     }
2484                     hi = hi << 4;
2485                     percent = FORM_PERCENTB;
2486                     continue;
2487                 }
2488                 if (FORM_PERCENTB == percent) {
2489                     if (c >= 'a') {
2490                         low = c - 'a' + 10;
2491                     }
2492                     else if (c >= 'A') {
2493                         low = c - 'A' + 10;
2494                     }
2495                     else if (c >= '0') {
2496                         low = c - '0';
2497                     }
2498                     c = low | hi;
2499                     percent = FORM_NORMAL;
2500                 }
2501                 switch (state) {
2502                     case FORM_AMP:
2503                         if (pair) {
2504                             const char *tmp = apr_pmemdup(r->pool, buffer, offset);
2505                             apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
2506                             APR_BRIGADE_INSERT_TAIL(pair->value, b);
2507                         }
2508                         state = FORM_NAME;
2509                         pair = NULL;
2510                         offset = 0;
2511                         num--;
2512                         break;
2513                     case FORM_NAME:
2514                         if (offset < HUGE_STRING_LEN) {
2515                             if ('=' == c) {
2516                                 buffer[offset] = 0;
2517                                 offset = 0;
2518                                 pair = (ap_form_pair_t *) apr_array_push(pairs);
2519                                 pair->name = apr_pstrdup(r->pool, buffer);
2520                                 pair->value = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2521                                 state = FORM_VALUE;
2522                             }
2523                             else {
2524                                 buffer[offset++] = c;
2525                                 size--;
2526                             }
2527                         }
2528                         else {
2529                             state = FORM_ABORT;
2530                         }
2531                         break;
2532                     case FORM_VALUE:
2533                         if (offset >= HUGE_STRING_LEN) {
2534                             const char *tmp = apr_pmemdup(r->pool, buffer, offset);
2535                             apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
2536                             APR_BRIGADE_INSERT_TAIL(pair->value, b);
2537                             offset = 0;
2538                         }
2539                         buffer[offset++] = c;
2540                         size--;
2541                         break;
2542                     default:
2543                         break;
2544                 }
2545             }
2546
2547         }
2548
2549         apr_brigade_cleanup(bb);
2550     } while (!seen_eos);
2551
2552     if (FORM_ABORT == state || size < 0 || num == 0) {
2553         return HTTP_REQUEST_ENTITY_TOO_LARGE;
2554     }
2555     else if (FORM_VALUE == state && pair && offset > 0) {
2556         const char *tmp = apr_pmemdup(r->pool, buffer, offset);
2557         apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
2558         APR_BRIGADE_INSERT_TAIL(pair->value, b);
2559     }
2560
2561     return OK;
2562
2563 }
2564
2565 #define VARBUF_SMALL_SIZE 2048
2566 #define VARBUF_MAX_SIZE   (APR_SIZE_MAX - 1 -                                \
2567                            APR_ALIGN_DEFAULT(sizeof(struct ap_varbuf_info)))
2568
2569 struct ap_varbuf_info {
2570     struct apr_memnode_t *node;
2571     apr_allocator_t *allocator;
2572 };
2573
2574 static apr_status_t varbuf_cleanup(void *info_)
2575 {
2576     struct ap_varbuf_info *info = info_;
2577     info->node->next = NULL;
2578     apr_allocator_free(info->allocator, info->node);
2579     return APR_SUCCESS;
2580 }
2581
2582 const char nul = '\0';
2583 static char * const varbuf_empty = (char *)&nul;
2584
2585 AP_DECLARE(void) ap_varbuf_init(apr_pool_t *p, struct ap_varbuf *vb,
2586                                 apr_size_t init_size)
2587 {
2588     vb->buf = varbuf_empty;
2589     vb->avail = 0;
2590     vb->strlen = AP_VARBUF_UNKNOWN;
2591     vb->pool = p;
2592     vb->info = NULL;
2593
2594     ap_varbuf_grow(vb, init_size);
2595 }
2596
2597 AP_DECLARE(void) ap_varbuf_grow(struct ap_varbuf *vb, apr_size_t new_len)
2598 {
2599     apr_memnode_t *new_node = NULL;
2600     apr_allocator_t *allocator;
2601     struct ap_varbuf_info *new_info;
2602     char *new;
2603
2604     AP_DEBUG_ASSERT(vb->strlen == AP_VARBUF_UNKNOWN || vb->avail >= vb->strlen);
2605
2606     if (new_len <= vb->avail)
2607         return;
2608
2609     if (new_len < 2 * vb->avail && vb->avail < VARBUF_MAX_SIZE/2) {
2610         /* at least double the size, to avoid repeated reallocations */
2611         new_len = 2 * vb->avail;
2612     }
2613     else if (new_len > VARBUF_MAX_SIZE) {
2614         apr_abortfunc_t abort_fn = apr_pool_abort_get(vb->pool);
2615         ap_assert(abort_fn != NULL);
2616         abort_fn(APR_ENOMEM);
2617         return;
2618     }
2619
2620     new_len++;  /* add space for trailing \0 */
2621     if (new_len <= VARBUF_SMALL_SIZE) {
2622         new_len = APR_ALIGN_DEFAULT(new_len);
2623         new = apr_palloc(vb->pool, new_len);
2624         if (vb->avail && vb->strlen != 0) {
2625             AP_DEBUG_ASSERT(vb->buf != NULL);
2626             AP_DEBUG_ASSERT(vb->buf != varbuf_empty);
2627             if (new == vb->buf + vb->avail + 1) {
2628                 /* We are lucky: the new memory lies directly after our old
2629                  * buffer, we can now use both.
2630                  */
2631                 vb->avail += new_len;
2632                 return;
2633             }
2634             else {
2635                 /* copy up to vb->strlen + 1 bytes */
2636                 memcpy(new, vb->buf, vb->strlen == AP_VARBUF_UNKNOWN ?
2637                                      vb->avail + 1 : vb->strlen + 1);
2638             }
2639         }
2640         else {
2641             *new = '\0';
2642         }
2643         vb->avail = new_len - 1;
2644         vb->buf = new;
2645         return;
2646     }
2647
2648     /* The required block is rather larger. Use allocator directly so that
2649      * the memory can be freed independently from the pool. */
2650     allocator = apr_pool_allocator_get(vb->pool);
2651     if (new_len <= VARBUF_MAX_SIZE)
2652         new_node = apr_allocator_alloc(allocator,
2653                                        new_len + APR_ALIGN_DEFAULT(sizeof(*new_info)));
2654     if (!new_node) {
2655         apr_abortfunc_t abort_fn = apr_pool_abort_get(vb->pool);
2656         ap_assert(abort_fn != NULL);
2657         abort_fn(APR_ENOMEM);
2658         return;
2659     }
2660     new_info = (struct ap_varbuf_info *)new_node->first_avail;
2661     new_node->first_avail += APR_ALIGN_DEFAULT(sizeof(*new_info));
2662     new_info->node = new_node;
2663     new_info->allocator = allocator;
2664     new = new_node->first_avail;
2665     AP_DEBUG_ASSERT(new_node->endp - new_node->first_avail >= new_len);
2666     new_len = new_node->endp - new_node->first_avail;
2667
2668     if (vb->avail && vb->strlen != 0)
2669         memcpy(new, vb->buf, vb->strlen == AP_VARBUF_UNKNOWN ?
2670                              vb->avail + 1 : vb->strlen + 1);
2671     else
2672         *new = '\0';
2673     if (vb->info)
2674         apr_pool_cleanup_run(vb->pool, vb->info, varbuf_cleanup);
2675     apr_pool_cleanup_register(vb->pool, new_info, varbuf_cleanup,
2676                               apr_pool_cleanup_null);
2677     vb->info = new_info;
2678     vb->buf = new;
2679     vb->avail = new_len - 1;
2680 }
2681
2682 AP_DECLARE(void) ap_varbuf_strmemcat(struct ap_varbuf *vb, const char *str,
2683                                      int len)
2684 {
2685     if (len == 0)
2686         return;
2687     if (!vb->avail) {
2688         ap_varbuf_grow(vb, len);
2689         memcpy(vb->buf, str, len);
2690         vb->buf[len] = '\0';
2691         vb->strlen = len;
2692         return;
2693     }
2694     if (vb->strlen == AP_VARBUF_UNKNOWN)
2695         vb->strlen = strlen(vb->buf);
2696     ap_varbuf_grow(vb, vb->strlen + len);
2697     memcpy(vb->buf + vb->strlen, str, len);
2698     vb->strlen += len;
2699     vb->buf[vb->strlen] = '\0';
2700 }
2701
2702 AP_DECLARE(void) ap_varbuf_free(struct ap_varbuf *vb)
2703 {
2704     if (vb->info) {
2705         apr_pool_cleanup_run(vb->pool, vb->info, varbuf_cleanup);
2706         vb->info = NULL;
2707     }
2708     vb->buf = NULL;
2709 }
2710
2711 AP_DECLARE(char *) ap_varbuf_pdup(apr_pool_t *p, struct ap_varbuf *buf,
2712                                   const char *prepend, apr_size_t prepend_len,
2713                                   const char *append, apr_size_t append_len,
2714                                   apr_size_t *new_len)
2715 {
2716     apr_size_t i = 0;
2717     struct iovec vec[3];
2718
2719     if (prepend) {
2720         vec[i].iov_base = (void *)prepend;
2721         vec[i].iov_len = prepend_len;
2722         i++;
2723     }
2724     if (buf->avail && buf->strlen) {
2725         if (buf->strlen == AP_VARBUF_UNKNOWN)
2726             buf->strlen = strlen(buf->buf);
2727         vec[i].iov_base = (void *)buf->buf;
2728         vec[i].iov_len = buf->strlen;
2729         i++;
2730     }
2731     if (append) {
2732         vec[i].iov_base = (void *)append;
2733         vec[i].iov_len = append_len;
2734         i++;
2735     }
2736     if (i)
2737         return apr_pstrcatv(p, vec, i, new_len);
2738
2739     if (new_len)
2740         *new_len = 0;
2741     return "";
2742 }
2743
2744 AP_DECLARE(apr_status_t) ap_varbuf_regsub(struct ap_varbuf *vb,
2745                                           const char *input,
2746                                           const char *source,
2747                                           apr_size_t nmatch,
2748                                           ap_regmatch_t pmatch[],
2749                                           apr_size_t maxlen)
2750 {
2751     return regsub_core(NULL, NULL, vb, input, source, nmatch, pmatch, maxlen);
2752 }
2753
2754 static const char * const oom_message = "[crit] Memory allocation failed, "
2755                                         "aborting process." APR_EOL_STR;
2756
2757 AP_DECLARE(void) ap_abort_on_oom()
2758 {
2759     int written, count = strlen(oom_message);
2760     const char *buf = oom_message;
2761     do {
2762         written = write(STDERR_FILENO, buf, count);
2763         if (written == count)
2764             break;
2765         if (written > 0) {
2766             buf += written;
2767             count -= written;
2768         }
2769     } while (written >= 0 || errno == EINTR);
2770     abort();
2771 }
2772
2773 AP_DECLARE(void *) ap_malloc(size_t size)
2774 {
2775     void *p = malloc(size);
2776     if (p == NULL && size != 0)
2777         ap_abort_on_oom();
2778     return p;
2779 }
2780
2781 AP_DECLARE(void *) ap_calloc(size_t nelem, size_t size)
2782 {
2783     void *p = calloc(nelem, size);
2784     if (p == NULL && nelem != 0 && size != 0)
2785         ap_abort_on_oom();
2786     return p;
2787 }
2788
2789 AP_DECLARE(void *) ap_realloc(void *ptr, size_t size)
2790 {
2791     void *p = realloc(ptr, size);
2792     if (p == NULL && size != 0)
2793         ap_abort_on_oom();
2794     return p;
2795 }
2796
2797 AP_DECLARE(void) ap_get_sload(ap_sload_t *ld)
2798 {
2799     int i, j, server_limit, thread_limit;
2800     int ready = 0;
2801     int busy = 0;
2802     int total;
2803     ap_generation_t mpm_generation;
2804
2805     /* preload errored fields, we overwrite */
2806     ld->idle = -1;
2807     ld->busy = -1;
2808     ld->bytes_served = 0;
2809     ld->access_count = 0;
2810
2811     ap_mpm_query(AP_MPMQ_GENERATION, &mpm_generation);
2812     ap_mpm_query(AP_MPMQ_HARD_LIMIT_THREADS, &thread_limit);
2813     ap_mpm_query(AP_MPMQ_HARD_LIMIT_DAEMONS, &server_limit);
2814
2815     for (i = 0; i < server_limit; i++) {
2816         process_score *ps;
2817         ps = ap_get_scoreboard_process(i);
2818
2819         for (j = 0; j < thread_limit; j++) {
2820             int res;
2821             worker_score *ws = NULL;
2822             ws = &ap_scoreboard_image->servers[i][j];
2823             res = ws->status;
2824
2825             if (!ps->quiescing && ps->pid) {
2826                 if (res == SERVER_READY && ps->generation == mpm_generation) {
2827                     ready++;
2828                 }
2829                 else if (res != SERVER_DEAD &&
2830                          res != SERVER_STARTING && res != SERVER_IDLE_KILL &&
2831                          ps->generation == mpm_generation) {
2832                     busy++;
2833                 }   
2834             }
2835
2836             if (ap_extended_status && !ps->quiescing && ps->pid) {
2837                 if (ws->access_count != 0 
2838                     || (res != SERVER_READY && res != SERVER_DEAD)) {
2839                     ld->access_count += ws->access_count;
2840                     ld->bytes_served += ws->bytes_served;
2841                 }
2842             }
2843         }
2844     }
2845     total = busy + ready;
2846     if (total) {
2847         ld->idle = ready * 100 / total;
2848         ld->busy = busy * 100 / total;
2849     }
2850 }
2851
2852 AP_DECLARE(void) ap_get_loadavg(ap_loadavg_t *ld)
2853 {
2854     /* preload errored fields, we overwrite */
2855     ld->loadavg = -1.0;
2856     ld->loadavg5 = -1.0;
2857     ld->loadavg15 = -1.0;
2858
2859 #if HAVE_GETLOADAVG
2860     {
2861         double la[3];
2862         int num;
2863
2864         num = getloadavg(la, 3);
2865         if (num > 0) {
2866             ld->loadavg = (float)la[0];
2867         }
2868         if (num > 1) {
2869             ld->loadavg5 = (float)la[1];
2870         }
2871         if (num > 2) {
2872             ld->loadavg15 = (float)la[2];
2873         }
2874     }
2875 #endif
2876 }