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