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