1 const char filters_rcs[] = "$Id: filters.c,v 1.36 2001/10/10 16:44:16 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `acl_addr', `add_stats', `block_acl', `block_imageurl',
9 * `block_url', `url_actions', `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.36 2001/10/10 16:44:16 oes
42 * Added match_portlist function
44 * Revision 1.35 2001/10/07 15:41:23 oes
45 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
47 * New function remove_chunked_transfer_coding that strips chunked
48 * transfer coding to plain and is called by pcrs_filter_response
49 * and gif_deanimate_response if neccessary
51 * Improved handling of zero-change re_filter runs
53 * pcrs_filter_response and gif_deanimate_response now remove
54 * chunked transfer codeing before processing the body.
56 * Revision 1.34 2001/09/20 15:49:36 steudten
58 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
59 * See cgi.c fill_template().
61 * Revision 1.33 2001/09/16 17:05:14 jongfoster
62 * Removing unused #include showarg.h
64 * Revision 1.32 2001/09/16 13:21:27 jongfoster
65 * Changes to use new list functions.
67 * Revision 1.31 2001/09/16 11:38:02 jongfoster
68 * Splitting fill_template() into 2 functions:
69 * template_load() loads the file
70 * template_fill() performs the PCRS regexps.
71 * This is because the CGI edit interface has a "table row"
72 * template which is used many times in the page - this
73 * change means it's only loaded from disk once.
75 * Revision 1.30 2001/09/16 11:00:10 jongfoster
76 * New function alloc_http_response, for symmetry with free_http_response
78 * Revision 1.29 2001/09/13 23:32:40 jongfoster
79 * Moving image data to cgi.c rather than cgi.h
80 * Fixing a GPF under Win32 (and any other OS that protects global
81 * constants from being written to).
83 * Revision 1.28 2001/09/10 10:18:51 oes
84 * Silenced compiler warnings
86 * Revision 1.27 2001/08/05 16:06:20 jongfoster
87 * Modifiying "struct map" so that there are now separate header and
88 * "map_entry" structures. This means that functions which modify a
89 * map no longer need to return a pointer to the modified map.
90 * Also, it no longer reverses the order of the entries (which may be
91 * important with some advanced template substitutions).
93 * Revision 1.26 2001/07/30 22:08:36 jongfoster
94 * Tidying up #defines:
95 * - All feature #defines are now of the form FEATURE_xxx
96 * - Permanently turned off WIN_GUI_EDIT
97 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
99 * Revision 1.25 2001/07/26 10:09:46 oes
100 * Made browser detection a little less naive
102 * Revision 1.24 2001/07/25 17:22:51 oes
103 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
105 * Revision 1.23 2001/07/23 13:40:12 oes
106 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
108 * Revision 1.22 2001/07/18 12:29:34 oes
109 * - Made gif_deanimate_response respect
110 * csp->action->string[ACTION_STRING_DEANIMATE]
111 * - Logging cosmetics
113 * Revision 1.21 2001/07/13 13:59:53 oes
114 * - Introduced gif_deanimate_response which shares the
115 * generic content modification interface of pcrs_filter_response
116 * and acts as a wrapper to deanimate.c:gif_deanimate()
117 * - Renamed re_process_buffer to pcrs_filter_response
118 * - pcrs_filter_response now returns NULL on failiure
119 * - Removed all #ifdef PCRS
121 * Revision 1.20 2001/07/01 17:01:04 oes
122 * Added comments and missing return statement in is_untrusted_url()
124 * Revision 1.19 2001/06/29 21:45:41 oes
125 * Indentation, CRLF->LF, Tab-> Space
127 * Revision 1.18 2001/06/29 13:27:38 oes
128 * - Cleaned up, renamed and reorderd functions
129 * and improved comments
132 * - Ported to CGI platform. Now delivers
133 * http_response or NULL
134 * - Unified HTML and GIF generation (moved image detection
135 * and GIF generation here from jcc.c:chat())
136 * - Fixed HTTP status to:
137 * - 403 (Forbidden) for the "blocked" HTML message
138 * - 200 (OK) for GIF answers
139 * - 302 (Redirect) for redirect to GIF
142 * - Ported to CGI platform. Now delivers
143 * http_response or NULL
144 * - Separated detection of untrusted URL into
145 * (bool)is_untrusted_url
146 * - Added enforcement of untrusted requests
148 * - Moved redirect_url() from cgi.c to here
149 * and ported it to the CGI platform
151 * - Removed logentry from cancelled commit
153 * Revision 1.17 2001/06/09 10:55:28 jongfoster
154 * Changing BUFSIZ ==> BUFFER_SIZE
156 * Revision 1.16 2001/06/07 23:10:26 jongfoster
157 * Allowing unanchored domain patterns to back off and retry
158 * if they partially match. Optimized right-anchored patterns.
159 * Moving ACL and forward files into config file.
160 * Replacing struct gateway with struct forward_spec
162 * Revision 1.15 2001/06/03 19:12:00 oes
163 * extracted-CGI relevant stuff
165 * Revision 1.14 2001/06/01 10:30:55 oes
166 * Added optional left-anchoring to domaincmp
168 * Revision 1.13 2001/05/31 21:21:30 jongfoster
169 * Permissionsfile / actions file changes:
170 * - Changed "permission" to "action" throughout
171 * - changes to file format to allow string parameters
172 * - Moved helper functions to actions.c
174 * Revision 1.12 2001/05/31 17:35:20 oes
176 * - Enhanced domain part globbing with infix and prefix asterisk
177 * matching and optional unanchored operation
179 * Revision 1.11 2001/05/29 11:53:23 oes
180 * "See why" link added to "blocked" page
182 * Revision 1.10 2001/05/29 09:50:24 jongfoster
183 * Unified blocklist/imagelist/permissionslist.
184 * File format is still under discussion, but the internal changes
187 * Also modified interceptor behaviour:
188 * - We now intercept all URLs beginning with one of the following
189 * prefixes (and *only* these prefixes):
191 * * http://ijbswa.sf.net/config/
192 * * http://ijbswa.sourceforge.net/config/
193 * - New interceptors "home page" - go to http://i.j.b/ to see it.
194 * - Internal changes so that intercepted and fast redirect pages
195 * are not replaced with an image.
196 * - Interceptors now have the option to send a binary page direct
197 * to the client. (i.e. ijb-send-banner uses this)
198 * - Implemented show-url-info interceptor. (Which is why I needed
199 * the above interceptors changes - a typical URL is
200 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
201 * The previous mechanism would not have intercepted that, and
202 * if it had been intercepted then it then it would have replaced
205 * Revision 1.9 2001/05/27 22:17:04 oes
207 * - re_process_buffer no longer writes the modified buffer
208 * to the client, which was very ugly. It now returns the
209 * buffer, which it is then written by chat.
211 * - content_length now adjusts the Content-Length: header
212 * for modified documents rather than crunch()ing it.
213 * (Length info in csp->content_length, which is 0 for
214 * unmodified documents)
216 * - For this to work, sed() is called twice when filtering.
218 * Revision 1.8 2001/05/26 17:13:28 jongfoster
219 * Filled in a function comment.
221 * Revision 1.7 2001/05/26 15:26:15 jongfoster
222 * ACL feature now provides more security by immediately dropping
223 * connections from untrusted hosts.
225 * Revision 1.6 2001/05/26 00:28:36 jongfoster
226 * Automatic reloading of config file.
227 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
228 * Most of the global variables have been moved to a new
229 * struct configuration_spec, accessed through csp->config->globalname
230 * Most of the globals remaining are used by the Win32 GUI.
232 * Revision 1.5 2001/05/25 22:34:30 jongfoster
235 * Revision 1.4 2001/05/22 18:46:04 oes
237 * - Enabled filtering banners by size rather than URL
238 * by adding patterns that replace all standard banner
239 * sizes with the "Junkbuster" gif to the re_filterfile
241 * - Enabled filtering WebBugs by providing a pattern
242 * which kills all 1x1 images
244 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
245 * which is selected by the (nonstandard and therefore
246 * capital) letter 'U' in the option string.
247 * It causes the quantifiers to be ungreedy by default.
248 * Appending a ? turns back to greedy (!).
250 * - Added a new interceptor ijb-send-banner, which
251 * sends back the "Junkbuster" gif. Without imagelist or
252 * MSIE detection support, or if tinygif = 1, or the
253 * URL isn't recognized as an imageurl, a lame HTML
254 * explanation is sent instead.
256 * - Added new feature, which permits blocking remote
257 * script redirects and firing back a local redirect
259 * The feature is conditionally compiled, i.e. it
260 * can be disabled with --disable-fast-redirects,
261 * plus it must be activated by a "fast-redirects"
262 * line in the config file, has its own log level
263 * and of course wants to be displayed by show-proxy-args
264 * Note: Boy, all the #ifdefs in 1001 locations and
265 * all the fumbling with configure.in and acconfig.h
266 * were *way* more work than the feature itself :-(
268 * - Because a generic redirect template was needed for
269 * this, tinygif = 3 now uses the same.
271 * - Moved GIFs, and other static HTTP response templates
276 * - Removed some >400 CRs again (Jon, you really worked
279 * Revision 1.3 2001/05/20 16:44:47 jongfoster
280 * Removing last hardcoded JunkBusters.com URLs.
282 * Revision 1.2 2001/05/20 01:21:20 jongfoster
283 * Version 2.9.4 checkin.
284 * - Merged popupfile and cookiefile, and added control over PCRS
285 * filtering, in new "permissionsfile".
286 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
287 * file error you now get a message box (in the Win32 GUI) rather
288 * than the program exiting with no explanation.
289 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
291 * - Removed tabs from "config"
292 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
293 * - Bumped up version number.
295 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
296 * Initial import of version 2.9.3 source tree
299 *********************************************************************/
305 #include <sys/types.h>
313 #include <netinet/in.h>
315 #include <winsock2.h>
324 #include "jbsockets.h"
325 #include "miscutil.h"
329 #include "deanimate.h"
335 const char filters_h_rcs[] = FILTERS_H_VERSION;
337 /* Fix a problem with Solaris. There should be no effect on other
339 * Solaris's isspace() is a macro which uses it's argument directly
340 * as an array index. Therefore we need to make sure that high-bit
341 * characters generate +ve values, and ideally we also want to make
342 * the argument match the declared parameter type of "int".
344 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
348 /*********************************************************************
350 * Function : block_acl
352 * Description : Block this request?
353 * Decide yes or no based on ACL file.
356 * 1 : dst = The proxy or gateway address this is going to.
357 * Or NULL to check all possible targets.
358 * 2 : csp = Current client state (buffers, headers, etc...)
359 * Also includes the client IP address.
361 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
363 *********************************************************************/
364 int block_acl(struct access_control_addr *dst, struct client_state *csp)
366 struct access_control_list *acl = csp->config->acl;
368 /* if not using an access control list, then permit the connection */
374 /* search the list */
377 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
381 /* Just want to check if they have any access */
382 if (acl->action == ACL_PERMIT)
387 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
388 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
390 if (acl->action == ACL_PERMIT)
408 /*********************************************************************
410 * Function : acl_addr
412 * Description : Called from `load_aclfile' to parse an ACL address.
415 * 1 : aspec = String specifying ACL address.
416 * 2 : aca = struct access_control_addr to fill in.
418 * Returns : 0 => Ok, everything else is an error.
420 *********************************************************************/
421 int acl_addr(char *aspec, struct access_control_addr *aca)
423 int i, masklength, port;
429 if ((p = strchr(aspec, '/')))
433 if (ijb_isdigit(*p) == 0)
437 masklength = atoi(p);
440 if ((masklength < 0) || (masklength > 32))
445 if ((p = strchr(aspec, ':')))
449 if (ijb_isdigit(*p) == 0)
458 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
462 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
466 /* build the netmask */
468 for (i=1; i <= masklength ; i++)
470 aca->mask |= (1 << (32 - i));
473 /* now mask off the host portion of the ip address
474 * (i.e. save on the network portion of the address).
476 aca->addr = aca->addr & aca->mask;
481 #endif /* def FEATURE_ACL */
484 /*********************************************************************
486 * Function : match_portlist
488 * Description : Check if a given number is covered by a comma
489 * separated list of numbers and ranges (a,b-c,d,..)
492 * 1 : portlist = String with list
493 * 2 : port = port to check
495 * Returns : 0 => no match
498 *********************************************************************/
499 int match_portlist(const char *portlist, int port)
501 char *min, *max, *next, *portlist_copy;
503 min = next = portlist_copy = strdup(portlist);
506 * Zero-terminate first item and remember offset for next
508 if (NULL != (next = strchr(portlist_copy, (int) ',')))
514 * Loop through all items, checking for match
518 if (NULL == (max = strchr(min, (int) '-')))
521 * No dash, check for equality
523 if (port == atoi(min))
532 * This is a range, so check if between min and max,
533 * or, if max was omitted, between min and 65K
536 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
550 * Zero-terminate next item and remember offset for n+1
552 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
564 /*********************************************************************
566 * Function : block_url
568 * Description : Called from `chat'. Check to see if we need to block this.
571 * 1 : csp = Current client state (buffers, headers, etc...)
573 * Returns : NULL => unblocked, else HTTP block response
575 *********************************************************************/
576 struct http_response *block_url(struct client_state *csp)
578 #ifdef FEATURE_IMAGE_BLOCKING
580 #endif /* def FEATURE_IMAGE_BLOCKING */
581 struct http_response *rsp;
584 * If it's not blocked, don't block it ;-)
586 if ((csp->action->flags & ACTION_BLOCK) == 0)
592 * Else, prepare a response
594 if (NULL == (rsp = alloc_http_response()))
600 * If it's an image-url, send back an image or redirect
601 * as specified by the relevant +image action
603 #ifdef FEATURE_IMAGE_BLOCKING
604 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
607 /* determine HOW images should be blocked */
608 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
610 /* and handle accordingly: */
611 if ((p == NULL) || (0 == strcmpic(p, "logo")))
613 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
614 rsp->content_length = image_junkbuster_gif_length;
615 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
618 else if (0 == strcmpic(p, "blank"))
620 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
621 rsp->content_length = image_blank_gif_length;
622 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
627 rsp->status = strdup("302 Local Redirect from Junkbuster");
628 enlist_unique_header(rsp->headers, "Location", p);
632 #endif /* def FEATURE_IMAGE_BLOCKING */
635 * Else, generate an HTML "blocked" message:
638 struct map * exports = default_exports(csp, NULL);
639 #ifdef FEATURE_FORCE_LOAD
640 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
641 #else /* ifndef FEATURE_FORCE_LOAD */
642 map_block_killer(exports, "force-support");
643 #endif /* ndef FEATURE_FORCE_LOAD */
645 map(exports, "hostport", 1, csp->http->hostport, 1);
646 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
647 map(exports, "path", 1, csp->http->path, 1);
648 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
650 rsp->body = template_load(csp, "blocked");
651 template_fill(&rsp->body, exports);
657 * The entire OS/2 community will hit the stupid Netscape bug
658 * (all three of us! :-) so we'll just keep ourselves out
659 * of this contentious debate and special-case ourselves.
660 * The problem is... a this point in parsing, we don't know
661 * what the csp->http->user_agent is (yet). So we can't use
662 * it to decide if we should work around the NS bug or not.
664 rsp->status = strdup("200 Request for blocked URL");
667 * Workaround for stupid Netscape bug which prevents
668 * pages from being displayed if loading a referenced
669 * JavaScript or style sheet fails. So make it appear
670 * as if it succeeded.
672 if (csp->http->user_agent
673 && !strncmpic(csp->http->user_agent, "mozilla", 7)
674 && !strstr(csp->http->user_agent, "compatible")
675 && !strstr(csp->http->user_agent, "Opera"))
677 rsp->status = strdup("200 Request for blocked URL");
681 rsp->status = strdup("404 Request for blocked URL");
686 return(finish_http_response(rsp));
692 /*********************************************************************
694 * Function : trust_url FIXME: I should be called distrust_url
696 * Description : Calls is_untrusted_url to determine if the URL is trusted
697 * and if not, returns a HTTP 304 response with a reject message.
700 * 1 : csp = Current client state (buffers, headers, etc...)
702 * Returns : NULL => trusted, else http_response.
704 *********************************************************************/
705 struct http_response *trust_url(struct client_state *csp)
707 struct http_response *rsp;
708 struct map * exports;
709 char buf[BUFFER_SIZE], *p = NULL;
710 struct url_spec **tl, *t;
713 * Don't bother to work on trusted URLs
715 if (!is_untrusted_url(csp))
721 * Else, prepare a response:
723 if (NULL == (rsp = alloc_http_response()))
728 exports = default_exports(csp, NULL);
731 * Export the host, port, and referrer information
733 map(exports, "hostport", 1, csp->http->hostport, 1);
734 map(exports, "path", 1, csp->http->path, 1);
735 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
736 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
738 if (csp->referrer && strlen(csp->referrer) > 9)
740 map(exports, "referrer", 1, csp->referrer + 9, 1);
741 map(exports, "referrer-html", 1, html_encode(csp->referrer + 9), 0);
745 map(exports, "referrer", 1, "unknown", 1);
746 map(exports, "referrer-html", 1, "unknown", 1);
750 * Export the trust list
752 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
754 sprintf(buf, "<li>%s</li>\n", t->spec);
757 map(exports, "trusted-referrers", 1, p, 0);
761 * Export the trust info, if available
763 if (csp->config->trust_info->first)
765 struct list_entry *l;
767 for (l = csp->config->trust_info->first; l ; l = l->next)
769 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
772 map(exports, "trust-info", 1, p, 0);
776 map_block_killer(exports, "have-trust-info");
780 * Export the force prefix or the force conditional block killer
782 #ifdef FEATURE_FORCE_LOAD
783 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
784 #else /* ifndef FEATURE_FORCE_LOAD */
785 map_block_killer(exports, "force-support");
786 #endif /* ndef FEATURE_FORCE_LOAD */
791 rsp->body = template_load(csp, "untrusted");
792 template_fill(&rsp->body, exports);
795 return(finish_http_response(rsp));
798 #endif /* def FEATURE_TRUST */
801 #ifdef FEATURE_FAST_REDIRECTS
802 /*********************************************************************
804 * Function : redirect_url
806 * Description : Checks for redirection URLs and returns a HTTP redirect
807 * to the destination URL, if necessary
810 * 1 : csp = Current client state (buffers, headers, etc...)
812 * Returns : NULL if URL was clean, HTTP redirect otherwise.
814 *********************************************************************/
815 struct http_response *redirect_url(struct client_state *csp)
818 struct http_response *rsp;
820 p = q = csp->http->path;
821 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
824 * find the last URL encoded in the request
826 while ((p = strstr(p, "http://")))
832 * if there was any, generate and return a HTTP redirect
834 if (q != csp->http->path)
836 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
838 if (NULL == (rsp = alloc_http_response()))
843 rsp->status = strdup("302 Local Redirect from Junkbuster");
844 enlist_unique_header(rsp->headers, "Location", q);
846 return(finish_http_response(rsp));
854 #endif /* def FEATURE_FAST_REDIRECTS */
857 #ifdef FEATURE_IMAGE_BLOCKING
858 /*********************************************************************
860 * Function : is_imageurl
862 * Description : Given a URL, decide whether it is an image or not,
863 * using either the info from a previous +image action
864 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
865 * the browser's accept header.
868 * 1 : csp = Current client state (buffers, headers, etc...)
870 * Returns : True (nonzero) if URL is an image, false (0)
873 *********************************************************************/
874 int is_imageurl(struct client_state *csp)
876 #ifdef FEATURE_IMAGE_DETECT_MSIE
877 if ((csp->accept_types
878 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
879 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
883 else if ((csp->accept_types
884 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
885 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
889 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
891 return ((csp->action->flags & ACTION_IMAGE) != 0);
894 #endif /* def FEATURE_IMAGE_BLOCKING */
897 #ifdef FEATURE_COOKIE_JAR
898 /*********************************************************************
900 * Function : is_untrusted_url
902 * Description : Should we "distrust" this URL (and block it)?
904 * Yes if it matches a line in the trustfile, or if the
905 * referrer matches a line starting with "+" in the
910 * 1 : csp = Current client state (buffers, headers, etc...)
912 * Returns : 0 => trusted, 1 => untrusted
914 *********************************************************************/
915 int is_untrusted_url(struct client_state *csp)
917 struct file_list *fl;
918 struct block_spec *b;
919 struct url_spec url[1], **tl, *t;
920 struct http_request rhttp[1];
924 * If we don't have a trustlist, we trust everybody
926 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
933 * Do we trust the request URL itself?
935 *url = dsplit(csp->http->host);
937 /* if splitting the domain fails, punt */
938 if (url->dbuf == NULL) return(0);
940 memset(rhttp, '\0', sizeof(*rhttp));
942 for (b = b->next; b ; b = b->next)
944 if ((b->url->port == 0) || (b->url->port == csp->http->port))
946 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
948 if ((b->url->path == NULL) ||
950 (regexec(b->url->preg, csp->http->path, 0, NULL, 0) == 0)
952 (strncmp(b->url->path, csp->http->path, b->url->pathlen) == 0)
959 if (b->reject == 0) return(0);
970 if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
972 /* no referrer was supplied */
976 /* forge a URL from the referrer so we can use
977 * convert_url() to parse it into its components.
981 p = strsav(p, "GET ");
982 p = strsav(p, csp->referrer + 9); /* skip over "Referer: " */
983 p = strsav(p, " HTTP/1.0");
985 parse_http_request(p, rhttp, csp);
988 if (rhttp->cmd == NULL)
995 * If not, do we maybe trust its referrer?
997 *url = dsplit(rhttp->host);
999 /* if splitting the domain fails, punt */
1000 if (url->dbuf == NULL) return(1);
1002 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
1004 if ((t->port == 0) || (t->port == rhttp->port))
1006 if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
1008 if ((t->path == NULL) ||
1010 (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
1012 (strncmp(t->path, rhttp->path, t->pathlen) == 0)
1016 /* if the URL's referrer is from a trusted referrer, then
1017 * add the target spec to the trustfile as an unblocked
1018 * domain and return NULL (which means it's OK).
1026 if ((fp = fopen(csp->config->trustfile, "a")))
1031 h = strsav(h, csp->http->hostport);
1033 p = csp->http->path;
1037 /* since this path points into a user's home space
1038 * be sure to include this spec in the trustfile.
1040 if ((p = strchr(p, '/')))
1043 h = strsav(h, csp->http->path); /* FIXME: p?! */
1048 fprintf(fp, "%s\n", h);
1059 #endif /* def FEATURE_COOKIE_JAR */
1062 /*********************************************************************
1064 * Function : pcrs_filter_response
1066 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
1067 * to the text buffer that's been accumulated in
1068 * csp->iob->buf and set csp->content_length to the modified
1069 * size and raise the CSP_FLAG_MODIFIED flag if appropriate.
1072 * 1 : csp = Current client state (buffers, headers, etc...)
1074 * Returns : a pointer to the (newly allocated) modified buffer.
1075 * or NULL in case something went wrong
1077 *********************************************************************/
1078 char *pcrs_filter_response(struct client_state *csp)
1083 char *old = csp->iob->cur, *new = NULL;
1086 struct file_list *fl;
1087 struct re_filterfile_spec *b;
1090 if (csp->iob->cur >= csp->iob->eod)
1094 size = csp->iob->eod - csp->iob->cur;
1097 * If the body has a "chunked" transfer-encoding,
1098 * get rid of it first, adjusting size and iob->eod
1100 if (csp->flags & CSP_FLAG_CHUNKED)
1102 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1103 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1107 csp->iob->eod = csp->iob->cur + size;
1108 csp->flags |= CSP_FLAG_MODIFIED;
1111 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1113 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1117 if ( NULL == b->joblist )
1119 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1123 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1124 csp->http->hostport, csp->http->path, size);
1126 /* Apply all jobs from the joblist */
1127 for (job = b->joblist; NULL != job; job = job->next)
1129 hits += pcrs_execute(job, old, size, &new, &size);
1130 if (old != csp->iob->cur) free(old);
1134 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1137 * If there were no hits, destroy our copy and let
1138 * chat() use the original in csp->iob
1146 csp->flags |= CSP_FLAG_MODIFIED;
1147 csp->content_length = size;
1155 /*********************************************************************
1157 * Function : gif_deanimate_response
1159 * Description : Deanimate the GIF image that has been accumulated in
1160 * csp->iob->buf, set csp->content_length to the modified
1161 * size and raise the CSP_FLAG_MODIFIED flag.
1164 * 1 : csp = Current client state (buffers, headers, etc...)
1166 * Returns : a pointer to the (newly allocated) modified buffer.
1167 * or NULL in case something went wrong.
1169 *********************************************************************/
1170 char *gif_deanimate_response(struct client_state *csp)
1172 struct binbuffer *in, *out;
1174 int size = csp->iob->eod - csp->iob->cur;
1177 * If the body has a "chunked" transfer-encoding,
1178 * get rid of it first, adjusting size and iob->eod
1180 if (csp->flags & CSP_FLAG_CHUNKED)
1182 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1183 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1187 csp->iob->eod = csp->iob->cur + size;
1188 csp->flags |= CSP_FLAG_MODIFIED;
1191 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1192 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1194 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1198 in->buffer = csp->iob->cur;
1201 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1203 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1210 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1211 csp->content_length = out->offset;
1212 csp->flags |= CSP_FLAG_MODIFIED;
1222 /*********************************************************************
1224 * Function : remove_chunked_transfer_coding
1226 * Description : In-situ remove the "chunked" transfer coding as defined
1227 * in rfc2616 from a buffer.
1230 * 1 : buffer = Pointer to the text buffer
1231 * 2 : size = Number of bytes to be processed
1233 * Returns : The new size, i.e. the number of bytes from buffer which
1234 * are occupied by the stripped body, or 0 in case something
1237 *********************************************************************/
1238 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1241 unsigned int chunksize = 0;
1242 char *from_p, *to_p;
1245 from_p = to_p = buffer;
1247 if (sscanf(buffer, "%x", &chunksize) != 1)
1249 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1253 while (chunksize > 0)
1255 if (NULL == (from_p = strstr(from_p, "\r\n")))
1257 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1260 newsize += chunksize;
1263 memmove(to_p, from_p, (size_t) chunksize);
1264 to_p = buffer + newsize;
1265 from_p += chunksize + 2;
1267 if (sscanf(from_p, "%x", &chunksize) != 1)
1269 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1274 /* FIXME: Should this get its own loglevel? */
1275 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1281 /*********************************************************************
1283 * Function : url_actions
1285 * Description : Gets the actions for this URL.
1288 * 1 : http = http_request request for blocked URLs
1289 * 2 : csp = Current client state (buffers, headers, etc...)
1293 *********************************************************************/
1294 void url_actions(struct http_request *http,
1295 struct client_state *csp)
1297 struct file_list *fl;
1298 struct url_actions *b;
1300 init_current_action(csp->action);
1302 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1307 apply_url_actions(csp->action, http, b);
1312 /*********************************************************************
1314 * Function : apply_url_actions
1316 * Description : Applies a list of URL actions.
1319 * 1 : action = Destination.
1320 * 2 : http = Current URL
1321 * 3 : b = list of URL actions to apply
1325 *********************************************************************/
1326 void apply_url_actions(struct current_action_spec *action,
1327 struct http_request *http,
1328 struct url_actions *b)
1330 struct url_spec url[1];
1334 /* Should never happen */
1338 *url = dsplit(http->host);
1340 /* if splitting the domain fails, punt */
1341 if (url->dbuf == NULL)
1346 for (b = b->next; NULL != b; b = b->next)
1348 if ((b->url->port == 0) || (b->url->port == http->port))
1350 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1352 if ((b->url->path == NULL) ||
1354 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
1356 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
1360 merge_current_action(action, b->action);
1371 /*********************************************************************
1373 * Function : forward_url
1375 * Description : Should we forward this to another proxy?
1378 * 1 : http = http_request request for current URL
1379 * 2 : csp = Current client state (buffers, headers, etc...)
1381 * Returns : Pointer to forwarding information.
1383 *********************************************************************/
1384 const struct forward_spec * forward_url(struct http_request *http,
1385 struct client_state *csp)
1387 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1388 struct forward_spec *fwd = csp->config->forward;
1389 struct url_spec url[1];
1393 return(fwd_default);
1396 *url = dsplit(http->host);
1398 /* if splitting the domain fails, punt */
1399 if (url->dbuf == NULL)
1401 return(fwd_default);
1406 if ((fwd->url->port == 0) || (fwd->url->port == http->port))
1408 if ((fwd->url->domain[0] == '\0') || (domaincmp(fwd->url, url) == 0))
1410 if ((fwd->url->path == NULL) ||
1412 (regexec(fwd->url->preg, http->path, 0, NULL, 0) == 0)
1414 (strncmp(fwd->url->path, http->path, fwd->url->pathlen) == 0)
1429 return(fwd_default);
1434 /*********************************************************************
1438 * Description : Takes a domain and returns a pointer to a url_spec
1439 * structure populated with dbuf, dcnt and dvec. The
1440 * other fields in the structure that is returned are zero.
1443 * 1 : domain = a URL address
1445 * Returns : url_spec structure populated with dbuf, dcnt and dvec.
1447 *********************************************************************/
1448 struct url_spec dsplit(char *domain)
1450 struct url_spec ret[1];
1451 char *v[BUFFER_SIZE];
1455 memset(ret, '\0', sizeof(*ret));
1457 if (domain[strlen(domain) - 1] == '.')
1459 ret->unanchored |= ANCHOR_RIGHT;
1462 if (domain[0] == '.')
1464 ret->unanchored |= ANCHOR_LEFT;
1467 ret->dbuf = strdup(domain);
1469 /* map to lower case */
1470 for (p = ret->dbuf; *p ; p++) *p = tolower(*p);
1472 /* split the domain name into components */
1473 ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
1477 memset(ret, '\0', sizeof(ret));
1481 /* save a copy of the pointers in dvec */
1482 size = ret->dcnt * sizeof(*ret->dvec);
1484 if ((ret->dvec = (char **)malloc(size)))
1486 memcpy(ret->dvec, v, size);
1494 /*********************************************************************
1496 * Function : simple_domaincmp
1498 * Description : Domain-wise Compare fqdn's. The comparison is
1499 * both left- and right-anchored. The individual
1500 * domain names are compared with simplematch().
1501 * This is only used by domaincmp.
1504 * 1 : pv = array of patterns to compare
1505 * 2 : fv = array of domain components to compare
1506 * 3 : len = length of the arrays (both arrays are the
1507 * same length - if they weren't, it couldn't
1508 * possibly be a match).
1510 * Returns : 0 => domains are equivalent, else no match.
1512 *********************************************************************/
1513 static int simple_domaincmp(char **pv, char **fv, int len)
1517 for (n = 0; n < len; n++)
1519 if (simplematch(pv[n], fv[n]))
1530 /*********************************************************************
1532 * Function : domaincmp
1534 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1535 * pattern->unachored, the comparison is un-, left-,
1536 * right-anchored, or both.
1537 * The individual domain names are compared with
1541 * 1 : pattern = a domain that may contain a '*' as a wildcard.
1542 * 2 : fqdn = domain name against which the patterns are compared.
1544 * Returns : 0 => domains are equivalent, else no match.
1546 *********************************************************************/
1547 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1549 char **pv, **fv; /* vectors */
1551 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1553 plen = pattern->dcnt;
1558 /* fqdn is too short to match this pattern */
1565 if (unanchored == ANCHOR_LEFT)
1570 * Convert this into a fully anchored pattern with
1571 * the fqdn and pattern the same length
1573 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1574 return simple_domaincmp(pv, fv, plen);
1576 else if (unanchored == 0)
1578 /* Fully anchored, check length */
1583 return simple_domaincmp(pv, fv, plen);
1585 else if (unanchored == ANCHOR_RIGHT)
1587 /* Left anchored, ignore all extra in fqdn */
1588 return simple_domaincmp(pv, fv, plen);
1594 int maxn = flen - plen;
1595 for (n = 0; n <= maxn; n++)
1597 if (!simple_domaincmp(pv, fv, plen))
1602 * Doesn't match from start of fqdn
1603 * Try skipping first part of fqdn