1 const char filters_rcs[] = "$Id: filters.c,v 1.162 2011/12/26 17:02:54 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-2011 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>
56 #endif /* ndef __OS2__ */
57 #include <netinet/in.h>
60 #endif /* ndef _WIN32 */
64 #endif /* def __OS2__ */
72 #include "jbsockets.h"
77 #include "deanimate.h"
85 const char filters_h_rcs[] = FILTERS_H_VERSION;
87 /* Fix a problem with Solaris. There should be no effect on other
89 * Solaris's isspace() is a macro which uses it's argument directly
90 * as an array index. Therefore we need to make sure that high-bit
91 * characters generate +ve values, and ideally we also want to make
92 * the argument match the declared parameter type of "int".
94 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
96 typedef char *(*filter_function_ptr)();
97 static filter_function_ptr get_filter_function(const struct client_state *csp);
98 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
99 static jb_err prepare_for_filtering(struct client_state *csp);
103 /*********************************************************************
105 * Function : sockaddr_storage_to_ip
107 * Description : Access internal structure of sockaddr_storage
110 * 1 : addr = socket address
111 * 2 : ip = IP address as array of octets in network order
112 * (it points into addr)
113 * 3 : len = length of IP address in octets
114 * 4 : port = port number in network order;
116 * Returns : 0 = no errror; -1 otherwise.
118 *********************************************************************/
119 static int sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
120 uint8_t **ip, unsigned int *len,
128 switch (addr->ss_family)
138 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
142 *port = &((struct sockaddr_in *)addr)->sin_port;
153 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
157 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
162 /* Unsupported address family */
170 /*********************************************************************
172 * Function : match_sockaddr
174 * Description : Check whether address matches network (IP address and port)
177 * 1 : network = socket address of subnework
178 * 2 : netmask = network mask as socket address
179 * 3 : address = checked socket address against given network
181 * Returns : 0 = doesn't match; 1 = does match
183 *********************************************************************/
184 static int match_sockaddr(const struct sockaddr_storage *network,
185 const struct sockaddr_storage *netmask,
186 const struct sockaddr_storage *address)
188 uint8_t *network_addr, *netmask_addr, *address_addr;
189 unsigned int addr_len;
190 in_port_t *network_port, *netmask_port, *address_port;
193 if (network->ss_family != netmask->ss_family)
195 /* This should never happen */
196 log_error(LOG_LEVEL_ERROR,
197 "Internal error at %s:%llu: network and netmask differ in family",
202 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
203 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
204 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
206 /* Check for family */
207 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
208 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
210 /* Map AF_INET6 V4MAPPED address into AF_INET */
214 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
215 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
217 /* Map AF_INET6 V4MAPPED network into AF_INET */
222 else if (network->ss_family != address->ss_family)
227 /* XXX: Port check is signaled in netmask */
228 if (*netmask_port && *network_port != *address_port)
233 /* TODO: Optimize by checking by words insted of octets */
234 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
236 if ((network_addr[i] & netmask_addr[i]) !=
237 (address_addr[i] & netmask_addr[i]))
245 #endif /* def HAVE_RFC2553 */
248 /*********************************************************************
250 * Function : block_acl
252 * Description : Block this request?
253 * Decide yes or no based on ACL file.
256 * 1 : dst = The proxy or gateway address this is going to.
257 * Or NULL to check all possible targets.
258 * 2 : csp = Current client state (buffers, headers, etc...)
259 * Also includes the client IP address.
261 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
263 *********************************************************************/
264 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
266 struct access_control_list *acl = csp->config->acl;
268 /* if not using an access control list, then permit the connection */
274 /* search the list */
279 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
281 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
287 /* Just want to check if they have any access */
288 if (acl->action == ACL_PERMIT)
300 * XXX: An undefined acl->dst is full of zeros and should be
301 * considered a wildcard address. sockaddr_storage_to_ip()
302 * fails on such destinations because of unknown sa_familly
303 * (glibc only?). However this test is not portable.
305 * So, we signal the acl->dst is wildcard in wildcard_dst.
308 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
310 ((dst->addr & acl->dst->mask) == acl->dst->addr)
311 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
315 if (acl->action == ACL_PERMIT)
333 /*********************************************************************
335 * Function : acl_addr
337 * Description : Called from `load_config' to parse an ACL address.
340 * 1 : aspec = String specifying ACL address.
341 * 2 : aca = struct access_control_addr to fill in.
343 * Returns : 0 => Ok, everything else is an error.
345 *********************************************************************/
346 int acl_addr(const char *aspec, struct access_control_addr *aca)
350 struct addrinfo hints, *result;
352 in_port_t *mask_port;
353 unsigned int addr_len;
356 #endif /* def HAVE_RFC2553 */
358 char *acl_spec = NULL;
361 /* XXX: Depend on ai_family */
369 * Use a temporary acl spec copy so we can log
370 * the unmodified original in case of parse errors.
372 acl_spec = strdup(aspec);
373 if (acl_spec == NULL)
375 /* XXX: This will be logged as parse error. */
379 if ((p = strchr(acl_spec, '/')) != NULL)
382 if (ijb_isdigit(*p) == 0)
387 masklength = atoi(p);
390 if ((masklength < 0) ||
402 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
405 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
414 p = strchr(acl_spec, ':');
418 memset(&hints, 0, sizeof(struct addrinfo));
419 hints.ai_family = AF_UNSPEC;
420 hints.ai_socktype = SOCK_STREAM;
422 i = getaddrinfo(acl_spec, ((p) ? ++p : NULL), &hints, &result);
426 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
427 acl_spec, p, gai_strerror(i));
433 /* TODO: Allow multihomed hostnames */
434 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
435 freeaddrinfo(result);
442 port = strtol(p, &endptr, 10);
444 if (port <= 0 || port > 65535 || *endptr != '\0')
451 aca->port = (unsigned long)port;
453 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
456 if (aca->addr == INADDR_NONE)
458 /* XXX: This will be logged as parse error. */
461 #endif /* def HAVE_RFC2553 */
463 /* build the netmask */
465 /* Clip masklength according to current family. */
466 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
471 aca->mask.ss_family = aca->addr.ss_family;
472 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
479 /* ACL contains a port number, check ports in the future. */
484 * XXX: This could be optimized to operate on whole words instead
485 * of octets (128-bit CPU could do it in one iteration).
488 * Octets after prefix can be omitted because of
489 * previous initialization to zeros.
491 for (i = 0; (i < addr_len) && masklength; i++)
501 * XXX: This assumes MSB of octet is on the left side.
502 * This should be true for all architectures or solved
505 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
512 for (i=1; i <= masklength ; i++)
514 aca->mask |= (1U << (32 - i));
517 /* now mask off the host portion of the ip address
518 * (i.e. save on the network portion of the address).
520 aca->addr = aca->addr & aca->mask;
521 #endif /* def HAVE_RFC2553 */
526 #endif /* def FEATURE_ACL */
529 /*********************************************************************
531 * Function : connect_port_is_forbidden
533 * Description : Check to see if CONNECT requests to the destination
534 * port of this request are forbidden. The check is
535 * independend of the actual request method.
538 * 1 : csp = Current client state (buffers, headers, etc...)
540 * Returns : True if yes, false otherwise.
542 *********************************************************************/
543 int connect_port_is_forbidden(const struct client_state *csp)
545 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
546 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
551 /*********************************************************************
553 * Function : block_url
555 * Description : Called from `chat'. Check to see if we need to block this.
558 * 1 : csp = Current client state (buffers, headers, etc...)
560 * Returns : NULL => unblocked, else HTTP block response
562 *********************************************************************/
563 struct http_response *block_url(struct client_state *csp)
565 struct http_response *rsp;
566 const char *new_content_type = NULL;
569 * If it's not blocked, don't block it ;-)
571 if ((csp->action->flags & ACTION_BLOCK) == 0)
575 if (csp->action->flags & ACTION_REDIRECT)
577 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
580 * Else, prepare a response
582 if (NULL == (rsp = alloc_http_response()))
584 return cgi_error_memory();
588 * If it's an image-url, send back an image or redirect
589 * as specified by the relevant +image action
591 #ifdef FEATURE_IMAGE_BLOCKING
592 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
596 /* determine HOW images should be blocked */
597 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
599 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
601 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
604 /* and handle accordingly: */
605 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
607 rsp->status = strdup("403 Request blocked by Privoxy");
608 if (rsp->status == NULL)
610 free_http_response(rsp);
611 return cgi_error_memory();
613 rsp->body = bindup(image_pattern_data, image_pattern_length);
614 if (rsp->body == NULL)
616 free_http_response(rsp);
617 return cgi_error_memory();
619 rsp->content_length = image_pattern_length;
621 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
623 free_http_response(rsp);
624 return cgi_error_memory();
627 else if (0 == strcmpic(p, "blank"))
629 rsp->status = strdup("403 Request blocked by Privoxy");
630 if (rsp->status == NULL)
632 free_http_response(rsp);
633 return cgi_error_memory();
635 rsp->body = bindup(image_blank_data, image_blank_length);
636 if (rsp->body == NULL)
638 free_http_response(rsp);
639 return cgi_error_memory();
641 rsp->content_length = image_blank_length;
643 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
645 free_http_response(rsp);
646 return cgi_error_memory();
651 rsp->status = strdup("302 Local Redirect from Privoxy");
652 if (rsp->status == NULL)
654 free_http_response(rsp);
655 return cgi_error_memory();
658 if (enlist_unique_header(rsp->headers, "Location", p))
660 free_http_response(rsp);
661 return cgi_error_memory();
667 #endif /* def FEATURE_IMAGE_BLOCKING */
668 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
671 * Send empty document.
673 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
676 rsp->body = strdup(" ");
677 rsp->content_length = 1;
679 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
682 * Workaround for firefox bug 492459
683 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
684 * Return a 200 OK status for pages blocked with +handle-as-empty-document
685 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
687 rsp->status = strdup("200 Request blocked by Privoxy");
691 rsp->status = strdup("403 Request blocked by Privoxy");
694 if (rsp->status == NULL)
696 free_http_response(rsp);
697 return cgi_error_memory();
699 if (new_content_type != 0)
701 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
702 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
704 free_http_response(rsp);
705 return cgi_error_memory();
712 * Else, generate an HTML "blocked" message:
716 struct map * exports;
718 rsp->status = strdup("403 Request blocked by Privoxy");
719 if (rsp->status == NULL)
721 free_http_response(rsp);
722 return cgi_error_memory();
725 exports = default_exports(csp, NULL);
728 free_http_response(rsp);
729 return cgi_error_memory();
732 #ifdef FEATURE_FORCE_LOAD
733 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
735 * Export the force conditional block killer if
737 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
738 * - Privoxy is configured to enforce blocks, or
739 * - it's a CONNECT request and enforcing wouldn't work anyway.
741 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
742 || (0 == strcmpic(csp->http->gpc, "connect")))
743 #endif /* ndef FEATURE_FORCE_LOAD */
745 err = map_block_killer(exports, "force-support");
748 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
749 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
750 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
751 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
754 const char *block_reason;
755 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
757 block_reason = csp->action->string[ACTION_STRING_BLOCK];
761 assert(connect_port_is_forbidden(csp));
762 block_reason = "Forbidden CONNECT port.";
764 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
769 free_http_response(rsp);
770 return cgi_error_memory();
773 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
776 free_http_response(rsp);
777 return cgi_error_memory();
780 rsp->crunch_reason = BLOCKED;
782 return finish_http_response(csp, rsp);
788 /*********************************************************************
790 * Function : trust_url FIXME: I should be called distrust_url
792 * Description : Calls is_untrusted_url to determine if the URL is trusted
793 * and if not, returns a HTTP 403 response with a reject message.
796 * 1 : csp = Current client state (buffers, headers, etc...)
798 * Returns : NULL => trusted, else http_response.
800 *********************************************************************/
801 struct http_response *trust_url(struct client_state *csp)
803 struct http_response *rsp;
804 struct map * exports;
805 char buf[BUFFER_SIZE];
807 struct url_spec **tl;
812 * Don't bother to work on trusted URLs
814 if (!is_untrusted_url(csp))
820 * Else, prepare a response:
822 if (NULL == (rsp = alloc_http_response()))
824 return cgi_error_memory();
827 rsp->status = strdup("403 Request blocked by Privoxy");
828 exports = default_exports(csp, NULL);
829 if (exports == NULL || rsp->status == NULL)
831 free_http_response(rsp);
832 return cgi_error_memory();
836 * Export the protocol, host, port, and referrer information
838 err = map(exports, "hostport", 1, csp->http->hostport, 1);
839 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
840 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
842 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
844 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
848 if (!err) err = map(exports, "referrer", 1, "none set", 1);
854 free_http_response(rsp);
855 return cgi_error_memory();
859 * Export the trust list
862 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
864 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
865 string_append(&p, buf);
867 err = map(exports, "trusted-referrers", 1, p, 0);
872 free_http_response(rsp);
873 return cgi_error_memory();
877 * Export the trust info, if available
879 if (csp->config->trust_info->first)
881 struct list_entry *l;
884 for (l = csp->config->trust_info->first; l ; l = l->next)
886 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
887 string_append(&p, buf);
889 err = map(exports, "trust-info", 1, p, 0);
893 err = map_block_killer(exports, "have-trust-info");
899 free_http_response(rsp);
900 return cgi_error_memory();
904 * Export the force conditional block killer if
906 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
907 * - Privoxy is configured to enforce blocks, or
908 * - it's a CONNECT request and enforcing wouldn't work anyway.
910 #ifdef FEATURE_FORCE_LOAD
911 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
912 || (0 == strcmpic(csp->http->gpc, "connect")))
914 err = map_block_killer(exports, "force-support");
918 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
920 #else /* ifndef FEATURE_FORCE_LOAD */
921 err = map_block_killer(exports, "force-support");
922 #endif /* ndef FEATURE_FORCE_LOAD */
927 free_http_response(rsp);
928 return cgi_error_memory();
934 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
937 free_http_response(rsp);
938 return cgi_error_memory();
940 rsp->crunch_reason = UNTRUSTED;
942 return finish_http_response(csp, rsp);
944 #endif /* def FEATURE_TRUST */
947 /*********************************************************************
949 * Function : compile_dynamic_pcrs_job_list
951 * Description : Compiles a dynamic pcrs job list (one with variables
952 * resolved at request time)
955 * 1 : csp = Current client state (buffers, headers, etc...)
956 * 2 : b = The filter list to compile
958 * Returns : NULL in case of errors, otherwise the
961 *********************************************************************/
962 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
964 struct list_entry *pattern;
965 pcrs_job *job_list = NULL;
966 pcrs_job *dummy = NULL;
967 pcrs_job *lastjob = NULL;
970 const struct pcrs_variable variables[] =
972 {"url", csp->http->url, 1},
973 {"path", csp->http->path, 1},
974 {"host", csp->http->host, 1},
975 {"origin", csp->ip_addr_str, 1},
979 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
981 assert(pattern->str != NULL);
983 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
986 log_error(LOG_LEVEL_ERROR,
987 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
988 pattern->str, b->name, error, pcrs_strerror(error));
993 if (error == PCRS_WARN_TRUNCATION)
995 log_error(LOG_LEVEL_ERROR,
996 "At least one of the variables in \'%s\' had to "
997 "be truncated before compilation", pattern->str);
999 if (job_list == NULL)
1005 lastjob->next = dummy;
1015 /*********************************************************************
1017 * Function : rewrite_url
1019 * Description : Rewrites a URL with a single pcrs command
1020 * and returns the result if it differs from the
1021 * original and isn't obviously invalid.
1024 * 1 : old_url = URL to rewrite.
1025 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1028 * Returns : NULL if the pcrs_command didn't change the url, or
1029 * the result of the modification.
1031 *********************************************************************/
1032 char *rewrite_url(char *old_url, const char *pcrs_command)
1034 char *new_url = NULL;
1038 assert(pcrs_command);
1040 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1044 log_error(LOG_LEVEL_REDIRECTS,
1045 "pcrs command \"%s\" didn't change \"%s\".",
1046 pcrs_command, old_url);
1051 log_error(LOG_LEVEL_REDIRECTS,
1052 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1053 pcrs_command, old_url, pcrs_strerror(hits));
1056 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1058 log_error(LOG_LEVEL_ERROR,
1059 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1060 "but the result doesn't look like a valid URL and will be ignored.",
1061 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1066 log_error(LOG_LEVEL_REDIRECTS,
1067 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1068 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1076 #ifdef FEATURE_FAST_REDIRECTS
1077 /*********************************************************************
1079 * Function : get_last_url
1081 * Description : Search for the last URL inside a string.
1082 * If the string already is a URL, it will
1083 * be the first URL found.
1086 * 1 : subject = the string to check
1087 * 2 : redirect_mode = +fast-redirect{} mode
1089 * Returns : NULL if no URL was found, or
1090 * the last URL found.
1092 *********************************************************************/
1093 char *get_last_url(char *subject, const char *redirect_mode)
1095 char *new_url = NULL;
1099 assert(redirect_mode);
1101 subject = strdup(subject);
1102 if (subject == NULL)
1104 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1108 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1110 log_error(LOG_LEVEL_REDIRECTS,
1111 "Checking \"%s\" for encoded redirects.", subject);
1114 * Check each parameter in the URL separately.
1115 * Sectionize the URL at "?" and "&",
1116 * go backwards through the segments, URL-decode them
1117 * and look for a URL in the decoded result.
1118 * Stop the search after the first match.
1120 char *url_segment = NULL;
1122 * XXX: This estimate is guaranteed to be high enough as we
1123 * let ssplit() ignore empty fields, but also a bit wasteful.
1125 size_t max_segments = strlen(subject) / 2;
1126 char **url_segments = malloc(max_segments * sizeof(char *));
1129 if (NULL == url_segments)
1131 log_error(LOG_LEVEL_ERROR, "Out of memory while decoding URL: %s", new_url);
1136 segments = ssplit(subject, "?&", url_segments, max_segments, 1, 1);
1138 while (segments-- > 0)
1140 char *dtoken = url_decode(url_segments[segments]);
1143 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1146 url_segment = strstr(dtoken, "http://");
1147 if (NULL == url_segment)
1149 url_segment = strstr(dtoken, "https://");
1151 if (NULL != url_segment)
1153 url_segment = strdup(url_segment);
1155 if (url_segment == NULL)
1157 log_error(LOG_LEVEL_ERROR,
1158 "Out of memory while searching for redirects.");
1166 freez(url_segments);
1168 if (url_segment == NULL)
1172 subject = url_segment;
1176 /* Look for a URL inside this one, without decoding anything. */
1177 log_error(LOG_LEVEL_REDIRECTS,
1178 "Checking \"%s\" for unencoded redirects.", subject);
1182 * Find the last URL encoded in the request
1185 while ((tmp = strstr(tmp, "http://")) != NULL)
1189 tmp = (new_url != NULL) ? new_url : subject;
1190 while ((tmp = strstr(tmp, "https://")) != NULL)
1195 if ((new_url != NULL)
1196 && ( (new_url != subject)
1197 || (0 == strncmpic(subject, "http://", 7))
1198 || (0 == strncmpic(subject, "https://", 8))
1202 * Return new URL if we found a redirect
1203 * or if the subject already was a URL.
1205 * The second case makes sure that we can
1206 * chain get_last_url after another redirection check
1207 * (like rewrite_url) without losing earlier redirects.
1209 new_url = strdup(new_url);
1218 #endif /* def FEATURE_FAST_REDIRECTS */
1221 /*********************************************************************
1223 * Function : redirect_url
1225 * Description : Checks if Privoxy should answer the request with
1226 * a HTTP redirect and generates the redirect if
1230 * 1 : csp = Current client state (buffers, headers, etc...)
1232 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1234 *********************************************************************/
1235 struct http_response *redirect_url(struct client_state *csp)
1237 struct http_response *rsp;
1238 #ifdef FEATURE_FAST_REDIRECTS
1240 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1241 * as compile-time option? The user can easily disable
1242 * it in his action file.
1244 char * redirect_mode;
1245 #endif /* def FEATURE_FAST_REDIRECTS */
1246 char *old_url = NULL;
1247 char *new_url = NULL;
1248 char *redirection_string;
1250 if ((csp->action->flags & ACTION_REDIRECT))
1252 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1255 * If the redirection string begins with 's',
1256 * assume it's a pcrs command, otherwise treat it as
1257 * properly formatted URL and use it for the redirection
1260 * According to RFC 2616 section 14.30 the URL
1261 * has to be absolute and if the user tries:
1262 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1263 * she would get undefined results anyway.
1267 if (*redirection_string == 's')
1269 old_url = csp->http->url;
1270 new_url = rewrite_url(old_url, redirection_string);
1274 log_error(LOG_LEVEL_REDIRECTS,
1275 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1276 redirection_string);
1277 new_url = strdup(redirection_string);
1281 #ifdef FEATURE_FAST_REDIRECTS
1282 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1284 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1287 * If it exists, use the previously rewritten URL as input
1288 * otherwise just use the old path.
1290 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1291 new_url = get_last_url(old_url, redirect_mode);
1296 * Disable redirect checkers, so that they
1297 * will be only run more than once if the user
1298 * also enables them through tags.
1300 * From a performance point of view
1301 * it doesn't matter, but the duplicated
1302 * log messages are annoying.
1304 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1305 #endif /* def FEATURE_FAST_REDIRECTS */
1306 csp->action->flags &= ~ACTION_REDIRECT;
1308 /* Did any redirect action trigger? */
1311 if (url_requires_percent_encoding(new_url))
1314 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1315 strlen(new_url), new_url);
1316 encoded_url = percent_encode_url(new_url);
1318 if (encoded_url == NULL)
1320 return cgi_error_memory();
1322 new_url = encoded_url;
1323 assert(FALSE == url_requires_percent_encoding(new_url));
1326 if (0 == strcmpic(new_url, csp->http->url))
1328 log_error(LOG_LEVEL_ERROR,
1329 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1330 csp->http->url, new_url);
1335 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1337 if (NULL == (rsp = alloc_http_response()))
1340 return cgi_error_memory();
1343 if (enlist_unique_header(rsp->headers, "Location", new_url)
1344 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))))
1347 free_http_response(rsp);
1348 return cgi_error_memory();
1350 rsp->crunch_reason = REDIRECTED;
1353 return finish_http_response(csp, rsp);
1357 /* Only reached if no redirect is required */
1363 #ifdef FEATURE_IMAGE_BLOCKING
1364 /*********************************************************************
1366 * Function : is_imageurl
1368 * Description : Given a URL, decide whether it is an image or not,
1369 * using either the info from a previous +image action
1370 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1371 * is MSIE and not on a Mac, tell from the browser's accept
1375 * 1 : csp = Current client state (buffers, headers, etc...)
1377 * Returns : True (nonzero) if URL is an image, false (0)
1380 *********************************************************************/
1381 int is_imageurl(const struct client_state *csp)
1383 #ifdef FEATURE_IMAGE_DETECT_MSIE
1386 tmp = get_header_value(csp->headers, "User-Agent:");
1387 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1389 tmp = get_header_value(csp->headers, "Accept:");
1390 if (tmp && strstr(tmp, "image/gif"))
1392 /* Client will accept HTML. If this seems counterintuitive,
1402 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1404 return ((csp->action->flags & ACTION_IMAGE) != 0);
1407 #endif /* def FEATURE_IMAGE_BLOCKING */
1410 #ifdef FEATURE_TRUST
1411 /*********************************************************************
1413 * Function : is_untrusted_url
1415 * Description : Should we "distrust" this URL (and block it)?
1417 * Yes if it matches a line in the trustfile, or if the
1418 * referrer matches a line starting with "+" in the
1423 * 1 : csp = Current client state (buffers, headers, etc...)
1425 * Returns : 0 => trusted, 1 => untrusted
1427 *********************************************************************/
1428 int is_untrusted_url(const struct client_state *csp)
1430 struct file_list *fl;
1431 struct block_spec *b;
1432 struct url_spec **trusted_url;
1433 struct http_request rhttp[1];
1434 const char * referer;
1438 * If we don't have a trustlist, we trust everybody
1440 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1445 memset(rhttp, '\0', sizeof(*rhttp));
1448 * Do we trust the request URL itself?
1450 for (b = b->next; b ; b = b->next)
1452 if (url_match(b->url, csp->http))
1458 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1460 /* no referrer was supplied */
1466 * If not, do we maybe trust its referrer?
1468 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1474 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1476 if (url_match(*trusted_url, rhttp))
1478 /* if the URL's referrer is from a trusted referrer, then
1479 * add the target spec to the trustfile as an unblocked
1480 * domain and return 0 (which means it's OK).
1485 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1489 char * new_entry = strdup("~");
1491 string_append(&new_entry, csp->http->hostport);
1493 path = csp->http->path;
1494 if ( (path[0] == '/')
1496 && ((path_end = strchr(path + 2, '/')) != NULL))
1498 /* since this path points into a user's home space
1499 * be sure to include this spec in the trustfile.
1501 long path_len = path_end - path; /* save offset */
1502 path = strdup(path); /* Copy string */
1505 path_end = path + path_len; /* regenerate ptr to new buffer */
1506 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1508 string_join(&new_entry, path);
1512 * Give a reason for generating this entry.
1514 string_append(&new_entry, " # Trusted referrer was: ");
1515 string_append(&new_entry, referer);
1517 if (new_entry != NULL)
1519 if (-1 == fprintf(fp, "%s\n", new_entry))
1521 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1522 new_entry, csp->config->trustfile);
1528 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1529 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1536 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1537 csp->http->hostport, csp->config->trustfile);
1545 #endif /* def FEATURE_TRUST */
1548 /*********************************************************************
1550 * Function : pcrs_filter_response
1552 * Description : Execute all text substitutions from all applying
1553 * +filter actions on the text buffer that's been
1554 * accumulated in csp->iob->buf.
1557 * 1 : csp = Current client state (buffers, headers, etc...)
1559 * Returns : a pointer to the (newly allocated) modified buffer.
1560 * or NULL if there were no hits or something went wrong
1562 *********************************************************************/
1563 static char *pcrs_filter_response(struct client_state *csp)
1567 size_t size, prev_size;
1573 struct file_list *fl;
1574 struct re_filterfile_spec *b;
1575 struct list_entry *filtername;
1580 if (csp->iob->cur >= csp->iob->eod)
1585 if (filters_available(csp) == FALSE)
1587 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1588 "content filtering enabled, but no content filters available.");
1592 size = (size_t)(csp->iob->eod - csp->iob->cur);
1593 old = csp->iob->cur;
1595 for (i = 0; i < MAX_AF_FILES; i++)
1598 if ((NULL == fl) || (NULL == fl->f))
1601 * Either there are no filter files
1602 * left, or this filter file just
1603 * contains no valid filters.
1605 * Continue to be sure we don't miss
1606 * valid filter files that are chained
1607 * after empty or invalid ones.
1612 * For all applying +filter actions, look if a filter by that
1613 * name exists and if yes, execute it's pcrs_joblist on the
1616 for (b = fl->f; b; b = b->next)
1618 if (b->type != FT_CONTENT_FILTER)
1620 /* Skip header filters */
1624 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1625 filtername ; filtername = filtername->next)
1627 if (strcmp(b->name, filtername->str) == 0)
1629 int current_hits = 0; /* Number of hits caused by this filter */
1630 int job_number = 0; /* Which job we're currently executing */
1631 int job_hits = 0; /* How many hits the current job caused */
1632 pcrs_job *joblist = b->joblist;
1634 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1636 if (NULL == joblist)
1638 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1643 /* Apply all jobs from the joblist */
1644 for (job = joblist; NULL != job; job = job->next)
1647 job_hits = pcrs_execute(job, old, size, &new, &size);
1652 * That went well. Continue filtering
1653 * and use the result of this job as
1654 * input for the next one.
1656 current_hits += job_hits;
1657 if (old != csp->iob->cur)
1666 * This job caused an unexpected error. Inform the user
1667 * and skip the rest of the jobs in this filter. We could
1668 * continue with the next job, but usually the jobs
1669 * depend on each other or are similar enough to
1670 * fail for the same reason.
1672 * At the moment our pcrs expects the error codes of pcre 3.4,
1673 * but newer pcre versions can return additional error codes.
1674 * As a result pcrs_strerror()'s error message might be
1675 * "Unknown error ...", therefore we print the numerical value
1678 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1679 * should we use LOG_LEVEL_RE_FILTER instead?
1681 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1682 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1687 if (b->dynamic) pcrs_free_joblist(joblist);
1689 log_error(LOG_LEVEL_RE_FILTER,
1690 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1691 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1693 hits += current_hits;
1700 * If there were no hits, destroy our copy and let
1701 * chat() use the original in csp->iob
1709 csp->flags |= CSP_FLAG_MODIFIED;
1710 csp->content_length = size;
1718 /*********************************************************************
1720 * Function : gif_deanimate_response
1722 * Description : Deanimate the GIF image that has been accumulated in
1723 * csp->iob->buf, set csp->content_length to the modified
1724 * size and raise the CSP_FLAG_MODIFIED flag.
1727 * 1 : csp = Current client state (buffers, headers, etc...)
1729 * Returns : a pointer to the (newly allocated) modified buffer.
1730 * or NULL in case something went wrong.
1732 *********************************************************************/
1733 static char *gif_deanimate_response(struct client_state *csp)
1735 struct binbuffer *in, *out;
1739 size = (size_t)(csp->iob->eod - csp->iob->cur);
1741 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1742 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1744 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1748 in->buffer = csp->iob->cur;
1751 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1753 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1760 if ((int)size == out->offset)
1762 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1766 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1768 csp->content_length = out->offset;
1769 csp->flags |= CSP_FLAG_MODIFIED;
1779 /*********************************************************************
1781 * Function : get_filter_function
1783 * Description : Decides which content filter function has
1784 * to be applied (if any).
1787 * 1 : csp = Current client state (buffers, headers, etc...)
1789 * Returns : The content filter function to run, or
1790 * NULL if no content filter is active
1792 *********************************************************************/
1793 static filter_function_ptr get_filter_function(const struct client_state *csp)
1795 filter_function_ptr filter_function = NULL;
1798 * Choose the applying filter function based on
1799 * the content type and action settings.
1801 if ((csp->content_type & CT_TEXT) &&
1802 (csp->rlist != NULL) &&
1803 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1805 filter_function = pcrs_filter_response;
1807 else if ((csp->content_type & CT_GIF) &&
1808 (csp->action->flags & ACTION_DEANIMATE))
1810 filter_function = gif_deanimate_response;
1813 return filter_function;
1817 /*********************************************************************
1819 * Function : remove_chunked_transfer_coding
1821 * Description : In-situ remove the "chunked" transfer coding as defined
1822 * in rfc2616 from a buffer.
1825 * 1 : buffer = Pointer to the text buffer
1826 * 2 : size = In: Number of bytes to be processed,
1827 * Out: Number of bytes after de-chunking.
1828 * (undefined in case of errors)
1830 * Returns : JB_ERR_OK for success,
1831 * JB_ERR_PARSE otherwise
1833 *********************************************************************/
1834 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1837 unsigned int chunksize = 0;
1838 char *from_p, *to_p;
1841 from_p = to_p = buffer;
1843 if (sscanf(buffer, "%x", &chunksize) != 1)
1845 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1846 return JB_ERR_PARSE;
1849 while (chunksize > 0U)
1851 if (NULL == (from_p = strstr(from_p, "\r\n")))
1853 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1854 return JB_ERR_PARSE;
1857 if (chunksize >= *size - newsize)
1859 log_error(LOG_LEVEL_ERROR,
1860 "Chunk size %u exceeds buffered data left. "
1861 "Already digested %u of %u buffered bytes.",
1862 chunksize, (unsigned int)newsize, (unsigned int)*size);
1863 return JB_ERR_PARSE;
1865 newsize += chunksize;
1868 memmove(to_p, from_p, (size_t) chunksize);
1869 to_p = buffer + newsize;
1870 from_p += chunksize + 2;
1872 if (sscanf(from_p, "%x", &chunksize) != 1)
1874 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1879 /* XXX: Should get its own loglevel. */
1880 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1889 /*********************************************************************
1891 * Function : prepare_for_filtering
1893 * Description : If necessary, de-chunks and decompresses
1894 * the content so it can get filterd.
1897 * 1 : csp = Current client state (buffers, headers, etc...)
1899 * Returns : JB_ERR_OK for success,
1900 * JB_ERR_PARSE otherwise
1902 *********************************************************************/
1903 static jb_err prepare_for_filtering(struct client_state *csp)
1905 jb_err err = JB_ERR_OK;
1908 * If the body has a "chunked" transfer-encoding,
1909 * get rid of it, adjusting size and iob->eod
1911 if (csp->flags & CSP_FLAG_CHUNKED)
1913 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1915 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1916 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1917 if (JB_ERR_OK == err)
1919 csp->iob->eod = csp->iob->cur + size;
1920 csp->flags |= CSP_FLAG_MODIFIED;
1924 return JB_ERR_PARSE;
1930 * If the body has a supported transfer-encoding,
1931 * decompress it, adjusting size and iob->eod.
1933 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1935 if (0 == csp->iob->eod - csp->iob->cur)
1937 /* Nothing left after de-chunking. */
1941 err = decompress_iob(csp);
1943 if (JB_ERR_OK == err)
1945 csp->flags |= CSP_FLAG_MODIFIED;
1946 csp->content_type &= ~CT_TABOO;
1951 * Unset CT_GZIP and CT_DEFLATE to remember not
1952 * to modify the Content-Encoding header later.
1954 csp->content_type &= ~CT_GZIP;
1955 csp->content_type &= ~CT_DEFLATE;
1964 /*********************************************************************
1966 * Function : execute_content_filters
1968 * Description : Executes a given content filter.
1971 * 1 : csp = Current client state (buffers, headers, etc...)
1973 * Returns : Pointer to the modified buffer, or
1974 * NULL if filtering failed or wasn't necessary.
1976 *********************************************************************/
1977 char *execute_content_filters(struct client_state *csp)
1979 filter_function_ptr content_filter;
1981 assert(content_filters_enabled(csp->action));
1983 if (0 == csp->iob->eod - csp->iob->cur)
1986 * No content (probably status code 301, 302 ...),
1987 * no filtering necessary.
1992 if (JB_ERR_OK != prepare_for_filtering(csp))
1995 * failed to de-chunk or decompress.
2000 if (0 == csp->iob->eod - csp->iob->cur)
2003 * Clown alarm: chunked and/or compressed nothing delivered.
2008 content_filter = get_filter_function(csp);
2010 return ((*content_filter)(csp));
2014 /*********************************************************************
2016 * Function : get_url_actions
2018 * Description : Gets the actions for this URL.
2021 * 1 : csp = Current client state (buffers, headers, etc...)
2022 * 2 : http = http_request request for blocked URLs
2026 *********************************************************************/
2027 void get_url_actions(struct client_state *csp, struct http_request *http)
2029 struct file_list *fl;
2030 struct url_actions *b;
2033 init_current_action(csp->action);
2035 for (i = 0; i < MAX_AF_FILES; i++)
2037 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2042 apply_url_actions(csp->action, http, b);
2049 /*********************************************************************
2051 * Function : apply_url_actions
2053 * Description : Applies a list of URL actions.
2056 * 1 : action = Destination.
2057 * 2 : http = Current URL
2058 * 3 : b = list of URL actions to apply
2062 *********************************************************************/
2063 void apply_url_actions(struct current_action_spec *action,
2064 struct http_request *http,
2065 struct url_actions *b)
2069 /* Should never happen */
2073 for (b = b->next; NULL != b; b = b->next)
2075 if (url_match(b->url, http))
2077 merge_current_action(action, b->action);
2083 /*********************************************************************
2085 * Function : get_forward_override_settings
2087 * Description : Returns forward settings as specified with the
2088 * forward-override{} action. forward-override accepts
2089 * forward lines similar to the one used in the
2090 * configuration file, but without the URL pattern.
2096 * in the configuration file can be replaced with
2097 * the action section:
2099 * {+forward-override{forward .}}
2103 * 1 : csp = Current client state (buffers, headers, etc...)
2105 * Returns : Pointer to forwarding structure in case of success.
2106 * Invalid syntax is fatal.
2108 *********************************************************************/
2109 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2111 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2112 char forward_settings[BUFFER_SIZE];
2113 char *http_parent = NULL;
2114 /* variable names were chosen for consistency reasons. */
2115 struct forward_spec *fwd = NULL;
2119 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2120 /* Should be enforced by load_one_actions_file() */
2121 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2123 /* Create a copy ssplit can modify */
2124 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2126 if (NULL != csp->fwd)
2129 * XXX: Currently necessary to prevent memory
2130 * leaks when the show-url-info cgi page is visited.
2132 unload_forward_spec(csp->fwd);
2136 * allocate a new forward node, valid only for
2137 * the lifetime of this request. Save its location
2138 * in csp as well, so sweep() can free it later on.
2140 fwd = csp->fwd = zalloc(sizeof(*fwd));
2143 log_error(LOG_LEVEL_FATAL,
2144 "can't allocate memory for forward-override{%s}", forward_override_line);
2145 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2149 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2150 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2152 fwd->type = SOCKS_NONE;
2154 /* Parse the parent HTTP proxy host:port */
2155 http_parent = vec[1];
2158 else if (vec_count == 3)
2160 char *socks_proxy = NULL;
2162 if (!strcasecmp(vec[0], "forward-socks4"))
2164 fwd->type = SOCKS_4;
2165 socks_proxy = vec[1];
2167 else if (!strcasecmp(vec[0], "forward-socks4a"))
2169 fwd->type = SOCKS_4A;
2170 socks_proxy = vec[1];
2172 else if (!strcasecmp(vec[0], "forward-socks5"))
2174 fwd->type = SOCKS_5;
2175 socks_proxy = vec[1];
2178 if (NULL != socks_proxy)
2180 /* Parse the SOCKS proxy host[:port] */
2181 fwd->gateway_port = 1080;
2182 parse_forwarder_address(socks_proxy,
2183 &fwd->gateway_host, &fwd->gateway_port);
2185 http_parent = vec[2];
2189 if (NULL == http_parent)
2191 log_error(LOG_LEVEL_FATAL,
2192 "Invalid forward-override syntax in: %s", forward_override_line);
2193 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2196 /* Parse http forwarding settings */
2197 if (strcmp(http_parent, ".") != 0)
2199 fwd->forward_port = 8000;
2200 parse_forwarder_address(http_parent,
2201 &fwd->forward_host, &fwd->forward_port);
2204 assert (NULL != fwd);
2206 log_error(LOG_LEVEL_CONNECT,
2207 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2213 /*********************************************************************
2215 * Function : forward_url
2217 * Description : Should we forward this to another proxy?
2220 * 1 : csp = Current client state (buffers, headers, etc...)
2221 * 2 : http = http_request request for current URL
2223 * Returns : Pointer to forwarding information.
2225 *********************************************************************/
2226 const struct forward_spec *forward_url(struct client_state *csp,
2227 const struct http_request *http)
2229 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2230 struct forward_spec *fwd = csp->config->forward;
2232 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2234 return get_forward_override_settings(csp);
2244 if (url_match(fwd->url, http))
2255 /*********************************************************************
2257 * Function : direct_response
2259 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2260 * request and if so, return a HTTP 501 to the client.
2262 * FIXME: I have a stupid name and I should handle the
2263 * requests properly. Still, what we do here is rfc-
2264 * compliant, whereas ignoring or forwarding are not.
2267 * 1 : csp = Current client state (buffers, headers, etc...)
2269 * Returns : http_response if , NULL if nonmatch or handler fail
2271 *********************************************************************/
2272 struct http_response *direct_response(struct client_state *csp)
2274 struct http_response *rsp;
2275 struct list_entry *p;
2277 if ((0 == strcmpic(csp->http->gpc, "trace"))
2278 || (0 == strcmpic(csp->http->gpc, "options")))
2280 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2282 if (!strncmpic(p->str, "Max-Forwards:", 13))
2284 unsigned int max_forwards;
2287 * If it's a Max-Forwards value of zero,
2288 * we have to intercept the request.
2290 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2293 * FIXME: We could handle at least TRACE here,
2294 * but that would require a verbatim copy of
2295 * the request which we don't have anymore
2297 log_error(LOG_LEVEL_HEADER,
2298 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2301 /* Get mem for response or fail*/
2302 if (NULL == (rsp = alloc_http_response()))
2304 return cgi_error_memory();
2307 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2309 free_http_response(rsp);
2310 return cgi_error_memory();
2314 rsp->crunch_reason = UNSUPPORTED;
2316 return(finish_http_response(csp, rsp));
2325 /*********************************************************************
2327 * Function : content_requires_filtering
2329 * Description : Checks whether there are any content filters
2330 * enabled for the current request and if they
2331 * can actually be applied..
2334 * 1 : csp = Current client state (buffers, headers, etc...)
2336 * Returns : TRUE for yes, FALSE otherwise
2338 *********************************************************************/
2339 int content_requires_filtering(struct client_state *csp)
2341 if ((csp->content_type & CT_TABOO)
2342 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2348 * Are we enabling text mode by force?
2350 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2353 * Do we really have to?
2355 if (csp->content_type & CT_TEXT)
2357 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2361 csp->content_type |= CT_TEXT;
2362 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2366 if (!(csp->content_type & CT_DECLARED))
2369 * The server didn't bother to declare a MIME-Type.
2370 * Assume it's text that can be filtered.
2372 * This also regulary happens with 304 responses,
2373 * therefore logging anything here would cause
2376 csp->content_type |= CT_TEXT;
2380 * Choose the applying filter function based on
2381 * the content type and action settings.
2383 if ((csp->content_type & CT_TEXT) &&
2384 (csp->rlist != NULL) &&
2385 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2389 else if ((csp->content_type & CT_GIF) &&
2390 (csp->action->flags & ACTION_DEANIMATE))
2400 /*********************************************************************
2402 * Function : content_filters_enabled
2404 * Description : Checks whether there are any content filters
2405 * enabled for the current request.
2408 * 1 : action = Action spec to check.
2410 * Returns : TRUE for yes, FALSE otherwise
2412 *********************************************************************/
2413 int content_filters_enabled(const struct current_action_spec *action)
2415 return ((action->flags & ACTION_DEANIMATE) ||
2416 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));
2420 /*********************************************************************
2422 * Function : filters_available
2424 * Description : Checks whether there are any filters available.
2427 * 1 : csp = Current client state (buffers, headers, etc...)
2429 * Returns : TRUE for yes, FALSE otherwise.
2431 *********************************************************************/
2432 int filters_available(const struct client_state *csp)
2435 for (i = 0; i < MAX_AF_FILES; i++)
2437 const struct file_list *fl = csp->rlist[i];
2438 if ((NULL != fl) && (NULL != fl->f))