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