1 const char filters_rcs[] = "$Id: filters.c,v 1.43 2002/01/22 23:51:59 jongfoster 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.43 2002/01/22 23:51:59 jongfoster
42 * Replacing strsav() with the safer string_append().
44 * Adding missing html_encode() to error message generators. Where encoded
45 * and unencoded versions of a string were provided, removing the unencoded
48 * Revision 1.42 2002/01/17 21:00:32 jongfoster
49 * Moving all our URL and URL pattern parsing code to urlmatch.c.
51 * Using a single, simple url_match(pattern,url) function - rather than
52 * the 3-line match routine which was repeated all over the place.
54 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
56 * Using parse_http_url() to parse URLs without faking a HTTP
57 * request line for parse_http_request().
59 * Revision 1.41 2001/11/13 00:14:07 jongfoster
60 * Fixing stupid bug now I've figured out what || means.
61 * (It always returns 0 or 1, not one of it's paramaters.)
63 * Revision 1.40 2001/10/26 17:37:55 oes
64 * - Re-enabled Netscape 200/404 bug workaround in block_url():
65 * - Removed OS/2 special case
66 * - Made block_url() independant from sed() having been run
67 * - Made trust_url independant from sed() having been run
68 * - Made is_imageurl independant from sed() having been run.
69 * It now checks User-Agent: and Accept: by itself.
72 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
73 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
74 * threads to call select() simultaneously. So, it's time to do a real, live,
75 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
76 * (native). Both versions will work, but using __OS2__ offers multi-threading.
78 * Revision 1.38 2001/10/23 21:32:33 jongfoster
79 * Adding error-checking to selected functions
81 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
82 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
83 * filters.c. Added a FIXME in front of the offending code. I'll gladly
84 * put in a better/more robust fix for all parties if one is presented...
85 * It seems that just returning 200 instead of 404 would pretty much fix
86 * it for everyone, but I don't know all the history of the problem.
88 * Revision 1.36 2001/10/10 16:44:16 oes
89 * Added match_portlist function
91 * Revision 1.35 2001/10/07 15:41:23 oes
92 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
94 * New function remove_chunked_transfer_coding that strips chunked
95 * transfer coding to plain and is called by pcrs_filter_response
96 * and gif_deanimate_response if neccessary
98 * Improved handling of zero-change re_filter runs
100 * pcrs_filter_response and gif_deanimate_response now remove
101 * chunked transfer codeing before processing the body.
103 * Revision 1.34 2001/09/20 15:49:36 steudten
105 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
106 * See cgi.c fill_template().
108 * Revision 1.33 2001/09/16 17:05:14 jongfoster
109 * Removing unused #include showarg.h
111 * Revision 1.32 2001/09/16 13:21:27 jongfoster
112 * Changes to use new list functions.
114 * Revision 1.31 2001/09/16 11:38:02 jongfoster
115 * Splitting fill_template() into 2 functions:
116 * template_load() loads the file
117 * template_fill() performs the PCRS regexps.
118 * This is because the CGI edit interface has a "table row"
119 * template which is used many times in the page - this
120 * change means it's only loaded from disk once.
122 * Revision 1.30 2001/09/16 11:00:10 jongfoster
123 * New function alloc_http_response, for symmetry with free_http_response
125 * Revision 1.29 2001/09/13 23:32:40 jongfoster
126 * Moving image data to cgi.c rather than cgi.h
127 * Fixing a GPF under Win32 (and any other OS that protects global
128 * constants from being written to).
130 * Revision 1.28 2001/09/10 10:18:51 oes
131 * Silenced compiler warnings
133 * Revision 1.27 2001/08/05 16:06:20 jongfoster
134 * Modifiying "struct map" so that there are now separate header and
135 * "map_entry" structures. This means that functions which modify a
136 * map no longer need to return a pointer to the modified map.
137 * Also, it no longer reverses the order of the entries (which may be
138 * important with some advanced template substitutions).
140 * Revision 1.26 2001/07/30 22:08:36 jongfoster
141 * Tidying up #defines:
142 * - All feature #defines are now of the form FEATURE_xxx
143 * - Permanently turned off WIN_GUI_EDIT
144 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
146 * Revision 1.25 2001/07/26 10:09:46 oes
147 * Made browser detection a little less naive
149 * Revision 1.24 2001/07/25 17:22:51 oes
150 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
152 * Revision 1.23 2001/07/23 13:40:12 oes
153 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
155 * Revision 1.22 2001/07/18 12:29:34 oes
156 * - Made gif_deanimate_response respect
157 * csp->action->string[ACTION_STRING_DEANIMATE]
158 * - Logging cosmetics
160 * Revision 1.21 2001/07/13 13:59:53 oes
161 * - Introduced gif_deanimate_response which shares the
162 * generic content modification interface of pcrs_filter_response
163 * and acts as a wrapper to deanimate.c:gif_deanimate()
164 * - Renamed re_process_buffer to pcrs_filter_response
165 * - pcrs_filter_response now returns NULL on failiure
166 * - Removed all #ifdef PCRS
168 * Revision 1.20 2001/07/01 17:01:04 oes
169 * Added comments and missing return statement in is_untrusted_url()
171 * Revision 1.19 2001/06/29 21:45:41 oes
172 * Indentation, CRLF->LF, Tab-> Space
174 * Revision 1.18 2001/06/29 13:27:38 oes
175 * - Cleaned up, renamed and reorderd functions
176 * and improved comments
179 * - Ported to CGI platform. Now delivers
180 * http_response or NULL
181 * - Unified HTML and GIF generation (moved image detection
182 * and GIF generation here from jcc.c:chat())
183 * - Fixed HTTP status to:
184 * - 403 (Forbidden) for the "blocked" HTML message
185 * - 200 (OK) for GIF answers
186 * - 302 (Redirect) for redirect to GIF
189 * - Ported to CGI platform. Now delivers
190 * http_response or NULL
191 * - Separated detection of untrusted URL into
192 * (bool)is_untrusted_url
193 * - Added enforcement of untrusted requests
195 * - Moved redirect_url() from cgi.c to here
196 * and ported it to the CGI platform
198 * - Removed logentry from cancelled commit
200 * Revision 1.17 2001/06/09 10:55:28 jongfoster
201 * Changing BUFSIZ ==> BUFFER_SIZE
203 * Revision 1.16 2001/06/07 23:10:26 jongfoster
204 * Allowing unanchored domain patterns to back off and retry
205 * if they partially match. Optimized right-anchored patterns.
206 * Moving ACL and forward files into config file.
207 * Replacing struct gateway with struct forward_spec
209 * Revision 1.15 2001/06/03 19:12:00 oes
210 * extracted-CGI relevant stuff
212 * Revision 1.14 2001/06/01 10:30:55 oes
213 * Added optional left-anchoring to domaincmp
215 * Revision 1.13 2001/05/31 21:21:30 jongfoster
216 * Permissionsfile / actions file changes:
217 * - Changed "permission" to "action" throughout
218 * - changes to file format to allow string parameters
219 * - Moved helper functions to actions.c
221 * Revision 1.12 2001/05/31 17:35:20 oes
223 * - Enhanced domain part globbing with infix and prefix asterisk
224 * matching and optional unanchored operation
226 * Revision 1.11 2001/05/29 11:53:23 oes
227 * "See why" link added to "blocked" page
229 * Revision 1.10 2001/05/29 09:50:24 jongfoster
230 * Unified blocklist/imagelist/permissionslist.
231 * File format is still under discussion, but the internal changes
234 * Also modified interceptor behaviour:
235 * - We now intercept all URLs beginning with one of the following
236 * prefixes (and *only* these prefixes):
238 * * http://ijbswa.sf.net/config/
239 * * http://ijbswa.sourceforge.net/config/
240 * - New interceptors "home page" - go to http://i.j.b/ to see it.
241 * - Internal changes so that intercepted and fast redirect pages
242 * are not replaced with an image.
243 * - Interceptors now have the option to send a binary page direct
244 * to the client. (i.e. ijb-send-banner uses this)
245 * - Implemented show-url-info interceptor. (Which is why I needed
246 * the above interceptors changes - a typical URL is
247 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
248 * The previous mechanism would not have intercepted that, and
249 * if it had been intercepted then it then it would have replaced
252 * Revision 1.9 2001/05/27 22:17:04 oes
254 * - re_process_buffer no longer writes the modified buffer
255 * to the client, which was very ugly. It now returns the
256 * buffer, which it is then written by chat.
258 * - content_length now adjusts the Content-Length: header
259 * for modified documents rather than crunch()ing it.
260 * (Length info in csp->content_length, which is 0 for
261 * unmodified documents)
263 * - For this to work, sed() is called twice when filtering.
265 * Revision 1.8 2001/05/26 17:13:28 jongfoster
266 * Filled in a function comment.
268 * Revision 1.7 2001/05/26 15:26:15 jongfoster
269 * ACL feature now provides more security by immediately dropping
270 * connections from untrusted hosts.
272 * Revision 1.6 2001/05/26 00:28:36 jongfoster
273 * Automatic reloading of config file.
274 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
275 * Most of the global variables have been moved to a new
276 * struct configuration_spec, accessed through csp->config->globalname
277 * Most of the globals remaining are used by the Win32 GUI.
279 * Revision 1.5 2001/05/25 22:34:30 jongfoster
282 * Revision 1.4 2001/05/22 18:46:04 oes
284 * - Enabled filtering banners by size rather than URL
285 * by adding patterns that replace all standard banner
286 * sizes with the "Junkbuster" gif to the re_filterfile
288 * - Enabled filtering WebBugs by providing a pattern
289 * which kills all 1x1 images
291 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
292 * which is selected by the (nonstandard and therefore
293 * capital) letter 'U' in the option string.
294 * It causes the quantifiers to be ungreedy by default.
295 * Appending a ? turns back to greedy (!).
297 * - Added a new interceptor ijb-send-banner, which
298 * sends back the "Junkbuster" gif. Without imagelist or
299 * MSIE detection support, or if tinygif = 1, or the
300 * URL isn't recognized as an imageurl, a lame HTML
301 * explanation is sent instead.
303 * - Added new feature, which permits blocking remote
304 * script redirects and firing back a local redirect
306 * The feature is conditionally compiled, i.e. it
307 * can be disabled with --disable-fast-redirects,
308 * plus it must be activated by a "fast-redirects"
309 * line in the config file, has its own log level
310 * and of course wants to be displayed by show-proxy-args
311 * Note: Boy, all the #ifdefs in 1001 locations and
312 * all the fumbling with configure.in and acconfig.h
313 * were *way* more work than the feature itself :-(
315 * - Because a generic redirect template was needed for
316 * this, tinygif = 3 now uses the same.
318 * - Moved GIFs, and other static HTTP response templates
323 * - Removed some >400 CRs again (Jon, you really worked
326 * Revision 1.3 2001/05/20 16:44:47 jongfoster
327 * Removing last hardcoded JunkBusters.com URLs.
329 * Revision 1.2 2001/05/20 01:21:20 jongfoster
330 * Version 2.9.4 checkin.
331 * - Merged popupfile and cookiefile, and added control over PCRS
332 * filtering, in new "permissionsfile".
333 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
334 * file error you now get a message box (in the Win32 GUI) rather
335 * than the program exiting with no explanation.
336 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
338 * - Removed tabs from "config"
339 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
340 * - Bumped up version number.
342 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
343 * Initial import of version 2.9.3 source tree
346 *********************************************************************/
352 #include <sys/types.h>
361 #endif /* ndef __OS2__ */
362 #include <netinet/in.h>
364 #include <winsock2.h>
365 #endif /* ndef _WIN32 */
369 #endif /* def __OS2__ */
377 #include "jbsockets.h"
378 #include "miscutil.h"
382 #include "deanimate.h"
383 #include "urlmatch.h"
389 const char filters_h_rcs[] = FILTERS_H_VERSION;
391 /* Fix a problem with Solaris. There should be no effect on other
393 * Solaris's isspace() is a macro which uses it's argument directly
394 * as an array index. Therefore we need to make sure that high-bit
395 * characters generate +ve values, and ideally we also want to make
396 * the argument match the declared parameter type of "int".
398 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
402 /*********************************************************************
404 * Function : block_acl
406 * Description : Block this request?
407 * Decide yes or no based on ACL file.
410 * 1 : dst = The proxy or gateway address this is going to.
411 * Or NULL to check all possible targets.
412 * 2 : csp = Current client state (buffers, headers, etc...)
413 * Also includes the client IP address.
415 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
417 *********************************************************************/
418 int block_acl(struct access_control_addr *dst, struct client_state *csp)
420 struct access_control_list *acl = csp->config->acl;
422 /* if not using an access control list, then permit the connection */
428 /* search the list */
431 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
435 /* Just want to check if they have any access */
436 if (acl->action == ACL_PERMIT)
441 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
442 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
444 if (acl->action == ACL_PERMIT)
462 /*********************************************************************
464 * Function : acl_addr
466 * Description : Called from `load_config' to parse an ACL address.
469 * 1 : aspec = String specifying ACL address.
470 * 2 : aca = struct access_control_addr to fill in.
472 * Returns : 0 => Ok, everything else is an error.
474 *********************************************************************/
475 int acl_addr(char *aspec, struct access_control_addr *aca)
477 int i, masklength, port;
483 if ((p = strchr(aspec, '/')))
487 if (ijb_isdigit(*p) == 0)
491 masklength = atoi(p);
494 if ((masklength < 0) || (masklength > 32))
499 if ((p = strchr(aspec, ':')))
503 if (ijb_isdigit(*p) == 0)
512 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
514 if (aca->addr == INADDR_NONE)
519 /* build the netmask */
521 for (i=1; i <= masklength ; i++)
523 aca->mask |= (1 << (32 - i));
526 /* now mask off the host portion of the ip address
527 * (i.e. save on the network portion of the address).
529 aca->addr = aca->addr & aca->mask;
534 #endif /* def FEATURE_ACL */
537 /*********************************************************************
539 * Function : match_portlist
541 * Description : Check if a given number is covered by a comma
542 * separated list of numbers and ranges (a,b-c,d,..)
545 * 1 : portlist = String with list
546 * 2 : port = port to check
548 * Returns : 0 => no match
551 *********************************************************************/
552 int match_portlist(const char *portlist, int port)
554 char *min, *max, *next, *portlist_copy;
556 min = next = portlist_copy = strdup(portlist);
559 * Zero-terminate first item and remember offset for next
561 if (NULL != (next = strchr(portlist_copy, (int) ',')))
567 * Loop through all items, checking for match
571 if (NULL == (max = strchr(min, (int) '-')))
574 * No dash, check for equality
576 if (port == atoi(min))
585 * This is a range, so check if between min and max,
586 * or, if max was omitted, between min and 65K
589 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
603 * Zero-terminate next item and remember offset for n+1
605 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
617 /*********************************************************************
619 * Function : block_url
621 * Description : Called from `chat'. Check to see if we need to block this.
624 * 1 : csp = Current client state (buffers, headers, etc...)
626 * Returns : NULL => unblocked, else HTTP block response
628 *********************************************************************/
629 struct http_response *block_url(struct client_state *csp)
631 #ifdef FEATURE_IMAGE_BLOCKING
633 #endif /* def FEATURE_IMAGE_BLOCKING */
634 struct http_response *rsp;
637 * If it's not blocked, don't block it ;-)
639 if ((csp->action->flags & ACTION_BLOCK) == 0)
645 * Else, prepare a response
647 if (NULL == (rsp = alloc_http_response()))
649 return cgi_error_memory();
653 * If it's an image-url, send back an image or redirect
654 * as specified by the relevant +image action
656 #ifdef FEATURE_IMAGE_BLOCKING
657 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
660 /* determine HOW images should be blocked */
661 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
663 /* and handle accordingly: */
664 if ((p == NULL) || (0 == strcmpic(p, "logo")))
666 rsp->body = bindup(image_logo_data, image_logo_length);
667 if (rsp->body == NULL)
669 free_http_response(rsp);
670 return cgi_error_memory();
672 rsp->content_length = image_logo_length;
674 if (enlist_unique_header(rsp->headers, "Content-Type", "image/png"))
676 free_http_response(rsp);
677 return cgi_error_memory();
681 else if (0 == strcmpic(p, "blank"))
683 rsp->body = bindup(image_blank_data, image_blank_length);
684 if (rsp->body == NULL)
686 free_http_response(rsp);
687 return cgi_error_memory();
689 rsp->content_length = image_blank_length;
691 if (enlist_unique_header(rsp->headers, "Content-Type", "image/png"))
693 free_http_response(rsp);
694 return cgi_error_memory();
698 else if (0 == strcmpic(p, "pattern"))
700 rsp->body = bindup(image_pattern_data, image_pattern_length);
701 if (rsp->body == NULL)
703 free_http_response(rsp);
704 return cgi_error_memory();
706 rsp->content_length = image_pattern_length;
708 if (enlist_unique_header(rsp->headers, "Content-Type", "image/png"))
710 free_http_response(rsp);
711 return cgi_error_memory();
717 rsp->status = strdup("302 Local Redirect from Junkbuster");
718 if (rsp->status == NULL)
720 free_http_response(rsp);
721 return cgi_error_memory();
724 if (enlist_unique_header(rsp->headers, "Location", p))
726 free_http_response(rsp);
727 return cgi_error_memory();
732 #endif /* def FEATURE_IMAGE_BLOCKING */
735 * Else, generate an HTML "blocked" message:
739 struct map * exports;
742 * Workaround for stupid Netscape bug which prevents
743 * pages from being displayed if loading a referenced
744 * JavaScript or style sheet fails. So make it appear
745 * as if it succeeded.
747 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
748 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
749 && !strstr(p, "Gecko") /* save Mozilla, */
750 && !strstr(p, "compatible") /* MSIE */
751 && !strstr(p, "Opera")) /* and Opera. */
753 rsp->status = strdup("200 Request for blocked URL");
757 rsp->status = strdup("404 Request for blocked URL");
760 if (rsp->status == NULL)
762 free_http_response(rsp);
763 return cgi_error_memory();
766 exports = default_exports(csp, NULL);
769 free_http_response(rsp);
770 return cgi_error_memory();
773 #ifdef FEATURE_FORCE_LOAD
774 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
775 #else /* ifndef FEATURE_FORCE_LOAD */
776 err = map_block_killer(exports, "force-support");
777 #endif /* ndef FEATURE_FORCE_LOAD */
779 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
780 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
785 free_http_response(rsp);
786 return cgi_error_memory();
789 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
792 free_http_response(rsp);
793 return cgi_error_memory();
797 return finish_http_response(rsp);
803 /*********************************************************************
805 * Function : trust_url FIXME: I should be called distrust_url
807 * Description : Calls is_untrusted_url to determine if the URL is trusted
808 * and if not, returns a HTTP 304 response with a reject message.
811 * 1 : csp = Current client state (buffers, headers, etc...)
813 * Returns : NULL => trusted, else http_response.
815 *********************************************************************/
816 struct http_response *trust_url(struct client_state *csp)
818 struct http_response *rsp;
819 struct map * exports;
820 char buf[BUFFER_SIZE];
822 struct url_spec **tl;
827 * Don't bother to work on trusted URLs
829 if (!is_untrusted_url(csp))
835 * Else, prepare a response:
837 if (NULL == (rsp = alloc_http_response()))
839 return cgi_error_memory();
842 exports = default_exports(csp, NULL);
845 free_http_response(rsp);
846 return cgi_error_memory();
850 * Export the host, port, and referrer information
852 err = map(exports, "hostport", 1, csp->http->hostport, 1);
853 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
855 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
857 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
861 if (!err) err = map(exports, "referrer", 1, "unknown", 1);
867 free_http_response(rsp);
868 return cgi_error_memory();
872 * Export the trust list
875 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
877 sprintf(buf, "<li>%s</li>\n", t->spec);
878 string_append(&p, buf);
880 err = map(exports, "trusted-referrers", 1, p, 0);
885 free_http_response(rsp);
886 return cgi_error_memory();
890 * Export the trust info, if available
892 if (csp->config->trust_info->first)
894 struct list_entry *l;
897 for (l = csp->config->trust_info->first; l ; l = l->next)
899 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
900 string_append(&p, buf);
902 err = map(exports, "trust-info", 1, p, 0);
906 err = map_block_killer(exports, "have-trust-info");
912 free_http_response(rsp);
913 return cgi_error_memory();
917 * Export the force prefix or the force conditional block killer
919 #ifdef FEATURE_FORCE_LOAD
920 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
921 #else /* ifndef FEATURE_FORCE_LOAD */
922 err = map_block_killer(exports, "force-support");
923 #endif /* ndef FEATURE_FORCE_LOAD */
928 free_http_response(rsp);
929 return cgi_error_memory();
935 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
938 free_http_response(rsp);
939 return cgi_error_memory();
942 return finish_http_response(rsp);
944 #endif /* def FEATURE_TRUST */
947 #ifdef FEATURE_FAST_REDIRECTS
948 /*********************************************************************
950 * Function : redirect_url
952 * Description : Checks for redirection URLs and returns a HTTP redirect
953 * to the destination URL, if necessary
956 * 1 : csp = Current client state (buffers, headers, etc...)
958 * Returns : NULL if URL was clean, HTTP redirect otherwise.
960 *********************************************************************/
961 struct http_response *redirect_url(struct client_state *csp)
964 struct http_response *rsp;
966 p = q = csp->http->path;
967 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
970 * find the last URL encoded in the request
972 while ((p = strstr(p, "http://")))
978 * if there was any, generate and return a HTTP redirect
980 if (q != csp->http->path)
982 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
984 if (NULL == (rsp = alloc_http_response()))
986 return cgi_error_memory();
989 if ( enlist_unique_header(rsp->headers, "Location", q)
990 || (NULL == (rsp->status = strdup("302 Local Redirect from Junkbuster"))) )
992 free_http_response(rsp);
993 return cgi_error_memory();
996 return finish_http_response(rsp);
1004 #endif /* def FEATURE_FAST_REDIRECTS */
1007 #ifdef FEATURE_IMAGE_BLOCKING
1008 /*********************************************************************
1010 * Function : is_imageurl
1012 * Description : Given a URL, decide whether it is an image or not,
1013 * using either the info from a previous +image action
1014 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
1015 * the browser's accept header.
1018 * 1 : csp = Current client state (buffers, headers, etc...)
1020 * Returns : True (nonzero) if URL is an image, false (0)
1023 *********************************************************************/
1024 int is_imageurl(struct client_state *csp)
1026 #ifdef FEATURE_IMAGE_DETECT_MSIE
1029 tmp = get_header_value(csp->headers, "User-Agent:");
1030 if (tmp && strstr(tmp, "MSIE"))
1032 tmp = get_header_value(csp->headers, "Accept:");
1033 if (tmp && strstr(tmp, "image/gif"))
1035 /* Client will accept HTML. If this seems counterintuitive,
1045 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1047 return ((csp->action->flags & ACTION_IMAGE) != 0);
1050 #endif /* def FEATURE_IMAGE_BLOCKING */
1053 #ifdef FEATURE_COOKIE_JAR
1054 /*********************************************************************
1056 * Function : is_untrusted_url
1058 * Description : Should we "distrust" this URL (and block it)?
1060 * Yes if it matches a line in the trustfile, or if the
1061 * referrer matches a line starting with "+" in the
1066 * 1 : csp = Current client state (buffers, headers, etc...)
1068 * Returns : 0 => trusted, 1 => untrusted
1070 *********************************************************************/
1071 int is_untrusted_url(struct client_state *csp)
1073 struct file_list *fl;
1074 struct block_spec *b;
1075 struct url_spec **trusted_url;
1076 struct http_request rhttp[1];
1077 const char * referer;
1081 * If we don't have a trustlist, we trust everybody
1083 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1088 memset(rhttp, '\0', sizeof(*rhttp));
1091 * Do we trust the request URL itself?
1093 for (b = b->next; b ; b = b->next)
1095 if (url_match(b->url, csp->http))
1101 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1103 /* no referrer was supplied */
1108 * If not, do we maybe trust its referrer?
1113 * Parse the URL from the referrer
1116 err = parse_http_url(referer, rhttp, csp);
1122 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1124 if (url_match(*trusted_url, rhttp))
1126 /* if the URL's referrer is from a trusted referrer, then
1127 * add the target spec to the trustfile as an unblocked
1128 * domain and return NULL (which means it's OK).
1133 if ((fp = fopen(csp->config->trustfile, "a")))
1137 char * new_entry = strdup("~");
1139 string_append(&new_entry, csp->http->hostport);
1141 path = csp->http->path;
1142 if ( (path[0] == '/')
1144 && ((path_end = strchr(path + 2, '/')) != NULL))
1146 /* since this path points into a user's home space
1147 * be sure to include this spec in the trustfile.
1149 int path_len = path_end - path; /* save offset */
1150 path = strdup(path); /* Copy string */
1153 path_end = path + path_len; /* regenerate ptr to new buffer */
1154 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1156 string_join(&new_entry, path);
1159 if (new_entry != NULL)
1161 fprintf(fp, "%s\n", new_entry);
1166 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1167 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1177 #endif /* def FEATURE_COOKIE_JAR */
1180 /*********************************************************************
1182 * Function : pcrs_filter_response
1184 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
1185 * to the text buffer that's been accumulated in
1186 * csp->iob->buf and set csp->content_length to the modified
1187 * size and raise the CSP_FLAG_MODIFIED flag if appropriate.
1190 * 1 : csp = Current client state (buffers, headers, etc...)
1192 * Returns : a pointer to the (newly allocated) modified buffer.
1193 * or NULL in case something went wrong
1195 *********************************************************************/
1196 char *pcrs_filter_response(struct client_state *csp)
1201 char *old = csp->iob->cur, *new = NULL;
1204 struct file_list *fl;
1205 struct re_filterfile_spec *b;
1208 if (csp->iob->cur >= csp->iob->eod)
1212 size = csp->iob->eod - csp->iob->cur;
1215 * If the body has a "chunked" transfer-encoding,
1216 * get rid of it first, adjusting size and iob->eod
1218 if (csp->flags & CSP_FLAG_CHUNKED)
1220 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1221 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1225 csp->iob->eod = csp->iob->cur + size;
1226 csp->flags |= CSP_FLAG_MODIFIED;
1229 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1231 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1235 if ( NULL == b->joblist )
1237 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1241 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1242 csp->http->hostport, csp->http->path, size);
1244 /* Apply all jobs from the joblist */
1245 for (job = b->joblist; NULL != job; job = job->next)
1247 hits += pcrs_execute(job, old, size, &new, &size);
1248 if (old != csp->iob->cur) free(old);
1252 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1255 * If there were no hits, destroy our copy and let
1256 * chat() use the original in csp->iob
1264 csp->flags |= CSP_FLAG_MODIFIED;
1265 csp->content_length = size;
1273 /*********************************************************************
1275 * Function : gif_deanimate_response
1277 * Description : Deanimate the GIF image that has been accumulated in
1278 * csp->iob->buf, set csp->content_length to the modified
1279 * size and raise the CSP_FLAG_MODIFIED flag.
1282 * 1 : csp = Current client state (buffers, headers, etc...)
1284 * Returns : a pointer to the (newly allocated) modified buffer.
1285 * or NULL in case something went wrong.
1287 *********************************************************************/
1288 char *gif_deanimate_response(struct client_state *csp)
1290 struct binbuffer *in, *out;
1292 size_t size = csp->iob->eod - csp->iob->cur;
1295 * If the body has a "chunked" transfer-encoding,
1296 * get rid of it first, adjusting size and iob->eod
1298 if (csp->flags & CSP_FLAG_CHUNKED)
1300 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1301 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1305 csp->iob->eod = csp->iob->cur + size;
1306 csp->flags |= CSP_FLAG_MODIFIED;
1309 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1310 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1312 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1316 in->buffer = csp->iob->cur;
1319 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1321 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1328 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1329 csp->content_length = out->offset;
1330 csp->flags |= CSP_FLAG_MODIFIED;
1340 /*********************************************************************
1342 * Function : remove_chunked_transfer_coding
1344 * Description : In-situ remove the "chunked" transfer coding as defined
1345 * in rfc2616 from a buffer.
1348 * 1 : buffer = Pointer to the text buffer
1349 * 2 : size = Number of bytes to be processed
1351 * Returns : The new size, i.e. the number of bytes from buffer which
1352 * are occupied by the stripped body, or 0 in case something
1355 *********************************************************************/
1356 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1359 unsigned int chunksize = 0;
1360 char *from_p, *to_p;
1363 from_p = to_p = buffer;
1365 if (sscanf(buffer, "%x", &chunksize) != 1)
1367 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1371 while (chunksize > 0)
1373 if (NULL == (from_p = strstr(from_p, "\r\n")))
1375 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1378 newsize += chunksize;
1381 memmove(to_p, from_p, (size_t) chunksize);
1382 to_p = buffer + newsize;
1383 from_p += chunksize + 2;
1385 if (sscanf(from_p, "%x", &chunksize) != 1)
1387 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1392 /* FIXME: Should this get its own loglevel? */
1393 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1399 /*********************************************************************
1401 * Function : url_actions
1403 * Description : Gets the actions for this URL.
1406 * 1 : http = http_request request for blocked URLs
1407 * 2 : csp = Current client state (buffers, headers, etc...)
1411 *********************************************************************/
1412 void url_actions(struct http_request *http,
1413 struct client_state *csp)
1415 struct file_list *fl;
1416 struct url_actions *b;
1418 init_current_action(csp->action);
1420 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1425 apply_url_actions(csp->action, http, b);
1430 /*********************************************************************
1432 * Function : apply_url_actions
1434 * Description : Applies a list of URL actions.
1437 * 1 : action = Destination.
1438 * 2 : http = Current URL
1439 * 3 : b = list of URL actions to apply
1443 *********************************************************************/
1444 void apply_url_actions(struct current_action_spec *action,
1445 struct http_request *http,
1446 struct url_actions *b)
1450 /* Should never happen */
1454 for (b = b->next; NULL != b; b = b->next)
1456 if (url_match(b->url, http))
1458 merge_current_action(action, b->action);
1464 /*********************************************************************
1466 * Function : forward_url
1468 * Description : Should we forward this to another proxy?
1471 * 1 : http = http_request request for current URL
1472 * 2 : csp = Current client state (buffers, headers, etc...)
1474 * Returns : Pointer to forwarding information.
1476 *********************************************************************/
1477 const struct forward_spec * forward_url(struct http_request *http,
1478 struct client_state *csp)
1480 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1481 struct forward_spec *fwd = csp->config->forward;
1490 if (url_match(fwd->url, http))