1 const char filters_rcs[] = "$Id: filters.c,v 1.37 2001/10/22 15:33:56 david__schmidt 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', `domaincmp', `dsplit',
10 * `filter_popups', `forward_url', 'redirect_url',
11 * `ij_untrusted_url', `intercept_url', `pcrs_filter_respose',
12 * `show_proxy_args', '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.37 2001/10/22 15:33:56 david__schmidt
42 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
43 * filters.c. Added a FIXME in front of the offending code. I'll gladly
44 * put in a better/more robust fix for all parties if one is presented...
45 * It seems that just returning 200 instead of 404 would pretty much fix
46 * it for everyone, but I don't know all the history of the problem.
48 * Revision 1.36 2001/10/10 16:44:16 oes
49 * Added match_portlist function
51 * Revision 1.35 2001/10/07 15:41:23 oes
52 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
54 * New function remove_chunked_transfer_coding that strips chunked
55 * transfer coding to plain and is called by pcrs_filter_response
56 * and gif_deanimate_response if neccessary
58 * Improved handling of zero-change re_filter runs
60 * pcrs_filter_response and gif_deanimate_response now remove
61 * chunked transfer codeing before processing the body.
63 * Revision 1.34 2001/09/20 15:49:36 steudten
65 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
66 * See cgi.c fill_template().
68 * Revision 1.33 2001/09/16 17:05:14 jongfoster
69 * Removing unused #include showarg.h
71 * Revision 1.32 2001/09/16 13:21:27 jongfoster
72 * Changes to use new list functions.
74 * Revision 1.31 2001/09/16 11:38:02 jongfoster
75 * Splitting fill_template() into 2 functions:
76 * template_load() loads the file
77 * template_fill() performs the PCRS regexps.
78 * This is because the CGI edit interface has a "table row"
79 * template which is used many times in the page - this
80 * change means it's only loaded from disk once.
82 * Revision 1.30 2001/09/16 11:00:10 jongfoster
83 * New function alloc_http_response, for symmetry with free_http_response
85 * Revision 1.29 2001/09/13 23:32:40 jongfoster
86 * Moving image data to cgi.c rather than cgi.h
87 * Fixing a GPF under Win32 (and any other OS that protects global
88 * constants from being written to).
90 * Revision 1.28 2001/09/10 10:18:51 oes
91 * Silenced compiler warnings
93 * Revision 1.27 2001/08/05 16:06:20 jongfoster
94 * Modifiying "struct map" so that there are now separate header and
95 * "map_entry" structures. This means that functions which modify a
96 * map no longer need to return a pointer to the modified map.
97 * Also, it no longer reverses the order of the entries (which may be
98 * important with some advanced template substitutions).
100 * Revision 1.26 2001/07/30 22:08:36 jongfoster
101 * Tidying up #defines:
102 * - All feature #defines are now of the form FEATURE_xxx
103 * - Permanently turned off WIN_GUI_EDIT
104 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
106 * Revision 1.25 2001/07/26 10:09:46 oes
107 * Made browser detection a little less naive
109 * Revision 1.24 2001/07/25 17:22:51 oes
110 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
112 * Revision 1.23 2001/07/23 13:40:12 oes
113 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
115 * Revision 1.22 2001/07/18 12:29:34 oes
116 * - Made gif_deanimate_response respect
117 * csp->action->string[ACTION_STRING_DEANIMATE]
118 * - Logging cosmetics
120 * Revision 1.21 2001/07/13 13:59:53 oes
121 * - Introduced gif_deanimate_response which shares the
122 * generic content modification interface of pcrs_filter_response
123 * and acts as a wrapper to deanimate.c:gif_deanimate()
124 * - Renamed re_process_buffer to pcrs_filter_response
125 * - pcrs_filter_response now returns NULL on failiure
126 * - Removed all #ifdef PCRS
128 * Revision 1.20 2001/07/01 17:01:04 oes
129 * Added comments and missing return statement in is_untrusted_url()
131 * Revision 1.19 2001/06/29 21:45:41 oes
132 * Indentation, CRLF->LF, Tab-> Space
134 * Revision 1.18 2001/06/29 13:27:38 oes
135 * - Cleaned up, renamed and reorderd functions
136 * and improved comments
139 * - Ported to CGI platform. Now delivers
140 * http_response or NULL
141 * - Unified HTML and GIF generation (moved image detection
142 * and GIF generation here from jcc.c:chat())
143 * - Fixed HTTP status to:
144 * - 403 (Forbidden) for the "blocked" HTML message
145 * - 200 (OK) for GIF answers
146 * - 302 (Redirect) for redirect to GIF
149 * - Ported to CGI platform. Now delivers
150 * http_response or NULL
151 * - Separated detection of untrusted URL into
152 * (bool)is_untrusted_url
153 * - Added enforcement of untrusted requests
155 * - Moved redirect_url() from cgi.c to here
156 * and ported it to the CGI platform
158 * - Removed logentry from cancelled commit
160 * Revision 1.17 2001/06/09 10:55:28 jongfoster
161 * Changing BUFSIZ ==> BUFFER_SIZE
163 * Revision 1.16 2001/06/07 23:10:26 jongfoster
164 * Allowing unanchored domain patterns to back off and retry
165 * if they partially match. Optimized right-anchored patterns.
166 * Moving ACL and forward files into config file.
167 * Replacing struct gateway with struct forward_spec
169 * Revision 1.15 2001/06/03 19:12:00 oes
170 * extracted-CGI relevant stuff
172 * Revision 1.14 2001/06/01 10:30:55 oes
173 * Added optional left-anchoring to domaincmp
175 * Revision 1.13 2001/05/31 21:21:30 jongfoster
176 * Permissionsfile / actions file changes:
177 * - Changed "permission" to "action" throughout
178 * - changes to file format to allow string parameters
179 * - Moved helper functions to actions.c
181 * Revision 1.12 2001/05/31 17:35:20 oes
183 * - Enhanced domain part globbing with infix and prefix asterisk
184 * matching and optional unanchored operation
186 * Revision 1.11 2001/05/29 11:53:23 oes
187 * "See why" link added to "blocked" page
189 * Revision 1.10 2001/05/29 09:50:24 jongfoster
190 * Unified blocklist/imagelist/permissionslist.
191 * File format is still under discussion, but the internal changes
194 * Also modified interceptor behaviour:
195 * - We now intercept all URLs beginning with one of the following
196 * prefixes (and *only* these prefixes):
198 * * http://ijbswa.sf.net/config/
199 * * http://ijbswa.sourceforge.net/config/
200 * - New interceptors "home page" - go to http://i.j.b/ to see it.
201 * - Internal changes so that intercepted and fast redirect pages
202 * are not replaced with an image.
203 * - Interceptors now have the option to send a binary page direct
204 * to the client. (i.e. ijb-send-banner uses this)
205 * - Implemented show-url-info interceptor. (Which is why I needed
206 * the above interceptors changes - a typical URL is
207 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
208 * The previous mechanism would not have intercepted that, and
209 * if it had been intercepted then it then it would have replaced
212 * Revision 1.9 2001/05/27 22:17:04 oes
214 * - re_process_buffer no longer writes the modified buffer
215 * to the client, which was very ugly. It now returns the
216 * buffer, which it is then written by chat.
218 * - content_length now adjusts the Content-Length: header
219 * for modified documents rather than crunch()ing it.
220 * (Length info in csp->content_length, which is 0 for
221 * unmodified documents)
223 * - For this to work, sed() is called twice when filtering.
225 * Revision 1.8 2001/05/26 17:13:28 jongfoster
226 * Filled in a function comment.
228 * Revision 1.7 2001/05/26 15:26:15 jongfoster
229 * ACL feature now provides more security by immediately dropping
230 * connections from untrusted hosts.
232 * Revision 1.6 2001/05/26 00:28:36 jongfoster
233 * Automatic reloading of config file.
234 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
235 * Most of the global variables have been moved to a new
236 * struct configuration_spec, accessed through csp->config->globalname
237 * Most of the globals remaining are used by the Win32 GUI.
239 * Revision 1.5 2001/05/25 22:34:30 jongfoster
242 * Revision 1.4 2001/05/22 18:46:04 oes
244 * - Enabled filtering banners by size rather than URL
245 * by adding patterns that replace all standard banner
246 * sizes with the "Junkbuster" gif to the re_filterfile
248 * - Enabled filtering WebBugs by providing a pattern
249 * which kills all 1x1 images
251 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
252 * which is selected by the (nonstandard and therefore
253 * capital) letter 'U' in the option string.
254 * It causes the quantifiers to be ungreedy by default.
255 * Appending a ? turns back to greedy (!).
257 * - Added a new interceptor ijb-send-banner, which
258 * sends back the "Junkbuster" gif. Without imagelist or
259 * MSIE detection support, or if tinygif = 1, or the
260 * URL isn't recognized as an imageurl, a lame HTML
261 * explanation is sent instead.
263 * - Added new feature, which permits blocking remote
264 * script redirects and firing back a local redirect
266 * The feature is conditionally compiled, i.e. it
267 * can be disabled with --disable-fast-redirects,
268 * plus it must be activated by a "fast-redirects"
269 * line in the config file, has its own log level
270 * and of course wants to be displayed by show-proxy-args
271 * Note: Boy, all the #ifdefs in 1001 locations and
272 * all the fumbling with configure.in and acconfig.h
273 * were *way* more work than the feature itself :-(
275 * - Because a generic redirect template was needed for
276 * this, tinygif = 3 now uses the same.
278 * - Moved GIFs, and other static HTTP response templates
283 * - Removed some >400 CRs again (Jon, you really worked
286 * Revision 1.3 2001/05/20 16:44:47 jongfoster
287 * Removing last hardcoded JunkBusters.com URLs.
289 * Revision 1.2 2001/05/20 01:21:20 jongfoster
290 * Version 2.9.4 checkin.
291 * - Merged popupfile and cookiefile, and added control over PCRS
292 * filtering, in new "permissionsfile".
293 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
294 * file error you now get a message box (in the Win32 GUI) rather
295 * than the program exiting with no explanation.
296 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
298 * - Removed tabs from "config"
299 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
300 * - Bumped up version number.
302 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
303 * Initial import of version 2.9.3 source tree
306 *********************************************************************/
312 #include <sys/types.h>
320 #include <netinet/in.h>
322 #include <winsock2.h>
331 #include "jbsockets.h"
332 #include "miscutil.h"
336 #include "deanimate.h"
342 const char filters_h_rcs[] = FILTERS_H_VERSION;
344 /* Fix a problem with Solaris. There should be no effect on other
346 * Solaris's isspace() is a macro which uses it's argument directly
347 * as an array index. Therefore we need to make sure that high-bit
348 * characters generate +ve values, and ideally we also want to make
349 * the argument match the declared parameter type of "int".
351 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
355 /*********************************************************************
357 * Function : block_acl
359 * Description : Block this request?
360 * Decide yes or no based on ACL file.
363 * 1 : dst = The proxy or gateway address this is going to.
364 * Or NULL to check all possible targets.
365 * 2 : csp = Current client state (buffers, headers, etc...)
366 * Also includes the client IP address.
368 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
370 *********************************************************************/
371 int block_acl(struct access_control_addr *dst, struct client_state *csp)
373 struct access_control_list *acl = csp->config->acl;
375 /* if not using an access control list, then permit the connection */
381 /* search the list */
384 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
388 /* Just want to check if they have any access */
389 if (acl->action == ACL_PERMIT)
394 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
395 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
397 if (acl->action == ACL_PERMIT)
415 /*********************************************************************
417 * Function : acl_addr
419 * Description : Called from `load_aclfile' to parse an ACL address.
422 * 1 : aspec = String specifying ACL address.
423 * 2 : aca = struct access_control_addr to fill in.
425 * Returns : 0 => Ok, everything else is an error.
427 *********************************************************************/
428 int acl_addr(char *aspec, struct access_control_addr *aca)
430 int i, masklength, port;
436 if ((p = strchr(aspec, '/')))
440 if (ijb_isdigit(*p) == 0)
444 masklength = atoi(p);
447 if ((masklength < 0) || (masklength > 32))
452 if ((p = strchr(aspec, ':')))
456 if (ijb_isdigit(*p) == 0)
465 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
469 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
473 /* build the netmask */
475 for (i=1; i <= masklength ; i++)
477 aca->mask |= (1 << (32 - i));
480 /* now mask off the host portion of the ip address
481 * (i.e. save on the network portion of the address).
483 aca->addr = aca->addr & aca->mask;
488 #endif /* def FEATURE_ACL */
491 /*********************************************************************
493 * Function : match_portlist
495 * Description : Check if a given number is covered by a comma
496 * separated list of numbers and ranges (a,b-c,d,..)
499 * 1 : portlist = String with list
500 * 2 : port = port to check
502 * Returns : 0 => no match
505 *********************************************************************/
506 int match_portlist(const char *portlist, int port)
508 char *min, *max, *next, *portlist_copy;
510 min = next = portlist_copy = strdup(portlist);
513 * Zero-terminate first item and remember offset for next
515 if (NULL != (next = strchr(portlist_copy, (int) ',')))
521 * Loop through all items, checking for match
525 if (NULL == (max = strchr(min, (int) '-')))
528 * No dash, check for equality
530 if (port == atoi(min))
539 * This is a range, so check if between min and max,
540 * or, if max was omitted, between min and 65K
543 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
557 * Zero-terminate next item and remember offset for n+1
559 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
571 /*********************************************************************
573 * Function : block_url
575 * Description : Called from `chat'. Check to see if we need to block this.
578 * 1 : csp = Current client state (buffers, headers, etc...)
580 * Returns : NULL => unblocked, else HTTP block response
582 *********************************************************************/
583 struct http_response *block_url(struct client_state *csp)
585 #ifdef FEATURE_IMAGE_BLOCKING
587 #endif /* def FEATURE_IMAGE_BLOCKING */
588 struct http_response *rsp;
591 * If it's not blocked, don't block it ;-)
593 if ((csp->action->flags & ACTION_BLOCK) == 0)
599 * Else, prepare a response
601 if (NULL == (rsp = alloc_http_response()))
603 return cgi_error_memory();
607 * If it's an image-url, send back an image or redirect
608 * as specified by the relevant +image action
610 #ifdef FEATURE_IMAGE_BLOCKING
611 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
614 /* determine HOW images should be blocked */
615 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
617 /* and handle accordingly: */
618 if ((p == NULL) || (0 == strcmpic(p, "logo")))
620 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
621 if (rsp->body == NULL)
623 free_http_response(rsp);
624 return cgi_error_memory();
626 rsp->content_length = image_junkbuster_gif_length;
628 if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
630 free_http_response(rsp);
631 return cgi_error_memory();
635 else if (0 == strcmpic(p, "blank"))
637 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
638 if (rsp->body == NULL)
640 free_http_response(rsp);
641 return cgi_error_memory();
643 rsp->content_length = image_blank_gif_length;
645 if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
647 free_http_response(rsp);
648 return cgi_error_memory();
654 rsp->status = strdup("302 Local Redirect from Junkbuster");
655 if (rsp->status == NULL)
657 free_http_response(rsp);
658 return cgi_error_memory();
661 if (enlist_unique_header(rsp->headers, "Location", p))
663 free_http_response(rsp);
664 return cgi_error_memory();
669 #endif /* def FEATURE_IMAGE_BLOCKING */
672 * Else, generate an HTML "blocked" message:
676 struct map * exports;
681 * The entire OS/2 community will hit the stupid Netscape bug
682 * (all three of us! :-) so we'll just keep ourselves out
683 * of this contentious debate and special-case ourselves.
684 * The problem is... a this point in parsing, we don't know
685 * what the csp->http->user_agent is (yet). So we can't use
686 * it to decide if we should work around the NS bug or not.
688 rsp->status = strdup("200 Request for blocked URL");
691 * Workaround for stupid Netscape bug which prevents
692 * pages from being displayed if loading a referenced
693 * JavaScript or style sheet fails. So make it appear
694 * as if it succeeded.
696 if (csp->http->user_agent
697 && !strncmpic(csp->http->user_agent, "mozilla", 7)
698 && !strstr(csp->http->user_agent, "compatible")
699 && !strstr(csp->http->user_agent, "Opera"))
701 rsp->status = strdup("200 Request for blocked URL");
705 rsp->status = strdup("404 Request for blocked URL");
708 if (rsp->status == NULL)
710 free_http_response(rsp);
711 return cgi_error_memory();
714 exports = default_exports(csp, NULL);
717 free_http_response(rsp);
718 return cgi_error_memory();
721 #ifdef FEATURE_FORCE_LOAD
722 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
723 #else /* ifndef FEATURE_FORCE_LOAD */
724 err = map_block_killer(exports, "force-support");
725 #endif /* ndef FEATURE_FORCE_LOAD */
727 err = err || map(exports, "hostport", 1, csp->http->hostport, 1);
728 err = err || map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
729 err = err || map(exports, "path", 1, csp->http->path, 1);
730 err = err || map(exports, "path-html", 1, html_encode(csp->http->path), 0);
735 free_http_response(rsp);
736 return cgi_error_memory();
739 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
742 free_http_response(rsp);
743 return cgi_error_memory();
747 return finish_http_response(rsp);
753 /*********************************************************************
755 * Function : trust_url FIXME: I should be called distrust_url
757 * Description : Calls is_untrusted_url to determine if the URL is trusted
758 * and if not, returns a HTTP 304 response with a reject message.
761 * 1 : csp = Current client state (buffers, headers, etc...)
763 * Returns : NULL => trusted, else http_response.
765 *********************************************************************/
766 struct http_response *trust_url(struct client_state *csp)
768 struct http_response *rsp;
769 struct map * exports;
770 char buf[BUFFER_SIZE];
772 struct url_spec **tl;
777 * Don't bother to work on trusted URLs
779 if (!is_untrusted_url(csp))
785 * Else, prepare a response:
787 if (NULL == (rsp = alloc_http_response()))
789 return cgi_error_memory();
792 exports = default_exports(csp, NULL);
795 free_http_response(rsp);
796 return cgi_error_memory();
800 * Export the host, port, and referrer information
802 err = map(exports, "hostport", 1, csp->http->hostport, 1)
803 || map(exports, "path", 1, csp->http->path, 1)
804 || map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0)
805 || map(exports, "path-html", 1, html_encode(csp->http->path), 0);
807 if (csp->referrer && strlen(csp->referrer) > 9)
809 err = err || map(exports, "referrer", 1, csp->referrer + 9, 1);
810 err = err || map(exports, "referrer-html", 1, html_encode(csp->referrer + 9), 0);
814 err = err || map(exports, "referrer", 1, "unknown", 1);
815 err = err || map(exports, "referrer-html", 1, "unknown", 1);
821 free_http_response(rsp);
822 return cgi_error_memory();
826 * Export the trust list
829 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
831 sprintf(buf, "<li>%s</li>\n", t->spec);
832 string_append(&p, buf);
834 err = map(exports, "trusted-referrers", 1, p, 0);
839 free_http_response(rsp);
840 return cgi_error_memory();
844 * Export the trust info, if available
846 if (csp->config->trust_info->first)
848 struct list_entry *l;
851 for (l = csp->config->trust_info->first; l ; l = l->next)
853 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
854 string_append(&p, buf);
856 err = map(exports, "trust-info", 1, p, 0);
860 err = map_block_killer(exports, "have-trust-info");
866 free_http_response(rsp);
867 return cgi_error_memory();
871 * Export the force prefix or the force conditional block killer
873 #ifdef FEATURE_FORCE_LOAD
874 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
875 #else /* ifndef FEATURE_FORCE_LOAD */
876 err = map_block_killer(exports, "force-support");
877 #endif /* ndef FEATURE_FORCE_LOAD */
882 free_http_response(rsp);
883 return cgi_error_memory();
889 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
892 free_http_response(rsp);
893 return cgi_error_memory();
896 return finish_http_response(rsp);
898 #endif /* def FEATURE_TRUST */
901 #ifdef FEATURE_FAST_REDIRECTS
902 /*********************************************************************
904 * Function : redirect_url
906 * Description : Checks for redirection URLs and returns a HTTP redirect
907 * to the destination URL, if necessary
910 * 1 : csp = Current client state (buffers, headers, etc...)
912 * Returns : NULL if URL was clean, HTTP redirect otherwise.
914 *********************************************************************/
915 struct http_response *redirect_url(struct client_state *csp)
918 struct http_response *rsp;
920 p = q = csp->http->path;
921 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
924 * find the last URL encoded in the request
926 while ((p = strstr(p, "http://")))
932 * if there was any, generate and return a HTTP redirect
934 if (q != csp->http->path)
936 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
938 if (NULL == (rsp = alloc_http_response()))
940 return cgi_error_memory();
943 if ( enlist_unique_header(rsp->headers, "Location", q)
944 || (NULL == (rsp->status = strdup("302 Local Redirect from Junkbuster"))) )
946 free_http_response(rsp);
947 return cgi_error_memory();
950 return finish_http_response(rsp);
958 #endif /* def FEATURE_FAST_REDIRECTS */
961 #ifdef FEATURE_IMAGE_BLOCKING
962 /*********************************************************************
964 * Function : is_imageurl
966 * Description : Given a URL, decide whether it is an image or not,
967 * using either the info from a previous +image action
968 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
969 * the browser's accept header.
972 * 1 : csp = Current client state (buffers, headers, etc...)
974 * Returns : True (nonzero) if URL is an image, false (0)
977 *********************************************************************/
978 int is_imageurl(struct client_state *csp)
980 #ifdef FEATURE_IMAGE_DETECT_MSIE
981 if ((csp->accept_types
982 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
983 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
987 else if ((csp->accept_types
988 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
989 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
993 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
995 return ((csp->action->flags & ACTION_IMAGE) != 0);
998 #endif /* def FEATURE_IMAGE_BLOCKING */
1001 #ifdef FEATURE_COOKIE_JAR
1002 /*********************************************************************
1004 * Function : is_untrusted_url
1006 * Description : Should we "distrust" this URL (and block it)?
1008 * Yes if it matches a line in the trustfile, or if the
1009 * referrer matches a line starting with "+" in the
1014 * 1 : csp = Current client state (buffers, headers, etc...)
1016 * Returns : 0 => trusted, 1 => untrusted
1018 *********************************************************************/
1019 int is_untrusted_url(struct client_state *csp)
1021 struct file_list *fl;
1022 struct block_spec *b;
1023 struct url_spec url[1], **tl, *t;
1024 struct http_request rhttp[1];
1028 * If we don't have a trustlist, we trust everybody
1030 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1037 * Do we trust the request URL itself?
1039 *url = dsplit(csp->http->host);
1041 /* if splitting the domain fails, punt */
1042 if (url->dbuf == NULL) return(0);
1044 memset(rhttp, '\0', sizeof(*rhttp));
1046 for (b = b->next; b ; b = b->next)
1048 if ((b->url->port == 0) || (b->url->port == csp->http->port))
1050 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1052 if ((b->url->path == NULL) ||
1054 (regexec(b->url->preg, csp->http->path, 0, NULL, 0) == 0)
1056 (strncmp(b->url->path, csp->http->path, b->url->pathlen) == 0)
1063 if (b->reject == 0) return(0);
1074 if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
1076 /* no referrer was supplied */
1080 /* forge a URL from the referrer so we can use
1081 * convert_url() to parse it into its components.
1085 p = strsav(p, "GET ");
1086 p = strsav(p, csp->referrer + 9); /* skip over "Referer: " */
1087 p = strsav(p, " HTTP/1.0");
1089 parse_http_request(p, rhttp, csp);
1092 if (rhttp->cmd == NULL)
1099 * If not, do we maybe trust its referrer?
1101 *url = dsplit(rhttp->host);
1103 /* if splitting the domain fails, punt */
1104 if (url->dbuf == NULL) return(1);
1106 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
1108 if ((t->port == 0) || (t->port == rhttp->port))
1110 if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
1112 if ((t->path == NULL) ||
1114 (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
1116 (strncmp(t->path, rhttp->path, t->pathlen) == 0)
1120 /* if the URL's referrer is from a trusted referrer, then
1121 * add the target spec to the trustfile as an unblocked
1122 * domain and return NULL (which means it's OK).
1130 if ((fp = fopen(csp->config->trustfile, "a")))
1135 h = strsav(h, csp->http->hostport);
1137 p = csp->http->path;
1141 /* since this path points into a user's home space
1142 * be sure to include this spec in the trustfile.
1144 if ((p = strchr(p, '/')))
1147 h = strsav(h, csp->http->path); /* FIXME: p?! */
1152 fprintf(fp, "%s\n", h);
1163 #endif /* def FEATURE_COOKIE_JAR */
1166 /*********************************************************************
1168 * Function : pcrs_filter_response
1170 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
1171 * to the text buffer that's been accumulated in
1172 * csp->iob->buf and set csp->content_length to the modified
1173 * size and raise the CSP_FLAG_MODIFIED flag if appropriate.
1176 * 1 : csp = Current client state (buffers, headers, etc...)
1178 * Returns : a pointer to the (newly allocated) modified buffer.
1179 * or NULL in case something went wrong
1181 *********************************************************************/
1182 char *pcrs_filter_response(struct client_state *csp)
1187 char *old = csp->iob->cur, *new = NULL;
1190 struct file_list *fl;
1191 struct re_filterfile_spec *b;
1194 if (csp->iob->cur >= csp->iob->eod)
1198 size = csp->iob->eod - csp->iob->cur;
1201 * If the body has a "chunked" transfer-encoding,
1202 * get rid of it first, adjusting size and iob->eod
1204 if (csp->flags & CSP_FLAG_CHUNKED)
1206 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1207 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1211 csp->iob->eod = csp->iob->cur + size;
1212 csp->flags |= CSP_FLAG_MODIFIED;
1215 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1217 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1221 if ( NULL == b->joblist )
1223 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1227 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1228 csp->http->hostport, csp->http->path, size);
1230 /* Apply all jobs from the joblist */
1231 for (job = b->joblist; NULL != job; job = job->next)
1233 hits += pcrs_execute(job, old, size, &new, &size);
1234 if (old != csp->iob->cur) free(old);
1238 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1241 * If there were no hits, destroy our copy and let
1242 * chat() use the original in csp->iob
1250 csp->flags |= CSP_FLAG_MODIFIED;
1251 csp->content_length = size;
1259 /*********************************************************************
1261 * Function : gif_deanimate_response
1263 * Description : Deanimate the GIF image that has been accumulated in
1264 * csp->iob->buf, set csp->content_length to the modified
1265 * size and raise the CSP_FLAG_MODIFIED flag.
1268 * 1 : csp = Current client state (buffers, headers, etc...)
1270 * Returns : a pointer to the (newly allocated) modified buffer.
1271 * or NULL in case something went wrong.
1273 *********************************************************************/
1274 char *gif_deanimate_response(struct client_state *csp)
1276 struct binbuffer *in, *out;
1278 int size = csp->iob->eod - csp->iob->cur;
1281 * If the body has a "chunked" transfer-encoding,
1282 * get rid of it first, adjusting size and iob->eod
1284 if (csp->flags & CSP_FLAG_CHUNKED)
1286 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1287 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1291 csp->iob->eod = csp->iob->cur + size;
1292 csp->flags |= CSP_FLAG_MODIFIED;
1295 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1296 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1298 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1302 in->buffer = csp->iob->cur;
1305 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1307 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1314 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1315 csp->content_length = out->offset;
1316 csp->flags |= CSP_FLAG_MODIFIED;
1326 /*********************************************************************
1328 * Function : remove_chunked_transfer_coding
1330 * Description : In-situ remove the "chunked" transfer coding as defined
1331 * in rfc2616 from a buffer.
1334 * 1 : buffer = Pointer to the text buffer
1335 * 2 : size = Number of bytes to be processed
1337 * Returns : The new size, i.e. the number of bytes from buffer which
1338 * are occupied by the stripped body, or 0 in case something
1341 *********************************************************************/
1342 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1345 unsigned int chunksize = 0;
1346 char *from_p, *to_p;
1349 from_p = to_p = buffer;
1351 if (sscanf(buffer, "%x", &chunksize) != 1)
1353 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1357 while (chunksize > 0)
1359 if (NULL == (from_p = strstr(from_p, "\r\n")))
1361 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1364 newsize += chunksize;
1367 memmove(to_p, from_p, (size_t) chunksize);
1368 to_p = buffer + newsize;
1369 from_p += chunksize + 2;
1371 if (sscanf(from_p, "%x", &chunksize) != 1)
1373 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1378 /* FIXME: Should this get its own loglevel? */
1379 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1385 /*********************************************************************
1387 * Function : url_actions
1389 * Description : Gets the actions for this URL.
1392 * 1 : http = http_request request for blocked URLs
1393 * 2 : csp = Current client state (buffers, headers, etc...)
1397 *********************************************************************/
1398 void url_actions(struct http_request *http,
1399 struct client_state *csp)
1401 struct file_list *fl;
1402 struct url_actions *b;
1404 init_current_action(csp->action);
1406 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1411 apply_url_actions(csp->action, http, b);
1416 /*********************************************************************
1418 * Function : apply_url_actions
1420 * Description : Applies a list of URL actions.
1423 * 1 : action = Destination.
1424 * 2 : http = Current URL
1425 * 3 : b = list of URL actions to apply
1429 *********************************************************************/
1430 void apply_url_actions(struct current_action_spec *action,
1431 struct http_request *http,
1432 struct url_actions *b)
1434 struct url_spec url[1];
1438 /* Should never happen */
1442 *url = dsplit(http->host);
1444 /* if splitting the domain fails, punt */
1445 if (url->dbuf == NULL)
1450 for (b = b->next; NULL != b; b = b->next)
1452 if ((b->url->port == 0) || (b->url->port == http->port))
1454 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1456 if ((b->url->path == NULL) ||
1458 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
1460 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
1464 merge_current_action(action, b->action);
1475 /*********************************************************************
1477 * Function : forward_url
1479 * Description : Should we forward this to another proxy?
1482 * 1 : http = http_request request for current URL
1483 * 2 : csp = Current client state (buffers, headers, etc...)
1485 * Returns : Pointer to forwarding information.
1487 *********************************************************************/
1488 const struct forward_spec * forward_url(struct http_request *http,
1489 struct client_state *csp)
1491 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1492 struct forward_spec *fwd = csp->config->forward;
1493 struct url_spec url[1];
1497 return(fwd_default);
1500 *url = dsplit(http->host);
1502 /* if splitting the domain fails, punt */
1503 if (url->dbuf == NULL)
1505 return(fwd_default);
1510 if ((fwd->url->port == 0) || (fwd->url->port == http->port))
1512 if ((fwd->url->domain[0] == '\0') || (domaincmp(fwd->url, url) == 0))
1514 if ((fwd->url->path == NULL) ||
1516 (regexec(fwd->url->preg, http->path, 0, NULL, 0) == 0)
1518 (strncmp(fwd->url->path, http->path, fwd->url->pathlen) == 0)
1533 return(fwd_default);
1538 /*********************************************************************
1542 * Description : Takes a domain and returns a pointer to a url_spec
1543 * structure populated with dbuf, dcnt and dvec. The
1544 * other fields in the structure that is returned are zero.
1547 * 1 : domain = a URL address
1549 * Returns : url_spec structure populated with dbuf, dcnt and dvec.
1550 * On error, the dbuf field will be set to NULL. (As
1551 * will all the others, but you don't need to check
1554 * FIXME: Returning a structure is horribly inefficient, please can
1555 * this structure take a (struct url_spec * dest)
1558 *********************************************************************/
1559 struct url_spec dsplit(char *domain)
1561 struct url_spec ret[1];
1562 char *v[BUFFER_SIZE];
1566 memset(ret, '\0', sizeof(*ret));
1568 if (domain[strlen(domain) - 1] == '.')
1570 ret->unanchored |= ANCHOR_RIGHT;
1573 if (domain[0] == '.')
1575 ret->unanchored |= ANCHOR_LEFT;
1578 ret->dbuf = strdup(domain);
1579 if (NULL == ret->dbuf)
1584 /* map to lower case */
1585 for (p = ret->dbuf; *p ; p++)
1587 *p = tolower((int)(unsigned char)*p);
1590 /* split the domain name into components */
1591 ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
1596 memset(ret, '\0', sizeof(ret));
1599 else if (ret->dcnt == 0)
1604 /* save a copy of the pointers in dvec */
1605 size = ret->dcnt * sizeof(*ret->dvec);
1607 ret->dvec = (char **)malloc(size);
1608 if (NULL == ret->dvec)
1611 memset(ret, '\0', sizeof(ret));
1615 memcpy(ret->dvec, v, size);
1622 /*********************************************************************
1624 * Function : simple_domaincmp
1626 * Description : Domain-wise Compare fqdn's. The comparison is
1627 * both left- and right-anchored. The individual
1628 * domain names are compared with simplematch().
1629 * This is only used by domaincmp.
1632 * 1 : pv = array of patterns to compare
1633 * 2 : fv = array of domain components to compare
1634 * 3 : len = length of the arrays (both arrays are the
1635 * same length - if they weren't, it couldn't
1636 * possibly be a match).
1638 * Returns : 0 => domains are equivalent, else no match.
1640 *********************************************************************/
1641 static int simple_domaincmp(char **pv, char **fv, int len)
1645 for (n = 0; n < len; n++)
1647 if (simplematch(pv[n], fv[n]))
1658 /*********************************************************************
1660 * Function : domaincmp
1662 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1663 * pattern->unachored, the comparison is un-, left-,
1664 * right-anchored, or both.
1665 * The individual domain names are compared with
1669 * 1 : pattern = a domain that may contain a '*' as a wildcard.
1670 * 2 : fqdn = domain name against which the patterns are compared.
1672 * Returns : 0 => domains are equivalent, else no match.
1674 *********************************************************************/
1675 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1677 char **pv, **fv; /* vectors */
1679 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1681 plen = pattern->dcnt;
1686 /* fqdn is too short to match this pattern */
1693 if (unanchored == ANCHOR_LEFT)
1698 * Convert this into a fully anchored pattern with
1699 * the fqdn and pattern the same length
1701 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1702 return simple_domaincmp(pv, fv, plen);
1704 else if (unanchored == 0)
1706 /* Fully anchored, check length */
1711 return simple_domaincmp(pv, fv, plen);
1713 else if (unanchored == ANCHOR_RIGHT)
1715 /* Left anchored, ignore all extra in fqdn */
1716 return simple_domaincmp(pv, fv, plen);
1722 int maxn = flen - plen;
1723 for (n = 0; n <= maxn; n++)
1725 if (!simple_domaincmp(pv, fv, plen))
1730 * Doesn't match from start of fqdn
1731 * Try skipping first part of fqdn