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