1 const char filters_rcs[] = "$Id: filters.c,v 1.31 2001/09/16 11:38:02 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.31 2001/09/16 11:38:02 jongfoster
42 * Splitting fill_template() into 2 functions:
43 * template_load() loads the file
44 * template_fill() performs the PCRS regexps.
45 * This is because the CGI edit interface has a "table row"
46 * template which is used many times in the page - this
47 * change means it's only loaded from disk once.
49 * Revision 1.30 2001/09/16 11:00:10 jongfoster
50 * New function alloc_http_response, for symmetry with free_http_response
52 * Revision 1.29 2001/09/13 23:32:40 jongfoster
53 * Moving image data to cgi.c rather than cgi.h
54 * Fixing a GPF under Win32 (and any other OS that protects global
55 * constants from being written to).
57 * Revision 1.28 2001/09/10 10:18:51 oes
58 * Silenced compiler warnings
60 * Revision 1.27 2001/08/05 16:06:20 jongfoster
61 * Modifiying "struct map" so that there are now separate header and
62 * "map_entry" structures. This means that functions which modify a
63 * map no longer need to return a pointer to the modified map.
64 * Also, it no longer reverses the order of the entries (which may be
65 * important with some advanced template substitutions).
67 * Revision 1.26 2001/07/30 22:08:36 jongfoster
68 * Tidying up #defines:
69 * - All feature #defines are now of the form FEATURE_xxx
70 * - Permanently turned off WIN_GUI_EDIT
71 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
73 * Revision 1.25 2001/07/26 10:09:46 oes
74 * Made browser detection a little less naive
76 * Revision 1.24 2001/07/25 17:22:51 oes
77 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
79 * Revision 1.23 2001/07/23 13:40:12 oes
80 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
82 * Revision 1.22 2001/07/18 12:29:34 oes
83 * - Made gif_deanimate_response respect
84 * csp->action->string[ACTION_STRING_DEANIMATE]
87 * Revision 1.21 2001/07/13 13:59:53 oes
88 * - Introduced gif_deanimate_response which shares the
89 * generic content modification interface of pcrs_filter_response
90 * and acts as a wrapper to deanimate.c:gif_deanimate()
91 * - Renamed re_process_buffer to pcrs_filter_response
92 * - pcrs_filter_response now returns NULL on failiure
93 * - Removed all #ifdef PCRS
95 * Revision 1.20 2001/07/01 17:01:04 oes
96 * Added comments and missing return statement in is_untrusted_url()
98 * Revision 1.19 2001/06/29 21:45:41 oes
99 * Indentation, CRLF->LF, Tab-> Space
101 * Revision 1.18 2001/06/29 13:27:38 oes
102 * - Cleaned up, renamed and reorderd functions
103 * and improved comments
106 * - Ported to CGI platform. Now delivers
107 * http_response or NULL
108 * - Unified HTML and GIF generation (moved image detection
109 * and GIF generation here from jcc.c:chat())
110 * - Fixed HTTP status to:
111 * - 403 (Forbidden) for the "blocked" HTML message
112 * - 200 (OK) for GIF answers
113 * - 302 (Redirect) for redirect to GIF
116 * - Ported to CGI platform. Now delivers
117 * http_response or NULL
118 * - Separated detection of untrusted URL into
119 * (bool)is_untrusted_url
120 * - Added enforcement of untrusted requests
122 * - Moved redirect_url() from cgi.c to here
123 * and ported it to the CGI platform
125 * - Removed logentry from cancelled commit
127 * Revision 1.17 2001/06/09 10:55:28 jongfoster
128 * Changing BUFSIZ ==> BUFFER_SIZE
130 * Revision 1.16 2001/06/07 23:10:26 jongfoster
131 * Allowing unanchored domain patterns to back off and retry
132 * if they partially match. Optimized right-anchored patterns.
133 * Moving ACL and forward files into config file.
134 * Replacing struct gateway with struct forward_spec
136 * Revision 1.15 2001/06/03 19:12:00 oes
137 * extracted-CGI relevant stuff
139 * Revision 1.14 2001/06/01 10:30:55 oes
140 * Added optional left-anchoring to domaincmp
142 * Revision 1.13 2001/05/31 21:21:30 jongfoster
143 * Permissionsfile / actions file changes:
144 * - Changed "permission" to "action" throughout
145 * - changes to file format to allow string parameters
146 * - Moved helper functions to actions.c
148 * Revision 1.12 2001/05/31 17:35:20 oes
150 * - Enhanced domain part globbing with infix and prefix asterisk
151 * matching and optional unanchored operation
153 * Revision 1.11 2001/05/29 11:53:23 oes
154 * "See why" link added to "blocked" page
156 * Revision 1.10 2001/05/29 09:50:24 jongfoster
157 * Unified blocklist/imagelist/permissionslist.
158 * File format is still under discussion, but the internal changes
161 * Also modified interceptor behaviour:
162 * - We now intercept all URLs beginning with one of the following
163 * prefixes (and *only* these prefixes):
165 * * http://ijbswa.sf.net/config/
166 * * http://ijbswa.sourceforge.net/config/
167 * - New interceptors "home page" - go to http://i.j.b/ to see it.
168 * - Internal changes so that intercepted and fast redirect pages
169 * are not replaced with an image.
170 * - Interceptors now have the option to send a binary page direct
171 * to the client. (i.e. ijb-send-banner uses this)
172 * - Implemented show-url-info interceptor. (Which is why I needed
173 * the above interceptors changes - a typical URL is
174 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
175 * The previous mechanism would not have intercepted that, and
176 * if it had been intercepted then it then it would have replaced
179 * Revision 1.9 2001/05/27 22:17:04 oes
181 * - re_process_buffer no longer writes the modified buffer
182 * to the client, which was very ugly. It now returns the
183 * buffer, which it is then written by chat.
185 * - content_length now adjusts the Content-Length: header
186 * for modified documents rather than crunch()ing it.
187 * (Length info in csp->content_length, which is 0 for
188 * unmodified documents)
190 * - For this to work, sed() is called twice when filtering.
192 * Revision 1.8 2001/05/26 17:13:28 jongfoster
193 * Filled in a function comment.
195 * Revision 1.7 2001/05/26 15:26:15 jongfoster
196 * ACL feature now provides more security by immediately dropping
197 * connections from untrusted hosts.
199 * Revision 1.6 2001/05/26 00:28:36 jongfoster
200 * Automatic reloading of config file.
201 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
202 * Most of the global variables have been moved to a new
203 * struct configuration_spec, accessed through csp->config->globalname
204 * Most of the globals remaining are used by the Win32 GUI.
206 * Revision 1.5 2001/05/25 22:34:30 jongfoster
209 * Revision 1.4 2001/05/22 18:46:04 oes
211 * - Enabled filtering banners by size rather than URL
212 * by adding patterns that replace all standard banner
213 * sizes with the "Junkbuster" gif to the re_filterfile
215 * - Enabled filtering WebBugs by providing a pattern
216 * which kills all 1x1 images
218 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
219 * which is selected by the (nonstandard and therefore
220 * capital) letter 'U' in the option string.
221 * It causes the quantifiers to be ungreedy by default.
222 * Appending a ? turns back to greedy (!).
224 * - Added a new interceptor ijb-send-banner, which
225 * sends back the "Junkbuster" gif. Without imagelist or
226 * MSIE detection support, or if tinygif = 1, or the
227 * URL isn't recognized as an imageurl, a lame HTML
228 * explanation is sent instead.
230 * - Added new feature, which permits blocking remote
231 * script redirects and firing back a local redirect
233 * The feature is conditionally compiled, i.e. it
234 * can be disabled with --disable-fast-redirects,
235 * plus it must be activated by a "fast-redirects"
236 * line in the config file, has its own log level
237 * and of course wants to be displayed by show-proxy-args
238 * Note: Boy, all the #ifdefs in 1001 locations and
239 * all the fumbling with configure.in and acconfig.h
240 * were *way* more work than the feature itself :-(
242 * - Because a generic redirect template was needed for
243 * this, tinygif = 3 now uses the same.
245 * - Moved GIFs, and other static HTTP response templates
250 * - Removed some >400 CRs again (Jon, you really worked
253 * Revision 1.3 2001/05/20 16:44:47 jongfoster
254 * Removing last hardcoded JunkBusters.com URLs.
256 * Revision 1.2 2001/05/20 01:21:20 jongfoster
257 * Version 2.9.4 checkin.
258 * - Merged popupfile and cookiefile, and added control over PCRS
259 * filtering, in new "permissionsfile".
260 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
261 * file error you now get a message box (in the Win32 GUI) rather
262 * than the program exiting with no explanation.
263 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
265 * - Removed tabs from "config"
266 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
267 * - Bumped up version number.
269 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
270 * Initial import of version 2.9.3 source tree
273 *********************************************************************/
279 #include <sys/types.h>
286 #include <netinet/in.h>
288 #include <winsock2.h>
295 #include "showargs.h"
299 #include "jbsockets.h"
301 #include "jbsockets.h"
302 #include "miscutil.h"
306 #include "deanimate.h"
312 const char filters_h_rcs[] = FILTERS_H_VERSION;
314 /* Fix a problem with Solaris. There should be no effect on other
316 * Solaris's isspace() is a macro which uses it's argument directly
317 * as an array index. Therefore we need to make sure that high-bit
318 * characters generate +ve values, and ideally we also want to make
319 * the argument match the declared parameter type of "int".
321 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
325 /*********************************************************************
327 * Function : block_acl
329 * Description : Block this request?
330 * Decide yes or no based on ACL file.
333 * 1 : dst = The proxy or gateway address this is going to.
334 * Or NULL to check all possible targets.
335 * 2 : csp = Current client state (buffers, headers, etc...)
336 * Also includes the client IP address.
338 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
340 *********************************************************************/
341 int block_acl(struct access_control_addr *dst, struct client_state *csp)
343 struct access_control_list *acl = csp->config->acl;
345 /* if not using an access control list, then permit the connection */
351 /* search the list */
354 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
358 /* Just want to check if they have any access */
359 if (acl->action == ACL_PERMIT)
364 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
365 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
367 if (acl->action == ACL_PERMIT)
385 /*********************************************************************
387 * Function : acl_addr
389 * Description : Called from `load_aclfile' to parse an ACL address.
392 * 1 : aspec = String specifying ACL address.
393 * 2 : aca = struct access_control_addr to fill in.
395 * Returns : 0 => Ok, everything else is an error.
397 *********************************************************************/
398 int acl_addr(char *aspec, struct access_control_addr *aca)
400 int i, masklength, port;
406 if ((p = strchr(aspec, '/')))
410 if (ijb_isdigit(*p) == 0)
414 masklength = atoi(p);
417 if ((masklength < 0) || (masklength > 32))
422 if ((p = strchr(aspec, ':')))
426 if (ijb_isdigit(*p) == 0)
435 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
439 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
443 /* build the netmask */
445 for (i=1; i <= masklength ; i++)
447 aca->mask |= (1 << (32 - i));
450 /* now mask off the host portion of the ip address
451 * (i.e. save on the network portion of the address).
453 aca->addr = aca->addr & aca->mask;
458 #endif /* def FEATURE_ACL */
461 /*********************************************************************
463 * Function : block_url
465 * Description : Called from `chat'. Check to see if we need to block this.
468 * 1 : csp = Current client state (buffers, headers, etc...)
470 * Returns : NULL => unblocked, else HTTP block response
472 *********************************************************************/
473 struct http_response *block_url(struct client_state *csp)
475 #ifdef FEATURE_IMAGE_BLOCKING
477 #endif /* def FEATURE_IMAGE_BLOCKING */
478 struct http_response *rsp;
481 * If it's not blocked, don't block it ;-)
483 if ((csp->action->flags & ACTION_BLOCK) == 0)
489 * Else, prepare a response
491 if (NULL == (rsp = alloc_http_response()))
497 * If it's an image-url, send back an image or redirect
498 * as specified by the relevant +image action
500 #ifdef FEATURE_IMAGE_BLOCKING
501 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
504 /* determine HOW images should be blocked */
505 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
507 /* and handle accordingly: */
508 if ((p == NULL) || (0 == strcmpic(p, "logo")))
510 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
511 rsp->content_length = image_junkbuster_gif_length;
512 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
515 else if (0 == strcmpic(p, "blank"))
517 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
518 rsp->content_length = image_blank_gif_length;
519 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
524 rsp->status = strdup("302 Local Redirect from Junkbuster");
525 enlist_unique_header(rsp->headers, "Location", p);
529 #endif /* def FEATURE_IMAGE_BLOCKING */
532 * Else, generate an HTML "blocked" message:
535 struct map * exports = default_exports(csp, NULL);
536 #ifdef FEATURE_FORCE_LOAD
537 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
538 #else /* ifndef FEATURE_FORCE_LOAD */
539 map_block_killer(exports, "force-support");
540 #endif /* ndef FEATURE_FORCE_LOAD */
542 map(exports, "hostport", 1, csp->http->hostport, 1);
543 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
544 map(exports, "path", 1, csp->http->path, 1);
545 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
547 rsp->body = template_load(csp, "blocked");
548 template_fill(&rsp->body, exports);
552 * Workaround for stupid Netscape bug which prevents
553 * pages from being displayed if loading a referenced
554 * JavaScript or style sheet fails. So make it appear
555 * as if it succeeded.
557 if (csp->http->user_agent
558 && !strncmpic(csp->http->user_agent, "mozilla", 7)
559 && !strstr(csp->http->user_agent, "compatible")
560 && !strstr(csp->http->user_agent, "Opera"))
562 rsp->status = strdup("200 Request for blocked URL");
566 rsp->status = strdup("404 Request for blocked URL");
571 return(finish_http_response(rsp));
577 /*********************************************************************
579 * Function : trust_url FIXME: I should be called distrust_url
581 * Description : Calls is_untrusted_url to determine if the URL is trusted
582 * and if not, returns a HTTP 304 response with a reject message.
585 * 1 : csp = Current client state (buffers, headers, etc...)
587 * Returns : NULL => trusted, else http_response.
589 *********************************************************************/
590 struct http_response *trust_url(struct client_state *csp)
592 struct http_response *rsp;
593 struct map * exports;
594 char buf[BUFFER_SIZE], *p = NULL;
595 struct url_spec **tl, *t;
598 * Don't bother to work on trusted URLs
600 if (!is_untrusted_url(csp))
606 * Else, prepare a response:
608 if (NULL == (rsp = alloc_http_response()))
613 exports = default_exports(csp, NULL);
616 * Export the host, port, and referrer information
618 map(exports, "hostport", 1, csp->http->hostport, 1);
619 map(exports, "path", 1, csp->http->path, 1);
620 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
621 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
623 if (csp->referrer && strlen(csp->referrer) > 9)
625 map(exports, "referrer", 1, csp->referrer + 9, 1);
626 map(exports, "referrer-html", 1, html_encode(csp->referrer + 9), 0);
630 map(exports, "referrer", 1, "unknown", 1);
631 map(exports, "referrer-html", 1, "unknown", 1);
635 * Export the trust list
637 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
639 sprintf(buf, "<li>%s</li>\n", t->spec);
642 map(exports, "trusted-referrers", 1, p, 0);
646 * Export the trust info, if available
648 if (csp->config->trust_info->first)
650 struct list_entry *l;
652 for (l = csp->config->trust_info->first; l ; l = l->next)
654 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
657 map(exports, "trust-info", 1, p, 0);
661 map_block_killer(exports, "have-trust-info");
665 * Export the force prefix or the force conditional block killer
667 #ifdef FEATURE_FORCE_LOAD
668 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
669 #else /* ifndef FEATURE_FORCE_LOAD */
670 map_block_killer(exports, "force-support");
671 #endif /* ndef FEATURE_FORCE_LOAD */
676 rsp->body = template_load(csp, "untrusted");
677 template_fill(&rsp->body, exports);
680 return(finish_http_response(rsp));
683 #endif /* def FEATURE_TRUST */
686 #ifdef FEATURE_FAST_REDIRECTS
687 /*********************************************************************
689 * Function : redirect_url
691 * Description : Checks for redirection URLs and returns a HTTP redirect
692 * to the destination URL, if necessary
695 * 1 : csp = Current client state (buffers, headers, etc...)
697 * Returns : NULL if URL was clean, HTTP redirect otherwise.
699 *********************************************************************/
700 struct http_response *redirect_url(struct client_state *csp)
703 struct http_response *rsp;
705 p = q = csp->http->path;
706 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
709 * find the last URL encoded in the request
711 while ((p = strstr(p, "http://")))
717 * if there was any, generate and return a HTTP redirect
719 if (q != csp->http->path)
721 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
723 if (NULL == (rsp = alloc_http_response()))
728 rsp->status = strdup("302 Local Redirect from Junkbuster");
729 enlist_unique_header(rsp->headers, "Location", q);
731 return(finish_http_response(rsp));
739 #endif /* def FEATURE_FAST_REDIRECTS */
742 #ifdef FEATURE_IMAGE_BLOCKING
743 /*********************************************************************
745 * Function : is_imageurl
747 * Description : Given a URL, decide whether it is an image or not,
748 * using either the info from a previous +image action
749 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
750 * the browser's accept header.
753 * 1 : csp = Current client state (buffers, headers, etc...)
755 * Returns : True (nonzero) if URL is an image, false (0)
758 *********************************************************************/
759 int is_imageurl(struct client_state *csp)
761 #ifdef FEATURE_IMAGE_DETECT_MSIE
762 if ((csp->accept_types
763 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
764 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
768 else if ((csp->accept_types
769 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
770 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
774 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
776 return ((csp->action->flags & ACTION_IMAGE) != 0);
779 #endif /* def FEATURE_IMAGE_BLOCKING */
782 #ifdef FEATURE_COOKIE_JAR
783 /*********************************************************************
785 * Function : is_untrusted_url
787 * Description : Should we "distrust" this URL (and block it)?
789 * Yes if it matches a line in the trustfile, or if the
790 * referrer matches a line starting with "+" in the
795 * 1 : csp = Current client state (buffers, headers, etc...)
797 * Returns : 0 => trusted, 1 => untrusted
799 *********************************************************************/
800 int is_untrusted_url(struct client_state *csp)
802 struct file_list *fl;
803 struct block_spec *b;
804 struct url_spec url[1], **tl, *t;
805 struct http_request rhttp[1];
809 * If we don't have a trustlist, we trust everybody
811 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
818 * Do we trust the request URL itself?
820 *url = dsplit(csp->http->host);
822 /* if splitting the domain fails, punt */
823 if (url->dbuf == NULL) return(0);
825 memset(rhttp, '\0', sizeof(*rhttp));
827 for (b = b->next; b ; b = b->next)
829 if ((b->url->port == 0) || (b->url->port == csp->http->port))
831 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
833 if ((b->url->path == NULL) ||
835 (regexec(b->url->preg, csp->http->path, 0, NULL, 0) == 0)
837 (strncmp(b->url->path, csp->http->path, b->url->pathlen) == 0)
844 if (b->reject == 0) return(0);
855 if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
857 /* no referrer was supplied */
861 /* forge a URL from the referrer so we can use
862 * convert_url() to parse it into its components.
866 p = strsav(p, "GET ");
867 p = strsav(p, csp->referrer + 9); /* skip over "Referer: " */
868 p = strsav(p, " HTTP/1.0");
870 parse_http_request(p, rhttp, csp);
873 if (rhttp->cmd == NULL)
880 * If not, do we maybe trust its referrer?
882 *url = dsplit(rhttp->host);
884 /* if splitting the domain fails, punt */
885 if (url->dbuf == NULL) return(1);
887 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
889 if ((t->port == 0) || (t->port == rhttp->port))
891 if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
893 if ((t->path == NULL) ||
895 (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
897 (strncmp(t->path, rhttp->path, t->pathlen) == 0)
901 /* if the URL's referrer is from a trusted referrer, then
902 * add the target spec to the trustfile as an unblocked
903 * domain and return NULL (which means it's OK).
911 if ((fp = fopen(csp->config->trustfile, "a")))
916 h = strsav(h, csp->http->hostport);
922 /* since this path points into a user's home space
923 * be sure to include this spec in the trustfile.
925 if ((p = strchr(p, '/')))
928 h = strsav(h, csp->http->path); /* FIXME: p?! */
933 fprintf(fp, "%s\n", h);
944 #endif /* def FEATURE_COOKIE_JAR */
947 /*********************************************************************
949 * Function : pcrs_filter_response
951 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
952 * to the text buffer that's been accumulated in
953 * csp->iob->buf and set csp->content_length to the modified
957 * 1 : csp = Current client state (buffers, headers, etc...)
959 * Returns : a pointer to the (newly allocated) modified buffer.
960 * or NULL in case something went wrong
962 *********************************************************************/
963 char *pcrs_filter_response(struct client_state *csp)
966 int size = csp->iob->eod - csp->iob->cur;
968 char *old = csp->iob->cur, *new = NULL;
971 struct file_list *fl;
972 struct re_filterfile_spec *b;
974 /* Sanity first ;-) */
980 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
982 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
986 if ( NULL == b->joblist )
988 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
992 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
993 csp->http->hostport, csp->http->path, size);
995 /* Apply all jobs from the joblist */
996 for (job = b->joblist; NULL != job; job = job->next)
998 hits += pcrs_execute(job, old, size, &new, &size);
999 if (old != csp->iob->cur) free(old);
1003 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1005 csp->content_length = size;
1007 /* fwiw, reset the iob */
1014 /*********************************************************************
1016 * Function : gif_deanimate_response
1018 * Description : Deanimate the GIF image that has been accumulated in
1019 * csp->iob->buf and set csp->content_length to the modified
1023 * 1 : csp = Current client state (buffers, headers, etc...)
1025 * Returns : a pointer to the (newly allocated) modified buffer.
1026 * or NULL in case something went wrong.
1028 *********************************************************************/
1029 char *gif_deanimate_response(struct client_state *csp)
1031 struct binbuffer *in, *out;
1033 int size = csp->iob->eod - csp->iob->cur;
1035 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1036 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1038 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1042 in->buffer = csp->iob->cur;
1045 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1047 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1054 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1055 csp->content_length = out->offset;
1065 /*********************************************************************
1067 * Function : url_actions
1069 * Description : Gets the actions for this URL.
1072 * 1 : http = http_request request for blocked URLs
1073 * 2 : csp = Current client state (buffers, headers, etc...)
1077 *********************************************************************/
1078 void url_actions(struct http_request *http,
1079 struct client_state *csp)
1081 struct file_list *fl;
1082 struct url_actions *b;
1084 init_current_action(csp->action);
1086 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1091 apply_url_actions(csp->action, http, b);
1096 /*********************************************************************
1098 * Function : apply_url_actions
1100 * Description : Applies a list of URL actions.
1103 * 1 : action = Destination.
1104 * 2 : http = Current URL
1105 * 3 : b = list of URL actions to apply
1109 *********************************************************************/
1110 void apply_url_actions(struct current_action_spec *action,
1111 struct http_request *http,
1112 struct url_actions *b)
1114 struct url_spec url[1];
1118 /* Should never happen */
1122 *url = dsplit(http->host);
1124 /* if splitting the domain fails, punt */
1125 if (url->dbuf == NULL)
1130 for (b = b->next; NULL != b; b = b->next)
1132 if ((b->url->port == 0) || (b->url->port == http->port))
1134 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1136 if ((b->url->path == NULL) ||
1138 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
1140 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
1144 merge_current_action(action, b->action);
1155 /*********************************************************************
1157 * Function : forward_url
1159 * Description : Should we forward this to another proxy?
1162 * 1 : http = http_request request for current URL
1163 * 2 : csp = Current client state (buffers, headers, etc...)
1165 * Returns : Pointer to forwarding information.
1167 *********************************************************************/
1168 const struct forward_spec * forward_url(struct http_request *http,
1169 struct client_state *csp)
1171 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1172 struct forward_spec *fwd = csp->config->forward;
1173 struct url_spec url[1];
1177 return(fwd_default);
1180 *url = dsplit(http->host);
1182 /* if splitting the domain fails, punt */
1183 if (url->dbuf == NULL)
1185 return(fwd_default);
1190 if ((fwd->url->port == 0) || (fwd->url->port == http->port))
1192 if ((fwd->url->domain[0] == '\0') || (domaincmp(fwd->url, url) == 0))
1194 if ((fwd->url->path == NULL) ||
1196 (regexec(fwd->url->preg, http->path, 0, NULL, 0) == 0)
1198 (strncmp(fwd->url->path, http->path, fwd->url->pathlen) == 0)
1213 return(fwd_default);
1218 /*********************************************************************
1222 * Description : Takes a domain and returns a pointer to a url_spec
1223 * structure populated with dbuf, dcnt and dvec. The
1224 * other fields in the structure that is returned are zero.
1227 * 1 : domain = a URL address
1229 * Returns : url_spec structure populated with dbuf, dcnt and dvec.
1231 *********************************************************************/
1232 struct url_spec dsplit(char *domain)
1234 struct url_spec ret[1];
1235 char *v[BUFFER_SIZE];
1239 memset(ret, '\0', sizeof(*ret));
1241 if (domain[strlen(domain) - 1] == '.')
1243 ret->unanchored |= ANCHOR_RIGHT;
1246 if (domain[0] == '.')
1248 ret->unanchored |= ANCHOR_LEFT;
1251 ret->dbuf = strdup(domain);
1253 /* map to lower case */
1254 for (p = ret->dbuf; *p ; p++) *p = tolower(*p);
1256 /* split the domain name into components */
1257 ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
1261 memset(ret, '\0', sizeof(ret));
1265 /* save a copy of the pointers in dvec */
1266 size = ret->dcnt * sizeof(*ret->dvec);
1268 if ((ret->dvec = (char **)malloc(size)))
1270 memcpy(ret->dvec, v, size);
1278 /*********************************************************************
1280 * Function : simple_domaincmp
1282 * Description : Domain-wise Compare fqdn's. The comparison is
1283 * both left- and right-anchored. The individual
1284 * domain names are compared with simplematch().
1285 * This is only used by domaincmp.
1288 * 1 : pv = array of patterns to compare
1289 * 2 : fv = array of domain components to compare
1290 * 3 : len = length of the arrays (both arrays are the
1291 * same length - if they weren't, it couldn't
1292 * possibly be a match).
1294 * Returns : 0 => domains are equivalent, else no match.
1296 *********************************************************************/
1297 static int simple_domaincmp(char **pv, char **fv, int len)
1301 for (n = 0; n < len; n++)
1303 if (simplematch(pv[n], fv[n]))
1314 /*********************************************************************
1316 * Function : domaincmp
1318 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1319 * pattern->unachored, the comparison is un-, left-,
1320 * right-anchored, or both.
1321 * The individual domain names are compared with
1325 * 1 : pattern = a domain that may contain a '*' as a wildcard.
1326 * 2 : fqdn = domain name against which the patterns are compared.
1328 * Returns : 0 => domains are equivalent, else no match.
1330 *********************************************************************/
1331 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1333 char **pv, **fv; /* vectors */
1335 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1337 plen = pattern->dcnt;
1342 /* fqdn is too short to match this pattern */
1349 if (unanchored == ANCHOR_LEFT)
1354 * Convert this into a fully anchored pattern with
1355 * the fqdn and pattern the same length
1357 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1358 return simple_domaincmp(pv, fv, plen);
1360 else if (unanchored == 0)
1362 /* Fully anchored, check length */
1367 return simple_domaincmp(pv, fv, plen);
1369 else if (unanchored == ANCHOR_RIGHT)
1371 /* Left anchored, ignore all extra in fqdn */
1372 return simple_domaincmp(pv, fv, plen);
1378 int maxn = flen - plen;
1379 for (n = 0; n <= maxn; n++)
1381 if (!simple_domaincmp(pv, fv, plen))
1386 * Doesn't match from start of fqdn
1387 * Try skipping first part of fqdn