1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/urlmatch.c,v $
5 * Purpose : Declares functions to match URLs against URL
8 * Copyright : Written by and Copyright (C) 2001-2020
9 * the Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
40 #include <sys/types.h>
48 #if !defined(_WIN32) && !defined(__OS2__)
65 static jb_err compile_vanilla_host_pattern(struct pattern_spec *url, const char *host_pattern);
66 #ifdef FEATURE_PCRE_HOST_PATTERNS
67 static jb_err compile_pcre_host_pattern(struct pattern_spec *url, const char *host_pattern);
70 /*********************************************************************
72 * Function : free_http_request
74 * Description : Freez a http_request structure
77 * 1 : http = points to a http_request structure to free
81 *********************************************************************/
82 void free_http_request(struct http_request *http)
91 freez(http->hostport);
94 freez(http->host_ip_addr_str);
101 /*********************************************************************
103 * Function : init_domain_components
105 * Description : Splits the domain name so we can compare it
106 * against wildcards. It used to be part of
107 * parse_http_url, but was separated because the
108 * same code is required in chat in case of
109 * intercepted requests.
112 * 1 : http = pointer to the http structure to hold elements.
114 * Returns : JB_ERR_OK on success
115 * JB_ERR_PARSE on malformed command/URL
116 * or >100 domains deep.
118 *********************************************************************/
119 jb_err init_domain_components(struct http_request *http)
121 char *vec[BUFFER_SIZE];
125 http->dbuffer = strdup_or_die(http->host);
127 /* map to lower case */
128 for (p = http->dbuffer; *p ; p++)
130 *p = (char)privoxy_tolower(*p);
133 /* split the domain name into components */
134 http->dcount = ssplit(http->dbuffer, ".", vec, SZ(vec));
136 if (http->dcount <= 0)
139 * Error: More than SZ(vec) components in domain
140 * or: no components in domain
142 log_error(LOG_LEVEL_ERROR, "More than SZ(vec) components in domain or none at all.");
146 /* save a copy of the pointers in dvec */
147 size = (size_t)http->dcount * sizeof(*http->dvec);
149 http->dvec = malloc_or_die(size);
151 memcpy(http->dvec, vec, size);
157 /*********************************************************************
159 * Function : url_requires_percent_encoding
161 * Description : Checks if an URL contains invalid characters
162 * according to RFC 3986 that should be percent-encoded.
163 * Does not verify whether or not the passed string
164 * actually is a valid URL.
167 * 1 : url = URL to check
169 * Returns : True in case of valid URLs, false otherwise
171 *********************************************************************/
172 int url_requires_percent_encoding(const char *url)
174 static const char allowed_characters[128] = {
175 '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
176 '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
177 '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
178 '\0', '\0', '\0', '!', '\0', '#', '$', '%', '&', '\'',
179 '(', ')', '*', '+', ',', '-', '.', '/', '0', '1',
180 '2', '3', '4', '5', '6', '7', '8', '9', ':', ';',
181 '\0', '=', '\0', '?', '@', 'A', 'B', 'C', 'D', 'E',
182 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
183 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
184 'Z', '[', '\0', ']', '\0', '_', '\0', 'a', 'b', 'c',
185 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
186 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
187 'x', 'y', 'z', '\0', '\0', '\0', '~', '\0'
192 const unsigned int i = (unsigned char)*url++;
193 if (i >= sizeof(allowed_characters) || '\0' == allowed_characters[i])
204 /*********************************************************************
206 * Function : parse_http_url
208 * Description : Parse out the host and port from the URL. Find the
209 * hostname & path, port (if ':'), and/or password (if '@')
212 * 1 : url = URL (or is it URI?) to break down
213 * 2 : http = pointer to the http structure to hold elements.
214 * Must be initialized with valid values (like NULLs).
215 * 3 : require_protocol = Whether or not URLs without
216 * protocol are acceptable.
218 * Returns : JB_ERR_OK on success
219 * JB_ERR_PARSE on malformed command/URL
220 * or >100 domains deep.
222 *********************************************************************/
223 jb_err parse_http_url(const char *url, struct http_request *http, int require_protocol)
225 int host_available = 1; /* A proxy can dream. */
228 * Save our initial URL
230 http->url = strdup_or_die(url);
233 * Check for * URI. If found, we're done.
235 if (*http->url == '*')
237 http->path = strdup_or_die("*");
238 http->hostport = strdup_or_die("");
239 if (http->url[1] != '\0')
248 * Split URL into protocol,hostport,path.
255 buf = strdup_or_die(url);
257 /* Find the start of the URL in our scratch space */
259 if (strncmpic(url_noproto, "http://", 7) == 0)
263 else if (strncmpic(url_noproto, "https://", 8) == 0)
266 * Should only happen when called from cgi_show_url_info().
271 else if (*url_noproto == '/')
274 * Short request line without protocol and host.
275 * Most likely because the client's request
276 * was intercepted and redirected into Privoxy.
281 else if (require_protocol)
287 url_path = strchr(url_noproto, '/');
288 if (url_path != NULL)
293 * If FEATURE_HTTPS_INSPECTION isn't available, ignore the
294 * path for https URLs so that we get consistent behaviour
295 * if a https URL is parsed. When the URL is actually
296 * retrieved, https hides the path part.
298 http->path = strdup_or_die(
299 #ifndef FEATURE_HTTPS_INSPECTION
305 http->hostport = strdup_or_die(url_noproto);
310 * Repair broken HTTP requests that don't contain a path,
311 * or CONNECT requests
313 http->path = strdup_or_die("/");
314 http->hostport = strdup_or_die(url_noproto);
322 /* Without host, there is nothing left to do here */
327 * Split hostport into user/password (ignored), host, port.
334 buf = strdup_or_die(http->hostport);
336 /* check if url contains username and/or password */
337 host = strchr(buf, '@');
340 /* Contains username/password, skip it and the @ sign. */
345 /* No username or password. */
349 /* Move after hostname before port number */
352 /* Numeric IPv6 address delimited by brackets */
354 port = strchr(host, ']');
358 /* Missing closing bracket */
369 else if (*port != ':')
371 /* Garbage after closing bracket */
378 /* Plain non-escaped hostname */
379 port = strchr(host, ':');
382 /* check if url contains port */
388 /* Terminate hostname and point to start of port string */
390 parsed_port = strtol(port, &endptr, 10);
391 if ((parsed_port <= 0) || (parsed_port > 65535) || (*endptr != '\0'))
393 log_error(LOG_LEVEL_ERROR, "Invalid port in URL: %s.", url);
397 http->port = (int)parsed_port;
401 /* No port specified. */
402 http->port = (http->ssl ? 443 : 80);
405 http->host = strdup_or_die(host);
410 /* Split domain name so we can compare it against wildcards */
411 return init_domain_components(http);
416 /*********************************************************************
418 * Function : unknown_method
420 * Description : Checks whether a method is unknown.
423 * 1 : method = points to a http method
425 * Returns : TRUE if it's unknown, FALSE otherwise.
427 *********************************************************************/
428 static int unknown_method(const char *method)
430 static const char * const known_http_methods[] = {
431 /* Basic HTTP request type */
432 "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CONNECT",
433 /* webDAV extensions (RFC2518) */
434 "PROPFIND", "PROPPATCH", "MOVE", "COPY", "MKCOL", "LOCK", "UNLOCK",
436 * Microsoft webDAV extension for Exchange 2000. See:
437 * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
438 * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
440 "BCOPY", "BMOVE", "BDELETE", "BPROPFIND", "BPROPPATCH",
442 * Another Microsoft webDAV extension for Exchange 2000. See:
443 * http://systems.cs.colorado.edu/grunwald/MobileComputing/Papers/draft-cohen-gena-p-base-00.txt
444 * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
445 * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
447 "SUBSCRIBE", "UNSUBSCRIBE", "NOTIFY", "POLL",
449 * Yet another WebDAV extension, this time for
450 * Web Distributed Authoring and Versioning (RFC3253)
452 "VERSION-CONTROL", "REPORT", "CHECKOUT", "CHECKIN", "UNCHECKOUT",
453 "MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL", "MKACTIVITY",
455 * The PATCH method is defined by RFC5789, the format of the
456 * actual patch in the body depends on the application, but from
457 * Privoxy's point of view it doesn't matter.
463 for (i = 0; i < SZ(known_http_methods); i++)
465 if (0 == strcmpic(method, known_http_methods[i]))
476 /*********************************************************************
478 * Function : normalize_http_version
480 * Description : Take a supported HTTP version string and remove
481 * leading zeroes etc., reject unsupported versions.
483 * This is an explicit RFC 2616 (3.1) MUST and
484 * RFC 7230 mandates that intermediaries send their
485 * own HTTP-version in forwarded messages.
488 * 1 : http_version = HTTP version string
490 * Returns : JB_ERR_OK on success
491 * JB_ERR_PARSE if the HTTP version is unsupported
493 *********************************************************************/
494 static jb_err normalize_http_version(char *http_version)
496 unsigned int major_version;
497 unsigned int minor_version;
499 if (2 != sscanf(http_version, "HTTP/%u.%u", &major_version, &minor_version))
501 log_error(LOG_LEVEL_ERROR, "Unsupported HTTP version: %s", http_version);
505 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
507 log_error(LOG_LEVEL_ERROR, "The only supported HTTP "
508 "versions are 1.0 and 1.1. This rules out: %s", http_version);
512 assert(strlen(http_version) >= 8);
513 snprintf(http_version, 9, "HTTP/%u.%u", major_version, minor_version);
520 /*********************************************************************
522 * Function : parse_http_request
524 * Description : Parse out the host and port from the URL. Find the
525 * hostname & path, port (if ':'), and/or password (if '@')
528 * 1 : req = HTTP request line to break down
529 * 2 : http = pointer to the http structure to hold elements
531 * Returns : JB_ERR_OK on success
532 * JB_ERR_CGI_PARAMS on malformed command/URL
533 * or >100 domains deep.
535 *********************************************************************/
536 jb_err parse_http_request(const char *req, struct http_request *http)
543 memset(http, '\0', sizeof(*http));
545 buf = strdup_or_die(req);
547 n = ssplit(buf, " \r\n", v, SZ(v));
555 * Fail in case of unknown methods
556 * which we might not handle correctly.
558 * XXX: There should be a config option
559 * to forward requests with unknown methods
560 * anyway. Most of them don't need special
563 if (unknown_method(v[0]))
565 log_error(LOG_LEVEL_ERROR, "Unknown HTTP method detected: %s", v[0]);
570 if (JB_ERR_OK != normalize_http_version(v[2]))
576 http->ssl = !strcmpic(v[0], "CONNECT");
578 err = parse_http_url(v[1], http, !http->ssl);
586 * Copy the details into the structure
588 http->cmd = strdup_or_die(req);
589 http->gpc = strdup_or_die(v[0]);
590 http->version = strdup_or_die(v[2]);
591 http->ocmd = strdup_or_die(http->cmd);
600 /*********************************************************************
602 * Function : compile_pattern
604 * Description : Compiles a host, domain or TAG pattern.
607 * 1 : pattern = The pattern to compile.
608 * 2 : anchoring = How the regex should be modified
609 * before compilation. Can be either
610 * one of NO_ANCHORING, LEFT_ANCHORED,
611 * RIGHT_ANCHORED or RIGHT_ANCHORED_HOST.
612 * 3 : url = In case of failures, the spec member is
613 * logged and the structure freed.
614 * 4 : regex = Where the compiled regex should be stored.
616 * Returns : JB_ERR_OK - Success
617 * JB_ERR_PARSE - Cannot parse regex
619 *********************************************************************/
620 static jb_err compile_pattern(const char *pattern, enum regex_anchoring anchoring,
621 struct pattern_spec *url, regex_t **regex)
624 const char *fmt = NULL;
630 if (pattern[0] == '\0')
644 case RIGHT_ANCHORED_HOST:
651 log_error(LOG_LEVEL_FATAL,
652 "Invalid anchoring in compile_pattern %d", anchoring);
654 rebuf_size = strlen(pattern) + strlen(fmt);
655 rebuf = malloc_or_die(rebuf_size);
656 *regex = zalloc_or_die(sizeof(**regex));
658 snprintf(rebuf, rebuf_size, fmt, pattern);
660 errcode = regcomp(*regex, rebuf, (REG_EXTENDED|REG_NOSUB|REG_ICASE));
664 size_t errlen = regerror(errcode, *regex, rebuf, rebuf_size);
665 if (errlen > (rebuf_size - (size_t)1))
667 errlen = rebuf_size - (size_t)1;
669 rebuf[errlen] = '\0';
670 log_error(LOG_LEVEL_ERROR, "error compiling %s from %s: %s",
671 pattern, url->spec, rebuf);
672 free_pattern_spec(url);
684 /*********************************************************************
686 * Function : compile_url_pattern
688 * Description : Compiles the three parts of an URL pattern.
691 * 1 : url = Target pattern_spec to be filled in.
692 * 2 : buf = The url pattern to compile. Will be messed up.
694 * Returns : JB_ERR_OK - Success
695 * JB_ERR_MEMORY - Out of memory
696 * JB_ERR_PARSE - Cannot parse regex
698 *********************************************************************/
699 static jb_err compile_url_pattern(struct pattern_spec *url, char *buf)
703 #ifdef FEATURE_PCRE_HOST_PATTERNS
704 const size_t prefix_length = 18;
705 if (strncmpic(buf, "PCRE-HOST-PATTERN:", prefix_length) == 0)
707 url->pattern.url_spec.host_regex_type = PCRE_HOST_PATTERN;
708 /* Overwrite the "PCRE-HOST-PATTERN:" prefix */
709 memmove(buf, buf+prefix_length, strlen(buf+prefix_length)+1);
713 url->pattern.url_spec.host_regex_type = VANILLA_HOST_PATTERN;
717 p = strchr(buf, '/');
721 * Only compile the regex if it consists of more than
722 * a single slash, otherwise it wouldn't affect the result.
727 * XXX: does it make sense to compile the slash at the beginning?
729 jb_err err = compile_pattern(p, LEFT_ANCHORED, url, &url->pattern.url_spec.preg);
731 if (JB_ERR_OK != err)
740 * IPv6 numeric hostnames can contain colons, thus we need
741 * to delimit the hostname before the real port separator.
742 * As brackets are already used in the hostname pattern,
743 * we use angle brackets ('<', '>') instead.
745 if ((buf[0] == '<') && (NULL != (p = strchr(buf + 1, '>'))))
752 /* IPv6 address without port number */
757 /* Garbage after address delimiter */
763 p = strchr(buf, ':');
769 url->pattern.url_spec.port_list = strdup_or_die(p);
773 url->pattern.url_spec.port_list = NULL;
778 #ifdef FEATURE_PCRE_HOST_PATTERNS
779 if (url->pattern.url_spec.host_regex_type == PCRE_HOST_PATTERN)
781 return compile_pcre_host_pattern(url, buf);
786 return compile_vanilla_host_pattern(url, buf);
795 #ifdef FEATURE_PCRE_HOST_PATTERNS
796 /*********************************************************************
798 * Function : compile_pcre_host_pattern
800 * Description : Parses and compiles a pcre host pattern.
803 * 1 : url = Target pattern_spec to be filled in.
804 * 2 : host_pattern = Host pattern to compile.
806 * Returns : JB_ERR_OK - Success
807 * JB_ERR_MEMORY - Out of memory
808 * JB_ERR_PARSE - Cannot parse regex
810 *********************************************************************/
811 static jb_err compile_pcre_host_pattern(struct pattern_spec *url, const char *host_pattern)
813 return compile_pattern(host_pattern, RIGHT_ANCHORED_HOST, url, &url->pattern.url_spec.host_regex);
815 #endif /* def FEATURE_PCRE_HOST_PATTERNS */
818 /*********************************************************************
820 * Function : compile_vanilla_host_pattern
822 * Description : Parses and "compiles" an old-school host pattern.
825 * 1 : url = Target pattern_spec to be filled in.
826 * 2 : host_pattern = Host pattern to parse.
828 * Returns : JB_ERR_OK - Success
829 * JB_ERR_PARSE - Cannot parse regex
831 *********************************************************************/
832 static jb_err compile_vanilla_host_pattern(struct pattern_spec *url, const char *host_pattern)
841 if (host_pattern[strlen(host_pattern) - 1] == '.')
843 url->pattern.url_spec.unanchored |= ANCHOR_RIGHT;
845 if (host_pattern[0] == '.')
847 url->pattern.url_spec.unanchored |= ANCHOR_LEFT;
851 * Split domain into components
853 url->pattern.url_spec.dbuffer = strdup_or_die(host_pattern);
858 for (p = url->pattern.url_spec.dbuffer; *p ; p++)
860 *p = (char)privoxy_tolower(*p);
864 * Split the domain name into components
866 url->pattern.url_spec.dcount = ssplit(url->pattern.url_spec.dbuffer, ".", v, SZ(v));
868 if (url->pattern.url_spec.dcount < 0)
870 free_pattern_spec(url);
873 else if (url->pattern.url_spec.dcount != 0)
876 * Save a copy of the pointers in dvec
878 size = (size_t)url->pattern.url_spec.dcount * sizeof(*url->pattern.url_spec.dvec);
880 url->pattern.url_spec.dvec = malloc_or_die(size);
882 memcpy(url->pattern.url_spec.dvec, v, size);
885 * else dcount == 0 in which case we needn't do anything,
886 * since dvec will never be accessed and the pattern will
893 /*********************************************************************
895 * Function : simplematch
897 * Description : String matching, with a (greedy) '*' wildcard that
898 * stands for zero or more arbitrary characters and
899 * character classes in [], which take both enumerations
903 * 1 : pattern = pattern for matching
904 * 2 : text = text to be matched
906 * Returns : 0 if match, else nonzero
908 *********************************************************************/
909 static int simplematch(const char *pattern, const char *text)
911 const unsigned char *pat = (const unsigned char *)pattern;
912 const unsigned char *txt = (const unsigned char *)text;
913 const unsigned char *fallback = pat;
916 unsigned char lastchar = 'a';
918 unsigned char charmap[32];
923 /* EOF pattern but !EOF text? */
936 /* '*' in the pattern? */
940 /* The pattern ends afterwards? Speed up the return. */
946 /* Else, set wildcard mode and remember position after '*' */
951 /* Character range specification? */
954 memset(charmap, '\0', sizeof(charmap));
956 while (*++pat != ']')
962 else if (*pat == '-')
964 if ((*++pat == ']') || *pat == '\0')
968 for (i = lastchar; i <= *pat; i++)
970 charmap[i / 8] |= (unsigned char)(1 << (i % 8));
975 charmap[*pat / 8] |= (unsigned char)(1 << (*pat % 8));
979 } /* -END- if Character range specification */
983 * Char match, or char range match?
987 || ((*pat == ']') && (charmap[*txt / 8] & (1 << (*txt % 8)))))
997 * No match && no wildcard: No luck
1001 else if (pat != fallback)
1004 * Increment text pointer if in char range matching
1011 * Wildcard mode && nonmatch beyond fallback: Rewind pattern
1015 * Restart matching from current text pointer
1022 /* Cut off extra '*'s */
1023 if (*pat == '*') pat++;
1025 /* If this is the pattern's end, fine! */
1031 /*********************************************************************
1033 * Function : simple_domaincmp
1035 * Description : Domain-wise Compare fqdn's. The comparison is
1036 * both left- and right-anchored. The individual
1037 * domain names are compared with simplematch().
1038 * This is only used by domain_match.
1041 * 1 : pv = array of patterns to compare
1042 * 2 : fv = array of domain components to compare
1043 * 3 : len = length of the arrays (both arrays are the
1044 * same length - if they weren't, it couldn't
1045 * possibly be a match).
1047 * Returns : 0 => domains are equivalent, else no match.
1049 *********************************************************************/
1050 static int simple_domaincmp(char **pv, char **fv, int len)
1054 for (n = 0; n < len; n++)
1056 if (simplematch(pv[n], fv[n]))
1067 /*********************************************************************
1069 * Function : domain_match
1071 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1072 * p.pattern->unachored, the comparison is un-, left-,
1073 * right-anchored, or both.
1074 * The individual domain names are compared with
1078 * 1 : p = a domain that may contain a '*' as a wildcard.
1079 * 2 : fqdn = domain name against which the patterns are compared.
1081 * Returns : 0 => domains are equivalent, else no match.
1083 *********************************************************************/
1084 static int domain_match(const struct pattern_spec *p, const struct http_request *fqdn)
1086 char **pv, **fv; /* vectors */
1088 int unanchored = p->pattern.url_spec.unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1090 plen = p->pattern.url_spec.dcount;
1091 flen = fqdn->dcount;
1095 /* fqdn is too short to match this pattern */
1099 pv = p->pattern.url_spec.dvec;
1102 if (unanchored == ANCHOR_LEFT)
1107 * Convert this into a fully anchored pattern with
1108 * the fqdn and pattern the same length
1110 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1111 return simple_domaincmp(pv, fv, plen);
1113 else if (unanchored == 0)
1115 /* Fully anchored, check length */
1120 return simple_domaincmp(pv, fv, plen);
1122 else if (unanchored == ANCHOR_RIGHT)
1124 /* Left anchored, ignore all extra in fqdn */
1125 return simple_domaincmp(pv, fv, plen);
1131 int maxn = flen - plen;
1132 for (n = 0; n <= maxn; n++)
1134 if (!simple_domaincmp(pv, fv, plen))
1139 * Doesn't match from start of fqdn
1140 * Try skipping first part of fqdn
1150 /*********************************************************************
1152 * Function : create_pattern_spec
1154 * Description : Creates a "pattern_spec" structure from a string.
1155 * When finished, free with free_pattern_spec().
1158 * 1 : pattern = Target pattern_spec to be filled in.
1159 * Will be zeroed before use.
1160 * 2 : buf = Source pattern, null terminated. NOTE: The
1161 * contents of this buffer are destroyed by this
1162 * function. If this function succeeds, the
1163 * buffer is copied to pattern->spec. If this
1164 * function fails, the contents of the buffer
1167 * Returns : JB_ERR_OK - Success
1168 * JB_ERR_PARSE - Cannot parse regex (Detailed message
1169 * written to system log)
1171 *********************************************************************/
1172 jb_err create_pattern_spec(struct pattern_spec *pattern, char *buf)
1176 /** The tag pattern prefix to match */
1179 /** The length of the prefix to match */
1180 const size_t prefix_length;
1182 /** The pattern flag */
1183 const unsigned flag;
1185 { "TAG:", 4, PATTERN_SPEC_TAG_PATTERN},
1186 #ifdef FEATURE_CLIENT_TAGS
1187 { "CLIENT-TAG:", 11, PATTERN_SPEC_CLIENT_TAG_PATTERN},
1189 { "NO-REQUEST-TAG:", 15, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN},
1190 { "NO-RESPONSE-TAG:", 16, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN}
1197 memset(pattern, '\0', sizeof(*pattern));
1199 /* Remember the original specification for the CGI pages. */
1200 pattern->spec = strdup_or_die(buf);
1202 /* Check if it's a tag pattern */
1203 for (i = 0; i < SZ(tag_pattern); i++)
1205 if (0 == strncmpic(pattern->spec, tag_pattern[i].prefix, tag_pattern[i].prefix_length))
1207 /* The regex starts after the prefix */
1208 const char *tag_regex = buf + tag_pattern[i].prefix_length;
1210 pattern->flags |= tag_pattern[i].flag;
1212 return compile_pattern(tag_regex, NO_ANCHORING, pattern,
1213 &pattern->pattern.tag_regex);
1217 /* If it isn't a tag pattern it must be an URL pattern. */
1218 pattern->flags |= PATTERN_SPEC_URL_PATTERN;
1220 return compile_url_pattern(pattern, buf);
1225 /*********************************************************************
1227 * Function : free_pattern_spec
1229 * Description : Called from the "unloaders". Freez the pattern
1230 * structure elements.
1233 * 1 : pattern = pointer to a pattern_spec structure.
1237 *********************************************************************/
1238 void free_pattern_spec(struct pattern_spec *pattern)
1240 if (pattern == NULL) return;
1242 freez(pattern->spec);
1243 #ifdef FEATURE_PCRE_HOST_PATTERNS
1244 if (pattern->pattern.url_spec.host_regex)
1246 regfree(pattern->pattern.url_spec.host_regex);
1247 freez(pattern->pattern.url_spec.host_regex);
1249 #endif /* def FEATURE_PCRE_HOST_PATTERNS */
1250 freez(pattern->pattern.url_spec.dbuffer);
1251 freez(pattern->pattern.url_spec.dvec);
1252 pattern->pattern.url_spec.dcount = 0;
1253 freez(pattern->pattern.url_spec.port_list);
1254 if (pattern->pattern.url_spec.preg)
1256 regfree(pattern->pattern.url_spec.preg);
1257 freez(pattern->pattern.url_spec.preg);
1259 if (pattern->pattern.tag_regex)
1261 regfree(pattern->pattern.tag_regex);
1262 freez(pattern->pattern.tag_regex);
1267 /*********************************************************************
1269 * Function : port_matches
1271 * Description : Compares a port against a port list.
1274 * 1 : port = The port to check.
1275 * 2 : port_list = The list of port to compare with.
1277 * Returns : TRUE for yes, FALSE otherwise.
1279 *********************************************************************/
1280 static int port_matches(const int port, const char *port_list)
1282 return ((NULL == port_list) || match_portlist(port_list, port));
1286 /*********************************************************************
1288 * Function : host_matches
1290 * Description : Compares a host against a host pattern.
1293 * 1 : url = The URL to match
1294 * 2 : pattern = The URL pattern
1296 * Returns : TRUE for yes, FALSE otherwise.
1298 *********************************************************************/
1299 static int host_matches(const struct http_request *http,
1300 const struct pattern_spec *pattern)
1302 assert(http->host != NULL);
1303 #ifdef FEATURE_PCRE_HOST_PATTERNS
1304 if (pattern->pattern.url_spec.host_regex_type == PCRE_HOST_PATTERN)
1306 return ((NULL == pattern->pattern.url_spec.host_regex)
1307 || (0 == regexec(pattern->pattern.url_spec.host_regex,
1308 http->host, 0, NULL, 0)));
1311 return ((NULL == pattern->pattern.url_spec.dbuffer) || (0 == domain_match(pattern, http)));
1315 /*********************************************************************
1317 * Function : path_matches
1319 * Description : Compares a path against a path pattern.
1322 * 1 : path = The path to match
1323 * 2 : pattern = The URL pattern
1325 * Returns : TRUE for yes, FALSE otherwise.
1327 *********************************************************************/
1328 static int path_matches(const char *path, const struct pattern_spec *pattern)
1330 return ((NULL == pattern->pattern.url_spec.preg)
1331 || (0 == regexec(pattern->pattern.url_spec.preg, path, 0, NULL, 0)));
1335 /*********************************************************************
1337 * Function : url_match
1339 * Description : Compare a URL against a URL pattern.
1342 * 1 : pattern = a URL pattern
1343 * 2 : url = URL to match
1345 * Returns : Nonzero if the URL matches the pattern, else 0.
1347 *********************************************************************/
1348 int url_match(const struct pattern_spec *pattern,
1349 const struct http_request *http)
1351 if (!(pattern->flags & PATTERN_SPEC_URL_PATTERN))
1353 /* It's not an URL pattern and thus shouldn't be matched against URLs */
1357 return (port_matches(http->port, pattern->pattern.url_spec.port_list)
1358 && host_matches(http, pattern) && path_matches(http->path, pattern));
1363 /*********************************************************************
1365 * Function : match_portlist
1367 * Description : Check if a given number is covered by a comma
1368 * separated list of numbers and ranges (a,b-c,d,..)
1371 * 1 : portlist = String with list
1372 * 2 : port = port to check
1374 * Returns : 0 => no match
1377 *********************************************************************/
1378 int match_portlist(const char *portlist, int port)
1380 char *min, *max, *next, *portlist_copy;
1382 min = portlist_copy = strdup_or_die(portlist);
1385 * Zero-terminate first item and remember offset for next
1387 if (NULL != (next = strchr(portlist_copy, (int) ',')))
1393 * Loop through all items, checking for match
1397 if (NULL == (max = strchr(min, (int) '-')))
1400 * No dash, check for equality
1402 if (port == atoi(min))
1404 freez(portlist_copy);
1411 * This is a range, so check if between min and max,
1412 * or, if max was omitted, between min and 65K
1415 if (port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
1417 freez(portlist_copy);
1429 * Zero-terminate next item and remember offset for n+1
1431 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
1437 freez(portlist_copy);
1443 /*********************************************************************
1445 * Function : parse_forwarder_address
1447 * Description : Parse out the username, password, host and port from
1448 * a forwarder address.
1451 * 1 : address = The forwarder address to parse.
1452 * 2 : hostname = Used to return the hostname. NULL on error.
1453 * 3 : port = Used to return the port. Untouched if no port
1455 * 4 : username = Used to return the username if any.
1456 * 5 : password = Used to return the password if any.
1458 * Returns : JB_ERR_OK on success
1459 * JB_ERR_MEMORY on out of memory
1460 * JB_ERR_PARSE on malformed address.
1462 *********************************************************************/
1463 jb_err parse_forwarder_address(char *address, char **hostname, int *port,
1464 char **username, char **password)
1469 tmp = *hostname = strdup_or_die(address);
1471 /* Parse username and password */
1472 if (username && password && (NULL != (p = strchr(*hostname, '@'))))
1475 *username = strdup_or_die(*hostname);
1476 *hostname = strdup_or_die(p);
1478 if (NULL != (p = strchr(*username, ':')))
1481 *password = strdup_or_die(p);
1486 /* Parse hostname and port */
1488 if ((*p == '[') && (NULL == strchr(p, ']')))
1490 /* XXX: Should do some more validity checks here. */
1491 return JB_ERR_PARSE;
1494 if ((**hostname == '[') && (NULL != (p = strchr(*hostname, ']'))))
1497 memmove(*hostname, (*hostname + 1), (size_t)(p - *hostname));
1500 *port = (int)strtol(++p, NULL, 0);
1503 else if (NULL != (p = strchr(*hostname, ':')))
1506 *port = (int)strtol(p, NULL, 0);