1 const char filters_rcs[] = "$Id: filters.c,v 2.5 2003/09/22 00:33:01 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', and `trust_url'
14 * Copyright : Written by and Copyright (C) 2001 the SourceForge
15 * Privoxy team. http://www.privoxy.org/
17 * Based on the Internet Junkbuster originally written
18 * by and Copyright (C) 1997 Anonymous Coders and
19 * Junkbusters Corporation. http://www.junkbusters.com
21 * This program is free software; you can redistribute it
22 * and/or modify it under the terms of the GNU General
23 * Public License as published by the Free Software
24 * Foundation; either version 2 of the License, or (at
25 * your option) any later version.
27 * This program is distributed in the hope that it will
28 * be useful, but WITHOUT ANY WARRANTY; without even the
29 * implied warranty of MERCHANTABILITY or FITNESS FOR A
30 * PARTICULAR PURPOSE. See the GNU General Public
31 * License for more details.
33 * The GNU General Public License should be included with
34 * this file. If not, you can view it at
35 * http://www.gnu.org/copyleft/gpl.html
36 * or write to the Free Software Foundation, Inc., 59
37 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
41 * Revision 2.5 2003/09/22 00:33:01 david__schmidt
42 * Enable sending a custom 'blocked' image. Shows up as
43 * "image-blocker-custom-file" parameter in config, and
44 * "+set-image-blocker{custom}" in action files.
46 * Revision 2.4 2003/01/21 02:49:27 david__schmidt
47 * Developer TODO 612294: src: C++ keyword as variable name
48 * I changed all ocurrences of 'new' to 'new_something' wherever I found
49 * one. I also brought up all the source files in MSDEV to see if I could
50 * spot any highlighted keywords that really were variables. Non-scientific,
51 * but at least I tried. :-)
53 * Revision 2.3 2002/12/28 03:58:19 david__schmidt
54 * Initial drop of dashboard instrumentation - enabled with
55 * --enable-activity-console
57 * Revision 2.2 2002/09/04 15:38:24 oes
58 * Synced with the stable branch:
59 * Revision 1.58.2.2 2002/08/01 17:18:28 oes
60 * Fixed BR 537651 / SR 579724 (MSIE image detect improper for IE/Mac)
62 * Revision 1.58.2.1 2002/07/26 15:18:53 oes
63 * - Bugfix: Executing a filters without jobs no longer results in
64 * turing off *all* filters.
65 * - Security fix: Malicious web servers can't cause a seg fault
66 * through bogus chunk sizes anymore
68 * Revision 2.1 2002/08/26 11:08:18 sarantis
71 * Revision 2.0 2002/06/04 14:34:21 jongfoster
72 * Moving source files to src/
74 * Revision 1.58 2002/04/24 02:11:17 oes
75 * Jon's multiple AF patch: url_actions now evaluates rules
78 * Revision 1.57 2002/04/08 20:38:34 swa
81 * Revision 1.56 2002/04/05 15:51:24 oes
82 * - bugfix: error-pages now get correct request protocol
83 * - fix for invalid HTML in trust info
85 * Revision 1.55 2002/04/02 16:13:51 oes
86 * Fix: No "Go there anyway" for SSL
88 * Revision 1.54 2002/04/02 14:55:56 oes
89 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
91 * Revision 1.53 2002/03/26 22:29:54 swa
92 * we have a new homepage!
94 * Revision 1.52 2002/03/24 16:35:57 jongfoster
97 * Revision 1.51 2002/03/24 15:23:33 jongfoster
100 * Revision 1.50 2002/03/24 13:25:43 swa
101 * name change related issues
103 * Revision 1.49 2002/03/16 20:29:14 oes
106 * Revision 1.48 2002/03/13 20:25:34 oes
107 * Better logging for content filters
109 * Revision 1.47 2002/03/13 00:30:52 jongfoster
111 * Added option of always sending redirect for imageblock,
112 * currently disabled with #if 0.
114 * Revision 1.46 2002/03/12 01:42:49 oes
115 * Introduced modular filters
117 * Revision 1.45 2002/03/08 16:47:50 oes
118 * Added choice beween GIF and PNG built-in images
120 * Revision 1.44 2002/03/07 03:49:31 oes
121 * - Fixed compiler warnings etc
122 * - Changed built-in images from GIF to PNG
123 * (with regard to Unisys patent issue)
124 * - Added a 4x4 pattern PNG which is less intrusive
125 * than the logo but also clearly marks the deleted banners
127 * Revision 1.43 2002/01/22 23:51:59 jongfoster
128 * Replacing strsav() with the safer string_append().
130 * Adding missing html_encode() to error message generators. Where encoded
131 * and unencoded versions of a string were provided, removing the unencoded
134 * Revision 1.42 2002/01/17 21:00:32 jongfoster
135 * Moving all our URL and URL pattern parsing code to urlmatch.c.
137 * Using a single, simple url_match(pattern,url) function - rather than
138 * the 3-line match routine which was repeated all over the place.
140 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
142 * Using parse_http_url() to parse URLs without faking a HTTP
143 * request line for parse_http_request().
145 * Revision 1.41 2001/11/13 00:14:07 jongfoster
146 * Fixing stupid bug now I've figured out what || means.
147 * (It always returns 0 or 1, not one of it's paramaters.)
149 * Revision 1.40 2001/10/26 17:37:55 oes
150 * - Re-enabled Netscape 200/404 bug workaround in block_url():
151 * - Removed OS/2 special case
152 * - Made block_url() independant from sed() having been run
153 * - Made trust_url independant from sed() having been run
154 * - Made is_imageurl independant from sed() having been run.
155 * It now checks User-Agent: and Accept: by itself.
158 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
159 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
160 * threads to call select() simultaneously. So, it's time to do a real, live,
161 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
162 * (native). Both versions will work, but using __OS2__ offers multi-threading.
164 * Revision 1.38 2001/10/23 21:32:33 jongfoster
165 * Adding error-checking to selected functions
167 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
168 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
169 * filters.c. Added a FIXME in front of the offending code. I'll gladly
170 * put in a better/more robust fix for all parties if one is presented...
171 * It seems that just returning 200 instead of 404 would pretty much fix
172 * it for everyone, but I don't know all the history of the problem.
174 * Revision 1.36 2001/10/10 16:44:16 oes
175 * Added match_portlist function
177 * Revision 1.35 2001/10/07 15:41:23 oes
178 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
180 * New function remove_chunked_transfer_coding that strips chunked
181 * transfer coding to plain and is called by pcrs_filter_response
182 * and gif_deanimate_response if neccessary
184 * Improved handling of zero-change re_filter runs
186 * pcrs_filter_response and gif_deanimate_response now remove
187 * chunked transfer codeing before processing the body.
189 * Revision 1.34 2001/09/20 15:49:36 steudten
191 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
192 * See cgi.c fill_template().
194 * Revision 1.33 2001/09/16 17:05:14 jongfoster
195 * Removing unused #include showarg.h
197 * Revision 1.32 2001/09/16 13:21:27 jongfoster
198 * Changes to use new list functions.
200 * Revision 1.31 2001/09/16 11:38:02 jongfoster
201 * Splitting fill_template() into 2 functions:
202 * template_load() loads the file
203 * template_fill() performs the PCRS regexps.
204 * This is because the CGI edit interface has a "table row"
205 * template which is used many times in the page - this
206 * change means it's only loaded from disk once.
208 * Revision 1.30 2001/09/16 11:00:10 jongfoster
209 * New function alloc_http_response, for symmetry with free_http_response
211 * Revision 1.29 2001/09/13 23:32:40 jongfoster
212 * Moving image data to cgi.c rather than cgi.h
213 * Fixing a GPF under Win32 (and any other OS that protects global
214 * constants from being written to).
216 * Revision 1.28 2001/09/10 10:18:51 oes
217 * Silenced compiler warnings
219 * Revision 1.27 2001/08/05 16:06:20 jongfoster
220 * Modifiying "struct map" so that there are now separate header and
221 * "map_entry" structures. This means that functions which modify a
222 * map no longer need to return a pointer to the modified map.
223 * Also, it no longer reverses the order of the entries (which may be
224 * important with some advanced template substitutions).
226 * Revision 1.26 2001/07/30 22:08:36 jongfoster
227 * Tidying up #defines:
228 * - All feature #defines are now of the form FEATURE_xxx
229 * - Permanently turned off WIN_GUI_EDIT
230 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
232 * Revision 1.25 2001/07/26 10:09:46 oes
233 * Made browser detection a little less naive
235 * Revision 1.24 2001/07/25 17:22:51 oes
236 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
238 * Revision 1.23 2001/07/23 13:40:12 oes
239 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
241 * Revision 1.22 2001/07/18 12:29:34 oes
242 * - Made gif_deanimate_response respect
243 * csp->action->string[ACTION_STRING_DEANIMATE]
244 * - Logging cosmetics
246 * Revision 1.21 2001/07/13 13:59:53 oes
247 * - Introduced gif_deanimate_response which shares the
248 * generic content modification interface of pcrs_filter_response
249 * and acts as a wrapper to deanimate.c:gif_deanimate()
250 * - Renamed re_process_buffer to pcrs_filter_response
251 * - pcrs_filter_response now returns NULL on failure
252 * - Removed all #ifdef PCRS
254 * Revision 1.20 2001/07/01 17:01:04 oes
255 * Added comments and missing return statement in is_untrusted_url()
257 * Revision 1.19 2001/06/29 21:45:41 oes
258 * Indentation, CRLF->LF, Tab-> Space
260 * Revision 1.18 2001/06/29 13:27:38 oes
261 * - Cleaned up, renamed and reorderd functions
262 * and improved comments
265 * - Ported to CGI platform. Now delivers
266 * http_response or NULL
267 * - Unified HTML and GIF generation (moved image detection
268 * and GIF generation here from jcc.c:chat())
269 * - Fixed HTTP status to:
270 * - 403 (Forbidden) for the "blocked" HTML message
271 * - 200 (OK) for GIF answers
272 * - 302 (Redirect) for redirect to GIF
275 * - Ported to CGI platform. Now delivers
276 * http_response or NULL
277 * - Separated detection of untrusted URL into
278 * (bool)is_untrusted_url
279 * - Added enforcement of untrusted requests
281 * - Moved redirect_url() from cgi.c to here
282 * and ported it to the CGI platform
284 * - Removed logentry from cancelled commit
286 * Revision 1.17 2001/06/09 10:55:28 jongfoster
287 * Changing BUFSIZ ==> BUFFER_SIZE
289 * Revision 1.16 2001/06/07 23:10:26 jongfoster
290 * Allowing unanchored domain patterns to back off and retry
291 * if they partially match. Optimized right-anchored patterns.
292 * Moving ACL and forward files into config file.
293 * Replacing struct gateway with struct forward_spec
295 * Revision 1.15 2001/06/03 19:12:00 oes
296 * extracted-CGI relevant stuff
298 * Revision 1.14 2001/06/01 10:30:55 oes
299 * Added optional left-anchoring to domaincmp
301 * Revision 1.13 2001/05/31 21:21:30 jongfoster
302 * Permissionsfile / actions file changes:
303 * - Changed "permission" to "action" throughout
304 * - changes to file format to allow string parameters
305 * - Moved helper functions to actions.c
307 * Revision 1.12 2001/05/31 17:35:20 oes
309 * - Enhanced domain part globbing with infix and prefix asterisk
310 * matching and optional unanchored operation
312 * Revision 1.11 2001/05/29 11:53:23 oes
313 * "See why" link added to "blocked" page
315 * Revision 1.10 2001/05/29 09:50:24 jongfoster
316 * Unified blocklist/imagelist/permissionslist.
317 * File format is still under discussion, but the internal changes
320 * Also modified interceptor behaviour:
321 * - We now intercept all URLs beginning with one of the following
322 * prefixes (and *only* these prefixes):
324 * * http://ijbswa.sf.net/config/
325 * * http://ijbswa.sourceforge.net/config/
326 * - New interceptors "home page" - go to http://i.j.b/ to see it.
327 * - Internal changes so that intercepted and fast redirect pages
328 * are not replaced with an image.
329 * - Interceptors now have the option to send a binary page direct
330 * to the client. (i.e. ijb-send-banner uses this)
331 * - Implemented show-url-info interceptor. (Which is why I needed
332 * the above interceptors changes - a typical URL is
333 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
334 * The previous mechanism would not have intercepted that, and
335 * if it had been intercepted then it then it would have replaced
338 * Revision 1.9 2001/05/27 22:17:04 oes
340 * - re_process_buffer no longer writes the modified buffer
341 * to the client, which was very ugly. It now returns the
342 * buffer, which it is then written by chat.
344 * - content_length now adjusts the Content-Length: header
345 * for modified documents rather than crunch()ing it.
346 * (Length info in csp->content_length, which is 0 for
347 * unmodified documents)
349 * - For this to work, sed() is called twice when filtering.
351 * Revision 1.8 2001/05/26 17:13:28 jongfoster
352 * Filled in a function comment.
354 * Revision 1.7 2001/05/26 15:26:15 jongfoster
355 * ACL feature now provides more security by immediately dropping
356 * connections from untrusted hosts.
358 * Revision 1.6 2001/05/26 00:28:36 jongfoster
359 * Automatic reloading of config file.
360 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
361 * Most of the global variables have been moved to a new
362 * struct configuration_spec, accessed through csp->config->globalname
363 * Most of the globals remaining are used by the Win32 GUI.
365 * Revision 1.5 2001/05/25 22:34:30 jongfoster
368 * Revision 1.4 2001/05/22 18:46:04 oes
370 * - Enabled filtering banners by size rather than URL
371 * by adding patterns that replace all standard banner
372 * sizes with the "Junkbuster" gif to the re_filterfile
374 * - Enabled filtering WebBugs by providing a pattern
375 * which kills all 1x1 images
377 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
378 * which is selected by the (nonstandard and therefore
379 * capital) letter 'U' in the option string.
380 * It causes the quantifiers to be ungreedy by default.
381 * Appending a ? turns back to greedy (!).
383 * - Added a new interceptor ijb-send-banner, which
384 * sends back the "Junkbuster" gif. Without imagelist or
385 * MSIE detection support, or if tinygif = 1, or the
386 * URL isn't recognized as an imageurl, a lame HTML
387 * explanation is sent instead.
389 * - Added new feature, which permits blocking remote
390 * script redirects and firing back a local redirect
392 * The feature is conditionally compiled, i.e. it
393 * can be disabled with --disable-fast-redirects,
394 * plus it must be activated by a "fast-redirects"
395 * line in the config file, has its own log level
396 * and of course wants to be displayed by show-proxy-args
397 * Note: Boy, all the #ifdefs in 1001 locations and
398 * all the fumbling with configure.in and acconfig.h
399 * were *way* more work than the feature itself :-(
401 * - Because a generic redirect template was needed for
402 * this, tinygif = 3 now uses the same.
404 * - Moved GIFs, and other static HTTP response templates
409 * - Removed some >400 CRs again (Jon, you really worked
412 * Revision 1.3 2001/05/20 16:44:47 jongfoster
413 * Removing last hardcoded Junkbusters.com URLs.
415 * Revision 1.2 2001/05/20 01:21:20 jongfoster
416 * Version 2.9.4 checkin.
417 * - Merged popupfile and cookiefile, and added control over PCRS
418 * filtering, in new "permissionsfile".
419 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
420 * file error you now get a message box (in the Win32 GUI) rather
421 * than the program exiting with no explanation.
422 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
424 * - Removed tabs from "config"
425 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
426 * - Bumped up version number.
428 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
429 * Initial import of version 2.9.3 source tree
432 *********************************************************************/
438 #include <sys/types.h>
447 #endif /* ndef __OS2__ */
448 #include <netinet/in.h>
450 #include <winsock2.h>
451 #endif /* ndef _WIN32 */
455 #endif /* def __OS2__ */
463 #include "jbsockets.h"
464 #include "miscutil.h"
468 #include "deanimate.h"
469 #include "urlmatch.h"
470 #ifdef FEATURE_ACTIVITY_CONSOLE
472 #endif /* def FEATURE_ACTIVITY_CONSOLE */
477 const char filters_h_rcs[] = FILTERS_H_VERSION;
479 /* Fix a problem with Solaris. There should be no effect on other
481 * Solaris's isspace() is a macro which uses it's argument directly
482 * as an array index. Therefore we need to make sure that high-bit
483 * characters generate +ve values, and ideally we also want to make
484 * the argument match the declared parameter type of "int".
486 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
490 /*********************************************************************
492 * Function : block_acl
494 * Description : Block this request?
495 * Decide yes or no based on ACL file.
498 * 1 : dst = The proxy or gateway address this is going to.
499 * Or NULL to check all possible targets.
500 * 2 : csp = Current client state (buffers, headers, etc...)
501 * Also includes the client IP address.
503 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
505 *********************************************************************/
506 int block_acl(struct access_control_addr *dst, struct client_state *csp)
508 struct access_control_list *acl = csp->config->acl;
510 /* if not using an access control list, then permit the connection */
516 /* search the list */
519 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
523 /* Just want to check if they have any access */
524 if (acl->action == ACL_PERMIT)
529 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
530 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
532 if (acl->action == ACL_PERMIT)
538 #ifdef FEATURE_ACTIVITY_CONSOLE
539 accumulate_stats(STATS_ACL_RESTRICT, 1);
540 #endif /* def FEATURE_ACTIVITY_CONSOLE */
553 /*********************************************************************
555 * Function : acl_addr
557 * Description : Called from `load_config' to parse an ACL address.
560 * 1 : aspec = String specifying ACL address.
561 * 2 : aca = struct access_control_addr to fill in.
563 * Returns : 0 => Ok, everything else is an error.
565 *********************************************************************/
566 int acl_addr(char *aspec, struct access_control_addr *aca)
568 int i, masklength, port;
574 if ((p = strchr(aspec, '/')) != NULL)
578 if (ijb_isdigit(*p) == 0)
582 masklength = atoi(p);
585 if ((masklength < 0) || (masklength > 32))
590 if ((p = strchr(aspec, ':')) != NULL)
594 if (ijb_isdigit(*p) == 0)
603 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
605 if (aca->addr == INADDR_NONE)
610 /* build the netmask */
612 for (i=1; i <= masklength ; i++)
614 aca->mask |= (1 << (32 - i));
617 /* now mask off the host portion of the ip address
618 * (i.e. save on the network portion of the address).
620 aca->addr = aca->addr & aca->mask;
625 #endif /* def FEATURE_ACL */
628 /*********************************************************************
630 * Function : match_portlist
632 * Description : Check if a given number is covered by a comma
633 * separated list of numbers and ranges (a,b-c,d,..)
636 * 1 : portlist = String with list
637 * 2 : port = port to check
639 * Returns : 0 => no match
642 *********************************************************************/
643 int match_portlist(const char *portlist, int port)
645 char *min, *max, *next, *portlist_copy;
647 min = next = portlist_copy = strdup(portlist);
650 * Zero-terminate first item and remember offset for next
652 if (NULL != (next = strchr(portlist_copy, (int) ',')))
658 * Loop through all items, checking for match
662 if (NULL == (max = strchr(min, (int) '-')))
665 * No dash, check for equality
667 if (port == atoi(min))
676 * This is a range, so check if between min and max,
677 * or, if max was omitted, between min and 65K
680 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
694 * Zero-terminate next item and remember offset for n+1
696 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
708 /*********************************************************************
710 * Function : block_url
712 * Description : Called from `chat'. Check to see if we need to block this.
715 * 1 : csp = Current client state (buffers, headers, etc...)
717 * Returns : NULL => unblocked, else HTTP block response
719 *********************************************************************/
720 struct http_response *block_url(struct client_state *csp)
722 #ifdef FEATURE_IMAGE_BLOCKING
724 #endif /* def FEATURE_IMAGE_BLOCKING */
725 struct http_response *rsp;
728 * If it's not blocked, don't block it ;-)
730 if ((csp->action->flags & ACTION_BLOCK) == 0)
736 * Else, prepare a response
738 if (NULL == (rsp = alloc_http_response()))
740 return cgi_error_memory();
744 * If it's an image-url, send back an image or redirect
745 * as specified by the relevant +image action
747 #ifdef FEATURE_IMAGE_BLOCKING
748 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
751 /* determine HOW images should be blocked */
752 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
754 #if 1 /* Two alternative strategies, use this one for now: */
756 /* and handle accordingly: */
757 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
759 #ifdef FEATURE_ACTIVITY_CONSOLE
760 accumulate_stats(STATS_IMAGE_BLOCK, 1);
761 #endif /* def FEATURE_ACTIVITY_CONSOLE */
762 rsp->body = bindup(image_pattern_data, image_pattern_length);
763 if (rsp->body == NULL)
765 free_http_response(rsp);
766 return cgi_error_memory();
768 rsp->content_length = image_pattern_length;
770 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
772 free_http_response(rsp);
773 return cgi_error_memory();
777 else if (0 == strcmpic(p, "blank"))
779 #ifdef FEATURE_ACTIVITY_CONSOLE
780 accumulate_stats(STATS_IMAGE_BLOCK, 1);
781 #endif /* def FEATURE_ACTIVITY_CONSOLE */
782 rsp->body = bindup(image_blank_data, image_blank_length);
783 if (rsp->body == NULL)
785 free_http_response(rsp);
786 return cgi_error_memory();
788 rsp->content_length = image_blank_length;
790 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
792 free_http_response(rsp);
793 return cgi_error_memory();
797 else if (0 == strcmpic(p, "custom"))
799 rsp->body = bindup(csp->config->image_blocker_data, csp->config->image_blocker_length);
800 if (rsp->body == NULL)
802 free_http_response(rsp);
803 return cgi_error_memory();
805 rsp->content_length = csp->config->image_blocker_length;
807 if (enlist_unique_header(rsp->headers, "Content-Type", csp->config->image_blocker_format))
809 free_http_response(rsp);
810 return cgi_error_memory();
816 rsp->status = strdup("302 Local Redirect from Privoxy");
817 if (rsp->status == NULL)
819 free_http_response(rsp);
820 return cgi_error_memory();
823 if (enlist_unique_header(rsp->headers, "Location", p))
825 free_http_response(rsp);
826 return cgi_error_memory();
830 #else /* Following code is disabled for now */
832 /* and handle accordingly: */
833 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
835 p = CGI_PREFIX "send-banner?type=pattern";
837 else if (0 == strcmpic(p, "blank"))
839 p = CGI_PREFIX "send-banner?type=blank";
841 rsp->status = strdup("302 Local Redirect from Privoxy");
842 if (rsp->status == NULL)
844 free_http_response(rsp);
845 return cgi_error_memory();
848 if (enlist_unique_header(rsp->headers, "Location", p))
850 free_http_response(rsp);
851 return cgi_error_memory();
853 #endif /* Preceeding code is disabled for now */
856 #endif /* def FEATURE_IMAGE_BLOCKING */
859 * Else, generate an HTML "blocked" message:
863 struct map * exports;
866 * Workaround for stupid Netscape bug which prevents
867 * pages from being displayed if loading a referenced
868 * JavaScript or style sheet fails. So make it appear
869 * as if it succeeded.
871 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
872 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
873 && !strstr(p, "Gecko") /* save Mozilla, */
874 && !strstr(p, "compatible") /* MSIE */
875 && !strstr(p, "Opera")) /* and Opera. */
877 rsp->status = strdup("200 Request for blocked URL");
881 rsp->status = strdup("404 Request for blocked URL");
884 if (rsp->status == NULL)
886 free_http_response(rsp);
887 return cgi_error_memory();
890 exports = default_exports(csp, NULL);
893 free_http_response(rsp);
894 return cgi_error_memory();
897 #ifdef FEATURE_FORCE_LOAD
898 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
899 if (csp->http->ssl != 0)
900 #endif /* ndef FEATURE_FORCE_LOAD */
902 err = map_block_killer(exports, "force-support");
905 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
906 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
907 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
912 free_http_response(rsp);
913 return cgi_error_memory();
916 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
919 free_http_response(rsp);
920 return cgi_error_memory();
924 return finish_http_response(rsp);
930 /*********************************************************************
932 * Function : trust_url FIXME: I should be called distrust_url
934 * Description : Calls is_untrusted_url to determine if the URL is trusted
935 * and if not, returns a HTTP 304 response with a reject message.
938 * 1 : csp = Current client state (buffers, headers, etc...)
940 * Returns : NULL => trusted, else http_response.
942 *********************************************************************/
943 struct http_response *trust_url(struct client_state *csp)
945 struct http_response *rsp;
946 struct map * exports;
947 char buf[BUFFER_SIZE];
949 struct url_spec **tl;
954 * Don't bother to work on trusted URLs
956 if (!is_untrusted_url(csp))
962 * Else, prepare a response:
964 if (NULL == (rsp = alloc_http_response()))
966 return cgi_error_memory();
969 exports = default_exports(csp, NULL);
972 free_http_response(rsp);
973 return cgi_error_memory();
977 * Export the protocol, host, port, and referrer information
979 err = map(exports, "hostport", 1, csp->http->hostport, 1);
980 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
981 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
983 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
985 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
989 if (!err) err = map(exports, "referrer", 1, "unknown", 1);
995 free_http_response(rsp);
996 return cgi_error_memory();
1000 * Export the trust list
1003 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
1005 sprintf(buf, "<li>%s</li>\n", t->spec);
1006 string_append(&p, buf);
1008 err = map(exports, "trusted-referrers", 1, p, 0);
1013 free_http_response(rsp);
1014 return cgi_error_memory();
1018 * Export the trust info, if available
1020 if (csp->config->trust_info->first)
1022 struct list_entry *l;
1025 for (l = csp->config->trust_info->first; l ; l = l->next)
1027 sprintf(buf, "<li> <a href=\"%s\">%s</a><br>\n",l->str, l->str);
1028 string_append(&p, buf);
1030 err = map(exports, "trust-info", 1, p, 0);
1034 err = map_block_killer(exports, "have-trust-info");
1040 free_http_response(rsp);
1041 return cgi_error_memory();
1045 * Export the force prefix or the force conditional block killer
1047 #ifdef FEATURE_FORCE_LOAD
1048 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1049 #else /* ifndef FEATURE_FORCE_LOAD */
1050 err = map_block_killer(exports, "force-support");
1051 #endif /* ndef FEATURE_FORCE_LOAD */
1056 free_http_response(rsp);
1057 return cgi_error_memory();
1061 * Build the response
1063 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1066 free_http_response(rsp);
1067 return cgi_error_memory();
1070 return finish_http_response(rsp);
1072 #endif /* def FEATURE_TRUST */
1075 #ifdef FEATURE_FAST_REDIRECTS
1076 /*********************************************************************
1078 * Function : redirect_url
1080 * Description : Checks for redirection URLs and returns a HTTP redirect
1081 * to the destination URL, if necessary
1084 * 1 : csp = Current client state (buffers, headers, etc...)
1086 * Returns : NULL if URL was clean, HTTP redirect otherwise.
1088 *********************************************************************/
1089 struct http_response *redirect_url(struct client_state *csp)
1092 struct http_response *rsp;
1094 p = q = csp->http->path;
1095 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
1098 * find the last URL encoded in the request
1100 while ((p = strstr(p, "http://")) != NULL)
1106 * if there was any, generate and return a HTTP redirect
1108 if (q != csp->http->path)
1110 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
1112 if (NULL == (rsp = alloc_http_response()))
1114 return cgi_error_memory();
1117 if ( enlist_unique_header(rsp->headers, "Location", q)
1118 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1120 free_http_response(rsp);
1121 return cgi_error_memory();
1124 return finish_http_response(rsp);
1132 #endif /* def FEATURE_FAST_REDIRECTS */
1135 #ifdef FEATURE_IMAGE_BLOCKING
1136 /*********************************************************************
1138 * Function : is_imageurl
1140 * Description : Given a URL, decide whether it is an image or not,
1141 * using either the info from a previous +image action
1142 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1143 * is MSIE and not on a Mac, tell from the browser's accept
1147 * 1 : csp = Current client state (buffers, headers, etc...)
1149 * Returns : True (nonzero) if URL is an image, false (0)
1152 *********************************************************************/
1153 int is_imageurl(struct client_state *csp)
1155 #ifdef FEATURE_IMAGE_DETECT_MSIE
1158 tmp = get_header_value(csp->headers, "User-Agent:");
1159 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1161 tmp = get_header_value(csp->headers, "Accept:");
1162 if (tmp && strstr(tmp, "image/gif"))
1164 /* Client will accept HTML. If this seems counterintuitive,
1174 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1176 return ((csp->action->flags & ACTION_IMAGE) != 0);
1179 #endif /* def FEATURE_IMAGE_BLOCKING */
1182 #ifdef FEATURE_TRUST
1183 /*********************************************************************
1185 * Function : is_untrusted_url
1187 * Description : Should we "distrust" this URL (and block it)?
1189 * Yes if it matches a line in the trustfile, or if the
1190 * referrer matches a line starting with "+" in the
1195 * 1 : csp = Current client state (buffers, headers, etc...)
1197 * Returns : 0 => trusted, 1 => untrusted
1199 *********************************************************************/
1200 int is_untrusted_url(struct client_state *csp)
1202 struct file_list *fl;
1203 struct block_spec *b;
1204 struct url_spec **trusted_url;
1205 struct http_request rhttp[1];
1206 const char * referer;
1210 * If we don't have a trustlist, we trust everybody
1212 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1217 memset(rhttp, '\0', sizeof(*rhttp));
1220 * Do we trust the request URL itself?
1222 for (b = b->next; b ; b = b->next)
1224 if (url_match(b->url, csp->http))
1230 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1232 /* no referrer was supplied */
1238 * If not, do we maybe trust its referrer?
1240 err = parse_http_url(referer, rhttp, csp);
1246 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1248 if (url_match(*trusted_url, rhttp))
1250 /* if the URL's referrer is from a trusted referrer, then
1251 * add the target spec to the trustfile as an unblocked
1252 * domain and return NULL (which means it's OK).
1257 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1261 char * new_entry = strdup("~");
1263 string_append(&new_entry, csp->http->hostport);
1265 path = csp->http->path;
1266 if ( (path[0] == '/')
1268 && ((path_end = strchr(path + 2, '/')) != NULL))
1270 /* since this path points into a user's home space
1271 * be sure to include this spec in the trustfile.
1273 int path_len = path_end - path; /* save offset */
1274 path = strdup(path); /* Copy string */
1277 path_end = path + path_len; /* regenerate ptr to new buffer */
1278 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1280 string_join(&new_entry, path);
1283 if (new_entry != NULL)
1285 fprintf(fp, "%s\n", new_entry);
1290 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1291 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1301 #endif /* def FEATURE_TRUST */
1304 /*********************************************************************
1306 * Function : pcrs_filter_response
1308 * Description : Ecexute all text substitutions from all applying
1309 * +filter actions on the text buffer that's been accumulated
1310 * in csp->iob->buf. If this changes the contents, set
1311 * csp->content_length to the modified size and raise the
1312 * CSP_FLAG_MODIFIED flag.
1315 * 1 : csp = Current client state (buffers, headers, etc...)
1317 * Returns : a pointer to the (newly allocated) modified buffer.
1318 * or NULL if there were no hits or something went wrong
1320 *********************************************************************/
1321 char *pcrs_filter_response(struct client_state *csp)
1324 size_t size, prev_size;
1326 char *old_buf = csp->iob->cur, *new_buf = NULL;
1329 struct file_list *fl;
1330 struct re_filterfile_spec *b;
1331 struct list_entry *filtername;
1336 if (csp->iob->cur >= csp->iob->eod)
1340 size = csp->iob->eod - csp->iob->cur;
1342 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == fl->f) )
1344 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1349 * If the body has a "chunked" transfer-encoding,
1350 * get rid of it first, adjusting size and iob->eod
1352 if (csp->flags & CSP_FLAG_CHUNKED)
1354 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1355 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1359 csp->iob->eod = csp->iob->cur + size;
1360 csp->flags |= CSP_FLAG_MODIFIED;
1364 * For all applying +filter actions, look if a filter by that
1365 * name exists and if yes, execute it's pcrs_joblist on the
1368 for (b = fl->f; b; b = b->next)
1370 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1371 filtername ; filtername = filtername->next)
1373 if (strcmp(b->name, filtername->str) == 0)
1375 int current_hits = 0;
1377 if ( NULL == b->joblist )
1379 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1384 /* Apply all jobs from the joblist */
1385 for (job = b->joblist; NULL != job; job = job->next)
1387 current_hits += pcrs_execute(job, old_buf, size, &new_buf, &size);
1388 if (old_buf != csp->iob->cur) free(old_buf);
1392 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) with filter %s produced %d hits (new size %d).",
1393 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1395 hits += current_hits;
1401 * If there were no hits, destroy our copy and let
1402 * chat() use the original in csp->iob
1409 #ifdef FEATURE_ACTIVITY_CONSOLE
1411 accumulate_stats(STATS_FILTER, hits);
1412 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1414 csp->flags |= CSP_FLAG_MODIFIED;
1415 csp->content_length = size;
1423 /*********************************************************************
1425 * Function : gif_deanimate_response
1427 * Description : Deanimate the GIF image that has been accumulated in
1428 * csp->iob->buf, set csp->content_length to the modified
1429 * size and raise the CSP_FLAG_MODIFIED flag.
1432 * 1 : csp = Current client state (buffers, headers, etc...)
1434 * Returns : a pointer to the (newly allocated) modified buffer.
1435 * or NULL in case something went wrong.
1437 *********************************************************************/
1438 char *gif_deanimate_response(struct client_state *csp)
1440 struct binbuffer *in, *out;
1442 size_t size = csp->iob->eod - csp->iob->cur;
1445 * If the body has a "chunked" transfer-encoding,
1446 * get rid of it first, adjusting size and iob->eod
1448 if (csp->flags & CSP_FLAG_CHUNKED)
1450 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1451 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1455 csp->iob->eod = csp->iob->cur + size;
1456 csp->flags |= CSP_FLAG_MODIFIED;
1459 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1460 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1462 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1466 in->buffer = csp->iob->cur;
1469 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1471 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1478 if ((int)size == out->offset)
1480 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1484 #ifdef FEATURE_ACTIVITY_CONSOLE
1485 accumulate_stats(STATS_GIF_DEANIMATE, 1);
1486 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1487 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1489 csp->content_length = out->offset;
1490 csp->flags |= CSP_FLAG_MODIFIED;
1500 /*********************************************************************
1502 * Function : remove_chunked_transfer_coding
1504 * Description : In-situ remove the "chunked" transfer coding as defined
1505 * in rfc2616 from a buffer.
1508 * 1 : buffer = Pointer to the text buffer
1509 * 2 : size = Number of bytes to be processed
1511 * Returns : The new size, i.e. the number of bytes from buffer which
1512 * are occupied by the stripped body, or 0 in case something
1515 *********************************************************************/
1516 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1519 unsigned int chunksize = 0;
1520 char *from_p, *to_p;
1523 from_p = to_p = buffer;
1525 if (sscanf(buffer, "%x", &chunksize) != 1)
1527 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1531 while (chunksize > 0)
1533 if (NULL == (from_p = strstr(from_p, "\r\n")))
1535 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1539 if ((newsize += chunksize) >= size)
1541 log_error(LOG_LEVEL_ERROR, "Chunksize exceeds buffer in \"chunked\" transfer coding");
1546 memmove(to_p, from_p, (size_t) chunksize);
1547 to_p = buffer + newsize;
1548 from_p += chunksize + 2;
1550 if (sscanf(from_p, "%x", &chunksize) != 1)
1552 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1557 /* FIXME: Should this get its own loglevel? */
1558 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1564 /*********************************************************************
1566 * Function : url_actions
1568 * Description : Gets the actions for this URL.
1571 * 1 : http = http_request request for blocked URLs
1572 * 2 : csp = Current client state (buffers, headers, etc...)
1576 *********************************************************************/
1577 void url_actions(struct http_request *http,
1578 struct client_state *csp)
1580 struct file_list *fl;
1581 struct url_actions *b;
1584 init_current_action(csp->action);
1586 for (i = 0; i < MAX_ACTION_FILES; i++)
1588 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
1593 apply_url_actions(csp->action, http, b);
1600 /*********************************************************************
1602 * Function : apply_url_actions
1604 * Description : Applies a list of URL actions.
1607 * 1 : action = Destination.
1608 * 2 : http = Current URL
1609 * 3 : b = list of URL actions to apply
1613 *********************************************************************/
1614 void apply_url_actions(struct current_action_spec *action,
1615 struct http_request *http,
1616 struct url_actions *b)
1620 /* Should never happen */
1624 for (b = b->next; NULL != b; b = b->next)
1626 if (url_match(b->url, http))
1628 merge_current_action(action, b->action);
1634 /*********************************************************************
1636 * Function : forward_url
1638 * Description : Should we forward this to another proxy?
1641 * 1 : http = http_request request for current URL
1642 * 2 : csp = Current client state (buffers, headers, etc...)
1644 * Returns : Pointer to forwarding information.
1646 *********************************************************************/
1647 const struct forward_spec * forward_url(struct http_request *http,
1648 struct client_state *csp)
1650 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1651 struct forward_spec *fwd = csp->config->forward;
1660 if (url_match(fwd->url, http))