1 const char filters_rcs[] = "$Id: filters.c,v 1.71 2006/12/22 14:24:52 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.71 2006/12/22 14:24:52 fabiankeil
44 * Skip empty filter files in pcrs_filter_response,
45 * but don't ignore the ones that come afterwards.
46 * Fixes parts of BR 1619208.
48 * Revision 1.70 2006/12/09 13:33:15 fabiankeil
49 * Added some sanity checks for get_last_url().
50 * Fixed possible segfault caused by my last commit.
52 * Revision 1.69 2006/12/08 12:39:13 fabiankeil
53 * Let get_last_url() catch https URLs as well.
55 * Revision 1.68 2006/12/05 14:45:48 fabiankeil
56 * Make sure get_last_url() behaves like advertised
57 * and fast-redirects{} can be combined with redirect{}.
59 * Revision 1.67 2006/11/28 15:19:43 fabiankeil
60 * Implemented +redirect{s@foo@bar@} to generate
61 * a redirect based on a rewritten version of the
64 * Revision 1.66 2006/09/23 13:26:38 roro
65 * Replace TABs by spaces in source code.
67 * Revision 1.65 2006/09/21 12:54:43 fabiankeil
68 * Fix +redirect{}. Didn't work with -fast-redirects.
70 * Revision 1.64 2006/08/31 10:55:49 fabiankeil
71 * Block requests for untrusted URLs with status
72 * code 403 instead of 200.
74 * Revision 1.63 2006/08/31 10:11:28 fabiankeil
75 * Don't free p which is still in use and will be later
76 * freed by free_map(). Don't claim the referrer is unknown
77 * when the client didn't set one.
79 * Revision 1.62 2006/08/14 00:27:47 david__schmidt
80 * Feature request 595948: Re-Filter logging in single line
82 * Revision 1.61 2006/08/03 02:46:41 david__schmidt
83 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
85 * Revision 1.60 2006/07/18 14:48:46 david__schmidt
86 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
87 * with what was really the latest development (the v_3_0_branch branch)
89 * Revision 1.58.2.9 2006/01/29 23:10:56 david__schmidt
90 * Multiple filter file support
92 * Revision 1.58.2.8 2005/05/07 21:50:55 david__schmidt
93 * A few memory leaks plugged (mostly on error paths)
95 * Revision 1.58.2.7 2004/10/03 12:53:32 david__schmidt
96 * Add the ability to check jpeg images for invalid
97 * lengths of comment blocks. Defensive strategy
98 * against the exploit:
99 * Microsoft Security Bulletin MS04-028
100 * Buffer Overrun in JPEG Processing (GDI+) Could
101 * Allow Code Execution (833987)
102 * Enabled with +inspect-jpegs in actions files.
104 * Revision 1.58.2.6 2003/12/06 22:18:27 gliptak
105 * Correcting compile problem with FEATURE_IMAGE_BLOCKING
107 * Revision 1.58.2.5 2003/11/11 13:10:31 oes
108 * Fixed bug #839859: "See why" link URL now gets url-encoded.
110 * Revision 1.58.2.4 2003/02/28 12:52:45 oes
113 * Revision 1.58.2.3 2002/09/25 14:51:51 oes
114 * Added basic support for OPTIONS and TRACE HTTP methods:
115 * New function direct_response which handles OPTIONS and
116 * TRACE requests whose Max-Forwards header field is zero.
118 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
119 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
121 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
122 * - Bugfix: Executing a filters without jobs no longer results in
123 * turing off *all* filters.
124 * - Security fix: Malicious web servers can't cause a seg fault
125 * through bogus chunk sizes anymore
127 * Revision 1.58 2002/04/24 02:11:17 oes
128 * Jon's multiple AF patch: url_actions now evaluates rules
131 * Revision 1.57 2002/04/08 20:38:34 swa
134 * Revision 1.56 2002/04/05 15:51:24 oes
135 * - bugfix: error-pages now get correct request protocol
136 * - fix for invalid HTML in trust info
138 * Revision 1.55 2002/04/02 16:13:51 oes
139 * Fix: No "Go there anyway" for SSL
141 * Revision 1.54 2002/04/02 14:55:56 oes
142 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
144 * Revision 1.53 2002/03/26 22:29:54 swa
145 * we have a new homepage!
147 * Revision 1.52 2002/03/24 16:35:57 jongfoster
150 * Revision 1.51 2002/03/24 15:23:33 jongfoster
153 * Revision 1.50 2002/03/24 13:25:43 swa
154 * name change related issues
156 * Revision 1.49 2002/03/16 20:29:14 oes
159 * Revision 1.48 2002/03/13 20:25:34 oes
160 * Better logging for content filters
162 * Revision 1.47 2002/03/13 00:30:52 jongfoster
164 * Added option of always sending redirect for imageblock,
165 * currently disabled with #if 0.
167 * Revision 1.46 2002/03/12 01:42:49 oes
168 * Introduced modular filters
170 * Revision 1.45 2002/03/08 16:47:50 oes
171 * Added choice beween GIF and PNG built-in images
173 * Revision 1.44 2002/03/07 03:49:31 oes
174 * - Fixed compiler warnings etc
175 * - Changed built-in images from GIF to PNG
176 * (with regard to Unisys patent issue)
177 * - Added a 4x4 pattern PNG which is less intrusive
178 * than the logo but also clearly marks the deleted banners
180 * Revision 1.43 2002/01/22 23:51:59 jongfoster
181 * Replacing strsav() with the safer string_append().
183 * Adding missing html_encode() to error message generators. Where encoded
184 * and unencoded versions of a string were provided, removing the unencoded
187 * Revision 1.42 2002/01/17 21:00:32 jongfoster
188 * Moving all our URL and URL pattern parsing code to urlmatch.c.
190 * Using a single, simple url_match(pattern,url) function - rather than
191 * the 3-line match routine which was repeated all over the place.
193 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
195 * Using parse_http_url() to parse URLs without faking a HTTP
196 * request line for parse_http_request().
198 * Revision 1.41 2001/11/13 00:14:07 jongfoster
199 * Fixing stupid bug now I've figured out what || means.
200 * (It always returns 0 or 1, not one of it's paramaters.)
202 * Revision 1.40 2001/10/26 17:37:55 oes
203 * - Re-enabled Netscape 200/404 bug workaround in block_url():
204 * - Removed OS/2 special case
205 * - Made block_url() independant from sed() having been run
206 * - Made trust_url independant from sed() having been run
207 * - Made is_imageurl independant from sed() having been run.
208 * It now checks User-Agent: and Accept: by itself.
211 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
212 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
213 * threads to call select() simultaneously. So, it's time to do a real, live,
214 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
215 * (native). Both versions will work, but using __OS2__ offers multi-threading.
217 * Revision 1.38 2001/10/23 21:32:33 jongfoster
218 * Adding error-checking to selected functions
220 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
221 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
222 * filters.c. Added a FIXME in front of the offending code. I'll gladly
223 * put in a better/more robust fix for all parties if one is presented...
224 * It seems that just returning 200 instead of 404 would pretty much fix
225 * it for everyone, but I don't know all the history of the problem.
227 * Revision 1.36 2001/10/10 16:44:16 oes
228 * Added match_portlist function
230 * Revision 1.35 2001/10/07 15:41:23 oes
231 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
233 * New function remove_chunked_transfer_coding that strips chunked
234 * transfer coding to plain and is called by pcrs_filter_response
235 * and gif_deanimate_response if neccessary
237 * Improved handling of zero-change re_filter runs
239 * pcrs_filter_response and gif_deanimate_response now remove
240 * chunked transfer codeing before processing the body.
242 * Revision 1.34 2001/09/20 15:49:36 steudten
244 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
245 * See cgi.c fill_template().
247 * Revision 1.33 2001/09/16 17:05:14 jongfoster
248 * Removing unused #include showarg.h
250 * Revision 1.32 2001/09/16 13:21:27 jongfoster
251 * Changes to use new list functions.
253 * Revision 1.31 2001/09/16 11:38:02 jongfoster
254 * Splitting fill_template() into 2 functions:
255 * template_load() loads the file
256 * template_fill() performs the PCRS regexps.
257 * This is because the CGI edit interface has a "table row"
258 * template which is used many times in the page - this
259 * change means it's only loaded from disk once.
261 * Revision 1.30 2001/09/16 11:00:10 jongfoster
262 * New function alloc_http_response, for symmetry with free_http_response
264 * Revision 1.29 2001/09/13 23:32:40 jongfoster
265 * Moving image data to cgi.c rather than cgi.h
266 * Fixing a GPF under Win32 (and any other OS that protects global
267 * constants from being written to).
269 * Revision 1.28 2001/09/10 10:18:51 oes
270 * Silenced compiler warnings
272 * Revision 1.27 2001/08/05 16:06:20 jongfoster
273 * Modifiying "struct map" so that there are now separate header and
274 * "map_entry" structures. This means that functions which modify a
275 * map no longer need to return a pointer to the modified map.
276 * Also, it no longer reverses the order of the entries (which may be
277 * important with some advanced template substitutions).
279 * Revision 1.26 2001/07/30 22:08:36 jongfoster
280 * Tidying up #defines:
281 * - All feature #defines are now of the form FEATURE_xxx
282 * - Permanently turned off WIN_GUI_EDIT
283 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
285 * Revision 1.25 2001/07/26 10:09:46 oes
286 * Made browser detection a little less naive
288 * Revision 1.24 2001/07/25 17:22:51 oes
289 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
291 * Revision 1.23 2001/07/23 13:40:12 oes
292 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
294 * Revision 1.22 2001/07/18 12:29:34 oes
295 * - Made gif_deanimate_response respect
296 * csp->action->string[ACTION_STRING_DEANIMATE]
297 * - Logging cosmetics
299 * Revision 1.21 2001/07/13 13:59:53 oes
300 * - Introduced gif_deanimate_response which shares the
301 * generic content modification interface of pcrs_filter_response
302 * and acts as a wrapper to deanimate.c:gif_deanimate()
303 * - Renamed re_process_buffer to pcrs_filter_response
304 * - pcrs_filter_response now returns NULL on failiure
305 * - Removed all #ifdef PCRS
307 * Revision 1.20 2001/07/01 17:01:04 oes
308 * Added comments and missing return statement in is_untrusted_url()
310 * Revision 1.19 2001/06/29 21:45:41 oes
311 * Indentation, CRLF->LF, Tab-> Space
313 * Revision 1.18 2001/06/29 13:27:38 oes
314 * - Cleaned up, renamed and reorderd functions
315 * and improved comments
318 * - Ported to CGI platform. Now delivers
319 * http_response or NULL
320 * - Unified HTML and GIF generation (moved image detection
321 * and GIF generation here from jcc.c:chat())
322 * - Fixed HTTP status to:
323 * - 403 (Forbidden) for the "blocked" HTML message
324 * - 200 (OK) for GIF answers
325 * - 302 (Redirect) for redirect to GIF
328 * - Ported to CGI platform. Now delivers
329 * http_response or NULL
330 * - Separated detection of untrusted URL into
331 * (bool)is_untrusted_url
332 * - Added enforcement of untrusted requests
334 * - Moved redirect_url() from cgi.c to here
335 * and ported it to the CGI platform
337 * - Removed logentry from cancelled commit
339 * Revision 1.17 2001/06/09 10:55:28 jongfoster
340 * Changing BUFSIZ ==> BUFFER_SIZE
342 * Revision 1.16 2001/06/07 23:10:26 jongfoster
343 * Allowing unanchored domain patterns to back off and retry
344 * if they partially match. Optimized right-anchored patterns.
345 * Moving ACL and forward files into config file.
346 * Replacing struct gateway with struct forward_spec
348 * Revision 1.15 2001/06/03 19:12:00 oes
349 * extracted-CGI relevant stuff
351 * Revision 1.14 2001/06/01 10:30:55 oes
352 * Added optional left-anchoring to domaincmp
354 * Revision 1.13 2001/05/31 21:21:30 jongfoster
355 * Permissionsfile / actions file changes:
356 * - Changed "permission" to "action" throughout
357 * - changes to file format to allow string parameters
358 * - Moved helper functions to actions.c
360 * Revision 1.12 2001/05/31 17:35:20 oes
362 * - Enhanced domain part globbing with infix and prefix asterisk
363 * matching and optional unanchored operation
365 * Revision 1.11 2001/05/29 11:53:23 oes
366 * "See why" link added to "blocked" page
368 * Revision 1.10 2001/05/29 09:50:24 jongfoster
369 * Unified blocklist/imagelist/permissionslist.
370 * File format is still under discussion, but the internal changes
373 * Also modified interceptor behaviour:
374 * - We now intercept all URLs beginning with one of the following
375 * prefixes (and *only* these prefixes):
377 * * http://ijbswa.sf.net/config/
378 * * http://ijbswa.sourceforge.net/config/
379 * - New interceptors "home page" - go to http://i.j.b/ to see it.
380 * - Internal changes so that intercepted and fast redirect pages
381 * are not replaced with an image.
382 * - Interceptors now have the option to send a binary page direct
383 * to the client. (i.e. ijb-send-banner uses this)
384 * - Implemented show-url-info interceptor. (Which is why I needed
385 * the above interceptors changes - a typical URL is
386 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
387 * The previous mechanism would not have intercepted that, and
388 * if it had been intercepted then it then it would have replaced
391 * Revision 1.9 2001/05/27 22:17:04 oes
393 * - re_process_buffer no longer writes the modified buffer
394 * to the client, which was very ugly. It now returns the
395 * buffer, which it is then written by chat.
397 * - content_length now adjusts the Content-Length: header
398 * for modified documents rather than crunch()ing it.
399 * (Length info in csp->content_length, which is 0 for
400 * unmodified documents)
402 * - For this to work, sed() is called twice when filtering.
404 * Revision 1.8 2001/05/26 17:13:28 jongfoster
405 * Filled in a function comment.
407 * Revision 1.7 2001/05/26 15:26:15 jongfoster
408 * ACL feature now provides more security by immediately dropping
409 * connections from untrusted hosts.
411 * Revision 1.6 2001/05/26 00:28:36 jongfoster
412 * Automatic reloading of config file.
413 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
414 * Most of the global variables have been moved to a new
415 * struct configuration_spec, accessed through csp->config->globalname
416 * Most of the globals remaining are used by the Win32 GUI.
418 * Revision 1.5 2001/05/25 22:34:30 jongfoster
421 * Revision 1.4 2001/05/22 18:46:04 oes
423 * - Enabled filtering banners by size rather than URL
424 * by adding patterns that replace all standard banner
425 * sizes with the "Junkbuster" gif to the re_filterfile
427 * - Enabled filtering WebBugs by providing a pattern
428 * which kills all 1x1 images
430 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
431 * which is selected by the (nonstandard and therefore
432 * capital) letter 'U' in the option string.
433 * It causes the quantifiers to be ungreedy by default.
434 * Appending a ? turns back to greedy (!).
436 * - Added a new interceptor ijb-send-banner, which
437 * sends back the "Junkbuster" gif. Without imagelist or
438 * MSIE detection support, or if tinygif = 1, or the
439 * URL isn't recognized as an imageurl, a lame HTML
440 * explanation is sent instead.
442 * - Added new feature, which permits blocking remote
443 * script redirects and firing back a local redirect
445 * The feature is conditionally compiled, i.e. it
446 * can be disabled with --disable-fast-redirects,
447 * plus it must be activated by a "fast-redirects"
448 * line in the config file, has its own log level
449 * and of course wants to be displayed by show-proxy-args
450 * Note: Boy, all the #ifdefs in 1001 locations and
451 * all the fumbling with configure.in and acconfig.h
452 * were *way* more work than the feature itself :-(
454 * - Because a generic redirect template was needed for
455 * this, tinygif = 3 now uses the same.
457 * - Moved GIFs, and other static HTTP response templates
462 * - Removed some >400 CRs again (Jon, you really worked
465 * Revision 1.3 2001/05/20 16:44:47 jongfoster
466 * Removing last hardcoded Junkbusters.com URLs.
468 * Revision 1.2 2001/05/20 01:21:20 jongfoster
469 * Version 2.9.4 checkin.
470 * - Merged popupfile and cookiefile, and added control over PCRS
471 * filtering, in new "permissionsfile".
472 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
473 * file error you now get a message box (in the Win32 GUI) rather
474 * than the program exiting with no explanation.
475 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
477 * - Removed tabs from "config"
478 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
479 * - Bumped up version number.
481 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
482 * Initial import of version 2.9.3 source tree
485 *********************************************************************/
491 #include <sys/types.h>
500 #endif /* ndef __OS2__ */
501 #include <netinet/in.h>
503 #include <winsock2.h>
504 #endif /* ndef _WIN32 */
508 #endif /* def __OS2__ */
516 #include "jbsockets.h"
517 #include "miscutil.h"
521 #include "deanimate.h"
522 #include "urlmatch.h"
528 const char filters_h_rcs[] = FILTERS_H_VERSION;
530 /* Fix a problem with Solaris. There should be no effect on other
532 * Solaris's isspace() is a macro which uses it's argument directly
533 * as an array index. Therefore we need to make sure that high-bit
534 * characters generate +ve values, and ideally we also want to make
535 * the argument match the declared parameter type of "int".
537 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
541 /*********************************************************************
543 * Function : block_acl
545 * Description : Block this request?
546 * Decide yes or no based on ACL file.
549 * 1 : dst = The proxy or gateway address this is going to.
550 * Or NULL to check all possible targets.
551 * 2 : csp = Current client state (buffers, headers, etc...)
552 * Also includes the client IP address.
554 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
556 *********************************************************************/
557 int block_acl(struct access_control_addr *dst, struct client_state *csp)
559 struct access_control_list *acl = csp->config->acl;
561 /* if not using an access control list, then permit the connection */
567 /* search the list */
570 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
574 /* Just want to check if they have any access */
575 if (acl->action == ACL_PERMIT)
580 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
581 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
583 if (acl->action == ACL_PERMIT)
601 /*********************************************************************
603 * Function : acl_addr
605 * Description : Called from `load_config' to parse an ACL address.
608 * 1 : aspec = String specifying ACL address.
609 * 2 : aca = struct access_control_addr to fill in.
611 * Returns : 0 => Ok, everything else is an error.
613 *********************************************************************/
614 int acl_addr(char *aspec, struct access_control_addr *aca)
616 int i, masklength, port;
622 if ((p = strchr(aspec, '/')) != NULL)
626 if (ijb_isdigit(*p) == 0)
630 masklength = atoi(p);
633 if ((masklength < 0) || (masklength > 32))
638 if ((p = strchr(aspec, ':')) != NULL)
642 if (ijb_isdigit(*p) == 0)
651 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
653 if (aca->addr == INADDR_NONE)
658 /* build the netmask */
660 for (i=1; i <= masklength ; i++)
662 aca->mask |= (1 << (32 - i));
665 /* now mask off the host portion of the ip address
666 * (i.e. save on the network portion of the address).
668 aca->addr = aca->addr & aca->mask;
673 #endif /* def FEATURE_ACL */
676 /*********************************************************************
678 * Function : match_portlist
680 * Description : Check if a given number is covered by a comma
681 * separated list of numbers and ranges (a,b-c,d,..)
684 * 1 : portlist = String with list
685 * 2 : port = port to check
687 * Returns : 0 => no match
690 *********************************************************************/
691 int match_portlist(const char *portlist, int port)
693 char *min, *max, *next, *portlist_copy;
695 min = next = portlist_copy = strdup(portlist);
698 * Zero-terminate first item and remember offset for next
700 if (NULL != (next = strchr(portlist_copy, (int) ',')))
706 * Loop through all items, checking for match
710 if (NULL == (max = strchr(min, (int) '-')))
713 * No dash, check for equality
715 if (port == atoi(min))
724 * This is a range, so check if between min and max,
725 * or, if max was omitted, between min and 65K
728 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
742 * Zero-terminate next item and remember offset for n+1
744 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
756 /*********************************************************************
758 * Function : block_url
760 * Description : Called from `chat'. Check to see if we need to block this.
763 * 1 : csp = Current client state (buffers, headers, etc...)
765 * Returns : NULL => unblocked, else HTTP block response
767 *********************************************************************/
768 struct http_response *block_url(struct client_state *csp)
770 struct http_response *rsp;
771 const char *new_content_type = NULL;
774 * If it's not blocked, don't block it ;-)
776 if ((csp->action->flags & ACTION_BLOCK) == 0)
780 if (csp->action->flags & ACTION_REDIRECT)
782 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
785 * Else, prepare a response
787 if (NULL == (rsp = alloc_http_response()))
789 return cgi_error_memory();
793 * If it's an image-url, send back an image or redirect
794 * as specified by the relevant +image action
796 #ifdef FEATURE_IMAGE_BLOCKING
797 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
801 /* determine HOW images should be blocked */
802 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
804 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
806 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
808 #if 1 /* Two alternative strategies, use this one for now: */
810 /* and handle accordingly: */
811 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
813 rsp->status = strdup("403 Request blocked by Privoxy");
814 if (rsp->status == NULL)
816 free_http_response(rsp);
817 return cgi_error_memory();
819 rsp->body = bindup(image_pattern_data, image_pattern_length);
820 if (rsp->body == NULL)
822 free_http_response(rsp);
823 return cgi_error_memory();
825 rsp->content_length = image_pattern_length;
827 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
829 free_http_response(rsp);
830 return cgi_error_memory();
834 else if (0 == strcmpic(p, "blank"))
836 rsp->status = strdup("403 Request blocked by Privoxy");
837 if (rsp->status == NULL)
839 free_http_response(rsp);
840 return cgi_error_memory();
842 rsp->body = bindup(image_blank_data, image_blank_length);
843 if (rsp->body == NULL)
845 free_http_response(rsp);
846 return cgi_error_memory();
848 rsp->content_length = image_blank_length;
850 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
852 free_http_response(rsp);
853 return cgi_error_memory();
859 rsp->status = strdup("302 Local Redirect from Privoxy");
860 if (rsp->status == NULL)
862 free_http_response(rsp);
863 return cgi_error_memory();
866 if (enlist_unique_header(rsp->headers, "Location", p))
868 free_http_response(rsp);
869 return cgi_error_memory();
873 #else /* Following code is disabled for now */
875 /* and handle accordingly: */
876 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
878 p = CGI_PREFIX "send-banner?type=pattern";
880 else if (0 == strcmpic(p, "blank"))
882 p = CGI_PREFIX "send-banner?type=blank";
884 rsp->status = strdup("302 Local Redirect from Privoxy");
885 if (rsp->status == NULL)
887 free_http_response(rsp);
888 return cgi_error_memory();
891 if (enlist_unique_header(rsp->headers, "Location", p))
893 free_http_response(rsp);
894 return cgi_error_memory();
896 #endif /* Preceeding code is disabled for now */
898 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
901 * Send empty document.
903 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
906 rsp->body = strdup(" ");
907 rsp->content_length = 1;
909 rsp->status = strdup("403 Request blocked by Privoxy");
910 if (rsp->status == NULL)
912 free_http_response(rsp);
913 return cgi_error_memory();
915 if (new_content_type != 0)
917 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
918 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
920 free_http_response(rsp);
921 return cgi_error_memory();
927 #endif /* def FEATURE_IMAGE_BLOCKING */
930 * Else, generate an HTML "blocked" message:
934 struct map * exports;
938 * Workaround for stupid Netscape bug which prevents
939 * pages from being displayed if loading a referenced
940 * JavaScript or style sheet fails. So make it appear
941 * as if it succeeded.
943 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
944 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
945 && !strstr(p, "Gecko") /* save Mozilla, */
946 && !strstr(p, "compatible") /* MSIE */
947 && !strstr(p, "Opera")) /* and Opera. */
949 rsp->status = strdup("200 Request for blocked URL");
953 rsp->status = strdup("404 Request for blocked URL");
956 if (rsp->status == NULL)
958 free_http_response(rsp);
959 return cgi_error_memory();
962 exports = default_exports(csp, NULL);
965 free_http_response(rsp);
966 return cgi_error_memory();
969 #ifdef FEATURE_FORCE_LOAD
970 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
971 if (csp->http->ssl != 0)
972 #endif /* ndef FEATURE_FORCE_LOAD */
974 err = map_block_killer(exports, "force-support");
977 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
978 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
979 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
980 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
985 free_http_response(rsp);
986 return cgi_error_memory();
989 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
992 free_http_response(rsp);
993 return cgi_error_memory();
997 return finish_http_response(rsp);
1002 #ifdef FEATURE_TRUST
1003 /*********************************************************************
1005 * Function : trust_url FIXME: I should be called distrust_url
1007 * Description : Calls is_untrusted_url to determine if the URL is trusted
1008 * and if not, returns a HTTP 403 response with a reject message.
1011 * 1 : csp = Current client state (buffers, headers, etc...)
1013 * Returns : NULL => trusted, else http_response.
1015 *********************************************************************/
1016 struct http_response *trust_url(struct client_state *csp)
1018 struct http_response *rsp;
1019 struct map * exports;
1020 char buf[BUFFER_SIZE];
1022 struct url_spec **tl;
1027 * Don't bother to work on trusted URLs
1029 if (!is_untrusted_url(csp))
1035 * Else, prepare a response:
1037 if (NULL == (rsp = alloc_http_response()))
1039 return cgi_error_memory();
1042 rsp->status = strdup("403 Request blocked by Privoxy");
1043 exports = default_exports(csp, NULL);
1044 if (exports == NULL || rsp->status == NULL)
1046 free_http_response(rsp);
1047 return cgi_error_memory();
1051 * Export the protocol, host, port, and referrer information
1053 err = map(exports, "hostport", 1, csp->http->hostport, 1);
1054 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1055 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1057 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1059 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1063 if (!err) err = map(exports, "referrer", 1, "none set", 1);
1069 free_http_response(rsp);
1070 return cgi_error_memory();
1074 * Export the trust list
1077 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1079 sprintf(buf, "<li>%s</li>\n", t->spec);
1080 string_append(&p, buf);
1082 err = map(exports, "trusted-referrers", 1, p, 0);
1087 free_http_response(rsp);
1088 return cgi_error_memory();
1092 * Export the trust info, if available
1094 if (csp->config->trust_info->first)
1096 struct list_entry *l;
1099 for (l = csp->config->trust_info->first; l ; l = l->next)
1101 sprintf(buf, "<li> <a href=\"%s\">%s</a><br>\n",l->str, l->str);
1102 string_append(&p, buf);
1104 err = map(exports, "trust-info", 1, p, 0);
1108 err = map_block_killer(exports, "have-trust-info");
1114 free_http_response(rsp);
1115 return cgi_error_memory();
1119 * Export the force prefix or the force conditional block killer
1121 #ifdef FEATURE_FORCE_LOAD
1122 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1123 #else /* ifndef FEATURE_FORCE_LOAD */
1124 err = map_block_killer(exports, "force-support");
1125 #endif /* ndef FEATURE_FORCE_LOAD */
1130 free_http_response(rsp);
1131 return cgi_error_memory();
1135 * Build the response
1137 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1140 free_http_response(rsp);
1141 return cgi_error_memory();
1144 return finish_http_response(rsp);
1146 #endif /* def FEATURE_TRUST */
1148 /*********************************************************************
1150 * Function : execute_single_pcrs_command
1152 * Description : Apply single pcrs command to the subject.
1153 * The subject itself is left untouched, memory for the result
1154 * is malloc()ed and it is the caller's responsibility to free
1155 * the result when it's no longer needed.
1158 * 1 : subject = the subject (== original) string
1159 * 2 : pcrs_command = the pcrs command as string (s@foo@bar@)
1160 * 3 : hits = int* for returning the number of modifications
1162 * Returns : NULL in case of errors, otherwise the
1163 * result of the pcrs command.
1165 *********************************************************************/
1166 char *execute_single_pcrs_command(char *subject, const char *pcrs_command, int *hits)
1170 char *result = NULL;
1174 assert(pcrs_command);
1177 size = strlen(subject);
1179 if (NULL == (job = pcrs_compile_command(pcrs_command, &error)))
1181 log_error(LOG_LEVEL_ERROR, "Failed to compile pcrs command \"%s\". Error: %d.",
1182 pcrs_command, error);
1184 else if ((*hits = pcrs_execute(job, subject, size, &result, &size)) < 0)
1186 log_error(LOG_LEVEL_ERROR, "Failed to execute pcrs command: %s", pcrs_strerror(*hits));
1193 job = pcrs_free_job(job);
1200 /*********************************************************************
1202 * Function : rewrite_url
1204 * Description : Rewrites a URL with a single pcrs command
1205 * and returns the result if it differs from the
1206 * original and isn't obviously invalid.
1209 * 1 : old_url = URL to rewrite.
1210 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1213 * Returns : NULL if the pcrs_command didn't change the url, or
1214 * the result of the modification.
1216 *********************************************************************/
1217 char *rewrite_url(char *old_url, const char *pcrs_command)
1219 char *new_url = NULL;
1223 assert(pcrs_command);
1225 new_url = execute_single_pcrs_command(old_url, pcrs_command, &hits);
1229 log_error(LOG_LEVEL_REDIRECTS,
1230 "pcrs command \"%s\" didn't change \"%s\".",
1231 pcrs_command, old_url, new_url);
1234 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1236 log_error(LOG_LEVEL_ERROR,
1237 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1238 "but the result doesn't look like a valid URL and will be ignored.",
1239 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1244 log_error(LOG_LEVEL_REDIRECTS,
1245 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1246 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1254 #ifdef FEATURE_FAST_REDIRECTS
1255 /*********************************************************************
1257 * Function : get_last_url
1259 * Description : Search for the last URL inside a string.
1260 * If the string already is a URL, it will
1261 * be the first URL found.
1264 * 1 : subject = the string to check
1265 * 2 : redirect_mode = +fast-redirect{} mode
1267 * Returns : NULL if no URL was found, or
1268 * the last URL found.
1270 *********************************************************************/
1271 char *get_last_url(char *subject, const char *redirect_mode)
1273 char *new_url = NULL;
1277 assert(redirect_mode);
1279 subject = strdup(subject);
1280 if (subject == NULL)
1282 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1286 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1288 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1289 new_url = url_decode(subject);
1290 if (new_url != NULL)
1297 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1301 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1304 * Find the last URL encoded in the request
1307 while ((tmp = strstr(tmp, "http://")) != NULL)
1311 tmp = (new_url != NULL) ? new_url : subject;
1312 while ((tmp = strstr(tmp, "https://")) != NULL)
1317 if ((new_url != NULL)
1318 && ( (new_url != subject)
1319 || (0 == strncmpic(subject, "http://", 7))
1320 || (0 == strncmpic(subject, "https://", 8))
1324 * Return new URL if we found a redirect
1325 * or if the subject already was a URL.
1327 * The second case makes sure that we can
1328 * chain get_last_url after another redirection check
1329 * (like rewrite_url) without losing earlier redirects.
1331 new_url = strdup(new_url);
1340 #endif /* def FEATURE_FAST_REDIRECTS */
1343 /*********************************************************************
1345 * Function : redirect_url
1347 * Description : Checks if Privoxy should answer the request with
1348 * a HTTP redirect and generates the redirect if
1352 * 1 : csp = Current client state (buffers, headers, etc...)
1354 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1356 *********************************************************************/
1357 struct http_response *redirect_url(struct client_state *csp)
1359 struct http_response *rsp;
1360 #ifdef FEATURE_FAST_REDIRECTS
1362 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1363 * as compile-time option? The user can easily disable
1364 * it in his action file.
1366 char * redirect_mode;
1367 #endif /* def FEATURE_FAST_REDIRECTS */
1368 char *old_url = NULL;
1369 char *new_url = NULL;
1370 char *redirection_string;
1372 if ((csp->action->flags & ACTION_REDIRECT))
1374 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1377 * If the redirection string begins with 's',
1378 * assume it's a pcrs command, otherwise treat it as
1379 * properly formatted URL and use it for the redirection
1382 * According to RFC 2616 section 14.30 the URL
1383 * has to be absolute and if the user tries:
1384 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1385 * she would get undefined results anyway.
1389 if (*redirection_string == 's')
1391 old_url = csp->http->url;
1392 new_url = rewrite_url(old_url, redirection_string);
1396 log_error(LOG_LEVEL_REDIRECTS,
1397 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1398 redirection_string);
1399 new_url = strdup(redirection_string);
1403 #ifdef FEATURE_FAST_REDIRECTS
1404 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1406 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1409 * If it exists, use the previously rewritten URL as input
1410 * otherwise just use the old path.
1412 old_url = new_url ? new_url : strdup(csp->http->path);
1413 new_url = get_last_url(old_url, redirect_mode);
1416 #endif /* def FEATURE_FAST_REDIRECTS */
1418 /* Did any redirect action trigger? */
1421 if (0 == strcmpic(new_url, csp->http->url))
1423 log_error(LOG_LEVEL_ERROR,
1424 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1425 csp->http->url, new_url);
1430 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1432 if (NULL == (rsp = alloc_http_response()))
1435 return cgi_error_memory();
1438 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1439 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1442 free_http_response(rsp);
1443 return cgi_error_memory();
1446 return finish_http_response(rsp);
1450 /* Only reached if no redirect is required */
1456 #ifdef FEATURE_IMAGE_BLOCKING
1457 /*********************************************************************
1459 * Function : is_imageurl
1461 * Description : Given a URL, decide whether it is an image or not,
1462 * using either the info from a previous +image action
1463 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1464 * is MSIE and not on a Mac, tell from the browser's accept
1468 * 1 : csp = Current client state (buffers, headers, etc...)
1470 * Returns : True (nonzero) if URL is an image, false (0)
1473 *********************************************************************/
1474 int is_imageurl(struct client_state *csp)
1476 #ifdef FEATURE_IMAGE_DETECT_MSIE
1479 tmp = get_header_value(csp->headers, "User-Agent:");
1480 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1482 tmp = get_header_value(csp->headers, "Accept:");
1483 if (tmp && strstr(tmp, "image/gif"))
1485 /* Client will accept HTML. If this seems counterintuitive,
1495 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1497 return ((csp->action->flags & ACTION_IMAGE) != 0);
1500 #endif /* def FEATURE_IMAGE_BLOCKING */
1503 #ifdef FEATURE_TRUST
1504 /*********************************************************************
1506 * Function : is_untrusted_url
1508 * Description : Should we "distrust" this URL (and block it)?
1510 * Yes if it matches a line in the trustfile, or if the
1511 * referrer matches a line starting with "+" in the
1516 * 1 : csp = Current client state (buffers, headers, etc...)
1518 * Returns : 0 => trusted, 1 => untrusted
1520 *********************************************************************/
1521 int is_untrusted_url(struct client_state *csp)
1523 struct file_list *fl;
1524 struct block_spec *b;
1525 struct url_spec **trusted_url;
1526 struct http_request rhttp[1];
1527 const char * referer;
1531 * If we don't have a trustlist, we trust everybody
1533 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1538 memset(rhttp, '\0', sizeof(*rhttp));
1541 * Do we trust the request URL itself?
1543 for (b = b->next; b ; b = b->next)
1545 if (url_match(b->url, csp->http))
1551 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1553 /* no referrer was supplied */
1559 * If not, do we maybe trust its referrer?
1561 err = parse_http_url(referer, rhttp, csp);
1567 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1569 if (url_match(*trusted_url, rhttp))
1571 /* if the URL's referrer is from a trusted referrer, then
1572 * add the target spec to the trustfile as an unblocked
1573 * domain and return 0 (which means it's OK).
1578 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1582 char * new_entry = strdup("~");
1584 string_append(&new_entry, csp->http->hostport);
1586 path = csp->http->path;
1587 if ( (path[0] == '/')
1589 && ((path_end = strchr(path + 2, '/')) != NULL))
1591 /* since this path points into a user's home space
1592 * be sure to include this spec in the trustfile.
1594 int path_len = path_end - path; /* save offset */
1595 path = strdup(path); /* Copy string */
1598 path_end = path + path_len; /* regenerate ptr to new buffer */
1599 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1601 string_join(&new_entry, path);
1605 * Give a reason for generating this entry.
1607 string_append(&new_entry, " # Trusted referrer was: ");
1608 string_append(&new_entry, referer);
1610 if (new_entry != NULL)
1612 if (-1 == fprintf(fp, "%s\n", new_entry))
1614 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1615 new_entry, csp->config->trustfile);
1621 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1622 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1629 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1630 csp->http->hostport, csp->config->trustfile);
1637 #endif /* def FEATURE_TRUST */
1640 /*********************************************************************
1642 * Function : pcrs_filter_response
1644 * Description : Execute all text substitutions from all applying
1645 * +filter actions on the text buffer that's been accumulated
1646 * in csp->iob->buf. If this changes the contents, set
1647 * csp->content_length to the modified size and raise the
1648 * CSP_FLAG_MODIFIED flag.
1651 * 1 : csp = Current client state (buffers, headers, etc...)
1653 * Returns : a pointer to the (newly allocated) modified buffer.
1654 * or NULL if there were no hits or something went wrong
1656 *********************************************************************/
1657 char *pcrs_filter_response(struct client_state *csp)
1660 size_t size, prev_size;
1662 char *old = csp->iob->cur, *new = NULL;
1665 struct file_list *fl;
1666 struct re_filterfile_spec *b;
1667 struct list_entry *filtername;
1669 int i, found_filters = 0;
1674 if (csp->iob->cur >= csp->iob->eod)
1678 size = csp->iob->eod - csp->iob->cur;
1681 * Need to check the set of re_filterfiles...
1683 for (i = 0; i < MAX_AF_FILES; i++)
1696 if (0 == found_filters)
1698 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1703 * If the body has a "chunked" transfer-encoding,
1704 * get rid of it first, adjusting size and iob->eod
1706 if (csp->flags & CSP_FLAG_CHUNKED)
1708 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1709 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1713 csp->iob->eod = csp->iob->cur + size;
1714 csp->flags |= CSP_FLAG_MODIFIED;
1717 for (i = 0; i < MAX_AF_FILES; i++)
1720 if ((NULL == fl) || (NULL == fl->f))
1723 * Either there are no filter files
1724 * left, or this filter file just
1725 * contains no valid filters.
1727 * Continue to be sure we don't miss
1728 * valid filter files that are chained
1729 * after empty or invalid ones.
1734 * For all applying +filter actions, look if a filter by that
1735 * name exists and if yes, execute it's pcrs_joblist on the
1738 for (b = fl->f; b; b = b->next)
1740 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1741 filtername ; filtername = filtername->next)
1743 if (strcmp(b->name, filtername->str) == 0)
1745 int current_hits = 0;
1747 if ( NULL == b->joblist )
1749 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1754 /* Apply all jobs from the joblist */
1755 for (job = b->joblist; NULL != job; job = job->next)
1757 current_hits += pcrs_execute(job, old, size, &new, &size);
1758 if (old != csp->iob->cur) free(old);
1762 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) with filter %s produced %d hits (new size %d).",
1763 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1765 hits += current_hits;
1772 * If there were no hits, destroy our copy and let
1773 * chat() use the original in csp->iob
1781 csp->flags |= CSP_FLAG_MODIFIED;
1782 csp->content_length = size;
1790 /*********************************************************************
1792 * Function : gif_deanimate_response
1794 * Description : Deanimate the GIF image that has been accumulated in
1795 * csp->iob->buf, set csp->content_length to the modified
1796 * size and raise the CSP_FLAG_MODIFIED flag.
1799 * 1 : csp = Current client state (buffers, headers, etc...)
1801 * Returns : a pointer to the (newly allocated) modified buffer.
1802 * or NULL in case something went wrong.
1804 *********************************************************************/
1805 char *gif_deanimate_response(struct client_state *csp)
1807 struct binbuffer *in, *out;
1809 size_t size = csp->iob->eod - csp->iob->cur;
1812 * If the body has a "chunked" transfer-encoding,
1813 * get rid of it first, adjusting size and iob->eod
1815 if (csp->flags & CSP_FLAG_CHUNKED)
1817 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1818 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1822 csp->iob->eod = csp->iob->cur + size;
1823 csp->flags |= CSP_FLAG_MODIFIED;
1826 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1827 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1829 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1833 in->buffer = csp->iob->cur;
1836 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1838 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1845 if ((int)size == out->offset)
1847 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1851 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1853 csp->content_length = out->offset;
1854 csp->flags |= CSP_FLAG_MODIFIED;
1864 /*********************************************************************
1866 * Function : jpeg_inspect_response
1871 * 1 : csp = Current client state (buffers, headers, etc...)
1873 * Returns : a pointer to the (newly allocated) modified buffer
1874 * or NULL in case something went wrong.
1876 *********************************************************************/
1877 char *jpeg_inspect_response(struct client_state *csp)
1879 struct binbuffer *in = NULL, *out = NULL;
1881 size_t size = csp->iob->eod - csp->iob->cur;
1884 * If the body has a "chunked" transfer-encoding,
1885 * get rid of it first, adjusting size and iob->eod
1887 if (csp->flags & CSP_FLAG_CHUNKED)
1889 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1890 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1894 csp->iob->eod = csp->iob->cur + size;
1895 csp->flags |= CSP_FLAG_MODIFIED;
1898 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1900 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
1904 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
1906 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
1910 in->buffer = csp->iob->cur;
1914 * Calling jpeg_inspect has the side-effect of creating and
1915 * modifying the image buffer of "out" directly.
1917 if (jpeg_inspect(in, out))
1919 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
1927 csp->content_length = out->offset;
1928 csp->flags |= CSP_FLAG_MODIFIED;
1938 /*********************************************************************
1940 * Function : remove_chunked_transfer_coding
1942 * Description : In-situ remove the "chunked" transfer coding as defined
1943 * in rfc2616 from a buffer.
1946 * 1 : buffer = Pointer to the text buffer
1947 * 2 : size = Number of bytes to be processed
1949 * Returns : The new size, i.e. the number of bytes from buffer which
1950 * are occupied by the stripped body, or 0 in case something
1953 *********************************************************************/
1954 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1957 unsigned int chunksize = 0;
1958 char *from_p, *to_p;
1961 from_p = to_p = buffer;
1963 if (sscanf(buffer, "%x", &chunksize) != 1)
1965 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1969 while (chunksize > 0)
1971 if (NULL == (from_p = strstr(from_p, "\r\n")))
1973 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1977 if ((newsize += chunksize) >= size)
1979 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
1984 memmove(to_p, from_p, (size_t) chunksize);
1985 to_p = buffer + newsize;
1986 from_p += chunksize + 2;
1988 if (sscanf(from_p, "%x", &chunksize) != 1)
1990 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1995 /* FIXME: Should this get its own loglevel? */
1996 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
2002 /*********************************************************************
2004 * Function : url_actions
2006 * Description : Gets the actions for this URL.
2009 * 1 : http = http_request request for blocked URLs
2010 * 2 : csp = Current client state (buffers, headers, etc...)
2014 *********************************************************************/
2015 void url_actions(struct http_request *http,
2016 struct client_state *csp)
2018 struct file_list *fl;
2019 struct url_actions *b;
2022 init_current_action(csp->action);
2024 for (i = 0; i < MAX_AF_FILES; i++)
2026 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2031 apply_url_actions(csp->action, http, b);
2038 /*********************************************************************
2040 * Function : apply_url_actions
2042 * Description : Applies a list of URL actions.
2045 * 1 : action = Destination.
2046 * 2 : http = Current URL
2047 * 3 : b = list of URL actions to apply
2051 *********************************************************************/
2052 void apply_url_actions(struct current_action_spec *action,
2053 struct http_request *http,
2054 struct url_actions *b)
2058 /* Should never happen */
2062 for (b = b->next; NULL != b; b = b->next)
2064 if (url_match(b->url, http))
2066 merge_current_action(action, b->action);
2072 /*********************************************************************
2074 * Function : forward_url
2076 * Description : Should we forward this to another proxy?
2079 * 1 : http = http_request request for current URL
2080 * 2 : csp = Current client state (buffers, headers, etc...)
2082 * Returns : Pointer to forwarding information.
2084 *********************************************************************/
2085 const struct forward_spec * forward_url(struct http_request *http,
2086 struct client_state *csp)
2088 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2089 struct forward_spec *fwd = csp->config->forward;
2098 if (url_match(fwd->url, http))
2109 /*********************************************************************
2111 * Function : direct_response
2113 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2114 * request and if so, return a HTTP 501 to the client.
2116 * FIXME: I have a stupid name and I should handle the
2117 * requests properly. Still, what we do here is rfc-
2118 * compliant, whereas ignoring or forwarding are not.
2121 * 1 : csp = Current client state (buffers, headers, etc...)
2123 * Returns : http_response if , NULL if nonmatch or handler fail
2125 *********************************************************************/
2126 struct http_response *direct_response(struct client_state *csp)
2128 struct http_response *rsp;
2129 struct list_entry *p;
2131 if ((0 == strcmpic(csp->http->gpc, "trace"))
2132 || (0 == strcmpic(csp->http->gpc, "options")))
2134 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2136 if (!strncmp("Max-Forwards:", p->str, 13)
2137 && (*(p->str+13) != '\0') && (atoi(p->str+13) == 0))
2139 /* FIXME: We could handle at least TRACE here,
2140 but that would require a verbatim copy of
2141 the request which we don't have anymore */
2143 log_error(LOG_LEVEL_HEADER, "Found Max-Forwards:0 in OPTIONS or TRACE request -- Returning 501");
2145 /* Get mem for response or fail*/
2146 if (NULL == (rsp = alloc_http_response()))
2148 return cgi_error_memory();
2151 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2153 free_http_response(rsp);
2154 return cgi_error_memory();
2158 return(finish_http_response(rsp));