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