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