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