1 const char filters_rcs[] = "$Id: filters.c,v 1.15 2001/06/03 11:03:48 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `acl_addr', `add_stats', `block_acl', `block_imageurl',
9 * `block_url', `url_actions', `domaincmp', `dsplit',
10 * `filter_popups', `forward_url', 'redirect_url',
11 * `ij_untrusted_url', `intercept_url', `re_process_buffer',
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.15 2001/06/03 11:03:48 oes
48 * adapted to new enlist_unique arg format
52 * introduced confdir option
54 * filters.c filtrers.h
56 * extracted-CGI relevant stuff
64 * support for new cgi mechansim
68 * functions for new list type: "map"
69 * extended enlist_unique
76 * deleted const struct interceptors
84 * added struct http_response
85 * changes struct interceptors to struct cgi_dispatcher
86 * moved HTML stuff to cgi.h
95 * Revision 1.14 2001/06/01 10:30:55 oes
96 * Added optional left-anchoring to domaincmp
98 * Revision 1.13 2001/05/31 21:21:30 jongfoster
99 * Permissionsfile / actions file changes:
100 * - Changed "permission" to "action" throughout
101 * - changes to file format to allow string parameters
102 * - Moved helper functions to actions.c
104 * Revision 1.12 2001/05/31 17:35:20 oes
106 * - Enhanced domain part globbing with infix and prefix asterisk
107 * matching and optional unanchored operation
109 * Revision 1.11 2001/05/29 11:53:23 oes
110 * "See why" link added to "blocked" page
112 * Revision 1.10 2001/05/29 09:50:24 jongfoster
113 * Unified blocklist/imagelist/permissionslist.
114 * File format is still under discussion, but the internal changes
117 * Also modified interceptor behaviour:
118 * - We now intercept all URLs beginning with one of the following
119 * prefixes (and *only* these prefixes):
121 * * http://ijbswa.sf.net/config/
122 * * http://ijbswa.sourceforge.net/config/
123 * - New interceptors "home page" - go to http://i.j.b/ to see it.
124 * - Internal changes so that intercepted and fast redirect pages
125 * are not replaced with an image.
126 * - Interceptors now have the option to send a binary page direct
127 * to the client. (i.e. ijb-send-banner uses this)
128 * - Implemented show-url-info interceptor. (Which is why I needed
129 * the above interceptors changes - a typical URL is
130 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
131 * The previous mechanism would not have intercepted that, and
132 * if it had been intercepted then it then it would have replaced
135 * Revision 1.9 2001/05/27 22:17:04 oes
137 * - re_process_buffer no longer writes the modified buffer
138 * to the client, which was very ugly. It now returns the
139 * buffer, which it is then written by chat.
141 * - content_length now adjusts the Content-Length: header
142 * for modified documents rather than crunch()ing it.
143 * (Length info in csp->content_length, which is 0 for
144 * unmodified documents)
146 * - For this to work, sed() is called twice when filtering.
148 * Revision 1.8 2001/05/26 17:13:28 jongfoster
149 * Filled in a function comment.
151 * Revision 1.7 2001/05/26 15:26:15 jongfoster
152 * ACL feature now provides more security by immediately dropping
153 * connections from untrusted hosts.
155 * Revision 1.6 2001/05/26 00:28:36 jongfoster
156 * Automatic reloading of config file.
157 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
158 * Most of the global variables have been moved to a new
159 * struct configuration_spec, accessed through csp->config->globalname
160 * Most of the globals remaining are used by the Win32 GUI.
162 * Revision 1.5 2001/05/25 22:34:30 jongfoster
165 * Revision 1.4 2001/05/22 18:46:04 oes
167 * - Enabled filtering banners by size rather than URL
168 * by adding patterns that replace all standard banner
169 * sizes with the "Junkbuster" gif to the re_filterfile
171 * - Enabled filtering WebBugs by providing a pattern
172 * which kills all 1x1 images
174 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
175 * which is selected by the (nonstandard and therefore
176 * capital) letter 'U' in the option string.
177 * It causes the quantifiers to be ungreedy by default.
178 * Appending a ? turns back to greedy (!).
180 * - Added a new interceptor ijb-send-banner, which
181 * sends back the "Junkbuster" gif. Without imagelist or
182 * MSIE detection support, or if tinygif = 1, or the
183 * URL isn't recognized as an imageurl, a lame HTML
184 * explanation is sent instead.
186 * - Added new feature, which permits blocking remote
187 * script redirects and firing back a local redirect
189 * The feature is conditionally compiled, i.e. it
190 * can be disabled with --disable-fast-redirects,
191 * plus it must be activated by a "fast-redirects"
192 * line in the config file, has its own log level
193 * and of course wants to be displayed by show-proxy-args
194 * Note: Boy, all the #ifdefs in 1001 locations and
195 * all the fumbling with configure.in and acconfig.h
196 * were *way* more work than the feature itself :-(
198 * - Because a generic redirect template was needed for
199 * this, tinygif = 3 now uses the same.
201 * - Moved GIFs, and other static HTTP response templates
206 * - Removed some >400 CRs again (Jon, you really worked
209 * Revision 1.3 2001/05/20 16:44:47 jongfoster
210 * Removing last hardcoded JunkBusters.com URLs.
212 * Revision 1.2 2001/05/20 01:21:20 jongfoster
213 * Version 2.9.4 checkin.
214 * - Merged popupfile and cookiefile, and added control over PCRS
215 * filtering, in new "permissionsfile".
216 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
217 * file error you now get a message box (in the Win32 GUI) rather
218 * than the program exiting with no explanation.
219 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
221 * - Removed tabs from "config"
222 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
223 * - Bumped up version number.
225 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
226 * Initial import of version 2.9.3 source tree
229 *********************************************************************/
235 #include <sys/types.h>
242 #include <netinet/in.h>
244 #include <winsock2.h>
251 #include "showargs.h"
255 #include "jbsockets.h"
257 #include "jbsockets.h"
258 #include "miscutil.h"
266 const char filters_h_rcs[] = FILTERS_H_VERSION;
268 /* Fix a problem with Solaris. There should be no effect on other
270 * Solaris's isspace() is a macro which uses it's argument directly
271 * as an array index. Therefore we need to make sure that high-bit
272 * characters generate +ve values, and ideally we also want to make
273 * the argument match the declared parameter type of "int".
275 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
279 /*********************************************************************
281 * Function : block_acl
283 * Description : Block this request?
284 * Decide yes or no based on ACL file.
287 * 1 : dst = The proxy or gateway address this is going to.
288 * Or NULL to check all possible targets.
289 * 2 : csp = Current client state (buffers, headers, etc...)
290 * Also includes the client IP address.
292 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
294 *********************************************************************/
295 int block_acl(struct access_control_addr *dst,
296 struct client_state *csp)
298 struct file_list *fl;
299 struct access_control_list *a, *acl;
301 /* if not using an access control list, then permit the connection */
302 if (((fl = csp->alist) == NULL) ||
303 ((acl = (struct access_control_list *) fl->f) == NULL))
308 /* search the list */
309 for (a = acl->next ; a ; a = a->next)
311 if ((csp->ip_addr_long & a->src->mask) == a->src->addr)
315 /* Just want to check if they have any access */
316 if (a->action == ACL_PERMIT)
321 else if ( ((dst->addr & a->dst->mask) == a->dst->addr)
322 && ((dst->port == a->dst->port) || (a->dst->port == 0)))
324 if (a->action == ACL_PERMIT)
341 /*********************************************************************
343 * Function : acl_addr
345 * Description : Called from `load_aclfile' to parse an ACL address.
348 * 1 : aspec = String specifying ACL address.
349 * 2 : aca = struct access_control_addr to fill in.
351 * Returns : 0 => Ok, everything else is an error.
353 *********************************************************************/
354 int acl_addr(char *aspec, struct access_control_addr *aca)
356 int i, masklength, port;
362 if ((p = strchr(aspec, '/')))
366 if (ijb_isdigit(*p) == 0)
370 masklength = atoi(p);
373 if ((masklength < 0) || (masklength > 32))
378 if ((p = strchr(aspec, ':')))
382 if (ijb_isdigit(*p) == 0)
391 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
395 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
399 /* build the netmask */
401 for (i=1; i <= masklength ; i++)
403 aca->mask |= (1 << (32 - i));
406 /* now mask off the host portion of the ip address
407 * (i.e. save on the network portion of the address).
409 aca->addr = aca->addr & aca->mask;
414 #endif /* def ACL_FILES */
417 /*********************************************************************
419 * Function : block_url
421 * Description : Called from `chat'. Check to see if we need to block this.
424 * 1 : http = http_request request to "check" for blocked
425 * 2 : csp = Current client state (buffers, headers, etc...)
427 * Returns : NULL => unblocked, else string to HTML block description.
429 *********************************************************************/
430 char *block_url(struct http_request *http, struct client_state *csp)
436 if ((csp->action->flags & ACTION_BLOCK) == 0)
444 #endif /* def FORCE_LOAD */
447 n += factor * strlen(http->hostport);
448 n += factor * strlen(http->path);
450 p = (char *)malloc(n);
453 sprintf(p, CBLOCK, http->hostport, http->path, http->hostport, http->path,
454 http->hostport, http->path);
456 sprintf(p, CBLOCK, http->hostport, http->path, http->hostport, http->path);
457 #endif /* def FORCE_LOAD */
464 #ifdef IMAGE_BLOCKING
465 /*********************************************************************
467 * Function : block_imageurl
469 * Description : Given a URL which is blocked, decide whether to
470 * send the "blocked" image or HTML.
473 * 1 : http = URL to check.
474 * 2 : csp = Current client state (buffers, headers, etc...)
476 * Returns : True (nonzero) if URL is in image list, false (0)
479 *********************************************************************/
480 int block_imageurl(struct http_request *http, struct client_state *csp)
482 #ifdef DETECT_MSIE_IMAGES
483 if ((csp->accept_types
484 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
485 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
489 else if ((csp->accept_types
490 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
491 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
497 return ((csp->action->flags & ACTION_IMAGE) != 0);
499 #endif /* def IMAGE_BLOCKING */
503 /*********************************************************************
505 * Function : trust_url
507 * Description : Should we "trust" this URL? See "trustfile" line in config.
510 * 1 : http = http_request request for requested URL
511 * 2 : csp = Current client state (buffers, headers, etc...)
513 * Returns : NULL => trusted, else string to HTML "untrusted" description.
515 *********************************************************************/
516 char *trust_url(struct http_request *http, struct client_state *csp)
518 struct file_list *fl;
519 struct block_spec *b;
520 struct url_spec url[1], **tl, *t;
522 char *hostport, *path, *refer;
523 struct http_request rhttp[1];
526 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
531 *url = dsplit(http->host);
533 /* if splitting the domain fails, punt */
534 if (url->dbuf == NULL) return(NULL);
536 memset(rhttp, '\0', sizeof(*rhttp));
538 for (b = b->next; b ; b = b->next)
540 if ((b->url->port == 0) || (b->url->port == http->port))
542 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
544 if ((b->url->path == NULL) ||
546 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
548 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
555 if (b->reject == 0) return(NULL);
557 hostport = url_encode(http->hostport);
558 path = url_encode(http->path);
562 refer = url_encode(csp->referrer);
566 refer = url_encode("undefined");
570 n += strlen(hostport);
574 p = (char *)malloc(n);
576 sprintf(p, CTRUST, hostport, path, refer);
591 if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
593 /* no referrer was supplied */
594 goto trust_url_not_trusted;
597 /* forge a URL from the referrer so we can use
598 * convert_url() to parse it into its components.
602 p = strsav(p, "GET ");
603 p = strsav(p, csp->referrer + 9); /* skip over "Referer: " */
604 p = strsav(p, " HTTP/1.0");
606 parse_http_request(p, rhttp, csp);
608 if (rhttp->cmd == NULL)
611 goto trust_url_not_trusted;
616 *url = dsplit(rhttp->host);
618 /* if splitting the domain fails, punt */
619 if (url->dbuf == NULL) goto trust_url_not_trusted;
621 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
623 if ((t->port == 0) || (t->port == rhttp->port))
625 if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
627 if ((t->path == NULL) ||
629 (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
631 (strncmp(t->path, rhttp->path, t->pathlen) == 0)
635 /* if the URL's referrer is from a trusted referrer, then
636 * add the target spec to the trustfile as an unblocked
637 * domain and return NULL (which means it's OK).
645 if ((fp = fopen(csp->config->trustfile, "a")))
650 h = strsav(h, http->hostport);
656 /* since this path points into a user's home space
657 * be sure to include this spec in the trustfile.
659 if ((p = strchr(p, '/')))
662 h = strsav(h, http->path);
667 free_http_request(rhttp);
669 fprintf(fp, "%s\n", h);
679 trust_url_not_trusted:
680 free_http_request(rhttp);
682 hostport = url_encode(http->hostport);
683 path = url_encode(http->path);
687 refer = url_encode(csp->referrer);
691 refer = url_encode("undefined");
695 n += strlen(hostport);
699 p = (char *)malloc(n);
700 sprintf(p, CTRUST, hostport, path, refer);
709 #endif /* def TRUST_FILES */
713 /*********************************************************************
715 * Function : re_process_buffer
717 * Description : Apply all jobs from the joblist (aka. Perl regexp's) to
718 * the text buffer that's been accumulated in csp->iob->buf
719 * and set csp->content_length to the modified size.
722 * 1 : csp = Current client state (buffers, headers, etc...)
724 * Returns : a pointer to the (newly allocated) modified buffer.
727 *********************************************************************/
728 char *re_process_buffer(struct client_state *csp)
731 int size = csp->iob->eod - csp->iob->cur;
732 char *old=csp->iob->cur, *new = NULL;
733 pcrs_job *job, *joblist;
735 struct file_list *fl;
736 struct re_filterfile_spec *b;
738 /* Sanity first ;-) */
744 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
746 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
750 joblist = b->joblist;
753 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
754 csp->http->hostport, csp->http->path, size);
756 /* Apply all jobs from the joblist */
757 for (job = joblist; NULL != job; job = job->next)
759 hits += pcrs_exec_substitution(job, old, size, &new, &size);
760 if (old != csp->iob->cur) free(old);
764 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
766 csp->content_length = size;
768 /* fwiw, reset the iob */
773 #endif /* def PCRS */
776 /*********************************************************************
778 * Function : url_actions
780 * Description : Gets the actions for this URL.
783 * 1 : http = http_request request for blocked URLs
784 * 2 : csp = Current client state (buffers, headers, etc...)
788 *********************************************************************/
789 void url_actions(struct http_request *http,
790 struct client_state *csp)
792 struct file_list *fl;
793 struct url_actions *b;
795 init_current_action(csp->action);
797 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
802 apply_url_actions(csp->action, http, b);
806 /*********************************************************************
808 * Function : apply_url_actions
810 * Description : Applies a list of URL actions.
813 * 1 : action = Destination.
814 * 2 : http = Current URL
815 * 3 : b = list of URL actions to apply
819 *********************************************************************/
820 void apply_url_actions(struct current_action_spec *action,
821 struct http_request *http,
822 struct url_actions *b)
824 struct url_spec url[1];
828 /* Should never happen */
832 *url = dsplit(http->host);
834 /* if splitting the domain fails, punt */
835 if (url->dbuf == NULL)
840 for (b = b->next; NULL != b; b = b->next)
842 if ((b->url->port == 0) || (b->url->port == http->port))
844 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
846 if ((b->url->path == NULL) ||
848 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
850 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
854 merge_current_action(action, b->action);
865 /*********************************************************************
867 * Function : forward_url
869 * Description : Should we forward this to another proxy?
872 * 1 : http = http_request request for current URL
873 * 2 : csp = Current client state (buffers, headers, etc...)
875 * Returns : Return gw_default for no forward match,
876 * else a gateway pointer to a specific forwarding proxy.
878 *********************************************************************/
879 const struct gateway *forward_url(struct http_request *http, struct client_state *csp)
881 struct file_list *fl;
882 struct forward_spec *b;
883 struct url_spec url[1];
885 if (((fl = csp->flist) == NULL) || ((b = fl->f) == NULL))
890 *url = dsplit(http->host);
892 /* if splitting the domain fails, punt */
893 if (url->dbuf == NULL) return(gw_default);
895 for (b = b->next; b ; b = b->next)
897 if ((b->url->port == 0) || (b->url->port == http->port))
899 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
901 if ((b->url->path == NULL) ||
903 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
905 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
924 /*********************************************************************
928 * Description : Takes a domain and returns a pointer to a url_spec
929 * structure populated with dbuf, dcnt and dvec. The
930 * other fields in the structure that is returned are zero.
933 * 1 : domain = a URL address
935 * Returns : url_spec structure populated with dbuf, dcnt and dvec.
937 *********************************************************************/
938 struct url_spec dsplit(char *domain)
940 struct url_spec ret[1];
945 memset(ret, '\0', sizeof(*ret));
947 if (domain[strlen(domain) - 1] == '.')
949 ret->unanchored |= ANCHOR_RIGHT;
951 if (domain[0] == '.')
953 ret->unanchored |= ANCHOR_LEFT;
956 ret->dbuf = strdup(domain);
958 /* map to lower case */
959 for (p = ret->dbuf; *p ; p++) *p = tolower(*p);
961 /* split the domain name into components */
962 ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
966 memset(ret, '\0', sizeof(ret));
970 /* save a copy of the pointers in dvec */
971 size = ret->dcnt * sizeof(*ret->dvec);
973 if ((ret->dvec = (char **)malloc(size)))
975 memcpy(ret->dvec, v, size);
984 /*********************************************************************
986 * Function : domaincmp
988 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
989 * pattern->unachored, the comparison is un-, left-,
990 * right-anchored, or both.
991 * The individual domain names are compared with
995 * 1 : pattern = a domain that may contain a '*' as a wildcard.
996 * 2 : fqdn = domain name against which the patterns are compared.
998 * Returns : 0 => domains are equivalent, else no match.
1000 *********************************************************************/
1001 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1003 char **pv, **fv; /* vectors */
1004 int pn, fn; /* counters */
1005 char *p, *f; /* chars */
1011 while (fn < fqdn->dcnt && pn < pattern->dcnt)
1016 if (simplematch(p, f))
1018 if(pn || !(pattern->unanchored & ANCHOR_LEFT))
1030 return ((pn < pattern->dcnt) || ((fn < fqdn->dcnt) && !(pattern->unanchored & ANCHOR_RIGHT)));