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