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"
33 #include "apr_md5.h" /* for apr_password_validate */
35 #define APR_WANT_STDIO
36 #define APR_WANT_STRFUNC
42 #if APR_HAVE_PROCESS_H
43 #include <process.h> /* for getpid() on Win32 */
46 #include <netdb.h> /* for gethostbyname() */
49 #include "ap_config.h"
50 #include "apr_base64.h"
52 #include "http_main.h"
54 #include "http_protocol.h"
55 #include "http_config.h"
56 #include "http_core.h"
57 #include "util_ebcdic.h"
58 #include "util_varbuf.h"
66 #ifdef HAVE_SYS_LOADAVG_H
67 #include <sys/loadavg.h>
72 /* A bunch of functions in util.c scan strings looking for certain characters.
73 * To make that more efficient we encode a lookup table. The test_char_table
74 * is generated automatically by gen_test_char.c.
76 #include "test_char.h"
78 /* we assume the folks using this ensure 0 <= c < 256... which means
79 * you need a cast to (unsigned char) first, you can't just plug a
80 * char in here and get it to work, because if char is signed then it
81 * will first be sign extended.
83 #define TEST_CHAR(c, f) (test_char_table[(unsigned)(c)] & (f))
85 /* Win32/NetWare/OS2 need to check for both forward and back slashes
86 * in ap_getparents() and ap_escape_url.
88 #ifdef CASE_BLIND_FILESYSTEM
89 #define IS_SLASH(s) ((s == '/') || (s == '\\'))
92 #define IS_SLASH(s) (s == '/')
96 /* we know core's module_index is 0 */
97 #undef APLOG_MODULE_INDEX
98 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
102 * Examine a field value (such as a media-/content-type) string and return
103 * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
105 AP_DECLARE(char *) ap_field_noparam(apr_pool_t *p, const char *intype)
109 if (intype == NULL) return NULL;
111 semi = ap_strchr_c(intype, ';');
113 return apr_pstrdup(p, intype);
116 while ((semi > intype) && apr_isspace(semi[-1])) {
119 return apr_pstrndup(p, intype, semi - intype);
123 AP_DECLARE(char *) ap_ht_time(apr_pool_t *p, apr_time_t t, const char *fmt,
127 char ts[MAX_STRING_LEN];
128 char tf[MAX_STRING_LEN];
135 apr_time_exp_gmt(&xt, t);
136 /* Convert %Z to "GMT" and %z to "+0000";
137 * on hosts that do not have a time zone string in struct tm,
138 * strftime must assume its argument is local time.
140 for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
142 if (*f != '%') continue;
153 case 'z': /* common extension */
167 apr_time_exp_lt(&xt, t);
170 /* check return code? */
171 apr_strftime(ts, &retcode, MAX_STRING_LEN, fmt, &xt);
172 ts[MAX_STRING_LEN - 1] = '\0';
173 return apr_pstrdup(p, ts);
176 /* Roy owes Rob beer. */
177 /* Rob owes Roy dinner. */
179 /* These legacy comments would make a lot more sense if Roy hadn't
180 * replaced the old later_than() routine with util_date.c.
182 * Well, okay, they still wouldn't make any sense.
185 /* Match = 0, NoMatch = 1, Abort = -1
186 * Based loosely on sections of wildmat.c by Rich Salz
187 * Hmmm... shouldn't this really go component by component?
189 AP_DECLARE(int) ap_strcmp_match(const char *str, const char *expected)
193 for (x = 0, y = 0; expected[y]; ++y, ++x) {
194 if ((!str[x]) && (expected[y] != '*'))
196 if (expected[y] == '*') {
197 while (expected[++y] == '*');
202 if ((ret = ap_strcmp_match(&str[x++], &expected[y])) != 1)
207 else if ((expected[y] != '?') && (str[x] != expected[y]))
210 return (str[x] != '\0');
213 AP_DECLARE(int) ap_strcasecmp_match(const char *str, const char *expected)
217 for (x = 0, y = 0; expected[y]; ++y, ++x) {
218 if (!str[x] && expected[y] != '*')
220 if (expected[y] == '*') {
221 while (expected[++y] == '*');
226 if ((ret = ap_strcasecmp_match(&str[x++], &expected[y])) != 1)
231 else if (expected[y] != '?'
232 && apr_tolower(str[x]) != apr_tolower(expected[y]))
235 return (str[x] != '\0');
238 /* We actually compare the canonical root to this root, (but we don't
239 * waste time checking the case), since every use of this function in
240 * httpd-2.1 tests if the path is 'proper', meaning we've already passed
241 * it through apr_filepath_merge, or we haven't.
243 AP_DECLARE(int) ap_os_is_path_absolute(apr_pool_t *p, const char *dir)
246 const char *ourdir = dir;
247 if (apr_filepath_root(&newpath, &dir, 0, p) != APR_SUCCESS
248 || strncmp(newpath, ourdir, strlen(newpath)) != 0) {
254 AP_DECLARE(int) ap_is_matchexp(const char *str)
258 for (x = 0; str[x]; x++)
259 if ((str[x] == '*') || (str[x] == '?'))
265 * Here's a pool-based interface to the POSIX-esque ap_regcomp().
266 * Note that we return ap_regex_t instead of being passed one.
267 * The reason is that if you use an already-used ap_regex_t structure,
268 * the memory that you've already allocated gets forgotten, and
269 * regfree() doesn't clear it. So we don't allow it.
272 static apr_status_t regex_cleanup(void *preg)
274 ap_regfree((ap_regex_t *) preg);
278 AP_DECLARE(ap_regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
281 ap_regex_t *preg = apr_palloc(p, sizeof *preg);
282 int err = ap_regcomp(preg, pattern, cflags);
284 if (err == AP_REG_ESPACE)
289 apr_pool_cleanup_register(p, (void *) preg, regex_cleanup,
290 apr_pool_cleanup_null);
295 AP_DECLARE(void) ap_pregfree(apr_pool_t *p, ap_regex_t *reg)
298 apr_pool_cleanup_kill(p, (void *) reg, regex_cleanup);
302 * Similar to standard strstr() but we ignore case in this version.
303 * Based on the strstr() implementation further below.
305 AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
313 for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
317 /* found first character of s2, see if the rest matches */
320 for (++p1, ++p2; apr_tolower(*p1) == apr_tolower(*p2); ++p1, ++p2) {
322 /* both strings ended together */
327 /* second string ended, a match */
330 /* didn't find a match here, try starting at next character in s1 */
337 * Returns an offsetted pointer in bigstring immediately after
338 * prefix. Returns bigstring if bigstring doesn't start with
339 * prefix or if prefix is longer than bigstring while still matching.
340 * NOTE: pointer returned is relative to bigstring, so we
341 * can use standard pointer comparisons in the calling function
342 * (eg: test if ap_stripprefix(a,b) == a)
344 AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
353 while (*p1 && *prefix) {
354 if (*p1++ != *prefix++)
360 /* hit the end of bigstring! */
364 /* This function substitutes for $0-$9, filling in regular expression
365 * submatches. Pass it the same nmatch and pmatch arguments that you
366 * passed ap_regexec(). pmatch should not be greater than the maximum number
367 * of subexpressions - i.e. one more than the re_nsub member of ap_regex_t.
369 * nmatch must be <=AP_MAX_REG_MATCH (10).
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 if a vbuf is used.
375 * On errors, returns the orig string.
377 * Parts of this code are based on Henry Spencer's regsub(), from his
378 * AT&T V8 regexp package.
381 static apr_status_t regsub_core(apr_pool_t *p, char **result,
382 struct ap_varbuf *vb, const char *input,
383 const char *source, apr_size_t nmatch,
384 ap_regmatch_t pmatch[], apr_size_t maxlen)
386 const char *src = input;
392 AP_DEBUG_ASSERT((result && p && !vb) || (vb && !p && !result));
393 if (!source || nmatch>AP_MAX_REG_MATCH)
397 if (maxlen > 0 && len >= maxlen)
400 *result = apr_pstrmemdup(p, src, len);
404 ap_varbuf_strmemcat(vb, src, len);
409 /* First pass, find the size */
410 while ((c = *src++) != '\0') {
411 if (c == '$' && apr_isdigit(*src))
414 no = AP_MAX_REG_MATCH;
416 if (no >= AP_MAX_REG_MATCH) { /* Ordinary character. */
417 if (c == '\\' && *src)
421 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
422 if (APR_SIZE_MAX - len <= pmatch[no].rm_eo - pmatch[no].rm_so)
424 len += pmatch[no].rm_eo - pmatch[no].rm_so;
429 if (len >= maxlen && maxlen > 0)
433 *result = dst = apr_palloc(p, len + 1);
436 if (vb->strlen == AP_VARBUF_UNKNOWN)
437 vb->strlen = strlen(vb->buf);
438 ap_varbuf_grow(vb, vb->strlen + len);
439 dst = vb->buf + vb->strlen;
443 /* Now actually fill in the string */
447 while ((c = *src++) != '\0') {
448 if (c == '$' && apr_isdigit(*src))
451 no = AP_MAX_REG_MATCH;
453 if (no >= AP_MAX_REG_MATCH) { /* Ordinary character. */
454 if (c == '\\' && *src)
458 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
459 len = pmatch[no].rm_eo - pmatch[no].rm_so;
460 memcpy(dst, source + pmatch[no].rm_so, len);
470 #ifndef AP_PREGSUB_MAXLEN
471 #define AP_PREGSUB_MAXLEN (HUGE_STRING_LEN * 8)
473 AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input,
474 const char *source, apr_size_t nmatch,
475 ap_regmatch_t pmatch[])
478 apr_status_t rc = regsub_core(p, &result, NULL, input, source, nmatch,
479 pmatch, AP_PREGSUB_MAXLEN);
480 if (rc != APR_SUCCESS)
485 AP_DECLARE(apr_status_t) ap_pregsub_ex(apr_pool_t *p, char **result,
486 const char *input, const char *source,
487 apr_size_t nmatch, ap_regmatch_t pmatch[],
490 apr_status_t rc = regsub_core(p, result, NULL, input, source, nmatch,
492 if (rc != APR_SUCCESS)
498 * Parse .. so we don't compromise security
500 AP_DECLARE(void) ap_getparents(char *name)
505 /* Four paseses, as per RFC 1808 */
506 /* a) remove ./ path segments */
507 for (next = name; *next && (*next != '.'); next++) {
510 l = w = first_dot = next - name;
511 while (name[l] != '\0') {
512 if (name[l] == '.' && IS_SLASH(name[l + 1])
513 && (l == 0 || IS_SLASH(name[l - 1])))
516 name[w++] = name[l++];
519 /* b) remove trailing . path, segment */
520 if (w == 1 && name[0] == '.')
522 else if (w > 1 && name[w - 1] == '.' && IS_SLASH(name[w - 2]))
526 /* c) remove all xx/../ segments. (including leading ../ and /../) */
529 while (name[l] != '\0') {
530 if (name[l] == '.' && name[l + 1] == '.' && IS_SLASH(name[l + 2])
531 && (l == 0 || IS_SLASH(name[l - 1]))) {
532 register int m = l + 3, n;
536 while (l >= 0 && !IS_SLASH(name[l]))
543 while ((name[n] = name[m]))
550 /* d) remove trailing xx/.. segment. */
551 if (l == 2 && name[0] == '.' && name[1] == '.')
553 else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.'
554 && IS_SLASH(name[l - 3])) {
557 while (l >= 0 && !IS_SLASH(name[l]))
567 AP_DECLARE(void) ap_no2slash(char *name)
573 #ifdef HAVE_UNC_PATHS
574 /* Check for UNC names. Leave leading two slashes. */
575 if (s[0] == '/' && s[1] == '/')
580 if ((*d++ = *s) == '/') {
594 * copy at most n leading directories of s into d
595 * d should be at least as large as s plus 1 extra byte
597 * the return value is the ever useful pointer to the trailing \0 of d
599 * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments,
600 * so that if n == 0, "/" is returned in d with n == 1
601 * and s == "e:/test.html", "e:/" is returned in d
602 * *** See also directory_walk in modules/http/http_request.c
605 * /a/b, 0 ==> / (true for all platforms)
614 * c:/a/b 3 ==> c:/a/b
615 * c:/a/b 4 ==> c:/a/b
617 AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
626 if (*s == '\0' || (*s == '/' && (--n) == 0)) {
638 * return the parent directory name including trailing / of the file s
640 AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
642 const char *last_slash = ap_strrchr_c(s, '/');
646 if (last_slash == NULL) {
647 return apr_pstrdup(p, "");
649 l = (last_slash - s) + 1;
650 d = apr_pstrmemdup(p, s, l);
656 AP_DECLARE(int) ap_count_dirs(const char *path)
660 for (x = 0, n = 0; path[x]; x++)
666 AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
668 return ap_getword(atrans, (const char **) line, stop);
671 AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
673 const char *pos = *line;
677 while ((*pos != stop) && *pos) {
682 res = apr_pstrmemdup(atrans, *line, len);
685 while (*pos == stop) {
694 AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
696 return ap_getword_white(atrans, (const char **) line);
699 AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
701 const char *pos = *line;
705 while (!apr_isspace(*pos) && *pos) {
710 res = apr_pstrmemdup(atrans, *line, len);
712 while (apr_isspace(*pos)) {
721 AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line,
724 return ap_getword_nulls(atrans, (const char **) line, stop);
727 AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line,
730 const char *pos = ap_strchr_c(*line, stop);
734 apr_size_t len = strlen(*line);
735 res = apr_pstrmemdup(atrans, *line, len);
740 res = apr_pstrndup(atrans, *line, pos - *line);
749 /* Get a word, (new) config-file style --- quoted strings and backslashes
753 static char *substring_conf(apr_pool_t *p, const char *start, int len,
756 char *result = apr_palloc(p, len + 1);
760 for (i = 0; i < len; ++i) {
761 if (start[i] == '\\' && (start[i + 1] == '\\'
762 || (quote && start[i + 1] == quote)))
763 *resp++ = start[++i];
769 #if RESOLVE_ENV_PER_TOKEN
770 return (char *)ap_resolve_env(p,result);
776 AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
778 return ap_getword_conf(p, (const char **) line);
781 AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
783 const char *str = *line, *strend;
787 while (apr_isspace(*str))
795 if ((quote = *str) == '"' || quote == '\'') {
797 while (*strend && *strend != quote) {
798 if (*strend == '\\' && strend[1] &&
799 (strend[1] == quote || strend[1] == '\\')) {
806 res = substring_conf(p, str + 1, strend - str - 1, quote);
808 if (*strend == quote)
813 while (*strend && !apr_isspace(*strend))
816 res = substring_conf(p, str, strend - str, 0);
819 while (apr_isspace(*strend))
825 AP_DECLARE(int) ap_cfg_closefile(ap_configfile_t *cfp)
828 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(00551)
829 "Done with config file %s", cfp->name);
831 return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
834 /* we can't use apr_file_* directly because of linking issues on Windows */
835 static apr_status_t cfg_close(void *param)
837 return apr_file_close(param);
840 static apr_status_t cfg_getch(char *ch, void *param)
842 return apr_file_getc(ch, param);
845 static apr_status_t cfg_getstr(void *buf, apr_size_t bufsiz, void *param)
847 return apr_file_gets(buf, bufsiz, param);
850 /* Open a ap_configfile_t as FILE, return open ap_configfile_t struct pointer */
851 AP_DECLARE(apr_status_t) ap_pcfg_openfile(ap_configfile_t **ret_cfg,
852 apr_pool_t *p, const char *name)
854 ap_configfile_t *new_cfg;
855 apr_file_t *file = NULL;
863 ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00552)
864 "Internal error: pcfg_openfile() called with NULL filename");
868 status = apr_file_open(&file, name, APR_READ | APR_BUFFERED,
871 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(00553)
872 "Opening config file %s (%s)",
873 name, (status != APR_SUCCESS) ?
874 apr_strerror(status, buf, sizeof(buf)) : "successful");
876 if (status != APR_SUCCESS)
879 status = apr_file_info_get(&finfo, APR_FINFO_TYPE, file);
880 if (status != APR_SUCCESS)
883 if (finfo.filetype != APR_REG &&
884 #if defined(WIN32) || defined(OS2) || defined(NETWARE)
885 strcasecmp(apr_filepath_name_get(name), "nul") != 0) {
887 strcmp(name, "/dev/null") != 0) {
888 #endif /* WIN32 || OS2 */
889 ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00554)
890 "Access to file %s denied by server: not a regular file",
892 apr_file_close(file);
897 /* Some twisted character [no pun intended] at MS decided that a
898 * zero width joiner as the lead wide character would be ideal for
899 * describing Unicode text files. This was further convoluted to
900 * another MSism that the same character mapped into utf-8, EF BB BF
901 * would signify utf-8 text files.
903 * Since MS configuration files are all protecting utf-8 encoded
904 * Unicode path, file and resource names, we already have the correct
905 * WinNT encoding. But at least eat the stupid three bytes up front.
908 unsigned char buf[4];
910 status = apr_file_read(file, buf, &len);
911 if ((status != APR_SUCCESS) || (len < 3)
912 || memcmp(buf, "\xEF\xBB\xBF", 3) != 0) {
914 apr_file_seek(file, APR_SET, &zero);
919 new_cfg = apr_palloc(p, sizeof(*new_cfg));
920 new_cfg->param = file;
921 new_cfg->name = apr_pstrdup(p, name);
922 new_cfg->getch = cfg_getch;
923 new_cfg->getstr = cfg_getstr;
924 new_cfg->close = cfg_close;
925 new_cfg->line_number = 0;
931 /* Allocate a ap_configfile_t handle with user defined functions and params */
932 AP_DECLARE(ap_configfile_t *) ap_pcfg_open_custom(
933 apr_pool_t *p, const char *descr, void *param,
934 apr_status_t (*getc_func) (char *ch, void *param),
935 apr_status_t (*gets_func) (void *buf, apr_size_t bufsize, void *param),
936 apr_status_t (*close_func) (void *param))
938 ap_configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
939 new_cfg->param = param;
940 new_cfg->name = descr;
941 new_cfg->getch = getc_func;
942 new_cfg->getstr = gets_func;
943 new_cfg->close = close_func;
944 new_cfg->line_number = 0;
948 /* Read one character from a configfile_t */
949 AP_DECLARE(apr_status_t) ap_cfg_getc(char *ch, ap_configfile_t *cfp)
951 apr_status_t rc = cfp->getch(ch, cfp->param);
952 if (rc == APR_SUCCESS && *ch == LF)
957 AP_DECLARE(const char *) ap_pcfg_strerror(apr_pool_t *p, ap_configfile_t *cfp,
960 char buf[MAX_STRING_LEN];
961 if (rc == APR_SUCCESS)
963 return apr_psprintf(p, "Error reading %s at line %d: %s",
964 cfp->name, cfp->line_number,
965 rc == APR_ENOSPC ? "Line too long"
966 : apr_strerror(rc, buf, sizeof(buf)));
969 /* Read one line from open ap_configfile_t, strip LF, increase line number */
970 /* If custom handler does not define a getstr() function, read char by char */
971 static apr_status_t ap_cfg_getline_core(char *buf, apr_size_t bufsize,
972 ap_configfile_t *cfp)
975 /* If a "get string" function is defined, use it */
976 if (cfp->getstr != NULL) {
979 apr_size_t cbufsize = bufsize;
983 rc = cfp->getstr(cbuf, cbufsize, cfp->param);
993 if (rc != APR_SUCCESS) {
998 * check for line continuation,
999 * i.e. match [^\\]\\[\r]\n only
1003 if (cp > cbuf && cp[-1] == LF) {
1005 if (cp > cbuf && cp[-1] == CR)
1007 if (cp > cbuf && cp[-1] == '\\') {
1010 * line continuation requested -
1011 * then remove backslash and continue
1013 cbufsize -= (cp-cbuf);
1018 else if (cp - buf >= bufsize - 1) {
1024 /* No "get string" function defined; read character by character */
1028 /* too small, assume caller is crazy */
1035 rc = cfp->getch(&c, cfp->param);
1036 if (rc == APR_EOF) {
1042 if (rc != APR_SUCCESS)
1046 /* check for line continuation */
1047 if (i > 0 && buf[i-1] == '\\') {
1055 else if (i >= bufsize - 2) {
1066 static int cfg_trim_line(char *buf)
1070 * Leading and trailing white space is eliminated completely
1073 while (apr_isspace(*start))
1075 /* blast trailing whitespace */
1076 end = &start[strlen(start)];
1077 while (--end >= start && apr_isspace(*end))
1079 /* Zap leading whitespace by shifting */
1081 memmove(buf, start, end - start + 2);
1082 #ifdef DEBUG_CFG_LINES
1083 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL, APLOGNO(00555) "Read config: '%s'", buf);
1085 return end - start + 1;
1088 /* Read one line from open ap_configfile_t, strip LF, increase line number */
1089 /* If custom handler does not define a getstr() function, read char by char */
1090 AP_DECLARE(apr_status_t) ap_cfg_getline(char *buf, apr_size_t bufsize,
1091 ap_configfile_t *cfp)
1093 apr_status_t rc = ap_cfg_getline_core(buf, bufsize, cfp);
1094 if (rc == APR_SUCCESS)
1099 AP_DECLARE(apr_status_t) ap_varbuf_cfg_getline(struct ap_varbuf *vb,
1100 ap_configfile_t *cfp,
1108 if (vb->strlen == AP_VARBUF_UNKNOWN)
1109 vb->strlen = strlen(vb->buf);
1110 if (vb->avail - vb->strlen < 3) {
1111 new_len = vb->avail * 2;
1112 if (new_len > max_len)
1114 else if (new_len < 3)
1116 ap_varbuf_grow(vb, new_len);
1120 rc = ap_cfg_getline_core(vb->buf + vb->strlen, vb->avail - vb->strlen, cfp);
1121 if (rc == APR_ENOSPC || rc == APR_SUCCESS)
1122 vb->strlen += strlen(vb->buf + vb->strlen);
1123 if (rc != APR_ENOSPC)
1125 if (vb->avail >= max_len)
1127 new_len = vb->avail * 2;
1128 if (new_len > max_len)
1130 ap_varbuf_grow(vb, new_len);
1133 if (vb->strlen > max_len)
1135 if (rc == APR_SUCCESS)
1136 vb->strlen = cfg_trim_line(vb->buf);
1140 /* Size an HTTP header field list item, as separated by a comma.
1141 * The return value is a pointer to the beginning of the non-empty list item
1142 * within the original string (or NULL if there is none) and the address
1143 * of field is shifted to the next non-comma, non-whitespace character.
1144 * len is the length of the item excluding any beginning whitespace.
1146 AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1148 const unsigned char *ptr = (const unsigned char *)*field;
1149 const unsigned char *token;
1150 int in_qpair, in_qstr, in_com;
1152 /* Find first non-comma, non-whitespace byte */
1154 while (*ptr == ',' || apr_isspace(*ptr))
1159 /* Find the end of this item, skipping over dead bits */
1161 for (in_qpair = in_qstr = in_com = 0;
1162 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1170 case '\\': in_qpair = 1; /* quoted-pair */
1172 case '"' : if (!in_com) /* quoted string delim */
1175 case '(' : if (!in_qstr) /* comment (may nest) */
1178 case ')' : if (in_com) /* end comment */
1186 if ((*len = (ptr - token)) == 0) {
1187 *field = (const char *)ptr;
1191 /* Advance field pointer to the next non-comma, non-white byte */
1193 while (*ptr == ',' || apr_isspace(*ptr))
1196 *field = (const char *)ptr;
1197 return (const char *)token;
1200 /* Retrieve an HTTP header field list item, as separated by a comma,
1201 * while stripping insignificant whitespace and lowercasing anything not in
1202 * a quoted string or comment. The return value is a new string containing
1203 * the converted list item (or NULL if none) and the address pointed to by
1204 * field is shifted to the next non-comma, non-whitespace.
1206 AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1208 const char *tok_start;
1209 const unsigned char *ptr;
1212 int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1214 /* Find the beginning and maximum length of the list item so that
1215 * we can allocate a buffer for the new string and reset the field.
1217 if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1220 token = apr_palloc(p, tok_len + 1);
1222 /* Scan the token again, but this time copy only the good bytes.
1223 * We skip extra whitespace and any whitespace around a '=', '/',
1224 * or ';' and lowercase normal characters not within a comment,
1225 * quoted-string or quoted-pair.
1227 for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1228 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1237 case '\\': in_qpair = 1;
1243 case '"' : if (!in_com)
1250 case '(' : if (!in_qstr)
1257 case ')' : if (in_com)
1263 case '\t': if (addspace)
1265 if (in_com || in_qstr)
1272 case ';' : if (!(in_com || in_qstr))
1276 default : if (addspace == 1)
1278 *pos++ = (in_com || in_qstr) ? *ptr
1279 : apr_tolower(*ptr);
1290 typedef enum ap_etag_e {
1296 /* Find an item in canonical form (lowercase, no extra spaces) within
1297 * an HTTP field value list. Returns 1 if found, 0 if not found.
1298 * This would be much more efficient if we stored header fields as
1299 * an array of list items as they are received instead of a plain string.
1301 static int find_list_item(apr_pool_t *p, const char *line,
1302 const char *tok, ap_etag_e type)
1304 const unsigned char *pos;
1305 const unsigned char *ptr = (const unsigned char *)line;
1306 int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1308 if (!line || !tok) {
1311 if (type == AP_ETAG_STRONG && *tok != '\"') {
1314 if (type == AP_ETAG_WEAK) {
1315 if (*tok == 'W' && (*(tok+1)) == '/' && (*(tok+2)) == '\"') {
1318 else if (*tok != '\"') {
1323 do { /* loop for each item in line's list */
1325 /* Find first non-comma, non-whitespace byte */
1326 while (*ptr == ',' || apr_isspace(*ptr)) {
1330 /* Account for strong or weak Etags, depending on our search */
1331 if (type == AP_ETAG_STRONG && *ptr != '\"') {
1334 if (type == AP_ETAG_WEAK) {
1335 if (*ptr == 'W' && (*(ptr+1)) == '/' && (*(ptr+2)) == '\"') {
1338 else if (*ptr != '\"') {
1344 good = 1; /* until proven otherwise for this item */
1346 break; /* no items left and nothing good found */
1348 /* We skip extra whitespace and any whitespace around a '=', '/',
1349 * or ';' and lowercase normal characters not within a comment,
1350 * quoted-string or quoted-pair.
1352 for (pos = (const unsigned char *)tok;
1353 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1359 good = (*pos++ == *ptr);
1363 case '\\': in_qpair = 1;
1365 good = good && (*pos++ == ' ');
1366 good = good && (*pos++ == *ptr);
1369 case '"' : if (!in_com)
1372 good = good && (*pos++ == ' ');
1373 good = good && (*pos++ == *ptr);
1376 case '(' : if (!in_qstr)
1379 good = good && (*pos++ == ' ');
1380 good = good && (*pos++ == *ptr);
1383 case ')' : if (in_com)
1385 good = good && (*pos++ == *ptr);
1389 case '\t': if (addspace || !good)
1391 if (in_com || in_qstr)
1392 good = (*pos++ == *ptr);
1398 case ';' : if (!(in_com || in_qstr))
1400 good = good && (*pos++ == *ptr);
1402 default : if (!good)
1405 good = (*pos++ == ' ');
1406 if (in_com || in_qstr)
1407 good = good && (*pos++ == *ptr);
1410 && (apr_tolower(*pos++) == apr_tolower(*ptr));
1417 good = 0; /* not good if only a prefix was matched */
1419 } while (*ptr && !good);
1424 /* Find an item in canonical form (lowercase, no extra spaces) within
1425 * an HTTP field value list. Returns 1 if found, 0 if not found.
1426 * This would be much more efficient if we stored header fields as
1427 * an array of list items as they are received instead of a plain string.
1429 AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line,
1432 return find_list_item(p, line, tok, AP_ETAG_NONE);
1435 /* Find a strong Etag in canonical form (lowercase, no extra spaces) within
1436 * an HTTP field value list. Returns 1 if found, 0 if not found.
1438 AP_DECLARE(int) ap_find_etag_strong(apr_pool_t *p, const char *line,
1441 return find_list_item(p, line, tok, AP_ETAG_STRONG);
1444 /* Find a weak ETag in canonical form (lowercase, no extra spaces) within
1445 * an HTTP field value list. Returns 1 if found, 0 if not found.
1447 AP_DECLARE(int) ap_find_etag_weak(apr_pool_t *p, const char *line,
1450 return find_list_item(p, line, tok, AP_ETAG_WEAK);
1453 /* Retrieve a token, spacing over it and returning a pointer to
1454 * the first non-white byte afterwards. Note that these tokens
1455 * are delimited by semis and commas; and can also be delimited
1456 * by whitespace at the caller's option.
1459 AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line,
1462 const char *ptr = *accept_line;
1463 const char *tok_start;
1467 /* Find first non-white byte */
1469 while (apr_isspace(*ptr))
1474 /* find token end, skipping over quoted strings.
1475 * (comments are already gone).
1478 while (*ptr && (accept_white || !apr_isspace(*ptr))
1479 && *ptr != ';' && *ptr != ',') {
1486 tok_len = ptr - tok_start;
1487 token = apr_pstrndup(p, tok_start, tok_len);
1489 /* Advance accept_line pointer to the next non-white byte */
1491 while (apr_isspace(*ptr))
1499 /* find http tokens, see the definition of token from RFC2068 */
1500 AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1502 const unsigned char *start_token;
1503 const unsigned char *s;
1508 s = (const unsigned char *)line;
1510 /* find start of token, skip all stop characters, note NUL
1511 * isn't a token stop, so we don't need to test for it
1513 while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1520 /* find end of the token */
1521 while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1524 if (!strncasecmp((const char *)start_token, (const char *)tok,
1535 AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line,
1538 int llen, tlen, lidx;
1543 llen = strlen(line);
1548 (lidx > 0 && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1551 return (strncasecmp(&line[lidx], tok, tlen) == 0);
1554 AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1558 const unsigned char *s;
1560 cmd = apr_palloc(p, 2 * strlen(str) + 1); /* Be safe */
1561 d = (unsigned char *)cmd;
1562 s = (const unsigned char *)str;
1565 #if defined(OS2) || defined(WIN32)
1567 * Newlines to Win32/OS2 CreateProcess() are ill advised.
1568 * Convert them to spaces since they are effectively white
1569 * space to most applications
1571 if (*s == '\r' || *s == '\n') {
1577 if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1587 static char x2c(const char *what)
1589 register char digit;
1591 #if !APR_CHARSET_EBCDIC
1592 digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10
1595 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10
1597 #else /*APR_CHARSET_EBCDIC*/
1604 digit = apr_xlate_conv_byte(ap_hdrs_from_ascii,
1605 0xFF & strtol(xstr, NULL, 16));
1606 #endif /*APR_CHARSET_EBCDIC*/
1611 * Unescapes a URL, leaving reserved characters intact.
1612 * Returns 0 on success, non-zero on error
1614 * bad % escape returns HTTP_BAD_REQUEST
1616 * decoding %00 or a forbidden character returns HTTP_NOT_FOUND
1619 static int unescape_url(char *url, const char *forbid, const char *reserved)
1621 register int badesc, badpath;
1626 /* Initial scan for first '%'. Don't bother writing values before
1628 y = strchr(url, '%');
1632 for (x = y; *y; ++x, ++y) {
1637 if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1643 decoded = x2c(y + 1);
1644 if ((decoded == '\0')
1645 || (forbid && ap_strchr_c(forbid, decoded))) {
1650 else if (reserved && ap_strchr_c(reserved, decoded)) {
1664 return HTTP_BAD_REQUEST;
1667 return HTTP_NOT_FOUND;
1673 AP_DECLARE(int) ap_unescape_url(char *url)
1676 return unescape_url(url, SLASHES, NULL);
1678 AP_DECLARE(int) ap_unescape_url_keep2f(char *url, int decode_slashes)
1680 /* AllowEncodedSlashes (corrected) */
1681 if (decode_slashes) {
1682 /* no chars reserved */
1683 return unescape_url(url, NULL, NULL);
1685 /* reserve (do not decode) encoded slashes */
1686 return unescape_url(url, NULL, SLASHES);
1690 /* IFDEF these out until they've been thought through.
1691 * Just a germ of an API extension for now
1693 AP_DECLARE(int) ap_unescape_url_proxy(char *url)
1695 /* leave RFC1738 reserved characters intact, * so proxied URLs
1696 * don't get mangled. Where does that leave encoded '&' ?
1698 return unescape_url(url, NULL, "/;?");
1700 AP_DECLARE(int) ap_unescape_url_reserved(char *url, const char *reserved)
1702 return unescape_url(url, NULL, reserved);
1706 AP_DECLARE(int) ap_unescape_urlencoded(char *query)
1710 /* replace plus with a space */
1712 for (slider = query; *slider; slider++) {
1713 if (*slider == '+') {
1719 /* unescape everything else */
1720 return unescape_url(query, NULL, NULL);
1723 AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
1724 apr_port_t port, const request_rec *r)
1726 if (ap_is_default_port(port, r)) {
1727 return apr_pstrdup(p, hostname);
1730 return apr_psprintf(p, "%s:%u", hostname, port);
1734 AP_DECLARE(int) ap_unescape_all(char *url)
1736 return unescape_url(url, NULL, NULL);
1739 /* c2x takes an unsigned, and expects the caller has guaranteed that
1740 * 0 <= what < 256... which usually means that you have to cast to
1741 * unsigned char first, because (unsigned)(char)(x) first goes through
1742 * signed extension to an int before the unsigned cast.
1744 * The reason for this assumption is to assist gcc code generation --
1745 * the unsigned char -> unsigned extension is already done earlier in
1746 * both uses of this code, so there's no need to waste time doing it
1749 static const char c2x_table[] = "0123456789abcdef";
1751 static APR_INLINE unsigned char *c2x(unsigned what, unsigned char prefix,
1752 unsigned char *where)
1754 #if APR_CHARSET_EBCDIC
1755 what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
1756 #endif /*APR_CHARSET_EBCDIC*/
1758 *where++ = c2x_table[what >> 4];
1759 *where++ = c2x_table[what & 0xf];
1764 * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1765 * routine is (should be) OS independent.
1767 * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1768 * cases if a ':' occurs before the first '/' in the URL, the URL should be
1769 * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1770 * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1771 * efficiency reasons, we don't use escape_path_segment(), which is provided for
1772 * reference. Again, RFC 1808 is where this stuff is defined.
1774 * If partial is set, os_escape_path() assumes that the path will be appended to
1775 * something with a '/' in it (and thus does not prefix "./").
1778 AP_DECLARE(char *) ap_escape_path_segment_buffer(char *copy, const char *segment)
1780 const unsigned char *s = (const unsigned char *)segment;
1781 unsigned char *d = (unsigned char *)copy;
1785 if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1797 AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
1799 return ap_escape_path_segment_buffer(apr_palloc(p, 3 * strlen(segment) + 1), segment);
1802 AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
1804 char *copy = apr_palloc(p, 3 * strlen(path) + 3);
1805 const unsigned char *s = (const unsigned char *)path;
1806 unsigned char *d = (unsigned char *)copy;
1810 const char *colon = ap_strchr_c(path, ':');
1811 const char *slash = ap_strchr_c(path, '/');
1813 if (colon && (!slash || colon < slash)) {
1819 if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1831 AP_DECLARE(char *) ap_escape_urlencoded_buffer(char *copy, const char *buffer)
1833 const unsigned char *s = (const unsigned char *)buffer;
1834 unsigned char *d = (unsigned char *)copy;
1838 if (TEST_CHAR(c, T_ESCAPE_URLENCODED)) {
1841 else if (c == ' ') {
1853 AP_DECLARE(char *) ap_escape_urlencoded(apr_pool_t *p, const char *buffer)
1855 return ap_escape_urlencoded_buffer(apr_palloc(p, 3 * strlen(buffer) + 1), buffer);
1858 /* ap_escape_uri is now a macro for os_escape_path */
1860 AP_DECLARE(char *) ap_escape_html2(apr_pool_t *p, const char *s, int toasc)
1865 /* first, count the number of extra characters */
1866 for (i = 0, j = 0; s[i] != '\0'; i++)
1867 if (s[i] == '<' || s[i] == '>')
1869 else if (s[i] == '&')
1871 else if (s[i] == '"')
1873 else if (toasc && !apr_isascii(s[i]))
1877 return apr_pstrmemdup(p, s, i);
1879 x = apr_palloc(p, i + j + 1);
1880 for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1882 memcpy(&x[j], "<", 4);
1885 else if (s[i] == '>') {
1886 memcpy(&x[j], ">", 4);
1889 else if (s[i] == '&') {
1890 memcpy(&x[j], "&", 5);
1893 else if (s[i] == '"') {
1894 memcpy(&x[j], """, 6);
1897 else if (toasc && !apr_isascii(s[i])) {
1898 char *esc = apr_psprintf(p, "&#%3.3d;", (unsigned char)s[i]);
1899 memcpy(&x[j], esc, 6);
1908 AP_DECLARE(char *) ap_escape_logitem(apr_pool_t *p, const char *str)
1912 const unsigned char *s;
1913 apr_size_t length, escapes = 0;
1919 /* Compute how many characters need to be escaped */
1920 s = (const unsigned char *)str;
1922 if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
1927 /* Compute the length of the input string, including NULL */
1928 length = s - (const unsigned char *)str + 1;
1930 /* Fast path: nothing to escape */
1932 return apr_pmemdup(p, str, length);
1935 /* Each escaped character needs up to 3 extra bytes (0 --> \x00) */
1936 ret = apr_palloc(p, length + 3 * escapes);
1937 d = (unsigned char *)ret;
1938 s = (const unsigned char *)str;
1940 if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
1976 AP_DECLARE(apr_size_t) ap_escape_errorlog_item(char *dest, const char *source,
1979 unsigned char *d, *ep;
1980 const unsigned char *s;
1982 if (!source || !buflen) { /* be safe */
1986 d = (unsigned char *)dest;
1987 s = (const unsigned char *)source;
1988 ep = d + buflen - 1;
1990 for (; d < ep && *s; ++s) {
1992 if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
2018 case '"': /* no need for this in error log */
2023 ep = --d; /* break the for loop as well */
2036 return (d - (unsigned char *)dest);
2039 AP_DECLARE(void) ap_bin2hex(const void *src, apr_size_t srclen, char *dest)
2041 const unsigned char *in = src;
2044 for (i = 0; i < srclen; i++) {
2045 *dest++ = c2x_table[in[i] >> 4];
2046 *dest++ = c2x_table[in[i] & 0xf];
2051 AP_DECLARE(int) ap_has_cntrl(const char *str)
2054 if (apr_iscntrl(*str))
2061 AP_DECLARE(int) ap_is_directory(apr_pool_t *p, const char *path)
2065 if (apr_stat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
2066 return 0; /* in error condition, just return no */
2068 return (finfo.filetype == APR_DIR);
2071 AP_DECLARE(int) ap_is_rdirectory(apr_pool_t *p, const char *path)
2075 if (apr_stat(&finfo, path, APR_FINFO_LINK | APR_FINFO_TYPE, p) != APR_SUCCESS)
2076 return 0; /* in error condition, just return no */
2078 return (finfo.filetype == APR_DIR);
2081 AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
2084 apr_size_t len1, len2;
2087 len1 = strlen(src1);
2088 len2 = strlen(src2);
2089 /* allocate +3 for '/' delimiter, trailing NULL and overallocate
2090 * one extra byte to allow the caller to add a trailing '/'
2092 path = (char *)apr_palloc(a, len1 + len2 + 3);
2095 memcpy(path + 1, src2, len2 + 1);
2099 memcpy(path, src1, len1);
2101 if (next[-1] != '/') {
2104 memcpy(next, src2, len2 + 1);
2110 * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
2112 AP_DECLARE(int) ap_is_url(const char *u)
2116 for (x = 0; u[x] != ':'; x++) {
2118 ((!apr_isalpha(u[x])) && (!apr_isdigit(u[x])) &&
2119 (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
2124 return (x ? 1 : 0); /* If the first character is ':', it's broken, too */
2127 AP_DECLARE(int) ap_ind(const char *s, char c)
2129 const char *p = ap_strchr_c(s, c);
2136 AP_DECLARE(int) ap_rind(const char *s, char c)
2138 const char *p = ap_strrchr_c(s, c);
2145 AP_DECLARE(void) ap_str_tolower(char *str)
2148 *str = apr_tolower(*str);
2153 AP_DECLARE(void) ap_str_toupper(char *str)
2156 *str = apr_toupper(*str);
2162 * We must return a FQDN
2164 char *ap_get_local_host(apr_pool_t *a)
2166 #ifndef MAXHOSTNAMELEN
2167 #define MAXHOSTNAMELEN 256
2169 char str[MAXHOSTNAMELEN + 1];
2170 char *server_hostname = NULL;
2171 apr_sockaddr_t *sockaddr;
2174 if (apr_gethostname(str, sizeof(str) - 1, a) != APR_SUCCESS) {
2175 ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a, APLOGNO(00556)
2176 "%s: apr_gethostname() failed to determine ServerName",
2179 str[sizeof(str) - 1] = '\0';
2180 if (apr_sockaddr_info_get(&sockaddr, str, APR_UNSPEC, 0, 0, a) == APR_SUCCESS) {
2181 if ( (apr_getnameinfo(&hostname, sockaddr, 0) == APR_SUCCESS) &&
2182 (ap_strchr_c(hostname, '.')) ) {
2183 server_hostname = apr_pstrdup(a, hostname);
2184 return server_hostname;
2185 } else if (ap_strchr_c(str, '.')) {
2186 server_hostname = apr_pstrdup(a, str);
2188 apr_sockaddr_ip_get(&hostname, sockaddr);
2189 server_hostname = apr_pstrdup(a, hostname);
2192 ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a, APLOGNO(00557)
2193 "%s: apr_sockaddr_info_get() failed for %s",
2194 ap_server_argv0, str);
2198 if (!server_hostname)
2199 server_hostname = apr_pstrdup(a, "127.0.0.1");
2201 ap_log_perror(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0, a, APLOGNO(00558)
2202 "%s: Could not reliably determine the server's fully qualified "
2203 "domain name, using %s. Set the 'ServerName' directive globally "
2204 "to suppress this message",
2205 ap_server_argv0, server_hostname);
2207 return server_hostname;
2210 /* simple 'pool' alloc()ing glue to apr_base64.c
2212 AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
2217 decoded = (char *) apr_palloc(p, 1 + apr_base64_decode_len(bufcoded));
2218 l = apr_base64_decode(decoded, bufcoded);
2219 decoded[l] = '\0'; /* make binary sequence into string */
2224 AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string)
2227 int l = strlen(string);
2229 encoded = (char *) apr_palloc(p, 1 + apr_base64_encode_len(l));
2230 l = apr_base64_encode(encoded, string, l);
2231 encoded[l] = '\0'; /* make binary sequence into string */
2236 /* we want to downcase the type/subtype for comparison purposes
2237 * but nothing else because ;parameter=foo values are case sensitive.
2238 * XXX: in truth we want to downcase parameter names... but really,
2239 * apache has never handled parameters and such correctly. You
2240 * also need to compress spaces and such to be able to compare
2243 AP_DECLARE(void) ap_content_type_tolower(char *str)
2247 semi = strchr(str, ';');
2252 ap_str_tolower(str);
2260 * Given a string, replace any bare " with \" .
2262 AP_DECLARE(char *) ap_escape_quotes(apr_pool_t *p, const char *instring)
2265 const char *inchr = instring;
2266 char *outchr, *outstring;
2269 * Look through the input string, jogging the length of the output
2270 * string up by an extra byte each time we find an unescaped ".
2272 while (*inchr != '\0') {
2274 if (*inchr == '"') {
2278 * If we find a slosh, and it's not the last byte in the string,
2279 * it's escaping something - advance past both bytes.
2281 if ((*inchr == '\\') && (inchr[1] != '\0')) {
2287 outstring = apr_palloc(p, newlen + 1);
2291 * Now copy the input string to the output string, inserting a slosh
2292 * in front of every " that doesn't already have one.
2294 while (*inchr != '\0') {
2295 if ((*inchr == '\\') && (inchr[1] != '\0')) {
2296 *outchr++ = *inchr++;
2297 *outchr++ = *inchr++;
2299 if (*inchr == '"') {
2302 if (*inchr != '\0') {
2303 *outchr++ = *inchr++;
2311 * Given a string, append the PID deliminated by delim.
2312 * Usually used to create a pid-appended filepath name
2313 * (eg: /a/b/foo -> /a/b/foo.6726). A function, and not
2314 * a macro, to avoid unistd.h dependency
2316 AP_DECLARE(char *) ap_append_pid(apr_pool_t *p, const char *string,
2319 return apr_psprintf(p, "%s%s%" APR_PID_T_FMT, string,
2325 * Parse a given timeout parameter string into an apr_interval_time_t value.
2326 * The unit of the time interval is given as postfix string to the numeric
2327 * string. Currently the following units are understood:
2334 * If no unit is contained in the given timeout parameter the default_time_unit
2335 * will be used instead.
2336 * @param timeout_parameter The string containing the timeout parameter.
2337 * @param timeout The timeout value to be returned.
2338 * @param default_time_unit The default time unit to use if none is specified
2339 * in timeout_parameter.
2340 * @return Status value indicating whether the parsing was successful or not.
2342 AP_DECLARE(apr_status_t) ap_timeout_parameter_parse(
2343 const char *timeout_parameter,
2344 apr_interval_time_t *timeout,
2345 const char *default_time_unit)
2348 const char *time_str;
2351 tout = apr_strtoi64(timeout_parameter, &endp, 10);
2355 if (!endp || !*endp) {
2356 time_str = default_time_unit;
2362 switch (*time_str) {
2363 /* Time is in seconds */
2365 *timeout = (apr_interval_time_t) apr_time_from_sec(tout);
2368 /* Time is in hours */
2369 *timeout = (apr_interval_time_t) apr_time_from_sec(tout * 3600);
2372 switch (*(++time_str)) {
2373 /* Time is in milliseconds */
2375 *timeout = (apr_interval_time_t) tout * 1000;
2377 /* Time is in minutes */
2379 *timeout = (apr_interval_time_t) apr_time_from_sec(tout * 60);
2382 return APR_EGENERAL;
2386 return APR_EGENERAL;
2392 * Determine if a request has a request body or not.
2394 * @param r the request_rec of the request
2395 * @return truth value
2397 AP_DECLARE(int) ap_request_has_body(request_rec *r)
2404 has_body = (!r->header_only
2406 || apr_table_get(r->headers_in, "Transfer-Encoding")
2407 || ( (cls = apr_table_get(r->headers_in, "Content-Length"))
2408 && (apr_strtoff(&cl, cls, &estr, 10) == APR_SUCCESS)
2416 AP_DECLARE_NONSTD(apr_status_t) ap_pool_cleanup_set_null(void *data_)
2418 void **ptr = (void **)data_;
2423 AP_DECLARE(apr_status_t) ap_str2_alnum(const char *src, char *dest) {
2425 for ( ; *src; src++, dest++)
2427 if (!apr_isprint(*src))
2429 else if (!apr_isalnum(*src))
2439 AP_DECLARE(apr_status_t) ap_pstr2_alnum(apr_pool_t *p, const char *src,
2442 char *new = apr_palloc(p, strlen(src)+1);
2446 return ap_str2_alnum(src, new);
2450 * Read the body and parse any form found, which must be of the
2451 * type application/x-www-form-urlencoded.
2453 * Name/value pairs are returned in an array, with the names as
2454 * strings with a maximum length of HUGE_STRING_LEN, and the
2455 * values as bucket brigades. This allows values to be arbitrarily
2458 * All url-encoding is removed from both the names and the values
2459 * on the fly. The names are interpreted as strings, while the
2460 * values are interpreted as blocks of binary data, that may
2461 * contain the 0 character.
2463 * In order to ensure that resource limits are not exceeded, a
2464 * maximum size must be provided. If the sum of the lengths of
2465 * the names and the values exceed this size, this function
2466 * will return HTTP_REQUEST_ENTITY_TOO_LARGE.
2468 * An optional number of parameters can be provided, if the number
2469 * of parameters provided exceeds this amount, this function will
2470 * return HTTP_REQUEST_ENTITY_TOO_LARGE. If this value is negative,
2471 * no limit is imposed, and the number of parameters is in turn
2472 * constrained by the size parameter above.
2474 * This function honours any kept_body configuration, and the
2475 * original raw request body will be saved to the kept_body brigade
2476 * if so configured, just as ap_discard_request_body does.
2478 * NOTE: File upload is not yet supported, but can be without change
2479 * to the function call.
2482 /* form parsing stuff */
2493 AP_DECLARE(int) ap_parse_form_data(request_rec *r, ap_filter_t *f,
2494 apr_array_header_t **ptr,
2495 apr_size_t num, apr_size_t usize)
2497 apr_bucket_brigade *bb = NULL;
2499 char buffer[HUGE_STRING_LEN + 1];
2501 apr_size_t offset = 0;
2503 ap_form_type_t state = FORM_NAME, percent = FORM_NORMAL;
2504 ap_form_pair_t *pair = NULL;
2505 apr_array_header_t *pairs = apr_array_make(r->pool, 4, sizeof(ap_form_pair_t));
2512 /* sanity check - we only support forms for now */
2513 ct = apr_table_get(r->headers_in, "Content-Type");
2514 if (!ct || strncasecmp("application/x-www-form-urlencoded", ct, 33)) {
2515 return ap_discard_request_body(r);
2518 if (usize > APR_SIZE_MAX >> 1)
2519 size = APR_SIZE_MAX >> 1;
2524 f = r->input_filters;
2527 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2529 apr_bucket *bucket = NULL, *last = NULL;
2531 int rv = ap_get_brigade(f, bb, AP_MODE_READBYTES,
2532 APR_BLOCK_READ, HUGE_STRING_LEN);
2533 if (rv != APR_SUCCESS) {
2534 apr_brigade_destroy(bb);
2535 return ap_map_http_request_error(rv, HTTP_BAD_REQUEST);
2538 for (bucket = APR_BRIGADE_FIRST(bb);
2539 bucket != APR_BRIGADE_SENTINEL(bb);
2540 last = bucket, bucket = APR_BUCKET_NEXT(bucket)) {
2542 apr_size_t len, slide;
2545 apr_bucket_delete(last);
2547 if (APR_BUCKET_IS_EOS(bucket)) {
2551 if (bucket->length == 0) {
2555 rv = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
2556 if (rv != APR_SUCCESS) {
2557 apr_brigade_destroy(bb);
2558 return HTTP_BAD_REQUEST;
2562 while (state != FORM_ABORT && slide-- > 0 && size >= 0 && num != 0) {
2567 else if ('&' == c) {
2571 percent = FORM_PERCENTA;
2574 if (FORM_PERCENTA == percent) {
2578 else if (c >= 'A') {
2581 else if (c >= '0') {
2585 percent = FORM_PERCENTB;
2588 if (FORM_PERCENTB == percent) {
2592 else if (c >= 'A') {
2595 else if (c >= '0') {
2599 percent = FORM_NORMAL;
2604 const char *tmp = apr_pmemdup(r->pool, buffer, offset);
2605 apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
2606 APR_BRIGADE_INSERT_TAIL(pair->value, b);
2614 if (offset < HUGE_STRING_LEN) {
2618 pair = (ap_form_pair_t *) apr_array_push(pairs);
2619 pair->name = apr_pstrdup(r->pool, buffer);
2620 pair->value = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2624 buffer[offset++] = c;
2633 if (offset >= HUGE_STRING_LEN) {
2634 const char *tmp = apr_pmemdup(r->pool, buffer, offset);
2635 apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
2636 APR_BRIGADE_INSERT_TAIL(pair->value, b);
2639 buffer[offset++] = c;
2649 apr_brigade_cleanup(bb);
2650 } while (!seen_eos);
2652 if (FORM_ABORT == state || size < 0 || num == 0) {
2653 return HTTP_REQUEST_ENTITY_TOO_LARGE;
2655 else if (FORM_VALUE == state && pair && offset > 0) {
2656 const char *tmp = apr_pmemdup(r->pool, buffer, offset);
2657 apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
2658 APR_BRIGADE_INSERT_TAIL(pair->value, b);
2665 #define VARBUF_SMALL_SIZE 2048
2666 #define VARBUF_MAX_SIZE (APR_SIZE_MAX - 1 - \
2667 APR_ALIGN_DEFAULT(sizeof(struct ap_varbuf_info)))
2669 struct ap_varbuf_info {
2670 struct apr_memnode_t *node;
2671 apr_allocator_t *allocator;
2674 static apr_status_t varbuf_cleanup(void *info_)
2676 struct ap_varbuf_info *info = info_;
2677 info->node->next = NULL;
2678 apr_allocator_free(info->allocator, info->node);
2682 const char nul = '\0';
2683 static char * const varbuf_empty = (char *)&nul;
2685 AP_DECLARE(void) ap_varbuf_init(apr_pool_t *p, struct ap_varbuf *vb,
2686 apr_size_t init_size)
2688 vb->buf = varbuf_empty;
2690 vb->strlen = AP_VARBUF_UNKNOWN;
2694 ap_varbuf_grow(vb, init_size);
2697 AP_DECLARE(void) ap_varbuf_grow(struct ap_varbuf *vb, apr_size_t new_len)
2699 apr_memnode_t *new_node = NULL;
2700 apr_allocator_t *allocator;
2701 struct ap_varbuf_info *new_info;
2704 AP_DEBUG_ASSERT(vb->strlen == AP_VARBUF_UNKNOWN || vb->avail >= vb->strlen);
2706 if (new_len <= vb->avail)
2709 if (new_len < 2 * vb->avail && vb->avail < VARBUF_MAX_SIZE/2) {
2710 /* at least double the size, to avoid repeated reallocations */
2711 new_len = 2 * vb->avail;
2713 else if (new_len > VARBUF_MAX_SIZE) {
2714 apr_abortfunc_t abort_fn = apr_pool_abort_get(vb->pool);
2715 ap_assert(abort_fn != NULL);
2716 abort_fn(APR_ENOMEM);
2720 new_len++; /* add space for trailing \0 */
2721 if (new_len <= VARBUF_SMALL_SIZE) {
2722 new_len = APR_ALIGN_DEFAULT(new_len);
2723 new = apr_palloc(vb->pool, new_len);
2724 if (vb->avail && vb->strlen != 0) {
2725 AP_DEBUG_ASSERT(vb->buf != NULL);
2726 AP_DEBUG_ASSERT(vb->buf != varbuf_empty);
2727 if (new == vb->buf + vb->avail + 1) {
2728 /* We are lucky: the new memory lies directly after our old
2729 * buffer, we can now use both.
2731 vb->avail += new_len;
2735 /* copy up to vb->strlen + 1 bytes */
2736 memcpy(new, vb->buf, vb->strlen == AP_VARBUF_UNKNOWN ?
2737 vb->avail + 1 : vb->strlen + 1);
2743 vb->avail = new_len - 1;
2748 /* The required block is rather larger. Use allocator directly so that
2749 * the memory can be freed independently from the pool. */
2750 allocator = apr_pool_allocator_get(vb->pool);
2751 if (new_len <= VARBUF_MAX_SIZE)
2752 new_node = apr_allocator_alloc(allocator,
2753 new_len + APR_ALIGN_DEFAULT(sizeof(*new_info)));
2755 apr_abortfunc_t abort_fn = apr_pool_abort_get(vb->pool);
2756 ap_assert(abort_fn != NULL);
2757 abort_fn(APR_ENOMEM);
2760 new_info = (struct ap_varbuf_info *)new_node->first_avail;
2761 new_node->first_avail += APR_ALIGN_DEFAULT(sizeof(*new_info));
2762 new_info->node = new_node;
2763 new_info->allocator = allocator;
2764 new = new_node->first_avail;
2765 AP_DEBUG_ASSERT(new_node->endp - new_node->first_avail >= new_len);
2766 new_len = new_node->endp - new_node->first_avail;
2768 if (vb->avail && vb->strlen != 0)
2769 memcpy(new, vb->buf, vb->strlen == AP_VARBUF_UNKNOWN ?
2770 vb->avail + 1 : vb->strlen + 1);
2774 apr_pool_cleanup_run(vb->pool, vb->info, varbuf_cleanup);
2775 apr_pool_cleanup_register(vb->pool, new_info, varbuf_cleanup,
2776 apr_pool_cleanup_null);
2777 vb->info = new_info;
2779 vb->avail = new_len - 1;
2782 AP_DECLARE(void) ap_varbuf_strmemcat(struct ap_varbuf *vb, const char *str,
2788 ap_varbuf_grow(vb, len);
2789 memcpy(vb->buf, str, len);
2790 vb->buf[len] = '\0';
2794 if (vb->strlen == AP_VARBUF_UNKNOWN)
2795 vb->strlen = strlen(vb->buf);
2796 ap_varbuf_grow(vb, vb->strlen + len);
2797 memcpy(vb->buf + vb->strlen, str, len);
2799 vb->buf[vb->strlen] = '\0';
2802 AP_DECLARE(void) ap_varbuf_free(struct ap_varbuf *vb)
2805 apr_pool_cleanup_run(vb->pool, vb->info, varbuf_cleanup);
2811 AP_DECLARE(char *) ap_varbuf_pdup(apr_pool_t *p, struct ap_varbuf *buf,
2812 const char *prepend, apr_size_t prepend_len,
2813 const char *append, apr_size_t append_len,
2814 apr_size_t *new_len)
2817 struct iovec vec[3];
2820 vec[i].iov_base = (void *)prepend;
2821 vec[i].iov_len = prepend_len;
2824 if (buf->avail && buf->strlen) {
2825 if (buf->strlen == AP_VARBUF_UNKNOWN)
2826 buf->strlen = strlen(buf->buf);
2827 vec[i].iov_base = (void *)buf->buf;
2828 vec[i].iov_len = buf->strlen;
2832 vec[i].iov_base = (void *)append;
2833 vec[i].iov_len = append_len;
2837 return apr_pstrcatv(p, vec, i, new_len);
2844 AP_DECLARE(apr_status_t) ap_varbuf_regsub(struct ap_varbuf *vb,
2848 ap_regmatch_t pmatch[],
2851 return regsub_core(NULL, NULL, vb, input, source, nmatch, pmatch, maxlen);
2854 static const char * const oom_message = "[crit] Memory allocation failed, "
2855 "aborting process." APR_EOL_STR;
2857 AP_DECLARE(void) ap_abort_on_oom()
2859 int written, count = strlen(oom_message);
2860 const char *buf = oom_message;
2862 written = write(STDERR_FILENO, buf, count);
2863 if (written == count)
2869 } while (written >= 0 || errno == EINTR);
2873 AP_DECLARE(void *) ap_malloc(size_t size)
2875 void *p = malloc(size);
2876 if (p == NULL && size != 0)
2881 AP_DECLARE(void *) ap_calloc(size_t nelem, size_t size)
2883 void *p = calloc(nelem, size);
2884 if (p == NULL && nelem != 0 && size != 0)
2889 AP_DECLARE(void *) ap_realloc(void *ptr, size_t size)
2891 void *p = realloc(ptr, size);
2892 if (p == NULL && size != 0)
2897 AP_DECLARE(void) ap_get_sload(ap_sload_t *ld)
2899 int i, j, server_limit, thread_limit;
2903 ap_generation_t mpm_generation;
2905 /* preload errored fields, we overwrite */
2908 ld->bytes_served = 0;
2909 ld->access_count = 0;
2911 ap_mpm_query(AP_MPMQ_GENERATION, &mpm_generation);
2912 ap_mpm_query(AP_MPMQ_HARD_LIMIT_THREADS, &thread_limit);
2913 ap_mpm_query(AP_MPMQ_HARD_LIMIT_DAEMONS, &server_limit);
2915 for (i = 0; i < server_limit; i++) {
2917 ps = ap_get_scoreboard_process(i);
2919 for (j = 0; j < thread_limit; j++) {
2921 worker_score *ws = NULL;
2922 ws = &ap_scoreboard_image->servers[i][j];
2925 if (!ps->quiescing && ps->pid) {
2926 if (res == SERVER_READY && ps->generation == mpm_generation) {
2929 else if (res != SERVER_DEAD &&
2930 res != SERVER_STARTING && res != SERVER_IDLE_KILL &&
2931 ps->generation == mpm_generation) {
2936 if (ap_extended_status && !ps->quiescing && ps->pid) {
2937 if (ws->access_count != 0
2938 || (res != SERVER_READY && res != SERVER_DEAD)) {
2939 ld->access_count += ws->access_count;
2940 ld->bytes_served += ws->bytes_served;
2945 total = busy + ready;
2947 ld->idle = ready * 100 / total;
2948 ld->busy = busy * 100 / total;
2952 AP_DECLARE(void) ap_get_loadavg(ap_loadavg_t *ld)
2954 /* preload errored fields, we overwrite */
2956 ld->loadavg5 = -1.0;
2957 ld->loadavg15 = -1.0;
2964 num = getloadavg(la, 3);
2966 ld->loadavg = (float)la[0];
2969 ld->loadavg5 = (float)la[1];
2972 ld->loadavg15 = (float)la[2];
2978 static const char * const pw_cache_note_name = "conn_cache_note";
2980 /* varbuf contains concatenated password and hash */
2981 struct ap_varbuf vb;
2983 apr_status_t result;
2986 AP_DECLARE(apr_status_t) ap_password_validate(request_rec *r,
2987 const char *username,
2991 struct pw_cache *cache;
2994 cache = (struct pw_cache *)apr_table_get(r->connection->notes, pw_cache_note_name);
2995 if (cache != NULL) {
2996 if (strncmp(passwd, cache->vb.buf, cache->pwlen) == 0
2997 && strcmp(hash, cache->vb.buf + cache->pwlen) == 0) {
2998 return cache->result;
3000 /* make ap_varbuf_grow below not copy the old data */
3001 cache->vb.strlen = 0;
3004 cache = apr_palloc(r->connection->pool, sizeof(struct pw_cache));
3005 ap_varbuf_init(r->connection->pool, &cache->vb, 0);
3006 apr_table_setn(r->connection->notes, pw_cache_note_name, (void *)cache);
3008 cache->pwlen = strlen(passwd);
3009 hashlen = strlen(hash);
3010 ap_varbuf_grow(&cache->vb, cache->pwlen + hashlen + 1);
3011 memcpy(cache->vb.buf, passwd, cache->pwlen);
3012 memcpy(cache->vb.buf + cache->pwlen, hash, hashlen + 1);
3013 cache->result = apr_password_validate(passwd, hash);
3014 return cache->result;
3017 AP_DECLARE(char *) ap_get_exec_line(apr_pool_t *p,
3019 const char * const * argv)
3021 char buf[MAX_STRING_LEN];
3022 apr_procattr_t *procattr;
3025 apr_size_t nbytes = 1;
3029 if (apr_procattr_create(&procattr, p) != APR_SUCCESS)
3031 if (apr_procattr_io_set(procattr, APR_FULL_BLOCK, APR_FULL_BLOCK,
3032 APR_FULL_BLOCK) != APR_SUCCESS)
3034 if (apr_procattr_dir_set(procattr,
3035 ap_make_dirstr_parent(p, cmd)) != APR_SUCCESS)
3037 if (apr_procattr_cmdtype_set(procattr, APR_PROGRAM) != APR_SUCCESS)
3039 proc = apr_pcalloc(p, sizeof(apr_proc_t));
3040 if (apr_proc_create(proc, cmd, argv, NULL, procattr, p) != APR_SUCCESS)
3046 /* XXX: we are reading 1 byte at a time here */
3047 for (k = 0; apr_file_read(fp, &c, &nbytes) == APR_SUCCESS
3048 && nbytes == 1 && (k < MAX_STRING_LEN-1) ; ) {
3049 if (c == '\n' || c == '\r')
3056 return apr_pstrndup(p, buf, k);