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