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