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