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