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