1 const char filters_rcs[] = "$Id: filters.c,v 1.66 2006/09/23 13:26:38 roro 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.66 2006/09/23 13:26:38 roro
44 * Replace TABs by spaces in source code.
46 * Revision 1.65 2006/09/21 12:54:43 fabiankeil
47 * Fix +redirect{}. Didn't work with -fast-redirects.
49 * Revision 1.64 2006/08/31 10:55:49 fabiankeil
50 * Block requests for untrusted URLs with status
51 * code 403 instead of 200.
53 * Revision 1.63 2006/08/31 10:11:28 fabiankeil
54 * Don't free p which is still in use and will be later
55 * freed by free_map(). Don't claim the referrer is unknown
56 * when the client didn't set one.
58 * Revision 1.62 2006/08/14 00:27:47 david__schmidt
59 * Feature request 595948: Re-Filter logging in single line
61 * Revision 1.61 2006/08/03 02:46:41 david__schmidt
62 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
64 * Revision 1.60 2006/07/18 14:48:46 david__schmidt
65 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
66 * with what was really the latest development (the v_3_0_branch branch)
68 * Revision 1.58.2.9 2006/01/29 23:10:56 david__schmidt
69 * Multiple filter file support
71 * Revision 1.58.2.8 2005/05/07 21:50:55 david__schmidt
72 * A few memory leaks plugged (mostly on error paths)
74 * Revision 1.58.2.7 2004/10/03 12:53:32 david__schmidt
75 * Add the ability to check jpeg images for invalid
76 * lengths of comment blocks. Defensive strategy
77 * against the exploit:
78 * Microsoft Security Bulletin MS04-028
79 * Buffer Overrun in JPEG Processing (GDI+) Could
80 * Allow Code Execution (833987)
81 * Enabled with +inspect-jpegs in actions files.
83 * Revision 1.58.2.6 2003/12/06 22:18:27 gliptak
84 * Correcting compile problem with FEATURE_IMAGE_BLOCKING
86 * Revision 1.58.2.5 2003/11/11 13:10:31 oes
87 * Fixed bug #839859: "See why" link URL now gets url-encoded.
89 * Revision 1.58.2.4 2003/02/28 12:52:45 oes
92 * Revision 1.58.2.3 2002/09/25 14:51:51 oes
93 * Added basic support for OPTIONS and TRACE HTTP methods:
94 * New function direct_response which handles OPTIONS and
95 * TRACE requests whose Max-Forwards header field is zero.
97 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
98 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
100 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
101 * - Bugfix: Executing a filters without jobs no longer results in
102 * turing off *all* filters.
103 * - Security fix: Malicious web servers can't cause a seg fault
104 * through bogus chunk sizes anymore
106 * Revision 1.58 2002/04/24 02:11:17 oes
107 * Jon's multiple AF patch: url_actions now evaluates rules
110 * Revision 1.57 2002/04/08 20:38:34 swa
113 * Revision 1.56 2002/04/05 15:51:24 oes
114 * - bugfix: error-pages now get correct request protocol
115 * - fix for invalid HTML in trust info
117 * Revision 1.55 2002/04/02 16:13:51 oes
118 * Fix: No "Go there anyway" for SSL
120 * Revision 1.54 2002/04/02 14:55:56 oes
121 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
123 * Revision 1.53 2002/03/26 22:29:54 swa
124 * we have a new homepage!
126 * Revision 1.52 2002/03/24 16:35:57 jongfoster
129 * Revision 1.51 2002/03/24 15:23:33 jongfoster
132 * Revision 1.50 2002/03/24 13:25:43 swa
133 * name change related issues
135 * Revision 1.49 2002/03/16 20:29:14 oes
138 * Revision 1.48 2002/03/13 20:25:34 oes
139 * Better logging for content filters
141 * Revision 1.47 2002/03/13 00:30:52 jongfoster
143 * Added option of always sending redirect for imageblock,
144 * currently disabled with #if 0.
146 * Revision 1.46 2002/03/12 01:42:49 oes
147 * Introduced modular filters
149 * Revision 1.45 2002/03/08 16:47:50 oes
150 * Added choice beween GIF and PNG built-in images
152 * Revision 1.44 2002/03/07 03:49:31 oes
153 * - Fixed compiler warnings etc
154 * - Changed built-in images from GIF to PNG
155 * (with regard to Unisys patent issue)
156 * - Added a 4x4 pattern PNG which is less intrusive
157 * than the logo but also clearly marks the deleted banners
159 * Revision 1.43 2002/01/22 23:51:59 jongfoster
160 * Replacing strsav() with the safer string_append().
162 * Adding missing html_encode() to error message generators. Where encoded
163 * and unencoded versions of a string were provided, removing the unencoded
166 * Revision 1.42 2002/01/17 21:00:32 jongfoster
167 * Moving all our URL and URL pattern parsing code to urlmatch.c.
169 * Using a single, simple url_match(pattern,url) function - rather than
170 * the 3-line match routine which was repeated all over the place.
172 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
174 * Using parse_http_url() to parse URLs without faking a HTTP
175 * request line for parse_http_request().
177 * Revision 1.41 2001/11/13 00:14:07 jongfoster
178 * Fixing stupid bug now I've figured out what || means.
179 * (It always returns 0 or 1, not one of it's paramaters.)
181 * Revision 1.40 2001/10/26 17:37:55 oes
182 * - Re-enabled Netscape 200/404 bug workaround in block_url():
183 * - Removed OS/2 special case
184 * - Made block_url() independant from sed() having been run
185 * - Made trust_url independant from sed() having been run
186 * - Made is_imageurl independant from sed() having been run.
187 * It now checks User-Agent: and Accept: by itself.
190 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
191 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
192 * threads to call select() simultaneously. So, it's time to do a real, live,
193 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
194 * (native). Both versions will work, but using __OS2__ offers multi-threading.
196 * Revision 1.38 2001/10/23 21:32:33 jongfoster
197 * Adding error-checking to selected functions
199 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
200 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
201 * filters.c. Added a FIXME in front of the offending code. I'll gladly
202 * put in a better/more robust fix for all parties if one is presented...
203 * It seems that just returning 200 instead of 404 would pretty much fix
204 * it for everyone, but I don't know all the history of the problem.
206 * Revision 1.36 2001/10/10 16:44:16 oes
207 * Added match_portlist function
209 * Revision 1.35 2001/10/07 15:41:23 oes
210 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
212 * New function remove_chunked_transfer_coding that strips chunked
213 * transfer coding to plain and is called by pcrs_filter_response
214 * and gif_deanimate_response if neccessary
216 * Improved handling of zero-change re_filter runs
218 * pcrs_filter_response and gif_deanimate_response now remove
219 * chunked transfer codeing before processing the body.
221 * Revision 1.34 2001/09/20 15:49:36 steudten
223 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
224 * See cgi.c fill_template().
226 * Revision 1.33 2001/09/16 17:05:14 jongfoster
227 * Removing unused #include showarg.h
229 * Revision 1.32 2001/09/16 13:21:27 jongfoster
230 * Changes to use new list functions.
232 * Revision 1.31 2001/09/16 11:38:02 jongfoster
233 * Splitting fill_template() into 2 functions:
234 * template_load() loads the file
235 * template_fill() performs the PCRS regexps.
236 * This is because the CGI edit interface has a "table row"
237 * template which is used many times in the page - this
238 * change means it's only loaded from disk once.
240 * Revision 1.30 2001/09/16 11:00:10 jongfoster
241 * New function alloc_http_response, for symmetry with free_http_response
243 * Revision 1.29 2001/09/13 23:32:40 jongfoster
244 * Moving image data to cgi.c rather than cgi.h
245 * Fixing a GPF under Win32 (and any other OS that protects global
246 * constants from being written to).
248 * Revision 1.28 2001/09/10 10:18:51 oes
249 * Silenced compiler warnings
251 * Revision 1.27 2001/08/05 16:06:20 jongfoster
252 * Modifiying "struct map" so that there are now separate header and
253 * "map_entry" structures. This means that functions which modify a
254 * map no longer need to return a pointer to the modified map.
255 * Also, it no longer reverses the order of the entries (which may be
256 * important with some advanced template substitutions).
258 * Revision 1.26 2001/07/30 22:08:36 jongfoster
259 * Tidying up #defines:
260 * - All feature #defines are now of the form FEATURE_xxx
261 * - Permanently turned off WIN_GUI_EDIT
262 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
264 * Revision 1.25 2001/07/26 10:09:46 oes
265 * Made browser detection a little less naive
267 * Revision 1.24 2001/07/25 17:22:51 oes
268 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
270 * Revision 1.23 2001/07/23 13:40:12 oes
271 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
273 * Revision 1.22 2001/07/18 12:29:34 oes
274 * - Made gif_deanimate_response respect
275 * csp->action->string[ACTION_STRING_DEANIMATE]
276 * - Logging cosmetics
278 * Revision 1.21 2001/07/13 13:59:53 oes
279 * - Introduced gif_deanimate_response which shares the
280 * generic content modification interface of pcrs_filter_response
281 * and acts as a wrapper to deanimate.c:gif_deanimate()
282 * - Renamed re_process_buffer to pcrs_filter_response
283 * - pcrs_filter_response now returns NULL on failiure
284 * - Removed all #ifdef PCRS
286 * Revision 1.20 2001/07/01 17:01:04 oes
287 * Added comments and missing return statement in is_untrusted_url()
289 * Revision 1.19 2001/06/29 21:45:41 oes
290 * Indentation, CRLF->LF, Tab-> Space
292 * Revision 1.18 2001/06/29 13:27:38 oes
293 * - Cleaned up, renamed and reorderd functions
294 * and improved comments
297 * - Ported to CGI platform. Now delivers
298 * http_response or NULL
299 * - Unified HTML and GIF generation (moved image detection
300 * and GIF generation here from jcc.c:chat())
301 * - Fixed HTTP status to:
302 * - 403 (Forbidden) for the "blocked" HTML message
303 * - 200 (OK) for GIF answers
304 * - 302 (Redirect) for redirect to GIF
307 * - Ported to CGI platform. Now delivers
308 * http_response or NULL
309 * - Separated detection of untrusted URL into
310 * (bool)is_untrusted_url
311 * - Added enforcement of untrusted requests
313 * - Moved redirect_url() from cgi.c to here
314 * and ported it to the CGI platform
316 * - Removed logentry from cancelled commit
318 * Revision 1.17 2001/06/09 10:55:28 jongfoster
319 * Changing BUFSIZ ==> BUFFER_SIZE
321 * Revision 1.16 2001/06/07 23:10:26 jongfoster
322 * Allowing unanchored domain patterns to back off and retry
323 * if they partially match. Optimized right-anchored patterns.
324 * Moving ACL and forward files into config file.
325 * Replacing struct gateway with struct forward_spec
327 * Revision 1.15 2001/06/03 19:12:00 oes
328 * extracted-CGI relevant stuff
330 * Revision 1.14 2001/06/01 10:30:55 oes
331 * Added optional left-anchoring to domaincmp
333 * Revision 1.13 2001/05/31 21:21:30 jongfoster
334 * Permissionsfile / actions file changes:
335 * - Changed "permission" to "action" throughout
336 * - changes to file format to allow string parameters
337 * - Moved helper functions to actions.c
339 * Revision 1.12 2001/05/31 17:35:20 oes
341 * - Enhanced domain part globbing with infix and prefix asterisk
342 * matching and optional unanchored operation
344 * Revision 1.11 2001/05/29 11:53:23 oes
345 * "See why" link added to "blocked" page
347 * Revision 1.10 2001/05/29 09:50:24 jongfoster
348 * Unified blocklist/imagelist/permissionslist.
349 * File format is still under discussion, but the internal changes
352 * Also modified interceptor behaviour:
353 * - We now intercept all URLs beginning with one of the following
354 * prefixes (and *only* these prefixes):
356 * * http://ijbswa.sf.net/config/
357 * * http://ijbswa.sourceforge.net/config/
358 * - New interceptors "home page" - go to http://i.j.b/ to see it.
359 * - Internal changes so that intercepted and fast redirect pages
360 * are not replaced with an image.
361 * - Interceptors now have the option to send a binary page direct
362 * to the client. (i.e. ijb-send-banner uses this)
363 * - Implemented show-url-info interceptor. (Which is why I needed
364 * the above interceptors changes - a typical URL is
365 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
366 * The previous mechanism would not have intercepted that, and
367 * if it had been intercepted then it then it would have replaced
370 * Revision 1.9 2001/05/27 22:17:04 oes
372 * - re_process_buffer no longer writes the modified buffer
373 * to the client, which was very ugly. It now returns the
374 * buffer, which it is then written by chat.
376 * - content_length now adjusts the Content-Length: header
377 * for modified documents rather than crunch()ing it.
378 * (Length info in csp->content_length, which is 0 for
379 * unmodified documents)
381 * - For this to work, sed() is called twice when filtering.
383 * Revision 1.8 2001/05/26 17:13:28 jongfoster
384 * Filled in a function comment.
386 * Revision 1.7 2001/05/26 15:26:15 jongfoster
387 * ACL feature now provides more security by immediately dropping
388 * connections from untrusted hosts.
390 * Revision 1.6 2001/05/26 00:28:36 jongfoster
391 * Automatic reloading of config file.
392 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
393 * Most of the global variables have been moved to a new
394 * struct configuration_spec, accessed through csp->config->globalname
395 * Most of the globals remaining are used by the Win32 GUI.
397 * Revision 1.5 2001/05/25 22:34:30 jongfoster
400 * Revision 1.4 2001/05/22 18:46:04 oes
402 * - Enabled filtering banners by size rather than URL
403 * by adding patterns that replace all standard banner
404 * sizes with the "Junkbuster" gif to the re_filterfile
406 * - Enabled filtering WebBugs by providing a pattern
407 * which kills all 1x1 images
409 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
410 * which is selected by the (nonstandard and therefore
411 * capital) letter 'U' in the option string.
412 * It causes the quantifiers to be ungreedy by default.
413 * Appending a ? turns back to greedy (!).
415 * - Added a new interceptor ijb-send-banner, which
416 * sends back the "Junkbuster" gif. Without imagelist or
417 * MSIE detection support, or if tinygif = 1, or the
418 * URL isn't recognized as an imageurl, a lame HTML
419 * explanation is sent instead.
421 * - Added new feature, which permits blocking remote
422 * script redirects and firing back a local redirect
424 * The feature is conditionally compiled, i.e. it
425 * can be disabled with --disable-fast-redirects,
426 * plus it must be activated by a "fast-redirects"
427 * line in the config file, has its own log level
428 * and of course wants to be displayed by show-proxy-args
429 * Note: Boy, all the #ifdefs in 1001 locations and
430 * all the fumbling with configure.in and acconfig.h
431 * were *way* more work than the feature itself :-(
433 * - Because a generic redirect template was needed for
434 * this, tinygif = 3 now uses the same.
436 * - Moved GIFs, and other static HTTP response templates
441 * - Removed some >400 CRs again (Jon, you really worked
444 * Revision 1.3 2001/05/20 16:44:47 jongfoster
445 * Removing last hardcoded Junkbusters.com URLs.
447 * Revision 1.2 2001/05/20 01:21:20 jongfoster
448 * Version 2.9.4 checkin.
449 * - Merged popupfile and cookiefile, and added control over PCRS
450 * filtering, in new "permissionsfile".
451 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
452 * file error you now get a message box (in the Win32 GUI) rather
453 * than the program exiting with no explanation.
454 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
456 * - Removed tabs from "config"
457 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
458 * - Bumped up version number.
460 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
461 * Initial import of version 2.9.3 source tree
464 *********************************************************************/
470 #include <sys/types.h>
479 #endif /* ndef __OS2__ */
480 #include <netinet/in.h>
482 #include <winsock2.h>
483 #endif /* ndef _WIN32 */
487 #endif /* def __OS2__ */
495 #include "jbsockets.h"
496 #include "miscutil.h"
500 #include "deanimate.h"
501 #include "urlmatch.h"
507 const char filters_h_rcs[] = FILTERS_H_VERSION;
509 /* Fix a problem with Solaris. There should be no effect on other
511 * Solaris's isspace() is a macro which uses it's argument directly
512 * as an array index. Therefore we need to make sure that high-bit
513 * characters generate +ve values, and ideally we also want to make
514 * the argument match the declared parameter type of "int".
516 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
520 /*********************************************************************
522 * Function : block_acl
524 * Description : Block this request?
525 * Decide yes or no based on ACL file.
528 * 1 : dst = The proxy or gateway address this is going to.
529 * Or NULL to check all possible targets.
530 * 2 : csp = Current client state (buffers, headers, etc...)
531 * Also includes the client IP address.
533 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
535 *********************************************************************/
536 int block_acl(struct access_control_addr *dst, struct client_state *csp)
538 struct access_control_list *acl = csp->config->acl;
540 /* if not using an access control list, then permit the connection */
546 /* search the list */
549 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
553 /* Just want to check if they have any access */
554 if (acl->action == ACL_PERMIT)
559 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
560 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
562 if (acl->action == ACL_PERMIT)
580 /*********************************************************************
582 * Function : acl_addr
584 * Description : Called from `load_config' to parse an ACL address.
587 * 1 : aspec = String specifying ACL address.
588 * 2 : aca = struct access_control_addr to fill in.
590 * Returns : 0 => Ok, everything else is an error.
592 *********************************************************************/
593 int acl_addr(char *aspec, struct access_control_addr *aca)
595 int i, masklength, port;
601 if ((p = strchr(aspec, '/')) != NULL)
605 if (ijb_isdigit(*p) == 0)
609 masklength = atoi(p);
612 if ((masklength < 0) || (masklength > 32))
617 if ((p = strchr(aspec, ':')) != NULL)
621 if (ijb_isdigit(*p) == 0)
630 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
632 if (aca->addr == INADDR_NONE)
637 /* build the netmask */
639 for (i=1; i <= masklength ; i++)
641 aca->mask |= (1 << (32 - i));
644 /* now mask off the host portion of the ip address
645 * (i.e. save on the network portion of the address).
647 aca->addr = aca->addr & aca->mask;
652 #endif /* def FEATURE_ACL */
655 /*********************************************************************
657 * Function : match_portlist
659 * Description : Check if a given number is covered by a comma
660 * separated list of numbers and ranges (a,b-c,d,..)
663 * 1 : portlist = String with list
664 * 2 : port = port to check
666 * Returns : 0 => no match
669 *********************************************************************/
670 int match_portlist(const char *portlist, int port)
672 char *min, *max, *next, *portlist_copy;
674 min = next = portlist_copy = strdup(portlist);
677 * Zero-terminate first item and remember offset for next
679 if (NULL != (next = strchr(portlist_copy, (int) ',')))
685 * Loop through all items, checking for match
689 if (NULL == (max = strchr(min, (int) '-')))
692 * No dash, check for equality
694 if (port == atoi(min))
703 * This is a range, so check if between min and max,
704 * or, if max was omitted, between min and 65K
707 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
721 * Zero-terminate next item and remember offset for n+1
723 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
735 /*********************************************************************
737 * Function : block_url
739 * Description : Called from `chat'. Check to see if we need to block this.
742 * 1 : csp = Current client state (buffers, headers, etc...)
744 * Returns : NULL => unblocked, else HTTP block response
746 *********************************************************************/
747 struct http_response *block_url(struct client_state *csp)
749 struct http_response *rsp;
750 const char *new_content_type = NULL;
753 * If it's not blocked, don't block it ;-)
755 if ((csp->action->flags & ACTION_BLOCK) == 0)
759 if (csp->action->flags & ACTION_REDIRECT)
761 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
764 * Else, prepare a response
766 if (NULL == (rsp = alloc_http_response()))
768 return cgi_error_memory();
772 * If it's an image-url, send back an image or redirect
773 * as specified by the relevant +image action
775 #ifdef FEATURE_IMAGE_BLOCKING
776 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
780 /* determine HOW images should be blocked */
781 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
783 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
785 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
787 #if 1 /* Two alternative strategies, use this one for now: */
789 /* and handle accordingly: */
790 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
792 rsp->status = strdup("403 Request blocked by Privoxy");
793 if (rsp->status == NULL)
795 free_http_response(rsp);
796 return cgi_error_memory();
798 rsp->body = bindup(image_pattern_data, image_pattern_length);
799 if (rsp->body == NULL)
801 free_http_response(rsp);
802 return cgi_error_memory();
804 rsp->content_length = image_pattern_length;
806 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
808 free_http_response(rsp);
809 return cgi_error_memory();
813 else if (0 == strcmpic(p, "blank"))
815 rsp->status = strdup("403 Request blocked by Privoxy");
816 if (rsp->status == NULL)
818 free_http_response(rsp);
819 return cgi_error_memory();
821 rsp->body = bindup(image_blank_data, image_blank_length);
822 if (rsp->body == NULL)
824 free_http_response(rsp);
825 return cgi_error_memory();
827 rsp->content_length = image_blank_length;
829 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
831 free_http_response(rsp);
832 return cgi_error_memory();
838 rsp->status = strdup("302 Local Redirect from Privoxy");
839 if (rsp->status == NULL)
841 free_http_response(rsp);
842 return cgi_error_memory();
845 if (enlist_unique_header(rsp->headers, "Location", p))
847 free_http_response(rsp);
848 return cgi_error_memory();
852 #else /* Following code is disabled for now */
854 /* and handle accordingly: */
855 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
857 p = CGI_PREFIX "send-banner?type=pattern";
859 else if (0 == strcmpic(p, "blank"))
861 p = CGI_PREFIX "send-banner?type=blank";
863 rsp->status = strdup("302 Local Redirect from Privoxy");
864 if (rsp->status == NULL)
866 free_http_response(rsp);
867 return cgi_error_memory();
870 if (enlist_unique_header(rsp->headers, "Location", p))
872 free_http_response(rsp);
873 return cgi_error_memory();
875 #endif /* Preceeding code is disabled for now */
877 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
880 * Send empty document.
882 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
885 rsp->body = strdup(" ");
886 rsp->content_length = 1;
888 rsp->status = strdup("403 Request blocked by Privoxy");
889 if (rsp->status == NULL)
891 free_http_response(rsp);
892 return cgi_error_memory();
894 if (new_content_type != 0)
896 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
897 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
899 free_http_response(rsp);
900 return cgi_error_memory();
906 #endif /* def FEATURE_IMAGE_BLOCKING */
909 * Else, generate an HTML "blocked" message:
913 struct map * exports;
917 * Workaround for stupid Netscape bug which prevents
918 * pages from being displayed if loading a referenced
919 * JavaScript or style sheet fails. So make it appear
920 * as if it succeeded.
922 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
923 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
924 && !strstr(p, "Gecko") /* save Mozilla, */
925 && !strstr(p, "compatible") /* MSIE */
926 && !strstr(p, "Opera")) /* and Opera. */
928 rsp->status = strdup("200 Request for blocked URL");
932 rsp->status = strdup("404 Request for blocked URL");
935 if (rsp->status == NULL)
937 free_http_response(rsp);
938 return cgi_error_memory();
941 exports = default_exports(csp, NULL);
944 free_http_response(rsp);
945 return cgi_error_memory();
948 #ifdef FEATURE_FORCE_LOAD
949 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
950 if (csp->http->ssl != 0)
951 #endif /* ndef FEATURE_FORCE_LOAD */
953 err = map_block_killer(exports, "force-support");
956 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
957 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
958 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
959 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
964 free_http_response(rsp);
965 return cgi_error_memory();
968 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
971 free_http_response(rsp);
972 return cgi_error_memory();
976 return finish_http_response(rsp);
982 /*********************************************************************
984 * Function : trust_url FIXME: I should be called distrust_url
986 * Description : Calls is_untrusted_url to determine if the URL is trusted
987 * and if not, returns a HTTP 403 response with a reject message.
990 * 1 : csp = Current client state (buffers, headers, etc...)
992 * Returns : NULL => trusted, else http_response.
994 *********************************************************************/
995 struct http_response *trust_url(struct client_state *csp)
997 struct http_response *rsp;
998 struct map * exports;
999 char buf[BUFFER_SIZE];
1001 struct url_spec **tl;
1006 * Don't bother to work on trusted URLs
1008 if (!is_untrusted_url(csp))
1014 * Else, prepare a response:
1016 if (NULL == (rsp = alloc_http_response()))
1018 return cgi_error_memory();
1021 rsp->status = strdup("403 Request blocked by Privoxy");
1022 exports = default_exports(csp, NULL);
1023 if (exports == NULL || rsp->status == NULL)
1025 free_http_response(rsp);
1026 return cgi_error_memory();
1030 * Export the protocol, host, port, and referrer information
1032 err = map(exports, "hostport", 1, csp->http->hostport, 1);
1033 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1034 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
1036 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
1038 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
1042 if (!err) err = map(exports, "referrer", 1, "none set", 1);
1048 free_http_response(rsp);
1049 return cgi_error_memory();
1053 * Export the trust list
1056 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1058 sprintf(buf, "<li>%s</li>\n", t->spec);
1059 string_append(&p, buf);
1061 err = map(exports, "trusted-referrers", 1, p, 0);
1066 free_http_response(rsp);
1067 return cgi_error_memory();
1071 * Export the trust info, if available
1073 if (csp->config->trust_info->first)
1075 struct list_entry *l;
1078 for (l = csp->config->trust_info->first; l ; l = l->next)
1080 sprintf(buf, "<li> <a href=\"%s\">%s</a><br>\n",l->str, l->str);
1081 string_append(&p, buf);
1083 err = map(exports, "trust-info", 1, p, 0);
1087 err = map_block_killer(exports, "have-trust-info");
1093 free_http_response(rsp);
1094 return cgi_error_memory();
1098 * Export the force prefix or the force conditional block killer
1100 #ifdef FEATURE_FORCE_LOAD
1101 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1102 #else /* ifndef FEATURE_FORCE_LOAD */
1103 err = map_block_killer(exports, "force-support");
1104 #endif /* ndef FEATURE_FORCE_LOAD */
1109 free_http_response(rsp);
1110 return cgi_error_memory();
1114 * Build the response
1116 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1119 free_http_response(rsp);
1120 return cgi_error_memory();
1123 return finish_http_response(rsp);
1125 #endif /* def FEATURE_TRUST */
1127 /*********************************************************************
1129 * Function : execute_single_pcrs_command
1131 * Description : Apply single pcrs command to the subject.
1132 * The subject itself is left untouched, memory for the result
1133 * is malloc()ed and it is the caller's responsibility to free
1134 * the result when it's no longer needed.
1137 * 1 : subject = the subject (== original) string
1138 * 2 : pcrs_command = the pcrs command as string (s@foo@bar@)
1139 * 3 : hits = int* for returning the number of modifications
1141 * Returns : NULL in case of errors, otherwise the
1142 * result of the pcrs command.
1144 *********************************************************************/
1145 char *execute_single_pcrs_command(char *subject, const char *pcrs_command, int *hits)
1149 char *result = NULL;
1153 assert(pcrs_command);
1156 size = strlen(subject);
1158 if (NULL == (job = pcrs_compile_command(pcrs_command, &error)))
1160 log_error(LOG_LEVEL_ERROR, "Failed to compile pcrs command \"%s\". Error: %d.",
1161 pcrs_command, error);
1163 else if ((*hits = pcrs_execute(job, subject, size, &result, &size)) < 0)
1165 log_error(LOG_LEVEL_ERROR, "Failed to execute pcrs command: %s", pcrs_strerror(*hits));
1172 job = pcrs_free_job(job);
1179 /*********************************************************************
1181 * Function : rewrite_url
1183 * Description : Rewrites a URL with a single pcrs command
1184 * and returns the result if it differs from the
1185 * original and isn't obviously invalid.
1188 * 1 : old_url = URL to rewrite.
1189 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1192 * Returns : NULL if the pcrs_command didn't change the url, or
1193 * the result of the modification.
1195 *********************************************************************/
1196 char *rewrite_url(char *old_url, const char *pcrs_command)
1198 char *new_url = NULL;
1202 assert(pcrs_command);
1204 new_url = execute_single_pcrs_command(old_url, pcrs_command, &hits);
1208 log_error(LOG_LEVEL_REDIRECTS,
1209 "pcrs command \"%s\" didn't change \"%s\".",
1210 pcrs_command, old_url, new_url);
1213 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1215 log_error(LOG_LEVEL_ERROR,
1216 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1217 "but the result doesn't look like a valid URL and will be ignored.",
1218 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1223 log_error(LOG_LEVEL_REDIRECTS,
1224 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1225 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1233 #ifdef FEATURE_FAST_REDIRECTS
1234 /*********************************************************************
1236 * Function : get_last_url
1238 * Description : Search for the last URL inside a string.
1239 * If the string already is a URL, it will
1240 * be the first URL found.
1243 * 1 : subject = the string to check
1244 * 2 : redirect_mode = +fast-redirect{} mode
1246 * Returns : NULL if no URL was found, or
1247 * the last URL found.
1249 *********************************************************************/
1250 char *get_last_url(char *subject, const char *redirect_mode)
1256 assert(redirect_mode);
1258 subject = strdup(subject);
1260 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1262 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1263 new_url = url_decode(subject);
1268 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects", subject);
1271 * Find the last URL encoded in the request
1274 while ((tmp = strstr(tmp, "http://")) != NULL)
1279 if (new_url != subject)
1281 new_url = strdup(new_url);
1290 #endif /* def FEATURE_FAST_REDIRECTS */
1293 /*********************************************************************
1295 * Function : redirect_url
1297 * Description : Checks if Privoxy should answer the request with
1298 * a HTTP redirect and generates the redirect if
1302 * 1 : csp = Current client state (buffers, headers, etc...)
1304 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1306 *********************************************************************/
1307 struct http_response *redirect_url(struct client_state *csp)
1309 struct http_response *rsp;
1310 #ifdef FEATURE_FAST_REDIRECTS
1312 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1313 * as compile-time option? The user can easily disable
1314 * it in his action file.
1316 char * redirect_mode;
1317 #endif /* def FEATURE_FAST_REDIRECTS */
1318 char *old_url = NULL;
1319 char *new_url = NULL;
1320 char *redirection_string;
1322 if ((csp->action->flags & ACTION_REDIRECT))
1324 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1327 * If the redirection string begins with 's',
1328 * assume it's a pcrs command, otherwise treat it as
1329 * properly formatted URL and use it for the redirection
1332 * According to RFC 2616 section 14.30 the URL
1333 * has to be absolute and if the user tries:
1334 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1335 * she would get undefined results anyway.
1339 if (*redirection_string == 's')
1341 old_url = csp->http->url;
1342 new_url = rewrite_url(old_url, redirection_string);
1346 log_error(LOG_LEVEL_REDIRECTS,
1347 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1348 redirection_string);
1349 new_url = strdup(redirection_string);
1353 #ifdef FEATURE_FAST_REDIRECTS
1354 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1356 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1359 * If it exists, use the previously rewritten URL as input
1360 * otherwise just use the old path.
1362 old_url = new_url ? new_url : strdup(csp->http->path);
1363 new_url = get_last_url(old_url, redirect_mode);
1366 #endif /* def FEATURE_FAST_REDIRECTS */
1368 /* Did any redirect action trigger? */
1371 if (0 == strcmpic(new_url, csp->http->url))
1373 log_error(LOG_LEVEL_ERROR,
1374 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1375 csp->http->url, new_url);
1380 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1382 if (NULL == (rsp = alloc_http_response()))
1385 return cgi_error_memory();
1388 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1389 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1392 free_http_response(rsp);
1393 return cgi_error_memory();
1396 return finish_http_response(rsp);
1400 /* Only reached if no redirect is required */
1406 #ifdef FEATURE_IMAGE_BLOCKING
1407 /*********************************************************************
1409 * Function : is_imageurl
1411 * Description : Given a URL, decide whether it is an image or not,
1412 * using either the info from a previous +image action
1413 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1414 * is MSIE and not on a Mac, tell from the browser's accept
1418 * 1 : csp = Current client state (buffers, headers, etc...)
1420 * Returns : True (nonzero) if URL is an image, false (0)
1423 *********************************************************************/
1424 int is_imageurl(struct client_state *csp)
1426 #ifdef FEATURE_IMAGE_DETECT_MSIE
1429 tmp = get_header_value(csp->headers, "User-Agent:");
1430 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1432 tmp = get_header_value(csp->headers, "Accept:");
1433 if (tmp && strstr(tmp, "image/gif"))
1435 /* Client will accept HTML. If this seems counterintuitive,
1445 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1447 return ((csp->action->flags & ACTION_IMAGE) != 0);
1450 #endif /* def FEATURE_IMAGE_BLOCKING */
1453 #ifdef FEATURE_TRUST
1454 /*********************************************************************
1456 * Function : is_untrusted_url
1458 * Description : Should we "distrust" this URL (and block it)?
1460 * Yes if it matches a line in the trustfile, or if the
1461 * referrer matches a line starting with "+" in the
1466 * 1 : csp = Current client state (buffers, headers, etc...)
1468 * Returns : 0 => trusted, 1 => untrusted
1470 *********************************************************************/
1471 int is_untrusted_url(struct client_state *csp)
1473 struct file_list *fl;
1474 struct block_spec *b;
1475 struct url_spec **trusted_url;
1476 struct http_request rhttp[1];
1477 const char * referer;
1481 * If we don't have a trustlist, we trust everybody
1483 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1488 memset(rhttp, '\0', sizeof(*rhttp));
1491 * Do we trust the request URL itself?
1493 for (b = b->next; b ; b = b->next)
1495 if (url_match(b->url, csp->http))
1501 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1503 /* no referrer was supplied */
1509 * If not, do we maybe trust its referrer?
1511 err = parse_http_url(referer, rhttp, csp);
1517 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1519 if (url_match(*trusted_url, rhttp))
1521 /* if the URL's referrer is from a trusted referrer, then
1522 * add the target spec to the trustfile as an unblocked
1523 * domain and return NULL (which means it's OK).
1528 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1532 char * new_entry = strdup("~");
1534 string_append(&new_entry, csp->http->hostport);
1536 path = csp->http->path;
1537 if ( (path[0] == '/')
1539 && ((path_end = strchr(path + 2, '/')) != NULL))
1541 /* since this path points into a user's home space
1542 * be sure to include this spec in the trustfile.
1544 int path_len = path_end - path; /* save offset */
1545 path = strdup(path); /* Copy string */
1548 path_end = path + path_len; /* regenerate ptr to new buffer */
1549 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1551 string_join(&new_entry, path);
1554 if (new_entry != NULL)
1556 fprintf(fp, "%s\n", new_entry);
1561 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1562 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1572 #endif /* def FEATURE_TRUST */
1575 /*********************************************************************
1577 * Function : pcrs_filter_response
1579 * Description : Execute all text substitutions from all applying
1580 * +filter actions on the text buffer that's been accumulated
1581 * in csp->iob->buf. If this changes the contents, set
1582 * csp->content_length to the modified size and raise the
1583 * CSP_FLAG_MODIFIED flag.
1586 * 1 : csp = Current client state (buffers, headers, etc...)
1588 * Returns : a pointer to the (newly allocated) modified buffer.
1589 * or NULL if there were no hits or something went wrong
1591 *********************************************************************/
1592 char *pcrs_filter_response(struct client_state *csp)
1595 size_t size, prev_size;
1597 char *old = csp->iob->cur, *new = NULL;
1600 struct file_list *fl;
1601 struct re_filterfile_spec *b;
1602 struct list_entry *filtername;
1604 int i, found_filters = 0;
1609 if (csp->iob->cur >= csp->iob->eod)
1613 size = csp->iob->eod - csp->iob->cur;
1616 * Need to check the set of re_filterfiles...
1618 for (i = 0; i < MAX_AF_FILES; i++)
1631 if (0 == found_filters)
1633 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1638 * If the body has a "chunked" transfer-encoding,
1639 * get rid of it first, adjusting size and iob->eod
1641 if (csp->flags & CSP_FLAG_CHUNKED)
1643 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1644 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1648 csp->iob->eod = csp->iob->cur + size;
1649 csp->flags |= CSP_FLAG_MODIFIED;
1652 for (i = 0; i < MAX_AF_FILES; i++)
1655 if ((NULL == fl) || (NULL == fl->f))
1658 * For all applying +filter actions, look if a filter by that
1659 * name exists and if yes, execute it's pcrs_joblist on the
1662 for (b = fl->f; b; b = b->next)
1664 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1665 filtername ; filtername = filtername->next)
1667 if (strcmp(b->name, filtername->str) == 0)
1669 int current_hits = 0;
1671 if ( NULL == b->joblist )
1673 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1678 /* Apply all jobs from the joblist */
1679 for (job = b->joblist; NULL != job; job = job->next)
1681 current_hits += pcrs_execute(job, old, size, &new, &size);
1682 if (old != csp->iob->cur) free(old);
1686 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) with filter %s produced %d hits (new size %d).",
1687 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1689 hits += current_hits;
1696 * If there were no hits, destroy our copy and let
1697 * chat() use the original in csp->iob
1705 csp->flags |= CSP_FLAG_MODIFIED;
1706 csp->content_length = size;
1714 /*********************************************************************
1716 * Function : gif_deanimate_response
1718 * Description : Deanimate the GIF image that has been accumulated in
1719 * csp->iob->buf, set csp->content_length to the modified
1720 * size and raise the CSP_FLAG_MODIFIED flag.
1723 * 1 : csp = Current client state (buffers, headers, etc...)
1725 * Returns : a pointer to the (newly allocated) modified buffer.
1726 * or NULL in case something went wrong.
1728 *********************************************************************/
1729 char *gif_deanimate_response(struct client_state *csp)
1731 struct binbuffer *in, *out;
1733 size_t size = csp->iob->eod - csp->iob->cur;
1736 * If the body has a "chunked" transfer-encoding,
1737 * get rid of it first, adjusting size and iob->eod
1739 if (csp->flags & CSP_FLAG_CHUNKED)
1741 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1742 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1746 csp->iob->eod = csp->iob->cur + size;
1747 csp->flags |= CSP_FLAG_MODIFIED;
1750 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1751 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1753 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1757 in->buffer = csp->iob->cur;
1760 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1762 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1769 if ((int)size == out->offset)
1771 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1775 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1777 csp->content_length = out->offset;
1778 csp->flags |= CSP_FLAG_MODIFIED;
1788 /*********************************************************************
1790 * Function : jpeg_inspect_response
1795 * 1 : csp = Current client state (buffers, headers, etc...)
1797 * Returns : a pointer to the (newly allocated) modified buffer
1798 * or NULL in case something went wrong.
1800 *********************************************************************/
1801 char *jpeg_inspect_response(struct client_state *csp)
1803 struct binbuffer *in = NULL, *out = NULL;
1805 size_t size = csp->iob->eod - csp->iob->cur;
1808 * If the body has a "chunked" transfer-encoding,
1809 * get rid of it first, adjusting size and iob->eod
1811 if (csp->flags & CSP_FLAG_CHUNKED)
1813 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1814 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1818 csp->iob->eod = csp->iob->cur + size;
1819 csp->flags |= CSP_FLAG_MODIFIED;
1822 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1824 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
1828 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
1830 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
1834 in->buffer = csp->iob->cur;
1838 * Calling jpeg_inspect has the side-effect of creating and
1839 * modifying the image buffer of "out" directly.
1841 if (jpeg_inspect(in, out))
1843 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
1851 csp->content_length = out->offset;
1852 csp->flags |= CSP_FLAG_MODIFIED;
1862 /*********************************************************************
1864 * Function : remove_chunked_transfer_coding
1866 * Description : In-situ remove the "chunked" transfer coding as defined
1867 * in rfc2616 from a buffer.
1870 * 1 : buffer = Pointer to the text buffer
1871 * 2 : size = Number of bytes to be processed
1873 * Returns : The new size, i.e. the number of bytes from buffer which
1874 * are occupied by the stripped body, or 0 in case something
1877 *********************************************************************/
1878 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1881 unsigned int chunksize = 0;
1882 char *from_p, *to_p;
1885 from_p = to_p = buffer;
1887 if (sscanf(buffer, "%x", &chunksize) != 1)
1889 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1893 while (chunksize > 0)
1895 if (NULL == (from_p = strstr(from_p, "\r\n")))
1897 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1901 if ((newsize += chunksize) >= size)
1903 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
1908 memmove(to_p, from_p, (size_t) chunksize);
1909 to_p = buffer + newsize;
1910 from_p += chunksize + 2;
1912 if (sscanf(from_p, "%x", &chunksize) != 1)
1914 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1919 /* FIXME: Should this get its own loglevel? */
1920 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1926 /*********************************************************************
1928 * Function : url_actions
1930 * Description : Gets the actions for this URL.
1933 * 1 : http = http_request request for blocked URLs
1934 * 2 : csp = Current client state (buffers, headers, etc...)
1938 *********************************************************************/
1939 void url_actions(struct http_request *http,
1940 struct client_state *csp)
1942 struct file_list *fl;
1943 struct url_actions *b;
1946 init_current_action(csp->action);
1948 for (i = 0; i < MAX_AF_FILES; i++)
1950 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
1955 apply_url_actions(csp->action, http, b);
1962 /*********************************************************************
1964 * Function : apply_url_actions
1966 * Description : Applies a list of URL actions.
1969 * 1 : action = Destination.
1970 * 2 : http = Current URL
1971 * 3 : b = list of URL actions to apply
1975 *********************************************************************/
1976 void apply_url_actions(struct current_action_spec *action,
1977 struct http_request *http,
1978 struct url_actions *b)
1982 /* Should never happen */
1986 for (b = b->next; NULL != b; b = b->next)
1988 if (url_match(b->url, http))
1990 merge_current_action(action, b->action);
1996 /*********************************************************************
1998 * Function : forward_url
2000 * Description : Should we forward this to another proxy?
2003 * 1 : http = http_request request for current URL
2004 * 2 : csp = Current client state (buffers, headers, etc...)
2006 * Returns : Pointer to forwarding information.
2008 *********************************************************************/
2009 const struct forward_spec * forward_url(struct http_request *http,
2010 struct client_state *csp)
2012 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2013 struct forward_spec *fwd = csp->config->forward;
2022 if (url_match(fwd->url, http))
2033 /*********************************************************************
2035 * Function : direct_response
2037 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2038 * request and if so, return a HTTP 501 to the client.
2040 * FIXME: I have a stupid name and I should handle the
2041 * requests properly. Still, what we do here is rfc-
2042 * compliant, whereas ignoring or forwarding are not.
2045 * 1 : csp = Current client state (buffers, headers, etc...)
2047 * Returns : http_response if , NULL if nonmatch or handler fail
2049 *********************************************************************/
2050 struct http_response *direct_response(struct client_state *csp)
2052 struct http_response *rsp;
2053 struct list_entry *p;
2055 if ((0 == strcmpic(csp->http->gpc, "trace"))
2056 || (0 == strcmpic(csp->http->gpc, "options")))
2058 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2060 if (!strncmp("Max-Forwards:", p->str, 13)
2061 && (*(p->str+13) != '\0') && (atoi(p->str+13) == 0))
2063 /* FIXME: We could handle at least TRACE here,
2064 but that would require a verbatim copy of
2065 the request which we don't have anymore */
2067 log_error(LOG_LEVEL_HEADER, "Found Max-Forwards:0 in OPTIONS or TRACE request -- Returning 501");
2069 /* Get mem for response or fail*/
2070 if (NULL == (rsp = alloc_http_response()))
2072 return cgi_error_memory();
2075 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2077 free_http_response(rsp);
2078 return cgi_error_memory();
2082 return(finish_http_response(rsp));