1 const char filters_rcs[] = "$Id: filters.c,v 1.67 2006/11/28 15:19:43 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.67 2006/11/28 15:19:43 fabiankeil
44 * Implemented +redirect{s@foo@bar@} to generate
45 * a redirect based on a rewritten version of the
48 * Revision 1.66 2006/09/23 13:26:38 roro
49 * Replace TABs by spaces in source code.
51 * Revision 1.65 2006/09/21 12:54:43 fabiankeil
52 * Fix +redirect{}. Didn't work with -fast-redirects.
54 * Revision 1.64 2006/08/31 10:55:49 fabiankeil
55 * Block requests for untrusted URLs with status
56 * code 403 instead of 200.
58 * Revision 1.63 2006/08/31 10:11:28 fabiankeil
59 * Don't free p which is still in use and will be later
60 * freed by free_map(). Don't claim the referrer is unknown
61 * when the client didn't set one.
63 * Revision 1.62 2006/08/14 00:27:47 david__schmidt
64 * Feature request 595948: Re-Filter logging in single line
66 * Revision 1.61 2006/08/03 02:46:41 david__schmidt
67 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
69 * Revision 1.60 2006/07/18 14:48:46 david__schmidt
70 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
71 * with what was really the latest development (the v_3_0_branch branch)
73 * Revision 1.58.2.9 2006/01/29 23:10:56 david__schmidt
74 * Multiple filter file support
76 * Revision 1.58.2.8 2005/05/07 21:50:55 david__schmidt
77 * A few memory leaks plugged (mostly on error paths)
79 * Revision 1.58.2.7 2004/10/03 12:53:32 david__schmidt
80 * Add the ability to check jpeg images for invalid
81 * lengths of comment blocks. Defensive strategy
82 * against the exploit:
83 * Microsoft Security Bulletin MS04-028
84 * Buffer Overrun in JPEG Processing (GDI+) Could
85 * Allow Code Execution (833987)
86 * Enabled with +inspect-jpegs in actions files.
88 * Revision 1.58.2.6 2003/12/06 22:18:27 gliptak
89 * Correcting compile problem with FEATURE_IMAGE_BLOCKING
91 * Revision 1.58.2.5 2003/11/11 13:10:31 oes
92 * Fixed bug #839859: "See why" link URL now gets url-encoded.
94 * Revision 1.58.2.4 2003/02/28 12:52:45 oes
97 * Revision 1.58.2.3 2002/09/25 14:51:51 oes
98 * Added basic support for OPTIONS and TRACE HTTP methods:
99 * New function direct_response which handles OPTIONS and
100 * TRACE requests whose Max-Forwards header field is zero.
102 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
103 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
105 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
106 * - Bugfix: Executing a filters without jobs no longer results in
107 * turing off *all* filters.
108 * - Security fix: Malicious web servers can't cause a seg fault
109 * through bogus chunk sizes anymore
111 * Revision 1.58 2002/04/24 02:11:17 oes
112 * Jon's multiple AF patch: url_actions now evaluates rules
115 * Revision 1.57 2002/04/08 20:38:34 swa
118 * Revision 1.56 2002/04/05 15:51:24 oes
119 * - bugfix: error-pages now get correct request protocol
120 * - fix for invalid HTML in trust info
122 * Revision 1.55 2002/04/02 16:13:51 oes
123 * Fix: No "Go there anyway" for SSL
125 * Revision 1.54 2002/04/02 14:55:56 oes
126 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
128 * Revision 1.53 2002/03/26 22:29:54 swa
129 * we have a new homepage!
131 * Revision 1.52 2002/03/24 16:35:57 jongfoster
134 * Revision 1.51 2002/03/24 15:23:33 jongfoster
137 * Revision 1.50 2002/03/24 13:25:43 swa
138 * name change related issues
140 * Revision 1.49 2002/03/16 20:29:14 oes
143 * Revision 1.48 2002/03/13 20:25:34 oes
144 * Better logging for content filters
146 * Revision 1.47 2002/03/13 00:30:52 jongfoster
148 * Added option of always sending redirect for imageblock,
149 * currently disabled with #if 0.
151 * Revision 1.46 2002/03/12 01:42:49 oes
152 * Introduced modular filters
154 * Revision 1.45 2002/03/08 16:47:50 oes
155 * Added choice beween GIF and PNG built-in images
157 * Revision 1.44 2002/03/07 03:49:31 oes
158 * - Fixed compiler warnings etc
159 * - Changed built-in images from GIF to PNG
160 * (with regard to Unisys patent issue)
161 * - Added a 4x4 pattern PNG which is less intrusive
162 * than the logo but also clearly marks the deleted banners
164 * Revision 1.43 2002/01/22 23:51:59 jongfoster
165 * Replacing strsav() with the safer string_append().
167 * Adding missing html_encode() to error message generators. Where encoded
168 * and unencoded versions of a string were provided, removing the unencoded
171 * Revision 1.42 2002/01/17 21:00:32 jongfoster
172 * Moving all our URL and URL pattern parsing code to urlmatch.c.
174 * Using a single, simple url_match(pattern,url) function - rather than
175 * the 3-line match routine which was repeated all over the place.
177 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
179 * Using parse_http_url() to parse URLs without faking a HTTP
180 * request line for parse_http_request().
182 * Revision 1.41 2001/11/13 00:14:07 jongfoster
183 * Fixing stupid bug now I've figured out what || means.
184 * (It always returns 0 or 1, not one of it's paramaters.)
186 * Revision 1.40 2001/10/26 17:37:55 oes
187 * - Re-enabled Netscape 200/404 bug workaround in block_url():
188 * - Removed OS/2 special case
189 * - Made block_url() independant from sed() having been run
190 * - Made trust_url independant from sed() having been run
191 * - Made is_imageurl independant from sed() having been run.
192 * It now checks User-Agent: and Accept: by itself.
195 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
196 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
197 * threads to call select() simultaneously. So, it's time to do a real, live,
198 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
199 * (native). Both versions will work, but using __OS2__ offers multi-threading.
201 * Revision 1.38 2001/10/23 21:32:33 jongfoster
202 * Adding error-checking to selected functions
204 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
205 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
206 * filters.c. Added a FIXME in front of the offending code. I'll gladly
207 * put in a better/more robust fix for all parties if one is presented...
208 * It seems that just returning 200 instead of 404 would pretty much fix
209 * it for everyone, but I don't know all the history of the problem.
211 * Revision 1.36 2001/10/10 16:44:16 oes
212 * Added match_portlist function
214 * Revision 1.35 2001/10/07 15:41:23 oes
215 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
217 * New function remove_chunked_transfer_coding that strips chunked
218 * transfer coding to plain and is called by pcrs_filter_response
219 * and gif_deanimate_response if neccessary
221 * Improved handling of zero-change re_filter runs
223 * pcrs_filter_response and gif_deanimate_response now remove
224 * chunked transfer codeing before processing the body.
226 * Revision 1.34 2001/09/20 15:49:36 steudten
228 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
229 * See cgi.c fill_template().
231 * Revision 1.33 2001/09/16 17:05:14 jongfoster
232 * Removing unused #include showarg.h
234 * Revision 1.32 2001/09/16 13:21:27 jongfoster
235 * Changes to use new list functions.
237 * Revision 1.31 2001/09/16 11:38:02 jongfoster
238 * Splitting fill_template() into 2 functions:
239 * template_load() loads the file
240 * template_fill() performs the PCRS regexps.
241 * This is because the CGI edit interface has a "table row"
242 * template which is used many times in the page - this
243 * change means it's only loaded from disk once.
245 * Revision 1.30 2001/09/16 11:00:10 jongfoster
246 * New function alloc_http_response, for symmetry with free_http_response
248 * Revision 1.29 2001/09/13 23:32:40 jongfoster
249 * Moving image data to cgi.c rather than cgi.h
250 * Fixing a GPF under Win32 (and any other OS that protects global
251 * constants from being written to).
253 * Revision 1.28 2001/09/10 10:18:51 oes
254 * Silenced compiler warnings
256 * Revision 1.27 2001/08/05 16:06:20 jongfoster
257 * Modifiying "struct map" so that there are now separate header and
258 * "map_entry" structures. This means that functions which modify a
259 * map no longer need to return a pointer to the modified map.
260 * Also, it no longer reverses the order of the entries (which may be
261 * important with some advanced template substitutions).
263 * Revision 1.26 2001/07/30 22:08:36 jongfoster
264 * Tidying up #defines:
265 * - All feature #defines are now of the form FEATURE_xxx
266 * - Permanently turned off WIN_GUI_EDIT
267 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
269 * Revision 1.25 2001/07/26 10:09:46 oes
270 * Made browser detection a little less naive
272 * Revision 1.24 2001/07/25 17:22:51 oes
273 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
275 * Revision 1.23 2001/07/23 13:40:12 oes
276 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
278 * Revision 1.22 2001/07/18 12:29:34 oes
279 * - Made gif_deanimate_response respect
280 * csp->action->string[ACTION_STRING_DEANIMATE]
281 * - Logging cosmetics
283 * Revision 1.21 2001/07/13 13:59:53 oes
284 * - Introduced gif_deanimate_response which shares the
285 * generic content modification interface of pcrs_filter_response
286 * and acts as a wrapper to deanimate.c:gif_deanimate()
287 * - Renamed re_process_buffer to pcrs_filter_response
288 * - pcrs_filter_response now returns NULL on failiure
289 * - Removed all #ifdef PCRS
291 * Revision 1.20 2001/07/01 17:01:04 oes
292 * Added comments and missing return statement in is_untrusted_url()
294 * Revision 1.19 2001/06/29 21:45:41 oes
295 * Indentation, CRLF->LF, Tab-> Space
297 * Revision 1.18 2001/06/29 13:27:38 oes
298 * - Cleaned up, renamed and reorderd functions
299 * and improved comments
302 * - Ported to CGI platform. Now delivers
303 * http_response or NULL
304 * - Unified HTML and GIF generation (moved image detection
305 * and GIF generation here from jcc.c:chat())
306 * - Fixed HTTP status to:
307 * - 403 (Forbidden) for the "blocked" HTML message
308 * - 200 (OK) for GIF answers
309 * - 302 (Redirect) for redirect to GIF
312 * - Ported to CGI platform. Now delivers
313 * http_response or NULL
314 * - Separated detection of untrusted URL into
315 * (bool)is_untrusted_url
316 * - Added enforcement of untrusted requests
318 * - Moved redirect_url() from cgi.c to here
319 * and ported it to the CGI platform
321 * - Removed logentry from cancelled commit
323 * Revision 1.17 2001/06/09 10:55:28 jongfoster
324 * Changing BUFSIZ ==> BUFFER_SIZE
326 * Revision 1.16 2001/06/07 23:10:26 jongfoster
327 * Allowing unanchored domain patterns to back off and retry
328 * if they partially match. Optimized right-anchored patterns.
329 * Moving ACL and forward files into config file.
330 * Replacing struct gateway with struct forward_spec
332 * Revision 1.15 2001/06/03 19:12:00 oes
333 * extracted-CGI relevant stuff
335 * Revision 1.14 2001/06/01 10:30:55 oes
336 * Added optional left-anchoring to domaincmp
338 * Revision 1.13 2001/05/31 21:21:30 jongfoster
339 * Permissionsfile / actions file changes:
340 * - Changed "permission" to "action" throughout
341 * - changes to file format to allow string parameters
342 * - Moved helper functions to actions.c
344 * Revision 1.12 2001/05/31 17:35:20 oes
346 * - Enhanced domain part globbing with infix and prefix asterisk
347 * matching and optional unanchored operation
349 * Revision 1.11 2001/05/29 11:53:23 oes
350 * "See why" link added to "blocked" page
352 * Revision 1.10 2001/05/29 09:50:24 jongfoster
353 * Unified blocklist/imagelist/permissionslist.
354 * File format is still under discussion, but the internal changes
357 * Also modified interceptor behaviour:
358 * - We now intercept all URLs beginning with one of the following
359 * prefixes (and *only* these prefixes):
361 * * http://ijbswa.sf.net/config/
362 * * http://ijbswa.sourceforge.net/config/
363 * - New interceptors "home page" - go to http://i.j.b/ to see it.
364 * - Internal changes so that intercepted and fast redirect pages
365 * are not replaced with an image.
366 * - Interceptors now have the option to send a binary page direct
367 * to the client. (i.e. ijb-send-banner uses this)
368 * - Implemented show-url-info interceptor. (Which is why I needed
369 * the above interceptors changes - a typical URL is
370 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
371 * The previous mechanism would not have intercepted that, and
372 * if it had been intercepted then it then it would have replaced
375 * Revision 1.9 2001/05/27 22:17:04 oes
377 * - re_process_buffer no longer writes the modified buffer
378 * to the client, which was very ugly. It now returns the
379 * buffer, which it is then written by chat.
381 * - content_length now adjusts the Content-Length: header
382 * for modified documents rather than crunch()ing it.
383 * (Length info in csp->content_length, which is 0 for
384 * unmodified documents)
386 * - For this to work, sed() is called twice when filtering.
388 * Revision 1.8 2001/05/26 17:13:28 jongfoster
389 * Filled in a function comment.
391 * Revision 1.7 2001/05/26 15:26:15 jongfoster
392 * ACL feature now provides more security by immediately dropping
393 * connections from untrusted hosts.
395 * Revision 1.6 2001/05/26 00:28:36 jongfoster
396 * Automatic reloading of config file.
397 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
398 * Most of the global variables have been moved to a new
399 * struct configuration_spec, accessed through csp->config->globalname
400 * Most of the globals remaining are used by the Win32 GUI.
402 * Revision 1.5 2001/05/25 22:34:30 jongfoster
405 * Revision 1.4 2001/05/22 18:46:04 oes
407 * - Enabled filtering banners by size rather than URL
408 * by adding patterns that replace all standard banner
409 * sizes with the "Junkbuster" gif to the re_filterfile
411 * - Enabled filtering WebBugs by providing a pattern
412 * which kills all 1x1 images
414 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
415 * which is selected by the (nonstandard and therefore
416 * capital) letter 'U' in the option string.
417 * It causes the quantifiers to be ungreedy by default.
418 * Appending a ? turns back to greedy (!).
420 * - Added a new interceptor ijb-send-banner, which
421 * sends back the "Junkbuster" gif. Without imagelist or
422 * MSIE detection support, or if tinygif = 1, or the
423 * URL isn't recognized as an imageurl, a lame HTML
424 * explanation is sent instead.
426 * - Added new feature, which permits blocking remote
427 * script redirects and firing back a local redirect
429 * The feature is conditionally compiled, i.e. it
430 * can be disabled with --disable-fast-redirects,
431 * plus it must be activated by a "fast-redirects"
432 * line in the config file, has its own log level
433 * and of course wants to be displayed by show-proxy-args
434 * Note: Boy, all the #ifdefs in 1001 locations and
435 * all the fumbling with configure.in and acconfig.h
436 * were *way* more work than the feature itself :-(
438 * - Because a generic redirect template was needed for
439 * this, tinygif = 3 now uses the same.
441 * - Moved GIFs, and other static HTTP response templates
446 * - Removed some >400 CRs again (Jon, you really worked
449 * Revision 1.3 2001/05/20 16:44:47 jongfoster
450 * Removing last hardcoded Junkbusters.com URLs.
452 * Revision 1.2 2001/05/20 01:21:20 jongfoster
453 * Version 2.9.4 checkin.
454 * - Merged popupfile and cookiefile, and added control over PCRS
455 * filtering, in new "permissionsfile".
456 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
457 * file error you now get a message box (in the Win32 GUI) rather
458 * than the program exiting with no explanation.
459 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
461 * - Removed tabs from "config"
462 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
463 * - Bumped up version number.
465 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
466 * Initial import of version 2.9.3 source tree
469 *********************************************************************/
475 #include <sys/types.h>
484 #endif /* ndef __OS2__ */
485 #include <netinet/in.h>
487 #include <winsock2.h>
488 #endif /* ndef _WIN32 */
492 #endif /* def __OS2__ */
500 #include "jbsockets.h"
501 #include "miscutil.h"
505 #include "deanimate.h"
506 #include "urlmatch.h"
512 const char filters_h_rcs[] = FILTERS_H_VERSION;
514 /* Fix a problem with Solaris. There should be no effect on other
516 * Solaris's isspace() is a macro which uses it's argument directly
517 * as an array index. Therefore we need to make sure that high-bit
518 * characters generate +ve values, and ideally we also want to make
519 * the argument match the declared parameter type of "int".
521 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
525 /*********************************************************************
527 * Function : block_acl
529 * Description : Block this request?
530 * Decide yes or no based on ACL file.
533 * 1 : dst = The proxy or gateway address this is going to.
534 * Or NULL to check all possible targets.
535 * 2 : csp = Current client state (buffers, headers, etc...)
536 * Also includes the client IP address.
538 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
540 *********************************************************************/
541 int block_acl(struct access_control_addr *dst, struct client_state *csp)
543 struct access_control_list *acl = csp->config->acl;
545 /* if not using an access control list, then permit the connection */
551 /* search the list */
554 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
558 /* Just want to check if they have any access */
559 if (acl->action == ACL_PERMIT)
564 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
565 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
567 if (acl->action == ACL_PERMIT)
585 /*********************************************************************
587 * Function : acl_addr
589 * Description : Called from `load_config' to parse an ACL address.
592 * 1 : aspec = String specifying ACL address.
593 * 2 : aca = struct access_control_addr to fill in.
595 * Returns : 0 => Ok, everything else is an error.
597 *********************************************************************/
598 int acl_addr(char *aspec, struct access_control_addr *aca)
600 int i, masklength, port;
606 if ((p = strchr(aspec, '/')) != NULL)
610 if (ijb_isdigit(*p) == 0)
614 masklength = atoi(p);
617 if ((masklength < 0) || (masklength > 32))
622 if ((p = strchr(aspec, ':')) != NULL)
626 if (ijb_isdigit(*p) == 0)
635 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
637 if (aca->addr == INADDR_NONE)
642 /* build the netmask */
644 for (i=1; i <= masklength ; i++)
646 aca->mask |= (1 << (32 - i));
649 /* now mask off the host portion of the ip address
650 * (i.e. save on the network portion of the address).
652 aca->addr = aca->addr & aca->mask;
657 #endif /* def FEATURE_ACL */
660 /*********************************************************************
662 * Function : match_portlist
664 * Description : Check if a given number is covered by a comma
665 * separated list of numbers and ranges (a,b-c,d,..)
668 * 1 : portlist = String with list
669 * 2 : port = port to check
671 * Returns : 0 => no match
674 *********************************************************************/
675 int match_portlist(const char *portlist, int port)
677 char *min, *max, *next, *portlist_copy;
679 min = next = portlist_copy = strdup(portlist);
682 * Zero-terminate first item and remember offset for next
684 if (NULL != (next = strchr(portlist_copy, (int) ',')))
690 * Loop through all items, checking for match
694 if (NULL == (max = strchr(min, (int) '-')))
697 * No dash, check for equality
699 if (port == atoi(min))
708 * This is a range, so check if between min and max,
709 * or, if max was omitted, between min and 65K
712 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
726 * Zero-terminate next item and remember offset for n+1
728 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
740 /*********************************************************************
742 * Function : block_url
744 * Description : Called from `chat'. Check to see if we need to block this.
747 * 1 : csp = Current client state (buffers, headers, etc...)
749 * Returns : NULL => unblocked, else HTTP block response
751 *********************************************************************/
752 struct http_response *block_url(struct client_state *csp)
754 struct http_response *rsp;
755 const char *new_content_type = NULL;
758 * If it's not blocked, don't block it ;-)
760 if ((csp->action->flags & ACTION_BLOCK) == 0)
764 if (csp->action->flags & ACTION_REDIRECT)
766 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
769 * Else, prepare a response
771 if (NULL == (rsp = alloc_http_response()))
773 return cgi_error_memory();
777 * If it's an image-url, send back an image or redirect
778 * as specified by the relevant +image action
780 #ifdef FEATURE_IMAGE_BLOCKING
781 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
785 /* determine HOW images should be blocked */
786 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
788 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
790 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
792 #if 1 /* Two alternative strategies, use this one for now: */
794 /* and handle accordingly: */
795 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
797 rsp->status = strdup("403 Request blocked by Privoxy");
798 if (rsp->status == NULL)
800 free_http_response(rsp);
801 return cgi_error_memory();
803 rsp->body = bindup(image_pattern_data, image_pattern_length);
804 if (rsp->body == NULL)
806 free_http_response(rsp);
807 return cgi_error_memory();
809 rsp->content_length = image_pattern_length;
811 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
813 free_http_response(rsp);
814 return cgi_error_memory();
818 else if (0 == strcmpic(p, "blank"))
820 rsp->status = strdup("403 Request blocked by Privoxy");
821 if (rsp->status == NULL)
823 free_http_response(rsp);
824 return cgi_error_memory();
826 rsp->body = bindup(image_blank_data, image_blank_length);
827 if (rsp->body == NULL)
829 free_http_response(rsp);
830 return cgi_error_memory();
832 rsp->content_length = image_blank_length;
834 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
836 free_http_response(rsp);
837 return cgi_error_memory();
843 rsp->status = strdup("302 Local Redirect from Privoxy");
844 if (rsp->status == NULL)
846 free_http_response(rsp);
847 return cgi_error_memory();
850 if (enlist_unique_header(rsp->headers, "Location", p))
852 free_http_response(rsp);
853 return cgi_error_memory();
857 #else /* Following code is disabled for now */
859 /* and handle accordingly: */
860 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
862 p = CGI_PREFIX "send-banner?type=pattern";
864 else if (0 == strcmpic(p, "blank"))
866 p = CGI_PREFIX "send-banner?type=blank";
868 rsp->status = strdup("302 Local Redirect from Privoxy");
869 if (rsp->status == NULL)
871 free_http_response(rsp);
872 return cgi_error_memory();
875 if (enlist_unique_header(rsp->headers, "Location", p))
877 free_http_response(rsp);
878 return cgi_error_memory();
880 #endif /* Preceeding code is disabled for now */
882 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
885 * Send empty document.
887 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
890 rsp->body = strdup(" ");
891 rsp->content_length = 1;
893 rsp->status = strdup("403 Request blocked by Privoxy");
894 if (rsp->status == NULL)
896 free_http_response(rsp);
897 return cgi_error_memory();
899 if (new_content_type != 0)
901 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
902 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
904 free_http_response(rsp);
905 return cgi_error_memory();
911 #endif /* def FEATURE_IMAGE_BLOCKING */
914 * Else, generate an HTML "blocked" message:
918 struct map * exports;
922 * Workaround for stupid Netscape bug which prevents
923 * pages from being displayed if loading a referenced
924 * JavaScript or style sheet fails. So make it appear
925 * as if it succeeded.
927 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
928 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
929 && !strstr(p, "Gecko") /* save Mozilla, */
930 && !strstr(p, "compatible") /* MSIE */
931 && !strstr(p, "Opera")) /* and Opera. */
933 rsp->status = strdup("200 Request for blocked URL");
937 rsp->status = strdup("404 Request for blocked URL");
940 if (rsp->status == NULL)
942 free_http_response(rsp);
943 return cgi_error_memory();
946 exports = default_exports(csp, NULL);
949 free_http_response(rsp);
950 return cgi_error_memory();
953 #ifdef FEATURE_FORCE_LOAD
954 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
955 if (csp->http->ssl != 0)
956 #endif /* ndef FEATURE_FORCE_LOAD */
958 err = map_block_killer(exports, "force-support");
961 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
962 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
963 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
964 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
969 free_http_response(rsp);
970 return cgi_error_memory();
973 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
976 free_http_response(rsp);
977 return cgi_error_memory();
981 return finish_http_response(rsp);
987 /*********************************************************************
989 * Function : trust_url FIXME: I should be called distrust_url
991 * Description : Calls is_untrusted_url to determine if the URL is trusted
992 * and if not, returns a HTTP 403 response with a reject message.
995 * 1 : csp = Current client state (buffers, headers, etc...)
997 * Returns : NULL => trusted, else http_response.
999 *********************************************************************/
1000 struct http_response *trust_url(struct client_state *csp)
1002 struct http_response *rsp;
1003 struct map * exports;
1004 char buf[BUFFER_SIZE];
1006 struct url_spec **tl;
1011 * Don't bother to work on trusted URLs
1013 if (!is_untrusted_url(csp))
1019 * Else, prepare a response:
1021 if (NULL == (rsp = alloc_http_response()))
1023 return cgi_error_memory();
1026 rsp->status = strdup("403 Request blocked by Privoxy");
1027 exports = default_exports(csp, NULL);
1028 if (exports == NULL || rsp->status == NULL)
1030 free_http_response(rsp);
1031 return cgi_error_memory();
1035 * Export the protocol, host, port, and referrer information
1037 err = map(exports, "hostport", 1, csp->http->hostport, 1);
1038 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1039 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1041 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1043 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1047 if (!err) err = map(exports, "referrer", 1, "none set", 1);
1053 free_http_response(rsp);
1054 return cgi_error_memory();
1058 * Export the trust list
1061 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1063 sprintf(buf, "<li>%s</li>\n", t->spec);
1064 string_append(&p, buf);
1066 err = map(exports, "trusted-referrers", 1, p, 0);
1071 free_http_response(rsp);
1072 return cgi_error_memory();
1076 * Export the trust info, if available
1078 if (csp->config->trust_info->first)
1080 struct list_entry *l;
1083 for (l = csp->config->trust_info->first; l ; l = l->next)
1085 sprintf(buf, "<li> <a href=\"%s\">%s</a><br>\n",l->str, l->str);
1086 string_append(&p, buf);
1088 err = map(exports, "trust-info", 1, p, 0);
1092 err = map_block_killer(exports, "have-trust-info");
1098 free_http_response(rsp);
1099 return cgi_error_memory();
1103 * Export the force prefix or the force conditional block killer
1105 #ifdef FEATURE_FORCE_LOAD
1106 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1107 #else /* ifndef FEATURE_FORCE_LOAD */
1108 err = map_block_killer(exports, "force-support");
1109 #endif /* ndef FEATURE_FORCE_LOAD */
1114 free_http_response(rsp);
1115 return cgi_error_memory();
1119 * Build the response
1121 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1124 free_http_response(rsp);
1125 return cgi_error_memory();
1128 return finish_http_response(rsp);
1130 #endif /* def FEATURE_TRUST */
1132 /*********************************************************************
1134 * Function : execute_single_pcrs_command
1136 * Description : Apply single pcrs command to the subject.
1137 * The subject itself is left untouched, memory for the result
1138 * is malloc()ed and it is the caller's responsibility to free
1139 * the result when it's no longer needed.
1142 * 1 : subject = the subject (== original) string
1143 * 2 : pcrs_command = the pcrs command as string (s@foo@bar@)
1144 * 3 : hits = int* for returning the number of modifications
1146 * Returns : NULL in case of errors, otherwise the
1147 * result of the pcrs command.
1149 *********************************************************************/
1150 char *execute_single_pcrs_command(char *subject, const char *pcrs_command, int *hits)
1154 char *result = NULL;
1158 assert(pcrs_command);
1161 size = strlen(subject);
1163 if (NULL == (job = pcrs_compile_command(pcrs_command, &error)))
1165 log_error(LOG_LEVEL_ERROR, "Failed to compile pcrs command \"%s\". Error: %d.",
1166 pcrs_command, error);
1168 else if ((*hits = pcrs_execute(job, subject, size, &result, &size)) < 0)
1170 log_error(LOG_LEVEL_ERROR, "Failed to execute pcrs command: %s", pcrs_strerror(*hits));
1177 job = pcrs_free_job(job);
1184 /*********************************************************************
1186 * Function : rewrite_url
1188 * Description : Rewrites a URL with a single pcrs command
1189 * and returns the result if it differs from the
1190 * original and isn't obviously invalid.
1193 * 1 : old_url = URL to rewrite.
1194 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1197 * Returns : NULL if the pcrs_command didn't change the url, or
1198 * the result of the modification.
1200 *********************************************************************/
1201 char *rewrite_url(char *old_url, const char *pcrs_command)
1203 char *new_url = NULL;
1207 assert(pcrs_command);
1209 new_url = execute_single_pcrs_command(old_url, pcrs_command, &hits);
1213 log_error(LOG_LEVEL_REDIRECTS,
1214 "pcrs command \"%s\" didn't change \"%s\".",
1215 pcrs_command, old_url, new_url);
1218 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1220 log_error(LOG_LEVEL_ERROR,
1221 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1222 "but the result doesn't look like a valid URL and will be ignored.",
1223 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1228 log_error(LOG_LEVEL_REDIRECTS,
1229 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1230 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1238 #ifdef FEATURE_FAST_REDIRECTS
1239 /*********************************************************************
1241 * Function : get_last_url
1243 * Description : Search for the last URL inside a string.
1244 * If the string already is a URL, it will
1245 * be the first URL found.
1248 * 1 : subject = the string to check
1249 * 2 : redirect_mode = +fast-redirect{} mode
1251 * Returns : NULL if no URL was found, or
1252 * the last URL found.
1254 *********************************************************************/
1255 char *get_last_url(char *subject, const char *redirect_mode)
1261 assert(redirect_mode);
1263 subject = strdup(subject);
1265 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1267 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1268 new_url = url_decode(subject);
1273 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects", subject);
1276 * Find the last URL encoded in the request
1279 while ((tmp = strstr(tmp, "http://")) != NULL)
1284 if (new_url != subject || (0 == strncmpic(subject, "http://", 7)))
1287 * Return new URL if we found a redirect
1288 * or if the subject already was a URL.
1290 * The second case makes sure that we can
1291 * chain get_last_url after another redirection check
1292 * (like rewrite_url) without losing earlier redirects.
1294 new_url = strdup(new_url);
1303 #endif /* def FEATURE_FAST_REDIRECTS */
1306 /*********************************************************************
1308 * Function : redirect_url
1310 * Description : Checks if Privoxy should answer the request with
1311 * a HTTP redirect and generates the redirect if
1315 * 1 : csp = Current client state (buffers, headers, etc...)
1317 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1319 *********************************************************************/
1320 struct http_response *redirect_url(struct client_state *csp)
1322 struct http_response *rsp;
1323 #ifdef FEATURE_FAST_REDIRECTS
1325 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1326 * as compile-time option? The user can easily disable
1327 * it in his action file.
1329 char * redirect_mode;
1330 #endif /* def FEATURE_FAST_REDIRECTS */
1331 char *old_url = NULL;
1332 char *new_url = NULL;
1333 char *redirection_string;
1335 if ((csp->action->flags & ACTION_REDIRECT))
1337 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1340 * If the redirection string begins with 's',
1341 * assume it's a pcrs command, otherwise treat it as
1342 * properly formatted URL and use it for the redirection
1345 * According to RFC 2616 section 14.30 the URL
1346 * has to be absolute and if the user tries:
1347 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1348 * she would get undefined results anyway.
1352 if (*redirection_string == 's')
1354 old_url = csp->http->url;
1355 new_url = rewrite_url(old_url, redirection_string);
1359 log_error(LOG_LEVEL_REDIRECTS,
1360 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1361 redirection_string);
1362 new_url = strdup(redirection_string);
1366 #ifdef FEATURE_FAST_REDIRECTS
1367 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1369 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1372 * If it exists, use the previously rewritten URL as input
1373 * otherwise just use the old path.
1375 old_url = new_url ? new_url : strdup(csp->http->path);
1376 new_url = get_last_url(old_url, redirect_mode);
1379 #endif /* def FEATURE_FAST_REDIRECTS */
1381 /* Did any redirect action trigger? */
1384 if (0 == strcmpic(new_url, csp->http->url))
1386 log_error(LOG_LEVEL_ERROR,
1387 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1388 csp->http->url, new_url);
1393 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1395 if (NULL == (rsp = alloc_http_response()))
1398 return cgi_error_memory();
1401 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1402 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1405 free_http_response(rsp);
1406 return cgi_error_memory();
1409 return finish_http_response(rsp);
1413 /* Only reached if no redirect is required */
1419 #ifdef FEATURE_IMAGE_BLOCKING
1420 /*********************************************************************
1422 * Function : is_imageurl
1424 * Description : Given a URL, decide whether it is an image or not,
1425 * using either the info from a previous +image action
1426 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1427 * is MSIE and not on a Mac, tell from the browser's accept
1431 * 1 : csp = Current client state (buffers, headers, etc...)
1433 * Returns : True (nonzero) if URL is an image, false (0)
1436 *********************************************************************/
1437 int is_imageurl(struct client_state *csp)
1439 #ifdef FEATURE_IMAGE_DETECT_MSIE
1442 tmp = get_header_value(csp->headers, "User-Agent:");
1443 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1445 tmp = get_header_value(csp->headers, "Accept:");
1446 if (tmp && strstr(tmp, "image/gif"))
1448 /* Client will accept HTML. If this seems counterintuitive,
1458 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1460 return ((csp->action->flags & ACTION_IMAGE) != 0);
1463 #endif /* def FEATURE_IMAGE_BLOCKING */
1466 #ifdef FEATURE_TRUST
1467 /*********************************************************************
1469 * Function : is_untrusted_url
1471 * Description : Should we "distrust" this URL (and block it)?
1473 * Yes if it matches a line in the trustfile, or if the
1474 * referrer matches a line starting with "+" in the
1479 * 1 : csp = Current client state (buffers, headers, etc...)
1481 * Returns : 0 => trusted, 1 => untrusted
1483 *********************************************************************/
1484 int is_untrusted_url(struct client_state *csp)
1486 struct file_list *fl;
1487 struct block_spec *b;
1488 struct url_spec **trusted_url;
1489 struct http_request rhttp[1];
1490 const char * referer;
1494 * If we don't have a trustlist, we trust everybody
1496 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1501 memset(rhttp, '\0', sizeof(*rhttp));
1504 * Do we trust the request URL itself?
1506 for (b = b->next; b ; b = b->next)
1508 if (url_match(b->url, csp->http))
1514 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1516 /* no referrer was supplied */
1522 * If not, do we maybe trust its referrer?
1524 err = parse_http_url(referer, rhttp, csp);
1530 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1532 if (url_match(*trusted_url, rhttp))
1534 /* if the URL's referrer is from a trusted referrer, then
1535 * add the target spec to the trustfile as an unblocked
1536 * domain and return NULL (which means it's OK).
1541 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1545 char * new_entry = strdup("~");
1547 string_append(&new_entry, csp->http->hostport);
1549 path = csp->http->path;
1550 if ( (path[0] == '/')
1552 && ((path_end = strchr(path + 2, '/')) != NULL))
1554 /* since this path points into a user's home space
1555 * be sure to include this spec in the trustfile.
1557 int path_len = path_end - path; /* save offset */
1558 path = strdup(path); /* Copy string */
1561 path_end = path + path_len; /* regenerate ptr to new buffer */
1562 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1564 string_join(&new_entry, path);
1567 if (new_entry != NULL)
1569 fprintf(fp, "%s\n", new_entry);
1574 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1575 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1585 #endif /* def FEATURE_TRUST */
1588 /*********************************************************************
1590 * Function : pcrs_filter_response
1592 * Description : Execute all text substitutions from all applying
1593 * +filter actions on the text buffer that's been accumulated
1594 * in csp->iob->buf. If this changes the contents, set
1595 * csp->content_length to the modified size and raise the
1596 * CSP_FLAG_MODIFIED flag.
1599 * 1 : csp = Current client state (buffers, headers, etc...)
1601 * Returns : a pointer to the (newly allocated) modified buffer.
1602 * or NULL if there were no hits or something went wrong
1604 *********************************************************************/
1605 char *pcrs_filter_response(struct client_state *csp)
1608 size_t size, prev_size;
1610 char *old = csp->iob->cur, *new = NULL;
1613 struct file_list *fl;
1614 struct re_filterfile_spec *b;
1615 struct list_entry *filtername;
1617 int i, found_filters = 0;
1622 if (csp->iob->cur >= csp->iob->eod)
1626 size = csp->iob->eod - csp->iob->cur;
1629 * Need to check the set of re_filterfiles...
1631 for (i = 0; i < MAX_AF_FILES; i++)
1644 if (0 == found_filters)
1646 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1651 * If the body has a "chunked" transfer-encoding,
1652 * get rid of it first, adjusting size and iob->eod
1654 if (csp->flags & CSP_FLAG_CHUNKED)
1656 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1657 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1661 csp->iob->eod = csp->iob->cur + size;
1662 csp->flags |= CSP_FLAG_MODIFIED;
1665 for (i = 0; i < MAX_AF_FILES; i++)
1668 if ((NULL == fl) || (NULL == fl->f))
1671 * For all applying +filter actions, look if a filter by that
1672 * name exists and if yes, execute it's pcrs_joblist on the
1675 for (b = fl->f; b; b = b->next)
1677 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1678 filtername ; filtername = filtername->next)
1680 if (strcmp(b->name, filtername->str) == 0)
1682 int current_hits = 0;
1684 if ( NULL == b->joblist )
1686 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1691 /* Apply all jobs from the joblist */
1692 for (job = b->joblist; NULL != job; job = job->next)
1694 current_hits += pcrs_execute(job, old, size, &new, &size);
1695 if (old != csp->iob->cur) free(old);
1699 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) with filter %s produced %d hits (new size %d).",
1700 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1702 hits += current_hits;
1709 * If there were no hits, destroy our copy and let
1710 * chat() use the original in csp->iob
1718 csp->flags |= CSP_FLAG_MODIFIED;
1719 csp->content_length = size;
1727 /*********************************************************************
1729 * Function : gif_deanimate_response
1731 * Description : Deanimate the GIF image that has been accumulated in
1732 * csp->iob->buf, set csp->content_length to the modified
1733 * size and raise the CSP_FLAG_MODIFIED flag.
1736 * 1 : csp = Current client state (buffers, headers, etc...)
1738 * Returns : a pointer to the (newly allocated) modified buffer.
1739 * or NULL in case something went wrong.
1741 *********************************************************************/
1742 char *gif_deanimate_response(struct client_state *csp)
1744 struct binbuffer *in, *out;
1746 size_t size = csp->iob->eod - csp->iob->cur;
1749 * If the body has a "chunked" transfer-encoding,
1750 * get rid of it first, adjusting size and iob->eod
1752 if (csp->flags & CSP_FLAG_CHUNKED)
1754 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1755 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1759 csp->iob->eod = csp->iob->cur + size;
1760 csp->flags |= CSP_FLAG_MODIFIED;
1763 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1764 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1766 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1770 in->buffer = csp->iob->cur;
1773 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1775 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1782 if ((int)size == out->offset)
1784 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1788 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1790 csp->content_length = out->offset;
1791 csp->flags |= CSP_FLAG_MODIFIED;
1801 /*********************************************************************
1803 * Function : jpeg_inspect_response
1808 * 1 : csp = Current client state (buffers, headers, etc...)
1810 * Returns : a pointer to the (newly allocated) modified buffer
1811 * or NULL in case something went wrong.
1813 *********************************************************************/
1814 char *jpeg_inspect_response(struct client_state *csp)
1816 struct binbuffer *in = NULL, *out = NULL;
1818 size_t size = csp->iob->eod - csp->iob->cur;
1821 * If the body has a "chunked" transfer-encoding,
1822 * get rid of it first, adjusting size and iob->eod
1824 if (csp->flags & CSP_FLAG_CHUNKED)
1826 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1827 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1831 csp->iob->eod = csp->iob->cur + size;
1832 csp->flags |= CSP_FLAG_MODIFIED;
1835 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1837 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
1841 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
1843 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
1847 in->buffer = csp->iob->cur;
1851 * Calling jpeg_inspect has the side-effect of creating and
1852 * modifying the image buffer of "out" directly.
1854 if (jpeg_inspect(in, out))
1856 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
1864 csp->content_length = out->offset;
1865 csp->flags |= CSP_FLAG_MODIFIED;
1875 /*********************************************************************
1877 * Function : remove_chunked_transfer_coding
1879 * Description : In-situ remove the "chunked" transfer coding as defined
1880 * in rfc2616 from a buffer.
1883 * 1 : buffer = Pointer to the text buffer
1884 * 2 : size = Number of bytes to be processed
1886 * Returns : The new size, i.e. the number of bytes from buffer which
1887 * are occupied by the stripped body, or 0 in case something
1890 *********************************************************************/
1891 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1894 unsigned int chunksize = 0;
1895 char *from_p, *to_p;
1898 from_p = to_p = buffer;
1900 if (sscanf(buffer, "%x", &chunksize) != 1)
1902 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1906 while (chunksize > 0)
1908 if (NULL == (from_p = strstr(from_p, "\r\n")))
1910 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1914 if ((newsize += chunksize) >= size)
1916 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
1921 memmove(to_p, from_p, (size_t) chunksize);
1922 to_p = buffer + newsize;
1923 from_p += chunksize + 2;
1925 if (sscanf(from_p, "%x", &chunksize) != 1)
1927 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1932 /* FIXME: Should this get its own loglevel? */
1933 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1939 /*********************************************************************
1941 * Function : url_actions
1943 * Description : Gets the actions for this URL.
1946 * 1 : http = http_request request for blocked URLs
1947 * 2 : csp = Current client state (buffers, headers, etc...)
1951 *********************************************************************/
1952 void url_actions(struct http_request *http,
1953 struct client_state *csp)
1955 struct file_list *fl;
1956 struct url_actions *b;
1959 init_current_action(csp->action);
1961 for (i = 0; i < MAX_AF_FILES; i++)
1963 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
1968 apply_url_actions(csp->action, http, b);
1975 /*********************************************************************
1977 * Function : apply_url_actions
1979 * Description : Applies a list of URL actions.
1982 * 1 : action = Destination.
1983 * 2 : http = Current URL
1984 * 3 : b = list of URL actions to apply
1988 *********************************************************************/
1989 void apply_url_actions(struct current_action_spec *action,
1990 struct http_request *http,
1991 struct url_actions *b)
1995 /* Should never happen */
1999 for (b = b->next; NULL != b; b = b->next)
2001 if (url_match(b->url, http))
2003 merge_current_action(action, b->action);
2009 /*********************************************************************
2011 * Function : forward_url
2013 * Description : Should we forward this to another proxy?
2016 * 1 : http = http_request request for current URL
2017 * 2 : csp = Current client state (buffers, headers, etc...)
2019 * Returns : Pointer to forwarding information.
2021 *********************************************************************/
2022 const struct forward_spec * forward_url(struct http_request *http,
2023 struct client_state *csp)
2025 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2026 struct forward_spec *fwd = csp->config->forward;
2035 if (url_match(fwd->url, http))
2046 /*********************************************************************
2048 * Function : direct_response
2050 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2051 * request and if so, return a HTTP 501 to the client.
2053 * FIXME: I have a stupid name and I should handle the
2054 * requests properly. Still, what we do here is rfc-
2055 * compliant, whereas ignoring or forwarding are not.
2058 * 1 : csp = Current client state (buffers, headers, etc...)
2060 * Returns : http_response if , NULL if nonmatch or handler fail
2062 *********************************************************************/
2063 struct http_response *direct_response(struct client_state *csp)
2065 struct http_response *rsp;
2066 struct list_entry *p;
2068 if ((0 == strcmpic(csp->http->gpc, "trace"))
2069 || (0 == strcmpic(csp->http->gpc, "options")))
2071 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2073 if (!strncmp("Max-Forwards:", p->str, 13)
2074 && (*(p->str+13) != '\0') && (atoi(p->str+13) == 0))
2076 /* FIXME: We could handle at least TRACE here,
2077 but that would require a verbatim copy of
2078 the request which we don't have anymore */
2080 log_error(LOG_LEVEL_HEADER, "Found Max-Forwards:0 in OPTIONS or TRACE request -- Returning 501");
2082 /* Get mem for response or fail*/
2083 if (NULL == (rsp = alloc_http_response()))
2085 return cgi_error_memory();
2088 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2090 free_http_response(rsp);
2091 return cgi_error_memory();
2095 return(finish_http_response(rsp));