1 /* ====================================================================
2 * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in
13 * the documentation and/or other materials provided with the
16 * 3. All advertising materials mentioning features or use of this
17 * software must display the following acknowledgment:
18 * "This product includes software developed by the Apache Group
19 * for use in the Apache HTTP server project (http://www.apache.org/)."
21 * 4. The names "Apache Server" and "Apache Group" must not be used to
22 * endorse or promote products derived from this software without
23 * prior written permission. For written permission, please contact
26 * 5. Products derived from this software may not be called "Apache"
27 * nor may "Apache" appear in their names without prior written
28 * permission of the Apache Group.
30 * 6. Redistributions of any form whatsoever must retain the following
32 * "This product includes software developed by the Apache Group
33 * for use in the Apache HTTP server project (http://www.apache.org/)."
35 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
36 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46 * OF THE POSSIBILITY OF SUCH DAMAGE.
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Group and was originally based
51 * on public domain software written at the National Center for
52 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
53 * For more information on the Apache Group and the Apache HTTP server
54 * project, please see <http://www.apache.org/>.
59 * util.c: string utility things
62 * 1995-96 Many changes by the Apache Group
67 * #define DEBUG to trace all cfg_open*()/cfg_closefile() calls
68 * #define DEBUG_CFG_LINES to trace every line read from the config files
72 #include "http_main.h"
74 #include "http_protocol.h"
76 /* stdio.h has been read in ap_config.h already. Add missing prototypes here: */
77 extern int fgetc(FILE *);
78 extern char *fgets(char *s, int, FILE*);
79 extern int fclose(FILE *);
82 /* A bunch of functions in util.c scan strings looking for certain characters.
83 * To make that more efficient we encode a lookup table. The test_char_table
84 * is generated automatically by gen_test_char.c.
86 #include "test_char.h"
88 /* we assume the folks using this ensure 0 <= c < 256... which means
89 * you need a cast to (unsigned char) first, you can't just plug a
90 * char in here and get it to work, because if char is signed then it
91 * will first be sign extended.
93 #define TEST_CHAR(c, f) (test_char_table[(unsigned)(c)] & (f))
95 void ap_util_init(void)
97 /* nothing to do... previously there was run-time initialization of
98 * test_char_table here
103 API_VAR_EXPORT const char ap_month_snames[12][4] =
105 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
107 API_VAR_EXPORT const char ap_day_snames[7][4] =
109 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
112 API_EXPORT(char *) ap_get_time()
114 /* ZZZ When we abstract out time, this whole function should change to use
120 time_string = ctime(&t);
121 time_string[strlen(time_string) - 1] = '\0';
122 return (time_string);
126 * Examine a field value (such as a media-/content-type) string and return
127 * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
129 API_EXPORT(char *) ap_field_noparam(ap_context_t *p, const char *intype)
133 semi = strchr(intype, ';');
135 return ap_pstrdup(p, intype);
138 while ((semi > intype) && ap_isspace(semi[-1])) {
141 return ap_pstrndup(p, intype, semi - intype);
145 API_EXPORT(char *) ap_ht_time(ap_context_t *p, time_t t, const char *fmt, int gmt)
147 /* ZZZ this function can be replaced by calls to time formatting routines
149 char ts[MAX_STRING_LEN];
150 char tf[MAX_STRING_LEN];
153 tms = (gmt ? gmtime(&t) : localtime(&t));
155 /* Convert %Z to "GMT" and %z to "+0000";
156 * on hosts that do not have a time zone string in struct tm,
157 * strftime must assume its argument is local time.
161 for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
163 if (*f != '%') continue;
174 case 'z': /* common extension */
188 /* check return code? */
189 strftime(ts, MAX_STRING_LEN, fmt, tms);
190 ts[MAX_STRING_LEN - 1] = '\0';
191 return ap_pstrdup(p, ts);
194 API_EXPORT(char *) ap_gm_timestr_822(ap_context_t *p, time_t sec)
197 char *date_str = ap_palloc(p, 48 * sizeof(char));
198 char *date_str_ptr = date_str;
201 tms = gmtime(&sec); /* ZZZ replace with AP time routine */
203 /* Assumption: this is always 3 */
204 /* i = strlen(ap_day_snames[tms->tm_wday]); */
205 memcpy(date_str_ptr, ap_day_snames[tms->tm_wday], 3);
207 *date_str_ptr++ = ',';
208 *date_str_ptr++ = ' ';
209 *date_str_ptr++ = tms->tm_mday / 10 + '0';
210 *date_str_ptr++ = tms->tm_mday % 10 + '0';
211 *date_str_ptr++ = ' ';
212 /* Assumption: this is also always 3 */
213 /* i = strlen(ap_month_snames[tms->tm_mon]); */
214 memcpy(date_str_ptr, ap_month_snames[tms->tm_mon], 3);
216 *date_str_ptr++ = ' ';
217 real_year = 1900 + tms->tm_year;
218 /* This routine isn't y10k ready. */
219 *date_str_ptr++ = real_year / 1000 + '0';
220 *date_str_ptr++ = real_year % 1000 / 100 + '0';
221 *date_str_ptr++ = real_year % 100 / 10 + '0';
222 *date_str_ptr++ = real_year % 10 + '0';
223 *date_str_ptr++ = ' ';
224 *date_str_ptr++ = tms->tm_hour / 10 + '0';
225 *date_str_ptr++ = tms->tm_hour % 10 + '0';
226 *date_str_ptr++ = ':';
227 *date_str_ptr++ = tms->tm_min / 10 + '0';
228 *date_str_ptr++ = tms->tm_min % 10 + '0';
229 *date_str_ptr++ = ':';
230 *date_str_ptr++ = tms->tm_sec / 10 + '0';
231 *date_str_ptr++ = tms->tm_sec % 10 + '0';
232 *date_str_ptr++ = ' ';
233 *date_str_ptr++ = 'G';
234 *date_str_ptr++ = 'M';
235 *date_str_ptr++ = 'T';
236 *date_str_ptr = '\0';
239 /* RFC date format; as strftime '%a, %d %b %Y %T GMT' */
241 /* The equivalent using sprintf. Use this for more legible but slower code
242 return ap_psprintf(p,
243 "%s, %.2d %s %d %.2d:%.2d:%.2d GMT", ap_day_snames[tms->tm_wday],
244 tms->tm_mday, ap_month_snames[tms->tm_mon], tms->tm_year + 1900,
245 tms->tm_hour, tms->tm_min, tms->tm_sec);
249 /* What a pain in the ass. */
250 #if defined(HAVE_GMTOFF)
251 API_EXPORT(struct tm *) ap_get_gmtoff(int *tz)
253 time_t tt = time(NULL);
257 *tz = (int) (t->tm_gmtoff / 60);
261 API_EXPORT(struct tm *) ap_get_gmtoff(int *tz)
263 time_t tt = time(NULL);
266 int days, hours, minutes;
268 /* Assume we are never more than 24 hours away. */
269 gmt = *gmtime(&tt); /* remember gmtime/localtime return ptr to static */
270 t = localtime(&tt); /* buffer... so be careful */
271 days = t->tm_yday - gmt.tm_yday;
272 hours = ((days < -1 ? 24 : 1 < days ? -24 : days * 24)
273 + t->tm_hour - gmt.tm_hour);
274 minutes = hours * 60 + t->tm_min - gmt.tm_min;
280 /* Roy owes Rob beer. */
281 /* Rob owes Roy dinner. */
283 /* These legacy comments would make a lot more sense if Roy hadn't
284 * replaced the old later_than() routine with util_date.c.
286 * Well, okay, they still wouldn't make any sense.
289 /* Match = 0, NoMatch = 1, Abort = -1
290 * Based loosely on sections of wildmat.c by Rich Salz
291 * Hmmm... shouldn't this really go component by component?
293 API_EXPORT(int) ap_strcmp_match(const char *str, const char *exp)
297 for (x = 0, y = 0; exp[y]; ++y, ++x) {
298 if ((!str[x]) && (exp[y] != '*'))
301 while (exp[++y] == '*');
306 if ((ret = ap_strcmp_match(&str[x++], &exp[y])) != 1)
311 else if ((exp[y] != '?') && (str[x] != exp[y]))
314 return (str[x] != '\0');
317 API_EXPORT(int) ap_strcasecmp_match(const char *str, const char *exp)
321 for (x = 0, y = 0; exp[y]; ++y, ++x) {
322 if ((!str[x]) && (exp[y] != '*'))
325 while (exp[++y] == '*');
330 if ((ret = ap_strcasecmp_match(&str[x++], &exp[y])) != 1)
335 else if ((exp[y] != '?') && (ap_tolower(str[x]) != ap_tolower(exp[y])))
338 return (str[x] != '\0');
341 API_EXPORT(int) ap_is_matchexp(const char *str)
345 for (x = 0; str[x]; x++)
346 if ((str[x] == '*') || (str[x] == '?'))
352 * Apache stub function for the regex libraries regexec() to make sure the
353 * whole regex(3) API is available through the Apache (exported) namespace.
354 * This is especially important for the DSO situations of modules.
355 * DO NOT MAKE A MACRO OUT OF THIS FUNCTION!
357 API_EXPORT(int) ap_regexec(const regex_t *preg, const char *string,
358 size_t nmatch, regmatch_t pmatch[], int eflags)
360 return regexec(preg, string, nmatch, pmatch, eflags);
363 API_EXPORT(size_t) ap_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
365 return regerror(errcode, preg, errbuf, errbuf_size);
369 /* This function substitutes for $0-$9, filling in regular expression
370 * submatches. Pass it the same nmatch and pmatch arguments that you
371 * passed ap_regexec(). pmatch should not be greater than the maximum number
372 * of subexpressions - i.e. one more than the re_nsub member of regex_t.
374 * input should be the string with the $-expressions, source should be the
375 * string that was matched against.
377 * It returns the substituted string, or NULL on error.
379 * Parts of this code are based on Henry Spencer's regsub(), from his
380 * AT&T V8 regexp package.
383 API_EXPORT(char *) ap_pregsub(ap_context_t *p, const char *input, const char *source,
384 size_t nmatch, regmatch_t pmatch[])
386 const char *src = input;
395 return ap_pstrdup(p, src);
397 /* First pass, find the size */
401 while ((c = *src++) != '\0') {
404 else if (c == '$' && ap_isdigit(*src))
409 if (no > 9) { /* Ordinary character. */
410 if (c == '\\' && (*src == '$' || *src == '&'))
414 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
415 len += pmatch[no].rm_eo - pmatch[no].rm_so;
420 dest = dst = ap_pcalloc(p, len + 1);
422 /* Now actually fill in the string */
426 while ((c = *src++) != '\0') {
429 else if (c == '$' && ap_isdigit(*src))
434 if (no > 9) { /* Ordinary character. */
435 if (c == '\\' && (*src == '$' || *src == '&'))
439 else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) {
440 len = pmatch[no].rm_eo - pmatch[no].rm_so;
441 memcpy(dst, source + pmatch[no].rm_so, len);
452 * Parse .. so we don't compromise security
454 API_EXPORT(void) ap_getparents(char *name)
458 /* Four paseses, as per RFC 1808 */
459 /* a) remove ./ path segments */
461 for (l = 0, w = 0; name[l] != '\0';) {
462 if (name[l] == '.' && name[l + 1] == '/' && (l == 0 || name[l - 1] == '/'))
465 name[w++] = name[l++];
468 /* b) remove trailing . path, segment */
469 if (w == 1 && name[0] == '.')
471 else if (w > 1 && name[w - 1] == '.' && name[w - 2] == '/')
475 /* c) remove all xx/../ segments. (including leading ../ and /../) */
478 while (name[l] != '\0') {
479 if (name[l] == '.' && name[l + 1] == '.' && name[l + 2] == '/' &&
480 (l == 0 || name[l - 1] == '/')) {
481 register int m = l + 3, n;
485 while (l >= 0 && name[l] != '/')
492 while ((name[n] = name[m]))
499 /* d) remove trailing xx/.. segment. */
500 if (l == 2 && name[0] == '.' && name[1] == '.')
502 else if (l > 2 && name[l - 1] == '.' && name[l - 2] == '.' && name[l - 3] == '/') {
505 while (l >= 0 && name[l] != '/')
515 API_EXPORT(void) ap_no2slash(char *name)
522 /* Check for UNC names. Leave leading two slashes. */
523 if (s[0] == '/' && s[1] == '/')
528 if ((*d++ = *s) == '/') {
542 * copy at most n leading directories of s into d
543 * d should be at least as large as s plus 1 extra byte
545 * the return value is the ever useful pointer to the trailing \0 of d
553 API_EXPORT(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
556 if (*s == '\0' || (*s == '/' && (--n) == 0)) {
568 * return the parent directory name including trailing / of the file s
570 API_EXPORT(char *) ap_make_dirstr_parent(ap_context_t *p, const char *s)
572 char *last_slash = strrchr(s, '/');
576 if (last_slash == NULL) {
577 /* XXX: well this is really broken if this happens */
578 return (ap_pstrdup(p, "/"));
580 l = (last_slash - s) + 1;
581 d = ap_palloc(p, l + 1);
589 * This function is deprecated. Use one of the preceeding two functions
592 API_EXPORT(char *) ap_make_dirstr(ap_context_t *p, const char *s, int n)
597 for (x = 0, f = 0; s[x]; x++) {
600 res = ap_palloc(p, x + 2);
608 if (s[strlen(s) - 1] == '/')
609 return ap_pstrdup(p, s);
611 return ap_pstrcat(p, s, "/", NULL);
614 API_EXPORT(int) ap_count_dirs(const char *path)
618 for (x = 0, n = 0; path[x]; x++)
625 API_EXPORT(void) ap_chdir_file(const char *file)
628 char buf[HUGE_STRING_LEN];
630 x = strrchr(file, '/');
634 else if (x - file < sizeof(buf) - 1) {
635 memcpy(buf, file, x - file);
636 buf[x - file] = '\0';
639 /* XXX: well, this is a silly function, no method of reporting an
640 * error... ah well. */
643 API_EXPORT(char *) ap_getword_nc(ap_context_t *atrans, char **line, char stop)
645 return ap_getword(atrans, (const char **) line, stop);
648 API_EXPORT(char *) ap_getword(ap_context_t *atrans, const char **line, char stop)
650 char *pos = strchr(*line, stop);
654 res = ap_pstrdup(atrans, *line);
655 *line += strlen(*line);
659 res = ap_pstrndup(atrans, *line, pos - *line);
661 while (*pos == stop) {
670 API_EXPORT(char *) ap_getword_white_nc(ap_context_t *atrans, char **line)
672 return ap_getword_white(atrans, (const char **) line);
675 API_EXPORT(char *) ap_getword_white(ap_context_t *atrans, const char **line)
680 for (x = 0; (*line)[x]; x++) {
681 if (ap_isspace((*line)[x])) {
688 res = ap_pstrdup(atrans, *line);
689 *line += strlen(*line);
693 res = ap_palloc(atrans, pos + 1);
694 ap_cpystrn(res, *line, pos + 1);
696 while (ap_isspace((*line)[pos]))
704 API_EXPORT(char *) ap_getword_nulls_nc(ap_context_t *atrans, char **line, char stop)
706 return ap_getword_nulls(atrans, (const char **) line, stop);
709 API_EXPORT(char *) ap_getword_nulls(ap_context_t *atrans, const char **line, char stop)
711 char *pos = strchr(*line, stop);
715 res = ap_pstrdup(atrans, *line);
716 *line += strlen(*line);
720 res = ap_pstrndup(atrans, *line, pos - *line);
729 /* Get a word, (new) config-file style --- quoted strings and backslashes
733 static char *substring_conf(ap_context_t *p, const char *start, int len, char quote)
735 char *result = ap_palloc(p, len + 2);
739 for (i = 0; i < len; ++i) {
740 if (start[i] == '\\' && (start[i + 1] == '\\'
741 || (quote && start[i + 1] == quote)))
742 *resp++ = start[++i];
751 API_EXPORT(char *) ap_getword_conf_nc(ap_context_t *p, char **line)
753 return ap_getword_conf(p, (const char **) line);
756 API_EXPORT(char *) ap_getword_conf(ap_context_t *p, const char **line)
758 const char *str = *line, *strend;
762 while (*str && ap_isspace(*str))
770 if ((quote = *str) == '"' || quote == '\'') {
772 while (*strend && *strend != quote) {
773 if (*strend == '\\' && strend[1] && strend[1] == quote)
778 res = substring_conf(p, str + 1, strend - str - 1, quote);
780 if (*strend == quote)
785 while (*strend && !ap_isspace(*strend))
788 res = substring_conf(p, str, strend - str, 0);
791 while (*strend && ap_isspace(*strend))
797 API_EXPORT(int) ap_cfg_closefile(configfile_t *cfp)
800 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL,
801 "Done with config file %s", cfp->name);
803 return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
806 static ap_status_t cfg_close(void *param)
808 ap_file_t *cfp = (ap_file_t *) param;
809 return (ap_close(cfp));
812 static int cfg_getch(void *param)
815 ap_file_t *cfp = (ap_file_t *) param;
816 if (ap_getc(cfp, &ch) == APR_SUCCESS)
821 static void *cfg_getstr(void *buf, size_t bufsiz, void *param)
823 ap_file_t *cfp = (ap_file_t *) param;
824 if (ap_gets(cfp, buf, bufsiz) == APR_SUCCESS)
829 /* Open a configfile_t as FILE, return open configfile_t struct pointer */
830 API_EXPORT(configfile_t *) ap_pcfg_openfile(ap_context_t *p, const char *name)
832 configfile_t *new_cfg;
839 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, NULL,
840 "Internal error: pcfg_openfile() called with NULL filename");
844 if (!ap_os_is_filename_valid(name)) {
845 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, NULL,
846 "Access to config file %s denied: not a valid filename",
852 stat = ap_open(p, name, APR_READ | APR_BUFFERED, APR_OS_DEFAULT, &file);
855 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, NULL,
856 "Opening config file %s (%s)",
857 name, (stat != APR_SUCCESS) ? strerror(errno) : "successful");
860 if (stat != APR_SUCCESS)
863 if (ap_get_filetype(file, &type) == APR_SUCCESS &&
865 #if defined(WIN32) || defined(OS2)
866 !(strcasecmp(name, "nul") == 0 ||
867 (strlen(name) >= 4 &&
868 strcasecmp(name + strlen(name) - 4, "/nul") == 0))) {
870 strcmp(name, "/dev/null") == 0) {
871 #endif /* WIN32 || OS2 */
873 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, NULL,
874 "Access to file %s denied by server: not a regular file",
881 new_cfg = ap_palloc(p, sizeof(*new_cfg));
882 new_cfg->param = file;
883 new_cfg->name = ap_pstrdup(p, name);
884 new_cfg->getch = (int (*)(void *)) cfg_getch;
885 new_cfg->getstr = (void *(*)(void *, size_t, void *)) cfg_getstr;
886 new_cfg->close = (int (*)(void *)) cfg_close;
887 new_cfg->line_number = 0;
892 /* Allocate a configfile_t handle with user defined functions and params */
893 API_EXPORT(configfile_t *) ap_pcfg_open_custom(ap_context_t *p, const char *descr,
895 int(*getch)(void *param),
896 void *(*getstr) (void *buf, size_t bufsiz, void *param),
897 int(*close_func)(void *param))
899 configfile_t *new_cfg = ap_palloc(p, sizeof(*new_cfg));
901 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, NULL, "Opening config handler %s", descr);
903 new_cfg->param = param;
904 new_cfg->name = descr;
905 new_cfg->getch = getch;
906 new_cfg->getstr = getstr;
907 new_cfg->close = close_func;
908 new_cfg->line_number = 0;
913 /* Read one character from a configfile_t */
914 API_EXPORT(int) ap_cfg_getc(configfile_t *cfp)
916 register int ch = cfp->getch(cfp->param);
923 /* Read one line from open configfile_t, strip LF, increase line number */
924 /* If custom handler does not define a getstr() function, read char by char */
925 API_EXPORT(int) ap_cfg_getline(char *buf, size_t bufsize, configfile_t *cfp)
927 /* If a "get string" function is defined, use it */
928 if (cfp->getstr != NULL) {
932 size_t cbufsize = bufsize;
936 if (cfp->getstr(cbuf, cbufsize, cfp->param) == NULL)
940 * check for line continuation,
941 * i.e. match [^\\]\\[\r]\n only
944 while (cp < cbuf+cbufsize && *cp != '\0')
946 if (cp > cbuf && cp[-1] == LF) {
948 if (cp > cbuf && cp[-1] == CR)
950 if (cp > cbuf && cp[-1] == '\\') {
952 if (!(cp > cbuf && cp[-1] == '\\')) {
954 * line continuation requested -
955 * then remove backslash and continue
957 cbufsize -= (cp-cbuf);
963 * no real continuation because escaped -
964 * then just remove escape character
966 for ( ; cp < cbuf+cbufsize && *cp != '\0'; cp++)
975 * Leading and trailing white space is eliminated completely
978 while (ap_isspace(*src))
980 /* blast trailing whitespace */
981 dst = &src[strlen(src)];
982 while (--dst >= src && ap_isspace(*dst))
984 /* Zap leading whitespace by shifting */
986 for (dst = buf; (*dst++ = *src++) != '\0'; )
989 #ifdef DEBUG_CFG_LINES
990 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL, "Read config: %s", buf);
994 /* No "get string" function defined; read character by character */
996 register size_t i = 0;
999 /* skip leading whitespace */
1001 c = cfp->getch(cfp->param);
1002 } while (c == '\t' || c == ' ');
1008 /* too small, assume caller is crazy */
1013 if ((c == '\t') || (c == ' ')) {
1015 while ((c == '\t') || (c == ' '))
1016 c = cfp->getch(cfp->param);
1019 /* silently ignore CR (_assume_ that a LF follows) */
1020 c = cfp->getch(cfp->param);
1023 /* increase line number and return on LF */
1026 if (c == EOF || c == 0x4 || c == LF || i >= (bufsize - 2)) {
1028 * check for line continuation
1030 if (i > 0 && buf[i-1] == '\\') {
1032 if (!(i > 0 && buf[i-1] == '\\')) {
1033 /* line is continued */
1034 c = cfp->getch(cfp->param);
1037 /* else nothing needs be done because
1038 * then the backslash is escaped and
1039 * we just strip to a single one
1042 /* blast trailing whitespace */
1043 while (i > 0 && ap_isspace(buf[i - 1]))
1046 #ifdef DEBUG_CFG_LINES
1047 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL, "Read config: %s", buf);
1053 c = cfp->getch(cfp->param);
1058 /* Size an HTTP header field list item, as separated by a comma.
1059 * The return value is a pointer to the beginning of the non-empty list item
1060 * within the original string (or NULL if there is none) and the address
1061 * of field is shifted to the next non-comma, non-whitespace character.
1062 * len is the length of the item excluding any beginning whitespace.
1064 API_EXPORT(const char *) ap_size_list_item(const char **field, int *len)
1066 const unsigned char *ptr = (const unsigned char *)*field;
1067 const unsigned char *token;
1068 int in_qpair, in_qstr, in_com;
1070 /* Find first non-comma, non-whitespace byte */
1072 while (*ptr == ',' || ap_isspace(*ptr))
1077 /* Find the end of this item, skipping over dead bits */
1079 for (in_qpair = in_qstr = in_com = 0;
1080 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1088 case '\\': in_qpair = 1; /* quoted-pair */
1090 case '"' : if (!in_com) /* quoted string delim */
1093 case '(' : if (!in_qstr) /* comment (may nest) */
1096 case ')' : if (in_com) /* end comment */
1104 if ((*len = (ptr - token)) == 0) {
1105 *field = (const char *)ptr;
1109 /* Advance field pointer to the next non-comma, non-white byte */
1111 while (*ptr == ',' || ap_isspace(*ptr))
1114 *field = (const char *)ptr;
1115 return (const char *)token;
1118 /* Retrieve an HTTP header field list item, as separated by a comma,
1119 * while stripping insignificant whitespace and lowercasing anything not in
1120 * a quoted string or comment. The return value is a new string containing
1121 * the converted list item (or NULL if none) and the address pointed to by
1122 * field is shifted to the next non-comma, non-whitespace.
1124 API_EXPORT(char *) ap_get_list_item(ap_context_t *p, const char **field)
1126 const char *tok_start;
1127 const unsigned char *ptr;
1130 int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1132 /* Find the beginning and maximum length of the list item so that
1133 * we can allocate a buffer for the new string and reset the field.
1135 if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1138 token = ap_palloc(p, tok_len + 1);
1140 /* Scan the token again, but this time copy only the good bytes.
1141 * We skip extra whitespace and any whitespace around a '=', '/',
1142 * or ';' and lowercase normal characters not within a comment,
1143 * quoted-string or quoted-pair.
1145 for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1146 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1155 case '\\': in_qpair = 1;
1161 case '"' : if (!in_com)
1168 case '(' : if (!in_qstr)
1175 case ')' : if (in_com)
1181 case '\t': if (addspace)
1183 if (in_com || in_qstr)
1190 case ';' : if (!(in_com || in_qstr))
1194 default : if (addspace == 1)
1196 *pos++ = (in_com || in_qstr) ? *ptr
1208 /* Find an item in canonical form (lowercase, no extra spaces) within
1209 * an HTTP field value list. Returns 1 if found, 0 if not found.
1210 * This would be much more efficient if we stored header fields as
1211 * an array of list items as they are received instead of a plain string.
1213 API_EXPORT(int) ap_find_list_item(ap_context_t *p, const char *line, const char *tok)
1215 const unsigned char *pos;
1216 const unsigned char *ptr = (const unsigned char *)line;
1217 int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1222 do { /* loop for each item in line's list */
1224 /* Find first non-comma, non-whitespace byte */
1226 while (*ptr == ',' || ap_isspace(*ptr))
1230 good = 1; /* until proven otherwise for this item */
1232 break; /* no items left and nothing good found */
1234 /* We skip extra whitespace and any whitespace around a '=', '/',
1235 * or ';' and lowercase normal characters not within a comment,
1236 * quoted-string or quoted-pair.
1238 for (pos = (const unsigned char *)tok;
1239 *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1245 good = (*pos++ == *ptr);
1249 case '\\': in_qpair = 1;
1251 good = good && (*pos++ == ' ');
1252 good = good && (*pos++ == *ptr);
1255 case '"' : if (!in_com)
1258 good = good && (*pos++ == ' ');
1259 good = good && (*pos++ == *ptr);
1262 case '(' : if (!in_qstr)
1265 good = good && (*pos++ == ' ');
1266 good = good && (*pos++ == *ptr);
1269 case ')' : if (in_com)
1271 good = good && (*pos++ == *ptr);
1275 case '\t': if (addspace || !good)
1277 if (in_com || in_qstr)
1278 good = (*pos++ == *ptr);
1284 case ';' : if (!(in_com || in_qstr))
1286 good = good && (*pos++ == *ptr);
1288 default : if (!good)
1291 good = (*pos++ == ' ');
1292 if (in_com || in_qstr)
1293 good = good && (*pos++ == *ptr);
1295 good = good && (*pos++ == ap_tolower(*ptr));
1302 good = 0; /* not good if only a prefix was matched */
1304 } while (*ptr && !good);
1310 /* Retrieve a token, spacing over it and returning a pointer to
1311 * the first non-white byte afterwards. Note that these tokens
1312 * are delimited by semis and commas; and can also be delimited
1313 * by whitespace at the caller's option.
1316 API_EXPORT(char *) ap_get_token(ap_context_t *p, const char **accept_line, int accept_white)
1318 const char *ptr = *accept_line;
1319 const char *tok_start;
1323 /* Find first non-white byte */
1325 while (*ptr && ap_isspace(*ptr))
1330 /* find token end, skipping over quoted strings.
1331 * (comments are already gone).
1334 while (*ptr && (accept_white || !ap_isspace(*ptr))
1335 && *ptr != ';' && *ptr != ',') {
1342 tok_len = ptr - tok_start;
1343 token = ap_pstrndup(p, tok_start, tok_len);
1345 /* Advance accept_line pointer to the next non-white byte */
1347 while (*ptr && ap_isspace(*ptr))
1355 /* find http tokens, see the definition of token from RFC2068 */
1356 API_EXPORT(int) ap_find_token(ap_context_t *p, const char *line, const char *tok)
1358 const unsigned char *start_token;
1359 const unsigned char *s;
1364 s = (const unsigned char *)line;
1366 /* find start of token, skip all stop characters, note NUL
1367 * isn't a token stop, so we don't need to test for it
1369 while (TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1376 /* find end of the token */
1377 while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1380 if (!strncasecmp((const char *)start_token, (const char *)tok, s - start_token)) {
1390 API_EXPORT(int) ap_find_last_token(ap_context_t *p, const char *line, const char *tok)
1392 int llen, tlen, lidx;
1397 llen = strlen(line);
1402 ((lidx > 0) && !(ap_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1405 return (strncasecmp(&line[lidx], tok, tlen) == 0);
1408 API_EXPORT(char *) ap_escape_shell_cmd(ap_context_t *p, const char *str)
1412 const unsigned char *s;
1414 cmd = ap_palloc(p, 2 * strlen(str) + 1); /* Be safe */
1415 d = (unsigned char *)cmd;
1416 s = (const unsigned char *)str;
1419 #if defined(OS2) || defined(WIN32)
1420 /* Don't allow '&' in parameters under OS/2. */
1421 /* This can be used to send commands to the shell. */
1428 if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1438 static char x2c(const char *what)
1440 register char digit;
1442 #ifndef CHARSET_EBCDIC
1443 digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
1445 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
1446 #else /*CHARSET_EBCDIC*/
1453 digit = os_toebcdic[0xFF & strtol(xstr, NULL, 16)];
1454 #endif /*CHARSET_EBCDIC*/
1460 * Returns 0 on success, non-zero on error
1462 * bad % escape returns BAD_REQUEST
1464 * decoding %00 -> \0
1465 * decoding %2f -> / (a special character)
1468 API_EXPORT(int) ap_unescape_url(char *url)
1470 register int badesc, badpath;
1475 /* Initial scan for first '%'. Don't bother writing values before
1477 y = strchr(url, '%');
1481 for (x = y; *y; ++x, ++y) {
1485 if (!ap_isxdigit(*(y + 1)) || !ap_isxdigit(*(y + 2))) {
1492 if (*x == '/' || *x == '\0')
1506 API_EXPORT(char *) ap_construct_server(ap_context_t *p, const char *hostname,
1507 unsigned port, const request_rec *r)
1509 if (ap_is_default_port(port, r))
1510 return ap_pstrdup(p, hostname);
1512 return ap_psprintf(p, "%s:%u", hostname, port);
1516 /* c2x takes an unsigned, and expects the caller has guaranteed that
1517 * 0 <= what < 256... which usually means that you have to cast to
1518 * unsigned char first, because (unsigned)(char)(x) fist goes through
1519 * signed extension to an int before the unsigned cast.
1521 * The reason for this assumption is to assist gcc code generation --
1522 * the unsigned char -> unsigned extension is already done earlier in
1523 * both uses of this code, so there's no need to waste time doing it
1526 static const char c2x_table[] = "0123456789abcdef";
1528 static ap_inline unsigned char *c2x(unsigned what, unsigned char *where)
1531 *where++ = c2x_table[what >> 4];
1532 *where++ = c2x_table[what & 0xf];
1537 * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
1538 * routine is (should be) OS independent.
1540 * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
1541 * cases if a ':' occurs before the first '/' in the URL, the URL should be
1542 * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
1543 * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
1544 * efficiency reasons, we don't use escape_path_segment(), which is provided for
1545 * reference. Again, RFC 1808 is where this stuff is defined.
1547 * If partial is set, os_escape_path() assumes that the path will be appended to
1548 * something with a '/' in it (and thus does not prefix "./").
1551 API_EXPORT(char *) ap_escape_path_segment(ap_context_t *p, const char *segment)
1553 char *copy = ap_palloc(p, 3 * strlen(segment) + 1);
1554 const unsigned char *s = (const unsigned char *)segment;
1555 unsigned char *d = (unsigned char *)copy;
1559 if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
1571 API_EXPORT(char *) ap_os_escape_path(ap_context_t *p, const char *path, int partial)
1573 char *copy = ap_palloc(p, 3 * strlen(path) + 3);
1574 const unsigned char *s = (const unsigned char *)path;
1575 unsigned char *d = (unsigned char *)copy;
1579 char *colon = strchr(path, ':');
1580 char *slash = strchr(path, '/');
1582 if (colon && (!slash || colon < slash)) {
1588 if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
1600 /* ap_escape_uri is now a macro for os_escape_path */
1602 API_EXPORT(char *) ap_escape_html(ap_context_t *p, const char *s)
1607 /* first, count the number of extra characters */
1608 for (i = 0, j = 0; s[i] != '\0'; i++)
1609 if (s[i] == '<' || s[i] == '>')
1611 else if (s[i] == '&')
1615 return ap_pstrndup(p, s, i);
1617 x = ap_palloc(p, i + j + 1);
1618 for (i = 0, j = 0; s[i] != '\0'; i++, j++)
1620 memcpy(&x[j], "<", 4);
1623 else if (s[i] == '>') {
1624 memcpy(&x[j], ">", 4);
1627 else if (s[i] == '&') {
1628 memcpy(&x[j], "&", 5);
1638 API_EXPORT(int) ap_is_directory(const char *path)
1642 /* ZZZ replace with AP File Info func. */
1643 if (stat(path, &finfo) == -1)
1644 return 0; /* in error condition, just return no */
1646 return (S_ISDIR(finfo.st_mode));
1649 API_EXPORT(char *) ap_make_full_path(ap_context_t *a, const char *src1,
1656 return ap_pstrcat(a, "/", src2, NULL);
1658 if (src1[x - 1] != '/')
1659 return ap_pstrcat(a, src1, "/", src2, NULL);
1661 return ap_pstrcat(a, src1, src2, NULL);
1665 * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
1667 API_EXPORT(int) ap_is_url(const char *u)
1671 for (x = 0; u[x] != ':'; x++) {
1673 ((!ap_isalpha(u[x])) && (!ap_isdigit(u[x])) &&
1674 (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
1679 return (x ? 1 : 0); /* If the first character is ':', it's broken, too */
1683 char *strdup(const char *str)
1687 if (!(sdup = (char *) malloc(strlen(str) + 1))) {
1688 fprintf(stderr, "Ouch! Out of memory in our strdup()!\n");
1691 sdup = strcpy(sdup, str);
1697 /* The following two routines were donated for SVR4 by Andreas Vogel */
1698 #ifdef NEED_STRCASECMP
1699 int strcasecmp(const char *a, const char *b)
1703 for (p = a, q = b; *p && *q; p++, q++) {
1704 int diff = ap_tolower(*p) - ap_tolower(*q);
1709 return 1; /* p was longer than q */
1711 return -1; /* p was shorter than q */
1712 return 0; /* Exact match */
1717 #ifdef NEED_STRNCASECMP
1718 int strncasecmp(const char *a, const char *b, int n)
1723 for (p = a, q = b; /*NOTHING */ ; p++, q++) {
1726 return 0; /* Match up to n characters */
1729 diff = ap_tolower(*p) - ap_tolower(*q);
1737 /* The following routine was donated for UTS21 by dwd@bell-labs.com */
1739 char *strstr(char *s1, char *s2)
1746 while((s1 = strchr(s1, *s2)) != NULL) {
1747 /* found first character of s2, see if the rest matches */
1750 while (*++p1 == *++p2) {
1752 /* both strings ended together */
1757 /* second string ended, a match */
1760 /* didn't find a match here, try starting at next character in s1 */
1767 #ifdef NEED_INITGROUPS
1768 int initgroups(const char *name, gid_t basegid)
1770 #if defined(QNX) || defined(MPE) || defined(BEOS) || defined(_OSD_POSIX) || defined(TPF) || defined(__TANDEM)
1771 /* QNX, MPE and BeOS do not appear to support supplementary groups. */
1773 #else /* ndef QNX */
1774 gid_t groups[NGROUPS_MAX];
1780 groups[index++] = basegid;
1782 while (index < NGROUPS_MAX && ((g = getgrent()) != NULL))
1783 if (g->gr_gid != basegid) {
1786 for (names = g->gr_mem; *names != NULL; ++names)
1787 if (!strcmp(*names, name))
1788 groups[index++] = g->gr_gid;
1793 return setgroups(index, groups);
1794 #endif /* def QNX */
1796 #endif /* def NEED_INITGROUPS */
1799 /* From ikluft@amdahl.com
1800 * this is not ideal but it works for SVR3 variants
1801 * Modified by dwd@bell-labs.com to call wait3 instead of wait because
1802 * apache started to use the WNOHANG option.
1804 int waitpid(pid_t pid, int *statusp, int options)
1807 if (kill(pid, 0) == -1) {
1811 while (((tmp_pid = wait3(statusp, options, 0)) != pid) &&
1812 (tmp_pid != -1) && (tmp_pid != 0) && (pid != -1))
1818 API_EXPORT(int) ap_ind(const char *s, char c)
1822 for (x = 0; s[x]; x++)
1829 API_EXPORT(int) ap_rind(const char *s, char c)
1833 for (x = strlen(s) - 1; x != -1; x--)
1840 API_EXPORT(void) ap_str_tolower(char *str)
1843 *str = ap_tolower(*str);
1848 API_EXPORT(uid_t) ap_uname2id(const char *name)
1856 return (atoi(&name[1]));
1858 if (!(ent = getpwnam(name))) {
1859 fprintf(stderr, "%s: bad user name %s\n", ap_server_argv0, name);
1862 return (ent->pw_uid);
1866 API_EXPORT(gid_t) ap_gname2id(const char *name)
1874 return (atoi(&name[1]));
1876 if (!(ent = getgrnam(name))) {
1877 fprintf(stderr, "%s: bad group name %s\n", ap_server_argv0, name);
1880 return (ent->gr_gid);
1886 * Parses a host of the form <address>[:port]
1887 * :port is permitted if 'port' is not NULL
1889 unsigned long ap_get_virthost_addr(char *w, unsigned short *ports)
1891 /* ZZZ Redesign for AP func changes */
1892 struct hostent *hep;
1893 unsigned long my_addr;
1897 if (ports != NULL) {
1899 if (p != NULL && strcmp(p + 1, "*") != 0)
1900 *ports = atoi(p + 1);
1905 if (strcmp(w, "*") == 0) {
1908 return htonl(INADDR_ANY);
1911 my_addr = ap_inet_addr((char *)w);
1912 if (my_addr != INADDR_NONE) {
1918 hep = gethostbyname(w);
1920 if ((!hep) || (hep->h_addrtype != AF_INET || !hep->h_addr_list[0])) {
1921 fprintf(stderr, "Cannot resolve host name %s --- exiting!\n", w);
1925 if (hep->h_addr_list[1]) {
1926 fprintf(stderr, "Host %s has multiple addresses ---\n", w);
1927 fprintf(stderr, "you must choose one explicitly for use as\n");
1928 fprintf(stderr, "a virtual host. Exiting!!!\n");
1935 return ((struct in_addr *) (hep->h_addr))->s_addr;
1939 static char *find_fqdn(ap_context_t *a, struct hostent *p)
1943 if (!strchr(p->h_name, '.')) {
1944 for (x = 0; p->h_aliases[x]; ++x) {
1945 if (strchr(p->h_aliases[x], '.') &&
1946 (!strncasecmp(p->h_aliases[x], p->h_name, strlen(p->h_name))))
1947 return ap_pstrdup(a, p->h_aliases[x]);
1951 return ap_pstrdup(a, (void *) p->h_name);
1954 char *ap_get_local_host(ap_context_t *a)
1956 #ifndef MAXHOSTNAMELEN
1957 #define MAXHOSTNAMELEN 256
1959 char str[MAXHOSTNAMELEN + 1];
1960 char *server_hostname;
1963 /* ZZZ change to use AP funcs. */
1965 if (gethostname(str, sizeof(str) - 1) == 0)
1967 if (gethostname(str, sizeof(str) - 1) != 0)
1970 perror("Unable to gethostname");
1973 str[MAXHOSTNAMELEN] = '\0';
1974 if ((!(p = gethostbyname(str))) || (!(server_hostname = find_fqdn(a, p)))) {
1975 fprintf(stderr, "%s: cannot determine local host name.\n",
1977 fprintf(stderr, "Use the ServerName directive to set it manually.\n");
1981 return server_hostname;
1984 /* simple 'pool' alloc()ing glue to ap_base64.c
1986 API_EXPORT(char *) ap_pbase64decode(ap_context_t *p, const char *bufcoded)
1991 decoded = (char *) ap_palloc(p, 1 + ap_base64decode_len(bufcoded));
1992 l = ap_base64decode(decoded, bufcoded);
1993 decoded[l] = '\0'; /* make binary sequence into string */
1998 API_EXPORT(char *) ap_pbase64encode(ap_context_t *p, char *string)
2001 int l = strlen(string);
2003 encoded = (char *) ap_palloc(p, 1 + ap_base64encode_len(l));
2004 l = ap_base64encode(encoded, string, l);
2005 encoded[l] = '\0'; /* make binary sequence into string */
2010 /* deprecated names for the above two functions, here for compatibility
2012 API_EXPORT(char *) ap_uudecode(ap_context_t *p, const char *bufcoded)
2014 return ap_pbase64decode(p, bufcoded);
2017 API_EXPORT(char *) ap_uuencode(ap_context_t *p, char *string)
2019 return ap_pbase64encode(p, string);
2023 void os2pathname(char *path)
2025 char newpath[MAX_STRING_LEN];
2030 for (loop = 0; loop < (strlen(path) + 1) && loop < sizeof(newpath) - 1; loop++) {
2031 if (path[loop] == '/') {
2032 newpath[offset] = '\\';
2034 offset = offset + 1;
2035 newpath[offset] = '\\';
2039 newpath[offset] = path[loop];
2040 offset = offset + 1;
2042 /* Debugging code */
2043 /* fprintf(stderr, "%s \n", newpath); */
2045 strcpy(path, newpath);
2048 /* quotes in the string are doubled up.
2049 * Used to escape quotes in args passed to OS/2's cmd.exe
2051 char *ap_double_quotes(ap_context_t *p, char *str)
2055 char *quote_doubled_str, *dest;
2058 num_quotes += str[len++] == '\"';
2061 quote_doubled_str = ap_palloc(p, len + num_quotes + 1);
2062 dest = quote_doubled_str;
2067 *(dest++) = *(str++);
2071 return quote_doubled_str;
2076 #ifdef NEED_STRERROR
2082 extern char *const sys_errlist[];
2084 p = sys_errlist[err];
2089 #if defined(NEED_DIFFTIME)
2090 double difftime(time_t time1, time_t time0)
2092 return (time1 - time0);
2096 /* we want to downcase the type/subtype for comparison purposes
2097 * but nothing else because ;parameter=foo values are case sensitive.
2098 * XXX: in truth we want to downcase parameter names... but really,
2099 * apache has never handled parameters and such correctly. You
2100 * also need to compress spaces and such to be able to compare
2103 API_EXPORT(void) ap_content_type_tolower(char *str)
2107 semi = strchr(str, ';');
2112 *str = ap_tolower(*str);
2121 * Given a string, replace any bare " with \" .
2123 API_EXPORT(char *) ap_escape_quotes (ap_context_t *p, const char *instring)
2126 const char *inchr = instring;
2127 char *outchr, *outstring;
2130 * Look through the input string, jogging the length of the output
2131 * string up by an extra byte each time we find an unescaped ".
2133 while (*inchr != '\0') {
2135 if (*inchr == '"') {
2139 * If we find a slosh, and it's not the last byte in the string,
2140 * it's escaping something - advance past both bytes.
2142 if ((*inchr == '\\') && (inchr[1] != '\0')) {
2148 outstring = ap_palloc(p, newlen + 1);
2152 * Now copy the input string to the output string, inserting a slosh
2153 * in front of every " that doesn't already have one.
2155 while (*inchr != '\0') {
2156 if ((*inchr == '\\') && (inchr[1] != '\0')) {
2157 *outchr++ = *inchr++;
2158 *outchr++ = *inchr++;
2160 if (*inchr == '"') {
2163 if (*inchr != '\0') {
2164 *outchr++ = *inchr++;