1 const char filters_rcs[] = "$Id: filters.c,v 1.102 2008/03/01 14:00:44 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-2008 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.102 2008/03/01 14:00:44 fabiankeil
44 * Let the block action take the reason for the block
45 * as argument and show it on the "blocked" page.
47 * Revision 1.101 2008/02/23 16:57:12 fabiankeil
48 * Rename url_actions() to get_url_actions() and let it
49 * use the standard parameter ordering.
51 * Revision 1.100 2008/02/23 16:33:43 fabiankeil
52 * Let forward_url() use the standard parameter ordering
53 * and mark its second parameter immutable.
55 * Revision 1.99 2008/02/03 13:57:58 fabiankeil
56 * Add SOCKS5 support for forward-override{}.
58 * Revision 1.98 2008/01/04 17:43:45 fabiankeil
59 * Improve the warning messages that get logged if the action files
60 * "enable" filters but no filters of that type have been loaded.
62 * Revision 1.97 2007/11/30 15:37:03 fabiankeil
63 * Use freez instead of free.
65 * Revision 1.96 2007/10/19 16:53:28 fabiankeil
66 * Add helper function to check if any content filters are enabled.
68 * Revision 1.95 2007/10/17 19:31:20 fabiankeil
69 * Omitting the zero chunk that ends the chunk transfer encoding seems
70 * to be the new black. Log the problem and continue filtering anyway.
72 * Revision 1.94 2007/09/29 13:20:20 fabiankeil
73 * Remove two redundant and one useless log messages.
75 * Revision 1.93 2007/09/29 10:21:16 fabiankeil
76 * - Move get_filter_function() from jcc.c to filters.c
77 * so the filter functions can be static.
78 * - Don't bother filtering body-less responses.
80 * Revision 1.92 2007/09/28 16:38:55 fabiankeil
81 * - Execute content filters through execute_content_filter().
82 * - Add prepare_for_filtering() so filter functions don't have to
83 * care about de-chunking and decompression. As a side effect this enables
84 * decompression for gif_deanimate_response() and jpeg_inspect_response().
85 * - Change remove_chunked_transfer_coding()'s return type to jb_err.
86 * Some clowns feel like chunking empty responses in which case
87 * (size == 0) is valid but previously would be interpreted as error.
89 * Revision 1.91 2007/09/02 15:31:20 fabiankeil
90 * Move match_portlist() from filter.c to urlmatch.c.
91 * It's used for url matching, not for filtering.
93 * Revision 1.90 2007/09/02 12:44:17 fabiankeil
94 * Remove newline at the end of a log_error() message.
96 * Revision 1.89 2007/08/05 13:42:23 fabiankeil
97 * #1763173 from Stefan Huehner: declare some more functions static.
99 * Revision 1.88 2007/06/01 16:41:11 fabiankeil
100 * Add forward-override{} to change the forwarding settings through
101 * action sections. This is mainly interesting to forward different
102 * clients differently (for example based on User-Agent or request
105 * Revision 1.87 2007/04/30 15:53:10 fabiankeil
106 * Make sure filters with dynamic jobs actually use them.
108 * Revision 1.86 2007/04/30 15:03:28 fabiankeil
109 * - Introduce dynamic pcrs jobs that can resolve variables.
110 * - Don't run redirect functions more than once,
111 * unless they are activated more than once.
113 * Revision 1.85 2007/03/21 12:24:47 fabiankeil
114 * - Log the content size after decompression in decompress_iob()
115 * instead of pcrs_filter_response().
117 * Revision 1.84 2007/03/20 15:16:34 fabiankeil
118 * Use dedicated header filter actions instead of abusing "filter".
119 * Replace "filter-client-headers" and "filter-client-headers"
120 * with "server-header-filter" and "client-header-filter".
122 * Revision 1.83 2007/03/17 15:20:05 fabiankeil
123 * New config option: enforce-blocks.
125 * Revision 1.82 2007/03/13 11:28:43 fabiankeil
126 * - Fix port handling in acl_addr() and use a temporary acl spec
127 * copy so error messages don't contain a truncated version.
128 * - Log size of iob before and after decompression.
130 * Revision 1.81 2007/03/05 14:40:53 fabiankeil
131 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
132 * - Hide the "Go there anyway" link for blocked CONNECT
133 * requests where going there anyway doesn't work anyway.
135 * Revision 1.80 2007/02/07 10:55:20 fabiankeil
136 * - Save the reason for generating http_responses.
137 * - Block (+block) with status code 403 instead of 404.
138 * - Use a different kludge to remember a failed decompression.
140 * Revision 1.79 2007/01/31 16:21:38 fabiankeil
141 * Search for Max-Forwards headers case-insensitive,
142 * don't generate the "501 unsupported" message for invalid
143 * Max-Forwards values and don't increase negative ones.
145 * Revision 1.78 2007/01/28 13:41:18 fabiankeil
146 * - Add HEAD support to finish_http_response.
147 * - Add error favicon to internal HTML error messages.
149 * Revision 1.77 2007/01/12 15:36:44 fabiankeil
150 * Mark *csp as immutable for is_untrusted_url()
151 * and is_imageurl(). Closes FR 1237736.
153 * Revision 1.76 2007/01/01 19:36:37 fabiankeil
154 * Integrate a modified version of Wil Mahan's
155 * zlib patch (PR #895531).
157 * Revision 1.75 2006/12/29 18:30:46 fabiankeil
158 * Fixed gcc43 conversion warnings,
159 * changed sprintf calls to snprintf.
161 * Revision 1.74 2006/12/24 17:37:38 fabiankeil
162 * Adjust comment in pcrs_filter_response()
163 * to recent pcrs changes. Hohoho.
165 * Revision 1.73 2006/12/23 16:01:02 fabiankeil
166 * Don't crash if pcre returns an error code
167 * that pcrs didn't expect. Fixes BR 1621173.
169 * Revision 1.72 2006/12/22 18:52:53 fabiankeil
170 * Modified is_untrusted_url to complain in case of
171 * write errors and to give a reason when adding new
172 * entries to the trustfile. Closes FR 1097611.
174 * Revision 1.71 2006/12/22 14:24:52 fabiankeil
175 * Skip empty filter files in pcrs_filter_response,
176 * but don't ignore the ones that come afterwards.
177 * Fixes parts of BR 1619208.
179 * Revision 1.70 2006/12/09 13:33:15 fabiankeil
180 * Added some sanity checks for get_last_url().
181 * Fixed possible segfault caused by my last commit.
183 * Revision 1.69 2006/12/08 12:39:13 fabiankeil
184 * Let get_last_url() catch https URLs as well.
186 * Revision 1.68 2006/12/05 14:45:48 fabiankeil
187 * Make sure get_last_url() behaves like advertised
188 * and fast-redirects{} can be combined with redirect{}.
190 * Revision 1.67 2006/11/28 15:19:43 fabiankeil
191 * Implemented +redirect{s@foo@bar@} to generate
192 * a redirect based on a rewritten version of the
195 * Revision 1.66 2006/09/23 13:26:38 roro
196 * Replace TABs by spaces in source code.
198 * Revision 1.65 2006/09/21 12:54:43 fabiankeil
199 * Fix +redirect{}. Didn't work with -fast-redirects.
201 * Revision 1.64 2006/08/31 10:55:49 fabiankeil
202 * Block requests for untrusted URLs with status
203 * code 403 instead of 200.
205 * Revision 1.63 2006/08/31 10:11:28 fabiankeil
206 * Don't free p which is still in use and will be later
207 * freed by free_map(). Don't claim the referrer is unknown
208 * when the client didn't set one.
210 * Revision 1.62 2006/08/14 00:27:47 david__schmidt
211 * Feature request 595948: Re-Filter logging in single line
213 * Revision 1.61 2006/08/03 02:46:41 david__schmidt
214 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
216 * Revision 1.60 2006/07/18 14:48:46 david__schmidt
217 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
218 * with what was really the latest development (the v_3_0_branch branch)
220 * Revision 1.58.2.9 2006/01/29 23:10:56 david__schmidt
221 * Multiple filter file support
223 * Revision 1.58.2.8 2005/05/07 21:50:55 david__schmidt
224 * A few memory leaks plugged (mostly on error paths)
226 * Revision 1.58.2.7 2004/10/03 12:53:32 david__schmidt
227 * Add the ability to check jpeg images for invalid
228 * lengths of comment blocks. Defensive strategy
229 * against the exploit:
230 * Microsoft Security Bulletin MS04-028
231 * Buffer Overrun in JPEG Processing (GDI+) Could
232 * Allow Code Execution (833987)
233 * Enabled with +inspect-jpegs in actions files.
235 * Revision 1.58.2.6 2003/12/06 22:18:27 gliptak
236 * Correcting compile problem with FEATURE_IMAGE_BLOCKING
238 * Revision 1.58.2.5 2003/11/11 13:10:31 oes
239 * Fixed bug #839859: "See why" link URL now gets url-encoded.
241 * Revision 1.58.2.4 2003/02/28 12:52:45 oes
244 * Revision 1.58.2.3 2002/09/25 14:51:51 oes
245 * Added basic support for OPTIONS and TRACE HTTP methods:
246 * New function direct_response which handles OPTIONS and
247 * TRACE requests whose Max-Forwards header field is zero.
249 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
250 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
252 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
253 * - Bugfix: Executing a filters without jobs no longer results in
254 * turing off *all* filters.
255 * - Security fix: Malicious web servers can't cause a seg fault
256 * through bogus chunk sizes anymore
258 * Revision 1.58 2002/04/24 02:11:17 oes
259 * Jon's multiple AF patch: url_actions now evaluates rules
262 * Revision 1.57 2002/04/08 20:38:34 swa
265 * Revision 1.56 2002/04/05 15:51:24 oes
266 * - bugfix: error-pages now get correct request protocol
267 * - fix for invalid HTML in trust info
269 * Revision 1.55 2002/04/02 16:13:51 oes
270 * Fix: No "Go there anyway" for SSL
272 * Revision 1.54 2002/04/02 14:55:56 oes
273 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
275 * Revision 1.53 2002/03/26 22:29:54 swa
276 * we have a new homepage!
278 * Revision 1.52 2002/03/24 16:35:57 jongfoster
281 * Revision 1.51 2002/03/24 15:23:33 jongfoster
284 * Revision 1.50 2002/03/24 13:25:43 swa
285 * name change related issues
287 * Revision 1.49 2002/03/16 20:29:14 oes
290 * Revision 1.48 2002/03/13 20:25:34 oes
291 * Better logging for content filters
293 * Revision 1.47 2002/03/13 00:30:52 jongfoster
295 * Added option of always sending redirect for imageblock,
296 * currently disabled with #if 0.
298 * Revision 1.46 2002/03/12 01:42:49 oes
299 * Introduced modular filters
301 * Revision 1.45 2002/03/08 16:47:50 oes
302 * Added choice beween GIF and PNG built-in images
304 * Revision 1.44 2002/03/07 03:49:31 oes
305 * - Fixed compiler warnings etc
306 * - Changed built-in images from GIF to PNG
307 * (with regard to Unisys patent issue)
308 * - Added a 4x4 pattern PNG which is less intrusive
309 * than the logo but also clearly marks the deleted banners
311 * Revision 1.43 2002/01/22 23:51:59 jongfoster
312 * Replacing strsav() with the safer string_append().
314 * Adding missing html_encode() to error message generators. Where encoded
315 * and unencoded versions of a string were provided, removing the unencoded
318 * Revision 1.42 2002/01/17 21:00:32 jongfoster
319 * Moving all our URL and URL pattern parsing code to urlmatch.c.
321 * Using a single, simple url_match(pattern,url) function - rather than
322 * the 3-line match routine which was repeated all over the place.
324 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
326 * Using parse_http_url() to parse URLs without faking a HTTP
327 * request line for parse_http_request().
329 * Revision 1.41 2001/11/13 00:14:07 jongfoster
330 * Fixing stupid bug now I've figured out what || means.
331 * (It always returns 0 or 1, not one of it's paramaters.)
333 * Revision 1.40 2001/10/26 17:37:55 oes
334 * - Re-enabled Netscape 200/404 bug workaround in block_url():
335 * - Removed OS/2 special case
336 * - Made block_url() independant from sed() having been run
337 * - Made trust_url independant from sed() having been run
338 * - Made is_imageurl independant from sed() having been run.
339 * It now checks User-Agent: and Accept: by itself.
342 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
343 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
344 * threads to call select() simultaneously. So, it's time to do a real, live,
345 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
346 * (native). Both versions will work, but using __OS2__ offers multi-threading.
348 * Revision 1.38 2001/10/23 21:32:33 jongfoster
349 * Adding error-checking to selected functions
351 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
352 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
353 * filters.c. Added a FIXME in front of the offending code. I'll gladly
354 * put in a better/more robust fix for all parties if one is presented...
355 * It seems that just returning 200 instead of 404 would pretty much fix
356 * it for everyone, but I don't know all the history of the problem.
358 * Revision 1.36 2001/10/10 16:44:16 oes
359 * Added match_portlist function
361 * Revision 1.35 2001/10/07 15:41:23 oes
362 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
364 * New function remove_chunked_transfer_coding that strips chunked
365 * transfer coding to plain and is called by pcrs_filter_response
366 * and gif_deanimate_response if neccessary
368 * Improved handling of zero-change re_filter runs
370 * pcrs_filter_response and gif_deanimate_response now remove
371 * chunked transfer codeing before processing the body.
373 * Revision 1.34 2001/09/20 15:49:36 steudten
375 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
376 * See cgi.c fill_template().
378 * Revision 1.33 2001/09/16 17:05:14 jongfoster
379 * Removing unused #include showarg.h
381 * Revision 1.32 2001/09/16 13:21:27 jongfoster
382 * Changes to use new list functions.
384 * Revision 1.31 2001/09/16 11:38:02 jongfoster
385 * Splitting fill_template() into 2 functions:
386 * template_load() loads the file
387 * template_fill() performs the PCRS regexps.
388 * This is because the CGI edit interface has a "table row"
389 * template which is used many times in the page - this
390 * change means it's only loaded from disk once.
392 * Revision 1.30 2001/09/16 11:00:10 jongfoster
393 * New function alloc_http_response, for symmetry with free_http_response
395 * Revision 1.29 2001/09/13 23:32:40 jongfoster
396 * Moving image data to cgi.c rather than cgi.h
397 * Fixing a GPF under Win32 (and any other OS that protects global
398 * constants from being written to).
400 * Revision 1.28 2001/09/10 10:18:51 oes
401 * Silenced compiler warnings
403 * Revision 1.27 2001/08/05 16:06:20 jongfoster
404 * Modifiying "struct map" so that there are now separate header and
405 * "map_entry" structures. This means that functions which modify a
406 * map no longer need to return a pointer to the modified map.
407 * Also, it no longer reverses the order of the entries (which may be
408 * important with some advanced template substitutions).
410 * Revision 1.26 2001/07/30 22:08:36 jongfoster
411 * Tidying up #defines:
412 * - All feature #defines are now of the form FEATURE_xxx
413 * - Permanently turned off WIN_GUI_EDIT
414 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
416 * Revision 1.25 2001/07/26 10:09:46 oes
417 * Made browser detection a little less naive
419 * Revision 1.24 2001/07/25 17:22:51 oes
420 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
422 * Revision 1.23 2001/07/23 13:40:12 oes
423 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
425 * Revision 1.22 2001/07/18 12:29:34 oes
426 * - Made gif_deanimate_response respect
427 * csp->action->string[ACTION_STRING_DEANIMATE]
428 * - Logging cosmetics
430 * Revision 1.21 2001/07/13 13:59:53 oes
431 * - Introduced gif_deanimate_response which shares the
432 * generic content modification interface of pcrs_filter_response
433 * and acts as a wrapper to deanimate.c:gif_deanimate()
434 * - Renamed re_process_buffer to pcrs_filter_response
435 * - pcrs_filter_response now returns NULL on failiure
436 * - Removed all #ifdef PCRS
438 * Revision 1.20 2001/07/01 17:01:04 oes
439 * Added comments and missing return statement in is_untrusted_url()
441 * Revision 1.19 2001/06/29 21:45:41 oes
442 * Indentation, CRLF->LF, Tab-> Space
444 * Revision 1.18 2001/06/29 13:27:38 oes
445 * - Cleaned up, renamed and reorderd functions
446 * and improved comments
449 * - Ported to CGI platform. Now delivers
450 * http_response or NULL
451 * - Unified HTML and GIF generation (moved image detection
452 * and GIF generation here from jcc.c:chat())
453 * - Fixed HTTP status to:
454 * - 403 (Forbidden) for the "blocked" HTML message
455 * - 200 (OK) for GIF answers
456 * - 302 (Redirect) for redirect to GIF
459 * - Ported to CGI platform. Now delivers
460 * http_response or NULL
461 * - Separated detection of untrusted URL into
462 * (bool)is_untrusted_url
463 * - Added enforcement of untrusted requests
465 * - Moved redirect_url() from cgi.c to here
466 * and ported it to the CGI platform
468 * - Removed logentry from cancelled commit
470 * Revision 1.17 2001/06/09 10:55:28 jongfoster
471 * Changing BUFSIZ ==> BUFFER_SIZE
473 * Revision 1.16 2001/06/07 23:10:26 jongfoster
474 * Allowing unanchored domain patterns to back off and retry
475 * if they partially match. Optimized right-anchored patterns.
476 * Moving ACL and forward files into config file.
477 * Replacing struct gateway with struct forward_spec
479 * Revision 1.15 2001/06/03 19:12:00 oes
480 * extracted-CGI relevant stuff
482 * Revision 1.14 2001/06/01 10:30:55 oes
483 * Added optional left-anchoring to domaincmp
485 * Revision 1.13 2001/05/31 21:21:30 jongfoster
486 * Permissionsfile / actions file changes:
487 * - Changed "permission" to "action" throughout
488 * - changes to file format to allow string parameters
489 * - Moved helper functions to actions.c
491 * Revision 1.12 2001/05/31 17:35:20 oes
493 * - Enhanced domain part globbing with infix and prefix asterisk
494 * matching and optional unanchored operation
496 * Revision 1.11 2001/05/29 11:53:23 oes
497 * "See why" link added to "blocked" page
499 * Revision 1.10 2001/05/29 09:50:24 jongfoster
500 * Unified blocklist/imagelist/permissionslist.
501 * File format is still under discussion, but the internal changes
504 * Also modified interceptor behaviour:
505 * - We now intercept all URLs beginning with one of the following
506 * prefixes (and *only* these prefixes):
508 * * http://ijbswa.sf.net/config/
509 * * http://ijbswa.sourceforge.net/config/
510 * - New interceptors "home page" - go to http://i.j.b/ to see it.
511 * - Internal changes so that intercepted and fast redirect pages
512 * are not replaced with an image.
513 * - Interceptors now have the option to send a binary page direct
514 * to the client. (i.e. ijb-send-banner uses this)
515 * - Implemented show-url-info interceptor. (Which is why I needed
516 * the above interceptors changes - a typical URL is
517 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
518 * The previous mechanism would not have intercepted that, and
519 * if it had been intercepted then it then it would have replaced
522 * Revision 1.9 2001/05/27 22:17:04 oes
524 * - re_process_buffer no longer writes the modified buffer
525 * to the client, which was very ugly. It now returns the
526 * buffer, which it is then written by chat.
528 * - content_length now adjusts the Content-Length: header
529 * for modified documents rather than crunch()ing it.
530 * (Length info in csp->content_length, which is 0 for
531 * unmodified documents)
533 * - For this to work, sed() is called twice when filtering.
535 * Revision 1.8 2001/05/26 17:13:28 jongfoster
536 * Filled in a function comment.
538 * Revision 1.7 2001/05/26 15:26:15 jongfoster
539 * ACL feature now provides more security by immediately dropping
540 * connections from untrusted hosts.
542 * Revision 1.6 2001/05/26 00:28:36 jongfoster
543 * Automatic reloading of config file.
544 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
545 * Most of the global variables have been moved to a new
546 * struct configuration_spec, accessed through csp->config->globalname
547 * Most of the globals remaining are used by the Win32 GUI.
549 * Revision 1.5 2001/05/25 22:34:30 jongfoster
552 * Revision 1.4 2001/05/22 18:46:04 oes
554 * - Enabled filtering banners by size rather than URL
555 * by adding patterns that replace all standard banner
556 * sizes with the "Junkbuster" gif to the re_filterfile
558 * - Enabled filtering WebBugs by providing a pattern
559 * which kills all 1x1 images
561 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
562 * which is selected by the (nonstandard and therefore
563 * capital) letter 'U' in the option string.
564 * It causes the quantifiers to be ungreedy by default.
565 * Appending a ? turns back to greedy (!).
567 * - Added a new interceptor ijb-send-banner, which
568 * sends back the "Junkbuster" gif. Without imagelist or
569 * MSIE detection support, or if tinygif = 1, or the
570 * URL isn't recognized as an imageurl, a lame HTML
571 * explanation is sent instead.
573 * - Added new feature, which permits blocking remote
574 * script redirects and firing back a local redirect
576 * The feature is conditionally compiled, i.e. it
577 * can be disabled with --disable-fast-redirects,
578 * plus it must be activated by a "fast-redirects"
579 * line in the config file, has its own log level
580 * and of course wants to be displayed by show-proxy-args
581 * Note: Boy, all the #ifdefs in 1001 locations and
582 * all the fumbling with configure.in and acconfig.h
583 * were *way* more work than the feature itself :-(
585 * - Because a generic redirect template was needed for
586 * this, tinygif = 3 now uses the same.
588 * - Moved GIFs, and other static HTTP response templates
593 * - Removed some >400 CRs again (Jon, you really worked
596 * Revision 1.3 2001/05/20 16:44:47 jongfoster
597 * Removing last hardcoded Junkbusters.com URLs.
599 * Revision 1.2 2001/05/20 01:21:20 jongfoster
600 * Version 2.9.4 checkin.
601 * - Merged popupfile and cookiefile, and added control over PCRS
602 * filtering, in new "permissionsfile".
603 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
604 * file error you now get a message box (in the Win32 GUI) rather
605 * than the program exiting with no explanation.
606 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
608 * - Removed tabs from "config"
609 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
610 * - Bumped up version number.
612 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
613 * Initial import of version 2.9.3 source tree
616 *********************************************************************/
622 #include <sys/types.h>
631 #endif /* ndef __OS2__ */
632 #include <netinet/in.h>
634 #include <winsock2.h>
635 #endif /* ndef _WIN32 */
639 #endif /* def __OS2__ */
647 #include "jbsockets.h"
648 #include "miscutil.h"
652 #include "deanimate.h"
653 #include "urlmatch.h"
660 const char filters_h_rcs[] = FILTERS_H_VERSION;
662 /* Fix a problem with Solaris. There should be no effect on other
664 * Solaris's isspace() is a macro which uses it's argument directly
665 * as an array index. Therefore we need to make sure that high-bit
666 * characters generate +ve values, and ideally we also want to make
667 * the argument match the declared parameter type of "int".
669 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
671 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
672 static jb_err prepare_for_filtering(struct client_state *csp);
675 /*********************************************************************
677 * Function : block_acl
679 * Description : Block this request?
680 * Decide yes or no based on ACL file.
683 * 1 : dst = The proxy or gateway address this is going to.
684 * Or NULL to check all possible targets.
685 * 2 : csp = Current client state (buffers, headers, etc...)
686 * Also includes the client IP address.
688 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
690 *********************************************************************/
691 int block_acl(struct access_control_addr *dst, struct client_state *csp)
693 struct access_control_list *acl = csp->config->acl;
695 /* if not using an access control list, then permit the connection */
701 /* search the list */
704 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
708 /* Just want to check if they have any access */
709 if (acl->action == ACL_PERMIT)
714 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
715 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
717 if (acl->action == ACL_PERMIT)
735 /*********************************************************************
737 * Function : acl_addr
739 * Description : Called from `load_config' to parse an ACL address.
742 * 1 : aspec = String specifying ACL address.
743 * 2 : aca = struct access_control_addr to fill in.
745 * Returns : 0 => Ok, everything else is an error.
747 *********************************************************************/
748 int acl_addr(const char *aspec, struct access_control_addr *aca)
753 char *acl_spec = NULL;
759 * Use a temporary acl spec copy so we can log
760 * the unmodified original in case of parse errors.
762 acl_spec = strdup(aspec);
763 if (acl_spec == NULL)
765 /* XXX: This will be logged as parse error. */
769 if ((p = strchr(acl_spec, '/')) != NULL)
772 if (ijb_isdigit(*p) == 0)
777 masklength = atoi(p);
780 if ((masklength < 0) || (masklength > 32))
786 if ((p = strchr(acl_spec, ':')) != NULL)
791 port = strtol(p, &endptr, 10);
793 if (port <= 0 || port > 65535 || *endptr != '\0')
800 aca->port = (unsigned long)port;
802 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
805 if (aca->addr == INADDR_NONE)
807 /* XXX: This will be logged as parse error. */
811 /* build the netmask */
813 for (i=1; i <= masklength ; i++)
815 aca->mask |= (1 << (32 - i));
818 /* now mask off the host portion of the ip address
819 * (i.e. save on the network portion of the address).
821 aca->addr = aca->addr & aca->mask;
826 #endif /* def FEATURE_ACL */
829 /*********************************************************************
831 * Function : connect_port_is_forbidden
833 * Description : Check to see if CONNECT requests to the destination
834 * port of this request are forbidden. The check is
835 * independend of the actual request method.
838 * 1 : csp = Current client state (buffers, headers, etc...)
840 * Returns : True if yes, false otherwise.
842 *********************************************************************/
843 int connect_port_is_forbidden(const struct client_state *csp)
845 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
846 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
851 /*********************************************************************
853 * Function : block_url
855 * Description : Called from `chat'. Check to see if we need to block this.
858 * 1 : csp = Current client state (buffers, headers, etc...)
860 * Returns : NULL => unblocked, else HTTP block response
862 *********************************************************************/
863 struct http_response *block_url(struct client_state *csp)
865 struct http_response *rsp;
866 const char *new_content_type = NULL;
869 * If it's not blocked, don't block it ;-)
871 if ((csp->action->flags & ACTION_BLOCK) == 0)
875 if (csp->action->flags & ACTION_REDIRECT)
877 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
880 * Else, prepare a response
882 if (NULL == (rsp = alloc_http_response()))
884 return cgi_error_memory();
888 * If it's an image-url, send back an image or redirect
889 * as specified by the relevant +image action
891 #ifdef FEATURE_IMAGE_BLOCKING
892 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
896 /* determine HOW images should be blocked */
897 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
899 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
901 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
903 #if 1 /* Two alternative strategies, use this one for now: */
905 /* and handle accordingly: */
906 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
908 rsp->status = strdup("403 Request blocked by Privoxy");
909 if (rsp->status == NULL)
911 free_http_response(rsp);
912 return cgi_error_memory();
914 rsp->body = bindup(image_pattern_data, image_pattern_length);
915 if (rsp->body == NULL)
917 free_http_response(rsp);
918 return cgi_error_memory();
920 rsp->content_length = image_pattern_length;
922 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
924 free_http_response(rsp);
925 return cgi_error_memory();
929 else if (0 == strcmpic(p, "blank"))
931 rsp->status = strdup("403 Request blocked by Privoxy");
932 if (rsp->status == NULL)
934 free_http_response(rsp);
935 return cgi_error_memory();
937 rsp->body = bindup(image_blank_data, image_blank_length);
938 if (rsp->body == NULL)
940 free_http_response(rsp);
941 return cgi_error_memory();
943 rsp->content_length = image_blank_length;
945 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
947 free_http_response(rsp);
948 return cgi_error_memory();
954 rsp->status = strdup("302 Local Redirect from Privoxy");
955 if (rsp->status == NULL)
957 free_http_response(rsp);
958 return cgi_error_memory();
961 if (enlist_unique_header(rsp->headers, "Location", p))
963 free_http_response(rsp);
964 return cgi_error_memory();
968 #else /* Following code is disabled for now */
970 /* and handle accordingly: */
971 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
973 p = CGI_PREFIX "send-banner?type=pattern";
975 else if (0 == strcmpic(p, "blank"))
977 p = CGI_PREFIX "send-banner?type=blank";
979 rsp->status = strdup("302 Local Redirect from Privoxy");
980 if (rsp->status == NULL)
982 free_http_response(rsp);
983 return cgi_error_memory();
986 if (enlist_unique_header(rsp->headers, "Location", p))
988 free_http_response(rsp);
989 return cgi_error_memory();
991 #endif /* Preceeding code is disabled for now */
993 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
996 * Send empty document.
998 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1001 rsp->body = strdup(" ");
1002 rsp->content_length = 1;
1004 rsp->status = strdup("403 Request blocked by Privoxy");
1005 if (rsp->status == NULL)
1007 free_http_response(rsp);
1008 return cgi_error_memory();
1010 if (new_content_type != 0)
1012 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
1013 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
1015 free_http_response(rsp);
1016 return cgi_error_memory();
1021 #endif /* def FEATURE_IMAGE_BLOCKING */
1024 * Else, generate an HTML "blocked" message:
1028 struct map * exports;
1032 * Workaround for stupid Netscape bug which prevents
1033 * pages from being displayed if loading a referenced
1034 * JavaScript or style sheet fails. So make it appear
1035 * as if it succeeded.
1037 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
1038 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
1039 && !strstr(p, "Gecko") /* save Mozilla, */
1040 && !strstr(p, "compatible") /* MSIE */
1041 && !strstr(p, "Opera")) /* and Opera. */
1043 rsp->status = strdup("200 Request for blocked URL");
1047 rsp->status = strdup("403 Request for blocked URL");
1050 if (rsp->status == NULL)
1052 free_http_response(rsp);
1053 return cgi_error_memory();
1056 exports = default_exports(csp, NULL);
1057 if (exports == NULL)
1059 free_http_response(rsp);
1060 return cgi_error_memory();
1063 #ifdef FEATURE_FORCE_LOAD
1064 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1066 * Export the force conditional block killer if
1068 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1069 * - Privoxy is configured to enforce blocks, or
1070 * - it's a CONNECT request and enforcing wouldn't work anyway.
1072 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1073 || (0 == strcmpic(csp->http->gpc, "connect")))
1074 #endif /* ndef FEATURE_FORCE_LOAD */
1076 err = map_block_killer(exports, "force-support");
1079 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1080 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1081 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1082 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
1085 const char *block_reason;
1086 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
1088 block_reason = csp->action->string[ACTION_STRING_BLOCK];
1092 assert(connect_port_is_forbidden(csp));
1093 block_reason = "Forbidden CONNECT port.";
1095 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
1100 free_http_response(rsp);
1101 return cgi_error_memory();
1104 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
1107 free_http_response(rsp);
1108 return cgi_error_memory();
1111 rsp->reason = RSP_REASON_BLOCKED;
1113 return finish_http_response(csp, rsp);
1118 #ifdef FEATURE_TRUST
1119 /*********************************************************************
1121 * Function : trust_url FIXME: I should be called distrust_url
1123 * Description : Calls is_untrusted_url to determine if the URL is trusted
1124 * and if not, returns a HTTP 403 response with a reject message.
1127 * 1 : csp = Current client state (buffers, headers, etc...)
1129 * Returns : NULL => trusted, else http_response.
1131 *********************************************************************/
1132 struct http_response *trust_url(struct client_state *csp)
1134 struct http_response *rsp;
1135 struct map * exports;
1136 char buf[BUFFER_SIZE];
1138 struct url_spec **tl;
1143 * Don't bother to work on trusted URLs
1145 if (!is_untrusted_url(csp))
1151 * Else, prepare a response:
1153 if (NULL == (rsp = alloc_http_response()))
1155 return cgi_error_memory();
1158 rsp->status = strdup("403 Request blocked by Privoxy");
1159 exports = default_exports(csp, NULL);
1160 if (exports == NULL || rsp->status == NULL)
1162 free_http_response(rsp);
1163 return cgi_error_memory();
1167 * Export the protocol, host, port, and referrer information
1169 err = map(exports, "hostport", 1, csp->http->hostport, 1);
1170 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1171 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1173 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1175 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1179 if (!err) err = map(exports, "referrer", 1, "none set", 1);
1185 free_http_response(rsp);
1186 return cgi_error_memory();
1190 * Export the trust list
1193 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1195 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
1196 string_append(&p, buf);
1198 err = map(exports, "trusted-referrers", 1, p, 0);
1203 free_http_response(rsp);
1204 return cgi_error_memory();
1208 * Export the trust info, if available
1210 if (csp->config->trust_info->first)
1212 struct list_entry *l;
1215 for (l = csp->config->trust_info->first; l ; l = l->next)
1217 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
1218 string_append(&p, buf);
1220 err = map(exports, "trust-info", 1, p, 0);
1224 err = map_block_killer(exports, "have-trust-info");
1230 free_http_response(rsp);
1231 return cgi_error_memory();
1235 * Export the force conditional block killer if
1237 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1238 * - Privoxy is configured to enforce blocks, or
1239 * - it's a CONNECT request and enforcing wouldn't work anyway.
1241 #ifdef FEATURE_FORCE_LOAD
1242 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1243 || (0 == strcmpic(csp->http->gpc, "connect")))
1245 err = map_block_killer(exports, "force-support");
1249 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1251 #else /* ifndef FEATURE_FORCE_LOAD */
1252 err = map_block_killer(exports, "force-support");
1253 #endif /* ndef FEATURE_FORCE_LOAD */
1258 free_http_response(rsp);
1259 return cgi_error_memory();
1263 * Build the response
1265 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1268 free_http_response(rsp);
1269 return cgi_error_memory();
1271 rsp->reason = RSP_REASON_UNTRUSTED;
1273 return finish_http_response(csp, rsp);
1275 #endif /* def FEATURE_TRUST */
1278 /*********************************************************************
1280 * Function : compile_dynamic_pcrs_job_list
1282 * Description : Compiles a dynamic pcrs job list (one with variables
1283 * resolved at request time)
1286 * 1 : csp = Current client state (buffers, headers, etc...)
1287 * 2 : b = The filter list to compile
1289 * Returns : NULL in case of errors, otherwise the
1292 *********************************************************************/
1293 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
1295 struct list_entry *pattern;
1296 pcrs_job *job_list = NULL;
1297 pcrs_job *dummy = NULL;
1298 pcrs_job *lastjob = NULL;
1301 const struct pcrs_variable variables[] =
1303 {"url", csp->http->url, 1},
1304 {"path", csp->http->path, 1},
1305 {"host", csp->http->host, 1},
1306 {"origin", csp->ip_addr_str, 1},
1310 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
1312 assert(pattern->str != NULL);
1314 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
1318 log_error(LOG_LEVEL_ERROR,
1319 "Adding filter job \'%s\' to dynamic filter %s failed: %s",
1320 pattern->str, b->name, pcrs_strerror(error));
1325 if (error == PCRS_WARN_TRUNCATION)
1327 log_error(LOG_LEVEL_ERROR,
1328 "At least one of the variables in \'%s\' had to "
1329 "be truncated before compilation", pattern->str);
1331 if (job_list == NULL)
1337 lastjob->next = dummy;
1347 /*********************************************************************
1349 * Function : rewrite_url
1351 * Description : Rewrites a URL with a single pcrs command
1352 * and returns the result if it differs from the
1353 * original and isn't obviously invalid.
1356 * 1 : old_url = URL to rewrite.
1357 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1360 * Returns : NULL if the pcrs_command didn't change the url, or
1361 * the result of the modification.
1363 *********************************************************************/
1364 char *rewrite_url(char *old_url, const char *pcrs_command)
1366 char *new_url = NULL;
1370 assert(pcrs_command);
1372 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1376 log_error(LOG_LEVEL_REDIRECTS,
1377 "pcrs command \"%s\" didn't change \"%s\".",
1378 pcrs_command, old_url);
1383 log_error(LOG_LEVEL_REDIRECTS,
1384 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1385 pcrs_command, old_url, pcrs_strerror(hits));
1388 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1390 log_error(LOG_LEVEL_ERROR,
1391 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1392 "but the result doesn't look like a valid URL and will be ignored.",
1393 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1398 log_error(LOG_LEVEL_REDIRECTS,
1399 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1400 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1408 #ifdef FEATURE_FAST_REDIRECTS
1409 /*********************************************************************
1411 * Function : get_last_url
1413 * Description : Search for the last URL inside a string.
1414 * If the string already is a URL, it will
1415 * be the first URL found.
1418 * 1 : subject = the string to check
1419 * 2 : redirect_mode = +fast-redirect{} mode
1421 * Returns : NULL if no URL was found, or
1422 * the last URL found.
1424 *********************************************************************/
1425 char *get_last_url(char *subject, const char *redirect_mode)
1427 char *new_url = NULL;
1431 assert(redirect_mode);
1433 subject = strdup(subject);
1434 if (subject == NULL)
1436 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1440 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1442 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1443 new_url = url_decode(subject);
1444 if (new_url != NULL)
1451 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1455 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1458 * Find the last URL encoded in the request
1461 while ((tmp = strstr(tmp, "http://")) != NULL)
1465 tmp = (new_url != NULL) ? new_url : subject;
1466 while ((tmp = strstr(tmp, "https://")) != NULL)
1471 if ((new_url != NULL)
1472 && ( (new_url != subject)
1473 || (0 == strncmpic(subject, "http://", 7))
1474 || (0 == strncmpic(subject, "https://", 8))
1478 * Return new URL if we found a redirect
1479 * or if the subject already was a URL.
1481 * The second case makes sure that we can
1482 * chain get_last_url after another redirection check
1483 * (like rewrite_url) without losing earlier redirects.
1485 new_url = strdup(new_url);
1494 #endif /* def FEATURE_FAST_REDIRECTS */
1497 /*********************************************************************
1499 * Function : redirect_url
1501 * Description : Checks if Privoxy should answer the request with
1502 * a HTTP redirect and generates the redirect if
1506 * 1 : csp = Current client state (buffers, headers, etc...)
1508 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1510 *********************************************************************/
1511 struct http_response *redirect_url(struct client_state *csp)
1513 struct http_response *rsp;
1514 #ifdef FEATURE_FAST_REDIRECTS
1516 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1517 * as compile-time option? The user can easily disable
1518 * it in his action file.
1520 char * redirect_mode;
1521 #endif /* def FEATURE_FAST_REDIRECTS */
1522 char *old_url = NULL;
1523 char *new_url = NULL;
1524 char *redirection_string;
1526 if ((csp->action->flags & ACTION_REDIRECT))
1528 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1531 * If the redirection string begins with 's',
1532 * assume it's a pcrs command, otherwise treat it as
1533 * properly formatted URL and use it for the redirection
1536 * According to RFC 2616 section 14.30 the URL
1537 * has to be absolute and if the user tries:
1538 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1539 * she would get undefined results anyway.
1543 if (*redirection_string == 's')
1545 old_url = csp->http->url;
1546 new_url = rewrite_url(old_url, redirection_string);
1550 log_error(LOG_LEVEL_REDIRECTS,
1551 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1552 redirection_string);
1553 new_url = strdup(redirection_string);
1557 #ifdef FEATURE_FAST_REDIRECTS
1558 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1560 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1563 * If it exists, use the previously rewritten URL as input
1564 * otherwise just use the old path.
1566 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1567 new_url = get_last_url(old_url, redirect_mode);
1572 * Disable redirect checkers, so that they
1573 * will be only run more than once if the user
1574 * also enables them through tags.
1576 * From a performance point of view
1577 * it doesn't matter, but the duplicated
1578 * log messages are annoying.
1580 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1581 #endif /* def FEATURE_FAST_REDIRECTS */
1582 csp->action->flags &= ~ACTION_REDIRECT;
1584 /* Did any redirect action trigger? */
1587 if (0 == strcmpic(new_url, csp->http->url))
1589 log_error(LOG_LEVEL_ERROR,
1590 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1591 csp->http->url, new_url);
1596 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1598 if (NULL == (rsp = alloc_http_response()))
1601 return cgi_error_memory();
1604 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1605 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1608 free_http_response(rsp);
1609 return cgi_error_memory();
1611 rsp->reason = RSP_REASON_REDIRECTED;
1614 return finish_http_response(csp, rsp);
1618 /* Only reached if no redirect is required */
1624 #ifdef FEATURE_IMAGE_BLOCKING
1625 /*********************************************************************
1627 * Function : is_imageurl
1629 * Description : Given a URL, decide whether it is an image or not,
1630 * using either the info from a previous +image action
1631 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1632 * is MSIE and not on a Mac, tell from the browser's accept
1636 * 1 : csp = Current client state (buffers, headers, etc...)
1638 * Returns : True (nonzero) if URL is an image, false (0)
1641 *********************************************************************/
1642 int is_imageurl(const struct client_state *csp)
1644 #ifdef FEATURE_IMAGE_DETECT_MSIE
1647 tmp = get_header_value(csp->headers, "User-Agent:");
1648 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1650 tmp = get_header_value(csp->headers, "Accept:");
1651 if (tmp && strstr(tmp, "image/gif"))
1653 /* Client will accept HTML. If this seems counterintuitive,
1663 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1665 return ((csp->action->flags & ACTION_IMAGE) != 0);
1668 #endif /* def FEATURE_IMAGE_BLOCKING */
1671 #ifdef FEATURE_TRUST
1672 /*********************************************************************
1674 * Function : is_untrusted_url
1676 * Description : Should we "distrust" this URL (and block it)?
1678 * Yes if it matches a line in the trustfile, or if the
1679 * referrer matches a line starting with "+" in the
1684 * 1 : csp = Current client state (buffers, headers, etc...)
1686 * Returns : 0 => trusted, 1 => untrusted
1688 *********************************************************************/
1689 int is_untrusted_url(const struct client_state *csp)
1691 struct file_list *fl;
1692 struct block_spec *b;
1693 struct url_spec **trusted_url;
1694 struct http_request rhttp[1];
1695 const char * referer;
1699 * If we don't have a trustlist, we trust everybody
1701 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1706 memset(rhttp, '\0', sizeof(*rhttp));
1709 * Do we trust the request URL itself?
1711 for (b = b->next; b ; b = b->next)
1713 if (url_match(b->url, csp->http))
1719 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1721 /* no referrer was supplied */
1727 * If not, do we maybe trust its referrer?
1729 err = parse_http_url(referer, rhttp, csp);
1735 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1737 if (url_match(*trusted_url, rhttp))
1739 /* if the URL's referrer is from a trusted referrer, then
1740 * add the target spec to the trustfile as an unblocked
1741 * domain and return 0 (which means it's OK).
1746 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1750 char * new_entry = strdup("~");
1752 string_append(&new_entry, csp->http->hostport);
1754 path = csp->http->path;
1755 if ( (path[0] == '/')
1757 && ((path_end = strchr(path + 2, '/')) != NULL))
1759 /* since this path points into a user's home space
1760 * be sure to include this spec in the trustfile.
1762 int path_len = path_end - path; /* save offset */
1763 path = strdup(path); /* Copy string */
1766 path_end = path + path_len; /* regenerate ptr to new buffer */
1767 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1769 string_join(&new_entry, path);
1773 * Give a reason for generating this entry.
1775 string_append(&new_entry, " # Trusted referrer was: ");
1776 string_append(&new_entry, referer);
1778 if (new_entry != NULL)
1780 if (-1 == fprintf(fp, "%s\n", new_entry))
1782 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1783 new_entry, csp->config->trustfile);
1789 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1790 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1797 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1798 csp->http->hostport, csp->config->trustfile);
1806 #endif /* def FEATURE_TRUST */
1809 /*********************************************************************
1811 * Function : pcrs_filter_response
1813 * Description : Execute all text substitutions from all applying
1814 * +filter actions on the text buffer that's been
1815 * accumulated in csp->iob->buf.
1818 * 1 : csp = Current client state (buffers, headers, etc...)
1820 * Returns : a pointer to the (newly allocated) modified buffer.
1821 * or NULL if there were no hits or something went wrong
1823 *********************************************************************/
1824 static char *pcrs_filter_response(struct client_state *csp)
1827 size_t size, prev_size;
1833 struct file_list *fl;
1834 struct re_filterfile_spec *b;
1835 struct list_entry *filtername;
1837 int i, found_filters = 0;
1842 if (csp->iob->cur >= csp->iob->eod)
1848 * Need to check the set of re_filterfiles...
1850 for (i = 0; i < MAX_AF_FILES; i++)
1863 if (0 == found_filters)
1865 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1866 "content filtering enabled, but no content filters available.");
1870 size = (size_t)(csp->iob->eod - csp->iob->cur);
1871 old = csp->iob->cur;
1873 for (i = 0; i < MAX_AF_FILES; i++)
1876 if ((NULL == fl) || (NULL == fl->f))
1879 * Either there are no filter files
1880 * left, or this filter file just
1881 * contains no valid filters.
1883 * Continue to be sure we don't miss
1884 * valid filter files that are chained
1885 * after empty or invalid ones.
1890 * For all applying +filter actions, look if a filter by that
1891 * name exists and if yes, execute it's pcrs_joblist on the
1894 for (b = fl->f; b; b = b->next)
1896 if (b->type != FT_CONTENT_FILTER)
1898 /* Skip header filters */
1902 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1903 filtername ; filtername = filtername->next)
1905 if (strcmp(b->name, filtername->str) == 0)
1907 int current_hits = 0; /* Number of hits caused by this filter */
1908 int job_number = 0; /* Which job we're currently executing */
1909 int job_hits = 0; /* How many hits the current job caused */
1910 pcrs_job *joblist = b->joblist;
1912 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1914 if (NULL == joblist)
1916 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1921 /* Apply all jobs from the joblist */
1922 for (job = joblist; NULL != job; job = job->next)
1925 job_hits = pcrs_execute(job, old, size, &new, &size);
1930 * That went well. Continue filtering
1931 * and use the result of this job as
1932 * input for the next one.
1934 current_hits += job_hits;
1935 if (old != csp->iob->cur)
1944 * This job caused an unexpected error. Inform the user
1945 * and skip the rest of the jobs in this filter. We could
1946 * continue with the next job, but usually the jobs
1947 * depend on each other or are similar enough to
1948 * fail for the same reason.
1950 * At the moment our pcrs expects the error codes of pcre 3.4,
1951 * but newer pcre versions can return additional error codes.
1952 * As a result pcrs_strerror()'s error message might be
1953 * "Unknown error ...", therefore we print the numerical value
1956 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1957 * should we use LOG_LEVEL_RE_FILTER instead?
1959 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1960 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1965 if (b->dynamic) pcrs_free_joblist(joblist);
1967 log_error(LOG_LEVEL_RE_FILTER,
1968 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1969 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1971 hits += current_hits;
1978 * If there were no hits, destroy our copy and let
1979 * chat() use the original in csp->iob
1987 csp->flags |= CSP_FLAG_MODIFIED;
1988 csp->content_length = size;
1996 /*********************************************************************
1998 * Function : gif_deanimate_response
2000 * Description : Deanimate the GIF image that has been accumulated in
2001 * csp->iob->buf, set csp->content_length to the modified
2002 * size and raise the CSP_FLAG_MODIFIED flag.
2005 * 1 : csp = Current client state (buffers, headers, etc...)
2007 * Returns : a pointer to the (newly allocated) modified buffer.
2008 * or NULL in case something went wrong.
2010 *********************************************************************/
2011 static char *gif_deanimate_response(struct client_state *csp)
2013 struct binbuffer *in, *out;
2017 size = (size_t)(csp->iob->eod - csp->iob->cur);
2019 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
2020 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
2022 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
2026 in->buffer = csp->iob->cur;
2029 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
2031 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
2038 if ((int)size == out->offset)
2040 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
2044 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
2046 csp->content_length = out->offset;
2047 csp->flags |= CSP_FLAG_MODIFIED;
2057 /*********************************************************************
2059 * Function : jpeg_inspect_response
2064 * 1 : csp = Current client state (buffers, headers, etc...)
2066 * Returns : a pointer to the (newly allocated) modified buffer
2067 * or NULL in case something went wrong.
2069 *********************************************************************/
2070 static char *jpeg_inspect_response(struct client_state *csp)
2072 struct binbuffer *in = NULL;
2073 struct binbuffer *out = NULL;
2077 size = (size_t)(csp->iob->eod - csp->iob->cur);
2079 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
2081 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
2085 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
2087 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
2091 in->buffer = csp->iob->cur;
2095 * Calling jpeg_inspect has the side-effect of creating and
2096 * modifying the image buffer of "out" directly.
2098 if (jpeg_inspect(in, out))
2100 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
2108 csp->content_length = out->offset;
2109 csp->flags |= CSP_FLAG_MODIFIED;
2119 /*********************************************************************
2121 * Function : get_filter_function
2123 * Description : Decides which content filter function has
2124 * to be applied (if any).
2126 * XXX: Doesn't handle filter_popups()
2127 * because of the different prototype. Probably
2128 * we should ditch filter_popups() anyway, it's
2129 * even less reliable than popup blocking based
2133 * 1 : csp = Current client state (buffers, headers, etc...)
2135 * Returns : The content filter function to run, or
2136 * NULL if no content filter is active
2138 *********************************************************************/
2139 filter_function_ptr get_filter_function(struct client_state *csp)
2141 filter_function_ptr filter_function = NULL;
2144 * Are we enabling text mode by force?
2146 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2149 * Do we really have to?
2151 if (csp->content_type & CT_TEXT)
2153 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2157 csp->content_type |= CT_TEXT;
2158 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2162 if (!(csp->content_type & CT_DECLARED))
2165 * The server didn't bother to declare a MIME-Type.
2166 * Assume it's text that can be filtered.
2168 * This also regulary happens with 304 responses,
2169 * therefore logging anything here would cause
2172 csp->content_type |= CT_TEXT;
2176 * Choose the applying filter function based on
2177 * the content type and action settings.
2179 if ((csp->content_type & CT_TEXT) &&
2180 (csp->rlist != NULL) &&
2181 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2183 filter_function = pcrs_filter_response;
2185 else if ((csp->content_type & CT_GIF) &&
2186 (csp->action->flags & ACTION_DEANIMATE))
2188 filter_function = gif_deanimate_response;
2190 else if ((csp->content_type & CT_JPEG) &&
2191 (csp->action->flags & ACTION_JPEG_INSPECT))
2193 filter_function = jpeg_inspect_response;
2196 return filter_function;
2200 /*********************************************************************
2202 * Function : remove_chunked_transfer_coding
2204 * Description : In-situ remove the "chunked" transfer coding as defined
2205 * in rfc2616 from a buffer.
2208 * 1 : buffer = Pointer to the text buffer
2209 * 2 : size = In: Number of bytes to be processed,
2210 * Out: Number of bytes after de-chunking.
2211 * (undefined in case of errors)
2213 * Returns : JB_ERR_OK for success,
2214 * JB_ERR_PARSE otherwise
2216 *********************************************************************/
2217 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2220 unsigned int chunksize = 0;
2221 char *from_p, *to_p;
2224 from_p = to_p = buffer;
2226 if (sscanf(buffer, "%x", &chunksize) != 1)
2228 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2229 return JB_ERR_PARSE;
2232 while (chunksize > 0)
2234 if (NULL == (from_p = strstr(from_p, "\r\n")))
2236 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2237 return JB_ERR_PARSE;
2240 if ((newsize += chunksize) >= *size)
2242 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
2243 return JB_ERR_PARSE;
2247 memmove(to_p, from_p, (size_t) chunksize);
2248 to_p = buffer + newsize;
2249 from_p += chunksize + 2;
2251 if (sscanf(from_p, "%x", &chunksize) != 1)
2253 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2258 /* XXX: Should get its own loglevel. */
2259 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
2268 /*********************************************************************
2270 * Function : prepare_for_filtering
2272 * Description : If necessary, de-chunks and decompresses
2273 * the content so it can get filterd.
2276 * 1 : csp = Current client state (buffers, headers, etc...)
2278 * Returns : JB_ERR_OK for success,
2279 * JB_ERR_PARSE otherwise
2281 *********************************************************************/
2282 static jb_err prepare_for_filtering(struct client_state *csp)
2284 jb_err err = JB_ERR_OK;
2287 * If the body has a "chunked" transfer-encoding,
2288 * get rid of it, adjusting size and iob->eod
2290 if (csp->flags & CSP_FLAG_CHUNKED)
2292 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2294 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2295 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2296 if (JB_ERR_OK == err)
2298 csp->iob->eod = csp->iob->cur + size;
2299 csp->flags |= CSP_FLAG_MODIFIED;
2303 return JB_ERR_PARSE;
2309 * If the body has a supported transfer-encoding,
2310 * decompress it, adjusting size and iob->eod.
2312 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
2314 if (0 == csp->iob->eod - csp->iob->cur)
2316 /* Nothing left after de-chunking. */
2320 err = decompress_iob(csp);
2322 if (JB_ERR_OK == err)
2324 csp->flags |= CSP_FLAG_MODIFIED;
2325 csp->content_type &= ~CT_TABOO;
2330 * Unset CT_GZIP and CT_DEFLATE to remember not
2331 * to modify the Content-Encoding header later.
2333 csp->content_type &= ~CT_GZIP;
2334 csp->content_type &= ~CT_DEFLATE;
2343 /*********************************************************************
2345 * Function : execute_content_filter
2347 * Description : Executes a given content filter.
2350 * 1 : csp = Current client state (buffers, headers, etc...)
2351 * 2 : content_filter = The filter function to execute
2353 * Returns : Pointer to the modified buffer, or
2354 * NULL if filtering failed or wasn't necessary.
2356 *********************************************************************/
2357 char *execute_content_filter(struct client_state *csp, filter_function_ptr content_filter)
2359 if (0 == csp->iob->eod - csp->iob->cur)
2362 * No content (probably status code 301, 302 ...),
2363 * no filtering necessary.
2368 if (JB_ERR_OK != prepare_for_filtering(csp))
2371 * failed to de-chunk or decompress.
2376 if (0 == csp->iob->eod - csp->iob->cur)
2379 * Clown alarm: chunked and/or compressed nothing delivered.
2384 return ((*content_filter)(csp));
2388 /*********************************************************************
2390 * Function : get_url_actions
2392 * Description : Gets the actions for this URL.
2395 * 1 : csp = Current client state (buffers, headers, etc...)
2396 * 2 : http = http_request request for blocked URLs
2400 *********************************************************************/
2401 void get_url_actions(struct client_state *csp, struct http_request *http)
2403 struct file_list *fl;
2404 struct url_actions *b;
2407 init_current_action(csp->action);
2409 for (i = 0; i < MAX_AF_FILES; i++)
2411 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2416 apply_url_actions(csp->action, http, b);
2423 /*********************************************************************
2425 * Function : apply_url_actions
2427 * Description : Applies a list of URL actions.
2430 * 1 : action = Destination.
2431 * 2 : http = Current URL
2432 * 3 : b = list of URL actions to apply
2436 *********************************************************************/
2437 void apply_url_actions(struct current_action_spec *action,
2438 struct http_request *http,
2439 struct url_actions *b)
2443 /* Should never happen */
2447 for (b = b->next; NULL != b; b = b->next)
2449 if (url_match(b->url, http))
2451 merge_current_action(action, b->action);
2457 /*********************************************************************
2459 * Function : get_forward_override_settings
2461 * Description : Returns forward settings as specified with the
2462 * forward-override{} action. forward-override accepts
2463 * forward lines similar to the one used in the
2464 * configuration file, but without the URL pattern.
2470 * in the configuration file can be replaced with
2471 * the action section:
2473 * {+forward-override{forward .}}
2477 * 1 : csp = Current client state (buffers, headers, etc...)
2479 * Returns : Pointer to forwarding structure in case of success.
2480 * Invalid syntax is fatal.
2482 *********************************************************************/
2483 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2485 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2486 char forward_settings[BUFFER_SIZE];
2487 char *http_parent = NULL;
2488 /* variable names were chosen for consistency reasons. */
2489 struct forward_spec *fwd = NULL;
2493 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2494 /* Should be enforced by load_one_actions_file() */
2495 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2497 /* Create a copy ssplit can modify */
2498 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2500 if (NULL != csp->fwd)
2503 * XXX: Currently necessary to prevent memory
2504 * leaks when the show-url-info cgi page is visited.
2506 unload_forward_spec(csp->fwd);
2510 * allocate a new forward node, valid only for
2511 * the lifetime of this request. Save its location
2512 * in csp as well, so sweep() can free it later on.
2514 fwd = csp->fwd = zalloc(sizeof(*fwd));
2517 log_error(LOG_LEVEL_FATAL,
2518 "can't allocate memory for forward-override{%s}", forward_override_line);
2519 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2522 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2523 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2525 fwd->type = SOCKS_NONE;
2527 /* Parse the parent HTTP proxy host:port */
2528 http_parent = vec[1];
2531 else if (vec_count == 3)
2533 char *socks_proxy = NULL;
2535 if (!strcasecmp(vec[0], "forward-socks4"))
2537 fwd->type = SOCKS_4;
2538 socks_proxy = vec[1];
2540 else if (!strcasecmp(vec[0], "forward-socks4a"))
2542 fwd->type = SOCKS_4A;
2543 socks_proxy = vec[1];
2545 else if (!strcasecmp(vec[0], "forward-socks5"))
2547 fwd->type = SOCKS_5;
2548 socks_proxy = vec[1];
2551 if (NULL != socks_proxy)
2553 /* Parse the SOCKS proxy host[:port] */
2554 fwd->gateway_host = strdup(socks_proxy);
2556 if (NULL != (socks_proxy = strchr(fwd->gateway_host, ':')))
2558 *socks_proxy++ = '\0';
2559 fwd->gateway_port = strtol(socks_proxy, NULL, 0);
2562 if (fwd->gateway_port <= 0)
2564 fwd->gateway_port = 1080;
2567 http_parent = vec[2];
2571 if (NULL == http_parent)
2573 log_error(LOG_LEVEL_FATAL,
2574 "Invalid forward-override syntax in: %s", forward_override_line);
2575 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2578 /* Parse http forwarding settings */
2579 if (strcmp(http_parent, ".") != 0)
2581 fwd->forward_host = strdup(http_parent);
2583 if (NULL != (http_parent = strchr(fwd->forward_host, ':')))
2585 *http_parent++ = '\0';
2586 fwd->forward_port = strtol(http_parent, NULL, 0);
2589 if (fwd->forward_port <= 0)
2591 fwd->forward_port = 8000;
2595 assert (NULL != fwd);
2597 log_error(LOG_LEVEL_CONNECT,
2598 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2604 /*********************************************************************
2606 * Function : forward_url
2608 * Description : Should we forward this to another proxy?
2611 * 1 : csp = Current client state (buffers, headers, etc...)
2612 * 2 : http = http_request request for current URL
2614 * Returns : Pointer to forwarding information.
2616 *********************************************************************/
2617 const struct forward_spec *forward_url(struct client_state *csp,
2618 const struct http_request *http)
2620 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2621 struct forward_spec *fwd = csp->config->forward;
2623 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2625 return get_forward_override_settings(csp);
2635 if (url_match(fwd->url, http))
2646 /*********************************************************************
2648 * Function : direct_response
2650 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2651 * request and if so, return a HTTP 501 to the client.
2653 * FIXME: I have a stupid name and I should handle the
2654 * requests properly. Still, what we do here is rfc-
2655 * compliant, whereas ignoring or forwarding are not.
2658 * 1 : csp = Current client state (buffers, headers, etc...)
2660 * Returns : http_response if , NULL if nonmatch or handler fail
2662 *********************************************************************/
2663 struct http_response *direct_response(struct client_state *csp)
2665 struct http_response *rsp;
2666 struct list_entry *p;
2668 if ((0 == strcmpic(csp->http->gpc, "trace"))
2669 || (0 == strcmpic(csp->http->gpc, "options")))
2671 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2673 if (!strncmpic("Max-Forwards:", p->str, 13))
2675 unsigned int max_forwards;
2678 * If it's a Max-Forwards value of zero,
2679 * we have to intercept the request.
2681 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2684 * FIXME: We could handle at least TRACE here,
2685 * but that would require a verbatim copy of
2686 * the request which we don't have anymore
2688 log_error(LOG_LEVEL_HEADER,
2689 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2692 /* Get mem for response or fail*/
2693 if (NULL == (rsp = alloc_http_response()))
2695 return cgi_error_memory();
2698 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2700 free_http_response(rsp);
2701 return cgi_error_memory();
2705 rsp->reason = RSP_REASON_UNSUPPORTED;
2707 return(finish_http_response(csp, rsp));
2716 /*********************************************************************
2718 * Function : content_filters_enabled
2720 * Description : Checks whether there are any content filters
2721 * enabled for the current request.
2724 * 1 : csp = Current client state (buffers, headers, etc...)
2726 * Returns : TRUE for yes, FALSE otherwise
2728 *********************************************************************/
2729 inline int content_filters_enabled(const struct client_state *csp)
2731 return (((csp->rlist != NULL) &&
2732 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]))) ||
2733 (csp->action->flags & (ACTION_DEANIMATE|ACTION_JPEG_INSPECT|ACTION_NO_POPUPS)));