1 const char filters_rcs[] = "$Id: filters.c,v 1.42 2002/01/17 21:00:32 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.42 2002/01/17 21:00:32 jongfoster
42 * Moving all our URL and URL pattern parsing code to urlmatch.c.
44 * Using a single, simple url_match(pattern,url) function - rather than
45 * the 3-line match routine which was repeated all over the place.
47 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
49 * Using parse_http_url() to parse URLs without faking a HTTP
50 * request line for parse_http_request().
52 * Revision 1.41 2001/11/13 00:14:07 jongfoster
53 * Fixing stupid bug now I've figured out what || means.
54 * (It always returns 0 or 1, not one of it's paramaters.)
56 * Revision 1.40 2001/10/26 17:37:55 oes
57 * - Re-enabled Netscape 200/404 bug workaround in block_url():
58 * - Removed OS/2 special case
59 * - Made block_url() independant from sed() having been run
60 * - Made trust_url independant from sed() having been run
61 * - Made is_imageurl independant from sed() having been run.
62 * It now checks User-Agent: and Accept: by itself.
65 * Revision 1.39 2001/10/25 03:40:48 david__schmidt
66 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
67 * threads to call select() simultaneously. So, it's time to do a real, live,
68 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
69 * (native). Both versions will work, but using __OS2__ offers multi-threading.
71 * Revision 1.38 2001/10/23 21:32:33 jongfoster
72 * Adding error-checking to selected functions
74 * Revision 1.37 2001/10/22 15:33:56 david__schmidt
75 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
76 * filters.c. Added a FIXME in front of the offending code. I'll gladly
77 * put in a better/more robust fix for all parties if one is presented...
78 * It seems that just returning 200 instead of 404 would pretty much fix
79 * it for everyone, but I don't know all the history of the problem.
81 * Revision 1.36 2001/10/10 16:44:16 oes
82 * Added match_portlist function
84 * Revision 1.35 2001/10/07 15:41:23 oes
85 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
87 * New function remove_chunked_transfer_coding that strips chunked
88 * transfer coding to plain and is called by pcrs_filter_response
89 * and gif_deanimate_response if neccessary
91 * Improved handling of zero-change re_filter runs
93 * pcrs_filter_response and gif_deanimate_response now remove
94 * chunked transfer codeing before processing the body.
96 * Revision 1.34 2001/09/20 15:49:36 steudten
98 * Fix BUG: Change int size to size_t size in pcrs_filter_response().
99 * See cgi.c fill_template().
101 * Revision 1.33 2001/09/16 17:05:14 jongfoster
102 * Removing unused #include showarg.h
104 * Revision 1.32 2001/09/16 13:21:27 jongfoster
105 * Changes to use new list functions.
107 * Revision 1.31 2001/09/16 11:38:02 jongfoster
108 * Splitting fill_template() into 2 functions:
109 * template_load() loads the file
110 * template_fill() performs the PCRS regexps.
111 * This is because the CGI edit interface has a "table row"
112 * template which is used many times in the page - this
113 * change means it's only loaded from disk once.
115 * Revision 1.30 2001/09/16 11:00:10 jongfoster
116 * New function alloc_http_response, for symmetry with free_http_response
118 * Revision 1.29 2001/09/13 23:32:40 jongfoster
119 * Moving image data to cgi.c rather than cgi.h
120 * Fixing a GPF under Win32 (and any other OS that protects global
121 * constants from being written to).
123 * Revision 1.28 2001/09/10 10:18:51 oes
124 * Silenced compiler warnings
126 * Revision 1.27 2001/08/05 16:06:20 jongfoster
127 * Modifiying "struct map" so that there are now separate header and
128 * "map_entry" structures. This means that functions which modify a
129 * map no longer need to return a pointer to the modified map.
130 * Also, it no longer reverses the order of the entries (which may be
131 * important with some advanced template substitutions).
133 * Revision 1.26 2001/07/30 22:08:36 jongfoster
134 * Tidying up #defines:
135 * - All feature #defines are now of the form FEATURE_xxx
136 * - Permanently turned off WIN_GUI_EDIT
137 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
139 * Revision 1.25 2001/07/26 10:09:46 oes
140 * Made browser detection a little less naive
142 * Revision 1.24 2001/07/25 17:22:51 oes
143 * Added workaround for Netscape bug that prevents display of page when loading a component fails.
145 * Revision 1.23 2001/07/23 13:40:12 oes
146 * Fixed bug that caused document body to be dropped when pcrs joblist was empty.
148 * Revision 1.22 2001/07/18 12:29:34 oes
149 * - Made gif_deanimate_response respect
150 * csp->action->string[ACTION_STRING_DEANIMATE]
151 * - Logging cosmetics
153 * Revision 1.21 2001/07/13 13:59:53 oes
154 * - Introduced gif_deanimate_response which shares the
155 * generic content modification interface of pcrs_filter_response
156 * and acts as a wrapper to deanimate.c:gif_deanimate()
157 * - Renamed re_process_buffer to pcrs_filter_response
158 * - pcrs_filter_response now returns NULL on failiure
159 * - Removed all #ifdef PCRS
161 * Revision 1.20 2001/07/01 17:01:04 oes
162 * Added comments and missing return statement in is_untrusted_url()
164 * Revision 1.19 2001/06/29 21:45:41 oes
165 * Indentation, CRLF->LF, Tab-> Space
167 * Revision 1.18 2001/06/29 13:27:38 oes
168 * - Cleaned up, renamed and reorderd functions
169 * and improved comments
172 * - Ported to CGI platform. Now delivers
173 * http_response or NULL
174 * - Unified HTML and GIF generation (moved image detection
175 * and GIF generation here from jcc.c:chat())
176 * - Fixed HTTP status to:
177 * - 403 (Forbidden) for the "blocked" HTML message
178 * - 200 (OK) for GIF answers
179 * - 302 (Redirect) for redirect to GIF
182 * - Ported to CGI platform. Now delivers
183 * http_response or NULL
184 * - Separated detection of untrusted URL into
185 * (bool)is_untrusted_url
186 * - Added enforcement of untrusted requests
188 * - Moved redirect_url() from cgi.c to here
189 * and ported it to the CGI platform
191 * - Removed logentry from cancelled commit
193 * Revision 1.17 2001/06/09 10:55:28 jongfoster
194 * Changing BUFSIZ ==> BUFFER_SIZE
196 * Revision 1.16 2001/06/07 23:10:26 jongfoster
197 * Allowing unanchored domain patterns to back off and retry
198 * if they partially match. Optimized right-anchored patterns.
199 * Moving ACL and forward files into config file.
200 * Replacing struct gateway with struct forward_spec
202 * Revision 1.15 2001/06/03 19:12:00 oes
203 * extracted-CGI relevant stuff
205 * Revision 1.14 2001/06/01 10:30:55 oes
206 * Added optional left-anchoring to domaincmp
208 * Revision 1.13 2001/05/31 21:21:30 jongfoster
209 * Permissionsfile / actions file changes:
210 * - Changed "permission" to "action" throughout
211 * - changes to file format to allow string parameters
212 * - Moved helper functions to actions.c
214 * Revision 1.12 2001/05/31 17:35:20 oes
216 * - Enhanced domain part globbing with infix and prefix asterisk
217 * matching and optional unanchored operation
219 * Revision 1.11 2001/05/29 11:53:23 oes
220 * "See why" link added to "blocked" page
222 * Revision 1.10 2001/05/29 09:50:24 jongfoster
223 * Unified blocklist/imagelist/permissionslist.
224 * File format is still under discussion, but the internal changes
227 * Also modified interceptor behaviour:
228 * - We now intercept all URLs beginning with one of the following
229 * prefixes (and *only* these prefixes):
231 * * http://ijbswa.sf.net/config/
232 * * http://ijbswa.sourceforge.net/config/
233 * - New interceptors "home page" - go to http://i.j.b/ to see it.
234 * - Internal changes so that intercepted and fast redirect pages
235 * are not replaced with an image.
236 * - Interceptors now have the option to send a binary page direct
237 * to the client. (i.e. ijb-send-banner uses this)
238 * - Implemented show-url-info interceptor. (Which is why I needed
239 * the above interceptors changes - a typical URL is
240 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
241 * The previous mechanism would not have intercepted that, and
242 * if it had been intercepted then it then it would have replaced
245 * Revision 1.9 2001/05/27 22:17:04 oes
247 * - re_process_buffer no longer writes the modified buffer
248 * to the client, which was very ugly. It now returns the
249 * buffer, which it is then written by chat.
251 * - content_length now adjusts the Content-Length: header
252 * for modified documents rather than crunch()ing it.
253 * (Length info in csp->content_length, which is 0 for
254 * unmodified documents)
256 * - For this to work, sed() is called twice when filtering.
258 * Revision 1.8 2001/05/26 17:13:28 jongfoster
259 * Filled in a function comment.
261 * Revision 1.7 2001/05/26 15:26:15 jongfoster
262 * ACL feature now provides more security by immediately dropping
263 * connections from untrusted hosts.
265 * Revision 1.6 2001/05/26 00:28:36 jongfoster
266 * Automatic reloading of config file.
267 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
268 * Most of the global variables have been moved to a new
269 * struct configuration_spec, accessed through csp->config->globalname
270 * Most of the globals remaining are used by the Win32 GUI.
272 * Revision 1.5 2001/05/25 22:34:30 jongfoster
275 * Revision 1.4 2001/05/22 18:46:04 oes
277 * - Enabled filtering banners by size rather than URL
278 * by adding patterns that replace all standard banner
279 * sizes with the "Junkbuster" gif to the re_filterfile
281 * - Enabled filtering WebBugs by providing a pattern
282 * which kills all 1x1 images
284 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
285 * which is selected by the (nonstandard and therefore
286 * capital) letter 'U' in the option string.
287 * It causes the quantifiers to be ungreedy by default.
288 * Appending a ? turns back to greedy (!).
290 * - Added a new interceptor ijb-send-banner, which
291 * sends back the "Junkbuster" gif. Without imagelist or
292 * MSIE detection support, or if tinygif = 1, or the
293 * URL isn't recognized as an imageurl, a lame HTML
294 * explanation is sent instead.
296 * - Added new feature, which permits blocking remote
297 * script redirects and firing back a local redirect
299 * The feature is conditionally compiled, i.e. it
300 * can be disabled with --disable-fast-redirects,
301 * plus it must be activated by a "fast-redirects"
302 * line in the config file, has its own log level
303 * and of course wants to be displayed by show-proxy-args
304 * Note: Boy, all the #ifdefs in 1001 locations and
305 * all the fumbling with configure.in and acconfig.h
306 * were *way* more work than the feature itself :-(
308 * - Because a generic redirect template was needed for
309 * this, tinygif = 3 now uses the same.
311 * - Moved GIFs, and other static HTTP response templates
316 * - Removed some >400 CRs again (Jon, you really worked
319 * Revision 1.3 2001/05/20 16:44:47 jongfoster
320 * Removing last hardcoded JunkBusters.com URLs.
322 * Revision 1.2 2001/05/20 01:21:20 jongfoster
323 * Version 2.9.4 checkin.
324 * - Merged popupfile and cookiefile, and added control over PCRS
325 * filtering, in new "permissionsfile".
326 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
327 * file error you now get a message box (in the Win32 GUI) rather
328 * than the program exiting with no explanation.
329 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
331 * - Removed tabs from "config"
332 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
333 * - Bumped up version number.
335 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
336 * Initial import of version 2.9.3 source tree
339 *********************************************************************/
345 #include <sys/types.h>
354 #endif /* ndef __OS2__ */
355 #include <netinet/in.h>
357 #include <winsock2.h>
358 #endif /* ndef _WIN32 */
362 #endif /* def __OS2__ */
370 #include "jbsockets.h"
371 #include "miscutil.h"
375 #include "deanimate.h"
376 #include "urlmatch.h"
382 const char filters_h_rcs[] = FILTERS_H_VERSION;
384 /* Fix a problem with Solaris. There should be no effect on other
386 * Solaris's isspace() is a macro which uses it's argument directly
387 * as an array index. Therefore we need to make sure that high-bit
388 * characters generate +ve values, and ideally we also want to make
389 * the argument match the declared parameter type of "int".
391 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
395 /*********************************************************************
397 * Function : block_acl
399 * Description : Block this request?
400 * Decide yes or no based on ACL file.
403 * 1 : dst = The proxy or gateway address this is going to.
404 * Or NULL to check all possible targets.
405 * 2 : csp = Current client state (buffers, headers, etc...)
406 * Also includes the client IP address.
408 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
410 *********************************************************************/
411 int block_acl(struct access_control_addr *dst, struct client_state *csp)
413 struct access_control_list *acl = csp->config->acl;
415 /* if not using an access control list, then permit the connection */
421 /* search the list */
424 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
428 /* Just want to check if they have any access */
429 if (acl->action == ACL_PERMIT)
434 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
435 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
437 if (acl->action == ACL_PERMIT)
455 /*********************************************************************
457 * Function : acl_addr
459 * Description : Called from `load_aclfile' to parse an ACL address.
462 * 1 : aspec = String specifying ACL address.
463 * 2 : aca = struct access_control_addr to fill in.
465 * Returns : 0 => Ok, everything else is an error.
467 *********************************************************************/
468 int acl_addr(char *aspec, struct access_control_addr *aca)
470 int i, masklength, port;
476 if ((p = strchr(aspec, '/')))
480 if (ijb_isdigit(*p) == 0)
484 masklength = atoi(p);
487 if ((masklength < 0) || (masklength > 32))
492 if ((p = strchr(aspec, ':')))
496 if (ijb_isdigit(*p) == 0)
505 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
509 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
513 /* build the netmask */
515 for (i=1; i <= masklength ; i++)
517 aca->mask |= (1 << (32 - i));
520 /* now mask off the host portion of the ip address
521 * (i.e. save on the network portion of the address).
523 aca->addr = aca->addr & aca->mask;
528 #endif /* def FEATURE_ACL */
531 /*********************************************************************
533 * Function : match_portlist
535 * Description : Check if a given number is covered by a comma
536 * separated list of numbers and ranges (a,b-c,d,..)
539 * 1 : portlist = String with list
540 * 2 : port = port to check
542 * Returns : 0 => no match
545 *********************************************************************/
546 int match_portlist(const char *portlist, int port)
548 char *min, *max, *next, *portlist_copy;
550 min = next = portlist_copy = strdup(portlist);
553 * Zero-terminate first item and remember offset for next
555 if (NULL != (next = strchr(portlist_copy, (int) ',')))
561 * Loop through all items, checking for match
565 if (NULL == (max = strchr(min, (int) '-')))
568 * No dash, check for equality
570 if (port == atoi(min))
579 * This is a range, so check if between min and max,
580 * or, if max was omitted, between min and 65K
583 if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
597 * Zero-terminate next item and remember offset for n+1
599 if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
611 /*********************************************************************
613 * Function : block_url
615 * Description : Called from `chat'. Check to see if we need to block this.
618 * 1 : csp = Current client state (buffers, headers, etc...)
620 * Returns : NULL => unblocked, else HTTP block response
622 *********************************************************************/
623 struct http_response *block_url(struct client_state *csp)
625 #ifdef FEATURE_IMAGE_BLOCKING
627 #endif /* def FEATURE_IMAGE_BLOCKING */
628 struct http_response *rsp;
631 * If it's not blocked, don't block it ;-)
633 if ((csp->action->flags & ACTION_BLOCK) == 0)
639 * Else, prepare a response
641 if (NULL == (rsp = alloc_http_response()))
643 return cgi_error_memory();
647 * If it's an image-url, send back an image or redirect
648 * as specified by the relevant +image action
650 #ifdef FEATURE_IMAGE_BLOCKING
651 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
654 /* determine HOW images should be blocked */
655 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
657 /* and handle accordingly: */
658 if ((p == NULL) || (0 == strcmpic(p, "logo")))
660 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
661 if (rsp->body == NULL)
663 free_http_response(rsp);
664 return cgi_error_memory();
666 rsp->content_length = image_junkbuster_gif_length;
668 if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
670 free_http_response(rsp);
671 return cgi_error_memory();
675 else if (0 == strcmpic(p, "blank"))
677 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
678 if (rsp->body == NULL)
680 free_http_response(rsp);
681 return cgi_error_memory();
683 rsp->content_length = image_blank_gif_length;
685 if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
687 free_http_response(rsp);
688 return cgi_error_memory();
694 rsp->status = strdup("302 Local Redirect from Junkbuster");
695 if (rsp->status == NULL)
697 free_http_response(rsp);
698 return cgi_error_memory();
701 if (enlist_unique_header(rsp->headers, "Location", p))
703 free_http_response(rsp);
704 return cgi_error_memory();
709 #endif /* def FEATURE_IMAGE_BLOCKING */
712 * Else, generate an HTML "blocked" message:
716 struct map * exports;
719 * Workaround for stupid Netscape bug which prevents
720 * pages from being displayed if loading a referenced
721 * JavaScript or style sheet fails. So make it appear
722 * as if it succeeded.
724 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
725 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
726 && !strstr(p, "Gecko") /* save Mozilla, */
727 && !strstr(p, "compatible") /* MSIE */
728 && !strstr(p, "Opera")) /* and Opera. */
730 rsp->status = strdup("200 Request for blocked URL");
734 rsp->status = strdup("404 Request for blocked URL");
737 if (rsp->status == NULL)
739 free_http_response(rsp);
740 return cgi_error_memory();
743 exports = default_exports(csp, NULL);
746 free_http_response(rsp);
747 return cgi_error_memory();
750 #ifdef FEATURE_FORCE_LOAD
751 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
752 #else /* ifndef FEATURE_FORCE_LOAD */
753 err = map_block_killer(exports, "force-support");
754 #endif /* ndef FEATURE_FORCE_LOAD */
756 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
757 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
762 free_http_response(rsp);
763 return cgi_error_memory();
766 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
769 free_http_response(rsp);
770 return cgi_error_memory();
774 return finish_http_response(rsp);
780 /*********************************************************************
782 * Function : trust_url FIXME: I should be called distrust_url
784 * Description : Calls is_untrusted_url to determine if the URL is trusted
785 * and if not, returns a HTTP 304 response with a reject message.
788 * 1 : csp = Current client state (buffers, headers, etc...)
790 * Returns : NULL => trusted, else http_response.
792 *********************************************************************/
793 struct http_response *trust_url(struct client_state *csp)
795 struct http_response *rsp;
796 struct map * exports;
797 char buf[BUFFER_SIZE];
799 struct url_spec **tl;
804 * Don't bother to work on trusted URLs
806 if (!is_untrusted_url(csp))
812 * Else, prepare a response:
814 if (NULL == (rsp = alloc_http_response()))
816 return cgi_error_memory();
819 exports = default_exports(csp, NULL);
822 free_http_response(rsp);
823 return cgi_error_memory();
827 * Export the host, port, and referrer information
829 err = map(exports, "hostport", 1, csp->http->hostport, 1);
830 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
832 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
834 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
838 if (!err) err = map(exports, "referrer", 1, "unknown", 1);
844 free_http_response(rsp);
845 return cgi_error_memory();
849 * Export the trust list
852 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
854 sprintf(buf, "<li>%s</li>\n", t->spec);
855 string_append(&p, buf);
857 err = map(exports, "trusted-referrers", 1, p, 0);
862 free_http_response(rsp);
863 return cgi_error_memory();
867 * Export the trust info, if available
869 if (csp->config->trust_info->first)
871 struct list_entry *l;
874 for (l = csp->config->trust_info->first; l ; l = l->next)
876 sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
877 string_append(&p, buf);
879 err = map(exports, "trust-info", 1, p, 0);
883 err = map_block_killer(exports, "have-trust-info");
889 free_http_response(rsp);
890 return cgi_error_memory();
894 * Export the force prefix or the force conditional block killer
896 #ifdef FEATURE_FORCE_LOAD
897 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
898 #else /* ifndef FEATURE_FORCE_LOAD */
899 err = map_block_killer(exports, "force-support");
900 #endif /* ndef FEATURE_FORCE_LOAD */
905 free_http_response(rsp);
906 return cgi_error_memory();
912 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
915 free_http_response(rsp);
916 return cgi_error_memory();
919 return finish_http_response(rsp);
921 #endif /* def FEATURE_TRUST */
924 #ifdef FEATURE_FAST_REDIRECTS
925 /*********************************************************************
927 * Function : redirect_url
929 * Description : Checks for redirection URLs and returns a HTTP redirect
930 * to the destination URL, if necessary
933 * 1 : csp = Current client state (buffers, headers, etc...)
935 * Returns : NULL if URL was clean, HTTP redirect otherwise.
937 *********************************************************************/
938 struct http_response *redirect_url(struct client_state *csp)
941 struct http_response *rsp;
943 p = q = csp->http->path;
944 log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
947 * find the last URL encoded in the request
949 while ((p = strstr(p, "http://")))
955 * if there was any, generate and return a HTTP redirect
957 if (q != csp->http->path)
959 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
961 if (NULL == (rsp = alloc_http_response()))
963 return cgi_error_memory();
966 if ( enlist_unique_header(rsp->headers, "Location", q)
967 || (NULL == (rsp->status = strdup("302 Local Redirect from Junkbuster"))) )
969 free_http_response(rsp);
970 return cgi_error_memory();
973 return finish_http_response(rsp);
981 #endif /* def FEATURE_FAST_REDIRECTS */
984 #ifdef FEATURE_IMAGE_BLOCKING
985 /*********************************************************************
987 * Function : is_imageurl
989 * Description : Given a URL, decide whether it is an image or not,
990 * using either the info from a previous +image action
991 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
992 * the browser's accept header.
995 * 1 : csp = Current client state (buffers, headers, etc...)
997 * Returns : True (nonzero) if URL is an image, false (0)
1000 *********************************************************************/
1001 int is_imageurl(struct client_state *csp)
1003 #ifdef FEATURE_IMAGE_DETECT_MSIE
1006 tmp = get_header_value(csp->headers, "User-Agent:");
1007 if (tmp && strstr(tmp, "MSIE"))
1009 tmp = get_header_value(csp->headers, "Accept:");
1010 if (tmp && strstr(tmp, "image/gif"))
1012 /* Client will accept HTML. If this seems counterintuitive,
1022 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1024 return ((csp->action->flags & ACTION_IMAGE) != 0);
1027 #endif /* def FEATURE_IMAGE_BLOCKING */
1030 #ifdef FEATURE_COOKIE_JAR
1031 /*********************************************************************
1033 * Function : is_untrusted_url
1035 * Description : Should we "distrust" this URL (and block it)?
1037 * Yes if it matches a line in the trustfile, or if the
1038 * referrer matches a line starting with "+" in the
1043 * 1 : csp = Current client state (buffers, headers, etc...)
1045 * Returns : 0 => trusted, 1 => untrusted
1047 *********************************************************************/
1048 int is_untrusted_url(struct client_state *csp)
1050 struct file_list *fl;
1051 struct block_spec *b;
1052 struct url_spec **trusted_url;
1053 struct http_request rhttp[1];
1054 const char * referer;
1058 * If we don't have a trustlist, we trust everybody
1060 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1065 memset(rhttp, '\0', sizeof(*rhttp));
1068 * Do we trust the request URL itself?
1070 for (b = b->next; b ; b = b->next)
1072 if (url_match(b->url, csp->http))
1078 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1080 /* no referrer was supplied */
1085 * If not, do we maybe trust its referrer?
1090 * Parse the URL from the referrer
1093 err = parse_http_url(referer, rhttp, csp);
1099 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1101 if (url_match(*trusted_url, rhttp))
1103 /* if the URL's referrer is from a trusted referrer, then
1104 * add the target spec to the trustfile as an unblocked
1105 * domain and return NULL (which means it's OK).
1110 if ((fp = fopen(csp->config->trustfile, "a")))
1114 char * new_entry = strdup("~");
1116 string_append(&new_entry, csp->http->hostport);
1118 path = csp->http->path;
1119 if ( (path[0] == '/')
1121 && ((path_end = strchr(path + 2, '/')) != NULL))
1123 /* since this path points into a user's home space
1124 * be sure to include this spec in the trustfile.
1126 int path_len = path_end - path; /* save offset */
1127 path = strdup(path); /* Copy string */
1130 path_end = path + path_len; /* regenerate ptr to new buffer */
1131 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1133 string_join(&new_entry, path);
1136 if (new_entry != NULL)
1138 fprintf(fp, "%s\n", new_entry);
1143 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1144 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1154 #endif /* def FEATURE_COOKIE_JAR */
1157 /*********************************************************************
1159 * Function : pcrs_filter_response
1161 * Description : Apply all the pcrs jobs from the joblist (re_filterfile)
1162 * to the text buffer that's been accumulated in
1163 * csp->iob->buf and set csp->content_length to the modified
1164 * size and raise the CSP_FLAG_MODIFIED flag if appropriate.
1167 * 1 : csp = Current client state (buffers, headers, etc...)
1169 * Returns : a pointer to the (newly allocated) modified buffer.
1170 * or NULL in case something went wrong
1172 *********************************************************************/
1173 char *pcrs_filter_response(struct client_state *csp)
1178 char *old = csp->iob->cur, *new = NULL;
1181 struct file_list *fl;
1182 struct re_filterfile_spec *b;
1185 if (csp->iob->cur >= csp->iob->eod)
1189 size = csp->iob->eod - csp->iob->cur;
1192 * If the body has a "chunked" transfer-encoding,
1193 * get rid of it first, adjusting size and iob->eod
1195 if (csp->flags & CSP_FLAG_CHUNKED)
1197 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1198 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1202 csp->iob->eod = csp->iob->cur + size;
1203 csp->flags |= CSP_FLAG_MODIFIED;
1206 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1208 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1212 if ( NULL == b->joblist )
1214 log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1218 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1219 csp->http->hostport, csp->http->path, size);
1221 /* Apply all jobs from the joblist */
1222 for (job = b->joblist; NULL != job; job = job->next)
1224 hits += pcrs_execute(job, old, size, &new, &size);
1225 if (old != csp->iob->cur) free(old);
1229 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1232 * If there were no hits, destroy our copy and let
1233 * chat() use the original in csp->iob
1241 csp->flags |= CSP_FLAG_MODIFIED;
1242 csp->content_length = size;
1250 /*********************************************************************
1252 * Function : gif_deanimate_response
1254 * Description : Deanimate the GIF image that has been accumulated in
1255 * csp->iob->buf, set csp->content_length to the modified
1256 * size and raise the CSP_FLAG_MODIFIED flag.
1259 * 1 : csp = Current client state (buffers, headers, etc...)
1261 * Returns : a pointer to the (newly allocated) modified buffer.
1262 * or NULL in case something went wrong.
1264 *********************************************************************/
1265 char *gif_deanimate_response(struct client_state *csp)
1267 struct binbuffer *in, *out;
1269 int size = csp->iob->eod - csp->iob->cur;
1272 * If the body has a "chunked" transfer-encoding,
1273 * get rid of it first, adjusting size and iob->eod
1275 if (csp->flags & CSP_FLAG_CHUNKED)
1277 log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1278 if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1282 csp->iob->eod = csp->iob->cur + size;
1283 csp->flags |= CSP_FLAG_MODIFIED;
1286 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1287 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1289 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1293 in->buffer = csp->iob->cur;
1296 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1298 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1305 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1306 csp->content_length = out->offset;
1307 csp->flags |= CSP_FLAG_MODIFIED;
1317 /*********************************************************************
1319 * Function : remove_chunked_transfer_coding
1321 * Description : In-situ remove the "chunked" transfer coding as defined
1322 * in rfc2616 from a buffer.
1325 * 1 : buffer = Pointer to the text buffer
1326 * 2 : size = Number of bytes to be processed
1328 * Returns : The new size, i.e. the number of bytes from buffer which
1329 * are occupied by the stripped body, or 0 in case something
1332 *********************************************************************/
1333 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1336 unsigned int chunksize = 0;
1337 char *from_p, *to_p;
1340 from_p = to_p = buffer;
1342 if (sscanf(buffer, "%x", &chunksize) != 1)
1344 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1348 while (chunksize > 0)
1350 if (NULL == (from_p = strstr(from_p, "\r\n")))
1352 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1355 newsize += chunksize;
1358 memmove(to_p, from_p, (size_t) chunksize);
1359 to_p = buffer + newsize;
1360 from_p += chunksize + 2;
1362 if (sscanf(from_p, "%x", &chunksize) != 1)
1364 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1369 /* FIXME: Should this get its own loglevel? */
1370 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1376 /*********************************************************************
1378 * Function : url_actions
1380 * Description : Gets the actions for this URL.
1383 * 1 : http = http_request request for blocked URLs
1384 * 2 : csp = Current client state (buffers, headers, etc...)
1388 *********************************************************************/
1389 void url_actions(struct http_request *http,
1390 struct client_state *csp)
1392 struct file_list *fl;
1393 struct url_actions *b;
1395 init_current_action(csp->action);
1397 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1402 apply_url_actions(csp->action, http, b);
1407 /*********************************************************************
1409 * Function : apply_url_actions
1411 * Description : Applies a list of URL actions.
1414 * 1 : action = Destination.
1415 * 2 : http = Current URL
1416 * 3 : b = list of URL actions to apply
1420 *********************************************************************/
1421 void apply_url_actions(struct current_action_spec *action,
1422 struct http_request *http,
1423 struct url_actions *b)
1427 /* Should never happen */
1431 for (b = b->next; NULL != b; b = b->next)
1433 if (url_match(b->url, http))
1435 merge_current_action(action, b->action);
1441 /*********************************************************************
1443 * Function : forward_url
1445 * Description : Should we forward this to another proxy?
1448 * 1 : http = http_request request for current URL
1449 * 2 : csp = Current client state (buffers, headers, etc...)
1451 * Returns : Pointer to forwarding information.
1453 *********************************************************************/
1454 const struct forward_spec * forward_url(struct http_request *http,
1455 struct client_state *csp)
1457 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1458 struct forward_spec *fwd = csp->config->forward;
1467 if (url_match(fwd->url, http))