1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2001 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 * util.c: string utility things
63 * 1995-96 Many changes by the Apache Software Foundation
68 * #define DEBUG to trace all cfg_open*()/cfg_closefile() calls
69 * #define DEBUG_CFG_LINES to trace every line read from the config files
73 #include "apr_strings.h"
76 #define APR_WANT_STDIO
77 #define APR_WANT_STRFUNC
84 #include <netdb.h> /* for gethostbyname() */
89 #include "ap_config.h"
90 #include "apr_base64.h"
92 #include "http_main.h"
94 #include "http_protocol.h"
95 #include "http_config.h"
96 #include "util_ebcdic.h"
105 /* A bunch of functions in util.c scan strings looking for certain characters.
106 * To make that more efficient we encode a lookup table. The test_char_table
107 * is generated automatically by gen_test_char.c.
109 #include "test_char.h"
111 /* we assume the folks using this ensure 0 <= c < 256... which means
112 * you need a cast to (unsigned char) first, you can't just plug a
113 * char in here and get it to work, because if char is signed then it
114 * will first be sign extended.
116 #define TEST_CHAR(c, f) (test_char_table[(unsigned)(c)] & (f))
119 * Examine a field value (such as a media-/content-type) string and return
120 * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
122 AP_DECLARE(char *) ap_field_noparam(apr_pool_t *p, const char *intype)
126 if (intype == NULL) return NULL;
128 semi = ap_strchr_c(intype, ';');
130 return apr_pstrdup(p, intype);
133 while ((semi > intype) && apr_isspace(semi[-1])) {
136 return apr_pstrndup(p, intype, semi - intype);
140 AP_DECLARE(char *) ap_ht_time(apr_pool_t *p, apr_time_t t, const char *fmt, int gmt)
143 char ts[MAX_STRING_LEN];
144 char tf[MAX_STRING_LEN];
145 apr_exploded_time_t xt;
151 apr_explode_gmt(&xt, t);
152 /* Convert %Z to "GMT" and %z to "+0000";
153 * on hosts that do not have a time zone string in struct tm,
154 * strftime must assume its argument is local time.
156 for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
158 if (*f != '%') continue;
169 case 'z': /* common extension */
183 apr_explode_localtime(&xt, t);
186 /* check return code? */
187 apr_strftime(ts, &retcode, MAX_STRING_LEN, fmt, &xt);
188 ts[MAX_STRING_LEN - 1] = '\0';
189 return apr_pstrdup(p, ts);
192 /* Roy owes Rob beer. */
193 /* Rob owes Roy dinner. */
195 /* These legacy comments would make a lot more sense if Roy hadn't
196 * replaced the old later_than() routine with util_date.c.
198 * Well, okay, they still wouldn't make any sense.
201 /* Match = 0, NoMatch = 1, Abort = -1
202 * Based loosely on sections of wildmat.c by Rich Salz
203 * Hmmm... shouldn't this really go component by component?
205 AP_DECLARE(int) ap_strcmp_match(const char *str, const char *exp)
209 for (x = 0, y = 0; exp[y]; ++y, ++x) {
210 if ((!str[x]) && (exp[y] != '*'))
213 while (exp[++y] == '*');
218 if ((ret = ap_strcmp_match(&str[x++], &exp[y])) != 1)
223 else if ((exp[y] != '?') && (str[x] != exp[y]))
226 return (str[x] != '\0');
229 AP_DECLARE(int) ap_strcasecmp_match(const char *str, const char *exp)
233 for (x = 0, y = 0; exp[y]; ++y, ++x) {
234 if ((!str[x]) && (exp[y] != '*'))
237 while (exp[++y] == '*');
242 if ((ret = ap_strcasecmp_match(&str[x++], &exp[y])) != 1)
247 else if ((exp[y] != '?') && (apr_tolower(str[x]) != apr_tolower(exp[y])))
250 return (str[x] != '\0');
253 AP_DECLARE(int) ap_is_matchexp(const char *str)
257 for (x = 0; str[x]; x++)
258 if ((str[x] == '*') || (str[x] == '?'))
264 * Here's a pool-based interface to POSIX regex's regcomp().
265 * Note that we return regex_t instead of being passed one.
266 * The reason is that if you use an already-used regex_t structure,
267 * the memory that you've already allocated gets forgotten, and
268 * regfree() doesn't clear it. So we don't allow it.
271 static apr_status_t regex_cleanup(void *preg)
273 regfree((regex_t *) preg);
277 AP_DECLARE(regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
280 regex_t *preg = apr_palloc(p, sizeof(regex_t));
282 if (regcomp(preg, pattern, cflags)) {
286 apr_pool_cleanup_register(p, (void *) preg, regex_cleanup, regex_cleanup);
291 AP_DECLARE(void) ap_pregfree(apr_pool_t *p, regex_t * reg)
294 apr_pool_cleanup_kill(p, (void *) reg, regex_cleanup);
298 * Similar to standard strstr() but we ignore case in this version.
299 * Based on the strstr() implementation further below.
301 AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
309 for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
310 if (*s1 == '\0') return(NULL);
311 /* found first character of s2, see if the rest matches */
314 while (apr_tolower(*++p1) == apr_tolower(*++p2)) {
316 /* both strings ended together */
321 /* second string ended, a match */
324 /* didn't find a match here, try starting at next character in s1 */
331 * Returns an offsetted pointer in bigstring immediately after
332 * prefix. Returns bigstring if bigstring doesn't start with
333 * prefix or if prefix is longer than bigstring while still matching.
334 * NOTE: pointer returned is relative to bigstring, so we
335 * can use standard pointer comparisons in the calling function
336 * (eg: test if ap_stripprefix(a,b) == a)
338 AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
347 while (*p1 && *prefix) {
348 if (*p1++ != *prefix++)
354 /* hit the end of bigstring! */
359 * Apache stub function for the regex libraries regexec() to make sure the
360 * whole regex(3) API is available through the Apache (exported) namespace.
361 * This is especially important for the DSO situations of modules.
362 * DO NOT MAKE A MACRO OUT OF THIS FUNCTION!
364 AP_DECLARE(int) ap_regexec(regex_t *preg, const char *string,
365 size_t nmatch, regmatch_t pmatch[], int eflags)
367 return regexec(preg, string, nmatch, pmatch, eflags);
370 AP_DECLARE(size_t) ap_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
372 return regerror(errcode, preg, errbuf, errbuf_size);
376 /* This function substitutes for $0-$9, filling in regular expression
377 * submatches. Pass it the same nmatch and pmatch arguments that you
378 * passed ap_regexec(). pmatch should not be greater than the maximum number
379 * of subexpressions - i.e. one more than the re_nsub member of regex_t.
381 * input should be the string with the $-expressions, source should be the
382 * string that was matched against.
384 * It returns the substituted string, or NULL on error.
386 * Parts of this code are based on Henry Spencer's regsub(), from his
387 * AT&T V8 regexp package.
390 AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input, const char *source,
391 size_t nmatch, regmatch_t pmatch[])
393 const char *src = input;
402 return apr_pstrdup(p, src);
404 /* First pass, find the size */
408 while ((c = *src++) != '\0') {
411 else if (c == '$' && apr_isdigit(*src))
416 if (no > 9) { /* Ordinary character. */
417 if (c == '\\' && (*src == '$' || *src == '&'))
421 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
422 len += pmatch[no].rm_eo - pmatch[no].rm_so;
427 dest = dst = apr_pcalloc(p, len + 1);
429 /* Now actually fill in the string */
433 while ((c = *src++) != '\0') {
436 else if (c == '$' && apr_isdigit(*src))
441 if (no > 9) { /* Ordinary character. */
442 if (c == '\\' && (*src == '$' || *src == '&'))
446 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
447 len = pmatch[no].rm_eo - pmatch[no].rm_so;
448 memcpy(dst, source + pmatch[no].rm_so, len);
459 * Parse .. so we don't compromise security
461 AP_DECLARE(void) ap_getparents(char *name)
465 /* Four paseses, as per RFC 1808 */
466 /* a) remove ./ path segments */
468 for (l = 0, w = 0; name[l] != '\0';) {
469 if (name[l] == '.' && name[l + 1] == '/' && (l == 0 || name[l - 1] == '/'))
472 name[w++] = name[l++];
475 /* b) remove trailing . path, segment */
476 if (w == 1 && name[0] == '.')
478 else if (w > 1 && name[w - 1] == '.' && name[w - 2] == '/')
482 /* c) remove all xx/../ segments. (including leading ../ and /../) */
485 while (name[l] != '\0') {
486 if (name[l] == '.' && name[l + 1] == '.' && name[l + 2] == '/' &&
487 (l == 0 || name[l - 1] == '/')) {
488 register int m = l + 3, n;
492 while (l >= 0 && name[l] != '/')
499 while ((name[n] = name[m]))
506 /* d) remove trailing xx/.. segment. */
507 if (l == 2 && name[0] == '.' && name[1] == '.')
509 else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.' && name[l - 3] == '/') {
512 while (l >= 0 && name[l] != '/')
522 AP_DECLARE(void) ap_no2slash(char *name)
528 #ifdef HAVE_UNC_PATHS
529 /* Check for UNC names. Leave leading two slashes. */
530 if (s[0] == '/' && s[1] == '/')
535 if ((*d++ = *s) == '/') {
549 * copy at most n leading directories of s into d
550 * d should be at least as large as s plus 1 extra byte
552 * the return value is the ever useful pointer to the trailing \0 of d
554 * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments,
555 * so that if n == 0, "/" is returned in d with n == 1
556 * and s == "e:/test.html", "e:/" is returned in d
557 * *** See also directory_walk in modules/http/http_request.c
560 * /a/b, 0 ==> / (true for all platforms)
569 * c:/a/b 3 ==> c:/a/b
570 * c:/a/b 4 ==> c:/a/b
572 AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
581 if (*s == '\0' || (*s == '/' && (--n) == 0)) {
593 * return the parent directory name including trailing / of the file s
595 AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
597 const char *last_slash = ap_strrchr_c(s, '/');
601 if (last_slash == NULL) {
602 /* XXX: well this is really broken if this happens */
603 return (apr_pstrdup(p, "/"));
605 l = (last_slash - s) + 1;
606 d = apr_palloc(p, l + 1);
613 AP_DECLARE(int) ap_count_dirs(const char *path)
617 for (x = 0, n = 0; path[x]; x++)
623 AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
625 return ap_getword(atrans, (const char **) line, stop);
628 AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
630 const char *pos = ap_strchr_c(*line, stop);
634 res = apr_pstrdup(atrans, *line);
635 *line += strlen(*line);
639 res = apr_pstrndup(atrans, *line, pos - *line);
641 while (*pos == stop) {
650 AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
652 return ap_getword_white(atrans, (const char **) line);
655 AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
660 for (x = 0; (*line)[x]; x++) {
661 if (apr_isspace((*line)[x])) {
668 res = apr_pstrdup(atrans, *line);
669 *line += strlen(*line);
673 res = apr_palloc(atrans, pos + 1);
674 apr_cpystrn(res, *line, pos + 1);
676 while (apr_isspace((*line)[pos]))
684 AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line, char stop)
686 return ap_getword_nulls(atrans, (const char **) line, stop);
689 AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line, char stop)
691 const char *pos = ap_strchr_c(*line, stop);
695 res = apr_pstrdup(atrans, *line);
696 *line += strlen(*line);
700 res = apr_pstrndup(atrans, *line, pos - *line);
709 /* Get a word, (new) config-file style --- quoted strings and backslashes
713 static char *substring_conf(apr_pool_t *p, const char *start, int len, char quote)
715 char *result = apr_palloc(p, len + 2);
719 for (i = 0; i < len; ++i) {
720 if (start[i] == '\\' && (start[i + 1] == '\\'
721 || (quote && start[i + 1] == quote)))
722 *resp++ = start[++i];
728 #if RESOLVE_ENV_PER_TOKEN
729 return ap_resolve_env(p,result);
735 AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
737 return ap_getword_conf(p, (const char **) line);
740 AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
742 const char *str = *line, *strend;
746 while (*str && apr_isspace(*str))
754 if ((quote = *str) == '"' || quote == '\'') {
756 while (*strend && *strend != quote) {
757 if (*strend == '\\' && strend[1] && strend[1] == quote)
762 res = substring_conf(p, str + 1, strend - str - 1, quote);
764 if (*strend == quote)
769 while (*strend && !apr_isspace(*strend))
772 res = substring_conf(p, str, strend - str, 0);
775 while (*strend && apr_isspace(*strend))
781 /* Check a string for any ${ENV} environment variable
782 * construct and replace each them by the value of
783 * that environment variable, if it exists. If the
784 * environment value does not exist, leave the ${ENV}
785 * construct alone; it means something else.
787 AP_DECLARE(const char *) ap_resolve_env(apr_pool_t *p, const char * word)
789 char tmp[ MAX_STRING_LEN ];
793 if (!(s=ap_strchr_c(word,'$')))
797 /* XXX - relies on strncat() to add '\0'
799 strncat(tmp,word,s - word);
800 if ((s[1] == '{') && (e=ap_strchr_c(s,'}'))) {
807 strncat(tmp, s, e2-s);
811 /* ignore invalid strings */
815 } while ((s=ap_strchr_c(word,'$')));
818 return apr_pstrdup(p,tmp);
820 AP_DECLARE(int) ap_cfg_closefile(configfile_t *cfp)
823 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL,
824 "Done with config file %s", cfp->name);
826 return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
829 static apr_status_t cfg_close(void *param)
831 apr_file_t *cfp = (apr_file_t *) param;
832 return (apr_file_close(cfp));
835 static int cfg_getch(void *param)
838 apr_file_t *cfp = (apr_file_t *) param;
839 if (apr_file_getc(&ch, cfp) == APR_SUCCESS)
844 static void *cfg_getstr(void *buf, size_t bufsiz, void *param)
846 apr_file_t *cfp = (apr_file_t *) param;
848 rv = apr_file_gets(buf, bufsiz, cfp);
849 if (rv == APR_SUCCESS || (rv == APR_EOF && strcmp(buf, "")))
854 /* Open a configfile_t as FILE, return open configfile_t struct pointer */
855 AP_DECLARE(apr_status_t) ap_pcfg_openfile(configfile_t **ret_cfg, apr_pool_t *p, const char *name)
857 configfile_t *new_cfg;
858 apr_file_t *file = NULL;
866 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
867 "Internal error: pcfg_openfile() called with NULL filename");
871 /* ### We no longer need the test ap_os_is_filename_valid() here
872 * The directory was already walked on a segment by segment basis,
873 * so we should never be called with a bad path element, and device
874 * names as access file names never posed as security threats, since
875 * it was the admin's choice to assign the .htaccess file's name.
878 status = apr_file_open(&file, name, APR_READ | APR_BUFFERED, APR_OS_DEFAULT, p);
880 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL,
881 "Opening config file %s (%s)",
882 name, (status != APR_SUCCESS) ?
883 apr_strerror(status, buf, sizeof(buf)) : "successful");
885 if (status != APR_SUCCESS)
888 status = apr_file_info_get(&finfo, APR_FINFO_TYPE, file);
889 if (status != APR_SUCCESS)
892 if (finfo.filetype != APR_REG &&
893 #if defined(WIN32) || defined(OS2)
894 !(strcasecmp(name, "nul") == 0 ||
895 (strlen(name) >= 4 &&
896 strcasecmp(name + strlen(name) - 4, "/nul") == 0))) {
898 strcmp(name, "/dev/null") != 0) {
899 #endif /* WIN32 || OS2 */
900 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
901 "Access to file %s denied by server: not a regular file",
903 apr_file_close(file);
907 new_cfg = apr_palloc(p, sizeof(*new_cfg));
908 new_cfg->param = file;
909 new_cfg->name = apr_pstrdup(p, name);
910 new_cfg->getch = (int (*)(void *)) cfg_getch;
911 new_cfg->getstr = (void *(*)(void *, size_t, void *)) cfg_getstr;
912 new_cfg->close = (int (*)(void *)) cfg_close;
913 new_cfg->line_number = 0;
919 /* Allocate a configfile_t handle with user defined functions and params */
920 AP_DECLARE(configfile_t *) ap_pcfg_open_custom(apr_pool_t *p, const char *descr,
922 int(*getch)(void *param),
923 void *(*getstr) (void *buf, size_t bufsiz, void *param),
924 int(*close_func)(void *param))
926 configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
928 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL, "Opening config handler %s", descr);
930 new_cfg->param = param;
931 new_cfg->name = descr;
932 new_cfg->getch = getch;
933 new_cfg->getstr = getstr;
934 new_cfg->close = close_func;
935 new_cfg->line_number = 0;
940 /* Read one character from a configfile_t */
941 AP_DECLARE(int) ap_cfg_getc(configfile_t *cfp)
943 register int ch = cfp->getch(cfp->param);
950 /* Read one line from open configfile_t, strip LF, increase line number */
951 /* If custom handler does not define a getstr() function, read char by char */
952 AP_DECLARE(int) ap_cfg_getline(char *buf, size_t bufsize, configfile_t *cfp)
954 /* If a "get string" function is defined, use it */
955 if (cfp->getstr != NULL) {
959 size_t cbufsize = bufsize;
963 if (cfp->getstr(cbuf, cbufsize, cfp->param) == NULL)
967 * check for line continuation,
968 * i.e. match [^\\]\\[\r]\n only
971 while (cp < cbuf+cbufsize && *cp != '\0')
973 if (cp > cbuf && cp[-1] == LF) {
975 if (cp > cbuf && cp[-1] == CR)
977 if (cp > cbuf && cp[-1] == '\\') {
979 if (!(cp > cbuf && cp[-1] == '\\')) {
981 * line continuation requested -
982 * then remove backslash and continue
984 cbufsize -= (cp-cbuf);
990 * no real continuation because escaped -
991 * then just remove escape character
993 for ( ; cp < cbuf+cbufsize && *cp != '\0'; cp++)
1002 * Leading and trailing white space is eliminated completely
1005 while (apr_isspace(*src))
1007 /* blast trailing whitespace */
1008 dst = &src[strlen(src)];
1009 while (--dst >= src && apr_isspace(*dst))
1011 /* Zap leading whitespace by shifting */
1013 for (dst = buf; (*dst++ = *src++) != '\0'; )
1016 #ifdef DEBUG_CFG_LINES
1017 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1021 /* No "get string" function defined; read character by character */
1023 register size_t i = 0;
1026 /* skip leading whitespace */
1028 c = cfp->getch(cfp->param);
1029 } while (c == '\t' || c == ' ');
1035 /* too small, assume caller is crazy */
1040 if ((c == '\t') || (c == ' ')) {
1042 while ((c == '\t') || (c == ' '))
1043 c = cfp->getch(cfp->param);
1046 /* silently ignore CR (_assume_ that a LF follows) */
1047 c = cfp->getch(cfp->param);
1050 /* increase line number and return on LF */
1053 if (c == EOF || c == 0x4 || c == LF || i >= (bufsize - 2)) {
1055 * check for line continuation
1057 if (i > 0 && buf[i-1] == '\\') {
1059 if (!(i > 0 && buf[i-1] == '\\')) {
1060 /* line is continued */
1061 c = cfp->getch(cfp->param);
1064 /* else nothing needs be done because
1065 * then the backslash is escaped and
1066 * we just strip to a single one
1069 /* blast trailing whitespace */
1070 while (i > 0 && apr_isspace(buf[i - 1]))
1073 #ifdef DEBUG_CFG_LINES
1074 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1080 c = cfp->getch(cfp->param);
1085 /* Size an HTTP header field list item, as separated by a comma.
1086 * The return value is a pointer to the beginning of the non-empty list item
1087 * within the original string (or NULL if there is none) and the address
1088 * of field is shifted to the next non-comma, non-whitespace character.
1089 * len is the length of the item excluding any beginning whitespace.
1091 AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1093 const unsigned char *ptr = (const unsigned char *)*field;
1094 const unsigned char *token;
1095 int in_qpair, in_qstr, in_com;
1097 /* Find first non-comma, non-whitespace byte */
1099 while (*ptr == ',' || apr_isspace(*ptr))
1104 /* Find the end of this item, skipping over dead bits */
1106 for (in_qpair = in_qstr = in_com = 0;
1107 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1115 case '\\': in_qpair = 1; /* quoted-pair */
1117 case '"' : if (!in_com) /* quoted string delim */
1120 case '(' : if (!in_qstr) /* comment (may nest) */
1123 case ')' : if (in_com) /* end comment */
1131 if ((*len = (ptr - token)) == 0) {
1132 *field = (const char *)ptr;
1136 /* Advance field pointer to the next non-comma, non-white byte */
1138 while (*ptr == ',' || apr_isspace(*ptr))
1141 *field = (const char *)ptr;
1142 return (const char *)token;
1145 /* Retrieve an HTTP header field list item, as separated by a comma,
1146 * while stripping insignificant whitespace and lowercasing anything not in
1147 * a quoted string or comment. The return value is a new string containing
1148 * the converted list item (or NULL if none) and the address pointed to by
1149 * field is shifted to the next non-comma, non-whitespace.
1151 AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1153 const char *tok_start;
1154 const unsigned char *ptr;
1157 int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1159 /* Find the beginning and maximum length of the list item so that
1160 * we can allocate a buffer for the new string and reset the field.
1162 if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1165 token = apr_palloc(p, tok_len + 1);
1167 /* Scan the token again, but this time copy only the good bytes.
1168 * We skip extra whitespace and any whitespace around a '=', '/',
1169 * or ';' and lowercase normal characters not within a comment,
1170 * quoted-string or quoted-pair.
1172 for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1173 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1182 case '\\': in_qpair = 1;
1188 case '"' : if (!in_com)
1195 case '(' : if (!in_qstr)
1202 case ')' : if (in_com)
1208 case '\t': if (addspace)
1210 if (in_com || in_qstr)
1217 case ';' : if (!(in_com || in_qstr))
1221 default : if (addspace == 1)
1223 *pos++ = (in_com || in_qstr) ? *ptr
1224 : apr_tolower(*ptr);
1235 /* Find an item in canonical form (lowercase, no extra spaces) within
1236 * an HTTP field value list. Returns 1 if found, 0 if not found.
1237 * This would be much more efficient if we stored header fields as
1238 * an array of list items as they are received instead of a plain string.
1240 AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line, const char *tok)
1242 const unsigned char *pos;
1243 const unsigned char *ptr = (const unsigned char *)line;
1244 int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1249 do { /* loop for each item in line's list */
1251 /* Find first non-comma, non-whitespace byte */
1253 while (*ptr == ',' || apr_isspace(*ptr))
1257 good = 1; /* until proven otherwise for this item */
1259 break; /* no items left and nothing good found */
1261 /* We skip extra whitespace and any whitespace around a '=', '/',
1262 * or ';' and lowercase normal characters not within a comment,
1263 * quoted-string or quoted-pair.
1265 for (pos = (const unsigned char *)tok;
1266 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1272 good = (*pos++ == *ptr);
1276 case '\\': in_qpair = 1;
1278 good = good && (*pos++ == ' ');
1279 good = good && (*pos++ == *ptr);
1282 case '"' : if (!in_com)
1285 good = good && (*pos++ == ' ');
1286 good = good && (*pos++ == *ptr);
1289 case '(' : if (!in_qstr)
1292 good = good && (*pos++ == ' ');
1293 good = good && (*pos++ == *ptr);
1296 case ')' : if (in_com)
1298 good = good && (*pos++ == *ptr);
1302 case '\t': if (addspace || !good)
1304 if (in_com || in_qstr)
1305 good = (*pos++ == *ptr);
1311 case ';' : if (!(in_com || in_qstr))
1313 good = good && (*pos++ == *ptr);
1315 default : if (!good)
1318 good = (*pos++ == ' ');
1319 if (in_com || in_qstr)
1320 good = good && (*pos++ == *ptr);
1322 good = good && (*pos++ == apr_tolower(*ptr));
1329 good = 0; /* not good if only a prefix was matched */
1331 } while (*ptr && !good);
1337 /* Retrieve a token, spacing over it and returning a pointer to
1338 * the first non-white byte afterwards. Note that these tokens
1339 * are delimited by semis and commas; and can also be delimited
1340 * by whitespace at the caller's option.
1343 AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line, int accept_white)
1345 const char *ptr = *accept_line;
1346 const char *tok_start;
1350 /* Find first non-white byte */
1352 while (*ptr && apr_isspace(*ptr))
1357 /* find token end, skipping over quoted strings.
1358 * (comments are already gone).
1361 while (*ptr && (accept_white || !apr_isspace(*ptr))
1362 && *ptr != ';' && *ptr != ',') {
1369 tok_len = ptr - tok_start;
1370 token = apr_pstrndup(p, tok_start, tok_len);
1372 /* Advance accept_line pointer to the next non-white byte */
1374 while (*ptr && apr_isspace(*ptr))
1382 /* find http tokens, see the definition of token from RFC2068 */
1383 AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1385 const unsigned char *start_token;
1386 const unsigned char *s;
1391 s = (const unsigned char *)line;
1393 /* find start of token, skip all stop characters, note NUL
1394 * isn't a token stop, so we don't need to test for it
1396 while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1403 /* find end of the token */
1404 while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1407 if (!strncasecmp((const char *)start_token, (const char *)tok, s - start_token)) {
1417 AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line, const char *tok)
1419 int llen, tlen, lidx;
1424 llen = strlen(line);
1429 ((lidx > 0) && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1432 return (strncasecmp(&line[lidx], tok, tlen) == 0);
1435 AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1439 const unsigned char *s;
1441 cmd = apr_palloc(p, 2 * strlen(str) + 1); /* Be safe */
1442 d = (unsigned char *)cmd;
1443 s = (const unsigned char *)str;
1446 #if defined(OS2) || defined(WIN32)
1447 /* Don't allow '&' in parameters under OS/2. */
1448 /* This can be used to send commands to the shell. */
1455 if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1465 static char x2c(const char *what)
1467 register char digit;
1469 #if !APR_CHARSET_EBCDIC
1470 digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
1472 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
1473 #else /*APR_CHARSET_EBCDIC*/
1480 digit = apr_xlate_conv_byte(ap_hdrs_from_ascii, 0xFF & strtol(xstr, NULL, 16));
1481 #endif /*APR_CHARSET_EBCDIC*/
1487 * Returns 0 on success, non-zero on error
1489 * bad % escape returns HTTP_BAD_REQUEST
1491 * decoding %00 -> \0
1492 * decoding %2f -> / (a special character)
1493 * returns HTTP_NOT_FOUND
1495 AP_DECLARE(int) ap_unescape_url(char *url)
1497 register int badesc, badpath;
1502 /* Initial scan for first '%'. Don't bother writing values before
1504 y = strchr(url, '%');
1508 for (x = y; *y; ++x, ++y) {
1512 if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1519 if (*x == '/' || *x == '\0')
1526 return HTTP_BAD_REQUEST;
1528 return HTTP_NOT_FOUND;
1533 AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
1534 apr_port_t port, const request_rec *r)
1536 if (ap_is_default_port(port, r))
1537 return apr_pstrdup(p, hostname);
1539 return apr_psprintf(p, "%s:%u", hostname, port);
1543 /* c2x takes an unsigned, and expects the caller has guaranteed that
1544 * 0 <= what < 256... which usually means that you have to cast to
1545 * unsigned char first, because (unsigned)(char)(x) first goes through
1546 * signed extension to an int before the unsigned cast.
1548 * The reason for this assumption is to assist gcc code generation --
1549 * the unsigned char -> unsigned extension is already done earlier in
1550 * both uses of this code, so there's no need to waste time doing it
1553 static const char c2x_table[] = "0123456789abcdef";
1555 static apr_inline unsigned char *c2x(unsigned what, unsigned char *where)
1557 #if APR_CHARSET_EBCDIC
1558 what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
1559 #endif /*APR_CHARSET_EBCDIC*/
1561 *where++ = c2x_table[what >> 4];
1562 *where++ = c2x_table[what & 0xf];
1567 * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1568 * routine is (should be) OS independent.
1570 * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1571 * cases if a ':' occurs before the first '/' in the URL, the URL should be
1572 * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1573 * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1574 * efficiency reasons, we don't use escape_path_segment(), which is provided for
1575 * reference. Again, RFC 1808 is where this stuff is defined.
1577 * If partial is set, os_escape_path() assumes that the path will be appended to
1578 * something with a '/' in it (and thus does not prefix "./").
1581 AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
1583 char *copy = apr_palloc(p, 3 * strlen(segment) + 1);
1584 const unsigned char *s = (const unsigned char *)segment;
1585 unsigned char *d = (unsigned char *)copy;
1589 if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1601 AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
1603 char *copy = apr_palloc(p, 3 * strlen(path) + 3);
1604 const unsigned char *s = (const unsigned char *)path;
1605 unsigned char *d = (unsigned char *)copy;
1609 const char *colon = ap_strchr_c(path, ':');
1610 const char *slash = ap_strchr_c(path, '/');
1612 if (colon && (!slash || colon < slash)) {
1618 if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1630 /* ap_escape_uri is now a macro for os_escape_path */
1632 AP_DECLARE(char *) ap_escape_html(apr_pool_t *p, const char *s)
1637 /* first, count the number of extra characters */
1638 for (i = 0, j = 0; s[i] != '\0'; i++)
1639 if (s[i] == '<' || s[i] == '>')
1641 else if (s[i] == '&')
1645 return apr_pstrndup(p, s, i);
1647 x = apr_palloc(p, i + j + 1);
1648 for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1650 memcpy(&x[j], "<", 4);
1653 else if (s[i] == '>') {
1654 memcpy(&x[j], ">", 4);
1657 else if (s[i] == '&') {
1658 memcpy(&x[j], "&", 5);
1668 AP_DECLARE(int) ap_is_directory(apr_pool_t *p, const char *path)
1672 if (apr_stat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
1673 return 0; /* in error condition, just return no */
1675 return (finfo.filetype == APR_DIR);
1678 AP_DECLARE(int) ap_is_rdirectory(apr_pool_t *p, const char *path)
1682 if (apr_lstat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
1683 return 0; /* in error condition, just return no */
1685 return (finfo.filetype == APR_DIR);
1688 AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
1695 return apr_pstrcat(a, "/", src2, NULL);
1697 if (src1[x - 1] != '/')
1698 return apr_pstrcat(a, src1, "/", src2, NULL);
1700 return apr_pstrcat(a, src1, src2, NULL);
1704 * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
1706 AP_DECLARE(int) ap_is_url(const char *u)
1710 for (x = 0; u[x] != ':'; x++) {
1712 ((!apr_isalpha(u[x])) && (!apr_isdigit(u[x])) &&
1713 (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
1718 return (x ? 1 : 0); /* If the first character is ':', it's broken, too */
1721 AP_DECLARE(int) ap_ind(const char *s, char c)
1723 const char *p = ap_strchr_c(s, c);
1730 AP_DECLARE(int) ap_rind(const char *s, char c)
1732 const char *p = ap_strrchr_c(s, c);
1739 AP_DECLARE(void) ap_str_tolower(char *str)
1742 *str = apr_tolower(*str);
1747 static char *find_fqdn(apr_pool_t *a, struct hostent *p)
1751 if (!strchr(p->h_name, '.')) {
1752 for (x = 0; p->h_aliases[x]; ++x) {
1753 if (strchr(p->h_aliases[x], '.') &&
1754 (!strncasecmp(p->h_aliases[x], p->h_name, strlen(p->h_name))))
1755 return apr_pstrdup(a, p->h_aliases[x]);
1759 return apr_pstrdup(a, (void *) p->h_name);
1762 char *ap_get_local_host(apr_pool_t *a)
1764 #ifndef MAXHOSTNAMELEN
1765 #define MAXHOSTNAMELEN 256
1767 char str[MAXHOSTNAMELEN + 1];
1768 char *server_hostname = NULL;
1772 if (gethostname(str, sizeof(str) - 1) == 0)
1774 if (gethostname(str, sizeof(str) - 1) != 0)
1777 ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a,
1778 "%s: gethostname() failed to determine ServerName",
1783 str[sizeof(str) - 1] = '\0';
1784 if ((!(p = gethostbyname(str)))
1785 || (!(server_hostname = find_fqdn(a, p)))) {
1786 /* Recovery - return the default servername by IP: */
1787 if (p && p->h_addr_list[0]) {
1788 apr_snprintf(str, sizeof(str), "%pA", p->h_addr_list[0]);
1789 server_hostname = apr_pstrdup(a, str);
1790 /* We will drop through to report the IP-named server */
1794 /* Since we found a fdqn, return it with no logged message. */
1795 return server_hostname;
1799 if (!server_hostname)
1800 server_hostname = apr_pstrdup(a, "127.0.0.1");
1802 ap_log_perror(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO|APLOG_STARTUP, 0, a,
1803 "%s: Could not determine the server's fully qualified "
1804 "domain name, using %s for ServerName",
1805 ap_server_argv0, server_hostname);
1807 return server_hostname;
1810 /* simple 'pool' alloc()ing glue to apr_base64.c
1812 AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
1817 decoded = (char *) apr_palloc(p, 1 + apr_base64_decode_len(bufcoded));
1818 l = apr_base64_decode(decoded, bufcoded);
1819 decoded[l] = '\0'; /* make binary sequence into string */
1824 AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string)
1827 int l = strlen(string);
1829 encoded = (char *) apr_palloc(p, 1 + apr_base64_encode_len(l));
1830 l = apr_base64_encode(encoded, string, l);
1831 encoded[l] = '\0'; /* make binary sequence into string */
1836 /* we want to downcase the type/subtype for comparison purposes
1837 * but nothing else because ;parameter=foo values are case sensitive.
1838 * XXX: in truth we want to downcase parameter names... but really,
1839 * apache has never handled parameters and such correctly. You
1840 * also need to compress spaces and such to be able to compare
1843 AP_DECLARE(void) ap_content_type_tolower(char *str)
1847 semi = strchr(str, ';');
1852 *str = apr_tolower(*str);
1861 * Given a string, replace any bare " with \" .
1863 AP_DECLARE(char *) ap_escape_quotes (apr_pool_t *p, const char *instring)
1866 const char *inchr = instring;
1867 char *outchr, *outstring;
1870 * Look through the input string, jogging the length of the output
1871 * string up by an extra byte each time we find an unescaped ".
1873 while (*inchr != '\0') {
1875 if (*inchr == '"') {
1879 * If we find a slosh, and it's not the last byte in the string,
1880 * it's escaping something - advance past both bytes.
1882 if ((*inchr == '\\') && (inchr[1] != '\0')) {
1888 outstring = apr_palloc(p, newlen + 1);
1892 * Now copy the input string to the output string, inserting a slosh
1893 * in front of every " that doesn't already have one.
1895 while (*inchr != '\0') {
1896 if ((*inchr == '\\') && (inchr[1] != '\0')) {
1897 *outchr++ = *inchr++;
1898 *outchr++ = *inchr++;
1900 if (*inchr == '"') {
1903 if (*inchr != '\0') {
1904 *outchr++ = *inchr++;