1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * util.c: string utility things
21 * 1995-96 Many changes by the Apache Software Foundation
26 * #define DEBUG to trace all cfg_open*()/cfg_closefile() calls
27 * #define DEBUG_CFG_LINES to trace every line read from the config files
31 #include "apr_strings.h"
34 #define APR_WANT_STDIO
35 #define APR_WANT_STRFUNC
42 #include <netdb.h> /* for gethostbyname() */
47 #include "ap_config.h"
48 #include "apr_base64.h"
50 #include "http_main.h"
52 #include "http_protocol.h"
53 #include "http_config.h"
54 #include "util_ebcdic.h"
63 /* A bunch of functions in util.c scan strings looking for certain characters.
64 * To make that more efficient we encode a lookup table. The test_char_table
65 * is generated automatically by gen_test_char.c.
67 #include "test_char.h"
69 /* we assume the folks using this ensure 0 <= c < 256... which means
70 * you need a cast to (unsigned char) first, you can't just plug a
71 * char in here and get it to work, because if char is signed then it
72 * will first be sign extended.
74 #define TEST_CHAR(c, f) (test_char_table[(unsigned)(c)] & (f))
76 /* Win32/NetWare/OS2 need to check for both forward and back slashes
77 * in ap_getparents() and ap_escape_url.
79 #ifdef CASE_BLIND_FILESYSTEM
80 #define IS_SLASH(s) ((s == '/') || (s == '\\'))
82 #define IS_SLASH(s) (s == '/')
87 * Examine a field value (such as a media-/content-type) string and return
88 * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
90 AP_DECLARE(char *) ap_field_noparam(apr_pool_t *p, const char *intype)
94 if (intype == NULL) return NULL;
96 semi = ap_strchr_c(intype, ';');
98 return apr_pstrdup(p, intype);
101 while ((semi > intype) && apr_isspace(semi[-1])) {
104 return apr_pstrndup(p, intype, semi - intype);
108 AP_DECLARE(char *) ap_ht_time(apr_pool_t *p, apr_time_t t, const char *fmt,
112 char ts[MAX_STRING_LEN];
113 char tf[MAX_STRING_LEN];
120 apr_time_exp_gmt(&xt, t);
121 /* Convert %Z to "GMT" and %z to "+0000";
122 * on hosts that do not have a time zone string in struct tm,
123 * strftime must assume its argument is local time.
125 for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
127 if (*f != '%') continue;
138 case 'z': /* common extension */
152 apr_time_exp_lt(&xt, t);
155 /* check return code? */
156 apr_strftime(ts, &retcode, MAX_STRING_LEN, fmt, &xt);
157 ts[MAX_STRING_LEN - 1] = '\0';
158 return apr_pstrdup(p, ts);
161 /* Roy owes Rob beer. */
162 /* Rob owes Roy dinner. */
164 /* These legacy comments would make a lot more sense if Roy hadn't
165 * replaced the old later_than() routine with util_date.c.
167 * Well, okay, they still wouldn't make any sense.
170 /* Match = 0, NoMatch = 1, Abort = -1
171 * Based loosely on sections of wildmat.c by Rich Salz
172 * Hmmm... shouldn't this really go component by component?
174 AP_DECLARE(int) ap_strcmp_match(const char *str, const char *expected)
178 for (x = 0, y = 0; expected[y]; ++y, ++x) {
179 if ((!str[x]) && (expected[y] != '*'))
181 if (expected[y] == '*') {
182 while (expected[++y] == '*');
187 if ((ret = ap_strcmp_match(&str[x++], &expected[y])) != 1)
192 else if ((expected[y] != '?') && (str[x] != expected[y]))
195 return (str[x] != '\0');
198 AP_DECLARE(int) ap_strcasecmp_match(const char *str, const char *expected)
202 for (x = 0, y = 0; expected[y]; ++y, ++x) {
203 if (!str[x] && expected[y] != '*')
205 if (expected[y] == '*') {
206 while (expected[++y] == '*');
211 if ((ret = ap_strcasecmp_match(&str[x++], &expected[y])) != 1)
216 else if (expected[y] != '?'
217 && apr_tolower(str[x]) != apr_tolower(expected[y]))
220 return (str[x] != '\0');
223 /* We actually compare the canonical root to this root, (but we don't
224 * waste time checking the case), since every use of this function in
225 * httpd-2.0 tests if the path is 'proper', meaning we've already passed
226 * it through apr_filepath_merge, or we haven't.
228 AP_DECLARE(int) ap_os_is_path_absolute(apr_pool_t *p, const char *dir)
231 const char *ourdir = dir;
232 if (apr_filepath_root(&newpath, &dir, 0, p) != APR_SUCCESS
233 || strncmp(newpath, ourdir, strlen(newpath)) != 0) {
239 AP_DECLARE(int) ap_is_matchexp(const char *str)
243 for (x = 0; str[x]; x++)
244 if ((str[x] == '*') || (str[x] == '?'))
250 * Here's a pool-based interface to POSIX regex's regcomp().
251 * Note that we return regex_t instead of being passed one.
252 * The reason is that if you use an already-used regex_t structure,
253 * the memory that you've already allocated gets forgotten, and
254 * regfree() doesn't clear it. So we don't allow it.
257 static apr_status_t regex_cleanup(void *preg)
259 regfree((regex_t *) preg);
263 AP_DECLARE(regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
266 regex_t *preg = apr_palloc(p, sizeof(regex_t));
268 if (regcomp(preg, pattern, cflags)) {
272 apr_pool_cleanup_register(p, (void *) preg, regex_cleanup,
273 apr_pool_cleanup_null);
278 AP_DECLARE(void) ap_pregfree(apr_pool_t *p, regex_t * reg)
281 apr_pool_cleanup_kill(p, (void *) reg, regex_cleanup);
285 * Similar to standard strstr() but we ignore case in this version.
286 * Based on the strstr() implementation further below.
288 AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
296 for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
300 /* found first character of s2, see if the rest matches */
303 for (++p1, ++p2; apr_tolower(*p1) == apr_tolower(*p2); ++p1, ++p2) {
305 /* both strings ended together */
310 /* second string ended, a match */
313 /* didn't find a match here, try starting at next character in s1 */
320 * Returns an offsetted pointer in bigstring immediately after
321 * prefix. Returns bigstring if bigstring doesn't start with
322 * prefix or if prefix is longer than bigstring while still matching.
323 * NOTE: pointer returned is relative to bigstring, so we
324 * can use standard pointer comparisons in the calling function
325 * (eg: test if ap_stripprefix(a,b) == a)
327 AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
336 while (*p1 && *prefix) {
337 if (*p1++ != *prefix++)
343 /* hit the end of bigstring! */
348 * Apache stub function for the regex libraries regexec() to make sure the
349 * whole regex(3) API is available through the Apache (exported) namespace.
350 * This is especially important for the DSO situations of modules.
351 * DO NOT MAKE A MACRO OUT OF THIS FUNCTION!
353 AP_DECLARE(int) ap_regexec(regex_t *preg, const char *string,
354 size_t nmatch, regmatch_t pmatch[], int eflags)
356 return regexec(preg, string, nmatch, pmatch, eflags);
359 AP_DECLARE(size_t) ap_regerror(int errcode, const regex_t *preg, char *errbuf,
362 return regerror(errcode, preg, errbuf, errbuf_size);
366 /* This function substitutes for $0-$9, filling in regular expression
367 * submatches. Pass it the same nmatch and pmatch arguments that you
368 * passed ap_regexec(). pmatch should not be greater than the maximum number
369 * of subexpressions - i.e. one more than the re_nsub member of regex_t.
371 * input should be the string with the $-expressions, source should be the
372 * string that was matched against.
374 * It returns the substituted string, or NULL on error.
376 * Parts of this code are based on Henry Spencer's regsub(), from his
377 * AT&T V8 regexp package.
380 AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input,
381 const char *source, size_t nmatch,
384 const char *src = input;
393 return apr_pstrdup(p, src);
395 /* First pass, find the size */
399 while ((c = *src++) != '\0') {
402 else if (c == '$' && apr_isdigit(*src))
407 if (no > 9) { /* Ordinary character. */
408 if (c == '\\' && (*src == '$' || *src == '&'))
412 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
413 len += pmatch[no].rm_eo - pmatch[no].rm_so;
418 dest = dst = apr_pcalloc(p, len + 1);
420 /* Now actually fill in the string */
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;
439 memcpy(dst, source + pmatch[no].rm_so, len);
450 * Parse .. so we don't compromise security
452 AP_DECLARE(void) ap_getparents(char *name)
457 /* Four paseses, as per RFC 1808 */
458 /* a) remove ./ path segments */
459 for (next = name; *next && (*next != '.'); next++) {
462 l = w = first_dot = next - name;
463 while (name[l] != '\0') {
464 if (name[l] == '.' && IS_SLASH(name[l + 1])
465 && (l == 0 || IS_SLASH(name[l - 1])))
468 name[w++] = name[l++];
471 /* b) remove trailing . path, segment */
472 if (w == 1 && name[0] == '.')
474 else if (w > 1 && name[w - 1] == '.' && IS_SLASH(name[w - 2]))
478 /* c) remove all xx/../ segments. (including leading ../ and /../) */
481 while (name[l] != '\0') {
482 if (name[l] == '.' && name[l + 1] == '.' && IS_SLASH(name[l + 2])
483 && (l == 0 || IS_SLASH(name[l - 1]))) {
484 register int m = l + 3, n;
488 while (l >= 0 && !IS_SLASH(name[l]))
495 while ((name[n] = name[m]))
502 /* d) remove trailing xx/.. segment. */
503 if (l == 2 && name[0] == '.' && name[1] == '.')
505 else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.'
506 && IS_SLASH(name[l - 3])) {
509 while (l >= 0 && !IS_SLASH(name[l]))
519 AP_DECLARE(void) ap_no2slash(char *name)
525 #ifdef HAVE_UNC_PATHS
526 /* Check for UNC names. Leave leading two slashes. */
527 if (s[0] == '/' && s[1] == '/')
532 if ((*d++ = *s) == '/') {
546 * copy at most n leading directories of s into d
547 * d should be at least as large as s plus 1 extra byte
549 * the return value is the ever useful pointer to the trailing \0 of d
551 * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments,
552 * so that if n == 0, "/" is returned in d with n == 1
553 * and s == "e:/test.html", "e:/" is returned in d
554 * *** See also directory_walk in modules/http/http_request.c
557 * /a/b, 0 ==> / (true for all platforms)
566 * c:/a/b 3 ==> c:/a/b
567 * c:/a/b 4 ==> c:/a/b
569 AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
578 if (*s == '\0' || (*s == '/' && (--n) == 0)) {
590 * return the parent directory name including trailing / of the file s
592 AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
594 const char *last_slash = ap_strrchr_c(s, '/');
598 if (last_slash == NULL) {
599 return apr_pstrdup(p, "");
601 l = (last_slash - s) + 1;
602 d = apr_palloc(p, l + 1);
609 AP_DECLARE(int) ap_count_dirs(const char *path)
613 for (x = 0, n = 0; path[x]; x++)
619 AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
621 return ap_getword(atrans, (const char **) line, stop);
624 AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
626 const char *pos = *line;
630 while ((*pos != stop) && *pos) {
635 res = (char *)apr_palloc(atrans, len + 1);
636 memcpy(res, *line, len);
640 while (*pos == stop) {
649 AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
651 return ap_getword_white(atrans, (const char **) line);
654 AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
656 const char *pos = *line;
660 while (!apr_isspace(*pos) && *pos) {
665 res = (char *)apr_palloc(atrans, len + 1);
666 memcpy(res, *line, len);
669 while (apr_isspace(*pos)) {
678 AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line,
681 return ap_getword_nulls(atrans, (const char **) line, stop);
684 AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line,
687 const char *pos = ap_strchr_c(*line, stop);
691 res = apr_pstrdup(atrans, *line);
692 *line += strlen(*line);
696 res = apr_pstrndup(atrans, *line, pos - *line);
705 /* Get a word, (new) config-file style --- quoted strings and backslashes
709 static char *substring_conf(apr_pool_t *p, const char *start, int len,
712 char *result = apr_palloc(p, len + 2);
716 for (i = 0; i < len; ++i) {
717 if (start[i] == '\\' && (start[i + 1] == '\\'
718 || (quote && start[i + 1] == quote)))
719 *resp++ = start[++i];
725 #if RESOLVE_ENV_PER_TOKEN
726 return (char *)ap_resolve_env(p,result);
732 AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
734 return ap_getword_conf(p, (const char **) line);
737 AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
739 const char *str = *line, *strend;
743 while (*str && apr_isspace(*str))
751 if ((quote = *str) == '"' || quote == '\'') {
753 while (*strend && *strend != quote) {
754 if (*strend == '\\' && strend[1] && strend[1] == quote)
759 res = substring_conf(p, str + 1, strend - str - 1, quote);
761 if (*strend == quote)
766 while (*strend && !apr_isspace(*strend))
769 res = substring_conf(p, str, strend - str, 0);
772 while (*strend && apr_isspace(*strend))
778 /* Check a string for any ${ENV} environment variable
779 * construct and replace each them by the value of
780 * that environment variable, if it exists. If the
781 * environment value does not exist, leave the ${ENV}
782 * construct alone; it means something else.
784 AP_DECLARE(const char *) ap_resolve_env(apr_pool_t *p, const char * word)
786 # define SMALL_EXPANSION 5
791 } *result, *current, sresult[SMALL_EXPANSION];
793 const char *s, *e, *ep;
797 s = ap_strchr_c(word, '$');
802 /* well, actually something to do */
803 ep = word + strlen(word);
805 result = current = &(sresult[spc++]);
806 current->next = NULL;
807 current->string = word;
808 current->len = s - word;
809 outlen = current->len;
812 /* prepare next entry */
814 current->next = (spc < SMALL_EXPANSION)
816 : (struct sll *)apr_palloc(p,
817 sizeof(*current->next));
818 current = current->next;
819 current->next = NULL;
824 if (s[1] == '{' && (e = ap_strchr_c(s, '}'))) {
825 word = getenv(apr_pstrndup(p, s+2, e-s-2));
827 current->string = word;
828 current->len = strlen(word);
829 outlen += current->len;
833 current->len = e - s + 1;
834 outlen += current->len;
839 current->string = s++;
846 s = ap_strchr_c(s, '$');
847 current->string = word;
848 current->len = s ? s - word : ep - word;
849 outlen += current->len;
853 /* assemble result */
854 res_buf = cp = apr_palloc(p, outlen + 1);
857 memcpy(cp, result->string, result->len);
860 result = result->next;
862 res_buf[outlen] = '\0';
867 AP_DECLARE(int) ap_cfg_closefile(ap_configfile_t *cfp)
870 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
871 "Done with config file %s", cfp->name);
873 return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
876 static apr_status_t cfg_close(void *param)
878 apr_file_t *cfp = (apr_file_t *) param;
879 return (apr_file_close(cfp));
882 static int cfg_getch(void *param)
885 apr_file_t *cfp = (apr_file_t *) param;
886 if (apr_file_getc(&ch, cfp) == APR_SUCCESS)
891 static void *cfg_getstr(void *buf, size_t bufsiz, void *param)
893 apr_file_t *cfp = (apr_file_t *) param;
895 rv = apr_file_gets(buf, bufsiz, cfp);
896 if (rv == APR_SUCCESS || (APR_STATUS_IS_EOF(rv) && strcmp(buf, "")))
901 /* Open a ap_configfile_t as FILE, return open ap_configfile_t struct pointer */
902 AP_DECLARE(apr_status_t) ap_pcfg_openfile(ap_configfile_t **ret_cfg,
903 apr_pool_t *p, const char *name)
905 ap_configfile_t *new_cfg;
906 apr_file_t *file = NULL;
914 ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
915 "Internal error: pcfg_openfile() called with NULL filename");
919 status = apr_file_open(&file, name, APR_READ | APR_BUFFERED,
922 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
923 "Opening config file %s (%s)",
924 name, (status != APR_SUCCESS) ?
925 apr_strerror(status, buf, sizeof(buf)) : "successful");
927 if (status != APR_SUCCESS)
930 status = apr_file_info_get(&finfo, APR_FINFO_TYPE, file);
931 if (status != APR_SUCCESS)
934 if (finfo.filetype != APR_REG &&
935 #if defined(WIN32) || defined(OS2) || defined(NETWARE)
936 strcasecmp(apr_filename_of_pathname(name), "nul") != 0) {
938 strcmp(name, "/dev/null") != 0) {
939 #endif /* WIN32 || OS2 */
940 ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
941 "Access to file %s denied by server: not a regular file",
943 apr_file_close(file);
948 /* Some twisted character [no pun intended] at MS decided that a
949 * zero width joiner as the lead wide character would be ideal for
950 * describing Unicode text files. This was further convoluted to
951 * another MSism that the same character mapped into utf-8, EF BB BF
952 * would signify utf-8 text files.
954 * Since MS configuration files are all protecting utf-8 encoded
955 * Unicode path, file and resource names, we already have the correct
956 * WinNT encoding. But at least eat the stupid three bytes up front.
959 unsigned char buf[4];
961 status = apr_file_read(file, buf, &len);
962 if ((status != APR_SUCCESS) || (len < 3)
963 || memcmp(buf, "\xEF\xBB\xBF", 3) != 0) {
965 apr_file_seek(file, APR_SET, &zero);
970 new_cfg = apr_palloc(p, sizeof(*new_cfg));
971 new_cfg->param = file;
972 new_cfg->name = apr_pstrdup(p, name);
973 new_cfg->getch = (int (*)(void *)) cfg_getch;
974 new_cfg->getstr = (void *(*)(void *, size_t, void *)) cfg_getstr;
975 new_cfg->close = (int (*)(void *)) cfg_close;
976 new_cfg->line_number = 0;
982 /* Allocate a ap_configfile_t handle with user defined functions and params */
983 AP_DECLARE(ap_configfile_t *) ap_pcfg_open_custom(apr_pool_t *p,
986 int(*getch)(void *param),
987 void *(*getstr) (void *buf, size_t bufsiz, void *param),
988 int(*close_func)(void *param))
990 ap_configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
992 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
993 "Opening config handler %s", descr);
995 new_cfg->param = param;
996 new_cfg->name = descr;
997 new_cfg->getch = getch;
998 new_cfg->getstr = getstr;
999 new_cfg->close = close_func;
1000 new_cfg->line_number = 0;
1004 /* Read one character from a configfile_t */
1005 AP_DECLARE(int) ap_cfg_getc(ap_configfile_t *cfp)
1007 register int ch = cfp->getch(cfp->param);
1013 /* Read one line from open ap_configfile_t, strip LF, increase line number */
1014 /* If custom handler does not define a getstr() function, read char by char */
1015 AP_DECLARE(int) ap_cfg_getline(char *buf, size_t bufsize, ap_configfile_t *cfp)
1017 /* If a "get string" function is defined, use it */
1018 if (cfp->getstr != NULL) {
1022 size_t cbufsize = bufsize;
1026 if (cfp->getstr(cbuf, cbufsize, cfp->param) == NULL)
1030 * check for line continuation,
1031 * i.e. match [^\\]\\[\r]\n only
1034 while (cp < cbuf+cbufsize && *cp != '\0')
1036 if (cp > cbuf && cp[-1] == LF) {
1038 if (cp > cbuf && cp[-1] == CR)
1040 if (cp > cbuf && cp[-1] == '\\') {
1042 if (!(cp > cbuf && cp[-1] == '\\')) {
1044 * line continuation requested -
1045 * then remove backslash and continue
1047 cbufsize -= (cp-cbuf);
1053 * no real continuation because escaped -
1054 * then just remove escape character
1056 for ( ; cp < cbuf+cbufsize && *cp != '\0'; cp++)
1065 * Leading and trailing white space is eliminated completely
1068 while (apr_isspace(*src))
1070 /* blast trailing whitespace */
1071 dst = &src[strlen(src)];
1072 while (--dst >= src && apr_isspace(*dst))
1074 /* Zap leading whitespace by shifting */
1076 for (dst = buf; (*dst++ = *src++) != '\0'; )
1079 #ifdef DEBUG_CFG_LINES
1080 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, "Read config: %s", buf);
1084 /* No "get string" function defined; read character by character */
1086 register size_t i = 0;
1089 /* skip leading whitespace */
1091 c = cfp->getch(cfp->param);
1092 } while (c == '\t' || c == ' ');
1098 /* too small, assume caller is crazy */
1103 if ((c == '\t') || (c == ' ')) {
1105 while ((c == '\t') || (c == ' '))
1106 c = cfp->getch(cfp->param);
1109 /* silently ignore CR (_assume_ that a LF follows) */
1110 c = cfp->getch(cfp->param);
1113 /* increase line number and return on LF */
1116 if (c == EOF || c == 0x4 || c == LF || i >= (bufsize - 2)) {
1118 * check for line continuation
1120 if (i > 0 && buf[i-1] == '\\') {
1122 if (!(i > 0 && buf[i-1] == '\\')) {
1123 /* line is continued */
1124 c = cfp->getch(cfp->param);
1127 /* else nothing needs be done because
1128 * then the backslash is escaped and
1129 * we just strip to a single one
1132 /* blast trailing whitespace */
1133 while (i > 0 && apr_isspace(buf[i - 1]))
1136 #ifdef DEBUG_CFG_LINES
1137 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1138 "Read config: %s", buf);
1144 c = cfp->getch(cfp->param);
1149 /* Size an HTTP header field list item, as separated by a comma.
1150 * The return value is a pointer to the beginning of the non-empty list item
1151 * within the original string (or NULL if there is none) and the address
1152 * of field is shifted to the next non-comma, non-whitespace character.
1153 * len is the length of the item excluding any beginning whitespace.
1155 AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1157 const unsigned char *ptr = (const unsigned char *)*field;
1158 const unsigned char *token;
1159 int in_qpair, in_qstr, in_com;
1161 /* Find first non-comma, non-whitespace byte */
1163 while (*ptr == ',' || apr_isspace(*ptr))
1168 /* Find the end of this item, skipping over dead bits */
1170 for (in_qpair = in_qstr = in_com = 0;
1171 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1179 case '\\': in_qpair = 1; /* quoted-pair */
1181 case '"' : if (!in_com) /* quoted string delim */
1184 case '(' : if (!in_qstr) /* comment (may nest) */
1187 case ')' : if (in_com) /* end comment */
1195 if ((*len = (ptr - token)) == 0) {
1196 *field = (const char *)ptr;
1200 /* Advance field pointer to the next non-comma, non-white byte */
1202 while (*ptr == ',' || apr_isspace(*ptr))
1205 *field = (const char *)ptr;
1206 return (const char *)token;
1209 /* Retrieve an HTTP header field list item, as separated by a comma,
1210 * while stripping insignificant whitespace and lowercasing anything not in
1211 * a quoted string or comment. The return value is a new string containing
1212 * the converted list item (or NULL if none) and the address pointed to by
1213 * field is shifted to the next non-comma, non-whitespace.
1215 AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1217 const char *tok_start;
1218 const unsigned char *ptr;
1221 int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1223 /* Find the beginning and maximum length of the list item so that
1224 * we can allocate a buffer for the new string and reset the field.
1226 if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1229 token = apr_palloc(p, tok_len + 1);
1231 /* Scan the token again, but this time copy only the good bytes.
1232 * We skip extra whitespace and any whitespace around a '=', '/',
1233 * or ';' and lowercase normal characters not within a comment,
1234 * quoted-string or quoted-pair.
1236 for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1237 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1246 case '\\': in_qpair = 1;
1252 case '"' : if (!in_com)
1259 case '(' : if (!in_qstr)
1266 case ')' : if (in_com)
1272 case '\t': if (addspace)
1274 if (in_com || in_qstr)
1281 case ';' : if (!(in_com || in_qstr))
1285 default : if (addspace == 1)
1287 *pos++ = (in_com || in_qstr) ? *ptr
1288 : apr_tolower(*ptr);
1299 /* Find an item in canonical form (lowercase, no extra spaces) within
1300 * an HTTP field value list. Returns 1 if found, 0 if not found.
1301 * This would be much more efficient if we stored header fields as
1302 * an array of list items as they are received instead of a plain string.
1304 AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line,
1307 const unsigned char *pos;
1308 const unsigned char *ptr = (const unsigned char *)line;
1309 int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1314 do { /* loop for each item in line's list */
1316 /* Find first non-comma, non-whitespace byte */
1318 while (*ptr == ',' || apr_isspace(*ptr))
1322 good = 1; /* until proven otherwise for this item */
1324 break; /* no items left and nothing good found */
1326 /* We skip extra whitespace and any whitespace around a '=', '/',
1327 * or ';' and lowercase normal characters not within a comment,
1328 * quoted-string or quoted-pair.
1330 for (pos = (const unsigned char *)tok;
1331 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1337 good = (*pos++ == *ptr);
1341 case '\\': in_qpair = 1;
1343 good = good && (*pos++ == ' ');
1344 good = good && (*pos++ == *ptr);
1347 case '"' : if (!in_com)
1350 good = good && (*pos++ == ' ');
1351 good = good && (*pos++ == *ptr);
1354 case '(' : if (!in_qstr)
1357 good = good && (*pos++ == ' ');
1358 good = good && (*pos++ == *ptr);
1361 case ')' : if (in_com)
1363 good = good && (*pos++ == *ptr);
1367 case '\t': if (addspace || !good)
1369 if (in_com || in_qstr)
1370 good = (*pos++ == *ptr);
1376 case ';' : if (!(in_com || in_qstr))
1378 good = good && (*pos++ == *ptr);
1380 default : if (!good)
1383 good = (*pos++ == ' ');
1384 if (in_com || in_qstr)
1385 good = good && (*pos++ == *ptr);
1387 good = good && (*pos++ == apr_tolower(*ptr));
1394 good = 0; /* not good if only a prefix was matched */
1396 } while (*ptr && !good);
1402 /* Retrieve a token, spacing over it and returning a pointer to
1403 * the first non-white byte afterwards. Note that these tokens
1404 * are delimited by semis and commas; and can also be delimited
1405 * by whitespace at the caller's option.
1408 AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line,
1411 const char *ptr = *accept_line;
1412 const char *tok_start;
1416 /* Find first non-white byte */
1418 while (*ptr && apr_isspace(*ptr))
1423 /* find token end, skipping over quoted strings.
1424 * (comments are already gone).
1427 while (*ptr && (accept_white || !apr_isspace(*ptr))
1428 && *ptr != ';' && *ptr != ',') {
1435 tok_len = ptr - tok_start;
1436 token = apr_pstrndup(p, tok_start, tok_len);
1438 /* Advance accept_line pointer to the next non-white byte */
1440 while (*ptr && apr_isspace(*ptr))
1448 /* find http tokens, see the definition of token from RFC2068 */
1449 AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1451 const unsigned char *start_token;
1452 const unsigned char *s;
1457 s = (const unsigned char *)line;
1459 /* find start of token, skip all stop characters, note NUL
1460 * isn't a token stop, so we don't need to test for it
1462 while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1469 /* find end of the token */
1470 while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1473 if (!strncasecmp((const char *)start_token, (const char *)tok,
1484 AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line,
1487 int llen, tlen, lidx;
1492 llen = strlen(line);
1497 (lidx > 0 && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1500 return (strncasecmp(&line[lidx], tok, tlen) == 0);
1503 AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1507 const unsigned char *s;
1509 cmd = apr_palloc(p, 2 * strlen(str) + 1); /* Be safe */
1510 d = (unsigned char *)cmd;
1511 s = (const unsigned char *)str;
1514 #if defined(OS2) || defined(WIN32)
1516 * Newlines to Win32/OS2 CreateProcess() are ill advised.
1517 * Convert them to spaces since they are effectively white
1518 * space to most applications
1520 if (*s == '\r' || *s == '\n') {
1526 if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1536 static char x2c(const char *what)
1538 register char digit;
1540 #if !APR_CHARSET_EBCDIC
1541 digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10
1544 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10
1546 #else /*APR_CHARSET_EBCDIC*/
1553 digit = apr_xlate_conv_byte(ap_hdrs_from_ascii,
1554 0xFF & strtol(xstr, NULL, 16));
1555 #endif /*APR_CHARSET_EBCDIC*/
1561 * Returns 0 on success, non-zero on error
1563 * bad % escape returns HTTP_BAD_REQUEST
1565 * decoding %00 -> \0 (the null character)
1566 * decoding %2f -> / (a special character)
1567 * returns HTTP_NOT_FOUND
1569 AP_DECLARE(int) ap_unescape_url(char *url)
1571 register int badesc, badpath;
1576 /* Initial scan for first '%'. Don't bother writing values before
1578 y = strchr(url, '%');
1582 for (x = y; *y; ++x, ++y) {
1586 if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1593 if (IS_SLASH(*x) || *x == '\0')
1600 return HTTP_BAD_REQUEST;
1602 return HTTP_NOT_FOUND;
1607 AP_DECLARE(int) ap_unescape_url_keep2f(char *url)
1609 register int badesc, badpath;
1614 /* Initial scan for first '%'. Don't bother writing values before
1616 y = strchr(url, '%');
1620 for (x = y; *y; ++x, ++y) {
1625 if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1631 decoded = x2c(y + 1);
1632 if (decoded == '\0') {
1644 return HTTP_BAD_REQUEST;
1647 return HTTP_NOT_FOUND;
1654 AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
1655 apr_port_t port, const request_rec *r)
1657 if (ap_is_default_port(port, r)) {
1658 return apr_pstrdup(p, hostname);
1661 return apr_psprintf(p, "%s:%u", hostname, port);
1665 /* c2x takes an unsigned, and expects the caller has guaranteed that
1666 * 0 <= what < 256... which usually means that you have to cast to
1667 * unsigned char first, because (unsigned)(char)(x) first goes through
1668 * signed extension to an int before the unsigned cast.
1670 * The reason for this assumption is to assist gcc code generation --
1671 * the unsigned char -> unsigned extension is already done earlier in
1672 * both uses of this code, so there's no need to waste time doing it
1675 static const char c2x_table[] = "0123456789abcdef";
1677 static APR_INLINE unsigned char *c2x(unsigned what, unsigned char *where)
1679 #if APR_CHARSET_EBCDIC
1680 what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
1681 #endif /*APR_CHARSET_EBCDIC*/
1683 *where++ = c2x_table[what >> 4];
1684 *where++ = c2x_table[what & 0xf];
1689 * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1690 * routine is (should be) OS independent.
1692 * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1693 * cases if a ':' occurs before the first '/' in the URL, the URL should be
1694 * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1695 * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1696 * efficiency reasons, we don't use escape_path_segment(), which is provided for
1697 * reference. Again, RFC 1808 is where this stuff is defined.
1699 * If partial is set, os_escape_path() assumes that the path will be appended to
1700 * something with a '/' in it (and thus does not prefix "./").
1703 AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
1705 char *copy = apr_palloc(p, 3 * strlen(segment) + 1);
1706 const unsigned char *s = (const unsigned char *)segment;
1707 unsigned char *d = (unsigned char *)copy;
1711 if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1723 AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
1725 char *copy = apr_palloc(p, 3 * strlen(path) + 3);
1726 const unsigned char *s = (const unsigned char *)path;
1727 unsigned char *d = (unsigned char *)copy;
1731 const char *colon = ap_strchr_c(path, ':');
1732 const char *slash = ap_strchr_c(path, '/');
1734 if (colon && (!slash || colon < slash)) {
1740 if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1752 /* ap_escape_uri is now a macro for os_escape_path */
1754 AP_DECLARE(char *) ap_escape_html(apr_pool_t *p, const char *s)
1759 /* first, count the number of extra characters */
1760 for (i = 0, j = 0; s[i] != '\0'; i++)
1761 if (s[i] == '<' || s[i] == '>')
1763 else if (s[i] == '&')
1765 else if (s[i] == '"')
1769 return apr_pstrmemdup(p, s, i);
1771 x = apr_palloc(p, i + j + 1);
1772 for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1774 memcpy(&x[j], "<", 4);
1777 else if (s[i] == '>') {
1778 memcpy(&x[j], ">", 4);
1781 else if (s[i] == '&') {
1782 memcpy(&x[j], "&", 5);
1785 else if (s[i] == '"') {
1786 memcpy(&x[j], """, 6);
1796 AP_DECLARE(char *) ap_escape_logitem(apr_pool_t *p, const char *str)
1800 const unsigned char *s;
1806 ret = apr_palloc(p, 4 * strlen(str) + 1); /* Be safe */
1807 d = (unsigned char *)ret;
1808 s = (const unsigned char *)str;
1811 if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
1848 AP_DECLARE(apr_size_t) ap_escape_errorlog_item(char *dest, const char *source,
1851 unsigned char *d, *ep;
1852 const unsigned char *s;
1854 if (!source || !buflen) { /* be safe */
1858 d = (unsigned char *)dest;
1859 s = (const unsigned char *)source;
1860 ep = d + buflen - 1;
1862 for (; d < ep && *s; ++s) {
1864 if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
1890 case '"': /* no need for this in error log */
1895 ep = --d; /* break the for loop as well */
1909 return (d - (unsigned char *)dest);
1912 AP_DECLARE(int) ap_is_directory(apr_pool_t *p, const char *path)
1916 if (apr_stat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
1917 return 0; /* in error condition, just return no */
1919 return (finfo.filetype == APR_DIR);
1922 AP_DECLARE(int) ap_is_rdirectory(apr_pool_t *p, const char *path)
1926 if (apr_lstat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
1927 return 0; /* in error condition, just return no */
1929 return (finfo.filetype == APR_DIR);
1932 AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
1935 apr_size_t len1, len2;
1938 len1 = strlen(src1);
1939 len2 = strlen(src2);
1940 /* allocate +3 for '/' delimiter, trailing NULL and overallocate
1941 * one extra byte to allow the caller to add a trailing '/'
1943 path = (char *)apr_palloc(a, len1 + len2 + 3);
1946 memcpy(path + 1, src2, len2 + 1);
1950 memcpy(path, src1, len1);
1952 if (next[-1] != '/') {
1955 memcpy(next, src2, len2 + 1);
1961 * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
1963 AP_DECLARE(int) ap_is_url(const char *u)
1967 for (x = 0; u[x] != ':'; x++) {
1969 ((!apr_isalpha(u[x])) && (!apr_isdigit(u[x])) &&
1970 (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
1975 return (x ? 1 : 0); /* If the first character is ':', it's broken, too */
1978 AP_DECLARE(int) ap_ind(const char *s, char c)
1980 const char *p = ap_strchr_c(s, c);
1987 AP_DECLARE(int) ap_rind(const char *s, char c)
1989 const char *p = ap_strrchr_c(s, c);
1996 AP_DECLARE(void) ap_str_tolower(char *str)
1999 *str = apr_tolower(*str);
2004 static char *find_fqdn(apr_pool_t *a, struct hostent *p)
2008 if (!strchr(p->h_name, '.')) {
2010 for (x = 0; p->h_aliases[x]; ++x) {
2011 if (strchr(p->h_aliases[x], '.') &&
2012 (!strncasecmp(p->h_aliases[x], p->h_name,
2013 strlen(p->h_name))))
2014 return apr_pstrdup(a, p->h_aliases[x]);
2019 return apr_pstrdup(a, (void *) p->h_name);
2022 char *ap_get_local_host(apr_pool_t *a)
2024 #ifndef MAXHOSTNAMELEN
2025 #define MAXHOSTNAMELEN 256
2027 char str[MAXHOSTNAMELEN + 1];
2028 char *server_hostname = NULL;
2032 if (gethostname(str, sizeof(str) - 1) == 0)
2034 if (gethostname(str, sizeof(str) - 1) != 0)
2037 ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a,
2038 "%s: gethostname() failed to determine ServerName",
2043 str[sizeof(str) - 1] = '\0';
2044 /* TODO: Screaming for APR-ization */
2045 if ((!(p = gethostbyname(str)))
2046 || (!(server_hostname = find_fqdn(a, p)))) {
2047 /* Recovery - return the default servername by IP: */
2048 if (p && p->h_addr_list[0]) {
2049 apr_snprintf(str, sizeof(str), "%pA", p->h_addr_list[0]);
2050 server_hostname = apr_pstrdup(a, str);
2051 /* We will drop through to report the IP-named server */
2055 /* Since we found a fdqn, return it with no logged message. */
2056 return server_hostname;
2060 if (!server_hostname)
2061 server_hostname = apr_pstrdup(a, "127.0.0.1");
2063 ap_log_perror(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0, a,
2064 "%s: Could not determine the server's fully qualified "
2065 "domain name, using %s for ServerName",
2066 ap_server_argv0, server_hostname);
2068 return server_hostname;
2071 /* simple 'pool' alloc()ing glue to apr_base64.c
2073 AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
2078 decoded = (char *) apr_palloc(p, 1 + apr_base64_decode_len(bufcoded));
2079 l = apr_base64_decode(decoded, bufcoded);
2080 decoded[l] = '\0'; /* make binary sequence into string */
2085 AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string)
2088 int l = strlen(string);
2090 encoded = (char *) apr_palloc(p, 1 + apr_base64_encode_len(l));
2091 l = apr_base64_encode(encoded, string, l);
2092 encoded[l] = '\0'; /* make binary sequence into string */
2097 /* we want to downcase the type/subtype for comparison purposes
2098 * but nothing else because ;parameter=foo values are case sensitive.
2099 * XXX: in truth we want to downcase parameter names... but really,
2100 * apache has never handled parameters and such correctly. You
2101 * also need to compress spaces and such to be able to compare
2104 AP_DECLARE(void) ap_content_type_tolower(char *str)
2108 semi = strchr(str, ';');
2113 *str = apr_tolower(*str);
2122 * Given a string, replace any bare " with \" .
2124 AP_DECLARE(char *) ap_escape_quotes(apr_pool_t *p, const char *instring)
2127 const char *inchr = instring;
2128 char *outchr, *outstring;
2131 * Look through the input string, jogging the length of the output
2132 * string up by an extra byte each time we find an unescaped ".
2134 while (*inchr != '\0') {
2136 if (*inchr == '"') {
2140 * If we find a slosh, and it's not the last byte in the string,
2141 * it's escaping something - advance past both bytes.
2143 if ((*inchr == '\\') && (inchr[1] != '\0')) {
2149 outstring = apr_palloc(p, newlen + 1);
2153 * Now copy the input string to the output string, inserting a slosh
2154 * in front of every " that doesn't already have one.
2156 while (*inchr != '\0') {
2157 if ((*inchr == '\\') && (inchr[1] != '\0')) {
2158 *outchr++ = *inchr++;
2159 *outchr++ = *inchr++;
2161 if (*inchr == '"') {
2164 if (*inchr != '\0') {
2165 *outchr++ = *inchr++;