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