1 const char urlmatch_rcs[] = "$Id: urlmatch.c,v 1.17 2007/04/15 16:39:21 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-2003, 2006-2007 the SourceForge
10 * 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.
35 * $Log: urlmatch.c,v $
36 * Revision 1.17 2007/04/15 16:39:21 fabiankeil
37 * Introduce tags as alternative way to specify which
38 * actions apply to a request. At the moment tags can be
39 * created based on client and server headers.
41 * Revision 1.16 2007/02/13 13:59:24 fabiankeil
42 * Remove redundant log message.
44 * Revision 1.15 2007/01/28 16:11:23 fabiankeil
45 * Accept WebDAV methods for subversion
46 * in parse_http_request(). Closes FR 1581425.
48 * Revision 1.14 2007/01/06 14:23:56 fabiankeil
49 * Fix gcc43 warnings. Mark *csp as immutable
50 * for parse_http_url() and url_match().
51 * Replace a sprintf call with snprintf.
53 * Revision 1.13 2006/12/06 19:50:54 fabiankeil
54 * parse_http_url() now handles intercepted
55 * HTTP request lines as well. Moved parts
56 * of parse_http_url()'s code into
57 * init_domain_components() so that it can
58 * be reused in chat().
60 * Revision 1.12 2006/07/18 14:48:47 david__schmidt
61 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
62 * with what was really the latest development (the v_3_0_branch branch)
64 * Revision 1.10.2.7 2003/05/17 15:57:24 oes
65 * - parse_http_url now checks memory allocation failure for
66 * duplication of "*" URL and rejects "*something" URLs
68 * - Added a comment to what might look like a bug in
69 * create_url_spec (see !bug #736931)
72 * Revision 1.10.2.6 2003/05/07 12:39:48 oes
73 * Fix typo: Default port for https URLs is 443, not 143.
74 * Thanks to Scott Tregear for spotting this one.
76 * Revision 1.10.2.5 2003/02/28 13:09:29 oes
77 * Fixed a rare double free condition as per Bug #694713
79 * Revision 1.10.2.4 2003/02/28 12:57:44 oes
80 * Moved freeing of http request structure to its owner
81 * as per Dan Price's observations in Bug #694713
83 * Revision 1.10.2.3 2002/11/12 16:50:40 oes
84 * Fixed memory leak in parse_http_request() reported by Oliver Stoeneberg. Fixes bug #637073
86 * Revision 1.10.2.2 2002/09/25 14:53:15 oes
87 * Added basic support for OPTIONS and TRACE HTTP methods:
88 * parse_http_url now recognizes the "*" URI as well as
89 * the OPTIONS and TRACE method keywords.
91 * Revision 1.10.2.1 2002/06/06 19:06:44 jongfoster
92 * Adding support for proprietary Microsoft WebDAV extensions
94 * Revision 1.10 2002/05/12 21:40:37 jongfoster
95 * - Removing some unused code
97 * Revision 1.9 2002/04/04 00:36:36 gliptak
98 * always use pcre for matching
100 * Revision 1.8 2002/04/03 23:32:47 jongfoster
101 * Fixing memory leak on error
103 * Revision 1.7 2002/03/26 22:29:55 swa
104 * we have a new homepage!
106 * Revision 1.6 2002/03/24 13:25:43 swa
107 * name change related issues
109 * Revision 1.5 2002/03/13 00:27:05 jongfoster
112 * Revision 1.4 2002/03/07 03:46:17 oes
113 * Fixed compiler warnings
115 * Revision 1.3 2002/03/03 14:51:11 oes
116 * Fixed CLF logging: Added ocmd member for client's request to struct http_request
118 * Revision 1.2 2002/01/21 00:14:09 jongfoster
119 * Correcting comment style
120 * Fixing an uninitialized memory bug in create_url_spec()
122 * Revision 1.1 2002/01/17 20:53:46 jongfoster
123 * Moving all our URL and URL pattern parsing code to the same file - it
124 * was scattered around in filters.c, loaders.c and parsers.c.
126 * Providing a single, simple url_match(pattern,url) function - rather than
127 * the 3-line match routine which was repeated all over the place.
129 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
131 * Providing parse_http_url() so that URLs can be parsed without faking a
132 * HTTP request line for parse_http_request() or repeating the parsing
133 * code (both of which were techniques that were actually in use).
135 * Standardizing that struct http_request is used to represent a URL, and
136 * struct url_spec is used to represent a URL pattern. (Before, URLs were
137 * represented as seperate variables and a partially-filled-in url_spec).
140 *********************************************************************/
147 #include <sys/types.h>
155 #if !defined(_WIN32) && !defined(__OS2__)
160 #include "urlmatch.h"
162 #include "miscutil.h"
165 const char urlmatch_h_rcs[] = URLMATCH_H_VERSION;
168 /*********************************************************************
170 * Function : free_http_request
172 * Description : Freez a http_request structure
175 * 1 : http = points to a http_request structure to free
179 *********************************************************************/
180 void free_http_request(struct http_request *http)
189 freez(http->hostport);
192 freez(http->host_ip_addr_str);
193 freez(http->dbuffer);
198 /*********************************************************************
200 * Function : init_domain_components
202 * Description : Splits the domain name so we can compare it
203 * against wildcards. It used to be part of
204 * parse_http_url, but was separated because the
205 * same code is required in chat in case of
206 * intercepted requests.
209 * 1 : http = pointer to the http structure to hold elements.
211 * Returns : JB_ERR_OK on success
212 * JB_ERR_MEMORY on out of memory
213 * JB_ERR_PARSE on malformed command/URL
214 * or >100 domains deep.
216 *********************************************************************/
217 jb_err init_domain_components(struct http_request *http)
219 char *vec[BUFFER_SIZE];
223 http->dbuffer = strdup(http->host);
224 if (NULL == http->dbuffer)
226 return JB_ERR_MEMORY;
229 /* map to lower case */
230 for (p = http->dbuffer; *p ; p++)
232 *p = (char)tolower((int)(unsigned char)*p);
235 /* split the domain name into components */
236 http->dcount = ssplit(http->dbuffer, ".", vec, SZ(vec), 1, 1);
238 if (http->dcount <= 0)
241 * Error: More than SZ(vec) components in domain
242 * or: no components in domain
244 log_error(LOG_LEVEL_ERROR, "More than SZ(vec) components in domain or none at all.");
248 /* save a copy of the pointers in dvec */
249 size = (size_t)http->dcount * sizeof(*http->dvec);
251 http->dvec = (char **)malloc(size);
252 if (NULL == http->dvec)
254 return JB_ERR_MEMORY;
257 memcpy(http->dvec, vec, size);
262 /*********************************************************************
264 * Function : parse_http_url
266 * Description : Parse out the host and port from the URL. Find the
267 * hostname & path, port (if ':'), and/or password (if '@')
270 * 1 : url = URL (or is it URI?) to break down
271 * 2 : http = pointer to the http structure to hold elements.
272 * Will be zeroed before use. Note that this
273 * function sets the http->gpc and http->ver
275 * 3 : csp = Current client state (buffers, headers, etc...)
277 * Returns : JB_ERR_OK on success
278 * JB_ERR_MEMORY on out of memory
279 * JB_ERR_PARSE on malformed command/URL
280 * or >100 domains deep.
282 *********************************************************************/
283 jb_err parse_http_url(const char * url,
284 struct http_request *http,
285 const struct client_state *csp)
287 int host_available = 1; /* A proxy can dream. */
290 * Zero out the results structure
292 memset(http, '\0', sizeof(*http));
296 * Save our initial URL
298 http->url = strdup(url);
299 if (http->url == NULL)
301 return JB_ERR_MEMORY;
306 * Check for * URI. If found, we're done.
308 if (*http->url == '*')
310 if ( NULL == (http->path = strdup("*"))
311 || NULL == (http->hostport = strdup("")) )
313 return JB_ERR_MEMORY;
315 if (http->url[1] != '\0')
324 * Split URL into protocol,hostport,path.
334 return JB_ERR_MEMORY;
337 /* Find the start of the URL in our scratch space */
339 if (strncmpic(url_noproto, "http://", 7) == 0)
344 else if (strncmpic(url_noproto, "https://", 8) == 0)
349 else if (*url_noproto == '/')
352 * Short request line without protocol and host.
353 * Most likely because the client's request
354 * was intercepted and redirected into Privoxy.
365 url_path = strchr(url_noproto, '/');
366 if (url_path != NULL)
371 * NOTE: The following line ignores the path for HTTPS URLS.
372 * This means that you get consistent behaviour if you type a
373 * https URL in and it's parsed by the function. (When the
374 * URL is actually retrieved, SSL hides the path part).
376 http->path = strdup(http->ssl ? "/" : url_path);
378 http->hostport = strdup(url_noproto);
383 * Repair broken HTTP requests that don't contain a path,
384 * or CONNECT requests
386 http->path = strdup("/");
387 http->hostport = strdup(url_noproto);
392 if ( (http->path == NULL)
393 || (http->hostport == NULL))
395 return JB_ERR_MEMORY;
401 /* Without host, there is nothing left to do here */
406 * Split hostport into user/password (ignored), host, port.
413 buf = strdup(http->hostport);
416 return JB_ERR_MEMORY;
419 /* check if url contains username and/or password */
420 host = strchr(buf, '@');
423 /* Contains username/password, skip it and the @ sign. */
428 /* No username or password. */
432 /* check if url contains port */
433 port = strchr(host, ':');
437 /* Terminate hostname and point to start of port string */
439 http->port = atoi(port);
443 /* No port specified. */
444 http->port = (http->ssl ? 443 : 80);
447 http->host = strdup(host);
451 if (http->host == NULL)
453 return JB_ERR_MEMORY;
458 * Split domain name so we can compare it against wildcards
460 return init_domain_components(http);
465 /*********************************************************************
467 * Function : unknown_method
469 * Description : Checks whether a method is unknown.
472 * 1 : method = points to a http method
474 * Returns : TRUE if it's unknown, FALSE otherwise.
476 *********************************************************************/
477 static int unknown_method(const char *method)
479 static const char *known_http_methods[] = {
480 /* Basic HTTP request type */
481 "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CONNECT",
482 /* webDAV extensions (RFC2518) */
483 "PROPFIND", "PROPPATCH", "MOVE", "COPY", "MKCOL", "LOCK", "UNLOCK",
485 * Microsoft webDAV extension for Exchange 2000. See:
486 * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
487 * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
489 "BCOPY", "BMOVE", "BDELETE", "BPROPFIND", "BPROPPATCH",
491 * Another Microsoft webDAV extension for Exchange 2000. See:
492 * http://systems.cs.colorado.edu/grunwald/MobileComputing/Papers/draft-cohen-gena-p-base-00.txt
493 * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
494 * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
496 "SUBSCRIBE", "UNSUBSCRIBE", "NOTIFY", "POLL",
498 * Yet another WebDAV extension, this time for
499 * Web Distributed Authoring and Versioning (RFC3253)
501 "VERSION-CONTROL", "REPORT", "CHECKOUT", "CHECKIN", "UNCHECKOUT",
502 "MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL", "MKACTIVITY",
507 for (i = 0; NULL != known_http_methods[i]; i++)
509 if (0 == strcmpic(method, known_http_methods[i]))
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
530 * 3 : csp = Current client state (buffers, headers, etc...)
532 * Returns : JB_ERR_OK on success
533 * JB_ERR_MEMORY on out of memory
534 * JB_ERR_CGI_PARAMS on malformed command/URL
535 * or >100 domains deep.
537 *********************************************************************/
538 jb_err parse_http_request(const char *req,
539 struct http_request *http,
540 const struct client_state *csp)
543 char *v[10]; /* XXX: Why 10? We should only need three. */
548 memset(http, '\0', sizeof(*http));
553 return JB_ERR_MEMORY;
556 n = ssplit(buf, " \r\n", v, SZ(v), 1, 1);
564 * Fail in case of unknown methods
565 * which we might not handle correctly.
567 * XXX: There should be a config option
568 * to forward requests with unknown methods
569 * anyway. Most of them don't need special
572 if (unknown_method(v[0]))
574 log_error(LOG_LEVEL_ERROR, "Unknown HTTP method detected: %s", v[0]);
579 if (strcmpic(v[0], "CONNECT") == 0)
584 err = parse_http_url(v[1], http, csp);
592 * Copy the details into the structure
594 http->ssl = is_connect;
595 http->cmd = strdup(req);
596 http->gpc = strdup(v[0]);
597 http->ver = strdup(v[2]);
599 if ( (http->cmd == NULL)
600 || (http->gpc == NULL)
601 || (http->ver == NULL) )
604 return JB_ERR_MEMORY;
613 /*********************************************************************
615 * Function : simple_domaincmp
617 * Description : Domain-wise Compare fqdn's. The comparison is
618 * both left- and right-anchored. The individual
619 * domain names are compared with simplematch().
620 * This is only used by domain_match.
623 * 1 : pv = array of patterns to compare
624 * 2 : fv = array of domain components to compare
625 * 3 : len = length of the arrays (both arrays are the
626 * same length - if they weren't, it couldn't
627 * possibly be a match).
629 * Returns : 0 => domains are equivalent, else no match.
631 *********************************************************************/
632 static int simple_domaincmp(char **pv, char **fv, int len)
636 for (n = 0; n < len; n++)
638 if (simplematch(pv[n], fv[n]))
649 /*********************************************************************
651 * Function : domain_match
653 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
654 * pattern->unachored, the comparison is un-, left-,
655 * right-anchored, or both.
656 * The individual domain names are compared with
660 * 1 : pattern = a domain that may contain a '*' as a wildcard.
661 * 2 : fqdn = domain name against which the patterns are compared.
663 * Returns : 0 => domains are equivalent, else no match.
665 *********************************************************************/
666 static int domain_match(const struct url_spec *pattern, const struct http_request *fqdn)
668 char **pv, **fv; /* vectors */
670 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
672 plen = pattern->dcount;
677 /* fqdn is too short to match this pattern */
684 if (unanchored == ANCHOR_LEFT)
689 * Convert this into a fully anchored pattern with
690 * the fqdn and pattern the same length
692 fv += (flen - plen); /* flen - plen >= 0 due to check above */
693 return simple_domaincmp(pv, fv, plen);
695 else if (unanchored == 0)
697 /* Fully anchored, check length */
702 return simple_domaincmp(pv, fv, plen);
704 else if (unanchored == ANCHOR_RIGHT)
706 /* Left anchored, ignore all extra in fqdn */
707 return simple_domaincmp(pv, fv, plen);
713 int maxn = flen - plen;
714 for (n = 0; n <= maxn; n++)
716 if (!simple_domaincmp(pv, fv, plen))
721 * Doesn't match from start of fqdn
722 * Try skipping first part of fqdn
732 /*********************************************************************
734 * Function : create_url_spec
736 * Description : Creates a "url_spec" structure from a string.
737 * When finished, free with free_url_spec().
740 * 1 : url = Target url_spec to be filled in. Will be
742 * 2 : buf = Source pattern, null terminated. NOTE: The
743 * contents of this buffer are destroyed by this
744 * function. If this function succeeds, the
745 * buffer is copied to url->spec. If this
746 * function fails, the contents of the buffer
749 * Returns : JB_ERR_OK - Success
750 * JB_ERR_MEMORY - Out of memory
751 * JB_ERR_PARSE - Cannot parse regex (Detailed message
752 * written to system log)
754 *********************************************************************/
755 jb_err create_url_spec(struct url_spec * url, const char * buf)
760 char rebuf[BUFFER_SIZE];
768 memset(url, '\0', sizeof(*url));
771 * Save a copy of the orignal specification
773 if ((url->spec = strdup(buf)) == NULL)
775 return JB_ERR_MEMORY;
778 /* Is it tag pattern? */
779 if (0 == strncmpic("TAG:", url->spec, 4))
781 if (NULL == (url->tag_regex = zalloc(sizeof(*url->tag_regex))))
784 return JB_ERR_MEMORY;
787 /* buf + 4 to skip "TAG:" */
788 errcode = regcomp(url->tag_regex, buf + 4, (REG_EXTENDED|REG_NOSUB|REG_ICASE));
791 errlen = regerror(errcode, url->preg, rebuf, sizeof(rebuf));
792 if (errlen > (sizeof(rebuf) - 1))
794 errlen = sizeof(rebuf) - 1;
796 rebuf[errlen] = '\0';
798 log_error(LOG_LEVEL_ERROR, "error compiling %s: %s", url->spec, rebuf);
801 regfree(url->tag_regex);
802 freez(url->tag_regex);
809 /* Only reached for URL patterns */
810 if ((p = strchr(buf, '/')) != NULL)
812 if (NULL == (url->path = strdup(p)))
815 return JB_ERR_MEMORY;
817 url->pathlen = strlen(url->path);
827 if (NULL == (url->preg = zalloc(sizeof(*url->preg))))
831 return JB_ERR_MEMORY;
834 snprintf(rebuf, sizeof(rebuf), "^(%s)", url->path);
836 errcode = regcomp(url->preg, rebuf,
837 (REG_EXTENDED|REG_NOSUB|REG_ICASE));
840 errlen = regerror(errcode, url->preg, rebuf, sizeof(rebuf));
842 if (errlen > (sizeof(rebuf) - (size_t)1))
844 errlen = sizeof(rebuf) - (size_t)1;
846 rebuf[errlen] = '\0';
848 log_error(LOG_LEVEL_ERROR, "error compiling %s: %s",
859 if ((p = strchr(buf, ':')) == NULL)
877 if (buf[strlen(buf) - 1] == '.')
879 url->unanchored |= ANCHOR_RIGHT;
883 url->unanchored |= ANCHOR_LEFT;
887 * Split domain into components
889 url->dbuffer = strdup(buf);
890 if (NULL == url->dbuffer)
896 return JB_ERR_MEMORY;
902 for (p = url->dbuffer; *p ; p++)
904 *p = (char)tolower((int)(unsigned char)*p);
908 * Split the domain name into components
910 url->dcount = ssplit(url->dbuffer, ".", v, SZ(v), 1, 1);
920 return JB_ERR_MEMORY;
922 else if (url->dcount != 0)
926 * Save a copy of the pointers in dvec
928 size = (size_t)url->dcount * sizeof(*url->dvec);
930 url->dvec = (char **)malloc(size);
931 if (NULL == url->dvec)
939 return JB_ERR_MEMORY;
942 memcpy(url->dvec, v, size);
945 * else dcount == 0 in which case we needn't do anything,
946 * since dvec will never be accessed and the pattern will
956 /*********************************************************************
958 * Function : free_url_spec
960 * Description : Called from the "unloaders". Freez the url
961 * structure elements.
964 * 1 : url = pointer to a url_spec structure.
968 *********************************************************************/
969 void free_url_spec(struct url_spec *url)
971 if (url == NULL) return;
984 regfree(url->tag_regex);
985 freez(url->tag_regex);
990 /*********************************************************************
992 * Function : url_match
994 * Description : Compare a URL against a URL pattern.
997 * 1 : pattern = a URL pattern
998 * 2 : url = URL to match
1000 * Returns : Nonzero if the URL matches the pattern, else 0.
1002 *********************************************************************/
1003 int url_match(const struct url_spec *pattern,
1004 const struct http_request *url)
1006 if (pattern->tag_regex != NULL)
1008 /* It's a tag pattern and shouldn't be matched against URLs */
1012 return ((pattern->port == 0) || (pattern->port == url->port))
1013 && ((pattern->dbuffer == NULL) || (domain_match(pattern, url) == 0))
1014 && ((pattern->path == NULL) ||
1015 (regexec(pattern->preg, url->path, 0, NULL, 0) == 0)