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