1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2020 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
14 * This program is free software; you can redistribute it
15 * and/or modify it under the terms of the GNU General
16 * Public License as published by the Free Software
17 * Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * This program is distributed in the hope that it will
21 * be useful, but WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A
23 * PARTICULAR PURPOSE. See the GNU General Public
24 * License for more details.
26 * The GNU General Public License should be included with
27 * this file. If not, you can view it at
28 * http://www.gnu.org/copyleft/gpl.html
29 * or write to the Free Software Foundation, Inc., 59
30 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 *********************************************************************/
38 #include <sys/types.h>
47 #endif /* ndef __OS2__ */
48 #include <netinet/in.h>
51 #endif /* ndef _WIN32 */
55 #endif /* def __OS2__ */
63 #include "jbsockets.h"
69 #include "deanimate.h"
72 #ifdef FEATURE_CLIENT_TAGS
73 #include "client-tags.h"
80 typedef char *(*filter_function_ptr)();
81 static filter_function_ptr get_filter_function(const struct client_state *csp);
82 static jb_err prepare_for_filtering(struct client_state *csp);
83 static void apply_url_actions(struct current_action_spec *action,
84 struct http_request *http,
85 #ifdef FEATURE_CLIENT_TAGS
86 const struct list *client_tags,
88 struct url_actions *b);
90 #ifdef FEATURE_EXTENDED_STATISTICS
91 static void increment_block_reason_counter(const char *block_reason);
96 /*********************************************************************
98 * Function : sockaddr_storage_to_ip
100 * Description : Access internal structure of sockaddr_storage
103 * 1 : addr = socket address
104 * 2 : ip = IP address as array of octets in network order
105 * (it points into addr)
106 * 3 : len = length of IP address in octets
107 * 4 : port = port number in network order;
111 *********************************************************************/
112 static void sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
113 uint8_t **ip, unsigned int *len,
116 assert(NULL != addr);
117 assert(addr->ss_family == AF_INET || addr->ss_family == AF_INET6);
119 switch (addr->ss_family)
129 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
133 *port = &((struct sockaddr_in *)addr)->sin_port;
144 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
148 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
156 /*********************************************************************
158 * Function : match_sockaddr
160 * Description : Check whether address matches network (IP address and port)
163 * 1 : network = socket address of subnework
164 * 2 : netmask = network mask as socket address
165 * 3 : address = checked socket address against given network
167 * Returns : 0 = doesn't match; 1 = does match
169 *********************************************************************/
170 static int match_sockaddr(const struct sockaddr_storage *network,
171 const struct sockaddr_storage *netmask,
172 const struct sockaddr_storage *address)
174 uint8_t *network_addr, *netmask_addr, *address_addr;
175 unsigned int addr_len;
176 in_port_t *network_port, *netmask_port, *address_port;
179 if (network->ss_family != netmask->ss_family)
181 /* This should never happen */
182 assert(network->ss_family == netmask->ss_family);
183 log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
186 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
187 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
188 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
190 /* Check for family */
191 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
192 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
194 /* Map AF_INET6 V4MAPPED address into AF_INET */
198 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
199 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
201 /* Map AF_INET6 V4MAPPED network into AF_INET */
207 /* XXX: Port check is signaled in netmask */
208 if (*netmask_port && *network_port != *address_port)
213 /* TODO: Optimize by checking by words instead of octets */
214 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
216 if ((network_addr[i] & netmask_addr[i]) !=
217 (address_addr[i] & netmask_addr[i]))
225 #endif /* def HAVE_RFC2553 */
228 /*********************************************************************
230 * Function : block_acl
232 * Description : Block this request?
233 * Decide yes or no based on ACL file.
236 * 1 : dst = The proxy or gateway address this is going to.
237 * Or NULL to check all possible targets.
238 * 2 : csp = Current client state (buffers, headers, etc...)
239 * Also includes the client IP address.
241 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
243 *********************************************************************/
244 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
246 struct access_control_list *acl = csp->config->acl;
248 /* if not using an access control list, then permit the connection */
254 /* search the list */
259 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
261 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
267 /* Just want to check if they have any access */
268 if (acl->action == ACL_PERMIT)
280 * XXX: An undefined acl->dst is full of zeros and should be
281 * considered a wildcard address. sockaddr_storage_to_ip()
282 * fails on such destinations because of unknown sa_familly
283 * (glibc only?). However this test is not portable.
285 * So, we signal the acl->dst is wildcard in wildcard_dst.
288 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
290 ((dst->addr & acl->dst->mask) == acl->dst->addr)
291 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
295 if (acl->action == ACL_PERMIT)
313 /*********************************************************************
315 * Function : acl_addr
317 * Description : Called from `load_config' to parse an ACL address.
320 * 1 : aspec = String specifying ACL address.
321 * 2 : aca = struct access_control_addr to fill in.
323 * Returns : 0 => Ok, everything else is an error.
325 *********************************************************************/
326 int acl_addr(const char *aspec, struct access_control_addr *aca)
330 struct addrinfo hints, *result;
332 in_port_t *mask_port;
333 unsigned int addr_len;
336 #endif /* def HAVE_RFC2553 */
338 char *acl_spec = NULL;
341 /* XXX: Depend on ai_family */
349 * Use a temporary acl spec copy so we can log
350 * the unmodified original in case of parse errors.
352 acl_spec = strdup_or_die(aspec);
354 if ((p = strchr(acl_spec, '/')) != NULL)
357 if (privoxy_isdigit(*p) == 0)
362 masklength = atoi(p);
365 if ((masklength < 0) ||
377 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
380 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
389 p = strchr(acl_spec, ':');
399 memset(&hints, 0, sizeof(struct addrinfo));
400 hints.ai_family = AF_UNSPEC;
401 hints.ai_socktype = SOCK_STREAM;
403 i = getaddrinfo(acl_spec, p, &hints, &result);
407 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
408 acl_spec, p, gai_strerror(i));
414 /* TODO: Allow multihomed hostnames */
415 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
416 freeaddrinfo(result);
422 port = strtol(p, &endptr, 10);
424 if (port <= 0 || port > 65535 || *endptr != '\0')
431 aca->port = (unsigned long)port;
433 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
436 if (aca->addr == INADDR_NONE)
438 /* XXX: This will be logged as parse error. */
441 #endif /* def HAVE_RFC2553 */
443 /* build the netmask */
445 /* Clip masklength according to current family. */
446 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
451 aca->mask.ss_family = aca->addr.ss_family;
452 sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port);
456 /* ACL contains a port number, check ports in the future. */
461 * XXX: This could be optimized to operate on whole words instead
462 * of octets (128-bit CPU could do it in one iteration).
465 * Octets after prefix can be omitted because of
466 * previous initialization to zeros.
468 for (i = 0; (i < addr_len) && masklength; i++)
478 * XXX: This assumes MSB of octet is on the left side.
479 * This should be true for all architectures or solved
482 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
489 for (i=1; i <= masklength ; i++)
491 aca->mask |= (1U << (32 - i));
494 /* now mask off the host portion of the ip address
495 * (i.e. save on the network portion of the address).
497 aca->addr = aca->addr & aca->mask;
498 #endif /* def HAVE_RFC2553 */
503 #endif /* def FEATURE_ACL */
506 /*********************************************************************
508 * Function : connect_port_is_forbidden
510 * Description : Check to see if CONNECT requests to the destination
511 * port of this request are forbidden. The check is
512 * independent of the actual request method.
515 * 1 : csp = Current client state (buffers, headers, etc...)
517 * Returns : True if yes, false otherwise.
519 *********************************************************************/
520 int connect_port_is_forbidden(const struct client_state *csp)
522 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
523 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
528 /*********************************************************************
530 * Function : block_url
532 * Description : Called from `chat'. Check to see if we need to block this.
535 * 1 : csp = Current client state (buffers, headers, etc...)
537 * Returns : NULL => unblocked, else HTTP block response
539 *********************************************************************/
540 struct http_response *block_url(struct client_state *csp)
542 struct http_response *rsp;
543 const char *new_content_type = NULL;
546 * If it's not blocked, don't block it ;-)
548 if ((csp->action->flags & ACTION_BLOCK) == 0)
552 if (csp->action->flags & ACTION_REDIRECT)
554 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
557 * Else, prepare a response
559 if (NULL == (rsp = alloc_http_response()))
561 return cgi_error_memory();
564 #ifdef FEATURE_EXTENDED_STATISTICS
565 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
567 increment_block_reason_counter(csp->action->string[ACTION_STRING_BLOCK]);
572 * If it's an image-url, send back an image or redirect
573 * as specified by the relevant +image action
575 #ifdef FEATURE_IMAGE_BLOCKING
576 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
580 /* determine HOW images should be blocked */
581 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
583 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
585 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
588 /* and handle accordingly: */
589 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
591 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
592 rsp->body = bindup(image_pattern_data, image_pattern_length);
593 if (rsp->body == NULL)
595 free_http_response(rsp);
596 return cgi_error_memory();
598 rsp->content_length = image_pattern_length;
600 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
602 free_http_response(rsp);
603 return cgi_error_memory();
606 else if (0 == strcmpic(p, "blank"))
608 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
609 rsp->body = bindup(image_blank_data, image_blank_length);
610 if (rsp->body == NULL)
612 free_http_response(rsp);
613 return cgi_error_memory();
615 rsp->content_length = image_blank_length;
617 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
619 free_http_response(rsp);
620 return cgi_error_memory();
625 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
627 if (enlist_unique_header(rsp->headers, "Location", p))
629 free_http_response(rsp);
630 return cgi_error_memory();
636 #endif /* def FEATURE_IMAGE_BLOCKING */
637 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
640 * Send empty document.
642 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
645 rsp->body = strdup_or_die(" ");
646 rsp->content_length = 1;
648 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
651 * Workaround for firefox bug 492459
652 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
653 * Return a 200 OK status for pages blocked with +handle-as-empty-document
654 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
656 rsp->status = strdup_or_die("200 Request blocked by Privoxy");
660 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
663 if (new_content_type != 0)
665 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
666 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
668 free_http_response(rsp);
669 return cgi_error_memory();
676 * Else, generate an HTML "blocked" message:
680 struct map * exports;
682 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
684 exports = default_exports(csp, NULL);
687 free_http_response(rsp);
688 return cgi_error_memory();
691 #ifdef FEATURE_FORCE_LOAD
692 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
694 * Export the force conditional block killer if
696 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
697 * - Privoxy is configured to enforce blocks, or
698 * - it's a CONNECT request and enforcing wouldn't work anyway.
700 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
701 || (0 == strcmpic(csp->http->gpc, "connect")))
702 #endif /* ndef FEATURE_FORCE_LOAD */
704 err = map_block_killer(exports, "force-support");
707 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
708 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
709 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
710 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
713 const char *block_reason;
714 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
716 block_reason = csp->action->string[ACTION_STRING_BLOCK];
720 assert(connect_port_is_forbidden(csp));
721 block_reason = "Forbidden CONNECT port.";
723 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
728 free_http_response(rsp);
729 return cgi_error_memory();
732 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
735 free_http_response(rsp);
736 return cgi_error_memory();
739 rsp->crunch_reason = BLOCKED;
741 return finish_http_response(csp, rsp);
747 /*********************************************************************
749 * Function : trust_url FIXME: I should be called distrust_url
751 * Description : Calls is_untrusted_url to determine if the URL is trusted
752 * and if not, returns a HTTP 403 response with a reject message.
755 * 1 : csp = Current client state (buffers, headers, etc...)
757 * Returns : NULL => trusted, else http_response.
759 *********************************************************************/
760 struct http_response *trust_url(struct client_state *csp)
762 struct http_response *rsp;
763 struct map * exports;
764 char buf[BUFFER_SIZE];
766 struct pattern_spec **tl;
767 struct pattern_spec *t;
771 * Don't bother to work on trusted URLs
773 if (!is_untrusted_url(csp))
779 * Else, prepare a response:
781 if (NULL == (rsp = alloc_http_response()))
783 return cgi_error_memory();
786 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
787 exports = default_exports(csp, NULL);
790 free_http_response(rsp);
791 return cgi_error_memory();
795 * Export the protocol, host, port, and referrer information
797 err = map(exports, "hostport", 1, csp->http->hostport, 1);
798 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
799 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
801 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
803 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
807 if (!err) err = map(exports, "referrer", 1, "none set", 1);
813 free_http_response(rsp);
814 return cgi_error_memory();
818 * Export the trust list
820 p = strdup_or_die("");
821 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
823 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
824 string_append(&p, buf);
826 err = map(exports, "trusted-referrers", 1, p, 0);
831 free_http_response(rsp);
832 return cgi_error_memory();
836 * Export the trust info, if available
838 if (csp->config->trust_info->first)
840 struct list_entry *l;
842 p = strdup_or_die("");
843 for (l = csp->config->trust_info->first; l ; l = l->next)
845 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
846 string_append(&p, buf);
848 err = map(exports, "trust-info", 1, p, 0);
852 err = map_block_killer(exports, "have-trust-info");
858 free_http_response(rsp);
859 return cgi_error_memory();
863 * Export the force conditional block killer if
865 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
866 * - Privoxy is configured to enforce blocks, or
867 * - it's a CONNECT request and enforcing wouldn't work anyway.
869 #ifdef FEATURE_FORCE_LOAD
870 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
871 || (0 == strcmpic(csp->http->gpc, "connect")))
873 err = map_block_killer(exports, "force-support");
877 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
879 #else /* ifndef FEATURE_FORCE_LOAD */
880 err = map_block_killer(exports, "force-support");
881 #endif /* ndef FEATURE_FORCE_LOAD */
886 free_http_response(rsp);
887 return cgi_error_memory();
893 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
896 free_http_response(rsp);
897 return cgi_error_memory();
899 rsp->crunch_reason = UNTRUSTED;
901 return finish_http_response(csp, rsp);
903 #endif /* def FEATURE_TRUST */
906 /*********************************************************************
908 * Function : compile_dynamic_pcrs_job_list
910 * Description : Compiles a dynamic pcrs job list (one with variables
911 * resolved at request time)
914 * 1 : csp = Current client state (buffers, headers, etc...)
915 * 2 : b = The filter list to compile
917 * Returns : NULL in case of errors, otherwise the
920 *********************************************************************/
921 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
923 struct list_entry *pattern;
924 pcrs_job *job_list = NULL;
925 pcrs_job *dummy = NULL;
926 pcrs_job *lastjob = NULL;
929 const struct pcrs_variable variables[] =
931 {"url", csp->http->url, 1},
932 {"path", csp->http->path, 1},
933 {"host", csp->http->host, 1},
934 {"origin", csp->ip_addr_str, 1},
935 {"listen-address", csp->listen_addr_str, 1},
939 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
941 assert(pattern->str != NULL);
943 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
946 log_error(LOG_LEVEL_ERROR,
947 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
948 pattern->str, b->name, error, pcrs_strerror(error));
953 if (error == PCRS_WARN_TRUNCATION)
955 log_error(LOG_LEVEL_ERROR,
956 "At least one of the variables in \'%s\' had to "
957 "be truncated before compilation", pattern->str);
959 if (job_list == NULL)
965 lastjob->next = dummy;
975 /*********************************************************************
977 * Function : rewrite_url
979 * Description : Rewrites a URL with a single pcrs command
980 * and returns the result if it differs from the
981 * original and isn't obviously invalid.
984 * 1 : old_url = URL to rewrite.
985 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
988 * Returns : NULL if the pcrs_command didn't change the url, or
989 * the result of the modification.
991 *********************************************************************/
992 char *rewrite_url(char *old_url, const char *pcrs_command)
994 char *new_url = NULL;
998 assert(pcrs_command);
1000 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1004 log_error(LOG_LEVEL_REDIRECTS,
1005 "pcrs command \"%s\" didn't change \"%s\".",
1006 pcrs_command, old_url);
1011 log_error(LOG_LEVEL_REDIRECTS,
1012 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1013 pcrs_command, old_url, pcrs_strerror(hits));
1016 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1018 log_error(LOG_LEVEL_ERROR,
1019 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1020 "but the result doesn't look like a valid URL and will be ignored.",
1021 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1026 log_error(LOG_LEVEL_REDIRECTS,
1027 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1028 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1036 #ifdef FEATURE_FAST_REDIRECTS
1037 /*********************************************************************
1039 * Function : get_last_url
1041 * Description : Search for the last URL inside a string.
1042 * If the string already is a URL, it will
1043 * be the first URL found.
1046 * 1 : subject = the string to check
1047 * 2 : redirect_mode = +fast-redirect{} mode
1049 * Returns : NULL if no URL was found, or
1050 * the last URL found.
1052 *********************************************************************/
1053 static char *get_last_url(char *subject, const char *redirect_mode)
1055 char *new_url = NULL;
1059 assert(redirect_mode);
1061 subject = strdup(subject);
1062 if (subject == NULL)
1064 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1068 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1070 char *url_segment = NULL;
1071 char **url_segments;
1072 size_t max_segments;
1075 log_error(LOG_LEVEL_REDIRECTS,
1076 "Checking \"%s\" for encoded redirects.", subject);
1079 * Check each parameter in the URL separately.
1080 * Sectionize the URL at "?" and "&",
1081 * go backwards through the segments, URL-decode them
1082 * and look for a URL in the decoded result.
1083 * Stop the search after the first match.
1085 * XXX: This estimate is guaranteed to be high enough as we
1086 * let ssplit() ignore empty fields, but also a bit wasteful.
1088 max_segments = strlen(subject) / 2;
1089 url_segments = malloc(max_segments * sizeof(char *));
1091 if (NULL == url_segments)
1093 log_error(LOG_LEVEL_ERROR,
1094 "Out of memory while decoding URL: %s", subject);
1099 segments = ssplit(subject, "?&", url_segments, max_segments);
1101 while (segments-- > 0)
1103 char *dtoken = url_decode(url_segments[segments]);
1106 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1109 url_segment = strstr(dtoken, "http://");
1110 if (NULL == url_segment)
1112 url_segment = strstr(dtoken, "https://");
1114 if (NULL != url_segment)
1116 url_segment = strdup_or_die(url_segment);
1123 freez(url_segments);
1125 if (url_segment == NULL)
1129 subject = url_segment;
1133 /* Look for a URL inside this one, without decoding anything. */
1134 log_error(LOG_LEVEL_REDIRECTS,
1135 "Checking \"%s\" for unencoded redirects.", subject);
1139 * Find the last URL encoded in the request
1142 while ((tmp = strstr(tmp, "http://")) != NULL)
1146 tmp = (new_url != NULL) ? new_url : subject;
1147 while ((tmp = strstr(tmp, "https://")) != NULL)
1152 if ((new_url != NULL)
1153 && ( (new_url != subject)
1154 || (0 == strncmpic(subject, "http://", 7))
1155 || (0 == strncmpic(subject, "https://", 8))
1159 * Return new URL if we found a redirect
1160 * or if the subject already was a URL.
1162 * The second case makes sure that we can
1163 * chain get_last_url after another redirection check
1164 * (like rewrite_url) without losing earlier redirects.
1166 new_url = strdup(new_url);
1175 #endif /* def FEATURE_FAST_REDIRECTS */
1178 /*********************************************************************
1180 * Function : redirect_url
1182 * Description : Checks if Privoxy should answer the request with
1183 * a HTTP redirect and generates the redirect if
1187 * 1 : csp = Current client state (buffers, headers, etc...)
1189 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1191 *********************************************************************/
1192 struct http_response *redirect_url(struct client_state *csp)
1194 struct http_response *rsp;
1195 #ifdef FEATURE_FAST_REDIRECTS
1197 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1198 * as compile-time option? The user can easily disable
1199 * it in his action file.
1201 char * redirect_mode;
1202 #endif /* def FEATURE_FAST_REDIRECTS */
1203 char *old_url = NULL;
1204 char *new_url = NULL;
1205 char *redirection_string;
1207 if ((csp->action->flags & ACTION_REDIRECT))
1209 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1212 * If the redirection string begins with 's',
1213 * assume it's a pcrs command, otherwise treat it as
1214 * properly formatted URL and use it for the redirection
1217 * According to (the now obsolete) RFC 2616 section 14.30
1218 * the URL has to be absolute and if the user tries:
1219 * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
1220 * she would get undefined results anyway.
1222 * RFC 7231 7.1.2 actually allows relative references,
1223 * but those start with a leading slash (RFC 3986 4.2) and
1224 * thus can't be mistaken for pcrs commands either.
1227 if (*redirection_string == 's')
1229 old_url = csp->http->url;
1230 new_url = rewrite_url(old_url, redirection_string);
1234 log_error(LOG_LEVEL_REDIRECTS,
1235 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1236 redirection_string);
1237 new_url = strdup(redirection_string);
1241 #ifdef FEATURE_FAST_REDIRECTS
1242 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1244 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1247 * If it exists, use the previously rewritten URL as input
1248 * otherwise just use the old path.
1250 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1251 new_url = get_last_url(old_url, redirect_mode);
1256 * Disable redirect checkers, so that they
1257 * will be only run more than once if the user
1258 * also enables them through tags.
1260 * From a performance point of view
1261 * it doesn't matter, but the duplicated
1262 * log messages are annoying.
1264 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1265 #endif /* def FEATURE_FAST_REDIRECTS */
1266 csp->action->flags &= ~ACTION_REDIRECT;
1268 /* Did any redirect action trigger? */
1271 if (url_requires_percent_encoding(new_url))
1274 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1275 strlen(new_url), new_url);
1276 encoded_url = percent_encode_url(new_url);
1278 if (encoded_url == NULL)
1280 return cgi_error_memory();
1282 new_url = encoded_url;
1283 assert(FALSE == url_requires_percent_encoding(new_url));
1286 if (0 == strcmpic(new_url, csp->http->url))
1288 log_error(LOG_LEVEL_ERROR,
1289 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1290 csp->http->url, new_url);
1295 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1297 if (NULL == (rsp = alloc_http_response()))
1300 return cgi_error_memory();
1303 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
1304 if (enlist_unique_header(rsp->headers, "Location", new_url))
1307 free_http_response(rsp);
1308 return cgi_error_memory();
1310 rsp->crunch_reason = REDIRECTED;
1313 return finish_http_response(csp, rsp);
1317 /* Only reached if no redirect is required */
1323 #ifdef FEATURE_IMAGE_BLOCKING
1324 /*********************************************************************
1326 * Function : is_imageurl
1328 * Description : Given a URL, decide whether it should be treated
1329 * as image URL or not.
1332 * 1 : csp = Current client state (buffers, headers, etc...)
1334 * Returns : True (nonzero) if URL is an image URL, false (0)
1337 *********************************************************************/
1338 int is_imageurl(const struct client_state *csp)
1340 return ((csp->action->flags & ACTION_IMAGE) != 0);
1343 #endif /* def FEATURE_IMAGE_BLOCKING */
1346 #ifdef FEATURE_TRUST
1347 /*********************************************************************
1349 * Function : is_untrusted_url
1351 * Description : Should we "distrust" this URL (and block it)?
1353 * Yes if it matches a line in the trustfile, or if the
1354 * referrer matches a line starting with "+" in the
1359 * 1 : csp = Current client state (buffers, headers, etc...)
1361 * Returns : 0 => trusted, 1 => untrusted
1363 *********************************************************************/
1364 int is_untrusted_url(const struct client_state *csp)
1366 struct file_list *fl;
1367 struct block_spec *b;
1368 struct pattern_spec **trusted_url;
1369 struct http_request rhttp[1];
1370 const char * referer;
1374 * If we don't have a trustlist, we trust everybody
1376 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1381 memset(rhttp, '\0', sizeof(*rhttp));
1384 * Do we trust the request URL itself?
1386 for (b = b->next; b ; b = b->next)
1388 if (url_match(b->url, csp->http))
1394 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1396 /* no referrer was supplied */
1402 * If not, do we maybe trust its referrer?
1404 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1410 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1412 if (url_match(*trusted_url, rhttp))
1414 /* if the URL's referrer is from a trusted referrer, then
1415 * add the target spec to the trustfile as an unblocked
1416 * domain and return 0 (which means it's OK).
1421 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1425 char * new_entry = strdup_or_die("~");
1427 string_append(&new_entry, csp->http->hostport);
1429 path = csp->http->path;
1430 if ( (path[0] == '/')
1432 && ((path_end = strchr(path + 2, '/')) != NULL))
1434 /* since this path points into a user's home space
1435 * be sure to include this spec in the trustfile.
1437 long path_len = path_end - path; /* save offset */
1438 path = strdup(path); /* Copy string */
1441 path_end = path + path_len; /* regenerate ptr to new buffer */
1442 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1444 string_join(&new_entry, path);
1448 * Give a reason for generating this entry.
1450 string_append(&new_entry, " # Trusted referrer was: ");
1451 string_append(&new_entry, referer);
1453 if (new_entry != NULL)
1455 if (-1 == fprintf(fp, "%s\n", new_entry))
1457 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1458 new_entry, csp->config->trustfile);
1464 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1465 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1472 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1473 csp->http->hostport, csp->config->trustfile);
1481 #endif /* def FEATURE_TRUST */
1484 /*********************************************************************
1486 * Function : get_filter
1488 * Description : Get a filter with a given name and type.
1489 * Note that taggers are filters, too.
1492 * 1 : csp = Current client state (buffers, headers, etc...)
1493 * 2 : requested_name = Name of the content filter to get
1494 * 3 : requested_type = Type of the filter to tagger to lookup
1496 * Returns : A pointer to the requested filter
1497 * or NULL if the filter wasn't found
1499 *********************************************************************/
1500 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1501 const char *requested_name,
1502 enum filter_type requested_type)
1505 struct re_filterfile_spec *b;
1506 struct file_list *fl;
1508 for (i = 0; i < MAX_AF_FILES; i++)
1511 if ((NULL == fl) || (NULL == fl->f))
1514 * Either there are no filter files left or this
1515 * filter file just contains no valid filters.
1517 * Continue to be sure we don't miss valid filter
1518 * files that are chained after empty or invalid ones.
1523 for (b = fl->f; b != NULL; b = b->next)
1525 if (b->type != requested_type)
1527 /* The callers isn't interested in this filter type. */
1530 if (strcmp(b->name, requested_name) == 0)
1532 /* The requested filter has been found. Abort search. */
1538 /* No filter with the given name and type exists. */
1544 /*********************************************************************
1546 * Function : pcrs_filter_response
1548 * Description : Execute all text substitutions from all applying
1549 * +filter actions on the text buffer that's been
1550 * accumulated in csp->iob->buf.
1553 * 1 : csp = Current client state (buffers, headers, etc...)
1555 * Returns : a pointer to the (newly allocated) modified buffer.
1556 * or NULL if there were no hits or something went wrong
1558 *********************************************************************/
1559 static char *pcrs_filter_response(struct client_state *csp)
1562 size_t size, prev_size;
1568 struct re_filterfile_spec *b;
1569 struct list_entry *filtername;
1574 if (csp->iob->cur >= csp->iob->eod)
1579 if (filters_available(csp) == FALSE)
1581 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1582 "content filtering enabled, but no content filters available.");
1586 size = (size_t)(csp->iob->eod - csp->iob->cur);
1587 old = csp->iob->cur;
1590 * For all applying +filter actions, look if a filter by that
1591 * name exists and if yes, execute it's pcrs_joblist on the
1594 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1595 filtername != NULL; filtername = filtername->next)
1597 int current_hits = 0; /* Number of hits caused by this filter */
1598 int job_number = 0; /* Which job we're currently executing */
1599 int job_hits = 0; /* How many hits the current job caused */
1602 b = get_filter(csp, filtername->str, FT_CONTENT_FILTER);
1608 joblist = b->joblist;
1610 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1612 if (NULL == joblist)
1614 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1619 /* Apply all jobs from the joblist */
1620 for (job = joblist; NULL != job; job = job->next)
1623 job_hits = pcrs_execute(job, old, size, &new, &size);
1628 * That went well. Continue filtering
1629 * and use the result of this job as
1630 * input for the next one.
1632 current_hits += job_hits;
1633 if (old != csp->iob->cur)
1642 * This job caused an unexpected error. Inform the user
1643 * and skip the rest of the jobs in this filter. We could
1644 * continue with the next job, but usually the jobs
1645 * depend on each other or are similar enough to
1646 * fail for the same reason.
1648 * At the moment our pcrs expects the error codes of pcre 3.4,
1649 * but newer pcre versions can return additional error codes.
1650 * As a result pcrs_strerror()'s error message might be
1651 * "Unknown error ...", therefore we print the numerical value
1654 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1655 * should we use LOG_LEVEL_RE_FILTER instead?
1657 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1658 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1663 if (b->dynamic) pcrs_free_joblist(joblist);
1665 log_error(LOG_LEVEL_RE_FILTER,
1666 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1667 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1668 #ifdef FEATURE_EXTENDED_STATISTICS
1669 update_filter_statistics(b->name, current_hits);
1671 hits += current_hits;
1675 * If there were no hits, destroy our copy and let
1676 * chat() use the original in csp->iob
1684 csp->flags |= CSP_FLAG_MODIFIED;
1685 csp->content_length = size;
1686 clear_iob(csp->iob);
1693 #ifdef FEATURE_EXTERNAL_FILTERS
1694 /*********************************************************************
1696 * Function : get_external_filter
1698 * Description : Lookup the code to execute for an external filter.
1699 * Masks the misuse of the re_filterfile_spec.
1702 * 1 : csp = Current client state (buffers, headers, etc...)
1703 * 2 : name = Name of the content filter to get
1705 * Returns : A pointer to the requested code
1706 * or NULL if the filter wasn't found
1708 *********************************************************************/
1709 static const char *get_external_filter(const struct client_state *csp,
1712 struct re_filterfile_spec *external_filter;
1714 external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
1715 if (external_filter == NULL)
1717 log_error(LOG_LEVEL_FATAL,
1718 "Didn't find stuff to execute for external filter: %s",
1722 return external_filter->patterns->first->str;
1727 /*********************************************************************
1729 * Function : set_privoxy_variables
1731 * Description : Sets a couple of privoxy-specific environment variables
1734 * 1 : csp = Current client state (buffers, headers, etc...)
1738 *********************************************************************/
1739 static void set_privoxy_variables(const struct client_state *csp)
1746 { "PRIVOXY_URL", csp->http->url },
1747 { "PRIVOXY_PATH", csp->http->path },
1748 { "PRIVOXY_HOST", csp->http->host },
1749 { "PRIVOXY_ORIGIN", csp->ip_addr_str },
1750 { "PRIVOXY_LISTEN_ADDRESS", csp->listen_addr_str },
1753 for (i = 0; i < SZ(env); i++)
1755 if (setenv(env[i].name, env[i].value, 1))
1757 log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
1758 env[i].name, env[i].value);
1764 /*********************************************************************
1766 * Function : execute_external_filter
1768 * Description : Pipe content into external filter and return the output
1771 * 1 : csp = Current client state (buffers, headers, etc...)
1772 * 2 : name = Name of the external filter to execute
1773 * 3 : content = The original content to filter
1774 * 4 : size = The size of the content buffer
1776 * Returns : a pointer to the (newly allocated) modified buffer.
1777 * or NULL if there were no hits or something went wrong
1779 *********************************************************************/
1780 static char *execute_external_filter(const struct client_state *csp,
1781 const char *name, char *content, size_t *size)
1784 char file_name[FILENAME_MAX];
1786 char *filter_output;
1790 const char *external_filter;
1792 if (csp->config->temporary_directory == NULL)
1794 log_error(LOG_LEVEL_ERROR,
1795 "No temporary-directory configured. Can't execute filter: %s",
1800 external_filter = get_external_filter(csp, name);
1802 if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
1803 "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
1805 log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
1809 fd = mkstemp(file_name);
1812 log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
1816 fp = fdopen(fd, "w");
1819 log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
1825 * The size may be zero if a previous filter discarded everything.
1827 * This isn't necessary unintentional, so we just don't try
1828 * to fwrite() nothing and let the user deal with the rest.
1830 if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
1832 log_error(LOG_LEVEL_ERROR, "fwrite(..., %d, 1, ..) failed: %E", *size);
1839 if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
1841 log_error(LOG_LEVEL_ERROR,
1842 "temporary-directory or external filter path too long");
1847 log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
1850 * The locking is necessary to prevent other threads
1851 * from overwriting the environment variables before
1852 * the popen fork. Afterwards this no longer matters.
1854 privoxy_mutex_lock(&external_filter_mutex);
1855 set_privoxy_variables(csp);
1856 fp = popen(cmd, "r");
1857 privoxy_mutex_unlock(&external_filter_mutex);
1860 log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
1865 /* Allocate at least one byte */
1866 filter_output = malloc_or_die(*size + 1);
1869 while (!feof(fp) && !ferror(fp))
1872 /* Could be bigger ... */
1873 enum { READ_LENGTH = 2048 };
1875 if (new_size + READ_LENGTH >= *size)
1879 /* Could be considered wasteful if the content is 'large'. */
1880 *size += (*size >= READ_LENGTH) ? *size : READ_LENGTH;
1882 p = realloc(filter_output, *size);
1885 log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
1886 "external filter output. Using what we got so far.");
1891 assert(new_size + READ_LENGTH < *size);
1892 len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
1902 log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
1906 log_error(LOG_LEVEL_RE_FILTER,
1907 "Executing '%s' resulted in return value %d. "
1908 "Read %d of up to %d bytes.", name, (ret >> 8), new_size, *size);
1914 return filter_output;
1917 #endif /* def FEATURE_EXTERNAL_FILTERS */
1920 /*********************************************************************
1922 * Function : gif_deanimate_response
1924 * Description : Deanimate the GIF image that has been accumulated in
1925 * csp->iob->buf, set csp->content_length to the modified
1926 * size and raise the CSP_FLAG_MODIFIED flag.
1929 * 1 : csp = Current client state (buffers, headers, etc...)
1931 * Returns : a pointer to the (newly allocated) modified buffer.
1932 * or NULL in case something went wrong.
1934 *********************************************************************/
1936 char *gif_deanimate_response(struct client_state *csp)
1938 static char *gif_deanimate_response(struct client_state *csp)
1941 struct binbuffer *in, *out;
1945 size = (size_t)(csp->iob->eod - csp->iob->cur);
1947 in = zalloc_or_die(sizeof(*in));
1948 out = zalloc_or_die(sizeof(*out));
1950 in->buffer = csp->iob->cur;
1953 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1955 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1962 if ((int)size == out->offset)
1964 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1968 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1970 csp->content_length = out->offset;
1971 csp->flags |= CSP_FLAG_MODIFIED;
1981 /*********************************************************************
1983 * Function : get_filter_function
1985 * Description : Decides which content filter function has
1986 * to be applied (if any). Only considers functions
1987 * for internal filters which are mutually-exclusive.
1990 * 1 : csp = Current client state (buffers, headers, etc...)
1992 * Returns : The content filter function to run, or
1993 * NULL if no content filter is active
1995 *********************************************************************/
1996 static filter_function_ptr get_filter_function(const struct client_state *csp)
1998 filter_function_ptr filter_function = NULL;
2001 * Choose the applying filter function based on
2002 * the content type and action settings.
2004 if ((csp->content_type & CT_TEXT) &&
2005 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2007 filter_function = pcrs_filter_response;
2009 else if ((csp->content_type & CT_GIF) &&
2010 (csp->action->flags & ACTION_DEANIMATE))
2012 filter_function = gif_deanimate_response;
2015 return filter_function;
2019 /*********************************************************************
2021 * Function : remove_chunked_transfer_coding
2023 * Description : In-situ remove the "chunked" transfer coding as defined
2024 * in RFC 7230 4.1 from a buffer. XXX: The implementation
2025 * is neither complete nor compliant (TODO #129).
2028 * 1 : buffer = Pointer to the text buffer
2029 * 2 : size = In: Number of bytes to be processed,
2030 * Out: Number of bytes after de-chunking.
2031 * (undefined in case of errors)
2033 * Returns : JB_ERR_OK for success,
2034 * JB_ERR_PARSE otherwise
2036 *********************************************************************/
2038 extern jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2040 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2044 unsigned int chunksize = 0;
2045 char *from_p, *to_p;
2046 const char *end_of_buffer = buffer + *size;
2050 log_error(LOG_LEVEL_FATAL, "Invalid chunked input. Buffer is empty.");
2051 return JB_ERR_PARSE;
2055 from_p = to_p = buffer;
2057 if (sscanf(buffer, "%x", &chunksize) != 1)
2059 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2060 return JB_ERR_PARSE;
2063 while (chunksize > 0U)
2066 * If the chunk-size is valid, we should have at least
2067 * chunk-size bytes of chunk-data and five bytes of
2068 * meta data (chunk-size, CRLF, CRLF) left in the buffer.
2070 if (chunksize + 5 >= *size - newsize)
2072 log_error(LOG_LEVEL_ERROR,
2073 "Chunk size %u exceeds buffered data left. "
2074 "Already digested %u of %u buffered bytes.",
2075 chunksize, (unsigned int)newsize, (unsigned int)*size);
2076 return JB_ERR_PARSE;
2080 * Skip the chunk-size, the optional chunk-ext and the CRLF
2081 * that is supposed to be located directly before the start
2084 if (NULL == (from_p = strstr(from_p, "\r\n")))
2086 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2087 return JB_ERR_PARSE;
2092 * The previous strstr() does not enforce chunk-validity
2093 * and is sattisfied as long a CRLF is left in the buffer.
2095 * Make sure the bytes we consider chunk-data are within
2098 if (from_p + chunksize >= end_of_buffer)
2100 log_error(LOG_LEVEL_ERROR,
2101 "End of chunk is beyond the end of the buffer.");
2102 return JB_ERR_PARSE;
2105 memmove(to_p, from_p, (size_t) chunksize);
2106 newsize += chunksize;
2107 to_p = buffer + newsize;
2108 from_p += chunksize;
2111 * Not merging this check with the previous one allows us
2112 * to keep chunks without trailing CRLF. It's not clear
2113 * if we actually have to care about those, though.
2115 if (from_p + 2 >= end_of_buffer)
2117 log_error(LOG_LEVEL_ERROR, "Not enough room for trailing CRLF.");
2118 return JB_ERR_PARSE;
2121 if (sscanf(from_p, "%x", &chunksize) != 1)
2123 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2128 /* XXX: Should get its own loglevel. */
2129 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
2138 /*********************************************************************
2140 * Function : prepare_for_filtering
2142 * Description : If necessary, de-chunks and decompresses
2143 * the content so it can get filterd.
2146 * 1 : csp = Current client state (buffers, headers, etc...)
2148 * Returns : JB_ERR_OK for success,
2149 * JB_ERR_PARSE otherwise
2151 *********************************************************************/
2152 static jb_err prepare_for_filtering(struct client_state *csp)
2154 jb_err err = JB_ERR_OK;
2157 * If the body has a "chunked" transfer-encoding,
2158 * get rid of it, adjusting size and iob->eod
2160 if (csp->flags & CSP_FLAG_CHUNKED)
2162 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2164 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2165 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2166 if (JB_ERR_OK == err)
2168 csp->iob->eod = csp->iob->cur + size;
2169 csp->flags |= CSP_FLAG_MODIFIED;
2173 return JB_ERR_PARSE;
2179 * If the body has a supported transfer-encoding,
2180 * decompress it, adjusting size and iob->eod.
2182 if ((csp->content_type & (CT_GZIP|CT_DEFLATE))
2183 #ifdef FEATURE_BROTLI
2184 || (csp->content_type & CT_BROTLI)
2188 if (0 == csp->iob->eod - csp->iob->cur)
2190 /* Nothing left after de-chunking. */
2194 err = decompress_iob(csp);
2196 if (JB_ERR_OK == err)
2198 csp->flags |= CSP_FLAG_MODIFIED;
2199 csp->content_type &= ~CT_TABOO;
2204 * Unset content types to remember not to
2205 * modify the Content-Encoding header later.
2207 csp->content_type &= ~CT_GZIP;
2208 csp->content_type &= ~CT_DEFLATE;
2209 #ifdef FEATURE_BROTLI
2210 csp->content_type &= ~CT_BROTLI;
2220 /*********************************************************************
2222 * Function : execute_content_filters
2224 * Description : Executes a given content filter.
2227 * 1 : csp = Current client state (buffers, headers, etc...)
2229 * Returns : Pointer to the modified buffer, or
2230 * NULL if filtering failed or wasn't necessary.
2232 *********************************************************************/
2233 char *execute_content_filters(struct client_state *csp)
2236 filter_function_ptr content_filter;
2238 assert(content_filters_enabled(csp->action));
2240 if (0 == csp->iob->eod - csp->iob->cur)
2243 * No content (probably status code 301, 302 ...),
2244 * no filtering necessary.
2249 if (JB_ERR_OK != prepare_for_filtering(csp))
2252 * failed to de-chunk or decompress.
2257 if (0 == csp->iob->eod - csp->iob->cur)
2260 * Clown alarm: chunked and/or compressed nothing delivered.
2265 content_filter = get_filter_function(csp);
2266 content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
2268 #ifdef FEATURE_EXTERNAL_FILTERS
2269 if ((csp->content_type & CT_TEXT) &&
2270 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
2272 struct list_entry *filtername;
2273 size_t size = (size_t)csp->content_length;
2275 if (content == NULL)
2277 content = csp->iob->cur;
2278 size = (size_t)(csp->iob->eod - csp->iob->cur);
2281 for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
2282 filtername ; filtername = filtername->next)
2284 char *result = execute_external_filter(csp, filtername->str, content, &size);
2287 if (content != csp->iob->cur)
2294 csp->flags |= CSP_FLAG_MODIFIED;
2295 csp->content_length = size;
2297 #endif /* def FEATURE_EXTERNAL_FILTERS */
2304 /*********************************************************************
2306 * Function : get_url_actions
2308 * Description : Gets the actions for this URL.
2311 * 1 : csp = Current client state (buffers, headers, etc...)
2312 * 2 : http = http_request request for blocked URLs
2316 *********************************************************************/
2317 void get_url_actions(struct client_state *csp, struct http_request *http)
2319 struct file_list *fl;
2320 struct url_actions *b;
2323 init_current_action(csp->action);
2325 for (i = 0; i < MAX_AF_FILES; i++)
2327 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2332 #ifdef FEATURE_CLIENT_TAGS
2333 apply_url_actions(csp->action, http, csp->client_tags, b);
2335 apply_url_actions(csp->action, http, b);
2342 /*********************************************************************
2344 * Function : apply_url_actions
2346 * Description : Applies a list of URL actions.
2349 * 1 : action = Destination.
2350 * 2 : http = Current URL
2351 * 3 : client_tags = list of client tags
2352 * 4 : b = list of URL actions to apply
2356 *********************************************************************/
2357 static void apply_url_actions(struct current_action_spec *action,
2358 struct http_request *http,
2359 #ifdef FEATURE_CLIENT_TAGS
2360 const struct list *client_tags,
2362 struct url_actions *b)
2366 /* Should never happen */
2370 for (b = b->next; NULL != b; b = b->next)
2372 if (url_match(b->url, http))
2374 merge_current_action(action, b->action);
2376 #ifdef FEATURE_CLIENT_TAGS
2377 if (client_tag_match(b->url, client_tags))
2379 merge_current_action(action, b->action);
2386 /*********************************************************************
2388 * Function : get_forward_override_settings
2390 * Description : Returns forward settings as specified with the
2391 * forward-override{} action. forward-override accepts
2392 * forward lines similar to the one used in the
2393 * configuration file, but without the URL pattern.
2399 * in the configuration file can be replaced with
2400 * the action section:
2402 * {+forward-override{forward .}}
2406 * 1 : csp = Current client state (buffers, headers, etc...)
2408 * Returns : Pointer to forwarding structure in case of success.
2409 * Invalid syntax is fatal.
2411 *********************************************************************/
2412 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2414 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2415 char forward_settings[BUFFER_SIZE];
2416 char *http_parent = NULL;
2417 /* variable names were chosen for consistency reasons. */
2418 struct forward_spec *fwd = NULL;
2422 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2423 /* Should be enforced by load_one_actions_file() */
2424 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2426 /* Create a copy ssplit can modify */
2427 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2429 if (NULL != csp->fwd)
2432 * XXX: Currently necessary to prevent memory
2433 * leaks when the show-url-info cgi page is visited.
2435 unload_forward_spec(csp->fwd);
2439 * allocate a new forward node, valid only for
2440 * the lifetime of this request. Save its location
2441 * in csp as well, so sweep() can free it later on.
2443 fwd = csp->fwd = zalloc_or_die(sizeof(*fwd));
2445 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2446 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2448 fwd->type = SOCKS_NONE;
2450 /* Parse the parent HTTP proxy host:port */
2451 http_parent = vec[1];
2454 else if ((vec_count == 2) && !strcasecmp(vec[0], "forward-webserver"))
2456 fwd->type = FORWARD_WEBSERVER;
2458 /* Parse the parent HTTP server host:port */
2459 http_parent = vec[1];
2462 else if (vec_count == 3)
2464 char *socks_proxy = NULL;
2466 if (!strcasecmp(vec[0], "forward-socks4"))
2468 fwd->type = SOCKS_4;
2469 socks_proxy = vec[1];
2471 else if (!strcasecmp(vec[0], "forward-socks4a"))
2473 fwd->type = SOCKS_4A;
2474 socks_proxy = vec[1];
2476 else if (!strcasecmp(vec[0], "forward-socks5"))
2478 fwd->type = SOCKS_5;
2479 socks_proxy = vec[1];
2481 else if (!strcasecmp(vec[0], "forward-socks5t"))
2483 fwd->type = SOCKS_5T;
2484 socks_proxy = vec[1];
2487 if (NULL != socks_proxy)
2489 /* Parse the SOCKS proxy [user:pass@]host[:port] */
2490 fwd->gateway_port = 1080;
2491 parse_forwarder_address(socks_proxy,
2492 &fwd->gateway_host, &fwd->gateway_port,
2493 &fwd->auth_username, &fwd->auth_password);
2495 http_parent = vec[2];
2499 if (NULL == http_parent)
2501 log_error(LOG_LEVEL_FATAL,
2502 "Invalid forward-override syntax in: %s", forward_override_line);
2503 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2506 /* Parse http forwarding settings */
2507 if (strcmp(http_parent, ".") != 0)
2509 fwd->forward_port = 8000;
2510 parse_forwarder_address(http_parent,
2511 &fwd->forward_host, &fwd->forward_port,
2515 assert (NULL != fwd);
2517 log_error(LOG_LEVEL_CONNECT,
2518 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2524 /*********************************************************************
2526 * Function : forward_url
2528 * Description : Should we forward this to another proxy?
2531 * 1 : csp = Current client state (buffers, headers, etc...)
2532 * 2 : http = http_request request for current URL
2534 * Returns : Pointer to forwarding information.
2536 *********************************************************************/
2537 const struct forward_spec *forward_url(struct client_state *csp,
2538 const struct http_request *http)
2540 static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
2541 struct forward_spec *fwd = csp->config->forward;
2543 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2545 return get_forward_override_settings(csp);
2555 if (url_match(fwd->url, http))
2566 /*********************************************************************
2568 * Function : direct_response
2570 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2571 * request and if so, return a HTTP 501 to the client.
2573 * FIXME: I have a stupid name and I should handle the
2574 * requests properly. Still, what we do here is rfc-
2575 * compliant, whereas ignoring or forwarding are not.
2578 * 1 : csp = Current client state (buffers, headers, etc...)
2580 * Returns : http_response if , NULL if nonmatch or handler fail
2582 *********************************************************************/
2583 struct http_response *direct_response(struct client_state *csp)
2585 struct http_response *rsp;
2586 struct list_entry *p;
2588 if ((0 == strcmpic(csp->http->gpc, "trace"))
2589 || (0 == strcmpic(csp->http->gpc, "options")))
2591 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2593 if (!strncmpic(p->str, "Max-Forwards:", 13))
2595 unsigned int max_forwards;
2598 * If it's a Max-Forwards value of zero,
2599 * we have to intercept the request.
2601 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2604 * FIXME: We could handle at least TRACE here,
2605 * but that would require a verbatim copy of
2606 * the request which we don't have anymore
2608 log_error(LOG_LEVEL_HEADER,
2609 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2612 /* Get mem for response or fail*/
2613 if (NULL == (rsp = alloc_http_response()))
2615 return cgi_error_memory();
2618 rsp->status = strdup_or_die("501 Not Implemented");
2620 rsp->crunch_reason = UNSUPPORTED;
2622 return(finish_http_response(csp, rsp));
2631 /*********************************************************************
2633 * Function : content_requires_filtering
2635 * Description : Checks whether there are any content filters
2636 * enabled for the current request and if they
2637 * can actually be applied..
2640 * 1 : csp = Current client state (buffers, headers, etc...)
2642 * Returns : TRUE for yes, FALSE otherwise
2644 *********************************************************************/
2645 int content_requires_filtering(struct client_state *csp)
2647 if ((csp->content_type & CT_TABOO)
2648 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2654 * Are we enabling text mode by force?
2656 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2659 * Do we really have to?
2661 if (csp->content_type & CT_TEXT)
2663 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2667 csp->content_type |= CT_TEXT;
2668 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2672 if (!(csp->content_type & CT_DECLARED))
2675 * The server didn't bother to declare a MIME-Type.
2676 * Assume it's text that can be filtered.
2678 * This also regulary happens with 304 responses,
2679 * therefore logging anything here would cause
2682 csp->content_type |= CT_TEXT;
2686 * Choose the applying filter function based on
2687 * the content type and action settings.
2689 if ((csp->content_type & CT_TEXT) &&
2690 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
2691 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
2695 else if ((csp->content_type & CT_GIF) &&
2696 (csp->action->flags & ACTION_DEANIMATE))
2706 /*********************************************************************
2708 * Function : content_filters_enabled
2710 * Description : Checks whether there are any content filters
2711 * enabled for the current request.
2714 * 1 : action = Action spec to check.
2716 * Returns : TRUE for yes, FALSE otherwise
2718 *********************************************************************/
2719 int content_filters_enabled(const struct current_action_spec *action)
2721 return ((action->flags & ACTION_DEANIMATE) ||
2722 !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
2723 !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
2727 /*********************************************************************
2729 * Function : filters_available
2731 * Description : Checks whether there are any filters available.
2734 * 1 : csp = Current client state (buffers, headers, etc...)
2736 * Returns : TRUE for yes, FALSE otherwise.
2738 *********************************************************************/
2739 int filters_available(const struct client_state *csp)
2742 for (i = 0; i < MAX_AF_FILES; i++)
2744 const struct file_list *fl = csp->rlist[i];
2745 if ((NULL != fl) && (NULL != fl->f))
2753 #ifdef FEATURE_EXTENDED_STATISTICS
2755 struct filter_statistics_entry
2758 unsigned long long executions;
2759 unsigned long long pages_modified;
2760 unsigned long long hits;
2762 struct filter_statistics_entry *next;
2765 static struct filter_statistics_entry *filter_statistics = NULL;
2768 /*********************************************************************
2770 * Function : register_filter_for_statistics
2772 * Description : Registers a filter so we can gather statistics for
2773 * it unless the filter has already been registered
2777 * 1 : filter = Name of the filter to register
2781 *********************************************************************/
2782 void register_filter_for_statistics(const char *filter)
2784 struct filter_statistics_entry *entry;
2786 privoxy_mutex_lock(&filter_statistics_mutex);
2788 if (filter_statistics == NULL)
2790 filter_statistics = zalloc_or_die(sizeof(struct filter_statistics_entry));
2791 entry = filter_statistics;
2792 entry->filter = strdup_or_die(filter);
2793 privoxy_mutex_unlock(&filter_statistics_mutex);
2796 entry = filter_statistics;
2797 while (entry != NULL)
2799 if (!strcmp(entry->filter, filter))
2801 /* Already registered, nothing to do. */
2804 if (entry->next == NULL)
2806 entry->next = zalloc_or_die(sizeof(struct filter_statistics_entry));
2807 entry->next->filter = strdup_or_die(filter);
2810 entry = entry->next;
2813 privoxy_mutex_unlock(&filter_statistics_mutex);
2818 /*********************************************************************
2820 * Function : update_filter_statistics
2822 * Description : Updates the statistics for a filter.
2825 * 1 : filter = Name of the filter to update
2826 * 2 : hits = Hit count.
2830 *********************************************************************/
2831 void update_filter_statistics(const char *filter, int hits)
2833 struct filter_statistics_entry *entry;
2835 privoxy_mutex_lock(&filter_statistics_mutex);
2837 entry = filter_statistics;
2838 while (entry != NULL)
2840 if (!strcmp(entry->filter, filter))
2842 entry->executions++;
2845 entry->pages_modified++;
2846 entry->hits += (unsigned)hits;
2850 entry = entry->next;
2853 privoxy_mutex_unlock(&filter_statistics_mutex);
2858 /*********************************************************************
2860 * Function : get_filter_statistics
2862 * Description : Gets the statistics for a filter.
2865 * 1 : filter = Name of the filter to get statistics for.
2866 * 2 : executions = Storage for the execution count.
2867 * 3 : pages_modified = Storage for the number of modified pages.
2868 * 4 : hits = Storage for the number of hits.
2872 *********************************************************************/
2873 void get_filter_statistics(const char *filter, unsigned long long *executions,
2874 unsigned long long *pages_modified,
2875 unsigned long long *hits)
2877 struct filter_statistics_entry *entry;
2879 privoxy_mutex_lock(&filter_statistics_mutex);
2881 entry = filter_statistics;
2882 while (entry != NULL)
2884 if (!strcmp(entry->filter, filter))
2886 *executions = entry->executions;
2887 *pages_modified = entry->pages_modified;
2888 *hits = entry->hits;
2891 entry = entry->next;
2894 privoxy_mutex_unlock(&filter_statistics_mutex);
2899 struct block_statistics_entry
2902 unsigned long long count;
2904 struct block_statistics_entry *next;
2907 static struct block_statistics_entry *block_statistics = NULL;
2909 /*********************************************************************
2911 * Function : register_block_reason_for_statistics
2913 * Description : Registers a block reason so we can gather statistics
2914 * for it unless the block reason has already been
2915 * registered before.
2918 * 1 : block_reason = Block reason to register
2922 *********************************************************************/
2923 void register_block_reason_for_statistics(const char *block_reason)
2925 struct block_statistics_entry *entry;
2927 privoxy_mutex_lock(&block_statistics_mutex);
2929 if (block_statistics == NULL)
2931 block_statistics = zalloc_or_die(sizeof(struct block_statistics_entry));
2932 entry = block_statistics;
2933 entry->block_reason = strdup_or_die(block_reason);
2934 privoxy_mutex_unlock(&block_statistics_mutex);
2937 entry = block_statistics;
2938 while (entry != NULL)
2940 if (!strcmp(entry->block_reason, block_reason))
2942 /* Already registered, nothing to do. */
2945 if (entry->next == NULL)
2947 entry->next = zalloc_or_die(sizeof(struct block_statistics_entry));
2948 entry->next->block_reason = strdup_or_die(block_reason);
2951 entry = entry->next;
2954 privoxy_mutex_unlock(&block_statistics_mutex);
2959 /*********************************************************************
2961 * Function : increment_block_reason_counter
2963 * Description : Updates the counter for a block reason.
2966 * 1 : block_reason = Block reason to count
2970 *********************************************************************/
2971 static void increment_block_reason_counter(const char *block_reason)
2973 struct block_statistics_entry *entry;
2975 privoxy_mutex_lock(&block_statistics_mutex);
2977 entry = block_statistics;
2978 while (entry != NULL)
2980 if (!strcmp(entry->block_reason, block_reason))
2985 entry = entry->next;
2988 privoxy_mutex_unlock(&block_statistics_mutex);
2993 /*********************************************************************
2995 * Function : get_block_reason_count
2997 * Description : Gets number of times a block reason was used.
3000 * 1 : block_reason = Block reason to get statistics for.
3001 * 2 : count = Storage for the number of times the block
3006 *********************************************************************/
3007 void get_block_reason_count(const char *block_reason, unsigned long long *count)
3009 struct block_statistics_entry *entry;
3011 privoxy_mutex_lock(&block_statistics_mutex);
3013 entry = block_statistics;
3014 while (entry != NULL)
3016 if (!strcmp(entry->block_reason, block_reason))
3018 *count = entry->count;
3021 entry = entry->next;
3024 privoxy_mutex_unlock(&block_statistics_mutex);
3028 #endif /* def FEATURE_EXTENDED_STATISTICS */