1 const char filters_rcs[] = "$Id: filters.c,v 1.58 2002/04/24 02:11:17 oes 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.58 2002/04/24 02:11:17 oes
42 * Jon's multiple AF patch: url_actions now evaluates rules
45 * Revision 1.57 2002/04/08 20:38:34 swa
48 * Revision 1.56 2002/04/05 15:51:24 oes
49 * - bugfix: error-pages now get correct request protocol
50 * - fix for invalid HTML in trust info
52 * Revision 1.55 2002/04/02 16:13:51 oes
53 * Fix: No "Go there anyway" for SSL
55 * Revision 1.54 2002/04/02 14:55:56 oes
56 * Bugfix: is_untrusted_url() now depends on FEATURE_TRUST, not FEATURE_COOKIE_JAR
58 * Revision 1.53 2002/03/26 22:29:54 swa
59 * we have a new homepage!
61 * Revision 1.52 2002/03/24 16:35:57 jongfoster
64 * Revision 1.51 2002/03/24 15:23:33 jongfoster
67 * Revision 1.50 2002/03/24 13:25:43 swa
68 * name change related issues
70 * Revision 1.49 2002/03/16 20:29:14 oes
73 * Revision 1.48 2002/03/13 20:25:34 oes
74 * Better logging for content filters
76 * Revision 1.47 2002/03/13 00:30:52 jongfoster
78 * Added option of always sending redirect for imageblock,
79 * currently disabled with #if 0.
81 * Revision 1.46 2002/03/12 01:42:49 oes
82 * Introduced modular filters
84 * Revision 1.45 2002/03/08 16:47:50 oes
85 * Added choice beween GIF and PNG built-in images
87 * Revision 1.44 2002/03/07 03:49:31 oes
88 * - Fixed compiler warnings etc
89 * - Changed built-in images from GIF to PNG
90 * (with regard to Unisys patent issue)
91 * - Added a 4x4 pattern PNG which is less intrusive
92 * than the logo but also clearly marks the deleted banners
94 * Revision 1.43 2002/01/22 23:51:59 jongfoster
95 * Replacing strsav() with the safer string_append().
97 * Adding missing html_encode() to error message generators. Where encoded
98 * and unencoded versions of a string were provided, removing the unencoded
101 * Revision 1.42 2002/01/17 21:00:32 jongfoster
102 * Moving all our URL and URL pattern parsing code to urlmatch.c.
104 * Using a single, simple url_match(pattern,url) function - rather than
105 * the 3-line match routine which was repeated all over the place.
107 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
109 * Using parse_http_url() to parse URLs without faking a HTTP
110 * request line for parse_http_request().
112 * Revision 1.41 2001/11/13 00:14:07 jongfoster
113 * Fixing stupid bug now I've figured out what || means.
114 * (It always returns 0 or 1, not one of it's paramaters.)
116 * Revision 1.40 2001/10/26 17:37:55 oes
117 * - Re-enabled Netscape 200/404 bug workaround in block_url():
118 * - Removed OS/2 special case
119 * - Made block_url() independant from sed() having been run
120 * - Made trust_url independant from sed() having been run
121 * - Made is_imageurl independant from sed() having been run.
122 * It now checks User-Agent: and Accept: by itself.
125 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
126 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
127 * threads to call select() simultaneously. So, it's time to do a real, live,
128 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
129 * (native). Both versions will work, but using __OS2__ offers multi-threading.
131 * Revision 1.38 2001/10/23 21:32:33 jongfoster
132 * Adding error-checking to selected functions
134 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
135 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
136 * filters.c. Added a FIXME in front of the offending code. I'll gladly
137 * put in a better/more robust fix for all parties if one is presented...
138 * It seems that just returning 200 instead of 404 would pretty much fix
139 * it for everyone, but I don't know all the history of the problem.
141 * Revision 1.36 2001/10/10 16:44:16 oes
142 * Added match_portlist function
144 * Revision 1.35 2001/10/07 15:41:23 oes
145 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
147 * New function remove_chunked_transfer_coding that strips chunked
148 * transfer coding to plain and is called by pcrs_filter_response
149 * and gif_deanimate_response if neccessary
151 * Improved handling of zero-change re_filter runs
153 * pcrs_filter_response and gif_deanimate_response now remove
154 * chunked transfer codeing before processing the body.
156 * Revision 1.34 2001/09/20 15:49:36 steudten
158 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
159 * See cgi.c fill_template().
161 * Revision 1.33 2001/09/16 17:05:14 jongfoster
162 * Removing unused #include showarg.h
164 * Revision 1.32 2001/09/16 13:21:27 jongfoster
165 * Changes to use new list functions.
167 * Revision 1.31 2001/09/16 11:38:02 jongfoster
168 * Splitting fill_template() into 2 functions:
169 * template_load() loads the file
170 * template_fill() performs the PCRS regexps.
171 * This is because the CGI edit interface has a "table row"
172 * template which is used many times in the page - this
173 * change means it's only loaded from disk once.
175 * Revision 1.30 2001/09/16 11:00:10 jongfoster
176 * New function alloc_http_response, for symmetry with free_http_response
178 * Revision 1.29 2001/09/13 23:32:40 jongfoster
179 * Moving image data to cgi.c rather than cgi.h
180 * Fixing a GPF under Win32 (and any other OS that protects global
181 * constants from being written to).
183 * Revision 1.28 2001/09/10 10:18:51 oes
184 * Silenced compiler warnings
186 * Revision 1.27 2001/08/05 16:06:20 jongfoster
187 * Modifiying "struct map" so that there are now separate header and
188 * "map_entry" structures. This means that functions which modify a
189 * map no longer need to return a pointer to the modified map.
190 * Also, it no longer reverses the order of the entries (which may be
191 * important with some advanced template substitutions).
193 * Revision 1.26 2001/07/30 22:08:36 jongfoster
194 * Tidying up #defines:
195 * - All feature #defines are now of the form FEATURE_xxx
196 * - Permanently turned off WIN_GUI_EDIT
197 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
199 * Revision 1.25 2001/07/26 10:09:46 oes
200 * Made browser detection a little less naive
202 * Revision 1.24 2001/07/25 17:22:51 oes
203 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
205 * Revision 1.23 2001/07/23 13:40:12 oes
206 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
208 * Revision 1.22 2001/07/18 12:29:34 oes
209 * - Made gif_deanimate_response respect
210 * csp->action->string[ACTION_STRING_DEANIMATE]
211 * - Logging cosmetics
213 * Revision 1.21 2001/07/13 13:59:53 oes
214 * - Introduced gif_deanimate_response which shares the
215 * generic content modification interface of pcrs_filter_response
216 * and acts as a wrapper to deanimate.c:gif_deanimate()
217 * - Renamed re_process_buffer to pcrs_filter_response
218 * - pcrs_filter_response now returns NULL on failiure
219 * - Removed all #ifdef PCRS
221 * Revision 1.20 2001/07/01 17:01:04 oes
222 * Added comments and missing return statement in is_untrusted_url()
224 * Revision 1.19 2001/06/29 21:45:41 oes
225 * Indentation, CRLF->LF, Tab-> Space
227 * Revision 1.18 2001/06/29 13:27:38 oes
228 * - Cleaned up, renamed and reorderd functions
229 * and improved comments
232 * - Ported to CGI platform. Now delivers
233 * http_response or NULL
234 * - Unified HTML and GIF generation (moved image detection
235 * and GIF generation here from jcc.c:chat())
236 * - Fixed HTTP status to:
237 * - 403 (Forbidden) for the "blocked" HTML message
238 * - 200 (OK) for GIF answers
239 * - 302 (Redirect) for redirect to GIF
242 * - Ported to CGI platform. Now delivers
243 * http_response or NULL
244 * - Separated detection of untrusted URL into
245 * (bool)is_untrusted_url
246 * - Added enforcement of untrusted requests
248 * - Moved redirect_url() from cgi.c to here
249 * and ported it to the CGI platform
251 * - Removed logentry from cancelled commit
253 * Revision 1.17 2001/06/09 10:55:28 jongfoster
254 * Changing BUFSIZ ==> BUFFER_SIZE
256 * Revision 1.16 2001/06/07 23:10:26 jongfoster
257 * Allowing unanchored domain patterns to back off and retry
258 * if they partially match. Optimized right-anchored patterns.
259 * Moving ACL and forward files into config file.
260 * Replacing struct gateway with struct forward_spec
262 * Revision 1.15 2001/06/03 19:12:00 oes
263 * extracted-CGI relevant stuff
265 * Revision 1.14 2001/06/01 10:30:55 oes
266 * Added optional left-anchoring to domaincmp
268 * Revision 1.13 2001/05/31 21:21:30 jongfoster
269 * Permissionsfile / actions file changes:
270 * - Changed "permission" to "action" throughout
271 * - changes to file format to allow string parameters
272 * - Moved helper functions to actions.c
274 * Revision 1.12 2001/05/31 17:35:20 oes
276 * - Enhanced domain part globbing with infix and prefix asterisk
277 * matching and optional unanchored operation
279 * Revision 1.11 2001/05/29 11:53:23 oes
280 * "See why" link added to "blocked" page
282 * Revision 1.10 2001/05/29 09:50:24 jongfoster
283 * Unified blocklist/imagelist/permissionslist.
284 * File format is still under discussion, but the internal changes
287 * Also modified interceptor behaviour:
288 * - We now intercept all URLs beginning with one of the following
289 * prefixes (and *only* these prefixes):
291 * * http://ijbswa.sf.net/config/
292 * * http://ijbswa.sourceforge.net/config/
293 * - New interceptors "home page" - go to http://i.j.b/ to see it.
294 * - Internal changes so that intercepted and fast redirect pages
295 * are not replaced with an image.
296 * - Interceptors now have the option to send a binary page direct
297 * to the client. (i.e. ijb-send-banner uses this)
298 * - Implemented show-url-info interceptor. (Which is why I needed
299 * the above interceptors changes - a typical URL is
300 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
301 * The previous mechanism would not have intercepted that, and
302 * if it had been intercepted then it then it would have replaced
305 * Revision 1.9 2001/05/27 22:17:04 oes
307 * - re_process_buffer no longer writes the modified buffer
308 * to the client, which was very ugly. It now returns the
309 * buffer, which it is then written by chat.
311 * - content_length now adjusts the Content-Length: header
312 * for modified documents rather than crunch()ing it.
313 * (Length info in csp->content_length, which is 0 for
314 * unmodified documents)
316 * - For this to work, sed() is called twice when filtering.
318 * Revision 1.8 2001/05/26 17:13:28 jongfoster
319 * Filled in a function comment.
321 * Revision 1.7 2001/05/26 15:26:15 jongfoster
322 * ACL feature now provides more security by immediately dropping
323 * connections from untrusted hosts.
325 * Revision 1.6 2001/05/26 00:28:36 jongfoster
326 * Automatic reloading of config file.
327 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
328 * Most of the global variables have been moved to a new
329 * struct configuration_spec, accessed through csp->config->globalname
330 * Most of the globals remaining are used by the Win32 GUI.
332 * Revision 1.5 2001/05/25 22:34:30 jongfoster
335 * Revision 1.4 2001/05/22 18:46:04 oes
337 * - Enabled filtering banners by size rather than URL
338 * by adding patterns that replace all standard banner
339 * sizes with the "Junkbuster" gif to the re_filterfile
341 * - Enabled filtering WebBugs by providing a pattern
342 * which kills all 1x1 images
344 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
345 * which is selected by the (nonstandard and therefore
346 * capital) letter 'U' in the option string.
347 * It causes the quantifiers to be ungreedy by default.
348 * Appending a ? turns back to greedy (!).
350 * - Added a new interceptor ijb-send-banner, which
351 * sends back the "Junkbuster" gif. Without imagelist or
352 * MSIE detection support, or if tinygif = 1, or the
353 * URL isn't recognized as an imageurl, a lame HTML
354 * explanation is sent instead.
356 * - Added new feature, which permits blocking remote
357 * script redirects and firing back a local redirect
359 * The feature is conditionally compiled, i.e. it
360 * can be disabled with --disable-fast-redirects,
361 * plus it must be activated by a "fast-redirects"
362 * line in the config file, has its own log level
363 * and of course wants to be displayed by show-proxy-args
364 * Note: Boy, all the #ifdefs in 1001 locations and
365 * all the fumbling with configure.in and acconfig.h
366 * were *way* more work than the feature itself :-(
368 * - Because a generic redirect template was needed for
369 * this, tinygif = 3 now uses the same.
371 * - Moved GIFs, and other static HTTP response templates
376 * - Removed some >400 CRs again (Jon, you really worked
379 * Revision 1.3 2001/05/20 16:44:47 jongfoster
380 * Removing last hardcoded Junkbusters.com URLs.
382 * Revision 1.2 2001/05/20 01:21:20 jongfoster
383 * Version 2.9.4 checkin.
384 * - Merged popupfile and cookiefile, and added control over PCRS
385 * filtering, in new "permissionsfile".
386 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
387 * file error you now get a message box (in the Win32 GUI) rather
388 * than the program exiting with no explanation.
389 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
391 * - Removed tabs from "config"
392 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
393 * - Bumped up version number.
395 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
396 * Initial import of version 2.9.3 source tree
399 *********************************************************************/
405 #include <sys/types.h>
414 #endif /* ndef __OS2__ */
415 #include <netinet/in.h>
417 #include <winsock2.h>
418 #endif /* ndef _WIN32 */
422 #endif /* def __OS2__ */
430 #include "jbsockets.h"
431 #include "miscutil.h"
435 #include "deanimate.h"
436 #include "urlmatch.h"
442 const char filters_h_rcs[] = FILTERS_H_VERSION;
444 /* Fix a problem with Solaris. There should be no effect on other
446 * Solaris's isspace() is a macro which uses it's argument directly
447 * as an array index. Therefore we need to make sure that high-bit
448 * characters generate +ve values, and ideally we also want to make
449 * the argument match the declared parameter type of "int".
451 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
455 /*********************************************************************
457 * Function : block_acl
459 * Description : Block this request?
460 * Decide yes or no based on ACL file.
463 * 1 : dst = The proxy or gateway address this is going to.
464 * Or NULL to check all possible targets.
465 * 2 : csp = Current client state (buffers, headers, etc...)
466 * Also includes the client IP address.
468 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
470 *********************************************************************/
471 int block_acl(struct access_control_addr *dst, struct client_state *csp)
473 struct access_control_list *acl = csp->config->acl;
475 /* if not using an access control list, then permit the connection */
481 /* search the list */
484 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
488 /* Just want to check if they have any access */
489 if (acl->action == ACL_PERMIT)
494 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
495 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
497 if (acl->action == ACL_PERMIT)
515 /*********************************************************************
517 * Function : acl_addr
519 * Description : Called from `load_config' to parse an ACL address.
522 * 1 : aspec = String specifying ACL address.
523 * 2 : aca = struct access_control_addr to fill in.
525 * Returns : 0 => Ok, everything else is an error.
527 *********************************************************************/
528 int acl_addr(char *aspec, struct access_control_addr *aca)
530 int i, masklength, port;
536 if ((p = strchr(aspec, '/')) != NULL)
540 if (ijb_isdigit(*p) == 0)
544 masklength = atoi(p);
547 if ((masklength < 0) || (masklength > 32))
552 if ((p = strchr(aspec, ':')) != NULL)
556 if (ijb_isdigit(*p) == 0)
565 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
567 if (aca->addr == INADDR_NONE)
572 /* build the netmask */
574 for (i=1; i <= masklength ; i++)
576 aca->mask |= (1 << (32 - i));
579 /* now mask off the host portion of the ip address
580 * (i.e. save on the network portion of the address).
582 aca->addr = aca->addr & aca->mask;
587 #endif /* def FEATURE_ACL */
590 /*********************************************************************
592 * Function : match_portlist
594 * Description : Check if a given number is covered by a comma
595 * separated list of numbers and ranges (a,b-c,d,..)
598 * 1 : portlist = String with list
599 * 2 : port = port to check
601 * Returns : 0 => no match
604 *********************************************************************/
605 int match_portlist(const char *portlist, int port)
607 char *min, *max, *next, *portlist_copy;
609 min = next = portlist_copy = strdup(portlist);
612 * Zero-terminate first item and remember offset for next
614 if (NULL != (next = strchr(portlist_copy, (int) ',')))
620 * Loop through all items, checking for match
624 if (NULL == (max = strchr(min, (int) '-')))
627 * No dash, check for equality
629 if (port == atoi(min))
638 * This is a range, so check if between min and max,
639 * or, if max was omitted, between min and 65K
642 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
656 * Zero-terminate next item and remember offset for n+1
658 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
670 /*********************************************************************
672 * Function : block_url
674 * Description : Called from `chat'. Check to see if we need to block this.
677 * 1 : csp = Current client state (buffers, headers, etc...)
679 * Returns : NULL => unblocked, else HTTP block response
681 *********************************************************************/
682 struct http_response *block_url(struct client_state *csp)
684 #ifdef FEATURE_IMAGE_BLOCKING
686 #endif /* def FEATURE_IMAGE_BLOCKING */
687 struct http_response *rsp;
690 * If it's not blocked, don't block it ;-)
692 if ((csp->action->flags & ACTION_BLOCK) == 0)
698 * Else, prepare a response
700 if (NULL == (rsp = alloc_http_response()))
702 return cgi_error_memory();
706 * If it's an image-url, send back an image or redirect
707 * as specified by the relevant +image action
709 #ifdef FEATURE_IMAGE_BLOCKING
710 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
713 /* determine HOW images should be blocked */
714 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
716 #if 1 /* Two alternative strategies, use this one for now: */
718 /* and handle accordingly: */
719 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
721 rsp->body = bindup(image_pattern_data, image_pattern_length);
722 if (rsp->body == NULL)
724 free_http_response(rsp);
725 return cgi_error_memory();
727 rsp->content_length = image_pattern_length;
729 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
731 free_http_response(rsp);
732 return cgi_error_memory();
736 else if (0 == strcmpic(p, "blank"))
738 rsp->body = bindup(image_blank_data, image_blank_length);
739 if (rsp->body == NULL)
741 free_http_response(rsp);
742 return cgi_error_memory();
744 rsp->content_length = image_blank_length;
746 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
748 free_http_response(rsp);
749 return cgi_error_memory();
755 rsp->status = strdup("302 Local Redirect from Privoxy");
756 if (rsp->status == NULL)
758 free_http_response(rsp);
759 return cgi_error_memory();
762 if (enlist_unique_header(rsp->headers, "Location", p))
764 free_http_response(rsp);
765 return cgi_error_memory();
769 #else /* Following code is disabled for now */
771 /* and handle accordingly: */
772 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
774 p = CGI_PREFIX "send-banner?type=pattern";
776 else if (0 == strcmpic(p, "blank"))
778 p = CGI_PREFIX "send-banner?type=blank";
780 rsp->status = strdup("302 Local Redirect from Privoxy");
781 if (rsp->status == NULL)
783 free_http_response(rsp);
784 return cgi_error_memory();
787 if (enlist_unique_header(rsp->headers, "Location", p))
789 free_http_response(rsp);
790 return cgi_error_memory();
792 #endif /* Preceeding code is disabled for now */
795 #endif /* def FEATURE_IMAGE_BLOCKING */
798 * Else, generate an HTML "blocked" message:
802 struct map * exports;
805 * Workaround for stupid Netscape bug which prevents
806 * pages from being displayed if loading a referenced
807 * JavaScript or style sheet fails. So make it appear
808 * as if it succeeded.
810 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
811 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
812 && !strstr(p, "Gecko") /* save Mozilla, */
813 && !strstr(p, "compatible") /* MSIE */
814 && !strstr(p, "Opera")) /* and Opera. */
816 rsp->status = strdup("200 Request for blocked URL");
820 rsp->status = strdup("404 Request for blocked URL");
823 if (rsp->status == NULL)
825 free_http_response(rsp);
826 return cgi_error_memory();
829 exports = default_exports(csp, NULL);
832 free_http_response(rsp);
833 return cgi_error_memory();
836 #ifdef FEATURE_FORCE_LOAD
837 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
838 if (csp->http->ssl != 0)
839 #endif /* ndef FEATURE_FORCE_LOAD */
841 err = map_block_killer(exports, "force-support");
844 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
845 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
846 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
851 free_http_response(rsp);
852 return cgi_error_memory();
855 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
858 free_http_response(rsp);
859 return cgi_error_memory();
863 return finish_http_response(rsp);
869 /*********************************************************************
871 * Function : trust_url FIXME: I should be called distrust_url
873 * Description : Calls is_untrusted_url to determine if the URL is trusted
874 * and if not, returns a HTTP 304 response with a reject message.
877 * 1 : csp = Current client state (buffers, headers, etc...)
879 * Returns : NULL => trusted, else http_response.
881 *********************************************************************/
882 struct http_response *trust_url(struct client_state *csp)
884 struct http_response *rsp;
885 struct map * exports;
886 char buf[BUFFER_SIZE];
888 struct url_spec **tl;
893 * Don't bother to work on trusted URLs
895 if (!is_untrusted_url(csp))
901 * Else, prepare a response:
903 if (NULL == (rsp = alloc_http_response()))
905 return cgi_error_memory();
908 exports = default_exports(csp, NULL);
911 free_http_response(rsp);
912 return cgi_error_memory();
916 * Export the protocol, host, port, and referrer information
918 err = map(exports, "hostport", 1, csp->http->hostport, 1);
919 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
920 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
922 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
924 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
928 if (!err) err = map(exports, "referrer", 1, "unknown", 1);
934 free_http_response(rsp);
935 return cgi_error_memory();
939 * Export the trust list
942 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
944 sprintf(buf, "<li>%s</li>\n", t->spec);
945 string_append(&p, buf);
947 err = map(exports, "trusted-referrers", 1, p, 0);
952 free_http_response(rsp);
953 return cgi_error_memory();
957 * Export the trust info, if available
959 if (csp->config->trust_info->first)
961 struct list_entry *l;
964 for (l = csp->config->trust_info->first; l ; l = l->next)
966 sprintf(buf, "<li> <a href=\"%s\">%s</a><br>\n",l->str, l->str);
967 string_append(&p, buf);
969 err = map(exports, "trust-info", 1, p, 0);
973 err = map_block_killer(exports, "have-trust-info");
979 free_http_response(rsp);
980 return cgi_error_memory();
984 * Export the force prefix or the force conditional block killer
986 #ifdef FEATURE_FORCE_LOAD
987 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
988 #else /* ifndef FEATURE_FORCE_LOAD */
989 err = map_block_killer(exports, "force-support");
990 #endif /* ndef FEATURE_FORCE_LOAD */
995 free_http_response(rsp);
996 return cgi_error_memory();
1000 * Build the response
1002 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
1005 free_http_response(rsp);
1006 return cgi_error_memory();
1009 return finish_http_response(rsp);
1011 #endif /* def FEATURE_TRUST */
1014 #ifdef FEATURE_FAST_REDIRECTS
1015 /*********************************************************************
1017 * Function : redirect_url
1019 * Description : Checks for redirection URLs and returns a HTTP redirect
1020 * to the destination URL, if necessary
1023 * 1 : csp = Current client state (buffers, headers, etc...)
1025 * Returns : NULL if URL was clean, HTTP redirect otherwise.
1027 *********************************************************************/
1028 struct http_response *redirect_url(struct client_state *csp)
1031 struct http_response *rsp;
1033 p = q = csp->http->path;
1034 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
1037 * find the last URL encoded in the request
1039 while ((p = strstr(p, "http://")) != NULL)
1045 * if there was any, generate and return a HTTP redirect
1047 if (q != csp->http->path)
1049 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
1051 if (NULL == (rsp = alloc_http_response()))
1053 return cgi_error_memory();
1056 if ( enlist_unique_header(rsp->headers, "Location", q)
1057 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1059 free_http_response(rsp);
1060 return cgi_error_memory();
1063 return finish_http_response(rsp);
1071 #endif /* def FEATURE_FAST_REDIRECTS */
1074 #ifdef FEATURE_IMAGE_BLOCKING
1075 /*********************************************************************
1077 * Function : is_imageurl
1079 * Description : Given a URL, decide whether it is an image or not,
1080 * using either the info from a previous +image action
1081 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
1082 * the browser's accept header.
1085 * 1 : csp = Current client state (buffers, headers, etc...)
1087 * Returns : True (nonzero) if URL is an image, false (0)
1090 *********************************************************************/
1091 int is_imageurl(struct client_state *csp)
1093 #ifdef FEATURE_IMAGE_DETECT_MSIE
1096 tmp = get_header_value(csp->headers, "User-Agent:");
1097 if (tmp && strstr(tmp, "MSIE"))
1099 tmp = get_header_value(csp->headers, "Accept:");
1100 if (tmp && strstr(tmp, "image/gif"))
1102 /* Client will accept HTML. If this seems counterintuitive,
1112 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1114 return ((csp->action->flags & ACTION_IMAGE) != 0);
1117 #endif /* def FEATURE_IMAGE_BLOCKING */
1120 #ifdef FEATURE_TRUST
1121 /*********************************************************************
1123 * Function : is_untrusted_url
1125 * Description : Should we "distrust" this URL (and block it)?
1127 * Yes if it matches a line in the trustfile, or if the
1128 * referrer matches a line starting with "+" in the
1133 * 1 : csp = Current client state (buffers, headers, etc...)
1135 * Returns : 0 => trusted, 1 => untrusted
1137 *********************************************************************/
1138 int is_untrusted_url(struct client_state *csp)
1140 struct file_list *fl;
1141 struct block_spec *b;
1142 struct url_spec **trusted_url;
1143 struct http_request rhttp[1];
1144 const char * referer;
1148 * If we don't have a trustlist, we trust everybody
1150 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1155 memset(rhttp, '\0', sizeof(*rhttp));
1158 * Do we trust the request URL itself?
1160 for (b = b->next; b ; b = b->next)
1162 if (url_match(b->url, csp->http))
1168 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1170 /* no referrer was supplied */
1176 * If not, do we maybe trust its referrer?
1178 err = parse_http_url(referer, rhttp, csp);
1184 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1186 if (url_match(*trusted_url, rhttp))
1188 /* if the URL's referrer is from a trusted referrer, then
1189 * add the target spec to the trustfile as an unblocked
1190 * domain and return NULL (which means it's OK).
1195 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1199 char * new_entry = strdup("~");
1201 string_append(&new_entry, csp->http->hostport);
1203 path = csp->http->path;
1204 if ( (path[0] == '/')
1206 && ((path_end = strchr(path + 2, '/')) != NULL))
1208 /* since this path points into a user's home space
1209 * be sure to include this spec in the trustfile.
1211 int path_len = path_end - path; /* save offset */
1212 path = strdup(path); /* Copy string */
1215 path_end = path + path_len; /* regenerate ptr to new buffer */
1216 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1218 string_join(&new_entry, path);
1221 if (new_entry != NULL)
1223 fprintf(fp, "%s\n", new_entry);
1228 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1229 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1239 #endif /* def FEATURE_TRUST */
1242 /*********************************************************************
1244 * Function : pcrs_filter_response
1246 * Description : Ecexute all text substitutions from all applying
1247 * +filter actions on the text buffer that's been accumulated
1248 * in csp->iob->buf. If this changes the contents, set
1249 * csp->content_length to the modified size and raise the
1250 * CSP_FLAG_MODIFIED flag.
1253 * 1 : csp = Current client state (buffers, headers, etc...)
1255 * Returns : a pointer to the (newly allocated) modified buffer.
1256 * or NULL if there were no hits or something went wrong
1258 *********************************************************************/
1259 char *pcrs_filter_response(struct client_state *csp)
1264 char *old = csp->iob->cur, *new = NULL;
1267 struct file_list *fl;
1268 struct re_filterfile_spec *b;
1269 struct list_entry *filtername;
1274 if (csp->iob->cur >= csp->iob->eod)
1278 size = csp->iob->eod - csp->iob->cur;
1280 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == fl->f) )
1282 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1287 * If the body has a "chunked" transfer-encoding,
1288 * get rid of it first, adjusting size and iob->eod
1290 if (csp->flags & CSP_FLAG_CHUNKED)
1292 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1293 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1297 csp->iob->eod = csp->iob->cur + size;
1298 csp->flags |= CSP_FLAG_MODIFIED;
1302 * For all applying +filter actions, look if a filter by that
1303 * name exists and if yes, execute it's pcrs_joblist on the
1306 for (b = fl->f; b; b = b->next)
1308 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1309 filtername ; filtername = filtername->next)
1311 if (strcmp(b->name, filtername->str) == 0)
1313 int current_hits = 0;
1315 if ( NULL == b->joblist )
1317 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1321 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) with filter %s...",
1322 csp->http->hostport, csp->http->path, size, b->name);
1324 /* Apply all jobs from the joblist */
1325 for (job = b->joblist; NULL != job; job = job->next)
1327 current_hits += pcrs_execute(job, old, size, &new, &size);
1328 if (old != csp->iob->cur) free(old);
1332 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1333 hits += current_hits;
1339 * If there were no hits, destroy our copy and let
1340 * chat() use the original in csp->iob
1348 csp->flags |= CSP_FLAG_MODIFIED;
1349 csp->content_length = size;
1357 /*********************************************************************
1359 * Function : gif_deanimate_response
1361 * Description : Deanimate the GIF image that has been accumulated in
1362 * csp->iob->buf, set csp->content_length to the modified
1363 * size and raise the CSP_FLAG_MODIFIED flag.
1366 * 1 : csp = Current client state (buffers, headers, etc...)
1368 * Returns : a pointer to the (newly allocated) modified buffer.
1369 * or NULL in case something went wrong.
1371 *********************************************************************/
1372 char *gif_deanimate_response(struct client_state *csp)
1374 struct binbuffer *in, *out;
1376 size_t size = csp->iob->eod - csp->iob->cur;
1379 * If the body has a "chunked" transfer-encoding,
1380 * get rid of it first, adjusting size and iob->eod
1382 if (csp->flags & CSP_FLAG_CHUNKED)
1384 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1385 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1389 csp->iob->eod = csp->iob->cur + size;
1390 csp->flags |= CSP_FLAG_MODIFIED;
1393 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1394 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1396 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1400 in->buffer = csp->iob->cur;
1403 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1405 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1412 if ((int)size == out->offset)
1414 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1418 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1420 csp->content_length = out->offset;
1421 csp->flags |= CSP_FLAG_MODIFIED;
1431 /*********************************************************************
1433 * Function : remove_chunked_transfer_coding
1435 * Description : In-situ remove the "chunked" transfer coding as defined
1436 * in rfc2616 from a buffer.
1439 * 1 : buffer = Pointer to the text buffer
1440 * 2 : size = Number of bytes to be processed
1442 * Returns : The new size, i.e. the number of bytes from buffer which
1443 * are occupied by the stripped body, or 0 in case something
1446 *********************************************************************/
1447 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1450 unsigned int chunksize = 0;
1451 char *from_p, *to_p;
1454 from_p = to_p = buffer;
1456 if (sscanf(buffer, "%x", &chunksize) != 1)
1458 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1462 while (chunksize > 0)
1464 if (NULL == (from_p = strstr(from_p, "\r\n")))
1466 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1469 newsize += chunksize;
1472 memmove(to_p, from_p, (size_t) chunksize);
1473 to_p = buffer + newsize;
1474 from_p += chunksize + 2;
1476 if (sscanf(from_p, "%x", &chunksize) != 1)
1478 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1483 /* FIXME: Should this get its own loglevel? */
1484 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1490 /*********************************************************************
1492 * Function : url_actions
1494 * Description : Gets the actions for this URL.
1497 * 1 : http = http_request request for blocked URLs
1498 * 2 : csp = Current client state (buffers, headers, etc...)
1502 *********************************************************************/
1503 void url_actions(struct http_request *http,
1504 struct client_state *csp)
1506 struct file_list *fl;
1507 struct url_actions *b;
1510 init_current_action(csp->action);
1512 for (i = 0; i < MAX_ACTION_FILES; i++)
1514 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
1519 apply_url_actions(csp->action, http, b);
1526 /*********************************************************************
1528 * Function : apply_url_actions
1530 * Description : Applies a list of URL actions.
1533 * 1 : action = Destination.
1534 * 2 : http = Current URL
1535 * 3 : b = list of URL actions to apply
1539 *********************************************************************/
1540 void apply_url_actions(struct current_action_spec *action,
1541 struct http_request *http,
1542 struct url_actions *b)
1546 /* Should never happen */
1550 for (b = b->next; NULL != b; b = b->next)
1552 if (url_match(b->url, http))
1554 merge_current_action(action, b->action);
1560 /*********************************************************************
1562 * Function : forward_url
1564 * Description : Should we forward this to another proxy?
1567 * 1 : http = http_request request for current URL
1568 * 2 : csp = Current client state (buffers, headers, etc...)
1570 * Returns : Pointer to forwarding information.
1572 *********************************************************************/
1573 const struct forward_spec * forward_url(struct http_request *http,
1574 struct client_state *csp)
1576 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1577 struct forward_spec *fwd = csp->config->forward;
1586 if (url_match(fwd->url, http))