1 const char filters_rcs[] = "$Id: filters.c,v 1.41 2001/11/13 00:14:07 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', `domain_split',
10 * `filter_popups', `forward_url', 'redirect_url',
11 * `ij_untrusted_url', `intercept_url', `pcrs_filter_respose',
12 * '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.41 2001/11/13 00:14:07 jongfoster
42 * Fixing stupid bug now I've figured out what || means.
43 * (It always returns 0 or 1, not one of it's paramaters.)
45 * Revision 1.40 2001/10/26 17:37:55 oes
46 * - Re-enabled Netscape 200/404 bug workaround in block_url():
47 * - Removed OS/2 special case
48 * - Made block_url() independant from sed() having been run
49 * - Made trust_url independant from sed() having been run
50 * - Made is_imageurl independant from sed() having been run.
51 * It now checks User-Agent: and Accept: by itself.
54 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
55 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
56 * threads to call select() simultaneously. So, it's time to do a real, live,
57 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
58 * (native). Both versions will work, but using __OS2__ offers multi-threading.
60 * Revision 1.38 2001/10/23 21:32:33 jongfoster
61 * Adding error-checking to selected functions
63 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
64 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
65 * filters.c. Added a FIXME in front of the offending code. I'll gladly
66 * put in a better/more robust fix for all parties if one is presented...
67 * It seems that just returning 200 instead of 404 would pretty much fix
68 * it for everyone, but I don't know all the history of the problem.
70 * Revision 1.36 2001/10/10 16:44:16 oes
71 * Added match_portlist function
73 * Revision 1.35 2001/10/07 15:41:23 oes
74 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
76 * New function remove_chunked_transfer_coding that strips chunked
77 * transfer coding to plain and is called by pcrs_filter_response
78 * and gif_deanimate_response if neccessary
80 * Improved handling of zero-change re_filter runs
82 * pcrs_filter_response and gif_deanimate_response now remove
83 * chunked transfer codeing before processing the body.
85 * Revision 1.34 2001/09/20 15:49:36 steudten
87 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
88 * See cgi.c fill_template().
90 * Revision 1.33 2001/09/16 17:05:14 jongfoster
91 * Removing unused #include showarg.h
93 * Revision 1.32 2001/09/16 13:21:27 jongfoster
94 * Changes to use new list functions.
96 * Revision 1.31 2001/09/16 11:38:02 jongfoster
97 * Splitting fill_template() into 2 functions:
98 * template_load() loads the file
99 * template_fill() performs the PCRS regexps.
100 * This is because the CGI edit interface has a "table row"
101 * template which is used many times in the page - this
102 * change means it's only loaded from disk once.
104 * Revision 1.30 2001/09/16 11:00:10 jongfoster
105 * New function alloc_http_response, for symmetry with free_http_response
107 * Revision 1.29 2001/09/13 23:32:40 jongfoster
108 * Moving image data to cgi.c rather than cgi.h
109 * Fixing a GPF under Win32 (and any other OS that protects global
110 * constants from being written to).
112 * Revision 1.28 2001/09/10 10:18:51 oes
113 * Silenced compiler warnings
115 * Revision 1.27 2001/08/05 16:06:20 jongfoster
116 * Modifiying "struct map" so that there are now separate header and
117 * "map_entry" structures. This means that functions which modify a
118 * map no longer need to return a pointer to the modified map.
119 * Also, it no longer reverses the order of the entries (which may be
120 * important with some advanced template substitutions).
122 * Revision 1.26 2001/07/30 22:08:36 jongfoster
123 * Tidying up #defines:
124 * - All feature #defines are now of the form FEATURE_xxx
125 * - Permanently turned off WIN_GUI_EDIT
126 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
128 * Revision 1.25 2001/07/26 10:09:46 oes
129 * Made browser detection a little less naive
131 * Revision 1.24 2001/07/25 17:22:51 oes
132 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
134 * Revision 1.23 2001/07/23 13:40:12 oes
135 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
137 * Revision 1.22 2001/07/18 12:29:34 oes
138 * - Made gif_deanimate_response respect
139 * csp->action->string[ACTION_STRING_DEANIMATE]
140 * - Logging cosmetics
142 * Revision 1.21 2001/07/13 13:59:53 oes
143 * - Introduced gif_deanimate_response which shares the
144 * generic content modification interface of pcrs_filter_response
145 * and acts as a wrapper to deanimate.c:gif_deanimate()
146 * - Renamed re_process_buffer to pcrs_filter_response
147 * - pcrs_filter_response now returns NULL on failiure
148 * - Removed all #ifdef PCRS
150 * Revision 1.20 2001/07/01 17:01:04 oes
151 * Added comments and missing return statement in is_untrusted_url()
153 * Revision 1.19 2001/06/29 21:45:41 oes
154 * Indentation, CRLF->LF, Tab-> Space
156 * Revision 1.18 2001/06/29 13:27:38 oes
157 * - Cleaned up, renamed and reorderd functions
158 * and improved comments
161 * - Ported to CGI platform. Now delivers
162 * http_response or NULL
163 * - Unified HTML and GIF generation (moved image detection
164 * and GIF generation here from jcc.c:chat())
165 * - Fixed HTTP status to:
166 * - 403 (Forbidden) for the "blocked" HTML message
167 * - 200 (OK) for GIF answers
168 * - 302 (Redirect) for redirect to GIF
171 * - Ported to CGI platform. Now delivers
172 * http_response or NULL
173 * - Separated detection of untrusted URL into
174 * (bool)is_untrusted_url
175 * - Added enforcement of untrusted requests
177 * - Moved redirect_url() from cgi.c to here
178 * and ported it to the CGI platform
180 * - Removed logentry from cancelled commit
182 * Revision 1.17 2001/06/09 10:55:28 jongfoster
183 * Changing BUFSIZ ==> BUFFER_SIZE
185 * Revision 1.16 2001/06/07 23:10:26 jongfoster
186 * Allowing unanchored domain patterns to back off and retry
187 * if they partially match. Optimized right-anchored patterns.
188 * Moving ACL and forward files into config file.
189 * Replacing struct gateway with struct forward_spec
191 * Revision 1.15 2001/06/03 19:12:00 oes
192 * extracted-CGI relevant stuff
194 * Revision 1.14 2001/06/01 10:30:55 oes
195 * Added optional left-anchoring to domaincmp
197 * Revision 1.13 2001/05/31 21:21:30 jongfoster
198 * Permissionsfile / actions file changes:
199 * - Changed "permission" to "action" throughout
200 * - changes to file format to allow string parameters
201 * - Moved helper functions to actions.c
203 * Revision 1.12 2001/05/31 17:35:20 oes
205 * - Enhanced domain part globbing with infix and prefix asterisk
206 * matching and optional unanchored operation
208 * Revision 1.11 2001/05/29 11:53:23 oes
209 * "See why" link added to "blocked" page
211 * Revision 1.10 2001/05/29 09:50:24 jongfoster
212 * Unified blocklist/imagelist/permissionslist.
213 * File format is still under discussion, but the internal changes
216 * Also modified interceptor behaviour:
217 * - We now intercept all URLs beginning with one of the following
218 * prefixes (and *only* these prefixes):
220 * * http://ijbswa.sf.net/config/
221 * * http://ijbswa.sourceforge.net/config/
222 * - New interceptors "home page" - go to http://i.j.b/ to see it.
223 * - Internal changes so that intercepted and fast redirect pages
224 * are not replaced with an image.
225 * - Interceptors now have the option to send a binary page direct
226 * to the client. (i.e. ijb-send-banner uses this)
227 * - Implemented show-url-info interceptor. (Which is why I needed
228 * the above interceptors changes - a typical URL is
229 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
230 * The previous mechanism would not have intercepted that, and
231 * if it had been intercepted then it then it would have replaced
234 * Revision 1.9 2001/05/27 22:17:04 oes
236 * - re_process_buffer no longer writes the modified buffer
237 * to the client, which was very ugly. It now returns the
238 * buffer, which it is then written by chat.
240 * - content_length now adjusts the Content-Length: header
241 * for modified documents rather than crunch()ing it.
242 * (Length info in csp->content_length, which is 0 for
243 * unmodified documents)
245 * - For this to work, sed() is called twice when filtering.
247 * Revision 1.8 2001/05/26 17:13:28 jongfoster
248 * Filled in a function comment.
250 * Revision 1.7 2001/05/26 15:26:15 jongfoster
251 * ACL feature now provides more security by immediately dropping
252 * connections from untrusted hosts.
254 * Revision 1.6 2001/05/26 00:28:36 jongfoster
255 * Automatic reloading of config file.
256 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
257 * Most of the global variables have been moved to a new
258 * struct configuration_spec, accessed through csp->config->globalname
259 * Most of the globals remaining are used by the Win32 GUI.
261 * Revision 1.5 2001/05/25 22:34:30 jongfoster
264 * Revision 1.4 2001/05/22 18:46:04 oes
266 * - Enabled filtering banners by size rather than URL
267 * by adding patterns that replace all standard banner
268 * sizes with the "Junkbuster" gif to the re_filterfile
270 * - Enabled filtering WebBugs by providing a pattern
271 * which kills all 1x1 images
273 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
274 * which is selected by the (nonstandard and therefore
275 * capital) letter 'U' in the option string.
276 * It causes the quantifiers to be ungreedy by default.
277 * Appending a ? turns back to greedy (!).
279 * - Added a new interceptor ijb-send-banner, which
280 * sends back the "Junkbuster" gif. Without imagelist or
281 * MSIE detection support, or if tinygif = 1, or the
282 * URL isn't recognized as an imageurl, a lame HTML
283 * explanation is sent instead.
285 * - Added new feature, which permits blocking remote
286 * script redirects and firing back a local redirect
288 * The feature is conditionally compiled, i.e. it
289 * can be disabled with --disable-fast-redirects,
290 * plus it must be activated by a "fast-redirects"
291 * line in the config file, has its own log level
292 * and of course wants to be displayed by show-proxy-args
293 * Note: Boy, all the #ifdefs in 1001 locations and
294 * all the fumbling with configure.in and acconfig.h
295 * were *way* more work than the feature itself :-(
297 * - Because a generic redirect template was needed for
298 * this, tinygif = 3 now uses the same.
300 * - Moved GIFs, and other static HTTP response templates
305 * - Removed some >400 CRs again (Jon, you really worked
308 * Revision 1.3 2001/05/20 16:44:47 jongfoster
309 * Removing last hardcoded JunkBusters.com URLs.
311 * Revision 1.2 2001/05/20 01:21:20 jongfoster
312 * Version 2.9.4 checkin.
313 * - Merged popupfile and cookiefile, and added control over PCRS
314 * filtering, in new "permissionsfile".
315 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
316 * file error you now get a message box (in the Win32 GUI) rather
317 * than the program exiting with no explanation.
318 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
320 * - Removed tabs from "config"
321 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
322 * - Bumped up version number.
324 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
325 * Initial import of version 2.9.3 source tree
328 *********************************************************************/
334 #include <sys/types.h>
343 #endif /* ndef __OS2__ */
344 #include <netinet/in.h>
346 #include <winsock2.h>
347 #endif /* ndef _WIN32 */
351 #endif /* def __OS2__ */
359 #include "jbsockets.h"
360 #include "miscutil.h"
364 #include "deanimate.h"
365 #include "urlmatch.h"
371 const char filters_h_rcs[] = FILTERS_H_VERSION;
373 /* Fix a problem with Solaris. There should be no effect on other
375 * Solaris's isspace() is a macro which uses it's argument directly
376 * as an array index. Therefore we need to make sure that high-bit
377 * characters generate +ve values, and ideally we also want to make
378 * the argument match the declared parameter type of "int".
380 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
384 /*********************************************************************
386 * Function : block_acl
388 * Description : Block this request?
389 * Decide yes or no based on ACL file.
392 * 1 : dst = The proxy or gateway address this is going to.
393 * Or NULL to check all possible targets.
394 * 2 : csp = Current client state (buffers, headers, etc...)
395 * Also includes the client IP address.
397 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
399 *********************************************************************/
400 int block_acl(struct access_control_addr *dst, struct client_state *csp)
402 struct access_control_list *acl = csp->config->acl;
404 /* if not using an access control list, then permit the connection */
410 /* search the list */
413 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
417 /* Just want to check if they have any access */
418 if (acl->action == ACL_PERMIT)
423 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
424 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
426 if (acl->action == ACL_PERMIT)
444 /*********************************************************************
446 * Function : acl_addr
448 * Description : Called from `load_aclfile' to parse an ACL address.
451 * 1 : aspec = String specifying ACL address.
452 * 2 : aca = struct access_control_addr to fill in.
454 * Returns : 0 => Ok, everything else is an error.
456 *********************************************************************/
457 int acl_addr(char *aspec, struct access_control_addr *aca)
459 int i, masklength, port;
465 if ((p = strchr(aspec, '/')))
469 if (ijb_isdigit(*p) == 0)
473 masklength = atoi(p);
476 if ((masklength < 0) || (masklength > 32))
481 if ((p = strchr(aspec, ':')))
485 if (ijb_isdigit(*p) == 0)
494 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
498 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
502 /* build the netmask */
504 for (i=1; i <= masklength ; i++)
506 aca->mask |= (1 << (32 - i));
509 /* now mask off the host portion of the ip address
510 * (i.e. save on the network portion of the address).
512 aca->addr = aca->addr & aca->mask;
517 #endif /* def FEATURE_ACL */
520 /*********************************************************************
522 * Function : match_portlist
524 * Description : Check if a given number is covered by a comma
525 * separated list of numbers and ranges (a,b-c,d,..)
528 * 1 : portlist = String with list
529 * 2 : port = port to check
531 * Returns : 0 => no match
534 *********************************************************************/
535 int match_portlist(const char *portlist, int port)
537 char *min, *max, *next, *portlist_copy;
539 min = next = portlist_copy = strdup(portlist);
542 * Zero-terminate first item and remember offset for next
544 if (NULL != (next = strchr(portlist_copy, (int) ',')))
550 * Loop through all items, checking for match
554 if (NULL == (max = strchr(min, (int) '-')))
557 * No dash, check for equality
559 if (port == atoi(min))
568 * This is a range, so check if between min and max,
569 * or, if max was omitted, between min and 65K
572 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
586 * Zero-terminate next item and remember offset for n+1
588 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
600 /*********************************************************************
602 * Function : block_url
604 * Description : Called from `chat'. Check to see if we need to block this.
607 * 1 : csp = Current client state (buffers, headers, etc...)
609 * Returns : NULL => unblocked, else HTTP block response
611 *********************************************************************/
612 struct http_response *block_url(struct client_state *csp)
614 #ifdef FEATURE_IMAGE_BLOCKING
616 #endif /* def FEATURE_IMAGE_BLOCKING */
617 struct http_response *rsp;
620 * If it's not blocked, don't block it ;-)
622 if ((csp->action->flags & ACTION_BLOCK) == 0)
628 * Else, prepare a response
630 if (NULL == (rsp = alloc_http_response()))
632 return cgi_error_memory();
636 * If it's an image-url, send back an image or redirect
637 * as specified by the relevant +image action
639 #ifdef FEATURE_IMAGE_BLOCKING
640 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
643 /* determine HOW images should be blocked */
644 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
646 /* and handle accordingly: */
647 if ((p == NULL) || (0 == strcmpic(p, "logo")))
649 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
650 if (rsp->body == NULL)
652 free_http_response(rsp);
653 return cgi_error_memory();
655 rsp->content_length = image_junkbuster_gif_length;
657 if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
659 free_http_response(rsp);
660 return cgi_error_memory();
664 else if (0 == strcmpic(p, "blank"))
666 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
667 if (rsp->body == NULL)
669 free_http_response(rsp);
670 return cgi_error_memory();
672 rsp->content_length = image_blank_gif_length;
674 if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
676 free_http_response(rsp);
677 return cgi_error_memory();
683 rsp->status = strdup("302 Local Redirect from Junkbuster");
684 if (rsp->status == NULL)
686 free_http_response(rsp);
687 return cgi_error_memory();
690 if (enlist_unique_header(rsp->headers, "Location", p))
692 free_http_response(rsp);
693 return cgi_error_memory();
698 #endif /* def FEATURE_IMAGE_BLOCKING */
701 * Else, generate an HTML "blocked" message:
705 struct map * exports;
708 * Workaround for stupid Netscape bug which prevents
709 * pages from being displayed if loading a referenced
710 * JavaScript or style sheet fails. So make it appear
711 * as if it succeeded.
713 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
714 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
715 && !strstr(p, "Gecko") /* save Mozilla, */
716 && !strstr(p, "compatible") /* MSIE */
717 && !strstr(p, "Opera")) /* and Opera. */
719 rsp->status = strdup("200 Request for blocked URL");
723 rsp->status = strdup("404 Request for blocked URL");
726 if (rsp->status == NULL)
728 free_http_response(rsp);
729 return cgi_error_memory();
732 exports = default_exports(csp, NULL);
735 free_http_response(rsp);
736 return cgi_error_memory();
739 #ifdef FEATURE_FORCE_LOAD
740 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
741 #else /* ifndef FEATURE_FORCE_LOAD */
742 err = map_block_killer(exports, "force-support");
743 #endif /* ndef FEATURE_FORCE_LOAD */
745 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
746 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
751 free_http_response(rsp);
752 return cgi_error_memory();
755 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
758 free_http_response(rsp);
759 return cgi_error_memory();
763 return finish_http_response(rsp);
769 /*********************************************************************
771 * Function : trust_url FIXME: I should be called distrust_url
773 * Description : Calls is_untrusted_url to determine if the URL is trusted
774 * and if not, returns a HTTP 304 response with a reject message.
777 * 1 : csp = Current client state (buffers, headers, etc...)
779 * Returns : NULL => trusted, else http_response.
781 *********************************************************************/
782 struct http_response *trust_url(struct client_state *csp)
784 struct http_response *rsp;
785 struct map * exports;
786 char buf[BUFFER_SIZE];
788 struct url_spec **tl;
793 * Don't bother to work on trusted URLs
795 if (!is_untrusted_url(csp))
801 * Else, prepare a response:
803 if (NULL == (rsp = alloc_http_response()))
805 return cgi_error_memory();
808 exports = default_exports(csp, NULL);
811 free_http_response(rsp);
812 return cgi_error_memory();
816 * Export the host, port, and referrer information
818 err = map(exports, "hostport", 1, csp->http->hostport, 1);
819 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
820 if (!err) err = map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
821 if (!err) err = map(exports, "path-html", 1, html_encode(csp->http->path), 0);
823 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
825 if (!err) err = map(exports, "referrer", 1, p, 1);
826 if (!err) err = map(exports, "referrer-html", 1, html_encode(p), 0);
830 if (!err) err = map(exports, "referrer", 1, "unknown", 1);
831 if (!err) err = map(exports, "referrer-html", 1, "unknown", 1);
837 free_http_response(rsp);
838 return cgi_error_memory();
842 * Export the trust list
845 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
847 sprintf(buf, "<li>%s</li>\n", t->spec);
848 string_append(&p, buf);
850 err = map(exports, "trusted-referrers", 1, p, 0);
855 free_http_response(rsp);
856 return cgi_error_memory();
860 * Export the trust info, if available
862 if (csp->config->trust_info->first)
864 struct list_entry *l;
867 for (l = csp->config->trust_info->first; l ; l = l->next)
869 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
870 string_append(&p, buf);
872 err = map(exports, "trust-info", 1, p, 0);
876 err = map_block_killer(exports, "have-trust-info");
882 free_http_response(rsp);
883 return cgi_error_memory();
887 * Export the force prefix or the force conditional block killer
889 #ifdef FEATURE_FORCE_LOAD
890 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
891 #else /* ifndef FEATURE_FORCE_LOAD */
892 err = map_block_killer(exports, "force-support");
893 #endif /* ndef FEATURE_FORCE_LOAD */
898 free_http_response(rsp);
899 return cgi_error_memory();
905 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
908 free_http_response(rsp);
909 return cgi_error_memory();
912 return finish_http_response(rsp);
914 #endif /* def FEATURE_TRUST */
917 #ifdef FEATURE_FAST_REDIRECTS
918 /*********************************************************************
920 * Function : redirect_url
922 * Description : Checks for redirection URLs and returns a HTTP redirect
923 * to the destination URL, if necessary
926 * 1 : csp = Current client state (buffers, headers, etc...)
928 * Returns : NULL if URL was clean, HTTP redirect otherwise.
930 *********************************************************************/
931 struct http_response *redirect_url(struct client_state *csp)
934 struct http_response *rsp;
936 p = q = csp->http->path;
937 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
940 * find the last URL encoded in the request
942 while ((p = strstr(p, "http://")))
948 * if there was any, generate and return a HTTP redirect
950 if (q != csp->http->path)
952 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
954 if (NULL == (rsp = alloc_http_response()))
956 return cgi_error_memory();
959 if ( enlist_unique_header(rsp->headers, "Location", q)
960 || (NULL == (rsp->status = strdup("302 Local Redirect from Junkbuster"))) )
962 free_http_response(rsp);
963 return cgi_error_memory();
966 return finish_http_response(rsp);
974 #endif /* def FEATURE_FAST_REDIRECTS */
977 #ifdef FEATURE_IMAGE_BLOCKING
978 /*********************************************************************
980 * Function : is_imageurl
982 * Description : Given a URL, decide whether it is an image or not,
983 * using either the info from a previous +image action
984 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
985 * the browser's accept header.
988 * 1 : csp = Current client state (buffers, headers, etc...)
990 * Returns : True (nonzero) if URL is an image, false (0)
993 *********************************************************************/
994 int is_imageurl(struct client_state *csp)
996 #ifdef FEATURE_IMAGE_DETECT_MSIE
999 tmp = get_header_value(csp->headers, "User-Agent:");
1000 if (tmp && strstr(tmp, "MSIE"))
1002 tmp = get_header_value(csp->headers, "Accept:");
1003 if (tmp && strstr(tmp, "image/gif"))
1005 /* Client will accept HTML. If this seems counterintuitive,
1015 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1017 return ((csp->action->flags & ACTION_IMAGE) != 0);
1020 #endif /* def FEATURE_IMAGE_BLOCKING */
1023 #ifdef FEATURE_COOKIE_JAR
1024 /*********************************************************************
1026 * Function : is_untrusted_url
1028 * Description : Should we "distrust" this URL (and block it)?
1030 * Yes if it matches a line in the trustfile, or if the
1031 * referrer matches a line starting with "+" in the
1036 * 1 : csp = Current client state (buffers, headers, etc...)
1038 * Returns : 0 => trusted, 1 => untrusted
1040 *********************************************************************/
1041 int is_untrusted_url(struct client_state *csp)
1043 struct file_list *fl;
1044 struct block_spec *b;
1045 struct url_spec **trusted_url;
1046 struct http_request rhttp[1];
1051 * If we don't have a trustlist, we trust everybody
1053 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1058 memset(rhttp, '\0', sizeof(*rhttp));
1061 * Do we trust the request URL itself?
1063 for (b = b->next; b ; b = b->next)
1065 if (url_match(b->url, csp->http))
1071 if (NULL == (h = get_header_value(csp->headers, "Referer:")))
1073 /* no referrer was supplied */
1078 * If not, do we maybe trust its referrer?
1083 * Parse the URL from the referrer
1086 err = parse_http_url(h, rhttp, csp);
1092 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1094 if (url_match(*trusted_url, rhttp))
1096 /* if the URL's referrer is from a trusted referrer, then
1097 * add the target spec to the trustfile as an unblocked
1098 * domain and return NULL (which means it's OK).
1103 if ((fp = fopen(csp->config->trustfile, "a")))
1108 h = strsav(h, csp->http->hostport);
1110 p = csp->http->path;
1114 /* since this path points into a user's home space
1115 * be sure to include this spec in the trustfile.
1117 if ((p = strchr(p, '/')))
1119 *p = '\0'; /* FIXME: writing to csp->http->path is a bad idea */
1120 h = strsav(h, csp->http->path);
1125 fprintf(fp, "%s\n", h);
1134 #endif /* def FEATURE_COOKIE_JAR */
1137 /*********************************************************************
1139 * Function : pcrs_filter_response
1141 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
1142 * to the text buffer that's been accumulated in
1143 * csp->iob->buf and set csp->content_length to the modified
1144 * size and raise the CSP_FLAG_MODIFIED flag if appropriate.
1147 * 1 : csp = Current client state (buffers, headers, etc...)
1149 * Returns : a pointer to the (newly allocated) modified buffer.
1150 * or NULL in case something went wrong
1152 *********************************************************************/
1153 char *pcrs_filter_response(struct client_state *csp)
1158 char *old = csp->iob->cur, *new = NULL;
1161 struct file_list *fl;
1162 struct re_filterfile_spec *b;
1165 if (csp->iob->cur >= csp->iob->eod)
1169 size = csp->iob->eod - csp->iob->cur;
1172 * If the body has a "chunked" transfer-encoding,
1173 * get rid of it first, adjusting size and iob->eod
1175 if (csp->flags & CSP_FLAG_CHUNKED)
1177 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1178 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1182 csp->iob->eod = csp->iob->cur + size;
1183 csp->flags |= CSP_FLAG_MODIFIED;
1186 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1188 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1192 if ( NULL == b->joblist )
1194 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1198 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1199 csp->http->hostport, csp->http->path, size);
1201 /* Apply all jobs from the joblist */
1202 for (job = b->joblist; NULL != job; job = job->next)
1204 hits += pcrs_execute(job, old, size, &new, &size);
1205 if (old != csp->iob->cur) free(old);
1209 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1212 * If there were no hits, destroy our copy and let
1213 * chat() use the original in csp->iob
1221 csp->flags |= CSP_FLAG_MODIFIED;
1222 csp->content_length = size;
1230 /*********************************************************************
1232 * Function : gif_deanimate_response
1234 * Description : Deanimate the GIF image that has been accumulated in
1235 * csp->iob->buf, set csp->content_length to the modified
1236 * size and raise the CSP_FLAG_MODIFIED flag.
1239 * 1 : csp = Current client state (buffers, headers, etc...)
1241 * Returns : a pointer to the (newly allocated) modified buffer.
1242 * or NULL in case something went wrong.
1244 *********************************************************************/
1245 char *gif_deanimate_response(struct client_state *csp)
1247 struct binbuffer *in, *out;
1249 int size = csp->iob->eod - csp->iob->cur;
1252 * If the body has a "chunked" transfer-encoding,
1253 * get rid of it first, adjusting size and iob->eod
1255 if (csp->flags & CSP_FLAG_CHUNKED)
1257 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1258 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1262 csp->iob->eod = csp->iob->cur + size;
1263 csp->flags |= CSP_FLAG_MODIFIED;
1266 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1267 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1269 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1273 in->buffer = csp->iob->cur;
1276 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1278 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1285 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1286 csp->content_length = out->offset;
1287 csp->flags |= CSP_FLAG_MODIFIED;
1297 /*********************************************************************
1299 * Function : remove_chunked_transfer_coding
1301 * Description : In-situ remove the "chunked" transfer coding as defined
1302 * in rfc2616 from a buffer.
1305 * 1 : buffer = Pointer to the text buffer
1306 * 2 : size = Number of bytes to be processed
1308 * Returns : The new size, i.e. the number of bytes from buffer which
1309 * are occupied by the stripped body, or 0 in case something
1312 *********************************************************************/
1313 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1316 unsigned int chunksize = 0;
1317 char *from_p, *to_p;
1320 from_p = to_p = buffer;
1322 if (sscanf(buffer, "%x", &chunksize) != 1)
1324 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1328 while (chunksize > 0)
1330 if (NULL == (from_p = strstr(from_p, "\r\n")))
1332 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1335 newsize += chunksize;
1338 memmove(to_p, from_p, (size_t) chunksize);
1339 to_p = buffer + newsize;
1340 from_p += chunksize + 2;
1342 if (sscanf(from_p, "%x", &chunksize) != 1)
1344 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1349 /* FIXME: Should this get its own loglevel? */
1350 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1356 /*********************************************************************
1358 * Function : url_actions
1360 * Description : Gets the actions for this URL.
1363 * 1 : http = http_request request for blocked URLs
1364 * 2 : csp = Current client state (buffers, headers, etc...)
1368 *********************************************************************/
1369 void url_actions(struct http_request *http,
1370 struct client_state *csp)
1372 struct file_list *fl;
1373 struct url_actions *b;
1375 init_current_action(csp->action);
1377 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1382 apply_url_actions(csp->action, http, b);
1387 /*********************************************************************
1389 * Function : apply_url_actions
1391 * Description : Applies a list of URL actions.
1394 * 1 : action = Destination.
1395 * 2 : http = Current URL
1396 * 3 : b = list of URL actions to apply
1400 *********************************************************************/
1401 void apply_url_actions(struct current_action_spec *action,
1402 struct http_request *http,
1403 struct url_actions *b)
1407 /* Should never happen */
1411 for (b = b->next; NULL != b; b = b->next)
1413 if (url_match(b->url, http))
1415 merge_current_action(action, b->action);
1421 /*********************************************************************
1423 * Function : forward_url
1425 * Description : Should we forward this to another proxy?
1428 * 1 : http = http_request request for current URL
1429 * 2 : csp = Current client state (buffers, headers, etc...)
1431 * Returns : Pointer to forwarding information.
1433 *********************************************************************/
1434 const struct forward_spec * forward_url(struct http_request *http,
1435 struct client_state *csp)
1437 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1438 struct forward_spec *fwd = csp->config->forward;
1447 if (url_match(fwd->url, http))