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