correct feedback channels
[privoxy.git] / urlmatch.c
1 const char urlmatch_rcs[] = "$Id: urlmatch.c,v 1.4 2002/03/07 03:46:17 oes 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 the SourceForge
10  *                IJBSWA team.  http://ijbswa.sourceforge.net
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.4  2002/03/07 03:46:17  oes
37  *    Fixed compiler warnings
38  *
39  *    Revision 1.3  2002/03/03 14:51:11  oes
40  *    Fixed CLF logging: Added ocmd member for client's request to struct http_request
41  *
42  *    Revision 1.2  2002/01/21 00:14:09  jongfoster
43  *    Correcting comment style
44  *    Fixing an uninitialized memory bug in create_url_spec()
45  *
46  *    Revision 1.1  2002/01/17 20:53:46  jongfoster
47  *    Moving all our URL and URL pattern parsing code to the same file - it
48  *    was scattered around in filters.c, loaders.c and parsers.c.
49  *
50  *    Providing a single, simple url_match(pattern,url) function - rather than
51  *    the 3-line match routine which was repeated all over the place.
52  *
53  *    Renaming free_url to free_url_spec, since it frees a struct url_spec.
54  *
55  *    Providing parse_http_url() so that URLs can be parsed without faking a
56  *    HTTP request line for parse_http_request() or repeating the parsing
57  *    code (both of which were techniques that were actually in use).
58  *
59  *    Standardizing that struct http_request is used to represent a URL, and
60  *    struct url_spec is used to represent a URL pattern.  (Before, URLs were
61  *    represented as seperate variables and a partially-filled-in url_spec).
62  *
63  *
64  *********************************************************************/
65 \f
66
67 #include "config.h"
68
69 #ifndef _WIN32
70 #include <stdio.h>
71 #include <sys/types.h>
72 #endif
73
74 #include <stdlib.h>
75 #include <ctype.h>
76 #include <assert.h>
77 #include <string.h>
78
79 #if !defined(_WIN32) && !defined(__OS2__)
80 #include <unistd.h>
81 #endif
82
83 #include "project.h"
84 #include "urlmatch.h"
85 #include "ssplit.h"
86 #include "miscutil.h"
87 #include "errlog.h"
88
89 const char urlmatch_h_rcs[] = URLMATCH_H_VERSION;
90
91 /* Fix a problem with Solaris.  There should be no effect on other
92  * platforms.
93  * Solaris's isspace() is a macro which uses it's argument directly
94  * as an array index.  Therefore we need to make sure that high-bit
95  * characters generate +ve values, and ideally we also want to make
96  * the argument match the declared parameter type of "int".
97  *
98  * Why did they write a character function that can't take a simple
99  * "char" argument?  Doh!
100  */
101 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
102 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
103
104
105 /*********************************************************************
106  *
107  * Function    :  free_http_request
108  *
109  * Description :  Freez a http_request structure
110  *
111  * Parameters  :
112  *          1  :  http = points to a http_request structure to free
113  *
114  * Returns     :  N/A
115  *
116  *********************************************************************/
117 void free_http_request(struct http_request *http)
118 {
119    assert(http);
120
121    freez(http->cmd);
122    freez(http->ocmd);
123    freez(http->gpc);
124    freez(http->host);
125    freez(http->url);
126    freez(http->hostport);
127    freez(http->path);
128    freez(http->ver);
129    freez(http->host_ip_addr_str);
130    freez(http->dbuffer);
131    freez(http->dvec);
132    http->dcount = 0;
133 }
134
135
136 /*********************************************************************
137  *
138  * Function    :  parse_http_url
139  *
140  * Description :  Parse out the host and port from the URL.  Find the
141  *                hostname & path, port (if ':'), and/or password (if '@')
142  *
143  * Parameters  :
144  *          1  :  url = URL (or is it URI?) to break down
145  *          2  :  http = pointer to the http structure to hold elements.
146  *                       Will be zeroed before use.  Note that this
147  *                       function sets the http->gpc and http->ver
148  *                       members to NULL.
149  *          3  :  csp = Current client state (buffers, headers, etc...)
150  *
151  * Returns     :  JB_ERR_OK on success
152  *                JB_ERR_MEMORY on out of memory
153  *                JB_ERR_CGI_PARAMS on malformed command/URL
154  *                                  or >100 domains deep.
155  *
156  *********************************************************************/
157 jb_err parse_http_url(const char * url,
158                       struct http_request *http,
159                       struct client_state *csp)
160 {
161    /*
162     * Zero out the results structure
163     */
164    memset(http, '\0', sizeof(*http));
165
166
167    /*
168     * Save our initial URL
169     */
170    http->url = strdup(url);
171    if (http->url == NULL)
172    {
173       return JB_ERR_MEMORY;
174    }
175
176
177    /*
178     * Split URL into protocol,hostport,path.
179     */
180    {
181       char *buf;
182       char *url_noproto;
183       char *url_path;
184
185       buf = strdup(url);
186       if (buf == NULL)
187       {
188          return JB_ERR_MEMORY;
189       }
190
191       /* Find the start of the URL in our scratch space */
192       url_noproto = buf;
193       if (strncmpic(url_noproto, "http://",  7) == 0)
194       {
195          url_noproto += 7;
196          http->ssl = 0;
197       }
198       else if (strncmpic(url_noproto, "https://", 8) == 0)
199       {
200          url_noproto += 8;
201          http->ssl = 1;
202       }
203       else
204       {
205          http->ssl = 0;
206       }
207
208       url_path = strchr(url_noproto, '/');
209       if (url_path != NULL)
210       {
211          /*
212           * Got a path.
213           *
214           * NOTE: The following line ignores the path for HTTPS URLS.
215           * This means that you get consistent behaviour if you type a
216           * https URL in and it's parsed by the function.  (When the
217           * URL is actually retrieved, SSL hides the path part).
218           */
219          http->path = strdup(http->ssl ? "/" : url_path);
220          *url_path = '\0';
221          http->hostport = strdup(url_noproto);
222       }
223       else
224       {
225          /*
226           * Repair broken HTTP requests that don't contain a path,
227           * or CONNECT requests
228           */
229          http->path = strdup("/");
230          http->hostport = strdup(url_noproto);
231       }
232
233       free(buf);
234
235       if ( (http->path == NULL)
236         || (http->hostport == NULL))
237       {
238          free(buf);
239          free_http_request(http);
240          return JB_ERR_MEMORY;
241       }
242    }
243
244
245    /*
246     * Split hostport into user/password (ignored), host, port.
247     */
248    {
249       char *buf;
250       char *host;
251       char *port;
252
253       buf = strdup(http->hostport);
254       if (buf == NULL)
255       {
256          free_http_request(http);
257          return JB_ERR_MEMORY;
258       }
259
260       /* check if url contains username and/or password */
261       host = strchr(buf, '@');
262       if (host != NULL)
263       {
264          /* Contains username/password, skip it and the @ sign. */
265          host++;
266       }
267       else
268       {
269          /* No username or password. */
270          host = buf;
271       }
272
273       /* check if url contains port */
274       port = strchr(host, ':');
275       if (port != NULL)
276       {
277          /* Contains port */
278          /* Terminate hostname and point to start of port string */
279          *port++ = '\0';
280          http->port = atoi(port);
281       }
282       else
283       {
284          /* No port specified. */
285          http->port = (http->ssl ? 143 : 80);
286       }
287
288       http->host = strdup(host);
289
290       free(buf);
291
292       if (http->host == NULL)
293       {
294          free_http_request(http);
295          return JB_ERR_MEMORY;
296       }
297    }
298
299
300    /*
301     * Split domain name so we can compare it against wildcards
302     */
303    {
304       char *vec[BUFFER_SIZE];
305       size_t size;
306       char *p;
307
308       http->dbuffer = strdup(http->host);
309       if (NULL == http->dbuffer)
310       {
311          free_http_request(http);
312          return JB_ERR_MEMORY;
313       }
314
315       /* map to lower case */
316       for (p = http->dbuffer; *p ; p++)
317       {
318          *p = tolower((int)(unsigned char)*p);
319       }
320
321       /* split the domain name into components */
322       http->dcount = ssplit(http->dbuffer, ".", vec, SZ(vec), 1, 1);
323
324       if (http->dcount <= 0)
325       {
326          /*
327           * Error: More than SZ(vec) components in domain
328           *    or: no components in domain
329           */
330          free_http_request(http);
331          return JB_ERR_PARSE;
332       }
333
334       /* save a copy of the pointers in dvec */
335       size = http->dcount * sizeof(*http->dvec);
336
337       http->dvec = (char **)malloc(size);
338       if (NULL == http->dvec)
339       {
340          free_http_request(http);
341          return JB_ERR_MEMORY;
342       }
343
344       memcpy(http->dvec, vec, size);
345    }
346
347
348    return JB_ERR_OK;
349 }
350
351
352 /*********************************************************************
353  *
354  * Function    :  parse_http_request
355  *
356  * Description :  Parse out the host and port from the URL.  Find the
357  *                hostname & path, port (if ':'), and/or password (if '@')
358  *
359  * Parameters  :
360  *          1  :  req = HTTP request line to break down
361  *          2  :  http = pointer to the http structure to hold elements
362  *          3  :  csp = Current client state (buffers, headers, etc...)
363  *
364  * Returns     :  JB_ERR_OK on success
365  *                JB_ERR_MEMORY on out of memory
366  *                JB_ERR_CGI_PARAMS on malformed command/URL
367  *                                  or >100 domains deep.
368  *
369  *********************************************************************/
370 jb_err parse_http_request(const char *req,
371                           struct http_request *http,
372                           struct client_state *csp)
373 {
374    char *buf;
375    char *v[10];
376    int n;
377    jb_err err;
378    int is_connect = 0;
379
380    memset(http, '\0', sizeof(*http));
381
382    buf = strdup(req);
383    if (buf == NULL)
384    {
385       return JB_ERR_MEMORY;
386    }
387
388    n = ssplit(buf, " \r\n", v, SZ(v), 1, 1);
389    if (n != 3)
390    {
391       free(buf);
392       return JB_ERR_PARSE;
393    }
394
395    /* this could be a CONNECT request */
396    if (strcmpic(v[0], "connect") == 0)
397    {
398       /* Secure */
399       is_connect = 1;
400    }
401    /* or it could be any other basic HTTP request type */
402    else if ((0 == strcmpic(v[0], "get"))
403          || (0 == strcmpic(v[0], "head"))
404          || (0 == strcmpic(v[0], "post"))
405          || (0 == strcmpic(v[0], "put"))
406          || (0 == strcmpic(v[0], "delete"))
407  
408          /* or a webDAV extension (RFC2518) */
409          || (0 == strcmpic(v[0], "propfind"))
410          || (0 == strcmpic(v[0], "proppatch"))
411          || (0 == strcmpic(v[0], "move"))
412          || (0 == strcmpic(v[0], "copy"))
413          || (0 == strcmpic(v[0], "mkcol"))
414          || (0 == strcmpic(v[0], "lock"))
415          || (0 == strcmpic(v[0], "unlock"))
416          )
417    {
418       /* Normal */
419       is_connect = 0;
420    }
421    else
422    {
423       /* Unknown HTTP method */
424       free(buf);
425       return JB_ERR_PARSE;
426    }
427
428    err = parse_http_url(v[1], http, csp);
429    if (err)
430    {
431       free(buf);
432       return err;
433    }
434
435    /*
436     * Copy the details into the structure
437     */
438    http->ssl = is_connect;
439    http->cmd = strdup(req);
440    http->gpc = strdup(v[0]);
441    http->ver = strdup(v[2]);
442
443    if ( (http->cmd == NULL)
444      || (http->gpc == NULL)
445      || (http->ver == NULL) )
446    {
447       free(buf);
448       free_http_request(http);
449       return JB_ERR_MEMORY;
450    }
451
452    return JB_ERR_OK;
453 }
454
455
456 /*********************************************************************
457  *
458  * Function    :  simple_domaincmp
459  *
460  * Description :  Domain-wise Compare fqdn's.  The comparison is
461  *                both left- and right-anchored.  The individual
462  *                domain names are compared with simplematch().
463  *                This is only used by domain_match.
464  *
465  * Parameters  :
466  *          1  :  pv = array of patterns to compare
467  *          2  :  fv = array of domain components to compare
468  *          3  :  len = length of the arrays (both arrays are the
469  *                      same length - if they weren't, it couldn't
470  *                      possibly be a match).
471  *
472  * Returns     :  0 => domains are equivalent, else no match.
473  *
474  *********************************************************************/
475 static int simple_domaincmp(char **pv, char **fv, int len)
476 {
477    int n;
478
479    for (n = 0; n < len; n++)
480    {
481       if (simplematch(pv[n], fv[n]))
482       {
483          return 1;
484       }
485    }
486
487    return 0;
488
489 }
490
491
492 /*********************************************************************
493  *
494  * Function    :  domain_match
495  *
496  * Description :  Domain-wise Compare fqdn's. Governed by the bimap in
497  *                pattern->unachored, the comparison is un-, left-,
498  *                right-anchored, or both.
499  *                The individual domain names are compared with
500  *                simplematch().
501  *
502  * Parameters  :
503  *          1  :  pattern = a domain that may contain a '*' as a wildcard.
504  *          2  :  fqdn = domain name against which the patterns are compared.
505  *
506  * Returns     :  0 => domains are equivalent, else no match.
507  *
508  *********************************************************************/
509 static int domain_match(const struct url_spec *pattern, const struct http_request *fqdn)
510 {
511    char **pv, **fv;  /* vectors  */
512    int    plen, flen;
513    int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
514
515    plen = pattern->dcount;
516    flen = fqdn->dcount;
517
518    if (flen < plen)
519    {
520       /* fqdn is too short to match this pattern */
521       return 1;
522    }
523
524    pv   = pattern->dvec;
525    fv   = fqdn->dvec;
526
527    if (unanchored == ANCHOR_LEFT)
528    {
529       /*
530        * Right anchored.
531        *
532        * Convert this into a fully anchored pattern with
533        * the fqdn and pattern the same length
534        */
535       fv += (flen - plen); /* flen - plen >= 0 due to check above */
536       return simple_domaincmp(pv, fv, plen);
537    }
538    else if (unanchored == 0)
539    {
540       /* Fully anchored, check length */
541       if (flen != plen)
542       {
543          return 1;
544       }
545       return simple_domaincmp(pv, fv, plen);
546    }
547    else if (unanchored == ANCHOR_RIGHT)
548    {
549       /* Left anchored, ignore all extra in fqdn */
550       return simple_domaincmp(pv, fv, plen);
551    }
552    else
553    {
554       /* Unanchored */
555       int n;
556       int maxn = flen - plen;
557       for (n = 0; n <= maxn; n++)
558       {
559          if (!simple_domaincmp(pv, fv, plen))
560          {
561             return 0;
562          }
563          /*
564           * Doesn't match from start of fqdn
565           * Try skipping first part of fqdn
566           */
567          fv++;
568       }
569       return 1;
570    }
571
572 }
573
574
575 /*********************************************************************
576  *
577  * Function    :  create_url_spec
578  *
579  * Description :  Creates a "url_spec" structure from a string.
580  *                When finished, free with unload_url().
581  *
582  * Parameters  :
583  *          1  :  url = Target url_spec to be filled in.  Will be
584  *                      zeroed before use.
585  *          2  :  buf = Source pattern, null terminated.  NOTE: The
586  *                      contents of this buffer are destroyed by this
587  *                      function.  If this function succeeds, the
588  *                      buffer is copied to url->spec.  If this
589  *                      function fails, the contents of the buffer
590  *                      are lost forever.
591  *
592  * Returns     :  JB_ERR_OK - Success
593  *                JB_ERR_MEMORY - Out of memory
594  *                JB_ERR_PARSE - Cannot parse regex (Detailed message
595  *                               written to system log)
596  *
597  *********************************************************************/
598 jb_err create_url_spec(struct url_spec * url, const char * buf)
599 {
600    char *p;
601
602    assert(url);
603    assert(buf);
604
605    /* Zero memory */
606    memset(url, '\0', sizeof(*url));
607
608    /* save a copy of the orignal specification */
609    if ((url->spec = strdup(buf)) == NULL)
610    {
611       return JB_ERR_MEMORY;
612    }
613
614    if ((p = strchr(buf, '/')) != NULL)
615    {
616       if (NULL == (url->path = strdup(p)))
617       {
618          freez(url->spec);
619          return JB_ERR_MEMORY;
620       }
621       url->pathlen = strlen(url->path);
622       *p = '\0';
623    }
624    else
625    {
626       url->path    = NULL;
627       url->pathlen = 0;
628    }
629 #ifdef REGEX
630    if (url->path)
631    {
632       int errcode;
633       char rebuf[BUFFER_SIZE];
634
635       if (NULL == (url->preg = zalloc(sizeof(*url->preg))))
636       {
637          freez(url->spec);
638          freez(url->path);
639          return JB_ERR_MEMORY;
640       }
641
642       sprintf(rebuf, "^(%s)", url->path);
643
644       errcode = regcomp(url->preg, rebuf,
645             (REG_EXTENDED|REG_NOSUB|REG_ICASE));
646       if (errcode)
647       {
648          size_t errlen = regerror(errcode,
649             url->preg, rebuf, sizeof(rebuf));
650
651          if (errlen > (sizeof(rebuf) - (size_t)1))
652          {
653             errlen = sizeof(rebuf) - (size_t)1;
654          }
655          rebuf[errlen] = '\0';
656
657          log_error(LOG_LEVEL_ERROR, "error compiling %s: %s",
658             url->spec, rebuf);
659
660          freez(url->spec);
661          freez(url->path);
662          freez(url->preg);
663
664          return JB_ERR_PARSE;
665       }
666    }
667 #endif
668    if ((p = strchr(buf, ':')) == NULL)
669    {
670       url->port = 0;
671    }
672    else
673    {
674       *p++ = '\0';
675       url->port = atoi(p);
676    }
677
678    if (buf[0] != '\0')
679    {
680       char *v[150];
681       size_t size;
682
683       /* Parse domain part */
684       if (buf[strlen(buf) - 1] == '.')
685       {
686          url->unanchored |= ANCHOR_RIGHT;
687       }
688       if (buf[0] == '.')
689       {
690          url->unanchored |= ANCHOR_LEFT;
691       }
692
693       /* split domain into components */
694
695       url->dbuffer = strdup(buf);
696       if (NULL == url->dbuffer)
697       {
698          freez(url->spec);
699          freez(url->path);
700 #ifdef REGEX
701          freez(url->preg);
702 #endif /* def REGEX */
703          return JB_ERR_MEMORY;
704       }
705
706       /* map to lower case */
707       for (p = url->dbuffer; *p ; p++)
708       {
709          *p = tolower((int)(unsigned char)*p);
710       }
711
712       /* split the domain name into components */
713       url->dcount = ssplit(url->dbuffer, ".", v, SZ(v), 1, 1);
714
715       if (url->dcount < 0)
716       {
717          freez(url->spec);
718          freez(url->path);
719 #ifdef REGEX
720          freez(url->preg);
721 #endif /* def REGEX */
722          freez(url->dbuffer);
723          url->dcount = 0;
724          return JB_ERR_MEMORY;
725       }
726       else if (url->dcount != 0)
727       {
728
729          /* save a copy of the pointers in dvec */
730          size = url->dcount * sizeof(*url->dvec);
731
732          url->dvec = (char **)malloc(size);
733          if (NULL == url->dvec)
734          {
735             freez(url->spec);
736             freez(url->path);
737 #ifdef REGEX
738             freez(url->preg);
739 #endif /* def REGEX */
740             freez(url->dbuffer);
741             url->dcount = 0;
742             return JB_ERR_MEMORY;
743          }
744
745          memcpy(url->dvec, v, size);
746       }
747    }
748
749    return JB_ERR_OK;
750
751 }
752
753
754 /*********************************************************************
755  *
756  * Function    :  free_url_spec
757  *
758  * Description :  Called from the "unloaders".  Freez the url
759  *                structure elements.
760  *
761  * Parameters  :
762  *          1  :  url = pointer to a url_spec structure.
763  *
764  * Returns     :  N/A
765  *
766  *********************************************************************/
767 void free_url_spec(struct url_spec *url)
768 {
769    if (url == NULL) return;
770
771    freez(url->spec);
772    freez(url->dbuffer);
773    freez(url->dvec);
774    freez(url->path);
775 #ifdef REGEX
776    if (url->preg)
777    {
778       regfree(url->preg);
779       freez(url->preg);
780    }
781 #endif
782
783 }
784
785
786 /*********************************************************************
787  *
788  * Function    :  url_match
789  *
790  * Description :  Compare a URL against a URL pattern.
791  *
792  * Parameters  :
793  *          1  :  pattern = a URL pattern
794  *          2  :  url = URL to match
795  *
796  * Returns     :  0 iff the URL matches the pattern, else nonzero.
797  *
798  *********************************************************************/
799 int url_match(const struct url_spec *pattern,
800               const struct http_request *url)
801 {
802    return ((pattern->port == 0) || (pattern->port == url->port))
803        && ((pattern->dbuffer == NULL) || (domain_match(pattern, url) == 0))
804        && ((pattern->path == NULL) ||
805 #ifdef REGEX
806             (regexec(pattern->preg, url->path, 0, NULL, 0) == 0)
807 #else
808             (strncmp(pattern->path, url->path, pattern->pathlen) == 0)
809 #endif
810       );
811 }
812
813
814 /*
815   Local Variables:
816   tab-width: 3
817   end:
818 */