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