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