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