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