1 const char filters_rcs[] = "$Id: filters.c,v 1.93 2007/09/29 10:21:16 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.93 2007/09/29 10:21:16 fabiankeil
44 * - Move get_filter_function() from jcc.c to filters.c
45 * so the filter functions can be static.
46 * - Don't bother filtering body-less responses.
48 * Revision 1.92 2007/09/28 16:38:55 fabiankeil
49 * - Execute content filters through execute_content_filter().
50 * - Add prepare_for_filtering() so filter functions don't have to
51 * care about de-chunking and decompression. As a side effect this enables
52 * decompression for gif_deanimate_response() and jpeg_inspect_response().
53 * - Change remove_chunked_transfer_coding()'s return type to jb_err.
54 * Some clowns feel like chunking empty responses in which case
55 * (size == 0) is valid but previously would be interpreted as error.
57 * Revision 1.91 2007/09/02 15:31:20 fabiankeil
58 * Move match_portlist() from filter.c to urlmatch.c.
59 * It's used for url matching, not for filtering.
61 * Revision 1.90 2007/09/02 12:44:17 fabiankeil
62 * Remove newline at the end of a log_error() message.
64 * Revision 1.89 2007/08/05 13:42:23 fabiankeil
65 * #1763173 from Stefan Huehner: declare some more functions static.
67 * Revision 1.88 2007/06/01 16:41:11 fabiankeil
68 * Add forward-override{} to change the forwarding settings through
69 * action sections. This is mainly interesting to forward different
70 * clients differently (for example based on User-Agent or request
73 * Revision 1.87 2007/04/30 15:53:10 fabiankeil
74 * Make sure filters with dynamic jobs actually use them.
76 * Revision 1.86 2007/04/30 15:03:28 fabiankeil
77 * - Introduce dynamic pcrs jobs that can resolve variables.
78 * - Don't run redirect functions more than once,
79 * unless they are activated more than once.
81 * Revision 1.85 2007/03/21 12:24:47 fabiankeil
82 * - Log the content size after decompression in decompress_iob()
83 * instead of pcrs_filter_response().
85 * Revision 1.84 2007/03/20 15:16:34 fabiankeil
86 * Use dedicated header filter actions instead of abusing "filter".
87 * Replace "filter-client-headers" and "filter-client-headers"
88 * with "server-header-filter" and "client-header-filter".
90 * Revision 1.83 2007/03/17 15:20:05 fabiankeil
91 * New config option: enforce-blocks.
93 * Revision 1.82 2007/03/13 11:28:43 fabiankeil
94 * - Fix port handling in acl_addr() and use a temporary acl spec
95 * copy so error messages don't contain a truncated version.
96 * - Log size of iob before and after decompression.
98 * Revision 1.81 2007/03/05 14:40:53 fabiankeil
99 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
100 * - Hide the "Go there anyway" link for blocked CONNECT
101 * requests where going there anyway doesn't work anyway.
103 * Revision 1.80 2007/02/07 10:55:20 fabiankeil
104 * - Save the reason for generating http_responses.
105 * - Block (+block) with status code 403 instead of 404.
106 * - Use a different kludge to remember a failed decompression.
108 * Revision 1.79 2007/01/31 16:21:38 fabiankeil
109 * Search for Max-Forwards headers case-insensitive,
110 * don't generate the "501 unsupported" message for invalid
111 * Max-Forwards values and don't increase negative ones.
113 * Revision 1.78 2007/01/28 13:41:18 fabiankeil
114 * - Add HEAD support to finish_http_response.
115 * - Add error favicon to internal HTML error messages.
117 * Revision 1.77 2007/01/12 15:36:44 fabiankeil
118 * Mark *csp as immutable for is_untrusted_url()
119 * and is_imageurl(). Closes FR 1237736.
121 * Revision 1.76 2007/01/01 19:36:37 fabiankeil
122 * Integrate a modified version of Wil Mahan's
123 * zlib patch (PR #895531).
125 * Revision 1.75 2006/12/29 18:30:46 fabiankeil
126 * Fixed gcc43 conversion warnings,
127 * changed sprintf calls to snprintf.
129 * Revision 1.74 2006/12/24 17:37:38 fabiankeil
130 * Adjust comment in pcrs_filter_response()
131 * to recent pcrs changes. Hohoho.
133 * Revision 1.73 2006/12/23 16:01:02 fabiankeil
134 * Don't crash if pcre returns an error code
135 * that pcrs didn't expect. Fixes BR 1621173.
137 * Revision 1.72 2006/12/22 18:52:53 fabiankeil
138 * Modified is_untrusted_url to complain in case of
139 * write errors and to give a reason when adding new
140 * entries to the trustfile. Closes FR 1097611.
142 * Revision 1.71 2006/12/22 14:24:52 fabiankeil
143 * Skip empty filter files in pcrs_filter_response,
144 * but don't ignore the ones that come afterwards.
145 * Fixes parts of BR 1619208.
147 * Revision 1.70 2006/12/09 13:33:15 fabiankeil
148 * Added some sanity checks for get_last_url().
149 * Fixed possible segfault caused by my last commit.
151 * Revision 1.69 2006/12/08 12:39:13 fabiankeil
152 * Let get_last_url() catch https URLs as well.
154 * Revision 1.68 2006/12/05 14:45:48 fabiankeil
155 * Make sure get_last_url() behaves like advertised
156 * and fast-redirects{} can be combined with redirect{}.
158 * Revision 1.67 2006/11/28 15:19:43 fabiankeil
159 * Implemented +redirect{s@foo@bar@} to generate
160 * a redirect based on a rewritten version of the
163 * Revision 1.66 2006/09/23 13:26:38 roro
164 * Replace TABs by spaces in source code.
166 * Revision 1.65 2006/09/21 12:54:43 fabiankeil
167 * Fix +redirect{}. Didn't work with -fast-redirects.
169 * Revision 1.64 2006/08/31 10:55:49 fabiankeil
170 * Block requests for untrusted URLs with status
171 * code 403 instead of 200.
173 * Revision 1.63 2006/08/31 10:11:28 fabiankeil
174 * Don't free p which is still in use and will be later
175 * freed by free_map(). Don't claim the referrer is unknown
176 * when the client didn't set one.
178 * Revision 1.62 2006/08/14 00:27:47 david__schmidt
179 * Feature request 595948: Re-Filter logging in single line
181 * Revision 1.61 2006/08/03 02:46:41 david__schmidt
182 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
184 * Revision 1.60 2006/07/18 14:48:46 david__schmidt
185 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
186 * with what was really the latest development (the v_3_0_branch branch)
188 * Revision 1.58.2.9 2006/01/29 23:10:56 david__schmidt
189 * Multiple filter file support
191 * Revision 1.58.2.8 2005/05/07 21:50:55 david__schmidt
192 * A few memory leaks plugged (mostly on error paths)
194 * Revision 1.58.2.7 2004/10/03 12:53:32 david__schmidt
195 * Add the ability to check jpeg images for invalid
196 * lengths of comment blocks. Defensive strategy
197 * against the exploit:
198 * Microsoft Security Bulletin MS04-028
199 * Buffer Overrun in JPEG Processing (GDI+) Could
200 * Allow Code Execution (833987)
201 * Enabled with +inspect-jpegs in actions files.
203 * Revision 1.58.2.6 2003/12/06 22:18:27 gliptak
204 * Correcting compile problem with FEATURE_IMAGE_BLOCKING
206 * Revision 1.58.2.5 2003/11/11 13:10:31 oes
207 * Fixed bug #839859: "See why" link URL now gets url-encoded.
209 * Revision 1.58.2.4 2003/02/28 12:52:45 oes
212 * Revision 1.58.2.3 2002/09/25 14:51:51 oes
213 * Added basic support for OPTIONS and TRACE HTTP methods:
214 * New function direct_response which handles OPTIONS and
215 * TRACE requests whose Max-Forwards header field is zero.
217 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
218 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
220 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
221 * - Bugfix: Executing a filters without jobs no longer results in
222 * turing off *all* filters.
223 * - Security fix: Malicious web servers can't cause a seg fault
224 * through bogus chunk sizes anymore
226 * Revision 1.58 2002/04/24 02:11:17 oes
227 * Jon's multiple AF patch: url_actions now evaluates rules
230 * Revision 1.57 2002/04/08 20:38:34 swa
233 * Revision 1.56 2002/04/05 15:51:24 oes
234 * - bugfix: error-pages now get correct request protocol
235 * - fix for invalid HTML in trust info
237 * Revision 1.55 2002/04/02 16:13:51 oes
238 * Fix: No "Go there anyway" for SSL
240 * Revision 1.54 2002/04/02 14:55:56 oes
241 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
243 * Revision 1.53 2002/03/26 22:29:54 swa
244 * we have a new homepage!
246 * Revision 1.52 2002/03/24 16:35:57 jongfoster
249 * Revision 1.51 2002/03/24 15:23:33 jongfoster
252 * Revision 1.50 2002/03/24 13:25:43 swa
253 * name change related issues
255 * Revision 1.49 2002/03/16 20:29:14 oes
258 * Revision 1.48 2002/03/13 20:25:34 oes
259 * Better logging for content filters
261 * Revision 1.47 2002/03/13 00:30:52 jongfoster
263 * Added option of always sending redirect for imageblock,
264 * currently disabled with #if 0.
266 * Revision 1.46 2002/03/12 01:42:49 oes
267 * Introduced modular filters
269 * Revision 1.45 2002/03/08 16:47:50 oes
270 * Added choice beween GIF and PNG built-in images
272 * Revision 1.44 2002/03/07 03:49:31 oes
273 * - Fixed compiler warnings etc
274 * - Changed built-in images from GIF to PNG
275 * (with regard to Unisys patent issue)
276 * - Added a 4x4 pattern PNG which is less intrusive
277 * than the logo but also clearly marks the deleted banners
279 * Revision 1.43 2002/01/22 23:51:59 jongfoster
280 * Replacing strsav() with the safer string_append().
282 * Adding missing html_encode() to error message generators. Where encoded
283 * and unencoded versions of a string were provided, removing the unencoded
286 * Revision 1.42 2002/01/17 21:00:32 jongfoster
287 * Moving all our URL and URL pattern parsing code to urlmatch.c.
289 * Using a single, simple url_match(pattern,url) function - rather than
290 * the 3-line match routine which was repeated all over the place.
292 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
294 * Using parse_http_url() to parse URLs without faking a HTTP
295 * request line for parse_http_request().
297 * Revision 1.41 2001/11/13 00:14:07 jongfoster
298 * Fixing stupid bug now I've figured out what || means.
299 * (It always returns 0 or 1, not one of it's paramaters.)
301 * Revision 1.40 2001/10/26 17:37:55 oes
302 * - Re-enabled Netscape 200/404 bug workaround in block_url():
303 * - Removed OS/2 special case
304 * - Made block_url() independant from sed() having been run
305 * - Made trust_url independant from sed() having been run
306 * - Made is_imageurl independant from sed() having been run.
307 * It now checks User-Agent: and Accept: by itself.
310 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
311 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
312 * threads to call select() simultaneously. So, it's time to do a real, live,
313 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
314 * (native). Both versions will work, but using __OS2__ offers multi-threading.
316 * Revision 1.38 2001/10/23 21:32:33 jongfoster
317 * Adding error-checking to selected functions
319 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
320 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
321 * filters.c. Added a FIXME in front of the offending code. I'll gladly
322 * put in a better/more robust fix for all parties if one is presented...
323 * It seems that just returning 200 instead of 404 would pretty much fix
324 * it for everyone, but I don't know all the history of the problem.
326 * Revision 1.36 2001/10/10 16:44:16 oes
327 * Added match_portlist function
329 * Revision 1.35 2001/10/07 15:41:23 oes
330 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
332 * New function remove_chunked_transfer_coding that strips chunked
333 * transfer coding to plain and is called by pcrs_filter_response
334 * and gif_deanimate_response if neccessary
336 * Improved handling of zero-change re_filter runs
338 * pcrs_filter_response and gif_deanimate_response now remove
339 * chunked transfer codeing before processing the body.
341 * Revision 1.34 2001/09/20 15:49:36 steudten
343 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
344 * See cgi.c fill_template().
346 * Revision 1.33 2001/09/16 17:05:14 jongfoster
347 * Removing unused #include showarg.h
349 * Revision 1.32 2001/09/16 13:21:27 jongfoster
350 * Changes to use new list functions.
352 * Revision 1.31 2001/09/16 11:38:02 jongfoster
353 * Splitting fill_template() into 2 functions:
354 * template_load() loads the file
355 * template_fill() performs the PCRS regexps.
356 * This is because the CGI edit interface has a "table row"
357 * template which is used many times in the page - this
358 * change means it's only loaded from disk once.
360 * Revision 1.30 2001/09/16 11:00:10 jongfoster
361 * New function alloc_http_response, for symmetry with free_http_response
363 * Revision 1.29 2001/09/13 23:32:40 jongfoster
364 * Moving image data to cgi.c rather than cgi.h
365 * Fixing a GPF under Win32 (and any other OS that protects global
366 * constants from being written to).
368 * Revision 1.28 2001/09/10 10:18:51 oes
369 * Silenced compiler warnings
371 * Revision 1.27 2001/08/05 16:06:20 jongfoster
372 * Modifiying "struct map" so that there are now separate header and
373 * "map_entry" structures. This means that functions which modify a
374 * map no longer need to return a pointer to the modified map.
375 * Also, it no longer reverses the order of the entries (which may be
376 * important with some advanced template substitutions).
378 * Revision 1.26 2001/07/30 22:08:36 jongfoster
379 * Tidying up #defines:
380 * - All feature #defines are now of the form FEATURE_xxx
381 * - Permanently turned off WIN_GUI_EDIT
382 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
384 * Revision 1.25 2001/07/26 10:09:46 oes
385 * Made browser detection a little less naive
387 * Revision 1.24 2001/07/25 17:22:51 oes
388 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
390 * Revision 1.23 2001/07/23 13:40:12 oes
391 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
393 * Revision 1.22 2001/07/18 12:29:34 oes
394 * - Made gif_deanimate_response respect
395 * csp->action->string[ACTION_STRING_DEANIMATE]
396 * - Logging cosmetics
398 * Revision 1.21 2001/07/13 13:59:53 oes
399 * - Introduced gif_deanimate_response which shares the
400 * generic content modification interface of pcrs_filter_response
401 * and acts as a wrapper to deanimate.c:gif_deanimate()
402 * - Renamed re_process_buffer to pcrs_filter_response
403 * - pcrs_filter_response now returns NULL on failiure
404 * - Removed all #ifdef PCRS
406 * Revision 1.20 2001/07/01 17:01:04 oes
407 * Added comments and missing return statement in is_untrusted_url()
409 * Revision 1.19 2001/06/29 21:45:41 oes
410 * Indentation, CRLF->LF, Tab-> Space
412 * Revision 1.18 2001/06/29 13:27:38 oes
413 * - Cleaned up, renamed and reorderd functions
414 * and improved comments
417 * - Ported to CGI platform. Now delivers
418 * http_response or NULL
419 * - Unified HTML and GIF generation (moved image detection
420 * and GIF generation here from jcc.c:chat())
421 * - Fixed HTTP status to:
422 * - 403 (Forbidden) for the "blocked" HTML message
423 * - 200 (OK) for GIF answers
424 * - 302 (Redirect) for redirect to GIF
427 * - Ported to CGI platform. Now delivers
428 * http_response or NULL
429 * - Separated detection of untrusted URL into
430 * (bool)is_untrusted_url
431 * - Added enforcement of untrusted requests
433 * - Moved redirect_url() from cgi.c to here
434 * and ported it to the CGI platform
436 * - Removed logentry from cancelled commit
438 * Revision 1.17 2001/06/09 10:55:28 jongfoster
439 * Changing BUFSIZ ==> BUFFER_SIZE
441 * Revision 1.16 2001/06/07 23:10:26 jongfoster
442 * Allowing unanchored domain patterns to back off and retry
443 * if they partially match. Optimized right-anchored patterns.
444 * Moving ACL and forward files into config file.
445 * Replacing struct gateway with struct forward_spec
447 * Revision 1.15 2001/06/03 19:12:00 oes
448 * extracted-CGI relevant stuff
450 * Revision 1.14 2001/06/01 10:30:55 oes
451 * Added optional left-anchoring to domaincmp
453 * Revision 1.13 2001/05/31 21:21:30 jongfoster
454 * Permissionsfile / actions file changes:
455 * - Changed "permission" to "action" throughout
456 * - changes to file format to allow string parameters
457 * - Moved helper functions to actions.c
459 * Revision 1.12 2001/05/31 17:35:20 oes
461 * - Enhanced domain part globbing with infix and prefix asterisk
462 * matching and optional unanchored operation
464 * Revision 1.11 2001/05/29 11:53:23 oes
465 * "See why" link added to "blocked" page
467 * Revision 1.10 2001/05/29 09:50:24 jongfoster
468 * Unified blocklist/imagelist/permissionslist.
469 * File format is still under discussion, but the internal changes
472 * Also modified interceptor behaviour:
473 * - We now intercept all URLs beginning with one of the following
474 * prefixes (and *only* these prefixes):
476 * * http://ijbswa.sf.net/config/
477 * * http://ijbswa.sourceforge.net/config/
478 * - New interceptors "home page" - go to http://i.j.b/ to see it.
479 * - Internal changes so that intercepted and fast redirect pages
480 * are not replaced with an image.
481 * - Interceptors now have the option to send a binary page direct
482 * to the client. (i.e. ijb-send-banner uses this)
483 * - Implemented show-url-info interceptor. (Which is why I needed
484 * the above interceptors changes - a typical URL is
485 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
486 * The previous mechanism would not have intercepted that, and
487 * if it had been intercepted then it then it would have replaced
490 * Revision 1.9 2001/05/27 22:17:04 oes
492 * - re_process_buffer no longer writes the modified buffer
493 * to the client, which was very ugly. It now returns the
494 * buffer, which it is then written by chat.
496 * - content_length now adjusts the Content-Length: header
497 * for modified documents rather than crunch()ing it.
498 * (Length info in csp->content_length, which is 0 for
499 * unmodified documents)
501 * - For this to work, sed() is called twice when filtering.
503 * Revision 1.8 2001/05/26 17:13:28 jongfoster
504 * Filled in a function comment.
506 * Revision 1.7 2001/05/26 15:26:15 jongfoster
507 * ACL feature now provides more security by immediately dropping
508 * connections from untrusted hosts.
510 * Revision 1.6 2001/05/26 00:28:36 jongfoster
511 * Automatic reloading of config file.
512 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
513 * Most of the global variables have been moved to a new
514 * struct configuration_spec, accessed through csp->config->globalname
515 * Most of the globals remaining are used by the Win32 GUI.
517 * Revision 1.5 2001/05/25 22:34:30 jongfoster
520 * Revision 1.4 2001/05/22 18:46:04 oes
522 * - Enabled filtering banners by size rather than URL
523 * by adding patterns that replace all standard banner
524 * sizes with the "Junkbuster" gif to the re_filterfile
526 * - Enabled filtering WebBugs by providing a pattern
527 * which kills all 1x1 images
529 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
530 * which is selected by the (nonstandard and therefore
531 * capital) letter 'U' in the option string.
532 * It causes the quantifiers to be ungreedy by default.
533 * Appending a ? turns back to greedy (!).
535 * - Added a new interceptor ijb-send-banner, which
536 * sends back the "Junkbuster" gif. Without imagelist or
537 * MSIE detection support, or if tinygif = 1, or the
538 * URL isn't recognized as an imageurl, a lame HTML
539 * explanation is sent instead.
541 * - Added new feature, which permits blocking remote
542 * script redirects and firing back a local redirect
544 * The feature is conditionally compiled, i.e. it
545 * can be disabled with --disable-fast-redirects,
546 * plus it must be activated by a "fast-redirects"
547 * line in the config file, has its own log level
548 * and of course wants to be displayed by show-proxy-args
549 * Note: Boy, all the #ifdefs in 1001 locations and
550 * all the fumbling with configure.in and acconfig.h
551 * were *way* more work than the feature itself :-(
553 * - Because a generic redirect template was needed for
554 * this, tinygif = 3 now uses the same.
556 * - Moved GIFs, and other static HTTP response templates
561 * - Removed some >400 CRs again (Jon, you really worked
564 * Revision 1.3 2001/05/20 16:44:47 jongfoster
565 * Removing last hardcoded Junkbusters.com URLs.
567 * Revision 1.2 2001/05/20 01:21:20 jongfoster
568 * Version 2.9.4 checkin.
569 * - Merged popupfile and cookiefile, and added control over PCRS
570 * filtering, in new "permissionsfile".
571 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
572 * file error you now get a message box (in the Win32 GUI) rather
573 * than the program exiting with no explanation.
574 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
576 * - Removed tabs from "config"
577 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
578 * - Bumped up version number.
580 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
581 * Initial import of version 2.9.3 source tree
584 *********************************************************************/
590 #include <sys/types.h>
599 #endif /* ndef __OS2__ */
600 #include <netinet/in.h>
602 #include <winsock2.h>
603 #endif /* ndef _WIN32 */
607 #endif /* def __OS2__ */
615 #include "jbsockets.h"
616 #include "miscutil.h"
620 #include "deanimate.h"
621 #include "urlmatch.h"
628 const char filters_h_rcs[] = FILTERS_H_VERSION;
630 /* Fix a problem with Solaris. There should be no effect on other
632 * Solaris's isspace() is a macro which uses it's argument directly
633 * as an array index. Therefore we need to make sure that high-bit
634 * characters generate +ve values, and ideally we also want to make
635 * the argument match the declared parameter type of "int".
637 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
639 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
640 static jb_err prepare_for_filtering(struct client_state *csp);
643 /*********************************************************************
645 * Function : block_acl
647 * Description : Block this request?
648 * Decide yes or no based on ACL file.
651 * 1 : dst = The proxy or gateway address this is going to.
652 * Or NULL to check all possible targets.
653 * 2 : csp = Current client state (buffers, headers, etc...)
654 * Also includes the client IP address.
656 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
658 *********************************************************************/
659 int block_acl(struct access_control_addr *dst, struct client_state *csp)
661 struct access_control_list *acl = csp->config->acl;
663 /* if not using an access control list, then permit the connection */
669 /* search the list */
672 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
676 /* Just want to check if they have any access */
677 if (acl->action == ACL_PERMIT)
682 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
683 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
685 if (acl->action == ACL_PERMIT)
703 /*********************************************************************
705 * Function : acl_addr
707 * Description : Called from `load_config' to parse an ACL address.
710 * 1 : aspec = String specifying ACL address.
711 * 2 : aca = struct access_control_addr to fill in.
713 * Returns : 0 => Ok, everything else is an error.
715 *********************************************************************/
716 int acl_addr(const char *aspec, struct access_control_addr *aca)
721 char *acl_spec = NULL;
727 * Use a temporary acl spec copy so we can log
728 * the unmodified original in case of parse errors.
730 acl_spec = strdup(aspec);
731 if (acl_spec == NULL)
733 /* XXX: This will be logged as parse error. */
737 if ((p = strchr(acl_spec, '/')) != NULL)
740 if (ijb_isdigit(*p) == 0)
745 masklength = atoi(p);
748 if ((masklength < 0) || (masklength > 32))
754 if ((p = strchr(acl_spec, ':')) != NULL)
759 port = strtol(p, &endptr, 10);
761 if (port <= 0 || port > 65535 || *endptr != '\0')
768 aca->port = (unsigned long)port;
770 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
773 if (aca->addr == INADDR_NONE)
775 /* XXX: This will be logged as parse error. */
779 /* build the netmask */
781 for (i=1; i <= masklength ; i++)
783 aca->mask |= (1 << (32 - i));
786 /* now mask off the host portion of the ip address
787 * (i.e. save on the network portion of the address).
789 aca->addr = aca->addr & aca->mask;
794 #endif /* def FEATURE_ACL */
797 /*********************************************************************
799 * Function : block_url
801 * Description : Called from `chat'. Check to see if we need to block this.
804 * 1 : csp = Current client state (buffers, headers, etc...)
806 * Returns : NULL => unblocked, else HTTP block response
808 *********************************************************************/
809 struct http_response *block_url(struct client_state *csp)
811 struct http_response *rsp;
812 const char *new_content_type = NULL;
815 * If it's not blocked, don't block it ;-)
817 if ((csp->action->flags & ACTION_BLOCK) == 0)
821 if (csp->action->flags & ACTION_REDIRECT)
823 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
826 * Else, prepare a response
828 if (NULL == (rsp = alloc_http_response()))
830 return cgi_error_memory();
834 * If it's an image-url, send back an image or redirect
835 * as specified by the relevant +image action
837 #ifdef FEATURE_IMAGE_BLOCKING
838 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
842 /* determine HOW images should be blocked */
843 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
845 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
847 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
849 #if 1 /* Two alternative strategies, use this one for now: */
851 /* and handle accordingly: */
852 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
854 rsp->status = strdup("403 Request blocked by Privoxy");
855 if (rsp->status == NULL)
857 free_http_response(rsp);
858 return cgi_error_memory();
860 rsp->body = bindup(image_pattern_data, image_pattern_length);
861 if (rsp->body == NULL)
863 free_http_response(rsp);
864 return cgi_error_memory();
866 rsp->content_length = image_pattern_length;
868 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
870 free_http_response(rsp);
871 return cgi_error_memory();
875 else if (0 == strcmpic(p, "blank"))
877 rsp->status = strdup("403 Request blocked by Privoxy");
878 if (rsp->status == NULL)
880 free_http_response(rsp);
881 return cgi_error_memory();
883 rsp->body = bindup(image_blank_data, image_blank_length);
884 if (rsp->body == NULL)
886 free_http_response(rsp);
887 return cgi_error_memory();
889 rsp->content_length = image_blank_length;
891 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
893 free_http_response(rsp);
894 return cgi_error_memory();
900 rsp->status = strdup("302 Local Redirect from Privoxy");
901 if (rsp->status == NULL)
903 free_http_response(rsp);
904 return cgi_error_memory();
907 if (enlist_unique_header(rsp->headers, "Location", p))
909 free_http_response(rsp);
910 return cgi_error_memory();
914 #else /* Following code is disabled for now */
916 /* and handle accordingly: */
917 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
919 p = CGI_PREFIX "send-banner?type=pattern";
921 else if (0 == strcmpic(p, "blank"))
923 p = CGI_PREFIX "send-banner?type=blank";
925 rsp->status = strdup("302 Local Redirect from Privoxy");
926 if (rsp->status == NULL)
928 free_http_response(rsp);
929 return cgi_error_memory();
932 if (enlist_unique_header(rsp->headers, "Location", p))
934 free_http_response(rsp);
935 return cgi_error_memory();
937 #endif /* Preceeding code is disabled for now */
939 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
942 * Send empty document.
944 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
947 rsp->body = strdup(" ");
948 rsp->content_length = 1;
950 rsp->status = strdup("403 Request blocked by Privoxy");
951 if (rsp->status == NULL)
953 free_http_response(rsp);
954 return cgi_error_memory();
956 if (new_content_type != 0)
958 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
959 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
961 free_http_response(rsp);
962 return cgi_error_memory();
967 #endif /* def FEATURE_IMAGE_BLOCKING */
970 * Else, generate an HTML "blocked" message:
974 struct map * exports;
978 * Workaround for stupid Netscape bug which prevents
979 * pages from being displayed if loading a referenced
980 * JavaScript or style sheet fails. So make it appear
981 * as if it succeeded.
983 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
984 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
985 && !strstr(p, "Gecko") /* save Mozilla, */
986 && !strstr(p, "compatible") /* MSIE */
987 && !strstr(p, "Opera")) /* and Opera. */
989 rsp->status = strdup("200 Request for blocked URL");
993 rsp->status = strdup("403 Request for blocked URL");
996 if (rsp->status == NULL)
998 free_http_response(rsp);
999 return cgi_error_memory();
1002 exports = default_exports(csp, NULL);
1003 if (exports == NULL)
1005 free_http_response(rsp);
1006 return cgi_error_memory();
1009 #ifdef FEATURE_FORCE_LOAD
1010 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1012 * Export the force conditional block killer if
1014 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1015 * - Privoxy is configured to enforce blocks, or
1016 * - it's a CONNECT request and enforcing wouldn't work anyway.
1018 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1019 || (0 == strcmpic(csp->http->gpc, "connect")))
1020 #endif /* ndef FEATURE_FORCE_LOAD */
1022 err = map_block_killer(exports, "force-support");
1025 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1026 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1027 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1028 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
1033 free_http_response(rsp);
1034 return cgi_error_memory();
1037 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
1040 free_http_response(rsp);
1041 return cgi_error_memory();
1044 rsp->reason = RSP_REASON_BLOCKED;
1046 return finish_http_response(csp, rsp);
1051 #ifdef FEATURE_TRUST
1052 /*********************************************************************
1054 * Function : trust_url FIXME: I should be called distrust_url
1056 * Description : Calls is_untrusted_url to determine if the URL is trusted
1057 * and if not, returns a HTTP 403 response with a reject message.
1060 * 1 : csp = Current client state (buffers, headers, etc...)
1062 * Returns : NULL => trusted, else http_response.
1064 *********************************************************************/
1065 struct http_response *trust_url(struct client_state *csp)
1067 struct http_response *rsp;
1068 struct map * exports;
1069 char buf[BUFFER_SIZE];
1071 struct url_spec **tl;
1076 * Don't bother to work on trusted URLs
1078 if (!is_untrusted_url(csp))
1084 * Else, prepare a response:
1086 if (NULL == (rsp = alloc_http_response()))
1088 return cgi_error_memory();
1091 rsp->status = strdup("403 Request blocked by Privoxy");
1092 exports = default_exports(csp, NULL);
1093 if (exports == NULL || rsp->status == NULL)
1095 free_http_response(rsp);
1096 return cgi_error_memory();
1100 * Export the protocol, host, port, and referrer information
1102 err = map(exports, "hostport", 1, csp->http->hostport, 1);
1103 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1104 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1106 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1108 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1112 if (!err) err = map(exports, "referrer", 1, "none set", 1);
1118 free_http_response(rsp);
1119 return cgi_error_memory();
1123 * Export the trust list
1126 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1128 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
1129 string_append(&p, buf);
1131 err = map(exports, "trusted-referrers", 1, p, 0);
1136 free_http_response(rsp);
1137 return cgi_error_memory();
1141 * Export the trust info, if available
1143 if (csp->config->trust_info->first)
1145 struct list_entry *l;
1148 for (l = csp->config->trust_info->first; l ; l = l->next)
1150 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
1151 string_append(&p, buf);
1153 err = map(exports, "trust-info", 1, p, 0);
1157 err = map_block_killer(exports, "have-trust-info");
1163 free_http_response(rsp);
1164 return cgi_error_memory();
1168 * Export the force conditional block killer if
1170 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1171 * - Privoxy is configured to enforce blocks, or
1172 * - it's a CONNECT request and enforcing wouldn't work anyway.
1174 #ifdef FEATURE_FORCE_LOAD
1175 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1176 || (0 == strcmpic(csp->http->gpc, "connect")))
1178 err = map_block_killer(exports, "force-support");
1182 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1184 #else /* ifndef FEATURE_FORCE_LOAD */
1185 err = map_block_killer(exports, "force-support");
1186 #endif /* ndef FEATURE_FORCE_LOAD */
1191 free_http_response(rsp);
1192 return cgi_error_memory();
1196 * Build the response
1198 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1201 free_http_response(rsp);
1202 return cgi_error_memory();
1204 rsp->reason = RSP_REASON_UNTRUSTED;
1206 return finish_http_response(csp, rsp);
1208 #endif /* def FEATURE_TRUST */
1211 /*********************************************************************
1213 * Function : compile_dynamic_pcrs_job_list
1215 * Description : Compiles a dynamic pcrs job list (one with variables
1216 * resolved at request time)
1219 * 1 : csp = Current client state (buffers, headers, etc...)
1220 * 2 : b = The filter list to compile
1222 * Returns : NULL in case of errors, otherwise the
1225 *********************************************************************/
1226 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
1228 struct list_entry *pattern;
1229 pcrs_job *job_list = NULL;
1230 pcrs_job *dummy = NULL;
1231 pcrs_job *lastjob = NULL;
1234 const struct pcrs_variable variables[] =
1236 {"url", csp->http->url, 1},
1237 {"path", csp->http->path, 1},
1238 {"host", csp->http->host, 1},
1239 {"origin", csp->ip_addr_str, 1},
1243 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
1245 assert(pattern->str != NULL);
1247 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
1251 log_error(LOG_LEVEL_ERROR,
1252 "Adding filter job \'%s\' to dynamic filter %s failed: %s",
1253 pattern->str, b->name, pcrs_strerror(error));
1258 if (error == PCRS_WARN_TRUNCATION)
1260 log_error(LOG_LEVEL_ERROR,
1261 "At least one of the variables in \'%s\' had to "
1262 "be truncated before compilation", pattern->str);
1264 if (job_list == NULL)
1270 lastjob->next = dummy;
1280 /*********************************************************************
1282 * Function : rewrite_url
1284 * Description : Rewrites a URL with a single pcrs command
1285 * and returns the result if it differs from the
1286 * original and isn't obviously invalid.
1289 * 1 : old_url = URL to rewrite.
1290 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1293 * Returns : NULL if the pcrs_command didn't change the url, or
1294 * the result of the modification.
1296 *********************************************************************/
1297 char *rewrite_url(char *old_url, const char *pcrs_command)
1299 char *new_url = NULL;
1303 assert(pcrs_command);
1305 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1309 log_error(LOG_LEVEL_REDIRECTS,
1310 "pcrs command \"%s\" didn't change \"%s\".",
1311 pcrs_command, old_url);
1316 log_error(LOG_LEVEL_REDIRECTS,
1317 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1318 pcrs_command, old_url, pcrs_strerror(hits));
1321 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1323 log_error(LOG_LEVEL_ERROR,
1324 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1325 "but the result doesn't look like a valid URL and will be ignored.",
1326 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1331 log_error(LOG_LEVEL_REDIRECTS,
1332 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1333 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1341 #ifdef FEATURE_FAST_REDIRECTS
1342 /*********************************************************************
1344 * Function : get_last_url
1346 * Description : Search for the last URL inside a string.
1347 * If the string already is a URL, it will
1348 * be the first URL found.
1351 * 1 : subject = the string to check
1352 * 2 : redirect_mode = +fast-redirect{} mode
1354 * Returns : NULL if no URL was found, or
1355 * the last URL found.
1357 *********************************************************************/
1358 char *get_last_url(char *subject, const char *redirect_mode)
1360 char *new_url = NULL;
1364 assert(redirect_mode);
1366 subject = strdup(subject);
1367 if (subject == NULL)
1369 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1373 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1375 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1376 new_url = url_decode(subject);
1377 if (new_url != NULL)
1384 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1388 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1391 * Find the last URL encoded in the request
1394 while ((tmp = strstr(tmp, "http://")) != NULL)
1398 tmp = (new_url != NULL) ? new_url : subject;
1399 while ((tmp = strstr(tmp, "https://")) != NULL)
1404 if ((new_url != NULL)
1405 && ( (new_url != subject)
1406 || (0 == strncmpic(subject, "http://", 7))
1407 || (0 == strncmpic(subject, "https://", 8))
1411 * Return new URL if we found a redirect
1412 * or if the subject already was a URL.
1414 * The second case makes sure that we can
1415 * chain get_last_url after another redirection check
1416 * (like rewrite_url) without losing earlier redirects.
1418 new_url = strdup(new_url);
1427 #endif /* def FEATURE_FAST_REDIRECTS */
1430 /*********************************************************************
1432 * Function : redirect_url
1434 * Description : Checks if Privoxy should answer the request with
1435 * a HTTP redirect and generates the redirect if
1439 * 1 : csp = Current client state (buffers, headers, etc...)
1441 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1443 *********************************************************************/
1444 struct http_response *redirect_url(struct client_state *csp)
1446 struct http_response *rsp;
1447 #ifdef FEATURE_FAST_REDIRECTS
1449 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1450 * as compile-time option? The user can easily disable
1451 * it in his action file.
1453 char * redirect_mode;
1454 #endif /* def FEATURE_FAST_REDIRECTS */
1455 char *old_url = NULL;
1456 char *new_url = NULL;
1457 char *redirection_string;
1459 if ((csp->action->flags & ACTION_REDIRECT))
1461 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1464 * If the redirection string begins with 's',
1465 * assume it's a pcrs command, otherwise treat it as
1466 * properly formatted URL and use it for the redirection
1469 * According to RFC 2616 section 14.30 the URL
1470 * has to be absolute and if the user tries:
1471 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1472 * she would get undefined results anyway.
1476 if (*redirection_string == 's')
1478 old_url = csp->http->url;
1479 new_url = rewrite_url(old_url, redirection_string);
1483 log_error(LOG_LEVEL_REDIRECTS,
1484 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1485 redirection_string);
1486 new_url = strdup(redirection_string);
1490 #ifdef FEATURE_FAST_REDIRECTS
1491 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1493 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1496 * If it exists, use the previously rewritten URL as input
1497 * otherwise just use the old path.
1499 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1500 new_url = get_last_url(old_url, redirect_mode);
1505 * Disable redirect checkers, so that they
1506 * will be only run more than once if the user
1507 * also enables them through tags.
1509 * From a performance point of view
1510 * it doesn't matter, but the duplicated
1511 * log messages are annoying.
1513 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1514 #endif /* def FEATURE_FAST_REDIRECTS */
1515 csp->action->flags &= ~ACTION_REDIRECT;
1517 /* Did any redirect action trigger? */
1520 if (0 == strcmpic(new_url, csp->http->url))
1522 log_error(LOG_LEVEL_ERROR,
1523 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1524 csp->http->url, new_url);
1529 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1531 if (NULL == (rsp = alloc_http_response()))
1534 return cgi_error_memory();
1537 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1538 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1541 free_http_response(rsp);
1542 return cgi_error_memory();
1544 rsp->reason = RSP_REASON_REDIRECTED;
1547 return finish_http_response(csp, rsp);
1551 /* Only reached if no redirect is required */
1557 #ifdef FEATURE_IMAGE_BLOCKING
1558 /*********************************************************************
1560 * Function : is_imageurl
1562 * Description : Given a URL, decide whether it is an image or not,
1563 * using either the info from a previous +image action
1564 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1565 * is MSIE and not on a Mac, tell from the browser's accept
1569 * 1 : csp = Current client state (buffers, headers, etc...)
1571 * Returns : True (nonzero) if URL is an image, false (0)
1574 *********************************************************************/
1575 int is_imageurl(const struct client_state *csp)
1577 #ifdef FEATURE_IMAGE_DETECT_MSIE
1580 tmp = get_header_value(csp->headers, "User-Agent:");
1581 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1583 tmp = get_header_value(csp->headers, "Accept:");
1584 if (tmp && strstr(tmp, "image/gif"))
1586 /* Client will accept HTML. If this seems counterintuitive,
1596 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1598 return ((csp->action->flags & ACTION_IMAGE) != 0);
1601 #endif /* def FEATURE_IMAGE_BLOCKING */
1604 #ifdef FEATURE_TRUST
1605 /*********************************************************************
1607 * Function : is_untrusted_url
1609 * Description : Should we "distrust" this URL (and block it)?
1611 * Yes if it matches a line in the trustfile, or if the
1612 * referrer matches a line starting with "+" in the
1617 * 1 : csp = Current client state (buffers, headers, etc...)
1619 * Returns : 0 => trusted, 1 => untrusted
1621 *********************************************************************/
1622 int is_untrusted_url(const struct client_state *csp)
1624 struct file_list *fl;
1625 struct block_spec *b;
1626 struct url_spec **trusted_url;
1627 struct http_request rhttp[1];
1628 const char * referer;
1632 * If we don't have a trustlist, we trust everybody
1634 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1639 memset(rhttp, '\0', sizeof(*rhttp));
1642 * Do we trust the request URL itself?
1644 for (b = b->next; b ; b = b->next)
1646 if (url_match(b->url, csp->http))
1652 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1654 /* no referrer was supplied */
1660 * If not, do we maybe trust its referrer?
1662 err = parse_http_url(referer, rhttp, csp);
1668 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1670 if (url_match(*trusted_url, rhttp))
1672 /* if the URL's referrer is from a trusted referrer, then
1673 * add the target spec to the trustfile as an unblocked
1674 * domain and return 0 (which means it's OK).
1679 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1683 char * new_entry = strdup("~");
1685 string_append(&new_entry, csp->http->hostport);
1687 path = csp->http->path;
1688 if ( (path[0] == '/')
1690 && ((path_end = strchr(path + 2, '/')) != NULL))
1692 /* since this path points into a user's home space
1693 * be sure to include this spec in the trustfile.
1695 int path_len = path_end - path; /* save offset */
1696 path = strdup(path); /* Copy string */
1699 path_end = path + path_len; /* regenerate ptr to new buffer */
1700 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1702 string_join(&new_entry, path);
1706 * Give a reason for generating this entry.
1708 string_append(&new_entry, " # Trusted referrer was: ");
1709 string_append(&new_entry, referer);
1711 if (new_entry != NULL)
1713 if (-1 == fprintf(fp, "%s\n", new_entry))
1715 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1716 new_entry, csp->config->trustfile);
1722 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1723 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1730 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1731 csp->http->hostport, csp->config->trustfile);
1739 #endif /* def FEATURE_TRUST */
1742 /*********************************************************************
1744 * Function : pcrs_filter_response
1746 * Description : Execute all text substitutions from all applying
1747 * +filter actions on the text buffer that's been
1748 * accumulated in csp->iob->buf.
1751 * 1 : csp = Current client state (buffers, headers, etc...)
1753 * Returns : a pointer to the (newly allocated) modified buffer.
1754 * or NULL if there were no hits or something went wrong
1756 *********************************************************************/
1757 static char *pcrs_filter_response(struct client_state *csp)
1760 size_t size, prev_size;
1766 struct file_list *fl;
1767 struct re_filterfile_spec *b;
1768 struct list_entry *filtername;
1770 int i, found_filters = 0;
1775 if (csp->iob->cur >= csp->iob->eod)
1781 * Need to check the set of re_filterfiles...
1783 for (i = 0; i < MAX_AF_FILES; i++)
1796 if (0 == found_filters)
1798 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1802 size = (size_t)(csp->iob->eod - csp->iob->cur);
1803 old = csp->iob->cur;
1805 for (i = 0; i < MAX_AF_FILES; i++)
1808 if ((NULL == fl) || (NULL == fl->f))
1811 * Either there are no filter files
1812 * left, or this filter file just
1813 * contains no valid filters.
1815 * Continue to be sure we don't miss
1816 * valid filter files that are chained
1817 * after empty or invalid ones.
1822 * For all applying +filter actions, look if a filter by that
1823 * name exists and if yes, execute it's pcrs_joblist on the
1826 for (b = fl->f; b; b = b->next)
1828 if (b->type != FT_CONTENT_FILTER)
1830 /* Skip header filters */
1834 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1835 filtername ; filtername = filtername->next)
1837 if (strcmp(b->name, filtername->str) == 0)
1839 int current_hits = 0; /* Number of hits caused by this filter */
1840 int job_number = 0; /* Which job we're currently executing */
1841 int job_hits = 0; /* How many hits the current job caused */
1842 pcrs_job *joblist = b->joblist;
1844 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1846 if (NULL == joblist)
1848 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1853 /* Apply all jobs from the joblist */
1854 for (job = joblist; NULL != job; job = job->next)
1857 job_hits = pcrs_execute(job, old, size, &new, &size);
1862 * That went well. Continue filtering
1863 * and use the result of this job as
1864 * input for the next one.
1866 current_hits += job_hits;
1867 if (old != csp->iob->cur)
1876 * This job caused an unexpected error. Inform the user
1877 * and skip the rest of the jobs in this filter. We could
1878 * continue with the next job, but usually the jobs
1879 * depend on each other or are similar enough to
1880 * fail for the same reason.
1882 * At the moment our pcrs expects the error codes of pcre 3.4,
1883 * but newer pcre versions can return additional error codes.
1884 * As a result pcrs_strerror()'s error message might be
1885 * "Unknown error ...", therefore we print the numerical value
1888 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1889 * should we use LOG_LEVEL_RE_FILTER instead?
1891 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1892 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1897 if (b->dynamic) pcrs_free_joblist(joblist);
1899 log_error(LOG_LEVEL_RE_FILTER,
1900 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1901 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1903 hits += current_hits;
1910 * If there were no hits, destroy our copy and let
1911 * chat() use the original in csp->iob
1919 csp->flags |= CSP_FLAG_MODIFIED;
1920 csp->content_length = size;
1928 /*********************************************************************
1930 * Function : gif_deanimate_response
1932 * Description : Deanimate the GIF image that has been accumulated in
1933 * csp->iob->buf, set csp->content_length to the modified
1934 * size and raise the CSP_FLAG_MODIFIED flag.
1937 * 1 : csp = Current client state (buffers, headers, etc...)
1939 * Returns : a pointer to the (newly allocated) modified buffer.
1940 * or NULL in case something went wrong.
1942 *********************************************************************/
1943 static char *gif_deanimate_response(struct client_state *csp)
1945 struct binbuffer *in, *out;
1949 size = (size_t)(csp->iob->eod - csp->iob->cur);
1951 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1952 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1954 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1958 in->buffer = csp->iob->cur;
1961 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1963 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1970 if ((int)size == out->offset)
1972 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1976 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1978 csp->content_length = out->offset;
1979 csp->flags |= CSP_FLAG_MODIFIED;
1989 /*********************************************************************
1991 * Function : jpeg_inspect_response
1996 * 1 : csp = Current client state (buffers, headers, etc...)
1998 * Returns : a pointer to the (newly allocated) modified buffer
1999 * or NULL in case something went wrong.
2001 *********************************************************************/
2002 static char *jpeg_inspect_response(struct client_state *csp)
2004 struct binbuffer *in = NULL;
2005 struct binbuffer *out = NULL;
2009 size = (size_t)(csp->iob->eod - csp->iob->cur);
2011 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
2013 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
2017 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
2019 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
2023 in->buffer = csp->iob->cur;
2027 * Calling jpeg_inspect has the side-effect of creating and
2028 * modifying the image buffer of "out" directly.
2030 if (jpeg_inspect(in, out))
2032 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
2040 csp->content_length = out->offset;
2041 csp->flags |= CSP_FLAG_MODIFIED;
2051 /*********************************************************************
2053 * Function : get_filter_function
2055 * Description : Decides which content filter function has
2056 * to be applied (if any).
2058 * XXX: Doesn't handle filter_popups()
2059 * because of the different prototype. Probably
2060 * we should ditch filter_popups() anyway, it's
2061 * even less reliable than popup blocking based
2065 * 1 : csp = Current client state (buffers, headers, etc...)
2067 * Returns : The content filter function to run, or
2068 * NULL if no content filter is active
2070 *********************************************************************/
2071 filter_function_ptr get_filter_function(struct client_state *csp)
2073 filter_function_ptr filter_function = NULL;
2076 * Are we enabling text mode by force?
2078 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2081 * Do we really have to?
2083 if (csp->content_type & CT_TEXT)
2085 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2089 csp->content_type |= CT_TEXT;
2090 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2094 if (!(csp->content_type & CT_DECLARED))
2097 * The server didn't bother to declare a MIME-Type.
2098 * Assume it's text that can be filtered.
2100 * This also regulary happens with 304 responses,
2101 * therefore logging anything here would cause
2104 csp->content_type |= CT_TEXT;
2108 * Choose the applying filter function based on
2109 * the content type and action settings.
2111 if ((csp->content_type & CT_TEXT) &&
2112 (csp->rlist != NULL) &&
2113 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2115 filter_function = pcrs_filter_response;
2117 else if ((csp->content_type & CT_GIF) &&
2118 (csp->action->flags & ACTION_DEANIMATE))
2120 filter_function = gif_deanimate_response;
2122 else if ((csp->content_type & CT_JPEG) &&
2123 (csp->action->flags & ACTION_JPEG_INSPECT))
2125 filter_function = jpeg_inspect_response;
2128 return filter_function;
2132 /*********************************************************************
2134 * Function : remove_chunked_transfer_coding
2136 * Description : In-situ remove the "chunked" transfer coding as defined
2137 * in rfc2616 from a buffer.
2140 * 1 : buffer = Pointer to the text buffer
2141 * 2 : size = In: Number of bytes to be processed,
2142 * Out: Number of bytes after de-chunking.
2143 * (undefined in case of errors)
2145 * Returns : JB_ERR_OK for success,
2146 * JB_ERR_PARSE otherwise
2148 *********************************************************************/
2149 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2152 unsigned int chunksize = 0;
2153 char *from_p, *to_p;
2156 from_p = to_p = buffer;
2158 if (sscanf(buffer, "%x", &chunksize) != 1)
2160 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2161 return JB_ERR_PARSE;
2164 while (chunksize > 0)
2166 if (NULL == (from_p = strstr(from_p, "\r\n")))
2168 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2169 return JB_ERR_PARSE;
2172 if ((newsize += chunksize) >= *size)
2174 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
2175 return JB_ERR_PARSE;
2179 memmove(to_p, from_p, (size_t) chunksize);
2180 to_p = buffer + newsize;
2181 from_p += chunksize + 2;
2183 if (sscanf(from_p, "%x", &chunksize) != 1)
2185 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2186 return JB_ERR_PARSE;
2190 /* XXX: Should get its own loglevel. */
2191 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
2200 /*********************************************************************
2202 * Function : prepare_for_filtering
2204 * Description : If necessary, de-chunks and decompresses
2205 * the content so it can get filterd.
2208 * 1 : csp = Current client state (buffers, headers, etc...)
2210 * Returns : JB_ERR_OK for success,
2211 * JB_ERR_PARSE otherwise
2213 *********************************************************************/
2214 static jb_err prepare_for_filtering(struct client_state *csp)
2216 jb_err err = JB_ERR_OK;
2219 * If the body has a "chunked" transfer-encoding,
2220 * get rid of it, adjusting size and iob->eod
2222 if (csp->flags & CSP_FLAG_CHUNKED)
2224 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2226 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2227 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2228 if (JB_ERR_OK == err)
2230 csp->iob->eod = csp->iob->cur + size;
2231 csp->flags |= CSP_FLAG_MODIFIED;
2235 return JB_ERR_PARSE;
2241 * If the body has a supported transfer-encoding,
2242 * decompress it, adjusting size and iob->eod.
2244 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
2246 if (0 == csp->iob->eod - csp->iob->cur)
2248 /* Nothing left after de-chunking. */
2252 err = decompress_iob(csp);
2254 if (JB_ERR_OK == err)
2256 csp->flags |= CSP_FLAG_MODIFIED;
2257 csp->content_type &= ~CT_TABOO;
2262 * Unset CT_GZIP and CT_DEFLATE to remember not
2263 * to modify the Content-Encoding header later.
2265 csp->content_type &= ~CT_GZIP;
2266 csp->content_type &= ~CT_DEFLATE;
2275 /*********************************************************************
2277 * Function : execute_content_filter
2279 * Description : Executes a given content filter.
2282 * 1 : csp = Current client state (buffers, headers, etc...)
2283 * 2 : content_filter = The filter function to execute
2285 * Returns : Pointer to the modified buffer, or
2286 * NULL if filtering failed or wasn't necessary.
2288 *********************************************************************/
2289 char *execute_content_filter(struct client_state *csp, filter_function_ptr content_filter)
2291 if (0 == csp->iob->eod - csp->iob->cur)
2294 * No content (probably status code 301, 302 ...),
2295 * no filtering necessary.
2300 if (JB_ERR_OK != prepare_for_filtering(csp))
2303 * failed to de-chunk or decompress.
2304 * XXX: if possible, we should continue anyway.
2309 if (0 == csp->iob->eod - csp->iob->cur)
2312 * Clown alarm: chunked and/or compressed nothing delivered.
2317 return ((*content_filter)(csp));
2321 /*********************************************************************
2323 * Function : url_actions
2325 * Description : Gets the actions for this URL.
2328 * 1 : http = http_request request for blocked URLs
2329 * 2 : csp = Current client state (buffers, headers, etc...)
2333 *********************************************************************/
2334 void url_actions(struct http_request *http,
2335 struct client_state *csp)
2337 struct file_list *fl;
2338 struct url_actions *b;
2341 init_current_action(csp->action);
2343 for (i = 0; i < MAX_AF_FILES; i++)
2345 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2350 apply_url_actions(csp->action, http, b);
2357 /*********************************************************************
2359 * Function : apply_url_actions
2361 * Description : Applies a list of URL actions.
2364 * 1 : action = Destination.
2365 * 2 : http = Current URL
2366 * 3 : b = list of URL actions to apply
2370 *********************************************************************/
2371 void apply_url_actions(struct current_action_spec *action,
2372 struct http_request *http,
2373 struct url_actions *b)
2377 /* Should never happen */
2381 for (b = b->next; NULL != b; b = b->next)
2383 if (url_match(b->url, http))
2385 merge_current_action(action, b->action);
2391 /*********************************************************************
2393 * Function : get_forward_override_settings
2395 * Description : Returns forward settings as specified with the
2396 * forward-override{} action. forward-override accepts
2397 * forward lines similar to the one used in the
2398 * configuration file, but without the URL pattern.
2404 * in the configuration file can be replaced with
2405 * the action section:
2407 * {+forward-override{forward .}}
2411 * 1 : csp = Current client state (buffers, headers, etc...)
2413 * Returns : Pointer to forwarding structure in case of success.
2414 * Invalid syntax is fatal.
2416 *********************************************************************/
2417 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2419 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2420 char forward_settings[BUFFER_SIZE];
2421 char *http_parent = NULL;
2422 /* variable names were chosen for consistency reasons. */
2423 struct forward_spec *fwd = NULL;
2427 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2428 /* Should be enforced by load_one_actions_file() */
2429 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2431 /* Create a copy ssplit can modify */
2432 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2434 if (NULL != csp->fwd)
2437 * XXX: Currently necessary to prevent memory
2438 * leaks when the show-url-info cgi page is visited.
2440 unload_forward_spec(csp->fwd);
2444 * allocate a new forward node, valid only for
2445 * the lifetime of this request. Save its location
2446 * in csp as well, so sweep() can free it later on.
2448 fwd = csp->fwd = zalloc(sizeof(*fwd));
2451 log_error(LOG_LEVEL_FATAL,
2452 "can't allocate memory for forward-override{%s}", forward_override_line);
2453 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2456 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2457 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2459 fwd->type = SOCKS_NONE;
2461 /* Parse the parent HTTP proxy host:port */
2462 http_parent = vec[1];
2465 else if (vec_count == 3)
2467 char *socks_proxy = NULL;
2469 if (!strcasecmp(vec[0], "forward-socks4"))
2471 fwd->type = SOCKS_4;
2472 socks_proxy = vec[1];
2474 else if (!strcasecmp(vec[0], "forward-socks4a"))
2476 fwd->type = SOCKS_4A;
2477 socks_proxy = vec[1];
2480 if (NULL != socks_proxy)
2482 /* Parse the SOCKS proxy host[:port] */
2483 fwd->gateway_host = strdup(socks_proxy);
2485 if (NULL != (socks_proxy = strchr(fwd->gateway_host, ':')))
2487 *socks_proxy++ = '\0';
2488 fwd->gateway_port = strtol(socks_proxy, NULL, 0);
2491 if (fwd->gateway_port <= 0)
2493 fwd->gateway_port = 1080;
2496 http_parent = vec[2];
2500 if (NULL == http_parent)
2502 log_error(LOG_LEVEL_FATAL,
2503 "Invalid forward-override syntax in: %s", forward_override_line);
2504 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2507 /* Parse http forwarding settings */
2508 if (strcmp(http_parent, ".") != 0)
2510 fwd->forward_host = strdup(http_parent);
2512 if (NULL != (http_parent = strchr(fwd->forward_host, ':')))
2514 *http_parent++ = '\0';
2515 fwd->forward_port = strtol(http_parent, NULL, 0);
2518 if (fwd->forward_port <= 0)
2520 fwd->forward_port = 8000;
2524 assert (NULL != fwd);
2526 log_error(LOG_LEVEL_CONNECT,
2527 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2533 /*********************************************************************
2535 * Function : forward_url
2537 * Description : Should we forward this to another proxy?
2539 * XXX: Should be changed to make use of csp->fwd.
2542 * 1 : http = http_request request for current URL
2543 * 2 : csp = Current client state (buffers, headers, etc...)
2545 * Returns : Pointer to forwarding information.
2547 *********************************************************************/
2548 const struct forward_spec * forward_url(struct http_request *http,
2549 struct client_state *csp)
2551 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2552 struct forward_spec *fwd = csp->config->forward;
2554 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2556 return get_forward_override_settings(csp);
2566 if (url_match(fwd->url, http))
2577 /*********************************************************************
2579 * Function : direct_response
2581 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2582 * request and if so, return a HTTP 501 to the client.
2584 * FIXME: I have a stupid name and I should handle the
2585 * requests properly. Still, what we do here is rfc-
2586 * compliant, whereas ignoring or forwarding are not.
2589 * 1 : csp = Current client state (buffers, headers, etc...)
2591 * Returns : http_response if , NULL if nonmatch or handler fail
2593 *********************************************************************/
2594 struct http_response *direct_response(struct client_state *csp)
2596 struct http_response *rsp;
2597 struct list_entry *p;
2599 if ((0 == strcmpic(csp->http->gpc, "trace"))
2600 || (0 == strcmpic(csp->http->gpc, "options")))
2602 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2604 if (!strncmpic("Max-Forwards:", p->str, 13))
2606 unsigned int max_forwards;
2609 * If it's a Max-Forwards value of zero,
2610 * we have to intercept the request.
2612 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2615 * FIXME: We could handle at least TRACE here,
2616 * but that would require a verbatim copy of
2617 * the request which we don't have anymore
2619 log_error(LOG_LEVEL_HEADER,
2620 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2623 /* Get mem for response or fail*/
2624 if (NULL == (rsp = alloc_http_response()))
2626 return cgi_error_memory();
2629 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2631 free_http_response(rsp);
2632 return cgi_error_memory();
2636 rsp->reason = RSP_REASON_UNSUPPORTED;
2638 return(finish_http_response(csp, rsp));