57ad34c5fac87af64d20b20d4142b1e5669bb9c1
[privoxy.git] / filters.c
1 const char filters_rcs[] = "$Id: filters.c,v 1.37 2001/10/22 15:33:56 david__schmidt Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/filters.c,v $
5  *
6  * Purpose     :  Declares functions to parse/crunch headers and pages.
7  *                Functions declared include:
8  *                   `acl_addr', `add_stats', `block_acl', `block_imageurl',
9  *                   `block_url', `url_actions', `domaincmp', `dsplit',
10  *                   `filter_popups', `forward_url', 'redirect_url',
11  *                   `ij_untrusted_url', `intercept_url', `pcrs_filter_respose',
12  *                   `show_proxy_args', 'ijb_send_banner', and `trust_url'
13  *
14  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
15  *                IJBSWA team.  http://ijbswa.sourceforge.net
16  *
17  *                Based on the Internet Junkbuster originally written
18  *                by and Copyright (C) 1997 Anonymous Coders and 
19  *                Junkbusters Corporation.  http://www.junkbusters.com
20  *
21  *                This program is free software; you can redistribute it 
22  *                and/or modify it under the terms of the GNU General
23  *                Public License as published by the Free Software
24  *                Foundation; either version 2 of the License, or (at
25  *                your option) any later version.
26  *
27  *                This program is distributed in the hope that it will
28  *                be useful, but WITHOUT ANY WARRANTY; without even the
29  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
30  *                PARTICULAR PURPOSE.  See the GNU General Public
31  *                License for more details.
32  *
33  *                The GNU General Public License should be included with
34  *                this file.  If not, you can view it at
35  *                http://www.gnu.org/copyleft/gpl.html
36  *                or write to the Free Software Foundation, Inc., 59
37  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
38  *
39  * Revisions   :
40  *    $Log: filters.c,v $
41  *    Revision 1.37  2001/10/22 15:33:56  david__schmidt
42  *    Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
43  *    filters.c.  Added a FIXME in front of the offending code.  I'll gladly
44  *    put in a better/more robust fix for all parties if one is presented...
45  *    It seems that just returning 200 instead of 404 would pretty much fix
46  *    it for everyone, but I don't know all the history of the problem.
47  *
48  *    Revision 1.36  2001/10/10 16:44:16  oes
49  *    Added match_portlist function
50  *
51  *    Revision 1.35  2001/10/07 15:41:23  oes
52  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
53  *
54  *    New function remove_chunked_transfer_coding that strips chunked
55  *      transfer coding to plain and is called by pcrs_filter_response
56  *      and gif_deanimate_response if neccessary
57  *
58  *    Improved handling of zero-change re_filter runs
59  *
60  *    pcrs_filter_response and gif_deanimate_response now remove
61  *      chunked transfer codeing before processing the body.
62  *
63  *    Revision 1.34  2001/09/20 15:49:36  steudten
64  *
65  *    Fix BUG: Change int size to size_t size in pcrs_filter_response().
66  *    See cgi.c fill_template().
67  *
68  *    Revision 1.33  2001/09/16 17:05:14  jongfoster
69  *    Removing unused #include showarg.h
70  *
71  *    Revision 1.32  2001/09/16 13:21:27  jongfoster
72  *    Changes to use new list functions.
73  *
74  *    Revision 1.31  2001/09/16 11:38:02  jongfoster
75  *    Splitting fill_template() into 2 functions:
76  *    template_load() loads the file
77  *    template_fill() performs the PCRS regexps.
78  *    This is because the CGI edit interface has a "table row"
79  *    template which is used many times in the page - this
80  *    change means it's only loaded from disk once.
81  *
82  *    Revision 1.30  2001/09/16 11:00:10  jongfoster
83  *    New function alloc_http_response, for symmetry with free_http_response
84  *
85  *    Revision 1.29  2001/09/13 23:32:40  jongfoster
86  *    Moving image data to cgi.c rather than cgi.h
87  *    Fixing a GPF under Win32 (and any other OS that protects global
88  *    constants from being written to).
89  *
90  *    Revision 1.28  2001/09/10 10:18:51  oes
91  *    Silenced compiler warnings
92  *
93  *    Revision 1.27  2001/08/05 16:06:20  jongfoster
94  *    Modifiying "struct map" so that there are now separate header and
95  *    "map_entry" structures.  This means that functions which modify a
96  *    map no longer need to return a pointer to the modified map.
97  *    Also, it no longer reverses the order of the entries (which may be
98  *    important with some advanced template substitutions).
99  *
100  *    Revision 1.26  2001/07/30 22:08:36  jongfoster
101  *    Tidying up #defines:
102  *    - All feature #defines are now of the form FEATURE_xxx
103  *    - Permanently turned off WIN_GUI_EDIT
104  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
105  *
106  *    Revision 1.25  2001/07/26 10:09:46  oes
107  *    Made browser detection a little less naive
108  *
109  *    Revision 1.24  2001/07/25 17:22:51  oes
110  *    Added workaround for Netscape bug that prevents display of page when loading a component fails.
111  *
112  *    Revision 1.23  2001/07/23 13:40:12  oes
113  *    Fixed bug that caused document body to be dropped when pcrs joblist was empty.
114  *
115  *    Revision 1.22  2001/07/18 12:29:34  oes
116  *    - Made gif_deanimate_response respect
117  *      csp->action->string[ACTION_STRING_DEANIMATE]
118  *    - Logging cosmetics
119  *
120  *    Revision 1.21  2001/07/13 13:59:53  oes
121  *     - Introduced gif_deanimate_response which shares the
122  *       generic content modification interface of pcrs_filter_response
123  *       and acts as a wrapper to deanimate.c:gif_deanimate()
124  *     - Renamed re_process_buffer to pcrs_filter_response
125  *     - pcrs_filter_response now returns NULL on failiure
126  *     - Removed all #ifdef PCRS
127  *
128  *    Revision 1.20  2001/07/01 17:01:04  oes
129  *    Added comments and missing return statement in is_untrusted_url()
130  *
131  *    Revision 1.19  2001/06/29 21:45:41  oes
132  *    Indentation, CRLF->LF, Tab-> Space
133  *
134  *    Revision 1.18  2001/06/29 13:27:38  oes
135  *    - Cleaned up, renamed and reorderd functions
136  *      and improved comments
137  *
138  *    - block_url:
139  *      - Ported to CGI platform. Now delivers
140  *        http_response or NULL
141  *      - Unified HTML and GIF generation (moved image detection
142  *        and GIF generation here from jcc.c:chat())
143  *      - Fixed HTTP status to:
144  *       -  403 (Forbidden) for the "blocked" HTML message
145  *       -  200 (OK) for GIF answers
146  *       -  302 (Redirect) for redirect to GIF
147  *
148  *    - trust_url:
149  *      - Ported to CGI platform. Now delivers
150  *        http_response or NULL
151  *      - Separated detection of untrusted URL into
152  *        (bool)is_untrusted_url
153  *      - Added enforcement of untrusted requests
154  *
155  *    - Moved redirect_url() from cgi.c to here
156  *      and ported it to the CGI platform
157  *
158  *    - Removed logentry from cancelled commit
159  *
160  *    Revision 1.17  2001/06/09 10:55:28  jongfoster
161  *    Changing BUFSIZ ==> BUFFER_SIZE
162  *
163  *    Revision 1.16  2001/06/07 23:10:26  jongfoster
164  *    Allowing unanchored domain patterns to back off and retry
165  *    if they partially match.  Optimized right-anchored patterns.
166  *    Moving ACL and forward files into config file.
167  *    Replacing struct gateway with struct forward_spec
168  *
169  *    Revision 1.15  2001/06/03 19:12:00  oes
170  *    extracted-CGI relevant stuff
171  *
172  *    Revision 1.14  2001/06/01 10:30:55  oes
173  *    Added optional left-anchoring to domaincmp
174  *
175  *    Revision 1.13  2001/05/31 21:21:30  jongfoster
176  *    Permissionsfile / actions file changes:
177  *    - Changed "permission" to "action" throughout
178  *    - changes to file format to allow string parameters
179  *    - Moved helper functions to actions.c
180  *
181  *    Revision 1.12  2001/05/31 17:35:20  oes
182  *
183  *     - Enhanced domain part globbing with infix and prefix asterisk
184  *       matching and optional unanchored operation
185  *
186  *    Revision 1.11  2001/05/29 11:53:23  oes
187  *    "See why" link added to "blocked" page
188  *
189  *    Revision 1.10  2001/05/29 09:50:24  jongfoster
190  *    Unified blocklist/imagelist/permissionslist.
191  *    File format is still under discussion, but the internal changes
192  *    are (mostly) done.
193  *
194  *    Also modified interceptor behaviour:
195  *    - We now intercept all URLs beginning with one of the following
196  *      prefixes (and *only* these prefixes):
197  *        * http://i.j.b/
198  *        * http://ijbswa.sf.net/config/
199  *        * http://ijbswa.sourceforge.net/config/
200  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
201  *    - Internal changes so that intercepted and fast redirect pages
202  *      are not replaced with an image.
203  *    - Interceptors now have the option to send a binary page direct
204  *      to the client. (i.e. ijb-send-banner uses this)
205  *    - Implemented show-url-info interceptor.  (Which is why I needed
206  *      the above interceptors changes - a typical URL is
207  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
208  *      The previous mechanism would not have intercepted that, and
209  *      if it had been intercepted then it then it would have replaced
210  *      it with an image.)
211  *
212  *    Revision 1.9  2001/05/27 22:17:04  oes
213  *
214  *    - re_process_buffer no longer writes the modified buffer
215  *      to the client, which was very ugly. It now returns the
216  *      buffer, which it is then written by chat.
217  *
218  *    - content_length now adjusts the Content-Length: header
219  *      for modified documents rather than crunch()ing it.
220  *      (Length info in csp->content_length, which is 0 for
221  *      unmodified documents)
222  *
223  *    - For this to work, sed() is called twice when filtering.
224  *
225  *    Revision 1.8  2001/05/26 17:13:28  jongfoster
226  *    Filled in a function comment.
227  *
228  *    Revision 1.7  2001/05/26 15:26:15  jongfoster
229  *    ACL feature now provides more security by immediately dropping
230  *    connections from untrusted hosts.
231  *
232  *    Revision 1.6  2001/05/26 00:28:36  jongfoster
233  *    Automatic reloading of config file.
234  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
235  *    Most of the global variables have been moved to a new
236  *    struct configuration_spec, accessed through csp->config->globalname
237  *    Most of the globals remaining are used by the Win32 GUI.
238  *
239  *    Revision 1.5  2001/05/25 22:34:30  jongfoster
240  *    Hard tabs->Spaces
241  *
242  *    Revision 1.4  2001/05/22 18:46:04  oes
243  *
244  *    - Enabled filtering banners by size rather than URL
245  *      by adding patterns that replace all standard banner
246  *      sizes with the "Junkbuster" gif to the re_filterfile
247  *
248  *    - Enabled filtering WebBugs by providing a pattern
249  *      which kills all 1x1 images
250  *
251  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
252  *      which is selected by the (nonstandard and therefore
253  *      capital) letter 'U' in the option string.
254  *      It causes the quantifiers to be ungreedy by default.
255  *      Appending a ? turns back to greedy (!).
256  *
257  *    - Added a new interceptor ijb-send-banner, which
258  *      sends back the "Junkbuster" gif. Without imagelist or
259  *      MSIE detection support, or if tinygif = 1, or the
260  *      URL isn't recognized as an imageurl, a lame HTML
261  *      explanation is sent instead.
262  *
263  *    - Added new feature, which permits blocking remote
264  *      script redirects and firing back a local redirect
265  *      to the browser.
266  *      The feature is conditionally compiled, i.e. it
267  *      can be disabled with --disable-fast-redirects,
268  *      plus it must be activated by a "fast-redirects"
269  *      line in the config file, has its own log level
270  *      and of course wants to be displayed by show-proxy-args
271  *      Note: Boy, all the #ifdefs in 1001 locations and
272  *      all the fumbling with configure.in and acconfig.h
273  *      were *way* more work than the feature itself :-(
274  *
275  *    - Because a generic redirect template was needed for
276  *      this, tinygif = 3 now uses the same.
277  *
278  *    - Moved GIFs, and other static HTTP response templates
279  *      to project.h
280  *
281  *    - Some minor fixes
282  *
283  *    - Removed some >400 CRs again (Jon, you really worked
284  *      a lot! ;-)
285  *
286  *    Revision 1.3  2001/05/20 16:44:47  jongfoster
287  *    Removing last hardcoded JunkBusters.com URLs.
288  *
289  *    Revision 1.2  2001/05/20 01:21:20  jongfoster
290  *    Version 2.9.4 checkin.
291  *    - Merged popupfile and cookiefile, and added control over PCRS
292  *      filtering, in new "permissionsfile".
293  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
294  *      file error you now get a message box (in the Win32 GUI) rather
295  *      than the program exiting with no explanation.
296  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
297  *      skipping.
298  *    - Removed tabs from "config"
299  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
300  *    - Bumped up version number.
301  *
302  *    Revision 1.1.1.1  2001/05/15 13:58:52  oes
303  *    Initial import of version 2.9.3 source tree
304  *
305  *
306  *********************************************************************/
307 \f
308
309 #include "config.h"
310
311 #include <stdio.h>
312 #include <sys/types.h>
313 #include <stdlib.h>
314 #include <ctype.h>
315 #include <string.h>
316 #include <assert.h>
317
318 #ifndef _WIN32
319 #include <unistd.h>
320 #include <netinet/in.h>
321 #else
322 #include <winsock2.h>
323 #endif
324
325 #include "project.h"
326 #include "filters.h"
327 #include "encode.h"
328 #include "parsers.h"
329 #include "ssplit.h"
330 #include "errlog.h"
331 #include "jbsockets.h"
332 #include "miscutil.h"
333 #include "actions.h"
334 #include "cgi.h"
335 #include "list.h"
336 #include "deanimate.h"
337
338 #ifdef _WIN32
339 #include "win32.h"
340 #endif
341
342 const char filters_h_rcs[] = FILTERS_H_VERSION;
343
344 /* Fix a problem with Solaris.  There should be no effect on other
345  * platforms.
346  * Solaris's isspace() is a macro which uses it's argument directly
347  * as an array index.  Therefore we need to make sure that high-bit
348  * characters generate +ve values, and ideally we also want to make
349  * the argument match the declared parameter type of "int".
350  */
351 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
352
353
354 #ifdef FEATURE_ACL
355 /*********************************************************************
356  *
357  * Function    :  block_acl
358  *
359  * Description :  Block this request?
360  *                Decide yes or no based on ACL file.
361  *
362  * Parameters  :
363  *          1  :  dst = The proxy or gateway address this is going to.
364  *                      Or NULL to check all possible targets.
365  *          2  :  csp = Current client state (buffers, headers, etc...)
366  *                      Also includes the client IP address.
367  *
368  * Returns     : 0 = FALSE (don't block) and 1 = TRUE (do block)
369  *
370  *********************************************************************/
371 int block_acl(struct access_control_addr *dst, struct client_state *csp)
372 {
373    struct access_control_list *acl = csp->config->acl;
374
375    /* if not using an access control list, then permit the connection */
376    if (acl == NULL)
377    {
378       return(0);
379    }
380
381    /* search the list */
382    while (acl != NULL)
383    {
384       if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
385       {
386          if (dst == NULL)
387          {
388             /* Just want to check if they have any access */
389             if (acl->action == ACL_PERMIT)
390             {
391                return(0);
392             }
393          }
394          else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
395            && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
396          {
397             if (acl->action == ACL_PERMIT)
398             {
399                return(0);
400             }
401             else
402             {
403                return(1);
404             }
405          }
406       }
407       acl = acl->next;
408    }
409
410    return(1);
411
412 }
413
414
415 /*********************************************************************
416  *
417  * Function    :  acl_addr
418  *
419  * Description :  Called from `load_aclfile' to parse an ACL address.
420  *
421  * Parameters  :
422  *          1  :  aspec = String specifying ACL address.
423  *          2  :  aca = struct access_control_addr to fill in.
424  *
425  * Returns     :  0 => Ok, everything else is an error.
426  *
427  *********************************************************************/
428 int acl_addr(char *aspec, struct access_control_addr *aca)
429 {
430    int i, masklength, port;
431    char *p;
432
433    masklength = 32;
434    port       =  0;
435
436    if ((p = strchr(aspec, '/')))
437    {
438       *p++ = '\0';
439
440       if (ijb_isdigit(*p) == 0)
441       {
442          return(-1);
443       }
444       masklength = atoi(p);
445    }
446
447    if ((masklength < 0) || (masklength > 32))
448    {
449       return(-1);
450    }
451
452    if ((p = strchr(aspec, ':')))
453    {
454       *p++ = '\0';
455
456       if (ijb_isdigit(*p) == 0)
457       {
458          return(-1);
459       }
460       port = atoi(p);
461    }
462
463    aca->port = port;
464
465    aca->addr = ntohl(resolve_hostname_to_ip(aspec));
466
467    if (aca->addr == -1)
468    {
469       log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
470       return(-1);
471    }
472
473    /* build the netmask */
474    aca->mask = 0;
475    for (i=1; i <= masklength ; i++)
476    {
477       aca->mask |= (1 << (32 - i));
478    }
479
480    /* now mask off the host portion of the ip address
481     * (i.e. save on the network portion of the address).
482     */
483    aca->addr = aca->addr & aca->mask;
484
485    return(0);
486
487 }
488 #endif /* def FEATURE_ACL */
489
490
491 /*********************************************************************
492  *
493  * Function    :  match_portlist
494  *
495  * Description :  Check if a given number is covered by a comma
496  *                separated list of numbers and ranges (a,b-c,d,..)
497  *
498  * Parameters  :
499  *          1  :  portlist = String with list
500  *          2  :  port = port to check
501  *
502  * Returns     :  0 => no match
503  *                1 => match
504  *
505  *********************************************************************/
506 int match_portlist(const char *portlist, int port)
507 {
508    char *min, *max, *next, *portlist_copy;
509
510    min = next = portlist_copy = strdup(portlist);
511
512    /*
513     * Zero-terminate first item and remember offset for next
514     */
515    if (NULL != (next = strchr(portlist_copy, (int) ',')))
516    {
517       *next++ = '\0';
518    }
519    
520    /*
521     * Loop through all items, checking for match
522     */
523    while(min)
524    {
525       if (NULL == (max = strchr(min, (int) '-')))
526       {
527          /*
528           * No dash, check for equality
529           */
530          if (port == atoi(min))
531          {
532             free(portlist_copy);
533             return(1);
534          }
535       }
536       else
537       {
538          /*
539           * This is a range, so check if between min and max,
540           * or, if max was omitted, between min and 65K
541           */
542          *max++ = '\0';
543          if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
544          {
545             free(portlist_copy);
546             return(1);
547          }
548            
549       }      
550
551       /*
552        * Jump to next item
553        */
554       min = next;
555
556       /*
557        * Zero-terminate next item and remember offset for n+1
558        */
559       if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
560       {
561          *next++ = '\0';
562       }
563    }
564    
565    free(portlist_copy);
566    return 0;
567
568 }
569
570
571 /*********************************************************************
572  *
573  * Function    :  block_url
574  *
575  * Description :  Called from `chat'.  Check to see if we need to block this.
576  *
577  * Parameters  :
578  *          1  :  csp = Current client state (buffers, headers, etc...)
579  *
580  * Returns     :  NULL => unblocked, else HTTP block response
581  *
582  *********************************************************************/
583 struct http_response *block_url(struct client_state *csp)
584 {
585 #ifdef FEATURE_IMAGE_BLOCKING
586    char *p;
587 #endif /* def FEATURE_IMAGE_BLOCKING */
588    struct http_response *rsp;
589
590    /* 
591     * If it's not blocked, don't block it ;-)
592     */
593    if ((csp->action->flags & ACTION_BLOCK) == 0)
594    {
595       return NULL;
596    }
597
598    /* 
599     * Else, prepare a response
600     */
601    if (NULL == (rsp = alloc_http_response()))
602    {
603       return cgi_error_memory();
604    }
605
606    /*
607     * If it's an image-url, send back an image or redirect
608     * as specified by the relevant +image action
609     */
610 #ifdef FEATURE_IMAGE_BLOCKING
611    if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
612         && is_imageurl(csp))
613    {
614       /* determine HOW images should be blocked */
615       p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
616
617       /* and handle accordingly: */
618       if ((p == NULL) || (0 == strcmpic(p, "logo")))
619       {
620          rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
621          if (rsp->body == NULL)
622          {
623             free_http_response(rsp);
624             return cgi_error_memory();
625          }
626          rsp->content_length = image_junkbuster_gif_length;
627
628          if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
629          {
630             free_http_response(rsp);
631             return cgi_error_memory();
632          }
633       }
634
635       else if (0 == strcmpic(p, "blank"))
636       {
637          rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
638          if (rsp->body == NULL)
639          {
640             free_http_response(rsp);
641             return cgi_error_memory();
642          }
643          rsp->content_length = image_blank_gif_length;
644
645          if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
646          {
647             free_http_response(rsp);
648             return cgi_error_memory();
649          }
650       }
651
652       else
653       {
654          rsp->status = strdup("302 Local Redirect from Junkbuster");
655          if (rsp->status == NULL)
656          {
657             free_http_response(rsp);
658             return cgi_error_memory();
659          }
660
661          if (enlist_unique_header(rsp->headers, "Location", p))
662          {
663             free_http_response(rsp);
664             return cgi_error_memory();
665          }
666       }
667    }  
668    else
669 #endif /* def FEATURE_IMAGE_BLOCKING */
670
671    /* 
672     * Else, generate an HTML "blocked" message:
673     */
674    {
675       jb_err err;
676       struct map * exports;
677       
678       /* FIXME */
679 #ifdef __EMX__
680       /*
681        * The entire OS/2 community will hit the stupid Netscape bug
682        * (all three of us! :-) so we'll just keep ourselves out
683        * of this contentious debate and special-case ourselves.
684        * The problem is... a this point in parsing, we don't know
685        * what the csp->http->user_agent is (yet).  So we can't use
686        * it to decide if we should work around the NS bug or not.
687        */
688       rsp->status = strdup("200 Request for blocked URL"); 
689 #else
690       /*
691        * Workaround for stupid Netscape bug which prevents
692        * pages from being displayed if loading a referenced
693        * JavaScript or style sheet fails. So make it appear
694        * as if it succeeded.
695        */
696       if (csp->http->user_agent
697           && !strncmpic(csp->http->user_agent, "mozilla", 7)
698           && !strstr(csp->http->user_agent, "compatible")
699           && !strstr(csp->http->user_agent, "Opera"))
700       {
701          rsp->status = strdup("200 Request for blocked URL"); 
702       }
703       else
704       {
705          rsp->status = strdup("404 Request for blocked URL"); 
706       }
707 #endif /* __EMX__ */
708       if (rsp->status == NULL)
709       {
710          free_http_response(rsp);
711          return cgi_error_memory();
712       }
713
714       exports = default_exports(csp, NULL);
715       if (exports == NULL)
716       {
717          free_http_response(rsp);
718          return cgi_error_memory();
719       }
720
721 #ifdef FEATURE_FORCE_LOAD
722       err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
723 #else /* ifndef FEATURE_FORCE_LOAD */
724       err = map_block_killer(exports, "force-support");
725 #endif /* ndef FEATURE_FORCE_LOAD */
726
727       err = err || map(exports, "hostport", 1, csp->http->hostport, 1);
728       err = err || map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
729       err = err || map(exports, "path", 1, csp->http->path, 1);
730       err = err || map(exports, "path-html", 1, html_encode(csp->http->path), 0);
731
732       if (err)
733       {
734          free_map(exports);
735          free_http_response(rsp);
736          return cgi_error_memory();
737       }
738
739       err = template_fill_for_cgi(csp, "blocked", exports, rsp);
740       if (err)
741       {
742          free_http_response(rsp);
743          return cgi_error_memory();
744       }
745    }
746
747    return finish_http_response(rsp);
748
749 }
750
751
752 #ifdef FEATURE_TRUST
753 /*********************************************************************
754  *
755  * Function    :  trust_url FIXME: I should be called distrust_url
756  *
757  * Description :  Calls is_untrusted_url to determine if the URL is trusted
758  *                and if not, returns a HTTP 304 response with a reject message.
759  *
760  * Parameters  :
761  *          1  :  csp = Current client state (buffers, headers, etc...)
762  *
763  * Returns     :  NULL => trusted, else http_response.
764  *
765  *********************************************************************/
766 struct http_response *trust_url(struct client_state *csp)
767 {
768    struct http_response *rsp;
769    struct map * exports;
770    char buf[BUFFER_SIZE];
771    char *p;
772    struct url_spec **tl;
773    struct url_spec *t;
774    jb_err err;
775
776    /*
777     * Don't bother to work on trusted URLs
778     */
779    if (!is_untrusted_url(csp))
780    {
781       return NULL;
782    }
783
784    /* 
785     * Else, prepare a response:
786     */
787    if (NULL == (rsp = alloc_http_response()))
788    {
789       return cgi_error_memory();
790    }
791
792    exports = default_exports(csp, NULL);
793    if (exports == NULL)
794    {
795       free_http_response(rsp);
796       return cgi_error_memory();
797    }
798
799    /* 
800     * Export the host, port, and referrer information
801     */
802    err = map(exports, "hostport", 1, csp->http->hostport, 1)
803       || map(exports, "path", 1, csp->http->path, 1)
804       || map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0)
805       || map(exports, "path-html", 1, html_encode(csp->http->path), 0);
806
807    if (csp->referrer && strlen(csp->referrer) > 9)
808    {
809       err = err || map(exports, "referrer", 1, csp->referrer + 9, 1);
810       err = err || map(exports, "referrer-html", 1, html_encode(csp->referrer + 9), 0);
811    }
812    else
813    {
814       err = err || map(exports, "referrer", 1, "unknown", 1);
815       err = err || map(exports, "referrer-html", 1, "unknown", 1);
816    }
817
818    if (err)
819    {
820       free_map(exports);
821       free_http_response(rsp);
822       return cgi_error_memory();
823    }
824
825    /*
826     * Export the trust list
827     */
828    p = strdup("");
829    for (tl = csp->config->trust_list; (t = *tl) ; tl++)
830    {
831       sprintf(buf, "<li>%s</li>\n", t->spec);
832       string_append(&p, buf);
833    }
834    err = map(exports, "trusted-referrers", 1, p, 0);
835
836    if (err)
837    {
838       free_map(exports);
839       free_http_response(rsp);
840       return cgi_error_memory();
841    }
842
843    /*
844     * Export the trust info, if available
845     */
846    if (csp->config->trust_info->first)
847    {
848       struct list_entry *l;
849
850       p = strdup("");
851       for (l = csp->config->trust_info->first; l ; l = l->next)
852       {
853          sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
854          string_append(&p, buf);
855       }
856       err = map(exports, "trust-info", 1, p, 0);
857    }
858    else
859    {
860       err = map_block_killer(exports, "have-trust-info");
861    }
862
863    if (err)
864    {
865       free_map(exports);
866       free_http_response(rsp);
867       return cgi_error_memory();
868    }
869
870    /*
871     * Export the force prefix or the force conditional block killer
872     */
873 #ifdef FEATURE_FORCE_LOAD
874    err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
875 #else /* ifndef FEATURE_FORCE_LOAD */
876    err = map_block_killer(exports, "force-support");
877 #endif /* ndef FEATURE_FORCE_LOAD */
878
879    if (err)
880    {
881       free_map(exports);
882       free_http_response(rsp);
883       return cgi_error_memory();
884    }
885
886    /*
887     * Build the response
888     */
889    err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
890    if (err)
891    {
892       free_http_response(rsp);
893       return cgi_error_memory();
894    }
895
896    return finish_http_response(rsp);
897 }
898 #endif /* def FEATURE_TRUST */
899
900
901 #ifdef FEATURE_FAST_REDIRECTS
902 /*********************************************************************
903  *
904  * Function    :  redirect_url
905  *
906  * Description :  Checks for redirection URLs and returns a HTTP redirect
907  *                to the destination URL, if necessary
908  *
909  * Parameters  :
910  *          1  :  csp = Current client state (buffers, headers, etc...)
911  *
912  * Returns     :  NULL if URL was clean, HTTP redirect otherwise.
913  *
914  *********************************************************************/
915 struct http_response *redirect_url(struct client_state *csp)
916 {
917    char *p, *q;
918    struct http_response *rsp;
919
920    p = q = csp->http->path;
921    log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
922
923    /* 
924     * find the last URL encoded in the request
925     */
926    while ((p = strstr(p, "http://")))
927    {
928       q = p++;
929    }
930
931    /* 
932     * if there was any, generate and return a HTTP redirect
933     */
934    if (q != csp->http->path)
935    {
936       log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
937
938       if (NULL == (rsp = alloc_http_response()))
939       {
940          return cgi_error_memory();
941       }
942
943       if ( enlist_unique_header(rsp->headers, "Location", q)
944         || (NULL == (rsp->status = strdup("302 Local Redirect from Junkbuster"))) )
945       {
946          free_http_response(rsp);
947          return cgi_error_memory();
948       }
949
950       return finish_http_response(rsp);
951    }
952    else
953    {
954       return NULL;
955    }
956
957 }
958 #endif /* def FEATURE_FAST_REDIRECTS */
959
960
961 #ifdef FEATURE_IMAGE_BLOCKING
962 /*********************************************************************
963  *
964  * Function    :  is_imageurl
965  *
966  * Description :  Given a URL, decide whether it is an image or not,
967  *                using either the info from a previous +image action
968  *                or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
969  *                the browser's accept header.
970  *                
971  * Parameters  :
972  *          1  :  csp = Current client state (buffers, headers, etc...)
973  *
974  * Returns     :  True (nonzero) if URL is an image, false (0)
975  *                otherwise
976  *
977  *********************************************************************/
978 int is_imageurl(struct client_state *csp)
979 {
980 #ifdef FEATURE_IMAGE_DETECT_MSIE
981    if ((csp->accept_types 
982        & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
983        == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
984    {
985       return 1;
986    }
987    else if ((csp->accept_types 
988        & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
989        == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
990    {
991       return 0;
992    }
993 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
994
995    return ((csp->action->flags & ACTION_IMAGE) != 0);
996
997 }
998 #endif /* def FEATURE_IMAGE_BLOCKING */
999
1000
1001 #ifdef FEATURE_COOKIE_JAR
1002 /*********************************************************************
1003  *
1004  * Function    :  is_untrusted_url
1005  *
1006  * Description :  Should we "distrust" this URL (and block it)?
1007  *
1008  *                Yes if it matches a line in the trustfile, or if the
1009  *                    referrer matches a line starting with "+" in the
1010  *                    trustfile.
1011  *                No  otherwise.
1012  *
1013  * Parameters  :
1014  *          1  :  csp = Current client state (buffers, headers, etc...)
1015  *
1016  * Returns     :  0 => trusted, 1 => untrusted
1017  *
1018  *********************************************************************/
1019 int is_untrusted_url(struct client_state *csp)
1020 {
1021    struct file_list *fl;
1022    struct block_spec *b;
1023    struct url_spec url[1], **tl, *t;
1024    struct http_request rhttp[1];
1025    char *p, *h;
1026
1027    /*
1028     * If we don't have a trustlist, we trust everybody
1029     */
1030    if (((fl = csp->tlist) == NULL) || ((b  = fl->f) == NULL))
1031    {
1032       return(0);
1033    }
1034
1035
1036    /*
1037     * Do we trust the request URL itself?
1038     */
1039    *url = dsplit(csp->http->host);
1040
1041    /* if splitting the domain fails, punt */
1042    if (url->dbuf == NULL) return(0);
1043
1044    memset(rhttp, '\0', sizeof(*rhttp));
1045
1046    for (b = b->next; b ; b = b->next)
1047    {
1048       if ((b->url->port == 0) || (b->url->port == csp->http->port))
1049       {
1050          if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1051          {
1052             if ((b->url->path == NULL) ||
1053 #ifdef REGEX
1054                (regexec(b->url->preg, csp->http->path, 0, NULL, 0) == 0)
1055 #else
1056                (strncmp(b->url->path, csp->http->path, b->url->pathlen) == 0)
1057 #endif
1058             )
1059             {
1060                freez(url->dbuf);
1061                freez(url->dvec);
1062
1063                if (b->reject == 0) return(0);
1064
1065                return(1);
1066             }
1067          }
1068       }
1069    }
1070
1071    freez(url->dbuf);
1072    freez(url->dvec);
1073
1074    if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
1075    {
1076       /* no referrer was supplied */
1077       return(1);
1078    }
1079
1080    /* forge a URL from the referrer so we can use
1081     * convert_url() to parse it into its components.
1082     */
1083
1084    p = NULL;
1085    p = strsav(p, "GET ");
1086    p = strsav(p, csp->referrer + 9);   /* skip over "Referer: " */
1087    p = strsav(p, " HTTP/1.0");
1088
1089    parse_http_request(p, rhttp, csp);
1090    freez(p);
1091
1092    if (rhttp->cmd == NULL)
1093    {
1094       return(1);
1095    }
1096
1097
1098    /*
1099     * If not, do we maybe trust its referrer?
1100     */
1101    *url = dsplit(rhttp->host);
1102
1103    /* if splitting the domain fails, punt */
1104    if (url->dbuf == NULL) return(1);
1105
1106    for (tl = csp->config->trust_list; (t = *tl) ; tl++)
1107    {
1108       if ((t->port == 0) || (t->port == rhttp->port))
1109       {
1110          if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
1111          {
1112             if ((t->path == NULL) ||
1113 #ifdef REGEX
1114                (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
1115 #else
1116                (strncmp(t->path, rhttp->path, t->pathlen) == 0)
1117 #endif
1118             )
1119             {
1120                /* if the URL's referrer is from a trusted referrer, then
1121                 * add the target spec to the trustfile as an unblocked
1122                 * domain and return NULL (which means it's OK).
1123                 */
1124
1125                FILE *fp;
1126
1127                freez(url->dbuf);
1128                freez(url->dvec);
1129
1130                if ((fp = fopen(csp->config->trustfile, "a")))
1131                {
1132                   h = NULL;
1133
1134                   h = strsav(h, "~");
1135                   h = strsav(h, csp->http->hostport);
1136
1137                   p = csp->http->path;
1138                   if ((*p++ == '/')
1139                   && (*p++ == '~'))
1140                   {
1141                   /* since this path points into a user's home space
1142                    * be sure to include this spec in the trustfile.
1143                    */
1144                      if ((p = strchr(p, '/')))
1145                      {
1146                         *p = '\0';
1147                         h = strsav(h, csp->http->path); /* FIXME: p?! */
1148                         h = strsav(h, "/");
1149                      }
1150                   }
1151
1152                   fprintf(fp, "%s\n", h);
1153                   freez(h);
1154                   fclose(fp);
1155                }
1156                return(0);
1157             }
1158          }
1159       }
1160    }
1161    return(1);
1162 }
1163 #endif /* def FEATURE_COOKIE_JAR */
1164
1165
1166 /*********************************************************************
1167  *
1168  * Function    :  pcrs_filter_response
1169  *
1170  * Description :  Apply all the pcrs jobs from the joblist (re_filterfile)
1171  *                to the text buffer that's been accumulated in 
1172  *                csp->iob->buf and set csp->content_length to the modified
1173  *                size and raise the CSP_FLAG_MODIFIED flag if appropriate.
1174  *
1175  * Parameters  :
1176  *          1  :  csp = Current client state (buffers, headers, etc...)
1177  *
1178  * Returns     :  a pointer to the (newly allocated) modified buffer.
1179  *                or NULL in case something went wrong
1180  *                
1181  *********************************************************************/
1182 char *pcrs_filter_response(struct client_state *csp)
1183 {
1184    int hits=0;
1185    size_t size;
1186
1187    char *old = csp->iob->cur, *new = NULL;
1188    pcrs_job *job;
1189
1190    struct file_list *fl;
1191    struct re_filterfile_spec *b;
1192
1193    /* Sanity first */
1194    if (csp->iob->cur >= csp->iob->eod)
1195    {
1196       return(NULL);
1197    }
1198    size = csp->iob->eod - csp->iob->cur;
1199
1200    /*
1201     * If the body has a "chunked" transfer-encoding,
1202     * get rid of it first, adjusting size and iob->eod
1203     */
1204    if (csp->flags & CSP_FLAG_CHUNKED)
1205    {
1206       log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1207       if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1208       {
1209          return(NULL);
1210       }
1211       csp->iob->eod = csp->iob->cur + size;
1212       csp->flags |= CSP_FLAG_MODIFIED;
1213    }
1214
1215    if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1216    {
1217       log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1218       return(NULL);
1219    }
1220
1221    if ( NULL == b->joblist )
1222    {
1223       log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1224       return(NULL);
1225    }
1226
1227    log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1228               csp->http->hostport, csp->http->path, size);
1229
1230    /* Apply all jobs from the joblist */
1231    for (job = b->joblist; NULL != job; job = job->next)
1232    {
1233       hits += pcrs_execute(job, old, size, &new, &size);
1234       if (old != csp->iob->cur) free(old);
1235       old=new;
1236    }
1237
1238    log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1239
1240    /* 
1241     * If there were no hits, destroy our copy and let
1242     * chat() use the original in csp->iob
1243     */
1244    if (!hits)
1245    {
1246       free(new);
1247       return(NULL);
1248    }
1249
1250    csp->flags |= CSP_FLAG_MODIFIED;
1251    csp->content_length = size;
1252    IOB_RESET(csp);
1253
1254    return(new);
1255
1256 }
1257
1258
1259 /*********************************************************************
1260  *
1261  * Function    :  gif_deanimate_response
1262  *
1263  * Description :  Deanimate the GIF image that has been accumulated in 
1264  *                csp->iob->buf, set csp->content_length to the modified
1265  *                size and raise the CSP_FLAG_MODIFIED flag.
1266  *
1267  * Parameters  :
1268  *          1  :  csp = Current client state (buffers, headers, etc...)
1269  *
1270  * Returns     :  a pointer to the (newly allocated) modified buffer.
1271  *                or NULL in case something went wrong.
1272  *                
1273  *********************************************************************/
1274 char *gif_deanimate_response(struct client_state *csp)
1275 {
1276    struct binbuffer *in, *out;
1277    char *p;
1278    int size = csp->iob->eod - csp->iob->cur;
1279
1280    /*
1281     * If the body has a "chunked" transfer-encoding,
1282     * get rid of it first, adjusting size and iob->eod
1283     */
1284    if (csp->flags & CSP_FLAG_CHUNKED)
1285    {
1286       log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1287       if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1288       {
1289          return(NULL);
1290       }
1291       csp->iob->eod = csp->iob->cur + size;
1292       csp->flags |= CSP_FLAG_MODIFIED;
1293    }
1294
1295    if (  (NULL == (in =  (struct binbuffer *)zalloc(sizeof *in )))
1296       || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1297    {
1298       log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1299       return NULL;
1300    }
1301
1302    in->buffer = csp->iob->cur;
1303    in->size = size;
1304
1305    if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1306    {
1307       log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1308       free(in);
1309       buf_free(out);
1310       return(NULL);
1311    }
1312    else
1313    {
1314       log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1315       csp->content_length = out->offset;
1316       csp->flags |= CSP_FLAG_MODIFIED;
1317       p = out->buffer;
1318       free(in);
1319       free(out);
1320       return(p);
1321    }  
1322
1323 }
1324
1325
1326 /*********************************************************************
1327  *
1328  * Function    :  remove_chunked_transfer_coding
1329  *
1330  * Description :  In-situ remove the "chunked" transfer coding as defined
1331  *                in rfc2616 from a buffer.
1332  *
1333  * Parameters  :
1334  *          1  :  buffer = Pointer to the text buffer
1335  *          2  :  size = Number of bytes to be processed
1336  *
1337  * Returns     :  The new size, i.e. the number of bytes from buffer which
1338  *                are occupied by the stripped body, or 0 in case something
1339  *                went wrong
1340  *                
1341  *********************************************************************/
1342 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1343 {
1344    size_t newsize = 0;
1345    unsigned int chunksize = 0;
1346    char *from_p, *to_p;
1347
1348    assert(buffer);
1349    from_p = to_p = buffer;
1350
1351    if (sscanf(buffer, "%x", &chunksize) != 1)
1352    {
1353       log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1354       return(0);
1355    }
1356
1357    while (chunksize > 0)
1358    {
1359       if (NULL == (from_p = strstr(from_p, "\r\n")))
1360       {
1361          log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1362          return(0);
1363       }
1364       newsize += chunksize;
1365       from_p += 2;
1366       
1367       memmove(to_p, from_p, (size_t) chunksize);
1368       to_p = buffer + newsize;
1369       from_p += chunksize + 2;
1370
1371       if (sscanf(from_p, "%x", &chunksize) != 1)
1372       {
1373          log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1374          return(0);
1375       }
1376    }
1377
1378    /* FIXME: Should this get its own loglevel? */
1379    log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1380    return(newsize);
1381
1382 }
1383
1384
1385 /*********************************************************************
1386  *
1387  * Function    :  url_actions
1388  *
1389  * Description :  Gets the actions for this URL.
1390  *
1391  * Parameters  :
1392  *          1  :  http = http_request request for blocked URLs
1393  *          2  :  csp = Current client state (buffers, headers, etc...)
1394  *
1395  * Returns     :  N/A
1396  *
1397  *********************************************************************/
1398 void url_actions(struct http_request *http, 
1399                  struct client_state *csp)
1400 {
1401    struct file_list *fl;
1402    struct url_actions *b;
1403
1404    init_current_action(csp->action);
1405
1406    if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1407    {
1408       return;
1409    }
1410
1411    apply_url_actions(csp->action, http, b);
1412
1413 }
1414
1415
1416 /*********************************************************************
1417  *
1418  * Function    :  apply_url_actions
1419  *
1420  * Description :  Applies a list of URL actions.
1421  *
1422  * Parameters  :
1423  *          1  :  action = Destination.
1424  *          2  :  http = Current URL
1425  *          3  :  b = list of URL actions to apply
1426  *
1427  * Returns     :  N/A
1428  *
1429  *********************************************************************/
1430 void apply_url_actions(struct current_action_spec *action, 
1431                        struct http_request *http, 
1432                        struct url_actions *b)
1433 {
1434    struct url_spec url[1];
1435
1436    if (b == NULL)
1437    {
1438       /* Should never happen */
1439       return;
1440    }
1441
1442    *url = dsplit(http->host);
1443
1444    /* if splitting the domain fails, punt */
1445    if (url->dbuf == NULL)
1446    {
1447       return;
1448    }
1449
1450    for (b = b->next; NULL != b; b = b->next)
1451    {
1452       if ((b->url->port == 0) || (b->url->port == http->port))
1453       {
1454          if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1455          {
1456             if ((b->url->path == NULL) ||
1457 #ifdef REGEX
1458                (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
1459 #else
1460                (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
1461 #endif
1462             )
1463             {
1464                merge_current_action(action, b->action);
1465             }
1466          }
1467       }
1468    }
1469
1470    freez(url->dbuf);
1471    freez(url->dvec);
1472 }
1473
1474
1475 /*********************************************************************
1476  *
1477  * Function    :  forward_url
1478  *
1479  * Description :  Should we forward this to another proxy?
1480  *
1481  * Parameters  :
1482  *          1  :  http = http_request request for current URL
1483  *          2  :  csp = Current client state (buffers, headers, etc...)
1484  *
1485  * Returns     :  Pointer to forwarding information.
1486  *
1487  *********************************************************************/
1488 const struct forward_spec * forward_url(struct http_request *http,
1489                                         struct client_state *csp)
1490 {
1491    static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1492    struct forward_spec *fwd = csp->config->forward;
1493    struct url_spec url[1];
1494
1495    if (fwd == NULL)
1496    {
1497       return(fwd_default);
1498    }
1499
1500    *url = dsplit(http->host);
1501
1502    /* if splitting the domain fails, punt */
1503    if (url->dbuf == NULL)
1504    {
1505       return(fwd_default);
1506    }
1507
1508    while (fwd != NULL)
1509    {
1510       if ((fwd->url->port == 0) || (fwd->url->port == http->port))
1511       {
1512          if ((fwd->url->domain[0] == '\0') || (domaincmp(fwd->url, url) == 0))
1513          {
1514             if ((fwd->url->path == NULL) ||
1515 #ifdef REGEX
1516                (regexec(fwd->url->preg, http->path, 0, NULL, 0) == 0)
1517 #else
1518                (strncmp(fwd->url->path, http->path, fwd->url->pathlen) == 0)
1519 #endif
1520             )
1521             {
1522                freez(url->dbuf);
1523                freez(url->dvec);
1524                return(fwd);
1525             }
1526          }
1527       }
1528       fwd = fwd->next;
1529    }
1530
1531    freez(url->dbuf);
1532    freez(url->dvec);
1533    return(fwd_default);
1534
1535 }
1536
1537
1538 /*********************************************************************
1539  *
1540  * Function    :  dsplit
1541  *
1542  * Description :  Takes a domain and returns a pointer to a url_spec
1543  *                structure populated with dbuf, dcnt and dvec.  The
1544  *                other fields in the structure that is returned are zero.
1545  *
1546  * Parameters  :
1547  *          1  :  domain = a URL address
1548  *
1549  * Returns     :  url_spec structure populated with dbuf, dcnt and dvec.
1550  *                On error, the dbuf field will be set to NULL.  (As
1551  *                will all the others, but you don't need to check
1552  *                them).
1553  *
1554  * FIXME: Returning a structure is horribly inefficient, please can
1555  *        this structure take a (struct url_spec * dest) 
1556  *        pointer instead?
1557  *
1558  *********************************************************************/
1559 struct url_spec dsplit(char *domain)
1560 {
1561    struct url_spec ret[1];
1562    char *v[BUFFER_SIZE];
1563    int size;
1564    char *p;
1565
1566    memset(ret, '\0', sizeof(*ret));
1567
1568    if (domain[strlen(domain) - 1] == '.')
1569    {
1570       ret->unanchored |= ANCHOR_RIGHT;
1571    }
1572
1573    if (domain[0] == '.')
1574    {
1575       ret->unanchored |= ANCHOR_LEFT;
1576    }
1577
1578    ret->dbuf = strdup(domain);
1579    if (NULL == ret->dbuf)
1580    {
1581       return *ret;
1582    }
1583
1584    /* map to lower case */
1585    for (p = ret->dbuf; *p ; p++)
1586    {
1587       *p = tolower((int)(unsigned char)*p);
1588    }
1589
1590    /* split the domain name into components */
1591    ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
1592
1593    if (ret->dcnt < 0)
1594    {
1595       free(ret->dbuf);
1596       memset(ret, '\0', sizeof(ret));
1597       return *ret;
1598    }
1599    else if (ret->dcnt == 0)
1600    {
1601       return *ret;
1602    }
1603
1604    /* save a copy of the pointers in dvec */
1605    size = ret->dcnt * sizeof(*ret->dvec);
1606
1607    ret->dvec = (char **)malloc(size);
1608    if (NULL == ret->dvec)
1609    {
1610       free(ret->dbuf);
1611       memset(ret, '\0', sizeof(ret));
1612       return *ret;
1613    }
1614
1615    memcpy(ret->dvec, v, size);
1616
1617    return *ret;
1618
1619 }
1620
1621
1622 /*********************************************************************
1623  *
1624  * Function    :  simple_domaincmp
1625  *
1626  * Description :  Domain-wise Compare fqdn's.  The comparison is 
1627  *                both left- and right-anchored.  The individual
1628  *                domain names are compared with simplematch().
1629  *                This is only used by domaincmp.
1630  *
1631  * Parameters  :
1632  *          1  :  pv = array of patterns to compare
1633  *          2  :  fv = array of domain components to compare
1634  *          3  :  len = length of the arrays (both arrays are the
1635  *                      same length - if they weren't, it couldn't
1636  *                      possibly be a match).
1637  *
1638  * Returns     :  0 => domains are equivalent, else no match.
1639  *
1640  *********************************************************************/
1641 static int simple_domaincmp(char **pv, char **fv, int len)
1642 {
1643    int n;
1644
1645    for (n = 0; n < len; n++)
1646    {
1647       if (simplematch(pv[n], fv[n]))
1648       {
1649          return 1;
1650       }
1651    }
1652
1653    return 0;
1654
1655 }
1656
1657
1658 /*********************************************************************
1659  *
1660  * Function    :  domaincmp
1661  *
1662  * Description :  Domain-wise Compare fqdn's. Governed by the bimap in
1663  *                pattern->unachored, the comparison is un-, left-,
1664  *                right-anchored, or both.
1665  *                The individual domain names are compared with
1666  *                simplematch().
1667  *
1668  * Parameters  :
1669  *          1  :  pattern = a domain that may contain a '*' as a wildcard.
1670  *          2  :  fqdn = domain name against which the patterns are compared.
1671  *
1672  * Returns     :  0 => domains are equivalent, else no match.
1673  *
1674  *********************************************************************/
1675 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1676 {
1677    char **pv, **fv;  /* vectors  */
1678    int    plen, flen;
1679    int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1680
1681    plen = pattern->dcnt;
1682    flen = fqdn->dcnt;
1683
1684    if (flen < plen)
1685    {
1686       /* fqdn is too short to match this pattern */
1687       return 1;
1688    }
1689
1690    pv   = pattern->dvec;
1691    fv   = fqdn->dvec;
1692
1693    if (unanchored == ANCHOR_LEFT)
1694    {
1695       /*
1696        * Right anchored.
1697        *
1698        * Convert this into a fully anchored pattern with
1699        * the fqdn and pattern the same length
1700        */
1701       fv += (flen - plen); /* flen - plen >= 0 due to check above */
1702       return simple_domaincmp(pv, fv, plen);
1703    }
1704    else if (unanchored == 0)
1705    {
1706       /* Fully anchored, check length */
1707       if (flen != plen)
1708       {
1709          return 1;
1710       }
1711       return simple_domaincmp(pv, fv, plen);
1712    }
1713    else if (unanchored == ANCHOR_RIGHT)
1714    {
1715       /* Left anchored, ignore all extra in fqdn */
1716       return simple_domaincmp(pv, fv, plen);
1717    }
1718    else
1719    {
1720       /* Unanchored */
1721       int n;
1722       int maxn = flen - plen;
1723       for (n = 0; n <= maxn; n++)
1724       {
1725          if (!simple_domaincmp(pv, fv, plen))
1726          {
1727             return 0;
1728          }
1729          /*
1730           * Doesn't match from start of fqdn
1731           * Try skipping first part of fqdn
1732           */
1733          fv++;
1734       }
1735       return 1;
1736    }
1737
1738 }
1739
1740
1741 /*
1742   Local Variables:
1743   tab-width: 3
1744   end:
1745 */