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