]> granicus.if.org Git - apache/blob - server/util.c
showstoppers--;
[apache] / server / util.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /*
60  * util.c: string utility things
61  * 
62  * 3/21/93 Rob McCool
63  * 1995-96 Many changes by the Apache Software Foundation
64  * 
65  */
66
67 /* Debugging aid:
68  * #define DEBUG            to trace all cfg_open*()/cfg_closefile() calls
69  * #define DEBUG_CFG_LINES  to trace every line read from the config files
70  */
71
72 #include "apr.h"
73 #include "apr_strings.h"
74 #include "apr_lib.h"
75
76 #define APR_WANT_STDIO
77 #define APR_WANT_STRFUNC
78 #include "apr_want.h"
79
80 #if APR_HAVE_UNISTD_H
81 #include <unistd.h>
82 #endif
83 #if APR_HAVE_NETDB_H
84 #include <netdb.h>              /* for gethostbyname() */
85 #endif
86
87 #define CORE_PRIVATE
88
89 #include "ap_config.h"
90 #include "apr_base64.h"
91 #include "httpd.h"
92 #include "http_main.h"
93 #include "http_log.h"
94 #include "http_protocol.h"
95 #include "http_config.h"
96 #include "util_ebcdic.h"
97
98 #ifdef HAVE_PWD_H
99 #include <pwd.h>
100 #endif
101 #ifdef HAVE_GRP_H
102 #include <grp.h>
103 #endif
104
105 /* A bunch of functions in util.c scan strings looking for certain characters.
106  * To make that more efficient we encode a lookup table.  The test_char_table
107  * is generated automatically by gen_test_char.c.
108  */
109 #include "test_char.h"
110
111 /* we assume the folks using this ensure 0 <= c < 256... which means
112  * you need a cast to (unsigned char) first, you can't just plug a
113  * char in here and get it to work, because if char is signed then it
114  * will first be sign extended.
115  */
116 #define TEST_CHAR(c, f) (test_char_table[(unsigned)(c)] & (f))
117
118 /*
119  * Examine a field value (such as a media-/content-type) string and return
120  * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
121  */
122 AP_DECLARE(char *) ap_field_noparam(apr_pool_t *p, const char *intype)
123 {
124     const char *semi;
125
126     if (intype == NULL) return NULL;
127
128     semi = ap_strchr_c(intype, ';');
129     if (semi == NULL) {
130         return apr_pstrdup(p, intype);
131     } 
132     else {
133         while ((semi > intype) && apr_isspace(semi[-1])) {
134             semi--;
135         }
136         return apr_pstrndup(p, intype, semi - intype);
137     }
138 }
139
140 AP_DECLARE(char *) ap_ht_time(apr_pool_t *p, apr_time_t t, const char *fmt, int gmt)
141 {
142     apr_size_t retcode;
143     char ts[MAX_STRING_LEN];
144     char tf[MAX_STRING_LEN];
145     apr_exploded_time_t xt;
146
147     if (gmt) {
148         const char *f;
149         char *strp;
150
151         apr_explode_gmt(&xt, t);
152         /* Convert %Z to "GMT" and %z to "+0000";
153          * on hosts that do not have a time zone string in struct tm,
154          * strftime must assume its argument is local time.
155          */
156         for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
157             ; f++, strp++) {
158             if (*f != '%') continue;
159             switch (f[1]) {
160             case '%':
161                 *++strp = *++f;
162                 break;
163             case 'Z':
164                 *strp++ = 'G';
165                 *strp++ = 'M';
166                 *strp = 'T';
167                 f++;
168                 break;
169             case 'z': /* common extension */
170                 *strp++ = '+';
171                 *strp++ = '0';
172                 *strp++ = '0';
173                 *strp++ = '0';
174                 *strp = '0';
175                 f++;
176                 break;
177             }
178         }
179         *strp = '\0';
180         fmt = tf;
181     }
182     else {
183         apr_explode_localtime(&xt, t);
184     }
185
186     /* check return code? */
187     apr_strftime(ts, &retcode, MAX_STRING_LEN, fmt, &xt);
188     ts[MAX_STRING_LEN - 1] = '\0';
189     return apr_pstrdup(p, ts);
190 }
191
192 /* Roy owes Rob beer. */
193 /* Rob owes Roy dinner. */
194
195 /* These legacy comments would make a lot more sense if Roy hadn't
196  * replaced the old later_than() routine with util_date.c.
197  *
198  * Well, okay, they still wouldn't make any sense.
199  */
200
201 /* Match = 0, NoMatch = 1, Abort = -1
202  * Based loosely on sections of wildmat.c by Rich Salz
203  * Hmmm... shouldn't this really go component by component?
204  */
205 AP_DECLARE(int) ap_strcmp_match(const char *str, const char *exp)
206 {
207     int x, y;
208
209     for (x = 0, y = 0; exp[y]; ++y, ++x) {
210         if ((!str[x]) && (exp[y] != '*'))
211             return -1;
212         if (exp[y] == '*') {
213             while (exp[++y] == '*');
214             if (!exp[y])
215                 return 0;
216             while (str[x]) {
217                 int ret;
218                 if ((ret = ap_strcmp_match(&str[x++], &exp[y])) != 1)
219                     return ret;
220             }
221             return -1;
222         }
223         else if ((exp[y] != '?') && (str[x] != exp[y]))
224             return 1;
225     }
226     return (str[x] != '\0');
227 }
228
229 AP_DECLARE(int) ap_strcasecmp_match(const char *str, const char *exp)
230 {
231     int x, y;
232
233     for (x = 0, y = 0; exp[y]; ++y, ++x) {
234         if ((!str[x]) && (exp[y] != '*'))
235             return -1;
236         if (exp[y] == '*') {
237             while (exp[++y] == '*');
238             if (!exp[y])
239                 return 0;
240             while (str[x]) {
241                 int ret;
242                 if ((ret = ap_strcasecmp_match(&str[x++], &exp[y])) != 1)
243                     return ret;
244             }
245             return -1;
246         }
247         else if ((exp[y] != '?') && (apr_tolower(str[x]) != apr_tolower(exp[y])))
248             return 1;
249     }
250     return (str[x] != '\0');
251 }
252
253 /* We actually compare the canonical root to this root, (but we don't
254  * waste time checking the case), since every use of this function in 
255  * httpd-2.0 tests if the path is 'proper', meaning we've already passed
256  * it through apr_filepath_merge, or we haven't.
257  */
258 AP_DECLARE(int) ap_os_is_path_absolute(apr_pool_t *p, const char *dir) 
259 {
260     const char *newpath;
261     const char *ourdir = dir;
262     if (apr_filepath_root(&newpath, &dir, 0, p) != APR_SUCCESS
263             || strncmp(newpath, ourdir, strlen(newpath)) != 0) {
264         return 0;
265     }
266     return 1;
267 }
268
269 AP_DECLARE(int) ap_is_matchexp(const char *str)
270 {
271     register int x;
272
273     for (x = 0; str[x]; x++)
274         if ((str[x] == '*') || (str[x] == '?'))
275             return 1;
276     return 0;
277 }
278
279 /*
280  * Here's a pool-based interface to POSIX regex's regcomp().
281  * Note that we return regex_t instead of being passed one.
282  * The reason is that if you use an already-used regex_t structure,
283  * the memory that you've already allocated gets forgotten, and
284  * regfree() doesn't clear it. So we don't allow it.
285  */
286
287 static apr_status_t regex_cleanup(void *preg)
288 {
289     regfree((regex_t *) preg);
290     return APR_SUCCESS;
291 }
292
293 AP_DECLARE(regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
294                                    int cflags)
295 {
296     regex_t *preg = apr_palloc(p, sizeof(regex_t));
297
298     if (regcomp(preg, pattern, cflags)) {
299         return NULL;
300     }
301
302     apr_pool_cleanup_register(p, (void *) preg, regex_cleanup, regex_cleanup);
303
304     return preg;
305 }
306
307 AP_DECLARE(void) ap_pregfree(apr_pool_t *p, regex_t * reg)
308 {
309     regfree(reg);
310     apr_pool_cleanup_kill(p, (void *) reg, regex_cleanup);
311 }
312
313 /*
314  * Similar to standard strstr() but we ignore case in this version.
315  * Based on the strstr() implementation further below.
316  */
317 AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
318 {
319     char *p1, *p2;
320     if (*s2 == '\0') {
321         /* an empty s2 */
322         return((char *)s1);
323     }
324     while(1) {
325         for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
326         if (*s1 == '\0') return(NULL);
327         /* found first character of s2, see if the rest matches */
328         p1 = (char *)s1;
329         p2 = (char *)s2;
330         while (apr_tolower(*++p1) == apr_tolower(*++p2)) {
331             if (*p1 == '\0') {
332                 /* both strings ended together */
333                 return((char *)s1);
334             }
335         }
336         if (*p2 == '\0') {
337             /* second string ended, a match */
338             break;
339         }
340         /* didn't find a match here, try starting at next character in s1 */
341         s1++;
342     }
343     return((char *)s1);
344 }
345
346 /*
347  * Returns an offsetted pointer in bigstring immediately after
348  * prefix. Returns bigstring if bigstring doesn't start with
349  * prefix or if prefix is longer than bigstring while still matching.
350  * NOTE: pointer returned is relative to bigstring, so we
351  * can use standard pointer comparisons in the calling function
352  * (eg: test if ap_stripprefix(a,b) == a)
353  */
354 AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
355                                         const char *prefix)
356 {
357     const char *p1;
358
359     if (*prefix == '\0')
360         return bigstring;
361
362     p1 = bigstring;
363     while (*p1 && *prefix) {
364         if (*p1++ != *prefix++)
365             return bigstring;
366     }
367     if (*prefix == '\0')
368         return p1;
369
370     /* hit the end of bigstring! */
371     return bigstring;
372 }
373
374 /* 
375  * Apache stub function for the regex libraries regexec() to make sure the
376  * whole regex(3) API is available through the Apache (exported) namespace.
377  * This is especially important for the DSO situations of modules.
378  * DO NOT MAKE A MACRO OUT OF THIS FUNCTION!
379  */
380 AP_DECLARE(int) ap_regexec(regex_t *preg, const char *string,
381                            size_t nmatch, regmatch_t pmatch[], int eflags)
382 {
383     return regexec(preg, string, nmatch, pmatch, eflags);
384 }
385
386 AP_DECLARE(size_t) ap_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
387 {
388     return regerror(errcode, preg, errbuf, errbuf_size);
389 }
390
391
392 /* This function substitutes for $0-$9, filling in regular expression
393  * submatches. Pass it the same nmatch and pmatch arguments that you
394  * passed ap_regexec(). pmatch should not be greater than the maximum number
395  * of subexpressions - i.e. one more than the re_nsub member of regex_t.
396  *
397  * input should be the string with the $-expressions, source should be the
398  * string that was matched against.
399  *
400  * It returns the substituted string, or NULL on error.
401  *
402  * Parts of this code are based on Henry Spencer's regsub(), from his
403  * AT&T V8 regexp package.
404  */
405
406 AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input, const char *source,
407                            size_t nmatch, regmatch_t pmatch[])
408 {
409     const char *src = input;
410     char *dest, *dst;
411     char c;
412     size_t no;
413     int len;
414
415     if (!source)
416         return NULL;
417     if (!nmatch)
418         return apr_pstrdup(p, src);
419
420     /* First pass, find the size */
421
422     len = 0;
423
424     while ((c = *src++) != '\0') {
425         if (c == '&')
426             no = 0;
427         else if (c == '$' && apr_isdigit(*src))
428             no = *src++ - '0';
429         else
430             no = 10;
431
432         if (no > 9) {           /* Ordinary character. */
433             if (c == '\\' && (*src == '$' || *src == '&'))
434                 c = *src++;
435             len++;
436         }
437         else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
438             len += pmatch[no].rm_eo - pmatch[no].rm_so;
439         }
440
441     }
442
443     dest = dst = apr_pcalloc(p, len + 1);
444
445     /* Now actually fill in the string */
446
447     src = input;
448
449     while ((c = *src++) != '\0') {
450         if (c == '&')
451             no = 0;
452         else if (c == '$' && apr_isdigit(*src))
453             no = *src++ - '0';
454         else
455             no = 10;
456
457         if (no > 9) {           /* Ordinary character. */
458             if (c == '\\' && (*src == '$' || *src == '&'))
459                 c = *src++;
460             *dst++ = c;
461         }
462         else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
463             len = pmatch[no].rm_eo - pmatch[no].rm_so;
464             memcpy(dst, source + pmatch[no].rm_so, len);
465             dst += len;
466         }
467
468     }
469     *dst = '\0';
470
471     return dest;
472 }
473
474 /*
475  * Parse .. so we don't compromise security
476  */
477 AP_DECLARE(void) ap_getparents(char *name)
478 {
479     char *next;
480     int l, w, first_dot;
481
482     /* Four paseses, as per RFC 1808 */
483     /* a) remove ./ path segments */
484     for (next = name; *next && (*next != '.'); next++) {
485     }
486     l = w = first_dot = next - name;
487     while (name[l] != '\0') {
488         if (name[l] == '.' && name[l + 1] == '/' && (l == 0 || name[l - 1] == '/'))
489             l += 2;
490         else
491             name[w++] = name[l++];
492     }
493
494     /* b) remove trailing . path, segment */
495     if (w == 1 && name[0] == '.')
496         w--;
497     else if (w > 1 && name[w - 1] == '.' && name[w - 2] == '/')
498         w--;
499     name[w] = '\0';
500
501     /* c) remove all xx/../ segments. (including leading ../ and /../) */
502     l = first_dot;
503
504     while (name[l] != '\0') {
505         if (name[l] == '.' && name[l + 1] == '.' && name[l + 2] == '/' &&
506             (l == 0 || name[l - 1] == '/')) {
507             register int m = l + 3, n;
508
509             l = l - 2;
510             if (l >= 0) {
511                 while (l >= 0 && name[l] != '/')
512                     l--;
513                 l++;
514             }
515             else
516                 l = 0;
517             n = l;
518             while ((name[n] = name[m]))
519                 (++n, ++m);
520         }
521         else
522             ++l;
523     }
524
525     /* d) remove trailing xx/.. segment. */
526     if (l == 2 && name[0] == '.' && name[1] == '.')
527         name[0] = '\0';
528     else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.' && name[l - 3] == '/') {
529         l = l - 4;
530         if (l >= 0) {
531             while (l >= 0 && name[l] != '/')
532                 l--;
533             l++;
534         }
535         else
536             l = 0;
537         name[l] = '\0';
538     }
539 }
540
541 AP_DECLARE(void) ap_no2slash(char *name)
542 {
543     char *d, *s;
544
545     s = d = name;
546
547 #ifdef HAVE_UNC_PATHS
548     /* Check for UNC names.  Leave leading two slashes. */
549     if (s[0] == '/' && s[1] == '/')
550         *d++ = *s++;
551 #endif
552
553     while (*s) {
554         if ((*d++ = *s) == '/') {
555             do {
556                 ++s;
557             } while (*s == '/');
558         }
559         else {
560             ++s;
561         }
562     }
563     *d = '\0';
564 }
565
566
567 /*
568  * copy at most n leading directories of s into d
569  * d should be at least as large as s plus 1 extra byte
570  * assumes n > 0
571  * the return value is the ever useful pointer to the trailing \0 of d
572  *
573  * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments, 
574  * so that if n == 0, "/" is returned in d with n == 1 
575  * and s == "e:/test.html", "e:/" is returned in d
576  * *** See also directory_walk in modules/http/http_request.c
577
578  * examples:
579  *    /a/b, 0  ==> /  (true for all platforms)
580  *    /a/b, 1  ==> /
581  *    /a/b, 2  ==> /a/
582  *    /a/b, 3  ==> /a/b/
583  *    /a/b, 4  ==> /a/b/
584  *
585  *    c:/a/b 0 ==> /
586  *    c:/a/b 1 ==> c:/
587  *    c:/a/b 2 ==> c:/a/
588  *    c:/a/b 3 ==> c:/a/b
589  *    c:/a/b 4 ==> c:/a/b
590  */
591 AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
592 {
593     if (n < 1) {
594         *d = '/';
595         *++d = '\0';
596         return (d);
597     }
598
599     for (;;) {
600         if (*s == '\0' || (*s == '/' && (--n) == 0)) {
601             *d = '/';
602             break;
603         }
604         *d++ = *s++;
605     }
606     *++d = 0;
607     return (d);
608 }
609
610
611 /*
612  * return the parent directory name including trailing / of the file s
613  */
614 AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
615 {
616     const char *last_slash = ap_strrchr_c(s, '/');
617     char *d;
618     int l;
619
620     if (last_slash == NULL) {
621         return apr_pstrdup(p, "");
622     }
623     l = (last_slash - s) + 1;
624     d = apr_palloc(p, l + 1);
625     memcpy(d, s, l);
626     d[l] = 0;
627     return (d);
628 }
629
630
631 AP_DECLARE(int) ap_count_dirs(const char *path)
632 {
633     register int x, n;
634
635     for (x = 0, n = 0; path[x]; x++)
636         if (path[x] == '/')
637             n++;
638     return n;
639 }
640
641 AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
642 {
643     return ap_getword(atrans, (const char **) line, stop);
644 }
645
646 AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
647 {
648     const char *pos = *line;
649     int len;
650     char *res;
651
652     while ((*pos != stop) && *pos) {
653         ++pos;
654     }
655
656     len = pos - *line;
657     res = (char *)apr_palloc(atrans, len + 1);
658     memcpy(res, *line, len);
659     res[len] = 0;
660
661     if (stop) {
662         while (*pos == stop) {
663             ++pos;
664         }
665     }
666     *line = pos;
667
668     return res;
669 }
670
671 AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
672 {
673     return ap_getword_white(atrans, (const char **) line);
674 }
675
676 AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
677 {
678     int pos = -1, x;
679     char *res;
680
681     for (x = 0; (*line)[x]; x++) {
682         if (apr_isspace((*line)[x])) {
683             pos = x;
684             break;
685         }
686     }
687
688     if (pos == -1) {
689         res = apr_pstrdup(atrans, *line);
690         *line += strlen(*line);
691         return res;
692     }
693
694     res = apr_palloc(atrans, pos + 1);
695     apr_cpystrn(res, *line, pos + 1);
696
697     while (apr_isspace((*line)[pos]))
698         ++pos;
699
700     *line += pos;
701
702     return res;
703 }
704
705 AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line, char stop)
706 {
707     return ap_getword_nulls(atrans, (const char **) line, stop);
708 }
709
710 AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line, char stop)
711 {
712     const char *pos = ap_strchr_c(*line, stop);
713     char *res;
714
715     if (!pos) {
716         res = apr_pstrdup(atrans, *line);
717         *line += strlen(*line);
718         return res;
719     }
720
721     res = apr_pstrndup(atrans, *line, pos - *line);
722
723     ++pos;
724
725     *line = pos;
726
727     return res;
728 }
729
730 /* Get a word, (new) config-file style --- quoted strings and backslashes
731  * all honored
732  */
733
734 static char *substring_conf(apr_pool_t *p, const char *start, int len, char quote)
735 {
736     char *result = apr_palloc(p, len + 2);
737     char *resp = result;
738     int i;
739
740     for (i = 0; i < len; ++i) {
741         if (start[i] == '\\' && (start[i + 1] == '\\'
742                                  || (quote && start[i + 1] == quote)))
743             *resp++ = start[++i];
744         else
745             *resp++ = start[i];
746     }
747
748     *resp++ = '\0';
749 #if RESOLVE_ENV_PER_TOKEN
750     return ap_resolve_env(p,result);
751 #else
752     return result;
753 #endif
754 }
755
756 AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
757 {
758     return ap_getword_conf(p, (const char **) line);
759 }
760
761 AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
762 {
763     const char *str = *line, *strend;
764     char *res;
765     char quote;
766
767     while (*str && apr_isspace(*str))
768         ++str;
769
770     if (!*str) {
771         *line = str;
772         return "";
773     }
774
775     if ((quote = *str) == '"' || quote == '\'') {
776         strend = str + 1;
777         while (*strend && *strend != quote) {
778             if (*strend == '\\' && strend[1] && strend[1] == quote)
779                 strend += 2;
780             else
781                 ++strend;
782         }
783         res = substring_conf(p, str + 1, strend - str - 1, quote);
784
785         if (*strend == quote)
786             ++strend;
787     }
788     else {
789         strend = str;
790         while (*strend && !apr_isspace(*strend))
791             ++strend;
792
793         res = substring_conf(p, str, strend - str, 0);
794     }
795
796     while (*strend && apr_isspace(*strend))
797         ++strend;
798     *line = strend;
799     return res;
800 }
801
802 /* Check a string for any ${ENV} environment variable
803  * construct and replace each them by the value of
804  * that environment variable, if it exists. If the
805  * environment value does not exist, leave the ${ENV}
806  * construct alone; it means something else.
807  */
808 AP_DECLARE(const char *) ap_resolve_env(apr_pool_t *p, const char * word)
809 {
810        char tmp[ MAX_STRING_LEN ];
811        const char *s, *e;
812        tmp[0] = '\0';
813
814        if (!(s=ap_strchr_c(word,'$')))
815                return word;
816
817        do {
818                /* XXX - relies on strncat() to add '\0'
819                 */
820                strncat(tmp,word,s - word);
821                if ((s[1] == '{') && (e=ap_strchr_c(s,'}'))) {
822                        const char *e2 = e;
823                        word = e + 1;
824                        e = getenv(s+2);
825                        if (e) {
826                            strcat(tmp,e);
827                        } else {
828                            strncat(tmp, s, e2-s);
829                            strcat(tmp,"}");
830                        }
831                } else {
832                        /* ignore invalid strings */
833                        word = s+1;
834                        strcat(tmp,"$");
835                };
836        } while ((s=ap_strchr_c(word,'$')));
837        strcat(tmp,word);
838
839        return apr_pstrdup(p,tmp);
840 }
841 AP_DECLARE(int) ap_cfg_closefile(ap_configfile_t *cfp)
842 {
843 #ifdef DEBUG
844     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, 
845         "Done with config file %s", cfp->name);
846 #endif
847     return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
848 }
849
850 static apr_status_t cfg_close(void *param)
851 {
852     apr_file_t *cfp = (apr_file_t *) param;
853     return (apr_file_close(cfp));
854 }
855
856 static int cfg_getch(void *param)
857 {
858     char ch;
859     apr_file_t *cfp = (apr_file_t *) param;
860     if (apr_file_getc(&ch, cfp) == APR_SUCCESS)
861         return ch;
862     return (int)EOF;
863 }
864
865 static void *cfg_getstr(void *buf, size_t bufsiz, void *param)
866 {
867     apr_file_t *cfp = (apr_file_t *) param;
868     apr_status_t rv;
869     rv = apr_file_gets(buf, bufsiz, cfp);
870     if (rv == APR_SUCCESS || (rv == APR_EOF && strcmp(buf, "")))
871         return buf;
872     return NULL;
873 }
874
875 /* Open a ap_configfile_t as FILE, return open ap_configfile_t struct pointer */
876 AP_DECLARE(apr_status_t) ap_pcfg_openfile(ap_configfile_t **ret_cfg, apr_pool_t *p, const char *name)
877 {
878     ap_configfile_t *new_cfg;
879     apr_file_t *file = NULL;
880     apr_finfo_t finfo;
881     apr_status_t status;
882 #ifdef DEBUG
883     char buf[120];
884 #endif
885
886     if (name == NULL) {
887         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
888                "Internal error: pcfg_openfile() called with NULL filename");
889         return APR_EBADF;
890     }
891
892     status = apr_file_open(&file, name, APR_READ | APR_BUFFERED, APR_OS_DEFAULT, p);
893 #ifdef DEBUG
894     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL,
895                 "Opening config file %s (%s)",
896                 name, (status != APR_SUCCESS) ? 
897                 apr_strerror(status, buf, sizeof(buf)) : "successful");
898 #endif
899     if (status != APR_SUCCESS)
900         return status;
901
902     status = apr_file_info_get(&finfo, APR_FINFO_TYPE, file);
903     if (status != APR_SUCCESS)
904         return status;
905
906     if (finfo.filetype != APR_REG &&
907 #if defined(WIN32) || defined(OS2) || defined(NETWARE)
908         strcasecmp(apr_filename_of_pathname(name), "nul") != 0) {
909 #else
910         strcmp(name, "/dev/null") != 0) {
911 #endif /* WIN32 || OS2 */
912         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
913                     "Access to file %s denied by server: not a regular file",
914                     name);
915         apr_file_close(file);
916         return APR_EBADF;
917     }
918
919     new_cfg = apr_palloc(p, sizeof(*new_cfg));
920     new_cfg->param = file;
921     new_cfg->name = apr_pstrdup(p, name);
922     new_cfg->getch = (int (*)(void *)) cfg_getch;
923     new_cfg->getstr = (void *(*)(void *, size_t, void *)) cfg_getstr;
924     new_cfg->close = (int (*)(void *)) cfg_close;
925     new_cfg->line_number = 0;
926     *ret_cfg = new_cfg;
927     return APR_SUCCESS;
928 }
929
930
931 /* Allocate a ap_configfile_t handle with user defined functions and params */
932 AP_DECLARE(ap_configfile_t *) ap_pcfg_open_custom(apr_pool_t *p, const char *descr,
933     void *param,
934     int(*getch)(void *param),
935     void *(*getstr) (void *buf, size_t bufsiz, void *param),
936     int(*close_func)(void *param))
937 {
938     ap_configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
939 #ifdef DEBUG
940     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL, "Opening config handler %s", descr);
941 #endif
942     new_cfg->param = param;
943     new_cfg->name = descr;
944     new_cfg->getch = getch;
945     new_cfg->getstr = getstr;
946     new_cfg->close = close_func;
947     new_cfg->line_number = 0;
948     return new_cfg;
949 }
950    
951 /* Read one character from a configfile_t */
952 AP_DECLARE(int) ap_cfg_getc(ap_configfile_t *cfp)
953 {
954     register int ch = cfp->getch(cfp->param);
955     if (ch == LF) 
956         ++cfp->line_number;
957     return ch;
958 }
959   
960 /* Read one line from open ap_configfile_t, strip LF, increase line number */
961 /* If custom handler does not define a getstr() function, read char by char */
962 AP_DECLARE(int) ap_cfg_getline(char *buf, size_t bufsize, ap_configfile_t *cfp)
963 {
964     /* If a "get string" function is defined, use it */
965     if (cfp->getstr != NULL) {
966         char *src, *dst;
967         char *cp;
968         char *cbuf = buf;
969         size_t cbufsize = bufsize;
970
971         while (1) {
972             ++cfp->line_number;
973             if (cfp->getstr(cbuf, cbufsize, cfp->param) == NULL)
974                 return 1;
975
976             /*
977              *  check for line continuation,
978              *  i.e. match [^\\]\\[\r]\n only
979              */
980             cp = cbuf;
981             while (cp < cbuf+cbufsize && *cp != '\0')
982                 cp++;
983             if (cp > cbuf && cp[-1] == LF) {
984                 cp--;
985                 if (cp > cbuf && cp[-1] == CR)
986                     cp--;
987                 if (cp > cbuf && cp[-1] == '\\') {
988                     cp--;
989                     if (!(cp > cbuf && cp[-1] == '\\')) {
990                         /*
991                          * line continuation requested -
992                          * then remove backslash and continue
993                          */
994                         cbufsize -= (cp-cbuf);
995                         cbuf = cp;
996                         continue;
997                     }
998                     else {
999                         /* 
1000                          * no real continuation because escaped -
1001                          * then just remove escape character
1002                          */
1003                         for ( ; cp < cbuf+cbufsize && *cp != '\0'; cp++)
1004                             cp[0] = cp[1];
1005                     }   
1006                 }
1007             }
1008             break;
1009         }
1010
1011         /*
1012          * Leading and trailing white space is eliminated completely
1013          */
1014         src = buf;
1015         while (apr_isspace(*src))
1016             ++src;
1017         /* blast trailing whitespace */
1018         dst = &src[strlen(src)];
1019         while (--dst >= src && apr_isspace(*dst))
1020             *dst = '\0';
1021         /* Zap leading whitespace by shifting */
1022         if (src != buf)
1023             for (dst = buf; (*dst++ = *src++) != '\0'; )
1024                 ;
1025
1026 #ifdef DEBUG_CFG_LINES
1027         ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1028 #endif
1029         return 0;
1030     } else {
1031         /* No "get string" function defined; read character by character */
1032         register int c;
1033         register size_t i = 0;
1034
1035         buf[0] = '\0';
1036         /* skip leading whitespace */
1037         do {
1038             c = cfp->getch(cfp->param);
1039         } while (c == '\t' || c == ' ');
1040
1041         if (c == EOF)
1042             return 1;
1043         
1044         if(bufsize < 2) {
1045             /* too small, assume caller is crazy */
1046             return 1;
1047         }
1048
1049         while (1) {
1050             if ((c == '\t') || (c == ' ')) {
1051                 buf[i++] = ' ';
1052                 while ((c == '\t') || (c == ' '))
1053                     c = cfp->getch(cfp->param);
1054             }
1055             if (c == CR) {
1056                 /* silently ignore CR (_assume_ that a LF follows) */
1057                 c = cfp->getch(cfp->param);
1058             }
1059             if (c == LF) {
1060                 /* increase line number and return on LF */
1061                 ++cfp->line_number;
1062             }
1063             if (c == EOF || c == 0x4 || c == LF || i >= (bufsize - 2)) {
1064                 /* 
1065                  *  check for line continuation
1066                  */
1067                 if (i > 0 && buf[i-1] == '\\') {
1068                     i--;
1069                     if (!(i > 0 && buf[i-1] == '\\')) {
1070                         /* line is continued */
1071                         c = cfp->getch(cfp->param);
1072                         continue;
1073                     }
1074                     /* else nothing needs be done because
1075                      * then the backslash is escaped and
1076                      * we just strip to a single one
1077                      */
1078                 }
1079                 /* blast trailing whitespace */
1080                 while (i > 0 && apr_isspace(buf[i - 1]))
1081                     --i;
1082                 buf[i] = '\0';
1083 #ifdef DEBUG_CFG_LINES
1084                 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1085 #endif
1086                 return 0;
1087             }
1088             buf[i] = c;
1089             ++i;
1090             c = cfp->getch(cfp->param);
1091         }
1092     }
1093 }
1094
1095 /* Size an HTTP header field list item, as separated by a comma.
1096  * The return value is a pointer to the beginning of the non-empty list item
1097  * within the original string (or NULL if there is none) and the address
1098  * of field is shifted to the next non-comma, non-whitespace character.
1099  * len is the length of the item excluding any beginning whitespace.
1100  */
1101 AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1102 {
1103     const unsigned char *ptr = (const unsigned char *)*field;
1104     const unsigned char *token;
1105     int in_qpair, in_qstr, in_com;
1106
1107     /* Find first non-comma, non-whitespace byte */
1108
1109     while (*ptr == ',' || apr_isspace(*ptr))
1110         ++ptr;
1111
1112     token = ptr;
1113
1114     /* Find the end of this item, skipping over dead bits */
1115
1116     for (in_qpair = in_qstr = in_com = 0;
1117          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1118          ++ptr) {
1119
1120         if (in_qpair) {
1121             in_qpair = 0;
1122         }
1123         else {
1124             switch (*ptr) {
1125                 case '\\': in_qpair = 1;      /* quoted-pair         */
1126                            break;
1127                 case '"' : if (!in_com)       /* quoted string delim */
1128                                in_qstr = !in_qstr;
1129                            break;
1130                 case '(' : if (!in_qstr)      /* comment (may nest)  */
1131                                ++in_com;
1132                            break;
1133                 case ')' : if (in_com)        /* end comment         */
1134                                --in_com;
1135                            break;
1136                 default  : break;
1137             }
1138         }
1139     }
1140
1141     if ((*len = (ptr - token)) == 0) {
1142         *field = (const char *)ptr;
1143         return NULL;
1144     }
1145
1146     /* Advance field pointer to the next non-comma, non-white byte */
1147
1148     while (*ptr == ',' || apr_isspace(*ptr))
1149         ++ptr;
1150
1151     *field = (const char *)ptr;
1152     return (const char *)token;
1153 }
1154
1155 /* Retrieve an HTTP header field list item, as separated by a comma,
1156  * while stripping insignificant whitespace and lowercasing anything not in
1157  * a quoted string or comment.  The return value is a new string containing
1158  * the converted list item (or NULL if none) and the address pointed to by
1159  * field is shifted to the next non-comma, non-whitespace.
1160  */
1161 AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1162 {
1163     const char *tok_start;
1164     const unsigned char *ptr;
1165     unsigned char *pos;
1166     char *token;
1167     int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1168
1169     /* Find the beginning and maximum length of the list item so that
1170      * we can allocate a buffer for the new string and reset the field.
1171      */
1172     if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1173         return NULL;
1174     }
1175     token = apr_palloc(p, tok_len + 1);
1176
1177     /* Scan the token again, but this time copy only the good bytes.
1178      * We skip extra whitespace and any whitespace around a '=', '/',
1179      * or ';' and lowercase normal characters not within a comment,
1180      * quoted-string or quoted-pair.
1181      */
1182     for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1183          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1184          ++ptr) {
1185
1186         if (in_qpair) {
1187             in_qpair = 0;
1188             *pos++ = *ptr;
1189         }
1190         else {
1191             switch (*ptr) {
1192                 case '\\': in_qpair = 1;
1193                            if (addspace == 1)
1194                                *pos++ = ' ';
1195                            *pos++ = *ptr;
1196                            addspace = 0;
1197                            break;
1198                 case '"' : if (!in_com)
1199                                in_qstr = !in_qstr;
1200                            if (addspace == 1)
1201                                *pos++ = ' ';
1202                            *pos++ = *ptr;
1203                            addspace = 0;
1204                            break;
1205                 case '(' : if (!in_qstr)
1206                                ++in_com;
1207                            if (addspace == 1)
1208                                *pos++ = ' ';
1209                            *pos++ = *ptr;
1210                            addspace = 0;
1211                            break;
1212                 case ')' : if (in_com)
1213                                --in_com;
1214                            *pos++ = *ptr;
1215                            addspace = 0;
1216                            break;
1217                 case ' ' :
1218                 case '\t': if (addspace)
1219                                break;
1220                            if (in_com || in_qstr)
1221                                *pos++ = *ptr;
1222                            else
1223                                addspace = 1;
1224                            break;
1225                 case '=' :
1226                 case '/' :
1227                 case ';' : if (!(in_com || in_qstr))
1228                                addspace = -1;
1229                            *pos++ = *ptr;
1230                            break;
1231                 default  : if (addspace == 1)
1232                                *pos++ = ' ';
1233                            *pos++ = (in_com || in_qstr) ? *ptr
1234                                                         : apr_tolower(*ptr);
1235                            addspace = 0;
1236                            break;
1237             }
1238         }
1239     }
1240     *pos = '\0';
1241
1242     return token;
1243 }
1244
1245 /* Find an item in canonical form (lowercase, no extra spaces) within
1246  * an HTTP field value list.  Returns 1 if found, 0 if not found.
1247  * This would be much more efficient if we stored header fields as
1248  * an array of list items as they are received instead of a plain string.
1249  */
1250 AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line, const char *tok)
1251 {
1252     const unsigned char *pos;
1253     const unsigned char *ptr = (const unsigned char *)line;
1254     int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1255
1256     if (!line || !tok)
1257         return 0;
1258
1259     do {  /* loop for each item in line's list */
1260
1261         /* Find first non-comma, non-whitespace byte */
1262
1263         while (*ptr == ',' || apr_isspace(*ptr))
1264             ++ptr;
1265
1266         if (*ptr)
1267             good = 1;  /* until proven otherwise for this item */
1268         else
1269             break;     /* no items left and nothing good found */
1270
1271         /* We skip extra whitespace and any whitespace around a '=', '/',
1272          * or ';' and lowercase normal characters not within a comment,
1273          * quoted-string or quoted-pair.
1274          */
1275         for (pos = (const unsigned char *)tok;
1276              *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1277              ++ptr) {
1278
1279             if (in_qpair) {
1280                 in_qpair = 0;
1281                 if (good)
1282                     good = (*pos++ == *ptr);
1283             }
1284             else {
1285                 switch (*ptr) {
1286                     case '\\': in_qpair = 1;
1287                                if (addspace == 1)
1288                                    good = good && (*pos++ == ' ');
1289                                good = good && (*pos++ == *ptr);
1290                                addspace = 0;
1291                                break;
1292                     case '"' : if (!in_com)
1293                                    in_qstr = !in_qstr;
1294                                if (addspace == 1)
1295                                    good = good && (*pos++ == ' ');
1296                                good = good && (*pos++ == *ptr);
1297                                addspace = 0;
1298                                break;
1299                     case '(' : if (!in_qstr)
1300                                    ++in_com;
1301                                if (addspace == 1)
1302                                    good = good && (*pos++ == ' ');
1303                                good = good && (*pos++ == *ptr);
1304                                addspace = 0;
1305                                break;
1306                     case ')' : if (in_com)
1307                                    --in_com;
1308                                good = good && (*pos++ == *ptr);
1309                                addspace = 0;
1310                                break;
1311                     case ' ' :
1312                     case '\t': if (addspace || !good)
1313                                    break;
1314                                if (in_com || in_qstr)
1315                                    good = (*pos++ == *ptr);
1316                                else
1317                                    addspace = 1;
1318                                break;
1319                     case '=' :
1320                     case '/' :
1321                     case ';' : if (!(in_com || in_qstr))
1322                                    addspace = -1;
1323                                good = good && (*pos++ == *ptr);
1324                                break;
1325                     default  : if (!good)
1326                                    break;
1327                                if (addspace == 1)
1328                                    good = (*pos++ == ' ');
1329                                if (in_com || in_qstr)
1330                                    good = good && (*pos++ == *ptr);
1331                                else
1332                                    good = good && (*pos++ == apr_tolower(*ptr));
1333                                addspace = 0;
1334                                break;
1335                 }
1336             }
1337         }
1338         if (good && *pos)
1339             good = 0;          /* not good if only a prefix was matched */
1340
1341     } while (*ptr && !good);
1342
1343     return good;
1344 }
1345
1346
1347 /* Retrieve a token, spacing over it and returning a pointer to
1348  * the first non-white byte afterwards.  Note that these tokens
1349  * are delimited by semis and commas; and can also be delimited
1350  * by whitespace at the caller's option.
1351  */
1352
1353 AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line, int accept_white)
1354 {
1355     const char *ptr = *accept_line;
1356     const char *tok_start;
1357     char *token;
1358     int tok_len;
1359
1360     /* Find first non-white byte */
1361
1362     while (*ptr && apr_isspace(*ptr))
1363         ++ptr;
1364
1365     tok_start = ptr;
1366
1367     /* find token end, skipping over quoted strings.
1368      * (comments are already gone).
1369      */
1370
1371     while (*ptr && (accept_white || !apr_isspace(*ptr))
1372            && *ptr != ';' && *ptr != ',') {
1373         if (*ptr++ == '"')
1374             while (*ptr)
1375                 if (*ptr++ == '"')
1376                     break;
1377     }
1378
1379     tok_len = ptr - tok_start;
1380     token = apr_pstrndup(p, tok_start, tok_len);
1381
1382     /* Advance accept_line pointer to the next non-white byte */
1383
1384     while (*ptr && apr_isspace(*ptr))
1385         ++ptr;
1386
1387     *accept_line = ptr;
1388     return token;
1389 }
1390
1391
1392 /* find http tokens, see the definition of token from RFC2068 */
1393 AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1394 {
1395     const unsigned char *start_token;
1396     const unsigned char *s;
1397
1398     if (!line)
1399         return 0;
1400
1401     s = (const unsigned char *)line;
1402     for (;;) {
1403         /* find start of token, skip all stop characters, note NUL
1404          * isn't a token stop, so we don't need to test for it
1405          */
1406         while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1407             ++s;
1408         }
1409         if (!*s) {
1410             return 0;
1411         }
1412         start_token = s;
1413         /* find end of the token */
1414         while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1415             ++s;
1416         }
1417         if (!strncasecmp((const char *)start_token, (const char *)tok, s - start_token)) {
1418             return 1;
1419         }
1420         if (!*s) {
1421             return 0;
1422         }
1423     }
1424 }
1425
1426
1427 AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line, const char *tok)
1428 {
1429     int llen, tlen, lidx;
1430
1431     if (!line)
1432         return 0;
1433
1434     llen = strlen(line);
1435     tlen = strlen(tok);
1436     lidx = llen - tlen;
1437
1438     if ((lidx < 0) ||
1439         ((lidx > 0) && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1440         return 0;
1441
1442     return (strncasecmp(&line[lidx], tok, tlen) == 0);
1443 }
1444
1445 AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1446 {
1447     char *cmd;
1448     unsigned char *d;
1449     const unsigned char *s;
1450
1451     cmd = apr_palloc(p, 2 * strlen(str) + 1);   /* Be safe */
1452     d = (unsigned char *)cmd;
1453     s = (const unsigned char *)str;
1454     for (; *s; ++s) {
1455
1456 #if defined(OS2) || defined(WIN32)
1457         /* Don't allow '&' in parameters under OS/2. */
1458         /* This can be used to send commands to the shell. */
1459         if (*s == '&') {
1460             *d++ = ' ';
1461             continue;
1462         }
1463 #endif
1464
1465         if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1466             *d++ = '\\';
1467         }
1468         *d++ = *s;
1469     }
1470     *d = '\0';
1471
1472     return cmd;
1473 }
1474
1475 static char x2c(const char *what)
1476 {
1477     register char digit;
1478
1479 #if !APR_CHARSET_EBCDIC
1480     digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
1481     digit *= 16;
1482     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
1483 #else /*APR_CHARSET_EBCDIC*/
1484     char xstr[5];
1485     xstr[0]='0';
1486     xstr[1]='x';
1487     xstr[2]=what[0];
1488     xstr[3]=what[1];
1489     xstr[4]='\0';
1490     digit = apr_xlate_conv_byte(ap_hdrs_from_ascii, 0xFF & strtol(xstr, NULL, 16));
1491 #endif /*APR_CHARSET_EBCDIC*/
1492     return (digit);
1493 }
1494
1495 /*
1496  * Unescapes a URL.
1497  * Returns 0 on success, non-zero on error
1498  * Failure is due to
1499  *   bad % escape       returns HTTP_BAD_REQUEST
1500  *
1501  *   decoding %00 -> \0
1502  *   decoding %2f -> /   (a special character)
1503  *                      returns HTTP_NOT_FOUND
1504  */
1505 AP_DECLARE(int) ap_unescape_url(char *url)
1506 {
1507     register int badesc, badpath;
1508     char *x, *y;
1509
1510     badesc = 0;
1511     badpath = 0;
1512     /* Initial scan for first '%'. Don't bother writing values before
1513      * seeing a '%' */
1514     y = strchr(url, '%');
1515     if (y == NULL) {
1516         return OK;
1517     }
1518     for (x = y; *y; ++x, ++y) {
1519         if (*y != '%')
1520             *x = *y;
1521         else {
1522             if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1523                 badesc = 1;
1524                 *x = '%';
1525             }
1526             else {
1527                 *x = x2c(y + 1);
1528                 y += 2;
1529                 if (*x == '/' || *x == '\0')
1530                     badpath = 1;
1531             }
1532         }
1533     }
1534     *x = '\0';
1535     if (badesc)
1536         return HTTP_BAD_REQUEST;
1537     else if (badpath)
1538         return HTTP_NOT_FOUND;
1539     else
1540         return OK;
1541 }
1542
1543 AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
1544                                     apr_port_t port, const request_rec *r)
1545 {
1546     if (ap_is_default_port(port, r))
1547         return apr_pstrdup(p, hostname);
1548     else {
1549         return apr_psprintf(p, "%s:%u", hostname, port);
1550     }
1551 }
1552
1553 /* c2x takes an unsigned, and expects the caller has guaranteed that
1554  * 0 <= what < 256... which usually means that you have to cast to
1555  * unsigned char first, because (unsigned)(char)(x) first goes through
1556  * signed extension to an int before the unsigned cast.
1557  *
1558  * The reason for this assumption is to assist gcc code generation --
1559  * the unsigned char -> unsigned extension is already done earlier in
1560  * both uses of this code, so there's no need to waste time doing it
1561  * again.
1562  */
1563 static const char c2x_table[] = "0123456789abcdef";
1564
1565 static APR_INLINE unsigned char *c2x(unsigned what, unsigned char *where)
1566 {
1567 #if APR_CHARSET_EBCDIC
1568     what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
1569 #endif /*APR_CHARSET_EBCDIC*/
1570     *where++ = '%';
1571     *where++ = c2x_table[what >> 4];
1572     *where++ = c2x_table[what & 0xf];
1573     return where;
1574 }
1575
1576 /*
1577  * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1578  * routine is (should be) OS independent.
1579  *
1580  * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1581  * cases if a ':' occurs before the first '/' in the URL, the URL should be
1582  * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1583  * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1584  * efficiency reasons, we don't use escape_path_segment(), which is provided for
1585  * reference. Again, RFC 1808 is where this stuff is defined.
1586  *
1587  * If partial is set, os_escape_path() assumes that the path will be appended to
1588  * something with a '/' in it (and thus does not prefix "./").
1589  */
1590
1591 AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
1592 {
1593     char *copy = apr_palloc(p, 3 * strlen(segment) + 1);
1594     const unsigned char *s = (const unsigned char *)segment;
1595     unsigned char *d = (unsigned char *)copy;
1596     unsigned c;
1597
1598     while ((c = *s)) {
1599         if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1600             d = c2x(c, d);
1601         }
1602         else {
1603             *d++ = c;
1604         }
1605         ++s;
1606     }
1607     *d = '\0';
1608     return copy;
1609 }
1610
1611 AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
1612 {
1613     char *copy = apr_palloc(p, 3 * strlen(path) + 3);
1614     const unsigned char *s = (const unsigned char *)path;
1615     unsigned char *d = (unsigned char *)copy;
1616     unsigned c;
1617
1618     if (!partial) {
1619         const char *colon = ap_strchr_c(path, ':');
1620         const char *slash = ap_strchr_c(path, '/');
1621
1622         if (colon && (!slash || colon < slash)) {
1623             *d++ = '.';
1624             *d++ = '/';
1625         }
1626     }
1627     while ((c = *s)) {
1628         if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1629             d = c2x(c, d);
1630         }
1631         else {
1632             *d++ = c;
1633         }
1634         ++s;
1635     }
1636     *d = '\0';
1637     return copy;
1638 }
1639
1640 /* ap_escape_uri is now a macro for os_escape_path */
1641
1642 AP_DECLARE(char *) ap_escape_html(apr_pool_t *p, const char *s)
1643 {
1644     int i, j;
1645     char *x;
1646
1647     /* first, count the number of extra characters */
1648     for (i = 0, j = 0; s[i] != '\0'; i++)
1649         if (s[i] == '<' || s[i] == '>')
1650             j += 3;
1651         else if (s[i] == '&')
1652             j += 4;
1653
1654     if (j == 0)
1655         return apr_pstrmemdup(p, s, i);
1656
1657     x = apr_palloc(p, i + j + 1);
1658     for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1659         if (s[i] == '<') {
1660             memcpy(&x[j], "&lt;", 4);
1661             j += 3;
1662         }
1663         else if (s[i] == '>') {
1664             memcpy(&x[j], "&gt;", 4);
1665             j += 3;
1666         }
1667         else if (s[i] == '&') {
1668             memcpy(&x[j], "&amp;", 5);
1669             j += 4;
1670         }
1671         else
1672             x[j] = s[i];
1673
1674     x[j] = '\0';
1675     return x;
1676 }
1677
1678 AP_DECLARE(int) ap_is_directory(apr_pool_t *p, const char *path)
1679 {
1680     apr_finfo_t finfo;
1681
1682     if (apr_stat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
1683         return 0;               /* in error condition, just return no */
1684
1685     return (finfo.filetype == APR_DIR);
1686 }
1687
1688 AP_DECLARE(int) ap_is_rdirectory(apr_pool_t *p, const char *path)
1689 {
1690     apr_finfo_t finfo;
1691
1692     if (apr_lstat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
1693         return 0;               /* in error condition, just return no */
1694
1695     return (finfo.filetype == APR_DIR);
1696 }
1697
1698 AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
1699                                   const char *src2)
1700 {
1701     apr_size_t len1, len2;
1702     char *path;
1703
1704     len1 = strlen(src1);
1705     len2 = strlen(src2);
1706     path = (char *)apr_palloc(a, len1 + len2 + 2); /* +2 for '/' plus null */
1707     if (len1 == 0) {
1708         *path = '/';
1709         memcpy(path + 1, src2, len2 + 1);
1710     }
1711     else {
1712         char *next;
1713         memcpy(path, src1, len1);
1714         next = path + len1;
1715         if (next[-1] != '/') {
1716             *next++ = '/';
1717         }
1718         memcpy(next, src2, len2 + 1);
1719     }
1720     return path;
1721 }
1722
1723 /*
1724  * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
1725  */
1726 AP_DECLARE(int) ap_is_url(const char *u)
1727 {
1728     register int x;
1729
1730     for (x = 0; u[x] != ':'; x++) {
1731         if ((!u[x]) ||
1732             ((!apr_isalpha(u[x])) && (!apr_isdigit(u[x])) &&
1733              (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
1734             return 0;
1735         }
1736     }
1737
1738     return (x ? 1 : 0);         /* If the first character is ':', it's broken, too */
1739 }
1740
1741 AP_DECLARE(int) ap_ind(const char *s, char c)
1742 {
1743     const char *p = ap_strchr_c(s, c);
1744
1745     if (p == NULL)
1746         return -1;
1747     return p - s;
1748 }
1749
1750 AP_DECLARE(int) ap_rind(const char *s, char c)
1751 {
1752     const char *p = ap_strrchr_c(s, c);
1753
1754     if (p == NULL)
1755         return -1;
1756     return p - s;
1757 }
1758
1759 AP_DECLARE(void) ap_str_tolower(char *str)
1760 {
1761     while (*str) {
1762         *str = apr_tolower(*str);
1763         ++str;
1764     }
1765 }
1766
1767 static char *find_fqdn(apr_pool_t *a, struct hostent *p)
1768 {
1769     int x;
1770
1771     if (!strchr(p->h_name, '.')) {
1772         for (x = 0; p->h_aliases[x]; ++x) {
1773             if (strchr(p->h_aliases[x], '.') &&
1774                 (!strncasecmp(p->h_aliases[x], p->h_name, strlen(p->h_name))))
1775                 return apr_pstrdup(a, p->h_aliases[x]);
1776         }
1777         return NULL;
1778     }
1779     return apr_pstrdup(a, (void *) p->h_name);
1780 }
1781
1782 char *ap_get_local_host(apr_pool_t *a)
1783 {
1784 #ifndef MAXHOSTNAMELEN
1785 #define MAXHOSTNAMELEN 256
1786 #endif
1787     char str[MAXHOSTNAMELEN + 1];
1788     char *server_hostname = NULL;
1789     struct hostent *p;
1790
1791 #ifdef BEOS_R5
1792     if (gethostname(str, sizeof(str) - 1) == 0)
1793 #else
1794     if (gethostname(str, sizeof(str) - 1) != 0)
1795 #endif
1796     {
1797         ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a,
1798                      "%s: gethostname() failed to determine ServerName",
1799                      ap_server_argv0);
1800     }
1801     else 
1802     {
1803         str[sizeof(str) - 1] = '\0';
1804         if ((!(p = gethostbyname(str))) 
1805             || (!(server_hostname = find_fqdn(a, p)))) {
1806             /* Recovery - return the default servername by IP: */
1807             if (p && p->h_addr_list[0]) {
1808                 apr_snprintf(str, sizeof(str), "%pA", p->h_addr_list[0]);
1809                 server_hostname = apr_pstrdup(a, str);
1810                 /* We will drop through to report the IP-named server */
1811             }
1812         }
1813         else {
1814             /* Since we found a fdqn, return it with no logged message. */
1815             return server_hostname;
1816         }
1817     }
1818
1819     if (!server_hostname) 
1820         server_hostname = apr_pstrdup(a, "127.0.0.1");
1821
1822     ap_log_perror(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO|APLOG_STARTUP, 0, a,
1823                  "%s: Could not determine the server's fully qualified "
1824                  "domain name, using %s for ServerName",
1825                  ap_server_argv0, server_hostname);
1826              
1827     return server_hostname;
1828 }
1829
1830 /* simple 'pool' alloc()ing glue to apr_base64.c
1831  */
1832 AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
1833 {
1834     char *decoded;
1835     int l;
1836
1837     decoded = (char *) apr_palloc(p, 1 + apr_base64_decode_len(bufcoded));
1838     l = apr_base64_decode(decoded, bufcoded);
1839     decoded[l] = '\0'; /* make binary sequence into string */
1840
1841     return decoded;
1842 }
1843
1844 AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string) 
1845
1846     char *encoded;
1847     int l = strlen(string);
1848
1849     encoded = (char *) apr_palloc(p, 1 + apr_base64_encode_len(l));
1850     l = apr_base64_encode(encoded, string, l);
1851     encoded[l] = '\0'; /* make binary sequence into string */
1852
1853     return encoded;
1854 }
1855
1856 /* we want to downcase the type/subtype for comparison purposes
1857  * but nothing else because ;parameter=foo values are case sensitive.
1858  * XXX: in truth we want to downcase parameter names... but really,
1859  * apache has never handled parameters and such correctly.  You
1860  * also need to compress spaces and such to be able to compare
1861  * properly. -djg
1862  */
1863 AP_DECLARE(void) ap_content_type_tolower(char *str)
1864 {
1865     char *semi;
1866
1867     semi = strchr(str, ';');
1868     if (semi) {
1869         *semi = '\0';
1870     }
1871     while (*str) {
1872         *str = apr_tolower(*str);
1873         ++str;
1874     }
1875     if (semi) {
1876         *semi = ';';
1877     }
1878 }
1879
1880 /*
1881  * Given a string, replace any bare " with \" .
1882  */
1883 AP_DECLARE(char *) ap_escape_quotes (apr_pool_t *p, const char *instring)
1884 {
1885     int newlen = 0;
1886     const char *inchr = instring;
1887     char *outchr, *outstring;
1888
1889     /*
1890      * Look through the input string, jogging the length of the output
1891      * string up by an extra byte each time we find an unescaped ".
1892      */
1893     while (*inchr != '\0') {
1894         newlen++;
1895         if (*inchr == '"') {
1896             newlen++;
1897         }
1898         /*
1899          * If we find a slosh, and it's not the last byte in the string,
1900          * it's escaping something - advance past both bytes.
1901          */
1902         if ((*inchr == '\\') && (inchr[1] != '\0')) {
1903             inchr++;
1904             newlen++;
1905         }
1906         inchr++;
1907     }
1908     outstring = apr_palloc(p, newlen + 1);
1909     inchr = instring;
1910     outchr = outstring;
1911     /*
1912      * Now copy the input string to the output string, inserting a slosh
1913      * in front of every " that doesn't already have one.
1914      */
1915     while (*inchr != '\0') {
1916         if ((*inchr == '\\') && (inchr[1] != '\0')) {
1917             *outchr++ = *inchr++;
1918             *outchr++ = *inchr++;
1919         }
1920         if (*inchr == '"') {
1921             *outchr++ = '\\';
1922         }
1923         if (*inchr != '\0') {
1924             *outchr++ = *inchr++;
1925         }
1926     }
1927     *outchr = '\0';
1928     return outstring;
1929 }