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