1 const char urlmatch_rcs[] = "$Id: urlmatch.c,v 1.83 2014/06/20 09:46:56 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/urlmatch.c,v $
6 * Purpose : Declares functions to match URLs against URL
9 * Copyright : Written by and Copyright (C) 2001-2014
10 * the Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
41 #include <sys/types.h>
49 #if !defined(_WIN32) && !defined(__OS2__)
59 const char urlmatch_h_rcs[] = URLMATCH_H_VERSION;
68 static jb_err compile_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);
95 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
103 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
104 /*********************************************************************
106 * Function : init_domain_components
108 * Description : Splits the domain name so we can compare it
109 * against wildcards. It used to be part of
110 * parse_http_url, but was separated because the
111 * same code is required in chat in case of
112 * intercepted requests.
115 * 1 : http = pointer to the http structure to hold elements.
117 * Returns : JB_ERR_OK on success
118 * JB_ERR_PARSE on malformed command/URL
119 * or >100 domains deep.
121 *********************************************************************/
122 jb_err init_domain_components(struct http_request *http)
124 char *vec[BUFFER_SIZE];
128 http->dbuffer = strdup_or_die(http->host);
130 /* map to lower case */
131 for (p = http->dbuffer; *p ; p++)
133 *p = (char)privoxy_tolower(*p);
136 /* split the domain name into components */
137 http->dcount = ssplit(http->dbuffer, ".", vec, SZ(vec));
139 if (http->dcount <= 0)
142 * Error: More than SZ(vec) components in domain
143 * or: no components in domain
145 log_error(LOG_LEVEL_ERROR, "More than SZ(vec) components in domain or none at all.");
149 /* save a copy of the pointers in dvec */
150 size = (size_t)http->dcount * sizeof(*http->dvec);
152 http->dvec = malloc_or_die(size);
154 memcpy(http->dvec, vec, size);
158 #endif /* ndef FEATURE_EXTENDED_HOST_PATTERNS */
161 /*********************************************************************
163 * Function : url_requires_percent_encoding
165 * Description : Checks if an URL contains invalid characters
166 * according to RFC 3986 that should be percent-encoded.
167 * Does not verify whether or not the passed string
168 * actually is a valid URL.
171 * 1 : url = URL to check
173 * Returns : True in case of valid URLs, false otherwise
175 *********************************************************************/
176 int url_requires_percent_encoding(const char *url)
178 static const char allowed_characters[128] = {
179 '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
180 '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
181 '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
182 '\0', '\0', '\0', '!', '\0', '#', '$', '%', '&', '\'',
183 '(', ')', '*', '+', ',', '-', '.', '/', '0', '1',
184 '2', '3', '4', '5', '6', '7', '8', '9', ':', ';',
185 '\0', '=', '\0', '?', '@', 'A', 'B', 'C', 'D', 'E',
186 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
187 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
188 'Z', '[', '\0', ']', '\0', '_', '\0', 'a', 'b', 'c',
189 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
190 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
191 'x', 'y', 'z', '\0', '\0', '\0', '~', '\0'
196 const unsigned int i = (unsigned char)*url++;
197 if (i >= sizeof(allowed_characters) || '\0' == allowed_characters[i])
208 /*********************************************************************
210 * Function : parse_http_url
212 * Description : Parse out the host and port from the URL. Find the
213 * hostname & path, port (if ':'), and/or password (if '@')
216 * 1 : url = URL (or is it URI?) to break down
217 * 2 : http = pointer to the http structure to hold elements.
218 * Must be initialized with valid values (like NULLs).
219 * 3 : require_protocol = Whether or not URLs without
220 * protocol are acceptable.
222 * Returns : JB_ERR_OK on success
223 * JB_ERR_PARSE on malformed command/URL
224 * or >100 domains deep.
226 *********************************************************************/
227 jb_err parse_http_url(const char *url, struct http_request *http, int require_protocol)
229 int host_available = 1; /* A proxy can dream. */
232 * Save our initial URL
234 http->url = strdup_or_die(url);
237 * Check for * URI. If found, we're done.
239 if (*http->url == '*')
241 http->path = strdup_or_die("*");
242 http->hostport = strdup_or_die("");
243 if (http->url[1] != '\0')
252 * Split URL into protocol,hostport,path.
259 buf = strdup_or_die(url);
261 /* Find the start of the URL in our scratch space */
263 if (strncmpic(url_noproto, "http://", 7) == 0)
267 else if (strncmpic(url_noproto, "https://", 8) == 0)
270 * Should only happen when called from cgi_show_url_info().
275 else if (*url_noproto == '/')
278 * Short request line without protocol and host.
279 * Most likely because the client's request
280 * was intercepted and redirected into Privoxy.
285 else if (require_protocol)
291 url_path = strchr(url_noproto, '/');
292 if (url_path != NULL)
297 * NOTE: The following line ignores the path for HTTPS URLS.
298 * This means that you get consistent behaviour if you type a
299 * https URL in and it's parsed by the function. (When the
300 * URL is actually retrieved, SSL hides the path part).
302 http->path = strdup_or_die(http->ssl ? "/" : url_path);
304 http->hostport = strdup_or_die(url_noproto);
309 * Repair broken HTTP requests that don't contain a path,
310 * or CONNECT requests
312 http->path = strdup_or_die("/");
313 http->hostport = strdup_or_die(url_noproto);
321 /* Without host, there is nothing left to do here */
326 * Split hostport into user/password (ignored), host, port.
333 buf = strdup_or_die(http->hostport);
335 /* check if url contains username and/or password */
336 host = strchr(buf, '@');
339 /* Contains username/password, skip it and the @ sign. */
344 /* No username or password. */
348 /* Move after hostname before port number */
351 /* Numeric IPv6 address delimited by brackets */
353 port = strchr(host, ']');
357 /* Missing closing bracket */
368 else if (*port != ':')
370 /* Garbage after closing bracket */
377 /* Plain non-escaped hostname */
378 port = strchr(host, ':');
381 /* check if url contains port */
387 /* Terminate hostname and point to start of port string */
389 parsed_port = strtol(port, &endptr, 10);
390 if ((parsed_port <= 0) || (parsed_port > 65535) || (*endptr != '\0'))
392 log_error(LOG_LEVEL_ERROR, "Invalid port in URL: %s.", url);
396 http->port = (int)parsed_port;
400 /* No port specified. */
401 http->port = (http->ssl ? 443 : 80);
404 http->host = strdup_or_die(host);
409 #ifdef FEATURE_EXTENDED_HOST_PATTERNS
412 /* Split domain name so we can compare it against wildcards */
413 return init_domain_components(http);
414 #endif /* def FEATURE_EXTENDED_HOST_PATTERNS */
419 /*********************************************************************
421 * Function : unknown_method
423 * Description : Checks whether a method is unknown.
426 * 1 : method = points to a http method
428 * Returns : TRUE if it's unknown, FALSE otherwise.
430 *********************************************************************/
431 static int unknown_method(const char *method)
433 static const char * const known_http_methods[] = {
434 /* Basic HTTP request type */
435 "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CONNECT",
436 /* webDAV extensions (RFC2518) */
437 "PROPFIND", "PROPPATCH", "MOVE", "COPY", "MKCOL", "LOCK", "UNLOCK",
439 * Microsoft webDAV extension for Exchange 2000. See:
440 * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
441 * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
443 "BCOPY", "BMOVE", "BDELETE", "BPROPFIND", "BPROPPATCH",
445 * Another Microsoft webDAV extension for Exchange 2000. See:
446 * http://systems.cs.colorado.edu/grunwald/MobileComputing/Papers/draft-cohen-gena-p-base-00.txt
447 * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
448 * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
450 "SUBSCRIBE", "UNSUBSCRIBE", "NOTIFY", "POLL",
452 * Yet another WebDAV extension, this time for
453 * Web Distributed Authoring and Versioning (RFC3253)
455 "VERSION-CONTROL", "REPORT", "CHECKOUT", "CHECKIN", "UNCHECKOUT",
456 "MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL", "MKACTIVITY",
458 * The PATCH method is defined by RFC5789, the format of the
459 * actual patch in the body depends on the application, but from
460 * Privoxy's point of view it doesn't matter.
466 for (i = 0; i < SZ(known_http_methods); i++)
468 if (0 == strcmpic(method, known_http_methods[i]))
479 /*********************************************************************
481 * Function : parse_http_request
483 * Description : Parse out the host and port from the URL. Find the
484 * hostname & path, port (if ':'), and/or password (if '@')
487 * 1 : req = HTTP request line to break down
488 * 2 : http = pointer to the http structure to hold elements
490 * Returns : JB_ERR_OK on success
491 * JB_ERR_CGI_PARAMS on malformed command/URL
492 * or >100 domains deep.
494 *********************************************************************/
495 jb_err parse_http_request(const char *req, struct http_request *http)
502 memset(http, '\0', sizeof(*http));
504 buf = strdup_or_die(req);
506 n = ssplit(buf, " \r\n", v, SZ(v));
514 * Fail in case of unknown methods
515 * which we might not handle correctly.
517 * XXX: There should be a config option
518 * to forward requests with unknown methods
519 * anyway. Most of them don't need special
522 if (unknown_method(v[0]))
524 log_error(LOG_LEVEL_ERROR, "Unknown HTTP method detected: %s", v[0]);
529 if (strcmpic(v[2], "HTTP/1.1") && strcmpic(v[2], "HTTP/1.0"))
531 log_error(LOG_LEVEL_ERROR, "The only supported HTTP "
532 "versions are 1.0 and 1.1. This rules out: %s", v[2]);
537 http->ssl = !strcmpic(v[0], "CONNECT");
539 err = parse_http_url(v[1], http, !http->ssl);
547 * Copy the details into the structure
549 http->cmd = strdup_or_die(req);
550 http->gpc = strdup_or_die(v[0]);
551 http->ver = strdup_or_die(v[2]);
552 http->ocmd = strdup_or_die(http->cmd);
561 /*********************************************************************
563 * Function : compile_pattern
565 * Description : Compiles a host, domain or TAG pattern.
568 * 1 : pattern = The pattern to compile.
569 * 2 : anchoring = How the regex should be modified
570 * before compilation. Can be either
571 * one of NO_ANCHORING, LEFT_ANCHORED,
572 * RIGHT_ANCHORED or RIGHT_ANCHORED_HOST.
573 * 3 : url = In case of failures, the spec member is
574 * logged and the structure freed.
575 * 4 : regex = Where the compiled regex should be stored.
577 * Returns : JB_ERR_OK - Success
578 * JB_ERR_MEMORY - Out of memory
579 * JB_ERR_PARSE - Cannot parse regex
581 *********************************************************************/
582 static jb_err compile_pattern(const char *pattern, enum regex_anchoring anchoring,
583 struct pattern_spec *url, regex_t **regex)
586 char rebuf[BUFFER_SIZE];
587 const char *fmt = NULL;
590 assert(strlen(pattern) < sizeof(rebuf) - 2);
592 if (pattern[0] == '\0')
606 case RIGHT_ANCHORED_HOST:
613 log_error(LOG_LEVEL_FATAL,
614 "Invalid anchoring in compile_pattern %d", anchoring);
617 *regex = zalloc(sizeof(**regex));
620 free_pattern_spec(url);
621 return JB_ERR_MEMORY;
624 snprintf(rebuf, sizeof(rebuf), fmt, pattern);
626 errcode = regcomp(*regex, rebuf, (REG_EXTENDED|REG_NOSUB|REG_ICASE));
630 size_t errlen = regerror(errcode, *regex, rebuf, sizeof(rebuf));
631 if (errlen > (sizeof(rebuf) - (size_t)1))
633 errlen = sizeof(rebuf) - (size_t)1;
635 rebuf[errlen] = '\0';
636 log_error(LOG_LEVEL_ERROR, "error compiling %s from %s: %s",
637 pattern, url->spec, rebuf);
638 free_pattern_spec(url);
648 /*********************************************************************
650 * Function : compile_url_pattern
652 * Description : Compiles the three parts of an URL pattern.
655 * 1 : url = Target pattern_spec to be filled in.
656 * 2 : buf = The url pattern to compile. Will be messed up.
658 * Returns : JB_ERR_OK - Success
659 * JB_ERR_MEMORY - Out of memory
660 * JB_ERR_PARSE - Cannot parse regex
662 *********************************************************************/
663 static jb_err compile_url_pattern(struct pattern_spec *url, char *buf)
667 p = strchr(buf, '/');
671 * Only compile the regex if it consists of more than
672 * a single slash, otherwise it wouldn't affect the result.
677 * XXX: does it make sense to compile the slash at the beginning?
679 jb_err err = compile_pattern(p, LEFT_ANCHORED, url, &url->pattern.url_spec.preg);
681 if (JB_ERR_OK != err)
690 * IPv6 numeric hostnames can contain colons, thus we need
691 * to delimit the hostname before the real port separator.
692 * As brackets are already used in the hostname pattern,
693 * we use angle brackets ('<', '>') instead.
695 if ((buf[0] == '<') && (NULL != (p = strchr(buf + 1, '>'))))
702 /* IPv6 address without port number */
707 /* Garbage after address delimiter */
713 p = strchr(buf, ':');
719 url->pattern.url_spec.port_list = strdup_or_die(p);
723 url->pattern.url_spec.port_list = NULL;
728 return compile_host_pattern(url, buf);
736 #ifdef FEATURE_EXTENDED_HOST_PATTERNS
737 /*********************************************************************
739 * Function : compile_host_pattern
741 * Description : Parses and compiles a host pattern.
744 * 1 : url = Target pattern_spec to be filled in.
745 * 2 : host_pattern = Host pattern to compile.
747 * Returns : JB_ERR_OK - Success
748 * JB_ERR_MEMORY - Out of memory
749 * JB_ERR_PARSE - Cannot parse regex
751 *********************************************************************/
752 static jb_err compile_host_pattern(struct pattern_spec *url, const char *host_pattern)
754 return compile_pattern(host_pattern, RIGHT_ANCHORED_HOST, url, &url->pattern.url_spec.host_regex);
759 /*********************************************************************
761 * Function : compile_host_pattern
763 * Description : Parses and "compiles" an old-school host pattern.
766 * 1 : url = Target pattern_spec to be filled in.
767 * 2 : host_pattern = Host pattern to parse.
769 * Returns : JB_ERR_OK - Success
770 * JB_ERR_PARSE - Cannot parse regex
772 *********************************************************************/
773 static jb_err compile_host_pattern(struct pattern_spec *url, const char *host_pattern)
782 if (host_pattern[strlen(host_pattern) - 1] == '.')
784 url->pattern.url_spec.unanchored |= ANCHOR_RIGHT;
786 if (host_pattern[0] == '.')
788 url->pattern.url_spec.unanchored |= ANCHOR_LEFT;
792 * Split domain into components
794 url->pattern.url_spec.dbuffer = strdup_or_die(host_pattern);
799 for (p = url->pattern.url_spec.dbuffer; *p ; p++)
801 *p = (char)privoxy_tolower(*p);
805 * Split the domain name into components
807 url->pattern.url_spec.dcount = ssplit(url->pattern.url_spec.dbuffer, ".", v, SZ(v));
809 if (url->pattern.url_spec.dcount < 0)
811 free_pattern_spec(url);
814 else if (url->pattern.url_spec.dcount != 0)
817 * Save a copy of the pointers in dvec
819 size = (size_t)url->pattern.url_spec.dcount * sizeof(*url->pattern.url_spec.dvec);
821 url->pattern.url_spec.dvec = malloc_or_die(size);
823 memcpy(url->pattern.url_spec.dvec, v, size);
826 * else dcount == 0 in which case we needn't do anything,
827 * since dvec will never be accessed and the pattern will
834 /*********************************************************************
836 * Function : simplematch
838 * Description : String matching, with a (greedy) '*' wildcard that
839 * stands for zero or more arbitrary characters and
840 * character classes in [], which take both enumerations
844 * 1 : pattern = pattern for matching
845 * 2 : text = text to be matched
847 * Returns : 0 if match, else nonzero
849 *********************************************************************/
850 static int simplematch(const char *pattern, const char *text)
852 const unsigned char *pat = (const unsigned char *)pattern;
853 const unsigned char *txt = (const unsigned char *)text;
854 const unsigned char *fallback = pat;
857 unsigned char lastchar = 'a';
859 unsigned char charmap[32];
864 /* EOF pattern but !EOF text? */
877 /* '*' in the pattern? */
881 /* The pattern ends afterwards? Speed up the return. */
887 /* Else, set wildcard mode and remember position after '*' */
892 /* Character range specification? */
895 memset(charmap, '\0', sizeof(charmap));
897 while (*++pat != ']')
903 else if (*pat == '-')
905 if ((*++pat == ']') || *pat == '\0')
909 for (i = lastchar; i <= *pat; i++)
911 charmap[i / 8] |= (unsigned char)(1 << (i % 8));
916 charmap[*pat / 8] |= (unsigned char)(1 << (*pat % 8));
920 } /* -END- if Character range specification */
924 * Char match, or char range match?
928 || ((*pat == ']') && (charmap[*txt / 8] & (1 << (*txt % 8)))))
938 * No match && no wildcard: No luck
942 else if (pat != fallback)
945 * Increment text pointer if in char range matching
952 * Wildcard mode && nonmatch beyond fallback: Rewind pattern
956 * Restart matching from current text pointer
963 /* Cut off extra '*'s */
964 if (*pat == '*') pat++;
966 /* If this is the pattern's end, fine! */
972 /*********************************************************************
974 * Function : simple_domaincmp
976 * Description : Domain-wise Compare fqdn's. The comparison is
977 * both left- and right-anchored. The individual
978 * domain names are compared with simplematch().
979 * This is only used by domain_match.
982 * 1 : pv = array of patterns to compare
983 * 2 : fv = array of domain components to compare
984 * 3 : len = length of the arrays (both arrays are the
985 * same length - if they weren't, it couldn't
986 * possibly be a match).
988 * Returns : 0 => domains are equivalent, else no match.
990 *********************************************************************/
991 static int simple_domaincmp(char **pv, char **fv, int len)
995 for (n = 0; n < len; n++)
997 if (simplematch(pv[n], fv[n]))
1008 /*********************************************************************
1010 * Function : domain_match
1012 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1013 * p.pattern->unachored, the comparison is un-, left-,
1014 * right-anchored, or both.
1015 * The individual domain names are compared with
1019 * 1 : p = a domain that may contain a '*' as a wildcard.
1020 * 2 : fqdn = domain name against which the patterns are compared.
1022 * Returns : 0 => domains are equivalent, else no match.
1024 *********************************************************************/
1025 static int domain_match(const struct pattern_spec *p, const struct http_request *fqdn)
1027 char **pv, **fv; /* vectors */
1029 int unanchored = p->pattern.url_spec.unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1031 plen = p->pattern.url_spec.dcount;
1032 flen = fqdn->dcount;
1036 /* fqdn is too short to match this pattern */
1040 pv = p->pattern.url_spec.dvec;
1043 if (unanchored == ANCHOR_LEFT)
1048 * Convert this into a fully anchored pattern with
1049 * the fqdn and pattern the same length
1051 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1052 return simple_domaincmp(pv, fv, plen);
1054 else if (unanchored == 0)
1056 /* Fully anchored, check length */
1061 return simple_domaincmp(pv, fv, plen);
1063 else if (unanchored == ANCHOR_RIGHT)
1065 /* Left anchored, ignore all extra in fqdn */
1066 return simple_domaincmp(pv, fv, plen);
1072 int maxn = flen - plen;
1073 for (n = 0; n <= maxn; n++)
1075 if (!simple_domaincmp(pv, fv, plen))
1080 * Doesn't match from start of fqdn
1081 * Try skipping first part of fqdn
1089 #endif /* def FEATURE_EXTENDED_HOST_PATTERNS */
1092 /*********************************************************************
1094 * Function : create_pattern_spec
1096 * Description : Creates a "pattern_spec" structure from a string.
1097 * When finished, free with free_pattern_spec().
1100 * 1 : pattern = Target pattern_spec to be filled in.
1101 * Will be zeroed before use.
1102 * 2 : buf = Source pattern, null terminated. NOTE: The
1103 * contents of this buffer are destroyed by this
1104 * function. If this function succeeds, the
1105 * buffer is copied to pattern->spec. If this
1106 * function fails, the contents of the buffer
1109 * Returns : JB_ERR_OK - Success
1110 * JB_ERR_PARSE - Cannot parse regex (Detailed message
1111 * written to system log)
1113 *********************************************************************/
1114 jb_err create_pattern_spec(struct pattern_spec *pattern, char *buf)
1118 /** The tag pattern prefix to match */
1121 /** The length of the prefix to match */
1122 const size_t prefix_length;
1124 /** The pattern flag */
1125 const unsigned flag;
1127 { "TAG:", 4, PATTERN_SPEC_TAG_PATTERN},
1128 { "NO-REQUEST-TAG:", 15, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN},
1129 { "NO-RESPONSE-TAG:", 16, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN}
1136 memset(pattern, '\0', sizeof(*pattern));
1138 /* Remember the original specification for the CGI pages. */
1139 pattern->spec = strdup_or_die(buf);
1141 /* Check if it's a tag pattern */
1142 for (i = 0; i < SZ(tag_pattern); i++)
1144 if (0 == strncmpic(pattern->spec, tag_pattern[i].prefix, tag_pattern[i].prefix_length))
1146 /* The regex starts after the prefix */
1147 const char *tag_regex = buf + tag_pattern[i].prefix_length;
1149 pattern->flags |= tag_pattern[i].flag;
1151 return compile_pattern(tag_regex, NO_ANCHORING, pattern,
1152 &pattern->pattern.tag_regex);
1156 /* If it isn't a tag pattern it must be an URL pattern. */
1157 pattern->flags |= PATTERN_SPEC_URL_PATTERN;
1159 return compile_url_pattern(pattern, buf);
1164 /*********************************************************************
1166 * Function : free_pattern_spec
1168 * Description : Called from the "unloaders". Freez the pattern
1169 * structure elements.
1172 * 1 : pattern = pointer to a pattern_spec structure.
1176 *********************************************************************/
1177 void free_pattern_spec(struct pattern_spec *pattern)
1179 if (pattern == NULL) return;
1181 freez(pattern->spec);
1182 #ifdef FEATURE_EXTENDED_HOST_PATTERNS
1183 if (pattern->pattern.url_spec.host_regex)
1185 regfree(pattern->pattern.url_spec.host_regex);
1186 freez(pattern->pattern.url_spec.host_regex);
1189 freez(pattern->pattern.url_spec.dbuffer);
1190 freez(pattern->pattern.url_spec.dvec);
1191 pattern->pattern.url_spec.dcount = 0;
1192 #endif /* ndef FEATURE_EXTENDED_HOST_PATTERNS */
1193 freez(pattern->pattern.url_spec.port_list);
1194 if (pattern->pattern.url_spec.preg)
1196 regfree(pattern->pattern.url_spec.preg);
1197 freez(pattern->pattern.url_spec.preg);
1199 if (pattern->pattern.tag_regex)
1201 regfree(pattern->pattern.tag_regex);
1202 freez(pattern->pattern.tag_regex);
1207 /*********************************************************************
1209 * Function : port_matches
1211 * Description : Compares a port against a port list.
1214 * 1 : port = The port to check.
1215 * 2 : port_list = The list of port to compare with.
1217 * Returns : TRUE for yes, FALSE otherwise.
1219 *********************************************************************/
1220 static int port_matches(const int port, const char *port_list)
1222 return ((NULL == port_list) || match_portlist(port_list, port));
1226 /*********************************************************************
1228 * Function : host_matches
1230 * Description : Compares a host against a host pattern.
1233 * 1 : url = The URL to match
1234 * 2 : pattern = The URL pattern
1236 * Returns : TRUE for yes, FALSE otherwise.
1238 *********************************************************************/
1239 static int host_matches(const struct http_request *http,
1240 const struct pattern_spec *pattern)
1242 #ifdef FEATURE_EXTENDED_HOST_PATTERNS
1243 return ((NULL == pattern->pattern.url_spec.host_regex)
1244 || (0 == regexec(pattern->pattern.url_spec.host_regex, http->host, 0, NULL, 0)));
1246 return ((NULL == pattern->pattern.url_spec.dbuffer) || (0 == domain_match(pattern, http)));
1251 /*********************************************************************
1253 * Function : path_matches
1255 * Description : Compares a path against a path pattern.
1258 * 1 : path = The path to match
1259 * 2 : pattern = The URL pattern
1261 * Returns : TRUE for yes, FALSE otherwise.
1263 *********************************************************************/
1264 static int path_matches(const char *path, const struct pattern_spec *pattern)
1266 return ((NULL == pattern->pattern.url_spec.preg)
1267 || (0 == regexec(pattern->pattern.url_spec.preg, path, 0, NULL, 0)));
1271 /*********************************************************************
1273 * Function : url_match
1275 * Description : Compare a URL against a URL pattern.
1278 * 1 : pattern = a URL pattern
1279 * 2 : url = URL to match
1281 * Returns : Nonzero if the URL matches the pattern, else 0.
1283 *********************************************************************/
1284 int url_match(const struct pattern_spec *pattern,
1285 const struct http_request *http)
1287 if (!(pattern->flags & PATTERN_SPEC_URL_PATTERN))
1289 /* It's not an URL pattern and thus shouldn't be matched against URLs */
1293 return (port_matches(http->port, pattern->pattern.url_spec.port_list)
1294 && host_matches(http, pattern) && path_matches(http->path, pattern));
1299 /*********************************************************************
1301 * Function : match_portlist
1303 * Description : Check if a given number is covered by a comma
1304 * separated list of numbers and ranges (a,b-c,d,..)
1307 * 1 : portlist = String with list
1308 * 2 : port = port to check
1310 * Returns : 0 => no match
1313 *********************************************************************/
1314 int match_portlist(const char *portlist, int port)
1316 char *min, *max, *next, *portlist_copy;
1318 min = portlist_copy = strdup_or_die(portlist);
1321 * Zero-terminate first item and remember offset for next
1323 if (NULL != (next = strchr(portlist_copy, (int) ',')))
1329 * Loop through all items, checking for match
1333 if (NULL == (max = strchr(min, (int) '-')))
1336 * No dash, check for equality
1338 if (port == atoi(min))
1340 freez(portlist_copy);
1347 * This is a range, so check if between min and max,
1348 * or, if max was omitted, between min and 65K
1351 if (port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
1353 freez(portlist_copy);
1365 * Zero-terminate next item and remember offset for n+1
1367 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
1373 freez(portlist_copy);
1379 /*********************************************************************
1381 * Function : parse_forwarder_address
1383 * Description : Parse out the host and port from a forwarder address.
1386 * 1 : address = The forwarder address to parse.
1387 * 2 : hostname = Used to return the hostname. NULL on error.
1388 * 3 : port = Used to return the port. Untouched if no port
1391 * Returns : JB_ERR_OK on success
1392 * JB_ERR_MEMORY on out of memory
1393 * JB_ERR_PARSE on malformed address.
1395 *********************************************************************/
1396 jb_err parse_forwarder_address(char *address, char **hostname, int *port)
1400 if ((*address == '[') && (NULL == strchr(address, ']')))
1402 /* XXX: Should do some more validity checks here. */
1403 return JB_ERR_PARSE;
1406 *hostname = strdup_or_die(address);
1408 if ((**hostname == '[') && (NULL != (p = strchr(*hostname, ']'))))
1411 memmove(*hostname, (*hostname + 1), (size_t)(p - *hostname));
1414 *port = (int)strtol(++p, NULL, 0);
1417 else if (NULL != (p = strchr(*hostname, ':')))
1420 *port = (int)strtol(p, NULL, 0);