1 const char filters_rcs[] = "$Id: filters.c,v 2.6 2003/09/25 02:37:32 david__schmidt Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/src/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'
15 * Copyright : Written by and Copyright (C) 2001, 2004 the SourceForge
16 * Privoxy team. http://www.privoxy.org/
18 * Based on the Internet Junkbuster originally written
19 * by and Copyright (C) 1997 Anonymous Coders and
20 * Junkbusters Corporation. http://www.junkbusters.com
22 * This program is free software; you can redistribute it
23 * and/or modify it under the terms of the GNU General
24 * Public License as published by the Free Software
25 * Foundation; either version 2 of the License, or (at
26 * your option) any later version.
28 * This program is distributed in the hope that it will
29 * be useful, but WITHOUT ANY WARRANTY; without even the
30 * implied warranty of MERCHANTABILITY or FITNESS FOR A
31 * PARTICULAR PURPOSE. See the GNU General Public
32 * License for more details.
34 * The GNU General Public License should be included with
35 * this file. If not, you can view it at
36 * http://www.gnu.org/copyleft/gpl.html
37 * or write to the Free Software Foundation, Inc., 59
38 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
42 * Revision 2.6 2003/09/25 02:37:32 david__schmidt
43 * Feature request 595948: Re-Filter logging in single line
45 * Revision 2.5 2003/09/22 00:33:01 david__schmidt
46 * Enable sending a custom 'blocked' image. Shows up as
47 * "image-blocker-custom-file" parameter in config, and
48 * "+set-image-blocker{custom}" in action files.
50 * Revision 2.4 2003/01/21 02:49:27 david__schmidt
51 * Developer TODO 612294: src: C++ keyword as variable name
52 * I changed all ocurrences of 'new' to 'new_something' wherever I found
53 * one. I also brought up all the source files in MSDEV to see if I could
54 * spot any highlighted keywords that really were variables. Non-scientific,
55 * but at least I tried. :-)
57 * Revision 2.3 2002/12/28 03:58:19 david__schmidt
58 * Initial drop of dashboard instrumentation - enabled with
59 * --enable-activity-console
61 * Revision 2.2 2002/09/04 15:38:24 oes
62 * Synced with the stable branch:
63 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
64 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
66 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
67 * - Bugfix: Executing a filters without jobs no longer results in
68 * turing off *all* filters.
69 * - Security fix: Malicious web servers can't cause a seg fault
70 * through bogus chunk sizes anymore
72 * Revision 2.1 2002/08/26 11:08:18 sarantis
75 * Revision 2.0 2002/06/04 14:34:21 jongfoster
76 * Moving source files to src/
78 * Revision 1.58 2002/04/24 02:11:17 oes
79 * Jon's multiple AF patch: url_actions now evaluates rules
82 * Revision 1.57 2002/04/08 20:38:34 swa
85 * Revision 1.56 2002/04/05 15:51:24 oes
86 * - bugfix: error-pages now get correct request protocol
87 * - fix for invalid HTML in trust info
89 * Revision 1.55 2002/04/02 16:13:51 oes
90 * Fix: No "Go there anyway" for SSL
92 * Revision 1.54 2002/04/02 14:55:56 oes
93 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
95 * Revision 1.53 2002/03/26 22:29:54 swa
96 * we have a new homepage!
98 * Revision 1.52 2002/03/24 16:35:57 jongfoster
101 * Revision 1.51 2002/03/24 15:23:33 jongfoster
104 * Revision 1.50 2002/03/24 13:25:43 swa
105 * name change related issues
107 * Revision 1.49 2002/03/16 20:29:14 oes
110 * Revision 1.48 2002/03/13 20:25:34 oes
111 * Better logging for content filters
113 * Revision 1.47 2002/03/13 00:30:52 jongfoster
115 * Added option of always sending redirect for imageblock,
116 * currently disabled with #if 0.
118 * Revision 1.46 2002/03/12 01:42:49 oes
119 * Introduced modular filters
121 * Revision 1.45 2002/03/08 16:47:50 oes
122 * Added choice beween GIF and PNG built-in images
124 * Revision 1.44 2002/03/07 03:49:31 oes
125 * - Fixed compiler warnings etc
126 * - Changed built-in images from GIF to PNG
127 * (with regard to Unisys patent issue)
128 * - Added a 4x4 pattern PNG which is less intrusive
129 * than the logo but also clearly marks the deleted banners
131 * Revision 1.43 2002/01/22 23:51:59 jongfoster
132 * Replacing strsav() with the safer string_append().
134 * Adding missing html_encode() to error message generators. Where encoded
135 * and unencoded versions of a string were provided, removing the unencoded
138 * Revision 1.42 2002/01/17 21:00:32 jongfoster
139 * Moving all our URL and URL pattern parsing code to urlmatch.c.
141 * Using a single, simple url_match(pattern,url) function - rather than
142 * the 3-line match routine which was repeated all over the place.
144 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
146 * Using parse_http_url() to parse URLs without faking a HTTP
147 * request line for parse_http_request().
149 * Revision 1.41 2001/11/13 00:14:07 jongfoster
150 * Fixing stupid bug now I've figured out what || means.
151 * (It always returns 0 or 1, not one of it's paramaters.)
153 * Revision 1.40 2001/10/26 17:37:55 oes
154 * - Re-enabled Netscape 200/404 bug workaround in block_url():
155 * - Removed OS/2 special case
156 * - Made block_url() independant from sed() having been run
157 * - Made trust_url independant from sed() having been run
158 * - Made is_imageurl independant from sed() having been run.
159 * It now checks User-Agent: and Accept: by itself.
162 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
163 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
164 * threads to call select() simultaneously. So, it's time to do a real, live,
165 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
166 * (native). Both versions will work, but using __OS2__ offers multi-threading.
168 * Revision 1.38 2001/10/23 21:32:33 jongfoster
169 * Adding error-checking to selected functions
171 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
172 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
173 * filters.c. Added a FIXME in front of the offending code. I'll gladly
174 * put in a better/more robust fix for all parties if one is presented...
175 * It seems that just returning 200 instead of 404 would pretty much fix
176 * it for everyone, but I don't know all the history of the problem.
178 * Revision 1.36 2001/10/10 16:44:16 oes
179 * Added match_portlist function
181 * Revision 1.35 2001/10/07 15:41:23 oes
182 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
184 * New function remove_chunked_transfer_coding that strips chunked
185 * transfer coding to plain and is called by pcrs_filter_response
186 * and gif_deanimate_response if neccessary
188 * Improved handling of zero-change re_filter runs
190 * pcrs_filter_response and gif_deanimate_response now remove
191 * chunked transfer codeing before processing the body.
193 * Revision 1.34 2001/09/20 15:49:36 steudten
195 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
196 * See cgi.c fill_template().
198 * Revision 1.33 2001/09/16 17:05:14 jongfoster
199 * Removing unused #include showarg.h
201 * Revision 1.32 2001/09/16 13:21:27 jongfoster
202 * Changes to use new list functions.
204 * Revision 1.31 2001/09/16 11:38:02 jongfoster
205 * Splitting fill_template() into 2 functions:
206 * template_load() loads the file
207 * template_fill() performs the PCRS regexps.
208 * This is because the CGI edit interface has a "table row"
209 * template which is used many times in the page - this
210 * change means it's only loaded from disk once.
212 * Revision 1.30 2001/09/16 11:00:10 jongfoster
213 * New function alloc_http_response, for symmetry with free_http_response
215 * Revision 1.29 2001/09/13 23:32:40 jongfoster
216 * Moving image data to cgi.c rather than cgi.h
217 * Fixing a GPF under Win32 (and any other OS that protects global
218 * constants from being written to).
220 * Revision 1.28 2001/09/10 10:18:51 oes
221 * Silenced compiler warnings
223 * Revision 1.27 2001/08/05 16:06:20 jongfoster
224 * Modifiying "struct map" so that there are now separate header and
225 * "map_entry" structures. This means that functions which modify a
226 * map no longer need to return a pointer to the modified map.
227 * Also, it no longer reverses the order of the entries (which may be
228 * important with some advanced template substitutions).
230 * Revision 1.26 2001/07/30 22:08:36 jongfoster
231 * Tidying up #defines:
232 * - All feature #defines are now of the form FEATURE_xxx
233 * - Permanently turned off WIN_GUI_EDIT
234 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
236 * Revision 1.25 2001/07/26 10:09:46 oes
237 * Made browser detection a little less naive
239 * Revision 1.24 2001/07/25 17:22:51 oes
240 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
242 * Revision 1.23 2001/07/23 13:40:12 oes
243 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
245 * Revision 1.22 2001/07/18 12:29:34 oes
246 * - Made gif_deanimate_response respect
247 * csp->action->string[ACTION_STRING_DEANIMATE]
248 * - Logging cosmetics
250 * Revision 1.21 2001/07/13 13:59:53 oes
251 * - Introduced gif_deanimate_response which shares the
252 * generic content modification interface of pcrs_filter_response
253 * and acts as a wrapper to deanimate.c:gif_deanimate()
254 * - Renamed re_process_buffer to pcrs_filter_response
255 * - pcrs_filter_response now returns NULL on failure
256 * - Removed all #ifdef PCRS
258 * Revision 1.20 2001/07/01 17:01:04 oes
259 * Added comments and missing return statement in is_untrusted_url()
261 * Revision 1.19 2001/06/29 21:45:41 oes
262 * Indentation, CRLF->LF, Tab-> Space
264 * Revision 1.18 2001/06/29 13:27:38 oes
265 * - Cleaned up, renamed and reorderd functions
266 * and improved comments
269 * - Ported to CGI platform. Now delivers
270 * http_response or NULL
271 * - Unified HTML and GIF generation (moved image detection
272 * and GIF generation here from jcc.c:chat())
273 * - Fixed HTTP status to:
274 * - 403 (Forbidden) for the "blocked" HTML message
275 * - 200 (OK) for GIF answers
276 * - 302 (Redirect) for redirect to GIF
279 * - Ported to CGI platform. Now delivers
280 * http_response or NULL
281 * - Separated detection of untrusted URL into
282 * (bool)is_untrusted_url
283 * - Added enforcement of untrusted requests
285 * - Moved redirect_url() from cgi.c to here
286 * and ported it to the CGI platform
288 * - Removed logentry from cancelled commit
290 * Revision 1.17 2001/06/09 10:55:28 jongfoster
291 * Changing BUFSIZ ==> BUFFER_SIZE
293 * Revision 1.16 2001/06/07 23:10:26 jongfoster
294 * Allowing unanchored domain patterns to back off and retry
295 * if they partially match. Optimized right-anchored patterns.
296 * Moving ACL and forward files into config file.
297 * Replacing struct gateway with struct forward_spec
299 * Revision 1.15 2001/06/03 19:12:00 oes
300 * extracted-CGI relevant stuff
302 * Revision 1.14 2001/06/01 10:30:55 oes
303 * Added optional left-anchoring to domaincmp
305 * Revision 1.13 2001/05/31 21:21:30 jongfoster
306 * Permissionsfile / actions file changes:
307 * - Changed "permission" to "action" throughout
308 * - changes to file format to allow string parameters
309 * - Moved helper functions to actions.c
311 * Revision 1.12 2001/05/31 17:35:20 oes
313 * - Enhanced domain part globbing with infix and prefix asterisk
314 * matching and optional unanchored operation
316 * Revision 1.11 2001/05/29 11:53:23 oes
317 * "See why" link added to "blocked" page
319 * Revision 1.10 2001/05/29 09:50:24 jongfoster
320 * Unified blocklist/imagelist/permissionslist.
321 * File format is still under discussion, but the internal changes
324 * Also modified interceptor behaviour:
325 * - We now intercept all URLs beginning with one of the following
326 * prefixes (and *only* these prefixes):
328 * * http://ijbswa.sf.net/config/
329 * * http://ijbswa.sourceforge.net/config/
330 * - New interceptors "home page" - go to http://i.j.b/ to see it.
331 * - Internal changes so that intercepted and fast redirect pages
332 * are not replaced with an image.
333 * - Interceptors now have the option to send a binary page direct
334 * to the client. (i.e. ijb-send-banner uses this)
335 * - Implemented show-url-info interceptor. (Which is why I needed
336 * the above interceptors changes - a typical URL is
337 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
338 * The previous mechanism would not have intercepted that, and
339 * if it had been intercepted then it then it would have replaced
342 * Revision 1.9 2001/05/27 22:17:04 oes
344 * - re_process_buffer no longer writes the modified buffer
345 * to the client, which was very ugly. It now returns the
346 * buffer, which it is then written by chat.
348 * - content_length now adjusts the Content-Length: header
349 * for modified documents rather than crunch()ing it.
350 * (Length info in csp->content_length, which is 0 for
351 * unmodified documents)
353 * - For this to work, sed() is called twice when filtering.
355 * Revision 1.8 2001/05/26 17:13:28 jongfoster
356 * Filled in a function comment.
358 * Revision 1.7 2001/05/26 15:26:15 jongfoster
359 * ACL feature now provides more security by immediately dropping
360 * connections from untrusted hosts.
362 * Revision 1.6 2001/05/26 00:28:36 jongfoster
363 * Automatic reloading of config file.
364 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
365 * Most of the global variables have been moved to a new
366 * struct configuration_spec, accessed through csp->config->globalname
367 * Most of the globals remaining are used by the Win32 GUI.
369 * Revision 1.5 2001/05/25 22:34:30 jongfoster
372 * Revision 1.4 2001/05/22 18:46:04 oes
374 * - Enabled filtering banners by size rather than URL
375 * by adding patterns that replace all standard banner
376 * sizes with the "Junkbuster" gif to the re_filterfile
378 * - Enabled filtering WebBugs by providing a pattern
379 * which kills all 1x1 images
381 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
382 * which is selected by the (nonstandard and therefore
383 * capital) letter 'U' in the option string.
384 * It causes the quantifiers to be ungreedy by default.
385 * Appending a ? turns back to greedy (!).
387 * - Added a new interceptor ijb-send-banner, which
388 * sends back the "Junkbuster" gif. Without imagelist or
389 * MSIE detection support, or if tinygif = 1, or the
390 * URL isn't recognized as an imageurl, a lame HTML
391 * explanation is sent instead.
393 * - Added new feature, which permits blocking remote
394 * script redirects and firing back a local redirect
396 * The feature is conditionally compiled, i.e. it
397 * can be disabled with --disable-fast-redirects,
398 * plus it must be activated by a "fast-redirects"
399 * line in the config file, has its own log level
400 * and of course wants to be displayed by show-proxy-args
401 * Note: Boy, all the #ifdefs in 1001 locations and
402 * all the fumbling with configure.in and acconfig.h
403 * were *way* more work than the feature itself :-(
405 * - Because a generic redirect template was needed for
406 * this, tinygif = 3 now uses the same.
408 * - Moved GIFs, and other static HTTP response templates
413 * - Removed some >400 CRs again (Jon, you really worked
416 * Revision 1.3 2001/05/20 16:44:47 jongfoster
417 * Removing last hardcoded Junkbusters.com URLs.
419 * Revision 1.2 2001/05/20 01:21:20 jongfoster
420 * Version 2.9.4 checkin.
421 * - Merged popupfile and cookiefile, and added control over PCRS
422 * filtering, in new "permissionsfile".
423 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
424 * file error you now get a message box (in the Win32 GUI) rather
425 * than the program exiting with no explanation.
426 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
428 * - Removed tabs from "config"
429 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
430 * - Bumped up version number.
432 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
433 * Initial import of version 2.9.3 source tree
436 *********************************************************************/
442 #include <sys/types.h>
451 #endif /* ndef __OS2__ */
452 #include <netinet/in.h>
454 #include <winsock2.h>
455 #endif /* ndef _WIN32 */
459 #endif /* def __OS2__ */
467 #include "jbsockets.h"
468 #include "miscutil.h"
472 #include "deanimate.h"
473 #include "urlmatch.h"
474 #ifdef FEATURE_ACTIVITY_CONSOLE
476 #endif /* def FEATURE_ACTIVITY_CONSOLE */
481 const char filters_h_rcs[] = FILTERS_H_VERSION;
483 /* Fix a problem with Solaris. There should be no effect on other
485 * Solaris's isspace() is a macro which uses it's argument directly
486 * as an array index. Therefore we need to make sure that high-bit
487 * characters generate +ve values, and ideally we also want to make
488 * the argument match the declared parameter type of "int".
490 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
494 /*********************************************************************
496 * Function : block_acl
498 * Description : Block this request?
499 * Decide yes or no based on ACL file.
502 * 1 : dst = The proxy or gateway address this is going to.
503 * Or NULL to check all possible targets.
504 * 2 : csp = Current client state (buffers, headers, etc...)
505 * Also includes the client IP address.
507 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
509 *********************************************************************/
510 int block_acl(struct access_control_addr *dst, struct client_state *csp)
512 struct access_control_list *acl = csp->config->acl;
514 /* if not using an access control list, then permit the connection */
520 /* search the list */
523 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
527 /* Just want to check if they have any access */
528 if (acl->action == ACL_PERMIT)
533 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
534 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
536 if (acl->action == ACL_PERMIT)
542 #ifdef FEATURE_ACTIVITY_CONSOLE
543 accumulate_stats(STATS_ACL_RESTRICT, 1);
544 #endif /* def FEATURE_ACTIVITY_CONSOLE */
557 /*********************************************************************
559 * Function : acl_addr
561 * Description : Called from `load_config' to parse an ACL address.
564 * 1 : aspec = String specifying ACL address.
565 * 2 : aca = struct access_control_addr to fill in.
567 * Returns : 0 => Ok, everything else is an error.
569 *********************************************************************/
570 int acl_addr(char *aspec, struct access_control_addr *aca)
572 int i, masklength, port;
578 if ((p = strchr(aspec, '/')) != NULL)
582 if (ijb_isdigit(*p) == 0)
586 masklength = atoi(p);
589 if ((masklength < 0) || (masklength > 32))
594 if ((p = strchr(aspec, ':')) != NULL)
598 if (ijb_isdigit(*p) == 0)
607 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
609 if (aca->addr == INADDR_NONE)
614 /* build the netmask */
616 for (i=1; i <= masklength ; i++)
618 aca->mask |= (1 << (32 - i));
621 /* now mask off the host portion of the ip address
622 * (i.e. save on the network portion of the address).
624 aca->addr = aca->addr & aca->mask;
629 #endif /* def FEATURE_ACL */
632 /*********************************************************************
634 * Function : match_portlist
636 * Description : Check if a given number is covered by a comma
637 * separated list of numbers and ranges (a,b-c,d,..)
640 * 1 : portlist = String with list
641 * 2 : port = port to check
643 * Returns : 0 => no match
646 *********************************************************************/
647 int match_portlist(const char *portlist, int port)
649 char *min, *max, *next, *portlist_copy;
651 min = next = portlist_copy = strdup(portlist);
654 * Zero-terminate first item and remember offset for next
656 if (NULL != (next = strchr(portlist_copy, (int) ',')))
662 * Loop through all items, checking for match
666 if (NULL == (max = strchr(min, (int) '-')))
669 * No dash, check for equality
671 if (port == atoi(min))
680 * This is a range, so check if between min and max,
681 * or, if max was omitted, between min and 65K
684 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
698 * Zero-terminate next item and remember offset for n+1
700 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
712 /*********************************************************************
714 * Function : block_url
716 * Description : Called from `chat'. Check to see if we need to block this.
719 * 1 : csp = Current client state (buffers, headers, etc...)
721 * Returns : NULL => unblocked, else HTTP block response
723 *********************************************************************/
724 struct http_response *block_url(struct client_state *csp)
726 #ifdef FEATURE_IMAGE_BLOCKING
728 #endif /* def FEATURE_IMAGE_BLOCKING */
729 struct http_response *rsp;
732 * If it's not blocked, don't block it ;-)
734 if ((csp->action->flags & ACTION_BLOCK) == 0)
740 * Else, prepare a response
742 if (NULL == (rsp = alloc_http_response()))
744 return cgi_error_memory();
748 * If it's an image-url, send back an image or redirect
749 * as specified by the relevant +image action
751 #ifdef FEATURE_IMAGE_BLOCKING
752 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
755 /* determine HOW images should be blocked */
756 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
758 #if 1 /* Two alternative strategies, use this one for now: */
760 /* and handle accordingly: */
761 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
763 #ifdef FEATURE_ACTIVITY_CONSOLE
764 accumulate_stats(STATS_IMAGE_BLOCK, 1);
765 #endif /* def FEATURE_ACTIVITY_CONSOLE */
766 rsp->body = bindup(image_pattern_data, image_pattern_length);
767 if (rsp->body == NULL)
769 free_http_response(rsp);
770 return cgi_error_memory();
772 rsp->content_length = image_pattern_length;
774 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
776 free_http_response(rsp);
777 return cgi_error_memory();
781 else if (0 == strcmpic(p, "blank"))
783 #ifdef FEATURE_ACTIVITY_CONSOLE
784 accumulate_stats(STATS_IMAGE_BLOCK, 1);
785 #endif /* def FEATURE_ACTIVITY_CONSOLE */
786 rsp->body = bindup(image_blank_data, image_blank_length);
787 if (rsp->body == NULL)
789 free_http_response(rsp);
790 return cgi_error_memory();
792 rsp->content_length = image_blank_length;
794 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
796 free_http_response(rsp);
797 return cgi_error_memory();
801 else if (0 == strcmpic(p, "custom"))
803 rsp->body = bindup(csp->config->image_blocker_data, csp->config->image_blocker_length);
804 if (rsp->body == NULL)
806 free_http_response(rsp);
807 return cgi_error_memory();
809 rsp->content_length = csp->config->image_blocker_length;
811 if (enlist_unique_header(rsp->headers, "Content-Type", csp->config->image_blocker_format))
813 free_http_response(rsp);
814 return cgi_error_memory();
820 rsp->status = strdup("302 Local Redirect from Privoxy");
821 if (rsp->status == NULL)
823 free_http_response(rsp);
824 return cgi_error_memory();
827 if (enlist_unique_header(rsp->headers, "Location", p))
829 free_http_response(rsp);
830 return cgi_error_memory();
834 #else /* Following code is disabled for now */
836 /* and handle accordingly: */
837 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
839 p = CGI_PREFIX "send-banner?type=pattern";
841 else if (0 == strcmpic(p, "blank"))
843 p = CGI_PREFIX "send-banner?type=blank";
845 rsp->status = strdup("302 Local Redirect from Privoxy");
846 if (rsp->status == NULL)
848 free_http_response(rsp);
849 return cgi_error_memory();
852 if (enlist_unique_header(rsp->headers, "Location", p))
854 free_http_response(rsp);
855 return cgi_error_memory();
857 #endif /* Preceeding code is disabled for now */
860 #endif /* def FEATURE_IMAGE_BLOCKING */
863 * Else, generate an HTML "blocked" message:
867 struct map * exports;
870 * Workaround for stupid Netscape bug which prevents
871 * pages from being displayed if loading a referenced
872 * JavaScript or style sheet fails. So make it appear
873 * as if it succeeded.
875 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
876 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
877 && !strstr(p, "Gecko") /* save Mozilla, */
878 && !strstr(p, "compatible") /* MSIE */
879 && !strstr(p, "Opera")) /* and Opera. */
881 rsp->status = strdup("200 Request for blocked URL");
885 rsp->status = strdup("404 Request for blocked URL");
888 if (rsp->status == NULL)
890 free_http_response(rsp);
891 return cgi_error_memory();
894 exports = default_exports(csp, NULL);
897 free_http_response(rsp);
898 return cgi_error_memory();
901 #ifdef FEATURE_FORCE_LOAD
902 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
903 if (csp->http->ssl != 0)
904 #endif /* ndef FEATURE_FORCE_LOAD */
906 err = map_block_killer(exports, "force-support");
909 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
910 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
911 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
916 free_http_response(rsp);
917 return cgi_error_memory();
920 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
923 free_http_response(rsp);
924 return cgi_error_memory();
928 return finish_http_response(rsp);
934 /*********************************************************************
936 * Function : trust_url FIXME: I should be called distrust_url
938 * Description : Calls is_untrusted_url to determine if the URL is trusted
939 * and if not, returns a HTTP 304 response with a reject message.
942 * 1 : csp = Current client state (buffers, headers, etc...)
944 * Returns : NULL => trusted, else http_response.
946 *********************************************************************/
947 struct http_response *trust_url(struct client_state *csp)
949 struct http_response *rsp;
950 struct map * exports;
951 char buf[BUFFER_SIZE];
953 struct url_spec **tl;
958 * Don't bother to work on trusted URLs
960 if (!is_untrusted_url(csp))
966 * Else, prepare a response:
968 if (NULL == (rsp = alloc_http_response()))
970 return cgi_error_memory();
973 exports = default_exports(csp, NULL);
976 free_http_response(rsp);
977 return cgi_error_memory();
981 * Export the protocol, host, port, and referrer information
983 err = map(exports, "hostport", 1, csp->http->hostport, 1);
984 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
985 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
987 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
989 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
993 if (!err) err = map(exports, "referrer", 1, "unknown", 1);
999 free_http_response(rsp);
1000 return cgi_error_memory();
1004 * Export the trust list
1007 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1009 sprintf(buf, "<li>%s</li>\n", t->spec);
1010 string_append(&p, buf);
1012 err = map(exports, "trusted-referrers", 1, p, 0);
1017 free_http_response(rsp);
1018 return cgi_error_memory();
1022 * Export the trust info, if available
1024 if (csp->config->trust_info->first)
1026 struct list_entry *l;
1029 for (l = csp->config->trust_info->first; l ; l = l->next)
1031 sprintf(buf, "<li> <a href=\"%s\">%s</a><br>\n",l->str, l->str);
1032 string_append(&p, buf);
1034 err = map(exports, "trust-info", 1, p, 0);
1038 err = map_block_killer(exports, "have-trust-info");
1044 free_http_response(rsp);
1045 return cgi_error_memory();
1049 * Export the force prefix or the force conditional block killer
1051 #ifdef FEATURE_FORCE_LOAD
1052 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1053 #else /* ifndef FEATURE_FORCE_LOAD */
1054 err = map_block_killer(exports, "force-support");
1055 #endif /* ndef FEATURE_FORCE_LOAD */
1060 free_http_response(rsp);
1061 return cgi_error_memory();
1065 * Build the response
1067 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1070 free_http_response(rsp);
1071 return cgi_error_memory();
1074 return finish_http_response(rsp);
1076 #endif /* def FEATURE_TRUST */
1079 #ifdef FEATURE_FAST_REDIRECTS
1080 /*********************************************************************
1082 * Function : redirect_url
1084 * Description : Checks for redirection URLs and returns a HTTP redirect
1085 * to the destination URL, if necessary
1088 * 1 : csp = Current client state (buffers, headers, etc...)
1090 * Returns : NULL if URL was clean, HTTP redirect otherwise.
1092 *********************************************************************/
1093 struct http_response *redirect_url(struct client_state *csp)
1096 struct http_response *rsp;
1098 p = q = csp->http->path;
1099 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
1102 * find the last URL encoded in the request
1104 while ((p = strstr(p, "http://")) != NULL)
1110 * if there was any, generate and return a HTTP redirect
1112 if (q != csp->http->path)
1114 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
1116 if (NULL == (rsp = alloc_http_response()))
1118 return cgi_error_memory();
1121 if ( enlist_unique_header(rsp->headers, "Location", q)
1122 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1124 free_http_response(rsp);
1125 return cgi_error_memory();
1128 return finish_http_response(rsp);
1136 #endif /* def FEATURE_FAST_REDIRECTS */
1139 #ifdef FEATURE_IMAGE_BLOCKING
1140 /*********************************************************************
1142 * Function : is_imageurl
1144 * Description : Given a URL, decide whether it is an image or not,
1145 * using either the info from a previous +image action
1146 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1147 * is MSIE and not on a Mac, tell from the browser's accept
1151 * 1 : csp = Current client state (buffers, headers, etc...)
1153 * Returns : True (nonzero) if URL is an image, false (0)
1156 *********************************************************************/
1157 int is_imageurl(struct client_state *csp)
1159 #ifdef FEATURE_IMAGE_DETECT_MSIE
1162 tmp = get_header_value(csp->headers, "User-Agent:");
1163 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1165 tmp = get_header_value(csp->headers, "Accept:");
1166 if (tmp && strstr(tmp, "image/gif"))
1168 /* Client will accept HTML. If this seems counterintuitive,
1178 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1180 return ((csp->action->flags & ACTION_IMAGE) != 0);
1183 #endif /* def FEATURE_IMAGE_BLOCKING */
1186 #ifdef FEATURE_TRUST
1187 /*********************************************************************
1189 * Function : is_untrusted_url
1191 * Description : Should we "distrust" this URL (and block it)?
1193 * Yes if it matches a line in the trustfile, or if the
1194 * referrer matches a line starting with "+" in the
1199 * 1 : csp = Current client state (buffers, headers, etc...)
1201 * Returns : 0 => trusted, 1 => untrusted
1203 *********************************************************************/
1204 int is_untrusted_url(struct client_state *csp)
1206 struct file_list *fl;
1207 struct block_spec *b;
1208 struct url_spec **trusted_url;
1209 struct http_request rhttp[1];
1210 const char * referer;
1214 * If we don't have a trustlist, we trust everybody
1216 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1221 memset(rhttp, '\0', sizeof(*rhttp));
1224 * Do we trust the request URL itself?
1226 for (b = b->next; b ; b = b->next)
1228 if (url_match(b->url, csp->http))
1234 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1236 /* no referrer was supplied */
1242 * If not, do we maybe trust its referrer?
1244 err = parse_http_url(referer, rhttp, csp);
1250 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1252 if (url_match(*trusted_url, rhttp))
1254 /* if the URL's referrer is from a trusted referrer, then
1255 * add the target spec to the trustfile as an unblocked
1256 * domain and return NULL (which means it's OK).
1261 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1265 char * new_entry = strdup("~");
1267 string_append(&new_entry, csp->http->hostport);
1269 path = csp->http->path;
1270 if ( (path[0] == '/')
1272 && ((path_end = strchr(path + 2, '/')) != NULL))
1274 /* since this path points into a user's home space
1275 * be sure to include this spec in the trustfile.
1277 int path_len = path_end - path; /* save offset */
1278 path = strdup(path); /* Copy string */
1281 path_end = path + path_len; /* regenerate ptr to new buffer */
1282 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1284 string_join(&new_entry, path);
1287 if (new_entry != NULL)
1289 fprintf(fp, "%s\n", new_entry);
1294 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1295 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1305 #endif /* def FEATURE_TRUST */
1308 /*********************************************************************
1310 * Function : pcrs_filter_response
1312 * Description : Execute all text substitutions from all applying
1313 * +filter actions on the text buffer that's been accumulated
1314 * in csp->iob->buf. If this changes the contents, set
1315 * csp->content_length to the modified size and raise the
1316 * CSP_FLAG_MODIFIED flag.
1319 * 1 : csp = Current client state (buffers, headers, etc...)
1321 * Returns : a pointer to the (newly allocated) modified buffer.
1322 * or NULL if there were no hits or something went wrong
1324 *********************************************************************/
1325 char *pcrs_filter_response(struct client_state *csp)
1328 size_t size, prev_size;
1330 char *old_buf = csp->iob->cur, *new_buf = NULL;
1333 struct file_list *fl;
1334 struct re_filterfile_spec *b;
1335 struct list_entry *filtername;
1340 if (csp->iob->cur >= csp->iob->eod)
1344 size = csp->iob->eod - csp->iob->cur;
1346 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == fl->f) )
1348 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1353 * If the body has a "chunked" transfer-encoding,
1354 * get rid of it first, adjusting size and iob->eod
1356 if (csp->flags & CSP_FLAG_CHUNKED)
1358 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1359 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1363 csp->iob->eod = csp->iob->cur + size;
1364 csp->flags |= CSP_FLAG_MODIFIED;
1368 * For all applying +filter actions, look if a filter by that
1369 * name exists and if yes, execute it's pcrs_joblist on the
1372 for (b = fl->f; b; b = b->next)
1374 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1375 filtername ; filtername = filtername->next)
1377 if (strcmp(b->name, filtername->str) == 0)
1379 int current_hits = 0;
1381 if ( NULL == b->joblist )
1383 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1388 /* Apply all jobs from the joblist */
1389 for (job = b->joblist; NULL != job; job = job->next)
1391 current_hits += pcrs_execute(job, old_buf, size, &new_buf, &size);
1392 if (old_buf != csp->iob->cur) free(old_buf);
1396 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) with filter %s produced %d hits (new size %d).",
1397 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1399 hits += current_hits;
1405 * If there were no hits, destroy our copy and let
1406 * chat() use the original in csp->iob
1413 #ifdef FEATURE_ACTIVITY_CONSOLE
1415 accumulate_stats(STATS_FILTER, hits);
1416 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1418 csp->flags |= CSP_FLAG_MODIFIED;
1419 csp->content_length = size;
1427 /*********************************************************************
1429 * Function : gif_deanimate_response
1431 * Description : Deanimate the GIF image that has been accumulated in
1432 * csp->iob->buf, set csp->content_length to the modified
1433 * size and raise the CSP_FLAG_MODIFIED flag.
1436 * 1 : csp = Current client state (buffers, headers, etc...)
1438 * Returns : a pointer to the (newly allocated) modified buffer.
1439 * or NULL in case something went wrong.
1441 *********************************************************************/
1442 char *gif_deanimate_response(struct client_state *csp)
1444 struct binbuffer *in, *out;
1446 size_t size = csp->iob->eod - csp->iob->cur;
1449 * If the body has a "chunked" transfer-encoding,
1450 * get rid of it first, adjusting size and iob->eod
1452 if (csp->flags & CSP_FLAG_CHUNKED)
1454 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1455 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1459 csp->iob->eod = csp->iob->cur + size;
1460 csp->flags |= CSP_FLAG_MODIFIED;
1463 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1464 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1466 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1470 in->buffer = csp->iob->cur;
1473 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1475 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1482 if ((int)size == out->offset)
1484 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1488 #ifdef FEATURE_ACTIVITY_CONSOLE
1489 accumulate_stats(STATS_GIF_DEANIMATE, 1);
1490 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1491 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1493 csp->content_length = out->offset;
1494 csp->flags |= CSP_FLAG_MODIFIED;
1504 /*********************************************************************
1506 * Function : jpeg_inspect_response
1511 * 1 : csp = Current client state (buffers, headers, etc...)
1513 * Returns : a pointer to the (newly allocated) modified buffer
1514 * or NULL in case something went wrong.
1516 *********************************************************************/
1517 char *jpeg_inspect_response(struct client_state *csp)
1519 struct binbuffer *in = NULL, *out = NULL;
1521 size_t size = csp->iob->eod - csp->iob->cur;
1524 * If the body has a "chunked" transfer-encoding,
1525 * get rid of it first, adjusting size and iob->eod
1527 if (csp->flags & CSP_FLAG_CHUNKED)
1529 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1530 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1534 csp->iob->eod = csp->iob->cur + size;
1535 csp->flags |= CSP_FLAG_MODIFIED;
1538 if (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1540 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 1)");
1544 if (NULL == (out = (struct binbuffer *)zalloc(sizeof *out)))
1546 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg no mem 2)");
1550 in->buffer = csp->iob->cur;
1554 * Calling jpeg_inspect has the side-effect of creating and
1555 * modifying the image buffer of "out" directly.
1557 if (jpeg_inspect(in, out))
1559 log_error(LOG_LEVEL_DEANIMATE, "failed! (jpeg parsing)");
1567 csp->content_length = out->offset;
1568 csp->flags |= CSP_FLAG_MODIFIED;
1578 /*********************************************************************
1580 * Function : remove_chunked_transfer_coding
1582 * Description : In-situ remove the "chunked" transfer coding as defined
1583 * in rfc2616 from a buffer.
1586 * 1 : buffer = Pointer to the text buffer
1587 * 2 : size = Number of bytes to be processed
1589 * Returns : The new size, i.e. the number of bytes from buffer which
1590 * are occupied by the stripped body, or 0 in case something
1593 *********************************************************************/
1594 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1597 unsigned int chunksize = 0;
1598 char *from_p, *to_p;
1601 from_p = to_p = buffer;
1603 if (sscanf(buffer, "%x", &chunksize) != 1)
1605 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1609 while (chunksize > 0)
1611 if (NULL == (from_p = strstr(from_p, "\r\n")))
1613 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1617 if ((newsize += chunksize) >= size)
1619 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
1624 memmove(to_p, from_p, (size_t) chunksize);
1625 to_p = buffer + newsize;
1626 from_p += chunksize + 2;
1628 if (sscanf(from_p, "%x", &chunksize) != 1)
1630 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1635 /* FIXME: Should this get its own loglevel? */
1636 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1642 /*********************************************************************
1644 * Function : url_actions
1646 * Description : Gets the actions for this URL.
1649 * 1 : http = http_request request for blocked URLs
1650 * 2 : csp = Current client state (buffers, headers, etc...)
1654 *********************************************************************/
1655 void url_actions(struct http_request *http,
1656 struct client_state *csp)
1658 struct file_list *fl;
1659 struct url_actions *b;
1662 init_current_action(csp->action);
1664 for (i = 0; i < MAX_ACTION_FILES; i++)
1666 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
1671 apply_url_actions(csp->action, http, b);
1678 /*********************************************************************
1680 * Function : apply_url_actions
1682 * Description : Applies a list of URL actions.
1685 * 1 : action = Destination.
1686 * 2 : http = Current URL
1687 * 3 : b = list of URL actions to apply
1691 *********************************************************************/
1692 void apply_url_actions(struct current_action_spec *action,
1693 struct http_request *http,
1694 struct url_actions *b)
1698 /* Should never happen */
1702 for (b = b->next; NULL != b; b = b->next)
1704 if (url_match(b->url, http))
1706 merge_current_action(action, b->action);
1712 /*********************************************************************
1714 * Function : forward_url
1716 * Description : Should we forward this to another proxy?
1719 * 1 : http = http_request request for current URL
1720 * 2 : csp = Current client state (buffers, headers, etc...)
1722 * Returns : Pointer to forwarding information.
1724 *********************************************************************/
1725 const struct forward_spec * forward_url(struct http_request *http,
1726 struct client_state *csp)
1728 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1729 struct forward_spec *fwd = csp->config->forward;
1738 if (url_match(fwd->url, http))