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