1 const char filters_rcs[] = "$Id: filters.c,v 1.75 2006/12/29 18:30:46 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.75 2006/12/29 18:30:46 fabiankeil
44 * Fixed gcc43 conversion warnings,
45 * changed sprintf calls to snprintf.
47 * Revision 1.74 2006/12/24 17:37:38 fabiankeil
48 * Adjust comment in pcrs_filter_response()
49 * to recent pcrs changes. Hohoho.
51 * Revision 1.73 2006/12/23 16:01:02 fabiankeil
52 * Don't crash if pcre returns an error code
53 * that pcrs didn't expect. Fixes BR 1621173.
55 * Revision 1.72 2006/12/22 18:52:53 fabiankeil
56 * Modified is_untrusted_url to complain in case of
57 * write errors and to give a reason when adding new
58 * entries to the trustfile. Closes FR 1097611.
60 * Revision 1.71 2006/12/22 14:24:52 fabiankeil
61 * Skip empty filter files in pcrs_filter_response,
62 * but don't ignore the ones that come afterwards.
63 * Fixes parts of BR 1619208.
65 * Revision 1.70 2006/12/09 13:33:15 fabiankeil
66 * Added some sanity checks for get_last_url().
67 * Fixed possible segfault caused by my last commit.
69 * Revision 1.69 2006/12/08 12:39:13 fabiankeil
70 * Let get_last_url() catch https URLs as well.
72 * Revision 1.68 2006/12/05 14:45:48 fabiankeil
73 * Make sure get_last_url() behaves like advertised
74 * and fast-redirects{} can be combined with redirect{}.
76 * Revision 1.67 2006/11/28 15:19:43 fabiankeil
77 * Implemented +redirect{s@foo@bar@} to generate
78 * a redirect based on a rewritten version of the
81 * Revision 1.66 2006/09/23 13:26:38 roro
82 * Replace TABs by spaces in source code.
84 * Revision 1.65 2006/09/21 12:54:43 fabiankeil
85 * Fix +redirect{}. Didn't work with -fast-redirects.
87 * Revision 1.64 2006/08/31 10:55:49 fabiankeil
88 * Block requests for untrusted URLs with status
89 * code 403 instead of 200.
91 * Revision 1.63 2006/08/31 10:11:28 fabiankeil
92 * Don't free p which is still in use and will be later
93 * freed by free_map(). Don't claim the referrer is unknown
94 * when the client didn't set one.
96 * Revision 1.62 2006/08/14 00:27:47 david__schmidt
97 * Feature request 595948: Re-Filter logging in single line
99 * Revision 1.61 2006/08/03 02:46:41 david__schmidt
100 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
102 * Revision 1.60 2006/07/18 14:48:46 david__schmidt
103 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
104 * with what was really the latest development (the v_3_0_branch branch)
106 * Revision 1.58.2.9 2006/01/29 23:10:56 david__schmidt
107 * Multiple filter file support
109 * Revision 1.58.2.8 2005/05/07 21:50:55 david__schmidt
110 * A few memory leaks plugged (mostly on error paths)
112 * Revision 1.58.2.7 2004/10/03 12:53:32 david__schmidt
113 * Add the ability to check jpeg images for invalid
114 * lengths of comment blocks. Defensive strategy
115 * against the exploit:
116 * Microsoft Security Bulletin MS04-028
117 * Buffer Overrun in JPEG Processing (GDI+) Could
118 * Allow Code Execution (833987)
119 * Enabled with +inspect-jpegs in actions files.
121 * Revision 1.58.2.6 2003/12/06 22:18:27 gliptak
122 * Correcting compile problem with FEATURE_IMAGE_BLOCKING
124 * Revision 1.58.2.5 2003/11/11 13:10:31 oes
125 * Fixed bug #839859: "See why" link URL now gets url-encoded.
127 * Revision 1.58.2.4 2003/02/28 12:52:45 oes
130 * Revision 1.58.2.3 2002/09/25 14:51:51 oes
131 * Added basic support for OPTIONS and TRACE HTTP methods:
132 * New function direct_response which handles OPTIONS and
133 * TRACE requests whose Max-Forwards header field is zero.
135 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
136 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
138 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
139 * - Bugfix: Executing a filters without jobs no longer results in
140 * turing off *all* filters.
141 * - Security fix: Malicious web servers can't cause a seg fault
142 * through bogus chunk sizes anymore
144 * Revision 1.58 2002/04/24 02:11:17 oes
145 * Jon's multiple AF patch: url_actions now evaluates rules
148 * Revision 1.57 2002/04/08 20:38:34 swa
151 * Revision 1.56 2002/04/05 15:51:24 oes
152 * - bugfix: error-pages now get correct request protocol
153 * - fix for invalid HTML in trust info
155 * Revision 1.55 2002/04/02 16:13:51 oes
156 * Fix: No "Go there anyway" for SSL
158 * Revision 1.54 2002/04/02 14:55:56 oes
159 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
161 * Revision 1.53 2002/03/26 22:29:54 swa
162 * we have a new homepage!
164 * Revision 1.52 2002/03/24 16:35:57 jongfoster
167 * Revision 1.51 2002/03/24 15:23:33 jongfoster
170 * Revision 1.50 2002/03/24 13:25:43 swa
171 * name change related issues
173 * Revision 1.49 2002/03/16 20:29:14 oes
176 * Revision 1.48 2002/03/13 20:25:34 oes
177 * Better logging for content filters
179 * Revision 1.47 2002/03/13 00:30:52 jongfoster
181 * Added option of always sending redirect for imageblock,
182 * currently disabled with #if 0.
184 * Revision 1.46 2002/03/12 01:42:49 oes
185 * Introduced modular filters
187 * Revision 1.45 2002/03/08 16:47:50 oes
188 * Added choice beween GIF and PNG built-in images
190 * Revision 1.44 2002/03/07 03:49:31 oes
191 * - Fixed compiler warnings etc
192 * - Changed built-in images from GIF to PNG
193 * (with regard to Unisys patent issue)
194 * - Added a 4x4 pattern PNG which is less intrusive
195 * than the logo but also clearly marks the deleted banners
197 * Revision 1.43 2002/01/22 23:51:59 jongfoster
198 * Replacing strsav() with the safer string_append().
200 * Adding missing html_encode() to error message generators. Where encoded
201 * and unencoded versions of a string were provided, removing the unencoded
204 * Revision 1.42 2002/01/17 21:00:32 jongfoster
205 * Moving all our URL and URL pattern parsing code to urlmatch.c.
207 * Using a single, simple url_match(pattern,url) function - rather than
208 * the 3-line match routine which was repeated all over the place.
210 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
212 * Using parse_http_url() to parse URLs without faking a HTTP
213 * request line for parse_http_request().
215 * Revision 1.41 2001/11/13 00:14:07 jongfoster
216 * Fixing stupid bug now I've figured out what || means.
217 * (It always returns 0 or 1, not one of it's paramaters.)
219 * Revision 1.40 2001/10/26 17:37:55 oes
220 * - Re-enabled Netscape 200/404 bug workaround in block_url():
221 * - Removed OS/2 special case
222 * - Made block_url() independant from sed() having been run
223 * - Made trust_url independant from sed() having been run
224 * - Made is_imageurl independant from sed() having been run.
225 * It now checks User-Agent: and Accept: by itself.
228 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
229 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
230 * threads to call select() simultaneously. So, it's time to do a real, live,
231 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
232 * (native). Both versions will work, but using __OS2__ offers multi-threading.
234 * Revision 1.38 2001/10/23 21:32:33 jongfoster
235 * Adding error-checking to selected functions
237 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
238 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
239 * filters.c. Added a FIXME in front of the offending code. I'll gladly
240 * put in a better/more robust fix for all parties if one is presented...
241 * It seems that just returning 200 instead of 404 would pretty much fix
242 * it for everyone, but I don't know all the history of the problem.
244 * Revision 1.36 2001/10/10 16:44:16 oes
245 * Added match_portlist function
247 * Revision 1.35 2001/10/07 15:41:23 oes
248 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
250 * New function remove_chunked_transfer_coding that strips chunked
251 * transfer coding to plain and is called by pcrs_filter_response
252 * and gif_deanimate_response if neccessary
254 * Improved handling of zero-change re_filter runs
256 * pcrs_filter_response and gif_deanimate_response now remove
257 * chunked transfer codeing before processing the body.
259 * Revision 1.34 2001/09/20 15:49:36 steudten
261 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
262 * See cgi.c fill_template().
264 * Revision 1.33 2001/09/16 17:05:14 jongfoster
265 * Removing unused #include showarg.h
267 * Revision 1.32 2001/09/16 13:21:27 jongfoster
268 * Changes to use new list functions.
270 * Revision 1.31 2001/09/16 11:38:02 jongfoster
271 * Splitting fill_template() into 2 functions:
272 * template_load() loads the file
273 * template_fill() performs the PCRS regexps.
274 * This is because the CGI edit interface has a "table row"
275 * template which is used many times in the page - this
276 * change means it's only loaded from disk once.
278 * Revision 1.30 2001/09/16 11:00:10 jongfoster
279 * New function alloc_http_response, for symmetry with free_http_response
281 * Revision 1.29 2001/09/13 23:32:40 jongfoster
282 * Moving image data to cgi.c rather than cgi.h
283 * Fixing a GPF under Win32 (and any other OS that protects global
284 * constants from being written to).
286 * Revision 1.28 2001/09/10 10:18:51 oes
287 * Silenced compiler warnings
289 * Revision 1.27 2001/08/05 16:06:20 jongfoster
290 * Modifiying "struct map" so that there are now separate header and
291 * "map_entry" structures. This means that functions which modify a
292 * map no longer need to return a pointer to the modified map.
293 * Also, it no longer reverses the order of the entries (which may be
294 * important with some advanced template substitutions).
296 * Revision 1.26 2001/07/30 22:08:36 jongfoster
297 * Tidying up #defines:
298 * - All feature #defines are now of the form FEATURE_xxx
299 * - Permanently turned off WIN_GUI_EDIT
300 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
302 * Revision 1.25 2001/07/26 10:09:46 oes
303 * Made browser detection a little less naive
305 * Revision 1.24 2001/07/25 17:22:51 oes
306 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
308 * Revision 1.23 2001/07/23 13:40:12 oes
309 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
311 * Revision 1.22 2001/07/18 12:29:34 oes
312 * - Made gif_deanimate_response respect
313 * csp->action->string[ACTION_STRING_DEANIMATE]
314 * - Logging cosmetics
316 * Revision 1.21 2001/07/13 13:59:53 oes
317 * - Introduced gif_deanimate_response which shares the
318 * generic content modification interface of pcrs_filter_response
319 * and acts as a wrapper to deanimate.c:gif_deanimate()
320 * - Renamed re_process_buffer to pcrs_filter_response
321 * - pcrs_filter_response now returns NULL on failiure
322 * - Removed all #ifdef PCRS
324 * Revision 1.20 2001/07/01 17:01:04 oes
325 * Added comments and missing return statement in is_untrusted_url()
327 * Revision 1.19 2001/06/29 21:45:41 oes
328 * Indentation, CRLF->LF, Tab-> Space
330 * Revision 1.18 2001/06/29 13:27:38 oes
331 * - Cleaned up, renamed and reorderd functions
332 * and improved comments
335 * - Ported to CGI platform. Now delivers
336 * http_response or NULL
337 * - Unified HTML and GIF generation (moved image detection
338 * and GIF generation here from jcc.c:chat())
339 * - Fixed HTTP status to:
340 * - 403 (Forbidden) for the "blocked" HTML message
341 * - 200 (OK) for GIF answers
342 * - 302 (Redirect) for redirect to GIF
345 * - Ported to CGI platform. Now delivers
346 * http_response or NULL
347 * - Separated detection of untrusted URL into
348 * (bool)is_untrusted_url
349 * - Added enforcement of untrusted requests
351 * - Moved redirect_url() from cgi.c to here
352 * and ported it to the CGI platform
354 * - Removed logentry from cancelled commit
356 * Revision 1.17 2001/06/09 10:55:28 jongfoster
357 * Changing BUFSIZ ==> BUFFER_SIZE
359 * Revision 1.16 2001/06/07 23:10:26 jongfoster
360 * Allowing unanchored domain patterns to back off and retry
361 * if they partially match. Optimized right-anchored patterns.
362 * Moving ACL and forward files into config file.
363 * Replacing struct gateway with struct forward_spec
365 * Revision 1.15 2001/06/03 19:12:00 oes
366 * extracted-CGI relevant stuff
368 * Revision 1.14 2001/06/01 10:30:55 oes
369 * Added optional left-anchoring to domaincmp
371 * Revision 1.13 2001/05/31 21:21:30 jongfoster
372 * Permissionsfile / actions file changes:
373 * - Changed "permission" to "action" throughout
374 * - changes to file format to allow string parameters
375 * - Moved helper functions to actions.c
377 * Revision 1.12 2001/05/31 17:35:20 oes
379 * - Enhanced domain part globbing with infix and prefix asterisk
380 * matching and optional unanchored operation
382 * Revision 1.11 2001/05/29 11:53:23 oes
383 * "See why" link added to "blocked" page
385 * Revision 1.10 2001/05/29 09:50:24 jongfoster
386 * Unified blocklist/imagelist/permissionslist.
387 * File format is still under discussion, but the internal changes
390 * Also modified interceptor behaviour:
391 * - We now intercept all URLs beginning with one of the following
392 * prefixes (and *only* these prefixes):
394 * * http://ijbswa.sf.net/config/
395 * * http://ijbswa.sourceforge.net/config/
396 * - New interceptors "home page" - go to http://i.j.b/ to see it.
397 * - Internal changes so that intercepted and fast redirect pages
398 * are not replaced with an image.
399 * - Interceptors now have the option to send a binary page direct
400 * to the client. (i.e. ijb-send-banner uses this)
401 * - Implemented show-url-info interceptor. (Which is why I needed
402 * the above interceptors changes - a typical URL is
403 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
404 * The previous mechanism would not have intercepted that, and
405 * if it had been intercepted then it then it would have replaced
408 * Revision 1.9 2001/05/27 22:17:04 oes
410 * - re_process_buffer no longer writes the modified buffer
411 * to the client, which was very ugly. It now returns the
412 * buffer, which it is then written by chat.
414 * - content_length now adjusts the Content-Length: header
415 * for modified documents rather than crunch()ing it.
416 * (Length info in csp->content_length, which is 0 for
417 * unmodified documents)
419 * - For this to work, sed() is called twice when filtering.
421 * Revision 1.8 2001/05/26 17:13:28 jongfoster
422 * Filled in a function comment.
424 * Revision 1.7 2001/05/26 15:26:15 jongfoster
425 * ACL feature now provides more security by immediately dropping
426 * connections from untrusted hosts.
428 * Revision 1.6 2001/05/26 00:28:36 jongfoster
429 * Automatic reloading of config file.
430 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
431 * Most of the global variables have been moved to a new
432 * struct configuration_spec, accessed through csp->config->globalname
433 * Most of the globals remaining are used by the Win32 GUI.
435 * Revision 1.5 2001/05/25 22:34:30 jongfoster
438 * Revision 1.4 2001/05/22 18:46:04 oes
440 * - Enabled filtering banners by size rather than URL
441 * by adding patterns that replace all standard banner
442 * sizes with the "Junkbuster" gif to the re_filterfile
444 * - Enabled filtering WebBugs by providing a pattern
445 * which kills all 1x1 images
447 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
448 * which is selected by the (nonstandard and therefore
449 * capital) letter 'U' in the option string.
450 * It causes the quantifiers to be ungreedy by default.
451 * Appending a ? turns back to greedy (!).
453 * - Added a new interceptor ijb-send-banner, which
454 * sends back the "Junkbuster" gif. Without imagelist or
455 * MSIE detection support, or if tinygif = 1, or the
456 * URL isn't recognized as an imageurl, a lame HTML
457 * explanation is sent instead.
459 * - Added new feature, which permits blocking remote
460 * script redirects and firing back a local redirect
462 * The feature is conditionally compiled, i.e. it
463 * can be disabled with --disable-fast-redirects,
464 * plus it must be activated by a "fast-redirects"
465 * line in the config file, has its own log level
466 * and of course wants to be displayed by show-proxy-args
467 * Note: Boy, all the #ifdefs in 1001 locations and
468 * all the fumbling with configure.in and acconfig.h
469 * were *way* more work than the feature itself :-(
471 * - Because a generic redirect template was needed for
472 * this, tinygif = 3 now uses the same.
474 * - Moved GIFs, and other static HTTP response templates
479 * - Removed some >400 CRs again (Jon, you really worked
482 * Revision 1.3 2001/05/20 16:44:47 jongfoster
483 * Removing last hardcoded Junkbusters.com URLs.
485 * Revision 1.2 2001/05/20 01:21:20 jongfoster
486 * Version 2.9.4 checkin.
487 * - Merged popupfile and cookiefile, and added control over PCRS
488 * filtering, in new "permissionsfile".
489 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
490 * file error you now get a message box (in the Win32 GUI) rather
491 * than the program exiting with no explanation.
492 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
494 * - Removed tabs from "config"
495 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
496 * - Bumped up version number.
498 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
499 * Initial import of version 2.9.3 source tree
502 *********************************************************************/
508 #include <sys/types.h>
517 #endif /* ndef __OS2__ */
518 #include <netinet/in.h>
520 #include <winsock2.h>
521 #endif /* ndef _WIN32 */
525 #endif /* def __OS2__ */
533 #include "jbsockets.h"
534 #include "miscutil.h"
538 #include "deanimate.h"
539 #include "urlmatch.h"
545 const char filters_h_rcs[] = FILTERS_H_VERSION;
547 /* Fix a problem with Solaris. There should be no effect on other
549 * Solaris's isspace() is a macro which uses it's argument directly
550 * as an array index. Therefore we need to make sure that high-bit
551 * characters generate +ve values, and ideally we also want to make
552 * the argument match the declared parameter type of "int".
554 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
558 /*********************************************************************
560 * Function : block_acl
562 * Description : Block this request?
563 * Decide yes or no based on ACL file.
566 * 1 : dst = The proxy or gateway address this is going to.
567 * Or NULL to check all possible targets.
568 * 2 : csp = Current client state (buffers, headers, etc...)
569 * Also includes the client IP address.
571 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
573 *********************************************************************/
574 int block_acl(struct access_control_addr *dst, struct client_state *csp)
576 struct access_control_list *acl = csp->config->acl;
578 /* if not using an access control list, then permit the connection */
584 /* search the list */
587 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
591 /* Just want to check if they have any access */
592 if (acl->action == ACL_PERMIT)
597 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
598 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
600 if (acl->action == ACL_PERMIT)
618 /*********************************************************************
620 * Function : acl_addr
622 * Description : Called from `load_config' to parse an ACL address.
625 * 1 : aspec = String specifying ACL address.
626 * 2 : aca = struct access_control_addr to fill in.
628 * Returns : 0 => Ok, everything else is an error.
630 *********************************************************************/
631 int acl_addr(char *aspec, struct access_control_addr *aca)
633 int i, masklength, port;
639 if ((p = strchr(aspec, '/')) != NULL)
643 if (ijb_isdigit(*p) == 0)
647 masklength = atoi(p);
650 if ((masklength < 0) || (masklength > 32))
655 if ((p = strchr(aspec, ':')) != NULL)
659 if (ijb_isdigit(*p) == 0)
668 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
670 if (aca->addr == INADDR_NONE)
675 /* build the netmask */
677 for (i=1; i <= masklength ; i++)
679 aca->mask |= (1 << (32 - i));
682 /* now mask off the host portion of the ip address
683 * (i.e. save on the network portion of the address).
685 aca->addr = aca->addr & aca->mask;
690 #endif /* def FEATURE_ACL */
693 /*********************************************************************
695 * Function : match_portlist
697 * Description : Check if a given number is covered by a comma
698 * separated list of numbers and ranges (a,b-c,d,..)
701 * 1 : portlist = String with list
702 * 2 : port = port to check
704 * Returns : 0 => no match
707 *********************************************************************/
708 int match_portlist(const char *portlist, int port)
710 char *min, *max, *next, *portlist_copy;
712 min = next = portlist_copy = strdup(portlist);
715 * Zero-terminate first item and remember offset for next
717 if (NULL != (next = strchr(portlist_copy, (int) ',')))
723 * Loop through all items, checking for match
727 if (NULL == (max = strchr(min, (int) '-')))
730 * No dash, check for equality
732 if (port == atoi(min))
741 * This is a range, so check if between min and max,
742 * or, if max was omitted, between min and 65K
745 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
759 * Zero-terminate next item and remember offset for n+1
761 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
773 /*********************************************************************
775 * Function : block_url
777 * Description : Called from `chat'. Check to see if we need to block this.
780 * 1 : csp = Current client state (buffers, headers, etc...)
782 * Returns : NULL => unblocked, else HTTP block response
784 *********************************************************************/
785 struct http_response *block_url(struct client_state *csp)
787 struct http_response *rsp;
788 const char *new_content_type = NULL;
791 * If it's not blocked, don't block it ;-)
793 if ((csp->action->flags & ACTION_BLOCK) == 0)
797 if (csp->action->flags & ACTION_REDIRECT)
799 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
802 * Else, prepare a response
804 if (NULL == (rsp = alloc_http_response()))
806 return cgi_error_memory();
810 * If it's an image-url, send back an image or redirect
811 * as specified by the relevant +image action
813 #ifdef FEATURE_IMAGE_BLOCKING
814 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
818 /* determine HOW images should be blocked */
819 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
821 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
823 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
825 #if 1 /* Two alternative strategies, use this one for now: */
827 /* and handle accordingly: */
828 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
830 rsp->status = strdup("403 Request blocked by Privoxy");
831 if (rsp->status == NULL)
833 free_http_response(rsp);
834 return cgi_error_memory();
836 rsp->body = bindup(image_pattern_data, image_pattern_length);
837 if (rsp->body == NULL)
839 free_http_response(rsp);
840 return cgi_error_memory();
842 rsp->content_length = image_pattern_length;
844 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
846 free_http_response(rsp);
847 return cgi_error_memory();
851 else if (0 == strcmpic(p, "blank"))
853 rsp->status = strdup("403 Request blocked by Privoxy");
854 if (rsp->status == NULL)
856 free_http_response(rsp);
857 return cgi_error_memory();
859 rsp->body = bindup(image_blank_data, image_blank_length);
860 if (rsp->body == NULL)
862 free_http_response(rsp);
863 return cgi_error_memory();
865 rsp->content_length = image_blank_length;
867 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
869 free_http_response(rsp);
870 return cgi_error_memory();
876 rsp->status = strdup("302 Local Redirect from Privoxy");
877 if (rsp->status == NULL)
879 free_http_response(rsp);
880 return cgi_error_memory();
883 if (enlist_unique_header(rsp->headers, "Location", p))
885 free_http_response(rsp);
886 return cgi_error_memory();
890 #else /* Following code is disabled for now */
892 /* and handle accordingly: */
893 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
895 p = CGI_PREFIX "send-banner?type=pattern";
897 else if (0 == strcmpic(p, "blank"))
899 p = CGI_PREFIX "send-banner?type=blank";
901 rsp->status = strdup("302 Local Redirect from Privoxy");
902 if (rsp->status == NULL)
904 free_http_response(rsp);
905 return cgi_error_memory();
908 if (enlist_unique_header(rsp->headers, "Location", p))
910 free_http_response(rsp);
911 return cgi_error_memory();
913 #endif /* Preceeding code is disabled for now */
915 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
918 * Send empty document.
920 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
923 rsp->body = strdup(" ");
924 rsp->content_length = 1;
926 rsp->status = strdup("403 Request blocked by Privoxy");
927 if (rsp->status == NULL)
929 free_http_response(rsp);
930 return cgi_error_memory();
932 if (new_content_type != 0)
934 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
935 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
937 free_http_response(rsp);
938 return cgi_error_memory();
943 #endif /* def FEATURE_IMAGE_BLOCKING */
946 * Else, generate an HTML "blocked" message:
950 struct map * exports;
954 * Workaround for stupid Netscape bug which prevents
955 * pages from being displayed if loading a referenced
956 * JavaScript or style sheet fails. So make it appear
957 * as if it succeeded.
959 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
960 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
961 && !strstr(p, "Gecko") /* save Mozilla, */
962 && !strstr(p, "compatible") /* MSIE */
963 && !strstr(p, "Opera")) /* and Opera. */
965 rsp->status = strdup("200 Request for blocked URL");
969 rsp->status = strdup("404 Request for blocked URL");
972 if (rsp->status == NULL)
974 free_http_response(rsp);
975 return cgi_error_memory();
978 exports = default_exports(csp, NULL);
981 free_http_response(rsp);
982 return cgi_error_memory();
985 #ifdef FEATURE_FORCE_LOAD
986 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
987 if (csp->http->ssl != 0)
988 #endif /* ndef FEATURE_FORCE_LOAD */
990 err = map_block_killer(exports, "force-support");
993 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
994 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
995 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
996 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
1001 free_http_response(rsp);
1002 return cgi_error_memory();
1005 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
1008 free_http_response(rsp);
1009 return cgi_error_memory();
1013 return finish_http_response(rsp);
1018 #ifdef FEATURE_TRUST
1019 /*********************************************************************
1021 * Function : trust_url FIXME: I should be called distrust_url
1023 * Description : Calls is_untrusted_url to determine if the URL is trusted
1024 * and if not, returns a HTTP 403 response with a reject message.
1027 * 1 : csp = Current client state (buffers, headers, etc...)
1029 * Returns : NULL => trusted, else http_response.
1031 *********************************************************************/
1032 struct http_response *trust_url(struct client_state *csp)
1034 struct http_response *rsp;
1035 struct map * exports;
1036 char buf[BUFFER_SIZE];
1038 struct url_spec **tl;
1043 * Don't bother to work on trusted URLs
1045 if (!is_untrusted_url(csp))
1051 * Else, prepare a response:
1053 if (NULL == (rsp = alloc_http_response()))
1055 return cgi_error_memory();
1058 rsp->status = strdup("403 Request blocked by Privoxy");
1059 exports = default_exports(csp, NULL);
1060 if (exports == NULL || rsp->status == NULL)
1062 free_http_response(rsp);
1063 return cgi_error_memory();
1067 * Export the protocol, host, port, and referrer information
1069 err = map(exports, "hostport", 1, csp->http->hostport, 1);
1070 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1071 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1073 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1075 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1079 if (!err) err = map(exports, "referrer", 1, "none set", 1);
1085 free_http_response(rsp);
1086 return cgi_error_memory();
1090 * Export the trust list
1093 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1095 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
1096 string_append(&p, buf);
1098 err = map(exports, "trusted-referrers", 1, p, 0);
1103 free_http_response(rsp);
1104 return cgi_error_memory();
1108 * Export the trust info, if available
1110 if (csp->config->trust_info->first)
1112 struct list_entry *l;
1115 for (l = csp->config->trust_info->first; l ; l = l->next)
1117 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
1118 string_append(&p, buf);
1120 err = map(exports, "trust-info", 1, p, 0);
1124 err = map_block_killer(exports, "have-trust-info");
1130 free_http_response(rsp);
1131 return cgi_error_memory();
1135 * Export the force prefix or the force conditional block killer
1137 #ifdef FEATURE_FORCE_LOAD
1138 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1139 #else /* ifndef FEATURE_FORCE_LOAD */
1140 err = map_block_killer(exports, "force-support");
1141 #endif /* ndef FEATURE_FORCE_LOAD */
1146 free_http_response(rsp);
1147 return cgi_error_memory();
1151 * Build the response
1153 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1156 free_http_response(rsp);
1157 return cgi_error_memory();
1160 return finish_http_response(rsp);
1162 #endif /* def FEATURE_TRUST */
1164 /*********************************************************************
1166 * Function : execute_single_pcrs_command
1168 * Description : Apply single pcrs command to the subject.
1169 * The subject itself is left untouched, memory for the result
1170 * is malloc()ed and it is the caller's responsibility to free
1171 * the result when it's no longer needed.
1174 * 1 : subject = the subject (== original) string
1175 * 2 : pcrs_command = the pcrs command as string (s@foo@bar@)
1176 * 3 : hits = int* for returning the number of modifications
1178 * Returns : NULL in case of errors, otherwise the
1179 * result of the pcrs command.
1181 *********************************************************************/
1182 char *execute_single_pcrs_command(char *subject, const char *pcrs_command, int *hits)
1186 char *result = NULL;
1190 assert(pcrs_command);
1193 size = strlen(subject);
1195 if (NULL == (job = pcrs_compile_command(pcrs_command, &error)))
1197 log_error(LOG_LEVEL_ERROR, "Failed to compile pcrs command \"%s\". Error: %d.",
1198 pcrs_command, error);
1200 else if ((*hits = pcrs_execute(job, subject, size, &result, &size)) < 0)
1202 log_error(LOG_LEVEL_ERROR, "Failed to execute pcrs command: %s", pcrs_strerror(*hits));
1209 job = pcrs_free_job(job);
1216 /*********************************************************************
1218 * Function : rewrite_url
1220 * Description : Rewrites a URL with a single pcrs command
1221 * and returns the result if it differs from the
1222 * original and isn't obviously invalid.
1225 * 1 : old_url = URL to rewrite.
1226 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1229 * Returns : NULL if the pcrs_command didn't change the url, or
1230 * the result of the modification.
1232 *********************************************************************/
1233 char *rewrite_url(char *old_url, const char *pcrs_command)
1235 char *new_url = NULL;
1239 assert(pcrs_command);
1241 new_url = execute_single_pcrs_command(old_url, pcrs_command, &hits);
1245 log_error(LOG_LEVEL_REDIRECTS,
1246 "pcrs command \"%s\" didn't change \"%s\".",
1247 pcrs_command, old_url, new_url);
1250 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1252 log_error(LOG_LEVEL_ERROR,
1253 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1254 "but the result doesn't look like a valid URL and will be ignored.",
1255 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1260 log_error(LOG_LEVEL_REDIRECTS,
1261 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1262 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1270 #ifdef FEATURE_FAST_REDIRECTS
1271 /*********************************************************************
1273 * Function : get_last_url
1275 * Description : Search for the last URL inside a string.
1276 * If the string already is a URL, it will
1277 * be the first URL found.
1280 * 1 : subject = the string to check
1281 * 2 : redirect_mode = +fast-redirect{} mode
1283 * Returns : NULL if no URL was found, or
1284 * the last URL found.
1286 *********************************************************************/
1287 char *get_last_url(char *subject, const char *redirect_mode)
1289 char *new_url = NULL;
1293 assert(redirect_mode);
1295 subject = strdup(subject);
1296 if (subject == NULL)
1298 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1302 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1304 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1305 new_url = url_decode(subject);
1306 if (new_url != NULL)
1313 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1317 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1320 * Find the last URL encoded in the request
1323 while ((tmp = strstr(tmp, "http://")) != NULL)
1327 tmp = (new_url != NULL) ? new_url : subject;
1328 while ((tmp = strstr(tmp, "https://")) != NULL)
1333 if ((new_url != NULL)
1334 && ( (new_url != subject)
1335 || (0 == strncmpic(subject, "http://", 7))
1336 || (0 == strncmpic(subject, "https://", 8))
1340 * Return new URL if we found a redirect
1341 * or if the subject already was a URL.
1343 * The second case makes sure that we can
1344 * chain get_last_url after another redirection check
1345 * (like rewrite_url) without losing earlier redirects.
1347 new_url = strdup(new_url);
1356 #endif /* def FEATURE_FAST_REDIRECTS */
1359 /*********************************************************************
1361 * Function : redirect_url
1363 * Description : Checks if Privoxy should answer the request with
1364 * a HTTP redirect and generates the redirect if
1368 * 1 : csp = Current client state (buffers, headers, etc...)
1370 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1372 *********************************************************************/
1373 struct http_response *redirect_url(struct client_state *csp)
1375 struct http_response *rsp;
1376 #ifdef FEATURE_FAST_REDIRECTS
1378 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1379 * as compile-time option? The user can easily disable
1380 * it in his action file.
1382 char * redirect_mode;
1383 #endif /* def FEATURE_FAST_REDIRECTS */
1384 char *old_url = NULL;
1385 char *new_url = NULL;
1386 char *redirection_string;
1388 if ((csp->action->flags & ACTION_REDIRECT))
1390 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1393 * If the redirection string begins with 's',
1394 * assume it's a pcrs command, otherwise treat it as
1395 * properly formatted URL and use it for the redirection
1398 * According to RFC 2616 section 14.30 the URL
1399 * has to be absolute and if the user tries:
1400 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1401 * she would get undefined results anyway.
1405 if (*redirection_string == 's')
1407 old_url = csp->http->url;
1408 new_url = rewrite_url(old_url, redirection_string);
1412 log_error(LOG_LEVEL_REDIRECTS,
1413 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1414 redirection_string);
1415 new_url = strdup(redirection_string);
1419 #ifdef FEATURE_FAST_REDIRECTS
1420 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1422 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1425 * If it exists, use the previously rewritten URL as input
1426 * otherwise just use the old path.
1428 old_url = new_url ? new_url : strdup(csp->http->path);
1429 new_url = get_last_url(old_url, redirect_mode);
1432 #endif /* def FEATURE_FAST_REDIRECTS */
1434 /* Did any redirect action trigger? */
1437 if (0 == strcmpic(new_url, csp->http->url))
1439 log_error(LOG_LEVEL_ERROR,
1440 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1441 csp->http->url, new_url);
1446 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1448 if (NULL == (rsp = alloc_http_response()))
1451 return cgi_error_memory();
1454 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1455 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1458 free_http_response(rsp);
1459 return cgi_error_memory();
1462 return finish_http_response(rsp);
1466 /* Only reached if no redirect is required */
1472 #ifdef FEATURE_IMAGE_BLOCKING
1473 /*********************************************************************
1475 * Function : is_imageurl
1477 * Description : Given a URL, decide whether it is an image or not,
1478 * using either the info from a previous +image action
1479 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1480 * is MSIE and not on a Mac, tell from the browser's accept
1484 * 1 : csp = Current client state (buffers, headers, etc...)
1486 * Returns : True (nonzero) if URL is an image, false (0)
1489 *********************************************************************/
1490 int is_imageurl(struct client_state *csp)
1492 #ifdef FEATURE_IMAGE_DETECT_MSIE
1495 tmp = get_header_value(csp->headers, "User-Agent:");
1496 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1498 tmp = get_header_value(csp->headers, "Accept:");
1499 if (tmp && strstr(tmp, "image/gif"))
1501 /* Client will accept HTML. If this seems counterintuitive,
1511 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1513 return ((csp->action->flags & ACTION_IMAGE) != 0);
1516 #endif /* def FEATURE_IMAGE_BLOCKING */
1519 #ifdef FEATURE_TRUST
1520 /*********************************************************************
1522 * Function : is_untrusted_url
1524 * Description : Should we "distrust" this URL (and block it)?
1526 * Yes if it matches a line in the trustfile, or if the
1527 * referrer matches a line starting with "+" in the
1532 * 1 : csp = Current client state (buffers, headers, etc...)
1534 * Returns : 0 => trusted, 1 => untrusted
1536 *********************************************************************/
1537 int is_untrusted_url(struct client_state *csp)
1539 struct file_list *fl;
1540 struct block_spec *b;
1541 struct url_spec **trusted_url;
1542 struct http_request rhttp[1];
1543 const char * referer;
1547 * If we don't have a trustlist, we trust everybody
1549 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1554 memset(rhttp, '\0', sizeof(*rhttp));
1557 * Do we trust the request URL itself?
1559 for (b = b->next; b ; b = b->next)
1561 if (url_match(b->url, csp->http))
1567 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1569 /* no referrer was supplied */
1575 * If not, do we maybe trust its referrer?
1577 err = parse_http_url(referer, rhttp, csp);
1583 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1585 if (url_match(*trusted_url, rhttp))
1587 /* if the URL's referrer is from a trusted referrer, then
1588 * add the target spec to the trustfile as an unblocked
1589 * domain and return 0 (which means it's OK).
1594 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1598 char * new_entry = strdup("~");
1600 string_append(&new_entry, csp->http->hostport);
1602 path = csp->http->path;
1603 if ( (path[0] == '/')
1605 && ((path_end = strchr(path + 2, '/')) != NULL))
1607 /* since this path points into a user's home space
1608 * be sure to include this spec in the trustfile.
1610 int path_len = path_end - path; /* save offset */
1611 path = strdup(path); /* Copy string */
1614 path_end = path + path_len; /* regenerate ptr to new buffer */
1615 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1617 string_join(&new_entry, path);
1621 * Give a reason for generating this entry.
1623 string_append(&new_entry, " # Trusted referrer was: ");
1624 string_append(&new_entry, referer);
1626 if (new_entry != NULL)
1628 if (-1 == fprintf(fp, "%s\n", new_entry))
1630 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1631 new_entry, csp->config->trustfile);
1637 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1638 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1645 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1646 csp->http->hostport, csp->config->trustfile);
1653 #endif /* def FEATURE_TRUST */
1656 /*********************************************************************
1658 * Function : pcrs_filter_response
1660 * Description : Execute all text substitutions from all applying
1661 * +filter actions on the text buffer that's been accumulated
1662 * in csp->iob->buf. If this changes the contents, set
1663 * csp->content_length to the modified size and raise the
1664 * CSP_FLAG_MODIFIED flag.
1666 * XXX: Currently pcrs_filter_response is also responsible
1667 * for dechunking and decompressing. Both should be
1668 * done in separate functions so other content modifiers
1669 * profit as well, even if pcrs filtering is disabled.
1672 * 1 : csp = Current client state (buffers, headers, etc...)
1674 * Returns : a pointer to the (newly allocated) modified buffer.
1675 * or NULL if there were no hits or something went wrong
1677 *********************************************************************/
1678 char *pcrs_filter_response(struct client_state *csp)
1681 size_t size, prev_size;
1683 char *old = csp->iob->cur, *new = NULL;
1686 struct file_list *fl;
1687 struct re_filterfile_spec *b;
1688 struct list_entry *filtername;
1690 int i, found_filters = 0;
1695 if (csp->iob->cur >= csp->iob->eod)
1699 size = (size_t)(csp->iob->eod - csp->iob->cur);
1702 * Need to check the set of re_filterfiles...
1704 for (i = 0; i < MAX_AF_FILES; i++)
1717 if (0 == found_filters)
1719 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1724 * If the body has a "chunked" transfer-encoding,
1725 * get rid of it first, adjusting size and iob->eod
1727 if (csp->flags & CSP_FLAG_CHUNKED)
1729 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1730 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1734 csp->iob->eod = csp->iob->cur + size;
1735 csp->flags |= CSP_FLAG_MODIFIED;
1740 * If the body has a compressed transfer-encoding,
1741 * uncompress it first, adjusting size and iob->eod.
1742 * Note that decompression occurs after de-chunking.
1744 if (csp->content_type & CT_GZIP || csp->content_type & CT_DEFLATE)
1746 /* Notice that we at least tried to decompress. */
1747 if (JB_ERR_OK != decompress_iob(csp))
1750 * We failed to decompress the data; there's no point
1751 * in continuing since we can't filter. This is
1752 * slightly tricky because we need to remember not to
1753 * modify the Content-Encoding header later; using
1754 * CT_TABOO flag is a kludge for this purpose.
1756 csp->content_type |= CT_TABOO;
1759 log_error(LOG_LEVEL_RE_FILTER, "Decompressing successful");
1762 * Decompression gives us a completely new iob,
1763 * so we need to update.
1765 size = (size_t)(csp->iob->eod - csp->iob->cur);
1766 old = csp->iob->cur;
1768 csp->flags |= CSP_FLAG_MODIFIED;
1769 csp->content_type &= ~CT_TABOO;
1773 for (i = 0; i < MAX_AF_FILES; i++)
1776 if ((NULL == fl) || (NULL == fl->f))
1779 * Either there are no filter files
1780 * left, or this filter file just
1781 * contains no valid filters.
1783 * Continue to be sure we don't miss
1784 * valid filter files that are chained
1785 * after empty or invalid ones.
1790 * For all applying +filter actions, look if a filter by that
1791 * name exists and if yes, execute it's pcrs_joblist on the
1794 for (b = fl->f; b; b = b->next)
1796 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1797 filtername ; filtername = filtername->next)
1799 if (strcmp(b->name, filtername->str) == 0)
1801 int current_hits = 0; /* Number of hits caused by this filter */
1802 int job_number = 0; /* Which job we're currently executing */
1803 int job_hits = 0; /* How many hits the current job caused */
1805 if ( NULL == b->joblist )
1807 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1812 /* Apply all jobs from the joblist */
1813 for (job = b->joblist; NULL != job; job = job->next)
1816 job_hits = pcrs_execute(job, old, size, &new, &size);
1821 * That went well. Continue filtering
1822 * and use the result of this job as
1823 * input for the next one.
1825 current_hits += job_hits;
1826 if (old != csp->iob->cur)
1835 * This job caused an unexpected error. Inform the user
1836 * and skip the rest of the jobs in this filter. We could
1837 * continue with the next job, but usually the jobs
1838 * depend on each other or are similar enough to
1839 * fail for the same reason.
1841 * At the moment our pcrs expects the error codes of pcre 3.4,
1842 * but newer pcre versions can return additional error codes.
1843 * As a result pcrs_strerror()'s error message might be
1844 * "Unknown error ...", therefore we print the numerical value
1847 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1848 * should we use LOG_LEVEL_RE_FILTER instead?
1850 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1851 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1856 log_error(LOG_LEVEL_RE_FILTER,
1857 "re_filtering %s%s (size %d) with filter %s produced %d hits (new size %d).",
1858 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1860 hits += current_hits;
1867 * If there were no hits, destroy our copy and let
1868 * chat() use the original in csp->iob
1876 csp->flags |= CSP_FLAG_MODIFIED;
1877 csp->content_length = size;
1885 /*********************************************************************
1887 * Function : gif_deanimate_response
1889 * Description : Deanimate the GIF image that has been accumulated in
1890 * csp->iob->buf, set csp->content_length to the modified
1891 * size and raise the CSP_FLAG_MODIFIED flag.
1894 * 1 : csp = Current client state (buffers, headers, etc...)
1896 * Returns : a pointer to the (newly allocated) modified buffer.
1897 * or NULL in case something went wrong.
1899 *********************************************************************/
1900 char *gif_deanimate_response(struct client_state *csp)
1902 struct binbuffer *in, *out;
1906 size = (size_t)(csp->iob->eod - csp->iob->cur);
1909 * If the body has a "chunked" transfer-encoding,
1910 * get rid of it first, adjusting size and iob->eod
1912 if (csp->flags & CSP_FLAG_CHUNKED)
1914 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1915 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1919 csp->iob->eod = csp->iob->cur + size;
1920 csp->flags |= CSP_FLAG_MODIFIED;
1923 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1924 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1926 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1930 in->buffer = csp->iob->cur;
1933 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1935 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1942 if ((int)size == out->offset)
1944 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1948 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1950 csp->content_length = out->offset;
1951 csp->flags |= CSP_FLAG_MODIFIED;
1961 /*********************************************************************
1963 * Function : jpeg_inspect_response
1968 * 1 : csp = Current client state (buffers, headers, etc...)
1970 * Returns : a pointer to the (newly allocated) modified buffer
1971 * or NULL in case something went wrong.
1973 *********************************************************************/
1974 char *jpeg_inspect_response(struct client_state *csp)
1976 struct binbuffer *in = NULL;
1977 struct binbuffer *out = NULL;
1981 size = (size_t)(csp->iob->eod - csp->iob->cur);
1984 * If the body has a "chunked" transfer-encoding,
1985 * get rid of it first, adjusting size and iob->eod
1987 if (csp->flags & CSP_FLAG_CHUNKED)
1989 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1990 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1994 csp->iob->eod = csp->iob->cur + size;
1995 csp->flags |= CSP_FLAG_MODIFIED;
1998 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
2000 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
2004 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
2006 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
2010 in->buffer = csp->iob->cur;
2014 * Calling jpeg_inspect has the side-effect of creating and
2015 * modifying the image buffer of "out" directly.
2017 if (jpeg_inspect(in, out))
2019 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
2027 csp->content_length = out->offset;
2028 csp->flags |= CSP_FLAG_MODIFIED;
2038 /*********************************************************************
2040 * Function : remove_chunked_transfer_coding
2042 * Description : In-situ remove the "chunked" transfer coding as defined
2043 * in rfc2616 from a buffer.
2046 * 1 : buffer = Pointer to the text buffer
2047 * 2 : size = Number of bytes to be processed
2049 * Returns : The new size, i.e. the number of bytes from buffer which
2050 * are occupied by the stripped body, or 0 in case something
2053 *********************************************************************/
2054 size_t remove_chunked_transfer_coding(char *buffer, const size_t size)
2057 unsigned int chunksize = 0;
2058 char *from_p, *to_p;
2061 from_p = to_p = buffer;
2063 if (sscanf(buffer, "%x", &chunksize) != 1)
2065 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2069 while (chunksize > 0)
2071 if (NULL == (from_p = strstr(from_p, "\r\n")))
2073 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2077 if ((newsize += chunksize) >= size)
2079 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
2084 memmove(to_p, from_p, (size_t) chunksize);
2085 to_p = buffer + newsize;
2086 from_p += chunksize + 2;
2088 if (sscanf(from_p, "%x", &chunksize) != 1)
2090 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2095 /* FIXME: Should this get its own loglevel? */
2096 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
2102 /*********************************************************************
2104 * Function : url_actions
2106 * Description : Gets the actions for this URL.
2109 * 1 : http = http_request request for blocked URLs
2110 * 2 : csp = Current client state (buffers, headers, etc...)
2114 *********************************************************************/
2115 void url_actions(struct http_request *http,
2116 struct client_state *csp)
2118 struct file_list *fl;
2119 struct url_actions *b;
2122 init_current_action(csp->action);
2124 for (i = 0; i < MAX_AF_FILES; i++)
2126 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2131 apply_url_actions(csp->action, http, b);
2138 /*********************************************************************
2140 * Function : apply_url_actions
2142 * Description : Applies a list of URL actions.
2145 * 1 : action = Destination.
2146 * 2 : http = Current URL
2147 * 3 : b = list of URL actions to apply
2151 *********************************************************************/
2152 void apply_url_actions(struct current_action_spec *action,
2153 struct http_request *http,
2154 struct url_actions *b)
2158 /* Should never happen */
2162 for (b = b->next; NULL != b; b = b->next)
2164 if (url_match(b->url, http))
2166 merge_current_action(action, b->action);
2172 /*********************************************************************
2174 * Function : forward_url
2176 * Description : Should we forward this to another proxy?
2179 * 1 : http = http_request request for current URL
2180 * 2 : csp = Current client state (buffers, headers, etc...)
2182 * Returns : Pointer to forwarding information.
2184 *********************************************************************/
2185 const struct forward_spec * forward_url(struct http_request *http,
2186 struct client_state *csp)
2188 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2189 struct forward_spec *fwd = csp->config->forward;
2198 if (url_match(fwd->url, http))
2209 /*********************************************************************
2211 * Function : direct_response
2213 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2214 * request and if so, return a HTTP 501 to the client.
2216 * FIXME: I have a stupid name and I should handle the
2217 * requests properly. Still, what we do here is rfc-
2218 * compliant, whereas ignoring or forwarding are not.
2221 * 1 : csp = Current client state (buffers, headers, etc...)
2223 * Returns : http_response if , NULL if nonmatch or handler fail
2225 *********************************************************************/
2226 struct http_response *direct_response(struct client_state *csp)
2228 struct http_response *rsp;
2229 struct list_entry *p;
2231 if ((0 == strcmpic(csp->http->gpc, "trace"))
2232 || (0 == strcmpic(csp->http->gpc, "options")))
2234 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2236 if (!strncmp("Max-Forwards:", p->str, 13)
2237 && (*(p->str+13) != '\0') && (atoi(p->str+13) == 0))
2239 /* FIXME: We could handle at least TRACE here,
2240 but that would require a verbatim copy of
2241 the request which we don't have anymore */
2243 log_error(LOG_LEVEL_HEADER, "Found Max-Forwards:0 in OPTIONS or TRACE request -- Returning 501");
2245 /* Get mem for response or fail*/
2246 if (NULL == (rsp = alloc_http_response()))
2248 return cgi_error_memory();
2251 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2253 free_http_response(rsp);
2254 return cgi_error_memory();
2258 return(finish_http_response(rsp));