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