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