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