1 const char filters_rcs[] = "$Id: filters.c,v 1.32 2001/09/16 13:21:27 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.32 2001/09/16 13:21:27 jongfoster
42 * Changes to use new list functions.
44 * Revision 1.31 2001/09/16 11:38:02 jongfoster
45 * Splitting fill_template() into 2 functions:
46 * template_load() loads the file
47 * template_fill() performs the PCRS regexps.
48 * This is because the CGI edit interface has a "table row"
49 * template which is used many times in the page - this
50 * change means it's only loaded from disk once.
52 * Revision 1.30 2001/09/16 11:00:10 jongfoster
53 * New function alloc_http_response, for symmetry with free_http_response
55 * Revision 1.29 2001/09/13 23:32:40 jongfoster
56 * Moving image data to cgi.c rather than cgi.h
57 * Fixing a GPF under Win32 (and any other OS that protects global
58 * constants from being written to).
60 * Revision 1.28 2001/09/10 10:18:51 oes
61 * Silenced compiler warnings
63 * Revision 1.27 2001/08/05 16:06:20 jongfoster
64 * Modifiying "struct map" so that there are now separate header and
65 * "map_entry" structures. This means that functions which modify a
66 * map no longer need to return a pointer to the modified map.
67 * Also, it no longer reverses the order of the entries (which may be
68 * important with some advanced template substitutions).
70 * Revision 1.26 2001/07/30 22:08:36 jongfoster
71 * Tidying up #defines:
72 * - All feature #defines are now of the form FEATURE_xxx
73 * - Permanently turned off WIN_GUI_EDIT
74 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
76 * Revision 1.25 2001/07/26 10:09:46 oes
77 * Made browser detection a little less naive
79 * Revision 1.24 2001/07/25 17:22:51 oes
80 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
82 * Revision 1.23 2001/07/23 13:40:12 oes
83 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
85 * Revision 1.22 2001/07/18 12:29:34 oes
86 * - Made gif_deanimate_response respect
87 * csp->action->string[ACTION_STRING_DEANIMATE]
90 * Revision 1.21 2001/07/13 13:59:53 oes
91 * - Introduced gif_deanimate_response which shares the
92 * generic content modification interface of pcrs_filter_response
93 * and acts as a wrapper to deanimate.c:gif_deanimate()
94 * - Renamed re_process_buffer to pcrs_filter_response
95 * - pcrs_filter_response now returns NULL on failiure
96 * - Removed all #ifdef PCRS
98 * Revision 1.20 2001/07/01 17:01:04 oes
99 * Added comments and missing return statement in is_untrusted_url()
101 * Revision 1.19 2001/06/29 21:45:41 oes
102 * Indentation, CRLF->LF, Tab-> Space
104 * Revision 1.18 2001/06/29 13:27:38 oes
105 * - Cleaned up, renamed and reorderd functions
106 * and improved comments
109 * - Ported to CGI platform. Now delivers
110 * http_response or NULL
111 * - Unified HTML and GIF generation (moved image detection
112 * and GIF generation here from jcc.c:chat())
113 * - Fixed HTTP status to:
114 * - 403 (Forbidden) for the "blocked" HTML message
115 * - 200 (OK) for GIF answers
116 * - 302 (Redirect) for redirect to GIF
119 * - Ported to CGI platform. Now delivers
120 * http_response or NULL
121 * - Separated detection of untrusted URL into
122 * (bool)is_untrusted_url
123 * - Added enforcement of untrusted requests
125 * - Moved redirect_url() from cgi.c to here
126 * and ported it to the CGI platform
128 * - Removed logentry from cancelled commit
130 * Revision 1.17 2001/06/09 10:55:28 jongfoster
131 * Changing BUFSIZ ==> BUFFER_SIZE
133 * Revision 1.16 2001/06/07 23:10:26 jongfoster
134 * Allowing unanchored domain patterns to back off and retry
135 * if they partially match. Optimized right-anchored patterns.
136 * Moving ACL and forward files into config file.
137 * Replacing struct gateway with struct forward_spec
139 * Revision 1.15 2001/06/03 19:12:00 oes
140 * extracted-CGI relevant stuff
142 * Revision 1.14 2001/06/01 10:30:55 oes
143 * Added optional left-anchoring to domaincmp
145 * Revision 1.13 2001/05/31 21:21:30 jongfoster
146 * Permissionsfile / actions file changes:
147 * - Changed "permission" to "action" throughout
148 * - changes to file format to allow string parameters
149 * - Moved helper functions to actions.c
151 * Revision 1.12 2001/05/31 17:35:20 oes
153 * - Enhanced domain part globbing with infix and prefix asterisk
154 * matching and optional unanchored operation
156 * Revision 1.11 2001/05/29 11:53:23 oes
157 * "See why" link added to "blocked" page
159 * Revision 1.10 2001/05/29 09:50:24 jongfoster
160 * Unified blocklist/imagelist/permissionslist.
161 * File format is still under discussion, but the internal changes
164 * Also modified interceptor behaviour:
165 * - We now intercept all URLs beginning with one of the following
166 * prefixes (and *only* these prefixes):
168 * * http://ijbswa.sf.net/config/
169 * * http://ijbswa.sourceforge.net/config/
170 * - New interceptors "home page" - go to http://i.j.b/ to see it.
171 * - Internal changes so that intercepted and fast redirect pages
172 * are not replaced with an image.
173 * - Interceptors now have the option to send a binary page direct
174 * to the client. (i.e. ijb-send-banner uses this)
175 * - Implemented show-url-info interceptor. (Which is why I needed
176 * the above interceptors changes - a typical URL is
177 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
178 * The previous mechanism would not have intercepted that, and
179 * if it had been intercepted then it then it would have replaced
182 * Revision 1.9 2001/05/27 22:17:04 oes
184 * - re_process_buffer no longer writes the modified buffer
185 * to the client, which was very ugly. It now returns the
186 * buffer, which it is then written by chat.
188 * - content_length now adjusts the Content-Length: header
189 * for modified documents rather than crunch()ing it.
190 * (Length info in csp->content_length, which is 0 for
191 * unmodified documents)
193 * - For this to work, sed() is called twice when filtering.
195 * Revision 1.8 2001/05/26 17:13:28 jongfoster
196 * Filled in a function comment.
198 * Revision 1.7 2001/05/26 15:26:15 jongfoster
199 * ACL feature now provides more security by immediately dropping
200 * connections from untrusted hosts.
202 * Revision 1.6 2001/05/26 00:28:36 jongfoster
203 * Automatic reloading of config file.
204 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
205 * Most of the global variables have been moved to a new
206 * struct configuration_spec, accessed through csp->config->globalname
207 * Most of the globals remaining are used by the Win32 GUI.
209 * Revision 1.5 2001/05/25 22:34:30 jongfoster
212 * Revision 1.4 2001/05/22 18:46:04 oes
214 * - Enabled filtering banners by size rather than URL
215 * by adding patterns that replace all standard banner
216 * sizes with the "Junkbuster" gif to the re_filterfile
218 * - Enabled filtering WebBugs by providing a pattern
219 * which kills all 1x1 images
221 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
222 * which is selected by the (nonstandard and therefore
223 * capital) letter 'U' in the option string.
224 * It causes the quantifiers to be ungreedy by default.
225 * Appending a ? turns back to greedy (!).
227 * - Added a new interceptor ijb-send-banner, which
228 * sends back the "Junkbuster" gif. Without imagelist or
229 * MSIE detection support, or if tinygif = 1, or the
230 * URL isn't recognized as an imageurl, a lame HTML
231 * explanation is sent instead.
233 * - Added new feature, which permits blocking remote
234 * script redirects and firing back a local redirect
236 * The feature is conditionally compiled, i.e. it
237 * can be disabled with --disable-fast-redirects,
238 * plus it must be activated by a "fast-redirects"
239 * line in the config file, has its own log level
240 * and of course wants to be displayed by show-proxy-args
241 * Note: Boy, all the #ifdefs in 1001 locations and
242 * all the fumbling with configure.in and acconfig.h
243 * were *way* more work than the feature itself :-(
245 * - Because a generic redirect template was needed for
246 * this, tinygif = 3 now uses the same.
248 * - Moved GIFs, and other static HTTP response templates
253 * - Removed some >400 CRs again (Jon, you really worked
256 * Revision 1.3 2001/05/20 16:44:47 jongfoster
257 * Removing last hardcoded JunkBusters.com URLs.
259 * Revision 1.2 2001/05/20 01:21:20 jongfoster
260 * Version 2.9.4 checkin.
261 * - Merged popupfile and cookiefile, and added control over PCRS
262 * filtering, in new "permissionsfile".
263 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
264 * file error you now get a message box (in the Win32 GUI) rather
265 * than the program exiting with no explanation.
266 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
268 * - Removed tabs from "config"
269 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
270 * - Bumped up version number.
272 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
273 * Initial import of version 2.9.3 source tree
276 *********************************************************************/
282 #include <sys/types.h>
289 #include <netinet/in.h>
291 #include <winsock2.h>
300 #include "jbsockets.h"
301 #include "miscutil.h"
305 #include "deanimate.h"
311 const char filters_h_rcs[] = FILTERS_H_VERSION;
313 /* Fix a problem with Solaris. There should be no effect on other
315 * Solaris's isspace() is a macro which uses it's argument directly
316 * as an array index. Therefore we need to make sure that high-bit
317 * characters generate +ve values, and ideally we also want to make
318 * the argument match the declared parameter type of "int".
320 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
324 /*********************************************************************
326 * Function : block_acl
328 * Description : Block this request?
329 * Decide yes or no based on ACL file.
332 * 1 : dst = The proxy or gateway address this is going to.
333 * Or NULL to check all possible targets.
334 * 2 : csp = Current client state (buffers, headers, etc...)
335 * Also includes the client IP address.
337 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
339 *********************************************************************/
340 int block_acl(struct access_control_addr *dst, struct client_state *csp)
342 struct access_control_list *acl = csp->config->acl;
344 /* if not using an access control list, then permit the connection */
350 /* search the list */
353 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
357 /* Just want to check if they have any access */
358 if (acl->action == ACL_PERMIT)
363 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
364 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
366 if (acl->action == ACL_PERMIT)
384 /*********************************************************************
386 * Function : acl_addr
388 * Description : Called from `load_aclfile' to parse an ACL address.
391 * 1 : aspec = String specifying ACL address.
392 * 2 : aca = struct access_control_addr to fill in.
394 * Returns : 0 => Ok, everything else is an error.
396 *********************************************************************/
397 int acl_addr(char *aspec, struct access_control_addr *aca)
399 int i, masklength, port;
405 if ((p = strchr(aspec, '/')))
409 if (ijb_isdigit(*p) == 0)
413 masklength = atoi(p);
416 if ((masklength < 0) || (masklength > 32))
421 if ((p = strchr(aspec, ':')))
425 if (ijb_isdigit(*p) == 0)
434 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
438 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
442 /* build the netmask */
444 for (i=1; i <= masklength ; i++)
446 aca->mask |= (1 << (32 - i));
449 /* now mask off the host portion of the ip address
450 * (i.e. save on the network portion of the address).
452 aca->addr = aca->addr & aca->mask;
457 #endif /* def FEATURE_ACL */
460 /*********************************************************************
462 * Function : block_url
464 * Description : Called from `chat'. Check to see if we need to block this.
467 * 1 : csp = Current client state (buffers, headers, etc...)
469 * Returns : NULL => unblocked, else HTTP block response
471 *********************************************************************/
472 struct http_response *block_url(struct client_state *csp)
474 #ifdef FEATURE_IMAGE_BLOCKING
476 #endif /* def FEATURE_IMAGE_BLOCKING */
477 struct http_response *rsp;
480 * If it's not blocked, don't block it ;-)
482 if ((csp->action->flags & ACTION_BLOCK) == 0)
488 * Else, prepare a response
490 if (NULL == (rsp = alloc_http_response()))
496 * If it's an image-url, send back an image or redirect
497 * as specified by the relevant +image action
499 #ifdef FEATURE_IMAGE_BLOCKING
500 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
503 /* determine HOW images should be blocked */
504 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
506 /* and handle accordingly: */
507 if ((p == NULL) || (0 == strcmpic(p, "logo")))
509 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
510 rsp->content_length = image_junkbuster_gif_length;
511 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
514 else if (0 == strcmpic(p, "blank"))
516 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
517 rsp->content_length = image_blank_gif_length;
518 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
523 rsp->status = strdup("302 Local Redirect from Junkbuster");
524 enlist_unique_header(rsp->headers, "Location", p);
528 #endif /* def FEATURE_IMAGE_BLOCKING */
531 * Else, generate an HTML "blocked" message:
534 struct map * exports = default_exports(csp, NULL);
535 #ifdef FEATURE_FORCE_LOAD
536 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
537 #else /* ifndef FEATURE_FORCE_LOAD */
538 map_block_killer(exports, "force-support");
539 #endif /* ndef FEATURE_FORCE_LOAD */
541 map(exports, "hostport", 1, csp->http->hostport, 1);
542 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
543 map(exports, "path", 1, csp->http->path, 1);
544 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
546 rsp->body = template_load(csp, "blocked");
547 template_fill(&rsp->body, exports);
551 * Workaround for stupid Netscape bug which prevents
552 * pages from being displayed if loading a referenced
553 * JavaScript or style sheet fails. So make it appear
554 * as if it succeeded.
556 if (csp->http->user_agent
557 && !strncmpic(csp->http->user_agent, "mozilla", 7)
558 && !strstr(csp->http->user_agent, "compatible")
559 && !strstr(csp->http->user_agent, "Opera"))
561 rsp->status = strdup("200 Request for blocked URL");
565 rsp->status = strdup("404 Request for blocked URL");
570 return(finish_http_response(rsp));
576 /*********************************************************************
578 * Function : trust_url FIXME: I should be called distrust_url
580 * Description : Calls is_untrusted_url to determine if the URL is trusted
581 * and if not, returns a HTTP 304 response with a reject message.
584 * 1 : csp = Current client state (buffers, headers, etc...)
586 * Returns : NULL => trusted, else http_response.
588 *********************************************************************/
589 struct http_response *trust_url(struct client_state *csp)
591 struct http_response *rsp;
592 struct map * exports;
593 char buf[BUFFER_SIZE], *p = NULL;
594 struct url_spec **tl, *t;
597 * Don't bother to work on trusted URLs
599 if (!is_untrusted_url(csp))
605 * Else, prepare a response:
607 if (NULL == (rsp = alloc_http_response()))
612 exports = default_exports(csp, NULL);
615 * Export the host, port, and referrer information
617 map(exports, "hostport", 1, csp->http->hostport, 1);
618 map(exports, "path", 1, csp->http->path, 1);
619 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
620 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
622 if (csp->referrer && strlen(csp->referrer) > 9)
624 map(exports, "referrer", 1, csp->referrer + 9, 1);
625 map(exports, "referrer-html", 1, html_encode(csp->referrer + 9), 0);
629 map(exports, "referrer", 1, "unknown", 1);
630 map(exports, "referrer-html", 1, "unknown", 1);
634 * Export the trust list
636 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
638 sprintf(buf, "<li>%s</li>\n", t->spec);
641 map(exports, "trusted-referrers", 1, p, 0);
645 * Export the trust info, if available
647 if (csp->config->trust_info->first)
649 struct list_entry *l;
651 for (l = csp->config->trust_info->first; l ; l = l->next)
653 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
656 map(exports, "trust-info", 1, p, 0);
660 map_block_killer(exports, "have-trust-info");
664 * Export the force prefix or the force conditional block killer
666 #ifdef FEATURE_FORCE_LOAD
667 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
668 #else /* ifndef FEATURE_FORCE_LOAD */
669 map_block_killer(exports, "force-support");
670 #endif /* ndef FEATURE_FORCE_LOAD */
675 rsp->body = template_load(csp, "untrusted");
676 template_fill(&rsp->body, exports);
679 return(finish_http_response(rsp));
682 #endif /* def FEATURE_TRUST */
685 #ifdef FEATURE_FAST_REDIRECTS
686 /*********************************************************************
688 * Function : redirect_url
690 * Description : Checks for redirection URLs and returns a HTTP redirect
691 * to the destination URL, if necessary
694 * 1 : csp = Current client state (buffers, headers, etc...)
696 * Returns : NULL if URL was clean, HTTP redirect otherwise.
698 *********************************************************************/
699 struct http_response *redirect_url(struct client_state *csp)
702 struct http_response *rsp;
704 p = q = csp->http->path;
705 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
708 * find the last URL encoded in the request
710 while ((p = strstr(p, "http://")))
716 * if there was any, generate and return a HTTP redirect
718 if (q != csp->http->path)
720 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
722 if (NULL == (rsp = alloc_http_response()))
727 rsp->status = strdup("302 Local Redirect from Junkbuster");
728 enlist_unique_header(rsp->headers, "Location", q);
730 return(finish_http_response(rsp));
738 #endif /* def FEATURE_FAST_REDIRECTS */
741 #ifdef FEATURE_IMAGE_BLOCKING
742 /*********************************************************************
744 * Function : is_imageurl
746 * Description : Given a URL, decide whether it is an image or not,
747 * using either the info from a previous +image action
748 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
749 * the browser's accept header.
752 * 1 : csp = Current client state (buffers, headers, etc...)
754 * Returns : True (nonzero) if URL is an image, false (0)
757 *********************************************************************/
758 int is_imageurl(struct client_state *csp)
760 #ifdef FEATURE_IMAGE_DETECT_MSIE
761 if ((csp->accept_types
762 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
763 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
767 else if ((csp->accept_types
768 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
769 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
773 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
775 return ((csp->action->flags & ACTION_IMAGE) != 0);
778 #endif /* def FEATURE_IMAGE_BLOCKING */
781 #ifdef FEATURE_COOKIE_JAR
782 /*********************************************************************
784 * Function : is_untrusted_url
786 * Description : Should we "distrust" this URL (and block it)?
788 * Yes if it matches a line in the trustfile, or if the
789 * referrer matches a line starting with "+" in the
794 * 1 : csp = Current client state (buffers, headers, etc...)
796 * Returns : 0 => trusted, 1 => untrusted
798 *********************************************************************/
799 int is_untrusted_url(struct client_state *csp)
801 struct file_list *fl;
802 struct block_spec *b;
803 struct url_spec url[1], **tl, *t;
804 struct http_request rhttp[1];
808 * If we don't have a trustlist, we trust everybody
810 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
817 * Do we trust the request URL itself?
819 *url = dsplit(csp->http->host);
821 /* if splitting the domain fails, punt */
822 if (url->dbuf == NULL) return(0);
824 memset(rhttp, '\0', sizeof(*rhttp));
826 for (b = b->next; b ; b = b->next)
828 if ((b->url->port == 0) || (b->url->port == csp->http->port))
830 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
832 if ((b->url->path == NULL) ||
834 (regexec(b->url->preg, csp->http->path, 0, NULL, 0) == 0)
836 (strncmp(b->url->path, csp->http->path, b->url->pathlen) == 0)
843 if (b->reject == 0) return(0);
854 if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
856 /* no referrer was supplied */
860 /* forge a URL from the referrer so we can use
861 * convert_url() to parse it into its components.
865 p = strsav(p, "GET ");
866 p = strsav(p, csp->referrer + 9); /* skip over "Referer: " */
867 p = strsav(p, " HTTP/1.0");
869 parse_http_request(p, rhttp, csp);
872 if (rhttp->cmd == NULL)
879 * If not, do we maybe trust its referrer?
881 *url = dsplit(rhttp->host);
883 /* if splitting the domain fails, punt */
884 if (url->dbuf == NULL) return(1);
886 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
888 if ((t->port == 0) || (t->port == rhttp->port))
890 if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
892 if ((t->path == NULL) ||
894 (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
896 (strncmp(t->path, rhttp->path, t->pathlen) == 0)
900 /* if the URL's referrer is from a trusted referrer, then
901 * add the target spec to the trustfile as an unblocked
902 * domain and return NULL (which means it's OK).
910 if ((fp = fopen(csp->config->trustfile, "a")))
915 h = strsav(h, csp->http->hostport);
921 /* since this path points into a user's home space
922 * be sure to include this spec in the trustfile.
924 if ((p = strchr(p, '/')))
927 h = strsav(h, csp->http->path); /* FIXME: p?! */
932 fprintf(fp, "%s\n", h);
943 #endif /* def FEATURE_COOKIE_JAR */
946 /*********************************************************************
948 * Function : pcrs_filter_response
950 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
951 * to the text buffer that's been accumulated in
952 * csp->iob->buf and set csp->content_length to the modified
956 * 1 : csp = Current client state (buffers, headers, etc...)
958 * Returns : a pointer to the (newly allocated) modified buffer.
959 * or NULL in case something went wrong
961 *********************************************************************/
962 char *pcrs_filter_response(struct client_state *csp)
965 int size = csp->iob->eod - csp->iob->cur;
967 char *old = csp->iob->cur, *new = NULL;
970 struct file_list *fl;
971 struct re_filterfile_spec *b;
973 /* Sanity first ;-) */
979 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
981 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
985 if ( NULL == b->joblist )
987 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
991 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
992 csp->http->hostport, csp->http->path, size);
994 /* Apply all jobs from the joblist */
995 for (job = b->joblist; NULL != job; job = job->next)
997 hits += pcrs_execute(job, old, size, &new, &size);
998 if (old != csp->iob->cur) free(old);
1002 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1004 csp->content_length = size;
1006 /* fwiw, reset the iob */
1013 /*********************************************************************
1015 * Function : gif_deanimate_response
1017 * Description : Deanimate the GIF image that has been accumulated in
1018 * csp->iob->buf and set csp->content_length to the modified
1022 * 1 : csp = Current client state (buffers, headers, etc...)
1024 * Returns : a pointer to the (newly allocated) modified buffer.
1025 * or NULL in case something went wrong.
1027 *********************************************************************/
1028 char *gif_deanimate_response(struct client_state *csp)
1030 struct binbuffer *in, *out;
1032 int size = csp->iob->eod - csp->iob->cur;
1034 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1035 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1037 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1041 in->buffer = csp->iob->cur;
1044 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1046 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1053 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1054 csp->content_length = out->offset;
1064 /*********************************************************************
1066 * Function : url_actions
1068 * Description : Gets the actions for this URL.
1071 * 1 : http = http_request request for blocked URLs
1072 * 2 : csp = Current client state (buffers, headers, etc...)
1076 *********************************************************************/
1077 void url_actions(struct http_request *http,
1078 struct client_state *csp)
1080 struct file_list *fl;
1081 struct url_actions *b;
1083 init_current_action(csp->action);
1085 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1090 apply_url_actions(csp->action, http, b);
1095 /*********************************************************************
1097 * Function : apply_url_actions
1099 * Description : Applies a list of URL actions.
1102 * 1 : action = Destination.
1103 * 2 : http = Current URL
1104 * 3 : b = list of URL actions to apply
1108 *********************************************************************/
1109 void apply_url_actions(struct current_action_spec *action,
1110 struct http_request *http,
1111 struct url_actions *b)
1113 struct url_spec url[1];
1117 /* Should never happen */
1121 *url = dsplit(http->host);
1123 /* if splitting the domain fails, punt */
1124 if (url->dbuf == NULL)
1129 for (b = b->next; NULL != b; b = b->next)
1131 if ((b->url->port == 0) || (b->url->port == http->port))
1133 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1135 if ((b->url->path == NULL) ||
1137 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
1139 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
1143 merge_current_action(action, b->action);
1154 /*********************************************************************
1156 * Function : forward_url
1158 * Description : Should we forward this to another proxy?
1161 * 1 : http = http_request request for current URL
1162 * 2 : csp = Current client state (buffers, headers, etc...)
1164 * Returns : Pointer to forwarding information.
1166 *********************************************************************/
1167 const struct forward_spec * forward_url(struct http_request *http,
1168 struct client_state *csp)
1170 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1171 struct forward_spec *fwd = csp->config->forward;
1172 struct url_spec url[1];
1176 return(fwd_default);
1179 *url = dsplit(http->host);
1181 /* if splitting the domain fails, punt */
1182 if (url->dbuf == NULL)
1184 return(fwd_default);
1189 if ((fwd->url->port == 0) || (fwd->url->port == http->port))
1191 if ((fwd->url->domain[0] == '\0') || (domaincmp(fwd->url, url) == 0))
1193 if ((fwd->url->path == NULL) ||
1195 (regexec(fwd->url->preg, http->path, 0, NULL, 0) == 0)
1197 (strncmp(fwd->url->path, http->path, fwd->url->pathlen) == 0)
1212 return(fwd_default);
1217 /*********************************************************************
1221 * Description : Takes a domain and returns a pointer to a url_spec
1222 * structure populated with dbuf, dcnt and dvec. The
1223 * other fields in the structure that is returned are zero.
1226 * 1 : domain = a URL address
1228 * Returns : url_spec structure populated with dbuf, dcnt and dvec.
1230 *********************************************************************/
1231 struct url_spec dsplit(char *domain)
1233 struct url_spec ret[1];
1234 char *v[BUFFER_SIZE];
1238 memset(ret, '\0', sizeof(*ret));
1240 if (domain[strlen(domain) - 1] == '.')
1242 ret->unanchored |= ANCHOR_RIGHT;
1245 if (domain[0] == '.')
1247 ret->unanchored |= ANCHOR_LEFT;
1250 ret->dbuf = strdup(domain);
1252 /* map to lower case */
1253 for (p = ret->dbuf; *p ; p++) *p = tolower(*p);
1255 /* split the domain name into components */
1256 ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
1260 memset(ret, '\0', sizeof(ret));
1264 /* save a copy of the pointers in dvec */
1265 size = ret->dcnt * sizeof(*ret->dvec);
1267 if ((ret->dvec = (char **)malloc(size)))
1269 memcpy(ret->dvec, v, size);
1277 /*********************************************************************
1279 * Function : simple_domaincmp
1281 * Description : Domain-wise Compare fqdn's. The comparison is
1282 * both left- and right-anchored. The individual
1283 * domain names are compared with simplematch().
1284 * This is only used by domaincmp.
1287 * 1 : pv = array of patterns to compare
1288 * 2 : fv = array of domain components to compare
1289 * 3 : len = length of the arrays (both arrays are the
1290 * same length - if they weren't, it couldn't
1291 * possibly be a match).
1293 * Returns : 0 => domains are equivalent, else no match.
1295 *********************************************************************/
1296 static int simple_domaincmp(char **pv, char **fv, int len)
1300 for (n = 0; n < len; n++)
1302 if (simplematch(pv[n], fv[n]))
1313 /*********************************************************************
1315 * Function : domaincmp
1317 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1318 * pattern->unachored, the comparison is un-, left-,
1319 * right-anchored, or both.
1320 * The individual domain names are compared with
1324 * 1 : pattern = a domain that may contain a '*' as a wildcard.
1325 * 2 : fqdn = domain name against which the patterns are compared.
1327 * Returns : 0 => domains are equivalent, else no match.
1329 *********************************************************************/
1330 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1332 char **pv, **fv; /* vectors */
1334 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1336 plen = pattern->dcnt;
1341 /* fqdn is too short to match this pattern */
1348 if (unanchored == ANCHOR_LEFT)
1353 * Convert this into a fully anchored pattern with
1354 * the fqdn and pattern the same length
1356 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1357 return simple_domaincmp(pv, fv, plen);
1359 else if (unanchored == 0)
1361 /* Fully anchored, check length */
1366 return simple_domaincmp(pv, fv, plen);
1368 else if (unanchored == ANCHOR_RIGHT)
1370 /* Left anchored, ignore all extra in fqdn */
1371 return simple_domaincmp(pv, fv, plen);
1377 int maxn = flen - plen;
1378 for (n = 0; n <= maxn; n++)
1380 if (!simple_domaincmp(pv, fv, plen))
1385 * Doesn't match from start of fqdn
1386 * Try skipping first part of fqdn