1 const char filters_rcs[] = "$Id: filters.c,v 1.34 2001/09/20 15:49:36 steudten 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.34 2001/09/20 15:49:36 steudten
43 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
44 * See cgi.c fill_template().
46 * Revision 1.33 2001/09/16 17:05:14 jongfoster
47 * Removing unused #include showarg.h
49 * Revision 1.32 2001/09/16 13:21:27 jongfoster
50 * Changes to use new list functions.
52 * Revision 1.31 2001/09/16 11:38:02 jongfoster
53 * Splitting fill_template() into 2 functions:
54 * template_load() loads the file
55 * template_fill() performs the PCRS regexps.
56 * This is because the CGI edit interface has a "table row"
57 * template which is used many times in the page - this
58 * change means it's only loaded from disk once.
60 * Revision 1.30 2001/09/16 11:00:10 jongfoster
61 * New function alloc_http_response, for symmetry with free_http_response
63 * Revision 1.29 2001/09/13 23:32:40 jongfoster
64 * Moving image data to cgi.c rather than cgi.h
65 * Fixing a GPF under Win32 (and any other OS that protects global
66 * constants from being written to).
68 * Revision 1.28 2001/09/10 10:18:51 oes
69 * Silenced compiler warnings
71 * Revision 1.27 2001/08/05 16:06:20 jongfoster
72 * Modifiying "struct map" so that there are now separate header and
73 * "map_entry" structures. This means that functions which modify a
74 * map no longer need to return a pointer to the modified map.
75 * Also, it no longer reverses the order of the entries (which may be
76 * important with some advanced template substitutions).
78 * Revision 1.26 2001/07/30 22:08:36 jongfoster
79 * Tidying up #defines:
80 * - All feature #defines are now of the form FEATURE_xxx
81 * - Permanently turned off WIN_GUI_EDIT
82 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
84 * Revision 1.25 2001/07/26 10:09:46 oes
85 * Made browser detection a little less naive
87 * Revision 1.24 2001/07/25 17:22:51 oes
88 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
90 * Revision 1.23 2001/07/23 13:40:12 oes
91 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
93 * Revision 1.22 2001/07/18 12:29:34 oes
94 * - Made gif_deanimate_response respect
95 * csp->action->string[ACTION_STRING_DEANIMATE]
98 * Revision 1.21 2001/07/13 13:59:53 oes
99 * - Introduced gif_deanimate_response which shares the
100 * generic content modification interface of pcrs_filter_response
101 * and acts as a wrapper to deanimate.c:gif_deanimate()
102 * - Renamed re_process_buffer to pcrs_filter_response
103 * - pcrs_filter_response now returns NULL on failiure
104 * - Removed all #ifdef PCRS
106 * Revision 1.20 2001/07/01 17:01:04 oes
107 * Added comments and missing return statement in is_untrusted_url()
109 * Revision 1.19 2001/06/29 21:45:41 oes
110 * Indentation, CRLF->LF, Tab-> Space
112 * Revision 1.18 2001/06/29 13:27:38 oes
113 * - Cleaned up, renamed and reorderd functions
114 * and improved comments
117 * - Ported to CGI platform. Now delivers
118 * http_response or NULL
119 * - Unified HTML and GIF generation (moved image detection
120 * and GIF generation here from jcc.c:chat())
121 * - Fixed HTTP status to:
122 * - 403 (Forbidden) for the "blocked" HTML message
123 * - 200 (OK) for GIF answers
124 * - 302 (Redirect) for redirect to GIF
127 * - Ported to CGI platform. Now delivers
128 * http_response or NULL
129 * - Separated detection of untrusted URL into
130 * (bool)is_untrusted_url
131 * - Added enforcement of untrusted requests
133 * - Moved redirect_url() from cgi.c to here
134 * and ported it to the CGI platform
136 * - Removed logentry from cancelled commit
138 * Revision 1.17 2001/06/09 10:55:28 jongfoster
139 * Changing BUFSIZ ==> BUFFER_SIZE
141 * Revision 1.16 2001/06/07 23:10:26 jongfoster
142 * Allowing unanchored domain patterns to back off and retry
143 * if they partially match. Optimized right-anchored patterns.
144 * Moving ACL and forward files into config file.
145 * Replacing struct gateway with struct forward_spec
147 * Revision 1.15 2001/06/03 19:12:00 oes
148 * extracted-CGI relevant stuff
150 * Revision 1.14 2001/06/01 10:30:55 oes
151 * Added optional left-anchoring to domaincmp
153 * Revision 1.13 2001/05/31 21:21:30 jongfoster
154 * Permissionsfile / actions file changes:
155 * - Changed "permission" to "action" throughout
156 * - changes to file format to allow string parameters
157 * - Moved helper functions to actions.c
159 * Revision 1.12 2001/05/31 17:35:20 oes
161 * - Enhanced domain part globbing with infix and prefix asterisk
162 * matching and optional unanchored operation
164 * Revision 1.11 2001/05/29 11:53:23 oes
165 * "See why" link added to "blocked" page
167 * Revision 1.10 2001/05/29 09:50:24 jongfoster
168 * Unified blocklist/imagelist/permissionslist.
169 * File format is still under discussion, but the internal changes
172 * Also modified interceptor behaviour:
173 * - We now intercept all URLs beginning with one of the following
174 * prefixes (and *only* these prefixes):
176 * * http://ijbswa.sf.net/config/
177 * * http://ijbswa.sourceforge.net/config/
178 * - New interceptors "home page" - go to http://i.j.b/ to see it.
179 * - Internal changes so that intercepted and fast redirect pages
180 * are not replaced with an image.
181 * - Interceptors now have the option to send a binary page direct
182 * to the client. (i.e. ijb-send-banner uses this)
183 * - Implemented show-url-info interceptor. (Which is why I needed
184 * the above interceptors changes - a typical URL is
185 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
186 * The previous mechanism would not have intercepted that, and
187 * if it had been intercepted then it then it would have replaced
190 * Revision 1.9 2001/05/27 22:17:04 oes
192 * - re_process_buffer no longer writes the modified buffer
193 * to the client, which was very ugly. It now returns the
194 * buffer, which it is then written by chat.
196 * - content_length now adjusts the Content-Length: header
197 * for modified documents rather than crunch()ing it.
198 * (Length info in csp->content_length, which is 0 for
199 * unmodified documents)
201 * - For this to work, sed() is called twice when filtering.
203 * Revision 1.8 2001/05/26 17:13:28 jongfoster
204 * Filled in a function comment.
206 * Revision 1.7 2001/05/26 15:26:15 jongfoster
207 * ACL feature now provides more security by immediately dropping
208 * connections from untrusted hosts.
210 * Revision 1.6 2001/05/26 00:28:36 jongfoster
211 * Automatic reloading of config file.
212 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
213 * Most of the global variables have been moved to a new
214 * struct configuration_spec, accessed through csp->config->globalname
215 * Most of the globals remaining are used by the Win32 GUI.
217 * Revision 1.5 2001/05/25 22:34:30 jongfoster
220 * Revision 1.4 2001/05/22 18:46:04 oes
222 * - Enabled filtering banners by size rather than URL
223 * by adding patterns that replace all standard banner
224 * sizes with the "Junkbuster" gif to the re_filterfile
226 * - Enabled filtering WebBugs by providing a pattern
227 * which kills all 1x1 images
229 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
230 * which is selected by the (nonstandard and therefore
231 * capital) letter 'U' in the option string.
232 * It causes the quantifiers to be ungreedy by default.
233 * Appending a ? turns back to greedy (!).
235 * - Added a new interceptor ijb-send-banner, which
236 * sends back the "Junkbuster" gif. Without imagelist or
237 * MSIE detection support, or if tinygif = 1, or the
238 * URL isn't recognized as an imageurl, a lame HTML
239 * explanation is sent instead.
241 * - Added new feature, which permits blocking remote
242 * script redirects and firing back a local redirect
244 * The feature is conditionally compiled, i.e. it
245 * can be disabled with --disable-fast-redirects,
246 * plus it must be activated by a "fast-redirects"
247 * line in the config file, has its own log level
248 * and of course wants to be displayed by show-proxy-args
249 * Note: Boy, all the #ifdefs in 1001 locations and
250 * all the fumbling with configure.in and acconfig.h
251 * were *way* more work than the feature itself :-(
253 * - Because a generic redirect template was needed for
254 * this, tinygif = 3 now uses the same.
256 * - Moved GIFs, and other static HTTP response templates
261 * - Removed some >400 CRs again (Jon, you really worked
264 * Revision 1.3 2001/05/20 16:44:47 jongfoster
265 * Removing last hardcoded JunkBusters.com URLs.
267 * Revision 1.2 2001/05/20 01:21:20 jongfoster
268 * Version 2.9.4 checkin.
269 * - Merged popupfile and cookiefile, and added control over PCRS
270 * filtering, in new "permissionsfile".
271 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
272 * file error you now get a message box (in the Win32 GUI) rather
273 * than the program exiting with no explanation.
274 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
276 * - Removed tabs from "config"
277 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
278 * - Bumped up version number.
280 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
281 * Initial import of version 2.9.3 source tree
284 *********************************************************************/
290 #include <sys/types.h>
298 #include <netinet/in.h>
300 #include <winsock2.h>
309 #include "jbsockets.h"
310 #include "miscutil.h"
314 #include "deanimate.h"
320 const char filters_h_rcs[] = FILTERS_H_VERSION;
322 /* Fix a problem with Solaris. There should be no effect on other
324 * Solaris's isspace() is a macro which uses it's argument directly
325 * as an array index. Therefore we need to make sure that high-bit
326 * characters generate +ve values, and ideally we also want to make
327 * the argument match the declared parameter type of "int".
329 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
333 /*********************************************************************
335 * Function : block_acl
337 * Description : Block this request?
338 * Decide yes or no based on ACL file.
341 * 1 : dst = The proxy or gateway address this is going to.
342 * Or NULL to check all possible targets.
343 * 2 : csp = Current client state (buffers, headers, etc...)
344 * Also includes the client IP address.
346 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
348 *********************************************************************/
349 int block_acl(struct access_control_addr *dst, struct client_state *csp)
351 struct access_control_list *acl = csp->config->acl;
353 /* if not using an access control list, then permit the connection */
359 /* search the list */
362 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
366 /* Just want to check if they have any access */
367 if (acl->action == ACL_PERMIT)
372 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
373 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
375 if (acl->action == ACL_PERMIT)
393 /*********************************************************************
395 * Function : acl_addr
397 * Description : Called from `load_aclfile' to parse an ACL address.
400 * 1 : aspec = String specifying ACL address.
401 * 2 : aca = struct access_control_addr to fill in.
403 * Returns : 0 => Ok, everything else is an error.
405 *********************************************************************/
406 int acl_addr(char *aspec, struct access_control_addr *aca)
408 int i, masklength, port;
414 if ((p = strchr(aspec, '/')))
418 if (ijb_isdigit(*p) == 0)
422 masklength = atoi(p);
425 if ((masklength < 0) || (masklength > 32))
430 if ((p = strchr(aspec, ':')))
434 if (ijb_isdigit(*p) == 0)
443 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
447 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
451 /* build the netmask */
453 for (i=1; i <= masklength ; i++)
455 aca->mask |= (1 << (32 - i));
458 /* now mask off the host portion of the ip address
459 * (i.e. save on the network portion of the address).
461 aca->addr = aca->addr & aca->mask;
466 #endif /* def FEATURE_ACL */
469 /*********************************************************************
471 * Function : block_url
473 * Description : Called from `chat'. Check to see if we need to block this.
476 * 1 : csp = Current client state (buffers, headers, etc...)
478 * Returns : NULL => unblocked, else HTTP block response
480 *********************************************************************/
481 struct http_response *block_url(struct client_state *csp)
483 #ifdef FEATURE_IMAGE_BLOCKING
485 #endif /* def FEATURE_IMAGE_BLOCKING */
486 struct http_response *rsp;
489 * If it's not blocked, don't block it ;-)
491 if ((csp->action->flags & ACTION_BLOCK) == 0)
497 * Else, prepare a response
499 if (NULL == (rsp = alloc_http_response()))
505 * If it's an image-url, send back an image or redirect
506 * as specified by the relevant +image action
508 #ifdef FEATURE_IMAGE_BLOCKING
509 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
512 /* determine HOW images should be blocked */
513 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
515 /* and handle accordingly: */
516 if ((p == NULL) || (0 == strcmpic(p, "logo")))
518 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
519 rsp->content_length = image_junkbuster_gif_length;
520 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
523 else if (0 == strcmpic(p, "blank"))
525 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
526 rsp->content_length = image_blank_gif_length;
527 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
532 rsp->status = strdup("302 Local Redirect from Junkbuster");
533 enlist_unique_header(rsp->headers, "Location", p);
537 #endif /* def FEATURE_IMAGE_BLOCKING */
540 * Else, generate an HTML "blocked" message:
543 struct map * exports = default_exports(csp, NULL);
544 #ifdef FEATURE_FORCE_LOAD
545 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
546 #else /* ifndef FEATURE_FORCE_LOAD */
547 map_block_killer(exports, "force-support");
548 #endif /* ndef FEATURE_FORCE_LOAD */
550 map(exports, "hostport", 1, csp->http->hostport, 1);
551 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
552 map(exports, "path", 1, csp->http->path, 1);
553 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
555 rsp->body = template_load(csp, "blocked");
556 template_fill(&rsp->body, exports);
560 * Workaround for stupid Netscape bug which prevents
561 * pages from being displayed if loading a referenced
562 * JavaScript or style sheet fails. So make it appear
563 * as if it succeeded.
565 if (csp->http->user_agent
566 && !strncmpic(csp->http->user_agent, "mozilla", 7)
567 && !strstr(csp->http->user_agent, "compatible")
568 && !strstr(csp->http->user_agent, "Opera"))
570 rsp->status = strdup("200 Request for blocked URL");
574 rsp->status = strdup("404 Request for blocked URL");
579 return(finish_http_response(rsp));
585 /*********************************************************************
587 * Function : trust_url FIXME: I should be called distrust_url
589 * Description : Calls is_untrusted_url to determine if the URL is trusted
590 * and if not, returns a HTTP 304 response with a reject message.
593 * 1 : csp = Current client state (buffers, headers, etc...)
595 * Returns : NULL => trusted, else http_response.
597 *********************************************************************/
598 struct http_response *trust_url(struct client_state *csp)
600 struct http_response *rsp;
601 struct map * exports;
602 char buf[BUFFER_SIZE], *p = NULL;
603 struct url_spec **tl, *t;
606 * Don't bother to work on trusted URLs
608 if (!is_untrusted_url(csp))
614 * Else, prepare a response:
616 if (NULL == (rsp = alloc_http_response()))
621 exports = default_exports(csp, NULL);
624 * Export the host, port, and referrer information
626 map(exports, "hostport", 1, csp->http->hostport, 1);
627 map(exports, "path", 1, csp->http->path, 1);
628 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
629 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
631 if (csp->referrer && strlen(csp->referrer) > 9)
633 map(exports, "referrer", 1, csp->referrer + 9, 1);
634 map(exports, "referrer-html", 1, html_encode(csp->referrer + 9), 0);
638 map(exports, "referrer", 1, "unknown", 1);
639 map(exports, "referrer-html", 1, "unknown", 1);
643 * Export the trust list
645 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
647 sprintf(buf, "<li>%s</li>\n", t->spec);
650 map(exports, "trusted-referrers", 1, p, 0);
654 * Export the trust info, if available
656 if (csp->config->trust_info->first)
658 struct list_entry *l;
660 for (l = csp->config->trust_info->first; l ; l = l->next)
662 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
665 map(exports, "trust-info", 1, p, 0);
669 map_block_killer(exports, "have-trust-info");
673 * Export the force prefix or the force conditional block killer
675 #ifdef FEATURE_FORCE_LOAD
676 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
677 #else /* ifndef FEATURE_FORCE_LOAD */
678 map_block_killer(exports, "force-support");
679 #endif /* ndef FEATURE_FORCE_LOAD */
684 rsp->body = template_load(csp, "untrusted");
685 template_fill(&rsp->body, exports);
688 return(finish_http_response(rsp));
691 #endif /* def FEATURE_TRUST */
694 #ifdef FEATURE_FAST_REDIRECTS
695 /*********************************************************************
697 * Function : redirect_url
699 * Description : Checks for redirection URLs and returns a HTTP redirect
700 * to the destination URL, if necessary
703 * 1 : csp = Current client state (buffers, headers, etc...)
705 * Returns : NULL if URL was clean, HTTP redirect otherwise.
707 *********************************************************************/
708 struct http_response *redirect_url(struct client_state *csp)
711 struct http_response *rsp;
713 p = q = csp->http->path;
714 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
717 * find the last URL encoded in the request
719 while ((p = strstr(p, "http://")))
725 * if there was any, generate and return a HTTP redirect
727 if (q != csp->http->path)
729 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
731 if (NULL == (rsp = alloc_http_response()))
736 rsp->status = strdup("302 Local Redirect from Junkbuster");
737 enlist_unique_header(rsp->headers, "Location", q);
739 return(finish_http_response(rsp));
747 #endif /* def FEATURE_FAST_REDIRECTS */
750 #ifdef FEATURE_IMAGE_BLOCKING
751 /*********************************************************************
753 * Function : is_imageurl
755 * Description : Given a URL, decide whether it is an image or not,
756 * using either the info from a previous +image action
757 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
758 * the browser's accept header.
761 * 1 : csp = Current client state (buffers, headers, etc...)
763 * Returns : True (nonzero) if URL is an image, false (0)
766 *********************************************************************/
767 int is_imageurl(struct client_state *csp)
769 #ifdef FEATURE_IMAGE_DETECT_MSIE
770 if ((csp->accept_types
771 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
772 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
776 else if ((csp->accept_types
777 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
778 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
782 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
784 return ((csp->action->flags & ACTION_IMAGE) != 0);
787 #endif /* def FEATURE_IMAGE_BLOCKING */
790 #ifdef FEATURE_COOKIE_JAR
791 /*********************************************************************
793 * Function : is_untrusted_url
795 * Description : Should we "distrust" this URL (and block it)?
797 * Yes if it matches a line in the trustfile, or if the
798 * referrer matches a line starting with "+" in the
803 * 1 : csp = Current client state (buffers, headers, etc...)
805 * Returns : 0 => trusted, 1 => untrusted
807 *********************************************************************/
808 int is_untrusted_url(struct client_state *csp)
810 struct file_list *fl;
811 struct block_spec *b;
812 struct url_spec url[1], **tl, *t;
813 struct http_request rhttp[1];
817 * If we don't have a trustlist, we trust everybody
819 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
826 * Do we trust the request URL itself?
828 *url = dsplit(csp->http->host);
830 /* if splitting the domain fails, punt */
831 if (url->dbuf == NULL) return(0);
833 memset(rhttp, '\0', sizeof(*rhttp));
835 for (b = b->next; b ; b = b->next)
837 if ((b->url->port == 0) || (b->url->port == csp->http->port))
839 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
841 if ((b->url->path == NULL) ||
843 (regexec(b->url->preg, csp->http->path, 0, NULL, 0) == 0)
845 (strncmp(b->url->path, csp->http->path, b->url->pathlen) == 0)
852 if (b->reject == 0) return(0);
863 if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
865 /* no referrer was supplied */
869 /* forge a URL from the referrer so we can use
870 * convert_url() to parse it into its components.
874 p = strsav(p, "GET ");
875 p = strsav(p, csp->referrer + 9); /* skip over "Referer: " */
876 p = strsav(p, " HTTP/1.0");
878 parse_http_request(p, rhttp, csp);
881 if (rhttp->cmd == NULL)
888 * If not, do we maybe trust its referrer?
890 *url = dsplit(rhttp->host);
892 /* if splitting the domain fails, punt */
893 if (url->dbuf == NULL) return(1);
895 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
897 if ((t->port == 0) || (t->port == rhttp->port))
899 if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
901 if ((t->path == NULL) ||
903 (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
905 (strncmp(t->path, rhttp->path, t->pathlen) == 0)
909 /* if the URL's referrer is from a trusted referrer, then
910 * add the target spec to the trustfile as an unblocked
911 * domain and return NULL (which means it's OK).
919 if ((fp = fopen(csp->config->trustfile, "a")))
924 h = strsav(h, csp->http->hostport);
930 /* since this path points into a user's home space
931 * be sure to include this spec in the trustfile.
933 if ((p = strchr(p, '/')))
936 h = strsav(h, csp->http->path); /* FIXME: p?! */
941 fprintf(fp, "%s\n", h);
952 #endif /* def FEATURE_COOKIE_JAR */
955 /*********************************************************************
957 * Function : pcrs_filter_response
959 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
960 * to the text buffer that's been accumulated in
961 * csp->iob->buf and set csp->content_length to the modified
962 * size and raise the CSP_FLAG_MODIFIED flag if appropriate.
965 * 1 : csp = Current client state (buffers, headers, etc...)
967 * Returns : a pointer to the (newly allocated) modified buffer.
968 * or NULL in case something went wrong
970 *********************************************************************/
971 char *pcrs_filter_response(struct client_state *csp)
976 char *old = csp->iob->cur, *new = NULL;
979 struct file_list *fl;
980 struct re_filterfile_spec *b;
983 if (csp->iob->cur >= csp->iob->eod)
987 size = csp->iob->eod - csp->iob->cur;
990 * If the body has a "chunked" transfer-encoding,
991 * get rid of it first, adjusting size and iob->eod
993 if (csp->flags & CSP_FLAG_CHUNKED)
995 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
996 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1000 csp->iob->eod = csp->iob->cur + size;
1001 csp->flags |= CSP_FLAG_MODIFIED;
1004 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1006 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1010 if ( NULL == b->joblist )
1012 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1016 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1017 csp->http->hostport, csp->http->path, size);
1019 /* Apply all jobs from the joblist */
1020 for (job = b->joblist; NULL != job; job = job->next)
1022 hits += pcrs_execute(job, old, size, &new, &size);
1023 if (old != csp->iob->cur) free(old);
1027 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1030 * If there were no hits, destroy our copy and let
1031 * chat() use the original in csp->iob
1039 csp->flags |= CSP_FLAG_MODIFIED;
1040 csp->content_length = size;
1048 /*********************************************************************
1050 * Function : gif_deanimate_response
1052 * Description : Deanimate the GIF image that has been accumulated in
1053 * csp->iob->buf, set csp->content_length to the modified
1054 * size and raise the CSP_FLAG_MODIFIED flag.
1057 * 1 : csp = Current client state (buffers, headers, etc...)
1059 * Returns : a pointer to the (newly allocated) modified buffer.
1060 * or NULL in case something went wrong.
1062 *********************************************************************/
1063 char *gif_deanimate_response(struct client_state *csp)
1065 struct binbuffer *in, *out;
1067 int size = csp->iob->eod - csp->iob->cur;
1070 * If the body has a "chunked" transfer-encoding,
1071 * get rid of it first, adjusting size and iob->eod
1073 if (csp->flags & CSP_FLAG_CHUNKED)
1075 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1076 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1080 csp->iob->eod = csp->iob->cur + size;
1081 csp->flags |= CSP_FLAG_MODIFIED;
1084 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1085 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1087 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1091 in->buffer = csp->iob->cur;
1094 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1096 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1103 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1104 csp->content_length = out->offset;
1105 csp->flags |= CSP_FLAG_MODIFIED;
1115 /*********************************************************************
1117 * Function : remove_chunked_transfer_coding
1119 * Description : In-situ remove the "chunked" transfer coding as defined
1120 * in rfc2616 from a buffer.
1123 * 1 : buffer = Pointer to the text buffer
1124 * 2 : size = Number of bytes to be processed
1126 * Returns : The new size, i.e. the number of bytes from buffer which
1127 * are occupied by the stripped body, or 0 in case something
1130 *********************************************************************/
1131 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1134 unsigned int chunksize = 0;
1135 char *from_p, *to_p;
1138 from_p = to_p = buffer;
1140 if (sscanf(buffer, "%x", &chunksize) != 1)
1142 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1146 while (chunksize > 0)
1148 if (NULL == (from_p = strstr(from_p, "\r\n")))
1150 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1153 newsize += chunksize;
1156 memmove(to_p, from_p, (size_t) chunksize);
1157 to_p = buffer + newsize;
1158 from_p += chunksize + 2;
1160 if (sscanf(from_p, "%x", &chunksize) != 1)
1162 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1167 /* FIXME: Should this get its own loglevel? */
1168 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1174 /*********************************************************************
1176 * Function : url_actions
1178 * Description : Gets the actions for this URL.
1181 * 1 : http = http_request request for blocked URLs
1182 * 2 : csp = Current client state (buffers, headers, etc...)
1186 *********************************************************************/
1187 void url_actions(struct http_request *http,
1188 struct client_state *csp)
1190 struct file_list *fl;
1191 struct url_actions *b;
1193 init_current_action(csp->action);
1195 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1200 apply_url_actions(csp->action, http, b);
1205 /*********************************************************************
1207 * Function : apply_url_actions
1209 * Description : Applies a list of URL actions.
1212 * 1 : action = Destination.
1213 * 2 : http = Current URL
1214 * 3 : b = list of URL actions to apply
1218 *********************************************************************/
1219 void apply_url_actions(struct current_action_spec *action,
1220 struct http_request *http,
1221 struct url_actions *b)
1223 struct url_spec url[1];
1227 /* Should never happen */
1231 *url = dsplit(http->host);
1233 /* if splitting the domain fails, punt */
1234 if (url->dbuf == NULL)
1239 for (b = b->next; NULL != b; b = b->next)
1241 if ((b->url->port == 0) || (b->url->port == http->port))
1243 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1245 if ((b->url->path == NULL) ||
1247 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
1249 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
1253 merge_current_action(action, b->action);
1264 /*********************************************************************
1266 * Function : forward_url
1268 * Description : Should we forward this to another proxy?
1271 * 1 : http = http_request request for current URL
1272 * 2 : csp = Current client state (buffers, headers, etc...)
1274 * Returns : Pointer to forwarding information.
1276 *********************************************************************/
1277 const struct forward_spec * forward_url(struct http_request *http,
1278 struct client_state *csp)
1280 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1281 struct forward_spec *fwd = csp->config->forward;
1282 struct url_spec url[1];
1286 return(fwd_default);
1289 *url = dsplit(http->host);
1291 /* if splitting the domain fails, punt */
1292 if (url->dbuf == NULL)
1294 return(fwd_default);
1299 if ((fwd->url->port == 0) || (fwd->url->port == http->port))
1301 if ((fwd->url->domain[0] == '\0') || (domaincmp(fwd->url, url) == 0))
1303 if ((fwd->url->path == NULL) ||
1305 (regexec(fwd->url->preg, http->path, 0, NULL, 0) == 0)
1307 (strncmp(fwd->url->path, http->path, fwd->url->pathlen) == 0)
1322 return(fwd_default);
1327 /*********************************************************************
1331 * Description : Takes a domain and returns a pointer to a url_spec
1332 * structure populated with dbuf, dcnt and dvec. The
1333 * other fields in the structure that is returned are zero.
1336 * 1 : domain = a URL address
1338 * Returns : url_spec structure populated with dbuf, dcnt and dvec.
1340 *********************************************************************/
1341 struct url_spec dsplit(char *domain)
1343 struct url_spec ret[1];
1344 char *v[BUFFER_SIZE];
1348 memset(ret, '\0', sizeof(*ret));
1350 if (domain[strlen(domain) - 1] == '.')
1352 ret->unanchored |= ANCHOR_RIGHT;
1355 if (domain[0] == '.')
1357 ret->unanchored |= ANCHOR_LEFT;
1360 ret->dbuf = strdup(domain);
1362 /* map to lower case */
1363 for (p = ret->dbuf; *p ; p++) *p = tolower(*p);
1365 /* split the domain name into components */
1366 ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
1370 memset(ret, '\0', sizeof(ret));
1374 /* save a copy of the pointers in dvec */
1375 size = ret->dcnt * sizeof(*ret->dvec);
1377 if ((ret->dvec = (char **)malloc(size)))
1379 memcpy(ret->dvec, v, size);
1387 /*********************************************************************
1389 * Function : simple_domaincmp
1391 * Description : Domain-wise Compare fqdn's. The comparison is
1392 * both left- and right-anchored. The individual
1393 * domain names are compared with simplematch().
1394 * This is only used by domaincmp.
1397 * 1 : pv = array of patterns to compare
1398 * 2 : fv = array of domain components to compare
1399 * 3 : len = length of the arrays (both arrays are the
1400 * same length - if they weren't, it couldn't
1401 * possibly be a match).
1403 * Returns : 0 => domains are equivalent, else no match.
1405 *********************************************************************/
1406 static int simple_domaincmp(char **pv, char **fv, int len)
1410 for (n = 0; n < len; n++)
1412 if (simplematch(pv[n], fv[n]))
1423 /*********************************************************************
1425 * Function : domaincmp
1427 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1428 * pattern->unachored, the comparison is un-, left-,
1429 * right-anchored, or both.
1430 * The individual domain names are compared with
1434 * 1 : pattern = a domain that may contain a '*' as a wildcard.
1435 * 2 : fqdn = domain name against which the patterns are compared.
1437 * Returns : 0 => domains are equivalent, else no match.
1439 *********************************************************************/
1440 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1442 char **pv, **fv; /* vectors */
1444 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1446 plen = pattern->dcnt;
1451 /* fqdn is too short to match this pattern */
1458 if (unanchored == ANCHOR_LEFT)
1463 * Convert this into a fully anchored pattern with
1464 * the fqdn and pattern the same length
1466 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1467 return simple_domaincmp(pv, fv, plen);
1469 else if (unanchored == 0)
1471 /* Fully anchored, check length */
1476 return simple_domaincmp(pv, fv, plen);
1478 else if (unanchored == ANCHOR_RIGHT)
1480 /* Left anchored, ignore all extra in fqdn */
1481 return simple_domaincmp(pv, fv, plen);
1487 int maxn = flen - plen;
1488 for (n = 0; n <= maxn; n++)
1490 if (!simple_domaincmp(pv, fv, plen))
1495 * Doesn't match from start of fqdn
1496 * Try skipping first part of fqdn