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