]> granicus.if.org Git - apache/blob - server/util.c
Static var not neccessary here
[apache] / server / util.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * util.c: string utility things
19  *
20  * 3/21/93 Rob McCool
21  * 1995-96 Many changes by the Apache Software Foundation
22  *
23  */
24
25 /* Debugging aid:
26  * #define DEBUG            to trace all cfg_open*()/cfg_closefile() calls
27  * #define DEBUG_CFG_LINES  to trace every line read from the config files
28  */
29
30 #include "apr.h"
31 #include "apr_strings.h"
32 #include "apr_lib.h"
33 #include "apr_md5.h"            /* for apr_password_validate */
34
35 #define APR_WANT_STDIO
36 #define APR_WANT_STRFUNC
37 #include "apr_want.h"
38
39 #if APR_HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42 #if APR_HAVE_PROCESS_H
43 #include <process.h>            /* for getpid() on Win32 */
44 #endif
45 #if APR_HAVE_NETDB_H
46 #include <netdb.h>              /* for gethostbyname() */
47 #endif
48
49 #include "ap_config.h"
50 #include "apr_base64.h"
51 #include "httpd.h"
52 #include "http_main.h"
53 #include "http_log.h"
54 #include "http_protocol.h"
55 #include "http_config.h"
56 #include "http_core.h"
57 #include "util_ebcdic.h"
58 #include "util_varbuf.h"
59
60 #ifdef HAVE_PWD_H
61 #include <pwd.h>
62 #endif
63 #ifdef HAVE_GRP_H
64 #include <grp.h>
65 #endif
66 #ifdef HAVE_SYS_LOADAVG_H
67 #include <sys/loadavg.h>
68 #endif
69
70 #include "ap_mpm.h"
71
72 /* A bunch of functions in util.c scan strings looking for certain characters.
73  * To make that more efficient we encode a lookup table.  The test_char_table
74  * is generated automatically by gen_test_char.c.
75  */
76 #include "test_char.h"
77
78 /* we assume the folks using this ensure 0 <= c < 256... which means
79  * you need a cast to (unsigned char) first, you can't just plug a
80  * char in here and get it to work, because if char is signed then it
81  * will first be sign extended.
82  */
83 #define TEST_CHAR(c, f)        (test_char_table[(unsigned)(c)] & (f))
84
85 /* Win32/NetWare/OS2 need to check for both forward and back slashes
86  * in ap_getparents() and ap_escape_url.
87  */
88 #ifdef CASE_BLIND_FILESYSTEM
89 #define IS_SLASH(s) ((s == '/') || (s == '\\'))
90 #define SLASHES "/\\"
91 #else
92 #define IS_SLASH(s) (s == '/')
93 #define SLASHES "/"
94 #endif
95
96 /* we know core's module_index is 0 */
97 #undef APLOG_MODULE_INDEX
98 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
99
100
101 /*
102  * Examine a field value (such as a media-/content-type) string and return
103  * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
104  */
105 AP_DECLARE(char *) ap_field_noparam(apr_pool_t *p, const char *intype)
106 {
107     const char *semi;
108
109     if (intype == NULL) return NULL;
110
111     semi = ap_strchr_c(intype, ';');
112     if (semi == NULL) {
113         return apr_pstrdup(p, intype);
114     }
115     else {
116         while ((semi > intype) && apr_isspace(semi[-1])) {
117             semi--;
118         }
119         return apr_pstrndup(p, intype, semi - intype);
120     }
121 }
122
123 AP_DECLARE(char *) ap_ht_time(apr_pool_t *p, apr_time_t t, const char *fmt,
124                               int gmt)
125 {
126     apr_size_t retcode;
127     char ts[MAX_STRING_LEN];
128     char tf[MAX_STRING_LEN];
129     apr_time_exp_t xt;
130
131     if (gmt) {
132         const char *f;
133         char *strp;
134
135         apr_time_exp_gmt(&xt, t);
136         /* Convert %Z to "GMT" and %z to "+0000";
137          * on hosts that do not have a time zone string in struct tm,
138          * strftime must assume its argument is local time.
139          */
140         for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
141             ; f++, strp++) {
142             if (*f != '%') continue;
143             switch (f[1]) {
144             case '%':
145                 *++strp = *++f;
146                 break;
147             case 'Z':
148                 *strp++ = 'G';
149                 *strp++ = 'M';
150                 *strp = 'T';
151                 f++;
152                 break;
153             case 'z': /* common extension */
154                 *strp++ = '+';
155                 *strp++ = '0';
156                 *strp++ = '0';
157                 *strp++ = '0';
158                 *strp = '0';
159                 f++;
160                 break;
161             }
162         }
163         *strp = '\0';
164         fmt = tf;
165     }
166     else {
167         apr_time_exp_lt(&xt, t);
168     }
169
170     /* check return code? */
171     apr_strftime(ts, &retcode, MAX_STRING_LEN, fmt, &xt);
172     ts[MAX_STRING_LEN - 1] = '\0';
173     return apr_pstrdup(p, ts);
174 }
175
176 /* Roy owes Rob beer. */
177 /* Rob owes Roy dinner. */
178
179 /* These legacy comments would make a lot more sense if Roy hadn't
180  * replaced the old later_than() routine with util_date.c.
181  *
182  * Well, okay, they still wouldn't make any sense.
183  */
184
185 /* Match = 0, NoMatch = 1, Abort = -1
186  * Based loosely on sections of wildmat.c by Rich Salz
187  * Hmmm... shouldn't this really go component by component?
188  */
189 AP_DECLARE(int) ap_strcmp_match(const char *str, const char *expected)
190 {
191     int x, y;
192
193     for (x = 0, y = 0; expected[y]; ++y, ++x) {
194         if ((!str[x]) && (expected[y] != '*'))
195             return -1;
196         if (expected[y] == '*') {
197             while (expected[++y] == '*');
198             if (!expected[y])
199                 return 0;
200             while (str[x]) {
201                 int ret;
202                 if ((ret = ap_strcmp_match(&str[x++], &expected[y])) != 1)
203                     return ret;
204             }
205             return -1;
206         }
207         else if ((expected[y] != '?') && (str[x] != expected[y]))
208             return 1;
209     }
210     return (str[x] != '\0');
211 }
212
213 AP_DECLARE(int) ap_strcasecmp_match(const char *str, const char *expected)
214 {
215     int x, y;
216
217     for (x = 0, y = 0; expected[y]; ++y, ++x) {
218         if (!str[x] && expected[y] != '*')
219             return -1;
220         if (expected[y] == '*') {
221             while (expected[++y] == '*');
222             if (!expected[y])
223                 return 0;
224             while (str[x]) {
225                 int ret;
226                 if ((ret = ap_strcasecmp_match(&str[x++], &expected[y])) != 1)
227                     return ret;
228             }
229             return -1;
230         }
231         else if (expected[y] != '?'
232                  && apr_tolower(str[x]) != apr_tolower(expected[y]))
233             return 1;
234     }
235     return (str[x] != '\0');
236 }
237
238 /* We actually compare the canonical root to this root, (but we don't
239  * waste time checking the case), since every use of this function in
240  * httpd-2.1 tests if the path is 'proper', meaning we've already passed
241  * it through apr_filepath_merge, or we haven't.
242  */
243 AP_DECLARE(int) ap_os_is_path_absolute(apr_pool_t *p, const char *dir)
244 {
245     const char *newpath;
246     const char *ourdir = dir;
247     if (apr_filepath_root(&newpath, &dir, 0, p) != APR_SUCCESS
248             || strncmp(newpath, ourdir, strlen(newpath)) != 0) {
249         return 0;
250     }
251     return 1;
252 }
253
254 AP_DECLARE(int) ap_is_matchexp(const char *str)
255 {
256     register int x;
257
258     for (x = 0; str[x]; x++)
259         if ((str[x] == '*') || (str[x] == '?'))
260             return 1;
261     return 0;
262 }
263
264 /*
265  * Here's a pool-based interface to the POSIX-esque ap_regcomp().
266  * Note that we return ap_regex_t instead of being passed one.
267  * The reason is that if you use an already-used ap_regex_t structure,
268  * the memory that you've already allocated gets forgotten, and
269  * regfree() doesn't clear it. So we don't allow it.
270  */
271
272 static apr_status_t regex_cleanup(void *preg)
273 {
274     ap_regfree((ap_regex_t *) preg);
275     return APR_SUCCESS;
276 }
277
278 AP_DECLARE(ap_regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
279                                      int cflags)
280 {
281     ap_regex_t *preg = apr_palloc(p, sizeof *preg);
282     int err = ap_regcomp(preg, pattern, cflags);
283     if (err) {
284         if (err == AP_REG_ESPACE)
285             ap_abort_on_oom();
286         return NULL;
287     }
288
289     apr_pool_cleanup_register(p, (void *) preg, regex_cleanup,
290                               apr_pool_cleanup_null);
291
292     return preg;
293 }
294
295 AP_DECLARE(void) ap_pregfree(apr_pool_t *p, ap_regex_t *reg)
296 {
297     ap_regfree(reg);
298     apr_pool_cleanup_kill(p, (void *) reg, regex_cleanup);
299 }
300
301 /*
302  * Similar to standard strstr() but we ignore case in this version.
303  * Based on the strstr() implementation further below.
304  */
305 AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
306 {
307     char *p1, *p2;
308     if (*s2 == '\0') {
309         /* an empty s2 */
310         return((char *)s1);
311     }
312     while(1) {
313         for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
314         if (*s1 == '\0') {
315             return(NULL);
316         }
317         /* found first character of s2, see if the rest matches */
318         p1 = (char *)s1;
319         p2 = (char *)s2;
320         for (++p1, ++p2; apr_tolower(*p1) == apr_tolower(*p2); ++p1, ++p2) {
321             if (*p1 == '\0') {
322                 /* both strings ended together */
323                 return((char *)s1);
324             }
325         }
326         if (*p2 == '\0') {
327             /* second string ended, a match */
328             break;
329         }
330         /* didn't find a match here, try starting at next character in s1 */
331         s1++;
332     }
333     return((char *)s1);
334 }
335
336 /*
337  * Returns an offsetted pointer in bigstring immediately after
338  * prefix. Returns bigstring if bigstring doesn't start with
339  * prefix or if prefix is longer than bigstring while still matching.
340  * NOTE: pointer returned is relative to bigstring, so we
341  * can use standard pointer comparisons in the calling function
342  * (eg: test if ap_stripprefix(a,b) == a)
343  */
344 AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
345                                         const char *prefix)
346 {
347     const char *p1;
348
349     if (*prefix == '\0')
350         return bigstring;
351
352     p1 = bigstring;
353     while (*p1 && *prefix) {
354         if (*p1++ != *prefix++)
355             return bigstring;
356     }
357     if (*prefix == '\0')
358         return p1;
359
360     /* hit the end of bigstring! */
361     return bigstring;
362 }
363
364 /* This function substitutes for $0-$9, filling in regular expression
365  * submatches. Pass it the same nmatch and pmatch arguments that you
366  * passed ap_regexec(). pmatch should not be greater than the maximum number
367  * of subexpressions - i.e. one more than the re_nsub member of ap_regex_t.
368  *
369  * nmatch must be <=AP_MAX_REG_MATCH (10).
370  *
371  * input should be the string with the $-expressions, source should be the
372  * string that was matched against.
373  *
374  * It returns the substituted string, or NULL if a vbuf is used.
375  * On errors, returns the orig string.
376  *
377  * Parts of this code are based on Henry Spencer's regsub(), from his
378  * AT&T V8 regexp package.
379  */
380
381 static apr_status_t regsub_core(apr_pool_t *p, char **result,
382                                 struct ap_varbuf *vb, const char *input,
383                                 const char *source, apr_size_t nmatch,
384                                 ap_regmatch_t pmatch[], apr_size_t maxlen)
385 {
386     const char *src = input;
387     char *dst;
388     char c;
389     apr_size_t no;
390     apr_size_t len = 0;
391
392     AP_DEBUG_ASSERT((result && p && !vb) || (vb && !p && !result));
393     if (!source || nmatch>AP_MAX_REG_MATCH)
394         return APR_EINVAL;
395     if (!nmatch) {
396         len = strlen(src);
397         if (maxlen > 0 && len >= maxlen)
398             return APR_ENOMEM;
399         if (!vb) {
400             *result = apr_pstrmemdup(p, src, len);
401             return APR_SUCCESS;
402         }
403         else {
404             ap_varbuf_strmemcat(vb, src, len);
405             return APR_SUCCESS;
406         }
407     }
408
409     /* First pass, find the size */
410     while ((c = *src++) != '\0') {
411         if (c == '$' && apr_isdigit(*src))
412             no = *src++ - '0';
413         else
414             no = AP_MAX_REG_MATCH;
415
416         if (no >= AP_MAX_REG_MATCH) {  /* Ordinary character. */
417             if (c == '\\' && *src)
418                 src++;
419             len++;
420         }
421         else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
422             if (APR_SIZE_MAX - len <= pmatch[no].rm_eo - pmatch[no].rm_so)
423                 return APR_ENOMEM;
424             len += pmatch[no].rm_eo - pmatch[no].rm_so;
425         }
426
427     }
428
429     if (len >= maxlen && maxlen > 0)
430         return APR_ENOMEM;
431
432     if (!vb) {
433         *result = dst = apr_palloc(p, len + 1);
434     }
435     else {
436         if (vb->strlen == AP_VARBUF_UNKNOWN)
437             vb->strlen = strlen(vb->buf);
438         ap_varbuf_grow(vb, vb->strlen + len);
439         dst = vb->buf + vb->strlen;
440         vb->strlen += len;
441     }
442
443     /* Now actually fill in the string */
444
445     src = input;
446
447     while ((c = *src++) != '\0') {
448         if (c == '$' && apr_isdigit(*src))
449             no = *src++ - '0';
450         else
451             no = AP_MAX_REG_MATCH;
452
453         if (no >= AP_MAX_REG_MATCH) {  /* Ordinary character. */
454             if (c == '\\' && *src)
455                 c = *src++;
456             *dst++ = c;
457         }
458         else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
459             len = pmatch[no].rm_eo - pmatch[no].rm_so;
460             memcpy(dst, source + pmatch[no].rm_so, len);
461             dst += len;
462         }
463
464     }
465     *dst = '\0';
466
467     return APR_SUCCESS;
468 }
469
470 #ifndef AP_PREGSUB_MAXLEN
471 #define AP_PREGSUB_MAXLEN   (HUGE_STRING_LEN * 8)
472 #endif
473 AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input,
474                               const char *source, apr_size_t nmatch,
475                               ap_regmatch_t pmatch[])
476 {
477     char *result;
478     apr_status_t rc = regsub_core(p, &result, NULL, input, source, nmatch,
479                                   pmatch, AP_PREGSUB_MAXLEN);
480     if (rc != APR_SUCCESS)
481         result = NULL;
482     return result;
483 }
484
485 AP_DECLARE(apr_status_t) ap_pregsub_ex(apr_pool_t *p, char **result,
486                                        const char *input, const char *source,
487                                        apr_size_t nmatch, ap_regmatch_t pmatch[],
488                                        apr_size_t maxlen)
489 {
490     apr_status_t rc = regsub_core(p, result, NULL, input, source, nmatch,
491                                   pmatch, maxlen);
492     if (rc != APR_SUCCESS)
493         *result = NULL;
494     return rc;
495 }
496
497 /*
498  * Parse .. so we don't compromise security
499  */
500 AP_DECLARE(void) ap_getparents(char *name)
501 {
502     char *next;
503     int l, w, first_dot;
504
505     /* Four paseses, as per RFC 1808 */
506     /* a) remove ./ path segments */
507     for (next = name; *next && (*next != '.'); next++) {
508     }
509
510     l = w = first_dot = next - name;
511     while (name[l] != '\0') {
512         if (name[l] == '.' && IS_SLASH(name[l + 1])
513             && (l == 0 || IS_SLASH(name[l - 1])))
514             l += 2;
515         else
516             name[w++] = name[l++];
517     }
518
519     /* b) remove trailing . path, segment */
520     if (w == 1 && name[0] == '.')
521         w--;
522     else if (w > 1 && name[w - 1] == '.' && IS_SLASH(name[w - 2]))
523         w--;
524     name[w] = '\0';
525
526     /* c) remove all xx/../ segments. (including leading ../ and /../) */
527     l = first_dot;
528
529     while (name[l] != '\0') {
530         if (name[l] == '.' && name[l + 1] == '.' && IS_SLASH(name[l + 2])
531             && (l == 0 || IS_SLASH(name[l - 1]))) {
532             register int m = l + 3, n;
533
534             l = l - 2;
535             if (l >= 0) {
536                 while (l >= 0 && !IS_SLASH(name[l]))
537                     l--;
538                 l++;
539             }
540             else
541                 l = 0;
542             n = l;
543             while ((name[n] = name[m]))
544                 (++n, ++m);
545         }
546         else
547             ++l;
548     }
549
550     /* d) remove trailing xx/.. segment. */
551     if (l == 2 && name[0] == '.' && name[1] == '.')
552         name[0] = '\0';
553     else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.'
554              && IS_SLASH(name[l - 3])) {
555         l = l - 4;
556         if (l >= 0) {
557             while (l >= 0 && !IS_SLASH(name[l]))
558                 l--;
559             l++;
560         }
561         else
562             l = 0;
563         name[l] = '\0';
564     }
565 }
566
567 AP_DECLARE(void) ap_no2slash(char *name)
568 {
569     char *d, *s;
570
571     s = d = name;
572
573 #ifdef HAVE_UNC_PATHS
574     /* Check for UNC names.  Leave leading two slashes. */
575     if (s[0] == '/' && s[1] == '/')
576         *d++ = *s++;
577 #endif
578
579     while (*s) {
580         if ((*d++ = *s) == '/') {
581             do {
582                 ++s;
583             } while (*s == '/');
584         }
585         else {
586             ++s;
587         }
588     }
589     *d = '\0';
590 }
591
592
593 /*
594  * copy at most n leading directories of s into d
595  * d should be at least as large as s plus 1 extra byte
596  * assumes n > 0
597  * the return value is the ever useful pointer to the trailing \0 of d
598  *
599  * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments,
600  * so that if n == 0, "/" is returned in d with n == 1
601  * and s == "e:/test.html", "e:/" is returned in d
602  * *** See also directory_walk in modules/http/http_request.c
603
604  * examples:
605  *    /a/b, 0  ==> /  (true for all platforms)
606  *    /a/b, 1  ==> /
607  *    /a/b, 2  ==> /a/
608  *    /a/b, 3  ==> /a/b/
609  *    /a/b, 4  ==> /a/b/
610  *
611  *    c:/a/b 0 ==> /
612  *    c:/a/b 1 ==> c:/
613  *    c:/a/b 2 ==> c:/a/
614  *    c:/a/b 3 ==> c:/a/b
615  *    c:/a/b 4 ==> c:/a/b
616  */
617 AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
618 {
619     if (n < 1) {
620         *d = '/';
621         *++d = '\0';
622         return (d);
623     }
624
625     for (;;) {
626         if (*s == '\0' || (*s == '/' && (--n) == 0)) {
627             *d = '/';
628             break;
629         }
630         *d++ = *s++;
631     }
632     *++d = 0;
633     return (d);
634 }
635
636
637 /*
638  * return the parent directory name including trailing / of the file s
639  */
640 AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
641 {
642     const char *last_slash = ap_strrchr_c(s, '/');
643     char *d;
644     int l;
645
646     if (last_slash == NULL) {
647         return apr_pstrdup(p, "");
648     }
649     l = (last_slash - s) + 1;
650     d = apr_pstrmemdup(p, s, l);
651
652     return (d);
653 }
654
655
656 AP_DECLARE(int) ap_count_dirs(const char *path)
657 {
658     register int x, n;
659
660     for (x = 0, n = 0; path[x]; x++)
661         if (path[x] == '/')
662             n++;
663     return n;
664 }
665
666 AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
667 {
668     return ap_getword(atrans, (const char **) line, stop);
669 }
670
671 AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
672 {
673     const char *pos = *line;
674     int len;
675     char *res;
676
677     while ((*pos != stop) && *pos) {
678         ++pos;
679     }
680
681     len = pos - *line;
682     res = apr_pstrmemdup(atrans, *line, len);
683
684     if (stop) {
685         while (*pos == stop) {
686             ++pos;
687         }
688     }
689     *line = pos;
690
691     return res;
692 }
693
694 AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
695 {
696     return ap_getword_white(atrans, (const char **) line);
697 }
698
699 AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
700 {
701     const char *pos = *line;
702     int len;
703     char *res;
704
705     while (!apr_isspace(*pos) && *pos) {
706         ++pos;
707     }
708
709     len = pos - *line;
710     res = apr_pstrmemdup(atrans, *line, len);
711
712     while (apr_isspace(*pos)) {
713         ++pos;
714     }
715
716     *line = pos;
717
718     return res;
719 }
720
721 AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line,
722                                        char stop)
723 {
724     return ap_getword_nulls(atrans, (const char **) line, stop);
725 }
726
727 AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line,
728                                     char stop)
729 {
730     const char *pos = ap_strchr_c(*line, stop);
731     char *res;
732
733     if (!pos) {
734         apr_size_t len = strlen(*line);
735         res = apr_pstrmemdup(atrans, *line, len);
736         *line += len;
737         return res;
738     }
739
740     res = apr_pstrndup(atrans, *line, pos - *line);
741
742     ++pos;
743
744     *line = pos;
745
746     return res;
747 }
748
749 /* Get a word, (new) config-file style --- quoted strings and backslashes
750  * all honored
751  */
752
753 static char *substring_conf(apr_pool_t *p, const char *start, int len,
754                             char quote)
755 {
756     char *result = apr_palloc(p, len + 1);
757     char *resp = result;
758     int i;
759
760     for (i = 0; i < len; ++i) {
761         if (start[i] == '\\' && (start[i + 1] == '\\'
762                                  || (quote && start[i + 1] == quote)))
763             *resp++ = start[++i];
764         else
765             *resp++ = start[i];
766     }
767
768     *resp++ = '\0';
769 #if RESOLVE_ENV_PER_TOKEN
770     return (char *)ap_resolve_env(p,result);
771 #else
772     return result;
773 #endif
774 }
775
776 AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
777 {
778     return ap_getword_conf(p, (const char **) line);
779 }
780
781 AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
782 {
783     const char *str = *line, *strend;
784     char *res;
785     char quote;
786
787     while (apr_isspace(*str))
788         ++str;
789
790     if (!*str) {
791         *line = str;
792         return "";
793     }
794
795     if ((quote = *str) == '"' || quote == '\'') {
796         strend = str + 1;
797         while (*strend && *strend != quote) {
798             if (*strend == '\\' && strend[1] &&
799                 (strend[1] == quote || strend[1] == '\\')) {
800                 strend += 2;
801             }
802             else {
803                 ++strend;
804             }
805         }
806         res = substring_conf(p, str + 1, strend - str - 1, quote);
807
808         if (*strend == quote)
809             ++strend;
810     }
811     else {
812         strend = str;
813         while (*strend && !apr_isspace(*strend))
814             ++strend;
815
816         res = substring_conf(p, str, strend - str, 0);
817     }
818
819     while (apr_isspace(*strend))
820         ++strend;
821     *line = strend;
822     return res;
823 }
824
825 AP_DECLARE(int) ap_cfg_closefile(ap_configfile_t *cfp)
826 {
827 #ifdef DEBUG
828     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(00551)
829         "Done with config file %s", cfp->name);
830 #endif
831     return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
832 }
833
834 /* we can't use apr_file_* directly because of linking issues on Windows */
835 static apr_status_t cfg_close(void *param)
836 {
837     return apr_file_close(param);
838 }
839
840 static apr_status_t cfg_getch(char *ch, void *param)
841 {
842     return apr_file_getc(ch, param);
843 }
844
845 static apr_status_t cfg_getstr(void *buf, apr_size_t bufsiz, void *param)
846 {
847     return apr_file_gets(buf, bufsiz, param);
848 }
849
850 /* Open a ap_configfile_t as FILE, return open ap_configfile_t struct pointer */
851 AP_DECLARE(apr_status_t) ap_pcfg_openfile(ap_configfile_t **ret_cfg,
852                                           apr_pool_t *p, const char *name)
853 {
854     ap_configfile_t *new_cfg;
855     apr_file_t *file = NULL;
856     apr_finfo_t finfo;
857     apr_status_t status;
858 #ifdef DEBUG
859     char buf[120];
860 #endif
861
862     if (name == NULL) {
863         ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00552)
864                "Internal error: pcfg_openfile() called with NULL filename");
865         return APR_EBADF;
866     }
867
868     status = apr_file_open(&file, name, APR_READ | APR_BUFFERED,
869                            APR_OS_DEFAULT, p);
870 #ifdef DEBUG
871     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(00553)
872                 "Opening config file %s (%s)",
873                 name, (status != APR_SUCCESS) ?
874                 apr_strerror(status, buf, sizeof(buf)) : "successful");
875 #endif
876     if (status != APR_SUCCESS)
877         return status;
878
879     status = apr_file_info_get(&finfo, APR_FINFO_TYPE, file);
880     if (status != APR_SUCCESS)
881         return status;
882
883     if (finfo.filetype != APR_REG &&
884 #if defined(WIN32) || defined(OS2) || defined(NETWARE)
885         strcasecmp(apr_filepath_name_get(name), "nul") != 0) {
886 #else
887         strcmp(name, "/dev/null") != 0) {
888 #endif /* WIN32 || OS2 */
889         ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00554)
890                      "Access to file %s denied by server: not a regular file",
891                      name);
892         apr_file_close(file);
893         return APR_EBADF;
894     }
895
896 #ifdef WIN32
897     /* Some twisted character [no pun intended] at MS decided that a
898      * zero width joiner as the lead wide character would be ideal for
899      * describing Unicode text files.  This was further convoluted to
900      * another MSism that the same character mapped into utf-8, EF BB BF
901      * would signify utf-8 text files.
902      *
903      * Since MS configuration files are all protecting utf-8 encoded
904      * Unicode path, file and resource names, we already have the correct
905      * WinNT encoding.  But at least eat the stupid three bytes up front.
906      */
907     {
908         unsigned char buf[4];
909         apr_size_t len = 3;
910         status = apr_file_read(file, buf, &len);
911         if ((status != APR_SUCCESS) || (len < 3)
912               || memcmp(buf, "\xEF\xBB\xBF", 3) != 0) {
913             apr_off_t zero = 0;
914             apr_file_seek(file, APR_SET, &zero);
915         }
916     }
917 #endif
918
919     new_cfg = apr_palloc(p, sizeof(*new_cfg));
920     new_cfg->param = file;
921     new_cfg->name = apr_pstrdup(p, name);
922     new_cfg->getch = cfg_getch;
923     new_cfg->getstr = cfg_getstr;
924     new_cfg->close = cfg_close;
925     new_cfg->line_number = 0;
926     *ret_cfg = new_cfg;
927     return APR_SUCCESS;
928 }
929
930
931 /* Allocate a ap_configfile_t handle with user defined functions and params */
932 AP_DECLARE(ap_configfile_t *) ap_pcfg_open_custom(
933             apr_pool_t *p, const char *descr, void *param,
934             apr_status_t (*getc_func) (char *ch, void *param),
935             apr_status_t (*gets_func) (void *buf, apr_size_t bufsize, void *param),
936             apr_status_t (*close_func) (void *param))
937 {
938     ap_configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
939     new_cfg->param = param;
940     new_cfg->name = descr;
941     new_cfg->getch = getc_func;
942     new_cfg->getstr = gets_func;
943     new_cfg->close = close_func;
944     new_cfg->line_number = 0;
945     return new_cfg;
946 }
947
948 /* Read one character from a configfile_t */
949 AP_DECLARE(apr_status_t) ap_cfg_getc(char *ch, ap_configfile_t *cfp)
950 {
951     apr_status_t rc = cfp->getch(ch, cfp->param);
952     if (rc == APR_SUCCESS && *ch == LF)
953         ++cfp->line_number;
954     return rc;
955 }
956
957 AP_DECLARE(const char *) ap_pcfg_strerror(apr_pool_t *p, ap_configfile_t *cfp,
958                                           apr_status_t rc)
959 {
960     char buf[MAX_STRING_LEN];
961     if (rc == APR_SUCCESS)
962         return NULL;
963     return apr_psprintf(p, "Error reading %s at line %d: %s",
964                         cfp->name, cfp->line_number,
965                         rc == APR_ENOSPC ? "Line too long"
966                                          : apr_strerror(rc, buf, sizeof(buf)));
967 }
968
969 /* Read one line from open ap_configfile_t, strip LF, increase line number */
970 /* If custom handler does not define a getstr() function, read char by char */
971 static apr_status_t ap_cfg_getline_core(char *buf, apr_size_t bufsize,
972                                         ap_configfile_t *cfp)
973 {
974     apr_status_t rc;
975     /* If a "get string" function is defined, use it */
976     if (cfp->getstr != NULL) {
977         char *cp;
978         char *cbuf = buf;
979         apr_size_t cbufsize = bufsize;
980
981         while (1) {
982             ++cfp->line_number;
983             rc = cfp->getstr(cbuf, cbufsize, cfp->param);
984             if (rc == APR_EOF) {
985                 if (cbuf != buf) {
986                     *cbuf = '\0';
987                     break;
988                 }
989                 else {
990                     return APR_EOF;
991                 }
992             }
993             if (rc != APR_SUCCESS) {
994                 return rc;
995             }
996
997             /*
998              *  check for line continuation,
999              *  i.e. match [^\\]\\[\r]\n only
1000              */
1001             cp = cbuf;
1002             cp += strlen(cp);
1003             if (cp > cbuf && cp[-1] == LF) {
1004                 cp--;
1005                 if (cp > cbuf && cp[-1] == CR)
1006                     cp--;
1007                 if (cp > cbuf && cp[-1] == '\\') {
1008                     cp--;
1009                     /*
1010                      * line continuation requested -
1011                      * then remove backslash and continue
1012                      */
1013                     cbufsize -= (cp-cbuf);
1014                     cbuf = cp;
1015                     continue;
1016                 }
1017             }
1018             else if (cp - buf >= bufsize - 1) {
1019                 return APR_ENOSPC;
1020             }
1021             break;
1022         }
1023     } else {
1024         /* No "get string" function defined; read character by character */
1025         apr_size_t i = 0;
1026
1027         if (bufsize < 2) {
1028             /* too small, assume caller is crazy */
1029             return APR_EINVAL;
1030         }
1031         buf[0] = '\0';
1032
1033         while (1) {
1034             char c;
1035             rc = cfp->getch(&c, cfp->param);
1036             if (rc == APR_EOF) {
1037                 if (i > 0)
1038                     break;
1039                 else
1040                     return APR_EOF;
1041             }
1042             if (rc != APR_SUCCESS)
1043                 return rc;
1044             if (c == LF) {
1045                 ++cfp->line_number;
1046                 /* check for line continuation */
1047                 if (i > 0 && buf[i-1] == '\\') {
1048                     i--;
1049                     continue;
1050                 }
1051                 else {
1052                     break;
1053                 }
1054             }
1055             else if (i >= bufsize - 2) {
1056                 return APR_ENOSPC;
1057             }
1058             buf[i] = c;
1059             ++i;
1060         }
1061         buf[i] = '\0';
1062     }
1063     return APR_SUCCESS;
1064 }
1065
1066 static int cfg_trim_line(char *buf)
1067 {
1068     char *start, *end;
1069     /*
1070      * Leading and trailing white space is eliminated completely
1071      */
1072     start = buf;
1073     while (apr_isspace(*start))
1074         ++start;
1075     /* blast trailing whitespace */
1076     end = &start[strlen(start)];
1077     while (--end >= start && apr_isspace(*end))
1078         *end = '\0';
1079     /* Zap leading whitespace by shifting */
1080     if (start != buf)
1081         memmove(buf, start, end - start + 2);
1082 #ifdef DEBUG_CFG_LINES
1083     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL, APLOGNO(00555) "Read config: '%s'", buf);
1084 #endif
1085     return end - start + 1;
1086 }
1087
1088 /* Read one line from open ap_configfile_t, strip LF, increase line number */
1089 /* If custom handler does not define a getstr() function, read char by char */
1090 AP_DECLARE(apr_status_t) ap_cfg_getline(char *buf, apr_size_t bufsize,
1091                                         ap_configfile_t *cfp)
1092 {
1093     apr_status_t rc = ap_cfg_getline_core(buf, bufsize, cfp);
1094     if (rc == APR_SUCCESS)
1095         cfg_trim_line(buf);
1096     return rc;
1097 }
1098
1099 AP_DECLARE(apr_status_t) ap_varbuf_cfg_getline(struct ap_varbuf *vb,
1100                                                ap_configfile_t *cfp,
1101                                                apr_size_t max_len)
1102 {
1103     apr_status_t rc;
1104     apr_size_t new_len;
1105     vb->strlen = 0;
1106     *vb->buf = '\0';
1107
1108     if (vb->strlen == AP_VARBUF_UNKNOWN)
1109         vb->strlen = strlen(vb->buf);
1110     if (vb->avail - vb->strlen < 3) {
1111         new_len = vb->avail * 2;
1112         if (new_len > max_len)
1113             new_len = max_len;
1114         else if (new_len < 3)
1115             new_len = 3;
1116         ap_varbuf_grow(vb, new_len);
1117     }
1118
1119     for (;;) {
1120         rc = ap_cfg_getline_core(vb->buf + vb->strlen, vb->avail - vb->strlen, cfp);
1121         if (rc == APR_ENOSPC || rc == APR_SUCCESS)
1122             vb->strlen += strlen(vb->buf + vb->strlen);
1123         if (rc != APR_ENOSPC)
1124             break;
1125         if (vb->avail >= max_len)
1126             return APR_ENOSPC;
1127         new_len = vb->avail * 2;
1128         if (new_len > max_len)
1129             new_len = max_len;
1130         ap_varbuf_grow(vb, new_len);
1131         --cfp->line_number;
1132     }
1133     if (vb->strlen > max_len)
1134         return APR_ENOSPC;
1135     if (rc == APR_SUCCESS)
1136         vb->strlen = cfg_trim_line(vb->buf);
1137     return rc;
1138 }
1139
1140 /* Size an HTTP header field list item, as separated by a comma.
1141  * The return value is a pointer to the beginning of the non-empty list item
1142  * within the original string (or NULL if there is none) and the address
1143  * of field is shifted to the next non-comma, non-whitespace character.
1144  * len is the length of the item excluding any beginning whitespace.
1145  */
1146 AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1147 {
1148     const unsigned char *ptr = (const unsigned char *)*field;
1149     const unsigned char *token;
1150     int in_qpair, in_qstr, in_com;
1151
1152     /* Find first non-comma, non-whitespace byte */
1153
1154     while (*ptr == ',' || apr_isspace(*ptr))
1155         ++ptr;
1156
1157     token = ptr;
1158
1159     /* Find the end of this item, skipping over dead bits */
1160
1161     for (in_qpair = in_qstr = in_com = 0;
1162          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1163          ++ptr) {
1164
1165         if (in_qpair) {
1166             in_qpair = 0;
1167         }
1168         else {
1169             switch (*ptr) {
1170                 case '\\': in_qpair = 1;      /* quoted-pair         */
1171                            break;
1172                 case '"' : if (!in_com)       /* quoted string delim */
1173                                in_qstr = !in_qstr;
1174                            break;
1175                 case '(' : if (!in_qstr)      /* comment (may nest)  */
1176                                ++in_com;
1177                            break;
1178                 case ')' : if (in_com)        /* end comment         */
1179                                --in_com;
1180                            break;
1181                 default  : break;
1182             }
1183         }
1184     }
1185
1186     if ((*len = (ptr - token)) == 0) {
1187         *field = (const char *)ptr;
1188         return NULL;
1189     }
1190
1191     /* Advance field pointer to the next non-comma, non-white byte */
1192
1193     while (*ptr == ',' || apr_isspace(*ptr))
1194         ++ptr;
1195
1196     *field = (const char *)ptr;
1197     return (const char *)token;
1198 }
1199
1200 /* Retrieve an HTTP header field list item, as separated by a comma,
1201  * while stripping insignificant whitespace and lowercasing anything not in
1202  * a quoted string or comment.  The return value is a new string containing
1203  * the converted list item (or NULL if none) and the address pointed to by
1204  * field is shifted to the next non-comma, non-whitespace.
1205  */
1206 AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1207 {
1208     const char *tok_start;
1209     const unsigned char *ptr;
1210     unsigned char *pos;
1211     char *token;
1212     int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1213
1214     /* Find the beginning and maximum length of the list item so that
1215      * we can allocate a buffer for the new string and reset the field.
1216      */
1217     if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1218         return NULL;
1219     }
1220     token = apr_palloc(p, tok_len + 1);
1221
1222     /* Scan the token again, but this time copy only the good bytes.
1223      * We skip extra whitespace and any whitespace around a '=', '/',
1224      * or ';' and lowercase normal characters not within a comment,
1225      * quoted-string or quoted-pair.
1226      */
1227     for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1228          *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1229          ++ptr) {
1230
1231         if (in_qpair) {
1232             in_qpair = 0;
1233             *pos++ = *ptr;
1234         }
1235         else {
1236             switch (*ptr) {
1237                 case '\\': in_qpair = 1;
1238                            if (addspace == 1)
1239                                *pos++ = ' ';
1240                            *pos++ = *ptr;
1241                            addspace = 0;
1242                            break;
1243                 case '"' : if (!in_com)
1244                                in_qstr = !in_qstr;
1245                            if (addspace == 1)
1246                                *pos++ = ' ';
1247                            *pos++ = *ptr;
1248                            addspace = 0;
1249                            break;
1250                 case '(' : if (!in_qstr)
1251                                ++in_com;
1252                            if (addspace == 1)
1253                                *pos++ = ' ';
1254                            *pos++ = *ptr;
1255                            addspace = 0;
1256                            break;
1257                 case ')' : if (in_com)
1258                                --in_com;
1259                            *pos++ = *ptr;
1260                            addspace = 0;
1261                            break;
1262                 case ' ' :
1263                 case '\t': if (addspace)
1264                                break;
1265                            if (in_com || in_qstr)
1266                                *pos++ = *ptr;
1267                            else
1268                                addspace = 1;
1269                            break;
1270                 case '=' :
1271                 case '/' :
1272                 case ';' : if (!(in_com || in_qstr))
1273                                addspace = -1;
1274                            *pos++ = *ptr;
1275                            break;
1276                 default  : if (addspace == 1)
1277                                *pos++ = ' ';
1278                            *pos++ = (in_com || in_qstr) ? *ptr
1279                                                         : apr_tolower(*ptr);
1280                            addspace = 0;
1281                            break;
1282             }
1283         }
1284     }
1285     *pos = '\0';
1286
1287     return token;
1288 }
1289
1290 /* Find an item in canonical form (lowercase, no extra spaces) within
1291  * an HTTP field value list.  Returns 1 if found, 0 if not found.
1292  * This would be much more efficient if we stored header fields as
1293  * an array of list items as they are received instead of a plain string.
1294  */
1295 AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line,
1296                                   const char *tok)
1297 {
1298     const unsigned char *pos;
1299     const unsigned char *ptr = (const unsigned char *)line;
1300     int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1301
1302     if (!line || !tok)
1303         return 0;
1304
1305     do {  /* loop for each item in line's list */
1306
1307         /* Find first non-comma, non-whitespace byte */
1308
1309         while (*ptr == ',' || apr_isspace(*ptr))
1310             ++ptr;
1311
1312         if (*ptr)
1313             good = 1;  /* until proven otherwise for this item */
1314         else
1315             break;     /* no items left and nothing good found */
1316
1317         /* We skip extra whitespace and any whitespace around a '=', '/',
1318          * or ';' and lowercase normal characters not within a comment,
1319          * quoted-string or quoted-pair.
1320          */
1321         for (pos = (const unsigned char *)tok;
1322              *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1323              ++ptr) {
1324
1325             if (in_qpair) {
1326                 in_qpair = 0;
1327                 if (good)
1328                     good = (*pos++ == *ptr);
1329             }
1330             else {
1331                 switch (*ptr) {
1332                     case '\\': in_qpair = 1;
1333                                if (addspace == 1)
1334                                    good = good && (*pos++ == ' ');
1335                                good = good && (*pos++ == *ptr);
1336                                addspace = 0;
1337                                break;
1338                     case '"' : if (!in_com)
1339                                    in_qstr = !in_qstr;
1340                                if (addspace == 1)
1341                                    good = good && (*pos++ == ' ');
1342                                good = good && (*pos++ == *ptr);
1343                                addspace = 0;
1344                                break;
1345                     case '(' : if (!in_qstr)
1346                                    ++in_com;
1347                                if (addspace == 1)
1348                                    good = good && (*pos++ == ' ');
1349                                good = good && (*pos++ == *ptr);
1350                                addspace = 0;
1351                                break;
1352                     case ')' : if (in_com)
1353                                    --in_com;
1354                                good = good && (*pos++ == *ptr);
1355                                addspace = 0;
1356                                break;
1357                     case ' ' :
1358                     case '\t': if (addspace || !good)
1359                                    break;
1360                                if (in_com || in_qstr)
1361                                    good = (*pos++ == *ptr);
1362                                else
1363                                    addspace = 1;
1364                                break;
1365                     case '=' :
1366                     case '/' :
1367                     case ';' : if (!(in_com || in_qstr))
1368                                    addspace = -1;
1369                                good = good && (*pos++ == *ptr);
1370                                break;
1371                     default  : if (!good)
1372                                    break;
1373                                if (addspace == 1)
1374                                    good = (*pos++ == ' ');
1375                                if (in_com || in_qstr)
1376                                    good = good && (*pos++ == *ptr);
1377                                else
1378                                    good = good && (*pos++ == apr_tolower(*ptr));
1379                                addspace = 0;
1380                                break;
1381                 }
1382             }
1383         }
1384         if (good && *pos)
1385             good = 0;          /* not good if only a prefix was matched */
1386
1387     } while (*ptr && !good);
1388
1389     return good;
1390 }
1391
1392
1393 /* Retrieve a token, spacing over it and returning a pointer to
1394  * the first non-white byte afterwards.  Note that these tokens
1395  * are delimited by semis and commas; and can also be delimited
1396  * by whitespace at the caller's option.
1397  */
1398
1399 AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line,
1400                                 int accept_white)
1401 {
1402     const char *ptr = *accept_line;
1403     const char *tok_start;
1404     char *token;
1405     int tok_len;
1406
1407     /* Find first non-white byte */
1408
1409     while (apr_isspace(*ptr))
1410         ++ptr;
1411
1412     tok_start = ptr;
1413
1414     /* find token end, skipping over quoted strings.
1415      * (comments are already gone).
1416      */
1417
1418     while (*ptr && (accept_white || !apr_isspace(*ptr))
1419            && *ptr != ';' && *ptr != ',') {
1420         if (*ptr++ == '"')
1421             while (*ptr)
1422                 if (*ptr++ == '"')
1423                     break;
1424     }
1425
1426     tok_len = ptr - tok_start;
1427     token = apr_pstrndup(p, tok_start, tok_len);
1428
1429     /* Advance accept_line pointer to the next non-white byte */
1430
1431     while (apr_isspace(*ptr))
1432         ++ptr;
1433
1434     *accept_line = ptr;
1435     return token;
1436 }
1437
1438
1439 /* find http tokens, see the definition of token from RFC2068 */
1440 AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1441 {
1442     const unsigned char *start_token;
1443     const unsigned char *s;
1444
1445     if (!line)
1446         return 0;
1447
1448     s = (const unsigned char *)line;
1449     for (;;) {
1450         /* find start of token, skip all stop characters, note NUL
1451          * isn't a token stop, so we don't need to test for it
1452          */
1453         while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1454             ++s;
1455         }
1456         if (!*s) {
1457             return 0;
1458         }
1459         start_token = s;
1460         /* find end of the token */
1461         while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1462             ++s;
1463         }
1464         if (!strncasecmp((const char *)start_token, (const char *)tok,
1465                          s - start_token)) {
1466             return 1;
1467         }
1468         if (!*s) {
1469             return 0;
1470         }
1471     }
1472 }
1473
1474
1475 AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line,
1476                                    const char *tok)
1477 {
1478     int llen, tlen, lidx;
1479
1480     if (!line)
1481         return 0;
1482
1483     llen = strlen(line);
1484     tlen = strlen(tok);
1485     lidx = llen - tlen;
1486
1487     if (lidx < 0 ||
1488         (lidx > 0 && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1489         return 0;
1490
1491     return (strncasecmp(&line[lidx], tok, tlen) == 0);
1492 }
1493
1494 AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1495 {
1496     char *cmd;
1497     unsigned char *d;
1498     const unsigned char *s;
1499
1500     cmd = apr_palloc(p, 2 * strlen(str) + 1);        /* Be safe */
1501     d = (unsigned char *)cmd;
1502     s = (const unsigned char *)str;
1503     for (; *s; ++s) {
1504
1505 #if defined(OS2) || defined(WIN32)
1506         /*
1507          * Newlines to Win32/OS2 CreateProcess() are ill advised.
1508          * Convert them to spaces since they are effectively white
1509          * space to most applications
1510          */
1511         if (*s == '\r' || *s == '\n') {
1512              *d++ = ' ';
1513              continue;
1514          }
1515 #endif
1516
1517         if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1518             *d++ = '\\';
1519         }
1520         *d++ = *s;
1521     }
1522     *d = '\0';
1523
1524     return cmd;
1525 }
1526
1527 static char x2c(const char *what)
1528 {
1529     register char digit;
1530
1531 #if !APR_CHARSET_EBCDIC
1532     digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10
1533              : (what[0] - '0'));
1534     digit *= 16;
1535     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10
1536               : (what[1] - '0'));
1537 #else /*APR_CHARSET_EBCDIC*/
1538     char xstr[5];
1539     xstr[0]='0';
1540     xstr[1]='x';
1541     xstr[2]=what[0];
1542     xstr[3]=what[1];
1543     xstr[4]='\0';
1544     digit = apr_xlate_conv_byte(ap_hdrs_from_ascii,
1545                                 0xFF & strtol(xstr, NULL, 16));
1546 #endif /*APR_CHARSET_EBCDIC*/
1547     return (digit);
1548 }
1549
1550 /*
1551  * Unescapes a URL, leaving reserved characters intact.
1552  * Returns 0 on success, non-zero on error
1553  * Failure is due to
1554  *   bad % escape       returns HTTP_BAD_REQUEST
1555  *
1556  *   decoding %00 or a forbidden character returns HTTP_NOT_FOUND
1557  */
1558
1559 static int unescape_url(char *url, const char *forbid, const char *reserved)
1560 {
1561     register int badesc, badpath;
1562     char *x, *y;
1563
1564     badesc = 0;
1565     badpath = 0;
1566     /* Initial scan for first '%'. Don't bother writing values before
1567      * seeing a '%' */
1568     y = strchr(url, '%');
1569     if (y == NULL) {
1570         return OK;
1571     }
1572     for (x = y; *y; ++x, ++y) {
1573         if (*y != '%') {
1574             *x = *y;
1575         }
1576         else {
1577             if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1578                 badesc = 1;
1579                 *x = '%';
1580             }
1581             else {
1582                 char decoded;
1583                 decoded = x2c(y + 1);
1584                 if ((decoded == '\0')
1585                     || (forbid && ap_strchr_c(forbid, decoded))) {
1586                     badpath = 1;
1587                     *x = decoded;
1588                     y += 2;
1589                 }
1590                 else if (reserved && ap_strchr_c(reserved, decoded)) {
1591                     *x++ = *y++;
1592                     *x++ = *y++;
1593                     *x = *y;
1594                 }
1595                 else {
1596                     *x = decoded;
1597                     y += 2;
1598                 }
1599             }
1600         }
1601     }
1602     *x = '\0';
1603     if (badesc) {
1604         return HTTP_BAD_REQUEST;
1605     }
1606     else if (badpath) {
1607         return HTTP_NOT_FOUND;
1608     }
1609     else {
1610         return OK;
1611     }
1612 }
1613 AP_DECLARE(int) ap_unescape_url(char *url)
1614 {
1615     /* Traditional */
1616     return unescape_url(url, SLASHES, NULL);
1617 }
1618 AP_DECLARE(int) ap_unescape_url_keep2f(char *url, int decode_slashes)
1619 {
1620     /* AllowEncodedSlashes (corrected) */
1621     if (decode_slashes) {
1622         /* no chars reserved */
1623         return unescape_url(url, NULL, NULL);
1624     } else {
1625         /* reserve (do not decode) encoded slashes */
1626         return unescape_url(url, NULL, SLASHES);
1627     }
1628 }
1629 #ifdef NEW_APIS
1630 /* IFDEF these out until they've been thought through.
1631  * Just a germ of an API extension for now
1632  */
1633 AP_DECLARE(int) ap_unescape_url_proxy(char *url)
1634 {
1635     /* leave RFC1738 reserved characters intact, * so proxied URLs
1636      * don't get mangled.  Where does that leave encoded '&' ?
1637      */
1638     return unescape_url(url, NULL, "/;?");
1639 }
1640 AP_DECLARE(int) ap_unescape_url_reserved(char *url, const char *reserved)
1641 {
1642     return unescape_url(url, NULL, reserved);
1643 }
1644 #endif
1645
1646 AP_DECLARE(int) ap_unescape_urlencoded(char *query)
1647 {
1648     char *slider;
1649
1650     /* replace plus with a space */
1651     if (query) {
1652         for (slider = query; *slider; slider++) {
1653             if (*slider == '+') {
1654                 *slider = ' ';
1655             }
1656         }
1657     }
1658
1659     /* unescape everything else */
1660     return unescape_url(query, NULL, NULL);
1661 }
1662
1663 AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
1664                                        apr_port_t port, const request_rec *r)
1665 {
1666     if (ap_is_default_port(port, r)) {
1667         return apr_pstrdup(p, hostname);
1668     }
1669     else {
1670         return apr_psprintf(p, "%s:%u", hostname, port);
1671     }
1672 }
1673
1674 AP_DECLARE(int) ap_unescape_all(char *url)
1675 {
1676     return unescape_url(url, NULL, NULL);
1677 }
1678
1679 /* c2x takes an unsigned, and expects the caller has guaranteed that
1680  * 0 <= what < 256... which usually means that you have to cast to
1681  * unsigned char first, because (unsigned)(char)(x) first goes through
1682  * signed extension to an int before the unsigned cast.
1683  *
1684  * The reason for this assumption is to assist gcc code generation --
1685  * the unsigned char -> unsigned extension is already done earlier in
1686  * both uses of this code, so there's no need to waste time doing it
1687  * again.
1688  */
1689 static const char c2x_table[] = "0123456789abcdef";
1690
1691 static APR_INLINE unsigned char *c2x(unsigned what, unsigned char prefix,
1692                                      unsigned char *where)
1693 {
1694 #if APR_CHARSET_EBCDIC
1695     what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
1696 #endif /*APR_CHARSET_EBCDIC*/
1697     *where++ = prefix;
1698     *where++ = c2x_table[what >> 4];
1699     *where++ = c2x_table[what & 0xf];
1700     return where;
1701 }
1702
1703 /*
1704  * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1705  * routine is (should be) OS independent.
1706  *
1707  * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1708  * cases if a ':' occurs before the first '/' in the URL, the URL should be
1709  * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1710  * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1711  * efficiency reasons, we don't use escape_path_segment(), which is provided for
1712  * reference. Again, RFC 1808 is where this stuff is defined.
1713  *
1714  * If partial is set, os_escape_path() assumes that the path will be appended to
1715  * something with a '/' in it (and thus does not prefix "./").
1716  */
1717
1718 AP_DECLARE(char *) ap_escape_path_segment_buffer(char *copy, const char *segment)
1719 {
1720     const unsigned char *s = (const unsigned char *)segment;
1721     unsigned char *d = (unsigned char *)copy;
1722     unsigned c;
1723
1724     while ((c = *s)) {
1725         if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1726             d = c2x(c, '%', d);
1727         }
1728         else {
1729             *d++ = c;
1730         }
1731         ++s;
1732     }
1733     *d = '\0';
1734     return copy;
1735 }
1736
1737 AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
1738 {
1739     return ap_escape_path_segment_buffer(apr_palloc(p, 3 * strlen(segment) + 1), segment);
1740 }
1741
1742 AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
1743 {
1744     char *copy = apr_palloc(p, 3 * strlen(path) + 3);
1745     const unsigned char *s = (const unsigned char *)path;
1746     unsigned char *d = (unsigned char *)copy;
1747     unsigned c;
1748
1749     if (!partial) {
1750         const char *colon = ap_strchr_c(path, ':');
1751         const char *slash = ap_strchr_c(path, '/');
1752
1753         if (colon && (!slash || colon < slash)) {
1754             *d++ = '.';
1755             *d++ = '/';
1756         }
1757     }
1758     while ((c = *s)) {
1759         if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1760             d = c2x(c, '%', d);
1761         }
1762         else {
1763             *d++ = c;
1764         }
1765         ++s;
1766     }
1767     *d = '\0';
1768     return copy;
1769 }
1770
1771 AP_DECLARE(char *) ap_escape_urlencoded_buffer(char *copy, const char *buffer)
1772 {
1773     const unsigned char *s = (const unsigned char *)buffer;
1774     unsigned char *d = (unsigned char *)copy;
1775     unsigned c;
1776
1777     while ((c = *s)) {
1778         if (TEST_CHAR(c, T_ESCAPE_URLENCODED)) {
1779             d = c2x(c, '%', d);
1780         }
1781         else if (c == ' ') {
1782             *d++ = '+';
1783         }
1784         else {
1785             *d++ = c;
1786         }
1787         ++s;
1788     }
1789     *d = '\0';
1790     return copy;
1791 }
1792
1793 AP_DECLARE(char *) ap_escape_urlencoded(apr_pool_t *p, const char *buffer)
1794 {
1795     return ap_escape_urlencoded_buffer(apr_palloc(p, 3 * strlen(buffer) + 1), buffer);
1796 }
1797
1798 /* ap_escape_uri is now a macro for os_escape_path */
1799
1800 AP_DECLARE(char *) ap_escape_html2(apr_pool_t *p, const char *s, int toasc)
1801 {
1802     int i, j;
1803     char *x;
1804
1805     /* first, count the number of extra characters */
1806     for (i = 0, j = 0; s[i] != '\0'; i++)
1807         if (s[i] == '<' || s[i] == '>')
1808             j += 3;
1809         else if (s[i] == '&')
1810             j += 4;
1811         else if (s[i] == '"')
1812             j += 5;
1813         else if (toasc && !apr_isascii(s[i]))
1814             j += 5;
1815
1816     if (j == 0)
1817         return apr_pstrmemdup(p, s, i);
1818
1819     x = apr_palloc(p, i + j + 1);
1820     for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1821         if (s[i] == '<') {
1822             memcpy(&x[j], "&lt;", 4);
1823             j += 3;
1824         }
1825         else if (s[i] == '>') {
1826             memcpy(&x[j], "&gt;", 4);
1827             j += 3;
1828         }
1829         else if (s[i] == '&') {
1830             memcpy(&x[j], "&amp;", 5);
1831             j += 4;
1832         }
1833         else if (s[i] == '"') {
1834             memcpy(&x[j], "&quot;", 6);
1835             j += 5;
1836         }
1837         else if (toasc && !apr_isascii(s[i])) {
1838             char *esc = apr_psprintf(p, "&#%3.3d;", (unsigned char)s[i]);
1839             memcpy(&x[j], esc, 6);
1840             j += 5;
1841         }
1842         else
1843             x[j] = s[i];
1844
1845     x[j] = '\0';
1846     return x;
1847 }
1848 AP_DECLARE(char *) ap_escape_logitem(apr_pool_t *p, const char *str)
1849 {
1850     char *ret;
1851     unsigned char *d;
1852     const unsigned char *s;
1853     int length = 0;
1854
1855     if (!str) {
1856         return NULL;
1857     }
1858
1859     /* First, compute the space needed for the escaped string.
1860      * This could be tweaked a bit for '\b', '\n'... These characters
1861      * should not be common, so do not bother. */
1862     s = (const unsigned char *)str;
1863     for (; *s; ++s) {
1864         if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
1865             length += 4;        /* for '\\' + c2x() */
1866         }
1867         else {
1868             length++;
1869         }
1870     }
1871     
1872     ret = apr_palloc(p, length + 1);
1873     d = (unsigned char *)ret;
1874     s = (const unsigned char *)str;
1875     for (; *s; ++s) {
1876
1877         if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
1878             *d++ = '\\';
1879             switch(*s) {
1880             case '\b':
1881                 *d++ = 'b';
1882                 break;
1883             case '\n':
1884                 *d++ = 'n';
1885                 break;
1886             case '\r':
1887                 *d++ = 'r';
1888                 break;
1889             case '\t':
1890                 *d++ = 't';
1891                 break;
1892             case '\v':
1893                 *d++ = 'v';
1894                 break;
1895             case '\\':
1896             case '"':
1897                 *d++ = *s;
1898                 break;
1899             default:
1900                 c2x(*s, 'x', d);
1901                 d += 3;
1902             }
1903         }
1904         else {
1905             *d++ = *s;
1906         }
1907     }
1908     *d = '\0';
1909
1910     return ret;
1911 }
1912
1913 AP_DECLARE(apr_size_t) ap_escape_errorlog_item(char *dest, const char *source,
1914                                                apr_size_t buflen)
1915 {
1916     unsigned char *d, *ep;
1917     const unsigned char *s;
1918
1919     if (!source || !buflen) { /* be safe */
1920         return 0;
1921     }
1922
1923     d = (unsigned char *)dest;
1924     s = (const unsigned char *)source;
1925     ep = d + buflen - 1;
1926
1927     for (; d < ep && *s; ++s) {
1928
1929         if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
1930             *d++ = '\\';
1931             if (d >= ep) {
1932                 --d;
1933                 break;
1934             }
1935
1936             switch(*s) {
1937             case '\b':
1938                 *d++ = 'b';
1939                 break;
1940             case '\n':
1941                 *d++ = 'n';
1942                 break;
1943             case '\r':
1944                 *d++ = 'r';
1945                 break;
1946             case '\t':
1947                 *d++ = 't';
1948                 break;
1949             case '\v':
1950                 *d++ = 'v';
1951                 break;
1952             case '\\':
1953                 *d++ = *s;
1954                 break;
1955             case '"': /* no need for this in error log */
1956                 d[-1] = *s;
1957                 break;
1958             default:
1959                 if (d >= ep - 2) {
1960                     ep = --d; /* break the for loop as well */
1961                     break;
1962                 }
1963                 c2x(*s, 'x', d);
1964                 d += 3;
1965             }
1966         }
1967         else {
1968             *d++ = *s;
1969         }
1970     }
1971     *d = '\0';
1972
1973     return (d - (unsigned char *)dest);
1974 }
1975
1976 AP_DECLARE(void) ap_bin2hex(const void *src, apr_size_t srclen, char *dest)
1977 {
1978     const unsigned char *in = src;
1979     apr_size_t i;
1980
1981     for (i = 0; i < srclen; i++) {
1982         *dest++ = c2x_table[in[i] >> 4];
1983         *dest++ = c2x_table[in[i] & 0xf];
1984     }
1985     *dest = '\0';
1986 }
1987
1988 AP_DECLARE(int) ap_has_cntrl(const char *str)
1989 {
1990     while (*str) {
1991         if (apr_iscntrl(*str))
1992             return 1;
1993         str++;
1994     }
1995     return 0;
1996 }
1997
1998 AP_DECLARE(int) ap_is_directory(apr_pool_t *p, const char *path)
1999 {
2000     apr_finfo_t finfo;
2001
2002     if (apr_stat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
2003         return 0;                /* in error condition, just return no */
2004
2005     return (finfo.filetype == APR_DIR);
2006 }
2007
2008 AP_DECLARE(int) ap_is_rdirectory(apr_pool_t *p, const char *path)
2009 {
2010     apr_finfo_t finfo;
2011
2012     if (apr_stat(&finfo, path, APR_FINFO_LINK | APR_FINFO_TYPE, p) != APR_SUCCESS)
2013         return 0;                /* in error condition, just return no */
2014
2015     return (finfo.filetype == APR_DIR);
2016 }
2017
2018 AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
2019                                   const char *src2)
2020 {
2021     apr_size_t len1, len2;
2022     char *path;
2023
2024     len1 = strlen(src1);
2025     len2 = strlen(src2);
2026      /* allocate +3 for '/' delimiter, trailing NULL and overallocate
2027       * one extra byte to allow the caller to add a trailing '/'
2028       */
2029     path = (char *)apr_palloc(a, len1 + len2 + 3);
2030     if (len1 == 0) {
2031         *path = '/';
2032         memcpy(path + 1, src2, len2 + 1);
2033     }
2034     else {
2035         char *next;
2036         memcpy(path, src1, len1);
2037         next = path + len1;
2038         if (next[-1] != '/') {
2039             *next++ = '/';
2040         }
2041         memcpy(next, src2, len2 + 1);
2042     }
2043     return path;
2044 }
2045
2046 /*
2047  * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
2048  */
2049 AP_DECLARE(int) ap_is_url(const char *u)
2050 {
2051     register int x;
2052
2053     for (x = 0; u[x] != ':'; x++) {
2054         if ((!u[x]) ||
2055             ((!apr_isalpha(u[x])) && (!apr_isdigit(u[x])) &&
2056              (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
2057             return 0;
2058         }
2059     }
2060
2061     return (x ? 1 : 0);                /* If the first character is ':', it's broken, too */
2062 }
2063
2064 AP_DECLARE(int) ap_ind(const char *s, char c)
2065 {
2066     const char *p = ap_strchr_c(s, c);
2067
2068     if (p == NULL)
2069         return -1;
2070     return p - s;
2071 }
2072
2073 AP_DECLARE(int) ap_rind(const char *s, char c)
2074 {
2075     const char *p = ap_strrchr_c(s, c);
2076
2077     if (p == NULL)
2078         return -1;
2079     return p - s;
2080 }
2081
2082 AP_DECLARE(void) ap_str_tolower(char *str)
2083 {
2084     while (*str) {
2085         *str = apr_tolower(*str);
2086         ++str;
2087     }
2088 }
2089
2090 AP_DECLARE(void) ap_str_toupper(char *str)
2091 {
2092     while (*str) {
2093         *str = apr_toupper(*str);
2094         ++str;
2095     }
2096 }
2097
2098 /*
2099  * We must return a FQDN
2100  */
2101 char *ap_get_local_host(apr_pool_t *a)
2102 {
2103 #ifndef MAXHOSTNAMELEN
2104 #define MAXHOSTNAMELEN 256
2105 #endif
2106     char str[MAXHOSTNAMELEN + 1];
2107     char *server_hostname = NULL;
2108     apr_sockaddr_t *sockaddr;
2109     char *hostname;
2110
2111     if (apr_gethostname(str, sizeof(str) - 1, a) != APR_SUCCESS) {
2112         ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a, APLOGNO(00556)
2113                      "%s: apr_gethostname() failed to determine ServerName",
2114                      ap_server_argv0);
2115     } else {
2116         str[sizeof(str) - 1] = '\0';
2117         if (apr_sockaddr_info_get(&sockaddr, str, APR_UNSPEC, 0, 0, a) == APR_SUCCESS) {
2118             if ( (apr_getnameinfo(&hostname, sockaddr, 0) == APR_SUCCESS) &&
2119                 (ap_strchr_c(hostname, '.')) ) {
2120                 server_hostname = apr_pstrdup(a, hostname);
2121                 return server_hostname;
2122             } else if (ap_strchr_c(str, '.')) {
2123                 server_hostname = apr_pstrdup(a, str);
2124             } else {
2125                 apr_sockaddr_ip_get(&hostname, sockaddr);
2126                 server_hostname = apr_pstrdup(a, hostname);
2127             }
2128         } else {
2129             ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a, APLOGNO(00557)
2130                          "%s: apr_sockaddr_info_get() failed for %s",
2131                          ap_server_argv0, str);
2132         }
2133     }
2134
2135     if (!server_hostname)
2136         server_hostname = apr_pstrdup(a, "127.0.0.1");
2137
2138     ap_log_perror(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0, a, APLOGNO(00558)
2139                  "%s: Could not reliably determine the server's fully qualified "
2140                  "domain name, using %s. Set the 'ServerName' directive globally "
2141                  "to suppress this message",
2142                  ap_server_argv0, server_hostname);
2143
2144     return server_hostname;
2145 }
2146
2147 /* simple 'pool' alloc()ing glue to apr_base64.c
2148  */
2149 AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
2150 {
2151     char *decoded;
2152     int l;
2153
2154     decoded = (char *) apr_palloc(p, 1 + apr_base64_decode_len(bufcoded));
2155     l = apr_base64_decode(decoded, bufcoded);
2156     decoded[l] = '\0'; /* make binary sequence into string */
2157
2158     return decoded;
2159 }
2160
2161 AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string)
2162 {
2163     char *encoded;
2164     int l = strlen(string);
2165
2166     encoded = (char *) apr_palloc(p, 1 + apr_base64_encode_len(l));
2167     l = apr_base64_encode(encoded, string, l);
2168     encoded[l] = '\0'; /* make binary sequence into string */
2169
2170     return encoded;
2171 }
2172
2173 /* we want to downcase the type/subtype for comparison purposes
2174  * but nothing else because ;parameter=foo values are case sensitive.
2175  * XXX: in truth we want to downcase parameter names... but really,
2176  * apache has never handled parameters and such correctly.  You
2177  * also need to compress spaces and such to be able to compare
2178  * properly. -djg
2179  */
2180 AP_DECLARE(void) ap_content_type_tolower(char *str)
2181 {
2182     char *semi;
2183
2184     semi = strchr(str, ';');
2185     if (semi) {
2186         *semi = '\0';
2187     }
2188
2189     ap_str_tolower(str);
2190
2191     if (semi) {
2192         *semi = ';';
2193     }
2194 }
2195
2196 /*
2197  * Given a string, replace any bare " with \" .
2198  */
2199 AP_DECLARE(char *) ap_escape_quotes(apr_pool_t *p, const char *instring)
2200 {
2201     int newlen = 0;
2202     const char *inchr = instring;
2203     char *outchr, *outstring;
2204
2205     /*
2206      * Look through the input string, jogging the length of the output
2207      * string up by an extra byte each time we find an unescaped ".
2208      */
2209     while (*inchr != '\0') {
2210         newlen++;
2211         if (*inchr == '"') {
2212             newlen++;
2213         }
2214         /*
2215          * If we find a slosh, and it's not the last byte in the string,
2216          * it's escaping something - advance past both bytes.
2217          */
2218         if ((*inchr == '\\') && (inchr[1] != '\0')) {
2219             inchr++;
2220             newlen++;
2221         }
2222         inchr++;
2223     }
2224     outstring = apr_palloc(p, newlen + 1);
2225     inchr = instring;
2226     outchr = outstring;
2227     /*
2228      * Now copy the input string to the output string, inserting a slosh
2229      * in front of every " that doesn't already have one.
2230      */
2231     while (*inchr != '\0') {
2232         if ((*inchr == '\\') && (inchr[1] != '\0')) {
2233             *outchr++ = *inchr++;
2234             *outchr++ = *inchr++;
2235         }
2236         if (*inchr == '"') {
2237             *outchr++ = '\\';
2238         }
2239         if (*inchr != '\0') {
2240             *outchr++ = *inchr++;
2241         }
2242     }
2243     *outchr = '\0';
2244     return outstring;
2245 }
2246
2247 /*
2248  * Given a string, append the PID deliminated by delim.
2249  * Usually used to create a pid-appended filepath name
2250  * (eg: /a/b/foo -> /a/b/foo.6726). A function, and not
2251  * a macro, to avoid unistd.h dependency
2252  */
2253 AP_DECLARE(char *) ap_append_pid(apr_pool_t *p, const char *string,
2254                                     const char *delim)
2255 {
2256     return apr_psprintf(p, "%s%s%" APR_PID_T_FMT, string,
2257                         delim, getpid());
2258
2259 }
2260
2261 /**
2262  * Parse a given timeout parameter string into an apr_interval_time_t value.
2263  * The unit of the time interval is given as postfix string to the numeric
2264  * string. Currently the following units are understood:
2265  *
2266  * ms    : milliseconds
2267  * s     : seconds
2268  * mi[n] : minutes
2269  * h     : hours
2270  *
2271  * If no unit is contained in the given timeout parameter the default_time_unit
2272  * will be used instead.
2273  * @param timeout_parameter The string containing the timeout parameter.
2274  * @param timeout The timeout value to be returned.
2275  * @param default_time_unit The default time unit to use if none is specified
2276  * in timeout_parameter.
2277  * @return Status value indicating whether the parsing was successful or not.
2278  */
2279 AP_DECLARE(apr_status_t) ap_timeout_parameter_parse(
2280                                                const char *timeout_parameter,
2281                                                apr_interval_time_t *timeout,
2282                                                const char *default_time_unit)
2283 {
2284     char *endp;
2285     const char *time_str;
2286     apr_int64_t tout;
2287
2288     tout = apr_strtoi64(timeout_parameter, &endp, 10);
2289     if (errno) {
2290         return errno;
2291     }
2292     if (!endp || !*endp) {
2293         time_str = default_time_unit;
2294     }
2295     else {
2296         time_str = endp;
2297     }
2298
2299     switch (*time_str) {
2300         /* Time is in seconds */
2301     case 's':
2302         *timeout = (apr_interval_time_t) apr_time_from_sec(tout);
2303         break;
2304     case 'h':
2305         /* Time is in hours */
2306         *timeout = (apr_interval_time_t) apr_time_from_sec(tout * 3600);
2307         break;
2308     case 'm':
2309         switch (*(++time_str)) {
2310         /* Time is in milliseconds */
2311         case 's':
2312             *timeout = (apr_interval_time_t) tout * 1000;
2313             break;
2314         /* Time is in minutes */
2315         case 'i':
2316             *timeout = (apr_interval_time_t) apr_time_from_sec(tout * 60);
2317             break;
2318         default:
2319             return APR_EGENERAL;
2320         }
2321         break;
2322     default:
2323         return APR_EGENERAL;
2324     }
2325     return APR_SUCCESS;
2326 }
2327
2328 /**
2329  * Determine if a request has a request body or not.
2330  *
2331  * @param r the request_rec of the request
2332  * @return truth value
2333  */
2334 AP_DECLARE(int) ap_request_has_body(request_rec *r)
2335 {
2336     apr_off_t cl;
2337     char *estr;
2338     const char *cls;
2339     int has_body;
2340
2341     has_body = (!r->header_only
2342                 && (r->kept_body
2343                     || apr_table_get(r->headers_in, "Transfer-Encoding")
2344                     || ( (cls = apr_table_get(r->headers_in, "Content-Length"))
2345                         && (apr_strtoff(&cl, cls, &estr, 10) == APR_SUCCESS)
2346                         && (!*estr)
2347                         && (cl > 0) )
2348                     )
2349                 );
2350     return has_body;
2351 }
2352
2353 AP_DECLARE_NONSTD(apr_status_t) ap_pool_cleanup_set_null(void *data_)
2354 {
2355     void **ptr = (void **)data_;
2356     *ptr = NULL;
2357     return APR_SUCCESS;
2358 }
2359
2360 AP_DECLARE(apr_status_t) ap_str2_alnum(const char *src, char *dest) {
2361
2362     for ( ; *src; src++, dest++)
2363     {
2364         if (!apr_isprint(*src))
2365             *dest = 'x';
2366         else if (!apr_isalnum(*src))
2367             *dest = '_';
2368         else
2369             *dest = (char)*src;
2370     }
2371     *dest = '\0';
2372     return APR_SUCCESS;
2373
2374 }
2375
2376 AP_DECLARE(apr_status_t) ap_pstr2_alnum(apr_pool_t *p, const char *src,
2377                                         const char **dest)
2378 {
2379     char *new = apr_palloc(p, strlen(src)+1);
2380     if (!new)
2381         return APR_ENOMEM;
2382     *dest = new;
2383     return ap_str2_alnum(src, new);
2384 }
2385
2386 /**
2387  * Read the body and parse any form found, which must be of the
2388  * type application/x-www-form-urlencoded.
2389  *
2390  * Name/value pairs are returned in an array, with the names as
2391  * strings with a maximum length of HUGE_STRING_LEN, and the
2392  * values as bucket brigades. This allows values to be arbitrarily
2393  * large.
2394  *
2395  * All url-encoding is removed from both the names and the values
2396  * on the fly. The names are interpreted as strings, while the
2397  * values are interpreted as blocks of binary data, that may
2398  * contain the 0 character.
2399  *
2400  * In order to ensure that resource limits are not exceeded, a
2401  * maximum size must be provided. If the sum of the lengths of
2402  * the names and the values exceed this size, this function
2403  * will return HTTP_REQUEST_ENTITY_TOO_LARGE.
2404  *
2405  * An optional number of parameters can be provided, if the number
2406  * of parameters provided exceeds this amount, this function will
2407  * return HTTP_REQUEST_ENTITY_TOO_LARGE. If this value is negative,
2408  * no limit is imposed, and the number of parameters is in turn
2409  * constrained by the size parameter above.
2410  *
2411  * This function honours any kept_body configuration, and the
2412  * original raw request body will be saved to the kept_body brigade
2413  * if so configured, just as ap_discard_request_body does.
2414  *
2415  * NOTE: File upload is not yet supported, but can be without change
2416  * to the function call.
2417  */
2418
2419 /* form parsing stuff */
2420 typedef enum {
2421     FORM_NORMAL,
2422     FORM_AMP,
2423     FORM_NAME,
2424     FORM_VALUE,
2425     FORM_PERCENTA,
2426     FORM_PERCENTB,
2427     FORM_ABORT
2428 } ap_form_type_t;
2429
2430 AP_DECLARE(int) ap_parse_form_data(request_rec *r, ap_filter_t *f,
2431                                    apr_array_header_t **ptr,
2432                                    apr_size_t num, apr_size_t usize)
2433 {
2434     apr_bucket_brigade *bb = NULL;
2435     int seen_eos = 0;
2436     char buffer[HUGE_STRING_LEN + 1];
2437     const char *ct;
2438     apr_size_t offset = 0;
2439     apr_ssize_t size;
2440     ap_form_type_t state = FORM_NAME, percent = FORM_NORMAL;
2441     ap_form_pair_t *pair = NULL;
2442     apr_array_header_t *pairs = apr_array_make(r->pool, 4, sizeof(ap_form_pair_t));
2443
2444     char hi = 0;
2445     char low = 0;
2446
2447     *ptr = pairs;
2448
2449     /* sanity check - we only support forms for now */
2450     ct = apr_table_get(r->headers_in, "Content-Type");
2451     if (!ct || strncasecmp("application/x-www-form-urlencoded", ct, 33)) {
2452         return ap_discard_request_body(r);
2453     }
2454
2455     if (usize > APR_SIZE_MAX >> 1)
2456         size = APR_SIZE_MAX >> 1;
2457     else
2458         size = usize;
2459
2460     if (!f) {
2461         f = r->input_filters;
2462     }
2463
2464     bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2465     do {
2466         apr_bucket *bucket = NULL, *last = NULL;
2467
2468         int rv = ap_get_brigade(f, bb, AP_MODE_READBYTES,
2469                                 APR_BLOCK_READ, HUGE_STRING_LEN);
2470         if (rv != APR_SUCCESS) {
2471             apr_brigade_destroy(bb);
2472             return (rv == AP_FILTER_ERROR) ? rv : HTTP_BAD_REQUEST;
2473         }
2474
2475         for (bucket = APR_BRIGADE_FIRST(bb);
2476              bucket != APR_BRIGADE_SENTINEL(bb);
2477              last = bucket, bucket = APR_BUCKET_NEXT(bucket)) {
2478             const char *data;
2479             apr_size_t len, slide;
2480
2481             if (last) {
2482                 apr_bucket_delete(last);
2483             }
2484             if (APR_BUCKET_IS_EOS(bucket)) {
2485                 seen_eos = 1;
2486                 break;
2487             }
2488             if (bucket->length == 0) {
2489                 continue;
2490             }
2491
2492             rv = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
2493             if (rv != APR_SUCCESS) {
2494                 apr_brigade_destroy(bb);
2495                 return HTTP_BAD_REQUEST;
2496             }
2497
2498             slide = len;
2499             while (state != FORM_ABORT && slide-- > 0 && size >= 0 && num != 0) {
2500                 char c = *data++;
2501                 if ('+' == c) {
2502                     c = ' ';
2503                 }
2504                 else if ('&' == c) {
2505                     state = FORM_AMP;
2506                 }
2507                 if ('%' == c) {
2508                     percent = FORM_PERCENTA;
2509                     continue;
2510                 }
2511                 if (FORM_PERCENTA == percent) {
2512                     if (c >= 'a') {
2513                         hi = c - 'a' + 10;
2514                     }
2515                     else if (c >= 'A') {
2516                         hi = c - 'A' + 10;
2517                     }
2518                     else if (c >= '0') {
2519                         hi = c - '0';
2520                     }
2521                     hi = hi << 4;
2522                     percent = FORM_PERCENTB;
2523                     continue;
2524                 }
2525                 if (FORM_PERCENTB == percent) {
2526                     if (c >= 'a') {
2527                         low = c - 'a' + 10;
2528                     }
2529                     else if (c >= 'A') {
2530                         low = c - 'A' + 10;
2531                     }
2532                     else if (c >= '0') {
2533                         low = c - '0';
2534                     }
2535                     c = low | hi;
2536                     percent = FORM_NORMAL;
2537                 }
2538                 switch (state) {
2539                     case FORM_AMP:
2540                         if (pair) {
2541                             const char *tmp = apr_pmemdup(r->pool, buffer, offset);
2542                             apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
2543                             APR_BRIGADE_INSERT_TAIL(pair->value, b);
2544                         }
2545                         state = FORM_NAME;
2546                         pair = NULL;
2547                         offset = 0;
2548                         num--;
2549                         break;
2550                     case FORM_NAME:
2551                         if (offset < HUGE_STRING_LEN) {
2552                             if ('=' == c) {
2553                                 buffer[offset] = 0;
2554                                 offset = 0;
2555                                 pair = (ap_form_pair_t *) apr_array_push(pairs);
2556                                 pair->name = apr_pstrdup(r->pool, buffer);
2557                                 pair->value = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2558                                 state = FORM_VALUE;
2559                             }
2560                             else {
2561                                 buffer[offset++] = c;
2562                                 size--;
2563                             }
2564                         }
2565                         else {
2566                             state = FORM_ABORT;
2567                         }
2568                         break;
2569                     case FORM_VALUE:
2570                         if (offset >= HUGE_STRING_LEN) {
2571                             const char *tmp = apr_pmemdup(r->pool, buffer, offset);
2572                             apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
2573                             APR_BRIGADE_INSERT_TAIL(pair->value, b);
2574                             offset = 0;
2575                         }
2576                         buffer[offset++] = c;
2577                         size--;
2578                         break;
2579                     default:
2580                         break;
2581                 }
2582             }
2583
2584         }
2585
2586         apr_brigade_cleanup(bb);
2587     } while (!seen_eos);
2588
2589     if (FORM_ABORT == state || size < 0 || num == 0) {
2590         return HTTP_REQUEST_ENTITY_TOO_LARGE;
2591     }
2592     else if (FORM_VALUE == state && pair && offset > 0) {
2593         const char *tmp = apr_pmemdup(r->pool, buffer, offset);
2594         apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
2595         APR_BRIGADE_INSERT_TAIL(pair->value, b);
2596     }
2597
2598     return OK;
2599
2600 }
2601
2602 #define VARBUF_SMALL_SIZE 2048
2603 #define VARBUF_MAX_SIZE   (APR_SIZE_MAX - 1 -                                \
2604                            APR_ALIGN_DEFAULT(sizeof(struct ap_varbuf_info)))
2605
2606 struct ap_varbuf_info {
2607     struct apr_memnode_t *node;
2608     apr_allocator_t *allocator;
2609 };
2610
2611 static apr_status_t varbuf_cleanup(void *info_)
2612 {
2613     struct ap_varbuf_info *info = info_;
2614     info->node->next = NULL;
2615     apr_allocator_free(info->allocator, info->node);
2616     return APR_SUCCESS;
2617 }
2618
2619 const char nul = '\0';
2620 static char * const varbuf_empty = (char *)&nul;
2621
2622 AP_DECLARE(void) ap_varbuf_init(apr_pool_t *p, struct ap_varbuf *vb,
2623                                 apr_size_t init_size)
2624 {
2625     vb->buf = varbuf_empty;
2626     vb->avail = 0;
2627     vb->strlen = AP_VARBUF_UNKNOWN;
2628     vb->pool = p;
2629     vb->info = NULL;
2630
2631     ap_varbuf_grow(vb, init_size);
2632 }
2633
2634 AP_DECLARE(void) ap_varbuf_grow(struct ap_varbuf *vb, apr_size_t new_len)
2635 {
2636     apr_memnode_t *new_node = NULL;
2637     apr_allocator_t *allocator;
2638     struct ap_varbuf_info *new_info;
2639     char *new;
2640
2641     AP_DEBUG_ASSERT(vb->strlen == AP_VARBUF_UNKNOWN || vb->avail >= vb->strlen);
2642
2643     if (new_len <= vb->avail)
2644         return;
2645
2646     if (new_len < 2 * vb->avail && vb->avail < VARBUF_MAX_SIZE/2) {
2647         /* at least double the size, to avoid repeated reallocations */
2648         new_len = 2 * vb->avail;
2649     }
2650     else if (new_len > VARBUF_MAX_SIZE) {
2651         apr_abortfunc_t abort_fn = apr_pool_abort_get(vb->pool);
2652         ap_assert(abort_fn != NULL);
2653         abort_fn(APR_ENOMEM);
2654         return;
2655     }
2656
2657     new_len++;  /* add space for trailing \0 */
2658     if (new_len <= VARBUF_SMALL_SIZE) {
2659         new_len = APR_ALIGN_DEFAULT(new_len);
2660         new = apr_palloc(vb->pool, new_len);
2661         if (vb->avail && vb->strlen != 0) {
2662             AP_DEBUG_ASSERT(vb->buf != NULL);
2663             AP_DEBUG_ASSERT(vb->buf != varbuf_empty);
2664             if (new == vb->buf + vb->avail + 1) {
2665                 /* We are lucky: the new memory lies directly after our old
2666                  * buffer, we can now use both.
2667                  */
2668                 vb->avail += new_len;
2669                 return;
2670             }
2671             else {
2672                 /* copy up to vb->strlen + 1 bytes */
2673                 memcpy(new, vb->buf, vb->strlen == AP_VARBUF_UNKNOWN ?
2674                                      vb->avail + 1 : vb->strlen + 1);
2675             }
2676         }
2677         else {
2678             *new = '\0';
2679         }
2680         vb->avail = new_len - 1;
2681         vb->buf = new;
2682         return;
2683     }
2684
2685     /* The required block is rather larger. Use allocator directly so that
2686      * the memory can be freed independently from the pool. */
2687     allocator = apr_pool_allocator_get(vb->pool);
2688     if (new_len <= VARBUF_MAX_SIZE)
2689         new_node = apr_allocator_alloc(allocator,
2690                                        new_len + APR_ALIGN_DEFAULT(sizeof(*new_info)));
2691     if (!new_node) {
2692         apr_abortfunc_t abort_fn = apr_pool_abort_get(vb->pool);
2693         ap_assert(abort_fn != NULL);
2694         abort_fn(APR_ENOMEM);
2695         return;
2696     }
2697     new_info = (struct ap_varbuf_info *)new_node->first_avail;
2698     new_node->first_avail += APR_ALIGN_DEFAULT(sizeof(*new_info));
2699     new_info->node = new_node;
2700     new_info->allocator = allocator;
2701     new = new_node->first_avail;
2702     AP_DEBUG_ASSERT(new_node->endp - new_node->first_avail >= new_len);
2703     new_len = new_node->endp - new_node->first_avail;
2704
2705     if (vb->avail && vb->strlen != 0)
2706         memcpy(new, vb->buf, vb->strlen == AP_VARBUF_UNKNOWN ?
2707                              vb->avail + 1 : vb->strlen + 1);
2708     else
2709         *new = '\0';
2710     if (vb->info)
2711         apr_pool_cleanup_run(vb->pool, vb->info, varbuf_cleanup);
2712     apr_pool_cleanup_register(vb->pool, new_info, varbuf_cleanup,
2713                               apr_pool_cleanup_null);
2714     vb->info = new_info;
2715     vb->buf = new;
2716     vb->avail = new_len - 1;
2717 }
2718
2719 AP_DECLARE(void) ap_varbuf_strmemcat(struct ap_varbuf *vb, const char *str,
2720                                      int len)
2721 {
2722     if (len == 0)
2723         return;
2724     if (!vb->avail) {
2725         ap_varbuf_grow(vb, len);
2726         memcpy(vb->buf, str, len);
2727         vb->buf[len] = '\0';
2728         vb->strlen = len;
2729         return;
2730     }
2731     if (vb->strlen == AP_VARBUF_UNKNOWN)
2732         vb->strlen = strlen(vb->buf);
2733     ap_varbuf_grow(vb, vb->strlen + len);
2734     memcpy(vb->buf + vb->strlen, str, len);
2735     vb->strlen += len;
2736     vb->buf[vb->strlen] = '\0';
2737 }
2738
2739 AP_DECLARE(void) ap_varbuf_free(struct ap_varbuf *vb)
2740 {
2741     if (vb->info) {
2742         apr_pool_cleanup_run(vb->pool, vb->info, varbuf_cleanup);
2743         vb->info = NULL;
2744     }
2745     vb->buf = NULL;
2746 }
2747
2748 AP_DECLARE(char *) ap_varbuf_pdup(apr_pool_t *p, struct ap_varbuf *buf,
2749                                   const char *prepend, apr_size_t prepend_len,
2750                                   const char *append, apr_size_t append_len,
2751                                   apr_size_t *new_len)
2752 {
2753     apr_size_t i = 0;
2754     struct iovec vec[3];
2755
2756     if (prepend) {
2757         vec[i].iov_base = (void *)prepend;
2758         vec[i].iov_len = prepend_len;
2759         i++;
2760     }
2761     if (buf->avail && buf->strlen) {
2762         if (buf->strlen == AP_VARBUF_UNKNOWN)
2763             buf->strlen = strlen(buf->buf);
2764         vec[i].iov_base = (void *)buf->buf;
2765         vec[i].iov_len = buf->strlen;
2766         i++;
2767     }
2768     if (append) {
2769         vec[i].iov_base = (void *)append;
2770         vec[i].iov_len = append_len;
2771         i++;
2772     }
2773     if (i)
2774         return apr_pstrcatv(p, vec, i, new_len);
2775
2776     if (new_len)
2777         *new_len = 0;
2778     return "";
2779 }
2780
2781 AP_DECLARE(apr_status_t) ap_varbuf_regsub(struct ap_varbuf *vb,
2782                                           const char *input,
2783                                           const char *source,
2784                                           apr_size_t nmatch,
2785                                           ap_regmatch_t pmatch[],
2786                                           apr_size_t maxlen)
2787 {
2788     return regsub_core(NULL, NULL, vb, input, source, nmatch, pmatch, maxlen);
2789 }
2790
2791 static const char * const oom_message = "[crit] Memory allocation failed, "
2792                                         "aborting process." APR_EOL_STR;
2793
2794 AP_DECLARE(void) ap_abort_on_oom()
2795 {
2796     int written, count = strlen(oom_message);
2797     const char *buf = oom_message;
2798     do {
2799         written = write(STDERR_FILENO, buf, count);
2800         if (written == count)
2801             break;
2802         if (written > 0) {
2803             buf += written;
2804             count -= written;
2805         }
2806     } while (written >= 0 || errno == EINTR);
2807     abort();
2808 }
2809
2810 AP_DECLARE(void *) ap_malloc(size_t size)
2811 {
2812     void *p = malloc(size);
2813     if (p == NULL && size != 0)
2814         ap_abort_on_oom();
2815     return p;
2816 }
2817
2818 AP_DECLARE(void *) ap_calloc(size_t nelem, size_t size)
2819 {
2820     void *p = calloc(nelem, size);
2821     if (p == NULL && nelem != 0 && size != 0)
2822         ap_abort_on_oom();
2823     return p;
2824 }
2825
2826 AP_DECLARE(void *) ap_realloc(void *ptr, size_t size)
2827 {
2828     void *p = realloc(ptr, size);
2829     if (p == NULL && size != 0)
2830         ap_abort_on_oom();
2831     return p;
2832 }
2833
2834 AP_DECLARE(void) ap_get_sload(ap_sload_t *ld)
2835 {
2836     int i, j, server_limit, thread_limit;
2837     int ready = 0;
2838     int busy = 0;
2839     int total;
2840     ap_generation_t mpm_generation;
2841
2842     /* preload errored fields, we overwrite */
2843     ld->idle = -1;
2844     ld->busy = -1;
2845     ld->bytes_served = 0;
2846     ld->access_count = 0;
2847
2848     ap_mpm_query(AP_MPMQ_GENERATION, &mpm_generation);
2849     ap_mpm_query(AP_MPMQ_HARD_LIMIT_THREADS, &thread_limit);
2850     ap_mpm_query(AP_MPMQ_HARD_LIMIT_DAEMONS, &server_limit);
2851
2852     for (i = 0; i < server_limit; i++) {
2853         process_score *ps;
2854         ps = ap_get_scoreboard_process(i);
2855
2856         for (j = 0; j < thread_limit; j++) {
2857             int res;
2858             worker_score *ws = NULL;
2859             ws = &ap_scoreboard_image->servers[i][j];
2860             res = ws->status;
2861
2862             if (!ps->quiescing && ps->pid) {
2863                 if (res == SERVER_READY && ps->generation == mpm_generation) {
2864                     ready++;
2865                 }
2866                 else if (res != SERVER_DEAD &&
2867                          res != SERVER_STARTING && res != SERVER_IDLE_KILL &&
2868                          ps->generation == mpm_generation) {
2869                     busy++;
2870                 }   
2871             }
2872
2873             if (ap_extended_status && !ps->quiescing && ps->pid) {
2874                 if (ws->access_count != 0 
2875                     || (res != SERVER_READY && res != SERVER_DEAD)) {
2876                     ld->access_count += ws->access_count;
2877                     ld->bytes_served += ws->bytes_served;
2878                 }
2879             }
2880         }
2881     }
2882     total = busy + ready;
2883     if (total) {
2884         ld->idle = ready * 100 / total;
2885         ld->busy = busy * 100 / total;
2886     }
2887 }
2888
2889 AP_DECLARE(void) ap_get_loadavg(ap_loadavg_t *ld)
2890 {
2891     /* preload errored fields, we overwrite */
2892     ld->loadavg = -1.0;
2893     ld->loadavg5 = -1.0;
2894     ld->loadavg15 = -1.0;
2895
2896 #if HAVE_GETLOADAVG
2897     {
2898         double la[3];
2899         int num;
2900
2901         num = getloadavg(la, 3);
2902         if (num > 0) {
2903             ld->loadavg = (float)la[0];
2904         }
2905         if (num > 1) {
2906             ld->loadavg5 = (float)la[1];
2907         }
2908         if (num > 2) {
2909             ld->loadavg15 = (float)la[2];
2910         }
2911     }
2912 #endif
2913 }
2914
2915 static const char * const pw_cache_note_name = "conn_cache_note";
2916 struct pw_cache {
2917     /* varbuf contains concatenated password and hash */
2918     struct ap_varbuf vb;
2919     apr_size_t pwlen;
2920     apr_status_t result;
2921 };
2922
2923 AP_DECLARE(apr_status_t) ap_password_validate(request_rec *r,
2924                                               const char *username,
2925                                               const char *passwd,
2926                                               const char *hash)
2927 {
2928     struct pw_cache *cache;
2929     apr_size_t hashlen;
2930
2931     cache = (struct pw_cache *)apr_table_get(r->connection->notes, pw_cache_note_name);
2932     if (cache != NULL) {
2933         if (strncmp(passwd, cache->vb.buf, cache->pwlen) == 0
2934             && strcmp(hash, cache->vb.buf + cache->pwlen) == 0) {
2935             return cache->result;
2936         }
2937         /* make ap_varbuf_grow below not copy the old data */
2938         cache->vb.strlen = 0;
2939     }
2940     else {
2941         cache = apr_palloc(r->connection->pool, sizeof(struct pw_cache));
2942         ap_varbuf_init(r->connection->pool, &cache->vb, 0);
2943         apr_table_setn(r->connection->notes, pw_cache_note_name, (void *)cache);
2944     }
2945     cache->pwlen = strlen(passwd);
2946     hashlen = strlen(hash);
2947     ap_varbuf_grow(&cache->vb, cache->pwlen + hashlen + 1);
2948     memcpy(cache->vb.buf, passwd, cache->pwlen);
2949     memcpy(cache->vb.buf + cache->pwlen, hash, hashlen + 1);
2950     cache->result = apr_password_validate(passwd, hash);
2951     return cache->result;
2952 }
2953
2954 AP_DECLARE(char *) ap_get_exec_line(apr_pool_t *p,
2955                                     const char *cmd,
2956                                     const char * const * argv)
2957 {
2958     char buf[MAX_STRING_LEN];
2959     apr_procattr_t *procattr;
2960     apr_proc_t *proc;
2961     apr_file_t *fp;
2962     apr_size_t nbytes = 1;
2963     char c;
2964     int k;
2965
2966     if (apr_procattr_create(&procattr, p) != APR_SUCCESS)
2967         return NULL;
2968     if (apr_procattr_io_set(procattr, APR_FULL_BLOCK, APR_FULL_BLOCK,
2969                             APR_FULL_BLOCK) != APR_SUCCESS)
2970         return NULL;
2971     if (apr_procattr_dir_set(procattr,
2972                              ap_make_dirstr_parent(p, cmd)) != APR_SUCCESS)
2973         return NULL;
2974     if (apr_procattr_cmdtype_set(procattr, APR_PROGRAM) != APR_SUCCESS)
2975         return NULL;
2976     proc = apr_pcalloc(p, sizeof(apr_proc_t));
2977     if (apr_proc_create(proc, cmd, argv, NULL, procattr, p) != APR_SUCCESS)
2978         return NULL;
2979     fp = proc->out;
2980
2981     if (fp == NULL)
2982         return NULL;
2983     /* XXX: we are reading 1 byte at a time here */
2984     for (k = 0; apr_file_read(fp, &c, &nbytes) == APR_SUCCESS
2985                 && nbytes == 1 && (k < MAX_STRING_LEN-1)     ; ) {
2986         if (c == '\n' || c == '\r')
2987             break;
2988         buf[k++] = c;
2989     }
2990     buf[k] = '\0'; 
2991     apr_file_close(fp);
2992
2993     return buf;
2994 }