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