1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 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
74 #include "ap_config.h"
75 #include "ap_base64.h"
76 #include "apr_strings.h"
78 #include "http_main.h"
80 #include "http_protocol.h"
81 #include "http_config.h"
82 #include "util_ebcdic.h"
90 #ifdef HAVE_NETINET_IN_H
91 #include <netinet/in.h>
93 #ifdef HAVE_SYS_SOCKET_H
94 #include <sys/socket.h>
99 #ifdef HAVE_ARPA_INET_H
100 #include <arpa/inet.h>
108 #ifdef HAVE_STRINGS_H
112 /* A bunch of functions in util.c scan strings looking for certain characters.
113 * To make that more efficient we encode a lookup table. The test_char_table
114 * is generated automatically by gen_test_char.c.
116 #include "test_char.h"
118 /* we assume the folks using this ensure 0 <= c < 256... which means
119 * you need a cast to (unsigned char) first, you can't just plug a
120 * char in here and get it to work, because if char is signed then it
121 * will first be sign extended.
123 #define TEST_CHAR(c, f) (test_char_table[(unsigned)(c)] & (f))
126 * Examine a field value (such as a media-/content-type) string and return
127 * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
129 AP_DECLARE(char *) ap_field_noparam(apr_pool_t *p, const char *intype)
133 if (intype == NULL) return NULL;
135 semi = ap_strchr_c(intype, ';');
137 return apr_pstrdup(p, intype);
140 while ((semi > intype) && apr_isspace(semi[-1])) {
143 return apr_pstrndup(p, intype, semi - intype);
147 AP_DECLARE(char *) ap_ht_time(apr_pool_t *p, apr_time_t t, const char *fmt, int gmt)
150 char ts[MAX_STRING_LEN];
151 char tf[MAX_STRING_LEN];
152 apr_exploded_time_t xt;
158 apr_explode_gmt(&xt, t);
159 /* Convert %Z to "GMT" and %z to "+0000";
160 * on hosts that do not have a time zone string in struct tm,
161 * strftime must assume its argument is local time.
163 for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
165 if (*f != '%') continue;
176 case 'z': /* common extension */
190 apr_explode_localtime(&xt, t);
193 /* check return code? */
194 apr_strftime(ts, &retcode, MAX_STRING_LEN, fmt, &xt);
195 ts[MAX_STRING_LEN - 1] = '\0';
196 return apr_pstrdup(p, ts);
199 /* Roy owes Rob beer. */
200 /* Rob owes Roy dinner. */
202 /* These legacy comments would make a lot more sense if Roy hadn't
203 * replaced the old later_than() routine with util_date.c.
205 * Well, okay, they still wouldn't make any sense.
208 /* Match = 0, NoMatch = 1, Abort = -1
209 * Based loosely on sections of wildmat.c by Rich Salz
210 * Hmmm... shouldn't this really go component by component?
212 AP_DECLARE(int) ap_strcmp_match(const char *str, const char *exp)
216 for (x = 0, y = 0; exp[y]; ++y, ++x) {
217 if ((!str[x]) && (exp[y] != '*'))
220 while (exp[++y] == '*');
225 if ((ret = ap_strcmp_match(&str[x++], &exp[y])) != 1)
230 else if ((exp[y] != '?') && (str[x] != exp[y]))
233 return (str[x] != '\0');
236 AP_DECLARE(int) ap_strcasecmp_match(const char *str, const char *exp)
240 for (x = 0, y = 0; exp[y]; ++y, ++x) {
241 if ((!str[x]) && (exp[y] != '*'))
244 while (exp[++y] == '*');
249 if ((ret = ap_strcasecmp_match(&str[x++], &exp[y])) != 1)
254 else if ((exp[y] != '?') && (apr_tolower(str[x]) != apr_tolower(exp[y])))
257 return (str[x] != '\0');
260 AP_DECLARE(int) ap_is_matchexp(const char *str)
264 for (x = 0; str[x]; x++)
265 if ((str[x] == '*') || (str[x] == '?'))
271 * Here's a pool-based interface to POSIX regex's regcomp().
272 * Note that we return regex_t instead of being passed one.
273 * The reason is that if you use an already-used regex_t structure,
274 * the memory that you've already allocated gets forgotten, and
275 * regfree() doesn't clear it. So we don't allow it.
278 static apr_status_t regex_cleanup(void *preg)
280 regfree((regex_t *) preg);
284 AP_DECLARE(regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
287 regex_t *preg = apr_palloc(p, sizeof(regex_t));
289 if (regcomp(preg, pattern, cflags)) {
293 apr_register_cleanup(p, (void *) preg, regex_cleanup, regex_cleanup);
298 AP_DECLARE(void) ap_pregfree(apr_pool_t *p, regex_t * reg)
301 apr_kill_cleanup(p, (void *) reg, regex_cleanup);
305 * Similar to standard strstr() but we ignore case in this version.
306 * Based on the strstr() implementation further below.
308 AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
316 for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
317 if (*s1 == '\0') return(NULL);
318 /* found first character of s2, see if the rest matches */
321 while (apr_tolower(*++p1) == apr_tolower(*++p2)) {
323 /* both strings ended together */
328 /* second string ended, a match */
331 /* didn't find a match here, try starting at next character in s1 */
338 * Returns an offsetted pointer in bigstring immediately after
339 * prefix. Returns bigstring if bigstring doesn't start with
340 * prefix or if prefix is longer than bigstring while still matching.
341 * NOTE: pointer returned is relative to bigstring, so we
342 * can use standard pointer comparisons in the calling function
343 * (eg: test if ap_stripprefix(a,b) == a)
345 AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
354 while (*p1 && *prefix) {
355 if (*p1++ != *prefix++)
361 /* hit the end of bigstring! */
366 * Apache stub function for the regex libraries regexec() to make sure the
367 * whole regex(3) API is available through the Apache (exported) namespace.
368 * This is especially important for the DSO situations of modules.
369 * DO NOT MAKE A MACRO OUT OF THIS FUNCTION!
371 AP_DECLARE(int) ap_regexec(regex_t *preg, const char *string,
372 size_t nmatch, regmatch_t pmatch[], int eflags)
374 return regexec(preg, string, nmatch, pmatch, eflags);
377 AP_DECLARE(size_t) ap_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
379 return regerror(errcode, preg, errbuf, errbuf_size);
383 /* This function substitutes for $0-$9, filling in regular expression
384 * submatches. Pass it the same nmatch and pmatch arguments that you
385 * passed ap_regexec(). pmatch should not be greater than the maximum number
386 * of subexpressions - i.e. one more than the re_nsub member of regex_t.
388 * input should be the string with the $-expressions, source should be the
389 * string that was matched against.
391 * It returns the substituted string, or NULL on error.
393 * Parts of this code are based on Henry Spencer's regsub(), from his
394 * AT&T V8 regexp package.
397 AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input, const char *source,
398 size_t nmatch, regmatch_t pmatch[])
400 const char *src = input;
409 return apr_pstrdup(p, src);
411 /* First pass, find the size */
415 while ((c = *src++) != '\0') {
418 else if (c == '$' && apr_isdigit(*src))
423 if (no > 9) { /* Ordinary character. */
424 if (c == '\\' && (*src == '$' || *src == '&'))
428 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
429 len += pmatch[no].rm_eo - pmatch[no].rm_so;
434 dest = dst = apr_pcalloc(p, len + 1);
436 /* Now actually fill in the string */
440 while ((c = *src++) != '\0') {
443 else if (c == '$' && apr_isdigit(*src))
448 if (no > 9) { /* Ordinary character. */
449 if (c == '\\' && (*src == '$' || *src == '&'))
453 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
454 len = pmatch[no].rm_eo - pmatch[no].rm_so;
455 memcpy(dst, source + pmatch[no].rm_so, len);
466 * Parse .. so we don't compromise security
468 AP_DECLARE(void) ap_getparents(char *name)
472 /* Four paseses, as per RFC 1808 */
473 /* a) remove ./ path segments */
475 for (l = 0, w = 0; name[l] != '\0';) {
476 if (name[l] == '.' && name[l + 1] == '/' && (l == 0 || name[l - 1] == '/'))
479 name[w++] = name[l++];
482 /* b) remove trailing . path, segment */
483 if (w == 1 && name[0] == '.')
485 else if (w > 1 && name[w - 1] == '.' && name[w - 2] == '/')
489 /* c) remove all xx/../ segments. (including leading ../ and /../) */
492 while (name[l] != '\0') {
493 if (name[l] == '.' && name[l + 1] == '.' && name[l + 2] == '/' &&
494 (l == 0 || name[l - 1] == '/')) {
495 register int m = l + 3, n;
499 while (l >= 0 && name[l] != '/')
506 while ((name[n] = name[m]))
513 /* d) remove trailing xx/.. segment. */
514 if (l == 2 && name[0] == '.' && name[1] == '.')
516 else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.' && name[l - 3] == '/') {
519 while (l >= 0 && name[l] != '/')
529 AP_DECLARE(void) ap_no2slash(char *name)
535 #ifdef HAVE_UNC_PATHS
536 /* Check for UNC names. Leave leading two slashes. */
537 if (s[0] == '/' && s[1] == '/')
542 if ((*d++ = *s) == '/') {
556 * copy at most n leading directories of s into d
557 * d should be at least as large as s plus 1 extra byte
559 * the return value is the ever useful pointer to the trailing \0 of d
561 * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments,
562 * so that if n == 0, "/" is returned in d with n == 1
563 * and s == "e:/test.html", "e:/" is returned in d
564 * *** See also directory_walk in src/main/http_request.c
567 * /a/b, 0 ==> / (true for all platforms)
576 * c:/a/b 3 ==> c:/a/b
577 * c:/a/b 4 ==> c:/a/b
579 AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
588 if (*s == '\0' || (*s == '/' && (--n) == 0)) {
600 * return the parent directory name including trailing / of the file s
602 AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
604 const char *last_slash = ap_strrchr_c(s, '/');
608 if (last_slash == NULL) {
609 /* XXX: well this is really broken if this happens */
610 return (apr_pstrdup(p, "/"));
612 l = (last_slash - s) + 1;
613 d = apr_palloc(p, l + 1);
620 AP_DECLARE(int) ap_count_dirs(const char *path)
624 for (x = 0, n = 0; path[x]; x++)
631 AP_DECLARE(void) ap_chdir_file(const char *file)
634 char buf[HUGE_STRING_LEN];
636 x = ap_strrchr_c(file, '/');
640 else if (x - file < sizeof(buf) - 1) {
641 memcpy(buf, file, x - file);
642 buf[x - file] = '\0';
645 /* XXX: well, this is a silly function, no method of reporting an
646 * error... ah well. */
649 AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
651 return ap_getword(atrans, (const char **) line, stop);
654 AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
656 const char *pos = ap_strchr_c(*line, stop);
660 res = apr_pstrdup(atrans, *line);
661 *line += strlen(*line);
665 res = apr_pstrndup(atrans, *line, pos - *line);
667 while (*pos == stop) {
676 AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
678 return ap_getword_white(atrans, (const char **) line);
681 AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
686 for (x = 0; (*line)[x]; x++) {
687 if (apr_isspace((*line)[x])) {
694 res = apr_pstrdup(atrans, *line);
695 *line += strlen(*line);
699 res = apr_palloc(atrans, pos + 1);
700 apr_cpystrn(res, *line, pos + 1);
702 while (apr_isspace((*line)[pos]))
710 AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line, char stop)
712 return ap_getword_nulls(atrans, (const char **) line, stop);
715 AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line, char stop)
717 const char *pos = ap_strchr_c(*line, stop);
721 res = apr_pstrdup(atrans, *line);
722 *line += strlen(*line);
726 res = apr_pstrndup(atrans, *line, pos - *line);
735 /* Get a word, (new) config-file style --- quoted strings and backslashes
739 static char *substring_conf(apr_pool_t *p, const char *start, int len, char quote)
741 char *result = apr_palloc(p, len + 2);
745 for (i = 0; i < len; ++i) {
746 if (start[i] == '\\' && (start[i + 1] == '\\'
747 || (quote && start[i + 1] == quote)))
748 *resp++ = start[++i];
754 #if RESOLVE_ENV_PER_TOKEN
755 return ap_resolve_env(p,result);
761 AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
763 return ap_getword_conf(p, (const char **) line);
766 AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
768 const char *str = *line, *strend;
772 while (*str && apr_isspace(*str))
780 if ((quote = *str) == '"' || quote == '\'') {
782 while (*strend && *strend != quote) {
783 if (*strend == '\\' && strend[1] && strend[1] == quote)
788 res = substring_conf(p, str + 1, strend - str - 1, quote);
790 if (*strend == quote)
795 while (*strend && !apr_isspace(*strend))
798 res = substring_conf(p, str, strend - str, 0);
801 while (*strend && apr_isspace(*strend))
807 /* Check a string for any ${ENV} environment variable
808 * construct and replace each them by the value of
809 * that environment variable, if it exists. If the
810 * environment value does not exist, leave the ${ENV}
811 * construct alone; it means something else.
813 AP_DECLARE(const char *) ap_resolve_env(apr_pool_t *p, const char * word)
815 char tmp[ MAX_STRING_LEN ];
819 if (!(s=ap_strchr_c(word,'$')))
823 /* XXX - relies on strncat() to add '\0'
825 strncat(tmp,word,s - word);
826 if ((s[1] == '{') && (e=ap_strchr_c(s,'}'))) {
833 strncat(tmp, s, e2-s);
837 /* ignore invalid strings */
841 } while ((s=ap_strchr_c(word,'$')));
844 return apr_pstrdup(p,tmp);
846 AP_DECLARE(int) ap_cfg_closefile(configfile_t *cfp)
849 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL,
850 "Done with config file %s", cfp->name);
852 return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
855 static apr_status_t cfg_close(void *param)
857 apr_file_t *cfp = (apr_file_t *) param;
858 return (apr_close(cfp));
861 static int cfg_getch(void *param)
864 apr_file_t *cfp = (apr_file_t *) param;
865 if (apr_getc(&ch, cfp) == APR_SUCCESS)
870 static void *cfg_getstr(void *buf, size_t bufsiz, void *param)
872 apr_file_t *cfp = (apr_file_t *) param;
874 rv = apr_fgets(buf, bufsiz, cfp);
875 if (rv == APR_SUCCESS || (rv == APR_EOF && strcmp(buf, "")))
880 /* Open a configfile_t as FILE, return open configfile_t struct pointer */
881 AP_DECLARE(apr_status_t) ap_pcfg_openfile(configfile_t **ret_cfg, apr_pool_t *p, const char *name)
883 configfile_t *new_cfg;
884 apr_file_t *file = NULL;
892 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
893 "Internal error: pcfg_openfile() called with NULL filename");
897 if (!ap_os_is_filename_valid(name)) {
898 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
899 "Access to config file %s denied: not a valid filename",
904 status = apr_open(&file, name, APR_READ | APR_BUFFERED, APR_OS_DEFAULT, p);
906 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL,
907 "Opening config file %s (%s)",
908 name, (status != APR_SUCCESS) ?
909 apr_strerror(status, buf, sizeof(buf)) : "successful");
911 if (status != APR_SUCCESS)
914 status = apr_getfileinfo(&finfo, file);
915 if (status != APR_SUCCESS)
918 if (finfo.filetype != APR_REG &&
919 #if defined(WIN32) || defined(OS2)
920 !(strcasecmp(name, "nul") == 0 ||
921 (strlen(name) >= 4 &&
922 strcasecmp(name + strlen(name) - 4, "/nul") == 0))) {
924 strcmp(name, "/dev/null") != 0) {
925 #endif /* WIN32 || OS2 */
926 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
927 "Access to file %s denied by server: not a regular file",
933 new_cfg = apr_palloc(p, sizeof(*new_cfg));
934 new_cfg->param = file;
935 new_cfg->name = apr_pstrdup(p, name);
936 new_cfg->getch = (int (*)(void *)) cfg_getch;
937 new_cfg->getstr = (void *(*)(void *, size_t, void *)) cfg_getstr;
938 new_cfg->close = (int (*)(void *)) cfg_close;
939 new_cfg->line_number = 0;
945 /* Allocate a configfile_t handle with user defined functions and params */
946 AP_DECLARE(configfile_t *) ap_pcfg_open_custom(apr_pool_t *p, const char *descr,
948 int(*getch)(void *param),
949 void *(*getstr) (void *buf, size_t bufsiz, void *param),
950 int(*close_func)(void *param))
952 configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
954 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL, "Opening config handler %s", descr);
956 new_cfg->param = param;
957 new_cfg->name = descr;
958 new_cfg->getch = getch;
959 new_cfg->getstr = getstr;
960 new_cfg->close = close_func;
961 new_cfg->line_number = 0;
966 /* Read one character from a configfile_t */
967 AP_DECLARE(int) ap_cfg_getc(configfile_t *cfp)
969 register int ch = cfp->getch(cfp->param);
976 /* Read one line from open configfile_t, strip LF, increase line number */
977 /* If custom handler does not define a getstr() function, read char by char */
978 AP_DECLARE(int) ap_cfg_getline(char *buf, size_t bufsize, configfile_t *cfp)
980 /* If a "get string" function is defined, use it */
981 if (cfp->getstr != NULL) {
985 size_t cbufsize = bufsize;
989 if (cfp->getstr(cbuf, cbufsize, cfp->param) == NULL)
993 * check for line continuation,
994 * i.e. match [^\\]\\[\r]\n only
997 while (cp < cbuf+cbufsize && *cp != '\0')
999 if (cp > cbuf && cp[-1] == LF) {
1001 if (cp > cbuf && cp[-1] == CR)
1003 if (cp > cbuf && cp[-1] == '\\') {
1005 if (!(cp > cbuf && cp[-1] == '\\')) {
1007 * line continuation requested -
1008 * then remove backslash and continue
1010 cbufsize -= (cp-cbuf);
1016 * no real continuation because escaped -
1017 * then just remove escape character
1019 for ( ; cp < cbuf+cbufsize && *cp != '\0'; cp++)
1028 * Leading and trailing white space is eliminated completely
1031 while (apr_isspace(*src))
1033 /* blast trailing whitespace */
1034 dst = &src[strlen(src)];
1035 while (--dst >= src && apr_isspace(*dst))
1037 /* Zap leading whitespace by shifting */
1039 for (dst = buf; (*dst++ = *src++) != '\0'; )
1042 #ifdef DEBUG_CFG_LINES
1043 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1047 /* No "get string" function defined; read character by character */
1049 register size_t i = 0;
1052 /* skip leading whitespace */
1054 c = cfp->getch(cfp->param);
1055 } while (c == '\t' || c == ' ');
1061 /* too small, assume caller is crazy */
1066 if ((c == '\t') || (c == ' ')) {
1068 while ((c == '\t') || (c == ' '))
1069 c = cfp->getch(cfp->param);
1072 /* silently ignore CR (_assume_ that a LF follows) */
1073 c = cfp->getch(cfp->param);
1076 /* increase line number and return on LF */
1079 if (c == EOF || c == 0x4 || c == LF || i >= (bufsize - 2)) {
1081 * check for line continuation
1083 if (i > 0 && buf[i-1] == '\\') {
1085 if (!(i > 0 && buf[i-1] == '\\')) {
1086 /* line is continued */
1087 c = cfp->getch(cfp->param);
1090 /* else nothing needs be done because
1091 * then the backslash is escaped and
1092 * we just strip to a single one
1095 /* blast trailing whitespace */
1096 while (i > 0 && apr_isspace(buf[i - 1]))
1099 #ifdef DEBUG_CFG_LINES
1100 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1106 c = cfp->getch(cfp->param);
1111 /* Size an HTTP header field list item, as separated by a comma.
1112 * The return value is a pointer to the beginning of the non-empty list item
1113 * within the original string (or NULL if there is none) and the address
1114 * of field is shifted to the next non-comma, non-whitespace character.
1115 * len is the length of the item excluding any beginning whitespace.
1117 AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1119 const unsigned char *ptr = (const unsigned char *)*field;
1120 const unsigned char *token;
1121 int in_qpair, in_qstr, in_com;
1123 /* Find first non-comma, non-whitespace byte */
1125 while (*ptr == ',' || apr_isspace(*ptr))
1130 /* Find the end of this item, skipping over dead bits */
1132 for (in_qpair = in_qstr = in_com = 0;
1133 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1141 case '\\': in_qpair = 1; /* quoted-pair */
1143 case '"' : if (!in_com) /* quoted string delim */
1146 case '(' : if (!in_qstr) /* comment (may nest) */
1149 case ')' : if (in_com) /* end comment */
1157 if ((*len = (ptr - token)) == 0) {
1158 *field = (const char *)ptr;
1162 /* Advance field pointer to the next non-comma, non-white byte */
1164 while (*ptr == ',' || apr_isspace(*ptr))
1167 *field = (const char *)ptr;
1168 return (const char *)token;
1171 /* Retrieve an HTTP header field list item, as separated by a comma,
1172 * while stripping insignificant whitespace and lowercasing anything not in
1173 * a quoted string or comment. The return value is a new string containing
1174 * the converted list item (or NULL if none) and the address pointed to by
1175 * field is shifted to the next non-comma, non-whitespace.
1177 AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1179 const char *tok_start;
1180 const unsigned char *ptr;
1183 int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1185 /* Find the beginning and maximum length of the list item so that
1186 * we can allocate a buffer for the new string and reset the field.
1188 if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1191 token = apr_palloc(p, tok_len + 1);
1193 /* Scan the token again, but this time copy only the good bytes.
1194 * We skip extra whitespace and any whitespace around a '=', '/',
1195 * or ';' and lowercase normal characters not within a comment,
1196 * quoted-string or quoted-pair.
1198 for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1199 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1208 case '\\': in_qpair = 1;
1214 case '"' : if (!in_com)
1221 case '(' : if (!in_qstr)
1228 case ')' : if (in_com)
1234 case '\t': if (addspace)
1236 if (in_com || in_qstr)
1243 case ';' : if (!(in_com || in_qstr))
1247 default : if (addspace == 1)
1249 *pos++ = (in_com || in_qstr) ? *ptr
1250 : apr_tolower(*ptr);
1261 /* Find an item in canonical form (lowercase, no extra spaces) within
1262 * an HTTP field value list. Returns 1 if found, 0 if not found.
1263 * This would be much more efficient if we stored header fields as
1264 * an array of list items as they are received instead of a plain string.
1266 AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line, const char *tok)
1268 const unsigned char *pos;
1269 const unsigned char *ptr = (const unsigned char *)line;
1270 int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1275 do { /* loop for each item in line's list */
1277 /* Find first non-comma, non-whitespace byte */
1279 while (*ptr == ',' || apr_isspace(*ptr))
1283 good = 1; /* until proven otherwise for this item */
1285 break; /* no items left and nothing good found */
1287 /* We skip extra whitespace and any whitespace around a '=', '/',
1288 * or ';' and lowercase normal characters not within a comment,
1289 * quoted-string or quoted-pair.
1291 for (pos = (const unsigned char *)tok;
1292 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1298 good = (*pos++ == *ptr);
1302 case '\\': in_qpair = 1;
1304 good = good && (*pos++ == ' ');
1305 good = good && (*pos++ == *ptr);
1308 case '"' : if (!in_com)
1311 good = good && (*pos++ == ' ');
1312 good = good && (*pos++ == *ptr);
1315 case '(' : if (!in_qstr)
1318 good = good && (*pos++ == ' ');
1319 good = good && (*pos++ == *ptr);
1322 case ')' : if (in_com)
1324 good = good && (*pos++ == *ptr);
1328 case '\t': if (addspace || !good)
1330 if (in_com || in_qstr)
1331 good = (*pos++ == *ptr);
1337 case ';' : if (!(in_com || in_qstr))
1339 good = good && (*pos++ == *ptr);
1341 default : if (!good)
1344 good = (*pos++ == ' ');
1345 if (in_com || in_qstr)
1346 good = good && (*pos++ == *ptr);
1348 good = good && (*pos++ == apr_tolower(*ptr));
1355 good = 0; /* not good if only a prefix was matched */
1357 } while (*ptr && !good);
1363 /* Retrieve a token, spacing over it and returning a pointer to
1364 * the first non-white byte afterwards. Note that these tokens
1365 * are delimited by semis and commas; and can also be delimited
1366 * by whitespace at the caller's option.
1369 AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line, int accept_white)
1371 const char *ptr = *accept_line;
1372 const char *tok_start;
1376 /* Find first non-white byte */
1378 while (*ptr && apr_isspace(*ptr))
1383 /* find token end, skipping over quoted strings.
1384 * (comments are already gone).
1387 while (*ptr && (accept_white || !apr_isspace(*ptr))
1388 && *ptr != ';' && *ptr != ',') {
1395 tok_len = ptr - tok_start;
1396 token = apr_pstrndup(p, tok_start, tok_len);
1398 /* Advance accept_line pointer to the next non-white byte */
1400 while (*ptr && apr_isspace(*ptr))
1408 /* find http tokens, see the definition of token from RFC2068 */
1409 AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1411 const unsigned char *start_token;
1412 const unsigned char *s;
1417 s = (const unsigned char *)line;
1419 /* find start of token, skip all stop characters, note NUL
1420 * isn't a token stop, so we don't need to test for it
1422 while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1429 /* find end of the token */
1430 while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1433 if (!strncasecmp((const char *)start_token, (const char *)tok, s - start_token)) {
1443 AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line, const char *tok)
1445 int llen, tlen, lidx;
1450 llen = strlen(line);
1455 ((lidx > 0) && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1458 return (strncasecmp(&line[lidx], tok, tlen) == 0);
1461 AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1465 const unsigned char *s;
1467 cmd = apr_palloc(p, 2 * strlen(str) + 1); /* Be safe */
1468 d = (unsigned char *)cmd;
1469 s = (const unsigned char *)str;
1472 #if defined(OS2) || defined(WIN32)
1473 /* Don't allow '&' in parameters under OS/2. */
1474 /* This can be used to send commands to the shell. */
1481 if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1491 static char x2c(const char *what)
1493 register char digit;
1495 #ifndef CHARSET_EBCDIC
1496 digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
1498 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
1499 #else /*CHARSET_EBCDIC*/
1506 digit = apr_xlate_conv_byte(ap_hdrs_from_ascii, 0xFF & strtol(xstr, NULL, 16));
1507 #endif /*CHARSET_EBCDIC*/
1513 * Returns 0 on success, non-zero on error
1515 * bad % escape returns HTTP_BAD_REQUEST
1517 * decoding %00 -> \0
1518 * decoding %2f -> / (a special character)
1519 * returns HTTP_NOT_FOUND
1521 AP_DECLARE(int) ap_unescape_url(char *url)
1523 register int badesc, badpath;
1528 /* Initial scan for first '%'. Don't bother writing values before
1530 y = strchr(url, '%');
1534 for (x = y; *y; ++x, ++y) {
1538 if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1545 if (*x == '/' || *x == '\0')
1552 return HTTP_BAD_REQUEST;
1554 return HTTP_NOT_FOUND;
1559 AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
1560 apr_port_t port, const request_rec *r)
1562 if (ap_is_default_port(port, r))
1563 return apr_pstrdup(p, hostname);
1565 return apr_psprintf(p, "%s:%u", hostname, port);
1569 /* c2x takes an unsigned, and expects the caller has guaranteed that
1570 * 0 <= what < 256... which usually means that you have to cast to
1571 * unsigned char first, because (unsigned)(char)(x) first goes through
1572 * signed extension to an int before the unsigned cast.
1574 * The reason for this assumption is to assist gcc code generation --
1575 * the unsigned char -> unsigned extension is already done earlier in
1576 * both uses of this code, so there's no need to waste time doing it
1579 static const char c2x_table[] = "0123456789abcdef";
1581 static apr_inline unsigned char *c2x(unsigned what, unsigned char *where)
1583 #ifdef CHARSET_EBCDIC
1584 what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
1585 #endif /*CHARSET_EBCDIC*/
1587 *where++ = c2x_table[what >> 4];
1588 *where++ = c2x_table[what & 0xf];
1593 * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1594 * routine is (should be) OS independent.
1596 * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1597 * cases if a ':' occurs before the first '/' in the URL, the URL should be
1598 * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1599 * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1600 * efficiency reasons, we don't use escape_path_segment(), which is provided for
1601 * reference. Again, RFC 1808 is where this stuff is defined.
1603 * If partial is set, os_escape_path() assumes that the path will be appended to
1604 * something with a '/' in it (and thus does not prefix "./").
1607 AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
1609 char *copy = apr_palloc(p, 3 * strlen(segment) + 1);
1610 const unsigned char *s = (const unsigned char *)segment;
1611 unsigned char *d = (unsigned char *)copy;
1615 if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1627 AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
1629 char *copy = apr_palloc(p, 3 * strlen(path) + 3);
1630 const unsigned char *s = (const unsigned char *)path;
1631 unsigned char *d = (unsigned char *)copy;
1635 const char *colon = ap_strchr_c(path, ':');
1636 const char *slash = ap_strchr_c(path, '/');
1638 if (colon && (!slash || colon < slash)) {
1644 if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1656 /* ap_escape_uri is now a macro for os_escape_path */
1658 AP_DECLARE(char *) ap_escape_html(apr_pool_t *p, const char *s)
1663 /* first, count the number of extra characters */
1664 for (i = 0, j = 0; s[i] != '\0'; i++)
1665 if (s[i] == '<' || s[i] == '>')
1667 else if (s[i] == '&')
1671 return apr_pstrndup(p, s, i);
1673 x = apr_palloc(p, i + j + 1);
1674 for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1676 memcpy(&x[j], "<", 4);
1679 else if (s[i] == '>') {
1680 memcpy(&x[j], ">", 4);
1683 else if (s[i] == '&') {
1684 memcpy(&x[j], "&", 5);
1694 AP_DECLARE(int) ap_is_directory(const char *path)
1698 if (apr_stat(&finfo, path, NULL) == -1)
1699 return 0; /* in error condition, just return no */
1701 return (finfo.filetype == APR_DIR);
1704 AP_DECLARE(int) ap_is_rdirectory(const char *path)
1708 if (apr_lstat(&finfo, path, NULL) == -1)
1709 return 0; /* in error condition, just return no */
1711 return (finfo.filetype == APR_DIR);
1714 AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
1721 return apr_pstrcat(a, "/", src2, NULL);
1723 if (src1[x - 1] != '/')
1724 return apr_pstrcat(a, src1, "/", src2, NULL);
1726 return apr_pstrcat(a, src1, src2, NULL);
1730 * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
1732 AP_DECLARE(int) ap_is_url(const char *u)
1736 for (x = 0; u[x] != ':'; x++) {
1738 ((!apr_isalpha(u[x])) && (!apr_isdigit(u[x])) &&
1739 (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
1744 return (x ? 1 : 0); /* If the first character is ':', it's broken, too */
1747 #ifndef HAVE_INITGROUPS
1748 int initgroups(const char *name, gid_t basegid)
1750 #if defined(QNX) || defined(MPE) || defined(BEOS) || defined(_OSD_POSIX) || defined(TPF) || defined(__TANDEM) || defined(OS2) || defined(WIN32)
1751 /* QNX, MPE and BeOS do not appear to support supplementary groups. */
1753 #else /* ndef QNX */
1754 gid_t groups[NGROUPS_MAX];
1760 groups[index++] = basegid;
1762 while (index < NGROUPS_MAX && ((g = getgrent()) != NULL))
1763 if (g->gr_gid != basegid) {
1766 for (names = g->gr_mem; *names != NULL; ++names)
1767 if (!strcmp(*names, name))
1768 groups[index++] = g->gr_gid;
1773 return setgroups(index, groups);
1774 #endif /* def QNX */
1776 #endif /* def NEED_INITGROUPS */
1778 AP_DECLARE(int) ap_ind(const char *s, char c)
1782 for (x = 0; s[x]; x++)
1789 AP_DECLARE(int) ap_rind(const char *s, char c)
1793 for (x = strlen(s) - 1; x != -1; x--)
1800 AP_DECLARE(void) ap_str_tolower(char *str)
1803 *str = apr_tolower(*str);
1808 AP_DECLARE(uid_t) ap_uname2id(const char *name)
1816 return (atoi(&name[1]));
1818 if (!(ent = getpwnam(name))) {
1819 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "%s: bad user name %s", ap_server_argv0, name);
1822 return (ent->pw_uid);
1826 AP_DECLARE(gid_t) ap_gname2id(const char *name)
1834 return (atoi(&name[1]));
1836 if (!(ent = getgrnam(name))) {
1837 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "%s: bad group name %s", ap_server_argv0, name);
1840 return (ent->gr_gid);
1846 * Parses a host of the form <address>[:port]
1847 * :port is permitted if 'port' is not NULL
1849 unsigned long ap_get_virthost_addr(char *w, apr_port_t *ports)
1851 struct hostent *hep;
1852 unsigned long my_addr;
1856 if (ports != NULL) {
1858 if (p != NULL && strcmp(p + 1, "*") != 0)
1859 *ports = atoi(p + 1);
1864 if (strcmp(w, "*") == 0) {
1867 return htonl(INADDR_ANY);
1870 my_addr = apr_inet_addr((char *)w);
1871 if (my_addr != INADDR_NONE) {
1877 hep = gethostbyname(w);
1879 if ((!hep) || (hep->h_addrtype != AF_INET || !hep->h_addr_list[0])) {
1880 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "Cannot resolve host name %s --- exiting!", w);
1884 if (hep->h_addr_list[1]) {
1885 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "Host %s has multiple addresses ---", w);
1886 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "you must choose one explicitly for use as");
1887 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "a virtual host. Exiting!!!");
1894 return ((struct in_addr *) (hep->h_addr))->s_addr;
1898 static char *find_fqdn(apr_pool_t *a, struct hostent *p)
1902 if (!strchr(p->h_name, '.')) {
1903 for (x = 0; p->h_aliases[x]; ++x) {
1904 if (strchr(p->h_aliases[x], '.') &&
1905 (!strncasecmp(p->h_aliases[x], p->h_name, strlen(p->h_name))))
1906 return apr_pstrdup(a, p->h_aliases[x]);
1910 return apr_pstrdup(a, (void *) p->h_name);
1913 char *ap_get_local_host(apr_pool_t *a)
1915 #ifndef MAXHOSTNAMELEN
1916 #define MAXHOSTNAMELEN 256
1918 char str[MAXHOSTNAMELEN + 1];
1919 char *server_hostname = NULL;
1923 if (gethostname(str, sizeof(str) - 1) == 0)
1925 if (gethostname(str, sizeof(str) - 1) != 0)
1928 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, NULL,
1929 "%s: gethostname() failed to detemine ServerName",
1934 str[sizeof(str) - 1] = '\0';
1935 if ((!(p = gethostbyname(str)))
1936 || (!(server_hostname = find_fqdn(a, p)))) {
1937 /* Recovery - return the default servername by IP: */
1938 if (!str && p->h_addr_list[0]) {
1939 apr_snprintf(str, sizeof(str), "%pA", p->h_addr_list[0]);
1940 server_hostname = apr_pstrdup(a, str);
1941 /* We will drop through to report the IP-named server */
1945 /* Since we found a fdqn, return it with no logged message. */
1946 return server_hostname;
1950 if (!server_hostname)
1951 server_hostname = apr_pstrdup(a, "127.0.0.1");
1953 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO|APLOG_STARTUP, 0, NULL,
1954 "%s: Could not find determine the server's fully qualified "
1955 "domain name, using %s for ServerName",
1956 ap_server_argv0, server_hostname);
1958 return server_hostname;
1961 /* simple 'pool' alloc()ing glue to ap_base64.c
1963 AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
1968 decoded = (char *) apr_palloc(p, 1 + ap_base64decode_len(bufcoded));
1969 l = ap_base64decode(decoded, bufcoded);
1970 decoded[l] = '\0'; /* make binary sequence into string */
1975 AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string)
1978 int l = strlen(string);
1980 encoded = (char *) apr_palloc(p, 1 + ap_base64encode_len(l));
1981 l = ap_base64encode(encoded, string, l);
1982 encoded[l] = '\0'; /* make binary sequence into string */
1987 /* we want to downcase the type/subtype for comparison purposes
1988 * but nothing else because ;parameter=foo values are case sensitive.
1989 * XXX: in truth we want to downcase parameter names... but really,
1990 * apache has never handled parameters and such correctly. You
1991 * also need to compress spaces and such to be able to compare
1994 AP_DECLARE(void) ap_content_type_tolower(char *str)
1998 semi = strchr(str, ';');
2003 *str = apr_tolower(*str);
2012 * Given a string, replace any bare " with \" .
2014 AP_DECLARE(char *) ap_escape_quotes (apr_pool_t *p, const char *instring)
2017 const char *inchr = instring;
2018 char *outchr, *outstring;
2021 * Look through the input string, jogging the length of the output
2022 * string up by an extra byte each time we find an unescaped ".
2024 while (*inchr != '\0') {
2026 if (*inchr == '"') {
2030 * If we find a slosh, and it's not the last byte in the string,
2031 * it's escaping something - advance past both bytes.
2033 if ((*inchr == '\\') && (inchr[1] != '\0')) {
2039 outstring = apr_palloc(p, newlen + 1);
2043 * Now copy the input string to the output string, inserting a slosh
2044 * in front of every " that doesn't already have one.
2046 while (*inchr != '\0') {
2047 if ((*inchr == '\\') && (inchr[1] != '\0')) {
2048 *outchr++ = *inchr++;
2049 *outchr++ = *inchr++;
2051 if (*inchr == '"') {
2054 if (*inchr != '\0') {
2055 *outchr++ = *inchr++;