1 const char filters_rcs[] = "$Id: filters.c,v 1.38 2001/10/23 21:32:33 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', `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.38 2001/10/23 21:32:33 jongfoster
42 * Adding error-checking to selected functions
44 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
45 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
46 * filters.c. Added a FIXME in front of the offending code. I'll gladly
47 * put in a better/more robust fix for all parties if one is presented...
48 * It seems that just returning 200 instead of 404 would pretty much fix
49 * it for everyone, but I don't know all the history of the problem.
51 * Revision 1.36 2001/10/10 16:44:16 oes
52 * Added match_portlist function
54 * Revision 1.35 2001/10/07 15:41:23 oes
55 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
57 * New function remove_chunked_transfer_coding that strips chunked
58 * transfer coding to plain and is called by pcrs_filter_response
59 * and gif_deanimate_response if neccessary
61 * Improved handling of zero-change re_filter runs
63 * pcrs_filter_response and gif_deanimate_response now remove
64 * chunked transfer codeing before processing the body.
66 * Revision 1.34 2001/09/20 15:49:36 steudten
68 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
69 * See cgi.c fill_template().
71 * Revision 1.33 2001/09/16 17:05:14 jongfoster
72 * Removing unused #include showarg.h
74 * Revision 1.32 2001/09/16 13:21:27 jongfoster
75 * Changes to use new list functions.
77 * Revision 1.31 2001/09/16 11:38:02 jongfoster
78 * Splitting fill_template() into 2 functions:
79 * template_load() loads the file
80 * template_fill() performs the PCRS regexps.
81 * This is because the CGI edit interface has a "table row"
82 * template which is used many times in the page - this
83 * change means it's only loaded from disk once.
85 * Revision 1.30 2001/09/16 11:00:10 jongfoster
86 * New function alloc_http_response, for symmetry with free_http_response
88 * Revision 1.29 2001/09/13 23:32:40 jongfoster
89 * Moving image data to cgi.c rather than cgi.h
90 * Fixing a GPF under Win32 (and any other OS that protects global
91 * constants from being written to).
93 * Revision 1.28 2001/09/10 10:18:51 oes
94 * Silenced compiler warnings
96 * Revision 1.27 2001/08/05 16:06:20 jongfoster
97 * Modifiying "struct map" so that there are now separate header and
98 * "map_entry" structures. This means that functions which modify a
99 * map no longer need to return a pointer to the modified map.
100 * Also, it no longer reverses the order of the entries (which may be
101 * important with some advanced template substitutions).
103 * Revision 1.26 2001/07/30 22:08:36 jongfoster
104 * Tidying up #defines:
105 * - All feature #defines are now of the form FEATURE_xxx
106 * - Permanently turned off WIN_GUI_EDIT
107 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
109 * Revision 1.25 2001/07/26 10:09:46 oes
110 * Made browser detection a little less naive
112 * Revision 1.24 2001/07/25 17:22:51 oes
113 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
115 * Revision 1.23 2001/07/23 13:40:12 oes
116 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
118 * Revision 1.22 2001/07/18 12:29:34 oes
119 * - Made gif_deanimate_response respect
120 * csp->action->string[ACTION_STRING_DEANIMATE]
121 * - Logging cosmetics
123 * Revision 1.21 2001/07/13 13:59:53 oes
124 * - Introduced gif_deanimate_response which shares the
125 * generic content modification interface of pcrs_filter_response
126 * and acts as a wrapper to deanimate.c:gif_deanimate()
127 * - Renamed re_process_buffer to pcrs_filter_response
128 * - pcrs_filter_response now returns NULL on failiure
129 * - Removed all #ifdef PCRS
131 * Revision 1.20 2001/07/01 17:01:04 oes
132 * Added comments and missing return statement in is_untrusted_url()
134 * Revision 1.19 2001/06/29 21:45:41 oes
135 * Indentation, CRLF->LF, Tab-> Space
137 * Revision 1.18 2001/06/29 13:27:38 oes
138 * - Cleaned up, renamed and reorderd functions
139 * and improved comments
142 * - Ported to CGI platform. Now delivers
143 * http_response or NULL
144 * - Unified HTML and GIF generation (moved image detection
145 * and GIF generation here from jcc.c:chat())
146 * - Fixed HTTP status to:
147 * - 403 (Forbidden) for the "blocked" HTML message
148 * - 200 (OK) for GIF answers
149 * - 302 (Redirect) for redirect to GIF
152 * - Ported to CGI platform. Now delivers
153 * http_response or NULL
154 * - Separated detection of untrusted URL into
155 * (bool)is_untrusted_url
156 * - Added enforcement of untrusted requests
158 * - Moved redirect_url() from cgi.c to here
159 * and ported it to the CGI platform
161 * - Removed logentry from cancelled commit
163 * Revision 1.17 2001/06/09 10:55:28 jongfoster
164 * Changing BUFSIZ ==> BUFFER_SIZE
166 * Revision 1.16 2001/06/07 23:10:26 jongfoster
167 * Allowing unanchored domain patterns to back off and retry
168 * if they partially match. Optimized right-anchored patterns.
169 * Moving ACL and forward files into config file.
170 * Replacing struct gateway with struct forward_spec
172 * Revision 1.15 2001/06/03 19:12:00 oes
173 * extracted-CGI relevant stuff
175 * Revision 1.14 2001/06/01 10:30:55 oes
176 * Added optional left-anchoring to domaincmp
178 * Revision 1.13 2001/05/31 21:21:30 jongfoster
179 * Permissionsfile / actions file changes:
180 * - Changed "permission" to "action" throughout
181 * - changes to file format to allow string parameters
182 * - Moved helper functions to actions.c
184 * Revision 1.12 2001/05/31 17:35:20 oes
186 * - Enhanced domain part globbing with infix and prefix asterisk
187 * matching and optional unanchored operation
189 * Revision 1.11 2001/05/29 11:53:23 oes
190 * "See why" link added to "blocked" page
192 * Revision 1.10 2001/05/29 09:50:24 jongfoster
193 * Unified blocklist/imagelist/permissionslist.
194 * File format is still under discussion, but the internal changes
197 * Also modified interceptor behaviour:
198 * - We now intercept all URLs beginning with one of the following
199 * prefixes (and *only* these prefixes):
201 * * http://ijbswa.sf.net/config/
202 * * http://ijbswa.sourceforge.net/config/
203 * - New interceptors "home page" - go to http://i.j.b/ to see it.
204 * - Internal changes so that intercepted and fast redirect pages
205 * are not replaced with an image.
206 * - Interceptors now have the option to send a binary page direct
207 * to the client. (i.e. ijb-send-banner uses this)
208 * - Implemented show-url-info interceptor. (Which is why I needed
209 * the above interceptors changes - a typical URL is
210 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
211 * The previous mechanism would not have intercepted that, and
212 * if it had been intercepted then it then it would have replaced
215 * Revision 1.9 2001/05/27 22:17:04 oes
217 * - re_process_buffer no longer writes the modified buffer
218 * to the client, which was very ugly. It now returns the
219 * buffer, which it is then written by chat.
221 * - content_length now adjusts the Content-Length: header
222 * for modified documents rather than crunch()ing it.
223 * (Length info in csp->content_length, which is 0 for
224 * unmodified documents)
226 * - For this to work, sed() is called twice when filtering.
228 * Revision 1.8 2001/05/26 17:13:28 jongfoster
229 * Filled in a function comment.
231 * Revision 1.7 2001/05/26 15:26:15 jongfoster
232 * ACL feature now provides more security by immediately dropping
233 * connections from untrusted hosts.
235 * Revision 1.6 2001/05/26 00:28:36 jongfoster
236 * Automatic reloading of config file.
237 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
238 * Most of the global variables have been moved to a new
239 * struct configuration_spec, accessed through csp->config->globalname
240 * Most of the globals remaining are used by the Win32 GUI.
242 * Revision 1.5 2001/05/25 22:34:30 jongfoster
245 * Revision 1.4 2001/05/22 18:46:04 oes
247 * - Enabled filtering banners by size rather than URL
248 * by adding patterns that replace all standard banner
249 * sizes with the "Junkbuster" gif to the re_filterfile
251 * - Enabled filtering WebBugs by providing a pattern
252 * which kills all 1x1 images
254 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
255 * which is selected by the (nonstandard and therefore
256 * capital) letter 'U' in the option string.
257 * It causes the quantifiers to be ungreedy by default.
258 * Appending a ? turns back to greedy (!).
260 * - Added a new interceptor ijb-send-banner, which
261 * sends back the "Junkbuster" gif. Without imagelist or
262 * MSIE detection support, or if tinygif = 1, or the
263 * URL isn't recognized as an imageurl, a lame HTML
264 * explanation is sent instead.
266 * - Added new feature, which permits blocking remote
267 * script redirects and firing back a local redirect
269 * The feature is conditionally compiled, i.e. it
270 * can be disabled with --disable-fast-redirects,
271 * plus it must be activated by a "fast-redirects"
272 * line in the config file, has its own log level
273 * and of course wants to be displayed by show-proxy-args
274 * Note: Boy, all the #ifdefs in 1001 locations and
275 * all the fumbling with configure.in and acconfig.h
276 * were *way* more work than the feature itself :-(
278 * - Because a generic redirect template was needed for
279 * this, tinygif = 3 now uses the same.
281 * - Moved GIFs, and other static HTTP response templates
286 * - Removed some >400 CRs again (Jon, you really worked
289 * Revision 1.3 2001/05/20 16:44:47 jongfoster
290 * Removing last hardcoded JunkBusters.com URLs.
292 * Revision 1.2 2001/05/20 01:21:20 jongfoster
293 * Version 2.9.4 checkin.
294 * - Merged popupfile and cookiefile, and added control over PCRS
295 * filtering, in new "permissionsfile".
296 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
297 * file error you now get a message box (in the Win32 GUI) rather
298 * than the program exiting with no explanation.
299 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
301 * - Removed tabs from "config"
302 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
303 * - Bumped up version number.
305 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
306 * Initial import of version 2.9.3 source tree
309 *********************************************************************/
315 #include <sys/types.h>
324 #endif /* ndef __OS2__ */
325 #include <netinet/in.h>
327 #include <winsock2.h>
328 #endif /* ndef _WIN32 */
332 #endif /* def __OS2__ */
340 #include "jbsockets.h"
341 #include "miscutil.h"
345 #include "deanimate.h"
351 const char filters_h_rcs[] = FILTERS_H_VERSION;
353 /* Fix a problem with Solaris. There should be no effect on other
355 * Solaris's isspace() is a macro which uses it's argument directly
356 * as an array index. Therefore we need to make sure that high-bit
357 * characters generate +ve values, and ideally we also want to make
358 * the argument match the declared parameter type of "int".
360 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
364 /*********************************************************************
366 * Function : block_acl
368 * Description : Block this request?
369 * Decide yes or no based on ACL file.
372 * 1 : dst = The proxy or gateway address this is going to.
373 * Or NULL to check all possible targets.
374 * 2 : csp = Current client state (buffers, headers, etc...)
375 * Also includes the client IP address.
377 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
379 *********************************************************************/
380 int block_acl(struct access_control_addr *dst, struct client_state *csp)
382 struct access_control_list *acl = csp->config->acl;
384 /* if not using an access control list, then permit the connection */
390 /* search the list */
393 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
397 /* Just want to check if they have any access */
398 if (acl->action == ACL_PERMIT)
403 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
404 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
406 if (acl->action == ACL_PERMIT)
424 /*********************************************************************
426 * Function : acl_addr
428 * Description : Called from `load_aclfile' to parse an ACL address.
431 * 1 : aspec = String specifying ACL address.
432 * 2 : aca = struct access_control_addr to fill in.
434 * Returns : 0 => Ok, everything else is an error.
436 *********************************************************************/
437 int acl_addr(char *aspec, struct access_control_addr *aca)
439 int i, masklength, port;
445 if ((p = strchr(aspec, '/')))
449 if (ijb_isdigit(*p) == 0)
453 masklength = atoi(p);
456 if ((masklength < 0) || (masklength > 32))
461 if ((p = strchr(aspec, ':')))
465 if (ijb_isdigit(*p) == 0)
474 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
478 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
482 /* build the netmask */
484 for (i=1; i <= masklength ; i++)
486 aca->mask |= (1 << (32 - i));
489 /* now mask off the host portion of the ip address
490 * (i.e. save on the network portion of the address).
492 aca->addr = aca->addr & aca->mask;
497 #endif /* def FEATURE_ACL */
500 /*********************************************************************
502 * Function : match_portlist
504 * Description : Check if a given number is covered by a comma
505 * separated list of numbers and ranges (a,b-c,d,..)
508 * 1 : portlist = String with list
509 * 2 : port = port to check
511 * Returns : 0 => no match
514 *********************************************************************/
515 int match_portlist(const char *portlist, int port)
517 char *min, *max, *next, *portlist_copy;
519 min = next = portlist_copy = strdup(portlist);
522 * Zero-terminate first item and remember offset for next
524 if (NULL != (next = strchr(portlist_copy, (int) ',')))
530 * Loop through all items, checking for match
534 if (NULL == (max = strchr(min, (int) '-')))
537 * No dash, check for equality
539 if (port == atoi(min))
548 * This is a range, so check if between min and max,
549 * or, if max was omitted, between min and 65K
552 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
566 * Zero-terminate next item and remember offset for n+1
568 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
580 /*********************************************************************
582 * Function : block_url
584 * Description : Called from `chat'. Check to see if we need to block this.
587 * 1 : csp = Current client state (buffers, headers, etc...)
589 * Returns : NULL => unblocked, else HTTP block response
591 *********************************************************************/
592 struct http_response *block_url(struct client_state *csp)
594 #ifdef FEATURE_IMAGE_BLOCKING
596 #endif /* def FEATURE_IMAGE_BLOCKING */
597 struct http_response *rsp;
600 * If it's not blocked, don't block it ;-)
602 if ((csp->action->flags & ACTION_BLOCK) == 0)
608 * Else, prepare a response
610 if (NULL == (rsp = alloc_http_response()))
612 return cgi_error_memory();
616 * If it's an image-url, send back an image or redirect
617 * as specified by the relevant +image action
619 #ifdef FEATURE_IMAGE_BLOCKING
620 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
623 /* determine HOW images should be blocked */
624 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
626 /* and handle accordingly: */
627 if ((p == NULL) || (0 == strcmpic(p, "logo")))
629 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
630 if (rsp->body == NULL)
632 free_http_response(rsp);
633 return cgi_error_memory();
635 rsp->content_length = image_junkbuster_gif_length;
637 if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
639 free_http_response(rsp);
640 return cgi_error_memory();
644 else if (0 == strcmpic(p, "blank"))
646 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
647 if (rsp->body == NULL)
649 free_http_response(rsp);
650 return cgi_error_memory();
652 rsp->content_length = image_blank_gif_length;
654 if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
656 free_http_response(rsp);
657 return cgi_error_memory();
663 rsp->status = strdup("302 Local Redirect from Junkbuster");
664 if (rsp->status == NULL)
666 free_http_response(rsp);
667 return cgi_error_memory();
670 if (enlist_unique_header(rsp->headers, "Location", p))
672 free_http_response(rsp);
673 return cgi_error_memory();
678 #endif /* def FEATURE_IMAGE_BLOCKING */
681 * Else, generate an HTML "blocked" message:
685 struct map * exports;
690 * The entire OS/2 community will hit the stupid Netscape bug
691 * (all three of us! :-) so we'll just keep ourselves out
692 * of this contentious debate and special-case ourselves.
693 * The problem is... a this point in parsing, we don't know
694 * what the csp->http->user_agent is (yet). So we can't use
695 * it to decide if we should work around the NS bug or not.
697 rsp->status = strdup("200 Request for blocked URL");
700 * Workaround for stupid Netscape bug which prevents
701 * pages from being displayed if loading a referenced
702 * JavaScript or style sheet fails. So make it appear
703 * as if it succeeded.
705 if (csp->http->user_agent
706 && !strncmpic(csp->http->user_agent, "mozilla", 7)
707 && !strstr(csp->http->user_agent, "compatible")
708 && !strstr(csp->http->user_agent, "Opera"))
710 rsp->status = strdup("200 Request for blocked URL");
714 rsp->status = strdup("404 Request for blocked URL");
717 if (rsp->status == NULL)
719 free_http_response(rsp);
720 return cgi_error_memory();
723 exports = default_exports(csp, NULL);
726 free_http_response(rsp);
727 return cgi_error_memory();
730 #ifdef FEATURE_FORCE_LOAD
731 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
732 #else /* ifndef FEATURE_FORCE_LOAD */
733 err = map_block_killer(exports, "force-support");
734 #endif /* ndef FEATURE_FORCE_LOAD */
736 err = err || map(exports, "hostport", 1, csp->http->hostport, 1);
737 err = err || map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
738 err = err || map(exports, "path", 1, csp->http->path, 1);
739 err = err || map(exports, "path-html", 1, html_encode(csp->http->path), 0);
744 free_http_response(rsp);
745 return cgi_error_memory();
748 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
751 free_http_response(rsp);
752 return cgi_error_memory();
756 return finish_http_response(rsp);
762 /*********************************************************************
764 * Function : trust_url FIXME: I should be called distrust_url
766 * Description : Calls is_untrusted_url to determine if the URL is trusted
767 * and if not, returns a HTTP 304 response with a reject message.
770 * 1 : csp = Current client state (buffers, headers, etc...)
772 * Returns : NULL => trusted, else http_response.
774 *********************************************************************/
775 struct http_response *trust_url(struct client_state *csp)
777 struct http_response *rsp;
778 struct map * exports;
779 char buf[BUFFER_SIZE];
781 struct url_spec **tl;
786 * Don't bother to work on trusted URLs
788 if (!is_untrusted_url(csp))
794 * Else, prepare a response:
796 if (NULL == (rsp = alloc_http_response()))
798 return cgi_error_memory();
801 exports = default_exports(csp, NULL);
804 free_http_response(rsp);
805 return cgi_error_memory();
809 * Export the host, port, and referrer information
811 err = map(exports, "hostport", 1, csp->http->hostport, 1)
812 || map(exports, "path", 1, csp->http->path, 1)
813 || map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0)
814 || map(exports, "path-html", 1, html_encode(csp->http->path), 0);
816 if (csp->referrer && strlen(csp->referrer) > 9)
818 err = err || map(exports, "referrer", 1, csp->referrer + 9, 1);
819 err = err || map(exports, "referrer-html", 1, html_encode(csp->referrer + 9), 0);
823 err = err || map(exports, "referrer", 1, "unknown", 1);
824 err = err || map(exports, "referrer-html", 1, "unknown", 1);
830 free_http_response(rsp);
831 return cgi_error_memory();
835 * Export the trust list
838 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
840 sprintf(buf, "<li>%s</li>\n", t->spec);
841 string_append(&p, buf);
843 err = map(exports, "trusted-referrers", 1, p, 0);
848 free_http_response(rsp);
849 return cgi_error_memory();
853 * Export the trust info, if available
855 if (csp->config->trust_info->first)
857 struct list_entry *l;
860 for (l = csp->config->trust_info->first; l ; l = l->next)
862 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
863 string_append(&p, buf);
865 err = map(exports, "trust-info", 1, p, 0);
869 err = map_block_killer(exports, "have-trust-info");
875 free_http_response(rsp);
876 return cgi_error_memory();
880 * Export the force prefix or the force conditional block killer
882 #ifdef FEATURE_FORCE_LOAD
883 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
884 #else /* ifndef FEATURE_FORCE_LOAD */
885 err = map_block_killer(exports, "force-support");
886 #endif /* ndef FEATURE_FORCE_LOAD */
891 free_http_response(rsp);
892 return cgi_error_memory();
898 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
901 free_http_response(rsp);
902 return cgi_error_memory();
905 return finish_http_response(rsp);
907 #endif /* def FEATURE_TRUST */
910 #ifdef FEATURE_FAST_REDIRECTS
911 /*********************************************************************
913 * Function : redirect_url
915 * Description : Checks for redirection URLs and returns a HTTP redirect
916 * to the destination URL, if necessary
919 * 1 : csp = Current client state (buffers, headers, etc...)
921 * Returns : NULL if URL was clean, HTTP redirect otherwise.
923 *********************************************************************/
924 struct http_response *redirect_url(struct client_state *csp)
927 struct http_response *rsp;
929 p = q = csp->http->path;
930 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
933 * find the last URL encoded in the request
935 while ((p = strstr(p, "http://")))
941 * if there was any, generate and return a HTTP redirect
943 if (q != csp->http->path)
945 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
947 if (NULL == (rsp = alloc_http_response()))
949 return cgi_error_memory();
952 if ( enlist_unique_header(rsp->headers, "Location", q)
953 || (NULL == (rsp->status = strdup("302 Local Redirect from Junkbuster"))) )
955 free_http_response(rsp);
956 return cgi_error_memory();
959 return finish_http_response(rsp);
967 #endif /* def FEATURE_FAST_REDIRECTS */
970 #ifdef FEATURE_IMAGE_BLOCKING
971 /*********************************************************************
973 * Function : is_imageurl
975 * Description : Given a URL, decide whether it is an image or not,
976 * using either the info from a previous +image action
977 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
978 * the browser's accept header.
981 * 1 : csp = Current client state (buffers, headers, etc...)
983 * Returns : True (nonzero) if URL is an image, false (0)
986 *********************************************************************/
987 int is_imageurl(struct client_state *csp)
989 #ifdef FEATURE_IMAGE_DETECT_MSIE
990 if ((csp->accept_types
991 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
992 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
996 else if ((csp->accept_types
997 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
998 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
1002 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1004 return ((csp->action->flags & ACTION_IMAGE) != 0);
1007 #endif /* def FEATURE_IMAGE_BLOCKING */
1010 #ifdef FEATURE_COOKIE_JAR
1011 /*********************************************************************
1013 * Function : is_untrusted_url
1015 * Description : Should we "distrust" this URL (and block it)?
1017 * Yes if it matches a line in the trustfile, or if the
1018 * referrer matches a line starting with "+" in the
1023 * 1 : csp = Current client state (buffers, headers, etc...)
1025 * Returns : 0 => trusted, 1 => untrusted
1027 *********************************************************************/
1028 int is_untrusted_url(struct client_state *csp)
1030 struct file_list *fl;
1031 struct block_spec *b;
1032 struct url_spec url[1], **tl, *t;
1033 struct http_request rhttp[1];
1037 * If we don't have a trustlist, we trust everybody
1039 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1046 * Do we trust the request URL itself?
1048 *url = dsplit(csp->http->host);
1050 /* if splitting the domain fails, punt */
1051 if (url->dbuf == NULL) return(0);
1053 memset(rhttp, '\0', sizeof(*rhttp));
1055 for (b = b->next; b ; b = b->next)
1057 if ((b->url->port == 0) || (b->url->port == csp->http->port))
1059 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1061 if ((b->url->path == NULL) ||
1063 (regexec(b->url->preg, csp->http->path, 0, NULL, 0) == 0)
1065 (strncmp(b->url->path, csp->http->path, b->url->pathlen) == 0)
1072 if (b->reject == 0) return(0);
1083 if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
1085 /* no referrer was supplied */
1089 /* forge a URL from the referrer so we can use
1090 * convert_url() to parse it into its components.
1094 p = strsav(p, "GET ");
1095 p = strsav(p, csp->referrer + 9); /* skip over "Referer: " */
1096 p = strsav(p, " HTTP/1.0");
1098 parse_http_request(p, rhttp, csp);
1101 if (rhttp->cmd == NULL)
1108 * If not, do we maybe trust its referrer?
1110 *url = dsplit(rhttp->host);
1112 /* if splitting the domain fails, punt */
1113 if (url->dbuf == NULL) return(1);
1115 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
1117 if ((t->port == 0) || (t->port == rhttp->port))
1119 if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
1121 if ((t->path == NULL) ||
1123 (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
1125 (strncmp(t->path, rhttp->path, t->pathlen) == 0)
1129 /* if the URL's referrer is from a trusted referrer, then
1130 * add the target spec to the trustfile as an unblocked
1131 * domain and return NULL (which means it's OK).
1139 if ((fp = fopen(csp->config->trustfile, "a")))
1144 h = strsav(h, csp->http->hostport);
1146 p = csp->http->path;
1150 /* since this path points into a user's home space
1151 * be sure to include this spec in the trustfile.
1153 if ((p = strchr(p, '/')))
1156 h = strsav(h, csp->http->path); /* FIXME: p?! */
1161 fprintf(fp, "%s\n", h);
1172 #endif /* def FEATURE_COOKIE_JAR */
1175 /*********************************************************************
1177 * Function : pcrs_filter_response
1179 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
1180 * to the text buffer that's been accumulated in
1181 * csp->iob->buf and set csp->content_length to the modified
1182 * size and raise the CSP_FLAG_MODIFIED flag if appropriate.
1185 * 1 : csp = Current client state (buffers, headers, etc...)
1187 * Returns : a pointer to the (newly allocated) modified buffer.
1188 * or NULL in case something went wrong
1190 *********************************************************************/
1191 char *pcrs_filter_response(struct client_state *csp)
1196 char *old = csp->iob->cur, *new = NULL;
1199 struct file_list *fl;
1200 struct re_filterfile_spec *b;
1203 if (csp->iob->cur >= csp->iob->eod)
1207 size = csp->iob->eod - csp->iob->cur;
1210 * If the body has a "chunked" transfer-encoding,
1211 * get rid of it first, adjusting size and iob->eod
1213 if (csp->flags & CSP_FLAG_CHUNKED)
1215 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1216 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1220 csp->iob->eod = csp->iob->cur + size;
1221 csp->flags |= CSP_FLAG_MODIFIED;
1224 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1226 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1230 if ( NULL == b->joblist )
1232 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1236 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1237 csp->http->hostport, csp->http->path, size);
1239 /* Apply all jobs from the joblist */
1240 for (job = b->joblist; NULL != job; job = job->next)
1242 hits += pcrs_execute(job, old, size, &new, &size);
1243 if (old != csp->iob->cur) free(old);
1247 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1250 * If there were no hits, destroy our copy and let
1251 * chat() use the original in csp->iob
1259 csp->flags |= CSP_FLAG_MODIFIED;
1260 csp->content_length = size;
1268 /*********************************************************************
1270 * Function : gif_deanimate_response
1272 * Description : Deanimate the GIF image that has been accumulated in
1273 * csp->iob->buf, set csp->content_length to the modified
1274 * size and raise the CSP_FLAG_MODIFIED flag.
1277 * 1 : csp = Current client state (buffers, headers, etc...)
1279 * Returns : a pointer to the (newly allocated) modified buffer.
1280 * or NULL in case something went wrong.
1282 *********************************************************************/
1283 char *gif_deanimate_response(struct client_state *csp)
1285 struct binbuffer *in, *out;
1287 int size = csp->iob->eod - csp->iob->cur;
1290 * If the body has a "chunked" transfer-encoding,
1291 * get rid of it first, adjusting size and iob->eod
1293 if (csp->flags & CSP_FLAG_CHUNKED)
1295 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1296 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1300 csp->iob->eod = csp->iob->cur + size;
1301 csp->flags |= CSP_FLAG_MODIFIED;
1304 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1305 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1307 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1311 in->buffer = csp->iob->cur;
1314 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1316 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1323 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1324 csp->content_length = out->offset;
1325 csp->flags |= CSP_FLAG_MODIFIED;
1335 /*********************************************************************
1337 * Function : remove_chunked_transfer_coding
1339 * Description : In-situ remove the "chunked" transfer coding as defined
1340 * in rfc2616 from a buffer.
1343 * 1 : buffer = Pointer to the text buffer
1344 * 2 : size = Number of bytes to be processed
1346 * Returns : The new size, i.e. the number of bytes from buffer which
1347 * are occupied by the stripped body, or 0 in case something
1350 *********************************************************************/
1351 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1354 unsigned int chunksize = 0;
1355 char *from_p, *to_p;
1358 from_p = to_p = buffer;
1360 if (sscanf(buffer, "%x", &chunksize) != 1)
1362 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1366 while (chunksize > 0)
1368 if (NULL == (from_p = strstr(from_p, "\r\n")))
1370 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1373 newsize += chunksize;
1376 memmove(to_p, from_p, (size_t) chunksize);
1377 to_p = buffer + newsize;
1378 from_p += chunksize + 2;
1380 if (sscanf(from_p, "%x", &chunksize) != 1)
1382 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1387 /* FIXME: Should this get its own loglevel? */
1388 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1394 /*********************************************************************
1396 * Function : url_actions
1398 * Description : Gets the actions for this URL.
1401 * 1 : http = http_request request for blocked URLs
1402 * 2 : csp = Current client state (buffers, headers, etc...)
1406 *********************************************************************/
1407 void url_actions(struct http_request *http,
1408 struct client_state *csp)
1410 struct file_list *fl;
1411 struct url_actions *b;
1413 init_current_action(csp->action);
1415 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1420 apply_url_actions(csp->action, http, b);
1425 /*********************************************************************
1427 * Function : apply_url_actions
1429 * Description : Applies a list of URL actions.
1432 * 1 : action = Destination.
1433 * 2 : http = Current URL
1434 * 3 : b = list of URL actions to apply
1438 *********************************************************************/
1439 void apply_url_actions(struct current_action_spec *action,
1440 struct http_request *http,
1441 struct url_actions *b)
1443 struct url_spec url[1];
1447 /* Should never happen */
1451 *url = dsplit(http->host);
1453 /* if splitting the domain fails, punt */
1454 if (url->dbuf == NULL)
1459 for (b = b->next; NULL != b; b = b->next)
1461 if ((b->url->port == 0) || (b->url->port == http->port))
1463 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1465 if ((b->url->path == NULL) ||
1467 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
1469 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
1473 merge_current_action(action, b->action);
1484 /*********************************************************************
1486 * Function : forward_url
1488 * Description : Should we forward this to another proxy?
1491 * 1 : http = http_request request for current URL
1492 * 2 : csp = Current client state (buffers, headers, etc...)
1494 * Returns : Pointer to forwarding information.
1496 *********************************************************************/
1497 const struct forward_spec * forward_url(struct http_request *http,
1498 struct client_state *csp)
1500 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1501 struct forward_spec *fwd = csp->config->forward;
1502 struct url_spec url[1];
1506 return(fwd_default);
1509 *url = dsplit(http->host);
1511 /* if splitting the domain fails, punt */
1512 if (url->dbuf == NULL)
1514 return(fwd_default);
1519 if ((fwd->url->port == 0) || (fwd->url->port == http->port))
1521 if ((fwd->url->domain[0] == '\0') || (domaincmp(fwd->url, url) == 0))
1523 if ((fwd->url->path == NULL) ||
1525 (regexec(fwd->url->preg, http->path, 0, NULL, 0) == 0)
1527 (strncmp(fwd->url->path, http->path, fwd->url->pathlen) == 0)
1542 return(fwd_default);
1547 /*********************************************************************
1551 * Description : Takes a domain and returns a pointer to a url_spec
1552 * structure populated with dbuf, dcnt and dvec. The
1553 * other fields in the structure that is returned are zero.
1556 * 1 : domain = a URL address
1558 * Returns : url_spec structure populated with dbuf, dcnt and dvec.
1559 * On error, the dbuf field will be set to NULL. (As
1560 * will all the others, but you don't need to check
1563 * FIXME: Returning a structure is horribly inefficient, please can
1564 * this structure take a (struct url_spec * dest)
1567 *********************************************************************/
1568 struct url_spec dsplit(char *domain)
1570 struct url_spec ret[1];
1571 char *v[BUFFER_SIZE];
1575 memset(ret, '\0', sizeof(*ret));
1577 if (domain[strlen(domain) - 1] == '.')
1579 ret->unanchored |= ANCHOR_RIGHT;
1582 if (domain[0] == '.')
1584 ret->unanchored |= ANCHOR_LEFT;
1587 ret->dbuf = strdup(domain);
1588 if (NULL == ret->dbuf)
1593 /* map to lower case */
1594 for (p = ret->dbuf; *p ; p++)
1596 *p = tolower((int)(unsigned char)*p);
1599 /* split the domain name into components */
1600 ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
1605 memset(ret, '\0', sizeof(ret));
1608 else if (ret->dcnt == 0)
1613 /* save a copy of the pointers in dvec */
1614 size = ret->dcnt * sizeof(*ret->dvec);
1616 ret->dvec = (char **)malloc(size);
1617 if (NULL == ret->dvec)
1620 memset(ret, '\0', sizeof(ret));
1624 memcpy(ret->dvec, v, size);
1631 /*********************************************************************
1633 * Function : simple_domaincmp
1635 * Description : Domain-wise Compare fqdn's. The comparison is
1636 * both left- and right-anchored. The individual
1637 * domain names are compared with simplematch().
1638 * This is only used by domaincmp.
1641 * 1 : pv = array of patterns to compare
1642 * 2 : fv = array of domain components to compare
1643 * 3 : len = length of the arrays (both arrays are the
1644 * same length - if they weren't, it couldn't
1645 * possibly be a match).
1647 * Returns : 0 => domains are equivalent, else no match.
1649 *********************************************************************/
1650 static int simple_domaincmp(char **pv, char **fv, int len)
1654 for (n = 0; n < len; n++)
1656 if (simplematch(pv[n], fv[n]))
1667 /*********************************************************************
1669 * Function : domaincmp
1671 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1672 * pattern->unachored, the comparison is un-, left-,
1673 * right-anchored, or both.
1674 * The individual domain names are compared with
1678 * 1 : pattern = a domain that may contain a '*' as a wildcard.
1679 * 2 : fqdn = domain name against which the patterns are compared.
1681 * Returns : 0 => domains are equivalent, else no match.
1683 *********************************************************************/
1684 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1686 char **pv, **fv; /* vectors */
1688 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1690 plen = pattern->dcnt;
1695 /* fqdn is too short to match this pattern */
1702 if (unanchored == ANCHOR_LEFT)
1707 * Convert this into a fully anchored pattern with
1708 * the fqdn and pattern the same length
1710 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1711 return simple_domaincmp(pv, fv, plen);
1713 else if (unanchored == 0)
1715 /* Fully anchored, check length */
1720 return simple_domaincmp(pv, fv, plen);
1722 else if (unanchored == ANCHOR_RIGHT)
1724 /* Left anchored, ignore all extra in fqdn */
1725 return simple_domaincmp(pv, fv, plen);
1731 int maxn = flen - plen;
1732 for (n = 0; n <= maxn; n++)
1734 if (!simple_domaincmp(pv, fv, plen))
1739 * Doesn't match from start of fqdn
1740 * Try skipping first part of fqdn