1 const char filters_rcs[] = "$Id: filters.c,v 1.133 2010/09/14 07:16:07 fabiankeil 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', `trust_url', `gif_deanimate_response',
13 * `execute_single_pcrs_command', `rewrite_url',
16 * Copyright : Written by and Copyright (C) 2001-2010 the
17 * Privoxy team. http://www.privoxy.org/
19 * Based on the Internet Junkbuster originally written
20 * by and Copyright (C) 1997 Anonymous Coders and
21 * Junkbusters Corporation. http://www.junkbusters.com
23 * This program is free software; you can redistribute it
24 * and/or modify it under the terms of the GNU General
25 * Public License as published by the Free Software
26 * Foundation; either version 2 of the License, or (at
27 * your option) any later version.
29 * This program is distributed in the hope that it will
30 * be useful, but WITHOUT ANY WARRANTY; without even the
31 * implied warranty of MERCHANTABILITY or FITNESS FOR A
32 * PARTICULAR PURPOSE. See the GNU General Public
33 * License for more details.
35 * The GNU General Public License should be included with
36 * this file. If not, you can view it at
37 * http://www.gnu.org/copyleft/gpl.html
38 * or write to the Free Software Foundation, Inc., 59
39 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
41 *********************************************************************/
47 #include <sys/types.h>
55 #include <sys/socket.h>
56 #endif /* def HAVE_RFC2553 */
61 #endif /* ndef __OS2__ */
62 #include <netinet/in.h>
65 #endif /* ndef _WIN32 */
69 #endif /* def __OS2__ */
77 #include "jbsockets.h"
82 #include "deanimate.h"
90 const char filters_h_rcs[] = FILTERS_H_VERSION;
92 /* Fix a problem with Solaris. There should be no effect on other
94 * Solaris's isspace() is a macro which uses it's argument directly
95 * as an array index. Therefore we need to make sure that high-bit
96 * characters generate +ve values, and ideally we also want to make
97 * the argument match the declared parameter type of "int".
99 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
101 typedef char *(*filter_function_ptr)();
102 static filter_function_ptr get_filter_function(const struct client_state *csp);
103 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
104 static jb_err prepare_for_filtering(struct client_state *csp);
108 /*********************************************************************
110 * Function : sockaddr_storage_to_ip
112 * Description : Access internal structure of sockaddr_storage
115 * 1 : addr = socket address
116 * 2 : ip = IP address as array of octets in network order
117 * (it points into addr)
118 * 3 : len = length of IP address in octets
119 * 4 : port = port number in network order;
121 * Returns : 0 = no errror; -1 otherwise.
123 *********************************************************************/
124 static int sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
125 uint8_t **ip, unsigned int *len,
133 switch (addr->ss_family)
143 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
147 *port = &((struct sockaddr_in *)addr)->sin_port;
158 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
162 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
167 /* Unsupported address family */
175 /*********************************************************************
177 * Function : match_sockaddr
179 * Description : Check whether address matches network (IP address and port)
182 * 1 : network = socket address of subnework
183 * 2 : netmask = network mask as socket address
184 * 3 : address = checked socket address against given network
186 * Returns : 0 = doesn't match; 1 = does match
188 *********************************************************************/
189 static int match_sockaddr(const struct sockaddr_storage *network,
190 const struct sockaddr_storage *netmask,
191 const struct sockaddr_storage *address)
193 uint8_t *network_addr, *netmask_addr, *address_addr;
194 unsigned int addr_len;
195 in_port_t *network_port, *netmask_port, *address_port;
198 if (network->ss_family != netmask->ss_family)
200 /* This should never happen */
201 log_error(LOG_LEVEL_ERROR,
202 "Internal error at %s:%llu: network and netmask differ in family",
207 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
208 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
209 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
211 /* Check for family */
212 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
213 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
215 /* Map AF_INET6 V4MAPPED address into AF_INET */
219 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
220 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
222 /* Map AF_INET6 V4MAPPED network into AF_INET */
227 else if (network->ss_family != address->ss_family)
232 /* XXX: Port check is signaled in netmask */
233 if (*netmask_port && *network_port != *address_port)
238 /* TODO: Optimize by checking by words insted of octets */
239 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
241 if ((network_addr[i] & netmask_addr[i]) !=
242 (address_addr[i] & netmask_addr[i]))
250 #endif /* def HAVE_RFC2553 */
253 /*********************************************************************
255 * Function : block_acl
257 * Description : Block this request?
258 * Decide yes or no based on ACL file.
261 * 1 : dst = The proxy or gateway address this is going to.
262 * Or NULL to check all possible targets.
263 * 2 : csp = Current client state (buffers, headers, etc...)
264 * Also includes the client IP address.
266 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
268 *********************************************************************/
269 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
271 struct access_control_list *acl = csp->config->acl;
273 /* if not using an access control list, then permit the connection */
279 /* search the list */
284 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
286 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
292 /* Just want to check if they have any access */
293 if (acl->action == ACL_PERMIT)
301 * XXX: An undefined acl->dst is full of zeros and should be
302 * considered a wildcard address. sockaddr_storage_to_ip()
303 * fails on such destinations because of unknown sa_familly
304 * (glibc only?). However this test is not portable.
306 * So, we signal the acl->dst is wildcard in wildcard_dst.
309 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
311 ((dst->addr & acl->dst->mask) == acl->dst->addr)
312 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
316 if (acl->action == ACL_PERMIT)
334 /*********************************************************************
336 * Function : acl_addr
338 * Description : Called from `load_config' to parse an ACL address.
341 * 1 : aspec = String specifying ACL address.
342 * 2 : aca = struct access_control_addr to fill in.
344 * Returns : 0 => Ok, everything else is an error.
346 *********************************************************************/
347 int acl_addr(const char *aspec, struct access_control_addr *aca)
351 struct addrinfo hints, *result;
353 in_port_t *mask_port;
354 unsigned int addr_len;
357 #endif /* def HAVE_RFC2553 */
359 char *acl_spec = NULL;
362 /* XXX: Depend on ai_family */
370 * Use a temporary acl spec copy so we can log
371 * the unmodified original in case of parse errors.
373 acl_spec = strdup(aspec);
374 if (acl_spec == NULL)
376 /* XXX: This will be logged as parse error. */
380 if ((p = strchr(acl_spec, '/')) != NULL)
383 if (ijb_isdigit(*p) == 0)
388 masklength = atoi(p);
391 if ((masklength < 0) ||
403 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
406 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
415 p = strchr(acl_spec, ':');
419 memset(&hints, 0, sizeof(struct addrinfo));
420 hints.ai_family = AF_UNSPEC;
421 hints.ai_socktype = SOCK_STREAM;
423 i = getaddrinfo(acl_spec, ((p) ? ++p : NULL), &hints, &result);
427 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
428 acl_spec, p, gai_strerror(i));
434 /* TODO: Allow multihomed hostnames */
435 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
436 freeaddrinfo(result);
443 port = strtol(p, &endptr, 10);
445 if (port <= 0 || port > 65535 || *endptr != '\0')
452 aca->port = (unsigned long)port;
454 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
457 if (aca->addr == INADDR_NONE)
459 /* XXX: This will be logged as parse error. */
462 #endif /* def HAVE_RFC2553 */
464 /* build the netmask */
466 /* Clip masklength according to current family. */
467 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
472 aca->mask.ss_family = aca->addr.ss_family;
473 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
480 /* ACL contains a port number, check ports in the future. */
485 * XXX: This could be optimized to operate on whole words instead
486 * of octets (128-bit CPU could do it in one iteration).
489 * Octets after prefix can be ommitted because of
490 * previous initialization to zeros.
492 for (i = 0; (i < addr_len) && masklength; i++)
502 * XXX: This assumes MSB of octet is on the left side.
503 * This should be true for all architectures or solved
506 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
513 for (i=1; i <= masklength ; i++)
515 aca->mask |= (1U << (32 - i));
518 /* now mask off the host portion of the ip address
519 * (i.e. save on the network portion of the address).
521 aca->addr = aca->addr & aca->mask;
522 #endif /* def HAVE_RFC2553 */
527 #endif /* def FEATURE_ACL */
530 /*********************************************************************
532 * Function : connect_port_is_forbidden
534 * Description : Check to see if CONNECT requests to the destination
535 * port of this request are forbidden. The check is
536 * independend of the actual request method.
539 * 1 : csp = Current client state (buffers, headers, etc...)
541 * Returns : True if yes, false otherwise.
543 *********************************************************************/
544 int connect_port_is_forbidden(const struct client_state *csp)
546 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
547 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
552 /*********************************************************************
554 * Function : block_url
556 * Description : Called from `chat'. Check to see if we need to block this.
559 * 1 : csp = Current client state (buffers, headers, etc...)
561 * Returns : NULL => unblocked, else HTTP block response
563 *********************************************************************/
564 struct http_response *block_url(struct client_state *csp)
566 struct http_response *rsp;
567 const char *new_content_type = NULL;
570 * If it's not blocked, don't block it ;-)
572 if ((csp->action->flags & ACTION_BLOCK) == 0)
576 if (csp->action->flags & ACTION_REDIRECT)
578 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
581 * Else, prepare a response
583 if (NULL == (rsp = alloc_http_response()))
585 return cgi_error_memory();
589 * If it's an image-url, send back an image or redirect
590 * as specified by the relevant +image action
592 #ifdef FEATURE_IMAGE_BLOCKING
593 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
597 /* determine HOW images should be blocked */
598 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
600 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
602 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
605 /* and handle accordingly: */
606 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
608 rsp->status = strdup("403 Request blocked by Privoxy");
609 if (rsp->status == NULL)
611 free_http_response(rsp);
612 return cgi_error_memory();
614 rsp->body = bindup(image_pattern_data, image_pattern_length);
615 if (rsp->body == NULL)
617 free_http_response(rsp);
618 return cgi_error_memory();
620 rsp->content_length = image_pattern_length;
622 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
624 free_http_response(rsp);
625 return cgi_error_memory();
628 else if (0 == strcmpic(p, "blank"))
630 rsp->status = strdup("403 Request blocked by Privoxy");
631 if (rsp->status == NULL)
633 free_http_response(rsp);
634 return cgi_error_memory();
636 rsp->body = bindup(image_blank_data, image_blank_length);
637 if (rsp->body == NULL)
639 free_http_response(rsp);
640 return cgi_error_memory();
642 rsp->content_length = image_blank_length;
644 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
646 free_http_response(rsp);
647 return cgi_error_memory();
652 rsp->status = strdup("302 Local Redirect from Privoxy");
653 if (rsp->status == NULL)
655 free_http_response(rsp);
656 return cgi_error_memory();
659 if (enlist_unique_header(rsp->headers, "Location", p))
661 free_http_response(rsp);
662 return cgi_error_memory();
668 #endif /* def FEATURE_IMAGE_BLOCKING */
669 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
672 * Send empty document.
674 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
677 rsp->body = strdup(" ");
678 rsp->content_length = 1;
680 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
683 * Workaround for firefox bug 492459
684 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
685 * Return a 200 OK status for pages blocked with +handle-as-empty-document
686 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
688 rsp->status = strdup("200 Request blocked by Privoxy");
692 rsp->status = strdup("403 Request blocked by Privoxy");
695 if (rsp->status == NULL)
697 free_http_response(rsp);
698 return cgi_error_memory();
700 if (new_content_type != 0)
702 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
703 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
705 free_http_response(rsp);
706 return cgi_error_memory();
713 * Else, generate an HTML "blocked" message:
717 struct map * exports;
721 * Workaround for stupid Netscape bug which prevents
722 * pages from being displayed if loading a referenced
723 * JavaScript or style sheet fails. So make it appear
724 * as if it succeeded.
726 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
727 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
728 && !strstr(p, "Gecko") /* save Mozilla, */
729 && !strstr(p, "compatible") /* MSIE */
730 && !strstr(p, "Opera")) /* and Opera. */
732 rsp->status = strdup("200 Request for blocked URL");
736 rsp->status = strdup("403 Request for blocked URL");
739 if (rsp->status == NULL)
741 free_http_response(rsp);
742 return cgi_error_memory();
745 exports = default_exports(csp, NULL);
748 free_http_response(rsp);
749 return cgi_error_memory();
752 #ifdef FEATURE_FORCE_LOAD
753 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
755 * Export the force conditional block killer if
757 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
758 * - Privoxy is configured to enforce blocks, or
759 * - it's a CONNECT request and enforcing wouldn't work anyway.
761 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
762 || (0 == strcmpic(csp->http->gpc, "connect")))
763 #endif /* ndef FEATURE_FORCE_LOAD */
765 err = map_block_killer(exports, "force-support");
768 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
769 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
770 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
771 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
774 const char *block_reason;
775 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
777 block_reason = csp->action->string[ACTION_STRING_BLOCK];
781 assert(connect_port_is_forbidden(csp));
782 block_reason = "Forbidden CONNECT port.";
784 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
789 free_http_response(rsp);
790 return cgi_error_memory();
793 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
796 free_http_response(rsp);
797 return cgi_error_memory();
800 rsp->crunch_reason = BLOCKED;
802 return finish_http_response(csp, rsp);
808 /*********************************************************************
810 * Function : trust_url FIXME: I should be called distrust_url
812 * Description : Calls is_untrusted_url to determine if the URL is trusted
813 * and if not, returns a HTTP 403 response with a reject message.
816 * 1 : csp = Current client state (buffers, headers, etc...)
818 * Returns : NULL => trusted, else http_response.
820 *********************************************************************/
821 struct http_response *trust_url(struct client_state *csp)
823 struct http_response *rsp;
824 struct map * exports;
825 char buf[BUFFER_SIZE];
827 struct url_spec **tl;
832 * Don't bother to work on trusted URLs
834 if (!is_untrusted_url(csp))
840 * Else, prepare a response:
842 if (NULL == (rsp = alloc_http_response()))
844 return cgi_error_memory();
847 rsp->status = strdup("403 Request blocked by Privoxy");
848 exports = default_exports(csp, NULL);
849 if (exports == NULL || rsp->status == NULL)
851 free_http_response(rsp);
852 return cgi_error_memory();
856 * Export the protocol, host, port, and referrer information
858 err = map(exports, "hostport", 1, csp->http->hostport, 1);
859 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
860 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
862 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
864 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
868 if (!err) err = map(exports, "referrer", 1, "none set", 1);
874 free_http_response(rsp);
875 return cgi_error_memory();
879 * Export the trust list
882 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
884 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
885 string_append(&p, buf);
887 err = map(exports, "trusted-referrers", 1, p, 0);
892 free_http_response(rsp);
893 return cgi_error_memory();
897 * Export the trust info, if available
899 if (csp->config->trust_info->first)
901 struct list_entry *l;
904 for (l = csp->config->trust_info->first; l ; l = l->next)
906 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
907 string_append(&p, buf);
909 err = map(exports, "trust-info", 1, p, 0);
913 err = map_block_killer(exports, "have-trust-info");
919 free_http_response(rsp);
920 return cgi_error_memory();
924 * Export the force conditional block killer if
926 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
927 * - Privoxy is configured to enforce blocks, or
928 * - it's a CONNECT request and enforcing wouldn't work anyway.
930 #ifdef FEATURE_FORCE_LOAD
931 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
932 || (0 == strcmpic(csp->http->gpc, "connect")))
934 err = map_block_killer(exports, "force-support");
938 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
940 #else /* ifndef FEATURE_FORCE_LOAD */
941 err = map_block_killer(exports, "force-support");
942 #endif /* ndef FEATURE_FORCE_LOAD */
947 free_http_response(rsp);
948 return cgi_error_memory();
954 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
957 free_http_response(rsp);
958 return cgi_error_memory();
960 rsp->crunch_reason = UNTRUSTED;
962 return finish_http_response(csp, rsp);
964 #endif /* def FEATURE_TRUST */
967 /*********************************************************************
969 * Function : compile_dynamic_pcrs_job_list
971 * Description : Compiles a dynamic pcrs job list (one with variables
972 * resolved at request time)
975 * 1 : csp = Current client state (buffers, headers, etc...)
976 * 2 : b = The filter list to compile
978 * Returns : NULL in case of errors, otherwise the
981 *********************************************************************/
982 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
984 struct list_entry *pattern;
985 pcrs_job *job_list = NULL;
986 pcrs_job *dummy = NULL;
987 pcrs_job *lastjob = NULL;
990 const struct pcrs_variable variables[] =
992 {"url", csp->http->url, 1},
993 {"path", csp->http->path, 1},
994 {"host", csp->http->host, 1},
995 {"origin", csp->ip_addr_str, 1},
999 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
1001 assert(pattern->str != NULL);
1003 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
1007 log_error(LOG_LEVEL_ERROR,
1008 "Adding filter job \'%s\' to dynamic filter %s failed: %s",
1009 pattern->str, b->name, pcrs_strerror(error));
1014 if (error == PCRS_WARN_TRUNCATION)
1016 log_error(LOG_LEVEL_ERROR,
1017 "At least one of the variables in \'%s\' had to "
1018 "be truncated before compilation", pattern->str);
1020 if (job_list == NULL)
1026 lastjob->next = dummy;
1036 /*********************************************************************
1038 * Function : rewrite_url
1040 * Description : Rewrites a URL with a single pcrs command
1041 * and returns the result if it differs from the
1042 * original and isn't obviously invalid.
1045 * 1 : old_url = URL to rewrite.
1046 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1049 * Returns : NULL if the pcrs_command didn't change the url, or
1050 * the result of the modification.
1052 *********************************************************************/
1053 char *rewrite_url(char *old_url, const char *pcrs_command)
1055 char *new_url = NULL;
1059 assert(pcrs_command);
1061 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1065 log_error(LOG_LEVEL_REDIRECTS,
1066 "pcrs command \"%s\" didn't change \"%s\".",
1067 pcrs_command, old_url);
1072 log_error(LOG_LEVEL_REDIRECTS,
1073 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1074 pcrs_command, old_url, pcrs_strerror(hits));
1077 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1079 log_error(LOG_LEVEL_ERROR,
1080 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1081 "but the result doesn't look like a valid URL and will be ignored.",
1082 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1087 log_error(LOG_LEVEL_REDIRECTS,
1088 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1089 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1097 #ifdef FEATURE_FAST_REDIRECTS
1098 /*********************************************************************
1100 * Function : get_last_url
1102 * Description : Search for the last URL inside a string.
1103 * If the string already is a URL, it will
1104 * be the first URL found.
1107 * 1 : subject = the string to check
1108 * 2 : redirect_mode = +fast-redirect{} mode
1110 * Returns : NULL if no URL was found, or
1111 * the last URL found.
1113 *********************************************************************/
1114 char *get_last_url(char *subject, const char *redirect_mode)
1116 char *new_url = NULL;
1120 assert(redirect_mode);
1122 subject = strdup(subject);
1123 if (subject == NULL)
1125 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1129 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1131 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1132 new_url = url_decode(subject);
1133 if (new_url != NULL)
1140 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1144 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1147 * Find the last URL encoded in the request
1150 while ((tmp = strstr(tmp, "http://")) != NULL)
1154 tmp = (new_url != NULL) ? new_url : subject;
1155 while ((tmp = strstr(tmp, "https://")) != NULL)
1160 if ((new_url != NULL)
1161 && ( (new_url != subject)
1162 || (0 == strncmpic(subject, "http://", 7))
1163 || (0 == strncmpic(subject, "https://", 8))
1167 * Return new URL if we found a redirect
1168 * or if the subject already was a URL.
1170 * The second case makes sure that we can
1171 * chain get_last_url after another redirection check
1172 * (like rewrite_url) without losing earlier redirects.
1174 new_url = strdup(new_url);
1183 #endif /* def FEATURE_FAST_REDIRECTS */
1186 /*********************************************************************
1188 * Function : redirect_url
1190 * Description : Checks if Privoxy should answer the request with
1191 * a HTTP redirect and generates the redirect if
1195 * 1 : csp = Current client state (buffers, headers, etc...)
1197 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1199 *********************************************************************/
1200 struct http_response *redirect_url(struct client_state *csp)
1202 struct http_response *rsp;
1203 #ifdef FEATURE_FAST_REDIRECTS
1205 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1206 * as compile-time option? The user can easily disable
1207 * it in his action file.
1209 char * redirect_mode;
1210 #endif /* def FEATURE_FAST_REDIRECTS */
1211 char *old_url = NULL;
1212 char *new_url = NULL;
1213 char *redirection_string;
1215 if ((csp->action->flags & ACTION_REDIRECT))
1217 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1220 * If the redirection string begins with 's',
1221 * assume it's a pcrs command, otherwise treat it as
1222 * properly formatted URL and use it for the redirection
1225 * According to RFC 2616 section 14.30 the URL
1226 * has to be absolute and if the user tries:
1227 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1228 * she would get undefined results anyway.
1232 if (*redirection_string == 's')
1234 old_url = csp->http->url;
1235 new_url = rewrite_url(old_url, redirection_string);
1239 log_error(LOG_LEVEL_REDIRECTS,
1240 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1241 redirection_string);
1242 new_url = strdup(redirection_string);
1246 #ifdef FEATURE_FAST_REDIRECTS
1247 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1249 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1252 * If it exists, use the previously rewritten URL as input
1253 * otherwise just use the old path.
1255 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1256 new_url = get_last_url(old_url, redirect_mode);
1261 * Disable redirect checkers, so that they
1262 * will be only run more than once if the user
1263 * also enables them through tags.
1265 * From a performance point of view
1266 * it doesn't matter, but the duplicated
1267 * log messages are annoying.
1269 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1270 #endif /* def FEATURE_FAST_REDIRECTS */
1271 csp->action->flags &= ~ACTION_REDIRECT;
1273 /* Did any redirect action trigger? */
1276 if (0 == strcmpic(new_url, csp->http->url))
1278 log_error(LOG_LEVEL_ERROR,
1279 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1280 csp->http->url, new_url);
1285 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1287 if (NULL == (rsp = alloc_http_response()))
1290 return cgi_error_memory();
1293 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1294 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1297 free_http_response(rsp);
1298 return cgi_error_memory();
1300 rsp->crunch_reason = REDIRECTED;
1303 return finish_http_response(csp, rsp);
1307 /* Only reached if no redirect is required */
1313 #ifdef FEATURE_IMAGE_BLOCKING
1314 /*********************************************************************
1316 * Function : is_imageurl
1318 * Description : Given a URL, decide whether it is an image or not,
1319 * using either the info from a previous +image action
1320 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1321 * is MSIE and not on a Mac, tell from the browser's accept
1325 * 1 : csp = Current client state (buffers, headers, etc...)
1327 * Returns : True (nonzero) if URL is an image, false (0)
1330 *********************************************************************/
1331 int is_imageurl(const struct client_state *csp)
1333 #ifdef FEATURE_IMAGE_DETECT_MSIE
1336 tmp = get_header_value(csp->headers, "User-Agent:");
1337 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1339 tmp = get_header_value(csp->headers, "Accept:");
1340 if (tmp && strstr(tmp, "image/gif"))
1342 /* Client will accept HTML. If this seems counterintuitive,
1352 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1354 return ((csp->action->flags & ACTION_IMAGE) != 0);
1357 #endif /* def FEATURE_IMAGE_BLOCKING */
1360 #ifdef FEATURE_TRUST
1361 /*********************************************************************
1363 * Function : is_untrusted_url
1365 * Description : Should we "distrust" this URL (and block it)?
1367 * Yes if it matches a line in the trustfile, or if the
1368 * referrer matches a line starting with "+" in the
1373 * 1 : csp = Current client state (buffers, headers, etc...)
1375 * Returns : 0 => trusted, 1 => untrusted
1377 *********************************************************************/
1378 int is_untrusted_url(const struct client_state *csp)
1380 struct file_list *fl;
1381 struct block_spec *b;
1382 struct url_spec **trusted_url;
1383 struct http_request rhttp[1];
1384 const char * referer;
1388 * If we don't have a trustlist, we trust everybody
1390 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1395 memset(rhttp, '\0', sizeof(*rhttp));
1398 * Do we trust the request URL itself?
1400 for (b = b->next; b ; b = b->next)
1402 if (url_match(b->url, csp->http))
1408 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1410 /* no referrer was supplied */
1416 * If not, do we maybe trust its referrer?
1418 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1424 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1426 if (url_match(*trusted_url, rhttp))
1428 /* if the URL's referrer is from a trusted referrer, then
1429 * add the target spec to the trustfile as an unblocked
1430 * domain and return 0 (which means it's OK).
1435 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1439 char * new_entry = strdup("~");
1441 string_append(&new_entry, csp->http->hostport);
1443 path = csp->http->path;
1444 if ( (path[0] == '/')
1446 && ((path_end = strchr(path + 2, '/')) != NULL))
1448 /* since this path points into a user's home space
1449 * be sure to include this spec in the trustfile.
1451 long path_len = path_end - path; /* save offset */
1452 path = strdup(path); /* Copy string */
1455 path_end = path + path_len; /* regenerate ptr to new buffer */
1456 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1458 string_join(&new_entry, path);
1462 * Give a reason for generating this entry.
1464 string_append(&new_entry, " # Trusted referrer was: ");
1465 string_append(&new_entry, referer);
1467 if (new_entry != NULL)
1469 if (-1 == fprintf(fp, "%s\n", new_entry))
1471 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1472 new_entry, csp->config->trustfile);
1478 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1479 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1486 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1487 csp->http->hostport, csp->config->trustfile);
1495 #endif /* def FEATURE_TRUST */
1498 /*********************************************************************
1500 * Function : pcrs_filter_response
1502 * Description : Execute all text substitutions from all applying
1503 * +filter actions on the text buffer that's been
1504 * accumulated in csp->iob->buf.
1507 * 1 : csp = Current client state (buffers, headers, etc...)
1509 * Returns : a pointer to the (newly allocated) modified buffer.
1510 * or NULL if there were no hits or something went wrong
1512 *********************************************************************/
1513 static char *pcrs_filter_response(struct client_state *csp)
1517 size_t size, prev_size;
1523 struct file_list *fl;
1524 struct re_filterfile_spec *b;
1525 struct list_entry *filtername;
1530 if (csp->iob->cur >= csp->iob->eod)
1535 if (filters_available(csp) == FALSE)
1537 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1538 "content filtering enabled, but no content filters available.");
1542 size = (size_t)(csp->iob->eod - csp->iob->cur);
1543 old = csp->iob->cur;
1545 for (i = 0; i < MAX_AF_FILES; i++)
1548 if ((NULL == fl) || (NULL == fl->f))
1551 * Either there are no filter files
1552 * left, or this filter file just
1553 * contains no valid filters.
1555 * Continue to be sure we don't miss
1556 * valid filter files that are chained
1557 * after empty or invalid ones.
1562 * For all applying +filter actions, look if a filter by that
1563 * name exists and if yes, execute it's pcrs_joblist on the
1566 for (b = fl->f; b; b = b->next)
1568 if (b->type != FT_CONTENT_FILTER)
1570 /* Skip header filters */
1574 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1575 filtername ; filtername = filtername->next)
1577 if (strcmp(b->name, filtername->str) == 0)
1579 int current_hits = 0; /* Number of hits caused by this filter */
1580 int job_number = 0; /* Which job we're currently executing */
1581 int job_hits = 0; /* How many hits the current job caused */
1582 pcrs_job *joblist = b->joblist;
1584 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1586 if (NULL == joblist)
1588 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1593 /* Apply all jobs from the joblist */
1594 for (job = joblist; NULL != job; job = job->next)
1597 job_hits = pcrs_execute(job, old, size, &new, &size);
1602 * That went well. Continue filtering
1603 * and use the result of this job as
1604 * input for the next one.
1606 current_hits += job_hits;
1607 if (old != csp->iob->cur)
1616 * This job caused an unexpected error. Inform the user
1617 * and skip the rest of the jobs in this filter. We could
1618 * continue with the next job, but usually the jobs
1619 * depend on each other or are similar enough to
1620 * fail for the same reason.
1622 * At the moment our pcrs expects the error codes of pcre 3.4,
1623 * but newer pcre versions can return additional error codes.
1624 * As a result pcrs_strerror()'s error message might be
1625 * "Unknown error ...", therefore we print the numerical value
1628 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1629 * should we use LOG_LEVEL_RE_FILTER instead?
1631 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1632 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1637 if (b->dynamic) pcrs_free_joblist(joblist);
1639 log_error(LOG_LEVEL_RE_FILTER,
1640 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1641 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1643 hits += current_hits;
1650 * If there were no hits, destroy our copy and let
1651 * chat() use the original in csp->iob
1659 csp->flags |= CSP_FLAG_MODIFIED;
1660 csp->content_length = size;
1668 /*********************************************************************
1670 * Function : gif_deanimate_response
1672 * Description : Deanimate the GIF image that has been accumulated in
1673 * csp->iob->buf, set csp->content_length to the modified
1674 * size and raise the CSP_FLAG_MODIFIED flag.
1677 * 1 : csp = Current client state (buffers, headers, etc...)
1679 * Returns : a pointer to the (newly allocated) modified buffer.
1680 * or NULL in case something went wrong.
1682 *********************************************************************/
1683 static char *gif_deanimate_response(struct client_state *csp)
1685 struct binbuffer *in, *out;
1689 size = (size_t)(csp->iob->eod - csp->iob->cur);
1691 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1692 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1694 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1698 in->buffer = csp->iob->cur;
1701 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1703 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1710 if ((int)size == out->offset)
1712 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1716 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1718 csp->content_length = out->offset;
1719 csp->flags |= CSP_FLAG_MODIFIED;
1729 /*********************************************************************
1731 * Function : get_filter_function
1733 * Description : Decides which content filter function has
1734 * to be applied (if any).
1737 * 1 : csp = Current client state (buffers, headers, etc...)
1739 * Returns : The content filter function to run, or
1740 * NULL if no content filter is active
1742 *********************************************************************/
1743 static filter_function_ptr get_filter_function(const struct client_state *csp)
1745 filter_function_ptr filter_function = NULL;
1748 * Choose the applying filter function based on
1749 * the content type and action settings.
1751 if ((csp->content_type & CT_TEXT) &&
1752 (csp->rlist != NULL) &&
1753 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1755 filter_function = pcrs_filter_response;
1757 else if ((csp->content_type & CT_GIF) &&
1758 (csp->action->flags & ACTION_DEANIMATE))
1760 filter_function = gif_deanimate_response;
1763 return filter_function;
1767 /*********************************************************************
1769 * Function : remove_chunked_transfer_coding
1771 * Description : In-situ remove the "chunked" transfer coding as defined
1772 * in rfc2616 from a buffer.
1775 * 1 : buffer = Pointer to the text buffer
1776 * 2 : size = In: Number of bytes to be processed,
1777 * Out: Number of bytes after de-chunking.
1778 * (undefined in case of errors)
1780 * Returns : JB_ERR_OK for success,
1781 * JB_ERR_PARSE otherwise
1783 *********************************************************************/
1784 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1787 unsigned int chunksize = 0;
1788 char *from_p, *to_p;
1791 from_p = to_p = buffer;
1793 if (sscanf(buffer, "%x", &chunksize) != 1)
1795 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1796 return JB_ERR_PARSE;
1799 while (chunksize > 0U)
1801 if (NULL == (from_p = strstr(from_p, "\r\n")))
1803 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1804 return JB_ERR_PARSE;
1807 if ((newsize += chunksize) >= *size)
1809 log_error(LOG_LEVEL_ERROR,
1810 "Chunk size %d exceeds buffer size %d in \"chunked\" transfer coding",
1812 return JB_ERR_PARSE;
1816 memmove(to_p, from_p, (size_t) chunksize);
1817 to_p = buffer + newsize;
1818 from_p += chunksize + 2;
1820 if (sscanf(from_p, "%x", &chunksize) != 1)
1822 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1827 /* XXX: Should get its own loglevel. */
1828 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1837 /*********************************************************************
1839 * Function : prepare_for_filtering
1841 * Description : If necessary, de-chunks and decompresses
1842 * the content so it can get filterd.
1845 * 1 : csp = Current client state (buffers, headers, etc...)
1847 * Returns : JB_ERR_OK for success,
1848 * JB_ERR_PARSE otherwise
1850 *********************************************************************/
1851 static jb_err prepare_for_filtering(struct client_state *csp)
1853 jb_err err = JB_ERR_OK;
1856 * If the body has a "chunked" transfer-encoding,
1857 * get rid of it, adjusting size and iob->eod
1859 if (csp->flags & CSP_FLAG_CHUNKED)
1861 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1863 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1864 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1865 if (JB_ERR_OK == err)
1867 csp->iob->eod = csp->iob->cur + size;
1868 csp->flags |= CSP_FLAG_MODIFIED;
1872 return JB_ERR_PARSE;
1878 * If the body has a supported transfer-encoding,
1879 * decompress it, adjusting size and iob->eod.
1881 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1883 if (0 == csp->iob->eod - csp->iob->cur)
1885 /* Nothing left after de-chunking. */
1889 err = decompress_iob(csp);
1891 if (JB_ERR_OK == err)
1893 csp->flags |= CSP_FLAG_MODIFIED;
1894 csp->content_type &= ~CT_TABOO;
1899 * Unset CT_GZIP and CT_DEFLATE to remember not
1900 * to modify the Content-Encoding header later.
1902 csp->content_type &= ~CT_GZIP;
1903 csp->content_type &= ~CT_DEFLATE;
1912 /*********************************************************************
1914 * Function : execute_content_filters
1916 * Description : Executes a given content filter.
1919 * 1 : csp = Current client state (buffers, headers, etc...)
1921 * Returns : Pointer to the modified buffer, or
1922 * NULL if filtering failed or wasn't necessary.
1924 *********************************************************************/
1925 char *execute_content_filters(struct client_state *csp)
1927 filter_function_ptr content_filter;
1929 assert(content_filters_enabled(csp->action));
1931 if (0 == csp->iob->eod - csp->iob->cur)
1934 * No content (probably status code 301, 302 ...),
1935 * no filtering necessary.
1940 if (JB_ERR_OK != prepare_for_filtering(csp))
1943 * failed to de-chunk or decompress.
1948 if (0 == csp->iob->eod - csp->iob->cur)
1951 * Clown alarm: chunked and/or compressed nothing delivered.
1956 content_filter = get_filter_function(csp);
1958 return ((*content_filter)(csp));
1962 /*********************************************************************
1964 * Function : get_url_actions
1966 * Description : Gets the actions for this URL.
1969 * 1 : csp = Current client state (buffers, headers, etc...)
1970 * 2 : http = http_request request for blocked URLs
1974 *********************************************************************/
1975 void get_url_actions(struct client_state *csp, struct http_request *http)
1977 struct file_list *fl;
1978 struct url_actions *b;
1981 init_current_action(csp->action);
1983 for (i = 0; i < MAX_AF_FILES; i++)
1985 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
1990 apply_url_actions(csp->action, http, b);
1997 /*********************************************************************
1999 * Function : apply_url_actions
2001 * Description : Applies a list of URL actions.
2004 * 1 : action = Destination.
2005 * 2 : http = Current URL
2006 * 3 : b = list of URL actions to apply
2010 *********************************************************************/
2011 void apply_url_actions(struct current_action_spec *action,
2012 struct http_request *http,
2013 struct url_actions *b)
2017 /* Should never happen */
2021 for (b = b->next; NULL != b; b = b->next)
2023 if (url_match(b->url, http))
2025 merge_current_action(action, b->action);
2031 /*********************************************************************
2033 * Function : get_forward_override_settings
2035 * Description : Returns forward settings as specified with the
2036 * forward-override{} action. forward-override accepts
2037 * forward lines similar to the one used in the
2038 * configuration file, but without the URL pattern.
2044 * in the configuration file can be replaced with
2045 * the action section:
2047 * {+forward-override{forward .}}
2051 * 1 : csp = Current client state (buffers, headers, etc...)
2053 * Returns : Pointer to forwarding structure in case of success.
2054 * Invalid syntax is fatal.
2056 *********************************************************************/
2057 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2059 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2060 char forward_settings[BUFFER_SIZE];
2061 char *http_parent = NULL;
2062 /* variable names were chosen for consistency reasons. */
2063 struct forward_spec *fwd = NULL;
2067 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2068 /* Should be enforced by load_one_actions_file() */
2069 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2071 /* Create a copy ssplit can modify */
2072 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2074 if (NULL != csp->fwd)
2077 * XXX: Currently necessary to prevent memory
2078 * leaks when the show-url-info cgi page is visited.
2080 unload_forward_spec(csp->fwd);
2084 * allocate a new forward node, valid only for
2085 * the lifetime of this request. Save its location
2086 * in csp as well, so sweep() can free it later on.
2088 fwd = csp->fwd = zalloc(sizeof(*fwd));
2091 log_error(LOG_LEVEL_FATAL,
2092 "can't allocate memory for forward-override{%s}", forward_override_line);
2093 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2097 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2098 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2100 fwd->type = SOCKS_NONE;
2102 /* Parse the parent HTTP proxy host:port */
2103 http_parent = vec[1];
2106 else if (vec_count == 3)
2108 char *socks_proxy = NULL;
2110 if (!strcasecmp(vec[0], "forward-socks4"))
2112 fwd->type = SOCKS_4;
2113 socks_proxy = vec[1];
2115 else if (!strcasecmp(vec[0], "forward-socks4a"))
2117 fwd->type = SOCKS_4A;
2118 socks_proxy = vec[1];
2120 else if (!strcasecmp(vec[0], "forward-socks5"))
2122 fwd->type = SOCKS_5;
2123 socks_proxy = vec[1];
2126 if (NULL != socks_proxy)
2128 /* Parse the SOCKS proxy host[:port] */
2129 fwd->gateway_port = 1080;
2130 parse_forwarder_address(socks_proxy,
2131 &fwd->gateway_host, &fwd->gateway_port);
2133 http_parent = vec[2];
2137 if (NULL == http_parent)
2139 log_error(LOG_LEVEL_FATAL,
2140 "Invalid forward-override syntax in: %s", forward_override_line);
2141 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2144 /* Parse http forwarding settings */
2145 if (strcmp(http_parent, ".") != 0)
2147 fwd->forward_port = 8000;
2148 parse_forwarder_address(http_parent,
2149 &fwd->forward_host, &fwd->forward_port);
2152 assert (NULL != fwd);
2154 log_error(LOG_LEVEL_CONNECT,
2155 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2161 /*********************************************************************
2163 * Function : forward_url
2165 * Description : Should we forward this to another proxy?
2168 * 1 : csp = Current client state (buffers, headers, etc...)
2169 * 2 : http = http_request request for current URL
2171 * Returns : Pointer to forwarding information.
2173 *********************************************************************/
2174 const struct forward_spec *forward_url(struct client_state *csp,
2175 const struct http_request *http)
2177 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2178 struct forward_spec *fwd = csp->config->forward;
2180 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2182 return get_forward_override_settings(csp);
2192 if (url_match(fwd->url, http))
2203 /*********************************************************************
2205 * Function : direct_response
2207 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2208 * request and if so, return a HTTP 501 to the client.
2210 * FIXME: I have a stupid name and I should handle the
2211 * requests properly. Still, what we do here is rfc-
2212 * compliant, whereas ignoring or forwarding are not.
2215 * 1 : csp = Current client state (buffers, headers, etc...)
2217 * Returns : http_response if , NULL if nonmatch or handler fail
2219 *********************************************************************/
2220 struct http_response *direct_response(struct client_state *csp)
2222 struct http_response *rsp;
2223 struct list_entry *p;
2225 if ((0 == strcmpic(csp->http->gpc, "trace"))
2226 || (0 == strcmpic(csp->http->gpc, "options")))
2228 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2230 if (!strncmpic("Max-Forwards:", p->str, 13))
2232 unsigned int max_forwards;
2235 * If it's a Max-Forwards value of zero,
2236 * we have to intercept the request.
2238 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2241 * FIXME: We could handle at least TRACE here,
2242 * but that would require a verbatim copy of
2243 * the request which we don't have anymore
2245 log_error(LOG_LEVEL_HEADER,
2246 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2249 /* Get mem for response or fail*/
2250 if (NULL == (rsp = alloc_http_response()))
2252 return cgi_error_memory();
2255 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2257 free_http_response(rsp);
2258 return cgi_error_memory();
2262 rsp->crunch_reason = UNSUPPORTED;
2264 return(finish_http_response(csp, rsp));
2273 /*********************************************************************
2275 * Function : content_requires_filtering
2277 * Description : Checks whether there are any content filters
2278 * enabled for the current request and if they
2279 * can actually be applied..
2282 * 1 : csp = Current client state (buffers, headers, etc...)
2284 * Returns : TRUE for yes, FALSE otherwise
2286 *********************************************************************/
2287 int content_requires_filtering(struct client_state *csp)
2289 if ((csp->content_type & CT_TABOO)
2290 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2296 * Are we enabling text mode by force?
2298 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2301 * Do we really have to?
2303 if (csp->content_type & CT_TEXT)
2305 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2309 csp->content_type |= CT_TEXT;
2310 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2314 if (!(csp->content_type & CT_DECLARED))
2317 * The server didn't bother to declare a MIME-Type.
2318 * Assume it's text that can be filtered.
2320 * This also regulary happens with 304 responses,
2321 * therefore logging anything here would cause
2324 csp->content_type |= CT_TEXT;
2328 * Choose the applying filter function based on
2329 * the content type and action settings.
2331 if ((csp->content_type & CT_TEXT) &&
2332 (csp->rlist != NULL) &&
2333 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2337 else if ((csp->content_type & CT_GIF) &&
2338 (csp->action->flags & ACTION_DEANIMATE))
2348 /*********************************************************************
2350 * Function : content_filters_enabled
2352 * Description : Checks whether there are any content filters
2353 * enabled for the current request.
2356 * 1 : action = Action spec to check.
2358 * Returns : TRUE for yes, FALSE otherwise
2360 *********************************************************************/
2361 int content_filters_enabled(const struct current_action_spec *action)
2363 return ((action->flags & ACTION_DEANIMATE) ||
2364 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));
2368 /*********************************************************************
2370 * Function : filters_available
2372 * Description : Checks whether there are any filters available.
2375 * 1 : csp = Current client state (buffers, headers, etc...)
2377 * Returns : TRUE for yes, FALSE otherwise.
2379 *********************************************************************/
2380 int filters_available(const struct client_state *csp)
2383 for (i = 0; i < MAX_AF_FILES; i++)
2385 const struct file_list *fl = csp->rlist[i];
2386 if ((NULL != fl) && (NULL != fl->f))