1 const char filters_rcs[] = "$Id: filters.c,v 1.76 2007/01/01 19:36:37 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-2006 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.76 2007/01/01 19:36:37 fabiankeil
44 * Integrate a modified version of Wil Mahan's
45 * zlib patch (PR #895531).
47 * Revision 1.75 2006/12/29 18:30:46 fabiankeil
48 * Fixed gcc43 conversion warnings,
49 * changed sprintf calls to snprintf.
51 * Revision 1.74 2006/12/24 17:37:38 fabiankeil
52 * Adjust comment in pcrs_filter_response()
53 * to recent pcrs changes. Hohoho.
55 * Revision 1.73 2006/12/23 16:01:02 fabiankeil
56 * Don't crash if pcre returns an error code
57 * that pcrs didn't expect. Fixes BR 1621173.
59 * Revision 1.72 2006/12/22 18:52:53 fabiankeil
60 * Modified is_untrusted_url to complain in case of
61 * write errors and to give a reason when adding new
62 * entries to the trustfile. Closes FR 1097611.
64 * Revision 1.71 2006/12/22 14:24:52 fabiankeil
65 * Skip empty filter files in pcrs_filter_response,
66 * but don't ignore the ones that come afterwards.
67 * Fixes parts of BR 1619208.
69 * Revision 1.70 2006/12/09 13:33:15 fabiankeil
70 * Added some sanity checks for get_last_url().
71 * Fixed possible segfault caused by my last commit.
73 * Revision 1.69 2006/12/08 12:39:13 fabiankeil
74 * Let get_last_url() catch https URLs as well.
76 * Revision 1.68 2006/12/05 14:45:48 fabiankeil
77 * Make sure get_last_url() behaves like advertised
78 * and fast-redirects{} can be combined with redirect{}.
80 * Revision 1.67 2006/11/28 15:19:43 fabiankeil
81 * Implemented +redirect{s@foo@bar@} to generate
82 * a redirect based on a rewritten version of the
85 * Revision 1.66 2006/09/23 13:26:38 roro
86 * Replace TABs by spaces in source code.
88 * Revision 1.65 2006/09/21 12:54:43 fabiankeil
89 * Fix +redirect{}. Didn't work with -fast-redirects.
91 * Revision 1.64 2006/08/31 10:55:49 fabiankeil
92 * Block requests for untrusted URLs with status
93 * code 403 instead of 200.
95 * Revision 1.63 2006/08/31 10:11:28 fabiankeil
96 * Don't free p which is still in use and will be later
97 * freed by free_map(). Don't claim the referrer is unknown
98 * when the client didn't set one.
100 * Revision 1.62 2006/08/14 00:27:47 david__schmidt
101 * Feature request 595948: Re-Filter logging in single line
103 * Revision 1.61 2006/08/03 02:46:41 david__schmidt
104 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
106 * Revision 1.60 2006/07/18 14:48:46 david__schmidt
107 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
108 * with what was really the latest development (the v_3_0_branch branch)
110 * Revision 1.58.2.9 2006/01/29 23:10:56 david__schmidt
111 * Multiple filter file support
113 * Revision 1.58.2.8 2005/05/07 21:50:55 david__schmidt
114 * A few memory leaks plugged (mostly on error paths)
116 * Revision 1.58.2.7 2004/10/03 12:53:32 david__schmidt
117 * Add the ability to check jpeg images for invalid
118 * lengths of comment blocks. Defensive strategy
119 * against the exploit:
120 * Microsoft Security Bulletin MS04-028
121 * Buffer Overrun in JPEG Processing (GDI+) Could
122 * Allow Code Execution (833987)
123 * Enabled with +inspect-jpegs in actions files.
125 * Revision 1.58.2.6 2003/12/06 22:18:27 gliptak
126 * Correcting compile problem with FEATURE_IMAGE_BLOCKING
128 * Revision 1.58.2.5 2003/11/11 13:10:31 oes
129 * Fixed bug #839859: "See why" link URL now gets url-encoded.
131 * Revision 1.58.2.4 2003/02/28 12:52:45 oes
134 * Revision 1.58.2.3 2002/09/25 14:51:51 oes
135 * Added basic support for OPTIONS and TRACE HTTP methods:
136 * New function direct_response which handles OPTIONS and
137 * TRACE requests whose Max-Forwards header field is zero.
139 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
140 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
142 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
143 * - Bugfix: Executing a filters without jobs no longer results in
144 * turing off *all* filters.
145 * - Security fix: Malicious web servers can't cause a seg fault
146 * through bogus chunk sizes anymore
148 * Revision 1.58 2002/04/24 02:11:17 oes
149 * Jon's multiple AF patch: url_actions now evaluates rules
152 * Revision 1.57 2002/04/08 20:38:34 swa
155 * Revision 1.56 2002/04/05 15:51:24 oes
156 * - bugfix: error-pages now get correct request protocol
157 * - fix for invalid HTML in trust info
159 * Revision 1.55 2002/04/02 16:13:51 oes
160 * Fix: No "Go there anyway" for SSL
162 * Revision 1.54 2002/04/02 14:55:56 oes
163 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
165 * Revision 1.53 2002/03/26 22:29:54 swa
166 * we have a new homepage!
168 * Revision 1.52 2002/03/24 16:35:57 jongfoster
171 * Revision 1.51 2002/03/24 15:23:33 jongfoster
174 * Revision 1.50 2002/03/24 13:25:43 swa
175 * name change related issues
177 * Revision 1.49 2002/03/16 20:29:14 oes
180 * Revision 1.48 2002/03/13 20:25:34 oes
181 * Better logging for content filters
183 * Revision 1.47 2002/03/13 00:30:52 jongfoster
185 * Added option of always sending redirect for imageblock,
186 * currently disabled with #if 0.
188 * Revision 1.46 2002/03/12 01:42:49 oes
189 * Introduced modular filters
191 * Revision 1.45 2002/03/08 16:47:50 oes
192 * Added choice beween GIF and PNG built-in images
194 * Revision 1.44 2002/03/07 03:49:31 oes
195 * - Fixed compiler warnings etc
196 * - Changed built-in images from GIF to PNG
197 * (with regard to Unisys patent issue)
198 * - Added a 4x4 pattern PNG which is less intrusive
199 * than the logo but also clearly marks the deleted banners
201 * Revision 1.43 2002/01/22 23:51:59 jongfoster
202 * Replacing strsav() with the safer string_append().
204 * Adding missing html_encode() to error message generators. Where encoded
205 * and unencoded versions of a string were provided, removing the unencoded
208 * Revision 1.42 2002/01/17 21:00:32 jongfoster
209 * Moving all our URL and URL pattern parsing code to urlmatch.c.
211 * Using a single, simple url_match(pattern,url) function - rather than
212 * the 3-line match routine which was repeated all over the place.
214 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
216 * Using parse_http_url() to parse URLs without faking a HTTP
217 * request line for parse_http_request().
219 * Revision 1.41 2001/11/13 00:14:07 jongfoster
220 * Fixing stupid bug now I've figured out what || means.
221 * (It always returns 0 or 1, not one of it's paramaters.)
223 * Revision 1.40 2001/10/26 17:37:55 oes
224 * - Re-enabled Netscape 200/404 bug workaround in block_url():
225 * - Removed OS/2 special case
226 * - Made block_url() independant from sed() having been run
227 * - Made trust_url independant from sed() having been run
228 * - Made is_imageurl independant from sed() having been run.
229 * It now checks User-Agent: and Accept: by itself.
232 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
233 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
234 * threads to call select() simultaneously. So, it's time to do a real, live,
235 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
236 * (native). Both versions will work, but using __OS2__ offers multi-threading.
238 * Revision 1.38 2001/10/23 21:32:33 jongfoster
239 * Adding error-checking to selected functions
241 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
242 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
243 * filters.c. Added a FIXME in front of the offending code. I'll gladly
244 * put in a better/more robust fix for all parties if one is presented...
245 * It seems that just returning 200 instead of 404 would pretty much fix
246 * it for everyone, but I don't know all the history of the problem.
248 * Revision 1.36 2001/10/10 16:44:16 oes
249 * Added match_portlist function
251 * Revision 1.35 2001/10/07 15:41:23 oes
252 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
254 * New function remove_chunked_transfer_coding that strips chunked
255 * transfer coding to plain and is called by pcrs_filter_response
256 * and gif_deanimate_response if neccessary
258 * Improved handling of zero-change re_filter runs
260 * pcrs_filter_response and gif_deanimate_response now remove
261 * chunked transfer codeing before processing the body.
263 * Revision 1.34 2001/09/20 15:49:36 steudten
265 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
266 * See cgi.c fill_template().
268 * Revision 1.33 2001/09/16 17:05:14 jongfoster
269 * Removing unused #include showarg.h
271 * Revision 1.32 2001/09/16 13:21:27 jongfoster
272 * Changes to use new list functions.
274 * Revision 1.31 2001/09/16 11:38:02 jongfoster
275 * Splitting fill_template() into 2 functions:
276 * template_load() loads the file
277 * template_fill() performs the PCRS regexps.
278 * This is because the CGI edit interface has a "table row"
279 * template which is used many times in the page - this
280 * change means it's only loaded from disk once.
282 * Revision 1.30 2001/09/16 11:00:10 jongfoster
283 * New function alloc_http_response, for symmetry with free_http_response
285 * Revision 1.29 2001/09/13 23:32:40 jongfoster
286 * Moving image data to cgi.c rather than cgi.h
287 * Fixing a GPF under Win32 (and any other OS that protects global
288 * constants from being written to).
290 * Revision 1.28 2001/09/10 10:18:51 oes
291 * Silenced compiler warnings
293 * Revision 1.27 2001/08/05 16:06:20 jongfoster
294 * Modifiying "struct map" so that there are now separate header and
295 * "map_entry" structures. This means that functions which modify a
296 * map no longer need to return a pointer to the modified map.
297 * Also, it no longer reverses the order of the entries (which may be
298 * important with some advanced template substitutions).
300 * Revision 1.26 2001/07/30 22:08:36 jongfoster
301 * Tidying up #defines:
302 * - All feature #defines are now of the form FEATURE_xxx
303 * - Permanently turned off WIN_GUI_EDIT
304 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
306 * Revision 1.25 2001/07/26 10:09:46 oes
307 * Made browser detection a little less naive
309 * Revision 1.24 2001/07/25 17:22:51 oes
310 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
312 * Revision 1.23 2001/07/23 13:40:12 oes
313 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
315 * Revision 1.22 2001/07/18 12:29:34 oes
316 * - Made gif_deanimate_response respect
317 * csp->action->string[ACTION_STRING_DEANIMATE]
318 * - Logging cosmetics
320 * Revision 1.21 2001/07/13 13:59:53 oes
321 * - Introduced gif_deanimate_response which shares the
322 * generic content modification interface of pcrs_filter_response
323 * and acts as a wrapper to deanimate.c:gif_deanimate()
324 * - Renamed re_process_buffer to pcrs_filter_response
325 * - pcrs_filter_response now returns NULL on failiure
326 * - Removed all #ifdef PCRS
328 * Revision 1.20 2001/07/01 17:01:04 oes
329 * Added comments and missing return statement in is_untrusted_url()
331 * Revision 1.19 2001/06/29 21:45:41 oes
332 * Indentation, CRLF->LF, Tab-> Space
334 * Revision 1.18 2001/06/29 13:27:38 oes
335 * - Cleaned up, renamed and reorderd functions
336 * and improved comments
339 * - Ported to CGI platform. Now delivers
340 * http_response or NULL
341 * - Unified HTML and GIF generation (moved image detection
342 * and GIF generation here from jcc.c:chat())
343 * - Fixed HTTP status to:
344 * - 403 (Forbidden) for the "blocked" HTML message
345 * - 200 (OK) for GIF answers
346 * - 302 (Redirect) for redirect to GIF
349 * - Ported to CGI platform. Now delivers
350 * http_response or NULL
351 * - Separated detection of untrusted URL into
352 * (bool)is_untrusted_url
353 * - Added enforcement of untrusted requests
355 * - Moved redirect_url() from cgi.c to here
356 * and ported it to the CGI platform
358 * - Removed logentry from cancelled commit
360 * Revision 1.17 2001/06/09 10:55:28 jongfoster
361 * Changing BUFSIZ ==> BUFFER_SIZE
363 * Revision 1.16 2001/06/07 23:10:26 jongfoster
364 * Allowing unanchored domain patterns to back off and retry
365 * if they partially match. Optimized right-anchored patterns.
366 * Moving ACL and forward files into config file.
367 * Replacing struct gateway with struct forward_spec
369 * Revision 1.15 2001/06/03 19:12:00 oes
370 * extracted-CGI relevant stuff
372 * Revision 1.14 2001/06/01 10:30:55 oes
373 * Added optional left-anchoring to domaincmp
375 * Revision 1.13 2001/05/31 21:21:30 jongfoster
376 * Permissionsfile / actions file changes:
377 * - Changed "permission" to "action" throughout
378 * - changes to file format to allow string parameters
379 * - Moved helper functions to actions.c
381 * Revision 1.12 2001/05/31 17:35:20 oes
383 * - Enhanced domain part globbing with infix and prefix asterisk
384 * matching and optional unanchored operation
386 * Revision 1.11 2001/05/29 11:53:23 oes
387 * "See why" link added to "blocked" page
389 * Revision 1.10 2001/05/29 09:50:24 jongfoster
390 * Unified blocklist/imagelist/permissionslist.
391 * File format is still under discussion, but the internal changes
394 * Also modified interceptor behaviour:
395 * - We now intercept all URLs beginning with one of the following
396 * prefixes (and *only* these prefixes):
398 * * http://ijbswa.sf.net/config/
399 * * http://ijbswa.sourceforge.net/config/
400 * - New interceptors "home page" - go to http://i.j.b/ to see it.
401 * - Internal changes so that intercepted and fast redirect pages
402 * are not replaced with an image.
403 * - Interceptors now have the option to send a binary page direct
404 * to the client. (i.e. ijb-send-banner uses this)
405 * - Implemented show-url-info interceptor. (Which is why I needed
406 * the above interceptors changes - a typical URL is
407 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
408 * The previous mechanism would not have intercepted that, and
409 * if it had been intercepted then it then it would have replaced
412 * Revision 1.9 2001/05/27 22:17:04 oes
414 * - re_process_buffer no longer writes the modified buffer
415 * to the client, which was very ugly. It now returns the
416 * buffer, which it is then written by chat.
418 * - content_length now adjusts the Content-Length: header
419 * for modified documents rather than crunch()ing it.
420 * (Length info in csp->content_length, which is 0 for
421 * unmodified documents)
423 * - For this to work, sed() is called twice when filtering.
425 * Revision 1.8 2001/05/26 17:13:28 jongfoster
426 * Filled in a function comment.
428 * Revision 1.7 2001/05/26 15:26:15 jongfoster
429 * ACL feature now provides more security by immediately dropping
430 * connections from untrusted hosts.
432 * Revision 1.6 2001/05/26 00:28:36 jongfoster
433 * Automatic reloading of config file.
434 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
435 * Most of the global variables have been moved to a new
436 * struct configuration_spec, accessed through csp->config->globalname
437 * Most of the globals remaining are used by the Win32 GUI.
439 * Revision 1.5 2001/05/25 22:34:30 jongfoster
442 * Revision 1.4 2001/05/22 18:46:04 oes
444 * - Enabled filtering banners by size rather than URL
445 * by adding patterns that replace all standard banner
446 * sizes with the "Junkbuster" gif to the re_filterfile
448 * - Enabled filtering WebBugs by providing a pattern
449 * which kills all 1x1 images
451 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
452 * which is selected by the (nonstandard and therefore
453 * capital) letter 'U' in the option string.
454 * It causes the quantifiers to be ungreedy by default.
455 * Appending a ? turns back to greedy (!).
457 * - Added a new interceptor ijb-send-banner, which
458 * sends back the "Junkbuster" gif. Without imagelist or
459 * MSIE detection support, or if tinygif = 1, or the
460 * URL isn't recognized as an imageurl, a lame HTML
461 * explanation is sent instead.
463 * - Added new feature, which permits blocking remote
464 * script redirects and firing back a local redirect
466 * The feature is conditionally compiled, i.e. it
467 * can be disabled with --disable-fast-redirects,
468 * plus it must be activated by a "fast-redirects"
469 * line in the config file, has its own log level
470 * and of course wants to be displayed by show-proxy-args
471 * Note: Boy, all the #ifdefs in 1001 locations and
472 * all the fumbling with configure.in and acconfig.h
473 * were *way* more work than the feature itself :-(
475 * - Because a generic redirect template was needed for
476 * this, tinygif = 3 now uses the same.
478 * - Moved GIFs, and other static HTTP response templates
483 * - Removed some >400 CRs again (Jon, you really worked
486 * Revision 1.3 2001/05/20 16:44:47 jongfoster
487 * Removing last hardcoded Junkbusters.com URLs.
489 * Revision 1.2 2001/05/20 01:21:20 jongfoster
490 * Version 2.9.4 checkin.
491 * - Merged popupfile and cookiefile, and added control over PCRS
492 * filtering, in new "permissionsfile".
493 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
494 * file error you now get a message box (in the Win32 GUI) rather
495 * than the program exiting with no explanation.
496 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
498 * - Removed tabs from "config"
499 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
500 * - Bumped up version number.
502 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
503 * Initial import of version 2.9.3 source tree
506 *********************************************************************/
512 #include <sys/types.h>
521 #endif /* ndef __OS2__ */
522 #include <netinet/in.h>
524 #include <winsock2.h>
525 #endif /* ndef _WIN32 */
529 #endif /* def __OS2__ */
537 #include "jbsockets.h"
538 #include "miscutil.h"
542 #include "deanimate.h"
543 #include "urlmatch.h"
549 const char filters_h_rcs[] = FILTERS_H_VERSION;
551 /* Fix a problem with Solaris. There should be no effect on other
553 * Solaris's isspace() is a macro which uses it's argument directly
554 * as an array index. Therefore we need to make sure that high-bit
555 * characters generate +ve values, and ideally we also want to make
556 * the argument match the declared parameter type of "int".
558 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
562 /*********************************************************************
564 * Function : block_acl
566 * Description : Block this request?
567 * Decide yes or no based on ACL file.
570 * 1 : dst = The proxy or gateway address this is going to.
571 * Or NULL to check all possible targets.
572 * 2 : csp = Current client state (buffers, headers, etc...)
573 * Also includes the client IP address.
575 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
577 *********************************************************************/
578 int block_acl(struct access_control_addr *dst, struct client_state *csp)
580 struct access_control_list *acl = csp->config->acl;
582 /* if not using an access control list, then permit the connection */
588 /* search the list */
591 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
595 /* Just want to check if they have any access */
596 if (acl->action == ACL_PERMIT)
601 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
602 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
604 if (acl->action == ACL_PERMIT)
622 /*********************************************************************
624 * Function : acl_addr
626 * Description : Called from `load_config' to parse an ACL address.
629 * 1 : aspec = String specifying ACL address.
630 * 2 : aca = struct access_control_addr to fill in.
632 * Returns : 0 => Ok, everything else is an error.
634 *********************************************************************/
635 int acl_addr(char *aspec, struct access_control_addr *aca)
637 int i, masklength, port;
643 if ((p = strchr(aspec, '/')) != NULL)
647 if (ijb_isdigit(*p) == 0)
651 masklength = atoi(p);
654 if ((masklength < 0) || (masklength > 32))
659 if ((p = strchr(aspec, ':')) != NULL)
663 if (ijb_isdigit(*p) == 0)
672 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
674 if (aca->addr == INADDR_NONE)
679 /* build the netmask */
681 for (i=1; i <= masklength ; i++)
683 aca->mask |= (1 << (32 - i));
686 /* now mask off the host portion of the ip address
687 * (i.e. save on the network portion of the address).
689 aca->addr = aca->addr & aca->mask;
694 #endif /* def FEATURE_ACL */
697 /*********************************************************************
699 * Function : match_portlist
701 * Description : Check if a given number is covered by a comma
702 * separated list of numbers and ranges (a,b-c,d,..)
705 * 1 : portlist = String with list
706 * 2 : port = port to check
708 * Returns : 0 => no match
711 *********************************************************************/
712 int match_portlist(const char *portlist, int port)
714 char *min, *max, *next, *portlist_copy;
716 min = next = portlist_copy = strdup(portlist);
719 * Zero-terminate first item and remember offset for next
721 if (NULL != (next = strchr(portlist_copy, (int) ',')))
727 * Loop through all items, checking for match
731 if (NULL == (max = strchr(min, (int) '-')))
734 * No dash, check for equality
736 if (port == atoi(min))
745 * This is a range, so check if between min and max,
746 * or, if max was omitted, between min and 65K
749 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
763 * Zero-terminate next item and remember offset for n+1
765 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
777 /*********************************************************************
779 * Function : block_url
781 * Description : Called from `chat'. Check to see if we need to block this.
784 * 1 : csp = Current client state (buffers, headers, etc...)
786 * Returns : NULL => unblocked, else HTTP block response
788 *********************************************************************/
789 struct http_response *block_url(struct client_state *csp)
791 struct http_response *rsp;
792 const char *new_content_type = NULL;
795 * If it's not blocked, don't block it ;-)
797 if ((csp->action->flags & ACTION_BLOCK) == 0)
801 if (csp->action->flags & ACTION_REDIRECT)
803 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
806 * Else, prepare a response
808 if (NULL == (rsp = alloc_http_response()))
810 return cgi_error_memory();
814 * If it's an image-url, send back an image or redirect
815 * as specified by the relevant +image action
817 #ifdef FEATURE_IMAGE_BLOCKING
818 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
822 /* determine HOW images should be blocked */
823 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
825 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
827 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
829 #if 1 /* Two alternative strategies, use this one for now: */
831 /* and handle accordingly: */
832 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
834 rsp->status = strdup("403 Request blocked by Privoxy");
835 if (rsp->status == NULL)
837 free_http_response(rsp);
838 return cgi_error_memory();
840 rsp->body = bindup(image_pattern_data, image_pattern_length);
841 if (rsp->body == NULL)
843 free_http_response(rsp);
844 return cgi_error_memory();
846 rsp->content_length = image_pattern_length;
848 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
850 free_http_response(rsp);
851 return cgi_error_memory();
855 else if (0 == strcmpic(p, "blank"))
857 rsp->status = strdup("403 Request blocked by Privoxy");
858 if (rsp->status == NULL)
860 free_http_response(rsp);
861 return cgi_error_memory();
863 rsp->body = bindup(image_blank_data, image_blank_length);
864 if (rsp->body == NULL)
866 free_http_response(rsp);
867 return cgi_error_memory();
869 rsp->content_length = image_blank_length;
871 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
873 free_http_response(rsp);
874 return cgi_error_memory();
880 rsp->status = strdup("302 Local Redirect from Privoxy");
881 if (rsp->status == NULL)
883 free_http_response(rsp);
884 return cgi_error_memory();
887 if (enlist_unique_header(rsp->headers, "Location", p))
889 free_http_response(rsp);
890 return cgi_error_memory();
894 #else /* Following code is disabled for now */
896 /* and handle accordingly: */
897 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
899 p = CGI_PREFIX "send-banner?type=pattern";
901 else if (0 == strcmpic(p, "blank"))
903 p = CGI_PREFIX "send-banner?type=blank";
905 rsp->status = strdup("302 Local Redirect from Privoxy");
906 if (rsp->status == NULL)
908 free_http_response(rsp);
909 return cgi_error_memory();
912 if (enlist_unique_header(rsp->headers, "Location", p))
914 free_http_response(rsp);
915 return cgi_error_memory();
917 #endif /* Preceeding code is disabled for now */
919 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
922 * Send empty document.
924 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
927 rsp->body = strdup(" ");
928 rsp->content_length = 1;
930 rsp->status = strdup("403 Request blocked by Privoxy");
931 if (rsp->status == NULL)
933 free_http_response(rsp);
934 return cgi_error_memory();
936 if (new_content_type != 0)
938 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
939 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
941 free_http_response(rsp);
942 return cgi_error_memory();
947 #endif /* def FEATURE_IMAGE_BLOCKING */
950 * Else, generate an HTML "blocked" message:
954 struct map * exports;
958 * Workaround for stupid Netscape bug which prevents
959 * pages from being displayed if loading a referenced
960 * JavaScript or style sheet fails. So make it appear
961 * as if it succeeded.
963 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
964 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
965 && !strstr(p, "Gecko") /* save Mozilla, */
966 && !strstr(p, "compatible") /* MSIE */
967 && !strstr(p, "Opera")) /* and Opera. */
969 rsp->status = strdup("200 Request for blocked URL");
973 rsp->status = strdup("404 Request for blocked URL");
976 if (rsp->status == NULL)
978 free_http_response(rsp);
979 return cgi_error_memory();
982 exports = default_exports(csp, NULL);
985 free_http_response(rsp);
986 return cgi_error_memory();
989 #ifdef FEATURE_FORCE_LOAD
990 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
991 if (csp->http->ssl != 0)
992 #endif /* ndef FEATURE_FORCE_LOAD */
994 err = map_block_killer(exports, "force-support");
997 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
998 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
999 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1000 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
1005 free_http_response(rsp);
1006 return cgi_error_memory();
1009 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
1012 free_http_response(rsp);
1013 return cgi_error_memory();
1017 return finish_http_response(rsp);
1022 #ifdef FEATURE_TRUST
1023 /*********************************************************************
1025 * Function : trust_url FIXME: I should be called distrust_url
1027 * Description : Calls is_untrusted_url to determine if the URL is trusted
1028 * and if not, returns a HTTP 403 response with a reject message.
1031 * 1 : csp = Current client state (buffers, headers, etc...)
1033 * Returns : NULL => trusted, else http_response.
1035 *********************************************************************/
1036 struct http_response *trust_url(struct client_state *csp)
1038 struct http_response *rsp;
1039 struct map * exports;
1040 char buf[BUFFER_SIZE];
1042 struct url_spec **tl;
1047 * Don't bother to work on trusted URLs
1049 if (!is_untrusted_url(csp))
1055 * Else, prepare a response:
1057 if (NULL == (rsp = alloc_http_response()))
1059 return cgi_error_memory();
1062 rsp->status = strdup("403 Request blocked by Privoxy");
1063 exports = default_exports(csp, NULL);
1064 if (exports == NULL || rsp->status == NULL)
1066 free_http_response(rsp);
1067 return cgi_error_memory();
1071 * Export the protocol, host, port, and referrer information
1073 err = map(exports, "hostport", 1, csp->http->hostport, 1);
1074 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1075 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1077 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1079 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1083 if (!err) err = map(exports, "referrer", 1, "none set", 1);
1089 free_http_response(rsp);
1090 return cgi_error_memory();
1094 * Export the trust list
1097 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1099 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
1100 string_append(&p, buf);
1102 err = map(exports, "trusted-referrers", 1, p, 0);
1107 free_http_response(rsp);
1108 return cgi_error_memory();
1112 * Export the trust info, if available
1114 if (csp->config->trust_info->first)
1116 struct list_entry *l;
1119 for (l = csp->config->trust_info->first; l ; l = l->next)
1121 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
1122 string_append(&p, buf);
1124 err = map(exports, "trust-info", 1, p, 0);
1128 err = map_block_killer(exports, "have-trust-info");
1134 free_http_response(rsp);
1135 return cgi_error_memory();
1139 * Export the force prefix or the force conditional block killer
1141 #ifdef FEATURE_FORCE_LOAD
1142 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1143 #else /* ifndef FEATURE_FORCE_LOAD */
1144 err = map_block_killer(exports, "force-support");
1145 #endif /* ndef FEATURE_FORCE_LOAD */
1150 free_http_response(rsp);
1151 return cgi_error_memory();
1155 * Build the response
1157 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1160 free_http_response(rsp);
1161 return cgi_error_memory();
1164 return finish_http_response(rsp);
1166 #endif /* def FEATURE_TRUST */
1168 /*********************************************************************
1170 * Function : execute_single_pcrs_command
1172 * Description : Apply single pcrs command to the subject.
1173 * The subject itself is left untouched, memory for the result
1174 * is malloc()ed and it is the caller's responsibility to free
1175 * the result when it's no longer needed.
1178 * 1 : subject = the subject (== original) string
1179 * 2 : pcrs_command = the pcrs command as string (s@foo@bar@)
1180 * 3 : hits = int* for returning the number of modifications
1182 * Returns : NULL in case of errors, otherwise the
1183 * result of the pcrs command.
1185 *********************************************************************/
1186 char *execute_single_pcrs_command(char *subject, const char *pcrs_command, int *hits)
1190 char *result = NULL;
1194 assert(pcrs_command);
1197 size = strlen(subject);
1199 if (NULL == (job = pcrs_compile_command(pcrs_command, &error)))
1201 log_error(LOG_LEVEL_ERROR, "Failed to compile pcrs command \"%s\". Error: %d.",
1202 pcrs_command, error);
1204 else if ((*hits = pcrs_execute(job, subject, size, &result, &size)) < 0)
1206 log_error(LOG_LEVEL_ERROR, "Failed to execute pcrs command: %s", pcrs_strerror(*hits));
1213 job = pcrs_free_job(job);
1220 /*********************************************************************
1222 * Function : rewrite_url
1224 * Description : Rewrites a URL with a single pcrs command
1225 * and returns the result if it differs from the
1226 * original and isn't obviously invalid.
1229 * 1 : old_url = URL to rewrite.
1230 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1233 * Returns : NULL if the pcrs_command didn't change the url, or
1234 * the result of the modification.
1236 *********************************************************************/
1237 char *rewrite_url(char *old_url, const char *pcrs_command)
1239 char *new_url = NULL;
1243 assert(pcrs_command);
1245 new_url = execute_single_pcrs_command(old_url, pcrs_command, &hits);
1249 log_error(LOG_LEVEL_REDIRECTS,
1250 "pcrs command \"%s\" didn't change \"%s\".",
1251 pcrs_command, old_url, new_url);
1254 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1256 log_error(LOG_LEVEL_ERROR,
1257 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1258 "but the result doesn't look like a valid URL and will be ignored.",
1259 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1264 log_error(LOG_LEVEL_REDIRECTS,
1265 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1266 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1274 #ifdef FEATURE_FAST_REDIRECTS
1275 /*********************************************************************
1277 * Function : get_last_url
1279 * Description : Search for the last URL inside a string.
1280 * If the string already is a URL, it will
1281 * be the first URL found.
1284 * 1 : subject = the string to check
1285 * 2 : redirect_mode = +fast-redirect{} mode
1287 * Returns : NULL if no URL was found, or
1288 * the last URL found.
1290 *********************************************************************/
1291 char *get_last_url(char *subject, const char *redirect_mode)
1293 char *new_url = NULL;
1297 assert(redirect_mode);
1299 subject = strdup(subject);
1300 if (subject == NULL)
1302 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1306 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1308 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1309 new_url = url_decode(subject);
1310 if (new_url != NULL)
1317 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1321 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1324 * Find the last URL encoded in the request
1327 while ((tmp = strstr(tmp, "http://")) != NULL)
1331 tmp = (new_url != NULL) ? new_url : subject;
1332 while ((tmp = strstr(tmp, "https://")) != NULL)
1337 if ((new_url != NULL)
1338 && ( (new_url != subject)
1339 || (0 == strncmpic(subject, "http://", 7))
1340 || (0 == strncmpic(subject, "https://", 8))
1344 * Return new URL if we found a redirect
1345 * or if the subject already was a URL.
1347 * The second case makes sure that we can
1348 * chain get_last_url after another redirection check
1349 * (like rewrite_url) without losing earlier redirects.
1351 new_url = strdup(new_url);
1360 #endif /* def FEATURE_FAST_REDIRECTS */
1363 /*********************************************************************
1365 * Function : redirect_url
1367 * Description : Checks if Privoxy should answer the request with
1368 * a HTTP redirect and generates the redirect if
1372 * 1 : csp = Current client state (buffers, headers, etc...)
1374 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1376 *********************************************************************/
1377 struct http_response *redirect_url(struct client_state *csp)
1379 struct http_response *rsp;
1380 #ifdef FEATURE_FAST_REDIRECTS
1382 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1383 * as compile-time option? The user can easily disable
1384 * it in his action file.
1386 char * redirect_mode;
1387 #endif /* def FEATURE_FAST_REDIRECTS */
1388 char *old_url = NULL;
1389 char *new_url = NULL;
1390 char *redirection_string;
1392 if ((csp->action->flags & ACTION_REDIRECT))
1394 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1397 * If the redirection string begins with 's',
1398 * assume it's a pcrs command, otherwise treat it as
1399 * properly formatted URL and use it for the redirection
1402 * According to RFC 2616 section 14.30 the URL
1403 * has to be absolute and if the user tries:
1404 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1405 * she would get undefined results anyway.
1409 if (*redirection_string == 's')
1411 old_url = csp->http->url;
1412 new_url = rewrite_url(old_url, redirection_string);
1416 log_error(LOG_LEVEL_REDIRECTS,
1417 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1418 redirection_string);
1419 new_url = strdup(redirection_string);
1423 #ifdef FEATURE_FAST_REDIRECTS
1424 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1426 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1429 * If it exists, use the previously rewritten URL as input
1430 * otherwise just use the old path.
1432 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1433 new_url = get_last_url(old_url, redirect_mode);
1436 #endif /* def FEATURE_FAST_REDIRECTS */
1438 /* Did any redirect action trigger? */
1441 if (0 == strcmpic(new_url, csp->http->url))
1443 log_error(LOG_LEVEL_ERROR,
1444 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1445 csp->http->url, new_url);
1450 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1452 if (NULL == (rsp = alloc_http_response()))
1455 return cgi_error_memory();
1458 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1459 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1462 free_http_response(rsp);
1463 return cgi_error_memory();
1466 return finish_http_response(rsp);
1470 /* Only reached if no redirect is required */
1476 #ifdef FEATURE_IMAGE_BLOCKING
1477 /*********************************************************************
1479 * Function : is_imageurl
1481 * Description : Given a URL, decide whether it is an image or not,
1482 * using either the info from a previous +image action
1483 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1484 * is MSIE and not on a Mac, tell from the browser's accept
1488 * 1 : csp = Current client state (buffers, headers, etc...)
1490 * Returns : True (nonzero) if URL is an image, false (0)
1493 *********************************************************************/
1494 int is_imageurl(const struct client_state *csp)
1496 #ifdef FEATURE_IMAGE_DETECT_MSIE
1499 tmp = get_header_value(csp->headers, "User-Agent:");
1500 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1502 tmp = get_header_value(csp->headers, "Accept:");
1503 if (tmp && strstr(tmp, "image/gif"))
1505 /* Client will accept HTML. If this seems counterintuitive,
1515 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1517 return ((csp->action->flags & ACTION_IMAGE) != 0);
1520 #endif /* def FEATURE_IMAGE_BLOCKING */
1523 #ifdef FEATURE_TRUST
1524 /*********************************************************************
1526 * Function : is_untrusted_url
1528 * Description : Should we "distrust" this URL (and block it)?
1530 * Yes if it matches a line in the trustfile, or if the
1531 * referrer matches a line starting with "+" in the
1536 * 1 : csp = Current client state (buffers, headers, etc...)
1538 * Returns : 0 => trusted, 1 => untrusted
1540 *********************************************************************/
1541 int is_untrusted_url(const struct client_state *csp)
1543 struct file_list *fl;
1544 struct block_spec *b;
1545 struct url_spec **trusted_url;
1546 struct http_request rhttp[1];
1547 const char * referer;
1551 * If we don't have a trustlist, we trust everybody
1553 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1558 memset(rhttp, '\0', sizeof(*rhttp));
1561 * Do we trust the request URL itself?
1563 for (b = b->next; b ; b = b->next)
1565 if (url_match(b->url, csp->http))
1571 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1573 /* no referrer was supplied */
1579 * If not, do we maybe trust its referrer?
1581 err = parse_http_url(referer, rhttp, csp);
1587 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1589 if (url_match(*trusted_url, rhttp))
1591 /* if the URL's referrer is from a trusted referrer, then
1592 * add the target spec to the trustfile as an unblocked
1593 * domain and return 0 (which means it's OK).
1598 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1602 char * new_entry = strdup("~");
1604 string_append(&new_entry, csp->http->hostport);
1606 path = csp->http->path;
1607 if ( (path[0] == '/')
1609 && ((path_end = strchr(path + 2, '/')) != NULL))
1611 /* since this path points into a user's home space
1612 * be sure to include this spec in the trustfile.
1614 int path_len = path_end - path; /* save offset */
1615 path = strdup(path); /* Copy string */
1618 path_end = path + path_len; /* regenerate ptr to new buffer */
1619 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1621 string_join(&new_entry, path);
1625 * Give a reason for generating this entry.
1627 string_append(&new_entry, " # Trusted referrer was: ");
1628 string_append(&new_entry, referer);
1630 if (new_entry != NULL)
1632 if (-1 == fprintf(fp, "%s\n", new_entry))
1634 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1635 new_entry, csp->config->trustfile);
1641 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1642 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1649 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1650 csp->http->hostport, csp->config->trustfile);
1657 #endif /* def FEATURE_TRUST */
1660 /*********************************************************************
1662 * Function : pcrs_filter_response
1664 * Description : Execute all text substitutions from all applying
1665 * +filter actions on the text buffer that's been accumulated
1666 * in csp->iob->buf. If this changes the contents, set
1667 * csp->content_length to the modified size and raise the
1668 * CSP_FLAG_MODIFIED flag.
1670 * XXX: Currently pcrs_filter_response is also responsible
1671 * for dechunking and decompressing. Both should be
1672 * done in separate functions so other content modifiers
1673 * profit as well, even if pcrs filtering is disabled.
1676 * 1 : csp = Current client state (buffers, headers, etc...)
1678 * Returns : a pointer to the (newly allocated) modified buffer.
1679 * or NULL if there were no hits or something went wrong
1681 *********************************************************************/
1682 char *pcrs_filter_response(struct client_state *csp)
1685 size_t size, prev_size;
1687 char *old = csp->iob->cur, *new = NULL;
1690 struct file_list *fl;
1691 struct re_filterfile_spec *b;
1692 struct list_entry *filtername;
1694 int i, found_filters = 0;
1699 if (csp->iob->cur >= csp->iob->eod)
1703 size = (size_t)(csp->iob->eod - csp->iob->cur);
1706 * Need to check the set of re_filterfiles...
1708 for (i = 0; i < MAX_AF_FILES; i++)
1721 if (0 == found_filters)
1723 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1728 * If the body has a "chunked" transfer-encoding,
1729 * get rid of it first, adjusting size and iob->eod
1731 if (csp->flags & CSP_FLAG_CHUNKED)
1733 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1734 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1738 csp->iob->eod = csp->iob->cur + size;
1739 csp->flags |= CSP_FLAG_MODIFIED;
1744 * If the body has a compressed transfer-encoding,
1745 * uncompress it first, adjusting size and iob->eod.
1746 * Note that decompression occurs after de-chunking.
1748 if (csp->content_type & CT_GZIP || csp->content_type & CT_DEFLATE)
1750 /* Notice that we at least tried to decompress. */
1751 if (JB_ERR_OK != decompress_iob(csp))
1754 * We failed to decompress the data; there's no point
1755 * in continuing since we can't filter. This is
1756 * slightly tricky because we need to remember not to
1757 * modify the Content-Encoding header later; using
1758 * CT_TABOO flag is a kludge for this purpose.
1760 csp->content_type |= CT_TABOO;
1763 log_error(LOG_LEVEL_RE_FILTER, "Decompressing successful");
1766 * Decompression gives us a completely new iob,
1767 * so we need to update.
1769 size = (size_t)(csp->iob->eod - csp->iob->cur);
1770 old = csp->iob->cur;
1772 csp->flags |= CSP_FLAG_MODIFIED;
1773 csp->content_type &= ~CT_TABOO;
1777 for (i = 0; i < MAX_AF_FILES; i++)
1780 if ((NULL == fl) || (NULL == fl->f))
1783 * Either there are no filter files
1784 * left, or this filter file just
1785 * contains no valid filters.
1787 * Continue to be sure we don't miss
1788 * valid filter files that are chained
1789 * after empty or invalid ones.
1794 * For all applying +filter actions, look if a filter by that
1795 * name exists and if yes, execute it's pcrs_joblist on the
1798 for (b = fl->f; b; b = b->next)
1800 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1801 filtername ; filtername = filtername->next)
1803 if (strcmp(b->name, filtername->str) == 0)
1805 int current_hits = 0; /* Number of hits caused by this filter */
1806 int job_number = 0; /* Which job we're currently executing */
1807 int job_hits = 0; /* How many hits the current job caused */
1809 if ( NULL == b->joblist )
1811 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1816 /* Apply all jobs from the joblist */
1817 for (job = b->joblist; NULL != job; job = job->next)
1820 job_hits = pcrs_execute(job, old, size, &new, &size);
1825 * That went well. Continue filtering
1826 * and use the result of this job as
1827 * input for the next one.
1829 current_hits += job_hits;
1830 if (old != csp->iob->cur)
1839 * This job caused an unexpected error. Inform the user
1840 * and skip the rest of the jobs in this filter. We could
1841 * continue with the next job, but usually the jobs
1842 * depend on each other or are similar enough to
1843 * fail for the same reason.
1845 * At the moment our pcrs expects the error codes of pcre 3.4,
1846 * but newer pcre versions can return additional error codes.
1847 * As a result pcrs_strerror()'s error message might be
1848 * "Unknown error ...", therefore we print the numerical value
1851 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1852 * should we use LOG_LEVEL_RE_FILTER instead?
1854 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1855 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1860 log_error(LOG_LEVEL_RE_FILTER,
1861 "re_filtering %s%s (size %d) with filter %s produced %d hits (new size %d).",
1862 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1864 hits += current_hits;
1871 * If there were no hits, destroy our copy and let
1872 * chat() use the original in csp->iob
1880 csp->flags |= CSP_FLAG_MODIFIED;
1881 csp->content_length = size;
1889 /*********************************************************************
1891 * Function : gif_deanimate_response
1893 * Description : Deanimate the GIF image that has been accumulated in
1894 * csp->iob->buf, set csp->content_length to the modified
1895 * size and raise the CSP_FLAG_MODIFIED flag.
1898 * 1 : csp = Current client state (buffers, headers, etc...)
1900 * Returns : a pointer to the (newly allocated) modified buffer.
1901 * or NULL in case something went wrong.
1903 *********************************************************************/
1904 char *gif_deanimate_response(struct client_state *csp)
1906 struct binbuffer *in, *out;
1910 size = (size_t)(csp->iob->eod - csp->iob->cur);
1913 * If the body has a "chunked" transfer-encoding,
1914 * get rid of it first, adjusting size and iob->eod
1916 if (csp->flags & CSP_FLAG_CHUNKED)
1918 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1919 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1923 csp->iob->eod = csp->iob->cur + size;
1924 csp->flags |= CSP_FLAG_MODIFIED;
1927 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1928 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1930 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1934 in->buffer = csp->iob->cur;
1937 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1939 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1946 if ((int)size == out->offset)
1948 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1952 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1954 csp->content_length = out->offset;
1955 csp->flags |= CSP_FLAG_MODIFIED;
1965 /*********************************************************************
1967 * Function : jpeg_inspect_response
1972 * 1 : csp = Current client state (buffers, headers, etc...)
1974 * Returns : a pointer to the (newly allocated) modified buffer
1975 * or NULL in case something went wrong.
1977 *********************************************************************/
1978 char *jpeg_inspect_response(struct client_state *csp)
1980 struct binbuffer *in = NULL;
1981 struct binbuffer *out = NULL;
1985 size = (size_t)(csp->iob->eod - csp->iob->cur);
1988 * If the body has a "chunked" transfer-encoding,
1989 * get rid of it first, adjusting size and iob->eod
1991 if (csp->flags & CSP_FLAG_CHUNKED)
1993 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1994 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1998 csp->iob->eod = csp->iob->cur + size;
1999 csp->flags |= CSP_FLAG_MODIFIED;
2002 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
2004 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
2008 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
2010 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
2014 in->buffer = csp->iob->cur;
2018 * Calling jpeg_inspect has the side-effect of creating and
2019 * modifying the image buffer of "out" directly.
2021 if (jpeg_inspect(in, out))
2023 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
2031 csp->content_length = out->offset;
2032 csp->flags |= CSP_FLAG_MODIFIED;
2042 /*********************************************************************
2044 * Function : remove_chunked_transfer_coding
2046 * Description : In-situ remove the "chunked" transfer coding as defined
2047 * in rfc2616 from a buffer.
2050 * 1 : buffer = Pointer to the text buffer
2051 * 2 : size = Number of bytes to be processed
2053 * Returns : The new size, i.e. the number of bytes from buffer which
2054 * are occupied by the stripped body, or 0 in case something
2057 *********************************************************************/
2058 size_t remove_chunked_transfer_coding(char *buffer, const size_t size)
2061 unsigned int chunksize = 0;
2062 char *from_p, *to_p;
2065 from_p = to_p = buffer;
2067 if (sscanf(buffer, "%x", &chunksize) != 1)
2069 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2073 while (chunksize > 0)
2075 if (NULL == (from_p = strstr(from_p, "\r\n")))
2077 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2081 if ((newsize += chunksize) >= size)
2083 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
2088 memmove(to_p, from_p, (size_t) chunksize);
2089 to_p = buffer + newsize;
2090 from_p += chunksize + 2;
2092 if (sscanf(from_p, "%x", &chunksize) != 1)
2094 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2099 /* FIXME: Should this get its own loglevel? */
2100 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
2106 /*********************************************************************
2108 * Function : url_actions
2110 * Description : Gets the actions for this URL.
2113 * 1 : http = http_request request for blocked URLs
2114 * 2 : csp = Current client state (buffers, headers, etc...)
2118 *********************************************************************/
2119 void url_actions(struct http_request *http,
2120 struct client_state *csp)
2122 struct file_list *fl;
2123 struct url_actions *b;
2126 init_current_action(csp->action);
2128 for (i = 0; i < MAX_AF_FILES; i++)
2130 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2135 apply_url_actions(csp->action, http, b);
2142 /*********************************************************************
2144 * Function : apply_url_actions
2146 * Description : Applies a list of URL actions.
2149 * 1 : action = Destination.
2150 * 2 : http = Current URL
2151 * 3 : b = list of URL actions to apply
2155 *********************************************************************/
2156 void apply_url_actions(struct current_action_spec *action,
2157 struct http_request *http,
2158 struct url_actions *b)
2162 /* Should never happen */
2166 for (b = b->next; NULL != b; b = b->next)
2168 if (url_match(b->url, http))
2170 merge_current_action(action, b->action);
2176 /*********************************************************************
2178 * Function : forward_url
2180 * Description : Should we forward this to another proxy?
2183 * 1 : http = http_request request for current URL
2184 * 2 : csp = Current client state (buffers, headers, etc...)
2186 * Returns : Pointer to forwarding information.
2188 *********************************************************************/
2189 const struct forward_spec * forward_url(struct http_request *http,
2190 struct client_state *csp)
2192 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2193 struct forward_spec *fwd = csp->config->forward;
2202 if (url_match(fwd->url, http))
2213 /*********************************************************************
2215 * Function : direct_response
2217 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2218 * request and if so, return a HTTP 501 to the client.
2220 * FIXME: I have a stupid name and I should handle the
2221 * requests properly. Still, what we do here is rfc-
2222 * compliant, whereas ignoring or forwarding are not.
2225 * 1 : csp = Current client state (buffers, headers, etc...)
2227 * Returns : http_response if , NULL if nonmatch or handler fail
2229 *********************************************************************/
2230 struct http_response *direct_response(struct client_state *csp)
2232 struct http_response *rsp;
2233 struct list_entry *p;
2235 if ((0 == strcmpic(csp->http->gpc, "trace"))
2236 || (0 == strcmpic(csp->http->gpc, "options")))
2238 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2240 if (!strncmp("Max-Forwards:", p->str, 13)
2241 && (*(p->str+13) != '\0') && (atoi(p->str+13) == 0))
2243 /* FIXME: We could handle at least TRACE here,
2244 but that would require a verbatim copy of
2245 the request which we don't have anymore */
2247 log_error(LOG_LEVEL_HEADER, "Found Max-Forwards:0 in OPTIONS or TRACE request -- Returning 501");
2249 /* Get mem for response or fail*/
2250 if (NULL == (rsp = alloc_http_response()))
2252 return cgi_error_memory();
2255 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2257 free_http_response(rsp);
2258 return cgi_error_memory();
2262 return(finish_http_response(rsp));