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