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