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