]> granicus.if.org Git - apache/blob - server/util.c
Optimize ap_make_dirstr_prefix().
[apache] / server / util.c
1 /* ====================================================================
2  * Copyright (c) 1995-1999 The Apache Group.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer. 
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the Apache Group
19  *    for use in the Apache HTTP server project (http://www.apache.org/)."
20  *
21  * 4. The names "Apache Server" and "Apache Group" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    apache@apache.org.
25  *
26  * 5. Products derived from this software may not be called "Apache"
27  *    nor may "Apache" appear in their names without prior written
28  *    permission of the Apache Group.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the Apache Group
33  *    for use in the Apache HTTP server project (http://www.apache.org/)."
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Group and was originally based
51  * on public domain software written at the National Center for
52  * Supercomputing Applications, University of Illinois, Urbana-Champaign.
53  * For more information on the Apache Group and the Apache HTTP server
54  * project, please see <http://www.apache.org/>.
55  *
56  */
57
58 /*
59  * util.c: string utility things
60  * 
61  * 3/21/93 Rob McCool
62  * 1995-96 Many changes by the Apache Group
63  * 
64  */
65
66 /* Debugging aid:
67  * #define DEBUG            to trace all cfg_open*()/cfg_closefile() calls
68  * #define DEBUG_CFG_LINES  to trace every line read from the config files
69  */
70
71 #include "httpd.h"
72 #include "http_main.h"
73 #include "http_log.h"
74 #include "http_protocol.h"
75 #if defined(SUNOS4)
76 /* stdio.h has been read in ap_config.h already. Add missing prototypes here: */
77 extern int fgetc(FILE *);
78 extern char *fgets(char *s, int, FILE*);
79 extern int fclose(FILE *);
80 #endif
81
82 /* A bunch of functions in util.c scan strings looking for certain characters.
83  * To make that more efficient we encode a lookup table.  The test_char_table
84  * is generated automatically by gen_test_char.c.
85  */
86 #include "test_char.h"
87
88 /* we assume the folks using this ensure 0 <= c < 256... which means
89  * you need a cast to (unsigned char) first, you can't just plug a
90  * char in here and get it to work, because if char is signed then it
91  * will first be sign extended.
92  */
93 #define TEST_CHAR(c, f) (test_char_table[(unsigned)(c)] & (f))
94
95 void ap_util_init(void)
96 {
97     /* nothing to do... previously there was run-time initialization of
98      * test_char_table here
99      */
100 }
101
102
103 API_VAR_EXPORT const char ap_month_snames[12][4] =
104 {
105     "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
106 };
107 API_VAR_EXPORT const char ap_day_snames[7][4] =
108 {
109     "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
110 };
111
112 API_EXPORT(char *) ap_get_time()
113 {
114   /* ZZZ When we abstract out time, this whole function should change to use
115      AP funcs. */
116     time_t t;
117     char *time_string;
118
119     t = time(NULL);
120     time_string = ctime(&t);
121     time_string[strlen(time_string) - 1] = '\0';
122     return (time_string);
123 }
124
125 /*
126  * Examine a field value (such as a media-/content-type) string and return
127  * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
128  */
129 API_EXPORT(char *) ap_field_noparam(pool *p, const char *intype)
130 {
131     const char *semi;
132
133     semi = strchr(intype, ';');
134     if (semi == NULL) {
135         return ap_pstrdup(p, intype);
136     } 
137     else {
138         while ((semi > intype) && ap_isspace(semi[-1])) {
139             semi--;
140         }
141         return ap_pstrndup(p, intype, semi - intype);
142     }
143 }
144
145 API_EXPORT(char *) ap_ht_time(pool *p, time_t t, const char *fmt, int gmt)
146 {
147   /* ZZZ this function can be replaced by calls to time formatting routines
148      in APR.  */
149     char ts[MAX_STRING_LEN];
150     char tf[MAX_STRING_LEN];
151     struct tm *tms;
152
153     tms = (gmt ? gmtime(&t) : localtime(&t));
154     if(gmt) {
155         /* Convert %Z to "GMT" and %z to "+0000";
156          * on hosts that do not have a time zone string in struct tm,
157          * strftime must assume its argument is local time.
158          */
159         const char *f;
160         char *strp;
161         for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
162             ; f++, strp++) {
163             if (*f != '%') continue;
164             switch (f[1]) {
165             case '%':
166                 *++strp = *++f;
167                 break;
168             case 'Z':
169                 *strp++ = 'G';
170                 *strp++ = 'M';
171                 *strp = 'T';
172                 f++;
173                 break;
174             case 'z': /* common extension */
175                 *strp++ = '+';
176                 *strp++ = '0';
177                 *strp++ = '0';
178                 *strp++ = '0';
179                 *strp = '0';
180                 f++;
181                 break;
182             }
183         }
184         *strp = '\0';
185         fmt = tf;
186     }
187
188     /* check return code? */
189     strftime(ts, MAX_STRING_LEN, fmt, tms);
190     ts[MAX_STRING_LEN - 1] = '\0';
191     return ap_pstrdup(p, ts);
192 }
193
194 API_EXPORT(char *) ap_gm_timestr_822(pool *p, time_t sec)
195 {
196     struct tm *tms;
197     char *date_str = ap_palloc(p, 48 * sizeof(char));
198     char *date_str_ptr = date_str;
199     int real_year;
200
201     tms = gmtime(&sec);    /* ZZZ replace with AP time routine */
202
203     /* Assumption: this is always 3 */
204     /* i = strlen(ap_day_snames[tms->tm_wday]); */
205     memcpy(date_str_ptr, ap_day_snames[tms->tm_wday], 3);
206     date_str_ptr += 3;
207     *date_str_ptr++ = ',';
208     *date_str_ptr++ = ' ';
209     *date_str_ptr++ = tms->tm_mday / 10 + '0';
210     *date_str_ptr++ = tms->tm_mday % 10 + '0';
211     *date_str_ptr++ = ' ';
212     /* Assumption: this is also always 3 */
213     /* i = strlen(ap_month_snames[tms->tm_mon]); */
214     memcpy(date_str_ptr, ap_month_snames[tms->tm_mon], 3);
215     date_str_ptr += 3;
216     *date_str_ptr++ = ' ';
217     real_year = 1900 + tms->tm_year;
218     /* This routine isn't y10k ready. */
219     *date_str_ptr++ = real_year / 1000 + '0';
220     *date_str_ptr++ = real_year % 1000 / 100 + '0';
221     *date_str_ptr++ = real_year % 100 / 10 + '0';
222     *date_str_ptr++ = real_year % 10 + '0';
223     *date_str_ptr++ = ' ';
224     *date_str_ptr++ = tms->tm_hour / 10 + '0';
225     *date_str_ptr++ = tms->tm_hour % 10 + '0';
226     *date_str_ptr++ = ':';
227     *date_str_ptr++ = tms->tm_min / 10 + '0';
228     *date_str_ptr++ = tms->tm_min % 10 + '0';
229     *date_str_ptr++ = ':';
230     *date_str_ptr++ = tms->tm_sec / 10 + '0';
231     *date_str_ptr++ = tms->tm_sec % 10 + '0';
232     *date_str_ptr++ = ' ';
233     *date_str_ptr++ = 'G';
234     *date_str_ptr++ = 'M';
235     *date_str_ptr++ = 'T';
236     *date_str_ptr = '\0';
237
238     return date_str;
239     /* RFC date format; as strftime '%a, %d %b %Y %T GMT' */
240
241     /* The equivalent using sprintf. Use this for more legible but slower code
242     return ap_psprintf(p,
243                 "%s, %.2d %s %d %.2d:%.2d:%.2d GMT", ap_day_snames[tms->tm_wday],
244                 tms->tm_mday, ap_month_snames[tms->tm_mon], tms->tm_year + 1900,
245                 tms->tm_hour, tms->tm_min, tms->tm_sec);
246     */
247 }
248
249 /* What a pain in the ass. */
250 #if defined(HAVE_GMTOFF)
251 API_EXPORT(struct tm *) ap_get_gmtoff(int *tz)
252 {
253     time_t tt = time(NULL);
254     struct tm *t;
255
256     t = localtime(&tt);
257     *tz = (int) (t->tm_gmtoff / 60);
258     return t;
259 }
260 #else
261 API_EXPORT(struct tm *) ap_get_gmtoff(int *tz)
262 {
263     time_t tt = time(NULL);
264     struct tm gmt;
265     struct tm *t;
266     int days, hours, minutes;
267
268     /* Assume we are never more than 24 hours away. */
269     gmt = *gmtime(&tt);         /* remember gmtime/localtime return ptr to static */
270     t = localtime(&tt);         /* buffer... so be careful */
271     days = t->tm_yday - gmt.tm_yday;
272     hours = ((days < -1 ? 24 : 1 < days ? -24 : days * 24)
273              + t->tm_hour - gmt.tm_hour);
274     minutes = hours * 60 + t->tm_min - gmt.tm_min;
275     *tz = minutes;
276     return t;
277 }
278 #endif
279
280 /* Roy owes Rob beer. */
281 /* Rob owes Roy dinner. */
282
283 /* These legacy comments would make a lot more sense if Roy hadn't
284  * replaced the old later_than() routine with util_date.c.
285  *
286  * Well, okay, they still wouldn't make any sense.
287  */
288
289 /* Match = 0, NoMatch = 1, Abort = -1
290  * Based loosely on sections of wildmat.c by Rich Salz
291  * Hmmm... shouldn't this really go component by component?
292  */
293 API_EXPORT(int) ap_strcmp_match(const char *str, const char *exp)
294 {
295     int x, y;
296
297     for (x = 0, y = 0; exp[y]; ++y, ++x) {
298         if ((!str[x]) && (exp[y] != '*'))
299             return -1;
300         if (exp[y] == '*') {
301             while (exp[++y] == '*');
302             if (!exp[y])
303                 return 0;
304             while (str[x]) {
305                 int ret;
306                 if ((ret = ap_strcmp_match(&str[x++], &exp[y])) != 1)
307                     return ret;
308             }
309             return -1;
310         }
311         else if ((exp[y] != '?') && (str[x] != exp[y]))
312             return 1;
313     }
314     return (str[x] != '\0');
315 }
316
317 API_EXPORT(int) ap_strcasecmp_match(const char *str, const char *exp)
318 {
319     int x, y;
320
321     for (x = 0, y = 0; exp[y]; ++y, ++x) {
322         if ((!str[x]) && (exp[y] != '*'))
323             return -1;
324         if (exp[y] == '*') {
325             while (exp[++y] == '*');
326             if (!exp[y])
327                 return 0;
328             while (str[x]) {
329                 int ret;
330                 if ((ret = ap_strcasecmp_match(&str[x++], &exp[y])) != 1)
331                     return ret;
332             }
333             return -1;
334         }
335         else if ((exp[y] != '?') && (ap_tolower(str[x]) != ap_tolower(exp[y])))
336             return 1;
337     }
338     return (str[x] != '\0');
339 }
340
341 API_EXPORT(int) ap_is_matchexp(const char *str)
342 {
343     register int x;
344
345     for (x = 0; str[x]; x++)
346         if ((str[x] == '*') || (str[x] == '?'))
347             return 1;
348     return 0;
349 }
350
351 /* 
352  * Apache stub function for the regex libraries regexec() to make sure the
353  * whole regex(3) API is available through the Apache (exported) namespace.
354  * This is especially important for the DSO situations of modules.
355  * DO NOT MAKE A MACRO OUT OF THIS FUNCTION!
356  */
357 API_EXPORT(int) ap_regexec(const regex_t *preg, const char *string,
358                            size_t nmatch, regmatch_t pmatch[], int eflags)
359 {
360     return regexec(preg, string, nmatch, pmatch, eflags);
361 }
362
363 API_EXPORT(size_t) ap_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
364 {
365     return regerror(errcode, preg, errbuf, errbuf_size);
366 }
367
368
369 /* This function substitutes for $0-$9, filling in regular expression
370  * submatches. Pass it the same nmatch and pmatch arguments that you
371  * passed ap_regexec(). pmatch should not be greater than the maximum number
372  * of subexpressions - i.e. one more than the re_nsub member of regex_t.
373  *
374  * input should be the string with the $-expressions, source should be the
375  * string that was matched against.
376  *
377  * It returns the substituted string, or NULL on error.
378  *
379  * Parts of this code are based on Henry Spencer's regsub(), from his
380  * AT&T V8 regexp package.
381  */
382
383 API_EXPORT(char *) ap_pregsub(pool *p, const char *input, const char *source,
384                            size_t nmatch, regmatch_t pmatch[])
385 {
386     const char *src = input;
387     char *dest, *dst;
388     char c;
389     size_t no;
390     int len;
391
392     if (!source)
393         return NULL;
394     if (!nmatch)
395         return ap_pstrdup(p, src);
396
397     /* First pass, find the size */
398
399     len = 0;
400
401     while ((c = *src++) != '\0') {
402         if (c == '&')
403             no = 0;
404         else if (c == '$' && ap_isdigit(*src))
405             no = *src++ - '0';
406         else
407             no = 10;
408
409         if (no > 9) {           /* Ordinary character. */
410             if (c == '\\' && (*src == '$' || *src == '&'))
411                 c = *src++;
412             len++;
413         }
414         else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
415             len += pmatch[no].rm_eo - pmatch[no].rm_so;
416         }
417
418     }
419
420     dest = dst = ap_pcalloc(p, len + 1);
421
422     /* Now actually fill in the string */
423
424     src = input;
425
426     while ((c = *src++) != '\0') {
427         if (c == '&')
428             no = 0;
429         else if (c == '$' && ap_isdigit(*src))
430             no = *src++ - '0';
431         else
432             no = 10;
433
434         if (no > 9) {           /* Ordinary character. */
435             if (c == '\\' && (*src == '$' || *src == '&'))
436                 c = *src++;
437             *dst++ = c;
438         }
439         else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
440             len = pmatch[no].rm_eo - pmatch[no].rm_so;
441             memcpy(dst, source + pmatch[no].rm_so, len);
442             dst += len;
443         }
444
445     }
446     *dst = '\0';
447
448     return dest;
449 }
450
451 /*
452  * Parse .. so we don't compromise security
453  */
454 API_EXPORT(void) ap_getparents(char *name)
455 {
456     int l, w;
457
458     /* Four paseses, as per RFC 1808 */
459     /* a) remove ./ path segments */
460
461     for (l = 0, w = 0; name[l] != '\0';) {
462         if (name[l] == '.' && name[l + 1] == '/' && (l == 0 || name[l - 1] == '/'))
463             l += 2;
464         else
465             name[w++] = name[l++];
466     }
467
468     /* b) remove trailing . path, segment */
469     if (w == 1 && name[0] == '.')
470         w--;
471     else if (w > 1 && name[w - 1] == '.' && name[w - 2] == '/')
472         w--;
473     name[w] = '\0';
474
475     /* c) remove all xx/../ segments. (including leading ../ and /../) */
476     l = 0;
477
478     while (name[l] != '\0') {
479         if (name[l] == '.' && name[l + 1] == '.' && name[l + 2] == '/' &&
480             (l == 0 || name[l - 1] == '/')) {
481             register int m = l + 3, n;
482
483             l = l - 2;
484             if (l >= 0) {
485                 while (l >= 0 && name[l] != '/')
486                     l--;
487                 l++;
488             }
489             else
490                 l = 0;
491             n = l;
492             while ((name[n] = name[m]))
493                 (++n, ++m);
494         }
495         else
496             ++l;
497     }
498
499     /* d) remove trailing xx/.. segment. */
500     if (l == 2 && name[0] == '.' && name[1] == '.')
501         name[0] = '\0';
502     else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.' && name[l - 3] == '/') {
503         l = l - 4;
504         if (l >= 0) {
505             while (l >= 0 && name[l] != '/')
506                 l--;
507             l++;
508         }
509         else
510             l = 0;
511         name[l] = '\0';
512     }
513 }
514
515 API_EXPORT(void) ap_no2slash(char *name)
516 {
517     char *d, *s;
518
519     s = d = name;
520
521 #ifdef WIN32
522     /* Check for UNC names.  Leave leading two slashes. */
523     if (s[0] == '/' && s[1] == '/')
524         *d++ = *s++;
525 #endif
526
527     while (*s) {
528         if ((*d++ = *s) == '/') {
529             do {
530                 ++s;
531             } while (*s == '/');
532         }
533         else {
534             ++s;
535         }
536     }
537     *d = '\0';
538 }
539
540
541 /*
542  * copy at most n leading directories of s into d
543  * d should be at least as large as s plus 1 extra byte
544  * assumes n > 0
545  * the return value is the ever useful pointer to the trailing \0 of d
546  *
547  * examples:
548  *    /a/b, 1  ==> /
549  *    /a/b, 2  ==> /a/
550  *    /a/b, 3  ==> /a/b/
551  *    /a/b, 4  ==> /a/b/
552  */
553 API_EXPORT(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
554 {
555     for (;;) {
556         if (*s == '\0' || (*s == '/' && (--n) == 0)) {
557             *d = '/';
558             break;
559         }
560         *d++ = *s++;
561     }
562     *++d = 0;
563     return (d);
564 }
565
566
567 /*
568  * return the parent directory name including trailing / of the file s
569  */
570 API_EXPORT(char *) ap_make_dirstr_parent(pool *p, const char *s)
571 {
572     char *last_slash = strrchr(s, '/');
573     char *d;
574     int l;
575
576     if (last_slash == NULL) {
577         /* XXX: well this is really broken if this happens */
578         return (ap_pstrdup(p, "/"));
579     }
580     l = (last_slash - s) + 1;
581     d = ap_palloc(p, l + 1);
582     memcpy(d, s, l);
583     d[l] = 0;
584     return (d);
585 }
586
587
588 /*
589  * This function is deprecated.  Use one of the preceeding two functions
590  * which are faster.
591  */
592 API_EXPORT(char *) ap_make_dirstr(pool *p, const char *s, int n)
593 {
594     register int x, f;
595     char *res;
596
597     for (x = 0, f = 0; s[x]; x++) {
598         if (s[x] == '/')
599             if ((++f) == n) {
600                 res = ap_palloc(p, x + 2);
601                 memcpy(res, s, x);
602                 res[x] = '/';
603                 res[x + 1] = '\0';
604                 return res;
605             }
606     }
607
608     if (s[strlen(s) - 1] == '/')
609         return ap_pstrdup(p, s);
610     else
611         return ap_pstrcat(p, s, "/", NULL);
612 }
613
614 API_EXPORT(int) ap_count_dirs(const char *path)
615 {
616     register int x, n;
617
618     for (x = 0, n = 0; path[x]; x++)
619         if (path[x] == '/')
620             n++;
621     return n;
622 }
623
624
625 API_EXPORT(void) ap_chdir_file(const char *file)
626 {
627     const char *x;
628     char buf[HUGE_STRING_LEN];
629
630     x = strrchr(file, '/');
631     if (x == NULL) {
632         chdir(file);
633     }
634     else if (x - file < sizeof(buf) - 1) {
635         memcpy(buf, file, x - file);
636         buf[x - file] = '\0';
637         chdir(buf);
638     }
639     /* XXX: well, this is a silly function, no method of reporting an
640      * error... ah well. */
641 }
642
643 API_EXPORT(char *) ap_getword_nc(pool *atrans, char **line, char stop)
644 {
645     return ap_getword(atrans, (const char **) line, stop);
646 }
647
648 API_EXPORT(char *) ap_getword(pool *atrans, const char **line, char stop)
649 {
650     char *pos = strchr(*line, stop);
651     char *res;
652
653     if (!pos) {
654         res = ap_pstrdup(atrans, *line);
655         *line += strlen(*line);
656         return res;
657     }
658
659     res = ap_pstrndup(atrans, *line, pos - *line);
660
661     while (*pos == stop) {
662         ++pos;
663     }
664
665     *line = pos;
666
667     return res;
668 }
669
670 API_EXPORT(char *) ap_getword_white_nc(pool *atrans, char **line)
671 {
672     return ap_getword_white(atrans, (const char **) line);
673 }
674
675 API_EXPORT(char *) ap_getword_white(pool *atrans, const char **line)
676 {
677     int pos = -1, x;
678     char *res;
679
680     for (x = 0; (*line)[x]; x++) {
681         if (ap_isspace((*line)[x])) {
682             pos = x;
683             break;
684         }
685     }
686
687     if (pos == -1) {
688         res = ap_pstrdup(atrans, *line);
689         *line += strlen(*line);
690         return res;
691     }
692
693     res = ap_palloc(atrans, pos + 1);
694     ap_cpystrn(res, *line, pos + 1);
695
696     while (ap_isspace((*line)[pos]))
697         ++pos;
698
699     *line += pos;
700
701     return res;
702 }
703
704 API_EXPORT(char *) ap_getword_nulls_nc(pool *atrans, char **line, char stop)
705 {
706     return ap_getword_nulls(atrans, (const char **) line, stop);
707 }
708
709 API_EXPORT(char *) ap_getword_nulls(pool *atrans, const char **line, char stop)
710 {
711     char *pos = strchr(*line, stop);
712     char *res;
713
714     if (!pos) {
715         res = ap_pstrdup(atrans, *line);
716         *line += strlen(*line);
717         return res;
718     }
719
720     res = ap_pstrndup(atrans, *line, pos - *line);
721
722     ++pos;
723
724     *line = pos;
725
726     return res;
727 }
728
729 /* Get a word, (new) config-file style --- quoted strings and backslashes
730  * all honored
731  */
732
733 static char *substring_conf(pool *p, const char *start, int len, char quote)
734 {
735     char *result = ap_palloc(p, len + 2);
736     char *resp = result;
737     int i;
738
739     for (i = 0; i < len; ++i) {
740         if (start[i] == '\\' && (start[i + 1] == '\\'
741                                  || (quote && start[i + 1] == quote)))
742             *resp++ = start[++i];
743         else
744             *resp++ = start[i];
745     }
746
747     *resp++ = '\0';
748     return result;
749 }
750
751 API_EXPORT(char *) ap_getword_conf_nc(pool *p, char **line)
752 {
753     return ap_getword_conf(p, (const char **) line);
754 }
755
756 API_EXPORT(char *) ap_getword_conf(pool *p, const char **line)
757 {
758     const char *str = *line, *strend;
759     char *res;
760     char quote;
761
762     while (*str && ap_isspace(*str))
763         ++str;
764
765     if (!*str) {
766         *line = str;
767         return "";
768     }
769
770     if ((quote = *str) == '"' || quote == '\'') {
771         strend = str + 1;
772         while (*strend && *strend != quote) {
773             if (*strend == '\\' && strend[1] && strend[1] == quote)
774                 strend += 2;
775             else
776                 ++strend;
777         }
778         res = substring_conf(p, str + 1, strend - str - 1, quote);
779
780         if (*strend == quote)
781             ++strend;
782     }
783     else {
784         strend = str;
785         while (*strend && !ap_isspace(*strend))
786             ++strend;
787
788         res = substring_conf(p, str, strend - str, 0);
789     }
790
791     while (*strend && ap_isspace(*strend))
792         ++strend;
793     *line = strend;
794     return res;
795 }
796
797 API_EXPORT(int) ap_cfg_closefile(configfile_t *cfp)
798 {
799 #ifdef DEBUG
800     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL, 
801         "Done with config file %s", cfp->name);
802 #endif
803     return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
804 }
805
806 /* Common structure that holds the file and pool for ap_pcfg_openfile */
807 typedef struct {
808     struct pool *pool;
809     FILE *file;
810 } poolfile_t;
811
812 static int cfg_close(void *param)
813 {
814     poolfile_t *cfp = (poolfile_t *) param;
815     return (ap_pfclose(cfp->pool, cfp->file));
816 }
817
818 static int cfg_getch(void *param)
819 {
820     poolfile_t *cfp = (poolfile_t *) param;
821     return (fgetc(cfp->file));
822 }
823
824 static void *cfg_getstr(void *buf, size_t bufsiz, void *param)
825 {
826     poolfile_t *cfp = (poolfile_t *) param;
827     return (fgets(buf, bufsiz, cfp->file));
828 }
829
830 /* Open a configfile_t as FILE, return open configfile_t struct pointer */
831 API_EXPORT(configfile_t *) ap_pcfg_openfile(pool *p, const char *name)
832 {
833     configfile_t *new_cfg;
834     poolfile_t *new_pfile;
835     FILE *file;
836     struct stat stbuf;
837     int saved_errno;
838
839     if (name == NULL) {
840         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, NULL,
841                "Internal error: pcfg_openfile() called with NULL filename");
842         return NULL;
843     }
844
845     if (!ap_os_is_filename_valid(name)) {
846         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, NULL,
847                     "Access to config file %s denied: not a valid filename",
848                     name);
849         errno = EACCES;
850         return NULL;
851     }
852  
853     /* ZZZ bopenf and use AP defines for flags. */
854     file = ap_pfopen(p, name, "r");
855 #ifdef DEBUG
856     saved_errno = errno;
857     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, NULL,
858                 "Opening config file %s (%s)",
859                 name, (file == NULL) ? strerror(errno) : "successful");
860     errno = saved_errno;
861 #endif
862     if (file == NULL)
863         return NULL;
864
865     if (fstat(fileno(file), &stbuf) == 0 &&
866         !S_ISREG(stbuf.st_mode) &&
867 #if defined(WIN32) || defined(OS2)
868         !(strcasecmp(name, "nul") == 0 ||
869           (strlen(name) >= 4 &&
870            strcasecmp(name + strlen(name) - 4, "/nul") == 0))) {
871 #else
872         strcmp(name, "/dev/null") != 0) {
873 #endif /* WIN32 || OS2 */
874         saved_errno = errno;
875         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, NULL,
876                     "Access to file %s denied by server: not a regular file",
877                     name);
878         ap_pfclose(p, file);
879         errno = saved_errno;
880         return NULL;
881     }
882
883     new_cfg = ap_palloc(p, sizeof(*new_cfg));
884     new_pfile = ap_palloc(p, sizeof(*new_pfile));
885     new_pfile->file = file;
886     new_pfile->pool = p;
887     new_cfg->param = new_pfile;
888     new_cfg->name = ap_pstrdup(p, name);
889     new_cfg->getch = (int (*)(void *)) cfg_getch;
890     new_cfg->getstr = (void *(*)(void *, size_t, void *)) cfg_getstr;
891     new_cfg->close = (int (*)(void *)) cfg_close;
892     new_cfg->line_number = 0;
893     return new_cfg;
894 }
895
896
897 /* Allocate a configfile_t handle with user defined functions and params */
898 API_EXPORT(configfile_t *) ap_pcfg_open_custom(pool *p, const char *descr,
899     void *param,
900     int(*getch)(void *param),
901     void *(*getstr) (void *buf, size_t bufsiz, void *param),
902     int(*close_func)(void *param))
903 {
904     configfile_t *new_cfg = ap_palloc(p, sizeof(*new_cfg));
905 #ifdef DEBUG
906     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, NULL, "Opening config handler %s", descr);
907 #endif
908     new_cfg->param = param;
909     new_cfg->name = descr;
910     new_cfg->getch = getch;
911     new_cfg->getstr = getstr;
912     new_cfg->close = close_func;
913     new_cfg->line_number = 0;
914     return new_cfg;
915 }
916
917
918 /* Read one character from a configfile_t */
919 API_EXPORT(int) ap_cfg_getc(configfile_t *cfp)
920 {
921     register int ch = cfp->getch(cfp->param);
922     if (ch == LF) 
923         ++cfp->line_number;
924     return ch;
925 }
926
927
928 /* Read one line from open configfile_t, strip LF, increase line number */
929 /* If custom handler does not define a getstr() function, read char by char */
930 API_EXPORT(int) ap_cfg_getline(char *buf, size_t bufsize, configfile_t *cfp)
931 {
932     /* If a "get string" function is defined, use it */
933     if (cfp->getstr != NULL) {
934         char *src, *dst;
935         char *cp;
936         char *cbuf = buf;
937         size_t cbufsize = bufsize;
938
939         while (1) {
940             ++cfp->line_number;
941             if (cfp->getstr(cbuf, cbufsize, cfp->param) == NULL)
942                 return 1;
943
944             /*
945              *  check for line continuation,
946              *  i.e. match [^\\]\\[\r]\n only
947              */
948             cp = cbuf;
949             while (cp < cbuf+cbufsize && *cp != '\0')
950                 cp++;
951             if (cp > cbuf && cp[-1] == LF) {
952                 cp--;
953                 if (cp > cbuf && cp[-1] == CR)
954                     cp--;
955                 if (cp > cbuf && cp[-1] == '\\') {
956                     cp--;
957                     if (!(cp > cbuf && cp[-1] == '\\')) {
958                         /*
959                          * line continuation requested -
960                          * then remove backslash and continue
961                          */
962                         cbufsize -= (cp-cbuf);
963                         cbuf = cp;
964                         continue;
965                     }
966                     else {
967                         /* 
968                          * no real continuation because escaped -
969                          * then just remove escape character
970                          */
971                         for ( ; cp < cbuf+cbufsize && *cp != '\0'; cp++)
972                             cp[0] = cp[1];
973                     }   
974                 }
975             }
976             break;
977         }
978
979         /*
980          * Leading and trailing white space is eliminated completely
981          */
982         src = buf;
983         while (ap_isspace(*src))
984             ++src;
985         /* blast trailing whitespace */
986         dst = &src[strlen(src)];
987         while (--dst >= src && ap_isspace(*dst))
988             *dst = '\0';
989         /* Zap leading whitespace by shifting */
990         if (src != buf)
991             for (dst = buf; (*dst++ = *src++) != '\0'; )
992                 ;
993
994 #ifdef DEBUG_CFG_LINES
995         ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL, "Read config: %s", buf);
996 #endif
997         return 0;
998     } else {
999         /* No "get string" function defined; read character by character */
1000         register int c;
1001         register size_t i = 0;
1002
1003         buf[0] = '\0';
1004         /* skip leading whitespace */
1005         do {
1006             c = cfp->getch(cfp->param);
1007         } while (c == '\t' || c == ' ');
1008
1009         if (c == EOF)
1010             return 1;
1011         
1012         if(bufsize < 2) {
1013             /* too small, assume caller is crazy */
1014             return 1;
1015         }
1016
1017         while (1) {
1018             if ((c == '\t') || (c == ' ')) {
1019                 buf[i++] = ' ';
1020                 while ((c == '\t') || (c == ' '))
1021                     c = cfp->getch(cfp->param);
1022             }
1023             if (c == CR) {
1024                 /* silently ignore CR (_assume_ that a LF follows) */
1025                 c = cfp->getch(cfp->param);
1026             }
1027             if (c == LF) {
1028                 /* increase line number and return on LF */
1029                 ++cfp->line_number;
1030             }
1031             if (c == EOF || c == 0x4 || c == LF || i >= (bufsize - 2)) {
1032                 /* 
1033                  *  check for line continuation
1034                  */
1035                 if (i > 0 && buf[i-1] == '\\') {
1036                     i--;
1037                     if (!(i > 0 && buf[i-1] == '\\')) {
1038                         /* line is continued */
1039                         c = cfp->getch(cfp->param);
1040                         continue;
1041                     }
1042                     /* else nothing needs be done because
1043                      * then the backslash is escaped and
1044                      * we just strip to a single one
1045                      */
1046                 }
1047                 /* blast trailing whitespace */
1048                 while (i > 0 && ap_isspace(buf[i - 1]))
1049                     --i;
1050                 buf[i] = '\0';
1051 #ifdef DEBUG_CFG_LINES
1052                 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL, "Read config: %s", buf);
1053 #endif
1054                 return 0;
1055             }
1056             buf[i] = c;
1057             ++i;
1058             c = cfp->getch(cfp->param);
1059         }
1060     }
1061 }
1062
1063 /* Size an HTTP header field list item, as separated by a comma.
1064  * The return value is a pointer to the beginning of the non-empty list item
1065  * within the original string (or NULL if there is none) and the address
1066  * of field is shifted to the next non-comma, non-whitespace character.
1067  * len is the length of the item excluding any beginning whitespace.
1068  */
1069 API_EXPORT(const char *) ap_size_list_item(const char **field, int *len)
1070 {
1071     const unsigned char *ptr = (const unsigned char *)*field;
1072     const unsigned char *token;
1073     int in_qpair, in_qstr, in_com;
1074
1075     /* Find first non-comma, non-whitespace byte */
1076
1077     while (*ptr == ',' || ap_isspace(*ptr))
1078         ++ptr;
1079
1080     token = ptr;
1081
1082     /* Find the end of this item, skipping over dead bits */
1083
1084     for (in_qpair = in_qstr = in_com = 0;
1085          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1086          ++ptr) {
1087
1088         if (in_qpair) {
1089             in_qpair = 0;
1090         }
1091         else {
1092             switch (*ptr) {
1093                 case '\\': in_qpair = 1;      /* quoted-pair         */
1094                            break;
1095                 case '"' : if (!in_com)       /* quoted string delim */
1096                                in_qstr = !in_qstr;
1097                            break;
1098                 case '(' : if (!in_qstr)      /* comment (may nest)  */
1099                                ++in_com;
1100                            break;
1101                 case ')' : if (in_com)        /* end comment         */
1102                                --in_com;
1103                            break;
1104                 default  : break;
1105             }
1106         }
1107     }
1108
1109     if ((*len = (ptr - token)) == 0) {
1110         *field = (const char *)ptr;
1111         return NULL;
1112     }
1113
1114     /* Advance field pointer to the next non-comma, non-white byte */
1115
1116     while (*ptr == ',' || ap_isspace(*ptr))
1117         ++ptr;
1118
1119     *field = (const char *)ptr;
1120     return (const char *)token;
1121 }
1122
1123 /* Retrieve an HTTP header field list item, as separated by a comma,
1124  * while stripping insignificant whitespace and lowercasing anything not in
1125  * a quoted string or comment.  The return value is a new string containing
1126  * the converted list item (or NULL if none) and the address pointed to by
1127  * field is shifted to the next non-comma, non-whitespace.
1128  */
1129 API_EXPORT(char *) ap_get_list_item(pool *p, const char **field)
1130 {
1131     const char *tok_start;
1132     const unsigned char *ptr;
1133     unsigned char *pos;
1134     char *token;
1135     int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1136
1137     /* Find the beginning and maximum length of the list item so that
1138      * we can allocate a buffer for the new string and reset the field.
1139      */
1140     if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1141         return NULL;
1142     }
1143     token = ap_palloc(p, tok_len + 1);
1144
1145     /* Scan the token again, but this time copy only the good bytes.
1146      * We skip extra whitespace and any whitespace around a '=', '/',
1147      * or ';' and lowercase normal characters not within a comment,
1148      * quoted-string or quoted-pair.
1149      */
1150     for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1151          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1152          ++ptr) {
1153
1154         if (in_qpair) {
1155             in_qpair = 0;
1156             *pos++ = *ptr;
1157         }
1158         else {
1159             switch (*ptr) {
1160                 case '\\': in_qpair = 1;
1161                            if (addspace == 1)
1162                                *pos++ = ' ';
1163                            *pos++ = *ptr;
1164                            addspace = 0;
1165                            break;
1166                 case '"' : if (!in_com)
1167                                in_qstr = !in_qstr;
1168                            if (addspace == 1)
1169                                *pos++ = ' ';
1170                            *pos++ = *ptr;
1171                            addspace = 0;
1172                            break;
1173                 case '(' : if (!in_qstr)
1174                                ++in_com;
1175                            if (addspace == 1)
1176                                *pos++ = ' ';
1177                            *pos++ = *ptr;
1178                            addspace = 0;
1179                            break;
1180                 case ')' : if (in_com)
1181                                --in_com;
1182                            *pos++ = *ptr;
1183                            addspace = 0;
1184                            break;
1185                 case ' ' :
1186                 case '\t': if (addspace)
1187                                break;
1188                            if (in_com || in_qstr)
1189                                *pos++ = *ptr;
1190                            else
1191                                addspace = 1;
1192                            break;
1193                 case '=' :
1194                 case '/' :
1195                 case ';' : if (!(in_com || in_qstr))
1196                                addspace = -1;
1197                            *pos++ = *ptr;
1198                            break;
1199                 default  : if (addspace == 1)
1200                                *pos++ = ' ';
1201                            *pos++ = (in_com || in_qstr) ? *ptr
1202                                                         : ap_tolower(*ptr);
1203                            addspace = 0;
1204                            break;
1205             }
1206         }
1207     }
1208     *pos = '\0';
1209
1210     return token;
1211 }
1212
1213 /* Find an item in canonical form (lowercase, no extra spaces) within
1214  * an HTTP field value list.  Returns 1 if found, 0 if not found.
1215  * This would be much more efficient if we stored header fields as
1216  * an array of list items as they are received instead of a plain string.
1217  */
1218 API_EXPORT(int) ap_find_list_item(pool *p, const char *line, const char *tok)
1219 {
1220     const unsigned char *pos;
1221     const unsigned char *ptr = (const unsigned char *)line;
1222     int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1223
1224     if (!line || !tok)
1225         return 0;
1226
1227     do {  /* loop for each item in line's list */
1228
1229         /* Find first non-comma, non-whitespace byte */
1230
1231         while (*ptr == ',' || ap_isspace(*ptr))
1232             ++ptr;
1233
1234         if (*ptr)
1235             good = 1;  /* until proven otherwise for this item */
1236         else
1237             break;     /* no items left and nothing good found */
1238
1239         /* We skip extra whitespace and any whitespace around a '=', '/',
1240          * or ';' and lowercase normal characters not within a comment,
1241          * quoted-string or quoted-pair.
1242          */
1243         for (pos = (const unsigned char *)tok;
1244              *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1245              ++ptr) {
1246
1247             if (in_qpair) {
1248                 in_qpair = 0;
1249                 if (good)
1250                     good = (*pos++ == *ptr);
1251             }
1252             else {
1253                 switch (*ptr) {
1254                     case '\\': in_qpair = 1;
1255                                if (addspace == 1)
1256                                    good = good && (*pos++ == ' ');
1257                                good = good && (*pos++ == *ptr);
1258                                addspace = 0;
1259                                break;
1260                     case '"' : if (!in_com)
1261                                    in_qstr = !in_qstr;
1262                                if (addspace == 1)
1263                                    good = good && (*pos++ == ' ');
1264                                good = good && (*pos++ == *ptr);
1265                                addspace = 0;
1266                                break;
1267                     case '(' : if (!in_qstr)
1268                                    ++in_com;
1269                                if (addspace == 1)
1270                                    good = good && (*pos++ == ' ');
1271                                good = good && (*pos++ == *ptr);
1272                                addspace = 0;
1273                                break;
1274                     case ')' : if (in_com)
1275                                    --in_com;
1276                                good = good && (*pos++ == *ptr);
1277                                addspace = 0;
1278                                break;
1279                     case ' ' :
1280                     case '\t': if (addspace || !good)
1281                                    break;
1282                                if (in_com || in_qstr)
1283                                    good = (*pos++ == *ptr);
1284                                else
1285                                    addspace = 1;
1286                                break;
1287                     case '=' :
1288                     case '/' :
1289                     case ';' : if (!(in_com || in_qstr))
1290                                    addspace = -1;
1291                                good = good && (*pos++ == *ptr);
1292                                break;
1293                     default  : if (!good)
1294                                    break;
1295                                if (addspace == 1)
1296                                    good = (*pos++ == ' ');
1297                                if (in_com || in_qstr)
1298                                    good = good && (*pos++ == *ptr);
1299                                else
1300                                    good = good && (*pos++ == ap_tolower(*ptr));
1301                                addspace = 0;
1302                                break;
1303                 }
1304             }
1305         }
1306         if (good && *pos)
1307             good = 0;          /* not good if only a prefix was matched */
1308
1309     } while (*ptr && !good);
1310
1311     return good;
1312 }
1313
1314
1315 /* Retrieve a token, spacing over it and returning a pointer to
1316  * the first non-white byte afterwards.  Note that these tokens
1317  * are delimited by semis and commas; and can also be delimited
1318  * by whitespace at the caller's option.
1319  */
1320
1321 API_EXPORT(char *) ap_get_token(pool *p, const char **accept_line, int accept_white)
1322 {
1323     const char *ptr = *accept_line;
1324     const char *tok_start;
1325     char *token;
1326     int tok_len;
1327
1328     /* Find first non-white byte */
1329
1330     while (*ptr && ap_isspace(*ptr))
1331         ++ptr;
1332
1333     tok_start = ptr;
1334
1335     /* find token end, skipping over quoted strings.
1336      * (comments are already gone).
1337      */
1338
1339     while (*ptr && (accept_white || !ap_isspace(*ptr))
1340            && *ptr != ';' && *ptr != ',') {
1341         if (*ptr++ == '"')
1342             while (*ptr)
1343                 if (*ptr++ == '"')
1344                     break;
1345     }
1346
1347     tok_len = ptr - tok_start;
1348     token = ap_pstrndup(p, tok_start, tok_len);
1349
1350     /* Advance accept_line pointer to the next non-white byte */
1351
1352     while (*ptr && ap_isspace(*ptr))
1353         ++ptr;
1354
1355     *accept_line = ptr;
1356     return token;
1357 }
1358
1359
1360 /* find http tokens, see the definition of token from RFC2068 */
1361 API_EXPORT(int) ap_find_token(pool *p, const char *line, const char *tok)
1362 {
1363     const unsigned char *start_token;
1364     const unsigned char *s;
1365
1366     if (!line)
1367         return 0;
1368
1369     s = (const unsigned char *)line;
1370     for (;;) {
1371         /* find start of token, skip all stop characters, note NUL
1372          * isn't a token stop, so we don't need to test for it
1373          */
1374         while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1375             ++s;
1376         }
1377         if (!*s) {
1378             return 0;
1379         }
1380         start_token = s;
1381         /* find end of the token */
1382         while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1383             ++s;
1384         }
1385         if (!strncasecmp((const char *)start_token, (const char *)tok, s - start_token)) {
1386             return 1;
1387         }
1388         if (!*s) {
1389             return 0;
1390         }
1391     }
1392 }
1393
1394
1395 API_EXPORT(int) ap_find_last_token(pool *p, const char *line, const char *tok)
1396 {
1397     int llen, tlen, lidx;
1398
1399     if (!line)
1400         return 0;
1401
1402     llen = strlen(line);
1403     tlen = strlen(tok);
1404     lidx = llen - tlen;
1405
1406     if ((lidx < 0) ||
1407         ((lidx > 0) && !(ap_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1408         return 0;
1409
1410     return (strncasecmp(&line[lidx], tok, tlen) == 0);
1411 }
1412
1413 API_EXPORT(char *) ap_escape_shell_cmd(pool *p, const char *str)
1414 {
1415     char *cmd;
1416     unsigned char *d;
1417     const unsigned char *s;
1418
1419     cmd = ap_palloc(p, 2 * strlen(str) + 1);    /* Be safe */
1420     d = (unsigned char *)cmd;
1421     s = (const unsigned char *)str;
1422     for (; *s; ++s) {
1423
1424 #if defined(OS2) || defined(WIN32)
1425         /* Don't allow '&' in parameters under OS/2. */
1426         /* This can be used to send commands to the shell. */
1427         if (*s == '&') {
1428             *d++ = ' ';
1429             continue;
1430         }
1431 #endif
1432
1433         if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1434             *d++ = '\\';
1435         }
1436         *d++ = *s;
1437     }
1438     *d = '\0';
1439
1440     return cmd;
1441 }
1442
1443 static char x2c(const char *what)
1444 {
1445     register char digit;
1446
1447 #ifndef CHARSET_EBCDIC
1448     digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
1449     digit *= 16;
1450     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
1451 #else /*CHARSET_EBCDIC*/
1452     char xstr[5];
1453     xstr[0]='0';
1454     xstr[1]='x';
1455     xstr[2]=what[0];
1456     xstr[3]=what[1];
1457     xstr[4]='\0';
1458     digit = os_toebcdic[0xFF & strtol(xstr, NULL, 16)];
1459 #endif /*CHARSET_EBCDIC*/
1460     return (digit);
1461 }
1462
1463 /*
1464  * Unescapes a URL.
1465  * Returns 0 on success, non-zero on error
1466  * Failure is due to
1467  *   bad % escape       returns BAD_REQUEST
1468  *
1469  *   decoding %00 -> \0
1470  *   decoding %2f -> /   (a special character)
1471  *                      returns NOT_FOUND
1472  */
1473 API_EXPORT(int) ap_unescape_url(char *url)
1474 {
1475     register int badesc, badpath;
1476     char *x, *y;
1477
1478     badesc = 0;
1479     badpath = 0;
1480     /* Initial scan for first '%'. Don't bother writing values before
1481      * seeing a '%' */
1482     y = strchr(url, '%');
1483     if (y == NULL) {
1484         return OK;
1485     }
1486     for (x = y; *y; ++x, ++y) {
1487         if (*y != '%')
1488             *x = *y;
1489         else {
1490             if (!ap_isxdigit(*(y + 1)) || !ap_isxdigit(*(y + 2))) {
1491                 badesc = 1;
1492                 *x = '%';
1493             }
1494             else {
1495                 *x = x2c(y + 1);
1496                 y += 2;
1497                 if (*x == '/' || *x == '\0')
1498                     badpath = 1;
1499             }
1500         }
1501     }
1502     *x = '\0';
1503     if (badesc)
1504         return BAD_REQUEST;
1505     else if (badpath)
1506         return NOT_FOUND;
1507     else
1508         return OK;
1509 }
1510
1511 API_EXPORT(char *) ap_construct_server(pool *p, const char *hostname,
1512                                     unsigned port, const request_rec *r)
1513 {
1514     if (ap_is_default_port(port, r))
1515         return ap_pstrdup(p, hostname);
1516     else {
1517         return ap_psprintf(p, "%s:%u", hostname, port);
1518     }
1519 }
1520
1521 /* c2x takes an unsigned, and expects the caller has guaranteed that
1522  * 0 <= what < 256... which usually means that you have to cast to
1523  * unsigned char first, because (unsigned)(char)(x) fist goes through
1524  * signed extension to an int before the unsigned cast.
1525  *
1526  * The reason for this assumption is to assist gcc code generation --
1527  * the unsigned char -> unsigned extension is already done earlier in
1528  * both uses of this code, so there's no need to waste time doing it
1529  * again.
1530  */
1531 static const char c2x_table[] = "0123456789abcdef";
1532
1533 static ap_inline unsigned char *c2x(unsigned what, unsigned char *where)
1534 {
1535     *where++ = '%';
1536     *where++ = c2x_table[what >> 4];
1537     *where++ = c2x_table[what & 0xf];
1538     return where;
1539 }
1540
1541 /*
1542  * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1543  * routine is (should be) OS independent.
1544  *
1545  * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1546  * cases if a ':' occurs before the first '/' in the URL, the URL should be
1547  * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1548  * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1549  * efficiency reasons, we don't use escape_path_segment(), which is provided for
1550  * reference. Again, RFC 1808 is where this stuff is defined.
1551  *
1552  * If partial is set, os_escape_path() assumes that the path will be appended to
1553  * something with a '/' in it (and thus does not prefix "./").
1554  */
1555
1556 API_EXPORT(char *) ap_escape_path_segment(pool *p, const char *segment)
1557 {
1558     char *copy = ap_palloc(p, 3 * strlen(segment) + 1);
1559     const unsigned char *s = (const unsigned char *)segment;
1560     unsigned char *d = (unsigned char *)copy;
1561     unsigned c;
1562
1563     while ((c = *s)) {
1564         if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1565             d = c2x(c, d);
1566         }
1567         else {
1568             *d++ = c;
1569         }
1570         ++s;
1571     }
1572     *d = '\0';
1573     return copy;
1574 }
1575
1576 API_EXPORT(char *) ap_os_escape_path(pool *p, const char *path, int partial)
1577 {
1578     char *copy = ap_palloc(p, 3 * strlen(path) + 3);
1579     const unsigned char *s = (const unsigned char *)path;
1580     unsigned char *d = (unsigned char *)copy;
1581     unsigned c;
1582
1583     if (!partial) {
1584         char *colon = strchr(path, ':');
1585         char *slash = strchr(path, '/');
1586
1587         if (colon && (!slash || colon < slash)) {
1588             *d++ = '.';
1589             *d++ = '/';
1590         }
1591     }
1592     while ((c = *s)) {
1593         if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1594             d = c2x(c, d);
1595         }
1596         else {
1597             *d++ = c;
1598         }
1599         ++s;
1600     }
1601     *d = '\0';
1602     return copy;
1603 }
1604
1605 /* ap_escape_uri is now a macro for os_escape_path */
1606
1607 API_EXPORT(char *) ap_escape_html(pool *p, const char *s)
1608 {
1609     int i, j;
1610     char *x;
1611
1612     /* first, count the number of extra characters */
1613     for (i = 0, j = 0; s[i] != '\0'; i++)
1614         if (s[i] == '<' || s[i] == '>')
1615             j += 3;
1616         else if (s[i] == '&')
1617             j += 4;
1618
1619     if (j == 0)
1620         return ap_pstrndup(p, s, i);
1621
1622     x = ap_palloc(p, i + j + 1);
1623     for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1624         if (s[i] == '<') {
1625             memcpy(&x[j], "&lt;", 4);
1626             j += 3;
1627         }
1628         else if (s[i] == '>') {
1629             memcpy(&x[j], "&gt;", 4);
1630             j += 3;
1631         }
1632         else if (s[i] == '&') {
1633             memcpy(&x[j], "&amp;", 5);
1634             j += 4;
1635         }
1636         else
1637             x[j] = s[i];
1638
1639     x[j] = '\0';
1640     return x;
1641 }
1642
1643 API_EXPORT(int) ap_is_directory(const char *path)
1644 {
1645     struct stat finfo;
1646
1647     /* ZZZ replace with AP File Info func. */
1648     if (stat(path, &finfo) == -1)
1649         return 0;               /* in error condition, just return no */
1650
1651     return (S_ISDIR(finfo.st_mode));
1652 }
1653
1654 API_EXPORT(char *) ap_make_full_path(pool *a, const char *src1,
1655                                   const char *src2)
1656 {
1657     register int x;
1658
1659     x = strlen(src1);
1660     if (x == 0)
1661         return ap_pstrcat(a, "/", src2, NULL);
1662
1663     if (src1[x - 1] != '/')
1664         return ap_pstrcat(a, src1, "/", src2, NULL);
1665     else
1666         return ap_pstrcat(a, src1, src2, NULL);
1667 }
1668
1669 /*
1670  * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
1671  */
1672 API_EXPORT(int) ap_is_url(const char *u)
1673 {
1674     register int x;
1675
1676     for (x = 0; u[x] != ':'; x++) {
1677         if ((!u[x]) ||
1678             ((!ap_isalpha(u[x])) && (!ap_isdigit(u[x])) &&
1679              (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
1680             return 0;
1681         }
1682     }
1683
1684     return (x ? 1 : 0);         /* If the first character is ':', it's broken, too */
1685 }
1686
1687 API_EXPORT(int) ap_can_exec(const struct stat *finfo)
1688 {
1689 #ifdef MULTIPLE_GROUPS
1690     int cnt;
1691 #endif
1692 #if defined(OS2) || defined(WIN32)
1693     /* OS/2 dosen't have Users and Groups */
1694     return 1;
1695 #else
1696     if (ap_user_id == finfo->st_uid)
1697         if (finfo->st_mode & S_IXUSR)
1698             return 1;
1699     if (ap_group_id == finfo->st_gid)
1700         if (finfo->st_mode & S_IXGRP)
1701             return 1;
1702 #ifdef MULTIPLE_GROUPS
1703     for (cnt = 0; cnt < NGROUPS_MAX; cnt++) {
1704         if (group_id_list[cnt] == finfo->st_gid)
1705             if (finfo->st_mode & S_IXGRP)
1706                 return 1;
1707     }
1708 #endif
1709     return (finfo->st_mode & S_IXOTH);
1710 #endif
1711 }
1712
1713 #ifdef NEED_STRDUP
1714 char *strdup(const char *str)
1715 {
1716     char *sdup;
1717
1718     if (!(sdup = (char *) malloc(strlen(str) + 1))) {
1719         fprintf(stderr, "Ouch!  Out of memory in our strdup()!\n");
1720         return NULL;
1721     }
1722     sdup = strcpy(sdup, str);
1723
1724     return sdup;
1725 }
1726 #endif
1727
1728 /* The following two routines were donated for SVR4 by Andreas Vogel */
1729 #ifdef NEED_STRCASECMP
1730 int strcasecmp(const char *a, const char *b)
1731 {
1732     const char *p = a;
1733     const char *q = b;
1734     for (p = a, q = b; *p && *q; p++, q++) {
1735         int diff = ap_tolower(*p) - ap_tolower(*q);
1736         if (diff)
1737             return diff;
1738     }
1739     if (*p)
1740         return 1;               /* p was longer than q */
1741     if (*q)
1742         return -1;              /* p was shorter than q */
1743     return 0;                   /* Exact match */
1744 }
1745
1746 #endif
1747
1748 #ifdef NEED_STRNCASECMP
1749 int strncasecmp(const char *a, const char *b, int n)
1750 {
1751     const char *p = a;
1752     const char *q = b;
1753
1754     for (p = a, q = b; /*NOTHING */ ; p++, q++) {
1755         int diff;
1756         if (p == a + n)
1757             return 0;           /*   Match up to n characters */
1758         if (!(*p && *q))
1759             return *p - *q;
1760         diff = ap_tolower(*p) - ap_tolower(*q);
1761         if (diff)
1762             return diff;
1763     }
1764     /*NOTREACHED */
1765 }
1766 #endif
1767
1768 /* The following routine was donated for UTS21 by dwd@bell-labs.com */
1769 #ifdef NEED_STRSTR
1770 char *strstr(char *s1, char *s2)
1771 {
1772     char *p1, *p2;
1773     if (*s2 == '\0') {
1774         /* an empty s2 */
1775         return(s1);
1776     }
1777     while((s1 = strchr(s1, *s2)) != NULL) {
1778         /* found first character of s2, see if the rest matches */
1779         p1 = s1;
1780         p2 = s2;
1781         while (*++p1 == *++p2) {
1782             if (*p1 == '\0') {
1783                 /* both strings ended together */
1784                 return(s1);
1785             }
1786         }
1787         if (*p2 == '\0') {
1788             /* second string ended, a match */
1789             break;
1790         }
1791         /* didn't find a match here, try starting at next character in s1 */
1792         s1++;
1793     }
1794     return(s1);
1795 }
1796 #endif
1797
1798 #ifdef NEED_INITGROUPS
1799 int initgroups(const char *name, gid_t basegid)
1800 {
1801 #if defined(QNX) || defined(MPE) || defined(BEOS) || defined(_OSD_POSIX) || defined(TPF) || defined(__TANDEM)
1802 /* QNX, MPE and BeOS do not appear to support supplementary groups. */
1803     return 0;
1804 #else /* ndef QNX */
1805     gid_t groups[NGROUPS_MAX];
1806     struct group *g;
1807     int index = 0;
1808
1809     setgrent();
1810
1811     groups[index++] = basegid;
1812
1813     while (index < NGROUPS_MAX && ((g = getgrent()) != NULL))
1814         if (g->gr_gid != basegid) {
1815             char **names;
1816
1817             for (names = g->gr_mem; *names != NULL; ++names)
1818                 if (!strcmp(*names, name))
1819                     groups[index++] = g->gr_gid;
1820         }
1821
1822     endgrent();
1823
1824     return setgroups(index, groups);
1825 #endif /* def QNX */
1826 }
1827 #endif /* def NEED_INITGROUPS */
1828
1829 #ifdef NEED_WAITPID
1830 /* From ikluft@amdahl.com
1831  * this is not ideal but it works for SVR3 variants
1832  * Modified by dwd@bell-labs.com to call wait3 instead of wait because
1833  *   apache started to use the WNOHANG option.
1834  */
1835 int waitpid(pid_t pid, int *statusp, int options)
1836 {
1837     int tmp_pid;
1838     if (kill(pid, 0) == -1) {
1839         errno = ECHILD;
1840         return -1;
1841     }
1842     while (((tmp_pid = wait3(statusp, options, 0)) != pid) &&
1843                 (tmp_pid != -1) && (tmp_pid != 0) && (pid != -1))
1844         ;
1845     return tmp_pid;
1846 }
1847 #endif
1848
1849 API_EXPORT(int) ap_ind(const char *s, char c)
1850 {
1851     register int x;
1852
1853     for (x = 0; s[x]; x++)
1854         if (s[x] == c)
1855             return x;
1856
1857     return -1;
1858 }
1859
1860 API_EXPORT(int) ap_rind(const char *s, char c)
1861 {
1862     register int x;
1863
1864     for (x = strlen(s) - 1; x != -1; x--)
1865         if (s[x] == c)
1866             return x;
1867
1868     return -1;
1869 }
1870
1871 API_EXPORT(void) ap_str_tolower(char *str)
1872 {
1873     while (*str) {
1874         *str = ap_tolower(*str);
1875         ++str;
1876     }
1877 }
1878
1879 API_EXPORT(uid_t) ap_uname2id(const char *name)
1880 {
1881 #ifdef WIN32
1882     return (1);
1883 #else
1884     struct passwd *ent;
1885
1886     if (name[0] == '#')
1887         return (atoi(&name[1]));
1888
1889     if (!(ent = getpwnam(name))) {
1890         fprintf(stderr, "%s: bad user name %s\n", ap_server_argv0, name);
1891         exit(1);
1892     }
1893     return (ent->pw_uid);
1894 #endif
1895 }
1896
1897 API_EXPORT(gid_t) ap_gname2id(const char *name)
1898 {
1899 #ifdef WIN32
1900     return (1);
1901 #else
1902     struct group *ent;
1903
1904     if (name[0] == '#')
1905         return (atoi(&name[1]));
1906
1907     if (!(ent = getgrnam(name))) {
1908         fprintf(stderr, "%s: bad group name %s\n", ap_server_argv0, name);
1909         exit(1);
1910     }
1911     return (ent->gr_gid);
1912 #endif
1913 }
1914
1915
1916 /*
1917  * Parses a host of the form <address>[:port]
1918  * :port is permitted if 'port' is not NULL
1919  */
1920 unsigned long ap_get_virthost_addr(char *w, unsigned short *ports)
1921 {
1922   /* ZZZ Redesign for AP func changes */
1923     struct hostent *hep;
1924     unsigned long my_addr;
1925     char *p;
1926
1927     p = strchr(w, ':');
1928     if (ports != NULL) {
1929         *ports = 0;
1930         if (p != NULL && strcmp(p + 1, "*") != 0)
1931             *ports = atoi(p + 1);
1932     }
1933
1934     if (p != NULL)
1935         *p = '\0';
1936     if (strcmp(w, "*") == 0) {
1937         if (p != NULL)
1938             *p = ':';
1939         return htonl(INADDR_ANY);
1940     }
1941
1942     my_addr = ap_inet_addr((char *)w);
1943     if (my_addr != INADDR_NONE) {
1944         if (p != NULL)
1945             *p = ':';
1946         return my_addr;
1947     }
1948
1949     hep = gethostbyname(w);
1950
1951     if ((!hep) || (hep->h_addrtype != AF_INET || !hep->h_addr_list[0])) {
1952         fprintf(stderr, "Cannot resolve host name %s --- exiting!\n", w);
1953         exit(1);
1954     }
1955
1956     if (hep->h_addr_list[1]) {
1957         fprintf(stderr, "Host %s has multiple addresses ---\n", w);
1958         fprintf(stderr, "you must choose one explicitly for use as\n");
1959         fprintf(stderr, "a virtual host.  Exiting!!!\n");
1960         exit(1);
1961     }
1962
1963     if (p != NULL)
1964         *p = ':';
1965
1966     return ((struct in_addr *) (hep->h_addr))->s_addr;
1967 }
1968
1969
1970 static char *find_fqdn(pool *a, struct hostent *p)
1971 {
1972     int x;
1973
1974     if (!strchr(p->h_name, '.')) {
1975         for (x = 0; p->h_aliases[x]; ++x) {
1976             if (strchr(p->h_aliases[x], '.') &&
1977                 (!strncasecmp(p->h_aliases[x], p->h_name, strlen(p->h_name))))
1978                 return ap_pstrdup(a, p->h_aliases[x]);
1979         }
1980         return NULL;
1981     }
1982     return ap_pstrdup(a, (void *) p->h_name);
1983 }
1984
1985 char *ap_get_local_host(pool *a)
1986 {
1987 #ifndef MAXHOSTNAMELEN
1988 #define MAXHOSTNAMELEN 256
1989 #endif
1990     char str[MAXHOSTNAMELEN + 1];
1991     char *server_hostname;
1992     struct hostent *p;
1993
1994     /* ZZZ change to use AP funcs. */
1995 #ifdef BEOS
1996     if (gethostname(str, sizeof(str) - 1) == 0)
1997 #else
1998     if (gethostname(str, sizeof(str) - 1) != 0)
1999 #endif
2000     {
2001         perror("Unable to gethostname");
2002         exit(1);
2003     }
2004     str[MAXHOSTNAMELEN] = '\0';
2005     if ((!(p = gethostbyname(str))) || (!(server_hostname = find_fqdn(a, p)))) {
2006         fprintf(stderr, "%s: cannot determine local host name.\n",
2007                 ap_server_argv0);
2008         fprintf(stderr, "Use the ServerName directive to set it manually.\n");
2009         exit(1);
2010     }
2011
2012     return server_hostname;
2013 }
2014
2015 /* simple 'pool' alloc()ing glue to ap_base64.c
2016  */
2017 API_EXPORT(char *) ap_pbase64decode(pool *p, const char *bufcoded)
2018 {
2019     char *decoded;
2020     int l;
2021
2022     decoded = (char *) ap_palloc(p, 1 + ap_base64decode_len(bufcoded));
2023     l = ap_base64decode(decoded, bufcoded);
2024     decoded[l] = '\0'; /* make binary sequence into string */
2025
2026     return decoded;
2027 }
2028
2029 API_EXPORT(char *) ap_pbase64encode(pool *p, char *string) 
2030
2031     char *encoded;
2032     int l = strlen(string);
2033
2034     encoded = (char *) ap_palloc(p, 1 + ap_base64encode_len(l));
2035     l = ap_base64encode(encoded, string, l);
2036     encoded[l] = '\0'; /* make binary sequence into string */
2037
2038     return encoded;
2039 }
2040
2041 /* deprecated names for the above two functions, here for compatibility
2042  */
2043 API_EXPORT(char *) ap_uudecode(pool *p, const char *bufcoded)
2044 {
2045     return ap_pbase64decode(p, bufcoded);
2046 }
2047
2048 API_EXPORT(char *) ap_uuencode(pool *p, char *string) 
2049
2050     return ap_pbase64encode(p, string);
2051 }
2052
2053 #ifdef OS2
2054 void os2pathname(char *path)
2055 {
2056     char newpath[MAX_STRING_LEN];
2057     int loop;
2058     int offset;
2059
2060     offset = 0;
2061     for (loop = 0; loop < (strlen(path) + 1) && loop < sizeof(newpath) - 1; loop++) {
2062         if (path[loop] == '/') {
2063             newpath[offset] = '\\';
2064             /*
2065                offset = offset + 1;
2066                newpath[offset] = '\\';
2067              */
2068         }
2069         else
2070             newpath[offset] = path[loop];
2071         offset = offset + 1;
2072     };
2073     /* Debugging code */
2074     /* fprintf(stderr, "%s \n", newpath); */
2075
2076     strcpy(path, newpath);
2077 };
2078
2079 /* quotes in the string are doubled up.
2080  * Used to escape quotes in args passed to OS/2's cmd.exe
2081  */
2082 char *ap_double_quotes(pool *p, char *str)
2083 {
2084     int num_quotes = 0;
2085     int len = 0;
2086     char *quote_doubled_str, *dest;
2087     
2088     while (str[len]) {
2089         num_quotes += str[len++] == '\"';
2090     }
2091     
2092     quote_doubled_str = ap_palloc(p, len + num_quotes + 1);
2093     dest = quote_doubled_str;
2094     
2095     while (*str) {
2096         if (*str == '\"')
2097             *(dest++) = '\"';
2098         *(dest++) = *(str++);
2099     }
2100     
2101     *dest = 0;
2102     return quote_doubled_str;
2103 }
2104 #endif
2105
2106
2107 #ifdef NEED_STRERROR
2108 char *
2109      strerror(int err)
2110 {
2111
2112     char *p;
2113     extern char *const sys_errlist[];
2114
2115     p = sys_errlist[err];
2116     return (p);
2117 }
2118 #endif
2119
2120 #if defined(NEED_DIFFTIME)
2121 double difftime(time_t time1, time_t time0)
2122 {
2123     return (time1 - time0);
2124 }
2125 #endif
2126
2127 /* we want to downcase the type/subtype for comparison purposes
2128  * but nothing else because ;parameter=foo values are case sensitive.
2129  * XXX: in truth we want to downcase parameter names... but really,
2130  * apache has never handled parameters and such correctly.  You
2131  * also need to compress spaces and such to be able to compare
2132  * properly. -djg
2133  */
2134 API_EXPORT(void) ap_content_type_tolower(char *str)
2135 {
2136     char *semi;
2137
2138     semi = strchr(str, ';');
2139     if (semi) {
2140         *semi = '\0';
2141     }
2142     while (*str) {
2143         *str = ap_tolower(*str);
2144         ++str;
2145     }
2146     if (semi) {
2147         *semi = ';';
2148     }
2149 }
2150
2151 /*
2152  * Given a string, replace any bare " with \" .
2153  */
2154 API_EXPORT(char *) ap_escape_quotes (pool *p, const char *instring)
2155 {
2156     int newlen = 0;
2157     const char *inchr = instring;
2158     char *outchr, *outstring;
2159
2160     /*
2161      * Look through the input string, jogging the length of the output
2162      * string up by an extra byte each time we find an unescaped ".
2163      */
2164     while (*inchr != '\0') {
2165         newlen++;
2166         if (*inchr == '"') {
2167             newlen++;
2168         }
2169         /*
2170          * If we find a slosh, and it's not the last byte in the string,
2171          * it's escaping something - advance past both bytes.
2172          */
2173         if ((*inchr == '\\') && (inchr[1] != '\0')) {
2174             inchr++;
2175             newlen++;
2176         }
2177         inchr++;
2178     }
2179     outstring = ap_palloc(p, newlen + 1);
2180     inchr = instring;
2181     outchr = outstring;
2182     /*
2183      * Now copy the input string to the output string, inserting a slosh
2184      * in front of every " that doesn't already have one.
2185      */
2186     while (*inchr != '\0') {
2187         if ((*inchr == '\\') && (inchr[1] != '\0')) {
2188             *outchr++ = *inchr++;
2189             *outchr++ = *inchr++;
2190         }
2191         if (*inchr == '"') {
2192             *outchr++ = '\\';
2193         }
2194         if (*inchr != '\0') {
2195             *outchr++ = *inchr++;
2196         }
2197     }
2198     *outchr = '\0';
2199     return outstring;
2200 }