]> granicus.if.org Git - apache/blob - server/util.c
Odd comments and leftover bits from the pthreads version.
[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         *d = *s;
557         if (*d == '\0') {
558             *d = '/';
559             break;
560         }
561         if (*d == '/' && (--n) == 0)
562             break;
563         ++d;
564         ++s;
565     }
566     *++d = 0;
567     return (d);
568 }
569
570
571 /*
572  * return the parent directory name including trailing / of the file s
573  */
574 API_EXPORT(char *) ap_make_dirstr_parent(pool *p, const char *s)
575 {
576     char *last_slash = strrchr(s, '/');
577     char *d;
578     int l;
579
580     if (last_slash == NULL) {
581         /* XXX: well this is really broken if this happens */
582         return (ap_pstrdup(p, "/"));
583     }
584     l = (last_slash - s) + 1;
585     d = ap_palloc(p, l + 1);
586     memcpy(d, s, l);
587     d[l] = 0;
588     return (d);
589 }
590
591
592 /*
593  * This function is deprecated.  Use one of the preceeding two functions
594  * which are faster.
595  */
596 API_EXPORT(char *) ap_make_dirstr(pool *p, const char *s, int n)
597 {
598     register int x, f;
599     char *res;
600
601     for (x = 0, f = 0; s[x]; x++) {
602         if (s[x] == '/')
603             if ((++f) == n) {
604                 res = ap_palloc(p, x + 2);
605                 memcpy(res, s, x);
606                 res[x] = '/';
607                 res[x + 1] = '\0';
608                 return res;
609             }
610     }
611
612     if (s[strlen(s) - 1] == '/')
613         return ap_pstrdup(p, s);
614     else
615         return ap_pstrcat(p, s, "/", NULL);
616 }
617
618 API_EXPORT(int) ap_count_dirs(const char *path)
619 {
620     register int x, n;
621
622     for (x = 0, n = 0; path[x]; x++)
623         if (path[x] == '/')
624             n++;
625     return n;
626 }
627
628
629 API_EXPORT(void) ap_chdir_file(const char *file)
630 {
631     const char *x;
632     char buf[HUGE_STRING_LEN];
633
634     x = strrchr(file, '/');
635     if (x == NULL) {
636         chdir(file);
637     }
638     else if (x - file < sizeof(buf) - 1) {
639         memcpy(buf, file, x - file);
640         buf[x - file] = '\0';
641         chdir(buf);
642     }
643     /* XXX: well, this is a silly function, no method of reporting an
644      * error... ah well. */
645 }
646
647 API_EXPORT(char *) ap_getword_nc(pool *atrans, char **line, char stop)
648 {
649     return ap_getword(atrans, (const char **) line, stop);
650 }
651
652 API_EXPORT(char *) ap_getword(pool *atrans, const char **line, char stop)
653 {
654     char *pos = strchr(*line, stop);
655     char *res;
656
657     if (!pos) {
658         res = ap_pstrdup(atrans, *line);
659         *line += strlen(*line);
660         return res;
661     }
662
663     res = ap_pstrndup(atrans, *line, pos - *line);
664
665     while (*pos == stop) {
666         ++pos;
667     }
668
669     *line = pos;
670
671     return res;
672 }
673
674 API_EXPORT(char *) ap_getword_white_nc(pool *atrans, char **line)
675 {
676     return ap_getword_white(atrans, (const char **) line);
677 }
678
679 API_EXPORT(char *) ap_getword_white(pool *atrans, const char **line)
680 {
681     int pos = -1, x;
682     char *res;
683
684     for (x = 0; (*line)[x]; x++) {
685         if (ap_isspace((*line)[x])) {
686             pos = x;
687             break;
688         }
689     }
690
691     if (pos == -1) {
692         res = ap_pstrdup(atrans, *line);
693         *line += strlen(*line);
694         return res;
695     }
696
697     res = ap_palloc(atrans, pos + 1);
698     ap_cpystrn(res, *line, pos + 1);
699
700     while (ap_isspace((*line)[pos]))
701         ++pos;
702
703     *line += pos;
704
705     return res;
706 }
707
708 API_EXPORT(char *) ap_getword_nulls_nc(pool *atrans, char **line, char stop)
709 {
710     return ap_getword_nulls(atrans, (const char **) line, stop);
711 }
712
713 API_EXPORT(char *) ap_getword_nulls(pool *atrans, const char **line, char stop)
714 {
715     char *pos = strchr(*line, stop);
716     char *res;
717
718     if (!pos) {
719         res = ap_pstrdup(atrans, *line);
720         *line += strlen(*line);
721         return res;
722     }
723
724     res = ap_pstrndup(atrans, *line, pos - *line);
725
726     ++pos;
727
728     *line = pos;
729
730     return res;
731 }
732
733 /* Get a word, (new) config-file style --- quoted strings and backslashes
734  * all honored
735  */
736
737 static char *substring_conf(pool *p, const char *start, int len, char quote)
738 {
739     char *result = ap_palloc(p, len + 2);
740     char *resp = result;
741     int i;
742
743     for (i = 0; i < len; ++i) {
744         if (start[i] == '\\' && (start[i + 1] == '\\'
745                                  || (quote && start[i + 1] == quote)))
746             *resp++ = start[++i];
747         else
748             *resp++ = start[i];
749     }
750
751     *resp++ = '\0';
752     return result;
753 }
754
755 API_EXPORT(char *) ap_getword_conf_nc(pool *p, char **line)
756 {
757     return ap_getword_conf(p, (const char **) line);
758 }
759
760 API_EXPORT(char *) ap_getword_conf(pool *p, const char **line)
761 {
762     const char *str = *line, *strend;
763     char *res;
764     char quote;
765
766     while (*str && ap_isspace(*str))
767         ++str;
768
769     if (!*str) {
770         *line = str;
771         return "";
772     }
773
774     if ((quote = *str) == '"' || quote == '\'') {
775         strend = str + 1;
776         while (*strend && *strend != quote) {
777             if (*strend == '\\' && strend[1] && strend[1] == quote)
778                 strend += 2;
779             else
780                 ++strend;
781         }
782         res = substring_conf(p, str + 1, strend - str - 1, quote);
783
784         if (*strend == quote)
785             ++strend;
786     }
787     else {
788         strend = str;
789         while (*strend && !ap_isspace(*strend))
790             ++strend;
791
792         res = substring_conf(p, str, strend - str, 0);
793     }
794
795     while (*strend && ap_isspace(*strend))
796         ++strend;
797     *line = strend;
798     return res;
799 }
800
801 API_EXPORT(int) ap_cfg_closefile(configfile_t *cfp)
802 {
803 #ifdef DEBUG
804     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL, 
805         "Done with config file %s", cfp->name);
806 #endif
807     return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
808 }
809
810 /* Common structure that holds the file and pool for ap_pcfg_openfile */
811 typedef struct {
812     struct pool *pool;
813     FILE *file;
814 } poolfile_t;
815
816 static int cfg_close(void *param)
817 {
818     poolfile_t *cfp = (poolfile_t *) param;
819     return (ap_pfclose(cfp->pool, cfp->file));
820 }
821
822 static int cfg_getch(void *param)
823 {
824     poolfile_t *cfp = (poolfile_t *) param;
825     return (fgetc(cfp->file));
826 }
827
828 static void *cfg_getstr(void *buf, size_t bufsiz, void *param)
829 {
830     poolfile_t *cfp = (poolfile_t *) param;
831     return (fgets(buf, bufsiz, cfp->file));
832 }
833
834 /* Open a configfile_t as FILE, return open configfile_t struct pointer */
835 API_EXPORT(configfile_t *) ap_pcfg_openfile(pool *p, const char *name)
836 {
837     configfile_t *new_cfg;
838     poolfile_t *new_pfile;
839     FILE *file;
840     struct stat stbuf;
841     int saved_errno;
842
843     if (name == NULL) {
844         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, NULL,
845                "Internal error: pcfg_openfile() called with NULL filename");
846         return NULL;
847     }
848
849     if (!ap_os_is_filename_valid(name)) {
850         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, NULL,
851                     "Access to config file %s denied: not a valid filename",
852                     name);
853         errno = EACCES;
854         return NULL;
855     }
856  
857     /* ZZZ bopenf and use AP defines for flags. */
858     file = ap_pfopen(p, name, "r");
859 #ifdef DEBUG
860     saved_errno = errno;
861     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, NULL,
862                 "Opening config file %s (%s)",
863                 name, (file == NULL) ? strerror(errno) : "successful");
864     errno = saved_errno;
865 #endif
866     if (file == NULL)
867         return NULL;
868
869     if (fstat(fileno(file), &stbuf) == 0 &&
870         !S_ISREG(stbuf.st_mode) &&
871 #if defined(WIN32) || defined(OS2)
872         !(strcasecmp(name, "nul") == 0 ||
873           (strlen(name) >= 4 &&
874            strcasecmp(name + strlen(name) - 4, "/nul") == 0))) {
875 #else
876         strcmp(name, "/dev/null") != 0) {
877 #endif /* WIN32 || OS2 */
878         saved_errno = errno;
879         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, NULL,
880                     "Access to file %s denied by server: not a regular file",
881                     name);
882         ap_pfclose(p, file);
883         errno = saved_errno;
884         return NULL;
885     }
886
887     new_cfg = ap_palloc(p, sizeof(*new_cfg));
888     new_pfile = ap_palloc(p, sizeof(*new_pfile));
889     new_pfile->file = file;
890     new_pfile->pool = p;
891     new_cfg->param = new_pfile;
892     new_cfg->name = ap_pstrdup(p, name);
893     new_cfg->getch = (int (*)(void *)) cfg_getch;
894     new_cfg->getstr = (void *(*)(void *, size_t, void *)) cfg_getstr;
895     new_cfg->close = (int (*)(void *)) cfg_close;
896     new_cfg->line_number = 0;
897     return new_cfg;
898 }
899
900
901 /* Allocate a configfile_t handle with user defined functions and params */
902 API_EXPORT(configfile_t *) ap_pcfg_open_custom(pool *p, const char *descr,
903     void *param,
904     int(*getch)(void *param),
905     void *(*getstr) (void *buf, size_t bufsiz, void *param),
906     int(*close_func)(void *param))
907 {
908     configfile_t *new_cfg = ap_palloc(p, sizeof(*new_cfg));
909 #ifdef DEBUG
910     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, NULL, "Opening config handler %s", descr);
911 #endif
912     new_cfg->param = param;
913     new_cfg->name = descr;
914     new_cfg->getch = getch;
915     new_cfg->getstr = getstr;
916     new_cfg->close = close_func;
917     new_cfg->line_number = 0;
918     return new_cfg;
919 }
920
921
922 /* Read one character from a configfile_t */
923 API_EXPORT(int) ap_cfg_getc(configfile_t *cfp)
924 {
925     register int ch = cfp->getch(cfp->param);
926     if (ch == LF) 
927         ++cfp->line_number;
928     return ch;
929 }
930
931
932 /* Read one line from open configfile_t, strip LF, increase line number */
933 /* If custom handler does not define a getstr() function, read char by char */
934 API_EXPORT(int) ap_cfg_getline(char *buf, size_t bufsize, configfile_t *cfp)
935 {
936     /* If a "get string" function is defined, use it */
937     if (cfp->getstr != NULL) {
938         char *src, *dst;
939         char *cp;
940         char *cbuf = buf;
941         size_t cbufsize = bufsize;
942
943         while (1) {
944             ++cfp->line_number;
945             if (cfp->getstr(cbuf, cbufsize, cfp->param) == NULL)
946                 return 1;
947
948             /*
949              *  check for line continuation,
950              *  i.e. match [^\\]\\[\r]\n only
951              */
952             cp = cbuf;
953             while (cp < cbuf+cbufsize && *cp != '\0')
954                 cp++;
955             if (cp > cbuf && cp[-1] == LF) {
956                 cp--;
957                 if (cp > cbuf && cp[-1] == CR)
958                     cp--;
959                 if (cp > cbuf && cp[-1] == '\\') {
960                     cp--;
961                     if (!(cp > cbuf && cp[-1] == '\\')) {
962                         /*
963                          * line continuation requested -
964                          * then remove backslash and continue
965                          */
966                         cbufsize -= (cp-cbuf);
967                         cbuf = cp;
968                         continue;
969                     }
970                     else {
971                         /* 
972                          * no real continuation because escaped -
973                          * then just remove escape character
974                          */
975                         for ( ; cp < cbuf+cbufsize && *cp != '\0'; cp++)
976                             cp[0] = cp[1];
977                     }   
978                 }
979             }
980             break;
981         }
982
983         /*
984          * Leading and trailing white space is eliminated completely
985          */
986         src = buf;
987         while (ap_isspace(*src))
988             ++src;
989         /* blast trailing whitespace */
990         dst = &src[strlen(src)];
991         while (--dst >= src && ap_isspace(*dst))
992             *dst = '\0';
993         /* Zap leading whitespace by shifting */
994         if (src != buf)
995             for (dst = buf; (*dst++ = *src++) != '\0'; )
996                 ;
997
998 #ifdef DEBUG_CFG_LINES
999         ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL, "Read config: %s", buf);
1000 #endif
1001         return 0;
1002     } else {
1003         /* No "get string" function defined; read character by character */
1004         register int c;
1005         register size_t i = 0;
1006
1007         buf[0] = '\0';
1008         /* skip leading whitespace */
1009         do {
1010             c = cfp->getch(cfp->param);
1011         } while (c == '\t' || c == ' ');
1012
1013         if (c == EOF)
1014             return 1;
1015         
1016         if(bufsize < 2) {
1017             /* too small, assume caller is crazy */
1018             return 1;
1019         }
1020
1021         while (1) {
1022             if ((c == '\t') || (c == ' ')) {
1023                 buf[i++] = ' ';
1024                 while ((c == '\t') || (c == ' '))
1025                     c = cfp->getch(cfp->param);
1026             }
1027             if (c == CR) {
1028                 /* silently ignore CR (_assume_ that a LF follows) */
1029                 c = cfp->getch(cfp->param);
1030             }
1031             if (c == LF) {
1032                 /* increase line number and return on LF */
1033                 ++cfp->line_number;
1034             }
1035             if (c == EOF || c == 0x4 || c == LF || i >= (bufsize - 2)) {
1036                 /* 
1037                  *  check for line continuation
1038                  */
1039                 if (i > 0 && buf[i-1] == '\\') {
1040                     i--;
1041                     if (!(i > 0 && buf[i-1] == '\\')) {
1042                         /* line is continued */
1043                         c = cfp->getch(cfp->param);
1044                         continue;
1045                     }
1046                     /* else nothing needs be done because
1047                      * then the backslash is escaped and
1048                      * we just strip to a single one
1049                      */
1050                 }
1051                 /* blast trailing whitespace */
1052                 while (i > 0 && ap_isspace(buf[i - 1]))
1053                     --i;
1054                 buf[i] = '\0';
1055 #ifdef DEBUG_CFG_LINES
1056                 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL, "Read config: %s", buf);
1057 #endif
1058                 return 0;
1059             }
1060             buf[i] = c;
1061             ++i;
1062             c = cfp->getch(cfp->param);
1063         }
1064     }
1065 }
1066
1067 /* Size an HTTP header field list item, as separated by a comma.
1068  * The return value is a pointer to the beginning of the non-empty list item
1069  * within the original string (or NULL if there is none) and the address
1070  * of field is shifted to the next non-comma, non-whitespace character.
1071  * len is the length of the item excluding any beginning whitespace.
1072  */
1073 API_EXPORT(const char *) ap_size_list_item(const char **field, int *len)
1074 {
1075     const unsigned char *ptr = (const unsigned char *)*field;
1076     const unsigned char *token;
1077     int in_qpair, in_qstr, in_com;
1078
1079     /* Find first non-comma, non-whitespace byte */
1080
1081     while (*ptr == ',' || ap_isspace(*ptr))
1082         ++ptr;
1083
1084     token = ptr;
1085
1086     /* Find the end of this item, skipping over dead bits */
1087
1088     for (in_qpair = in_qstr = in_com = 0;
1089          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1090          ++ptr) {
1091
1092         if (in_qpair) {
1093             in_qpair = 0;
1094         }
1095         else {
1096             switch (*ptr) {
1097                 case '\\': in_qpair = 1;      /* quoted-pair         */
1098                            break;
1099                 case '"' : if (!in_com)       /* quoted string delim */
1100                                in_qstr = !in_qstr;
1101                            break;
1102                 case '(' : if (!in_qstr)      /* comment (may nest)  */
1103                                ++in_com;
1104                            break;
1105                 case ')' : if (in_com)        /* end comment         */
1106                                --in_com;
1107                            break;
1108                 default  : break;
1109             }
1110         }
1111     }
1112
1113     if ((*len = (ptr - token)) == 0) {
1114         *field = (const char *)ptr;
1115         return NULL;
1116     }
1117
1118     /* Advance field pointer to the next non-comma, non-white byte */
1119
1120     while (*ptr == ',' || ap_isspace(*ptr))
1121         ++ptr;
1122
1123     *field = (const char *)ptr;
1124     return (const char *)token;
1125 }
1126
1127 /* Retrieve an HTTP header field list item, as separated by a comma,
1128  * while stripping insignificant whitespace and lowercasing anything not in
1129  * a quoted string or comment.  The return value is a new string containing
1130  * the converted list item (or NULL if none) and the address pointed to by
1131  * field is shifted to the next non-comma, non-whitespace.
1132  */
1133 API_EXPORT(char *) ap_get_list_item(pool *p, const char **field)
1134 {
1135     const char *tok_start;
1136     const unsigned char *ptr;
1137     unsigned char *pos;
1138     char *token;
1139     int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1140
1141     /* Find the beginning and maximum length of the list item so that
1142      * we can allocate a buffer for the new string and reset the field.
1143      */
1144     if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1145         return NULL;
1146     }
1147     token = ap_palloc(p, tok_len + 1);
1148
1149     /* Scan the token again, but this time copy only the good bytes.
1150      * We skip extra whitespace and any whitespace around a '=', '/',
1151      * or ';' and lowercase normal characters not within a comment,
1152      * quoted-string or quoted-pair.
1153      */
1154     for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1155          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1156          ++ptr) {
1157
1158         if (in_qpair) {
1159             in_qpair = 0;
1160             *pos++ = *ptr;
1161         }
1162         else {
1163             switch (*ptr) {
1164                 case '\\': in_qpair = 1;
1165                            if (addspace == 1)
1166                                *pos++ = ' ';
1167                            *pos++ = *ptr;
1168                            addspace = 0;
1169                            break;
1170                 case '"' : if (!in_com)
1171                                in_qstr = !in_qstr;
1172                            if (addspace == 1)
1173                                *pos++ = ' ';
1174                            *pos++ = *ptr;
1175                            addspace = 0;
1176                            break;
1177                 case '(' : if (!in_qstr)
1178                                ++in_com;
1179                            if (addspace == 1)
1180                                *pos++ = ' ';
1181                            *pos++ = *ptr;
1182                            addspace = 0;
1183                            break;
1184                 case ')' : if (in_com)
1185                                --in_com;
1186                            *pos++ = *ptr;
1187                            addspace = 0;
1188                            break;
1189                 case ' ' :
1190                 case '\t': if (addspace)
1191                                break;
1192                            if (in_com || in_qstr)
1193                                *pos++ = *ptr;
1194                            else
1195                                addspace = 1;
1196                            break;
1197                 case '=' :
1198                 case '/' :
1199                 case ';' : if (!(in_com || in_qstr))
1200                                addspace = -1;
1201                            *pos++ = *ptr;
1202                            break;
1203                 default  : if (addspace == 1)
1204                                *pos++ = ' ';
1205                            *pos++ = (in_com || in_qstr) ? *ptr
1206                                                         : ap_tolower(*ptr);
1207                            addspace = 0;
1208                            break;
1209             }
1210         }
1211     }
1212     *pos = '\0';
1213
1214     return token;
1215 }
1216
1217 /* Find an item in canonical form (lowercase, no extra spaces) within
1218  * an HTTP field value list.  Returns 1 if found, 0 if not found.
1219  * This would be much more efficient if we stored header fields as
1220  * an array of list items as they are received instead of a plain string.
1221  */
1222 API_EXPORT(int) ap_find_list_item(pool *p, const char *line, const char *tok)
1223 {
1224     const unsigned char *pos;
1225     const unsigned char *ptr = (const unsigned char *)line;
1226     int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1227
1228     if (!line || !tok)
1229         return 0;
1230
1231     do {  /* loop for each item in line's list */
1232
1233         /* Find first non-comma, non-whitespace byte */
1234
1235         while (*ptr == ',' || ap_isspace(*ptr))
1236             ++ptr;
1237
1238         if (*ptr)
1239             good = 1;  /* until proven otherwise for this item */
1240         else
1241             break;     /* no items left and nothing good found */
1242
1243         /* We skip extra whitespace and any whitespace around a '=', '/',
1244          * or ';' and lowercase normal characters not within a comment,
1245          * quoted-string or quoted-pair.
1246          */
1247         for (pos = (const unsigned char *)tok;
1248              *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1249              ++ptr) {
1250
1251             if (in_qpair) {
1252                 in_qpair = 0;
1253                 if (good)
1254                     good = (*pos++ == *ptr);
1255             }
1256             else {
1257                 switch (*ptr) {
1258                     case '\\': in_qpair = 1;
1259                                if (addspace == 1)
1260                                    good = good && (*pos++ == ' ');
1261                                good = good && (*pos++ == *ptr);
1262                                addspace = 0;
1263                                break;
1264                     case '"' : if (!in_com)
1265                                    in_qstr = !in_qstr;
1266                                if (addspace == 1)
1267                                    good = good && (*pos++ == ' ');
1268                                good = good && (*pos++ == *ptr);
1269                                addspace = 0;
1270                                break;
1271                     case '(' : if (!in_qstr)
1272                                    ++in_com;
1273                                if (addspace == 1)
1274                                    good = good && (*pos++ == ' ');
1275                                good = good && (*pos++ == *ptr);
1276                                addspace = 0;
1277                                break;
1278                     case ')' : if (in_com)
1279                                    --in_com;
1280                                good = good && (*pos++ == *ptr);
1281                                addspace = 0;
1282                                break;
1283                     case ' ' :
1284                     case '\t': if (addspace || !good)
1285                                    break;
1286                                if (in_com || in_qstr)
1287                                    good = (*pos++ == *ptr);
1288                                else
1289                                    addspace = 1;
1290                                break;
1291                     case '=' :
1292                     case '/' :
1293                     case ';' : if (!(in_com || in_qstr))
1294                                    addspace = -1;
1295                                good = good && (*pos++ == *ptr);
1296                                break;
1297                     default  : if (!good)
1298                                    break;
1299                                if (addspace == 1)
1300                                    good = (*pos++ == ' ');
1301                                if (in_com || in_qstr)
1302                                    good = good && (*pos++ == *ptr);
1303                                else
1304                                    good = good && (*pos++ == ap_tolower(*ptr));
1305                                addspace = 0;
1306                                break;
1307                 }
1308             }
1309         }
1310         if (good && *pos)
1311             good = 0;          /* not good if only a prefix was matched */
1312
1313     } while (*ptr && !good);
1314
1315     return good;
1316 }
1317
1318
1319 /* Retrieve a token, spacing over it and returning a pointer to
1320  * the first non-white byte afterwards.  Note that these tokens
1321  * are delimited by semis and commas; and can also be delimited
1322  * by whitespace at the caller's option.
1323  */
1324
1325 API_EXPORT(char *) ap_get_token(pool *p, const char **accept_line, int accept_white)
1326 {
1327     const char *ptr = *accept_line;
1328     const char *tok_start;
1329     char *token;
1330     int tok_len;
1331
1332     /* Find first non-white byte */
1333
1334     while (*ptr && ap_isspace(*ptr))
1335         ++ptr;
1336
1337     tok_start = ptr;
1338
1339     /* find token end, skipping over quoted strings.
1340      * (comments are already gone).
1341      */
1342
1343     while (*ptr && (accept_white || !ap_isspace(*ptr))
1344            && *ptr != ';' && *ptr != ',') {
1345         if (*ptr++ == '"')
1346             while (*ptr)
1347                 if (*ptr++ == '"')
1348                     break;
1349     }
1350
1351     tok_len = ptr - tok_start;
1352     token = ap_pstrndup(p, tok_start, tok_len);
1353
1354     /* Advance accept_line pointer to the next non-white byte */
1355
1356     while (*ptr && ap_isspace(*ptr))
1357         ++ptr;
1358
1359     *accept_line = ptr;
1360     return token;
1361 }
1362
1363
1364 /* find http tokens, see the definition of token from RFC2068 */
1365 API_EXPORT(int) ap_find_token(pool *p, const char *line, const char *tok)
1366 {
1367     const unsigned char *start_token;
1368     const unsigned char *s;
1369
1370     if (!line)
1371         return 0;
1372
1373     s = (const unsigned char *)line;
1374     for (;;) {
1375         /* find start of token, skip all stop characters, note NUL
1376          * isn't a token stop, so we don't need to test for it
1377          */
1378         while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1379             ++s;
1380         }
1381         if (!*s) {
1382             return 0;
1383         }
1384         start_token = s;
1385         /* find end of the token */
1386         while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1387             ++s;
1388         }
1389         if (!strncasecmp((const char *)start_token, (const char *)tok, s - start_token)) {
1390             return 1;
1391         }
1392         if (!*s) {
1393             return 0;
1394         }
1395     }
1396 }
1397
1398
1399 API_EXPORT(int) ap_find_last_token(pool *p, const char *line, const char *tok)
1400 {
1401     int llen, tlen, lidx;
1402
1403     if (!line)
1404         return 0;
1405
1406     llen = strlen(line);
1407     tlen = strlen(tok);
1408     lidx = llen - tlen;
1409
1410     if ((lidx < 0) ||
1411         ((lidx > 0) && !(ap_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1412         return 0;
1413
1414     return (strncasecmp(&line[lidx], tok, tlen) == 0);
1415 }
1416
1417 API_EXPORT(char *) ap_escape_shell_cmd(pool *p, const char *str)
1418 {
1419     char *cmd;
1420     unsigned char *d;
1421     const unsigned char *s;
1422
1423     cmd = ap_palloc(p, 2 * strlen(str) + 1);    /* Be safe */
1424     d = (unsigned char *)cmd;
1425     s = (const unsigned char *)str;
1426     for (; *s; ++s) {
1427
1428 #if defined(OS2) || defined(WIN32)
1429         /* Don't allow '&' in parameters under OS/2. */
1430         /* This can be used to send commands to the shell. */
1431         if (*s == '&') {
1432             *d++ = ' ';
1433             continue;
1434         }
1435 #endif
1436
1437         if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1438             *d++ = '\\';
1439         }
1440         *d++ = *s;
1441     }
1442     *d = '\0';
1443
1444     return cmd;
1445 }
1446
1447 static char x2c(const char *what)
1448 {
1449     register char digit;
1450
1451 #ifndef CHARSET_EBCDIC
1452     digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
1453     digit *= 16;
1454     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
1455 #else /*CHARSET_EBCDIC*/
1456     char xstr[5];
1457     xstr[0]='0';
1458     xstr[1]='x';
1459     xstr[2]=what[0];
1460     xstr[3]=what[1];
1461     xstr[4]='\0';
1462     digit = os_toebcdic[0xFF & strtol(xstr, NULL, 16)];
1463 #endif /*CHARSET_EBCDIC*/
1464     return (digit);
1465 }
1466
1467 /*
1468  * Unescapes a URL.
1469  * Returns 0 on success, non-zero on error
1470  * Failure is due to
1471  *   bad % escape       returns BAD_REQUEST
1472  *
1473  *   decoding %00 -> \0
1474  *   decoding %2f -> /   (a special character)
1475  *                      returns NOT_FOUND
1476  */
1477 API_EXPORT(int) ap_unescape_url(char *url)
1478 {
1479     register int badesc, badpath;
1480     char *x, *y;
1481
1482     badesc = 0;
1483     badpath = 0;
1484     /* Initial scan for first '%'. Don't bother writing values before
1485      * seeing a '%' */
1486     y = strchr(url, '%');
1487     if (y == NULL) {
1488         return OK;
1489     }
1490     for (x = y; *y; ++x, ++y) {
1491         if (*y != '%')
1492             *x = *y;
1493         else {
1494             if (!ap_isxdigit(*(y + 1)) || !ap_isxdigit(*(y + 2))) {
1495                 badesc = 1;
1496                 *x = '%';
1497             }
1498             else {
1499                 *x = x2c(y + 1);
1500                 y += 2;
1501                 if (*x == '/' || *x == '\0')
1502                     badpath = 1;
1503             }
1504         }
1505     }
1506     *x = '\0';
1507     if (badesc)
1508         return BAD_REQUEST;
1509     else if (badpath)
1510         return NOT_FOUND;
1511     else
1512         return OK;
1513 }
1514
1515 API_EXPORT(char *) ap_construct_server(pool *p, const char *hostname,
1516                                     unsigned port, const request_rec *r)
1517 {
1518     if (ap_is_default_port(port, r))
1519         return ap_pstrdup(p, hostname);
1520     else {
1521         return ap_psprintf(p, "%s:%u", hostname, port);
1522     }
1523 }
1524
1525 /* c2x takes an unsigned, and expects the caller has guaranteed that
1526  * 0 <= what < 256... which usually means that you have to cast to
1527  * unsigned char first, because (unsigned)(char)(x) fist goes through
1528  * signed extension to an int before the unsigned cast.
1529  *
1530  * The reason for this assumption is to assist gcc code generation --
1531  * the unsigned char -> unsigned extension is already done earlier in
1532  * both uses of this code, so there's no need to waste time doing it
1533  * again.
1534  */
1535 static const char c2x_table[] = "0123456789abcdef";
1536
1537 static ap_inline unsigned char *c2x(unsigned what, unsigned char *where)
1538 {
1539     *where++ = '%';
1540     *where++ = c2x_table[what >> 4];
1541     *where++ = c2x_table[what & 0xf];
1542     return where;
1543 }
1544
1545 /*
1546  * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1547  * routine is (should be) OS independent.
1548  *
1549  * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1550  * cases if a ':' occurs before the first '/' in the URL, the URL should be
1551  * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1552  * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1553  * efficiency reasons, we don't use escape_path_segment(), which is provided for
1554  * reference. Again, RFC 1808 is where this stuff is defined.
1555  *
1556  * If partial is set, os_escape_path() assumes that the path will be appended to
1557  * something with a '/' in it (and thus does not prefix "./").
1558  */
1559
1560 API_EXPORT(char *) ap_escape_path_segment(pool *p, const char *segment)
1561 {
1562     char *copy = ap_palloc(p, 3 * strlen(segment) + 1);
1563     const unsigned char *s = (const unsigned char *)segment;
1564     unsigned char *d = (unsigned char *)copy;
1565     unsigned c;
1566
1567     while ((c = *s)) {
1568         if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1569             d = c2x(c, d);
1570         }
1571         else {
1572             *d++ = c;
1573         }
1574         ++s;
1575     }
1576     *d = '\0';
1577     return copy;
1578 }
1579
1580 API_EXPORT(char *) ap_os_escape_path(pool *p, const char *path, int partial)
1581 {
1582     char *copy = ap_palloc(p, 3 * strlen(path) + 3);
1583     const unsigned char *s = (const unsigned char *)path;
1584     unsigned char *d = (unsigned char *)copy;
1585     unsigned c;
1586
1587     if (!partial) {
1588         char *colon = strchr(path, ':');
1589         char *slash = strchr(path, '/');
1590
1591         if (colon && (!slash || colon < slash)) {
1592             *d++ = '.';
1593             *d++ = '/';
1594         }
1595     }
1596     while ((c = *s)) {
1597         if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1598             d = c2x(c, d);
1599         }
1600         else {
1601             *d++ = c;
1602         }
1603         ++s;
1604     }
1605     *d = '\0';
1606     return copy;
1607 }
1608
1609 /* ap_escape_uri is now a macro for os_escape_path */
1610
1611 API_EXPORT(char *) ap_escape_html(pool *p, const char *s)
1612 {
1613     int i, j;
1614     char *x;
1615
1616     /* first, count the number of extra characters */
1617     for (i = 0, j = 0; s[i] != '\0'; i++)
1618         if (s[i] == '<' || s[i] == '>')
1619             j += 3;
1620         else if (s[i] == '&')
1621             j += 4;
1622
1623     if (j == 0)
1624         return ap_pstrndup(p, s, i);
1625
1626     x = ap_palloc(p, i + j + 1);
1627     for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1628         if (s[i] == '<') {
1629             memcpy(&x[j], "&lt;", 4);
1630             j += 3;
1631         }
1632         else if (s[i] == '>') {
1633             memcpy(&x[j], "&gt;", 4);
1634             j += 3;
1635         }
1636         else if (s[i] == '&') {
1637             memcpy(&x[j], "&amp;", 5);
1638             j += 4;
1639         }
1640         else
1641             x[j] = s[i];
1642
1643     x[j] = '\0';
1644     return x;
1645 }
1646
1647 API_EXPORT(int) ap_is_directory(const char *path)
1648 {
1649     struct stat finfo;
1650
1651     /* ZZZ replace with AP File Info func. */
1652     if (stat(path, &finfo) == -1)
1653         return 0;               /* in error condition, just return no */
1654
1655     return (S_ISDIR(finfo.st_mode));
1656 }
1657
1658 API_EXPORT(char *) ap_make_full_path(pool *a, const char *src1,
1659                                   const char *src2)
1660 {
1661     register int x;
1662
1663     x = strlen(src1);
1664     if (x == 0)
1665         return ap_pstrcat(a, "/", src2, NULL);
1666
1667     if (src1[x - 1] != '/')
1668         return ap_pstrcat(a, src1, "/", src2, NULL);
1669     else
1670         return ap_pstrcat(a, src1, src2, NULL);
1671 }
1672
1673 /*
1674  * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
1675  */
1676 API_EXPORT(int) ap_is_url(const char *u)
1677 {
1678     register int x;
1679
1680     for (x = 0; u[x] != ':'; x++) {
1681         if ((!u[x]) ||
1682             ((!ap_isalpha(u[x])) && (!ap_isdigit(u[x])) &&
1683              (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
1684             return 0;
1685         }
1686     }
1687
1688     return (x ? 1 : 0);         /* If the first character is ':', it's broken, too */
1689 }
1690
1691 API_EXPORT(int) ap_can_exec(const struct stat *finfo)
1692 {
1693 #ifdef MULTIPLE_GROUPS
1694     int cnt;
1695 #endif
1696 #if defined(OS2) || defined(WIN32)
1697     /* OS/2 dosen't have Users and Groups */
1698     return 1;
1699 #else
1700     if (ap_user_id == finfo->st_uid)
1701         if (finfo->st_mode & S_IXUSR)
1702             return 1;
1703     if (ap_group_id == finfo->st_gid)
1704         if (finfo->st_mode & S_IXGRP)
1705             return 1;
1706 #ifdef MULTIPLE_GROUPS
1707     for (cnt = 0; cnt < NGROUPS_MAX; cnt++) {
1708         if (group_id_list[cnt] == finfo->st_gid)
1709             if (finfo->st_mode & S_IXGRP)
1710                 return 1;
1711     }
1712 #endif
1713     return (finfo->st_mode & S_IXOTH);
1714 #endif
1715 }
1716
1717 #ifdef NEED_STRDUP
1718 char *strdup(const char *str)
1719 {
1720     char *sdup;
1721
1722     if (!(sdup = (char *) malloc(strlen(str) + 1))) {
1723         fprintf(stderr, "Ouch!  Out of memory in our strdup()!\n");
1724         return NULL;
1725     }
1726     sdup = strcpy(sdup, str);
1727
1728     return sdup;
1729 }
1730 #endif
1731
1732 /* The following two routines were donated for SVR4 by Andreas Vogel */
1733 #ifdef NEED_STRCASECMP
1734 int strcasecmp(const char *a, const char *b)
1735 {
1736     const char *p = a;
1737     const char *q = b;
1738     for (p = a, q = b; *p && *q; p++, q++) {
1739         int diff = ap_tolower(*p) - ap_tolower(*q);
1740         if (diff)
1741             return diff;
1742     }
1743     if (*p)
1744         return 1;               /* p was longer than q */
1745     if (*q)
1746         return -1;              /* p was shorter than q */
1747     return 0;                   /* Exact match */
1748 }
1749
1750 #endif
1751
1752 #ifdef NEED_STRNCASECMP
1753 int strncasecmp(const char *a, const char *b, int n)
1754 {
1755     const char *p = a;
1756     const char *q = b;
1757
1758     for (p = a, q = b; /*NOTHING */ ; p++, q++) {
1759         int diff;
1760         if (p == a + n)
1761             return 0;           /*   Match up to n characters */
1762         if (!(*p && *q))
1763             return *p - *q;
1764         diff = ap_tolower(*p) - ap_tolower(*q);
1765         if (diff)
1766             return diff;
1767     }
1768     /*NOTREACHED */
1769 }
1770 #endif
1771
1772 /* The following routine was donated for UTS21 by dwd@bell-labs.com */
1773 #ifdef NEED_STRSTR
1774 char *strstr(char *s1, char *s2)
1775 {
1776     char *p1, *p2;
1777     if (*s2 == '\0') {
1778         /* an empty s2 */
1779         return(s1);
1780     }
1781     while((s1 = strchr(s1, *s2)) != NULL) {
1782         /* found first character of s2, see if the rest matches */
1783         p1 = s1;
1784         p2 = s2;
1785         while (*++p1 == *++p2) {
1786             if (*p1 == '\0') {
1787                 /* both strings ended together */
1788                 return(s1);
1789             }
1790         }
1791         if (*p2 == '\0') {
1792             /* second string ended, a match */
1793             break;
1794         }
1795         /* didn't find a match here, try starting at next character in s1 */
1796         s1++;
1797     }
1798     return(s1);
1799 }
1800 #endif
1801
1802 #ifdef NEED_INITGROUPS
1803 int initgroups(const char *name, gid_t basegid)
1804 {
1805 #if defined(QNX) || defined(MPE) || defined(BEOS) || defined(_OSD_POSIX) || defined(TPF) || defined(__TANDEM)
1806 /* QNX, MPE and BeOS do not appear to support supplementary groups. */
1807     return 0;
1808 #else /* ndef QNX */
1809     gid_t groups[NGROUPS_MAX];
1810     struct group *g;
1811     int index = 0;
1812
1813     setgrent();
1814
1815     groups[index++] = basegid;
1816
1817     while (index < NGROUPS_MAX && ((g = getgrent()) != NULL))
1818         if (g->gr_gid != basegid) {
1819             char **names;
1820
1821             for (names = g->gr_mem; *names != NULL; ++names)
1822                 if (!strcmp(*names, name))
1823                     groups[index++] = g->gr_gid;
1824         }
1825
1826     endgrent();
1827
1828     return setgroups(index, groups);
1829 #endif /* def QNX */
1830 }
1831 #endif /* def NEED_INITGROUPS */
1832
1833 #ifdef NEED_WAITPID
1834 /* From ikluft@amdahl.com
1835  * this is not ideal but it works for SVR3 variants
1836  * Modified by dwd@bell-labs.com to call wait3 instead of wait because
1837  *   apache started to use the WNOHANG option.
1838  */
1839 int waitpid(pid_t pid, int *statusp, int options)
1840 {
1841     int tmp_pid;
1842     if (kill(pid, 0) == -1) {
1843         errno = ECHILD;
1844         return -1;
1845     }
1846     while (((tmp_pid = wait3(statusp, options, 0)) != pid) &&
1847                 (tmp_pid != -1) && (tmp_pid != 0) && (pid != -1))
1848         ;
1849     return tmp_pid;
1850 }
1851 #endif
1852
1853 API_EXPORT(int) ap_ind(const char *s, char c)
1854 {
1855     register int x;
1856
1857     for (x = 0; s[x]; x++)
1858         if (s[x] == c)
1859             return x;
1860
1861     return -1;
1862 }
1863
1864 API_EXPORT(int) ap_rind(const char *s, char c)
1865 {
1866     register int x;
1867
1868     for (x = strlen(s) - 1; x != -1; x--)
1869         if (s[x] == c)
1870             return x;
1871
1872     return -1;
1873 }
1874
1875 API_EXPORT(void) ap_str_tolower(char *str)
1876 {
1877     while (*str) {
1878         *str = ap_tolower(*str);
1879         ++str;
1880     }
1881 }
1882
1883 API_EXPORT(uid_t) ap_uname2id(const char *name)
1884 {
1885 #ifdef WIN32
1886     return (1);
1887 #else
1888     struct passwd *ent;
1889
1890     if (name[0] == '#')
1891         return (atoi(&name[1]));
1892
1893     if (!(ent = getpwnam(name))) {
1894         fprintf(stderr, "%s: bad user name %s\n", ap_server_argv0, name);
1895         exit(1);
1896     }
1897     return (ent->pw_uid);
1898 #endif
1899 }
1900
1901 API_EXPORT(gid_t) ap_gname2id(const char *name)
1902 {
1903 #ifdef WIN32
1904     return (1);
1905 #else
1906     struct group *ent;
1907
1908     if (name[0] == '#')
1909         return (atoi(&name[1]));
1910
1911     if (!(ent = getgrnam(name))) {
1912         fprintf(stderr, "%s: bad group name %s\n", ap_server_argv0, name);
1913         exit(1);
1914     }
1915     return (ent->gr_gid);
1916 #endif
1917 }
1918
1919
1920 /*
1921  * Parses a host of the form <address>[:port]
1922  * :port is permitted if 'port' is not NULL
1923  */
1924 unsigned long ap_get_virthost_addr(char *w, unsigned short *ports)
1925 {
1926   /* ZZZ Redesign for AP func changes */
1927     struct hostent *hep;
1928     unsigned long my_addr;
1929     char *p;
1930
1931     p = strchr(w, ':');
1932     if (ports != NULL) {
1933         *ports = 0;
1934         if (p != NULL && strcmp(p + 1, "*") != 0)
1935             *ports = atoi(p + 1);
1936     }
1937
1938     if (p != NULL)
1939         *p = '\0';
1940     if (strcmp(w, "*") == 0) {
1941         if (p != NULL)
1942             *p = ':';
1943         return htonl(INADDR_ANY);
1944     }
1945
1946     my_addr = ap_inet_addr((char *)w);
1947     if (my_addr != INADDR_NONE) {
1948         if (p != NULL)
1949             *p = ':';
1950         return my_addr;
1951     }
1952
1953     hep = gethostbyname(w);
1954
1955     if ((!hep) || (hep->h_addrtype != AF_INET || !hep->h_addr_list[0])) {
1956         fprintf(stderr, "Cannot resolve host name %s --- exiting!\n", w);
1957         exit(1);
1958     }
1959
1960     if (hep->h_addr_list[1]) {
1961         fprintf(stderr, "Host %s has multiple addresses ---\n", w);
1962         fprintf(stderr, "you must choose one explicitly for use as\n");
1963         fprintf(stderr, "a virtual host.  Exiting!!!\n");
1964         exit(1);
1965     }
1966
1967     if (p != NULL)
1968         *p = ':';
1969
1970     return ((struct in_addr *) (hep->h_addr))->s_addr;
1971 }
1972
1973
1974 static char *find_fqdn(pool *a, struct hostent *p)
1975 {
1976     int x;
1977
1978     if (!strchr(p->h_name, '.')) {
1979         for (x = 0; p->h_aliases[x]; ++x) {
1980             if (strchr(p->h_aliases[x], '.') &&
1981                 (!strncasecmp(p->h_aliases[x], p->h_name, strlen(p->h_name))))
1982                 return ap_pstrdup(a, p->h_aliases[x]);
1983         }
1984         return NULL;
1985     }
1986     return ap_pstrdup(a, (void *) p->h_name);
1987 }
1988
1989 char *ap_get_local_host(pool *a)
1990 {
1991 #ifndef MAXHOSTNAMELEN
1992 #define MAXHOSTNAMELEN 256
1993 #endif
1994     char str[MAXHOSTNAMELEN + 1];
1995     char *server_hostname;
1996     struct hostent *p;
1997
1998     /* ZZZ change to use AP funcs. */
1999 #ifdef BEOS
2000     if (gethostname(str, sizeof(str) - 1) == 0)
2001 #else
2002     if (gethostname(str, sizeof(str) - 1) != 0)
2003 #endif
2004     {
2005         perror("Unable to gethostname");
2006         exit(1);
2007     }
2008     str[MAXHOSTNAMELEN] = '\0';
2009     if ((!(p = gethostbyname(str))) || (!(server_hostname = find_fqdn(a, p)))) {
2010         fprintf(stderr, "%s: cannot determine local host name.\n",
2011                 ap_server_argv0);
2012         fprintf(stderr, "Use the ServerName directive to set it manually.\n");
2013         exit(1);
2014     }
2015
2016     return server_hostname;
2017 }
2018
2019 /* simple 'pool' alloc()ing glue to ap_base64.c
2020  */
2021 API_EXPORT(char *) ap_pbase64decode(pool *p, const char *bufcoded)
2022 {
2023     char *decoded;
2024     int l;
2025
2026     decoded = (char *) ap_palloc(p, 1 + ap_base64decode_len(bufcoded));
2027     l = ap_base64decode(decoded, bufcoded);
2028     decoded[l] = '\0'; /* make binary sequence into string */
2029
2030     return decoded;
2031 }
2032
2033 API_EXPORT(char *) ap_pbase64encode(pool *p, char *string) 
2034
2035     char *encoded;
2036     int l = strlen(string);
2037
2038     encoded = (char *) ap_palloc(p, 1 + ap_base64encode_len(l));
2039     l = ap_base64encode(encoded, string, l);
2040     encoded[l] = '\0'; /* make binary sequence into string */
2041
2042     return encoded;
2043 }
2044
2045 /* deprecated names for the above two functions, here for compatibility
2046  */
2047 API_EXPORT(char *) ap_uudecode(pool *p, const char *bufcoded)
2048 {
2049     return ap_pbase64decode(p, bufcoded);
2050 }
2051
2052 API_EXPORT(char *) ap_uuencode(pool *p, char *string) 
2053
2054     return ap_pbase64encode(p, string);
2055 }
2056
2057 #ifdef OS2
2058 void os2pathname(char *path)
2059 {
2060     char newpath[MAX_STRING_LEN];
2061     int loop;
2062     int offset;
2063
2064     offset = 0;
2065     for (loop = 0; loop < (strlen(path) + 1) && loop < sizeof(newpath) - 1; loop++) {
2066         if (path[loop] == '/') {
2067             newpath[offset] = '\\';
2068             /*
2069                offset = offset + 1;
2070                newpath[offset] = '\\';
2071              */
2072         }
2073         else
2074             newpath[offset] = path[loop];
2075         offset = offset + 1;
2076     };
2077     /* Debugging code */
2078     /* fprintf(stderr, "%s \n", newpath); */
2079
2080     strcpy(path, newpath);
2081 };
2082
2083 /* quotes in the string are doubled up.
2084  * Used to escape quotes in args passed to OS/2's cmd.exe
2085  */
2086 char *ap_double_quotes(pool *p, char *str)
2087 {
2088     int num_quotes = 0;
2089     int len = 0;
2090     char *quote_doubled_str, *dest;
2091     
2092     while (str[len]) {
2093         num_quotes += str[len++] == '\"';
2094     }
2095     
2096     quote_doubled_str = ap_palloc(p, len + num_quotes + 1);
2097     dest = quote_doubled_str;
2098     
2099     while (*str) {
2100         if (*str == '\"')
2101             *(dest++) = '\"';
2102         *(dest++) = *(str++);
2103     }
2104     
2105     *dest = 0;
2106     return quote_doubled_str;
2107 }
2108 #endif
2109
2110
2111 #ifdef NEED_STRERROR
2112 char *
2113      strerror(int err)
2114 {
2115
2116     char *p;
2117     extern char *const sys_errlist[];
2118
2119     p = sys_errlist[err];
2120     return (p);
2121 }
2122 #endif
2123
2124 #if defined(NEED_DIFFTIME)
2125 double difftime(time_t time1, time_t time0)
2126 {
2127     return (time1 - time0);
2128 }
2129 #endif
2130
2131 /* we want to downcase the type/subtype for comparison purposes
2132  * but nothing else because ;parameter=foo values are case sensitive.
2133  * XXX: in truth we want to downcase parameter names... but really,
2134  * apache has never handled parameters and such correctly.  You
2135  * also need to compress spaces and such to be able to compare
2136  * properly. -djg
2137  */
2138 API_EXPORT(void) ap_content_type_tolower(char *str)
2139 {
2140     char *semi;
2141
2142     semi = strchr(str, ';');
2143     if (semi) {
2144         *semi = '\0';
2145     }
2146     while (*str) {
2147         *str = ap_tolower(*str);
2148         ++str;
2149     }
2150     if (semi) {
2151         *semi = ';';
2152     }
2153 }
2154
2155 /*
2156  * Given a string, replace any bare " with \" .
2157  */
2158 API_EXPORT(char *) ap_escape_quotes (pool *p, const char *instring)
2159 {
2160     int newlen = 0;
2161     const char *inchr = instring;
2162     char *outchr, *outstring;
2163
2164     /*
2165      * Look through the input string, jogging the length of the output
2166      * string up by an extra byte each time we find an unescaped ".
2167      */
2168     while (*inchr != '\0') {
2169         newlen++;
2170         if (*inchr == '"') {
2171             newlen++;
2172         }
2173         /*
2174          * If we find a slosh, and it's not the last byte in the string,
2175          * it's escaping something - advance past both bytes.
2176          */
2177         if ((*inchr == '\\') && (inchr[1] != '\0')) {
2178             inchr++;
2179             newlen++;
2180         }
2181         inchr++;
2182     }
2183     outstring = ap_palloc(p, newlen + 1);
2184     inchr = instring;
2185     outchr = outstring;
2186     /*
2187      * Now copy the input string to the output string, inserting a slosh
2188      * in front of every " that doesn't already have one.
2189      */
2190     while (*inchr != '\0') {
2191         if ((*inchr == '\\') && (inchr[1] != '\0')) {
2192             *outchr++ = *inchr++;
2193             *outchr++ = *inchr++;
2194         }
2195         if (*inchr == '"') {
2196             *outchr++ = '\\';
2197         }
2198         if (*inchr != '\0') {
2199             *outchr++ = *inchr++;
2200         }
2201     }
2202     *outchr = '\0';
2203     return outstring;
2204 }