1 const char filters_rcs[] = "$Id: filters.c,v 1.92 2007/09/28 16:38:55 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.92 2007/09/28 16:38:55 fabiankeil
44 * - Execute content filters through execute_content_filter().
45 * - Add prepare_for_filtering() so filter functions don't have to
46 * care about de-chunking and decompression. As a side effect this enables
47 * decompression for gif_deanimate_response() and jpeg_inspect_response().
48 * - Change remove_chunked_transfer_coding()'s return type to jb_err.
49 * Some clowns feel like chunking empty responses in which case
50 * (size == 0) is valid but previously would be interpreted as error.
52 * Revision 1.91 2007/09/02 15:31:20 fabiankeil
53 * Move match_portlist() from filter.c to urlmatch.c.
54 * It's used for url matching, not for filtering.
56 * Revision 1.90 2007/09/02 12:44:17 fabiankeil
57 * Remove newline at the end of a log_error() message.
59 * Revision 1.89 2007/08/05 13:42:23 fabiankeil
60 * #1763173 from Stefan Huehner: declare some more functions static.
62 * Revision 1.88 2007/06/01 16:41:11 fabiankeil
63 * Add forward-override{} to change the forwarding settings through
64 * action sections. This is mainly interesting to forward different
65 * clients differently (for example based on User-Agent or request
68 * Revision 1.87 2007/04/30 15:53:10 fabiankeil
69 * Make sure filters with dynamic jobs actually use them.
71 * Revision 1.86 2007/04/30 15:03:28 fabiankeil
72 * - Introduce dynamic pcrs jobs that can resolve variables.
73 * - Don't run redirect functions more than once,
74 * unless they are activated more than once.
76 * Revision 1.85 2007/03/21 12:24:47 fabiankeil
77 * - Log the content size after decompression in decompress_iob()
78 * instead of pcrs_filter_response().
80 * Revision 1.84 2007/03/20 15:16:34 fabiankeil
81 * Use dedicated header filter actions instead of abusing "filter".
82 * Replace "filter-client-headers" and "filter-client-headers"
83 * with "server-header-filter" and "client-header-filter".
85 * Revision 1.83 2007/03/17 15:20:05 fabiankeil
86 * New config option: enforce-blocks.
88 * Revision 1.82 2007/03/13 11:28:43 fabiankeil
89 * - Fix port handling in acl_addr() and use a temporary acl spec
90 * copy so error messages don't contain a truncated version.
91 * - Log size of iob before and after decompression.
93 * Revision 1.81 2007/03/05 14:40:53 fabiankeil
94 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
95 * - Hide the "Go there anyway" link for blocked CONNECT
96 * requests where going there anyway doesn't work anyway.
98 * Revision 1.80 2007/02/07 10:55:20 fabiankeil
99 * - Save the reason for generating http_responses.
100 * - Block (+block) with status code 403 instead of 404.
101 * - Use a different kludge to remember a failed decompression.
103 * Revision 1.79 2007/01/31 16:21:38 fabiankeil
104 * Search for Max-Forwards headers case-insensitive,
105 * don't generate the "501 unsupported" message for invalid
106 * Max-Forwards values and don't increase negative ones.
108 * Revision 1.78 2007/01/28 13:41:18 fabiankeil
109 * - Add HEAD support to finish_http_response.
110 * - Add error favicon to internal HTML error messages.
112 * Revision 1.77 2007/01/12 15:36:44 fabiankeil
113 * Mark *csp as immutable for is_untrusted_url()
114 * and is_imageurl(). Closes FR 1237736.
116 * Revision 1.76 2007/01/01 19:36:37 fabiankeil
117 * Integrate a modified version of Wil Mahan's
118 * zlib patch (PR #895531).
120 * Revision 1.75 2006/12/29 18:30:46 fabiankeil
121 * Fixed gcc43 conversion warnings,
122 * changed sprintf calls to snprintf.
124 * Revision 1.74 2006/12/24 17:37:38 fabiankeil
125 * Adjust comment in pcrs_filter_response()
126 * to recent pcrs changes. Hohoho.
128 * Revision 1.73 2006/12/23 16:01:02 fabiankeil
129 * Don't crash if pcre returns an error code
130 * that pcrs didn't expect. Fixes BR 1621173.
132 * Revision 1.72 2006/12/22 18:52:53 fabiankeil
133 * Modified is_untrusted_url to complain in case of
134 * write errors and to give a reason when adding new
135 * entries to the trustfile. Closes FR 1097611.
137 * Revision 1.71 2006/12/22 14:24:52 fabiankeil
138 * Skip empty filter files in pcrs_filter_response,
139 * but don't ignore the ones that come afterwards.
140 * Fixes parts of BR 1619208.
142 * Revision 1.70 2006/12/09 13:33:15 fabiankeil
143 * Added some sanity checks for get_last_url().
144 * Fixed possible segfault caused by my last commit.
146 * Revision 1.69 2006/12/08 12:39:13 fabiankeil
147 * Let get_last_url() catch https URLs as well.
149 * Revision 1.68 2006/12/05 14:45:48 fabiankeil
150 * Make sure get_last_url() behaves like advertised
151 * and fast-redirects{} can be combined with redirect{}.
153 * Revision 1.67 2006/11/28 15:19:43 fabiankeil
154 * Implemented +redirect{s@foo@bar@} to generate
155 * a redirect based on a rewritten version of the
158 * Revision 1.66 2006/09/23 13:26:38 roro
159 * Replace TABs by spaces in source code.
161 * Revision 1.65 2006/09/21 12:54:43 fabiankeil
162 * Fix +redirect{}. Didn't work with -fast-redirects.
164 * Revision 1.64 2006/08/31 10:55:49 fabiankeil
165 * Block requests for untrusted URLs with status
166 * code 403 instead of 200.
168 * Revision 1.63 2006/08/31 10:11:28 fabiankeil
169 * Don't free p which is still in use and will be later
170 * freed by free_map(). Don't claim the referrer is unknown
171 * when the client didn't set one.
173 * Revision 1.62 2006/08/14 00:27:47 david__schmidt
174 * Feature request 595948: Re-Filter logging in single line
176 * Revision 1.61 2006/08/03 02:46:41 david__schmidt
177 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
179 * Revision 1.60 2006/07/18 14:48:46 david__schmidt
180 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
181 * with what was really the latest development (the v_3_0_branch branch)
183 * Revision 1.58.2.9 2006/01/29 23:10:56 david__schmidt
184 * Multiple filter file support
186 * Revision 1.58.2.8 2005/05/07 21:50:55 david__schmidt
187 * A few memory leaks plugged (mostly on error paths)
189 * Revision 1.58.2.7 2004/10/03 12:53:32 david__schmidt
190 * Add the ability to check jpeg images for invalid
191 * lengths of comment blocks. Defensive strategy
192 * against the exploit:
193 * Microsoft Security Bulletin MS04-028
194 * Buffer Overrun in JPEG Processing (GDI+) Could
195 * Allow Code Execution (833987)
196 * Enabled with +inspect-jpegs in actions files.
198 * Revision 1.58.2.6 2003/12/06 22:18:27 gliptak
199 * Correcting compile problem with FEATURE_IMAGE_BLOCKING
201 * Revision 1.58.2.5 2003/11/11 13:10:31 oes
202 * Fixed bug #839859: "See why" link URL now gets url-encoded.
204 * Revision 1.58.2.4 2003/02/28 12:52:45 oes
207 * Revision 1.58.2.3 2002/09/25 14:51:51 oes
208 * Added basic support for OPTIONS and TRACE HTTP methods:
209 * New function direct_response which handles OPTIONS and
210 * TRACE requests whose Max-Forwards header field is zero.
212 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
213 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
215 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
216 * - Bugfix: Executing a filters without jobs no longer results in
217 * turing off *all* filters.
218 * - Security fix: Malicious web servers can't cause a seg fault
219 * through bogus chunk sizes anymore
221 * Revision 1.58 2002/04/24 02:11:17 oes
222 * Jon's multiple AF patch: url_actions now evaluates rules
225 * Revision 1.57 2002/04/08 20:38:34 swa
228 * Revision 1.56 2002/04/05 15:51:24 oes
229 * - bugfix: error-pages now get correct request protocol
230 * - fix for invalid HTML in trust info
232 * Revision 1.55 2002/04/02 16:13:51 oes
233 * Fix: No "Go there anyway" for SSL
235 * Revision 1.54 2002/04/02 14:55:56 oes
236 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
238 * Revision 1.53 2002/03/26 22:29:54 swa
239 * we have a new homepage!
241 * Revision 1.52 2002/03/24 16:35:57 jongfoster
244 * Revision 1.51 2002/03/24 15:23:33 jongfoster
247 * Revision 1.50 2002/03/24 13:25:43 swa
248 * name change related issues
250 * Revision 1.49 2002/03/16 20:29:14 oes
253 * Revision 1.48 2002/03/13 20:25:34 oes
254 * Better logging for content filters
256 * Revision 1.47 2002/03/13 00:30:52 jongfoster
258 * Added option of always sending redirect for imageblock,
259 * currently disabled with #if 0.
261 * Revision 1.46 2002/03/12 01:42:49 oes
262 * Introduced modular filters
264 * Revision 1.45 2002/03/08 16:47:50 oes
265 * Added choice beween GIF and PNG built-in images
267 * Revision 1.44 2002/03/07 03:49:31 oes
268 * - Fixed compiler warnings etc
269 * - Changed built-in images from GIF to PNG
270 * (with regard to Unisys patent issue)
271 * - Added a 4x4 pattern PNG which is less intrusive
272 * than the logo but also clearly marks the deleted banners
274 * Revision 1.43 2002/01/22 23:51:59 jongfoster
275 * Replacing strsav() with the safer string_append().
277 * Adding missing html_encode() to error message generators. Where encoded
278 * and unencoded versions of a string were provided, removing the unencoded
281 * Revision 1.42 2002/01/17 21:00:32 jongfoster
282 * Moving all our URL and URL pattern parsing code to urlmatch.c.
284 * Using a single, simple url_match(pattern,url) function - rather than
285 * the 3-line match routine which was repeated all over the place.
287 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
289 * Using parse_http_url() to parse URLs without faking a HTTP
290 * request line for parse_http_request().
292 * Revision 1.41 2001/11/13 00:14:07 jongfoster
293 * Fixing stupid bug now I've figured out what || means.
294 * (It always returns 0 or 1, not one of it's paramaters.)
296 * Revision 1.40 2001/10/26 17:37:55 oes
297 * - Re-enabled Netscape 200/404 bug workaround in block_url():
298 * - Removed OS/2 special case
299 * - Made block_url() independant from sed() having been run
300 * - Made trust_url independant from sed() having been run
301 * - Made is_imageurl independant from sed() having been run.
302 * It now checks User-Agent: and Accept: by itself.
305 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
306 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
307 * threads to call select() simultaneously. So, it's time to do a real, live,
308 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
309 * (native). Both versions will work, but using __OS2__ offers multi-threading.
311 * Revision 1.38 2001/10/23 21:32:33 jongfoster
312 * Adding error-checking to selected functions
314 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
315 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
316 * filters.c. Added a FIXME in front of the offending code. I'll gladly
317 * put in a better/more robust fix for all parties if one is presented...
318 * It seems that just returning 200 instead of 404 would pretty much fix
319 * it for everyone, but I don't know all the history of the problem.
321 * Revision 1.36 2001/10/10 16:44:16 oes
322 * Added match_portlist function
324 * Revision 1.35 2001/10/07 15:41:23 oes
325 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
327 * New function remove_chunked_transfer_coding that strips chunked
328 * transfer coding to plain and is called by pcrs_filter_response
329 * and gif_deanimate_response if neccessary
331 * Improved handling of zero-change re_filter runs
333 * pcrs_filter_response and gif_deanimate_response now remove
334 * chunked transfer codeing before processing the body.
336 * Revision 1.34 2001/09/20 15:49:36 steudten
338 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
339 * See cgi.c fill_template().
341 * Revision 1.33 2001/09/16 17:05:14 jongfoster
342 * Removing unused #include showarg.h
344 * Revision 1.32 2001/09/16 13:21:27 jongfoster
345 * Changes to use new list functions.
347 * Revision 1.31 2001/09/16 11:38:02 jongfoster
348 * Splitting fill_template() into 2 functions:
349 * template_load() loads the file
350 * template_fill() performs the PCRS regexps.
351 * This is because the CGI edit interface has a "table row"
352 * template which is used many times in the page - this
353 * change means it's only loaded from disk once.
355 * Revision 1.30 2001/09/16 11:00:10 jongfoster
356 * New function alloc_http_response, for symmetry with free_http_response
358 * Revision 1.29 2001/09/13 23:32:40 jongfoster
359 * Moving image data to cgi.c rather than cgi.h
360 * Fixing a GPF under Win32 (and any other OS that protects global
361 * constants from being written to).
363 * Revision 1.28 2001/09/10 10:18:51 oes
364 * Silenced compiler warnings
366 * Revision 1.27 2001/08/05 16:06:20 jongfoster
367 * Modifiying "struct map" so that there are now separate header and
368 * "map_entry" structures. This means that functions which modify a
369 * map no longer need to return a pointer to the modified map.
370 * Also, it no longer reverses the order of the entries (which may be
371 * important with some advanced template substitutions).
373 * Revision 1.26 2001/07/30 22:08:36 jongfoster
374 * Tidying up #defines:
375 * - All feature #defines are now of the form FEATURE_xxx
376 * - Permanently turned off WIN_GUI_EDIT
377 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
379 * Revision 1.25 2001/07/26 10:09:46 oes
380 * Made browser detection a little less naive
382 * Revision 1.24 2001/07/25 17:22:51 oes
383 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
385 * Revision 1.23 2001/07/23 13:40:12 oes
386 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
388 * Revision 1.22 2001/07/18 12:29:34 oes
389 * - Made gif_deanimate_response respect
390 * csp->action->string[ACTION_STRING_DEANIMATE]
391 * - Logging cosmetics
393 * Revision 1.21 2001/07/13 13:59:53 oes
394 * - Introduced gif_deanimate_response which shares the
395 * generic content modification interface of pcrs_filter_response
396 * and acts as a wrapper to deanimate.c:gif_deanimate()
397 * - Renamed re_process_buffer to pcrs_filter_response
398 * - pcrs_filter_response now returns NULL on failiure
399 * - Removed all #ifdef PCRS
401 * Revision 1.20 2001/07/01 17:01:04 oes
402 * Added comments and missing return statement in is_untrusted_url()
404 * Revision 1.19 2001/06/29 21:45:41 oes
405 * Indentation, CRLF->LF, Tab-> Space
407 * Revision 1.18 2001/06/29 13:27:38 oes
408 * - Cleaned up, renamed and reorderd functions
409 * and improved comments
412 * - Ported to CGI platform. Now delivers
413 * http_response or NULL
414 * - Unified HTML and GIF generation (moved image detection
415 * and GIF generation here from jcc.c:chat())
416 * - Fixed HTTP status to:
417 * - 403 (Forbidden) for the "blocked" HTML message
418 * - 200 (OK) for GIF answers
419 * - 302 (Redirect) for redirect to GIF
422 * - Ported to CGI platform. Now delivers
423 * http_response or NULL
424 * - Separated detection of untrusted URL into
425 * (bool)is_untrusted_url
426 * - Added enforcement of untrusted requests
428 * - Moved redirect_url() from cgi.c to here
429 * and ported it to the CGI platform
431 * - Removed logentry from cancelled commit
433 * Revision 1.17 2001/06/09 10:55:28 jongfoster
434 * Changing BUFSIZ ==> BUFFER_SIZE
436 * Revision 1.16 2001/06/07 23:10:26 jongfoster
437 * Allowing unanchored domain patterns to back off and retry
438 * if they partially match. Optimized right-anchored patterns.
439 * Moving ACL and forward files into config file.
440 * Replacing struct gateway with struct forward_spec
442 * Revision 1.15 2001/06/03 19:12:00 oes
443 * extracted-CGI relevant stuff
445 * Revision 1.14 2001/06/01 10:30:55 oes
446 * Added optional left-anchoring to domaincmp
448 * Revision 1.13 2001/05/31 21:21:30 jongfoster
449 * Permissionsfile / actions file changes:
450 * - Changed "permission" to "action" throughout
451 * - changes to file format to allow string parameters
452 * - Moved helper functions to actions.c
454 * Revision 1.12 2001/05/31 17:35:20 oes
456 * - Enhanced domain part globbing with infix and prefix asterisk
457 * matching and optional unanchored operation
459 * Revision 1.11 2001/05/29 11:53:23 oes
460 * "See why" link added to "blocked" page
462 * Revision 1.10 2001/05/29 09:50:24 jongfoster
463 * Unified blocklist/imagelist/permissionslist.
464 * File format is still under discussion, but the internal changes
467 * Also modified interceptor behaviour:
468 * - We now intercept all URLs beginning with one of the following
469 * prefixes (and *only* these prefixes):
471 * * http://ijbswa.sf.net/config/
472 * * http://ijbswa.sourceforge.net/config/
473 * - New interceptors "home page" - go to http://i.j.b/ to see it.
474 * - Internal changes so that intercepted and fast redirect pages
475 * are not replaced with an image.
476 * - Interceptors now have the option to send a binary page direct
477 * to the client. (i.e. ijb-send-banner uses this)
478 * - Implemented show-url-info interceptor. (Which is why I needed
479 * the above interceptors changes - a typical URL is
480 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
481 * The previous mechanism would not have intercepted that, and
482 * if it had been intercepted then it then it would have replaced
485 * Revision 1.9 2001/05/27 22:17:04 oes
487 * - re_process_buffer no longer writes the modified buffer
488 * to the client, which was very ugly. It now returns the
489 * buffer, which it is then written by chat.
491 * - content_length now adjusts the Content-Length: header
492 * for modified documents rather than crunch()ing it.
493 * (Length info in csp->content_length, which is 0 for
494 * unmodified documents)
496 * - For this to work, sed() is called twice when filtering.
498 * Revision 1.8 2001/05/26 17:13:28 jongfoster
499 * Filled in a function comment.
501 * Revision 1.7 2001/05/26 15:26:15 jongfoster
502 * ACL feature now provides more security by immediately dropping
503 * connections from untrusted hosts.
505 * Revision 1.6 2001/05/26 00:28:36 jongfoster
506 * Automatic reloading of config file.
507 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
508 * Most of the global variables have been moved to a new
509 * struct configuration_spec, accessed through csp->config->globalname
510 * Most of the globals remaining are used by the Win32 GUI.
512 * Revision 1.5 2001/05/25 22:34:30 jongfoster
515 * Revision 1.4 2001/05/22 18:46:04 oes
517 * - Enabled filtering banners by size rather than URL
518 * by adding patterns that replace all standard banner
519 * sizes with the "Junkbuster" gif to the re_filterfile
521 * - Enabled filtering WebBugs by providing a pattern
522 * which kills all 1x1 images
524 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
525 * which is selected by the (nonstandard and therefore
526 * capital) letter 'U' in the option string.
527 * It causes the quantifiers to be ungreedy by default.
528 * Appending a ? turns back to greedy (!).
530 * - Added a new interceptor ijb-send-banner, which
531 * sends back the "Junkbuster" gif. Without imagelist or
532 * MSIE detection support, or if tinygif = 1, or the
533 * URL isn't recognized as an imageurl, a lame HTML
534 * explanation is sent instead.
536 * - Added new feature, which permits blocking remote
537 * script redirects and firing back a local redirect
539 * The feature is conditionally compiled, i.e. it
540 * can be disabled with --disable-fast-redirects,
541 * plus it must be activated by a "fast-redirects"
542 * line in the config file, has its own log level
543 * and of course wants to be displayed by show-proxy-args
544 * Note: Boy, all the #ifdefs in 1001 locations and
545 * all the fumbling with configure.in and acconfig.h
546 * were *way* more work than the feature itself :-(
548 * - Because a generic redirect template was needed for
549 * this, tinygif = 3 now uses the same.
551 * - Moved GIFs, and other static HTTP response templates
556 * - Removed some >400 CRs again (Jon, you really worked
559 * Revision 1.3 2001/05/20 16:44:47 jongfoster
560 * Removing last hardcoded Junkbusters.com URLs.
562 * Revision 1.2 2001/05/20 01:21:20 jongfoster
563 * Version 2.9.4 checkin.
564 * - Merged popupfile and cookiefile, and added control over PCRS
565 * filtering, in new "permissionsfile".
566 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
567 * file error you now get a message box (in the Win32 GUI) rather
568 * than the program exiting with no explanation.
569 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
571 * - Removed tabs from "config"
572 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
573 * - Bumped up version number.
575 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
576 * Initial import of version 2.9.3 source tree
579 *********************************************************************/
585 #include <sys/types.h>
594 #endif /* ndef __OS2__ */
595 #include <netinet/in.h>
597 #include <winsock2.h>
598 #endif /* ndef _WIN32 */
602 #endif /* def __OS2__ */
610 #include "jbsockets.h"
611 #include "miscutil.h"
615 #include "deanimate.h"
616 #include "urlmatch.h"
623 const char filters_h_rcs[] = FILTERS_H_VERSION;
625 /* Fix a problem with Solaris. There should be no effect on other
627 * Solaris's isspace() is a macro which uses it's argument directly
628 * as an array index. Therefore we need to make sure that high-bit
629 * characters generate +ve values, and ideally we also want to make
630 * the argument match the declared parameter type of "int".
632 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
634 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
635 static jb_err prepare_for_filtering(struct client_state *csp);
638 /*********************************************************************
640 * Function : block_acl
642 * Description : Block this request?
643 * Decide yes or no based on ACL file.
646 * 1 : dst = The proxy or gateway address this is going to.
647 * Or NULL to check all possible targets.
648 * 2 : csp = Current client state (buffers, headers, etc...)
649 * Also includes the client IP address.
651 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
653 *********************************************************************/
654 int block_acl(struct access_control_addr *dst, struct client_state *csp)
656 struct access_control_list *acl = csp->config->acl;
658 /* if not using an access control list, then permit the connection */
664 /* search the list */
667 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
671 /* Just want to check if they have any access */
672 if (acl->action == ACL_PERMIT)
677 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
678 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
680 if (acl->action == ACL_PERMIT)
698 /*********************************************************************
700 * Function : acl_addr
702 * Description : Called from `load_config' to parse an ACL address.
705 * 1 : aspec = String specifying ACL address.
706 * 2 : aca = struct access_control_addr to fill in.
708 * Returns : 0 => Ok, everything else is an error.
710 *********************************************************************/
711 int acl_addr(const char *aspec, struct access_control_addr *aca)
716 char *acl_spec = NULL;
722 * Use a temporary acl spec copy so we can log
723 * the unmodified original in case of parse errors.
725 acl_spec = strdup(aspec);
726 if (acl_spec == NULL)
728 /* XXX: This will be logged as parse error. */
732 if ((p = strchr(acl_spec, '/')) != NULL)
735 if (ijb_isdigit(*p) == 0)
740 masklength = atoi(p);
743 if ((masklength < 0) || (masklength > 32))
749 if ((p = strchr(acl_spec, ':')) != NULL)
754 port = strtol(p, &endptr, 10);
756 if (port <= 0 || port > 65535 || *endptr != '\0')
763 aca->port = (unsigned long)port;
765 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
768 if (aca->addr == INADDR_NONE)
770 /* XXX: This will be logged as parse error. */
774 /* build the netmask */
776 for (i=1; i <= masklength ; i++)
778 aca->mask |= (1 << (32 - i));
781 /* now mask off the host portion of the ip address
782 * (i.e. save on the network portion of the address).
784 aca->addr = aca->addr & aca->mask;
789 #endif /* def FEATURE_ACL */
792 /*********************************************************************
794 * Function : block_url
796 * Description : Called from `chat'. Check to see if we need to block this.
799 * 1 : csp = Current client state (buffers, headers, etc...)
801 * Returns : NULL => unblocked, else HTTP block response
803 *********************************************************************/
804 struct http_response *block_url(struct client_state *csp)
806 struct http_response *rsp;
807 const char *new_content_type = NULL;
810 * If it's not blocked, don't block it ;-)
812 if ((csp->action->flags & ACTION_BLOCK) == 0)
816 if (csp->action->flags & ACTION_REDIRECT)
818 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
821 * Else, prepare a response
823 if (NULL == (rsp = alloc_http_response()))
825 return cgi_error_memory();
829 * If it's an image-url, send back an image or redirect
830 * as specified by the relevant +image action
832 #ifdef FEATURE_IMAGE_BLOCKING
833 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
837 /* determine HOW images should be blocked */
838 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
840 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
842 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
844 #if 1 /* Two alternative strategies, use this one for now: */
846 /* and handle accordingly: */
847 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
849 rsp->status = strdup("403 Request blocked by Privoxy");
850 if (rsp->status == NULL)
852 free_http_response(rsp);
853 return cgi_error_memory();
855 rsp->body = bindup(image_pattern_data, image_pattern_length);
856 if (rsp->body == NULL)
858 free_http_response(rsp);
859 return cgi_error_memory();
861 rsp->content_length = image_pattern_length;
863 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
865 free_http_response(rsp);
866 return cgi_error_memory();
870 else if (0 == strcmpic(p, "blank"))
872 rsp->status = strdup("403 Request blocked by Privoxy");
873 if (rsp->status == NULL)
875 free_http_response(rsp);
876 return cgi_error_memory();
878 rsp->body = bindup(image_blank_data, image_blank_length);
879 if (rsp->body == NULL)
881 free_http_response(rsp);
882 return cgi_error_memory();
884 rsp->content_length = image_blank_length;
886 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
888 free_http_response(rsp);
889 return cgi_error_memory();
895 rsp->status = strdup("302 Local Redirect from Privoxy");
896 if (rsp->status == NULL)
898 free_http_response(rsp);
899 return cgi_error_memory();
902 if (enlist_unique_header(rsp->headers, "Location", p))
904 free_http_response(rsp);
905 return cgi_error_memory();
909 #else /* Following code is disabled for now */
911 /* and handle accordingly: */
912 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
914 p = CGI_PREFIX "send-banner?type=pattern";
916 else if (0 == strcmpic(p, "blank"))
918 p = CGI_PREFIX "send-banner?type=blank";
920 rsp->status = strdup("302 Local Redirect from Privoxy");
921 if (rsp->status == NULL)
923 free_http_response(rsp);
924 return cgi_error_memory();
927 if (enlist_unique_header(rsp->headers, "Location", p))
929 free_http_response(rsp);
930 return cgi_error_memory();
932 #endif /* Preceeding code is disabled for now */
934 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
937 * Send empty document.
939 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
942 rsp->body = strdup(" ");
943 rsp->content_length = 1;
945 rsp->status = strdup("403 Request blocked by Privoxy");
946 if (rsp->status == NULL)
948 free_http_response(rsp);
949 return cgi_error_memory();
951 if (new_content_type != 0)
953 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
954 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
956 free_http_response(rsp);
957 return cgi_error_memory();
962 #endif /* def FEATURE_IMAGE_BLOCKING */
965 * Else, generate an HTML "blocked" message:
969 struct map * exports;
973 * Workaround for stupid Netscape bug which prevents
974 * pages from being displayed if loading a referenced
975 * JavaScript or style sheet fails. So make it appear
976 * as if it succeeded.
978 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
979 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
980 && !strstr(p, "Gecko") /* save Mozilla, */
981 && !strstr(p, "compatible") /* MSIE */
982 && !strstr(p, "Opera")) /* and Opera. */
984 rsp->status = strdup("200 Request for blocked URL");
988 rsp->status = strdup("403 Request for blocked URL");
991 if (rsp->status == NULL)
993 free_http_response(rsp);
994 return cgi_error_memory();
997 exports = default_exports(csp, NULL);
1000 free_http_response(rsp);
1001 return cgi_error_memory();
1004 #ifdef FEATURE_FORCE_LOAD
1005 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1007 * Export the force conditional block killer if
1009 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1010 * - Privoxy is configured to enforce blocks, or
1011 * - it's a CONNECT request and enforcing wouldn't work anyway.
1013 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1014 || (0 == strcmpic(csp->http->gpc, "connect")))
1015 #endif /* ndef FEATURE_FORCE_LOAD */
1017 err = map_block_killer(exports, "force-support");
1020 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1021 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1022 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1023 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
1028 free_http_response(rsp);
1029 return cgi_error_memory();
1032 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
1035 free_http_response(rsp);
1036 return cgi_error_memory();
1039 rsp->reason = RSP_REASON_BLOCKED;
1041 return finish_http_response(csp, rsp);
1046 #ifdef FEATURE_TRUST
1047 /*********************************************************************
1049 * Function : trust_url FIXME: I should be called distrust_url
1051 * Description : Calls is_untrusted_url to determine if the URL is trusted
1052 * and if not, returns a HTTP 403 response with a reject message.
1055 * 1 : csp = Current client state (buffers, headers, etc...)
1057 * Returns : NULL => trusted, else http_response.
1059 *********************************************************************/
1060 struct http_response *trust_url(struct client_state *csp)
1062 struct http_response *rsp;
1063 struct map * exports;
1064 char buf[BUFFER_SIZE];
1066 struct url_spec **tl;
1071 * Don't bother to work on trusted URLs
1073 if (!is_untrusted_url(csp))
1079 * Else, prepare a response:
1081 if (NULL == (rsp = alloc_http_response()))
1083 return cgi_error_memory();
1086 rsp->status = strdup("403 Request blocked by Privoxy");
1087 exports = default_exports(csp, NULL);
1088 if (exports == NULL || rsp->status == NULL)
1090 free_http_response(rsp);
1091 return cgi_error_memory();
1095 * Export the protocol, host, port, and referrer information
1097 err = map(exports, "hostport", 1, csp->http->hostport, 1);
1098 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1099 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1101 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1103 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1107 if (!err) err = map(exports, "referrer", 1, "none set", 1);
1113 free_http_response(rsp);
1114 return cgi_error_memory();
1118 * Export the trust list
1121 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1123 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
1124 string_append(&p, buf);
1126 err = map(exports, "trusted-referrers", 1, p, 0);
1131 free_http_response(rsp);
1132 return cgi_error_memory();
1136 * Export the trust info, if available
1138 if (csp->config->trust_info->first)
1140 struct list_entry *l;
1143 for (l = csp->config->trust_info->first; l ; l = l->next)
1145 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
1146 string_append(&p, buf);
1148 err = map(exports, "trust-info", 1, p, 0);
1152 err = map_block_killer(exports, "have-trust-info");
1158 free_http_response(rsp);
1159 return cgi_error_memory();
1163 * Export the force conditional block killer if
1165 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
1166 * - Privoxy is configured to enforce blocks, or
1167 * - it's a CONNECT request and enforcing wouldn't work anyway.
1169 #ifdef FEATURE_FORCE_LOAD
1170 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1171 || (0 == strcmpic(csp->http->gpc, "connect")))
1173 err = map_block_killer(exports, "force-support");
1177 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1179 #else /* ifndef FEATURE_FORCE_LOAD */
1180 err = map_block_killer(exports, "force-support");
1181 #endif /* ndef FEATURE_FORCE_LOAD */
1186 free_http_response(rsp);
1187 return cgi_error_memory();
1191 * Build the response
1193 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1196 free_http_response(rsp);
1197 return cgi_error_memory();
1199 rsp->reason = RSP_REASON_UNTRUSTED;
1201 return finish_http_response(csp, rsp);
1203 #endif /* def FEATURE_TRUST */
1206 /*********************************************************************
1208 * Function : compile_dynamic_pcrs_job_list
1210 * Description : Compiles a dynamic pcrs job list (one with variables
1211 * resolved at request time)
1214 * 1 : csp = Current client state (buffers, headers, etc...)
1215 * 2 : b = The filter list to compile
1217 * Returns : NULL in case of errors, otherwise the
1220 *********************************************************************/
1221 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
1223 struct list_entry *pattern;
1224 pcrs_job *job_list = NULL;
1225 pcrs_job *dummy = NULL;
1226 pcrs_job *lastjob = NULL;
1229 const struct pcrs_variable variables[] =
1231 {"url", csp->http->url, 1},
1232 {"path", csp->http->path, 1},
1233 {"host", csp->http->host, 1},
1234 {"origin", csp->ip_addr_str, 1},
1238 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
1240 assert(pattern->str != NULL);
1242 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
1246 log_error(LOG_LEVEL_ERROR,
1247 "Adding filter job \'%s\' to dynamic filter %s failed: %s",
1248 pattern->str, b->name, pcrs_strerror(error));
1253 if (error == PCRS_WARN_TRUNCATION)
1255 log_error(LOG_LEVEL_ERROR,
1256 "At least one of the variables in \'%s\' had to "
1257 "be truncated before compilation", pattern->str);
1259 if (job_list == NULL)
1265 lastjob->next = dummy;
1275 /*********************************************************************
1277 * Function : rewrite_url
1279 * Description : Rewrites a URL with a single pcrs command
1280 * and returns the result if it differs from the
1281 * original and isn't obviously invalid.
1284 * 1 : old_url = URL to rewrite.
1285 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1288 * Returns : NULL if the pcrs_command didn't change the url, or
1289 * the result of the modification.
1291 *********************************************************************/
1292 char *rewrite_url(char *old_url, const char *pcrs_command)
1294 char *new_url = NULL;
1298 assert(pcrs_command);
1300 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1304 log_error(LOG_LEVEL_REDIRECTS,
1305 "pcrs command \"%s\" didn't change \"%s\".",
1306 pcrs_command, old_url);
1311 log_error(LOG_LEVEL_REDIRECTS,
1312 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1313 pcrs_command, old_url, pcrs_strerror(hits));
1316 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1318 log_error(LOG_LEVEL_ERROR,
1319 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1320 "but the result doesn't look like a valid URL and will be ignored.",
1321 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1326 log_error(LOG_LEVEL_REDIRECTS,
1327 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1328 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1336 #ifdef FEATURE_FAST_REDIRECTS
1337 /*********************************************************************
1339 * Function : get_last_url
1341 * Description : Search for the last URL inside a string.
1342 * If the string already is a URL, it will
1343 * be the first URL found.
1346 * 1 : subject = the string to check
1347 * 2 : redirect_mode = +fast-redirect{} mode
1349 * Returns : NULL if no URL was found, or
1350 * the last URL found.
1352 *********************************************************************/
1353 char *get_last_url(char *subject, const char *redirect_mode)
1355 char *new_url = NULL;
1359 assert(redirect_mode);
1361 subject = strdup(subject);
1362 if (subject == NULL)
1364 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1368 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1370 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1371 new_url = url_decode(subject);
1372 if (new_url != NULL)
1379 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1383 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1386 * Find the last URL encoded in the request
1389 while ((tmp = strstr(tmp, "http://")) != NULL)
1393 tmp = (new_url != NULL) ? new_url : subject;
1394 while ((tmp = strstr(tmp, "https://")) != NULL)
1399 if ((new_url != NULL)
1400 && ( (new_url != subject)
1401 || (0 == strncmpic(subject, "http://", 7))
1402 || (0 == strncmpic(subject, "https://", 8))
1406 * Return new URL if we found a redirect
1407 * or if the subject already was a URL.
1409 * The second case makes sure that we can
1410 * chain get_last_url after another redirection check
1411 * (like rewrite_url) without losing earlier redirects.
1413 new_url = strdup(new_url);
1422 #endif /* def FEATURE_FAST_REDIRECTS */
1425 /*********************************************************************
1427 * Function : redirect_url
1429 * Description : Checks if Privoxy should answer the request with
1430 * a HTTP redirect and generates the redirect if
1434 * 1 : csp = Current client state (buffers, headers, etc...)
1436 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1438 *********************************************************************/
1439 struct http_response *redirect_url(struct client_state *csp)
1441 struct http_response *rsp;
1442 #ifdef FEATURE_FAST_REDIRECTS
1444 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1445 * as compile-time option? The user can easily disable
1446 * it in his action file.
1448 char * redirect_mode;
1449 #endif /* def FEATURE_FAST_REDIRECTS */
1450 char *old_url = NULL;
1451 char *new_url = NULL;
1452 char *redirection_string;
1454 if ((csp->action->flags & ACTION_REDIRECT))
1456 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1459 * If the redirection string begins with 's',
1460 * assume it's a pcrs command, otherwise treat it as
1461 * properly formatted URL and use it for the redirection
1464 * According to RFC 2616 section 14.30 the URL
1465 * has to be absolute and if the user tries:
1466 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1467 * she would get undefined results anyway.
1471 if (*redirection_string == 's')
1473 old_url = csp->http->url;
1474 new_url = rewrite_url(old_url, redirection_string);
1478 log_error(LOG_LEVEL_REDIRECTS,
1479 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1480 redirection_string);
1481 new_url = strdup(redirection_string);
1485 #ifdef FEATURE_FAST_REDIRECTS
1486 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1488 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1491 * If it exists, use the previously rewritten URL as input
1492 * otherwise just use the old path.
1494 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1495 new_url = get_last_url(old_url, redirect_mode);
1500 * Disable redirect checkers, so that they
1501 * will be only run more than once if the user
1502 * also enables them through tags.
1504 * From a performance point of view
1505 * it doesn't matter, but the duplicated
1506 * log messages are annoying.
1508 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1509 #endif /* def FEATURE_FAST_REDIRECTS */
1510 csp->action->flags &= ~ACTION_REDIRECT;
1512 /* Did any redirect action trigger? */
1515 if (0 == strcmpic(new_url, csp->http->url))
1517 log_error(LOG_LEVEL_ERROR,
1518 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1519 csp->http->url, new_url);
1524 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1526 if (NULL == (rsp = alloc_http_response()))
1529 return cgi_error_memory();
1532 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1533 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1536 free_http_response(rsp);
1537 return cgi_error_memory();
1539 rsp->reason = RSP_REASON_REDIRECTED;
1542 return finish_http_response(csp, rsp);
1546 /* Only reached if no redirect is required */
1552 #ifdef FEATURE_IMAGE_BLOCKING
1553 /*********************************************************************
1555 * Function : is_imageurl
1557 * Description : Given a URL, decide whether it is an image or not,
1558 * using either the info from a previous +image action
1559 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1560 * is MSIE and not on a Mac, tell from the browser's accept
1564 * 1 : csp = Current client state (buffers, headers, etc...)
1566 * Returns : True (nonzero) if URL is an image, false (0)
1569 *********************************************************************/
1570 int is_imageurl(const struct client_state *csp)
1572 #ifdef FEATURE_IMAGE_DETECT_MSIE
1575 tmp = get_header_value(csp->headers, "User-Agent:");
1576 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1578 tmp = get_header_value(csp->headers, "Accept:");
1579 if (tmp && strstr(tmp, "image/gif"))
1581 /* Client will accept HTML. If this seems counterintuitive,
1591 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1593 return ((csp->action->flags & ACTION_IMAGE) != 0);
1596 #endif /* def FEATURE_IMAGE_BLOCKING */
1599 #ifdef FEATURE_TRUST
1600 /*********************************************************************
1602 * Function : is_untrusted_url
1604 * Description : Should we "distrust" this URL (and block it)?
1606 * Yes if it matches a line in the trustfile, or if the
1607 * referrer matches a line starting with "+" in the
1612 * 1 : csp = Current client state (buffers, headers, etc...)
1614 * Returns : 0 => trusted, 1 => untrusted
1616 *********************************************************************/
1617 int is_untrusted_url(const struct client_state *csp)
1619 struct file_list *fl;
1620 struct block_spec *b;
1621 struct url_spec **trusted_url;
1622 struct http_request rhttp[1];
1623 const char * referer;
1627 * If we don't have a trustlist, we trust everybody
1629 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1634 memset(rhttp, '\0', sizeof(*rhttp));
1637 * Do we trust the request URL itself?
1639 for (b = b->next; b ; b = b->next)
1641 if (url_match(b->url, csp->http))
1647 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1649 /* no referrer was supplied */
1655 * If not, do we maybe trust its referrer?
1657 err = parse_http_url(referer, rhttp, csp);
1663 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1665 if (url_match(*trusted_url, rhttp))
1667 /* if the URL's referrer is from a trusted referrer, then
1668 * add the target spec to the trustfile as an unblocked
1669 * domain and return 0 (which means it's OK).
1674 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1678 char * new_entry = strdup("~");
1680 string_append(&new_entry, csp->http->hostport);
1682 path = csp->http->path;
1683 if ( (path[0] == '/')
1685 && ((path_end = strchr(path + 2, '/')) != NULL))
1687 /* since this path points into a user's home space
1688 * be sure to include this spec in the trustfile.
1690 int path_len = path_end - path; /* save offset */
1691 path = strdup(path); /* Copy string */
1694 path_end = path + path_len; /* regenerate ptr to new buffer */
1695 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1697 string_join(&new_entry, path);
1701 * Give a reason for generating this entry.
1703 string_append(&new_entry, " # Trusted referrer was: ");
1704 string_append(&new_entry, referer);
1706 if (new_entry != NULL)
1708 if (-1 == fprintf(fp, "%s\n", new_entry))
1710 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1711 new_entry, csp->config->trustfile);
1717 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1718 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1725 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1726 csp->http->hostport, csp->config->trustfile);
1734 #endif /* def FEATURE_TRUST */
1737 /*********************************************************************
1739 * Function : pcrs_filter_response
1741 * Description : Execute all text substitutions from all applying
1742 * +filter actions on the text buffer that's been
1743 * accumulated in csp->iob->buf.
1746 * 1 : csp = Current client state (buffers, headers, etc...)
1748 * Returns : a pointer to the (newly allocated) modified buffer.
1749 * or NULL if there were no hits or something went wrong
1751 *********************************************************************/
1752 static char *pcrs_filter_response(struct client_state *csp)
1755 size_t size, prev_size;
1761 struct file_list *fl;
1762 struct re_filterfile_spec *b;
1763 struct list_entry *filtername;
1765 int i, found_filters = 0;
1770 if (csp->iob->cur >= csp->iob->eod)
1776 * Need to check the set of re_filterfiles...
1778 for (i = 0; i < MAX_AF_FILES; i++)
1791 if (0 == found_filters)
1793 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1797 size = (size_t)(csp->iob->eod - csp->iob->cur);
1798 old = csp->iob->cur;
1800 for (i = 0; i < MAX_AF_FILES; i++)
1803 if ((NULL == fl) || (NULL == fl->f))
1806 * Either there are no filter files
1807 * left, or this filter file just
1808 * contains no valid filters.
1810 * Continue to be sure we don't miss
1811 * valid filter files that are chained
1812 * after empty or invalid ones.
1817 * For all applying +filter actions, look if a filter by that
1818 * name exists and if yes, execute it's pcrs_joblist on the
1821 for (b = fl->f; b; b = b->next)
1823 if (b->type != FT_CONTENT_FILTER)
1825 /* Skip header filters */
1829 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1830 filtername ; filtername = filtername->next)
1832 if (strcmp(b->name, filtername->str) == 0)
1834 int current_hits = 0; /* Number of hits caused by this filter */
1835 int job_number = 0; /* Which job we're currently executing */
1836 int job_hits = 0; /* How many hits the current job caused */
1837 pcrs_job *joblist = b->joblist;
1839 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1841 if (NULL == joblist)
1843 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1848 /* Apply all jobs from the joblist */
1849 for (job = joblist; NULL != job; job = job->next)
1852 job_hits = pcrs_execute(job, old, size, &new, &size);
1857 * That went well. Continue filtering
1858 * and use the result of this job as
1859 * input for the next one.
1861 current_hits += job_hits;
1862 if (old != csp->iob->cur)
1871 * This job caused an unexpected error. Inform the user
1872 * and skip the rest of the jobs in this filter. We could
1873 * continue with the next job, but usually the jobs
1874 * depend on each other or are similar enough to
1875 * fail for the same reason.
1877 * At the moment our pcrs expects the error codes of pcre 3.4,
1878 * but newer pcre versions can return additional error codes.
1879 * As a result pcrs_strerror()'s error message might be
1880 * "Unknown error ...", therefore we print the numerical value
1883 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1884 * should we use LOG_LEVEL_RE_FILTER instead?
1886 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1887 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1892 if (b->dynamic) pcrs_free_joblist(joblist);
1894 log_error(LOG_LEVEL_RE_FILTER,
1895 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1896 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1898 hits += current_hits;
1905 * If there were no hits, destroy our copy and let
1906 * chat() use the original in csp->iob
1914 csp->flags |= CSP_FLAG_MODIFIED;
1915 csp->content_length = size;
1923 /*********************************************************************
1925 * Function : gif_deanimate_response
1927 * Description : Deanimate the GIF image that has been accumulated in
1928 * csp->iob->buf, set csp->content_length to the modified
1929 * size and raise the CSP_FLAG_MODIFIED flag.
1932 * 1 : csp = Current client state (buffers, headers, etc...)
1934 * Returns : a pointer to the (newly allocated) modified buffer.
1935 * or NULL in case something went wrong.
1937 *********************************************************************/
1938 static char *gif_deanimate_response(struct client_state *csp)
1940 struct binbuffer *in, *out;
1944 size = (size_t)(csp->iob->eod - csp->iob->cur);
1946 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1947 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1949 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1953 in->buffer = csp->iob->cur;
1956 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1958 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1965 if ((int)size == out->offset)
1967 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1971 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1973 csp->content_length = out->offset;
1974 csp->flags |= CSP_FLAG_MODIFIED;
1984 /*********************************************************************
1986 * Function : jpeg_inspect_response
1991 * 1 : csp = Current client state (buffers, headers, etc...)
1993 * Returns : a pointer to the (newly allocated) modified buffer
1994 * or NULL in case something went wrong.
1996 *********************************************************************/
1997 static char *jpeg_inspect_response(struct client_state *csp)
1999 struct binbuffer *in = NULL;
2000 struct binbuffer *out = NULL;
2004 size = (size_t)(csp->iob->eod - csp->iob->cur);
2006 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
2008 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
2012 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
2014 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
2018 in->buffer = csp->iob->cur;
2022 * Calling jpeg_inspect has the side-effect of creating and
2023 * modifying the image buffer of "out" directly.
2025 if (jpeg_inspect(in, out))
2027 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
2035 csp->content_length = out->offset;
2036 csp->flags |= CSP_FLAG_MODIFIED;
2046 /*********************************************************************
2048 * Function : get_filter_function
2050 * Description : Decides which content filter function has
2051 * to be applied (if any).
2053 * XXX: Doesn't handle filter_popups()
2054 * because of the different prototype. Probably
2055 * we should ditch filter_popups() anyway, it's
2056 * even less reliable than popup blocking based
2060 * 1 : csp = Current client state (buffers, headers, etc...)
2062 * Returns : The content filter function to run, or
2063 * NULL if no content filter is active
2065 *********************************************************************/
2066 filter_function_ptr get_filter_function(struct client_state *csp)
2068 filter_function_ptr filter_function = NULL;
2071 * Are we enabling text mode by force?
2073 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2076 * Do we really have to?
2078 if (csp->content_type & CT_TEXT)
2080 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2084 csp->content_type |= CT_TEXT;
2085 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2089 if (!(csp->content_type & CT_DECLARED))
2092 * The server didn't bother to declare a MIME-Type.
2093 * Assume it's text that can be filtered.
2095 * This also regulary happens with 304 responses,
2096 * therefore logging anything here would cause
2099 csp->content_type |= CT_TEXT;
2103 * Choose the applying filter function based on
2104 * the content type and action settings.
2106 if ((csp->content_type & CT_TEXT) &&
2107 (csp->rlist != NULL) &&
2108 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2110 filter_function = pcrs_filter_response;
2112 else if ((csp->content_type & CT_GIF) &&
2113 (csp->action->flags & ACTION_DEANIMATE))
2115 filter_function = gif_deanimate_response;
2117 else if ((csp->content_type & CT_JPEG) &&
2118 (csp->action->flags & ACTION_JPEG_INSPECT))
2120 filter_function = jpeg_inspect_response;
2123 return filter_function;
2127 /*********************************************************************
2129 * Function : remove_chunked_transfer_coding
2131 * Description : In-situ remove the "chunked" transfer coding as defined
2132 * in rfc2616 from a buffer.
2135 * 1 : buffer = Pointer to the text buffer
2136 * 2 : size = In: Number of bytes to be processed,
2137 * Out: Number of bytes after de-chunking.
2138 * (undefined in case of errors)
2140 * Returns : JB_ERR_OK for success,
2141 * JB_ERR_PARSE otherwise
2143 *********************************************************************/
2144 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2147 unsigned int chunksize = 0;
2148 char *from_p, *to_p;
2151 from_p = to_p = buffer;
2153 if (sscanf(buffer, "%x", &chunksize) != 1)
2155 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2156 return JB_ERR_PARSE;
2159 while (chunksize > 0)
2161 if (NULL == (from_p = strstr(from_p, "\r\n")))
2163 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2164 return JB_ERR_PARSE;
2167 if ((newsize += chunksize) >= *size)
2169 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
2170 return JB_ERR_PARSE;
2174 memmove(to_p, from_p, (size_t) chunksize);
2175 to_p = buffer + newsize;
2176 from_p += chunksize + 2;
2178 if (sscanf(from_p, "%x", &chunksize) != 1)
2180 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2181 return JB_ERR_PARSE;
2187 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
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 log_error(LOG_LEVEL_ERROR, "Failed to de-chunk content.");
2236 return JB_ERR_PARSE;
2242 * If the body has a supported transfer-encoding,
2243 * decompress it, adjusting size and iob->eod.
2245 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
2247 if (0 == csp->iob->eod - csp->iob->cur)
2249 /* Nothing left after de-chunking. */
2253 err = decompress_iob(csp);
2255 if (JB_ERR_OK == err)
2257 csp->flags |= CSP_FLAG_MODIFIED;
2258 csp->content_type &= ~CT_TABOO;
2263 * Unset CT_GZIP and CT_DEFLATE to remember not
2264 * to modify the Content-Encoding header later.
2266 csp->content_type &= ~CT_GZIP;
2267 csp->content_type &= ~CT_DEFLATE;
2268 log_error(LOG_LEVEL_ERROR, "Failed to decompress content.");
2277 /*********************************************************************
2279 * Function : execute_content_filter
2281 * Description : Executes a given content filter.
2284 * 1 : csp = Current client state (buffers, headers, etc...)
2285 * 2 : content_filter = The filter function to execute
2287 * Returns : Pointer to the modified buffer, or
2288 * NULL if filtering failed or wasn't necessary.
2290 *********************************************************************/
2291 char *execute_content_filter(struct client_state *csp, filter_function_ptr content_filter)
2293 if (0 == csp->iob->eod - csp->iob->cur)
2296 * No content (probably status code 301, 302 ...),
2297 * no filtering necessary.
2302 if (JB_ERR_OK != prepare_for_filtering(csp))
2305 * failed to de-chunk or decompress.
2306 * XXX: if possible, we should continue anyway.
2311 if (0 == csp->iob->eod - csp->iob->cur)
2314 * Clown alarm: chunked and/or compressed nothing delivered.
2319 return ((*content_filter)(csp));
2323 /*********************************************************************
2325 * Function : url_actions
2327 * Description : Gets the actions for this URL.
2330 * 1 : http = http_request request for blocked URLs
2331 * 2 : csp = Current client state (buffers, headers, etc...)
2335 *********************************************************************/
2336 void url_actions(struct http_request *http,
2337 struct client_state *csp)
2339 struct file_list *fl;
2340 struct url_actions *b;
2343 init_current_action(csp->action);
2345 for (i = 0; i < MAX_AF_FILES; i++)
2347 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2352 apply_url_actions(csp->action, http, b);
2359 /*********************************************************************
2361 * Function : apply_url_actions
2363 * Description : Applies a list of URL actions.
2366 * 1 : action = Destination.
2367 * 2 : http = Current URL
2368 * 3 : b = list of URL actions to apply
2372 *********************************************************************/
2373 void apply_url_actions(struct current_action_spec *action,
2374 struct http_request *http,
2375 struct url_actions *b)
2379 /* Should never happen */
2383 for (b = b->next; NULL != b; b = b->next)
2385 if (url_match(b->url, http))
2387 merge_current_action(action, b->action);
2393 /*********************************************************************
2395 * Function : get_forward_override_settings
2397 * Description : Returns forward settings as specified with the
2398 * forward-override{} action. forward-override accepts
2399 * forward lines similar to the one used in the
2400 * configuration file, but without the URL pattern.
2406 * in the configuration file can be replaced with
2407 * the action section:
2409 * {+forward-override{forward .}}
2413 * 1 : csp = Current client state (buffers, headers, etc...)
2415 * Returns : Pointer to forwarding structure in case of success.
2416 * Invalid syntax is fatal.
2418 *********************************************************************/
2419 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2421 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2422 char forward_settings[BUFFER_SIZE];
2423 char *http_parent = NULL;
2424 /* variable names were chosen for consistency reasons. */
2425 struct forward_spec *fwd = NULL;
2429 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2430 /* Should be enforced by load_one_actions_file() */
2431 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2433 /* Create a copy ssplit can modify */
2434 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2436 if (NULL != csp->fwd)
2439 * XXX: Currently necessary to prevent memory
2440 * leaks when the show-url-info cgi page is visited.
2442 unload_forward_spec(csp->fwd);
2446 * allocate a new forward node, valid only for
2447 * the lifetime of this request. Save its location
2448 * in csp as well, so sweep() can free it later on.
2450 fwd = csp->fwd = zalloc(sizeof(*fwd));
2453 log_error(LOG_LEVEL_FATAL,
2454 "can't allocate memory for forward-override{%s}", forward_override_line);
2455 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2458 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2459 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2461 fwd->type = SOCKS_NONE;
2463 /* Parse the parent HTTP proxy host:port */
2464 http_parent = vec[1];
2467 else if (vec_count == 3)
2469 char *socks_proxy = NULL;
2471 if (!strcasecmp(vec[0], "forward-socks4"))
2473 fwd->type = SOCKS_4;
2474 socks_proxy = vec[1];
2476 else if (!strcasecmp(vec[0], "forward-socks4a"))
2478 fwd->type = SOCKS_4A;
2479 socks_proxy = vec[1];
2482 if (NULL != socks_proxy)
2484 /* Parse the SOCKS proxy host[:port] */
2485 fwd->gateway_host = strdup(socks_proxy);
2487 if (NULL != (socks_proxy = strchr(fwd->gateway_host, ':')))
2489 *socks_proxy++ = '\0';
2490 fwd->gateway_port = strtol(socks_proxy, NULL, 0);
2493 if (fwd->gateway_port <= 0)
2495 fwd->gateway_port = 1080;
2498 http_parent = vec[2];
2502 if (NULL == http_parent)
2504 log_error(LOG_LEVEL_FATAL,
2505 "Invalid forward-override syntax in: %s", forward_override_line);
2506 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2509 /* Parse http forwarding settings */
2510 if (strcmp(http_parent, ".") != 0)
2512 fwd->forward_host = strdup(http_parent);
2514 if (NULL != (http_parent = strchr(fwd->forward_host, ':')))
2516 *http_parent++ = '\0';
2517 fwd->forward_port = strtol(http_parent, NULL, 0);
2520 if (fwd->forward_port <= 0)
2522 fwd->forward_port = 8000;
2526 assert (NULL != fwd);
2528 log_error(LOG_LEVEL_CONNECT,
2529 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2535 /*********************************************************************
2537 * Function : forward_url
2539 * Description : Should we forward this to another proxy?
2541 * XXX: Should be changed to make use of csp->fwd.
2544 * 1 : http = http_request request for current URL
2545 * 2 : csp = Current client state (buffers, headers, etc...)
2547 * Returns : Pointer to forwarding information.
2549 *********************************************************************/
2550 const struct forward_spec * forward_url(struct http_request *http,
2551 struct client_state *csp)
2553 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2554 struct forward_spec *fwd = csp->config->forward;
2556 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2558 return get_forward_override_settings(csp);
2568 if (url_match(fwd->url, http))
2579 /*********************************************************************
2581 * Function : direct_response
2583 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2584 * request and if so, return a HTTP 501 to the client.
2586 * FIXME: I have a stupid name and I should handle the
2587 * requests properly. Still, what we do here is rfc-
2588 * compliant, whereas ignoring or forwarding are not.
2591 * 1 : csp = Current client state (buffers, headers, etc...)
2593 * Returns : http_response if , NULL if nonmatch or handler fail
2595 *********************************************************************/
2596 struct http_response *direct_response(struct client_state *csp)
2598 struct http_response *rsp;
2599 struct list_entry *p;
2601 if ((0 == strcmpic(csp->http->gpc, "trace"))
2602 || (0 == strcmpic(csp->http->gpc, "options")))
2604 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2606 if (!strncmpic("Max-Forwards:", p->str, 13))
2608 unsigned int max_forwards;
2611 * If it's a Max-Forwards value of zero,
2612 * we have to intercept the request.
2614 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2617 * FIXME: We could handle at least TRACE here,
2618 * but that would require a verbatim copy of
2619 * the request which we don't have anymore
2621 log_error(LOG_LEVEL_HEADER,
2622 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2625 /* Get mem for response or fail*/
2626 if (NULL == (rsp = alloc_http_response()))
2628 return cgi_error_memory();
2631 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2633 free_http_response(rsp);
2634 return cgi_error_memory();
2638 rsp->reason = RSP_REASON_UNSUPPORTED;
2640 return(finish_http_response(csp, rsp));