9c9ae2e622ff9cf83482458ce5eaab0c2c23f76a
[privoxy.git] / filters.c
1 const char filters_rcs[] = "$Id: filters.c,v 1.99 2008/02/03 13:57:58 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', `execute_single_pcrs_command',
14  *                   `rewrite_url', `get_last_url'
15  *
16  * Copyright   :  Written by and Copyright (C) 2001, 2004-2007 the SourceForge
17  *                Privoxy team. http://www.privoxy.org/
18  *
19  *                Based on the Internet Junkbuster originally written
20  *                by and Copyright (C) 1997 Anonymous Coders and
21  *                Junkbusters Corporation.  http://www.junkbusters.com
22  *
23  *                This program is free software; you can redistribute it
24  *                and/or modify it under the terms of the GNU General
25  *                Public License as published by the Free Software
26  *                Foundation; either version 2 of the License, or (at
27  *                your option) any later version.
28  *
29  *                This program is distributed in the hope that it will
30  *                be useful, but WITHOUT ANY WARRANTY; without even the
31  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
32  *                PARTICULAR PURPOSE.  See the GNU General Public
33  *                License for more details.
34  *
35  *                The GNU General Public License should be included with
36  *                this file.  If not, you can view it at
37  *                http://www.gnu.org/copyleft/gpl.html
38  *                or write to the Free Software Foundation, Inc., 59
39  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
40  *
41  * Revisions   :
42  *    $Log: filters.c,v $
43  *    Revision 1.99  2008/02/03 13:57:58  fabiankeil
44  *    Add SOCKS5 support for forward-override{}.
45  *
46  *    Revision 1.98  2008/01/04 17:43:45  fabiankeil
47  *    Improve the warning messages that get logged if the action files
48  *    "enable" filters but no filters of that type have been loaded.
49  *
50  *    Revision 1.97  2007/11/30 15:37:03  fabiankeil
51  *    Use freez instead of free.
52  *
53  *    Revision 1.96  2007/10/19 16:53:28  fabiankeil
54  *    Add helper function to check if any content filters are enabled.
55  *
56  *    Revision 1.95  2007/10/17 19:31:20  fabiankeil
57  *    Omitting the zero chunk that ends the chunk transfer encoding seems
58  *    to be the new black. Log the problem and continue filtering anyway.
59  *
60  *    Revision 1.94  2007/09/29 13:20:20  fabiankeil
61  *    Remove two redundant and one useless log messages.
62  *
63  *    Revision 1.93  2007/09/29 10:21:16  fabiankeil
64  *    - Move get_filter_function() from jcc.c to filters.c
65  *      so the filter functions can be static.
66  *    - Don't bother filtering body-less responses.
67  *
68  *    Revision 1.92  2007/09/28 16:38:55  fabiankeil
69  *    - Execute content filters through execute_content_filter().
70  *    - Add prepare_for_filtering() so filter functions don't have to
71  *      care about de-chunking and decompression. As a side effect this enables
72  *      decompression for gif_deanimate_response() and jpeg_inspect_response().
73  *    - Change remove_chunked_transfer_coding()'s return type to jb_err.
74  *      Some clowns feel like chunking empty responses in which case
75  *      (size == 0) is valid but previously would be interpreted as error.
76  *
77  *    Revision 1.91  2007/09/02 15:31:20  fabiankeil
78  *    Move match_portlist() from filter.c to urlmatch.c.
79  *    It's used for url matching, not for filtering.
80  *
81  *    Revision 1.90  2007/09/02 12:44:17  fabiankeil
82  *    Remove newline at the end of a log_error() message.
83  *
84  *    Revision 1.89  2007/08/05 13:42:23  fabiankeil
85  *    #1763173 from Stefan Huehner: declare some more functions static.
86  *
87  *    Revision 1.88  2007/06/01 16:41:11  fabiankeil
88  *    Add forward-override{} to change the forwarding settings through
89  *    action sections. This is mainly interesting to forward different
90  *    clients differently (for example based on User-Agent or request
91  *    origin).
92  *
93  *    Revision 1.87  2007/04/30 15:53:10  fabiankeil
94  *    Make sure filters with dynamic jobs actually use them.
95  *
96  *    Revision 1.86  2007/04/30 15:03:28  fabiankeil
97  *    - Introduce dynamic pcrs jobs that can resolve variables.
98  *    - Don't run redirect functions more than once,
99  *      unless they are activated more than once.
100  *
101  *    Revision 1.85  2007/03/21 12:24:47  fabiankeil
102  *    - Log the content size after decompression in decompress_iob()
103  *      instead of pcrs_filter_response().
104  *
105  *    Revision 1.84  2007/03/20 15:16:34  fabiankeil
106  *    Use dedicated header filter actions instead of abusing "filter".
107  *    Replace "filter-client-headers" and "filter-client-headers"
108  *    with "server-header-filter" and "client-header-filter".
109  *
110  *    Revision 1.83  2007/03/17 15:20:05  fabiankeil
111  *    New config option: enforce-blocks.
112  *
113  *    Revision 1.82  2007/03/13 11:28:43  fabiankeil
114  *    - Fix port handling in acl_addr() and use a temporary acl spec
115  *      copy so error messages don't contain a truncated version.
116  *    - Log size of iob before and after decompression.
117  *
118  *    Revision 1.81  2007/03/05 14:40:53  fabiankeil
119  *    - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
120  *    - Hide the "Go there anyway" link for blocked CONNECT
121  *      requests where going there anyway doesn't work anyway.
122  *
123  *    Revision 1.80  2007/02/07 10:55:20  fabiankeil
124  *    - Save the reason for generating http_responses.
125  *    - Block (+block) with status code 403 instead of 404.
126  *    - Use a different kludge to remember a failed decompression.
127  *
128  *    Revision 1.79  2007/01/31 16:21:38  fabiankeil
129  *    Search for Max-Forwards headers case-insensitive,
130  *    don't generate the "501 unsupported" message for invalid
131  *    Max-Forwards values and don't increase negative ones.
132  *
133  *    Revision 1.78  2007/01/28 13:41:18  fabiankeil
134  *    - Add HEAD support to finish_http_response.
135  *    - Add error favicon to internal HTML error messages.
136  *
137  *    Revision 1.77  2007/01/12 15:36:44  fabiankeil
138  *    Mark *csp as immutable for is_untrusted_url()
139  *    and is_imageurl(). Closes FR 1237736.
140  *
141  *    Revision 1.76  2007/01/01 19:36:37  fabiankeil
142  *    Integrate a modified version of Wil Mahan's
143  *    zlib patch (PR #895531).
144  *
145  *    Revision 1.75  2006/12/29 18:30:46  fabiankeil
146  *    Fixed gcc43 conversion warnings,
147  *    changed sprintf calls to snprintf.
148  *
149  *    Revision 1.74  2006/12/24 17:37:38  fabiankeil
150  *    Adjust comment in pcrs_filter_response()
151  *    to recent pcrs changes. Hohoho.
152  *
153  *    Revision 1.73  2006/12/23 16:01:02  fabiankeil
154  *    Don't crash if pcre returns an error code
155  *    that pcrs didn't expect. Fixes BR 1621173.
156  *
157  *    Revision 1.72  2006/12/22 18:52:53  fabiankeil
158  *    Modified is_untrusted_url to complain in case of
159  *    write errors and to give a reason when adding new
160  *    entries to the trustfile. Closes FR 1097611.
161  *
162  *    Revision 1.71  2006/12/22 14:24:52  fabiankeil
163  *    Skip empty filter files in pcrs_filter_response,
164  *    but don't ignore the ones that come afterwards.
165  *    Fixes parts of BR 1619208.
166  *
167  *    Revision 1.70  2006/12/09 13:33:15  fabiankeil
168  *    Added some sanity checks for get_last_url().
169  *    Fixed possible segfault caused by my last commit.
170  *
171  *    Revision 1.69  2006/12/08 12:39:13  fabiankeil
172  *    Let get_last_url() catch https URLs as well.
173  *
174  *    Revision 1.68  2006/12/05 14:45:48  fabiankeil
175  *    Make sure get_last_url() behaves like advertised
176  *    and fast-redirects{} can be combined with redirect{}.
177  *
178  *    Revision 1.67  2006/11/28 15:19:43  fabiankeil
179  *    Implemented +redirect{s@foo@bar@} to generate
180  *    a redirect based on a rewritten version of the
181  *    original URL.
182  *
183  *    Revision 1.66  2006/09/23 13:26:38  roro
184  *    Replace TABs by spaces in source code.
185  *
186  *    Revision 1.65  2006/09/21 12:54:43  fabiankeil
187  *    Fix +redirect{}. Didn't work with -fast-redirects.
188  *
189  *    Revision 1.64  2006/08/31 10:55:49  fabiankeil
190  *    Block requests for untrusted URLs with status
191  *    code 403 instead of 200.
192  *
193  *    Revision 1.63  2006/08/31 10:11:28  fabiankeil
194  *    Don't free p which is still in use and will be later
195  *    freed by free_map(). Don't claim the referrer is unknown
196  *    when the client didn't set one.
197  *
198  *    Revision 1.62  2006/08/14 00:27:47  david__schmidt
199  *    Feature request 595948: Re-Filter logging in single line
200  *
201  *    Revision 1.61  2006/08/03 02:46:41  david__schmidt
202  *    Incorporate Fabian Keil's patch work:\rhttp://www.fabiankeil.de/sourcecode/privoxy/
203  *
204  *    Revision 1.60  2006/07/18 14:48:46  david__schmidt
205  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
206  *    with what was really the latest development (the v_3_0_branch branch)
207  *
208  *    Revision 1.58.2.9  2006/01/29 23:10:56  david__schmidt
209  *    Multiple filter file support
210  *
211  *    Revision 1.58.2.8  2005/05/07 21:50:55  david__schmidt
212  *    A few memory leaks plugged (mostly on error paths)
213  *
214  *    Revision 1.58.2.7  2004/10/03 12:53:32  david__schmidt
215  *    Add the ability to check jpeg images for invalid
216  *    lengths of comment blocks.  Defensive strategy
217  *    against the exploit:
218  *       Microsoft Security Bulletin MS04-028
219  *       Buffer Overrun in JPEG Processing (GDI+) Could
220  *       Allow Code Execution (833987)
221  *    Enabled with +inspect-jpegs in actions files.
222  *
223  *    Revision 1.58.2.6  2003/12/06 22:18:27  gliptak
224  *    Correcting compile problem with FEATURE_IMAGE_BLOCKING
225  *
226  *    Revision 1.58.2.5  2003/11/11 13:10:31  oes
227  *    Fixed bug #839859: "See why" link URL now gets url-encoded.
228  *
229  *    Revision 1.58.2.4  2003/02/28 12:52:45  oes
230  *    Fixed a typo
231  *
232  *    Revision 1.58.2.3  2002/09/25 14:51:51  oes
233  *    Added basic support for OPTIONS and TRACE HTTP methods:
234  *    New function direct_response which handles OPTIONS and
235  *    TRACE requests whose Max-Forwards header field is zero.
236  *
237  *    Revision 1.58.2.2  2002/08/01 17:18:28  oes
238  *    Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
239  *
240  *    Revision 1.58.2.1  2002/07/26 15:18:53  oes
241  *    - Bugfix: Executing a filters without jobs no longer results in
242  *      turing off *all* filters.
243  *    - Security fix: Malicious web servers can't cause a seg fault
244  *      through bogus chunk sizes anymore
245  *
246  *    Revision 1.58  2002/04/24 02:11:17  oes
247  *    Jon's multiple AF patch: url_actions now evaluates rules
248  *    from all AFs.
249  *
250  *    Revision 1.57  2002/04/08 20:38:34  swa
251  *    fixed JB spelling
252  *
253  *    Revision 1.56  2002/04/05 15:51:24  oes
254  *     - bugfix: error-pages now get correct request protocol
255  *     - fix for invalid HTML in trust info
256  *
257  *    Revision 1.55  2002/04/02 16:13:51  oes
258  *    Fix: No "Go there anyway" for SSL
259  *
260  *    Revision 1.54  2002/04/02 14:55:56  oes
261  *    Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
262  *
263  *    Revision 1.53  2002/03/26 22:29:54  swa
264  *    we have a new homepage!
265  *
266  *    Revision 1.52  2002/03/24 16:35:57  jongfoster
267  *    Removing logo
268  *
269  *    Revision 1.51  2002/03/24 15:23:33  jongfoster
270  *    Name changes
271  *
272  *    Revision 1.50  2002/03/24 13:25:43  swa
273  *    name change related issues
274  *
275  *    Revision 1.49  2002/03/16 20:29:14  oes
276  *    Cosmetics
277  *
278  *    Revision 1.48  2002/03/13 20:25:34  oes
279  *    Better logging for content filters
280  *
281  *    Revision 1.47  2002/03/13 00:30:52  jongfoster
282  *    Killing warnings
283  *    Added option of always sending redirect for imageblock,
284  *    currently disabled with #if 0.
285  *
286  *    Revision 1.46  2002/03/12 01:42:49  oes
287  *    Introduced modular filters
288  *
289  *    Revision 1.45  2002/03/08 16:47:50  oes
290  *    Added choice beween GIF and PNG built-in images
291  *
292  *    Revision 1.44  2002/03/07 03:49:31  oes
293  *     - Fixed compiler warnings etc
294  *     - Changed built-in images from GIF to PNG
295  *       (with regard to Unisys patent issue)
296  *     - Added a 4x4 pattern PNG which is less intrusive
297  *       than the logo but also clearly marks the deleted banners
298  *
299  *    Revision 1.43  2002/01/22 23:51:59  jongfoster
300  *    Replacing strsav() with the safer string_append().
301  *
302  *    Adding missing html_encode() to error message generators.  Where encoded
303  *    and unencoded versions of a string were provided, removing the unencoded
304  *    one.
305  *
306  *    Revision 1.42  2002/01/17 21:00:32  jongfoster
307  *    Moving all our URL and URL pattern parsing code to urlmatch.c.
308  *
309  *    Using a single, simple url_match(pattern,url) function - rather than
310  *    the 3-line match routine which was repeated all over the place.
311  *
312  *    Renaming free_url to free_url_spec, since it frees a struct url_spec.
313  *
314  *    Using parse_http_url() to parse URLs without faking a HTTP
315  *    request line for parse_http_request().
316  *
317  *    Revision 1.41  2001/11/13 00:14:07  jongfoster
318  *    Fixing stupid bug now I've figured out what || means.
319  *    (It always returns 0 or 1, not one of it's paramaters.)
320  *
321  *    Revision 1.40  2001/10/26 17:37:55  oes
322  *    - Re-enabled Netscape 200/404 bug workaround in block_url():
323  *      - Removed OS/2 special case
324  *      - Made block_url() independant from sed() having been run
325  *    - Made trust_url independant from sed() having been run
326  *    - Made is_imageurl independant from sed() having been run.
327  *      It now checks User-Agent: and Accept: by itself.
328  *
329  *
330  *    Revision 1.39  2001/10/25 03:40:48  david__schmidt
331  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
332  *    threads to call select() simultaneously.  So, it's time to do a real, live,
333  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
334  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
335  *
336  *    Revision 1.38  2001/10/23 21:32:33  jongfoster
337  *    Adding error-checking to selected functions
338  *
339  *    Revision 1.37  2001/10/22 15:33:56  david__schmidt
340  *    Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
341  *    filters.c.  Added a FIXME in front of the offending code.  I'll gladly
342  *    put in a better/more robust fix for all parties if one is presented...
343  *    It seems that just returning 200 instead of 404 would pretty much fix
344  *    it for everyone, but I don't know all the history of the problem.
345  *
346  *    Revision 1.36  2001/10/10 16:44:16  oes
347  *    Added match_portlist function
348  *
349  *    Revision 1.35  2001/10/07 15:41:23  oes
350  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
351  *
352  *    New function remove_chunked_transfer_coding that strips chunked
353  *      transfer coding to plain and is called by pcrs_filter_response
354  *      and gif_deanimate_response if neccessary
355  *
356  *    Improved handling of zero-change re_filter runs
357  *
358  *    pcrs_filter_response and gif_deanimate_response now remove
359  *      chunked transfer codeing before processing the body.
360  *
361  *    Revision 1.34  2001/09/20 15:49:36  steudten
362  *
363  *    Fix BUG: Change int size to size_t size in pcrs_filter_response().
364  *    See cgi.c fill_template().
365  *
366  *    Revision 1.33  2001/09/16 17:05:14  jongfoster
367  *    Removing unused #include showarg.h
368  *
369  *    Revision 1.32  2001/09/16 13:21:27  jongfoster
370  *    Changes to use new list functions.
371  *
372  *    Revision 1.31  2001/09/16 11:38:02  jongfoster
373  *    Splitting fill_template() into 2 functions:
374  *    template_load() loads the file
375  *    template_fill() performs the PCRS regexps.
376  *    This is because the CGI edit interface has a "table row"
377  *    template which is used many times in the page - this
378  *    change means it's only loaded from disk once.
379  *
380  *    Revision 1.30  2001/09/16 11:00:10  jongfoster
381  *    New function alloc_http_response, for symmetry with free_http_response
382  *
383  *    Revision 1.29  2001/09/13 23:32:40  jongfoster
384  *    Moving image data to cgi.c rather than cgi.h
385  *    Fixing a GPF under Win32 (and any other OS that protects global
386  *    constants from being written to).
387  *
388  *    Revision 1.28  2001/09/10 10:18:51  oes
389  *    Silenced compiler warnings
390  *
391  *    Revision 1.27  2001/08/05 16:06:20  jongfoster
392  *    Modifiying "struct map" so that there are now separate header and
393  *    "map_entry" structures.  This means that functions which modify a
394  *    map no longer need to return a pointer to the modified map.
395  *    Also, it no longer reverses the order of the entries (which may be
396  *    important with some advanced template substitutions).
397  *
398  *    Revision 1.26  2001/07/30 22:08:36  jongfoster
399  *    Tidying up #defines:
400  *    - All feature #defines are now of the form FEATURE_xxx
401  *    - Permanently turned off WIN_GUI_EDIT
402  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
403  *
404  *    Revision 1.25  2001/07/26 10:09:46  oes
405  *    Made browser detection a little less naive
406  *
407  *    Revision 1.24  2001/07/25 17:22:51  oes
408  *    Added workaround for Netscape bug that prevents display of page when loading a component fails.
409  *
410  *    Revision 1.23  2001/07/23 13:40:12  oes
411  *    Fixed bug that caused document body to be dropped when pcrs joblist was empty.
412  *
413  *    Revision 1.22  2001/07/18 12:29:34  oes
414  *    - Made gif_deanimate_response respect
415  *      csp->action->string[ACTION_STRING_DEANIMATE]
416  *    - Logging cosmetics
417  *
418  *    Revision 1.21  2001/07/13 13:59:53  oes
419  *     - Introduced gif_deanimate_response which shares the
420  *       generic content modification interface of pcrs_filter_response
421  *       and acts as a wrapper to deanimate.c:gif_deanimate()
422  *     - Renamed re_process_buffer to pcrs_filter_response
423  *     - pcrs_filter_response now returns NULL on failiure
424  *     - Removed all #ifdef PCRS
425  *
426  *    Revision 1.20  2001/07/01 17:01:04  oes
427  *    Added comments and missing return statement in is_untrusted_url()
428  *
429  *    Revision 1.19  2001/06/29 21:45:41  oes
430  *    Indentation, CRLF->LF, Tab-> Space
431  *
432  *    Revision 1.18  2001/06/29 13:27:38  oes
433  *    - Cleaned up, renamed and reorderd functions
434  *      and improved comments
435  *
436  *    - block_url:
437  *      - Ported to CGI platform. Now delivers
438  *        http_response or NULL
439  *      - Unified HTML and GIF generation (moved image detection
440  *        and GIF generation here from jcc.c:chat())
441  *      - Fixed HTTP status to:
442  *       -  403 (Forbidden) for the "blocked" HTML message
443  *       -  200 (OK) for GIF answers
444  *       -  302 (Redirect) for redirect to GIF
445  *
446  *    - trust_url:
447  *      - Ported to CGI platform. Now delivers
448  *        http_response or NULL
449  *      - Separated detection of untrusted URL into
450  *        (bool)is_untrusted_url
451  *      - Added enforcement of untrusted requests
452  *
453  *    - Moved redirect_url() from cgi.c to here
454  *      and ported it to the CGI platform
455  *
456  *    - Removed logentry from cancelled commit
457  *
458  *    Revision 1.17  2001/06/09 10:55:28  jongfoster
459  *    Changing BUFSIZ ==> BUFFER_SIZE
460  *
461  *    Revision 1.16  2001/06/07 23:10:26  jongfoster
462  *    Allowing unanchored domain patterns to back off and retry
463  *    if they partially match.  Optimized right-anchored patterns.
464  *    Moving ACL and forward files into config file.
465  *    Replacing struct gateway with struct forward_spec
466  *
467  *    Revision 1.15  2001/06/03 19:12:00  oes
468  *    extracted-CGI relevant stuff
469  *
470  *    Revision 1.14  2001/06/01 10:30:55  oes
471  *    Added optional left-anchoring to domaincmp
472  *
473  *    Revision 1.13  2001/05/31 21:21:30  jongfoster
474  *    Permissionsfile / actions file changes:
475  *    - Changed "permission" to "action" throughout
476  *    - changes to file format to allow string parameters
477  *    - Moved helper functions to actions.c
478  *
479  *    Revision 1.12  2001/05/31 17:35:20  oes
480  *
481  *     - Enhanced domain part globbing with infix and prefix asterisk
482  *       matching and optional unanchored operation
483  *
484  *    Revision 1.11  2001/05/29 11:53:23  oes
485  *    "See why" link added to "blocked" page
486  *
487  *    Revision 1.10  2001/05/29 09:50:24  jongfoster
488  *    Unified blocklist/imagelist/permissionslist.
489  *    File format is still under discussion, but the internal changes
490  *    are (mostly) done.
491  *
492  *    Also modified interceptor behaviour:
493  *    - We now intercept all URLs beginning with one of the following
494  *      prefixes (and *only* these prefixes):
495  *        * http://i.j.b/
496  *        * http://ijbswa.sf.net/config/
497  *        * http://ijbswa.sourceforge.net/config/
498  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
499  *    - Internal changes so that intercepted and fast redirect pages
500  *      are not replaced with an image.
501  *    - Interceptors now have the option to send a binary page direct
502  *      to the client. (i.e. ijb-send-banner uses this)
503  *    - Implemented show-url-info interceptor.  (Which is why I needed
504  *      the above interceptors changes - a typical URL is
505  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
506  *      The previous mechanism would not have intercepted that, and
507  *      if it had been intercepted then it then it would have replaced
508  *      it with an image.)
509  *
510  *    Revision 1.9  2001/05/27 22:17:04  oes
511  *
512  *    - re_process_buffer no longer writes the modified buffer
513  *      to the client, which was very ugly. It now returns the
514  *      buffer, which it is then written by chat.
515  *
516  *    - content_length now adjusts the Content-Length: header
517  *      for modified documents rather than crunch()ing it.
518  *      (Length info in csp->content_length, which is 0 for
519  *      unmodified documents)
520  *
521  *    - For this to work, sed() is called twice when filtering.
522  *
523  *    Revision 1.8  2001/05/26 17:13:28  jongfoster
524  *    Filled in a function comment.
525  *
526  *    Revision 1.7  2001/05/26 15:26:15  jongfoster
527  *    ACL feature now provides more security by immediately dropping
528  *    connections from untrusted hosts.
529  *
530  *    Revision 1.6  2001/05/26 00:28:36  jongfoster
531  *    Automatic reloading of config file.
532  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
533  *    Most of the global variables have been moved to a new
534  *    struct configuration_spec, accessed through csp->config->globalname
535  *    Most of the globals remaining are used by the Win32 GUI.
536  *
537  *    Revision 1.5  2001/05/25 22:34:30  jongfoster
538  *    Hard tabs->Spaces
539  *
540  *    Revision 1.4  2001/05/22 18:46:04  oes
541  *
542  *    - Enabled filtering banners by size rather than URL
543  *      by adding patterns that replace all standard banner
544  *      sizes with the "Junkbuster" gif to the re_filterfile
545  *
546  *    - Enabled filtering WebBugs by providing a pattern
547  *      which kills all 1x1 images
548  *
549  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
550  *      which is selected by the (nonstandard and therefore
551  *      capital) letter 'U' in the option string.
552  *      It causes the quantifiers to be ungreedy by default.
553  *      Appending a ? turns back to greedy (!).
554  *
555  *    - Added a new interceptor ijb-send-banner, which
556  *      sends back the "Junkbuster" gif. Without imagelist or
557  *      MSIE detection support, or if tinygif = 1, or the
558  *      URL isn't recognized as an imageurl, a lame HTML
559  *      explanation is sent instead.
560  *
561  *    - Added new feature, which permits blocking remote
562  *      script redirects and firing back a local redirect
563  *      to the browser.
564  *      The feature is conditionally compiled, i.e. it
565  *      can be disabled with --disable-fast-redirects,
566  *      plus it must be activated by a "fast-redirects"
567  *      line in the config file, has its own log level
568  *      and of course wants to be displayed by show-proxy-args
569  *      Note: Boy, all the #ifdefs in 1001 locations and
570  *      all the fumbling with configure.in and acconfig.h
571  *      were *way* more work than the feature itself :-(
572  *
573  *    - Because a generic redirect template was needed for
574  *      this, tinygif = 3 now uses the same.
575  *
576  *    - Moved GIFs, and other static HTTP response templates
577  *      to project.h
578  *
579  *    - Some minor fixes
580  *
581  *    - Removed some >400 CRs again (Jon, you really worked
582  *      a lot! ;-)
583  *
584  *    Revision 1.3  2001/05/20 16:44:47  jongfoster
585  *    Removing last hardcoded Junkbusters.com URLs.
586  *
587  *    Revision 1.2  2001/05/20 01:21:20  jongfoster
588  *    Version 2.9.4 checkin.
589  *    - Merged popupfile and cookiefile, and added control over PCRS
590  *      filtering, in new "permissionsfile".
591  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
592  *      file error you now get a message box (in the Win32 GUI) rather
593  *      than the program exiting with no explanation.
594  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
595  *      skipping.
596  *    - Removed tabs from "config"
597  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
598  *    - Bumped up version number.
599  *
600  *    Revision 1.1.1.1  2001/05/15 13:58:52  oes
601  *    Initial import of version 2.9.3 source tree
602  *
603  *
604  *********************************************************************/
605 \f
606
607 #include "config.h"
608
609 #include <stdio.h>
610 #include <sys/types.h>
611 #include <stdlib.h>
612 #include <ctype.h>
613 #include <string.h>
614 #include <assert.h>
615
616 #ifndef _WIN32
617 #ifndef __OS2__
618 #include <unistd.h>
619 #endif /* ndef __OS2__ */
620 #include <netinet/in.h>
621 #else
622 #include <winsock2.h>
623 #endif /* ndef _WIN32 */
624
625 #ifdef __OS2__
626 #include <utils.h>
627 #endif /* def __OS2__ */
628
629 #include "project.h"
630 #include "filters.h"
631 #include "encode.h"
632 #include "parsers.h"
633 #include "ssplit.h"
634 #include "errlog.h"
635 #include "jbsockets.h"
636 #include "miscutil.h"
637 #include "actions.h"
638 #include "cgi.h"
639 #include "list.h"
640 #include "deanimate.h"
641 #include "urlmatch.h"
642 #include "loaders.h"
643
644 #ifdef _WIN32
645 #include "win32.h"
646 #endif
647
648 const char filters_h_rcs[] = FILTERS_H_VERSION;
649
650 /* Fix a problem with Solaris.  There should be no effect on other
651  * platforms.
652  * Solaris's isspace() is a macro which uses it's argument directly
653  * as an array index.  Therefore we need to make sure that high-bit
654  * characters generate +ve values, and ideally we also want to make
655  * the argument match the declared parameter type of "int".
656  */
657 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
658
659 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
660 static jb_err prepare_for_filtering(struct client_state *csp);
661
662 #ifdef FEATURE_ACL
663 /*********************************************************************
664  *
665  * Function    :  block_acl
666  *
667  * Description :  Block this request?
668  *                Decide yes or no based on ACL file.
669  *
670  * Parameters  :
671  *          1  :  dst = The proxy or gateway address this is going to.
672  *                      Or NULL to check all possible targets.
673  *          2  :  csp = Current client state (buffers, headers, etc...)
674  *                      Also includes the client IP address.
675  *
676  * Returns     : 0 = FALSE (don't block) and 1 = TRUE (do block)
677  *
678  *********************************************************************/
679 int block_acl(struct access_control_addr *dst, struct client_state *csp)
680 {
681    struct access_control_list *acl = csp->config->acl;
682
683    /* if not using an access control list, then permit the connection */
684    if (acl == NULL)
685    {
686       return(0);
687    }
688
689    /* search the list */
690    while (acl != NULL)
691    {
692       if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
693       {
694          if (dst == NULL)
695          {
696             /* Just want to check if they have any access */
697             if (acl->action == ACL_PERMIT)
698             {
699                return(0);
700             }
701          }
702          else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
703            && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
704          {
705             if (acl->action == ACL_PERMIT)
706             {
707                return(0);
708             }
709             else
710             {
711                return(1);
712             }
713          }
714       }
715       acl = acl->next;
716    }
717
718    return(1);
719
720 }
721
722
723 /*********************************************************************
724  *
725  * Function    :  acl_addr
726  *
727  * Description :  Called from `load_config' to parse an ACL address.
728  *
729  * Parameters  :
730  *          1  :  aspec = String specifying ACL address.
731  *          2  :  aca = struct access_control_addr to fill in.
732  *
733  * Returns     :  0 => Ok, everything else is an error.
734  *
735  *********************************************************************/
736 int acl_addr(const char *aspec, struct access_control_addr *aca)
737 {
738    int i, masklength;
739    long port;
740    char *p;
741    char *acl_spec = NULL;
742
743    masklength = 32;
744    port       =  0;
745
746    /*
747     * Use a temporary acl spec copy so we can log
748     * the unmodified original in case of parse errors.
749     */
750    acl_spec = strdup(aspec);
751    if (acl_spec == NULL)
752    {
753       /* XXX: This will be logged as parse error. */
754       return(-1);
755    }
756
757    if ((p = strchr(acl_spec, '/')) != NULL)
758    {
759       *p++ = '\0';
760       if (ijb_isdigit(*p) == 0)
761       {
762          freez(acl_spec);
763          return(-1);
764       }
765       masklength = atoi(p);
766    }
767
768    if ((masklength < 0) || (masklength > 32))
769    {
770       freez(acl_spec);
771       return(-1);
772    }
773
774    if ((p = strchr(acl_spec, ':')) != NULL)
775    {
776       char *endptr;
777
778       *p++ = '\0';
779       port = strtol(p, &endptr, 10);
780
781       if (port <= 0 || port > 65535 || *endptr != '\0')
782       {
783          freez(acl_spec);
784          return(-1);
785       }
786    }
787
788    aca->port = (unsigned long)port;
789
790    aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
791    freez(acl_spec);
792
793    if (aca->addr == INADDR_NONE)
794    {
795       /* XXX: This will be logged as parse error. */
796       return(-1);
797    }
798
799    /* build the netmask */
800    aca->mask = 0;
801    for (i=1; i <= masklength ; i++)
802    {
803       aca->mask |= (1 << (32 - i));
804    }
805
806    /* now mask off the host portion of the ip address
807     * (i.e. save on the network portion of the address).
808     */
809    aca->addr = aca->addr & aca->mask;
810
811    return(0);
812
813 }
814 #endif /* def FEATURE_ACL */
815
816
817 /*********************************************************************
818  *
819  * Function    :  block_url
820  *
821  * Description :  Called from `chat'.  Check to see if we need to block this.
822  *
823  * Parameters  :
824  *          1  :  csp = Current client state (buffers, headers, etc...)
825  *
826  * Returns     :  NULL => unblocked, else HTTP block response
827  *
828  *********************************************************************/
829 struct http_response *block_url(struct client_state *csp)
830 {
831    struct http_response *rsp;
832    const char *new_content_type = NULL;
833
834    /*
835     * If it's not blocked, don't block it ;-)
836     */
837    if ((csp->action->flags & ACTION_BLOCK) == 0)
838    {
839       return NULL;
840    }
841    if (csp->action->flags & ACTION_REDIRECT)
842    {
843       log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");     
844    }
845    /*
846     * Else, prepare a response
847     */
848    if (NULL == (rsp = alloc_http_response()))
849    {
850       return cgi_error_memory();
851    }
852
853    /*
854     * If it's an image-url, send back an image or redirect
855     * as specified by the relevant +image action
856     */
857 #ifdef FEATURE_IMAGE_BLOCKING
858    if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
859         && is_imageurl(csp))
860    {
861       char *p;
862       /* determine HOW images should be blocked */
863       p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
864
865       if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
866       {
867          log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
868       }
869 #if 1 /* Two alternative strategies, use this one for now: */
870
871       /* and handle accordingly: */
872       if ((p == NULL) || (0 == strcmpic(p, "pattern")))
873       {
874          rsp->status = strdup("403 Request blocked by Privoxy");
875          if (rsp->status == NULL)
876          {
877             free_http_response(rsp);
878             return cgi_error_memory();
879          }
880          rsp->body = bindup(image_pattern_data, image_pattern_length);
881          if (rsp->body == NULL)
882          {
883             free_http_response(rsp);
884             return cgi_error_memory();
885          }
886          rsp->content_length = image_pattern_length;
887
888          if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
889          {
890             free_http_response(rsp);
891             return cgi_error_memory();
892          }
893       }
894
895       else if (0 == strcmpic(p, "blank"))
896       {
897          rsp->status = strdup("403 Request blocked by Privoxy");
898          if (rsp->status == NULL)
899          {
900             free_http_response(rsp);
901             return cgi_error_memory();
902          }
903          rsp->body = bindup(image_blank_data, image_blank_length);
904          if (rsp->body == NULL)
905          {
906             free_http_response(rsp);
907             return cgi_error_memory();
908          }
909          rsp->content_length = image_blank_length;
910
911          if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
912          {
913             free_http_response(rsp);
914             return cgi_error_memory();
915          }
916       }
917
918       else
919       {
920          rsp->status = strdup("302 Local Redirect from Privoxy");
921          if (rsp->status == NULL)
922          {
923             free_http_response(rsp);
924             return cgi_error_memory();
925          }
926
927          if (enlist_unique_header(rsp->headers, "Location", p))
928          {
929             free_http_response(rsp);
930             return cgi_error_memory();
931          }
932       }
933
934 #else /* Following code is disabled for now */
935
936       /* and handle accordingly: */
937       if ((p == NULL) || (0 == strcmpic(p, "pattern")))
938       {
939          p = CGI_PREFIX "send-banner?type=pattern";
940       }
941       else if (0 == strcmpic(p, "blank"))
942       {
943          p = CGI_PREFIX "send-banner?type=blank";
944       }
945       rsp->status = strdup("302 Local Redirect from Privoxy");
946       if (rsp->status == NULL)
947       {
948          free_http_response(rsp);
949          return cgi_error_memory();
950       }
951
952       if (enlist_unique_header(rsp->headers, "Location", p))
953       {
954          free_http_response(rsp);
955          return cgi_error_memory();
956       }
957 #endif /* Preceeding code is disabled for now */
958    }
959    else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
960    {
961      /*
962       *  Send empty document.               
963       */
964       new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
965
966       freez(rsp->body);
967       rsp->body = strdup(" ");
968       rsp->content_length = 1;
969
970       rsp->status = strdup("403 Request blocked by Privoxy");
971       if (rsp->status == NULL)
972       {
973          free_http_response(rsp);
974          return cgi_error_memory();
975       }
976       if (new_content_type != 0)
977       {
978          log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
979          if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
980          {
981             free_http_response(rsp);
982             return cgi_error_memory();
983          }
984       }
985    }
986    else
987 #endif /* def FEATURE_IMAGE_BLOCKING */
988
989    /*
990     * Else, generate an HTML "blocked" message:
991     */
992    {
993       jb_err err;
994       struct map * exports;
995       char *p;
996
997       /*
998        * Workaround for stupid Netscape bug which prevents
999        * pages from being displayed if loading a referenced
1000        * JavaScript or style sheet fails. So make it appear
1001        * as if it succeeded.
1002        */
1003       if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
1004            && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
1005            && !strstr(p, "Gecko")         /* save Mozilla, */
1006            && !strstr(p, "compatible")    /* MSIE */
1007            && !strstr(p, "Opera"))        /* and Opera. */
1008       {
1009          rsp->status = strdup("200 Request for blocked URL");
1010       }
1011       else
1012       {
1013          rsp->status = strdup("403 Request for blocked URL");
1014       }
1015
1016       if (rsp->status == NULL)
1017       {
1018          free_http_response(rsp);
1019          return cgi_error_memory();
1020       }
1021
1022       exports = default_exports(csp, NULL);
1023       if (exports == NULL)
1024       {
1025          free_http_response(rsp);
1026          return cgi_error_memory();
1027       }
1028
1029 #ifdef FEATURE_FORCE_LOAD
1030       err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1031       /*
1032        * Export the force conditional block killer if
1033        *
1034        * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1035        * - Privoxy is configured to enforce blocks, or
1036        * - it's a CONNECT request and enforcing wouldn't work anyway.
1037        */
1038       if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1039        || (0 == strcmpic(csp->http->gpc, "connect")))
1040 #endif /* ndef FEATURE_FORCE_LOAD */
1041       {
1042          err = map_block_killer(exports, "force-support");
1043       }
1044
1045       if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1046       if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1047       if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1048       if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
1049
1050       if (err)
1051       {
1052          free_map(exports);
1053          free_http_response(rsp);
1054          return cgi_error_memory();
1055       }
1056
1057       err = template_fill_for_cgi(csp, "blocked", exports, rsp);
1058       if (err)
1059       {
1060          free_http_response(rsp);
1061          return cgi_error_memory();
1062       }
1063    }
1064    rsp->reason = RSP_REASON_BLOCKED;
1065
1066    return finish_http_response(csp, rsp);
1067
1068 }
1069
1070
1071 #ifdef FEATURE_TRUST
1072 /*********************************************************************
1073  *
1074  * Function    :  trust_url FIXME: I should be called distrust_url
1075  *
1076  * Description :  Calls is_untrusted_url to determine if the URL is trusted
1077  *                and if not, returns a HTTP 403 response with a reject message.
1078  *
1079  * Parameters  :
1080  *          1  :  csp = Current client state (buffers, headers, etc...)
1081  *
1082  * Returns     :  NULL => trusted, else http_response.
1083  *
1084  *********************************************************************/
1085 struct http_response *trust_url(struct client_state *csp)
1086 {
1087    struct http_response *rsp;
1088    struct map * exports;
1089    char buf[BUFFER_SIZE];
1090    char *p;
1091    struct url_spec **tl;
1092    struct url_spec *t;
1093    jb_err err;
1094
1095    /*
1096     * Don't bother to work on trusted URLs
1097     */
1098    if (!is_untrusted_url(csp))
1099    {
1100       return NULL;
1101    }
1102
1103    /*
1104     * Else, prepare a response:
1105     */
1106    if (NULL == (rsp = alloc_http_response()))
1107    {
1108       return cgi_error_memory();
1109    }
1110
1111    rsp->status = strdup("403 Request blocked by Privoxy");
1112    exports = default_exports(csp, NULL);
1113    if (exports == NULL || rsp->status == NULL)
1114    {
1115       free_http_response(rsp);
1116       return cgi_error_memory();
1117    }
1118
1119    /*
1120     * Export the protocol, host, port, and referrer information
1121     */
1122    err = map(exports, "hostport", 1, csp->http->hostport, 1);
1123    if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1); 
1124    if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1125
1126    if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1127    {
1128       if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1129    }
1130    else
1131    {
1132       if (!err) err = map(exports, "referrer", 1, "none set", 1);
1133    }
1134
1135    if (err)
1136    {
1137       free_map(exports);
1138       free_http_response(rsp);
1139       return cgi_error_memory();
1140    }
1141
1142    /*
1143     * Export the trust list
1144     */
1145    p = strdup("");
1146    for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1147    {
1148       snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
1149       string_append(&p, buf);
1150    }
1151    err = map(exports, "trusted-referrers", 1, p, 0);
1152
1153    if (err)
1154    {
1155       free_map(exports);
1156       free_http_response(rsp);
1157       return cgi_error_memory();
1158    }
1159
1160    /*
1161     * Export the trust info, if available
1162     */
1163    if (csp->config->trust_info->first)
1164    {
1165       struct list_entry *l;
1166
1167       p = strdup("");
1168       for (l = csp->config->trust_info->first; l ; l = l->next)
1169       {
1170          snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
1171          string_append(&p, buf);
1172       }
1173       err = map(exports, "trust-info", 1, p, 0);
1174    }
1175    else
1176    {
1177       err = map_block_killer(exports, "have-trust-info");
1178    }
1179
1180    if (err)
1181    {
1182       free_map(exports);
1183       free_http_response(rsp);
1184       return cgi_error_memory();
1185    }
1186
1187    /*
1188     * Export the force conditional block killer if
1189     *
1190     * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1191     * - Privoxy is configured to enforce blocks, or
1192     * - it's a CONNECT request and enforcing wouldn't work anyway.
1193     */
1194 #ifdef FEATURE_FORCE_LOAD
1195    if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1196     || (0 == strcmpic(csp->http->gpc, "connect")))
1197    {
1198       err = map_block_killer(exports, "force-support");
1199    }
1200    else
1201    {
1202       err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1203    }
1204 #else /* ifndef FEATURE_FORCE_LOAD */
1205    err = map_block_killer(exports, "force-support");
1206 #endif /* ndef FEATURE_FORCE_LOAD */
1207
1208    if (err)
1209    {
1210       free_map(exports);
1211       free_http_response(rsp);
1212       return cgi_error_memory();
1213    }
1214
1215    /*
1216     * Build the response
1217     */
1218    err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1219    if (err)
1220    {
1221       free_http_response(rsp);
1222       return cgi_error_memory();
1223    }
1224    rsp->reason = RSP_REASON_UNTRUSTED;
1225
1226    return finish_http_response(csp, rsp);
1227 }
1228 #endif /* def FEATURE_TRUST */
1229
1230
1231 /*********************************************************************
1232  *
1233  * Function    :  compile_dynamic_pcrs_job_list
1234  *
1235  * Description :  Compiles a dynamic pcrs job list (one with variables
1236  *                resolved at request time)
1237  *
1238  * Parameters  :
1239  *          1  :  csp = Current client state (buffers, headers, etc...)
1240  *          2  :  b = The filter list to compile
1241  *
1242  * Returns     :  NULL in case of errors, otherwise the
1243  *                pcrs job list.  
1244  *
1245  *********************************************************************/
1246 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
1247 {
1248    struct list_entry *pattern;
1249    pcrs_job *job_list = NULL;
1250    pcrs_job *dummy = NULL;
1251    pcrs_job *lastjob = NULL;
1252    int error = 0;
1253
1254    const struct pcrs_variable variables[] =
1255    {
1256       {"url",    csp->http->url,   1},
1257       {"path",   csp->http->path,  1},
1258       {"host",   csp->http->host,  1},
1259       {"origin", csp->ip_addr_str, 1},
1260       {NULL,     NULL,             1}
1261    };
1262
1263    for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
1264    {
1265       assert(pattern->str != NULL);
1266
1267       dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
1268       if (NULL == dummy)
1269       {
1270          assert(error < 0);
1271          log_error(LOG_LEVEL_ERROR,
1272             "Adding filter job \'%s\' to dynamic filter %s failed: %s",
1273             pattern->str, b->name, pcrs_strerror(error));
1274          continue;
1275       }
1276       else
1277       {
1278          if (error == PCRS_WARN_TRUNCATION)
1279          {
1280             log_error(LOG_LEVEL_ERROR,
1281                "At least one of the variables in \'%s\' had to "
1282                "be truncated before compilation", pattern->str);
1283          }
1284          if (job_list == NULL)
1285          {
1286             job_list = dummy;
1287          }
1288          else
1289          {
1290             lastjob->next = dummy;
1291          }
1292          lastjob = dummy;
1293       }
1294    }
1295
1296    return job_list;
1297 }
1298
1299
1300 /*********************************************************************
1301  *
1302  * Function    :  rewrite_url
1303  *
1304  * Description :  Rewrites a URL with a single pcrs command
1305  *                and returns the result if it differs from the
1306  *                original and isn't obviously invalid.
1307  *
1308  * Parameters  :
1309  *          1  :  old_url = URL to rewrite.
1310  *          2  :  pcrs_command = pcrs command formatted as string (s@foo@bar@)
1311  *
1312  *
1313  * Returns     :  NULL if the pcrs_command didn't change the url, or 
1314  *                the result of the modification.
1315  *
1316  *********************************************************************/
1317 char *rewrite_url(char *old_url, const char *pcrs_command)
1318 {
1319    char *new_url = NULL;
1320    int hits;
1321
1322    assert(old_url);
1323    assert(pcrs_command);
1324
1325    new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1326
1327    if (hits == 0)
1328    {
1329       log_error(LOG_LEVEL_REDIRECTS,
1330          "pcrs command \"%s\" didn't change \"%s\".",
1331          pcrs_command, old_url);
1332       freez(new_url);
1333    }
1334    else if (hits < 0)
1335    {
1336       log_error(LOG_LEVEL_REDIRECTS,
1337          "executing pcrs command \"%s\" to rewrite %s failed: %s",
1338          pcrs_command, old_url, pcrs_strerror(hits));
1339       freez(new_url);
1340    }
1341    else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1342    {
1343       log_error(LOG_LEVEL_ERROR,
1344          "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1345          "but the result doesn't look like a valid URL and will be ignored.",
1346          pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1347       freez(new_url);
1348    }
1349    else
1350    {
1351       log_error(LOG_LEVEL_REDIRECTS,
1352          "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1353          pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1354    }
1355
1356    return new_url;
1357
1358 }
1359
1360
1361 #ifdef FEATURE_FAST_REDIRECTS
1362 /*********************************************************************
1363  *
1364  * Function    :  get_last_url
1365  *
1366  * Description :  Search for the last URL inside a string.
1367  *                If the string already is a URL, it will
1368  *                be the first URL found.
1369  *
1370  * Parameters  :
1371  *          1  :  subject = the string to check
1372  *          2  :  redirect_mode = +fast-redirect{} mode 
1373  *
1374  * Returns     :  NULL if no URL was found, or
1375  *                the last URL found.
1376  *
1377  *********************************************************************/
1378 char *get_last_url(char *subject, const char *redirect_mode)
1379 {
1380    char *new_url = NULL;
1381    char *tmp;
1382
1383    assert(subject);
1384    assert(redirect_mode);
1385
1386    subject = strdup(subject);
1387    if (subject == NULL)
1388    {
1389       log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1390       return NULL;
1391    }
1392
1393    if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1394    {  
1395       log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1396       new_url = url_decode(subject);
1397       if (new_url != NULL)
1398       {
1399          freez(subject);
1400          subject = new_url;
1401       }
1402       else
1403       {
1404          log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1405       }
1406    }
1407
1408    log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1409
1410    /*
1411     * Find the last URL encoded in the request
1412     */
1413    tmp = subject;
1414    while ((tmp = strstr(tmp, "http://")) != NULL)
1415    {
1416       new_url = tmp++;
1417    }
1418    tmp = (new_url != NULL) ? new_url : subject;
1419    while ((tmp = strstr(tmp, "https://")) != NULL)
1420    {
1421       new_url = tmp++;
1422    }
1423
1424    if ((new_url != NULL)
1425       && (  (new_url != subject)
1426          || (0 == strncmpic(subject, "http://", 7))
1427          || (0 == strncmpic(subject, "https://", 8))
1428          ))
1429    {
1430       /*
1431        * Return new URL if we found a redirect 
1432        * or if the subject already was a URL.
1433        *
1434        * The second case makes sure that we can
1435        * chain get_last_url after another redirection check
1436        * (like rewrite_url) without losing earlier redirects.
1437        */
1438       new_url = strdup(new_url);
1439       freez(subject);
1440       return new_url;
1441    }
1442
1443    freez(subject);
1444    return NULL;
1445
1446 }
1447 #endif /* def FEATURE_FAST_REDIRECTS */
1448
1449
1450 /*********************************************************************
1451  *
1452  * Function    :  redirect_url
1453  *
1454  * Description :  Checks if Privoxy should answer the request with
1455  *                a HTTP redirect and generates the redirect if
1456  *                necessary.
1457  *
1458  * Parameters  :
1459  *          1  :  csp = Current client state (buffers, headers, etc...)
1460  *
1461  * Returns     :  NULL if the request can pass, HTTP redirect otherwise.
1462  *
1463  *********************************************************************/
1464 struct http_response *redirect_url(struct client_state *csp)
1465 {
1466    struct http_response *rsp;
1467 #ifdef FEATURE_FAST_REDIRECTS
1468    /*
1469     * XXX: Do we still need FEATURE_FAST_REDIRECTS
1470     * as compile-time option? The user can easily disable
1471     * it in his action file.
1472     */
1473    char * redirect_mode;
1474 #endif /* def FEATURE_FAST_REDIRECTS */
1475    char *old_url = NULL;
1476    char *new_url = NULL;
1477    char *redirection_string;
1478
1479    if ((csp->action->flags & ACTION_REDIRECT))
1480    {
1481       redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1482
1483       /*
1484        * If the redirection string begins with 's',
1485        * assume it's a pcrs command, otherwise treat it as
1486        * properly formatted URL and use it for the redirection
1487        * directly.
1488        *
1489        * According to RFC 2616 section 14.30 the URL
1490        * has to be absolute and if the user tries:
1491        * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1492        * she would get undefined results anyway.
1493        *
1494        */
1495
1496       if (*redirection_string == 's')
1497       {
1498          old_url = csp->http->url;
1499          new_url = rewrite_url(old_url, redirection_string);
1500       }
1501       else
1502       {
1503          log_error(LOG_LEVEL_REDIRECTS,
1504             "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1505             redirection_string);
1506          new_url = strdup(redirection_string);
1507       }
1508    }
1509
1510 #ifdef FEATURE_FAST_REDIRECTS
1511    if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1512    {
1513       redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1514
1515       /*
1516        * If it exists, use the previously rewritten URL as input
1517        * otherwise just use the old path.
1518        */
1519       old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1520       new_url = get_last_url(old_url, redirect_mode);
1521       freez(old_url);
1522    }
1523
1524    /*
1525     * Disable redirect checkers, so that they
1526     * will be only run more than once if the user
1527     * also enables them through tags.
1528     *
1529     * From a performance point of view
1530     * it doesn't matter, but the duplicated
1531     * log messages are annoying.
1532     */
1533    csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1534 #endif /* def FEATURE_FAST_REDIRECTS */
1535    csp->action->flags &= ~ACTION_REDIRECT;
1536
1537    /* Did any redirect action trigger? */   
1538    if (new_url)
1539    {
1540       if (0 == strcmpic(new_url, csp->http->url))
1541       {
1542          log_error(LOG_LEVEL_ERROR,
1543             "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1544             csp->http->url, new_url);
1545             freez(new_url);
1546       }
1547       else
1548       {
1549          log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1550
1551          if (NULL == (rsp = alloc_http_response()))
1552          {
1553             freez(new_url);
1554             return cgi_error_memory();
1555          }
1556
1557          if ( enlist_unique_header(rsp->headers, "Location", new_url)
1558            || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1559          {
1560             freez(new_url);
1561             free_http_response(rsp);
1562             return cgi_error_memory();
1563          }
1564          rsp->reason = RSP_REASON_REDIRECTED;
1565          freez(new_url);
1566
1567          return finish_http_response(csp, rsp);
1568       }
1569    }
1570
1571    /* Only reached if no redirect is required */
1572    return NULL;
1573
1574 }
1575
1576
1577 #ifdef FEATURE_IMAGE_BLOCKING
1578 /*********************************************************************
1579  *
1580  * Function    :  is_imageurl
1581  *
1582  * Description :  Given a URL, decide whether it is an image or not,
1583  *                using either the info from a previous +image action
1584  *                or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1585  *                is MSIE and not on a Mac, tell from the browser's accept
1586  *                header.
1587  *
1588  * Parameters  :
1589  *          1  :  csp = Current client state (buffers, headers, etc...)
1590  *
1591  * Returns     :  True (nonzero) if URL is an image, false (0)
1592  *                otherwise
1593  *
1594  *********************************************************************/
1595 int is_imageurl(const struct client_state *csp)
1596 {
1597 #ifdef FEATURE_IMAGE_DETECT_MSIE
1598    char *tmp;
1599
1600    tmp = get_header_value(csp->headers, "User-Agent:");
1601    if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1602    {
1603       tmp = get_header_value(csp->headers, "Accept:");
1604       if (tmp && strstr(tmp, "image/gif"))
1605       {
1606          /* Client will accept HTML.  If this seems counterintuitive,
1607           * blame Microsoft.
1608           */
1609          return(0);
1610       }
1611       else
1612       {
1613          return(1);
1614       }
1615    }
1616 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1617
1618    return ((csp->action->flags & ACTION_IMAGE) != 0);
1619
1620 }
1621 #endif /* def FEATURE_IMAGE_BLOCKING */
1622
1623
1624 #ifdef FEATURE_TRUST
1625 /*********************************************************************
1626  *
1627  * Function    :  is_untrusted_url
1628  *
1629  * Description :  Should we "distrust" this URL (and block it)?
1630  *
1631  *                Yes if it matches a line in the trustfile, or if the
1632  *                    referrer matches a line starting with "+" in the
1633  *                    trustfile.
1634  *                No  otherwise.
1635  *
1636  * Parameters  :
1637  *          1  :  csp = Current client state (buffers, headers, etc...)
1638  *
1639  * Returns     :  0 => trusted, 1 => untrusted
1640  *
1641  *********************************************************************/
1642 int is_untrusted_url(const struct client_state *csp)
1643 {
1644    struct file_list *fl;
1645    struct block_spec *b;
1646    struct url_spec **trusted_url;
1647    struct http_request rhttp[1];
1648    const char * referer;
1649    jb_err err;
1650
1651    /*
1652     * If we don't have a trustlist, we trust everybody
1653     */
1654    if (((fl = csp->tlist) == NULL) || ((b  = fl->f) == NULL))
1655    {
1656       return 0;
1657    }
1658
1659    memset(rhttp, '\0', sizeof(*rhttp));
1660
1661    /*
1662     * Do we trust the request URL itself?
1663     */
1664    for (b = b->next; b ; b = b->next)
1665    {
1666       if (url_match(b->url, csp->http))
1667       {
1668          return b->reject;
1669       }
1670    }
1671
1672    if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1673    {
1674       /* no referrer was supplied */
1675       return 1;
1676    }
1677
1678
1679    /*
1680     * If not, do we maybe trust its referrer?
1681     */
1682    err = parse_http_url(referer, rhttp, csp);
1683    if (err)
1684    {
1685       return 1;
1686    }
1687
1688    for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1689    {
1690       if (url_match(*trusted_url, rhttp))
1691       {
1692          /* if the URL's referrer is from a trusted referrer, then
1693           * add the target spec to the trustfile as an unblocked
1694           * domain and return 0 (which means it's OK).
1695           */
1696
1697          FILE *fp;
1698
1699          if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1700          {
1701             char * path;
1702             char * path_end;
1703             char * new_entry = strdup("~");
1704
1705             string_append(&new_entry, csp->http->hostport);
1706
1707             path = csp->http->path;
1708             if ( (path[0] == '/')
1709               && (path[1] == '~')
1710               && ((path_end = strchr(path + 2, '/')) != NULL))
1711             {
1712                /* since this path points into a user's home space
1713                 * be sure to include this spec in the trustfile.
1714                 */
1715                int path_len = path_end - path; /* save offset */
1716                path = strdup(path); /* Copy string */
1717                if (path != NULL)
1718                {
1719                   path_end = path + path_len; /* regenerate ptr to new buffer */
1720                   *(path_end + 1) = '\0'; /* Truncate path after '/' */
1721                }
1722                string_join(&new_entry, path);
1723             }
1724
1725             /*
1726              * Give a reason for generating this entry.
1727              */
1728             string_append(&new_entry, " # Trusted referrer was: ");
1729             string_append(&new_entry, referer);
1730
1731             if (new_entry != NULL)
1732             {
1733                if (-1 == fprintf(fp, "%s\n", new_entry))
1734                {
1735                   log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1736                      new_entry, csp->config->trustfile);
1737                }
1738                freez(new_entry);
1739             }
1740             else
1741             {
1742                /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1743                log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1744             }
1745
1746             fclose(fp);
1747          }
1748          else
1749          {
1750             log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1751                csp->http->hostport, csp->config->trustfile);
1752          }
1753          return 0;
1754       }
1755    }
1756
1757    return 1;
1758 }
1759 #endif /* def FEATURE_TRUST */
1760
1761
1762 /*********************************************************************
1763  *
1764  * Function    :  pcrs_filter_response
1765  *
1766  * Description :  Execute all text substitutions from all applying
1767  *                +filter actions on the text buffer that's been
1768  *                accumulated in csp->iob->buf.
1769  *
1770  * Parameters  :
1771  *          1  :  csp = Current client state (buffers, headers, etc...)
1772  *
1773  * Returns     :  a pointer to the (newly allocated) modified buffer.
1774  *                or NULL if there were no hits or something went wrong
1775  *
1776  *********************************************************************/
1777 static char *pcrs_filter_response(struct client_state *csp)
1778 {
1779    int hits=0;
1780    size_t size, prev_size;
1781
1782    char *old = NULL;
1783    char *new = NULL;
1784    pcrs_job *job;
1785
1786    struct file_list *fl;
1787    struct re_filterfile_spec *b;
1788    struct list_entry *filtername;
1789
1790    int i, found_filters = 0;
1791
1792    /* 
1793     * Sanity first
1794     */
1795    if (csp->iob->cur >= csp->iob->eod)
1796    {
1797       return(NULL);
1798    }
1799
1800    /*
1801     * Need to check the set of re_filterfiles...
1802     */
1803    for (i = 0; i < MAX_AF_FILES; i++)
1804    {
1805       fl = csp->rlist[i];
1806       if (NULL != fl)
1807       {
1808          if (NULL != fl->f)
1809          {
1810            found_filters = 1;
1811            break;
1812          }
1813       }
1814    }
1815
1816    if (0 == found_filters)
1817    {
1818       log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1819          "content filtering enabled, but no content filters available.");
1820       return(NULL);
1821    }
1822
1823    size = (size_t)(csp->iob->eod - csp->iob->cur);
1824    old = csp->iob->cur;
1825
1826    for (i = 0; i < MAX_AF_FILES; i++)
1827    {
1828      fl = csp->rlist[i];
1829      if ((NULL == fl) || (NULL == fl->f))
1830      {
1831         /*
1832          * Either there are no filter files
1833          * left, or this filter file just
1834          * contains no valid filters.
1835          *
1836          * Continue to be sure we don't miss
1837          * valid filter files that are chained
1838          * after empty or invalid ones.
1839          */
1840         continue;
1841      }
1842    /*
1843     * For all applying +filter actions, look if a filter by that
1844     * name exists and if yes, execute it's pcrs_joblist on the
1845     * buffer.
1846     */
1847    for (b = fl->f; b; b = b->next)
1848    {
1849       if (b->type != FT_CONTENT_FILTER)
1850       {
1851          /* Skip header filters */
1852          continue;
1853       }
1854
1855       for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1856            filtername ; filtername = filtername->next)
1857       {
1858          if (strcmp(b->name, filtername->str) == 0)
1859          {
1860             int current_hits = 0; /* Number of hits caused by this filter */
1861             int job_number   = 0; /* Which job we're currently executing  */
1862             int job_hits     = 0; /* How many hits the current job caused */
1863             pcrs_job *joblist = b->joblist;
1864
1865             if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1866
1867             if (NULL == joblist)
1868             {
1869                log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1870                continue;
1871             }
1872
1873             prev_size = size;
1874             /* Apply all jobs from the joblist */
1875             for (job = joblist; NULL != job; job = job->next)
1876             {
1877                job_number++;
1878                job_hits = pcrs_execute(job, old, size, &new, &size);
1879
1880                if (job_hits >= 0)
1881                {
1882                   /*
1883                    * That went well. Continue filtering
1884                    * and use the result of this job as
1885                    * input for the next one.
1886                    */
1887                   current_hits += job_hits;
1888                   if (old != csp->iob->cur)
1889                   {
1890                      freez(old);
1891                   }
1892                   old = new;
1893                }
1894                else
1895                {
1896                   /*
1897                    * This job caused an unexpected error. Inform the user
1898                    * and skip the rest of the jobs in this filter. We could
1899                    * continue with the next job, but usually the jobs
1900                    * depend on each other or are similar enough to
1901                    * fail for the same reason.
1902                    *
1903                    * At the moment our pcrs expects the error codes of pcre 3.4,
1904                    * but newer pcre versions can return additional error codes.
1905                    * As a result pcrs_strerror()'s error message might be
1906                    * "Unknown error ...", therefore we print the numerical value
1907                    * as well.
1908                    *
1909                    * XXX: Is this important enough for LOG_LEVEL_ERROR or
1910                    * should we use LOG_LEVEL_RE_FILTER instead?
1911                    */
1912                   log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1913                      b->name, job_number, pcrs_strerror(job_hits), job_hits);
1914                   break;
1915                }
1916             }
1917
1918             if (b->dynamic) pcrs_free_joblist(joblist);
1919
1920             log_error(LOG_LEVEL_RE_FILTER,
1921                "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1922                csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1923
1924             hits += current_hits;
1925          }
1926       }
1927    }
1928    }
1929
1930    /*
1931     * If there were no hits, destroy our copy and let
1932     * chat() use the original in csp->iob
1933     */
1934    if (!hits)
1935    {
1936       freez(new);
1937       return(NULL);
1938    }
1939
1940    csp->flags |= CSP_FLAG_MODIFIED;
1941    csp->content_length = size;
1942    IOB_RESET(csp);
1943
1944    return(new);
1945
1946 }
1947
1948
1949 /*********************************************************************
1950  *
1951  * Function    :  gif_deanimate_response
1952  *
1953  * Description :  Deanimate the GIF image that has been accumulated in
1954  *                csp->iob->buf, set csp->content_length to the modified
1955  *                size and raise the CSP_FLAG_MODIFIED flag.
1956  *
1957  * Parameters  :
1958  *          1  :  csp = Current client state (buffers, headers, etc...)
1959  *
1960  * Returns     :  a pointer to the (newly allocated) modified buffer.
1961  *                or NULL in case something went wrong.
1962  *
1963  *********************************************************************/
1964 static char *gif_deanimate_response(struct client_state *csp)
1965 {
1966    struct binbuffer *in, *out;
1967    char *p;
1968    size_t size;
1969
1970    size = (size_t)(csp->iob->eod - csp->iob->cur);
1971
1972    if (  (NULL == (in =  (struct binbuffer *)zalloc(sizeof *in )))
1973       || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1974    {
1975       log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1976       return NULL;
1977    }
1978
1979    in->buffer = csp->iob->cur;
1980    in->size = size;
1981
1982    if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1983    {
1984       log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1985       freez(in);
1986       buf_free(out);
1987       return(NULL);
1988    }
1989    else
1990    {
1991       if ((int)size == out->offset)
1992       {
1993          log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1994       }
1995       else
1996       {
1997          log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1998       }
1999       csp->content_length = out->offset;
2000       csp->flags |= CSP_FLAG_MODIFIED;
2001       p = out->buffer;
2002       freez(in);
2003       freez(out);
2004       return(p);
2005    }
2006
2007 }
2008
2009
2010 /*********************************************************************
2011  *
2012  * Function    :  jpeg_inspect_response
2013  *
2014  * Description :  
2015  *
2016  * Parameters  :
2017  *          1  :  csp = Current client state (buffers, headers, etc...)
2018  *
2019  * Returns     :  a pointer to the (newly allocated) modified buffer
2020  *                or NULL in case something went wrong.
2021  *
2022  *********************************************************************/
2023 static char *jpeg_inspect_response(struct client_state *csp)
2024 {
2025    struct binbuffer  *in = NULL;
2026    struct binbuffer *out = NULL;
2027    char *p = NULL;
2028    size_t size;
2029
2030    size = (size_t)(csp->iob->eod - csp->iob->cur);
2031
2032    if (NULL == (in =  (struct binbuffer *)zalloc(sizeof *in )))
2033    {
2034       log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
2035       return NULL;
2036    }
2037
2038    if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
2039    {
2040       log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
2041       return NULL;
2042    }
2043
2044    in->buffer = csp->iob->cur;
2045    in->size = size;
2046
2047    /*
2048     * Calling jpeg_inspect has the side-effect of creating and 
2049     * modifying the image buffer of "out" directly.
2050     */
2051    if (jpeg_inspect(in, out))
2052    {
2053       log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
2054       freez(in);
2055       buf_free(out);
2056       return(NULL);
2057
2058    }
2059    else
2060    {
2061       csp->content_length = out->offset;
2062       csp->flags |= CSP_FLAG_MODIFIED;
2063       p = out->buffer;
2064       freez(in);
2065       freez(out);
2066       return(p);
2067    }
2068
2069 }
2070
2071
2072 /*********************************************************************
2073  *
2074  * Function    :  get_filter_function
2075  *
2076  * Description :  Decides which content filter function has
2077  *                to be applied (if any).
2078  *
2079  *                XXX: Doesn't handle filter_popups()
2080  *                because of the different prototype. Probably
2081  *                we should ditch filter_popups() anyway, it's
2082  *                even less reliable than popup blocking based
2083  *                on pcrs filters.
2084  *
2085  * Parameters  :
2086  *          1  :  csp = Current client state (buffers, headers, etc...)
2087  *
2088  * Returns     :  The content filter function to run, or
2089  *                NULL if no content filter is active
2090  *
2091  *********************************************************************/
2092 filter_function_ptr get_filter_function(struct client_state *csp)
2093 {
2094    filter_function_ptr filter_function = NULL;
2095
2096    /*
2097     * Are we enabling text mode by force?
2098     */
2099    if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2100    {
2101       /*
2102        * Do we really have to?
2103        */
2104       if (csp->content_type & CT_TEXT)
2105       {
2106          log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");   
2107       }
2108       else
2109       {
2110          csp->content_type |= CT_TEXT;
2111          log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");   
2112       }
2113    }
2114
2115    if (!(csp->content_type & CT_DECLARED))
2116    {
2117       /*
2118        * The server didn't bother to declare a MIME-Type.
2119        * Assume it's text that can be filtered.
2120        *
2121        * This also regulary happens with 304 responses,
2122        * therefore logging anything here would cause
2123        * too much noise.
2124        */
2125       csp->content_type |= CT_TEXT;
2126    }
2127
2128    /*
2129     * Choose the applying filter function based on
2130     * the content type and action settings.
2131     */
2132    if ((csp->content_type & CT_TEXT) &&
2133        (csp->rlist != NULL) &&
2134        (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2135    {
2136       filter_function = pcrs_filter_response;
2137    }
2138    else if ((csp->content_type & CT_GIF)  &&
2139             (csp->action->flags & ACTION_DEANIMATE))
2140    {
2141       filter_function = gif_deanimate_response;
2142    }
2143    else if ((csp->content_type & CT_JPEG)  &&
2144             (csp->action->flags & ACTION_JPEG_INSPECT))
2145    {
2146       filter_function = jpeg_inspect_response;
2147    }
2148
2149    return filter_function;
2150 }
2151
2152
2153 /*********************************************************************
2154  *
2155  * Function    :  remove_chunked_transfer_coding
2156  *
2157  * Description :  In-situ remove the "chunked" transfer coding as defined
2158  *                in rfc2616 from a buffer.
2159  *
2160  * Parameters  :
2161  *          1  :  buffer = Pointer to the text buffer
2162  *          2  :  size =  In: Number of bytes to be processed,
2163  *                       Out: Number of bytes after de-chunking.
2164  *                       (undefined in case of errors)
2165  *
2166  * Returns     :  JB_ERR_OK for success,
2167  *                JB_ERR_PARSE otherwise
2168  *
2169  *********************************************************************/
2170 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2171 {
2172    size_t newsize = 0;
2173    unsigned int chunksize = 0;
2174    char *from_p, *to_p;
2175
2176    assert(buffer);
2177    from_p = to_p = buffer;
2178
2179    if (sscanf(buffer, "%x", &chunksize) != 1)
2180    {
2181       log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2182       return JB_ERR_PARSE;
2183    }
2184
2185    while (chunksize > 0)
2186    {
2187       if (NULL == (from_p = strstr(from_p, "\r\n")))
2188       {
2189          log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2190          return JB_ERR_PARSE;
2191       }
2192
2193       if ((newsize += chunksize) >= *size)
2194       {
2195          log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in  \"chunked\" transfer coding");
2196          return JB_ERR_PARSE;
2197       }
2198       from_p += 2;
2199
2200       memmove(to_p, from_p, (size_t) chunksize);
2201       to_p = buffer + newsize;
2202       from_p += chunksize + 2;
2203
2204       if (sscanf(from_p, "%x", &chunksize) != 1)
2205       {
2206          log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2207          break;
2208       }
2209    }
2210    
2211    /* XXX: Should get its own loglevel. */
2212    log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
2213
2214    *size = newsize;
2215
2216    return JB_ERR_OK;
2217
2218 }
2219
2220
2221 /*********************************************************************
2222  *
2223  * Function    :  prepare_for_filtering
2224  *
2225  * Description :  If necessary, de-chunks and decompresses
2226  *                the content so it can get filterd.
2227  *
2228  * Parameters  :
2229  *          1  :  csp = Current client state (buffers, headers, etc...)
2230  *
2231  * Returns     :  JB_ERR_OK for success,
2232  *                JB_ERR_PARSE otherwise
2233  *
2234  *********************************************************************/
2235 static jb_err prepare_for_filtering(struct client_state *csp)
2236 {
2237    jb_err err = JB_ERR_OK;
2238
2239    /*
2240     * If the body has a "chunked" transfer-encoding,
2241     * get rid of it, adjusting size and iob->eod
2242     */
2243    if (csp->flags & CSP_FLAG_CHUNKED)
2244    {
2245       size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2246
2247       log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2248       err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2249       if (JB_ERR_OK == err)
2250       {
2251          csp->iob->eod = csp->iob->cur + size;
2252          csp->flags |= CSP_FLAG_MODIFIED;
2253       }
2254       else
2255       {
2256          return JB_ERR_PARSE;
2257       }
2258    }
2259
2260 #ifdef FEATURE_ZLIB
2261    /*
2262     * If the body has a supported transfer-encoding,
2263     * decompress it, adjusting size and iob->eod.
2264     */
2265    if (csp->content_type & (CT_GZIP|CT_DEFLATE))
2266    {
2267       if (0 == csp->iob->eod - csp->iob->cur)
2268       {
2269          /* Nothing left after de-chunking. */
2270          return JB_ERR_OK;
2271       }
2272
2273       err = decompress_iob(csp);
2274
2275       if (JB_ERR_OK == err)
2276       {
2277          csp->flags |= CSP_FLAG_MODIFIED;
2278          csp->content_type &= ~CT_TABOO;
2279       }
2280       else
2281       {
2282          /*
2283           * Unset CT_GZIP and CT_DEFLATE to remember not
2284           * to modify the Content-Encoding header later.
2285           */
2286          csp->content_type &= ~CT_GZIP;
2287          csp->content_type &= ~CT_DEFLATE;
2288       }
2289    }
2290 #endif
2291
2292    return err;
2293 }
2294
2295
2296 /*********************************************************************
2297  *
2298  * Function    :  execute_content_filter
2299  *
2300  * Description :  Executes a given content filter.
2301  *
2302  * Parameters  :
2303  *          1  :  csp = Current client state (buffers, headers, etc...)
2304  *          2  :  content_filter = The filter function to execute
2305  *
2306  * Returns     :  Pointer to the modified buffer, or
2307  *                NULL if filtering failed or wasn't necessary.
2308  *
2309  *********************************************************************/
2310 char *execute_content_filter(struct client_state *csp, filter_function_ptr content_filter)
2311 {
2312    if (0 == csp->iob->eod - csp->iob->cur)
2313    {
2314       /*
2315        * No content (probably status code 301, 302 ...),
2316        * no filtering necessary.
2317        */
2318       return NULL;
2319    }
2320
2321    if (JB_ERR_OK != prepare_for_filtering(csp))
2322    {
2323       /*
2324        * failed to de-chunk or decompress.
2325        */
2326       return NULL;
2327    }
2328
2329    if (0 == csp->iob->eod - csp->iob->cur)
2330    {
2331       /*
2332        * Clown alarm: chunked and/or compressed nothing delivered.
2333        */
2334       return NULL;
2335    }
2336
2337    return ((*content_filter)(csp));
2338 }
2339
2340
2341 /*********************************************************************
2342  *
2343  * Function    :  url_actions
2344  *
2345  * Description :  Gets the actions for this URL.
2346  *
2347  * Parameters  :
2348  *          1  :  http = http_request request for blocked URLs
2349  *          2  :  csp = Current client state (buffers, headers, etc...)
2350  *
2351  * Returns     :  N/A
2352  *
2353  *********************************************************************/
2354 void url_actions(struct http_request *http,
2355                  struct client_state *csp)
2356 {
2357    struct file_list *fl;
2358    struct url_actions *b;
2359    int i;
2360
2361    init_current_action(csp->action);
2362
2363    for (i = 0; i < MAX_AF_FILES; i++)
2364    {
2365       if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2366       {
2367          return;
2368       }
2369
2370       apply_url_actions(csp->action, http, b);
2371    }
2372
2373    return;
2374 }
2375
2376
2377 /*********************************************************************
2378  *
2379  * Function    :  apply_url_actions
2380  *
2381  * Description :  Applies a list of URL actions.
2382  *
2383  * Parameters  :
2384  *          1  :  action = Destination.
2385  *          2  :  http = Current URL
2386  *          3  :  b = list of URL actions to apply
2387  *
2388  * Returns     :  N/A
2389  *
2390  *********************************************************************/
2391 void apply_url_actions(struct current_action_spec *action,
2392                        struct http_request *http,
2393                        struct url_actions *b)
2394 {
2395    if (b == NULL)
2396    {
2397       /* Should never happen */
2398       return;
2399    }
2400
2401    for (b = b->next; NULL != b; b = b->next)
2402    {
2403       if (url_match(b->url, http))
2404       {
2405          merge_current_action(action, b->action);
2406       }
2407    }
2408 }
2409
2410
2411 /*********************************************************************
2412  *
2413  * Function    :  get_forward_override_settings
2414  *
2415  * Description :  Returns forward settings as specified with the
2416  *                forward-override{} action. forward-override accepts
2417  *                forward lines similar to the one used in the
2418  *                configuration file, but without the URL pattern.
2419  *
2420  *                For example:
2421  *
2422  *                   forward / .
2423  *
2424  *                in the configuration file can be replaced with
2425  *                the action section:
2426  *
2427  *                 {+forward-override{forward .}}
2428  *                 /
2429  *
2430  * Parameters  :
2431  *          1  :  csp = Current client state (buffers, headers, etc...)
2432  *
2433  * Returns     :  Pointer to forwarding structure in case of success.
2434  *                Invalid syntax is fatal.
2435  *
2436  *********************************************************************/
2437 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2438 {
2439    const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2440    char forward_settings[BUFFER_SIZE];
2441    char *http_parent = NULL;
2442    /* variable names were chosen for consistency reasons. */
2443    struct forward_spec *fwd = NULL;
2444    int vec_count;
2445    char *vec[3];
2446
2447    assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2448    /* Should be enforced by load_one_actions_file() */
2449    assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2450
2451    /* Create a copy ssplit can modify */
2452    strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2453
2454    if (NULL != csp->fwd)
2455    {
2456       /*
2457        * XXX: Currently necessary to prevent memory
2458        * leaks when the show-url-info cgi page is visited.
2459        */
2460       unload_forward_spec(csp->fwd);
2461    }
2462
2463    /*
2464     * allocate a new forward node, valid only for
2465     * the lifetime of this request. Save its location
2466     * in csp as well, so sweep() can free it later on.
2467     */
2468    fwd = csp->fwd = zalloc(sizeof(*fwd));
2469    if (NULL == fwd)
2470    {
2471       log_error(LOG_LEVEL_FATAL,
2472          "can't allocate memory for forward-override{%s}", forward_override_line);
2473       /* Never get here - LOG_LEVEL_FATAL causes program exit */
2474    }
2475
2476    vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2477    if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2478    {
2479       fwd->type = SOCKS_NONE;
2480
2481       /* Parse the parent HTTP proxy host:port */
2482       http_parent = vec[1];
2483
2484    }
2485    else if (vec_count == 3)
2486    {
2487       char *socks_proxy = NULL;
2488
2489       if  (!strcasecmp(vec[0], "forward-socks4"))
2490       {
2491          fwd->type = SOCKS_4;
2492          socks_proxy = vec[1];
2493       }
2494       else if (!strcasecmp(vec[0], "forward-socks4a"))
2495       {
2496          fwd->type = SOCKS_4A;
2497          socks_proxy = vec[1];
2498       }
2499       else if (!strcasecmp(vec[0], "forward-socks5"))
2500       {
2501          fwd->type = SOCKS_5;
2502          socks_proxy = vec[1];
2503       }
2504
2505       if (NULL != socks_proxy)
2506       {
2507          /* Parse the SOCKS proxy host[:port] */
2508          fwd->gateway_host = strdup(socks_proxy);
2509
2510          if (NULL != (socks_proxy = strchr(fwd->gateway_host, ':')))
2511          {
2512             *socks_proxy++ = '\0';
2513             fwd->gateway_port = strtol(socks_proxy, NULL, 0);
2514          }
2515
2516          if (fwd->gateway_port <= 0)
2517          {
2518             fwd->gateway_port = 1080;
2519          }
2520
2521          http_parent = vec[2];
2522       }
2523    }
2524
2525    if (NULL == http_parent)
2526    {
2527       log_error(LOG_LEVEL_FATAL,
2528          "Invalid forward-override syntax in: %s", forward_override_line);
2529       /* Never get here - LOG_LEVEL_FATAL causes program exit */
2530    }
2531
2532    /* Parse http forwarding settings */
2533    if (strcmp(http_parent, ".") != 0)
2534    {
2535       fwd->forward_host = strdup(http_parent);
2536
2537       if (NULL != (http_parent = strchr(fwd->forward_host, ':')))
2538       {
2539          *http_parent++ = '\0';
2540          fwd->forward_port = strtol(http_parent, NULL, 0);
2541       }
2542
2543       if (fwd->forward_port <= 0)
2544       {
2545          fwd->forward_port = 8000;
2546       }
2547    }
2548
2549    assert (NULL != fwd);
2550
2551    log_error(LOG_LEVEL_CONNECT,
2552       "Overriding forwarding settings based on \'%s\'", forward_override_line);
2553
2554    return fwd;
2555 }
2556
2557
2558 /*********************************************************************
2559  *
2560  * Function    :  forward_url
2561  *
2562  * Description :  Should we forward this to another proxy?
2563  *
2564  * Parameters  :
2565  *          1  :  csp = Current client state (buffers, headers, etc...)
2566  *          2  :  http = http_request request for current URL
2567  *
2568  * Returns     :  Pointer to forwarding information.
2569  *
2570  *********************************************************************/
2571 const struct forward_spec *forward_url(struct client_state *csp,
2572                                        const struct http_request *http)
2573 {
2574    static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2575    struct forward_spec *fwd = csp->config->forward;
2576
2577    if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2578    {
2579       return get_forward_override_settings(csp);
2580    }
2581
2582    if (fwd == NULL)
2583    {
2584       return fwd_default;
2585    }
2586
2587    while (fwd != NULL)
2588    {
2589       if (url_match(fwd->url, http))
2590       {
2591          return fwd;
2592       }
2593       fwd = fwd->next;
2594    }
2595
2596    return fwd_default;
2597 }
2598
2599
2600 /*********************************************************************
2601  *
2602  * Function    :  direct_response 
2603  *
2604  * Description :  Check if Max-Forwards == 0 for an OPTIONS or TRACE
2605  *                request and if so, return a HTTP 501 to the client.
2606  *
2607  *                FIXME: I have a stupid name and I should handle the
2608  *                requests properly. Still, what we do here is rfc-
2609  *                compliant, whereas ignoring or forwarding are not.
2610  *
2611  * Parameters  :  
2612  *          1  :  csp = Current client state (buffers, headers, etc...)
2613  *
2614  * Returns     :  http_response if , NULL if nonmatch or handler fail
2615  *
2616  *********************************************************************/
2617 struct http_response *direct_response(struct client_state *csp)
2618 {
2619    struct http_response *rsp;
2620    struct list_entry *p;
2621
2622    if ((0 == strcmpic(csp->http->gpc, "trace"))
2623       || (0 == strcmpic(csp->http->gpc, "options")))
2624    {
2625       for (p = csp->headers->first; (p != NULL) ; p = p->next)
2626       {
2627          if (!strncmpic("Max-Forwards:", p->str, 13))
2628          {
2629             unsigned int max_forwards;
2630
2631             /*
2632              * If it's a Max-Forwards value of zero,
2633              * we have to intercept the request.
2634              */
2635             if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2636             {
2637                /*
2638                 * FIXME: We could handle at least TRACE here,
2639                 * but that would require a verbatim copy of
2640                 * the request which we don't have anymore
2641                 */
2642                 log_error(LOG_LEVEL_HEADER,
2643                   "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2644                   p->str);
2645
2646                /* Get mem for response or fail*/
2647                if (NULL == (rsp = alloc_http_response()))
2648                {
2649                   return cgi_error_memory();
2650                }
2651             
2652                if (NULL == (rsp->status = strdup("501 Not Implemented")))
2653                {
2654                   free_http_response(rsp);
2655                   return cgi_error_memory();
2656                }
2657
2658                rsp->is_static = 1;
2659                rsp->reason = RSP_REASON_UNSUPPORTED;
2660
2661                return(finish_http_response(csp, rsp));
2662             }
2663          }
2664       }
2665    }
2666    return NULL;
2667 }
2668
2669
2670 /*********************************************************************
2671  *
2672  * Function    :  content_filters_enabled
2673  *
2674  * Description :  Checks whether there are any content filters
2675  *                enabled for the current request.
2676  *
2677  * Parameters  :  
2678  *          1  :  csp = Current client state (buffers, headers, etc...)
2679  *
2680  * Returns     :  TRUE for yes, FALSE otherwise
2681  *
2682  *********************************************************************/
2683 inline int content_filters_enabled(const struct client_state *csp)
2684 {
2685    return (((csp->rlist != NULL) &&
2686       (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]))) ||
2687       (csp->action->flags & (ACTION_DEANIMATE|ACTION_JPEG_INSPECT|ACTION_NO_POPUPS)));
2688 }
2689
2690 /*
2691   Local Variables:
2692   tab-width: 3
2693   end:
2694 */