1 const char filters_rcs[] = "$Id: filters.c,v 1.44 2002/03/07 03:49:31 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 * IJBSWA team. http://ijbswa.sourceforge.net
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.44 2002/03/07 03:49:31 oes
42 * - Fixed compiler warnings etc
43 * - Changed built-in images from GIF to PNG
44 * (with regard to Unisys patent issue)
45 * - Added a 4x4 pattern PNG which is less intrusive
46 * than the logo but also clearly marks the deleted banners
48 * Revision 1.43 2002/01/22 23:51:59 jongfoster
49 * Replacing strsav() with the safer string_append().
51 * Adding missing html_encode() to error message generators. Where encoded
52 * and unencoded versions of a string were provided, removing the unencoded
55 * Revision 1.42 2002/01/17 21:00:32 jongfoster
56 * Moving all our URL and URL pattern parsing code to urlmatch.c.
58 * Using a single, simple url_match(pattern,url) function - rather than
59 * the 3-line match routine which was repeated all over the place.
61 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
63 * Using parse_http_url() to parse URLs without faking a HTTP
64 * request line for parse_http_request().
66 * Revision 1.41 2001/11/13 00:14:07 jongfoster
67 * Fixing stupid bug now I've figured out what || means.
68 * (It always returns 0 or 1, not one of it's paramaters.)
70 * Revision 1.40 2001/10/26 17:37:55 oes
71 * - Re-enabled Netscape 200/404 bug workaround in block_url():
72 * - Removed OS/2 special case
73 * - Made block_url() independant from sed() having been run
74 * - Made trust_url independant from sed() having been run
75 * - Made is_imageurl independant from sed() having been run.
76 * It now checks User-Agent: and Accept: by itself.
79 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
80 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
81 * threads to call select() simultaneously. So, it's time to do a real, live,
82 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
83 * (native). Both versions will work, but using __OS2__ offers multi-threading.
85 * Revision 1.38 2001/10/23 21:32:33 jongfoster
86 * Adding error-checking to selected functions
88 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
89 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
90 * filters.c. Added a FIXME in front of the offending code. I'll gladly
91 * put in a better/more robust fix for all parties if one is presented...
92 * It seems that just returning 200 instead of 404 would pretty much fix
93 * it for everyone, but I don't know all the history of the problem.
95 * Revision 1.36 2001/10/10 16:44:16 oes
96 * Added match_portlist function
98 * Revision 1.35 2001/10/07 15:41:23 oes
99 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
101 * New function remove_chunked_transfer_coding that strips chunked
102 * transfer coding to plain and is called by pcrs_filter_response
103 * and gif_deanimate_response if neccessary
105 * Improved handling of zero-change re_filter runs
107 * pcrs_filter_response and gif_deanimate_response now remove
108 * chunked transfer codeing before processing the body.
110 * Revision 1.34 2001/09/20 15:49:36 steudten
112 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
113 * See cgi.c fill_template().
115 * Revision 1.33 2001/09/16 17:05:14 jongfoster
116 * Removing unused #include showarg.h
118 * Revision 1.32 2001/09/16 13:21:27 jongfoster
119 * Changes to use new list functions.
121 * Revision 1.31 2001/09/16 11:38:02 jongfoster
122 * Splitting fill_template() into 2 functions:
123 * template_load() loads the file
124 * template_fill() performs the PCRS regexps.
125 * This is because the CGI edit interface has a "table row"
126 * template which is used many times in the page - this
127 * change means it's only loaded from disk once.
129 * Revision 1.30 2001/09/16 11:00:10 jongfoster
130 * New function alloc_http_response, for symmetry with free_http_response
132 * Revision 1.29 2001/09/13 23:32:40 jongfoster
133 * Moving image data to cgi.c rather than cgi.h
134 * Fixing a GPF under Win32 (and any other OS that protects global
135 * constants from being written to).
137 * Revision 1.28 2001/09/10 10:18:51 oes
138 * Silenced compiler warnings
140 * Revision 1.27 2001/08/05 16:06:20 jongfoster
141 * Modifiying "struct map" so that there are now separate header and
142 * "map_entry" structures. This means that functions which modify a
143 * map no longer need to return a pointer to the modified map.
144 * Also, it no longer reverses the order of the entries (which may be
145 * important with some advanced template substitutions).
147 * Revision 1.26 2001/07/30 22:08:36 jongfoster
148 * Tidying up #defines:
149 * - All feature #defines are now of the form FEATURE_xxx
150 * - Permanently turned off WIN_GUI_EDIT
151 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
153 * Revision 1.25 2001/07/26 10:09:46 oes
154 * Made browser detection a little less naive
156 * Revision 1.24 2001/07/25 17:22:51 oes
157 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
159 * Revision 1.23 2001/07/23 13:40:12 oes
160 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
162 * Revision 1.22 2001/07/18 12:29:34 oes
163 * - Made gif_deanimate_response respect
164 * csp->action->string[ACTION_STRING_DEANIMATE]
165 * - Logging cosmetics
167 * Revision 1.21 2001/07/13 13:59:53 oes
168 * - Introduced gif_deanimate_response which shares the
169 * generic content modification interface of pcrs_filter_response
170 * and acts as a wrapper to deanimate.c:gif_deanimate()
171 * - Renamed re_process_buffer to pcrs_filter_response
172 * - pcrs_filter_response now returns NULL on failiure
173 * - Removed all #ifdef PCRS
175 * Revision 1.20 2001/07/01 17:01:04 oes
176 * Added comments and missing return statement in is_untrusted_url()
178 * Revision 1.19 2001/06/29 21:45:41 oes
179 * Indentation, CRLF->LF, Tab-> Space
181 * Revision 1.18 2001/06/29 13:27:38 oes
182 * - Cleaned up, renamed and reorderd functions
183 * and improved comments
186 * - Ported to CGI platform. Now delivers
187 * http_response or NULL
188 * - Unified HTML and GIF generation (moved image detection
189 * and GIF generation here from jcc.c:chat())
190 * - Fixed HTTP status to:
191 * - 403 (Forbidden) for the "blocked" HTML message
192 * - 200 (OK) for GIF answers
193 * - 302 (Redirect) for redirect to GIF
196 * - Ported to CGI platform. Now delivers
197 * http_response or NULL
198 * - Separated detection of untrusted URL into
199 * (bool)is_untrusted_url
200 * - Added enforcement of untrusted requests
202 * - Moved redirect_url() from cgi.c to here
203 * and ported it to the CGI platform
205 * - Removed logentry from cancelled commit
207 * Revision 1.17 2001/06/09 10:55:28 jongfoster
208 * Changing BUFSIZ ==> BUFFER_SIZE
210 * Revision 1.16 2001/06/07 23:10:26 jongfoster
211 * Allowing unanchored domain patterns to back off and retry
212 * if they partially match. Optimized right-anchored patterns.
213 * Moving ACL and forward files into config file.
214 * Replacing struct gateway with struct forward_spec
216 * Revision 1.15 2001/06/03 19:12:00 oes
217 * extracted-CGI relevant stuff
219 * Revision 1.14 2001/06/01 10:30:55 oes
220 * Added optional left-anchoring to domaincmp
222 * Revision 1.13 2001/05/31 21:21:30 jongfoster
223 * Permissionsfile / actions file changes:
224 * - Changed "permission" to "action" throughout
225 * - changes to file format to allow string parameters
226 * - Moved helper functions to actions.c
228 * Revision 1.12 2001/05/31 17:35:20 oes
230 * - Enhanced domain part globbing with infix and prefix asterisk
231 * matching and optional unanchored operation
233 * Revision 1.11 2001/05/29 11:53:23 oes
234 * "See why" link added to "blocked" page
236 * Revision 1.10 2001/05/29 09:50:24 jongfoster
237 * Unified blocklist/imagelist/permissionslist.
238 * File format is still under discussion, but the internal changes
241 * Also modified interceptor behaviour:
242 * - We now intercept all URLs beginning with one of the following
243 * prefixes (and *only* these prefixes):
245 * * http://ijbswa.sf.net/config/
246 * * http://ijbswa.sourceforge.net/config/
247 * - New interceptors "home page" - go to http://i.j.b/ to see it.
248 * - Internal changes so that intercepted and fast redirect pages
249 * are not replaced with an image.
250 * - Interceptors now have the option to send a binary page direct
251 * to the client. (i.e. ijb-send-banner uses this)
252 * - Implemented show-url-info interceptor. (Which is why I needed
253 * the above interceptors changes - a typical URL is
254 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
255 * The previous mechanism would not have intercepted that, and
256 * if it had been intercepted then it then it would have replaced
259 * Revision 1.9 2001/05/27 22:17:04 oes
261 * - re_process_buffer no longer writes the modified buffer
262 * to the client, which was very ugly. It now returns the
263 * buffer, which it is then written by chat.
265 * - content_length now adjusts the Content-Length: header
266 * for modified documents rather than crunch()ing it.
267 * (Length info in csp->content_length, which is 0 for
268 * unmodified documents)
270 * - For this to work, sed() is called twice when filtering.
272 * Revision 1.8 2001/05/26 17:13:28 jongfoster
273 * Filled in a function comment.
275 * Revision 1.7 2001/05/26 15:26:15 jongfoster
276 * ACL feature now provides more security by immediately dropping
277 * connections from untrusted hosts.
279 * Revision 1.6 2001/05/26 00:28:36 jongfoster
280 * Automatic reloading of config file.
281 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
282 * Most of the global variables have been moved to a new
283 * struct configuration_spec, accessed through csp->config->globalname
284 * Most of the globals remaining are used by the Win32 GUI.
286 * Revision 1.5 2001/05/25 22:34:30 jongfoster
289 * Revision 1.4 2001/05/22 18:46:04 oes
291 * - Enabled filtering banners by size rather than URL
292 * by adding patterns that replace all standard banner
293 * sizes with the "Junkbuster" gif to the re_filterfile
295 * - Enabled filtering WebBugs by providing a pattern
296 * which kills all 1x1 images
298 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
299 * which is selected by the (nonstandard and therefore
300 * capital) letter 'U' in the option string.
301 * It causes the quantifiers to be ungreedy by default.
302 * Appending a ? turns back to greedy (!).
304 * - Added a new interceptor ijb-send-banner, which
305 * sends back the "Junkbuster" gif. Without imagelist or
306 * MSIE detection support, or if tinygif = 1, or the
307 * URL isn't recognized as an imageurl, a lame HTML
308 * explanation is sent instead.
310 * - Added new feature, which permits blocking remote
311 * script redirects and firing back a local redirect
313 * The feature is conditionally compiled, i.e. it
314 * can be disabled with --disable-fast-redirects,
315 * plus it must be activated by a "fast-redirects"
316 * line in the config file, has its own log level
317 * and of course wants to be displayed by show-proxy-args
318 * Note: Boy, all the #ifdefs in 1001 locations and
319 * all the fumbling with configure.in and acconfig.h
320 * were *way* more work than the feature itself :-(
322 * - Because a generic redirect template was needed for
323 * this, tinygif = 3 now uses the same.
325 * - Moved GIFs, and other static HTTP response templates
330 * - Removed some >400 CRs again (Jon, you really worked
333 * Revision 1.3 2001/05/20 16:44:47 jongfoster
334 * Removing last hardcoded JunkBusters.com URLs.
336 * Revision 1.2 2001/05/20 01:21:20 jongfoster
337 * Version 2.9.4 checkin.
338 * - Merged popupfile and cookiefile, and added control over PCRS
339 * filtering, in new "permissionsfile".
340 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
341 * file error you now get a message box (in the Win32 GUI) rather
342 * than the program exiting with no explanation.
343 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
345 * - Removed tabs from "config"
346 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
347 * - Bumped up version number.
349 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
350 * Initial import of version 2.9.3 source tree
353 *********************************************************************/
359 #include <sys/types.h>
368 #endif /* ndef __OS2__ */
369 #include <netinet/in.h>
371 #include <winsock2.h>
372 #endif /* ndef _WIN32 */
376 #endif /* def __OS2__ */
384 #include "jbsockets.h"
385 #include "miscutil.h"
389 #include "deanimate.h"
390 #include "urlmatch.h"
396 const char filters_h_rcs[] = FILTERS_H_VERSION;
398 /* Fix a problem with Solaris. There should be no effect on other
400 * Solaris's isspace() is a macro which uses it's argument directly
401 * as an array index. Therefore we need to make sure that high-bit
402 * characters generate +ve values, and ideally we also want to make
403 * the argument match the declared parameter type of "int".
405 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
409 /*********************************************************************
411 * Function : block_acl
413 * Description : Block this request?
414 * Decide yes or no based on ACL file.
417 * 1 : dst = The proxy or gateway address this is going to.
418 * Or NULL to check all possible targets.
419 * 2 : csp = Current client state (buffers, headers, etc...)
420 * Also includes the client IP address.
422 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
424 *********************************************************************/
425 int block_acl(struct access_control_addr *dst, struct client_state *csp)
427 struct access_control_list *acl = csp->config->acl;
429 /* if not using an access control list, then permit the connection */
435 /* search the list */
438 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
442 /* Just want to check if they have any access */
443 if (acl->action == ACL_PERMIT)
448 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
449 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
451 if (acl->action == ACL_PERMIT)
469 /*********************************************************************
471 * Function : acl_addr
473 * Description : Called from `load_config' to parse an ACL address.
476 * 1 : aspec = String specifying ACL address.
477 * 2 : aca = struct access_control_addr to fill in.
479 * Returns : 0 => Ok, everything else is an error.
481 *********************************************************************/
482 int acl_addr(char *aspec, struct access_control_addr *aca)
484 int i, masklength, port;
490 if ((p = strchr(aspec, '/')))
494 if (ijb_isdigit(*p) == 0)
498 masklength = atoi(p);
501 if ((masklength < 0) || (masklength > 32))
506 if ((p = strchr(aspec, ':')))
510 if (ijb_isdigit(*p) == 0)
519 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
521 if (aca->addr == INADDR_NONE)
526 /* build the netmask */
528 for (i=1; i <= masklength ; i++)
530 aca->mask |= (1 << (32 - i));
533 /* now mask off the host portion of the ip address
534 * (i.e. save on the network portion of the address).
536 aca->addr = aca->addr & aca->mask;
541 #endif /* def FEATURE_ACL */
544 /*********************************************************************
546 * Function : match_portlist
548 * Description : Check if a given number is covered by a comma
549 * separated list of numbers and ranges (a,b-c,d,..)
552 * 1 : portlist = String with list
553 * 2 : port = port to check
555 * Returns : 0 => no match
558 *********************************************************************/
559 int match_portlist(const char *portlist, int port)
561 char *min, *max, *next, *portlist_copy;
563 min = next = portlist_copy = strdup(portlist);
566 * Zero-terminate first item and remember offset for next
568 if (NULL != (next = strchr(portlist_copy, (int) ',')))
574 * Loop through all items, checking for match
578 if (NULL == (max = strchr(min, (int) '-')))
581 * No dash, check for equality
583 if (port == atoi(min))
592 * This is a range, so check if between min and max,
593 * or, if max was omitted, between min and 65K
596 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
610 * Zero-terminate next item and remember offset for n+1
612 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
624 /*********************************************************************
626 * Function : block_url
628 * Description : Called from `chat'. Check to see if we need to block this.
631 * 1 : csp = Current client state (buffers, headers, etc...)
633 * Returns : NULL => unblocked, else HTTP block response
635 *********************************************************************/
636 struct http_response *block_url(struct client_state *csp)
638 #ifdef FEATURE_IMAGE_BLOCKING
640 #endif /* def FEATURE_IMAGE_BLOCKING */
641 struct http_response *rsp;
644 * If it's not blocked, don't block it ;-)
646 if ((csp->action->flags & ACTION_BLOCK) == 0)
652 * Else, prepare a response
654 if (NULL == (rsp = alloc_http_response()))
656 return cgi_error_memory();
660 * If it's an image-url, send back an image or redirect
661 * as specified by the relevant +image action
663 #ifdef FEATURE_IMAGE_BLOCKING
664 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
667 /* determine HOW images should be blocked */
668 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
670 /* and handle accordingly: */
671 if ((p == NULL) || (0 == strcmpic(p, "logo")))
673 rsp->body = bindup(image_logo_data, image_logo_length);
674 if (rsp->body == NULL)
676 free_http_response(rsp);
677 return cgi_error_memory();
679 rsp->content_length = image_logo_length;
681 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
683 free_http_response(rsp);
684 return cgi_error_memory();
688 else if (0 == strcmpic(p, "blank"))
690 rsp->body = bindup(image_blank_data, image_blank_length);
691 if (rsp->body == NULL)
693 free_http_response(rsp);
694 return cgi_error_memory();
696 rsp->content_length = image_blank_length;
698 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
700 free_http_response(rsp);
701 return cgi_error_memory();
705 else if (0 == strcmpic(p, "pattern"))
707 rsp->body = bindup(image_pattern_data, image_pattern_length);
708 if (rsp->body == NULL)
710 free_http_response(rsp);
711 return cgi_error_memory();
713 rsp->content_length = image_pattern_length;
715 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
717 free_http_response(rsp);
718 return cgi_error_memory();
724 rsp->status = strdup("302 Local Redirect from Junkbuster");
725 if (rsp->status == NULL)
727 free_http_response(rsp);
728 return cgi_error_memory();
731 if (enlist_unique_header(rsp->headers, "Location", p))
733 free_http_response(rsp);
734 return cgi_error_memory();
739 #endif /* def FEATURE_IMAGE_BLOCKING */
742 * Else, generate an HTML "blocked" message:
746 struct map * exports;
749 * Workaround for stupid Netscape bug which prevents
750 * pages from being displayed if loading a referenced
751 * JavaScript or style sheet fails. So make it appear
752 * as if it succeeded.
754 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
755 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
756 && !strstr(p, "Gecko") /* save Mozilla, */
757 && !strstr(p, "compatible") /* MSIE */
758 && !strstr(p, "Opera")) /* and Opera. */
760 rsp->status = strdup("200 Request for blocked URL");
764 rsp->status = strdup("404 Request for blocked URL");
767 if (rsp->status == NULL)
769 free_http_response(rsp);
770 return cgi_error_memory();
773 exports = default_exports(csp, NULL);
776 free_http_response(rsp);
777 return cgi_error_memory();
780 #ifdef FEATURE_FORCE_LOAD
781 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
782 #else /* ifndef FEATURE_FORCE_LOAD */
783 err = map_block_killer(exports, "force-support");
784 #endif /* ndef FEATURE_FORCE_LOAD */
786 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
787 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
792 free_http_response(rsp);
793 return cgi_error_memory();
796 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
799 free_http_response(rsp);
800 return cgi_error_memory();
804 return finish_http_response(rsp);
810 /*********************************************************************
812 * Function : trust_url FIXME: I should be called distrust_url
814 * Description : Calls is_untrusted_url to determine if the URL is trusted
815 * and if not, returns a HTTP 304 response with a reject message.
818 * 1 : csp = Current client state (buffers, headers, etc...)
820 * Returns : NULL => trusted, else http_response.
822 *********************************************************************/
823 struct http_response *trust_url(struct client_state *csp)
825 struct http_response *rsp;
826 struct map * exports;
827 char buf[BUFFER_SIZE];
829 struct url_spec **tl;
834 * Don't bother to work on trusted URLs
836 if (!is_untrusted_url(csp))
842 * Else, prepare a response:
844 if (NULL == (rsp = alloc_http_response()))
846 return cgi_error_memory();
849 exports = default_exports(csp, NULL);
852 free_http_response(rsp);
853 return cgi_error_memory();
857 * Export the host, port, and referrer information
859 err = map(exports, "hostport", 1, csp->http->hostport, 1);
860 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
862 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
864 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
868 if (!err) err = map(exports, "referrer", 1, "unknown", 1);
874 free_http_response(rsp);
875 return cgi_error_memory();
879 * Export the trust list
882 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
884 sprintf(buf, "<li>%s</li>\n", t->spec);
885 string_append(&p, buf);
887 err = map(exports, "trusted-referrers", 1, p, 0);
892 free_http_response(rsp);
893 return cgi_error_memory();
897 * Export the trust info, if available
899 if (csp->config->trust_info->first)
901 struct list_entry *l;
904 for (l = csp->config->trust_info->first; l ; l = l->next)
906 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
907 string_append(&p, buf);
909 err = map(exports, "trust-info", 1, p, 0);
913 err = map_block_killer(exports, "have-trust-info");
919 free_http_response(rsp);
920 return cgi_error_memory();
924 * Export the force prefix or the force conditional block killer
926 #ifdef FEATURE_FORCE_LOAD
927 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
928 #else /* ifndef FEATURE_FORCE_LOAD */
929 err = map_block_killer(exports, "force-support");
930 #endif /* ndef FEATURE_FORCE_LOAD */
935 free_http_response(rsp);
936 return cgi_error_memory();
942 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
945 free_http_response(rsp);
946 return cgi_error_memory();
949 return finish_http_response(rsp);
951 #endif /* def FEATURE_TRUST */
954 #ifdef FEATURE_FAST_REDIRECTS
955 /*********************************************************************
957 * Function : redirect_url
959 * Description : Checks for redirection URLs and returns a HTTP redirect
960 * to the destination URL, if necessary
963 * 1 : csp = Current client state (buffers, headers, etc...)
965 * Returns : NULL if URL was clean, HTTP redirect otherwise.
967 *********************************************************************/
968 struct http_response *redirect_url(struct client_state *csp)
971 struct http_response *rsp;
973 p = q = csp->http->path;
974 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
977 * find the last URL encoded in the request
979 while ((p = strstr(p, "http://")))
985 * if there was any, generate and return a HTTP redirect
987 if (q != csp->http->path)
989 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
991 if (NULL == (rsp = alloc_http_response()))
993 return cgi_error_memory();
996 if ( enlist_unique_header(rsp->headers, "Location", q)
997 || (NULL == (rsp->status = strdup("302 Local Redirect from Junkbuster"))) )
999 free_http_response(rsp);
1000 return cgi_error_memory();
1003 return finish_http_response(rsp);
1011 #endif /* def FEATURE_FAST_REDIRECTS */
1014 #ifdef FEATURE_IMAGE_BLOCKING
1015 /*********************************************************************
1017 * Function : is_imageurl
1019 * Description : Given a URL, decide whether it is an image or not,
1020 * using either the info from a previous +image action
1021 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
1022 * the browser's accept header.
1025 * 1 : csp = Current client state (buffers, headers, etc...)
1027 * Returns : True (nonzero) if URL is an image, false (0)
1030 *********************************************************************/
1031 int is_imageurl(struct client_state *csp)
1033 #ifdef FEATURE_IMAGE_DETECT_MSIE
1036 tmp = get_header_value(csp->headers, "User-Agent:");
1037 if (tmp && strstr(tmp, "MSIE"))
1039 tmp = get_header_value(csp->headers, "Accept:");
1040 if (tmp && strstr(tmp, "image/gif"))
1042 /* Client will accept HTML. If this seems counterintuitive,
1052 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1054 return ((csp->action->flags & ACTION_IMAGE) != 0);
1057 #endif /* def FEATURE_IMAGE_BLOCKING */
1060 #ifdef FEATURE_COOKIE_JAR
1061 /*********************************************************************
1063 * Function : is_untrusted_url
1065 * Description : Should we "distrust" this URL (and block it)?
1067 * Yes if it matches a line in the trustfile, or if the
1068 * referrer matches a line starting with "+" in the
1073 * 1 : csp = Current client state (buffers, headers, etc...)
1075 * Returns : 0 => trusted, 1 => untrusted
1077 *********************************************************************/
1078 int is_untrusted_url(struct client_state *csp)
1080 struct file_list *fl;
1081 struct block_spec *b;
1082 struct url_spec **trusted_url;
1083 struct http_request rhttp[1];
1084 const char * referer;
1088 * If we don't have a trustlist, we trust everybody
1090 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1095 memset(rhttp, '\0', sizeof(*rhttp));
1098 * Do we trust the request URL itself?
1100 for (b = b->next; b ; b = b->next)
1102 if (url_match(b->url, csp->http))
1108 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1110 /* no referrer was supplied */
1115 * If not, do we maybe trust its referrer?
1120 * Parse the URL from the referrer
1123 err = parse_http_url(referer, rhttp, csp);
1129 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1131 if (url_match(*trusted_url, rhttp))
1133 /* if the URL's referrer is from a trusted referrer, then
1134 * add the target spec to the trustfile as an unblocked
1135 * domain and return NULL (which means it's OK).
1140 if ((fp = fopen(csp->config->trustfile, "a")))
1144 char * new_entry = strdup("~");
1146 string_append(&new_entry, csp->http->hostport);
1148 path = csp->http->path;
1149 if ( (path[0] == '/')
1151 && ((path_end = strchr(path + 2, '/')) != NULL))
1153 /* since this path points into a user's home space
1154 * be sure to include this spec in the trustfile.
1156 int path_len = path_end - path; /* save offset */
1157 path = strdup(path); /* Copy string */
1160 path_end = path + path_len; /* regenerate ptr to new buffer */
1161 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1163 string_join(&new_entry, path);
1166 if (new_entry != NULL)
1168 fprintf(fp, "%s\n", new_entry);
1173 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1174 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1184 #endif /* def FEATURE_COOKIE_JAR */
1187 /*********************************************************************
1189 * Function : pcrs_filter_response
1191 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
1192 * to the text buffer that's been accumulated in
1193 * csp->iob->buf and set csp->content_length to the modified
1194 * size and raise the CSP_FLAG_MODIFIED flag if appropriate.
1197 * 1 : csp = Current client state (buffers, headers, etc...)
1199 * Returns : a pointer to the (newly allocated) modified buffer.
1200 * or NULL in case something went wrong
1202 *********************************************************************/
1203 char *pcrs_filter_response(struct client_state *csp)
1208 char *old = csp->iob->cur, *new = NULL;
1211 struct file_list *fl;
1212 struct re_filterfile_spec *b;
1215 if (csp->iob->cur >= csp->iob->eod)
1219 size = csp->iob->eod - csp->iob->cur;
1222 * If the body has a "chunked" transfer-encoding,
1223 * get rid of it first, adjusting size and iob->eod
1225 if (csp->flags & CSP_FLAG_CHUNKED)
1227 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1228 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1232 csp->iob->eod = csp->iob->cur + size;
1233 csp->flags |= CSP_FLAG_MODIFIED;
1236 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1238 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1242 if ( NULL == b->joblist )
1244 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1248 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1249 csp->http->hostport, csp->http->path, size);
1251 /* Apply all jobs from the joblist */
1252 for (job = b->joblist; NULL != job; job = job->next)
1254 hits += pcrs_execute(job, old, size, &new, &size);
1255 if (old != csp->iob->cur) free(old);
1259 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1262 * If there were no hits, destroy our copy and let
1263 * chat() use the original in csp->iob
1271 csp->flags |= CSP_FLAG_MODIFIED;
1272 csp->content_length = size;
1280 /*********************************************************************
1282 * Function : gif_deanimate_response
1284 * Description : Deanimate the GIF image that has been accumulated in
1285 * csp->iob->buf, set csp->content_length to the modified
1286 * size and raise the CSP_FLAG_MODIFIED flag.
1289 * 1 : csp = Current client state (buffers, headers, etc...)
1291 * Returns : a pointer to the (newly allocated) modified buffer.
1292 * or NULL in case something went wrong.
1294 *********************************************************************/
1295 char *gif_deanimate_response(struct client_state *csp)
1297 struct binbuffer *in, *out;
1299 size_t size = csp->iob->eod - csp->iob->cur;
1302 * If the body has a "chunked" transfer-encoding,
1303 * get rid of it first, adjusting size and iob->eod
1305 if (csp->flags & CSP_FLAG_CHUNKED)
1307 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1308 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1312 csp->iob->eod = csp->iob->cur + size;
1313 csp->flags |= CSP_FLAG_MODIFIED;
1316 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1317 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1319 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1323 in->buffer = csp->iob->cur;
1326 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1328 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1335 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1336 csp->content_length = out->offset;
1337 csp->flags |= CSP_FLAG_MODIFIED;
1347 /*********************************************************************
1349 * Function : remove_chunked_transfer_coding
1351 * Description : In-situ remove the "chunked" transfer coding as defined
1352 * in rfc2616 from a buffer.
1355 * 1 : buffer = Pointer to the text buffer
1356 * 2 : size = Number of bytes to be processed
1358 * Returns : The new size, i.e. the number of bytes from buffer which
1359 * are occupied by the stripped body, or 0 in case something
1362 *********************************************************************/
1363 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1366 unsigned int chunksize = 0;
1367 char *from_p, *to_p;
1370 from_p = to_p = buffer;
1372 if (sscanf(buffer, "%x", &chunksize) != 1)
1374 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1378 while (chunksize > 0)
1380 if (NULL == (from_p = strstr(from_p, "\r\n")))
1382 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1385 newsize += chunksize;
1388 memmove(to_p, from_p, (size_t) chunksize);
1389 to_p = buffer + newsize;
1390 from_p += chunksize + 2;
1392 if (sscanf(from_p, "%x", &chunksize) != 1)
1394 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1399 /* FIXME: Should this get its own loglevel? */
1400 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1406 /*********************************************************************
1408 * Function : url_actions
1410 * Description : Gets the actions for this URL.
1413 * 1 : http = http_request request for blocked URLs
1414 * 2 : csp = Current client state (buffers, headers, etc...)
1418 *********************************************************************/
1419 void url_actions(struct http_request *http,
1420 struct client_state *csp)
1422 struct file_list *fl;
1423 struct url_actions *b;
1425 init_current_action(csp->action);
1427 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1432 apply_url_actions(csp->action, http, b);
1437 /*********************************************************************
1439 * Function : apply_url_actions
1441 * Description : Applies a list of URL actions.
1444 * 1 : action = Destination.
1445 * 2 : http = Current URL
1446 * 3 : b = list of URL actions to apply
1450 *********************************************************************/
1451 void apply_url_actions(struct current_action_spec *action,
1452 struct http_request *http,
1453 struct url_actions *b)
1457 /* Should never happen */
1461 for (b = b->next; NULL != b; b = b->next)
1463 if (url_match(b->url, http))
1465 merge_current_action(action, b->action);
1471 /*********************************************************************
1473 * Function : forward_url
1475 * Description : Should we forward this to another proxy?
1478 * 1 : http = http_request request for current URL
1479 * 2 : csp = Current client state (buffers, headers, etc...)
1481 * Returns : Pointer to forwarding information.
1483 *********************************************************************/
1484 const struct forward_spec * forward_url(struct http_request *http,
1485 struct client_state *csp)
1487 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1488 struct forward_spec *fwd = csp->config->forward;
1497 if (url_match(fwd->url, http))