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