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