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