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