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