1 const char filters_rcs[] = "$Id: filters.c,v 1.191 2014/10/18 11:28:36 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2014 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 #endif /* ndef __OS2__ */
49 #include <netinet/in.h>
52 #endif /* ndef _WIN32 */
56 #endif /* def __OS2__ */
64 #include "jbsockets.h"
70 #include "deanimate.h"
78 const char filters_h_rcs[] = FILTERS_H_VERSION;
80 typedef char *(*filter_function_ptr)();
81 static filter_function_ptr get_filter_function(const struct client_state *csp);
82 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
83 static jb_err prepare_for_filtering(struct client_state *csp);
87 /*********************************************************************
89 * Function : sockaddr_storage_to_ip
91 * Description : Access internal structure of sockaddr_storage
94 * 1 : addr = socket address
95 * 2 : ip = IP address as array of octets in network order
96 * (it points into addr)
97 * 3 : len = length of IP address in octets
98 * 4 : port = port number in network order;
100 * Returns : 0 = no errror; -1 otherwise.
102 *********************************************************************/
103 static int sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
104 uint8_t **ip, unsigned int *len,
112 switch (addr->ss_family)
122 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
126 *port = &((struct sockaddr_in *)addr)->sin_port;
137 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
141 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
146 /* Unsupported address family */
154 /*********************************************************************
156 * Function : match_sockaddr
158 * Description : Check whether address matches network (IP address and port)
161 * 1 : network = socket address of subnework
162 * 2 : netmask = network mask as socket address
163 * 3 : address = checked socket address against given network
165 * Returns : 0 = doesn't match; 1 = does match
167 *********************************************************************/
168 static int match_sockaddr(const struct sockaddr_storage *network,
169 const struct sockaddr_storage *netmask,
170 const struct sockaddr_storage *address)
172 uint8_t *network_addr, *netmask_addr, *address_addr;
173 unsigned int addr_len;
174 in_port_t *network_port, *netmask_port, *address_port;
177 if (network->ss_family != netmask->ss_family)
179 /* This should never happen */
180 assert(network->ss_family == netmask->ss_family);
181 log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
184 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
185 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
186 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
188 /* Check for family */
189 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
190 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
192 /* Map AF_INET6 V4MAPPED address into AF_INET */
196 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
197 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
199 /* Map AF_INET6 V4MAPPED network into AF_INET */
205 /* XXX: Port check is signaled in netmask */
206 if (*netmask_port && *network_port != *address_port)
211 /* TODO: Optimize by checking by words insted of octets */
212 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
214 if ((network_addr[i] & netmask_addr[i]) !=
215 (address_addr[i] & netmask_addr[i]))
223 #endif /* def HAVE_RFC2553 */
226 /*********************************************************************
228 * Function : block_acl
230 * Description : Block this request?
231 * Decide yes or no based on ACL file.
234 * 1 : dst = The proxy or gateway address this is going to.
235 * Or NULL to check all possible targets.
236 * 2 : csp = Current client state (buffers, headers, etc...)
237 * Also includes the client IP address.
239 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
241 *********************************************************************/
242 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
244 struct access_control_list *acl = csp->config->acl;
246 /* if not using an access control list, then permit the connection */
252 /* search the list */
257 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
259 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
265 /* Just want to check if they have any access */
266 if (acl->action == ACL_PERMIT)
278 * XXX: An undefined acl->dst is full of zeros and should be
279 * considered a wildcard address. sockaddr_storage_to_ip()
280 * fails on such destinations because of unknown sa_familly
281 * (glibc only?). However this test is not portable.
283 * So, we signal the acl->dst is wildcard in wildcard_dst.
286 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
288 ((dst->addr & acl->dst->mask) == acl->dst->addr)
289 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
293 if (acl->action == ACL_PERMIT)
311 /*********************************************************************
313 * Function : acl_addr
315 * Description : Called from `load_config' to parse an ACL address.
318 * 1 : aspec = String specifying ACL address.
319 * 2 : aca = struct access_control_addr to fill in.
321 * Returns : 0 => Ok, everything else is an error.
323 *********************************************************************/
324 int acl_addr(const char *aspec, struct access_control_addr *aca)
328 struct addrinfo hints, *result;
330 in_port_t *mask_port;
331 unsigned int addr_len;
334 #endif /* def HAVE_RFC2553 */
336 char *acl_spec = NULL;
339 /* XXX: Depend on ai_family */
347 * Use a temporary acl spec copy so we can log
348 * the unmodified original in case of parse errors.
350 acl_spec = strdup_or_die(aspec);
352 if ((p = strchr(acl_spec, '/')) != NULL)
355 if (privoxy_isdigit(*p) == 0)
360 masklength = atoi(p);
363 if ((masklength < 0) ||
375 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
378 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
387 p = strchr(acl_spec, ':');
391 memset(&hints, 0, sizeof(struct addrinfo));
392 hints.ai_family = AF_UNSPEC;
393 hints.ai_socktype = SOCK_STREAM;
395 i = getaddrinfo(acl_spec, ((p) ? ++p : NULL), &hints, &result);
399 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
400 acl_spec, p, gai_strerror(i));
406 /* TODO: Allow multihomed hostnames */
407 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
408 freeaddrinfo(result);
415 port = strtol(p, &endptr, 10);
417 if (port <= 0 || port > 65535 || *endptr != '\0')
424 aca->port = (unsigned long)port;
426 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
429 if (aca->addr == INADDR_NONE)
431 /* XXX: This will be logged as parse error. */
434 #endif /* def HAVE_RFC2553 */
436 /* build the netmask */
438 /* Clip masklength according to current family. */
439 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
444 aca->mask.ss_family = aca->addr.ss_family;
445 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
452 /* ACL contains a port number, check ports in the future. */
457 * XXX: This could be optimized to operate on whole words instead
458 * of octets (128-bit CPU could do it in one iteration).
461 * Octets after prefix can be omitted because of
462 * previous initialization to zeros.
464 for (i = 0; (i < addr_len) && masklength; i++)
474 * XXX: This assumes MSB of octet is on the left side.
475 * This should be true for all architectures or solved
478 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
485 for (i=1; i <= masklength ; i++)
487 aca->mask |= (1U << (32 - i));
490 /* now mask off the host portion of the ip address
491 * (i.e. save on the network portion of the address).
493 aca->addr = aca->addr & aca->mask;
494 #endif /* def HAVE_RFC2553 */
499 #endif /* def FEATURE_ACL */
502 /*********************************************************************
504 * Function : connect_port_is_forbidden
506 * Description : Check to see if CONNECT requests to the destination
507 * port of this request are forbidden. The check is
508 * independend of the actual request method.
511 * 1 : csp = Current client state (buffers, headers, etc...)
513 * Returns : True if yes, false otherwise.
515 *********************************************************************/
516 int connect_port_is_forbidden(const struct client_state *csp)
518 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
519 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
524 /*********************************************************************
526 * Function : block_url
528 * Description : Called from `chat'. Check to see if we need to block this.
531 * 1 : csp = Current client state (buffers, headers, etc...)
533 * Returns : NULL => unblocked, else HTTP block response
535 *********************************************************************/
536 struct http_response *block_url(struct client_state *csp)
538 struct http_response *rsp;
539 const char *new_content_type = NULL;
542 * If it's not blocked, don't block it ;-)
544 if ((csp->action->flags & ACTION_BLOCK) == 0)
548 if (csp->action->flags & ACTION_REDIRECT)
550 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
553 * Else, prepare a response
555 if (NULL == (rsp = alloc_http_response()))
557 return cgi_error_memory();
561 * If it's an image-url, send back an image or redirect
562 * as specified by the relevant +image action
564 #ifdef FEATURE_IMAGE_BLOCKING
565 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
569 /* determine HOW images should be blocked */
570 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
572 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
574 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
577 /* and handle accordingly: */
578 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
580 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
581 rsp->body = bindup(image_pattern_data, image_pattern_length);
582 if (rsp->body == NULL)
584 free_http_response(rsp);
585 return cgi_error_memory();
587 rsp->content_length = image_pattern_length;
589 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
591 free_http_response(rsp);
592 return cgi_error_memory();
595 else if (0 == strcmpic(p, "blank"))
597 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
598 rsp->body = bindup(image_blank_data, image_blank_length);
599 if (rsp->body == NULL)
601 free_http_response(rsp);
602 return cgi_error_memory();
604 rsp->content_length = image_blank_length;
606 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
608 free_http_response(rsp);
609 return cgi_error_memory();
614 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
616 if (enlist_unique_header(rsp->headers, "Location", p))
618 free_http_response(rsp);
619 return cgi_error_memory();
625 #endif /* def FEATURE_IMAGE_BLOCKING */
626 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
629 * Send empty document.
631 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
634 rsp->body = strdup_or_die(" ");
635 rsp->content_length = 1;
637 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
640 * Workaround for firefox bug 492459
641 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
642 * Return a 200 OK status for pages blocked with +handle-as-empty-document
643 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
645 rsp->status = strdup_or_die("200 Request blocked by Privoxy");
649 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
652 if (new_content_type != 0)
654 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
655 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
657 free_http_response(rsp);
658 return cgi_error_memory();
665 * Else, generate an HTML "blocked" message:
669 struct map * exports;
671 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
673 exports = default_exports(csp, NULL);
676 free_http_response(rsp);
677 return cgi_error_memory();
680 #ifdef FEATURE_FORCE_LOAD
681 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
683 * Export the force conditional block killer if
685 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
686 * - Privoxy is configured to enforce blocks, or
687 * - it's a CONNECT request and enforcing wouldn't work anyway.
689 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
690 || (0 == strcmpic(csp->http->gpc, "connect")))
691 #endif /* ndef FEATURE_FORCE_LOAD */
693 err = map_block_killer(exports, "force-support");
696 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
697 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
698 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
699 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
702 const char *block_reason;
703 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
705 block_reason = csp->action->string[ACTION_STRING_BLOCK];
709 assert(connect_port_is_forbidden(csp));
710 block_reason = "Forbidden CONNECT port.";
712 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
717 free_http_response(rsp);
718 return cgi_error_memory();
721 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
724 free_http_response(rsp);
725 return cgi_error_memory();
728 rsp->crunch_reason = BLOCKED;
730 return finish_http_response(csp, rsp);
736 /*********************************************************************
738 * Function : trust_url FIXME: I should be called distrust_url
740 * Description : Calls is_untrusted_url to determine if the URL is trusted
741 * and if not, returns a HTTP 403 response with a reject message.
744 * 1 : csp = Current client state (buffers, headers, etc...)
746 * Returns : NULL => trusted, else http_response.
748 *********************************************************************/
749 struct http_response *trust_url(struct client_state *csp)
751 struct http_response *rsp;
752 struct map * exports;
753 char buf[BUFFER_SIZE];
755 struct pattern_spec **tl;
756 struct pattern_spec *t;
760 * Don't bother to work on trusted URLs
762 if (!is_untrusted_url(csp))
768 * Else, prepare a response:
770 if (NULL == (rsp = alloc_http_response()))
772 return cgi_error_memory();
775 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
776 exports = default_exports(csp, NULL);
779 free_http_response(rsp);
780 return cgi_error_memory();
784 * Export the protocol, host, port, and referrer information
786 err = map(exports, "hostport", 1, csp->http->hostport, 1);
787 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
788 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
790 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
792 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
796 if (!err) err = map(exports, "referrer", 1, "none set", 1);
802 free_http_response(rsp);
803 return cgi_error_memory();
807 * Export the trust list
809 p = strdup_or_die("");
810 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
812 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
813 string_append(&p, buf);
815 err = map(exports, "trusted-referrers", 1, p, 0);
820 free_http_response(rsp);
821 return cgi_error_memory();
825 * Export the trust info, if available
827 if (csp->config->trust_info->first)
829 struct list_entry *l;
831 p = strdup_or_die("");
832 for (l = csp->config->trust_info->first; l ; l = l->next)
834 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
835 string_append(&p, buf);
837 err = map(exports, "trust-info", 1, p, 0);
841 err = map_block_killer(exports, "have-trust-info");
847 free_http_response(rsp);
848 return cgi_error_memory();
852 * Export the force conditional block killer if
854 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
855 * - Privoxy is configured to enforce blocks, or
856 * - it's a CONNECT request and enforcing wouldn't work anyway.
858 #ifdef FEATURE_FORCE_LOAD
859 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
860 || (0 == strcmpic(csp->http->gpc, "connect")))
862 err = map_block_killer(exports, "force-support");
866 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
868 #else /* ifndef FEATURE_FORCE_LOAD */
869 err = map_block_killer(exports, "force-support");
870 #endif /* ndef FEATURE_FORCE_LOAD */
875 free_http_response(rsp);
876 return cgi_error_memory();
882 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
885 free_http_response(rsp);
886 return cgi_error_memory();
888 rsp->crunch_reason = UNTRUSTED;
890 return finish_http_response(csp, rsp);
892 #endif /* def FEATURE_TRUST */
895 /*********************************************************************
897 * Function : compile_dynamic_pcrs_job_list
899 * Description : Compiles a dynamic pcrs job list (one with variables
900 * resolved at request time)
903 * 1 : csp = Current client state (buffers, headers, etc...)
904 * 2 : b = The filter list to compile
906 * Returns : NULL in case of errors, otherwise the
909 *********************************************************************/
910 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
912 struct list_entry *pattern;
913 pcrs_job *job_list = NULL;
914 pcrs_job *dummy = NULL;
915 pcrs_job *lastjob = NULL;
918 const struct pcrs_variable variables[] =
920 {"url", csp->http->url, 1},
921 {"path", csp->http->path, 1},
922 {"host", csp->http->host, 1},
923 {"origin", csp->ip_addr_str, 1},
927 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
929 assert(pattern->str != NULL);
931 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
934 log_error(LOG_LEVEL_ERROR,
935 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
936 pattern->str, b->name, error, pcrs_strerror(error));
941 if (error == PCRS_WARN_TRUNCATION)
943 log_error(LOG_LEVEL_ERROR,
944 "At least one of the variables in \'%s\' had to "
945 "be truncated before compilation", pattern->str);
947 if (job_list == NULL)
953 lastjob->next = dummy;
963 /*********************************************************************
965 * Function : rewrite_url
967 * Description : Rewrites a URL with a single pcrs command
968 * and returns the result if it differs from the
969 * original and isn't obviously invalid.
972 * 1 : old_url = URL to rewrite.
973 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
976 * Returns : NULL if the pcrs_command didn't change the url, or
977 * the result of the modification.
979 *********************************************************************/
980 char *rewrite_url(char *old_url, const char *pcrs_command)
982 char *new_url = NULL;
986 assert(pcrs_command);
988 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
992 log_error(LOG_LEVEL_REDIRECTS,
993 "pcrs command \"%s\" didn't change \"%s\".",
994 pcrs_command, old_url);
999 log_error(LOG_LEVEL_REDIRECTS,
1000 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1001 pcrs_command, old_url, pcrs_strerror(hits));
1004 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1006 log_error(LOG_LEVEL_ERROR,
1007 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1008 "but the result doesn't look like a valid URL and will be ignored.",
1009 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1014 log_error(LOG_LEVEL_REDIRECTS,
1015 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1016 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1024 #ifdef FEATURE_FAST_REDIRECTS
1025 /*********************************************************************
1027 * Function : get_last_url
1029 * Description : Search for the last URL inside a string.
1030 * If the string already is a URL, it will
1031 * be the first URL found.
1034 * 1 : subject = the string to check
1035 * 2 : redirect_mode = +fast-redirect{} mode
1037 * Returns : NULL if no URL was found, or
1038 * the last URL found.
1040 *********************************************************************/
1041 char *get_last_url(char *subject, const char *redirect_mode)
1043 char *new_url = NULL;
1047 assert(redirect_mode);
1049 subject = strdup(subject);
1050 if (subject == NULL)
1052 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1056 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1058 char *url_segment = NULL;
1059 char **url_segments;
1060 size_t max_segments;
1063 log_error(LOG_LEVEL_REDIRECTS,
1064 "Checking \"%s\" for encoded redirects.", subject);
1067 * Check each parameter in the URL separately.
1068 * Sectionize the URL at "?" and "&",
1069 * go backwards through the segments, URL-decode them
1070 * and look for a URL in the decoded result.
1071 * Stop the search after the first match.
1073 * XXX: This estimate is guaranteed to be high enough as we
1074 * let ssplit() ignore empty fields, but also a bit wasteful.
1076 max_segments = strlen(subject) / 2;
1077 url_segments = malloc(max_segments * sizeof(char *));
1079 if (NULL == url_segments)
1081 log_error(LOG_LEVEL_ERROR,
1082 "Out of memory while decoding URL: %s", subject);
1087 segments = ssplit(subject, "?&", url_segments, max_segments);
1089 while (segments-- > 0)
1091 char *dtoken = url_decode(url_segments[segments]);
1094 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1097 url_segment = strstr(dtoken, "http://");
1098 if (NULL == url_segment)
1100 url_segment = strstr(dtoken, "https://");
1102 if (NULL != url_segment)
1104 url_segment = strdup_or_die(url_segment);
1111 freez(url_segments);
1113 if (url_segment == NULL)
1117 subject = url_segment;
1121 /* Look for a URL inside this one, without decoding anything. */
1122 log_error(LOG_LEVEL_REDIRECTS,
1123 "Checking \"%s\" for unencoded redirects.", subject);
1127 * Find the last URL encoded in the request
1130 while ((tmp = strstr(tmp, "http://")) != NULL)
1134 tmp = (new_url != NULL) ? new_url : subject;
1135 while ((tmp = strstr(tmp, "https://")) != NULL)
1140 if ((new_url != NULL)
1141 && ( (new_url != subject)
1142 || (0 == strncmpic(subject, "http://", 7))
1143 || (0 == strncmpic(subject, "https://", 8))
1147 * Return new URL if we found a redirect
1148 * or if the subject already was a URL.
1150 * The second case makes sure that we can
1151 * chain get_last_url after another redirection check
1152 * (like rewrite_url) without losing earlier redirects.
1154 new_url = strdup(new_url);
1163 #endif /* def FEATURE_FAST_REDIRECTS */
1166 /*********************************************************************
1168 * Function : redirect_url
1170 * Description : Checks if Privoxy should answer the request with
1171 * a HTTP redirect and generates the redirect if
1175 * 1 : csp = Current client state (buffers, headers, etc...)
1177 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1179 *********************************************************************/
1180 struct http_response *redirect_url(struct client_state *csp)
1182 struct http_response *rsp;
1183 #ifdef FEATURE_FAST_REDIRECTS
1185 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1186 * as compile-time option? The user can easily disable
1187 * it in his action file.
1189 char * redirect_mode;
1190 #endif /* def FEATURE_FAST_REDIRECTS */
1191 char *old_url = NULL;
1192 char *new_url = NULL;
1193 char *redirection_string;
1195 if ((csp->action->flags & ACTION_REDIRECT))
1197 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1200 * If the redirection string begins with 's',
1201 * assume it's a pcrs command, otherwise treat it as
1202 * properly formatted URL and use it for the redirection
1205 * According to (the now obsolete) RFC 2616 section 14.30
1206 * the URL has to be absolute and if the user tries:
1207 * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
1208 * she would get undefined results anyway.
1210 * RFC 7231 7.1.2 actually allows relative references,
1211 * but those start with a leading slash (RFC 3986 4.2) and
1212 * thus can't be mistaken for pcrs commands either.
1215 if (*redirection_string == 's')
1217 old_url = csp->http->url;
1218 new_url = rewrite_url(old_url, redirection_string);
1222 log_error(LOG_LEVEL_REDIRECTS,
1223 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1224 redirection_string);
1225 new_url = strdup(redirection_string);
1229 #ifdef FEATURE_FAST_REDIRECTS
1230 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1232 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1235 * If it exists, use the previously rewritten URL as input
1236 * otherwise just use the old path.
1238 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1239 new_url = get_last_url(old_url, redirect_mode);
1244 * Disable redirect checkers, so that they
1245 * will be only run more than once if the user
1246 * also enables them through tags.
1248 * From a performance point of view
1249 * it doesn't matter, but the duplicated
1250 * log messages are annoying.
1252 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1253 #endif /* def FEATURE_FAST_REDIRECTS */
1254 csp->action->flags &= ~ACTION_REDIRECT;
1256 /* Did any redirect action trigger? */
1259 if (url_requires_percent_encoding(new_url))
1262 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1263 strlen(new_url), new_url);
1264 encoded_url = percent_encode_url(new_url);
1266 if (encoded_url == NULL)
1268 return cgi_error_memory();
1270 new_url = encoded_url;
1271 assert(FALSE == url_requires_percent_encoding(new_url));
1274 if (0 == strcmpic(new_url, csp->http->url))
1276 log_error(LOG_LEVEL_ERROR,
1277 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1278 csp->http->url, new_url);
1283 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1285 if (NULL == (rsp = alloc_http_response()))
1288 return cgi_error_memory();
1291 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
1292 if (enlist_unique_header(rsp->headers, "Location", new_url))
1295 free_http_response(rsp);
1296 return cgi_error_memory();
1298 rsp->crunch_reason = REDIRECTED;
1301 return finish_http_response(csp, rsp);
1305 /* Only reached if no redirect is required */
1311 #ifdef FEATURE_IMAGE_BLOCKING
1312 /*********************************************************************
1314 * Function : is_imageurl
1316 * Description : Given a URL, decide whether it is an image or not,
1317 * using either the info from a previous +image action
1318 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1319 * is MSIE and not on a Mac, tell from the browser's accept
1323 * 1 : csp = Current client state (buffers, headers, etc...)
1325 * Returns : True (nonzero) if URL is an image, false (0)
1328 *********************************************************************/
1329 int is_imageurl(const struct client_state *csp)
1331 #ifdef FEATURE_IMAGE_DETECT_MSIE
1334 tmp = get_header_value(csp->headers, "User-Agent:");
1335 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1337 tmp = get_header_value(csp->headers, "Accept:");
1338 if (tmp && strstr(tmp, "image/gif"))
1340 /* Client will accept HTML. If this seems counterintuitive,
1350 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1352 return ((csp->action->flags & ACTION_IMAGE) != 0);
1355 #endif /* def FEATURE_IMAGE_BLOCKING */
1358 #ifdef FEATURE_TRUST
1359 /*********************************************************************
1361 * Function : is_untrusted_url
1363 * Description : Should we "distrust" this URL (and block it)?
1365 * Yes if it matches a line in the trustfile, or if the
1366 * referrer matches a line starting with "+" in the
1371 * 1 : csp = Current client state (buffers, headers, etc...)
1373 * Returns : 0 => trusted, 1 => untrusted
1375 *********************************************************************/
1376 int is_untrusted_url(const struct client_state *csp)
1378 struct file_list *fl;
1379 struct block_spec *b;
1380 struct pattern_spec **trusted_url;
1381 struct http_request rhttp[1];
1382 const char * referer;
1386 * If we don't have a trustlist, we trust everybody
1388 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1393 memset(rhttp, '\0', sizeof(*rhttp));
1396 * Do we trust the request URL itself?
1398 for (b = b->next; b ; b = b->next)
1400 if (url_match(b->url, csp->http))
1406 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1408 /* no referrer was supplied */
1414 * If not, do we maybe trust its referrer?
1416 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1422 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1424 if (url_match(*trusted_url, rhttp))
1426 /* if the URL's referrer is from a trusted referrer, then
1427 * add the target spec to the trustfile as an unblocked
1428 * domain and return 0 (which means it's OK).
1433 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1437 char * new_entry = strdup_or_die("~");
1439 string_append(&new_entry, csp->http->hostport);
1441 path = csp->http->path;
1442 if ( (path[0] == '/')
1444 && ((path_end = strchr(path + 2, '/')) != NULL))
1446 /* since this path points into a user's home space
1447 * be sure to include this spec in the trustfile.
1449 long path_len = path_end - path; /* save offset */
1450 path = strdup(path); /* Copy string */
1453 path_end = path + path_len; /* regenerate ptr to new buffer */
1454 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1456 string_join(&new_entry, path);
1460 * Give a reason for generating this entry.
1462 string_append(&new_entry, " # Trusted referrer was: ");
1463 string_append(&new_entry, referer);
1465 if (new_entry != NULL)
1467 if (-1 == fprintf(fp, "%s\n", new_entry))
1469 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1470 new_entry, csp->config->trustfile);
1476 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1477 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1484 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1485 csp->http->hostport, csp->config->trustfile);
1493 #endif /* def FEATURE_TRUST */
1496 /*********************************************************************
1498 * Function : get_filter
1500 * Description : Get a filter with a given name and type.
1501 * Note that taggers are filters, too.
1504 * 1 : csp = Current client state (buffers, headers, etc...)
1505 * 2 : requested_name = Name of the content filter to get
1506 * 3 : requested_type = Type of the filter to tagger to lookup
1508 * Returns : A pointer to the requested filter
1509 * or NULL if the filter wasn't found
1511 *********************************************************************/
1512 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1513 const char *requested_name,
1514 enum filter_type requested_type)
1517 struct re_filterfile_spec *b;
1518 struct file_list *fl;
1520 for (i = 0; i < MAX_AF_FILES; i++)
1523 if ((NULL == fl) || (NULL == fl->f))
1526 * Either there are no filter files left or this
1527 * filter file just contains no valid filters.
1529 * Continue to be sure we don't miss valid filter
1530 * files that are chained after empty or invalid ones.
1535 for (b = fl->f; b != NULL; b = b->next)
1537 if (b->type != requested_type)
1539 /* The callers isn't interested in this filter type. */
1542 if (strcmp(b->name, requested_name) == 0)
1544 /* The requested filter has been found. Abort search. */
1550 /* No filter with the given name and type exists. */
1556 /*********************************************************************
1558 * Function : pcrs_filter_response
1560 * Description : Execute all text substitutions from all applying
1561 * +filter actions on the text buffer that's been
1562 * accumulated in csp->iob->buf.
1565 * 1 : csp = Current client state (buffers, headers, etc...)
1567 * Returns : a pointer to the (newly allocated) modified buffer.
1568 * or NULL if there were no hits or something went wrong
1570 *********************************************************************/
1571 static char *pcrs_filter_response(struct client_state *csp)
1574 size_t size, prev_size;
1580 struct re_filterfile_spec *b;
1581 struct list_entry *filtername;
1586 if (csp->iob->cur >= csp->iob->eod)
1591 if (filters_available(csp) == FALSE)
1593 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1594 "content filtering enabled, but no content filters available.");
1598 size = (size_t)(csp->iob->eod - csp->iob->cur);
1599 old = csp->iob->cur;
1602 * For all applying +filter actions, look if a filter by that
1603 * name exists and if yes, execute it's pcrs_joblist on the
1606 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1607 filtername != NULL; filtername = filtername->next)
1609 int current_hits = 0; /* Number of hits caused by this filter */
1610 int job_number = 0; /* Which job we're currently executing */
1611 int job_hits = 0; /* How many hits the current job caused */
1614 b = get_filter(csp, filtername->str, FT_CONTENT_FILTER);
1620 joblist = b->joblist;
1622 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1624 if (NULL == joblist)
1626 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1631 /* Apply all jobs from the joblist */
1632 for (job = joblist; NULL != job; job = job->next)
1635 job_hits = pcrs_execute(job, old, size, &new, &size);
1640 * That went well. Continue filtering
1641 * and use the result of this job as
1642 * input for the next one.
1644 current_hits += job_hits;
1645 if (old != csp->iob->cur)
1654 * This job caused an unexpected error. Inform the user
1655 * and skip the rest of the jobs in this filter. We could
1656 * continue with the next job, but usually the jobs
1657 * depend on each other or are similar enough to
1658 * fail for the same reason.
1660 * At the moment our pcrs expects the error codes of pcre 3.4,
1661 * but newer pcre versions can return additional error codes.
1662 * As a result pcrs_strerror()'s error message might be
1663 * "Unknown error ...", therefore we print the numerical value
1666 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1667 * should we use LOG_LEVEL_RE_FILTER instead?
1669 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1670 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1675 if (b->dynamic) pcrs_free_joblist(joblist);
1677 log_error(LOG_LEVEL_RE_FILTER,
1678 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1679 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1681 hits += current_hits;
1685 * If there were no hits, destroy our copy and let
1686 * chat() use the original in csp->iob
1694 csp->flags |= CSP_FLAG_MODIFIED;
1695 csp->content_length = size;
1696 clear_iob(csp->iob);
1703 #ifdef FEATURE_EXTERNAL_FILTERS
1704 /*********************************************************************
1706 * Function : get_external_filter
1708 * Description : Lookup the code to execute for an external filter.
1709 * Masks the misuse of the re_filterfile_spec.
1712 * 1 : csp = Current client state (buffers, headers, etc...)
1713 * 2 : name = Name of the content filter to get
1715 * Returns : A pointer to the requested code
1716 * or NULL if the filter wasn't found
1718 *********************************************************************/
1719 static const char *get_external_filter(const struct client_state *csp,
1722 struct re_filterfile_spec *external_filter;
1724 external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
1725 if (external_filter == NULL)
1727 log_error(LOG_LEVEL_FATAL,
1728 "Didn't find stuff to execute for external filter: %s",
1732 return external_filter->patterns->first->str;
1737 /*********************************************************************
1739 * Function : set_privoxy_variables
1741 * Description : Sets a couple of privoxy-specific environment variables
1744 * 1 : csp = Current client state (buffers, headers, etc...)
1748 *********************************************************************/
1749 static void set_privoxy_variables(const struct client_state *csp)
1756 { "PRIVOXY_URL", csp->http->url },
1757 { "PRIVOXY_PATH", csp->http->path },
1758 { "PRIVOXY_HOST", csp->http->host },
1759 { "PRIVOXY_ORIGIN", csp->ip_addr_str },
1762 for (i = 0; i < SZ(env); i++)
1764 if (setenv(env[i].name, env[i].value, 1))
1766 log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
1767 env[i].name, env[i].value);
1773 /*********************************************************************
1775 * Function : execute_external_filter
1777 * Description : Pipe content into external filter and return the output
1780 * 1 : csp = Current client state (buffers, headers, etc...)
1781 * 2 : name = Name of the external filter to execute
1782 * 3 : content = The original content to filter
1783 * 4 : size = The size of the content buffer
1785 * Returns : a pointer to the (newly allocated) modified buffer.
1786 * or NULL if there were no hits or something went wrong
1788 *********************************************************************/
1789 static char *execute_external_filter(const struct client_state *csp,
1790 const char *name, char *content, size_t *size)
1793 char file_name[FILENAME_MAX];
1795 char *filter_output;
1799 const char *external_filter;
1801 if (csp->config->temporary_directory == NULL)
1803 log_error(LOG_LEVEL_ERROR,
1804 "No temporary-directory configured. Can't execute filter: %s",
1809 external_filter = get_external_filter(csp, name);
1811 if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
1812 "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
1814 log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
1818 fd = mkstemp(file_name);
1821 log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
1825 fp = fdopen(fd, "w");
1828 log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
1834 * The size may be zero if a previous filter discarded everything.
1836 * This isn't necessary unintentional, so we just don't try
1837 * to fwrite() nothing and let the user deal with the rest.
1839 if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
1841 log_error(LOG_LEVEL_ERROR, "fwrite(..., %d, 1, ..) failed: %E", *size);
1848 if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
1850 log_error(LOG_LEVEL_ERROR,
1851 "temporary-directory or external filter path too long");
1856 log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
1859 * The locking is necessary to prevent other threads
1860 * from overwriting the environment variables before
1861 * the popen fork. Afterwards this no longer matters.
1863 privoxy_mutex_lock(&external_filter_mutex);
1864 set_privoxy_variables(csp);
1865 fp = popen(cmd, "r");
1866 privoxy_mutex_unlock(&external_filter_mutex);
1869 log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
1874 filter_output = malloc_or_die(*size);
1877 while (!feof(fp) && !ferror(fp))
1880 /* Could be bigger ... */
1881 enum { READ_LENGTH = 2048 };
1883 if (new_size + READ_LENGTH >= *size)
1887 /* Could be considered wasteful if the content is 'large'. */
1888 *size = (*size != 0) ? *size * 2 : READ_LENGTH;
1890 p = realloc(filter_output, *size);
1893 log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
1894 "external filter output. Using what we got so far.");
1899 len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
1909 log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
1913 log_error(LOG_LEVEL_RE_FILTER,
1914 "Executing '%s' resulted in return value %d. "
1915 "Read %d of up to %d bytes.", name, (ret >> 8), new_size, *size);
1921 return filter_output;
1924 #endif /* def FEATURE_EXTERNAL_FILTERS */
1927 /*********************************************************************
1929 * Function : gif_deanimate_response
1931 * Description : Deanimate the GIF image that has been accumulated in
1932 * csp->iob->buf, set csp->content_length to the modified
1933 * size and raise the CSP_FLAG_MODIFIED flag.
1936 * 1 : csp = Current client state (buffers, headers, etc...)
1938 * Returns : a pointer to the (newly allocated) modified buffer.
1939 * or NULL in case something went wrong.
1941 *********************************************************************/
1942 static char *gif_deanimate_response(struct client_state *csp)
1944 struct binbuffer *in, *out;
1948 size = (size_t)(csp->iob->eod - csp->iob->cur);
1950 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1951 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1953 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1957 in->buffer = csp->iob->cur;
1960 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1962 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1969 if ((int)size == out->offset)
1971 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1975 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1977 csp->content_length = out->offset;
1978 csp->flags |= CSP_FLAG_MODIFIED;
1988 /*********************************************************************
1990 * Function : get_filter_function
1992 * Description : Decides which content filter function has
1993 * to be applied (if any). Only considers functions
1994 * for internal filters which are mutually-exclusive.
1997 * 1 : csp = Current client state (buffers, headers, etc...)
1999 * Returns : The content filter function to run, or
2000 * NULL if no content filter is active
2002 *********************************************************************/
2003 static filter_function_ptr get_filter_function(const struct client_state *csp)
2005 filter_function_ptr filter_function = NULL;
2008 * Choose the applying filter function based on
2009 * the content type and action settings.
2011 if ((csp->content_type & CT_TEXT) &&
2012 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2014 filter_function = pcrs_filter_response;
2016 else if ((csp->content_type & CT_GIF) &&
2017 (csp->action->flags & ACTION_DEANIMATE))
2019 filter_function = gif_deanimate_response;
2022 return filter_function;
2026 /*********************************************************************
2028 * Function : remove_chunked_transfer_coding
2030 * Description : In-situ remove the "chunked" transfer coding as defined
2031 * in RFC 7230 4.1 from a buffer. XXX: The implementation
2032 * is neither complete nor compliant (TODO #129).
2035 * 1 : buffer = Pointer to the text buffer
2036 * 2 : size = In: Number of bytes to be processed,
2037 * Out: Number of bytes after de-chunking.
2038 * (undefined in case of errors)
2040 * Returns : JB_ERR_OK for success,
2041 * JB_ERR_PARSE otherwise
2043 *********************************************************************/
2044 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2047 unsigned int chunksize = 0;
2048 char *from_p, *to_p;
2051 from_p = to_p = buffer;
2053 if (sscanf(buffer, "%x", &chunksize) != 1)
2055 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2056 return JB_ERR_PARSE;
2059 while (chunksize > 0U)
2061 if (NULL == (from_p = strstr(from_p, "\r\n")))
2063 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2064 return JB_ERR_PARSE;
2067 if (chunksize >= *size - newsize)
2069 log_error(LOG_LEVEL_ERROR,
2070 "Chunk size %u exceeds buffered data left. "
2071 "Already digested %u of %u buffered bytes.",
2072 chunksize, (unsigned int)newsize, (unsigned int)*size);
2073 return JB_ERR_PARSE;
2075 newsize += chunksize;
2078 memmove(to_p, from_p, (size_t) chunksize);
2079 to_p = buffer + newsize;
2080 from_p += chunksize + 2;
2082 if (sscanf(from_p, "%x", &chunksize) != 1)
2084 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2089 /* XXX: Should get its own loglevel. */
2090 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
2099 /*********************************************************************
2101 * Function : prepare_for_filtering
2103 * Description : If necessary, de-chunks and decompresses
2104 * the content so it can get filterd.
2107 * 1 : csp = Current client state (buffers, headers, etc...)
2109 * Returns : JB_ERR_OK for success,
2110 * JB_ERR_PARSE otherwise
2112 *********************************************************************/
2113 static jb_err prepare_for_filtering(struct client_state *csp)
2115 jb_err err = JB_ERR_OK;
2118 * If the body has a "chunked" transfer-encoding,
2119 * get rid of it, adjusting size and iob->eod
2121 if (csp->flags & CSP_FLAG_CHUNKED)
2123 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2125 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2126 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2127 if (JB_ERR_OK == err)
2129 csp->iob->eod = csp->iob->cur + size;
2130 csp->flags |= CSP_FLAG_MODIFIED;
2134 return JB_ERR_PARSE;
2140 * If the body has a supported transfer-encoding,
2141 * decompress it, adjusting size and iob->eod.
2143 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
2145 if (0 == csp->iob->eod - csp->iob->cur)
2147 /* Nothing left after de-chunking. */
2151 err = decompress_iob(csp);
2153 if (JB_ERR_OK == err)
2155 csp->flags |= CSP_FLAG_MODIFIED;
2156 csp->content_type &= ~CT_TABOO;
2161 * Unset CT_GZIP and CT_DEFLATE to remember not
2162 * to modify the Content-Encoding header later.
2164 csp->content_type &= ~CT_GZIP;
2165 csp->content_type &= ~CT_DEFLATE;
2174 /*********************************************************************
2176 * Function : execute_content_filters
2178 * Description : Executes a given content filter.
2181 * 1 : csp = Current client state (buffers, headers, etc...)
2183 * Returns : Pointer to the modified buffer, or
2184 * NULL if filtering failed or wasn't necessary.
2186 *********************************************************************/
2187 char *execute_content_filters(struct client_state *csp)
2190 filter_function_ptr content_filter;
2192 assert(content_filters_enabled(csp->action));
2194 if (0 == csp->iob->eod - csp->iob->cur)
2197 * No content (probably status code 301, 302 ...),
2198 * no filtering necessary.
2203 if (JB_ERR_OK != prepare_for_filtering(csp))
2206 * failed to de-chunk or decompress.
2211 if (0 == csp->iob->eod - csp->iob->cur)
2214 * Clown alarm: chunked and/or compressed nothing delivered.
2219 content_filter = get_filter_function(csp);
2220 content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
2222 #ifdef FEATURE_EXTERNAL_FILTERS
2223 if ((csp->content_type & CT_TEXT) &&
2224 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
2226 struct list_entry *filtername;
2227 size_t size = (size_t)csp->content_length;
2229 if (content == NULL)
2231 content = csp->iob->cur;
2232 size = (size_t)(csp->iob->eod - csp->iob->cur);
2235 for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
2236 filtername ; filtername = filtername->next)
2238 char *result = execute_external_filter(csp, filtername->str, content, &size);
2241 if (content != csp->iob->cur)
2248 csp->flags |= CSP_FLAG_MODIFIED;
2249 csp->content_length = size;
2251 #endif /* def FEATURE_EXTERNAL_FILTERS */
2258 /*********************************************************************
2260 * Function : get_url_actions
2262 * Description : Gets the actions for this URL.
2265 * 1 : csp = Current client state (buffers, headers, etc...)
2266 * 2 : http = http_request request for blocked URLs
2270 *********************************************************************/
2271 void get_url_actions(struct client_state *csp, struct http_request *http)
2273 struct file_list *fl;
2274 struct url_actions *b;
2277 init_current_action(csp->action);
2279 for (i = 0; i < MAX_AF_FILES; i++)
2281 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2286 apply_url_actions(csp->action, http, b);
2293 /*********************************************************************
2295 * Function : apply_url_actions
2297 * Description : Applies a list of URL actions.
2300 * 1 : action = Destination.
2301 * 2 : http = Current URL
2302 * 3 : b = list of URL actions to apply
2306 *********************************************************************/
2307 void apply_url_actions(struct current_action_spec *action,
2308 struct http_request *http,
2309 struct url_actions *b)
2313 /* Should never happen */
2317 for (b = b->next; NULL != b; b = b->next)
2319 if (url_match(b->url, http))
2321 merge_current_action(action, b->action);
2327 /*********************************************************************
2329 * Function : get_forward_override_settings
2331 * Description : Returns forward settings as specified with the
2332 * forward-override{} action. forward-override accepts
2333 * forward lines similar to the one used in the
2334 * configuration file, but without the URL pattern.
2340 * in the configuration file can be replaced with
2341 * the action section:
2343 * {+forward-override{forward .}}
2347 * 1 : csp = Current client state (buffers, headers, etc...)
2349 * Returns : Pointer to forwarding structure in case of success.
2350 * Invalid syntax is fatal.
2352 *********************************************************************/
2353 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2355 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2356 char forward_settings[BUFFER_SIZE];
2357 char *http_parent = NULL;
2358 /* variable names were chosen for consistency reasons. */
2359 struct forward_spec *fwd = NULL;
2363 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2364 /* Should be enforced by load_one_actions_file() */
2365 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2367 /* Create a copy ssplit can modify */
2368 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2370 if (NULL != csp->fwd)
2373 * XXX: Currently necessary to prevent memory
2374 * leaks when the show-url-info cgi page is visited.
2376 unload_forward_spec(csp->fwd);
2380 * allocate a new forward node, valid only for
2381 * the lifetime of this request. Save its location
2382 * in csp as well, so sweep() can free it later on.
2384 fwd = csp->fwd = zalloc(sizeof(*fwd));
2387 log_error(LOG_LEVEL_FATAL,
2388 "can't allocate memory for forward-override{%s}", forward_override_line);
2389 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2393 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2394 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2396 fwd->type = SOCKS_NONE;
2398 /* Parse the parent HTTP proxy host:port */
2399 http_parent = vec[1];
2402 else if (vec_count == 3)
2404 char *socks_proxy = NULL;
2406 if (!strcasecmp(vec[0], "forward-socks4"))
2408 fwd->type = SOCKS_4;
2409 socks_proxy = vec[1];
2411 else if (!strcasecmp(vec[0], "forward-socks4a"))
2413 fwd->type = SOCKS_4A;
2414 socks_proxy = vec[1];
2416 else if (!strcasecmp(vec[0], "forward-socks5"))
2418 fwd->type = SOCKS_5;
2419 socks_proxy = vec[1];
2421 else if (!strcasecmp(vec[0], "forward-socks5t"))
2423 fwd->type = SOCKS_5T;
2424 socks_proxy = vec[1];
2427 if (NULL != socks_proxy)
2429 /* Parse the SOCKS proxy host[:port] */
2430 fwd->gateway_port = 1080;
2431 parse_forwarder_address(socks_proxy,
2432 &fwd->gateway_host, &fwd->gateway_port);
2434 http_parent = vec[2];
2438 if (NULL == http_parent)
2440 log_error(LOG_LEVEL_FATAL,
2441 "Invalid forward-override syntax in: %s", forward_override_line);
2442 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2445 /* Parse http forwarding settings */
2446 if (strcmp(http_parent, ".") != 0)
2448 fwd->forward_port = 8000;
2449 parse_forwarder_address(http_parent,
2450 &fwd->forward_host, &fwd->forward_port);
2453 assert (NULL != fwd);
2455 log_error(LOG_LEVEL_CONNECT,
2456 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2462 /*********************************************************************
2464 * Function : forward_url
2466 * Description : Should we forward this to another proxy?
2469 * 1 : csp = Current client state (buffers, headers, etc...)
2470 * 2 : http = http_request request for current URL
2472 * Returns : Pointer to forwarding information.
2474 *********************************************************************/
2475 const struct forward_spec *forward_url(struct client_state *csp,
2476 const struct http_request *http)
2478 static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
2479 struct forward_spec *fwd = csp->config->forward;
2481 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2483 return get_forward_override_settings(csp);
2493 if (url_match(fwd->url, http))
2504 /*********************************************************************
2506 * Function : direct_response
2508 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2509 * request and if so, return a HTTP 501 to the client.
2511 * FIXME: I have a stupid name and I should handle the
2512 * requests properly. Still, what we do here is rfc-
2513 * compliant, whereas ignoring or forwarding are not.
2516 * 1 : csp = Current client state (buffers, headers, etc...)
2518 * Returns : http_response if , NULL if nonmatch or handler fail
2520 *********************************************************************/
2521 struct http_response *direct_response(struct client_state *csp)
2523 struct http_response *rsp;
2524 struct list_entry *p;
2526 if ((0 == strcmpic(csp->http->gpc, "trace"))
2527 || (0 == strcmpic(csp->http->gpc, "options")))
2529 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2531 if (!strncmpic(p->str, "Max-Forwards:", 13))
2533 unsigned int max_forwards;
2536 * If it's a Max-Forwards value of zero,
2537 * we have to intercept the request.
2539 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2542 * FIXME: We could handle at least TRACE here,
2543 * but that would require a verbatim copy of
2544 * the request which we don't have anymore
2546 log_error(LOG_LEVEL_HEADER,
2547 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2550 /* Get mem for response or fail*/
2551 if (NULL == (rsp = alloc_http_response()))
2553 return cgi_error_memory();
2556 rsp->status = strdup_or_die("501 Not Implemented");
2558 rsp->crunch_reason = UNSUPPORTED;
2560 return(finish_http_response(csp, rsp));
2569 /*********************************************************************
2571 * Function : content_requires_filtering
2573 * Description : Checks whether there are any content filters
2574 * enabled for the current request and if they
2575 * can actually be applied..
2578 * 1 : csp = Current client state (buffers, headers, etc...)
2580 * Returns : TRUE for yes, FALSE otherwise
2582 *********************************************************************/
2583 int content_requires_filtering(struct client_state *csp)
2585 if ((csp->content_type & CT_TABOO)
2586 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2592 * Are we enabling text mode by force?
2594 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2597 * Do we really have to?
2599 if (csp->content_type & CT_TEXT)
2601 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2605 csp->content_type |= CT_TEXT;
2606 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2610 if (!(csp->content_type & CT_DECLARED))
2613 * The server didn't bother to declare a MIME-Type.
2614 * Assume it's text that can be filtered.
2616 * This also regulary happens with 304 responses,
2617 * therefore logging anything here would cause
2620 csp->content_type |= CT_TEXT;
2624 * Choose the applying filter function based on
2625 * the content type and action settings.
2627 if ((csp->content_type & CT_TEXT) &&
2628 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
2629 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
2633 else if ((csp->content_type & CT_GIF) &&
2634 (csp->action->flags & ACTION_DEANIMATE))
2644 /*********************************************************************
2646 * Function : content_filters_enabled
2648 * Description : Checks whether there are any content filters
2649 * enabled for the current request.
2652 * 1 : action = Action spec to check.
2654 * Returns : TRUE for yes, FALSE otherwise
2656 *********************************************************************/
2657 int content_filters_enabled(const struct current_action_spec *action)
2659 return ((action->flags & ACTION_DEANIMATE) ||
2660 !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
2661 !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
2665 /*********************************************************************
2667 * Function : filters_available
2669 * Description : Checks whether there are any filters available.
2672 * 1 : csp = Current client state (buffers, headers, etc...)
2674 * Returns : TRUE for yes, FALSE otherwise.
2676 *********************************************************************/
2677 int filters_available(const struct client_state *csp)
2680 for (i = 0; i < MAX_AF_FILES; i++)
2682 const struct file_list *fl = csp->rlist[i];
2683 if ((NULL != fl) && (NULL != fl->f))