3745492619d0ed501dd308aab0de7065431cafff
[privoxy.git] / urlmatch.c
1 const char urlmatch_rcs[] = "$Id: urlmatch.c,v 1.26 2008/04/07 16:57:18 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/urlmatch.c,v $
5  *
6  * Purpose     :  Declares functions to match URLs against URL
7  *                patterns.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001-2003, 2006-2008 the SourceForge
10  *                Privoxy team. http://www.privoxy.org/
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
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.
21  *
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.
27  *
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.
33  *
34  * Revisions   :
35  *    $Log: urlmatch.c,v $
36  *    Revision 1.26  2008/04/07 16:57:18  fabiankeil
37  *    - Use free_url_spec() more consistently.
38  *    - Let it reset url->dcount just in case.
39  *
40  *    Revision 1.25  2008/04/06 15:18:38  fabiankeil
41  *    Oh well, rename the --enable-pcre-host-patterns option to
42  *    --enable-extended-host-patterns as it's not really PCRE syntax.
43  *
44  *    Revision 1.24  2008/04/06 14:54:26  fabiankeil
45  *    Use PCRE syntax in host patterns when configured
46  *    with --enable-pcre-host-patterns.
47  *
48  *    Revision 1.23  2008/04/05 12:19:20  fabiankeil
49  *    Factor compile_host_pattern() out of create_url_spec().
50  *
51  *    Revision 1.22  2008/03/30 15:02:32  fabiankeil
52  *    SZitify unknown_method().
53  *
54  *    Revision 1.21  2007/12/24 16:34:23  fabiankeil
55  *    Band-aid (and micro-optimization) that makes it less likely to run out of
56  *    stack space with overly-complex path patterns. Probably masks the problem
57  *    reported by Lee in #1856679. Hohoho.
58  *
59  *    Revision 1.20  2007/09/02 15:31:20  fabiankeil
60  *    Move match_portlist() from filter.c to urlmatch.c.
61  *    It's used for url matching, not for filtering.
62  *
63  *    Revision 1.19  2007/09/02 13:42:11  fabiankeil
64  *    - Allow port lists in url patterns.
65  *    - Ditch unused url_spec member pathlen.
66  *
67  *    Revision 1.18  2007/07/30 16:42:21  fabiankeil
68  *    Move the method check into unknown_method()
69  *    and loop through the known methods instead
70  *    of using a screen-long OR chain.
71  *
72  *    Revision 1.17  2007/04/15 16:39:21  fabiankeil
73  *    Introduce tags as alternative way to specify which
74  *    actions apply to a request. At the moment tags can be
75  *    created based on client and server headers.
76  *
77  *    Revision 1.16  2007/02/13 13:59:24  fabiankeil
78  *    Remove redundant log message.
79  *
80  *    Revision 1.15  2007/01/28 16:11:23  fabiankeil
81  *    Accept WebDAV methods for subversion
82  *    in parse_http_request(). Closes FR 1581425.
83  *
84  *    Revision 1.14  2007/01/06 14:23:56  fabiankeil
85  *    Fix gcc43 warnings. Mark *csp as immutable
86  *    for parse_http_url() and url_match().
87  *    Replace a sprintf call with snprintf.
88  *
89  *    Revision 1.13  2006/12/06 19:50:54  fabiankeil
90  *    parse_http_url() now handles intercepted
91  *    HTTP request lines as well. Moved parts
92  *    of parse_http_url()'s code into
93  *    init_domain_components() so that it can
94  *    be reused in chat().
95  *
96  *    Revision 1.12  2006/07/18 14:48:47  david__schmidt
97  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
98  *    with what was really the latest development (the v_3_0_branch branch)
99  *
100  *    Revision 1.10.2.7  2003/05/17 15:57:24  oes
101  *     - parse_http_url now checks memory allocation failure for
102  *       duplication of "*" URL and rejects "*something" URLs
103  *       Closes bug #736344
104  *     - Added a comment to what might look like a bug in
105  *       create_url_spec (see !bug #736931)
106  *     - Comment cosmetics
107  *
108  *    Revision 1.10.2.6  2003/05/07 12:39:48  oes
109  *    Fix typo: Default port for https URLs is 443, not 143.
110  *    Thanks to Scott Tregear for spotting this one.
111  *
112  *    Revision 1.10.2.5  2003/02/28 13:09:29  oes
113  *    Fixed a rare double free condition as per Bug #694713
114  *
115  *    Revision 1.10.2.4  2003/02/28 12:57:44  oes
116  *    Moved freeing of http request structure to its owner
117  *    as per Dan Price's observations in Bug #694713
118  *
119  *    Revision 1.10.2.3  2002/11/12 16:50:40  oes
120  *    Fixed memory leak in parse_http_request() reported by Oliver Stoeneberg. Fixes bug #637073
121  *
122  *    Revision 1.10.2.2  2002/09/25 14:53:15  oes
123  *    Added basic support for OPTIONS and TRACE HTTP methods:
124  *    parse_http_url now recognizes the "*" URI as well as
125  *    the OPTIONS and TRACE method keywords.
126  *
127  *    Revision 1.10.2.1  2002/06/06 19:06:44  jongfoster
128  *    Adding support for proprietary Microsoft WebDAV extensions
129  *
130  *    Revision 1.10  2002/05/12 21:40:37  jongfoster
131  *    - Removing some unused code
132  *
133  *    Revision 1.9  2002/04/04 00:36:36  gliptak
134  *    always use pcre for matching
135  *
136  *    Revision 1.8  2002/04/03 23:32:47  jongfoster
137  *    Fixing memory leak on error
138  *
139  *    Revision 1.7  2002/03/26 22:29:55  swa
140  *    we have a new homepage!
141  *
142  *    Revision 1.6  2002/03/24 13:25:43  swa
143  *    name change related issues
144  *
145  *    Revision 1.5  2002/03/13 00:27:05  jongfoster
146  *    Killing warnings
147  *
148  *    Revision 1.4  2002/03/07 03:46:17  oes
149  *    Fixed compiler warnings
150  *
151  *    Revision 1.3  2002/03/03 14:51:11  oes
152  *    Fixed CLF logging: Added ocmd member for client's request to struct http_request
153  *
154  *    Revision 1.2  2002/01/21 00:14:09  jongfoster
155  *    Correcting comment style
156  *    Fixing an uninitialized memory bug in create_url_spec()
157  *
158  *    Revision 1.1  2002/01/17 20:53:46  jongfoster
159  *    Moving all our URL and URL pattern parsing code to the same file - it
160  *    was scattered around in filters.c, loaders.c and parsers.c.
161  *
162  *    Providing a single, simple url_match(pattern,url) function - rather than
163  *    the 3-line match routine which was repeated all over the place.
164  *
165  *    Renaming free_url to free_url_spec, since it frees a struct url_spec.
166  *
167  *    Providing parse_http_url() so that URLs can be parsed without faking a
168  *    HTTP request line for parse_http_request() or repeating the parsing
169  *    code (both of which were techniques that were actually in use).
170  *
171  *    Standardizing that struct http_request is used to represent a URL, and
172  *    struct url_spec is used to represent a URL pattern.  (Before, URLs were
173  *    represented as seperate variables and a partially-filled-in url_spec).
174  *
175  *
176  *********************************************************************/
177 \f
178
179 #include "config.h"
180
181 #ifndef _WIN32
182 #include <stdio.h>
183 #include <sys/types.h>
184 #endif
185
186 #include <stdlib.h>
187 #include <ctype.h>
188 #include <assert.h>
189 #include <string.h>
190
191 #if !defined(_WIN32) && !defined(__OS2__)
192 #include <unistd.h>
193 #endif
194
195 #include "project.h"
196 #include "urlmatch.h"
197 #include "ssplit.h"
198 #include "miscutil.h"
199 #include "errlog.h"
200
201 const char urlmatch_h_rcs[] = URLMATCH_H_VERSION;
202
203
204 /*********************************************************************
205  *
206  * Function    :  free_http_request
207  *
208  * Description :  Freez a http_request structure
209  *
210  * Parameters  :
211  *          1  :  http = points to a http_request structure to free
212  *
213  * Returns     :  N/A
214  *
215  *********************************************************************/
216 void free_http_request(struct http_request *http)
217 {
218    assert(http);
219
220    freez(http->cmd);
221    freez(http->ocmd);
222    freez(http->gpc);
223    freez(http->host);
224    freez(http->url);
225    freez(http->hostport);
226    freez(http->path);
227    freez(http->ver);
228    freez(http->host_ip_addr_str);
229    freez(http->dbuffer);
230    freez(http->dvec);
231    http->dcount = 0;
232 }
233
234
235 /*********************************************************************
236  *
237  * Function    :  init_domain_components
238  *
239  * Description :  Splits the domain name so we can compare it
240  *                against wildcards. It used to be part of
241  *                parse_http_url, but was separated because the
242  *                same code is required in chat in case of
243  *                intercepted requests.
244  *
245  * Parameters  :
246  *          1  :  http = pointer to the http structure to hold elements.
247  *
248  * Returns     :  JB_ERR_OK on success
249  *                JB_ERR_MEMORY on out of memory
250  *                JB_ERR_PARSE on malformed command/URL
251  *                             or >100 domains deep.
252  *
253  *********************************************************************/
254 jb_err init_domain_components(struct http_request *http)
255 {
256    char *vec[BUFFER_SIZE];
257    size_t size;
258    char *p;
259
260    http->dbuffer = strdup(http->host);
261    if (NULL == http->dbuffer)
262    {
263       return JB_ERR_MEMORY;
264    }
265
266    /* map to lower case */
267    for (p = http->dbuffer; *p ; p++)
268    {
269       *p = (char)tolower((int)(unsigned char)*p);
270    }
271
272    /* split the domain name into components */
273    http->dcount = ssplit(http->dbuffer, ".", vec, SZ(vec), 1, 1);
274
275    if (http->dcount <= 0)
276    {
277       /*
278        * Error: More than SZ(vec) components in domain
279        *    or: no components in domain
280        */
281       log_error(LOG_LEVEL_ERROR, "More than SZ(vec) components in domain or none at all.");
282       return JB_ERR_PARSE;
283    }
284
285    /* save a copy of the pointers in dvec */
286    size = (size_t)http->dcount * sizeof(*http->dvec);
287
288    http->dvec = (char **)malloc(size);
289    if (NULL == http->dvec)
290    {
291       return JB_ERR_MEMORY;
292    }
293
294    memcpy(http->dvec, vec, size);
295
296    return JB_ERR_OK;
297 }
298
299
300 /*********************************************************************
301  *
302  * Function    :  parse_http_url
303  *
304  * Description :  Parse out the host and port from the URL.  Find the
305  *                hostname & path, port (if ':'), and/or password (if '@')
306  *
307  * Parameters  :
308  *          1  :  url = URL (or is it URI?) to break down
309  *          2  :  http = pointer to the http structure to hold elements.
310  *                       Will be zeroed before use.  Note that this
311  *                       function sets the http->gpc and http->ver
312  *                       members to NULL.
313  *          3  :  csp = Current client state (buffers, headers, etc...)
314  *
315  * Returns     :  JB_ERR_OK on success
316  *                JB_ERR_MEMORY on out of memory
317  *                JB_ERR_PARSE on malformed command/URL
318  *                             or >100 domains deep.
319  *
320  *********************************************************************/
321 jb_err parse_http_url(const char * url,
322                       struct http_request *http,
323                       const struct client_state *csp)
324 {
325    int host_available = 1; /* A proxy can dream. */
326
327    /*
328     * Zero out the results structure
329     */
330    memset(http, '\0', sizeof(*http));
331
332
333    /*
334     * Save our initial URL
335     */
336    http->url = strdup(url);
337    if (http->url == NULL)
338    {
339       return JB_ERR_MEMORY;
340    }
341
342
343    /*
344     * Check for * URI. If found, we're done.
345     */  
346    if (*http->url == '*')
347    {
348       if  ( NULL == (http->path = strdup("*"))
349          || NULL == (http->hostport = strdup("")) ) 
350       {
351          return JB_ERR_MEMORY;
352       }
353       if (http->url[1] != '\0')
354       {
355          return JB_ERR_PARSE;
356       }
357       return JB_ERR_OK;
358    }
359
360
361    /*
362     * Split URL into protocol,hostport,path.
363     */
364    {
365       char *buf;
366       char *url_noproto;
367       char *url_path;
368
369       buf = strdup(url);
370       if (buf == NULL)
371       {
372          return JB_ERR_MEMORY;
373       }
374
375       /* Find the start of the URL in our scratch space */
376       url_noproto = buf;
377       if (strncmpic(url_noproto, "http://",  7) == 0)
378       {
379          url_noproto += 7;
380          http->ssl = 0;
381       }
382       else if (strncmpic(url_noproto, "https://", 8) == 0)
383       {
384          url_noproto += 8;
385          http->ssl = 1;
386       }
387       else if (*url_noproto == '/')
388       {
389         /*
390          * Short request line without protocol and host.
391          * Most likely because the client's request
392          * was intercepted and redirected into Privoxy.
393          */
394          http->ssl = 0;
395          http->host = NULL;
396          host_available = 0;
397       }
398       else
399       {
400          http->ssl = 0;
401       }
402
403       url_path = strchr(url_noproto, '/');
404       if (url_path != NULL)
405       {
406          /*
407           * Got a path.
408           *
409           * NOTE: The following line ignores the path for HTTPS URLS.
410           * This means that you get consistent behaviour if you type a
411           * https URL in and it's parsed by the function.  (When the
412           * URL is actually retrieved, SSL hides the path part).
413           */
414          http->path = strdup(http->ssl ? "/" : url_path);
415          *url_path = '\0';
416          http->hostport = strdup(url_noproto);
417       }
418       else
419       {
420          /*
421           * Repair broken HTTP requests that don't contain a path,
422           * or CONNECT requests
423           */
424          http->path = strdup("/");
425          http->hostport = strdup(url_noproto);
426       }
427
428       freez(buf);
429
430       if ( (http->path == NULL)
431         || (http->hostport == NULL))
432       {
433          return JB_ERR_MEMORY;
434       }
435    }
436
437    if (!host_available)
438    {
439       /* Without host, there is nothing left to do here */
440       return JB_ERR_OK;
441    }
442
443    /*
444     * Split hostport into user/password (ignored), host, port.
445     */
446    {
447       char *buf;
448       char *host;
449       char *port;
450
451       buf = strdup(http->hostport);
452       if (buf == NULL)
453       {
454          return JB_ERR_MEMORY;
455       }
456
457       /* check if url contains username and/or password */
458       host = strchr(buf, '@');
459       if (host != NULL)
460       {
461          /* Contains username/password, skip it and the @ sign. */
462          host++;
463       }
464       else
465       {
466          /* No username or password. */
467          host = buf;
468       }
469
470       /* check if url contains port */
471       port = strchr(host, ':');
472       if (port != NULL)
473       {
474          /* Contains port */
475          /* Terminate hostname and point to start of port string */
476          *port++ = '\0';
477          http->port = atoi(port);
478       }
479       else
480       {
481          /* No port specified. */
482          http->port = (http->ssl ? 443 : 80);
483       }
484
485       http->host = strdup(host);
486
487       free(buf);
488
489       if (http->host == NULL)
490       {
491          return JB_ERR_MEMORY;
492       }
493    }
494
495    /*
496     * Split domain name so we can compare it against wildcards
497     */
498    return init_domain_components(http);
499
500 }
501
502
503 /*********************************************************************
504  *
505  * Function    :  unknown_method
506  *
507  * Description :  Checks whether a method is unknown.
508  *
509  * Parameters  :
510  *          1  :  method = points to a http method
511  *
512  * Returns     :  TRUE if it's unknown, FALSE otherwise.
513  *
514  *********************************************************************/
515 static int unknown_method(const char *method)
516 {
517    static const char *known_http_methods[] = {
518       /* Basic HTTP request type */
519       "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CONNECT",
520       /* webDAV extensions (RFC2518) */
521       "PROPFIND", "PROPPATCH", "MOVE", "COPY", "MKCOL", "LOCK", "UNLOCK",
522       /*
523        * Microsoft webDAV extension for Exchange 2000.  See:
524        * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
525        * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
526        */ 
527       "BCOPY", "BMOVE", "BDELETE", "BPROPFIND", "BPROPPATCH",
528       /*
529        * Another Microsoft webDAV extension for Exchange 2000.  See:
530        * http://systems.cs.colorado.edu/grunwald/MobileComputing/Papers/draft-cohen-gena-p-base-00.txt
531        * http://lists.w3.org/Archives/Public/w3c-dist-auth/2002JanMar/0001.html
532        * http://msdn.microsoft.com/library/en-us/wss/wss/_webdav_methods.asp
533        */ 
534       "SUBSCRIBE", "UNSUBSCRIBE", "NOTIFY", "POLL",
535       /*
536        * Yet another WebDAV extension, this time for
537        * Web Distributed Authoring and Versioning (RFC3253)
538        */
539       "VERSION-CONTROL", "REPORT", "CHECKOUT", "CHECKIN", "UNCHECKOUT",
540       "MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL", "MKACTIVITY",
541    };
542    int i;
543
544    for (i = 0; i < SZ(known_http_methods); i++)
545    {
546       if (0 == strcmpic(method, known_http_methods[i]))
547       {
548          return FALSE;
549       }
550    }
551
552    return TRUE;
553
554 }
555
556
557 /*********************************************************************
558  *
559  * Function    :  parse_http_request
560  *
561  * Description :  Parse out the host and port from the URL.  Find the
562  *                hostname & path, port (if ':'), and/or password (if '@')
563  *
564  * Parameters  :
565  *          1  :  req = HTTP request line to break down
566  *          2  :  http = pointer to the http structure to hold elements
567  *          3  :  csp = Current client state (buffers, headers, etc...)
568  *
569  * Returns     :  JB_ERR_OK on success
570  *                JB_ERR_MEMORY on out of memory
571  *                JB_ERR_CGI_PARAMS on malformed command/URL
572  *                                  or >100 domains deep.
573  *
574  *********************************************************************/
575 jb_err parse_http_request(const char *req,
576                           struct http_request *http,
577                           const struct client_state *csp)
578 {
579    char *buf;
580    char *v[10]; /* XXX: Why 10? We should only need three. */
581    int n;
582    jb_err err;
583    int is_connect = 0;
584
585    memset(http, '\0', sizeof(*http));
586
587    buf = strdup(req);
588    if (buf == NULL)
589    {
590       return JB_ERR_MEMORY;
591    }
592
593    n = ssplit(buf, " \r\n", v, SZ(v), 1, 1);
594    if (n != 3)
595    {
596       free(buf);
597       return JB_ERR_PARSE;
598    }
599
600    /*
601     * Fail in case of unknown methods
602     * which we might not handle correctly.
603     *
604     * XXX: There should be a config option
605     * to forward requests with unknown methods
606     * anyway. Most of them don't need special
607     * steps.
608     */
609    if (unknown_method(v[0]))
610    {
611       log_error(LOG_LEVEL_ERROR, "Unknown HTTP method detected: %s", v[0]);
612       free(buf);
613       return JB_ERR_PARSE;
614    }
615
616    if (strcmpic(v[0], "CONNECT") == 0)
617    {
618       is_connect = 1;
619    }
620
621    err = parse_http_url(v[1], http, csp);
622    if (err)
623    {
624       free(buf);
625       return err;
626    }
627
628    /*
629     * Copy the details into the structure
630     */
631    http->ssl = is_connect;
632    http->cmd = strdup(req);
633    http->gpc = strdup(v[0]);
634    http->ver = strdup(v[2]);
635
636    if ( (http->cmd == NULL)
637      || (http->gpc == NULL)
638      || (http->ver == NULL) )
639    {
640       free(buf);
641       return JB_ERR_MEMORY;
642    }
643
644    free(buf);
645    return JB_ERR_OK;
646
647 }
648
649
650 #ifdef FEATURE_EXTENDED_HOST_PATTERNS
651 /*********************************************************************
652  *
653  * Function    :  compile_host_pattern
654  *
655  * Description :  Parses and compiles a PCRE host pattern..
656  *
657  * Parameters  :
658  *          1  :  url = Target url_spec to be filled in.
659  *          2  :  host_pattern = Host pattern to compile.
660  *
661  * Returns     :  JB_ERR_OK - Success
662  *                JB_ERR_MEMORY - Out of memory
663  *                JB_ERR_PARSE - Cannot parse regex
664  *
665  *********************************************************************/
666 static jb_err compile_host_pattern(struct url_spec *url, const char *host_pattern)
667 {
668    int errcode;
669    char rebuf[BUFFER_SIZE];
670
671    assert(host_pattern);
672    assert(strlen(host_pattern) < sizeof(rebuf) - 2);
673
674    url->host_regex = zalloc(sizeof(*url->host_regex));
675    if (NULL == url->host_regex)
676    {
677       free_url_spec(url);
678       return JB_ERR_MEMORY;
679    }
680
681    snprintf(rebuf, sizeof(rebuf), "%s$", host_pattern);
682
683    errcode = regcomp(url->host_regex, rebuf,
684       (REG_EXTENDED|REG_NOSUB|REG_ICASE));
685
686    if (errcode)
687    {
688       size_t errlen = regerror(errcode, url->host_regex, rebuf, sizeof(rebuf));
689       if (errlen > (sizeof(rebuf) - (size_t)1))
690       {
691          errlen = sizeof(rebuf) - (size_t)1;
692       }
693       rebuf[errlen] = '\0';
694       log_error(LOG_LEVEL_ERROR, "error compiling %s: %s", url->spec, rebuf);
695       free_url_spec(url);
696
697       return JB_ERR_PARSE;
698    }
699
700    return JB_ERR_OK;
701
702 }
703
704 #else
705
706 /*********************************************************************
707  *
708  * Function    :  compile_host_pattern
709  *
710  * Description :  Parses and "compiles" an old-school host pattern.
711  *
712  * Parameters  :
713  *          1  :  url = Target url_spec to be filled in.
714  *          2  :  host_pattern = Host pattern to parse.
715  *
716  * Returns     :  JB_ERR_OK - Success
717  *                JB_ERR_MEMORY - Out of memory
718  *                JB_ERR_PARSE - Cannot parse regex
719  *
720  *********************************************************************/
721 static jb_err compile_host_pattern(struct url_spec *url, const char *host_pattern)
722 {
723    char *v[150];
724    size_t size;
725    char *p;
726
727    /*
728     * Parse domain part
729     */
730    if (host_pattern[strlen(host_pattern) - 1] == '.')
731    {
732       url->unanchored |= ANCHOR_RIGHT;
733    }
734    if (host_pattern[0] == '.')
735    {
736       url->unanchored |= ANCHOR_LEFT;
737    }
738
739    /* 
740     * Split domain into components
741     */
742    url->dbuffer = strdup(host_pattern);
743    if (NULL == url->dbuffer)
744    {
745       free_url_spec(url);
746       return JB_ERR_MEMORY;
747    }
748
749    /* 
750     * Map to lower case
751     */
752    for (p = url->dbuffer; *p ; p++)
753    {
754       *p = (char)tolower((int)(unsigned char)*p);
755    }
756
757    /* 
758     * Split the domain name into components
759     */
760    url->dcount = ssplit(url->dbuffer, ".", v, SZ(v), 1, 1);
761
762    if (url->dcount < 0)
763    {
764       free_url_spec(url);
765       return JB_ERR_MEMORY;
766    }
767    else if (url->dcount != 0)
768    {
769       /* 
770        * Save a copy of the pointers in dvec
771        */
772       size = (size_t)url->dcount * sizeof(*url->dvec);
773       
774       url->dvec = (char **)malloc(size);
775       if (NULL == url->dvec)
776       {
777          free_url_spec(url);
778          return JB_ERR_MEMORY;
779       }
780
781       memcpy(url->dvec, v, size);
782    }
783    /*
784     * else dcount == 0 in which case we needn't do anything,
785     * since dvec will never be accessed and the pattern will
786     * match all domains.
787     */
788    return JB_ERR_OK;
789 }
790
791
792 /*********************************************************************
793  *
794  * Function    :  simple_domaincmp
795  *
796  * Description :  Domain-wise Compare fqdn's.  The comparison is
797  *                both left- and right-anchored.  The individual
798  *                domain names are compared with simplematch().
799  *                This is only used by domain_match.
800  *
801  * Parameters  :
802  *          1  :  pv = array of patterns to compare
803  *          2  :  fv = array of domain components to compare
804  *          3  :  len = length of the arrays (both arrays are the
805  *                      same length - if they weren't, it couldn't
806  *                      possibly be a match).
807  *
808  * Returns     :  0 => domains are equivalent, else no match.
809  *
810  *********************************************************************/
811 static int simple_domaincmp(char **pv, char **fv, int len)
812 {
813    int n;
814
815    for (n = 0; n < len; n++)
816    {
817       if (simplematch(pv[n], fv[n]))
818       {
819          return 1;
820       }
821    }
822
823    return 0;
824
825 }
826
827
828 /*********************************************************************
829  *
830  * Function    :  domain_match
831  *
832  * Description :  Domain-wise Compare fqdn's. Governed by the bimap in
833  *                pattern->unachored, the comparison is un-, left-,
834  *                right-anchored, or both.
835  *                The individual domain names are compared with
836  *                simplematch().
837  *
838  * Parameters  :
839  *          1  :  pattern = a domain that may contain a '*' as a wildcard.
840  *          2  :  fqdn = domain name against which the patterns are compared.
841  *
842  * Returns     :  0 => domains are equivalent, else no match.
843  *
844  *********************************************************************/
845 static int domain_match(const struct url_spec *pattern, const struct http_request *fqdn)
846 {
847    char **pv, **fv;  /* vectors  */
848    int    plen, flen;
849    int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
850
851    plen = pattern->dcount;
852    flen = fqdn->dcount;
853
854    if (flen < plen)
855    {
856       /* fqdn is too short to match this pattern */
857       return 1;
858    }
859
860    pv   = pattern->dvec;
861    fv   = fqdn->dvec;
862
863    if (unanchored == ANCHOR_LEFT)
864    {
865       /*
866        * Right anchored.
867        *
868        * Convert this into a fully anchored pattern with
869        * the fqdn and pattern the same length
870        */
871       fv += (flen - plen); /* flen - plen >= 0 due to check above */
872       return simple_domaincmp(pv, fv, plen);
873    }
874    else if (unanchored == 0)
875    {
876       /* Fully anchored, check length */
877       if (flen != plen)
878       {
879          return 1;
880       }
881       return simple_domaincmp(pv, fv, plen);
882    }
883    else if (unanchored == ANCHOR_RIGHT)
884    {
885       /* Left anchored, ignore all extra in fqdn */
886       return simple_domaincmp(pv, fv, plen);
887    }
888    else
889    {
890       /* Unanchored */
891       int n;
892       int maxn = flen - plen;
893       for (n = 0; n <= maxn; n++)
894       {
895          if (!simple_domaincmp(pv, fv, plen))
896          {
897             return 0;
898          }
899          /*
900           * Doesn't match from start of fqdn
901           * Try skipping first part of fqdn
902           */
903          fv++;
904       }
905       return 1;
906    }
907
908 }
909 #endif /* def FEATURE_EXTENDED_HOST_PATTERNS */
910
911
912 /*********************************************************************
913  *
914  * Function    :  create_url_spec
915  *
916  * Description :  Creates a "url_spec" structure from a string.
917  *                When finished, free with free_url_spec().
918  *
919  * Parameters  :
920  *          1  :  url = Target url_spec to be filled in.  Will be
921  *                      zeroed before use.
922  *          2  :  buf = Source pattern, null terminated.  NOTE: The
923  *                      contents of this buffer are destroyed by this
924  *                      function.  If this function succeeds, the
925  *                      buffer is copied to url->spec.  If this
926  *                      function fails, the contents of the buffer
927  *                      are lost forever.
928  *
929  * Returns     :  JB_ERR_OK - Success
930  *                JB_ERR_MEMORY - Out of memory
931  *                JB_ERR_PARSE - Cannot parse regex (Detailed message
932  *                               written to system log)
933  *
934  *********************************************************************/
935 jb_err create_url_spec(struct url_spec * url, const char * buf)
936 {
937    char *p;
938    int errcode;
939    size_t errlen;
940    char rebuf[BUFFER_SIZE];
941
942    assert(url);
943    assert(buf);
944
945    /*
946     * Zero memory
947     */
948    memset(url, '\0', sizeof(*url));
949
950    /*
951     * Save a copy of the orignal specification
952     */
953    if ((url->spec = strdup(buf)) == NULL)
954    {
955       return JB_ERR_MEMORY;
956    }
957
958    /* Is it tag pattern? */
959    if (0 == strncmpic("TAG:", url->spec, 4))
960    {
961       if (NULL == (url->tag_regex = zalloc(sizeof(*url->tag_regex))))
962       {
963          freez(url->spec);
964          return JB_ERR_MEMORY;
965       }
966
967       /* buf + 4 to skip "TAG:" */
968       errcode = regcomp(url->tag_regex, buf + 4, (REG_EXTENDED|REG_NOSUB|REG_ICASE));
969       if (errcode)
970       {
971          errlen = regerror(errcode, url->preg, rebuf, sizeof(rebuf));
972          if (errlen > (sizeof(rebuf) - 1))
973          {
974             errlen = sizeof(rebuf) - 1;
975          }
976          rebuf[errlen] = '\0';
977          log_error(LOG_LEVEL_ERROR, "error compiling %s: %s", url->spec, rebuf);
978          free_url_spec(url);
979
980          return JB_ERR_PARSE;
981       }
982       return JB_ERR_OK;
983    }
984
985    /* Only reached for URL patterns */
986    p = strchr(buf, '/');
987    if (NULL != p)
988    {
989       if (*(p+1) != '\0')
990       {
991          url->path = strdup(p);
992          if (NULL == url->path)
993          {
994             free_url_spec(url);
995             return JB_ERR_MEMORY;
996          }
997       }
998       else
999       {
1000          /*
1001           * The path pattern is a single slash and can
1002           * be ignored as it won't affect the result.
1003           */
1004          assert(NULL == url->path);
1005          url->path = NULL;
1006       }
1007       *p = '\0';
1008    }
1009    else
1010    {
1011       url->path = NULL;
1012    }
1013    if (url->path)
1014    {
1015       if (NULL == (url->preg = zalloc(sizeof(*url->preg))))
1016       {
1017          free_url_spec(url);
1018          return JB_ERR_MEMORY;
1019       }
1020
1021       snprintf(rebuf, sizeof(rebuf), "^(%s)", url->path);
1022
1023       errcode = regcomp(url->preg, rebuf,
1024             (REG_EXTENDED|REG_NOSUB|REG_ICASE));
1025       if (errcode)
1026       {
1027          errlen = regerror(errcode, url->preg, rebuf, sizeof(rebuf));
1028
1029          if (errlen > (sizeof(rebuf) - (size_t)1))
1030          {
1031             errlen = sizeof(rebuf) - (size_t)1;
1032          }
1033          rebuf[errlen] = '\0';
1034          log_error(LOG_LEVEL_ERROR, "error compiling %s: %s",
1035             url->spec, rebuf);
1036          free_url_spec(url);
1037
1038          return JB_ERR_PARSE;
1039       }
1040    }
1041
1042    p = strchr(buf, ':');
1043    if (NULL != p)
1044    {
1045       *p++ = '\0';
1046       url->port_list = strdup(p);
1047       if (NULL == url->port_list)
1048       {
1049          return JB_ERR_MEMORY;
1050       }
1051    }
1052    else
1053    {
1054       url->port_list = NULL;
1055    }
1056
1057    if (buf[0] != '\0')
1058    {
1059       return compile_host_pattern(url, buf);
1060    }
1061
1062    return JB_ERR_OK;
1063
1064 }
1065
1066
1067 /*********************************************************************
1068  *
1069  * Function    :  free_url_spec
1070  *
1071  * Description :  Called from the "unloaders".  Freez the url
1072  *                structure elements.
1073  *
1074  * Parameters  :
1075  *          1  :  url = pointer to a url_spec structure.
1076  *
1077  * Returns     :  N/A
1078  *
1079  *********************************************************************/
1080 void free_url_spec(struct url_spec *url)
1081 {
1082    if (url == NULL) return;
1083
1084    freez(url->spec);
1085 #ifdef FEATURE_EXTENDED_HOST_PATTERNS
1086    if (url->host_regex)
1087    {
1088       regfree(url->host_regex);
1089       freez(url->host_regex);
1090    }
1091 #else
1092    freez(url->dbuffer);
1093    freez(url->dvec);
1094    url->dcount = 0;
1095 #endif /* ndef FEATURE_EXTENDED_HOST_PATTERNS */
1096    freez(url->path);
1097    freez(url->port_list);
1098    if (url->preg)
1099    {
1100       regfree(url->preg);
1101       freez(url->preg);
1102    }
1103    if (url->tag_regex)
1104    {
1105       regfree(url->tag_regex);
1106       freez(url->tag_regex);
1107    }
1108 }
1109
1110
1111 /*********************************************************************
1112  *
1113  * Function    :  url_match
1114  *
1115  * Description :  Compare a URL against a URL pattern.
1116  *
1117  * Parameters  :
1118  *          1  :  pattern = a URL pattern
1119  *          2  :  url = URL to match
1120  *
1121  * Returns     :  Nonzero if the URL matches the pattern, else 0.
1122  *
1123  *********************************************************************/
1124 int url_match(const struct url_spec *pattern,
1125               const struct http_request *url)
1126 {
1127    /* XXX: these should probably be functions. */
1128 #define PORT_MATCHES ((NULL == pattern->port_list) || match_portlist(pattern->port_list, url->port))
1129 #ifdef FEATURE_EXTENDED_HOST_PATTERNS
1130 #define DOMAIN_MATCHES ((NULL == pattern->host_regex) || (0 == regexec(pattern->host_regex, url->host, 0, NULL, 0)))
1131 #else
1132 #define DOMAIN_MATCHES ((NULL == pattern->dbuffer) || (0 == domain_match(pattern, url)))
1133 #endif
1134 #define PATH_MATCHES ((NULL == pattern->path) || (0 == regexec(pattern->preg, url->path, 0, NULL, 0)))
1135
1136    if (pattern->tag_regex != NULL)
1137    {
1138       /* It's a tag pattern and shouldn't be matched against URLs */
1139       return 0;
1140    } 
1141
1142    return (PORT_MATCHES && DOMAIN_MATCHES && PATH_MATCHES);
1143
1144 }
1145
1146
1147 /*********************************************************************
1148  *
1149  * Function    :  match_portlist
1150  *
1151  * Description :  Check if a given number is covered by a comma
1152  *                separated list of numbers and ranges (a,b-c,d,..)
1153  *
1154  * Parameters  :
1155  *          1  :  portlist = String with list
1156  *          2  :  port = port to check
1157  *
1158  * Returns     :  0 => no match
1159  *                1 => match
1160  *
1161  *********************************************************************/
1162 int match_portlist(const char *portlist, int port)
1163 {
1164    char *min, *max, *next, *portlist_copy;
1165
1166    min = next = portlist_copy = strdup(portlist);
1167
1168    /*
1169     * Zero-terminate first item and remember offset for next
1170     */
1171    if (NULL != (next = strchr(portlist_copy, (int) ',')))
1172    {
1173       *next++ = '\0';
1174    }
1175
1176    /*
1177     * Loop through all items, checking for match
1178     */
1179    while(min)
1180    {
1181       if (NULL == (max = strchr(min, (int) '-')))
1182       {
1183          /*
1184           * No dash, check for equality
1185           */
1186          if (port == atoi(min))
1187          {
1188             free(portlist_copy);
1189             return(1);
1190          }
1191       }
1192       else
1193       {
1194          /*
1195           * This is a range, so check if between min and max,
1196           * or, if max was omitted, between min and 65K
1197           */
1198          *max++ = '\0';
1199          if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
1200          {
1201             free(portlist_copy);
1202             return(1);
1203          }
1204
1205       }
1206
1207       /*
1208        * Jump to next item
1209        */
1210       min = next;
1211
1212       /*
1213        * Zero-terminate next item and remember offset for n+1
1214        */
1215       if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
1216       {
1217          *next++ = '\0';
1218       }
1219    }
1220
1221    free(portlist_copy);
1222    return 0;
1223
1224 }
1225
1226
1227 /*
1228   Local Variables:
1229   tab-width: 3
1230   end:
1231 */