1 const char filters_rcs[] = "$Id: filters.c,v 1.95 2007/10/17 19:31:20 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
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'
16 * Copyright : Written by and Copyright (C) 2001, 2004-2007 the SourceForge
17 * Privoxy team. http://www.privoxy.org/
19 * Based on the Internet Junkbuster originally written
20 * by and Copyright (C) 1997 Anonymous Coders and
21 * Junkbusters Corporation. http://www.junkbusters.com
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.
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.
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.
43 * Revision 1.95 2007/10/17 19:31:20 fabiankeil
44 * Omitting the zero chunk that ends the chunk transfer encoding seems
45 * to be the new black. Log the problem and continue filtering anyway.
47 * Revision 1.94 2007/09/29 13:20:20 fabiankeil
48 * Remove two redundant and one useless log messages.
50 * Revision 1.93 2007/09/29 10:21:16 fabiankeil
51 * - Move get_filter_function() from jcc.c to filters.c
52 * so the filter functions can be static.
53 * - Don't bother filtering body-less responses.
55 * Revision 1.92 2007/09/28 16:38:55 fabiankeil
56 * - Execute content filters through execute_content_filter().
57 * - Add prepare_for_filtering() so filter functions don't have to
58 * care about de-chunking and decompression. As a side effect this enables
59 * decompression for gif_deanimate_response() and jpeg_inspect_response().
60 * - Change remove_chunked_transfer_coding()'s return type to jb_err.
61 * Some clowns feel like chunking empty responses in which case
62 * (size == 0) is valid but previously would be interpreted as error.
64 * Revision 1.91 2007/09/02 15:31:20 fabiankeil
65 * Move match_portlist() from filter.c to urlmatch.c.
66 * It's used for url matching, not for filtering.
68 * Revision 1.90 2007/09/02 12:44:17 fabiankeil
69 * Remove newline at the end of a log_error() message.
71 * Revision 1.89 2007/08/05 13:42:23 fabiankeil
72 * #1763173 from Stefan Huehner: declare some more functions static.
74 * Revision 1.88 2007/06/01 16:41:11 fabiankeil
75 * Add forward-override{} to change the forwarding settings through
76 * action sections. This is mainly interesting to forward different
77 * clients differently (for example based on User-Agent or request
80 * Revision 1.87 2007/04/30 15:53:10 fabiankeil
81 * Make sure filters with dynamic jobs actually use them.
83 * Revision 1.86 2007/04/30 15:03:28 fabiankeil
84 * - Introduce dynamic pcrs jobs that can resolve variables.
85 * - Don't run redirect functions more than once,
86 * unless they are activated more than once.
88 * Revision 1.85 2007/03/21 12:24:47 fabiankeil
89 * - Log the content size after decompression in decompress_iob()
90 * instead of pcrs_filter_response().
92 * Revision 1.84 2007/03/20 15:16:34 fabiankeil
93 * Use dedicated header filter actions instead of abusing "filter".
94 * Replace "filter-client-headers" and "filter-client-headers"
95 * with "server-header-filter" and "client-header-filter".
97 * Revision 1.83 2007/03/17 15:20:05 fabiankeil
98 * New config option: enforce-blocks.
100 * Revision 1.82 2007/03/13 11:28:43 fabiankeil
101 * - Fix port handling in acl_addr() and use a temporary acl spec
102 * copy so error messages don't contain a truncated version.
103 * - Log size of iob before and after decompression.
105 * Revision 1.81 2007/03/05 14:40:53 fabiankeil
106 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
107 * - Hide the "Go there anyway" link for blocked CONNECT
108 * requests where going there anyway doesn't work anyway.
110 * Revision 1.80 2007/02/07 10:55:20 fabiankeil
111 * - Save the reason for generating http_responses.
112 * - Block (+block) with status code 403 instead of 404.
113 * - Use a different kludge to remember a failed decompression.
115 * Revision 1.79 2007/01/31 16:21:38 fabiankeil
116 * Search for Max-Forwards headers case-insensitive,
117 * don't generate the "501 unsupported" message for invalid
118 * Max-Forwards values and don't increase negative ones.
120 * Revision 1.78 2007/01/28 13:41:18 fabiankeil
121 * - Add HEAD support to finish_http_response.
122 * - Add error favicon to internal HTML error messages.
124 * Revision 1.77 2007/01/12 15:36:44 fabiankeil
125 * Mark *csp as immutable for is_untrusted_url()
126 * and is_imageurl(). Closes FR 1237736.
128 * Revision 1.76 2007/01/01 19:36:37 fabiankeil
129 * Integrate a modified version of Wil Mahan's
130 * zlib patch (PR #895531).
132 * Revision 1.75 2006/12/29 18:30:46 fabiankeil
133 * Fixed gcc43 conversion warnings,
134 * changed sprintf calls to snprintf.
136 * Revision 1.74 2006/12/24 17:37:38 fabiankeil
137 * Adjust comment in pcrs_filter_response()
138 * to recent pcrs changes. Hohoho.
140 * Revision 1.73 2006/12/23 16:01:02 fabiankeil
141 * Don't crash if pcre returns an error code
142 * that pcrs didn't expect. Fixes BR 1621173.
144 * Revision 1.72 2006/12/22 18:52:53 fabiankeil
145 * Modified is_untrusted_url to complain in case of
146 * write errors and to give a reason when adding new
147 * entries to the trustfile. Closes FR 1097611.
149 * Revision 1.71 2006/12/22 14:24:52 fabiankeil
150 * Skip empty filter files in pcrs_filter_response,
151 * but don't ignore the ones that come afterwards.
152 * Fixes parts of BR 1619208.
154 * Revision 1.70 2006/12/09 13:33:15 fabiankeil
155 * Added some sanity checks for get_last_url().
156 * Fixed possible segfault caused by my last commit.
158 * Revision 1.69 2006/12/08 12:39:13 fabiankeil
159 * Let get_last_url() catch https URLs as well.
161 * Revision 1.68 2006/12/05 14:45:48 fabiankeil
162 * Make sure get_last_url() behaves like advertised
163 * and fast-redirects{} can be combined with redirect{}.
165 * Revision 1.67 2006/11/28 15:19:43 fabiankeil
166 * Implemented +redirect{s@foo@bar@} to generate
167 * a redirect based on a rewritten version of the
170 * Revision 1.66 2006/09/23 13:26:38 roro
171 * Replace TABs by spaces in source code.
173 * Revision 1.65 2006/09/21 12:54:43 fabiankeil
174 * Fix +redirect{}. Didn't work with -fast-redirects.
176 * Revision 1.64 2006/08/31 10:55:49 fabiankeil
177 * Block requests for untrusted URLs with status
178 * code 403 instead of 200.
180 * Revision 1.63 2006/08/31 10:11:28 fabiankeil
181 * Don't free p which is still in use and will be later
182 * freed by free_map(). Don't claim the referrer is unknown
183 * when the client didn't set one.
185 * Revision 1.62 2006/08/14 00:27:47 david__schmidt
186 * Feature request 595948: Re-Filter logging in single line
188 * Revision 1.61 2006/08/03 02:46:41 david__schmidt
189 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
191 * Revision 1.60 2006/07/18 14:48:46 david__schmidt
192 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
193 * with what was really the latest development (the v_3_0_branch branch)
195 * Revision 1.58.2.9 2006/01/29 23:10:56 david__schmidt
196 * Multiple filter file support
198 * Revision 1.58.2.8 2005/05/07 21:50:55 david__schmidt
199 * A few memory leaks plugged (mostly on error paths)
201 * Revision 1.58.2.7 2004/10/03 12:53:32 david__schmidt
202 * Add the ability to check jpeg images for invalid
203 * lengths of comment blocks. Defensive strategy
204 * against the exploit:
205 * Microsoft Security Bulletin MS04-028
206 * Buffer Overrun in JPEG Processing (GDI+) Could
207 * Allow Code Execution (833987)
208 * Enabled with +inspect-jpegs in actions files.
210 * Revision 1.58.2.6 2003/12/06 22:18:27 gliptak
211 * Correcting compile problem with FEATURE_IMAGE_BLOCKING
213 * Revision 1.58.2.5 2003/11/11 13:10:31 oes
214 * Fixed bug #839859: "See why" link URL now gets url-encoded.
216 * Revision 1.58.2.4 2003/02/28 12:52:45 oes
219 * Revision 1.58.2.3 2002/09/25 14:51:51 oes
220 * Added basic support for OPTIONS and TRACE HTTP methods:
221 * New function direct_response which handles OPTIONS and
222 * TRACE requests whose Max-Forwards header field is zero.
224 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
225 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
227 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
228 * - Bugfix: Executing a filters without jobs no longer results in
229 * turing off *all* filters.
230 * - Security fix: Malicious web servers can't cause a seg fault
231 * through bogus chunk sizes anymore
233 * Revision 1.58 2002/04/24 02:11:17 oes
234 * Jon's multiple AF patch: url_actions now evaluates rules
237 * Revision 1.57 2002/04/08 20:38:34 swa
240 * Revision 1.56 2002/04/05 15:51:24 oes
241 * - bugfix: error-pages now get correct request protocol
242 * - fix for invalid HTML in trust info
244 * Revision 1.55 2002/04/02 16:13:51 oes
245 * Fix: No "Go there anyway" for SSL
247 * Revision 1.54 2002/04/02 14:55:56 oes
248 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
250 * Revision 1.53 2002/03/26 22:29:54 swa
251 * we have a new homepage!
253 * Revision 1.52 2002/03/24 16:35:57 jongfoster
256 * Revision 1.51 2002/03/24 15:23:33 jongfoster
259 * Revision 1.50 2002/03/24 13:25:43 swa
260 * name change related issues
262 * Revision 1.49 2002/03/16 20:29:14 oes
265 * Revision 1.48 2002/03/13 20:25:34 oes
266 * Better logging for content filters
268 * Revision 1.47 2002/03/13 00:30:52 jongfoster
270 * Added option of always sending redirect for imageblock,
271 * currently disabled with #if 0.
273 * Revision 1.46 2002/03/12 01:42:49 oes
274 * Introduced modular filters
276 * Revision 1.45 2002/03/08 16:47:50 oes
277 * Added choice beween GIF and PNG built-in images
279 * Revision 1.44 2002/03/07 03:49:31 oes
280 * - Fixed compiler warnings etc
281 * - Changed built-in images from GIF to PNG
282 * (with regard to Unisys patent issue)
283 * - Added a 4x4 pattern PNG which is less intrusive
284 * than the logo but also clearly marks the deleted banners
286 * Revision 1.43 2002/01/22 23:51:59 jongfoster
287 * Replacing strsav() with the safer string_append().
289 * Adding missing html_encode() to error message generators. Where encoded
290 * and unencoded versions of a string were provided, removing the unencoded
293 * Revision 1.42 2002/01/17 21:00:32 jongfoster
294 * Moving all our URL and URL pattern parsing code to urlmatch.c.
296 * Using a single, simple url_match(pattern,url) function - rather than
297 * the 3-line match routine which was repeated all over the place.
299 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
301 * Using parse_http_url() to parse URLs without faking a HTTP
302 * request line for parse_http_request().
304 * Revision 1.41 2001/11/13 00:14:07 jongfoster
305 * Fixing stupid bug now I've figured out what || means.
306 * (It always returns 0 or 1, not one of it's paramaters.)
308 * Revision 1.40 2001/10/26 17:37:55 oes
309 * - Re-enabled Netscape 200/404 bug workaround in block_url():
310 * - Removed OS/2 special case
311 * - Made block_url() independant from sed() having been run
312 * - Made trust_url independant from sed() having been run
313 * - Made is_imageurl independant from sed() having been run.
314 * It now checks User-Agent: and Accept: by itself.
317 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
318 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
319 * threads to call select() simultaneously. So, it's time to do a real, live,
320 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
321 * (native). Both versions will work, but using __OS2__ offers multi-threading.
323 * Revision 1.38 2001/10/23 21:32:33 jongfoster
324 * Adding error-checking to selected functions
326 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
327 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
328 * filters.c. Added a FIXME in front of the offending code. I'll gladly
329 * put in a better/more robust fix for all parties if one is presented...
330 * It seems that just returning 200 instead of 404 would pretty much fix
331 * it for everyone, but I don't know all the history of the problem.
333 * Revision 1.36 2001/10/10 16:44:16 oes
334 * Added match_portlist function
336 * Revision 1.35 2001/10/07 15:41:23 oes
337 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
339 * New function remove_chunked_transfer_coding that strips chunked
340 * transfer coding to plain and is called by pcrs_filter_response
341 * and gif_deanimate_response if neccessary
343 * Improved handling of zero-change re_filter runs
345 * pcrs_filter_response and gif_deanimate_response now remove
346 * chunked transfer codeing before processing the body.
348 * Revision 1.34 2001/09/20 15:49:36 steudten
350 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
351 * See cgi.c fill_template().
353 * Revision 1.33 2001/09/16 17:05:14 jongfoster
354 * Removing unused #include showarg.h
356 * Revision 1.32 2001/09/16 13:21:27 jongfoster
357 * Changes to use new list functions.
359 * Revision 1.31 2001/09/16 11:38:02 jongfoster
360 * Splitting fill_template() into 2 functions:
361 * template_load() loads the file
362 * template_fill() performs the PCRS regexps.
363 * This is because the CGI edit interface has a "table row"
364 * template which is used many times in the page - this
365 * change means it's only loaded from disk once.
367 * Revision 1.30 2001/09/16 11:00:10 jongfoster
368 * New function alloc_http_response, for symmetry with free_http_response
370 * Revision 1.29 2001/09/13 23:32:40 jongfoster
371 * Moving image data to cgi.c rather than cgi.h
372 * Fixing a GPF under Win32 (and any other OS that protects global
373 * constants from being written to).
375 * Revision 1.28 2001/09/10 10:18:51 oes
376 * Silenced compiler warnings
378 * Revision 1.27 2001/08/05 16:06:20 jongfoster
379 * Modifiying "struct map" so that there are now separate header and
380 * "map_entry" structures. This means that functions which modify a
381 * map no longer need to return a pointer to the modified map.
382 * Also, it no longer reverses the order of the entries (which may be
383 * important with some advanced template substitutions).
385 * Revision 1.26 2001/07/30 22:08:36 jongfoster
386 * Tidying up #defines:
387 * - All feature #defines are now of the form FEATURE_xxx
388 * - Permanently turned off WIN_GUI_EDIT
389 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
391 * Revision 1.25 2001/07/26 10:09:46 oes
392 * Made browser detection a little less naive
394 * Revision 1.24 2001/07/25 17:22:51 oes
395 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
397 * Revision 1.23 2001/07/23 13:40:12 oes
398 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
400 * Revision 1.22 2001/07/18 12:29:34 oes
401 * - Made gif_deanimate_response respect
402 * csp->action->string[ACTION_STRING_DEANIMATE]
403 * - Logging cosmetics
405 * Revision 1.21 2001/07/13 13:59:53 oes
406 * - Introduced gif_deanimate_response which shares the
407 * generic content modification interface of pcrs_filter_response
408 * and acts as a wrapper to deanimate.c:gif_deanimate()
409 * - Renamed re_process_buffer to pcrs_filter_response
410 * - pcrs_filter_response now returns NULL on failiure
411 * - Removed all #ifdef PCRS
413 * Revision 1.20 2001/07/01 17:01:04 oes
414 * Added comments and missing return statement in is_untrusted_url()
416 * Revision 1.19 2001/06/29 21:45:41 oes
417 * Indentation, CRLF->LF, Tab-> Space
419 * Revision 1.18 2001/06/29 13:27:38 oes
420 * - Cleaned up, renamed and reorderd functions
421 * and improved comments
424 * - Ported to CGI platform. Now delivers
425 * http_response or NULL
426 * - Unified HTML and GIF generation (moved image detection
427 * and GIF generation here from jcc.c:chat())
428 * - Fixed HTTP status to:
429 * - 403 (Forbidden) for the "blocked" HTML message
430 * - 200 (OK) for GIF answers
431 * - 302 (Redirect) for redirect to GIF
434 * - Ported to CGI platform. Now delivers
435 * http_response or NULL
436 * - Separated detection of untrusted URL into
437 * (bool)is_untrusted_url
438 * - Added enforcement of untrusted requests
440 * - Moved redirect_url() from cgi.c to here
441 * and ported it to the CGI platform
443 * - Removed logentry from cancelled commit
445 * Revision 1.17 2001/06/09 10:55:28 jongfoster
446 * Changing BUFSIZ ==> BUFFER_SIZE
448 * Revision 1.16 2001/06/07 23:10:26 jongfoster
449 * Allowing unanchored domain patterns to back off and retry
450 * if they partially match. Optimized right-anchored patterns.
451 * Moving ACL and forward files into config file.
452 * Replacing struct gateway with struct forward_spec
454 * Revision 1.15 2001/06/03 19:12:00 oes
455 * extracted-CGI relevant stuff
457 * Revision 1.14 2001/06/01 10:30:55 oes
458 * Added optional left-anchoring to domaincmp
460 * Revision 1.13 2001/05/31 21:21:30 jongfoster
461 * Permissionsfile / actions file changes:
462 * - Changed "permission" to "action" throughout
463 * - changes to file format to allow string parameters
464 * - Moved helper functions to actions.c
466 * Revision 1.12 2001/05/31 17:35:20 oes
468 * - Enhanced domain part globbing with infix and prefix asterisk
469 * matching and optional unanchored operation
471 * Revision 1.11 2001/05/29 11:53:23 oes
472 * "See why" link added to "blocked" page
474 * Revision 1.10 2001/05/29 09:50:24 jongfoster
475 * Unified blocklist/imagelist/permissionslist.
476 * File format is still under discussion, but the internal changes
479 * Also modified interceptor behaviour:
480 * - We now intercept all URLs beginning with one of the following
481 * prefixes (and *only* these prefixes):
483 * * http://ijbswa.sf.net/config/
484 * * http://ijbswa.sourceforge.net/config/
485 * - New interceptors "home page" - go to http://i.j.b/ to see it.
486 * - Internal changes so that intercepted and fast redirect pages
487 * are not replaced with an image.
488 * - Interceptors now have the option to send a binary page direct
489 * to the client. (i.e. ijb-send-banner uses this)
490 * - Implemented show-url-info interceptor. (Which is why I needed
491 * the above interceptors changes - a typical URL is
492 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
493 * The previous mechanism would not have intercepted that, and
494 * if it had been intercepted then it then it would have replaced
497 * Revision 1.9 2001/05/27 22:17:04 oes
499 * - re_process_buffer no longer writes the modified buffer
500 * to the client, which was very ugly. It now returns the
501 * buffer, which it is then written by chat.
503 * - content_length now adjusts the Content-Length: header
504 * for modified documents rather than crunch()ing it.
505 * (Length info in csp->content_length, which is 0 for
506 * unmodified documents)
508 * - For this to work, sed() is called twice when filtering.
510 * Revision 1.8 2001/05/26 17:13:28 jongfoster
511 * Filled in a function comment.
513 * Revision 1.7 2001/05/26 15:26:15 jongfoster
514 * ACL feature now provides more security by immediately dropping
515 * connections from untrusted hosts.
517 * Revision 1.6 2001/05/26 00:28:36 jongfoster
518 * Automatic reloading of config file.
519 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
520 * Most of the global variables have been moved to a new
521 * struct configuration_spec, accessed through csp->config->globalname
522 * Most of the globals remaining are used by the Win32 GUI.
524 * Revision 1.5 2001/05/25 22:34:30 jongfoster
527 * Revision 1.4 2001/05/22 18:46:04 oes
529 * - Enabled filtering banners by size rather than URL
530 * by adding patterns that replace all standard banner
531 * sizes with the "Junkbuster" gif to the re_filterfile
533 * - Enabled filtering WebBugs by providing a pattern
534 * which kills all 1x1 images
536 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
537 * which is selected by the (nonstandard and therefore
538 * capital) letter 'U' in the option string.
539 * It causes the quantifiers to be ungreedy by default.
540 * Appending a ? turns back to greedy (!).
542 * - Added a new interceptor ijb-send-banner, which
543 * sends back the "Junkbuster" gif. Without imagelist or
544 * MSIE detection support, or if tinygif = 1, or the
545 * URL isn't recognized as an imageurl, a lame HTML
546 * explanation is sent instead.
548 * - Added new feature, which permits blocking remote
549 * script redirects and firing back a local redirect
551 * The feature is conditionally compiled, i.e. it
552 * can be disabled with --disable-fast-redirects,
553 * plus it must be activated by a "fast-redirects"
554 * line in the config file, has its own log level
555 * and of course wants to be displayed by show-proxy-args
556 * Note: Boy, all the #ifdefs in 1001 locations and
557 * all the fumbling with configure.in and acconfig.h
558 * were *way* more work than the feature itself :-(
560 * - Because a generic redirect template was needed for
561 * this, tinygif = 3 now uses the same.
563 * - Moved GIFs, and other static HTTP response templates
568 * - Removed some >400 CRs again (Jon, you really worked
571 * Revision 1.3 2001/05/20 16:44:47 jongfoster
572 * Removing last hardcoded Junkbusters.com URLs.
574 * Revision 1.2 2001/05/20 01:21:20 jongfoster
575 * Version 2.9.4 checkin.
576 * - Merged popupfile and cookiefile, and added control over PCRS
577 * filtering, in new "permissionsfile".
578 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
579 * file error you now get a message box (in the Win32 GUI) rather
580 * than the program exiting with no explanation.
581 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
583 * - Removed tabs from "config"
584 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
585 * - Bumped up version number.
587 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
588 * Initial import of version 2.9.3 source tree
591 *********************************************************************/
597 #include <sys/types.h>
606 #endif /* ndef __OS2__ */
607 #include <netinet/in.h>
609 #include <winsock2.h>
610 #endif /* ndef _WIN32 */
614 #endif /* def __OS2__ */
622 #include "jbsockets.h"
623 #include "miscutil.h"
627 #include "deanimate.h"
628 #include "urlmatch.h"
635 const char filters_h_rcs[] = FILTERS_H_VERSION;
637 /* Fix a problem with Solaris. There should be no effect on other
639 * Solaris's isspace() is a macro which uses it's argument directly
640 * as an array index. Therefore we need to make sure that high-bit
641 * characters generate +ve values, and ideally we also want to make
642 * the argument match the declared parameter type of "int".
644 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
646 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
647 static jb_err prepare_for_filtering(struct client_state *csp);
650 /*********************************************************************
652 * Function : block_acl
654 * Description : Block this request?
655 * Decide yes or no based on ACL file.
658 * 1 : dst = The proxy or gateway address this is going to.
659 * Or NULL to check all possible targets.
660 * 2 : csp = Current client state (buffers, headers, etc...)
661 * Also includes the client IP address.
663 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
665 *********************************************************************/
666 int block_acl(struct access_control_addr *dst, struct client_state *csp)
668 struct access_control_list *acl = csp->config->acl;
670 /* if not using an access control list, then permit the connection */
676 /* search the list */
679 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
683 /* Just want to check if they have any access */
684 if (acl->action == ACL_PERMIT)
689 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
690 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
692 if (acl->action == ACL_PERMIT)
710 /*********************************************************************
712 * Function : acl_addr
714 * Description : Called from `load_config' to parse an ACL address.
717 * 1 : aspec = String specifying ACL address.
718 * 2 : aca = struct access_control_addr to fill in.
720 * Returns : 0 => Ok, everything else is an error.
722 *********************************************************************/
723 int acl_addr(const char *aspec, struct access_control_addr *aca)
728 char *acl_spec = NULL;
734 * Use a temporary acl spec copy so we can log
735 * the unmodified original in case of parse errors.
737 acl_spec = strdup(aspec);
738 if (acl_spec == NULL)
740 /* XXX: This will be logged as parse error. */
744 if ((p = strchr(acl_spec, '/')) != NULL)
747 if (ijb_isdigit(*p) == 0)
752 masklength = atoi(p);
755 if ((masklength < 0) || (masklength > 32))
761 if ((p = strchr(acl_spec, ':')) != NULL)
766 port = strtol(p, &endptr, 10);
768 if (port <= 0 || port > 65535 || *endptr != '\0')
775 aca->port = (unsigned long)port;
777 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
780 if (aca->addr == INADDR_NONE)
782 /* XXX: This will be logged as parse error. */
786 /* build the netmask */
788 for (i=1; i <= masklength ; i++)
790 aca->mask |= (1 << (32 - i));
793 /* now mask off the host portion of the ip address
794 * (i.e. save on the network portion of the address).
796 aca->addr = aca->addr & aca->mask;
801 #endif /* def FEATURE_ACL */
804 /*********************************************************************
806 * Function : block_url
808 * Description : Called from `chat'. Check to see if we need to block this.
811 * 1 : csp = Current client state (buffers, headers, etc...)
813 * Returns : NULL => unblocked, else HTTP block response
815 *********************************************************************/
816 struct http_response *block_url(struct client_state *csp)
818 struct http_response *rsp;
819 const char *new_content_type = NULL;
822 * If it's not blocked, don't block it ;-)
824 if ((csp->action->flags & ACTION_BLOCK) == 0)
828 if (csp->action->flags & ACTION_REDIRECT)
830 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
833 * Else, prepare a response
835 if (NULL == (rsp = alloc_http_response()))
837 return cgi_error_memory();
841 * If it's an image-url, send back an image or redirect
842 * as specified by the relevant +image action
844 #ifdef FEATURE_IMAGE_BLOCKING
845 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
849 /* determine HOW images should be blocked */
850 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
852 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
854 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
856 #if 1 /* Two alternative strategies, use this one for now: */
858 /* and handle accordingly: */
859 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
861 rsp->status = strdup("403 Request blocked by Privoxy");
862 if (rsp->status == NULL)
864 free_http_response(rsp);
865 return cgi_error_memory();
867 rsp->body = bindup(image_pattern_data, image_pattern_length);
868 if (rsp->body == NULL)
870 free_http_response(rsp);
871 return cgi_error_memory();
873 rsp->content_length = image_pattern_length;
875 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
877 free_http_response(rsp);
878 return cgi_error_memory();
882 else if (0 == strcmpic(p, "blank"))
884 rsp->status = strdup("403 Request blocked by Privoxy");
885 if (rsp->status == NULL)
887 free_http_response(rsp);
888 return cgi_error_memory();
890 rsp->body = bindup(image_blank_data, image_blank_length);
891 if (rsp->body == NULL)
893 free_http_response(rsp);
894 return cgi_error_memory();
896 rsp->content_length = image_blank_length;
898 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
900 free_http_response(rsp);
901 return cgi_error_memory();
907 rsp->status = strdup("302 Local Redirect from Privoxy");
908 if (rsp->status == NULL)
910 free_http_response(rsp);
911 return cgi_error_memory();
914 if (enlist_unique_header(rsp->headers, "Location", p))
916 free_http_response(rsp);
917 return cgi_error_memory();
921 #else /* Following code is disabled for now */
923 /* and handle accordingly: */
924 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
926 p = CGI_PREFIX "send-banner?type=pattern";
928 else if (0 == strcmpic(p, "blank"))
930 p = CGI_PREFIX "send-banner?type=blank";
932 rsp->status = strdup("302 Local Redirect from Privoxy");
933 if (rsp->status == NULL)
935 free_http_response(rsp);
936 return cgi_error_memory();
939 if (enlist_unique_header(rsp->headers, "Location", p))
941 free_http_response(rsp);
942 return cgi_error_memory();
944 #endif /* Preceeding code is disabled for now */
946 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
949 * Send empty document.
951 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
954 rsp->body = strdup(" ");
955 rsp->content_length = 1;
957 rsp->status = strdup("403 Request blocked by Privoxy");
958 if (rsp->status == NULL)
960 free_http_response(rsp);
961 return cgi_error_memory();
963 if (new_content_type != 0)
965 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
966 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
968 free_http_response(rsp);
969 return cgi_error_memory();
974 #endif /* def FEATURE_IMAGE_BLOCKING */
977 * Else, generate an HTML "blocked" message:
981 struct map * exports;
985 * Workaround for stupid Netscape bug which prevents
986 * pages from being displayed if loading a referenced
987 * JavaScript or style sheet fails. So make it appear
988 * as if it succeeded.
990 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
991 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
992 && !strstr(p, "Gecko") /* save Mozilla, */
993 && !strstr(p, "compatible") /* MSIE */
994 && !strstr(p, "Opera")) /* and Opera. */
996 rsp->status = strdup("200 Request for blocked URL");
1000 rsp->status = strdup("403 Request for blocked URL");
1003 if (rsp->status == NULL)
1005 free_http_response(rsp);
1006 return cgi_error_memory();
1009 exports = default_exports(csp, NULL);
1010 if (exports == NULL)
1012 free_http_response(rsp);
1013 return cgi_error_memory();
1016 #ifdef FEATURE_FORCE_LOAD
1017 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1019 * Export the force conditional block killer if
1021 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1022 * - Privoxy is configured to enforce blocks, or
1023 * - it's a CONNECT request and enforcing wouldn't work anyway.
1025 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1026 || (0 == strcmpic(csp->http->gpc, "connect")))
1027 #endif /* ndef FEATURE_FORCE_LOAD */
1029 err = map_block_killer(exports, "force-support");
1032 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1033 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1034 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1035 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
1040 free_http_response(rsp);
1041 return cgi_error_memory();
1044 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
1047 free_http_response(rsp);
1048 return cgi_error_memory();
1051 rsp->reason = RSP_REASON_BLOCKED;
1053 return finish_http_response(csp, rsp);
1058 #ifdef FEATURE_TRUST
1059 /*********************************************************************
1061 * Function : trust_url FIXME: I should be called distrust_url
1063 * Description : Calls is_untrusted_url to determine if the URL is trusted
1064 * and if not, returns a HTTP 403 response with a reject message.
1067 * 1 : csp = Current client state (buffers, headers, etc...)
1069 * Returns : NULL => trusted, else http_response.
1071 *********************************************************************/
1072 struct http_response *trust_url(struct client_state *csp)
1074 struct http_response *rsp;
1075 struct map * exports;
1076 char buf[BUFFER_SIZE];
1078 struct url_spec **tl;
1083 * Don't bother to work on trusted URLs
1085 if (!is_untrusted_url(csp))
1091 * Else, prepare a response:
1093 if (NULL == (rsp = alloc_http_response()))
1095 return cgi_error_memory();
1098 rsp->status = strdup("403 Request blocked by Privoxy");
1099 exports = default_exports(csp, NULL);
1100 if (exports == NULL || rsp->status == NULL)
1102 free_http_response(rsp);
1103 return cgi_error_memory();
1107 * Export the protocol, host, port, and referrer information
1109 err = map(exports, "hostport", 1, csp->http->hostport, 1);
1110 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1111 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1113 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1115 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1119 if (!err) err = map(exports, "referrer", 1, "none set", 1);
1125 free_http_response(rsp);
1126 return cgi_error_memory();
1130 * Export the trust list
1133 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1135 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
1136 string_append(&p, buf);
1138 err = map(exports, "trusted-referrers", 1, p, 0);
1143 free_http_response(rsp);
1144 return cgi_error_memory();
1148 * Export the trust info, if available
1150 if (csp->config->trust_info->first)
1152 struct list_entry *l;
1155 for (l = csp->config->trust_info->first; l ; l = l->next)
1157 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
1158 string_append(&p, buf);
1160 err = map(exports, "trust-info", 1, p, 0);
1164 err = map_block_killer(exports, "have-trust-info");
1170 free_http_response(rsp);
1171 return cgi_error_memory();
1175 * Export the force conditional block killer if
1177 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1178 * - Privoxy is configured to enforce blocks, or
1179 * - it's a CONNECT request and enforcing wouldn't work anyway.
1181 #ifdef FEATURE_FORCE_LOAD
1182 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1183 || (0 == strcmpic(csp->http->gpc, "connect")))
1185 err = map_block_killer(exports, "force-support");
1189 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1191 #else /* ifndef FEATURE_FORCE_LOAD */
1192 err = map_block_killer(exports, "force-support");
1193 #endif /* ndef FEATURE_FORCE_LOAD */
1198 free_http_response(rsp);
1199 return cgi_error_memory();
1203 * Build the response
1205 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1208 free_http_response(rsp);
1209 return cgi_error_memory();
1211 rsp->reason = RSP_REASON_UNTRUSTED;
1213 return finish_http_response(csp, rsp);
1215 #endif /* def FEATURE_TRUST */
1218 /*********************************************************************
1220 * Function : compile_dynamic_pcrs_job_list
1222 * Description : Compiles a dynamic pcrs job list (one with variables
1223 * resolved at request time)
1226 * 1 : csp = Current client state (buffers, headers, etc...)
1227 * 2 : b = The filter list to compile
1229 * Returns : NULL in case of errors, otherwise the
1232 *********************************************************************/
1233 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
1235 struct list_entry *pattern;
1236 pcrs_job *job_list = NULL;
1237 pcrs_job *dummy = NULL;
1238 pcrs_job *lastjob = NULL;
1241 const struct pcrs_variable variables[] =
1243 {"url", csp->http->url, 1},
1244 {"path", csp->http->path, 1},
1245 {"host", csp->http->host, 1},
1246 {"origin", csp->ip_addr_str, 1},
1250 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
1252 assert(pattern->str != NULL);
1254 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
1258 log_error(LOG_LEVEL_ERROR,
1259 "Adding filter job \'%s\' to dynamic filter %s failed: %s",
1260 pattern->str, b->name, pcrs_strerror(error));
1265 if (error == PCRS_WARN_TRUNCATION)
1267 log_error(LOG_LEVEL_ERROR,
1268 "At least one of the variables in \'%s\' had to "
1269 "be truncated before compilation", pattern->str);
1271 if (job_list == NULL)
1277 lastjob->next = dummy;
1287 /*********************************************************************
1289 * Function : rewrite_url
1291 * Description : Rewrites a URL with a single pcrs command
1292 * and returns the result if it differs from the
1293 * original and isn't obviously invalid.
1296 * 1 : old_url = URL to rewrite.
1297 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1300 * Returns : NULL if the pcrs_command didn't change the url, or
1301 * the result of the modification.
1303 *********************************************************************/
1304 char *rewrite_url(char *old_url, const char *pcrs_command)
1306 char *new_url = NULL;
1310 assert(pcrs_command);
1312 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1316 log_error(LOG_LEVEL_REDIRECTS,
1317 "pcrs command \"%s\" didn't change \"%s\".",
1318 pcrs_command, old_url);
1323 log_error(LOG_LEVEL_REDIRECTS,
1324 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1325 pcrs_command, old_url, pcrs_strerror(hits));
1328 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1330 log_error(LOG_LEVEL_ERROR,
1331 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1332 "but the result doesn't look like a valid URL and will be ignored.",
1333 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1338 log_error(LOG_LEVEL_REDIRECTS,
1339 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1340 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1348 #ifdef FEATURE_FAST_REDIRECTS
1349 /*********************************************************************
1351 * Function : get_last_url
1353 * Description : Search for the last URL inside a string.
1354 * If the string already is a URL, it will
1355 * be the first URL found.
1358 * 1 : subject = the string to check
1359 * 2 : redirect_mode = +fast-redirect{} mode
1361 * Returns : NULL if no URL was found, or
1362 * the last URL found.
1364 *********************************************************************/
1365 char *get_last_url(char *subject, const char *redirect_mode)
1367 char *new_url = NULL;
1371 assert(redirect_mode);
1373 subject = strdup(subject);
1374 if (subject == NULL)
1376 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1380 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1382 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1383 new_url = url_decode(subject);
1384 if (new_url != NULL)
1391 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1395 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1398 * Find the last URL encoded in the request
1401 while ((tmp = strstr(tmp, "http://")) != NULL)
1405 tmp = (new_url != NULL) ? new_url : subject;
1406 while ((tmp = strstr(tmp, "https://")) != NULL)
1411 if ((new_url != NULL)
1412 && ( (new_url != subject)
1413 || (0 == strncmpic(subject, "http://", 7))
1414 || (0 == strncmpic(subject, "https://", 8))
1418 * Return new URL if we found a redirect
1419 * or if the subject already was a URL.
1421 * The second case makes sure that we can
1422 * chain get_last_url after another redirection check
1423 * (like rewrite_url) without losing earlier redirects.
1425 new_url = strdup(new_url);
1434 #endif /* def FEATURE_FAST_REDIRECTS */
1437 /*********************************************************************
1439 * Function : redirect_url
1441 * Description : Checks if Privoxy should answer the request with
1442 * a HTTP redirect and generates the redirect if
1446 * 1 : csp = Current client state (buffers, headers, etc...)
1448 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1450 *********************************************************************/
1451 struct http_response *redirect_url(struct client_state *csp)
1453 struct http_response *rsp;
1454 #ifdef FEATURE_FAST_REDIRECTS
1456 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1457 * as compile-time option? The user can easily disable
1458 * it in his action file.
1460 char * redirect_mode;
1461 #endif /* def FEATURE_FAST_REDIRECTS */
1462 char *old_url = NULL;
1463 char *new_url = NULL;
1464 char *redirection_string;
1466 if ((csp->action->flags & ACTION_REDIRECT))
1468 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1471 * If the redirection string begins with 's',
1472 * assume it's a pcrs command, otherwise treat it as
1473 * properly formatted URL and use it for the redirection
1476 * According to RFC 2616 section 14.30 the URL
1477 * has to be absolute and if the user tries:
1478 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1479 * she would get undefined results anyway.
1483 if (*redirection_string == 's')
1485 old_url = csp->http->url;
1486 new_url = rewrite_url(old_url, redirection_string);
1490 log_error(LOG_LEVEL_REDIRECTS,
1491 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1492 redirection_string);
1493 new_url = strdup(redirection_string);
1497 #ifdef FEATURE_FAST_REDIRECTS
1498 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1500 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1503 * If it exists, use the previously rewritten URL as input
1504 * otherwise just use the old path.
1506 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1507 new_url = get_last_url(old_url, redirect_mode);
1512 * Disable redirect checkers, so that they
1513 * will be only run more than once if the user
1514 * also enables them through tags.
1516 * From a performance point of view
1517 * it doesn't matter, but the duplicated
1518 * log messages are annoying.
1520 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1521 #endif /* def FEATURE_FAST_REDIRECTS */
1522 csp->action->flags &= ~ACTION_REDIRECT;
1524 /* Did any redirect action trigger? */
1527 if (0 == strcmpic(new_url, csp->http->url))
1529 log_error(LOG_LEVEL_ERROR,
1530 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1531 csp->http->url, new_url);
1536 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1538 if (NULL == (rsp = alloc_http_response()))
1541 return cgi_error_memory();
1544 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1545 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1548 free_http_response(rsp);
1549 return cgi_error_memory();
1551 rsp->reason = RSP_REASON_REDIRECTED;
1554 return finish_http_response(csp, rsp);
1558 /* Only reached if no redirect is required */
1564 #ifdef FEATURE_IMAGE_BLOCKING
1565 /*********************************************************************
1567 * Function : is_imageurl
1569 * Description : Given a URL, decide whether it is an image or not,
1570 * using either the info from a previous +image action
1571 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1572 * is MSIE and not on a Mac, tell from the browser's accept
1576 * 1 : csp = Current client state (buffers, headers, etc...)
1578 * Returns : True (nonzero) if URL is an image, false (0)
1581 *********************************************************************/
1582 int is_imageurl(const struct client_state *csp)
1584 #ifdef FEATURE_IMAGE_DETECT_MSIE
1587 tmp = get_header_value(csp->headers, "User-Agent:");
1588 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1590 tmp = get_header_value(csp->headers, "Accept:");
1591 if (tmp && strstr(tmp, "image/gif"))
1593 /* Client will accept HTML. If this seems counterintuitive,
1603 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1605 return ((csp->action->flags & ACTION_IMAGE) != 0);
1608 #endif /* def FEATURE_IMAGE_BLOCKING */
1611 #ifdef FEATURE_TRUST
1612 /*********************************************************************
1614 * Function : is_untrusted_url
1616 * Description : Should we "distrust" this URL (and block it)?
1618 * Yes if it matches a line in the trustfile, or if the
1619 * referrer matches a line starting with "+" in the
1624 * 1 : csp = Current client state (buffers, headers, etc...)
1626 * Returns : 0 => trusted, 1 => untrusted
1628 *********************************************************************/
1629 int is_untrusted_url(const struct client_state *csp)
1631 struct file_list *fl;
1632 struct block_spec *b;
1633 struct url_spec **trusted_url;
1634 struct http_request rhttp[1];
1635 const char * referer;
1639 * If we don't have a trustlist, we trust everybody
1641 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1646 memset(rhttp, '\0', sizeof(*rhttp));
1649 * Do we trust the request URL itself?
1651 for (b = b->next; b ; b = b->next)
1653 if (url_match(b->url, csp->http))
1659 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1661 /* no referrer was supplied */
1667 * If not, do we maybe trust its referrer?
1669 err = parse_http_url(referer, rhttp, csp);
1675 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1677 if (url_match(*trusted_url, rhttp))
1679 /* if the URL's referrer is from a trusted referrer, then
1680 * add the target spec to the trustfile as an unblocked
1681 * domain and return 0 (which means it's OK).
1686 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1690 char * new_entry = strdup("~");
1692 string_append(&new_entry, csp->http->hostport);
1694 path = csp->http->path;
1695 if ( (path[0] == '/')
1697 && ((path_end = strchr(path + 2, '/')) != NULL))
1699 /* since this path points into a user's home space
1700 * be sure to include this spec in the trustfile.
1702 int path_len = path_end - path; /* save offset */
1703 path = strdup(path); /* Copy string */
1706 path_end = path + path_len; /* regenerate ptr to new buffer */
1707 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1709 string_join(&new_entry, path);
1713 * Give a reason for generating this entry.
1715 string_append(&new_entry, " # Trusted referrer was: ");
1716 string_append(&new_entry, referer);
1718 if (new_entry != NULL)
1720 if (-1 == fprintf(fp, "%s\n", new_entry))
1722 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1723 new_entry, csp->config->trustfile);
1729 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1730 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1737 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1738 csp->http->hostport, csp->config->trustfile);
1746 #endif /* def FEATURE_TRUST */
1749 /*********************************************************************
1751 * Function : pcrs_filter_response
1753 * Description : Execute all text substitutions from all applying
1754 * +filter actions on the text buffer that's been
1755 * accumulated in csp->iob->buf.
1758 * 1 : csp = Current client state (buffers, headers, etc...)
1760 * Returns : a pointer to the (newly allocated) modified buffer.
1761 * or NULL if there were no hits or something went wrong
1763 *********************************************************************/
1764 static char *pcrs_filter_response(struct client_state *csp)
1767 size_t size, prev_size;
1773 struct file_list *fl;
1774 struct re_filterfile_spec *b;
1775 struct list_entry *filtername;
1777 int i, found_filters = 0;
1782 if (csp->iob->cur >= csp->iob->eod)
1788 * Need to check the set of re_filterfiles...
1790 for (i = 0; i < MAX_AF_FILES; i++)
1803 if (0 == found_filters)
1805 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1809 size = (size_t)(csp->iob->eod - csp->iob->cur);
1810 old = csp->iob->cur;
1812 for (i = 0; i < MAX_AF_FILES; i++)
1815 if ((NULL == fl) || (NULL == fl->f))
1818 * Either there are no filter files
1819 * left, or this filter file just
1820 * contains no valid filters.
1822 * Continue to be sure we don't miss
1823 * valid filter files that are chained
1824 * after empty or invalid ones.
1829 * For all applying +filter actions, look if a filter by that
1830 * name exists and if yes, execute it's pcrs_joblist on the
1833 for (b = fl->f; b; b = b->next)
1835 if (b->type != FT_CONTENT_FILTER)
1837 /* Skip header filters */
1841 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1842 filtername ; filtername = filtername->next)
1844 if (strcmp(b->name, filtername->str) == 0)
1846 int current_hits = 0; /* Number of hits caused by this filter */
1847 int job_number = 0; /* Which job we're currently executing */
1848 int job_hits = 0; /* How many hits the current job caused */
1849 pcrs_job *joblist = b->joblist;
1851 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1853 if (NULL == joblist)
1855 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1860 /* Apply all jobs from the joblist */
1861 for (job = joblist; NULL != job; job = job->next)
1864 job_hits = pcrs_execute(job, old, size, &new, &size);
1869 * That went well. Continue filtering
1870 * and use the result of this job as
1871 * input for the next one.
1873 current_hits += job_hits;
1874 if (old != csp->iob->cur)
1883 * This job caused an unexpected error. Inform the user
1884 * and skip the rest of the jobs in this filter. We could
1885 * continue with the next job, but usually the jobs
1886 * depend on each other or are similar enough to
1887 * fail for the same reason.
1889 * At the moment our pcrs expects the error codes of pcre 3.4,
1890 * but newer pcre versions can return additional error codes.
1891 * As a result pcrs_strerror()'s error message might be
1892 * "Unknown error ...", therefore we print the numerical value
1895 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1896 * should we use LOG_LEVEL_RE_FILTER instead?
1898 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1899 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1904 if (b->dynamic) pcrs_free_joblist(joblist);
1906 log_error(LOG_LEVEL_RE_FILTER,
1907 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1908 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1910 hits += current_hits;
1917 * If there were no hits, destroy our copy and let
1918 * chat() use the original in csp->iob
1926 csp->flags |= CSP_FLAG_MODIFIED;
1927 csp->content_length = size;
1935 /*********************************************************************
1937 * Function : gif_deanimate_response
1939 * Description : Deanimate the GIF image that has been accumulated in
1940 * csp->iob->buf, set csp->content_length to the modified
1941 * size and raise the CSP_FLAG_MODIFIED flag.
1944 * 1 : csp = Current client state (buffers, headers, etc...)
1946 * Returns : a pointer to the (newly allocated) modified buffer.
1947 * or NULL in case something went wrong.
1949 *********************************************************************/
1950 static char *gif_deanimate_response(struct client_state *csp)
1952 struct binbuffer *in, *out;
1956 size = (size_t)(csp->iob->eod - csp->iob->cur);
1958 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1959 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1961 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1965 in->buffer = csp->iob->cur;
1968 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1970 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1977 if ((int)size == out->offset)
1979 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1983 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1985 csp->content_length = out->offset;
1986 csp->flags |= CSP_FLAG_MODIFIED;
1996 /*********************************************************************
1998 * Function : jpeg_inspect_response
2003 * 1 : csp = Current client state (buffers, headers, etc...)
2005 * Returns : a pointer to the (newly allocated) modified buffer
2006 * or NULL in case something went wrong.
2008 *********************************************************************/
2009 static char *jpeg_inspect_response(struct client_state *csp)
2011 struct binbuffer *in = NULL;
2012 struct binbuffer *out = NULL;
2016 size = (size_t)(csp->iob->eod - csp->iob->cur);
2018 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
2020 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
2024 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
2026 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
2030 in->buffer = csp->iob->cur;
2034 * Calling jpeg_inspect has the side-effect of creating and
2035 * modifying the image buffer of "out" directly.
2037 if (jpeg_inspect(in, out))
2039 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
2047 csp->content_length = out->offset;
2048 csp->flags |= CSP_FLAG_MODIFIED;
2058 /*********************************************************************
2060 * Function : get_filter_function
2062 * Description : Decides which content filter function has
2063 * to be applied (if any).
2065 * XXX: Doesn't handle filter_popups()
2066 * because of the different prototype. Probably
2067 * we should ditch filter_popups() anyway, it's
2068 * even less reliable than popup blocking based
2072 * 1 : csp = Current client state (buffers, headers, etc...)
2074 * Returns : The content filter function to run, or
2075 * NULL if no content filter is active
2077 *********************************************************************/
2078 filter_function_ptr get_filter_function(struct client_state *csp)
2080 filter_function_ptr filter_function = NULL;
2083 * Are we enabling text mode by force?
2085 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2088 * Do we really have to?
2090 if (csp->content_type & CT_TEXT)
2092 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2096 csp->content_type |= CT_TEXT;
2097 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2101 if (!(csp->content_type & CT_DECLARED))
2104 * The server didn't bother to declare a MIME-Type.
2105 * Assume it's text that can be filtered.
2107 * This also regulary happens with 304 responses,
2108 * therefore logging anything here would cause
2111 csp->content_type |= CT_TEXT;
2115 * Choose the applying filter function based on
2116 * the content type and action settings.
2118 if ((csp->content_type & CT_TEXT) &&
2119 (csp->rlist != NULL) &&
2120 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2122 filter_function = pcrs_filter_response;
2124 else if ((csp->content_type & CT_GIF) &&
2125 (csp->action->flags & ACTION_DEANIMATE))
2127 filter_function = gif_deanimate_response;
2129 else if ((csp->content_type & CT_JPEG) &&
2130 (csp->action->flags & ACTION_JPEG_INSPECT))
2132 filter_function = jpeg_inspect_response;
2135 return filter_function;
2139 /*********************************************************************
2141 * Function : remove_chunked_transfer_coding
2143 * Description : In-situ remove the "chunked" transfer coding as defined
2144 * in rfc2616 from a buffer.
2147 * 1 : buffer = Pointer to the text buffer
2148 * 2 : size = In: Number of bytes to be processed,
2149 * Out: Number of bytes after de-chunking.
2150 * (undefined in case of errors)
2152 * Returns : JB_ERR_OK for success,
2153 * JB_ERR_PARSE otherwise
2155 *********************************************************************/
2156 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2159 unsigned int chunksize = 0;
2160 char *from_p, *to_p;
2163 from_p = to_p = buffer;
2165 if (sscanf(buffer, "%x", &chunksize) != 1)
2167 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2168 return JB_ERR_PARSE;
2171 while (chunksize > 0)
2173 if (NULL == (from_p = strstr(from_p, "\r\n")))
2175 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2176 return JB_ERR_PARSE;
2179 if ((newsize += chunksize) >= *size)
2181 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
2182 return JB_ERR_PARSE;
2186 memmove(to_p, from_p, (size_t) chunksize);
2187 to_p = buffer + newsize;
2188 from_p += chunksize + 2;
2190 if (sscanf(from_p, "%x", &chunksize) != 1)
2192 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2197 /* XXX: Should get its own loglevel. */
2198 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
2207 /*********************************************************************
2209 * Function : prepare_for_filtering
2211 * Description : If necessary, de-chunks and decompresses
2212 * the content so it can get filterd.
2215 * 1 : csp = Current client state (buffers, headers, etc...)
2217 * Returns : JB_ERR_OK for success,
2218 * JB_ERR_PARSE otherwise
2220 *********************************************************************/
2221 static jb_err prepare_for_filtering(struct client_state *csp)
2223 jb_err err = JB_ERR_OK;
2226 * If the body has a "chunked" transfer-encoding,
2227 * get rid of it, adjusting size and iob->eod
2229 if (csp->flags & CSP_FLAG_CHUNKED)
2231 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2233 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2234 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2235 if (JB_ERR_OK == err)
2237 csp->iob->eod = csp->iob->cur + size;
2238 csp->flags |= CSP_FLAG_MODIFIED;
2242 return JB_ERR_PARSE;
2248 * If the body has a supported transfer-encoding,
2249 * decompress it, adjusting size and iob->eod.
2251 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
2253 if (0 == csp->iob->eod - csp->iob->cur)
2255 /* Nothing left after de-chunking. */
2259 err = decompress_iob(csp);
2261 if (JB_ERR_OK == err)
2263 csp->flags |= CSP_FLAG_MODIFIED;
2264 csp->content_type &= ~CT_TABOO;
2269 * Unset CT_GZIP and CT_DEFLATE to remember not
2270 * to modify the Content-Encoding header later.
2272 csp->content_type &= ~CT_GZIP;
2273 csp->content_type &= ~CT_DEFLATE;
2282 /*********************************************************************
2284 * Function : execute_content_filter
2286 * Description : Executes a given content filter.
2289 * 1 : csp = Current client state (buffers, headers, etc...)
2290 * 2 : content_filter = The filter function to execute
2292 * Returns : Pointer to the modified buffer, or
2293 * NULL if filtering failed or wasn't necessary.
2295 *********************************************************************/
2296 char *execute_content_filter(struct client_state *csp, filter_function_ptr content_filter)
2298 if (0 == csp->iob->eod - csp->iob->cur)
2301 * No content (probably status code 301, 302 ...),
2302 * no filtering necessary.
2307 if (JB_ERR_OK != prepare_for_filtering(csp))
2310 * failed to de-chunk or decompress.
2315 if (0 == csp->iob->eod - csp->iob->cur)
2318 * Clown alarm: chunked and/or compressed nothing delivered.
2323 return ((*content_filter)(csp));
2327 /*********************************************************************
2329 * Function : url_actions
2331 * Description : Gets the actions for this URL.
2334 * 1 : http = http_request request for blocked URLs
2335 * 2 : csp = Current client state (buffers, headers, etc...)
2339 *********************************************************************/
2340 void url_actions(struct http_request *http,
2341 struct client_state *csp)
2343 struct file_list *fl;
2344 struct url_actions *b;
2347 init_current_action(csp->action);
2349 for (i = 0; i < MAX_AF_FILES; i++)
2351 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2356 apply_url_actions(csp->action, http, b);
2363 /*********************************************************************
2365 * Function : apply_url_actions
2367 * Description : Applies a list of URL actions.
2370 * 1 : action = Destination.
2371 * 2 : http = Current URL
2372 * 3 : b = list of URL actions to apply
2376 *********************************************************************/
2377 void apply_url_actions(struct current_action_spec *action,
2378 struct http_request *http,
2379 struct url_actions *b)
2383 /* Should never happen */
2387 for (b = b->next; NULL != b; b = b->next)
2389 if (url_match(b->url, http))
2391 merge_current_action(action, b->action);
2397 /*********************************************************************
2399 * Function : get_forward_override_settings
2401 * Description : Returns forward settings as specified with the
2402 * forward-override{} action. forward-override accepts
2403 * forward lines similar to the one used in the
2404 * configuration file, but without the URL pattern.
2410 * in the configuration file can be replaced with
2411 * the action section:
2413 * {+forward-override{forward .}}
2417 * 1 : csp = Current client state (buffers, headers, etc...)
2419 * Returns : Pointer to forwarding structure in case of success.
2420 * Invalid syntax is fatal.
2422 *********************************************************************/
2423 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2425 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2426 char forward_settings[BUFFER_SIZE];
2427 char *http_parent = NULL;
2428 /* variable names were chosen for consistency reasons. */
2429 struct forward_spec *fwd = NULL;
2433 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2434 /* Should be enforced by load_one_actions_file() */
2435 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2437 /* Create a copy ssplit can modify */
2438 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2440 if (NULL != csp->fwd)
2443 * XXX: Currently necessary to prevent memory
2444 * leaks when the show-url-info cgi page is visited.
2446 unload_forward_spec(csp->fwd);
2450 * allocate a new forward node, valid only for
2451 * the lifetime of this request. Save its location
2452 * in csp as well, so sweep() can free it later on.
2454 fwd = csp->fwd = zalloc(sizeof(*fwd));
2457 log_error(LOG_LEVEL_FATAL,
2458 "can't allocate memory for forward-override{%s}", forward_override_line);
2459 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2462 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2463 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2465 fwd->type = SOCKS_NONE;
2467 /* Parse the parent HTTP proxy host:port */
2468 http_parent = vec[1];
2471 else if (vec_count == 3)
2473 char *socks_proxy = NULL;
2475 if (!strcasecmp(vec[0], "forward-socks4"))
2477 fwd->type = SOCKS_4;
2478 socks_proxy = vec[1];
2480 else if (!strcasecmp(vec[0], "forward-socks4a"))
2482 fwd->type = SOCKS_4A;
2483 socks_proxy = vec[1];
2486 if (NULL != socks_proxy)
2488 /* Parse the SOCKS proxy host[:port] */
2489 fwd->gateway_host = strdup(socks_proxy);
2491 if (NULL != (socks_proxy = strchr(fwd->gateway_host, ':')))
2493 *socks_proxy++ = '\0';
2494 fwd->gateway_port = strtol(socks_proxy, NULL, 0);
2497 if (fwd->gateway_port <= 0)
2499 fwd->gateway_port = 1080;
2502 http_parent = vec[2];
2506 if (NULL == http_parent)
2508 log_error(LOG_LEVEL_FATAL,
2509 "Invalid forward-override syntax in: %s", forward_override_line);
2510 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2513 /* Parse http forwarding settings */
2514 if (strcmp(http_parent, ".") != 0)
2516 fwd->forward_host = strdup(http_parent);
2518 if (NULL != (http_parent = strchr(fwd->forward_host, ':')))
2520 *http_parent++ = '\0';
2521 fwd->forward_port = strtol(http_parent, NULL, 0);
2524 if (fwd->forward_port <= 0)
2526 fwd->forward_port = 8000;
2530 assert (NULL != fwd);
2532 log_error(LOG_LEVEL_CONNECT,
2533 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2539 /*********************************************************************
2541 * Function : forward_url
2543 * Description : Should we forward this to another proxy?
2545 * XXX: Should be changed to make use of csp->fwd.
2548 * 1 : http = http_request request for current URL
2549 * 2 : csp = Current client state (buffers, headers, etc...)
2551 * Returns : Pointer to forwarding information.
2553 *********************************************************************/
2554 const struct forward_spec * forward_url(struct http_request *http,
2555 struct client_state *csp)
2557 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2558 struct forward_spec *fwd = csp->config->forward;
2560 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2562 return get_forward_override_settings(csp);
2572 if (url_match(fwd->url, http))
2583 /*********************************************************************
2585 * Function : direct_response
2587 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2588 * request and if so, return a HTTP 501 to the client.
2590 * FIXME: I have a stupid name and I should handle the
2591 * requests properly. Still, what we do here is rfc-
2592 * compliant, whereas ignoring or forwarding are not.
2595 * 1 : csp = Current client state (buffers, headers, etc...)
2597 * Returns : http_response if , NULL if nonmatch or handler fail
2599 *********************************************************************/
2600 struct http_response *direct_response(struct client_state *csp)
2602 struct http_response *rsp;
2603 struct list_entry *p;
2605 if ((0 == strcmpic(csp->http->gpc, "trace"))
2606 || (0 == strcmpic(csp->http->gpc, "options")))
2608 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2610 if (!strncmpic("Max-Forwards:", p->str, 13))
2612 unsigned int max_forwards;
2615 * If it's a Max-Forwards value of zero,
2616 * we have to intercept the request.
2618 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2621 * FIXME: We could handle at least TRACE here,
2622 * but that would require a verbatim copy of
2623 * the request which we don't have anymore
2625 log_error(LOG_LEVEL_HEADER,
2626 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2629 /* Get mem for response or fail*/
2630 if (NULL == (rsp = alloc_http_response()))
2632 return cgi_error_memory();
2635 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2637 free_http_response(rsp);
2638 return cgi_error_memory();
2642 rsp->reason = RSP_REASON_UNSUPPORTED;
2644 return(finish_http_response(csp, rsp));
2653 /*********************************************************************
2655 * Function : content_filters_enabled
2657 * Description : Checks whether there are any content filters
2658 * enabled for the current request.
2661 * 1 : csp = Current client state (buffers, headers, etc...)
2663 * Returns : TRUE for yes, FALSE otherwise
2665 *********************************************************************/
2666 inline int content_filters_enabled(const struct client_state *csp)
2668 return (((csp->rlist != NULL) &&
2669 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]))) ||
2670 (csp->action->flags & (ACTION_DEANIMATE|ACTION_JPEG_INSPECT|ACTION_NO_POPUPS)));