1 const char urlmatch_rcs[] = "$Id: urlmatch.c,v 1.5 2002/03/13 00:27:05 jongfoster 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 the SourceForge
10 * Privoxy team. http://ijbswa.sourceforge.net
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.5 2002/03/13 00:27:05 jongfoster
39 * Revision 1.4 2002/03/07 03:46:17 oes
40 * Fixed compiler warnings
42 * Revision 1.3 2002/03/03 14:51:11 oes
43 * Fixed CLF logging: Added ocmd member for client's request to struct http_request
45 * Revision 1.2 2002/01/21 00:14:09 jongfoster
46 * Correcting comment style
47 * Fixing an uninitialized memory bug in create_url_spec()
49 * Revision 1.1 2002/01/17 20:53:46 jongfoster
50 * Moving all our URL and URL pattern parsing code to the same file - it
51 * was scattered around in filters.c, loaders.c and parsers.c.
53 * Providing a single, simple url_match(pattern,url) function - rather than
54 * the 3-line match routine which was repeated all over the place.
56 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
58 * Providing parse_http_url() so that URLs can be parsed without faking a
59 * HTTP request line for parse_http_request() or repeating the parsing
60 * code (both of which were techniques that were actually in use).
62 * Standardizing that struct http_request is used to represent a URL, and
63 * struct url_spec is used to represent a URL pattern. (Before, URLs were
64 * represented as seperate variables and a partially-filled-in url_spec).
67 *********************************************************************/
74 #include <sys/types.h>
82 #if !defined(_WIN32) && !defined(__OS2__)
92 const char urlmatch_h_rcs[] = URLMATCH_H_VERSION;
94 /* Fix a problem with Solaris. There should be no effect on other
96 * Solaris's isspace() is a macro which uses it's argument directly
97 * as an array index. Therefore we need to make sure that high-bit
98 * characters generate +ve values, and ideally we also want to make
99 * the argument match the declared parameter type of "int".
101 * Why did they write a character function that can't take a simple
102 * "char" argument? Doh!
104 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
105 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
108 /*********************************************************************
110 * Function : free_http_request
112 * Description : Freez a http_request structure
115 * 1 : http = points to a http_request structure to free
119 *********************************************************************/
120 void free_http_request(struct http_request *http)
129 freez(http->hostport);
132 freez(http->host_ip_addr_str);
133 freez(http->dbuffer);
139 /*********************************************************************
141 * Function : parse_http_url
143 * Description : Parse out the host and port from the URL. Find the
144 * hostname & path, port (if ':'), and/or password (if '@')
147 * 1 : url = URL (or is it URI?) to break down
148 * 2 : http = pointer to the http structure to hold elements.
149 * Will be zeroed before use. Note that this
150 * function sets the http->gpc and http->ver
152 * 3 : csp = Current client state (buffers, headers, etc...)
154 * Returns : JB_ERR_OK on success
155 * JB_ERR_MEMORY on out of memory
156 * JB_ERR_CGI_PARAMS on malformed command/URL
157 * or >100 domains deep.
159 *********************************************************************/
160 jb_err parse_http_url(const char * url,
161 struct http_request *http,
162 struct client_state *csp)
165 * Zero out the results structure
167 memset(http, '\0', sizeof(*http));
171 * Save our initial URL
173 http->url = strdup(url);
174 if (http->url == NULL)
176 return JB_ERR_MEMORY;
181 * Split URL into protocol,hostport,path.
191 return JB_ERR_MEMORY;
194 /* Find the start of the URL in our scratch space */
196 if (strncmpic(url_noproto, "http://", 7) == 0)
201 else if (strncmpic(url_noproto, "https://", 8) == 0)
211 url_path = strchr(url_noproto, '/');
212 if (url_path != NULL)
217 * NOTE: The following line ignores the path for HTTPS URLS.
218 * This means that you get consistent behaviour if you type a
219 * https URL in and it's parsed by the function. (When the
220 * URL is actually retrieved, SSL hides the path part).
222 http->path = strdup(http->ssl ? "/" : url_path);
224 http->hostport = strdup(url_noproto);
229 * Repair broken HTTP requests that don't contain a path,
230 * or CONNECT requests
232 http->path = strdup("/");
233 http->hostport = strdup(url_noproto);
238 if ( (http->path == NULL)
239 || (http->hostport == NULL))
242 free_http_request(http);
243 return JB_ERR_MEMORY;
249 * Split hostport into user/password (ignored), host, port.
256 buf = strdup(http->hostport);
259 free_http_request(http);
260 return JB_ERR_MEMORY;
263 /* check if url contains username and/or password */
264 host = strchr(buf, '@');
267 /* Contains username/password, skip it and the @ sign. */
272 /* No username or password. */
276 /* check if url contains port */
277 port = strchr(host, ':');
281 /* Terminate hostname and point to start of port string */
283 http->port = atoi(port);
287 /* No port specified. */
288 http->port = (http->ssl ? 143 : 80);
291 http->host = strdup(host);
295 if (http->host == NULL)
297 free_http_request(http);
298 return JB_ERR_MEMORY;
304 * Split domain name so we can compare it against wildcards
307 char *vec[BUFFER_SIZE];
311 http->dbuffer = strdup(http->host);
312 if (NULL == http->dbuffer)
314 free_http_request(http);
315 return JB_ERR_MEMORY;
318 /* map to lower case */
319 for (p = http->dbuffer; *p ; p++)
321 *p = tolower((int)(unsigned char)*p);
324 /* split the domain name into components */
325 http->dcount = ssplit(http->dbuffer, ".", vec, SZ(vec), 1, 1);
327 if (http->dcount <= 0)
330 * Error: More than SZ(vec) components in domain
331 * or: no components in domain
333 free_http_request(http);
337 /* save a copy of the pointers in dvec */
338 size = http->dcount * sizeof(*http->dvec);
340 http->dvec = (char **)malloc(size);
341 if (NULL == http->dvec)
343 free_http_request(http);
344 return JB_ERR_MEMORY;
347 memcpy(http->dvec, vec, size);
355 /*********************************************************************
357 * Function : parse_http_request
359 * Description : Parse out the host and port from the URL. Find the
360 * hostname & path, port (if ':'), and/or password (if '@')
363 * 1 : req = HTTP request line to break down
364 * 2 : http = pointer to the http structure to hold elements
365 * 3 : csp = Current client state (buffers, headers, etc...)
367 * Returns : JB_ERR_OK on success
368 * JB_ERR_MEMORY on out of memory
369 * JB_ERR_CGI_PARAMS on malformed command/URL
370 * or >100 domains deep.
372 *********************************************************************/
373 jb_err parse_http_request(const char *req,
374 struct http_request *http,
375 struct client_state *csp)
383 memset(http, '\0', sizeof(*http));
388 return JB_ERR_MEMORY;
391 n = ssplit(buf, " \r\n", v, SZ(v), 1, 1);
398 /* this could be a CONNECT request */
399 if (strcmpic(v[0], "connect") == 0)
404 /* or it could be any other basic HTTP request type */
405 else if ((0 == strcmpic(v[0], "get"))
406 || (0 == strcmpic(v[0], "head"))
407 || (0 == strcmpic(v[0], "post"))
408 || (0 == strcmpic(v[0], "put"))
409 || (0 == strcmpic(v[0], "delete"))
411 /* or a webDAV extension (RFC2518) */
412 || (0 == strcmpic(v[0], "propfind"))
413 || (0 == strcmpic(v[0], "proppatch"))
414 || (0 == strcmpic(v[0], "move"))
415 || (0 == strcmpic(v[0], "copy"))
416 || (0 == strcmpic(v[0], "mkcol"))
417 || (0 == strcmpic(v[0], "lock"))
418 || (0 == strcmpic(v[0], "unlock"))
426 /* Unknown HTTP method */
431 err = parse_http_url(v[1], http, csp);
439 * Copy the details into the structure
441 http->ssl = is_connect;
442 http->cmd = strdup(req);
443 http->gpc = strdup(v[0]);
444 http->ver = strdup(v[2]);
446 if ( (http->cmd == NULL)
447 || (http->gpc == NULL)
448 || (http->ver == NULL) )
451 free_http_request(http);
452 return JB_ERR_MEMORY;
459 /*********************************************************************
461 * Function : simple_domaincmp
463 * Description : Domain-wise Compare fqdn's. The comparison is
464 * both left- and right-anchored. The individual
465 * domain names are compared with simplematch().
466 * This is only used by domain_match.
469 * 1 : pv = array of patterns to compare
470 * 2 : fv = array of domain components to compare
471 * 3 : len = length of the arrays (both arrays are the
472 * same length - if they weren't, it couldn't
473 * possibly be a match).
475 * Returns : 0 => domains are equivalent, else no match.
477 *********************************************************************/
478 static int simple_domaincmp(char **pv, char **fv, int len)
482 for (n = 0; n < len; n++)
484 if (simplematch(pv[n], fv[n]))
495 /*********************************************************************
497 * Function : domain_match
499 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
500 * pattern->unachored, the comparison is un-, left-,
501 * right-anchored, or both.
502 * The individual domain names are compared with
506 * 1 : pattern = a domain that may contain a '*' as a wildcard.
507 * 2 : fqdn = domain name against which the patterns are compared.
509 * Returns : 0 => domains are equivalent, else no match.
511 *********************************************************************/
512 static int domain_match(const struct url_spec *pattern, const struct http_request *fqdn)
514 char **pv, **fv; /* vectors */
516 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
518 plen = pattern->dcount;
523 /* fqdn is too short to match this pattern */
530 if (unanchored == ANCHOR_LEFT)
535 * Convert this into a fully anchored pattern with
536 * the fqdn and pattern the same length
538 fv += (flen - plen); /* flen - plen >= 0 due to check above */
539 return simple_domaincmp(pv, fv, plen);
541 else if (unanchored == 0)
543 /* Fully anchored, check length */
548 return simple_domaincmp(pv, fv, plen);
550 else if (unanchored == ANCHOR_RIGHT)
552 /* Left anchored, ignore all extra in fqdn */
553 return simple_domaincmp(pv, fv, plen);
559 int maxn = flen - plen;
560 for (n = 0; n <= maxn; n++)
562 if (!simple_domaincmp(pv, fv, plen))
567 * Doesn't match from start of fqdn
568 * Try skipping first part of fqdn
578 /*********************************************************************
580 * Function : create_url_spec
582 * Description : Creates a "url_spec" structure from a string.
583 * When finished, free with unload_url().
586 * 1 : url = Target url_spec to be filled in. Will be
588 * 2 : buf = Source pattern, null terminated. NOTE: The
589 * contents of this buffer are destroyed by this
590 * function. If this function succeeds, the
591 * buffer is copied to url->spec. If this
592 * function fails, the contents of the buffer
595 * Returns : JB_ERR_OK - Success
596 * JB_ERR_MEMORY - Out of memory
597 * JB_ERR_PARSE - Cannot parse regex (Detailed message
598 * written to system log)
600 *********************************************************************/
601 jb_err create_url_spec(struct url_spec * url, const char * buf)
609 memset(url, '\0', sizeof(*url));
611 /* save a copy of the orignal specification */
612 if ((url->spec = strdup(buf)) == NULL)
614 return JB_ERR_MEMORY;
617 if ((p = strchr(buf, '/')) != NULL)
619 if (NULL == (url->path = strdup(p)))
622 return JB_ERR_MEMORY;
624 url->pathlen = strlen(url->path);
636 char rebuf[BUFFER_SIZE];
638 if (NULL == (url->preg = zalloc(sizeof(*url->preg))))
642 return JB_ERR_MEMORY;
645 sprintf(rebuf, "^(%s)", url->path);
647 errcode = regcomp(url->preg, rebuf,
648 (REG_EXTENDED|REG_NOSUB|REG_ICASE));
651 size_t errlen = regerror(errcode,
652 url->preg, rebuf, sizeof(rebuf));
654 if (errlen > (sizeof(rebuf) - (size_t)1))
656 errlen = sizeof(rebuf) - (size_t)1;
658 rebuf[errlen] = '\0';
660 log_error(LOG_LEVEL_ERROR, "error compiling %s: %s",
671 if ((p = strchr(buf, ':')) == NULL)
686 /* Parse domain part */
687 if (buf[strlen(buf) - 1] == '.')
689 url->unanchored |= ANCHOR_RIGHT;
693 url->unanchored |= ANCHOR_LEFT;
696 /* split domain into components */
698 url->dbuffer = strdup(buf);
699 if (NULL == url->dbuffer)
705 #endif /* def REGEX */
706 return JB_ERR_MEMORY;
709 /* map to lower case */
710 for (p = url->dbuffer; *p ; p++)
712 *p = tolower((int)(unsigned char)*p);
715 /* split the domain name into components */
716 url->dcount = ssplit(url->dbuffer, ".", v, SZ(v), 1, 1);
724 #endif /* def REGEX */
727 return JB_ERR_MEMORY;
729 else if (url->dcount != 0)
732 /* save a copy of the pointers in dvec */
733 size = url->dcount * sizeof(*url->dvec);
735 url->dvec = (char **)malloc(size);
736 if (NULL == url->dvec)
742 #endif /* def REGEX */
745 return JB_ERR_MEMORY;
748 memcpy(url->dvec, v, size);
757 /*********************************************************************
759 * Function : free_url_spec
761 * Description : Called from the "unloaders". Freez the url
762 * structure elements.
765 * 1 : url = pointer to a url_spec structure.
769 *********************************************************************/
770 void free_url_spec(struct url_spec *url)
772 if (url == NULL) return;
789 /*********************************************************************
791 * Function : url_match
793 * Description : Compare a URL against a URL pattern.
796 * 1 : pattern = a URL pattern
797 * 2 : url = URL to match
799 * Returns : 0 iff the URL matches the pattern, else nonzero.
801 *********************************************************************/
802 int url_match(const struct url_spec *pattern,
803 const struct http_request *url)
805 return ((pattern->port == 0) || (pattern->port == url->port))
806 && ((pattern->dbuffer == NULL) || (domain_match(pattern, url) == 0))
807 && ((pattern->path == NULL) ||
809 (regexec(pattern->preg, url->path, 0, NULL, 0) == 0)
811 (strncmp(pattern->path, url->path, pattern->pathlen) == 0)