1 const char filters_rcs[] = "$Id: filters.c,v 1.53 2002/03/26 22:29:54 swa 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', 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 1.53 2002/03/26 22:29:54 swa
42 * we have a new homepage!
44 * Revision 1.52 2002/03/24 16:35:57 jongfoster
47 * Revision 1.51 2002/03/24 15:23:33 jongfoster
50 * Revision 1.50 2002/03/24 13:25:43 swa
51 * name change related issues
53 * Revision 1.49 2002/03/16 20:29:14 oes
56 * Revision 1.48 2002/03/13 20:25:34 oes
57 * Better logging for content filters
59 * Revision 1.47 2002/03/13 00:30:52 jongfoster
61 * Added option of always sending redirect for imageblock,
62 * currently disabled with #if 0.
64 * Revision 1.46 2002/03/12 01:42:49 oes
65 * Introduced modular filters
67 * Revision 1.45 2002/03/08 16:47:50 oes
68 * Added choice beween GIF and PNG built-in images
70 * Revision 1.44 2002/03/07 03:49:31 oes
71 * - Fixed compiler warnings etc
72 * - Changed built-in images from GIF to PNG
73 * (with regard to Unisys patent issue)
74 * - Added a 4x4 pattern PNG which is less intrusive
75 * than the logo but also clearly marks the deleted banners
77 * Revision 1.43 2002/01/22 23:51:59 jongfoster
78 * Replacing strsav() with the safer string_append().
80 * Adding missing html_encode() to error message generators. Where encoded
81 * and unencoded versions of a string were provided, removing the unencoded
84 * Revision 1.42 2002/01/17 21:00:32 jongfoster
85 * Moving all our URL and URL pattern parsing code to urlmatch.c.
87 * Using a single, simple url_match(pattern,url) function - rather than
88 * the 3-line match routine which was repeated all over the place.
90 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
92 * Using parse_http_url() to parse URLs without faking a HTTP
93 * request line for parse_http_request().
95 * Revision 1.41 2001/11/13 00:14:07 jongfoster
96 * Fixing stupid bug now I've figured out what || means.
97 * (It always returns 0 or 1, not one of it's paramaters.)
99 * Revision 1.40 2001/10/26 17:37:55 oes
100 * - Re-enabled Netscape 200/404 bug workaround in block_url():
101 * - Removed OS/2 special case
102 * - Made block_url() independant from sed() having been run
103 * - Made trust_url independant from sed() having been run
104 * - Made is_imageurl independant from sed() having been run.
105 * It now checks User-Agent: and Accept: by itself.
108 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
109 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
110 * threads to call select() simultaneously. So, it's time to do a real, live,
111 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
112 * (native). Both versions will work, but using __OS2__ offers multi-threading.
114 * Revision 1.38 2001/10/23 21:32:33 jongfoster
115 * Adding error-checking to selected functions
117 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
118 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
119 * filters.c. Added a FIXME in front of the offending code. I'll gladly
120 * put in a better/more robust fix for all parties if one is presented...
121 * It seems that just returning 200 instead of 404 would pretty much fix
122 * it for everyone, but I don't know all the history of the problem.
124 * Revision 1.36 2001/10/10 16:44:16 oes
125 * Added match_portlist function
127 * Revision 1.35 2001/10/07 15:41:23 oes
128 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
130 * New function remove_chunked_transfer_coding that strips chunked
131 * transfer coding to plain and is called by pcrs_filter_response
132 * and gif_deanimate_response if neccessary
134 * Improved handling of zero-change re_filter runs
136 * pcrs_filter_response and gif_deanimate_response now remove
137 * chunked transfer codeing before processing the body.
139 * Revision 1.34 2001/09/20 15:49:36 steudten
141 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
142 * See cgi.c fill_template().
144 * Revision 1.33 2001/09/16 17:05:14 jongfoster
145 * Removing unused #include showarg.h
147 * Revision 1.32 2001/09/16 13:21:27 jongfoster
148 * Changes to use new list functions.
150 * Revision 1.31 2001/09/16 11:38:02 jongfoster
151 * Splitting fill_template() into 2 functions:
152 * template_load() loads the file
153 * template_fill() performs the PCRS regexps.
154 * This is because the CGI edit interface has a "table row"
155 * template which is used many times in the page - this
156 * change means it's only loaded from disk once.
158 * Revision 1.30 2001/09/16 11:00:10 jongfoster
159 * New function alloc_http_response, for symmetry with free_http_response
161 * Revision 1.29 2001/09/13 23:32:40 jongfoster
162 * Moving image data to cgi.c rather than cgi.h
163 * Fixing a GPF under Win32 (and any other OS that protects global
164 * constants from being written to).
166 * Revision 1.28 2001/09/10 10:18:51 oes
167 * Silenced compiler warnings
169 * Revision 1.27 2001/08/05 16:06:20 jongfoster
170 * Modifiying "struct map" so that there are now separate header and
171 * "map_entry" structures. This means that functions which modify a
172 * map no longer need to return a pointer to the modified map.
173 * Also, it no longer reverses the order of the entries (which may be
174 * important with some advanced template substitutions).
176 * Revision 1.26 2001/07/30 22:08:36 jongfoster
177 * Tidying up #defines:
178 * - All feature #defines are now of the form FEATURE_xxx
179 * - Permanently turned off WIN_GUI_EDIT
180 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
182 * Revision 1.25 2001/07/26 10:09:46 oes
183 * Made browser detection a little less naive
185 * Revision 1.24 2001/07/25 17:22:51 oes
186 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
188 * Revision 1.23 2001/07/23 13:40:12 oes
189 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
191 * Revision 1.22 2001/07/18 12:29:34 oes
192 * - Made gif_deanimate_response respect
193 * csp->action->string[ACTION_STRING_DEANIMATE]
194 * - Logging cosmetics
196 * Revision 1.21 2001/07/13 13:59:53 oes
197 * - Introduced gif_deanimate_response which shares the
198 * generic content modification interface of pcrs_filter_response
199 * and acts as a wrapper to deanimate.c:gif_deanimate()
200 * - Renamed re_process_buffer to pcrs_filter_response
201 * - pcrs_filter_response now returns NULL on failiure
202 * - Removed all #ifdef PCRS
204 * Revision 1.20 2001/07/01 17:01:04 oes
205 * Added comments and missing return statement in is_untrusted_url()
207 * Revision 1.19 2001/06/29 21:45:41 oes
208 * Indentation, CRLF->LF, Tab-> Space
210 * Revision 1.18 2001/06/29 13:27:38 oes
211 * - Cleaned up, renamed and reorderd functions
212 * and improved comments
215 * - Ported to CGI platform. Now delivers
216 * http_response or NULL
217 * - Unified HTML and GIF generation (moved image detection
218 * and GIF generation here from jcc.c:chat())
219 * - Fixed HTTP status to:
220 * - 403 (Forbidden) for the "blocked" HTML message
221 * - 200 (OK) for GIF answers
222 * - 302 (Redirect) for redirect to GIF
225 * - Ported to CGI platform. Now delivers
226 * http_response or NULL
227 * - Separated detection of untrusted URL into
228 * (bool)is_untrusted_url
229 * - Added enforcement of untrusted requests
231 * - Moved redirect_url() from cgi.c to here
232 * and ported it to the CGI platform
234 * - Removed logentry from cancelled commit
236 * Revision 1.17 2001/06/09 10:55:28 jongfoster
237 * Changing BUFSIZ ==> BUFFER_SIZE
239 * Revision 1.16 2001/06/07 23:10:26 jongfoster
240 * Allowing unanchored domain patterns to back off and retry
241 * if they partially match. Optimized right-anchored patterns.
242 * Moving ACL and forward files into config file.
243 * Replacing struct gateway with struct forward_spec
245 * Revision 1.15 2001/06/03 19:12:00 oes
246 * extracted-CGI relevant stuff
248 * Revision 1.14 2001/06/01 10:30:55 oes
249 * Added optional left-anchoring to domaincmp
251 * Revision 1.13 2001/05/31 21:21:30 jongfoster
252 * Permissionsfile / actions file changes:
253 * - Changed "permission" to "action" throughout
254 * - changes to file format to allow string parameters
255 * - Moved helper functions to actions.c
257 * Revision 1.12 2001/05/31 17:35:20 oes
259 * - Enhanced domain part globbing with infix and prefix asterisk
260 * matching and optional unanchored operation
262 * Revision 1.11 2001/05/29 11:53:23 oes
263 * "See why" link added to "blocked" page
265 * Revision 1.10 2001/05/29 09:50:24 jongfoster
266 * Unified blocklist/imagelist/permissionslist.
267 * File format is still under discussion, but the internal changes
270 * Also modified interceptor behaviour:
271 * - We now intercept all URLs beginning with one of the following
272 * prefixes (and *only* these prefixes):
274 * * http://ijbswa.sf.net/config/
275 * * http://ijbswa.sourceforge.net/config/
276 * - New interceptors "home page" - go to http://i.j.b/ to see it.
277 * - Internal changes so that intercepted and fast redirect pages
278 * are not replaced with an image.
279 * - Interceptors now have the option to send a binary page direct
280 * to the client. (i.e. ijb-send-banner uses this)
281 * - Implemented show-url-info interceptor. (Which is why I needed
282 * the above interceptors changes - a typical URL is
283 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
284 * The previous mechanism would not have intercepted that, and
285 * if it had been intercepted then it then it would have replaced
288 * Revision 1.9 2001/05/27 22:17:04 oes
290 * - re_process_buffer no longer writes the modified buffer
291 * to the client, which was very ugly. It now returns the
292 * buffer, which it is then written by chat.
294 * - content_length now adjusts the Content-Length: header
295 * for modified documents rather than crunch()ing it.
296 * (Length info in csp->content_length, which is 0 for
297 * unmodified documents)
299 * - For this to work, sed() is called twice when filtering.
301 * Revision 1.8 2001/05/26 17:13:28 jongfoster
302 * Filled in a function comment.
304 * Revision 1.7 2001/05/26 15:26:15 jongfoster
305 * ACL feature now provides more security by immediately dropping
306 * connections from untrusted hosts.
308 * Revision 1.6 2001/05/26 00:28:36 jongfoster
309 * Automatic reloading of config file.
310 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
311 * Most of the global variables have been moved to a new
312 * struct configuration_spec, accessed through csp->config->globalname
313 * Most of the globals remaining are used by the Win32 GUI.
315 * Revision 1.5 2001/05/25 22:34:30 jongfoster
318 * Revision 1.4 2001/05/22 18:46:04 oes
320 * - Enabled filtering banners by size rather than URL
321 * by adding patterns that replace all standard banner
322 * sizes with the "Junkbuster" gif to the re_filterfile
324 * - Enabled filtering WebBugs by providing a pattern
325 * which kills all 1x1 images
327 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
328 * which is selected by the (nonstandard and therefore
329 * capital) letter 'U' in the option string.
330 * It causes the quantifiers to be ungreedy by default.
331 * Appending a ? turns back to greedy (!).
333 * - Added a new interceptor ijb-send-banner, which
334 * sends back the "Junkbuster" gif. Without imagelist or
335 * MSIE detection support, or if tinygif = 1, or the
336 * URL isn't recognized as an imageurl, a lame HTML
337 * explanation is sent instead.
339 * - Added new feature, which permits blocking remote
340 * script redirects and firing back a local redirect
342 * The feature is conditionally compiled, i.e. it
343 * can be disabled with --disable-fast-redirects,
344 * plus it must be activated by a "fast-redirects"
345 * line in the config file, has its own log level
346 * and of course wants to be displayed by show-proxy-args
347 * Note: Boy, all the #ifdefs in 1001 locations and
348 * all the fumbling with configure.in and acconfig.h
349 * were *way* more work than the feature itself :-(
351 * - Because a generic redirect template was needed for
352 * this, tinygif = 3 now uses the same.
354 * - Moved GIFs, and other static HTTP response templates
359 * - Removed some >400 CRs again (Jon, you really worked
362 * Revision 1.3 2001/05/20 16:44:47 jongfoster
363 * Removing last hardcoded JunkBusters.com URLs.
365 * Revision 1.2 2001/05/20 01:21:20 jongfoster
366 * Version 2.9.4 checkin.
367 * - Merged popupfile and cookiefile, and added control over PCRS
368 * filtering, in new "permissionsfile".
369 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
370 * file error you now get a message box (in the Win32 GUI) rather
371 * than the program exiting with no explanation.
372 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
374 * - Removed tabs from "config"
375 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
376 * - Bumped up version number.
378 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
379 * Initial import of version 2.9.3 source tree
382 *********************************************************************/
388 #include <sys/types.h>
397 #endif /* ndef __OS2__ */
398 #include <netinet/in.h>
400 #include <winsock2.h>
401 #endif /* ndef _WIN32 */
405 #endif /* def __OS2__ */
413 #include "jbsockets.h"
414 #include "miscutil.h"
418 #include "deanimate.h"
419 #include "urlmatch.h"
425 const char filters_h_rcs[] = FILTERS_H_VERSION;
427 /* Fix a problem with Solaris. There should be no effect on other
429 * Solaris's isspace() is a macro which uses it's argument directly
430 * as an array index. Therefore we need to make sure that high-bit
431 * characters generate +ve values, and ideally we also want to make
432 * the argument match the declared parameter type of "int".
434 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
438 /*********************************************************************
440 * Function : block_acl
442 * Description : Block this request?
443 * Decide yes or no based on ACL file.
446 * 1 : dst = The proxy or gateway address this is going to.
447 * Or NULL to check all possible targets.
448 * 2 : csp = Current client state (buffers, headers, etc...)
449 * Also includes the client IP address.
451 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
453 *********************************************************************/
454 int block_acl(struct access_control_addr *dst, struct client_state *csp)
456 struct access_control_list *acl = csp->config->acl;
458 /* if not using an access control list, then permit the connection */
464 /* search the list */
467 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
471 /* Just want to check if they have any access */
472 if (acl->action == ACL_PERMIT)
477 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
478 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
480 if (acl->action == ACL_PERMIT)
498 /*********************************************************************
500 * Function : acl_addr
502 * Description : Called from `load_config' to parse an ACL address.
505 * 1 : aspec = String specifying ACL address.
506 * 2 : aca = struct access_control_addr to fill in.
508 * Returns : 0 => Ok, everything else is an error.
510 *********************************************************************/
511 int acl_addr(char *aspec, struct access_control_addr *aca)
513 int i, masklength, port;
519 if ((p = strchr(aspec, '/')) != NULL)
523 if (ijb_isdigit(*p) == 0)
527 masklength = atoi(p);
530 if ((masklength < 0) || (masklength > 32))
535 if ((p = strchr(aspec, ':')) != NULL)
539 if (ijb_isdigit(*p) == 0)
548 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
550 if (aca->addr == INADDR_NONE)
555 /* build the netmask */
557 for (i=1; i <= masklength ; i++)
559 aca->mask |= (1 << (32 - i));
562 /* now mask off the host portion of the ip address
563 * (i.e. save on the network portion of the address).
565 aca->addr = aca->addr & aca->mask;
570 #endif /* def FEATURE_ACL */
573 /*********************************************************************
575 * Function : match_portlist
577 * Description : Check if a given number is covered by a comma
578 * separated list of numbers and ranges (a,b-c,d,..)
581 * 1 : portlist = String with list
582 * 2 : port = port to check
584 * Returns : 0 => no match
587 *********************************************************************/
588 int match_portlist(const char *portlist, int port)
590 char *min, *max, *next, *portlist_copy;
592 min = next = portlist_copy = strdup(portlist);
595 * Zero-terminate first item and remember offset for next
597 if (NULL != (next = strchr(portlist_copy, (int) ',')))
603 * Loop through all items, checking for match
607 if (NULL == (max = strchr(min, (int) '-')))
610 * No dash, check for equality
612 if (port == atoi(min))
621 * This is a range, so check if between min and max,
622 * or, if max was omitted, between min and 65K
625 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
639 * Zero-terminate next item and remember offset for n+1
641 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
653 /*********************************************************************
655 * Function : block_url
657 * Description : Called from `chat'. Check to see if we need to block this.
660 * 1 : csp = Current client state (buffers, headers, etc...)
662 * Returns : NULL => unblocked, else HTTP block response
664 *********************************************************************/
665 struct http_response *block_url(struct client_state *csp)
667 #ifdef FEATURE_IMAGE_BLOCKING
669 #endif /* def FEATURE_IMAGE_BLOCKING */
670 struct http_response *rsp;
673 * If it's not blocked, don't block it ;-)
675 if ((csp->action->flags & ACTION_BLOCK) == 0)
681 * Else, prepare a response
683 if (NULL == (rsp = alloc_http_response()))
685 return cgi_error_memory();
689 * If it's an image-url, send back an image or redirect
690 * as specified by the relevant +image action
692 #ifdef FEATURE_IMAGE_BLOCKING
693 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
696 /* determine HOW images should be blocked */
697 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
699 #if 1 /* Two alternative strategies, use this one for now: */
701 /* and handle accordingly: */
702 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
704 rsp->body = bindup(image_pattern_data, image_pattern_length);
705 if (rsp->body == NULL)
707 free_http_response(rsp);
708 return cgi_error_memory();
710 rsp->content_length = image_pattern_length;
712 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
714 free_http_response(rsp);
715 return cgi_error_memory();
719 else if (0 == strcmpic(p, "blank"))
721 rsp->body = bindup(image_blank_data, image_blank_length);
722 if (rsp->body == NULL)
724 free_http_response(rsp);
725 return cgi_error_memory();
727 rsp->content_length = image_blank_length;
729 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
731 free_http_response(rsp);
732 return cgi_error_memory();
738 rsp->status = strdup("302 Local Redirect from Privoxy");
739 if (rsp->status == NULL)
741 free_http_response(rsp);
742 return cgi_error_memory();
745 if (enlist_unique_header(rsp->headers, "Location", p))
747 free_http_response(rsp);
748 return cgi_error_memory();
752 #else /* Following code is disabled for now */
754 /* and handle accordingly: */
755 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
757 p = CGI_PREFIX "send-banner?type=pattern";
759 else if (0 == strcmpic(p, "blank"))
761 p = CGI_PREFIX "send-banner?type=blank";
763 rsp->status = strdup("302 Local Redirect from Privoxy");
764 if (rsp->status == NULL)
766 free_http_response(rsp);
767 return cgi_error_memory();
770 if (enlist_unique_header(rsp->headers, "Location", p))
772 free_http_response(rsp);
773 return cgi_error_memory();
775 #endif /* Preceeding code is disabled for now */
778 #endif /* def FEATURE_IMAGE_BLOCKING */
781 * Else, generate an HTML "blocked" message:
785 struct map * exports;
788 * Workaround for stupid Netscape bug which prevents
789 * pages from being displayed if loading a referenced
790 * JavaScript or style sheet fails. So make it appear
791 * as if it succeeded.
793 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
794 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
795 && !strstr(p, "Gecko") /* save Mozilla, */
796 && !strstr(p, "compatible") /* MSIE */
797 && !strstr(p, "Opera")) /* and Opera. */
799 rsp->status = strdup("200 Request for blocked URL");
803 rsp->status = strdup("404 Request for blocked URL");
806 if (rsp->status == NULL)
808 free_http_response(rsp);
809 return cgi_error_memory();
812 exports = default_exports(csp, NULL);
815 free_http_response(rsp);
816 return cgi_error_memory();
819 #ifdef FEATURE_FORCE_LOAD
820 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
821 #else /* ifndef FEATURE_FORCE_LOAD */
822 err = map_block_killer(exports, "force-support");
823 #endif /* ndef FEATURE_FORCE_LOAD */
825 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
826 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
831 free_http_response(rsp);
832 return cgi_error_memory();
835 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
838 free_http_response(rsp);
839 return cgi_error_memory();
843 return finish_http_response(rsp);
849 /*********************************************************************
851 * Function : trust_url FIXME: I should be called distrust_url
853 * Description : Calls is_untrusted_url to determine if the URL is trusted
854 * and if not, returns a HTTP 304 response with a reject message.
857 * 1 : csp = Current client state (buffers, headers, etc...)
859 * Returns : NULL => trusted, else http_response.
861 *********************************************************************/
862 struct http_response *trust_url(struct client_state *csp)
864 struct http_response *rsp;
865 struct map * exports;
866 char buf[BUFFER_SIZE];
868 struct url_spec **tl;
873 * Don't bother to work on trusted URLs
875 if (!is_untrusted_url(csp))
881 * Else, prepare a response:
883 if (NULL == (rsp = alloc_http_response()))
885 return cgi_error_memory();
888 exports = default_exports(csp, NULL);
891 free_http_response(rsp);
892 return cgi_error_memory();
896 * Export the host, port, and referrer information
898 err = map(exports, "hostport", 1, csp->http->hostport, 1);
899 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
901 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
903 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
907 if (!err) err = map(exports, "referrer", 1, "unknown", 1);
913 free_http_response(rsp);
914 return cgi_error_memory();
918 * Export the trust list
921 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
923 sprintf(buf, "<li>%s</li>\n", t->spec);
924 string_append(&p, buf);
926 err = map(exports, "trusted-referrers", 1, p, 0);
931 free_http_response(rsp);
932 return cgi_error_memory();
936 * Export the trust info, if available
938 if (csp->config->trust_info->first)
940 struct list_entry *l;
943 for (l = csp->config->trust_info->first; l ; l = l->next)
945 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
946 string_append(&p, buf);
948 err = map(exports, "trust-info", 1, p, 0);
952 err = map_block_killer(exports, "have-trust-info");
958 free_http_response(rsp);
959 return cgi_error_memory();
963 * Export the force prefix or the force conditional block killer
965 #ifdef FEATURE_FORCE_LOAD
966 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
967 #else /* ifndef FEATURE_FORCE_LOAD */
968 err = map_block_killer(exports, "force-support");
969 #endif /* ndef FEATURE_FORCE_LOAD */
974 free_http_response(rsp);
975 return cgi_error_memory();
981 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
984 free_http_response(rsp);
985 return cgi_error_memory();
988 return finish_http_response(rsp);
990 #endif /* def FEATURE_TRUST */
993 #ifdef FEATURE_FAST_REDIRECTS
994 /*********************************************************************
996 * Function : redirect_url
998 * Description : Checks for redirection URLs and returns a HTTP redirect
999 * to the destination URL, if necessary
1002 * 1 : csp = Current client state (buffers, headers, etc...)
1004 * Returns : NULL if URL was clean, HTTP redirect otherwise.
1006 *********************************************************************/
1007 struct http_response *redirect_url(struct client_state *csp)
1010 struct http_response *rsp;
1012 p = q = csp->http->path;
1013 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
1016 * find the last URL encoded in the request
1018 while ((p = strstr(p, "http://")) != NULL)
1024 * if there was any, generate and return a HTTP redirect
1026 if (q != csp->http->path)
1028 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
1030 if (NULL == (rsp = alloc_http_response()))
1032 return cgi_error_memory();
1035 if ( enlist_unique_header(rsp->headers, "Location", q)
1036 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1038 free_http_response(rsp);
1039 return cgi_error_memory();
1042 return finish_http_response(rsp);
1050 #endif /* def FEATURE_FAST_REDIRECTS */
1053 #ifdef FEATURE_IMAGE_BLOCKING
1054 /*********************************************************************
1056 * Function : is_imageurl
1058 * Description : Given a URL, decide whether it is an image or not,
1059 * using either the info from a previous +image action
1060 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
1061 * the browser's accept header.
1064 * 1 : csp = Current client state (buffers, headers, etc...)
1066 * Returns : True (nonzero) if URL is an image, false (0)
1069 *********************************************************************/
1070 int is_imageurl(struct client_state *csp)
1072 #ifdef FEATURE_IMAGE_DETECT_MSIE
1075 tmp = get_header_value(csp->headers, "User-Agent:");
1076 if (tmp && strstr(tmp, "MSIE"))
1078 tmp = get_header_value(csp->headers, "Accept:");
1079 if (tmp && strstr(tmp, "image/gif"))
1081 /* Client will accept HTML. If this seems counterintuitive,
1091 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1093 return ((csp->action->flags & ACTION_IMAGE) != 0);
1096 #endif /* def FEATURE_IMAGE_BLOCKING */
1099 #ifdef FEATURE_TRUST
1100 /*********************************************************************
1102 * Function : is_untrusted_url
1104 * Description : Should we "distrust" this URL (and block it)?
1106 * Yes if it matches a line in the trustfile, or if the
1107 * referrer matches a line starting with "+" in the
1112 * 1 : csp = Current client state (buffers, headers, etc...)
1114 * Returns : 0 => trusted, 1 => untrusted
1116 *********************************************************************/
1117 int is_untrusted_url(struct client_state *csp)
1119 struct file_list *fl;
1120 struct block_spec *b;
1121 struct url_spec **trusted_url;
1122 struct http_request rhttp[1];
1123 const char * referer;
1127 * If we don't have a trustlist, we trust everybody
1129 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1134 memset(rhttp, '\0', sizeof(*rhttp));
1137 * Do we trust the request URL itself?
1139 for (b = b->next; b ; b = b->next)
1141 if (url_match(b->url, csp->http))
1147 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1149 /* no referrer was supplied */
1155 * If not, do we maybe trust its referrer?
1157 err = parse_http_url(referer, rhttp, csp);
1163 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1165 if (url_match(*trusted_url, rhttp))
1167 /* if the URL's referrer is from a trusted referrer, then
1168 * add the target spec to the trustfile as an unblocked
1169 * domain and return NULL (which means it's OK).
1174 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1178 char * new_entry = strdup("~");
1180 string_append(&new_entry, csp->http->hostport);
1182 path = csp->http->path;
1183 if ( (path[0] == '/')
1185 && ((path_end = strchr(path + 2, '/')) != NULL))
1187 /* since this path points into a user's home space
1188 * be sure to include this spec in the trustfile.
1190 int path_len = path_end - path; /* save offset */
1191 path = strdup(path); /* Copy string */
1194 path_end = path + path_len; /* regenerate ptr to new buffer */
1195 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1197 string_join(&new_entry, path);
1200 if (new_entry != NULL)
1202 fprintf(fp, "%s\n", new_entry);
1207 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1208 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1218 #endif /* def FEATURE_TRUST */
1221 /*********************************************************************
1223 * Function : pcrs_filter_response
1225 * Description : Ecexute all text substitutions from all applying
1226 * +filter actions on the text buffer that's been accumulated
1227 * in csp->iob->buf. If this changes the contents, set
1228 * csp->content_length to the modified size and raise the
1229 * CSP_FLAG_MODIFIED flag.
1232 * 1 : csp = Current client state (buffers, headers, etc...)
1234 * Returns : a pointer to the (newly allocated) modified buffer.
1235 * or NULL if there were no hits or something went wrong
1237 *********************************************************************/
1238 char *pcrs_filter_response(struct client_state *csp)
1243 char *old = csp->iob->cur, *new = NULL;
1246 struct file_list *fl;
1247 struct re_filterfile_spec *b;
1248 struct list_entry *filtername;
1253 if (csp->iob->cur >= csp->iob->eod)
1257 size = csp->iob->eod - csp->iob->cur;
1259 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == fl->f) )
1261 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1266 * If the body has a "chunked" transfer-encoding,
1267 * get rid of it first, adjusting size and iob->eod
1269 if (csp->flags & CSP_FLAG_CHUNKED)
1271 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1272 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1276 csp->iob->eod = csp->iob->cur + size;
1277 csp->flags |= CSP_FLAG_MODIFIED;
1281 * For all applying +filter actions, look if a filter by that
1282 * name exists and if yes, execute it's pcrs_joblist on the
1285 for (b = fl->f; b; b = b->next)
1287 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1288 filtername ; filtername = filtername->next)
1290 if (strcmp(b->name, filtername->str) == 0)
1292 int current_hits = 0;
1294 if ( NULL == b->joblist )
1296 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1300 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) with filter %s...",
1301 csp->http->hostport, csp->http->path, size, b->name);
1303 /* Apply all jobs from the joblist */
1304 for (job = b->joblist; NULL != job; job = job->next)
1306 current_hits += pcrs_execute(job, old, size, &new, &size);
1307 if (old != csp->iob->cur) free(old);
1311 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1312 hits += current_hits;
1318 * If there were no hits, destroy our copy and let
1319 * chat() use the original in csp->iob
1327 csp->flags |= CSP_FLAG_MODIFIED;
1328 csp->content_length = size;
1336 /*********************************************************************
1338 * Function : gif_deanimate_response
1340 * Description : Deanimate the GIF image that has been accumulated in
1341 * csp->iob->buf, set csp->content_length to the modified
1342 * size and raise the CSP_FLAG_MODIFIED flag.
1345 * 1 : csp = Current client state (buffers, headers, etc...)
1347 * Returns : a pointer to the (newly allocated) modified buffer.
1348 * or NULL in case something went wrong.
1350 *********************************************************************/
1351 char *gif_deanimate_response(struct client_state *csp)
1353 struct binbuffer *in, *out;
1355 size_t size = csp->iob->eod - csp->iob->cur;
1358 * If the body has a "chunked" transfer-encoding,
1359 * get rid of it first, adjusting size and iob->eod
1361 if (csp->flags & CSP_FLAG_CHUNKED)
1363 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1364 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1368 csp->iob->eod = csp->iob->cur + size;
1369 csp->flags |= CSP_FLAG_MODIFIED;
1372 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1373 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1375 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1379 in->buffer = csp->iob->cur;
1382 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1384 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1391 if ((int)size == out->offset)
1393 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1397 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1399 csp->content_length = out->offset;
1400 csp->flags |= CSP_FLAG_MODIFIED;
1410 /*********************************************************************
1412 * Function : remove_chunked_transfer_coding
1414 * Description : In-situ remove the "chunked" transfer coding as defined
1415 * in rfc2616 from a buffer.
1418 * 1 : buffer = Pointer to the text buffer
1419 * 2 : size = Number of bytes to be processed
1421 * Returns : The new size, i.e. the number of bytes from buffer which
1422 * are occupied by the stripped body, or 0 in case something
1425 *********************************************************************/
1426 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1429 unsigned int chunksize = 0;
1430 char *from_p, *to_p;
1433 from_p = to_p = buffer;
1435 if (sscanf(buffer, "%x", &chunksize) != 1)
1437 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1441 while (chunksize > 0)
1443 if (NULL == (from_p = strstr(from_p, "\r\n")))
1445 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1448 newsize += chunksize;
1451 memmove(to_p, from_p, (size_t) chunksize);
1452 to_p = buffer + newsize;
1453 from_p += chunksize + 2;
1455 if (sscanf(from_p, "%x", &chunksize) != 1)
1457 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1462 /* FIXME: Should this get its own loglevel? */
1463 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1469 /*********************************************************************
1471 * Function : url_actions
1473 * Description : Gets the actions for this URL.
1476 * 1 : http = http_request request for blocked URLs
1477 * 2 : csp = Current client state (buffers, headers, etc...)
1481 *********************************************************************/
1482 void url_actions(struct http_request *http,
1483 struct client_state *csp)
1485 struct file_list *fl;
1486 struct url_actions *b;
1488 init_current_action(csp->action);
1490 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1495 apply_url_actions(csp->action, http, b);
1500 /*********************************************************************
1502 * Function : apply_url_actions
1504 * Description : Applies a list of URL actions.
1507 * 1 : action = Destination.
1508 * 2 : http = Current URL
1509 * 3 : b = list of URL actions to apply
1513 *********************************************************************/
1514 void apply_url_actions(struct current_action_spec *action,
1515 struct http_request *http,
1516 struct url_actions *b)
1520 /* Should never happen */
1524 for (b = b->next; NULL != b; b = b->next)
1526 if (url_match(b->url, http))
1528 merge_current_action(action, b->action);
1534 /*********************************************************************
1536 * Function : forward_url
1538 * Description : Should we forward this to another proxy?
1541 * 1 : http = http_request request for current URL
1542 * 2 : csp = Current client state (buffers, headers, etc...)
1544 * Returns : Pointer to forwarding information.
1546 *********************************************************************/
1547 const struct forward_spec * forward_url(struct http_request *http,
1548 struct client_state *csp)
1550 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1551 struct forward_spec *fwd = csp->config->forward;
1560 if (url_match(fwd->url, http))