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