1 const char filters_rcs[] = "$Id: filters.c,v 1.29 2001/09/13 23:32:40 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.29 2001/09/13 23:32:40 jongfoster
42 * Moving image data to cgi.c rather than cgi.h
43 * Fixing a GPF under Win32 (and any other OS that protects global
44 * constants from being written to).
46 * Revision 1.28 2001/09/10 10:18:51 oes
47 * Silenced compiler warnings
49 * Revision 1.27 2001/08/05 16:06:20 jongfoster
50 * Modifiying "struct map" so that there are now separate header and
51 * "map_entry" structures. This means that functions which modify a
52 * map no longer need to return a pointer to the modified map.
53 * Also, it no longer reverses the order of the entries (which may be
54 * important with some advanced template substitutions).
56 * Revision 1.26 2001/07/30 22:08:36 jongfoster
57 * Tidying up #defines:
58 * - All feature #defines are now of the form FEATURE_xxx
59 * - Permanently turned off WIN_GUI_EDIT
60 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
62 * Revision 1.25 2001/07/26 10:09:46 oes
63 * Made browser detection a little less naive
65 * Revision 1.24 2001/07/25 17:22:51 oes
66 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
68 * Revision 1.23 2001/07/23 13:40:12 oes
69 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
71 * Revision 1.22 2001/07/18 12:29:34 oes
72 * - Made gif_deanimate_response respect
73 * csp->action->string[ACTION_STRING_DEANIMATE]
76 * Revision 1.21 2001/07/13 13:59:53 oes
77 * - Introduced gif_deanimate_response which shares the
78 * generic content modification interface of pcrs_filter_response
79 * and acts as a wrapper to deanimate.c:gif_deanimate()
80 * - Renamed re_process_buffer to pcrs_filter_response
81 * - pcrs_filter_response now returns NULL on failiure
82 * - Removed all #ifdef PCRS
84 * Revision 1.20 2001/07/01 17:01:04 oes
85 * Added comments and missing return statement in is_untrusted_url()
87 * Revision 1.19 2001/06/29 21:45:41 oes
88 * Indentation, CRLF->LF, Tab-> Space
90 * Revision 1.18 2001/06/29 13:27:38 oes
91 * - Cleaned up, renamed and reorderd functions
92 * and improved comments
95 * - Ported to CGI platform. Now delivers
96 * http_response or NULL
97 * - Unified HTML and GIF generation (moved image detection
98 * and GIF generation here from jcc.c:chat())
99 * - Fixed HTTP status to:
100 * - 403 (Forbidden) for the "blocked" HTML message
101 * - 200 (OK) for GIF answers
102 * - 302 (Redirect) for redirect to GIF
105 * - Ported to CGI platform. Now delivers
106 * http_response or NULL
107 * - Separated detection of untrusted URL into
108 * (bool)is_untrusted_url
109 * - Added enforcement of untrusted requests
111 * - Moved redirect_url() from cgi.c to here
112 * and ported it to the CGI platform
114 * - Removed logentry from cancelled commit
116 * Revision 1.17 2001/06/09 10:55:28 jongfoster
117 * Changing BUFSIZ ==> BUFFER_SIZE
119 * Revision 1.16 2001/06/07 23:10:26 jongfoster
120 * Allowing unanchored domain patterns to back off and retry
121 * if they partially match. Optimized right-anchored patterns.
122 * Moving ACL and forward files into config file.
123 * Replacing struct gateway with struct forward_spec
125 * Revision 1.15 2001/06/03 19:12:00 oes
126 * extracted-CGI relevant stuff
128 * Revision 1.14 2001/06/01 10:30:55 oes
129 * Added optional left-anchoring to domaincmp
131 * Revision 1.13 2001/05/31 21:21:30 jongfoster
132 * Permissionsfile / actions file changes:
133 * - Changed "permission" to "action" throughout
134 * - changes to file format to allow string parameters
135 * - Moved helper functions to actions.c
137 * Revision 1.12 2001/05/31 17:35:20 oes
139 * - Enhanced domain part globbing with infix and prefix asterisk
140 * matching and optional unanchored operation
142 * Revision 1.11 2001/05/29 11:53:23 oes
143 * "See why" link added to "blocked" page
145 * Revision 1.10 2001/05/29 09:50:24 jongfoster
146 * Unified blocklist/imagelist/permissionslist.
147 * File format is still under discussion, but the internal changes
150 * Also modified interceptor behaviour:
151 * - We now intercept all URLs beginning with one of the following
152 * prefixes (and *only* these prefixes):
154 * * http://ijbswa.sf.net/config/
155 * * http://ijbswa.sourceforge.net/config/
156 * - New interceptors "home page" - go to http://i.j.b/ to see it.
157 * - Internal changes so that intercepted and fast redirect pages
158 * are not replaced with an image.
159 * - Interceptors now have the option to send a binary page direct
160 * to the client. (i.e. ijb-send-banner uses this)
161 * - Implemented show-url-info interceptor. (Which is why I needed
162 * the above interceptors changes - a typical URL is
163 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
164 * The previous mechanism would not have intercepted that, and
165 * if it had been intercepted then it then it would have replaced
168 * Revision 1.9 2001/05/27 22:17:04 oes
170 * - re_process_buffer no longer writes the modified buffer
171 * to the client, which was very ugly. It now returns the
172 * buffer, which it is then written by chat.
174 * - content_length now adjusts the Content-Length: header
175 * for modified documents rather than crunch()ing it.
176 * (Length info in csp->content_length, which is 0 for
177 * unmodified documents)
179 * - For this to work, sed() is called twice when filtering.
181 * Revision 1.8 2001/05/26 17:13:28 jongfoster
182 * Filled in a function comment.
184 * Revision 1.7 2001/05/26 15:26:15 jongfoster
185 * ACL feature now provides more security by immediately dropping
186 * connections from untrusted hosts.
188 * Revision 1.6 2001/05/26 00:28:36 jongfoster
189 * Automatic reloading of config file.
190 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
191 * Most of the global variables have been moved to a new
192 * struct configuration_spec, accessed through csp->config->globalname
193 * Most of the globals remaining are used by the Win32 GUI.
195 * Revision 1.5 2001/05/25 22:34:30 jongfoster
198 * Revision 1.4 2001/05/22 18:46:04 oes
200 * - Enabled filtering banners by size rather than URL
201 * by adding patterns that replace all standard banner
202 * sizes with the "Junkbuster" gif to the re_filterfile
204 * - Enabled filtering WebBugs by providing a pattern
205 * which kills all 1x1 images
207 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
208 * which is selected by the (nonstandard and therefore
209 * capital) letter 'U' in the option string.
210 * It causes the quantifiers to be ungreedy by default.
211 * Appending a ? turns back to greedy (!).
213 * - Added a new interceptor ijb-send-banner, which
214 * sends back the "Junkbuster" gif. Without imagelist or
215 * MSIE detection support, or if tinygif = 1, or the
216 * URL isn't recognized as an imageurl, a lame HTML
217 * explanation is sent instead.
219 * - Added new feature, which permits blocking remote
220 * script redirects and firing back a local redirect
222 * The feature is conditionally compiled, i.e. it
223 * can be disabled with --disable-fast-redirects,
224 * plus it must be activated by a "fast-redirects"
225 * line in the config file, has its own log level
226 * and of course wants to be displayed by show-proxy-args
227 * Note: Boy, all the #ifdefs in 1001 locations and
228 * all the fumbling with configure.in and acconfig.h
229 * were *way* more work than the feature itself :-(
231 * - Because a generic redirect template was needed for
232 * this, tinygif = 3 now uses the same.
234 * - Moved GIFs, and other static HTTP response templates
239 * - Removed some >400 CRs again (Jon, you really worked
242 * Revision 1.3 2001/05/20 16:44:47 jongfoster
243 * Removing last hardcoded JunkBusters.com URLs.
245 * Revision 1.2 2001/05/20 01:21:20 jongfoster
246 * Version 2.9.4 checkin.
247 * - Merged popupfile and cookiefile, and added control over PCRS
248 * filtering, in new "permissionsfile".
249 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
250 * file error you now get a message box (in the Win32 GUI) rather
251 * than the program exiting with no explanation.
252 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
254 * - Removed tabs from "config"
255 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
256 * - Bumped up version number.
258 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
259 * Initial import of version 2.9.3 source tree
262 *********************************************************************/
268 #include <sys/types.h>
275 #include <netinet/in.h>
277 #include <winsock2.h>
284 #include "showargs.h"
288 #include "jbsockets.h"
290 #include "jbsockets.h"
291 #include "miscutil.h"
295 #include "deanimate.h"
301 const char filters_h_rcs[] = FILTERS_H_VERSION;
303 /* Fix a problem with Solaris. There should be no effect on other
305 * Solaris's isspace() is a macro which uses it's argument directly
306 * as an array index. Therefore we need to make sure that high-bit
307 * characters generate +ve values, and ideally we also want to make
308 * the argument match the declared parameter type of "int".
310 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
314 /*********************************************************************
316 * Function : block_acl
318 * Description : Block this request?
319 * Decide yes or no based on ACL file.
322 * 1 : dst = The proxy or gateway address this is going to.
323 * Or NULL to check all possible targets.
324 * 2 : csp = Current client state (buffers, headers, etc...)
325 * Also includes the client IP address.
327 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
329 *********************************************************************/
330 int block_acl(struct access_control_addr *dst, struct client_state *csp)
332 struct access_control_list *acl = csp->config->acl;
334 /* if not using an access control list, then permit the connection */
340 /* search the list */
343 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
347 /* Just want to check if they have any access */
348 if (acl->action == ACL_PERMIT)
353 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
354 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
356 if (acl->action == ACL_PERMIT)
374 /*********************************************************************
376 * Function : acl_addr
378 * Description : Called from `load_aclfile' to parse an ACL address.
381 * 1 : aspec = String specifying ACL address.
382 * 2 : aca = struct access_control_addr to fill in.
384 * Returns : 0 => Ok, everything else is an error.
386 *********************************************************************/
387 int acl_addr(char *aspec, struct access_control_addr *aca)
389 int i, masklength, port;
395 if ((p = strchr(aspec, '/')))
399 if (ijb_isdigit(*p) == 0)
403 masklength = atoi(p);
406 if ((masklength < 0) || (masklength > 32))
411 if ((p = strchr(aspec, ':')))
415 if (ijb_isdigit(*p) == 0)
424 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
428 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
432 /* build the netmask */
434 for (i=1; i <= masklength ; i++)
436 aca->mask |= (1 << (32 - i));
439 /* now mask off the host portion of the ip address
440 * (i.e. save on the network portion of the address).
442 aca->addr = aca->addr & aca->mask;
447 #endif /* def FEATURE_ACL */
450 /*********************************************************************
452 * Function : block_url
454 * Description : Called from `chat'. Check to see if we need to block this.
457 * 1 : csp = Current client state (buffers, headers, etc...)
459 * Returns : NULL => unblocked, else HTTP block response
461 *********************************************************************/
462 struct http_response *block_url(struct client_state *csp)
464 #ifdef FEATURE_IMAGE_BLOCKING
466 #endif /* def FEATURE_IMAGE_BLOCKING */
467 struct http_response *rsp;
470 * If it's not blocked, don't block it ;-)
472 if ((csp->action->flags & ACTION_BLOCK) == 0)
478 * Else, prepare a response
480 if (NULL == (rsp = alloc_http_response()))
486 * If it's an image-url, send back an image or redirect
487 * as specified by the relevant +image action
489 #ifdef FEATURE_IMAGE_BLOCKING
490 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
493 /* determine HOW images should be blocked */
494 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
496 /* and handle accordingly: */
497 if ((p == NULL) || (0 == strcmpic(p, "logo")))
499 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
500 rsp->content_length = image_junkbuster_gif_length;
501 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
504 else if (0 == strcmpic(p, "blank"))
506 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
507 rsp->content_length = image_blank_gif_length;
508 enlist_unique_header(rsp->headers, "Content-Type", "image/gif");
513 rsp->status = strdup("302 Local Redirect from Junkbuster");
514 enlist_unique_header(rsp->headers, "Location", p);
518 #endif /* def FEATURE_IMAGE_BLOCKING */
521 * Else, generate an HTML "blocked" message:
524 struct map * exports = default_exports(csp, NULL);
525 #ifdef FEATURE_FORCE_LOAD
526 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
527 #else /* ifndef FEATURE_FORCE_LOAD */
528 map_block_killer(exports, "force-support");
529 #endif /* ndef FEATURE_FORCE_LOAD */
531 map(exports, "hostport", 1, csp->http->hostport, 1);
532 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
533 map(exports, "path", 1, csp->http->path, 1);
534 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
536 rsp->body = fill_template(csp, "blocked", exports);
540 * Workaround for stupid Netscape bug which prevents
541 * pages from being displayed if loading a referenced
542 * JavaScript or style sheet fails. So make it appear
543 * as if it succeeded.
545 if (csp->http->user_agent
546 && !strncmpic(csp->http->user_agent, "mozilla", 7)
547 && !strstr(csp->http->user_agent, "compatible")
548 && !strstr(csp->http->user_agent, "Opera"))
550 rsp->status = strdup("200 Request for blocked URL");
554 rsp->status = strdup("404 Request for blocked URL");
559 return(finish_http_response(rsp));
565 /*********************************************************************
567 * Function : trust_url FIXME: I should be called distrust_url
569 * Description : Calls is_untrusted_url to determine if the URL is trusted
570 * and if not, returns a HTTP 304 response with a reject message.
573 * 1 : csp = Current client state (buffers, headers, etc...)
575 * Returns : NULL => trusted, else http_response.
577 *********************************************************************/
578 struct http_response *trust_url(struct client_state *csp)
580 struct http_response *rsp;
581 struct map * exports;
582 char buf[BUFFER_SIZE], *p = NULL;
583 struct url_spec **tl, *t;
586 * Don't bother to work on trusted URLs
588 if (!is_untrusted_url(csp))
594 * Else, prepare a response:
596 if (NULL == (rsp = alloc_http_response()))
601 exports = default_exports(csp, NULL);
604 * Export the host, port, and referrer information
606 map(exports, "hostport", 1, csp->http->hostport, 1);
607 map(exports, "path", 1, csp->http->path, 1);
608 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
609 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
611 if (csp->referrer && strlen(csp->referrer) > 9)
613 map(exports, "referrer", 1, csp->referrer + 9, 1);
614 map(exports, "referrer-html", 1, html_encode(csp->referrer + 9), 0);
618 map(exports, "referrer", 1, "unknown", 1);
619 map(exports, "referrer-html", 1, "unknown", 1);
623 * Export the trust list
625 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
627 sprintf(buf, "<li>%s</li>\n", t->spec);
630 map(exports, "trusted-referrers", 1, p, 0);
634 * Export the trust info, if available
636 if (csp->config->trust_info->next)
640 for (l = csp->config->trust_info->next; l ; l = l->next)
642 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
645 map(exports, "trust-info", 1, p, 0);
649 map_block_killer(exports, "have-trust-info");
653 * Export the force prefix or the force conditional block killer
655 #ifdef FEATURE_FORCE_LOAD
656 map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
657 #else /* ifndef FEATURE_FORCE_LOAD */
658 map_block_killer(exports, "force-support");
659 #endif /* ndef FEATURE_FORCE_LOAD */
664 rsp->body = fill_template(csp, "untrusted", exports);
667 return(finish_http_response(rsp));
670 #endif /* def FEATURE_TRUST */
673 #ifdef FEATURE_FAST_REDIRECTS
674 /*********************************************************************
676 * Function : redirect_url
678 * Description : Checks for redirection URLs and returns a HTTP redirect
679 * to the destination URL, if necessary
682 * 1 : csp = Current client state (buffers, headers, etc...)
684 * Returns : NULL if URL was clean, HTTP redirect otherwise.
686 *********************************************************************/
687 struct http_response *redirect_url(struct client_state *csp)
690 struct http_response *rsp;
692 p = q = csp->http->path;
693 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
696 * find the last URL encoded in the request
698 while ((p = strstr(p, "http://")))
704 * if there was any, generate and return a HTTP redirect
706 if (q != csp->http->path)
708 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
710 if (NULL == (rsp = alloc_http_response()))
715 rsp->status = strdup("302 Local Redirect from Junkbuster");
716 enlist_unique_header(rsp->headers, "Location", q);
718 return(finish_http_response(rsp));
726 #endif /* def FEATURE_FAST_REDIRECTS */
729 #ifdef FEATURE_IMAGE_BLOCKING
730 /*********************************************************************
732 * Function : is_imageurl
734 * Description : Given a URL, decide whether it is an image or not,
735 * using either the info from a previous +image action
736 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
737 * the browser's accept header.
740 * 1 : csp = Current client state (buffers, headers, etc...)
742 * Returns : True (nonzero) if URL is an image, false (0)
745 *********************************************************************/
746 int is_imageurl(struct client_state *csp)
748 #ifdef FEATURE_IMAGE_DETECT_MSIE
749 if ((csp->accept_types
750 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
751 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
755 else if ((csp->accept_types
756 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
757 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
761 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
763 return ((csp->action->flags & ACTION_IMAGE) != 0);
766 #endif /* def FEATURE_IMAGE_BLOCKING */
769 #ifdef FEATURE_COOKIE_JAR
770 /*********************************************************************
772 * Function : is_untrusted_url
774 * Description : Should we "distrust" this URL (and block it)?
776 * Yes if it matches a line in the trustfile, or if the
777 * referrer matches a line starting with "+" in the
782 * 1 : csp = Current client state (buffers, headers, etc...)
784 * Returns : 0 => trusted, 1 => untrusted
786 *********************************************************************/
787 int is_untrusted_url(struct client_state *csp)
789 struct file_list *fl;
790 struct block_spec *b;
791 struct url_spec url[1], **tl, *t;
792 struct http_request rhttp[1];
796 * If we don't have a trustlist, we trust everybody
798 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
805 * Do we trust the request URL itself?
807 *url = dsplit(csp->http->host);
809 /* if splitting the domain fails, punt */
810 if (url->dbuf == NULL) return(0);
812 memset(rhttp, '\0', sizeof(*rhttp));
814 for (b = b->next; b ; b = b->next)
816 if ((b->url->port == 0) || (b->url->port == csp->http->port))
818 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
820 if ((b->url->path == NULL) ||
822 (regexec(b->url->preg, csp->http->path, 0, NULL, 0) == 0)
824 (strncmp(b->url->path, csp->http->path, b->url->pathlen) == 0)
831 if (b->reject == 0) return(0);
842 if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
844 /* no referrer was supplied */
848 /* forge a URL from the referrer so we can use
849 * convert_url() to parse it into its components.
853 p = strsav(p, "GET ");
854 p = strsav(p, csp->referrer + 9); /* skip over "Referer: " */
855 p = strsav(p, " HTTP/1.0");
857 parse_http_request(p, rhttp, csp);
860 if (rhttp->cmd == NULL)
867 * If not, do we maybe trust its referrer?
869 *url = dsplit(rhttp->host);
871 /* if splitting the domain fails, punt */
872 if (url->dbuf == NULL) return(1);
874 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
876 if ((t->port == 0) || (t->port == rhttp->port))
878 if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
880 if ((t->path == NULL) ||
882 (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
884 (strncmp(t->path, rhttp->path, t->pathlen) == 0)
888 /* if the URL's referrer is from a trusted referrer, then
889 * add the target spec to the trustfile as an unblocked
890 * domain and return NULL (which means it's OK).
898 if ((fp = fopen(csp->config->trustfile, "a")))
903 h = strsav(h, csp->http->hostport);
909 /* since this path points into a user's home space
910 * be sure to include this spec in the trustfile.
912 if ((p = strchr(p, '/')))
915 h = strsav(h, csp->http->path); /* FIXME: p?! */
920 fprintf(fp, "%s\n", h);
931 #endif /* def FEATURE_COOKIE_JAR */
934 /*********************************************************************
936 * Function : pcrs_filter_response
938 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
939 * to the text buffer that's been accumulated in
940 * csp->iob->buf and set csp->content_length to the modified
944 * 1 : csp = Current client state (buffers, headers, etc...)
946 * Returns : a pointer to the (newly allocated) modified buffer.
947 * or NULL in case something went wrong
949 *********************************************************************/
950 char *pcrs_filter_response(struct client_state *csp)
953 int size = csp->iob->eod - csp->iob->cur;
955 char *old = csp->iob->cur, *new = NULL;
958 struct file_list *fl;
959 struct re_filterfile_spec *b;
961 /* Sanity first ;-) */
967 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
969 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
973 if ( NULL == b->joblist )
975 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
979 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
980 csp->http->hostport, csp->http->path, size);
982 /* Apply all jobs from the joblist */
983 for (job = b->joblist; NULL != job; job = job->next)
985 hits += pcrs_execute(job, old, size, &new, &size);
986 if (old != csp->iob->cur) free(old);
990 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
992 csp->content_length = size;
994 /* fwiw, reset the iob */
1001 /*********************************************************************
1003 * Function : gif_deanimate_response
1005 * Description : Deanimate the GIF image that has been accumulated in
1006 * csp->iob->buf and set csp->content_length to the modified
1010 * 1 : csp = Current client state (buffers, headers, etc...)
1012 * Returns : a pointer to the (newly allocated) modified buffer.
1013 * or NULL in case something went wrong.
1015 *********************************************************************/
1016 char *gif_deanimate_response(struct client_state *csp)
1018 struct binbuffer *in, *out;
1020 int size = csp->iob->eod - csp->iob->cur;
1022 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1023 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1025 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1029 in->buffer = csp->iob->cur;
1032 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1034 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1041 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1042 csp->content_length = out->offset;
1052 /*********************************************************************
1054 * Function : url_actions
1056 * Description : Gets the actions for this URL.
1059 * 1 : http = http_request request for blocked URLs
1060 * 2 : csp = Current client state (buffers, headers, etc...)
1064 *********************************************************************/
1065 void url_actions(struct http_request *http,
1066 struct client_state *csp)
1068 struct file_list *fl;
1069 struct url_actions *b;
1071 init_current_action(csp->action);
1073 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1078 apply_url_actions(csp->action, http, b);
1083 /*********************************************************************
1085 * Function : apply_url_actions
1087 * Description : Applies a list of URL actions.
1090 * 1 : action = Destination.
1091 * 2 : http = Current URL
1092 * 3 : b = list of URL actions to apply
1096 *********************************************************************/
1097 void apply_url_actions(struct current_action_spec *action,
1098 struct http_request *http,
1099 struct url_actions *b)
1101 struct url_spec url[1];
1105 /* Should never happen */
1109 *url = dsplit(http->host);
1111 /* if splitting the domain fails, punt */
1112 if (url->dbuf == NULL)
1117 for (b = b->next; NULL != b; b = b->next)
1119 if ((b->url->port == 0) || (b->url->port == http->port))
1121 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
1123 if ((b->url->path == NULL) ||
1125 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
1127 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
1131 merge_current_action(action, b->action);
1142 /*********************************************************************
1144 * Function : forward_url
1146 * Description : Should we forward this to another proxy?
1149 * 1 : http = http_request request for current URL
1150 * 2 : csp = Current client state (buffers, headers, etc...)
1152 * Returns : Pointer to forwarding information.
1154 *********************************************************************/
1155 const struct forward_spec * forward_url(struct http_request *http,
1156 struct client_state *csp)
1158 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1159 struct forward_spec *fwd = csp->config->forward;
1160 struct url_spec url[1];
1164 return(fwd_default);
1167 *url = dsplit(http->host);
1169 /* if splitting the domain fails, punt */
1170 if (url->dbuf == NULL)
1172 return(fwd_default);
1177 if ((fwd->url->port == 0) || (fwd->url->port == http->port))
1179 if ((fwd->url->domain[0] == '\0') || (domaincmp(fwd->url, url) == 0))
1181 if ((fwd->url->path == NULL) ||
1183 (regexec(fwd->url->preg, http->path, 0, NULL, 0) == 0)
1185 (strncmp(fwd->url->path, http->path, fwd->url->pathlen) == 0)
1200 return(fwd_default);
1205 /*********************************************************************
1209 * Description : Takes a domain and returns a pointer to a url_spec
1210 * structure populated with dbuf, dcnt and dvec. The
1211 * other fields in the structure that is returned are zero.
1214 * 1 : domain = a URL address
1216 * Returns : url_spec structure populated with dbuf, dcnt and dvec.
1218 *********************************************************************/
1219 struct url_spec dsplit(char *domain)
1221 struct url_spec ret[1];
1222 char *v[BUFFER_SIZE];
1226 memset(ret, '\0', sizeof(*ret));
1228 if (domain[strlen(domain) - 1] == '.')
1230 ret->unanchored |= ANCHOR_RIGHT;
1233 if (domain[0] == '.')
1235 ret->unanchored |= ANCHOR_LEFT;
1238 ret->dbuf = strdup(domain);
1240 /* map to lower case */
1241 for (p = ret->dbuf; *p ; p++) *p = tolower(*p);
1243 /* split the domain name into components */
1244 ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
1248 memset(ret, '\0', sizeof(ret));
1252 /* save a copy of the pointers in dvec */
1253 size = ret->dcnt * sizeof(*ret->dvec);
1255 if ((ret->dvec = (char **)malloc(size)))
1257 memcpy(ret->dvec, v, size);
1265 /*********************************************************************
1267 * Function : simple_domaincmp
1269 * Description : Domain-wise Compare fqdn's. The comparison is
1270 * both left- and right-anchored. The individual
1271 * domain names are compared with simplematch().
1272 * This is only used by domaincmp.
1275 * 1 : pv = array of patterns to compare
1276 * 2 : fv = array of domain components to compare
1277 * 3 : len = length of the arrays (both arrays are the
1278 * same length - if they weren't, it couldn't
1279 * possibly be a match).
1281 * Returns : 0 => domains are equivalent, else no match.
1283 *********************************************************************/
1284 static int simple_domaincmp(char **pv, char **fv, int len)
1288 for (n = 0; n < len; n++)
1290 if (simplematch(pv[n], fv[n]))
1301 /*********************************************************************
1303 * Function : domaincmp
1305 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1306 * pattern->unachored, the comparison is un-, left-,
1307 * right-anchored, or both.
1308 * The individual domain names are compared with
1312 * 1 : pattern = a domain that may contain a '*' as a wildcard.
1313 * 2 : fqdn = domain name against which the patterns are compared.
1315 * Returns : 0 => domains are equivalent, else no match.
1317 *********************************************************************/
1318 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1320 char **pv, **fv; /* vectors */
1322 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1324 plen = pattern->dcnt;
1329 /* fqdn is too short to match this pattern */
1336 if (unanchored == ANCHOR_LEFT)
1341 * Convert this into a fully anchored pattern with
1342 * the fqdn and pattern the same length
1344 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1345 return simple_domaincmp(pv, fv, plen);
1347 else if (unanchored == 0)
1349 /* Fully anchored, check length */
1354 return simple_domaincmp(pv, fv, plen);
1356 else if (unanchored == ANCHOR_RIGHT)
1358 /* Left anchored, ignore all extra in fqdn */
1359 return simple_domaincmp(pv, fv, plen);
1365 int maxn = flen - plen;
1366 for (n = 0; n <= maxn; n++)
1368 if (!simple_domaincmp(pv, fv, plen))
1373 * Doesn't match from start of fqdn
1374 * Try skipping first part of fqdn