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