1 const char urlmatch_rcs[] = "$Id: urlmatch.c,v 1.18 2007/07/30 16:42: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.18 2007/07/30 16:42:21 fabiankeil
37 * Move the method check into unknown_method()
38 * and loop through the known methods instead
39 * of using a screen-long OR chain.
41 * Revision 1.17 2007/04/15 16:39:21 fabiankeil
42 * Introduce tags as alternative way to specify which
43 * actions apply to a request. At the moment tags can be
44 * created based on client and server headers.
46 * Revision 1.16 2007/02/13 13:59:24 fabiankeil
47 * Remove redundant log message.
49 * Revision 1.15 2007/01/28 16:11:23 fabiankeil
50 * Accept WebDAV methods for subversion
51 * in parse_http_request(). Closes FR 1581425.
53 * Revision 1.14 2007/01/06 14:23:56 fabiankeil
54 * Fix gcc43 warnings. Mark *csp as immutable
55 * for parse_http_url() and url_match().
56 * Replace a sprintf call with snprintf.
58 * Revision 1.13 2006/12/06 19:50:54 fabiankeil
59 * parse_http_url() now handles intercepted
60 * HTTP request lines as well. Moved parts
61 * of parse_http_url()'s code into
62 * init_domain_components() so that it can
63 * be reused in chat().
65 * Revision 1.12 2006/07/18 14:48:47 david__schmidt
66 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
67 * with what was really the latest development (the v_3_0_branch branch)
69 * Revision 1.10.2.7 2003/05/17 15:57:24 oes
70 * - parse_http_url now checks memory allocation failure for
71 * duplication of "*" URL and rejects "*something" URLs
73 * - Added a comment to what might look like a bug in
74 * create_url_spec (see !bug #736931)
77 * Revision 1.10.2.6 2003/05/07 12:39:48 oes
78 * Fix typo: Default port for https URLs is 443, not 143.
79 * Thanks to Scott Tregear for spotting this one.
81 * Revision 1.10.2.5 2003/02/28 13:09:29 oes
82 * Fixed a rare double free condition as per Bug #694713
84 * Revision 1.10.2.4 2003/02/28 12:57:44 oes
85 * Moved freeing of http request structure to its owner
86 * as per Dan Price's observations in Bug #694713
88 * Revision 1.10.2.3 2002/11/12 16:50:40 oes
89 * Fixed memory leak in parse_http_request() reported by Oliver Stoeneberg. Fixes bug #637073
91 * Revision 1.10.2.2 2002/09/25 14:53:15 oes
92 * Added basic support for OPTIONS and TRACE HTTP methods:
93 * parse_http_url now recognizes the "*" URI as well as
94 * the OPTIONS and TRACE method keywords.
96 * Revision 1.10.2.1 2002/06/06 19:06:44 jongfoster
97 * Adding support for proprietary Microsoft WebDAV extensions
99 * Revision 1.10 2002/05/12 21:40:37 jongfoster
100 * - Removing some unused code
102 * Revision 1.9 2002/04/04 00:36:36 gliptak
103 * always use pcre for matching
105 * Revision 1.8 2002/04/03 23:32:47 jongfoster
106 * Fixing memory leak on error
108 * Revision 1.7 2002/03/26 22:29:55 swa
109 * we have a new homepage!
111 * Revision 1.6 2002/03/24 13:25:43 swa
112 * name change related issues
114 * Revision 1.5 2002/03/13 00:27:05 jongfoster
117 * Revision 1.4 2002/03/07 03:46:17 oes
118 * Fixed compiler warnings
120 * Revision 1.3 2002/03/03 14:51:11 oes
121 * Fixed CLF logging: Added ocmd member for client's request to struct http_request
123 * Revision 1.2 2002/01/21 00:14:09 jongfoster
124 * Correcting comment style
125 * Fixing an uninitialized memory bug in create_url_spec()
127 * Revision 1.1 2002/01/17 20:53:46 jongfoster
128 * Moving all our URL and URL pattern parsing code to the same file - it
129 * was scattered around in filters.c, loaders.c and parsers.c.
131 * Providing a single, simple url_match(pattern,url) function - rather than
132 * the 3-line match routine which was repeated all over the place.
134 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
136 * Providing parse_http_url() so that URLs can be parsed without faking a
137 * HTTP request line for parse_http_request() or repeating the parsing
138 * code (both of which were techniques that were actually in use).
140 * Standardizing that struct http_request is used to represent a URL, and
141 * struct url_spec is used to represent a URL pattern. (Before, URLs were
142 * represented as seperate variables and a partially-filled-in url_spec).
145 *********************************************************************/
152 #include <sys/types.h>
160 #if !defined(_WIN32) && !defined(__OS2__)
165 #include "urlmatch.h"
167 #include "miscutil.h"
170 * XXX: only for match_portlist() which I will relocate soonish.
174 const char urlmatch_h_rcs[] = URLMATCH_H_VERSION;
177 /*********************************************************************
179 * Function : free_http_request
181 * Description : Freez a http_request structure
184 * 1 : http = points to a http_request structure to free
188 *********************************************************************/
189 void free_http_request(struct http_request *http)
198 freez(http->hostport);
201 freez(http->host_ip_addr_str);
202 freez(http->dbuffer);
207 /*********************************************************************
209 * Function : init_domain_components
211 * Description : Splits the domain name so we can compare it
212 * against wildcards. It used to be part of
213 * parse_http_url, but was separated because the
214 * same code is required in chat in case of
215 * intercepted requests.
218 * 1 : http = pointer to the http structure to hold elements.
220 * Returns : JB_ERR_OK on success
221 * JB_ERR_MEMORY on out of memory
222 * JB_ERR_PARSE on malformed command/URL
223 * or >100 domains deep.
225 *********************************************************************/
226 jb_err init_domain_components(struct http_request *http)
228 char *vec[BUFFER_SIZE];
232 http->dbuffer = strdup(http->host);
233 if (NULL == http->dbuffer)
235 return JB_ERR_MEMORY;
238 /* map to lower case */
239 for (p = http->dbuffer; *p ; p++)
241 *p = (char)tolower((int)(unsigned char)*p);
244 /* split the domain name into components */
245 http->dcount = ssplit(http->dbuffer, ".", vec, SZ(vec), 1, 1);
247 if (http->dcount <= 0)
250 * Error: More than SZ(vec) components in domain
251 * or: no components in domain
253 log_error(LOG_LEVEL_ERROR, "More than SZ(vec) components in domain or none at all.");
257 /* save a copy of the pointers in dvec */
258 size = (size_t)http->dcount * sizeof(*http->dvec);
260 http->dvec = (char **)malloc(size);
261 if (NULL == http->dvec)
263 return JB_ERR_MEMORY;
266 memcpy(http->dvec, vec, size);
271 /*********************************************************************
273 * Function : parse_http_url
275 * Description : Parse out the host and port from the URL. Find the
276 * hostname & path, port (if ':'), and/or password (if '@')
279 * 1 : url = URL (or is it URI?) to break down
280 * 2 : http = pointer to the http structure to hold elements.
281 * Will be zeroed before use. Note that this
282 * function sets the http->gpc and http->ver
284 * 3 : csp = Current client state (buffers, headers, etc...)
286 * Returns : JB_ERR_OK on success
287 * JB_ERR_MEMORY on out of memory
288 * JB_ERR_PARSE on malformed command/URL
289 * or >100 domains deep.
291 *********************************************************************/
292 jb_err parse_http_url(const char * url,
293 struct http_request *http,
294 const struct client_state *csp)
296 int host_available = 1; /* A proxy can dream. */
299 * Zero out the results structure
301 memset(http, '\0', sizeof(*http));
305 * Save our initial URL
307 http->url = strdup(url);
308 if (http->url == NULL)
310 return JB_ERR_MEMORY;
315 * Check for * URI. If found, we're done.
317 if (*http->url == '*')
319 if ( NULL == (http->path = strdup("*"))
320 || NULL == (http->hostport = strdup("")) )
322 return JB_ERR_MEMORY;
324 if (http->url[1] != '\0')
333 * Split URL into protocol,hostport,path.
343 return JB_ERR_MEMORY;
346 /* Find the start of the URL in our scratch space */
348 if (strncmpic(url_noproto, "http://", 7) == 0)
353 else if (strncmpic(url_noproto, "https://", 8) == 0)
358 else if (*url_noproto == '/')
361 * Short request line without protocol and host.
362 * Most likely because the client's request
363 * was intercepted and redirected into Privoxy.
374 url_path = strchr(url_noproto, '/');
375 if (url_path != NULL)
380 * NOTE: The following line ignores the path for HTTPS URLS.
381 * This means that you get consistent behaviour if you type a
382 * https URL in and it's parsed by the function. (When the
383 * URL is actually retrieved, SSL hides the path part).
385 http->path = strdup(http->ssl ? "/" : url_path);
387 http->hostport = strdup(url_noproto);
392 * Repair broken HTTP requests that don't contain a path,
393 * or CONNECT requests
395 http->path = strdup("/");
396 http->hostport = strdup(url_noproto);
401 if ( (http->path == NULL)
402 || (http->hostport == NULL))
404 return JB_ERR_MEMORY;
410 /* Without host, there is nothing left to do here */
415 * Split hostport into user/password (ignored), host, port.
422 buf = strdup(http->hostport);
425 return JB_ERR_MEMORY;
428 /* check if url contains username and/or password */
429 host = strchr(buf, '@');
432 /* Contains username/password, skip it and the @ sign. */
437 /* No username or password. */
441 /* check if url contains port */
442 port = strchr(host, ':');
446 /* Terminate hostname and point to start of port string */
448 http->port = atoi(port);
452 /* No port specified. */
453 http->port = (http->ssl ? 443 : 80);
456 http->host = strdup(host);
460 if (http->host == NULL)
462 return JB_ERR_MEMORY;
467 * Split domain name so we can compare it against wildcards
469 return init_domain_components(http);
474 /*********************************************************************
476 * Function : unknown_method
478 * Description : Checks whether a method is unknown.
481 * 1 : method = points to a http method
483 * Returns : TRUE if it's unknown, FALSE otherwise.
485 *********************************************************************/
486 static int unknown_method(const char *method)
488 static const char *known_http_methods[] = {
489 /* Basic HTTP request type */
490 "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CONNECT",
491 /* webDAV extensions (RFC2518) */
492 "PROPFIND", "PROPPATCH", "MOVE", "COPY", "MKCOL", "LOCK", "UNLOCK",
494 * Microsoft webDAV extension for Exchange 2000. See:
495 * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
496 * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
498 "BCOPY", "BMOVE", "BDELETE", "BPROPFIND", "BPROPPATCH",
500 * Another Microsoft webDAV extension for Exchange 2000. See:
501 * http://systems.cs.colorado.edu/grunwald/MobileComputing/Papers/draft-cohen-gena-p-base-00.txt
502 * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
503 * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
505 "SUBSCRIBE", "UNSUBSCRIBE", "NOTIFY", "POLL",
507 * Yet another WebDAV extension, this time for
508 * Web Distributed Authoring and Versioning (RFC3253)
510 "VERSION-CONTROL", "REPORT", "CHECKOUT", "CHECKIN", "UNCHECKOUT",
511 "MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL", "MKACTIVITY",
516 for (i = 0; NULL != known_http_methods[i]; i++)
518 if (0 == strcmpic(method, known_http_methods[i]))
529 /*********************************************************************
531 * Function : parse_http_request
533 * Description : Parse out the host and port from the URL. Find the
534 * hostname & path, port (if ':'), and/or password (if '@')
537 * 1 : req = HTTP request line to break down
538 * 2 : http = pointer to the http structure to hold elements
539 * 3 : csp = Current client state (buffers, headers, etc...)
541 * Returns : JB_ERR_OK on success
542 * JB_ERR_MEMORY on out of memory
543 * JB_ERR_CGI_PARAMS on malformed command/URL
544 * or >100 domains deep.
546 *********************************************************************/
547 jb_err parse_http_request(const char *req,
548 struct http_request *http,
549 const struct client_state *csp)
552 char *v[10]; /* XXX: Why 10? We should only need three. */
557 memset(http, '\0', sizeof(*http));
562 return JB_ERR_MEMORY;
565 n = ssplit(buf, " \r\n", v, SZ(v), 1, 1);
573 * Fail in case of unknown methods
574 * which we might not handle correctly.
576 * XXX: There should be a config option
577 * to forward requests with unknown methods
578 * anyway. Most of them don't need special
581 if (unknown_method(v[0]))
583 log_error(LOG_LEVEL_ERROR, "Unknown HTTP method detected: %s", v[0]);
588 if (strcmpic(v[0], "CONNECT") == 0)
593 err = parse_http_url(v[1], http, csp);
601 * Copy the details into the structure
603 http->ssl = is_connect;
604 http->cmd = strdup(req);
605 http->gpc = strdup(v[0]);
606 http->ver = strdup(v[2]);
608 if ( (http->cmd == NULL)
609 || (http->gpc == NULL)
610 || (http->ver == NULL) )
613 return JB_ERR_MEMORY;
622 /*********************************************************************
624 * Function : simple_domaincmp
626 * Description : Domain-wise Compare fqdn's. The comparison is
627 * both left- and right-anchored. The individual
628 * domain names are compared with simplematch().
629 * This is only used by domain_match.
632 * 1 : pv = array of patterns to compare
633 * 2 : fv = array of domain components to compare
634 * 3 : len = length of the arrays (both arrays are the
635 * same length - if they weren't, it couldn't
636 * possibly be a match).
638 * Returns : 0 => domains are equivalent, else no match.
640 *********************************************************************/
641 static int simple_domaincmp(char **pv, char **fv, int len)
645 for (n = 0; n < len; n++)
647 if (simplematch(pv[n], fv[n]))
658 /*********************************************************************
660 * Function : domain_match
662 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
663 * pattern->unachored, the comparison is un-, left-,
664 * right-anchored, or both.
665 * The individual domain names are compared with
669 * 1 : pattern = a domain that may contain a '*' as a wildcard.
670 * 2 : fqdn = domain name against which the patterns are compared.
672 * Returns : 0 => domains are equivalent, else no match.
674 *********************************************************************/
675 static int domain_match(const struct url_spec *pattern, const struct http_request *fqdn)
677 char **pv, **fv; /* vectors */
679 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
681 plen = pattern->dcount;
686 /* fqdn is too short to match this pattern */
693 if (unanchored == ANCHOR_LEFT)
698 * Convert this into a fully anchored pattern with
699 * the fqdn and pattern the same length
701 fv += (flen - plen); /* flen - plen >= 0 due to check above */
702 return simple_domaincmp(pv, fv, plen);
704 else if (unanchored == 0)
706 /* Fully anchored, check length */
711 return simple_domaincmp(pv, fv, plen);
713 else if (unanchored == ANCHOR_RIGHT)
715 /* Left anchored, ignore all extra in fqdn */
716 return simple_domaincmp(pv, fv, plen);
722 int maxn = flen - plen;
723 for (n = 0; n <= maxn; n++)
725 if (!simple_domaincmp(pv, fv, plen))
730 * Doesn't match from start of fqdn
731 * Try skipping first part of fqdn
741 /*********************************************************************
743 * Function : create_url_spec
745 * Description : Creates a "url_spec" structure from a string.
746 * When finished, free with free_url_spec().
749 * 1 : url = Target url_spec to be filled in. Will be
751 * 2 : buf = Source pattern, null terminated. NOTE: The
752 * contents of this buffer are destroyed by this
753 * function. If this function succeeds, the
754 * buffer is copied to url->spec. If this
755 * function fails, the contents of the buffer
758 * Returns : JB_ERR_OK - Success
759 * JB_ERR_MEMORY - Out of memory
760 * JB_ERR_PARSE - Cannot parse regex (Detailed message
761 * written to system log)
763 *********************************************************************/
764 jb_err create_url_spec(struct url_spec * url, const char * buf)
769 char rebuf[BUFFER_SIZE];
777 memset(url, '\0', sizeof(*url));
780 * Save a copy of the orignal specification
782 if ((url->spec = strdup(buf)) == NULL)
784 return JB_ERR_MEMORY;
787 /* Is it tag pattern? */
788 if (0 == strncmpic("TAG:", url->spec, 4))
790 if (NULL == (url->tag_regex = zalloc(sizeof(*url->tag_regex))))
793 return JB_ERR_MEMORY;
796 /* buf + 4 to skip "TAG:" */
797 errcode = regcomp(url->tag_regex, buf + 4, (REG_EXTENDED|REG_NOSUB|REG_ICASE));
800 errlen = regerror(errcode, url->preg, rebuf, sizeof(rebuf));
801 if (errlen > (sizeof(rebuf) - 1))
803 errlen = sizeof(rebuf) - 1;
805 rebuf[errlen] = '\0';
807 log_error(LOG_LEVEL_ERROR, "error compiling %s: %s", url->spec, rebuf);
810 regfree(url->tag_regex);
811 freez(url->tag_regex);
818 /* Only reached for URL patterns */
819 p = strchr(buf, '/');
822 url->path = strdup(p);
823 if (NULL == url->path)
826 return JB_ERR_MEMORY;
836 if (NULL == (url->preg = zalloc(sizeof(*url->preg))))
840 return JB_ERR_MEMORY;
843 snprintf(rebuf, sizeof(rebuf), "^(%s)", url->path);
845 errcode = regcomp(url->preg, rebuf,
846 (REG_EXTENDED|REG_NOSUB|REG_ICASE));
849 errlen = regerror(errcode, url->preg, rebuf, sizeof(rebuf));
851 if (errlen > (sizeof(rebuf) - (size_t)1))
853 errlen = sizeof(rebuf) - (size_t)1;
855 rebuf[errlen] = '\0';
857 log_error(LOG_LEVEL_ERROR, "error compiling %s: %s",
869 p = strchr(buf, ':');
873 url->port_list = strdup(p);
874 if (NULL == url->port_list)
876 return JB_ERR_MEMORY;
881 url->port_list = NULL;
892 if (buf[strlen(buf) - 1] == '.')
894 url->unanchored |= ANCHOR_RIGHT;
898 url->unanchored |= ANCHOR_LEFT;
902 * Split domain into components
904 url->dbuffer = strdup(buf);
905 if (NULL == url->dbuffer)
911 return JB_ERR_MEMORY;
917 for (p = url->dbuffer; *p ; p++)
919 *p = (char)tolower((int)(unsigned char)*p);
923 * Split the domain name into components
925 url->dcount = ssplit(url->dbuffer, ".", v, SZ(v), 1, 1);
935 return JB_ERR_MEMORY;
937 else if (url->dcount != 0)
941 * Save a copy of the pointers in dvec
943 size = (size_t)url->dcount * sizeof(*url->dvec);
945 url->dvec = (char **)malloc(size);
946 if (NULL == url->dvec)
954 return JB_ERR_MEMORY;
957 memcpy(url->dvec, v, size);
960 * else dcount == 0 in which case we needn't do anything,
961 * since dvec will never be accessed and the pattern will
971 /*********************************************************************
973 * Function : free_url_spec
975 * Description : Called from the "unloaders". Freez the url
976 * structure elements.
979 * 1 : url = pointer to a url_spec structure.
983 *********************************************************************/
984 void free_url_spec(struct url_spec *url)
986 if (url == NULL) return;
992 freez(url->port_list);
1000 regfree(url->tag_regex);
1001 freez(url->tag_regex);
1006 /*********************************************************************
1008 * Function : url_match
1010 * Description : Compare a URL against a URL pattern.
1013 * 1 : pattern = a URL pattern
1014 * 2 : url = URL to match
1016 * Returns : Nonzero if the URL matches the pattern, else 0.
1018 *********************************************************************/
1019 int url_match(const struct url_spec *pattern,
1020 const struct http_request *url)
1026 if (pattern->tag_regex != NULL)
1028 /* It's a tag pattern and shouldn't be matched against URLs */
1032 port_matches = (NULL == pattern->port_list) || match_portlist(pattern->port_list, url->port);
1033 domain_matches = (NULL == pattern->dbuffer) || (0 == domain_match(pattern, url));
1034 path_matches = (NULL == pattern->path) || (0 == regexec(pattern->preg, url->path, 0, NULL, 0));
1036 return (port_matches && domain_matches && path_matches);