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