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 /* We actually compare the canonical root to this root, (but we don't
254 * waste time checking the case), since every use of this function in
255 * httpd-2.0 tests if the path is 'proper', meaning we've already passed
256 * it through apr_filepath_merge, or we haven't.
258 AP_DECLARE(int) ap_os_is_path_absolute(apr_pool_t *p, const char *dir)
261 const char *ourdir = dir;
262 if (apr_filepath_root(&newpath, &dir, 0, p) != APR_SUCCESS
263 || strncmp(newpath, ourdir, strlen(newpath)) != 0) {
269 AP_DECLARE(int) ap_is_matchexp(const char *str)
273 for (x = 0; str[x]; x++)
274 if ((str[x] == '*') || (str[x] == '?'))
280 * Here's a pool-based interface to POSIX regex's regcomp().
281 * Note that we return regex_t instead of being passed one.
282 * The reason is that if you use an already-used regex_t structure,
283 * the memory that you've already allocated gets forgotten, and
284 * regfree() doesn't clear it. So we don't allow it.
287 static apr_status_t regex_cleanup(void *preg)
289 regfree((regex_t *) preg);
293 AP_DECLARE(regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
296 regex_t *preg = apr_palloc(p, sizeof(regex_t));
298 if (regcomp(preg, pattern, cflags)) {
302 apr_pool_cleanup_register(p, (void *) preg, regex_cleanup, regex_cleanup);
307 AP_DECLARE(void) ap_pregfree(apr_pool_t *p, regex_t * reg)
310 apr_pool_cleanup_kill(p, (void *) reg, regex_cleanup);
314 * Similar to standard strstr() but we ignore case in this version.
315 * Based on the strstr() implementation further below.
317 AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
325 for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
326 if (*s1 == '\0') return(NULL);
327 /* found first character of s2, see if the rest matches */
330 while (apr_tolower(*++p1) == apr_tolower(*++p2)) {
332 /* both strings ended together */
337 /* second string ended, a match */
340 /* didn't find a match here, try starting at next character in s1 */
347 * Returns an offsetted pointer in bigstring immediately after
348 * prefix. Returns bigstring if bigstring doesn't start with
349 * prefix or if prefix is longer than bigstring while still matching.
350 * NOTE: pointer returned is relative to bigstring, so we
351 * can use standard pointer comparisons in the calling function
352 * (eg: test if ap_stripprefix(a,b) == a)
354 AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
363 while (*p1 && *prefix) {
364 if (*p1++ != *prefix++)
370 /* hit the end of bigstring! */
375 * Apache stub function for the regex libraries regexec() to make sure the
376 * whole regex(3) API is available through the Apache (exported) namespace.
377 * This is especially important for the DSO situations of modules.
378 * DO NOT MAKE A MACRO OUT OF THIS FUNCTION!
380 AP_DECLARE(int) ap_regexec(regex_t *preg, const char *string,
381 size_t nmatch, regmatch_t pmatch[], int eflags)
383 return regexec(preg, string, nmatch, pmatch, eflags);
386 AP_DECLARE(size_t) ap_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
388 return regerror(errcode, preg, errbuf, errbuf_size);
392 /* This function substitutes for $0-$9, filling in regular expression
393 * submatches. Pass it the same nmatch and pmatch arguments that you
394 * passed ap_regexec(). pmatch should not be greater than the maximum number
395 * of subexpressions - i.e. one more than the re_nsub member of regex_t.
397 * input should be the string with the $-expressions, source should be the
398 * string that was matched against.
400 * It returns the substituted string, or NULL on error.
402 * Parts of this code are based on Henry Spencer's regsub(), from his
403 * AT&T V8 regexp package.
406 AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input, const char *source,
407 size_t nmatch, regmatch_t pmatch[])
409 const char *src = input;
418 return apr_pstrdup(p, src);
420 /* First pass, find the size */
424 while ((c = *src++) != '\0') {
427 else if (c == '$' && apr_isdigit(*src))
432 if (no > 9) { /* Ordinary character. */
433 if (c == '\\' && (*src == '$' || *src == '&'))
437 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
438 len += pmatch[no].rm_eo - pmatch[no].rm_so;
443 dest = dst = apr_pcalloc(p, len + 1);
445 /* Now actually fill in the string */
449 while ((c = *src++) != '\0') {
452 else if (c == '$' && apr_isdigit(*src))
457 if (no > 9) { /* Ordinary character. */
458 if (c == '\\' && (*src == '$' || *src == '&'))
462 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
463 len = pmatch[no].rm_eo - pmatch[no].rm_so;
464 memcpy(dst, source + pmatch[no].rm_so, len);
475 * Parse .. so we don't compromise security
477 AP_DECLARE(void) ap_getparents(char *name)
482 /* Four paseses, as per RFC 1808 */
483 /* a) remove ./ path segments */
484 for (next = name; *next && (*next != '.'); next++) {
486 l = w = first_dot = next - name;
487 while (name[l] != '\0') {
488 if (name[l] == '.' && name[l + 1] == '/' && (l == 0 || name[l - 1] == '/'))
491 name[w++] = name[l++];
494 /* b) remove trailing . path, segment */
495 if (w == 1 && name[0] == '.')
497 else if (w > 1 && name[w - 1] == '.' && name[w - 2] == '/')
501 /* c) remove all xx/../ segments. (including leading ../ and /../) */
504 while (name[l] != '\0') {
505 if (name[l] == '.' && name[l + 1] == '.' && name[l + 2] == '/' &&
506 (l == 0 || name[l - 1] == '/')) {
507 register int m = l + 3, n;
511 while (l >= 0 && name[l] != '/')
518 while ((name[n] = name[m]))
525 /* d) remove trailing xx/.. segment. */
526 if (l == 2 && name[0] == '.' && name[1] == '.')
528 else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.' && name[l - 3] == '/') {
531 while (l >= 0 && name[l] != '/')
541 AP_DECLARE(void) ap_no2slash(char *name)
547 #ifdef HAVE_UNC_PATHS
548 /* Check for UNC names. Leave leading two slashes. */
549 if (s[0] == '/' && s[1] == '/')
554 if ((*d++ = *s) == '/') {
568 * copy at most n leading directories of s into d
569 * d should be at least as large as s plus 1 extra byte
571 * the return value is the ever useful pointer to the trailing \0 of d
573 * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments,
574 * so that if n == 0, "/" is returned in d with n == 1
575 * and s == "e:/test.html", "e:/" is returned in d
576 * *** See also directory_walk in modules/http/http_request.c
579 * /a/b, 0 ==> / (true for all platforms)
588 * c:/a/b 3 ==> c:/a/b
589 * c:/a/b 4 ==> c:/a/b
591 AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
600 if (*s == '\0' || (*s == '/' && (--n) == 0)) {
612 * return the parent directory name including trailing / of the file s
614 AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
616 const char *last_slash = ap_strrchr_c(s, '/');
620 if (last_slash == NULL) {
621 return apr_pstrdup(p, "");
623 l = (last_slash - s) + 1;
624 d = apr_palloc(p, l + 1);
631 AP_DECLARE(int) ap_count_dirs(const char *path)
635 for (x = 0, n = 0; path[x]; x++)
641 AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
643 return ap_getword(atrans, (const char **) line, stop);
646 AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
648 const char *pos = *line;
652 while ((*pos != stop) && *pos) {
657 res = (char *)apr_palloc(atrans, len + 1);
658 memcpy(res, *line, len);
662 while (*pos == stop) {
671 AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
673 return ap_getword_white(atrans, (const char **) line);
676 AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
681 for (x = 0; (*line)[x]; x++) {
682 if (apr_isspace((*line)[x])) {
689 res = apr_pstrdup(atrans, *line);
690 *line += strlen(*line);
694 res = apr_palloc(atrans, pos + 1);
695 apr_cpystrn(res, *line, pos + 1);
697 while (apr_isspace((*line)[pos]))
705 AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line, char stop)
707 return ap_getword_nulls(atrans, (const char **) line, stop);
710 AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line, char stop)
712 const char *pos = ap_strchr_c(*line, stop);
716 res = apr_pstrdup(atrans, *line);
717 *line += strlen(*line);
721 res = apr_pstrndup(atrans, *line, pos - *line);
730 /* Get a word, (new) config-file style --- quoted strings and backslashes
734 static char *substring_conf(apr_pool_t *p, const char *start, int len, char quote)
736 char *result = apr_palloc(p, len + 2);
740 for (i = 0; i < len; ++i) {
741 if (start[i] == '\\' && (start[i + 1] == '\\'
742 || (quote && start[i + 1] == quote)))
743 *resp++ = start[++i];
749 #if RESOLVE_ENV_PER_TOKEN
750 return ap_resolve_env(p,result);
756 AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
758 return ap_getword_conf(p, (const char **) line);
761 AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
763 const char *str = *line, *strend;
767 while (*str && apr_isspace(*str))
775 if ((quote = *str) == '"' || quote == '\'') {
777 while (*strend && *strend != quote) {
778 if (*strend == '\\' && strend[1] && strend[1] == quote)
783 res = substring_conf(p, str + 1, strend - str - 1, quote);
785 if (*strend == quote)
790 while (*strend && !apr_isspace(*strend))
793 res = substring_conf(p, str, strend - str, 0);
796 while (*strend && apr_isspace(*strend))
802 /* Check a string for any ${ENV} environment variable
803 * construct and replace each them by the value of
804 * that environment variable, if it exists. If the
805 * environment value does not exist, leave the ${ENV}
806 * construct alone; it means something else.
808 AP_DECLARE(const char *) ap_resolve_env(apr_pool_t *p, const char * word)
810 char tmp[ MAX_STRING_LEN ];
814 if (!(s=ap_strchr_c(word,'$')))
818 /* XXX - relies on strncat() to add '\0'
820 strncat(tmp,word,s - word);
821 if ((s[1] == '{') && (e=ap_strchr_c(s,'}'))) {
828 strncat(tmp, s, e2-s);
832 /* ignore invalid strings */
836 } while ((s=ap_strchr_c(word,'$')));
839 return apr_pstrdup(p,tmp);
841 AP_DECLARE(int) ap_cfg_closefile(ap_configfile_t *cfp)
844 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL,
845 "Done with config file %s", cfp->name);
847 return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
850 static apr_status_t cfg_close(void *param)
852 apr_file_t *cfp = (apr_file_t *) param;
853 return (apr_file_close(cfp));
856 static int cfg_getch(void *param)
859 apr_file_t *cfp = (apr_file_t *) param;
860 if (apr_file_getc(&ch, cfp) == APR_SUCCESS)
865 static void *cfg_getstr(void *buf, size_t bufsiz, void *param)
867 apr_file_t *cfp = (apr_file_t *) param;
869 rv = apr_file_gets(buf, bufsiz, cfp);
870 if (rv == APR_SUCCESS || (rv == APR_EOF && strcmp(buf, "")))
875 /* Open a ap_configfile_t as FILE, return open ap_configfile_t struct pointer */
876 AP_DECLARE(apr_status_t) ap_pcfg_openfile(ap_configfile_t **ret_cfg, apr_pool_t *p, const char *name)
878 ap_configfile_t *new_cfg;
879 apr_file_t *file = NULL;
887 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
888 "Internal error: pcfg_openfile() called with NULL filename");
892 status = apr_file_open(&file, name, APR_READ | APR_BUFFERED, APR_OS_DEFAULT, p);
894 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL,
895 "Opening config file %s (%s)",
896 name, (status != APR_SUCCESS) ?
897 apr_strerror(status, buf, sizeof(buf)) : "successful");
899 if (status != APR_SUCCESS)
902 status = apr_file_info_get(&finfo, APR_FINFO_TYPE, file);
903 if (status != APR_SUCCESS)
906 if (finfo.filetype != APR_REG &&
907 #if defined(WIN32) || defined(OS2) || defined(NETWARE)
908 strcasecmp(apr_filename_of_pathname(name), "nul") != 0) {
910 strcmp(name, "/dev/null") != 0) {
911 #endif /* WIN32 || OS2 */
912 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
913 "Access to file %s denied by server: not a regular file",
915 apr_file_close(file);
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 = (int (*)(void *)) cfg_getch;
923 new_cfg->getstr = (void *(*)(void *, size_t, void *)) cfg_getstr;
924 new_cfg->close = (int (*)(void *)) cfg_close;
925 new_cfg->line_number = 0;
931 /* Allocate a ap_configfile_t handle with user defined functions and params */
932 AP_DECLARE(ap_configfile_t *) ap_pcfg_open_custom(apr_pool_t *p, const char *descr,
934 int(*getch)(void *param),
935 void *(*getstr) (void *buf, size_t bufsiz, void *param),
936 int(*close_func)(void *param))
938 ap_configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
940 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL, "Opening config handler %s", descr);
942 new_cfg->param = param;
943 new_cfg->name = descr;
944 new_cfg->getch = getch;
945 new_cfg->getstr = getstr;
946 new_cfg->close = close_func;
947 new_cfg->line_number = 0;
951 /* Read one character from a configfile_t */
952 AP_DECLARE(int) ap_cfg_getc(ap_configfile_t *cfp)
954 register int ch = cfp->getch(cfp->param);
960 /* Read one line from open ap_configfile_t, strip LF, increase line number */
961 /* If custom handler does not define a getstr() function, read char by char */
962 AP_DECLARE(int) ap_cfg_getline(char *buf, size_t bufsize, ap_configfile_t *cfp)
964 /* If a "get string" function is defined, use it */
965 if (cfp->getstr != NULL) {
969 size_t cbufsize = bufsize;
973 if (cfp->getstr(cbuf, cbufsize, cfp->param) == NULL)
977 * check for line continuation,
978 * i.e. match [^\\]\\[\r]\n only
981 while (cp < cbuf+cbufsize && *cp != '\0')
983 if (cp > cbuf && cp[-1] == LF) {
985 if (cp > cbuf && cp[-1] == CR)
987 if (cp > cbuf && cp[-1] == '\\') {
989 if (!(cp > cbuf && cp[-1] == '\\')) {
991 * line continuation requested -
992 * then remove backslash and continue
994 cbufsize -= (cp-cbuf);
1000 * no real continuation because escaped -
1001 * then just remove escape character
1003 for ( ; cp < cbuf+cbufsize && *cp != '\0'; cp++)
1012 * Leading and trailing white space is eliminated completely
1015 while (apr_isspace(*src))
1017 /* blast trailing whitespace */
1018 dst = &src[strlen(src)];
1019 while (--dst >= src && apr_isspace(*dst))
1021 /* Zap leading whitespace by shifting */
1023 for (dst = buf; (*dst++ = *src++) != '\0'; )
1026 #ifdef DEBUG_CFG_LINES
1027 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1031 /* No "get string" function defined; read character by character */
1033 register size_t i = 0;
1036 /* skip leading whitespace */
1038 c = cfp->getch(cfp->param);
1039 } while (c == '\t' || c == ' ');
1045 /* too small, assume caller is crazy */
1050 if ((c == '\t') || (c == ' ')) {
1052 while ((c == '\t') || (c == ' '))
1053 c = cfp->getch(cfp->param);
1056 /* silently ignore CR (_assume_ that a LF follows) */
1057 c = cfp->getch(cfp->param);
1060 /* increase line number and return on LF */
1063 if (c == EOF || c == 0x4 || c == LF || i >= (bufsize - 2)) {
1065 * check for line continuation
1067 if (i > 0 && buf[i-1] == '\\') {
1069 if (!(i > 0 && buf[i-1] == '\\')) {
1070 /* line is continued */
1071 c = cfp->getch(cfp->param);
1074 /* else nothing needs be done because
1075 * then the backslash is escaped and
1076 * we just strip to a single one
1079 /* blast trailing whitespace */
1080 while (i > 0 && apr_isspace(buf[i - 1]))
1083 #ifdef DEBUG_CFG_LINES
1084 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1090 c = cfp->getch(cfp->param);
1095 /* Size an HTTP header field list item, as separated by a comma.
1096 * The return value is a pointer to the beginning of the non-empty list item
1097 * within the original string (or NULL if there is none) and the address
1098 * of field is shifted to the next non-comma, non-whitespace character.
1099 * len is the length of the item excluding any beginning whitespace.
1101 AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1103 const unsigned char *ptr = (const unsigned char *)*field;
1104 const unsigned char *token;
1105 int in_qpair, in_qstr, in_com;
1107 /* Find first non-comma, non-whitespace byte */
1109 while (*ptr == ',' || apr_isspace(*ptr))
1114 /* Find the end of this item, skipping over dead bits */
1116 for (in_qpair = in_qstr = in_com = 0;
1117 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1125 case '\\': in_qpair = 1; /* quoted-pair */
1127 case '"' : if (!in_com) /* quoted string delim */
1130 case '(' : if (!in_qstr) /* comment (may nest) */
1133 case ')' : if (in_com) /* end comment */
1141 if ((*len = (ptr - token)) == 0) {
1142 *field = (const char *)ptr;
1146 /* Advance field pointer to the next non-comma, non-white byte */
1148 while (*ptr == ',' || apr_isspace(*ptr))
1151 *field = (const char *)ptr;
1152 return (const char *)token;
1155 /* Retrieve an HTTP header field list item, as separated by a comma,
1156 * while stripping insignificant whitespace and lowercasing anything not in
1157 * a quoted string or comment. The return value is a new string containing
1158 * the converted list item (or NULL if none) and the address pointed to by
1159 * field is shifted to the next non-comma, non-whitespace.
1161 AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1163 const char *tok_start;
1164 const unsigned char *ptr;
1167 int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1169 /* Find the beginning and maximum length of the list item so that
1170 * we can allocate a buffer for the new string and reset the field.
1172 if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1175 token = apr_palloc(p, tok_len + 1);
1177 /* Scan the token again, but this time copy only the good bytes.
1178 * We skip extra whitespace and any whitespace around a '=', '/',
1179 * or ';' and lowercase normal characters not within a comment,
1180 * quoted-string or quoted-pair.
1182 for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1183 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1192 case '\\': in_qpair = 1;
1198 case '"' : if (!in_com)
1205 case '(' : if (!in_qstr)
1212 case ')' : if (in_com)
1218 case '\t': if (addspace)
1220 if (in_com || in_qstr)
1227 case ';' : if (!(in_com || in_qstr))
1231 default : if (addspace == 1)
1233 *pos++ = (in_com || in_qstr) ? *ptr
1234 : apr_tolower(*ptr);
1245 /* Find an item in canonical form (lowercase, no extra spaces) within
1246 * an HTTP field value list. Returns 1 if found, 0 if not found.
1247 * This would be much more efficient if we stored header fields as
1248 * an array of list items as they are received instead of a plain string.
1250 AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line, const char *tok)
1252 const unsigned char *pos;
1253 const unsigned char *ptr = (const unsigned char *)line;
1254 int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1259 do { /* loop for each item in line's list */
1261 /* Find first non-comma, non-whitespace byte */
1263 while (*ptr == ',' || apr_isspace(*ptr))
1267 good = 1; /* until proven otherwise for this item */
1269 break; /* no items left and nothing good found */
1271 /* We skip extra whitespace and any whitespace around a '=', '/',
1272 * or ';' and lowercase normal characters not within a comment,
1273 * quoted-string or quoted-pair.
1275 for (pos = (const unsigned char *)tok;
1276 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1282 good = (*pos++ == *ptr);
1286 case '\\': in_qpair = 1;
1288 good = good && (*pos++ == ' ');
1289 good = good && (*pos++ == *ptr);
1292 case '"' : if (!in_com)
1295 good = good && (*pos++ == ' ');
1296 good = good && (*pos++ == *ptr);
1299 case '(' : if (!in_qstr)
1302 good = good && (*pos++ == ' ');
1303 good = good && (*pos++ == *ptr);
1306 case ')' : if (in_com)
1308 good = good && (*pos++ == *ptr);
1312 case '\t': if (addspace || !good)
1314 if (in_com || in_qstr)
1315 good = (*pos++ == *ptr);
1321 case ';' : if (!(in_com || in_qstr))
1323 good = good && (*pos++ == *ptr);
1325 default : if (!good)
1328 good = (*pos++ == ' ');
1329 if (in_com || in_qstr)
1330 good = good && (*pos++ == *ptr);
1332 good = good && (*pos++ == apr_tolower(*ptr));
1339 good = 0; /* not good if only a prefix was matched */
1341 } while (*ptr && !good);
1347 /* Retrieve a token, spacing over it and returning a pointer to
1348 * the first non-white byte afterwards. Note that these tokens
1349 * are delimited by semis and commas; and can also be delimited
1350 * by whitespace at the caller's option.
1353 AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line, int accept_white)
1355 const char *ptr = *accept_line;
1356 const char *tok_start;
1360 /* Find first non-white byte */
1362 while (*ptr && apr_isspace(*ptr))
1367 /* find token end, skipping over quoted strings.
1368 * (comments are already gone).
1371 while (*ptr && (accept_white || !apr_isspace(*ptr))
1372 && *ptr != ';' && *ptr != ',') {
1379 tok_len = ptr - tok_start;
1380 token = apr_pstrndup(p, tok_start, tok_len);
1382 /* Advance accept_line pointer to the next non-white byte */
1384 while (*ptr && apr_isspace(*ptr))
1392 /* find http tokens, see the definition of token from RFC2068 */
1393 AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1395 const unsigned char *start_token;
1396 const unsigned char *s;
1401 s = (const unsigned char *)line;
1403 /* find start of token, skip all stop characters, note NUL
1404 * isn't a token stop, so we don't need to test for it
1406 while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1413 /* find end of the token */
1414 while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1417 if (!strncasecmp((const char *)start_token, (const char *)tok, s - start_token)) {
1427 AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line, const char *tok)
1429 int llen, tlen, lidx;
1434 llen = strlen(line);
1439 ((lidx > 0) && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1442 return (strncasecmp(&line[lidx], tok, tlen) == 0);
1445 AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1449 const unsigned char *s;
1451 cmd = apr_palloc(p, 2 * strlen(str) + 1); /* Be safe */
1452 d = (unsigned char *)cmd;
1453 s = (const unsigned char *)str;
1456 #if defined(OS2) || defined(WIN32)
1457 /* Don't allow '&' in parameters under OS/2. */
1458 /* This can be used to send commands to the shell. */
1465 if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1475 static char x2c(const char *what)
1477 register char digit;
1479 #if !APR_CHARSET_EBCDIC
1480 digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
1482 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
1483 #else /*APR_CHARSET_EBCDIC*/
1490 digit = apr_xlate_conv_byte(ap_hdrs_from_ascii, 0xFF & strtol(xstr, NULL, 16));
1491 #endif /*APR_CHARSET_EBCDIC*/
1497 * Returns 0 on success, non-zero on error
1499 * bad % escape returns HTTP_BAD_REQUEST
1501 * decoding %00 -> \0
1502 * decoding %2f -> / (a special character)
1503 * returns HTTP_NOT_FOUND
1505 AP_DECLARE(int) ap_unescape_url(char *url)
1507 register int badesc, badpath;
1512 /* Initial scan for first '%'. Don't bother writing values before
1514 y = strchr(url, '%');
1518 for (x = y; *y; ++x, ++y) {
1522 if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1529 if (*x == '/' || *x == '\0')
1536 return HTTP_BAD_REQUEST;
1538 return HTTP_NOT_FOUND;
1543 AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
1544 apr_port_t port, const request_rec *r)
1546 if (ap_is_default_port(port, r))
1547 return apr_pstrdup(p, hostname);
1549 return apr_psprintf(p, "%s:%u", hostname, port);
1553 /* c2x takes an unsigned, and expects the caller has guaranteed that
1554 * 0 <= what < 256... which usually means that you have to cast to
1555 * unsigned char first, because (unsigned)(char)(x) first goes through
1556 * signed extension to an int before the unsigned cast.
1558 * The reason for this assumption is to assist gcc code generation --
1559 * the unsigned char -> unsigned extension is already done earlier in
1560 * both uses of this code, so there's no need to waste time doing it
1563 static const char c2x_table[] = "0123456789abcdef";
1565 static APR_INLINE unsigned char *c2x(unsigned what, unsigned char *where)
1567 #if APR_CHARSET_EBCDIC
1568 what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
1569 #endif /*APR_CHARSET_EBCDIC*/
1571 *where++ = c2x_table[what >> 4];
1572 *where++ = c2x_table[what & 0xf];
1577 * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1578 * routine is (should be) OS independent.
1580 * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1581 * cases if a ':' occurs before the first '/' in the URL, the URL should be
1582 * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1583 * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1584 * efficiency reasons, we don't use escape_path_segment(), which is provided for
1585 * reference. Again, RFC 1808 is where this stuff is defined.
1587 * If partial is set, os_escape_path() assumes that the path will be appended to
1588 * something with a '/' in it (and thus does not prefix "./").
1591 AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
1593 char *copy = apr_palloc(p, 3 * strlen(segment) + 1);
1594 const unsigned char *s = (const unsigned char *)segment;
1595 unsigned char *d = (unsigned char *)copy;
1599 if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1611 AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
1613 char *copy = apr_palloc(p, 3 * strlen(path) + 3);
1614 const unsigned char *s = (const unsigned char *)path;
1615 unsigned char *d = (unsigned char *)copy;
1619 const char *colon = ap_strchr_c(path, ':');
1620 const char *slash = ap_strchr_c(path, '/');
1622 if (colon && (!slash || colon < slash)) {
1628 if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1640 /* ap_escape_uri is now a macro for os_escape_path */
1642 AP_DECLARE(char *) ap_escape_html(apr_pool_t *p, const char *s)
1647 /* first, count the number of extra characters */
1648 for (i = 0, j = 0; s[i] != '\0'; i++)
1649 if (s[i] == '<' || s[i] == '>')
1651 else if (s[i] == '&')
1655 return apr_pstrmemdup(p, s, i);
1657 x = apr_palloc(p, i + j + 1);
1658 for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1660 memcpy(&x[j], "<", 4);
1663 else if (s[i] == '>') {
1664 memcpy(&x[j], ">", 4);
1667 else if (s[i] == '&') {
1668 memcpy(&x[j], "&", 5);
1678 AP_DECLARE(int) ap_is_directory(apr_pool_t *p, const char *path)
1682 if (apr_stat(&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(int) ap_is_rdirectory(apr_pool_t *p, const char *path)
1692 if (apr_lstat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
1693 return 0; /* in error condition, just return no */
1695 return (finfo.filetype == APR_DIR);
1698 AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
1701 apr_size_t len1, len2;
1704 len1 = strlen(src1);
1705 len2 = strlen(src2);
1706 path = (char *)apr_palloc(a, len1 + len2 + 2); /* +2 for '/' plus null */
1709 memcpy(path + 1, src2, len2 + 1);
1713 memcpy(path, src1, len1);
1715 if (next[-1] != '/') {
1718 memcpy(next, src2, len2 + 1);
1724 * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
1726 AP_DECLARE(int) ap_is_url(const char *u)
1730 for (x = 0; u[x] != ':'; x++) {
1732 ((!apr_isalpha(u[x])) && (!apr_isdigit(u[x])) &&
1733 (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
1738 return (x ? 1 : 0); /* If the first character is ':', it's broken, too */
1741 AP_DECLARE(int) ap_ind(const char *s, char c)
1743 const char *p = ap_strchr_c(s, c);
1750 AP_DECLARE(int) ap_rind(const char *s, char c)
1752 const char *p = ap_strrchr_c(s, c);
1759 AP_DECLARE(void) ap_str_tolower(char *str)
1762 *str = apr_tolower(*str);
1767 static char *find_fqdn(apr_pool_t *a, struct hostent *p)
1771 if (!strchr(p->h_name, '.')) {
1772 for (x = 0; p->h_aliases[x]; ++x) {
1773 if (strchr(p->h_aliases[x], '.') &&
1774 (!strncasecmp(p->h_aliases[x], p->h_name, strlen(p->h_name))))
1775 return apr_pstrdup(a, p->h_aliases[x]);
1779 return apr_pstrdup(a, (void *) p->h_name);
1782 char *ap_get_local_host(apr_pool_t *a)
1784 #ifndef MAXHOSTNAMELEN
1785 #define MAXHOSTNAMELEN 256
1787 char str[MAXHOSTNAMELEN + 1];
1788 char *server_hostname = NULL;
1792 if (gethostname(str, sizeof(str) - 1) == 0)
1794 if (gethostname(str, sizeof(str) - 1) != 0)
1797 ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a,
1798 "%s: gethostname() failed to determine ServerName",
1803 str[sizeof(str) - 1] = '\0';
1804 if ((!(p = gethostbyname(str)))
1805 || (!(server_hostname = find_fqdn(a, p)))) {
1806 /* Recovery - return the default servername by IP: */
1807 if (p && p->h_addr_list[0]) {
1808 apr_snprintf(str, sizeof(str), "%pA", p->h_addr_list[0]);
1809 server_hostname = apr_pstrdup(a, str);
1810 /* We will drop through to report the IP-named server */
1814 /* Since we found a fdqn, return it with no logged message. */
1815 return server_hostname;
1819 if (!server_hostname)
1820 server_hostname = apr_pstrdup(a, "127.0.0.1");
1822 ap_log_perror(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO|APLOG_STARTUP, 0, a,
1823 "%s: Could not determine the server's fully qualified "
1824 "domain name, using %s for ServerName",
1825 ap_server_argv0, server_hostname);
1827 return server_hostname;
1830 /* simple 'pool' alloc()ing glue to apr_base64.c
1832 AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
1837 decoded = (char *) apr_palloc(p, 1 + apr_base64_decode_len(bufcoded));
1838 l = apr_base64_decode(decoded, bufcoded);
1839 decoded[l] = '\0'; /* make binary sequence into string */
1844 AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string)
1847 int l = strlen(string);
1849 encoded = (char *) apr_palloc(p, 1 + apr_base64_encode_len(l));
1850 l = apr_base64_encode(encoded, string, l);
1851 encoded[l] = '\0'; /* make binary sequence into string */
1856 /* we want to downcase the type/subtype for comparison purposes
1857 * but nothing else because ;parameter=foo values are case sensitive.
1858 * XXX: in truth we want to downcase parameter names... but really,
1859 * apache has never handled parameters and such correctly. You
1860 * also need to compress spaces and such to be able to compare
1863 AP_DECLARE(void) ap_content_type_tolower(char *str)
1867 semi = strchr(str, ';');
1872 *str = apr_tolower(*str);
1881 * Given a string, replace any bare " with \" .
1883 AP_DECLARE(char *) ap_escape_quotes (apr_pool_t *p, const char *instring)
1886 const char *inchr = instring;
1887 char *outchr, *outstring;
1890 * Look through the input string, jogging the length of the output
1891 * string up by an extra byte each time we find an unescaped ".
1893 while (*inchr != '\0') {
1895 if (*inchr == '"') {
1899 * If we find a slosh, and it's not the last byte in the string,
1900 * it's escaping something - advance past both bytes.
1902 if ((*inchr == '\\') && (inchr[1] != '\0')) {
1908 outstring = apr_palloc(p, newlen + 1);
1912 * Now copy the input string to the output string, inserting a slosh
1913 * in front of every " that doesn't already have one.
1915 while (*inchr != '\0') {
1916 if ((*inchr == '\\') && (inchr[1] != '\0')) {
1917 *outchr++ = *inchr++;
1918 *outchr++ = *inchr++;
1920 if (*inchr == '"') {
1923 if (*inchr != '\0') {
1924 *outchr++ = *inchr++;