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