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