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