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
75 #include "apr_strings.h"
78 #include <stdio.h> /* for EOF */
80 #if APR_HAVE_NETINET_IN_H
81 #include <netinet/in.h>
83 #if APR_HAVE_SYS_SOCKET_H
84 #include <sys/socket.h>
87 #include "ap_config.h"
88 #include "ap_base64.h"
90 #include "http_main.h"
92 #include "http_protocol.h"
93 #include "http_config.h"
94 #include "util_ebcdic.h"
102 #ifdef HAVE_ARPA_INET_H
103 #include <arpa/inet.h>
111 #ifdef HAVE_STRINGS_H
115 /* A bunch of functions in util.c scan strings looking for certain characters.
116 * To make that more efficient we encode a lookup table. The test_char_table
117 * is generated automatically by gen_test_char.c.
119 #include "test_char.h"
121 /* we assume the folks using this ensure 0 <= c < 256... which means
122 * you need a cast to (unsigned char) first, you can't just plug a
123 * char in here and get it to work, because if char is signed then it
124 * will first be sign extended.
126 #define TEST_CHAR(c, f) (test_char_table[(unsigned)(c)] & (f))
129 * Examine a field value (such as a media-/content-type) string and return
130 * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
132 AP_DECLARE(char *) ap_field_noparam(apr_pool_t *p, const char *intype)
136 if (intype == NULL) return NULL;
138 semi = ap_strchr_c(intype, ';');
140 return apr_pstrdup(p, intype);
143 while ((semi > intype) && apr_isspace(semi[-1])) {
146 return apr_pstrndup(p, intype, semi - intype);
150 AP_DECLARE(char *) ap_ht_time(apr_pool_t *p, apr_time_t t, const char *fmt, int gmt)
153 char ts[MAX_STRING_LEN];
154 char tf[MAX_STRING_LEN];
155 apr_exploded_time_t xt;
161 apr_explode_gmt(&xt, t);
162 /* Convert %Z to "GMT" and %z to "+0000";
163 * on hosts that do not have a time zone string in struct tm,
164 * strftime must assume its argument is local time.
166 for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
168 if (*f != '%') continue;
179 case 'z': /* common extension */
193 apr_explode_localtime(&xt, t);
196 /* check return code? */
197 apr_strftime(ts, &retcode, MAX_STRING_LEN, fmt, &xt);
198 ts[MAX_STRING_LEN - 1] = '\0';
199 return apr_pstrdup(p, ts);
202 /* Roy owes Rob beer. */
203 /* Rob owes Roy dinner. */
205 /* These legacy comments would make a lot more sense if Roy hadn't
206 * replaced the old later_than() routine with util_date.c.
208 * Well, okay, they still wouldn't make any sense.
211 /* Match = 0, NoMatch = 1, Abort = -1
212 * Based loosely on sections of wildmat.c by Rich Salz
213 * Hmmm... shouldn't this really go component by component?
215 AP_DECLARE(int) ap_strcmp_match(const char *str, const char *exp)
219 for (x = 0, y = 0; exp[y]; ++y, ++x) {
220 if ((!str[x]) && (exp[y] != '*'))
223 while (exp[++y] == '*');
228 if ((ret = ap_strcmp_match(&str[x++], &exp[y])) != 1)
233 else if ((exp[y] != '?') && (str[x] != exp[y]))
236 return (str[x] != '\0');
239 AP_DECLARE(int) ap_strcasecmp_match(const char *str, const char *exp)
243 for (x = 0, y = 0; exp[y]; ++y, ++x) {
244 if ((!str[x]) && (exp[y] != '*'))
247 while (exp[++y] == '*');
252 if ((ret = ap_strcasecmp_match(&str[x++], &exp[y])) != 1)
257 else if ((exp[y] != '?') && (apr_tolower(str[x]) != apr_tolower(exp[y])))
260 return (str[x] != '\0');
263 AP_DECLARE(int) ap_is_matchexp(const char *str)
267 for (x = 0; str[x]; x++)
268 if ((str[x] == '*') || (str[x] == '?'))
274 * Here's a pool-based interface to POSIX regex's regcomp().
275 * Note that we return regex_t instead of being passed one.
276 * The reason is that if you use an already-used regex_t structure,
277 * the memory that you've already allocated gets forgotten, and
278 * regfree() doesn't clear it. So we don't allow it.
281 static apr_status_t regex_cleanup(void *preg)
283 regfree((regex_t *) preg);
287 AP_DECLARE(regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
290 regex_t *preg = apr_palloc(p, sizeof(regex_t));
292 if (regcomp(preg, pattern, cflags)) {
296 apr_register_cleanup(p, (void *) preg, regex_cleanup, regex_cleanup);
301 AP_DECLARE(void) ap_pregfree(apr_pool_t *p, regex_t * reg)
304 apr_kill_cleanup(p, (void *) reg, regex_cleanup);
308 * Similar to standard strstr() but we ignore case in this version.
309 * Based on the strstr() implementation further below.
311 AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
319 for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
320 if (*s1 == '\0') return(NULL);
321 /* found first character of s2, see if the rest matches */
324 while (apr_tolower(*++p1) == apr_tolower(*++p2)) {
326 /* both strings ended together */
331 /* second string ended, a match */
334 /* didn't find a match here, try starting at next character in s1 */
341 * Returns an offsetted pointer in bigstring immediately after
342 * prefix. Returns bigstring if bigstring doesn't start with
343 * prefix or if prefix is longer than bigstring while still matching.
344 * NOTE: pointer returned is relative to bigstring, so we
345 * can use standard pointer comparisons in the calling function
346 * (eg: test if ap_stripprefix(a,b) == a)
348 AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
357 while (*p1 && *prefix) {
358 if (*p1++ != *prefix++)
364 /* hit the end of bigstring! */
369 * Apache stub function for the regex libraries regexec() to make sure the
370 * whole regex(3) API is available through the Apache (exported) namespace.
371 * This is especially important for the DSO situations of modules.
372 * DO NOT MAKE A MACRO OUT OF THIS FUNCTION!
374 AP_DECLARE(int) ap_regexec(regex_t *preg, const char *string,
375 size_t nmatch, regmatch_t pmatch[], int eflags)
377 return regexec(preg, string, nmatch, pmatch, eflags);
380 AP_DECLARE(size_t) ap_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
382 return regerror(errcode, preg, errbuf, errbuf_size);
386 /* This function substitutes for $0-$9, filling in regular expression
387 * submatches. Pass it the same nmatch and pmatch arguments that you
388 * passed ap_regexec(). pmatch should not be greater than the maximum number
389 * of subexpressions - i.e. one more than the re_nsub member of regex_t.
391 * input should be the string with the $-expressions, source should be the
392 * string that was matched against.
394 * It returns the substituted string, or NULL on error.
396 * Parts of this code are based on Henry Spencer's regsub(), from his
397 * AT&T V8 regexp package.
400 AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input, const char *source,
401 size_t nmatch, regmatch_t pmatch[])
403 const char *src = input;
412 return apr_pstrdup(p, src);
414 /* First pass, find the size */
418 while ((c = *src++) != '\0') {
421 else if (c == '$' && apr_isdigit(*src))
426 if (no > 9) { /* Ordinary character. */
427 if (c == '\\' && (*src == '$' || *src == '&'))
431 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
432 len += pmatch[no].rm_eo - pmatch[no].rm_so;
437 dest = dst = apr_pcalloc(p, len + 1);
439 /* Now actually fill in the string */
443 while ((c = *src++) != '\0') {
446 else if (c == '$' && apr_isdigit(*src))
451 if (no > 9) { /* Ordinary character. */
452 if (c == '\\' && (*src == '$' || *src == '&'))
456 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
457 len = pmatch[no].rm_eo - pmatch[no].rm_so;
458 memcpy(dst, source + pmatch[no].rm_so, len);
469 * Parse .. so we don't compromise security
471 AP_DECLARE(void) ap_getparents(char *name)
475 /* Four paseses, as per RFC 1808 */
476 /* a) remove ./ path segments */
478 for (l = 0, w = 0; name[l] != '\0';) {
479 if (name[l] == '.' && name[l + 1] == '/' && (l == 0 || name[l - 1] == '/'))
482 name[w++] = name[l++];
485 /* b) remove trailing . path, segment */
486 if (w == 1 && name[0] == '.')
488 else if (w > 1 && name[w - 1] == '.' && name[w - 2] == '/')
492 /* c) remove all xx/../ segments. (including leading ../ and /../) */
495 while (name[l] != '\0') {
496 if (name[l] == '.' && name[l + 1] == '.' && name[l + 2] == '/' &&
497 (l == 0 || name[l - 1] == '/')) {
498 register int m = l + 3, n;
502 while (l >= 0 && name[l] != '/')
509 while ((name[n] = name[m]))
516 /* d) remove trailing xx/.. segment. */
517 if (l == 2 && name[0] == '.' && name[1] == '.')
519 else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.' && name[l - 3] == '/') {
522 while (l >= 0 && name[l] != '/')
532 AP_DECLARE(void) ap_no2slash(char *name)
538 #ifdef HAVE_UNC_PATHS
539 /* Check for UNC names. Leave leading two slashes. */
540 if (s[0] == '/' && s[1] == '/')
545 if ((*d++ = *s) == '/') {
559 * copy at most n leading directories of s into d
560 * d should be at least as large as s plus 1 extra byte
562 * the return value is the ever useful pointer to the trailing \0 of d
564 * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments,
565 * so that if n == 0, "/" is returned in d with n == 1
566 * and s == "e:/test.html", "e:/" is returned in d
567 * *** See also directory_walk in src/main/http_request.c
570 * /a/b, 0 ==> / (true for all platforms)
579 * c:/a/b 3 ==> c:/a/b
580 * c:/a/b 4 ==> c:/a/b
582 AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
591 if (*s == '\0' || (*s == '/' && (--n) == 0)) {
603 * return the parent directory name including trailing / of the file s
605 AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
607 const char *last_slash = ap_strrchr_c(s, '/');
611 if (last_slash == NULL) {
612 /* XXX: well this is really broken if this happens */
613 return (apr_pstrdup(p, "/"));
615 l = (last_slash - s) + 1;
616 d = apr_palloc(p, l + 1);
623 AP_DECLARE(int) ap_count_dirs(const char *path)
627 for (x = 0, n = 0; path[x]; x++)
634 AP_DECLARE(void) ap_chdir_file(const char *file)
637 char buf[HUGE_STRING_LEN];
639 x = ap_strrchr_c(file, '/');
643 else if (x - file < sizeof(buf) - 1) {
644 memcpy(buf, file, x - file);
645 buf[x - file] = '\0';
648 /* XXX: well, this is a silly function, no method of reporting an
649 * error... ah well. */
652 AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
654 return ap_getword(atrans, (const char **) line, stop);
657 AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
659 const char *pos = ap_strchr_c(*line, stop);
663 res = apr_pstrdup(atrans, *line);
664 *line += strlen(*line);
668 res = apr_pstrndup(atrans, *line, pos - *line);
670 while (*pos == stop) {
679 AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
681 return ap_getword_white(atrans, (const char **) line);
684 AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
689 for (x = 0; (*line)[x]; x++) {
690 if (apr_isspace((*line)[x])) {
697 res = apr_pstrdup(atrans, *line);
698 *line += strlen(*line);
702 res = apr_palloc(atrans, pos + 1);
703 apr_cpystrn(res, *line, pos + 1);
705 while (apr_isspace((*line)[pos]))
713 AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line, char stop)
715 return ap_getword_nulls(atrans, (const char **) line, stop);
718 AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line, char stop)
720 const char *pos = ap_strchr_c(*line, stop);
724 res = apr_pstrdup(atrans, *line);
725 *line += strlen(*line);
729 res = apr_pstrndup(atrans, *line, pos - *line);
738 /* Get a word, (new) config-file style --- quoted strings and backslashes
742 static char *substring_conf(apr_pool_t *p, const char *start, int len, char quote)
744 char *result = apr_palloc(p, len + 2);
748 for (i = 0; i < len; ++i) {
749 if (start[i] == '\\' && (start[i + 1] == '\\'
750 || (quote && start[i + 1] == quote)))
751 *resp++ = start[++i];
757 #if RESOLVE_ENV_PER_TOKEN
758 return ap_resolve_env(p,result);
764 AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
766 return ap_getword_conf(p, (const char **) line);
769 AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
771 const char *str = *line, *strend;
775 while (*str && apr_isspace(*str))
783 if ((quote = *str) == '"' || quote == '\'') {
785 while (*strend && *strend != quote) {
786 if (*strend == '\\' && strend[1] && strend[1] == quote)
791 res = substring_conf(p, str + 1, strend - str - 1, quote);
793 if (*strend == quote)
798 while (*strend && !apr_isspace(*strend))
801 res = substring_conf(p, str, strend - str, 0);
804 while (*strend && apr_isspace(*strend))
810 /* Check a string for any ${ENV} environment variable
811 * construct and replace each them by the value of
812 * that environment variable, if it exists. If the
813 * environment value does not exist, leave the ${ENV}
814 * construct alone; it means something else.
816 AP_DECLARE(const char *) ap_resolve_env(apr_pool_t *p, const char * word)
818 char tmp[ MAX_STRING_LEN ];
822 if (!(s=ap_strchr_c(word,'$')))
826 /* XXX - relies on strncat() to add '\0'
828 strncat(tmp,word,s - word);
829 if ((s[1] == '{') && (e=ap_strchr_c(s,'}'))) {
836 strncat(tmp, s, e2-s);
840 /* ignore invalid strings */
844 } while ((s=ap_strchr_c(word,'$')));
847 return apr_pstrdup(p,tmp);
849 AP_DECLARE(int) ap_cfg_closefile(configfile_t *cfp)
852 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL,
853 "Done with config file %s", cfp->name);
855 return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
858 static apr_status_t cfg_close(void *param)
860 apr_file_t *cfp = (apr_file_t *) param;
861 return (apr_close(cfp));
864 static int cfg_getch(void *param)
867 apr_file_t *cfp = (apr_file_t *) param;
868 if (apr_getc(&ch, cfp) == APR_SUCCESS)
873 static void *cfg_getstr(void *buf, size_t bufsiz, void *param)
875 apr_file_t *cfp = (apr_file_t *) param;
877 rv = apr_fgets(buf, bufsiz, cfp);
878 if (rv == APR_SUCCESS || (rv == APR_EOF && strcmp(buf, "")))
883 /* Open a configfile_t as FILE, return open configfile_t struct pointer */
884 AP_DECLARE(apr_status_t) ap_pcfg_openfile(configfile_t **ret_cfg, apr_pool_t *p, const char *name)
886 configfile_t *new_cfg;
887 apr_file_t *file = NULL;
895 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
896 "Internal error: pcfg_openfile() called with NULL filename");
900 /* ### We no longer need the test ap_os_is_filename_valid() here
901 * The directory was already walked on a segment by segment basis,
902 * so we should never be called with a bad path element, and device
903 * names as access file names never posed as security threats, since
904 * it was the admin's choice to assign the .htaccess file's name.
907 status = apr_open(&file, name, APR_READ | APR_BUFFERED, APR_OS_DEFAULT, p);
909 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL,
910 "Opening config file %s (%s)",
911 name, (status != APR_SUCCESS) ?
912 apr_strerror(status, buf, sizeof(buf)) : "successful");
914 if (status != APR_SUCCESS)
917 status = apr_getfileinfo(&finfo, file);
918 if (status != APR_SUCCESS)
921 if (finfo.filetype != APR_REG &&
922 #if defined(WIN32) || defined(OS2)
923 !(strcasecmp(name, "nul") == 0 ||
924 (strlen(name) >= 4 &&
925 strcasecmp(name + strlen(name) - 4, "/nul") == 0))) {
927 strcmp(name, "/dev/null") != 0) {
928 #endif /* WIN32 || OS2 */
929 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, NULL,
930 "Access to file %s denied by server: not a regular file",
936 new_cfg = apr_palloc(p, sizeof(*new_cfg));
937 new_cfg->param = file;
938 new_cfg->name = apr_pstrdup(p, name);
939 new_cfg->getch = (int (*)(void *)) cfg_getch;
940 new_cfg->getstr = (void *(*)(void *, size_t, void *)) cfg_getstr;
941 new_cfg->close = (int (*)(void *)) cfg_close;
942 new_cfg->line_number = 0;
948 /* Allocate a configfile_t handle with user defined functions and params */
949 AP_DECLARE(configfile_t *) ap_pcfg_open_custom(apr_pool_t *p, const char *descr,
951 int(*getch)(void *param),
952 void *(*getstr) (void *buf, size_t bufsiz, void *param),
953 int(*close_func)(void *param))
955 configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
957 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, NULL, "Opening config handler %s", descr);
959 new_cfg->param = param;
960 new_cfg->name = descr;
961 new_cfg->getch = getch;
962 new_cfg->getstr = getstr;
963 new_cfg->close = close_func;
964 new_cfg->line_number = 0;
969 /* Read one character from a configfile_t */
970 AP_DECLARE(int) ap_cfg_getc(configfile_t *cfp)
972 register int ch = cfp->getch(cfp->param);
979 /* Read one line from open configfile_t, strip LF, increase line number */
980 /* If custom handler does not define a getstr() function, read char by char */
981 AP_DECLARE(int) ap_cfg_getline(char *buf, size_t bufsize, configfile_t *cfp)
983 /* If a "get string" function is defined, use it */
984 if (cfp->getstr != NULL) {
988 size_t cbufsize = bufsize;
992 if (cfp->getstr(cbuf, cbufsize, cfp->param) == NULL)
996 * check for line continuation,
997 * i.e. match [^\\]\\[\r]\n only
1000 while (cp < cbuf+cbufsize && *cp != '\0')
1002 if (cp > cbuf && cp[-1] == LF) {
1004 if (cp > cbuf && cp[-1] == CR)
1006 if (cp > cbuf && cp[-1] == '\\') {
1008 if (!(cp > cbuf && cp[-1] == '\\')) {
1010 * line continuation requested -
1011 * then remove backslash and continue
1013 cbufsize -= (cp-cbuf);
1019 * no real continuation because escaped -
1020 * then just remove escape character
1022 for ( ; cp < cbuf+cbufsize && *cp != '\0'; cp++)
1031 * Leading and trailing white space is eliminated completely
1034 while (apr_isspace(*src))
1036 /* blast trailing whitespace */
1037 dst = &src[strlen(src)];
1038 while (--dst >= src && apr_isspace(*dst))
1040 /* Zap leading whitespace by shifting */
1042 for (dst = buf; (*dst++ = *src++) != '\0'; )
1045 #ifdef DEBUG_CFG_LINES
1046 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1050 /* No "get string" function defined; read character by character */
1052 register size_t i = 0;
1055 /* skip leading whitespace */
1057 c = cfp->getch(cfp->param);
1058 } while (c == '\t' || c == ' ');
1064 /* too small, assume caller is crazy */
1069 if ((c == '\t') || (c == ' ')) {
1071 while ((c == '\t') || (c == ' '))
1072 c = cfp->getch(cfp->param);
1075 /* silently ignore CR (_assume_ that a LF follows) */
1076 c = cfp->getch(cfp->param);
1079 /* increase line number and return on LF */
1082 if (c == EOF || c == 0x4 || c == LF || i >= (bufsize - 2)) {
1084 * check for line continuation
1086 if (i > 0 && buf[i-1] == '\\') {
1088 if (!(i > 0 && buf[i-1] == '\\')) {
1089 /* line is continued */
1090 c = cfp->getch(cfp->param);
1093 /* else nothing needs be done because
1094 * then the backslash is escaped and
1095 * we just strip to a single one
1098 /* blast trailing whitespace */
1099 while (i > 0 && apr_isspace(buf[i - 1]))
1102 #ifdef DEBUG_CFG_LINES
1103 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, NULL, "Read config: %s", buf);
1109 c = cfp->getch(cfp->param);
1114 /* Size an HTTP header field list item, as separated by a comma.
1115 * The return value is a pointer to the beginning of the non-empty list item
1116 * within the original string (or NULL if there is none) and the address
1117 * of field is shifted to the next non-comma, non-whitespace character.
1118 * len is the length of the item excluding any beginning whitespace.
1120 AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1122 const unsigned char *ptr = (const unsigned char *)*field;
1123 const unsigned char *token;
1124 int in_qpair, in_qstr, in_com;
1126 /* Find first non-comma, non-whitespace byte */
1128 while (*ptr == ',' || apr_isspace(*ptr))
1133 /* Find the end of this item, skipping over dead bits */
1135 for (in_qpair = in_qstr = in_com = 0;
1136 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1144 case '\\': in_qpair = 1; /* quoted-pair */
1146 case '"' : if (!in_com) /* quoted string delim */
1149 case '(' : if (!in_qstr) /* comment (may nest) */
1152 case ')' : if (in_com) /* end comment */
1160 if ((*len = (ptr - token)) == 0) {
1161 *field = (const char *)ptr;
1165 /* Advance field pointer to the next non-comma, non-white byte */
1167 while (*ptr == ',' || apr_isspace(*ptr))
1170 *field = (const char *)ptr;
1171 return (const char *)token;
1174 /* Retrieve an HTTP header field list item, as separated by a comma,
1175 * while stripping insignificant whitespace and lowercasing anything not in
1176 * a quoted string or comment. The return value is a new string containing
1177 * the converted list item (or NULL if none) and the address pointed to by
1178 * field is shifted to the next non-comma, non-whitespace.
1180 AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1182 const char *tok_start;
1183 const unsigned char *ptr;
1186 int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1188 /* Find the beginning and maximum length of the list item so that
1189 * we can allocate a buffer for the new string and reset the field.
1191 if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1194 token = apr_palloc(p, tok_len + 1);
1196 /* Scan the token again, but this time copy only the good bytes.
1197 * We skip extra whitespace and any whitespace around a '=', '/',
1198 * or ';' and lowercase normal characters not within a comment,
1199 * quoted-string or quoted-pair.
1201 for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1202 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1211 case '\\': in_qpair = 1;
1217 case '"' : if (!in_com)
1224 case '(' : if (!in_qstr)
1231 case ')' : if (in_com)
1237 case '\t': if (addspace)
1239 if (in_com || in_qstr)
1246 case ';' : if (!(in_com || in_qstr))
1250 default : if (addspace == 1)
1252 *pos++ = (in_com || in_qstr) ? *ptr
1253 : apr_tolower(*ptr);
1264 /* Find an item in canonical form (lowercase, no extra spaces) within
1265 * an HTTP field value list. Returns 1 if found, 0 if not found.
1266 * This would be much more efficient if we stored header fields as
1267 * an array of list items as they are received instead of a plain string.
1269 AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line, const char *tok)
1271 const unsigned char *pos;
1272 const unsigned char *ptr = (const unsigned char *)line;
1273 int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1278 do { /* loop for each item in line's list */
1280 /* Find first non-comma, non-whitespace byte */
1282 while (*ptr == ',' || apr_isspace(*ptr))
1286 good = 1; /* until proven otherwise for this item */
1288 break; /* no items left and nothing good found */
1290 /* We skip extra whitespace and any whitespace around a '=', '/',
1291 * or ';' and lowercase normal characters not within a comment,
1292 * quoted-string or quoted-pair.
1294 for (pos = (const unsigned char *)tok;
1295 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1301 good = (*pos++ == *ptr);
1305 case '\\': in_qpair = 1;
1307 good = good && (*pos++ == ' ');
1308 good = good && (*pos++ == *ptr);
1311 case '"' : if (!in_com)
1314 good = good && (*pos++ == ' ');
1315 good = good && (*pos++ == *ptr);
1318 case '(' : if (!in_qstr)
1321 good = good && (*pos++ == ' ');
1322 good = good && (*pos++ == *ptr);
1325 case ')' : if (in_com)
1327 good = good && (*pos++ == *ptr);
1331 case '\t': if (addspace || !good)
1333 if (in_com || in_qstr)
1334 good = (*pos++ == *ptr);
1340 case ';' : if (!(in_com || in_qstr))
1342 good = good && (*pos++ == *ptr);
1344 default : if (!good)
1347 good = (*pos++ == ' ');
1348 if (in_com || in_qstr)
1349 good = good && (*pos++ == *ptr);
1351 good = good && (*pos++ == apr_tolower(*ptr));
1358 good = 0; /* not good if only a prefix was matched */
1360 } while (*ptr && !good);
1366 /* Retrieve a token, spacing over it and returning a pointer to
1367 * the first non-white byte afterwards. Note that these tokens
1368 * are delimited by semis and commas; and can also be delimited
1369 * by whitespace at the caller's option.
1372 AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line, int accept_white)
1374 const char *ptr = *accept_line;
1375 const char *tok_start;
1379 /* Find first non-white byte */
1381 while (*ptr && apr_isspace(*ptr))
1386 /* find token end, skipping over quoted strings.
1387 * (comments are already gone).
1390 while (*ptr && (accept_white || !apr_isspace(*ptr))
1391 && *ptr != ';' && *ptr != ',') {
1398 tok_len = ptr - tok_start;
1399 token = apr_pstrndup(p, tok_start, tok_len);
1401 /* Advance accept_line pointer to the next non-white byte */
1403 while (*ptr && apr_isspace(*ptr))
1411 /* find http tokens, see the definition of token from RFC2068 */
1412 AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1414 const unsigned char *start_token;
1415 const unsigned char *s;
1420 s = (const unsigned char *)line;
1422 /* find start of token, skip all stop characters, note NUL
1423 * isn't a token stop, so we don't need to test for it
1425 while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1432 /* find end of the token */
1433 while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1436 if (!strncasecmp((const char *)start_token, (const char *)tok, s - start_token)) {
1446 AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line, const char *tok)
1448 int llen, tlen, lidx;
1453 llen = strlen(line);
1458 ((lidx > 0) && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1461 return (strncasecmp(&line[lidx], tok, tlen) == 0);
1464 AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1468 const unsigned char *s;
1470 cmd = apr_palloc(p, 2 * strlen(str) + 1); /* Be safe */
1471 d = (unsigned char *)cmd;
1472 s = (const unsigned char *)str;
1475 #if defined(OS2) || defined(WIN32)
1476 /* Don't allow '&' in parameters under OS/2. */
1477 /* This can be used to send commands to the shell. */
1484 if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1494 static char x2c(const char *what)
1496 register char digit;
1498 #if !APR_CHARSET_EBCDIC
1499 digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
1501 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
1502 #else /*APR_CHARSET_EBCDIC*/
1509 digit = apr_xlate_conv_byte(ap_hdrs_from_ascii, 0xFF & strtol(xstr, NULL, 16));
1510 #endif /*APR_CHARSET_EBCDIC*/
1516 * Returns 0 on success, non-zero on error
1518 * bad % escape returns HTTP_BAD_REQUEST
1520 * decoding %00 -> \0
1521 * decoding %2f -> / (a special character)
1522 * returns HTTP_NOT_FOUND
1524 AP_DECLARE(int) ap_unescape_url(char *url)
1526 register int badesc, badpath;
1531 /* Initial scan for first '%'. Don't bother writing values before
1533 y = strchr(url, '%');
1537 for (x = y; *y; ++x, ++y) {
1541 if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1548 if (*x == '/' || *x == '\0')
1555 return HTTP_BAD_REQUEST;
1557 return HTTP_NOT_FOUND;
1562 AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
1563 apr_port_t port, const request_rec *r)
1565 if (ap_is_default_port(port, r))
1566 return apr_pstrdup(p, hostname);
1568 return apr_psprintf(p, "%s:%u", hostname, port);
1572 /* c2x takes an unsigned, and expects the caller has guaranteed that
1573 * 0 <= what < 256... which usually means that you have to cast to
1574 * unsigned char first, because (unsigned)(char)(x) first goes through
1575 * signed extension to an int before the unsigned cast.
1577 * The reason for this assumption is to assist gcc code generation --
1578 * the unsigned char -> unsigned extension is already done earlier in
1579 * both uses of this code, so there's no need to waste time doing it
1582 static const char c2x_table[] = "0123456789abcdef";
1584 static apr_inline unsigned char *c2x(unsigned what, unsigned char *where)
1586 #if APR_CHARSET_EBCDIC
1587 what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
1588 #endif /*APR_CHARSET_EBCDIC*/
1590 *where++ = c2x_table[what >> 4];
1591 *where++ = c2x_table[what & 0xf];
1596 * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1597 * routine is (should be) OS independent.
1599 * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1600 * cases if a ':' occurs before the first '/' in the URL, the URL should be
1601 * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1602 * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1603 * efficiency reasons, we don't use escape_path_segment(), which is provided for
1604 * reference. Again, RFC 1808 is where this stuff is defined.
1606 * If partial is set, os_escape_path() assumes that the path will be appended to
1607 * something with a '/' in it (and thus does not prefix "./").
1610 AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
1612 char *copy = apr_palloc(p, 3 * strlen(segment) + 1);
1613 const unsigned char *s = (const unsigned char *)segment;
1614 unsigned char *d = (unsigned char *)copy;
1618 if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1630 AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
1632 char *copy = apr_palloc(p, 3 * strlen(path) + 3);
1633 const unsigned char *s = (const unsigned char *)path;
1634 unsigned char *d = (unsigned char *)copy;
1638 const char *colon = ap_strchr_c(path, ':');
1639 const char *slash = ap_strchr_c(path, '/');
1641 if (colon && (!slash || colon < slash)) {
1647 if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1659 /* ap_escape_uri is now a macro for os_escape_path */
1661 AP_DECLARE(char *) ap_escape_html(apr_pool_t *p, const char *s)
1666 /* first, count the number of extra characters */
1667 for (i = 0, j = 0; s[i] != '\0'; i++)
1668 if (s[i] == '<' || s[i] == '>')
1670 else if (s[i] == '&')
1674 return apr_pstrndup(p, s, i);
1676 x = apr_palloc(p, i + j + 1);
1677 for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1679 memcpy(&x[j], "<", 4);
1682 else if (s[i] == '>') {
1683 memcpy(&x[j], ">", 4);
1686 else if (s[i] == '&') {
1687 memcpy(&x[j], "&", 5);
1697 AP_DECLARE(int) ap_is_directory(const char *path)
1701 if (apr_stat(&finfo, path, NULL) == -1)
1702 return 0; /* in error condition, just return no */
1704 return (finfo.filetype == APR_DIR);
1707 AP_DECLARE(int) ap_is_rdirectory(const char *path)
1711 if (apr_lstat(&finfo, path, NULL) == -1)
1712 return 0; /* in error condition, just return no */
1714 return (finfo.filetype == APR_DIR);
1717 AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
1724 return apr_pstrcat(a, "/", src2, NULL);
1726 if (src1[x - 1] != '/')
1727 return apr_pstrcat(a, src1, "/", src2, NULL);
1729 return apr_pstrcat(a, src1, src2, NULL);
1733 * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
1735 AP_DECLARE(int) ap_is_url(const char *u)
1739 for (x = 0; u[x] != ':'; x++) {
1741 ((!apr_isalpha(u[x])) && (!apr_isdigit(u[x])) &&
1742 (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
1747 return (x ? 1 : 0); /* If the first character is ':', it's broken, too */
1750 #ifndef HAVE_INITGROUPS
1751 int initgroups(const char *name, gid_t basegid)
1753 #if defined(QNX) || defined(MPE) || defined(BEOS) || defined(_OSD_POSIX) || defined(TPF) || defined(__TANDEM) || defined(OS2) || defined(WIN32)
1754 /* QNX, MPE and BeOS do not appear to support supplementary groups. */
1756 #else /* ndef QNX */
1757 gid_t groups[NGROUPS_MAX];
1763 groups[index++] = basegid;
1765 while (index < NGROUPS_MAX && ((g = getgrent()) != NULL))
1766 if (g->gr_gid != basegid) {
1769 for (names = g->gr_mem; *names != NULL; ++names)
1770 if (!strcmp(*names, name))
1771 groups[index++] = g->gr_gid;
1776 return setgroups(index, groups);
1777 #endif /* def QNX */
1779 #endif /* def NEED_INITGROUPS */
1781 AP_DECLARE(int) ap_ind(const char *s, char c)
1785 for (x = 0; s[x]; x++)
1792 AP_DECLARE(int) ap_rind(const char *s, char c)
1796 for (x = strlen(s) - 1; x != -1; x--)
1803 AP_DECLARE(void) ap_str_tolower(char *str)
1806 *str = apr_tolower(*str);
1811 AP_DECLARE(uid_t) ap_uname2id(const char *name)
1819 return (atoi(&name[1]));
1821 if (!(ent = getpwnam(name))) {
1822 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "%s: bad user name %s", ap_server_argv0, name);
1825 return (ent->pw_uid);
1829 AP_DECLARE(gid_t) ap_gname2id(const char *name)
1837 return (atoi(&name[1]));
1839 if (!(ent = getgrnam(name))) {
1840 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "%s: bad group name %s", ap_server_argv0, name);
1843 return (ent->gr_gid);
1848 static char *find_fqdn(apr_pool_t *a, struct hostent *p)
1852 if (!strchr(p->h_name, '.')) {
1853 for (x = 0; p->h_aliases[x]; ++x) {
1854 if (strchr(p->h_aliases[x], '.') &&
1855 (!strncasecmp(p->h_aliases[x], p->h_name, strlen(p->h_name))))
1856 return apr_pstrdup(a, p->h_aliases[x]);
1860 return apr_pstrdup(a, (void *) p->h_name);
1863 char *ap_get_local_host(apr_pool_t *a)
1865 #ifndef MAXHOSTNAMELEN
1866 #define MAXHOSTNAMELEN 256
1868 char str[MAXHOSTNAMELEN + 1];
1869 char *server_hostname = NULL;
1873 if (gethostname(str, sizeof(str) - 1) == 0)
1875 if (gethostname(str, sizeof(str) - 1) != 0)
1878 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, NULL,
1879 "%s: gethostname() failed to determine ServerName",
1884 str[sizeof(str) - 1] = '\0';
1885 if ((!(p = gethostbyname(str)))
1886 || (!(server_hostname = find_fqdn(a, p)))) {
1887 /* Recovery - return the default servername by IP: */
1888 if (!str && p->h_addr_list[0]) {
1889 apr_snprintf(str, sizeof(str), "%pA", p->h_addr_list[0]);
1890 server_hostname = apr_pstrdup(a, str);
1891 /* We will drop through to report the IP-named server */
1895 /* Since we found a fdqn, return it with no logged message. */
1896 return server_hostname;
1900 if (!server_hostname)
1901 server_hostname = apr_pstrdup(a, "127.0.0.1");
1903 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO|APLOG_STARTUP, 0, NULL,
1904 "%s: Could not determine the server's fully qualified "
1905 "domain name, using %s for ServerName",
1906 ap_server_argv0, server_hostname);
1908 return server_hostname;
1911 /* simple 'pool' alloc()ing glue to ap_base64.c
1913 AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
1918 decoded = (char *) apr_palloc(p, 1 + ap_base64decode_len(bufcoded));
1919 l = ap_base64decode(decoded, bufcoded);
1920 decoded[l] = '\0'; /* make binary sequence into string */
1925 AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string)
1928 int l = strlen(string);
1930 encoded = (char *) apr_palloc(p, 1 + ap_base64encode_len(l));
1931 l = ap_base64encode(encoded, string, l);
1932 encoded[l] = '\0'; /* make binary sequence into string */
1937 /* we want to downcase the type/subtype for comparison purposes
1938 * but nothing else because ;parameter=foo values are case sensitive.
1939 * XXX: in truth we want to downcase parameter names... but really,
1940 * apache has never handled parameters and such correctly. You
1941 * also need to compress spaces and such to be able to compare
1944 AP_DECLARE(void) ap_content_type_tolower(char *str)
1948 semi = strchr(str, ';');
1953 *str = apr_tolower(*str);
1962 * Given a string, replace any bare " with \" .
1964 AP_DECLARE(char *) ap_escape_quotes (apr_pool_t *p, const char *instring)
1967 const char *inchr = instring;
1968 char *outchr, *outstring;
1971 * Look through the input string, jogging the length of the output
1972 * string up by an extra byte each time we find an unescaped ".
1974 while (*inchr != '\0') {
1976 if (*inchr == '"') {
1980 * If we find a slosh, and it's not the last byte in the string,
1981 * it's escaping something - advance past both bytes.
1983 if ((*inchr == '\\') && (inchr[1] != '\0')) {
1989 outstring = apr_palloc(p, newlen + 1);
1993 * Now copy the input string to the output string, inserting a slosh
1994 * in front of every " that doesn't already have one.
1996 while (*inchr != '\0') {
1997 if ((*inchr == '\\') && (inchr[1] != '\0')) {
1998 *outchr++ = *inchr++;
1999 *outchr++ = *inchr++;
2001 if (*inchr == '"') {
2004 if (*inchr != '\0') {
2005 *outchr++ = *inchr++;