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>
46 #include <netinet/in.h>
49 #endif /* ndef _WIN32 */
57 #include "jbsockets.h"
63 #include "deanimate.h"
66 #ifdef FEATURE_CLIENT_TAGS
67 #include "client-tags.h"
74 typedef char *(*filter_function_ptr)();
75 static filter_function_ptr get_filter_function(const struct client_state *csp);
76 static jb_err prepare_for_filtering(struct client_state *csp);
77 static void apply_url_actions(struct current_action_spec *action,
78 struct http_request *http,
79 #ifdef FEATURE_CLIENT_TAGS
80 const struct list *client_tags,
82 struct url_actions *b);
84 #ifdef FEATURE_EXTENDED_STATISTICS
85 static void increment_block_reason_counter(const char *block_reason);
90 /*********************************************************************
92 * Function : sockaddr_storage_to_ip
94 * Description : Access internal structure of sockaddr_storage
97 * 1 : addr = socket address
98 * 2 : ip = IP address as array of octets in network order
99 * (it points into addr)
100 * 3 : len = length of IP address in octets
101 * 4 : port = port number in network order;
105 *********************************************************************/
106 static void sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
107 uint8_t **ip, unsigned int *len,
110 assert(NULL != addr);
111 assert(addr->ss_family == AF_INET || addr->ss_family == AF_INET6);
113 switch (addr->ss_family)
123 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
127 *port = &((struct sockaddr_in *)addr)->sin_port;
138 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
142 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
150 /*********************************************************************
152 * Function : match_sockaddr
154 * Description : Check whether address matches network (IP address and port)
157 * 1 : network = socket address of subnework
158 * 2 : netmask = network mask as socket address
159 * 3 : address = checked socket address against given network
161 * Returns : 0 = doesn't match; 1 = does match
163 *********************************************************************/
164 static int match_sockaddr(const struct sockaddr_storage *network,
165 const struct sockaddr_storage *netmask,
166 const struct sockaddr_storage *address)
168 uint8_t *network_addr, *netmask_addr, *address_addr;
169 unsigned int addr_len;
170 in_port_t *network_port, *netmask_port, *address_port;
173 if (network->ss_family != netmask->ss_family)
175 /* This should never happen */
176 assert(network->ss_family == netmask->ss_family);
177 log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
180 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
181 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
182 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
184 /* Check for family */
185 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
186 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
188 /* Map AF_INET6 V4MAPPED address into AF_INET */
192 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
193 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
195 /* Map AF_INET6 V4MAPPED network into AF_INET */
201 /* XXX: Port check is signaled in netmask */
202 if (*netmask_port && *network_port != *address_port)
207 /* TODO: Optimize by checking by words instead of octets */
208 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
210 if ((network_addr[i] & netmask_addr[i]) !=
211 (address_addr[i] & netmask_addr[i]))
219 #endif /* def HAVE_RFC2553 */
222 /*********************************************************************
224 * Function : block_acl
226 * Description : Block this request?
227 * Decide yes or no based on ACL file.
230 * 1 : dst = The proxy or gateway address this is going to.
231 * Or NULL to check all possible targets.
232 * 2 : csp = Current client state (buffers, headers, etc...)
233 * Also includes the client IP address.
235 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
237 *********************************************************************/
238 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
240 struct access_control_list *acl = csp->config->acl;
242 /* if not using an access control list, then permit the connection */
248 /* search the list */
253 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
255 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
261 /* Just want to check if they have any access */
262 if (acl->action == ACL_PERMIT)
274 * XXX: An undefined acl->dst is full of zeros and should be
275 * considered a wildcard address. sockaddr_storage_to_ip()
276 * fails on such destinations because of unknown sa_familly
277 * (glibc only?). However this test is not portable.
279 * So, we signal the acl->dst is wildcard in wildcard_dst.
282 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
284 ((dst->addr & acl->dst->mask) == acl->dst->addr)
285 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
289 if (acl->action == ACL_PERMIT)
307 /*********************************************************************
309 * Function : acl_addr
311 * Description : Called from `load_config' to parse an ACL address.
314 * 1 : aspec = String specifying ACL address.
315 * 2 : aca = struct access_control_addr to fill in.
317 * Returns : 0 => Ok, everything else is an error.
319 *********************************************************************/
320 int acl_addr(const char *aspec, struct access_control_addr *aca)
324 struct addrinfo hints, *result;
326 in_port_t *mask_port;
327 unsigned int addr_len;
330 #endif /* def HAVE_RFC2553 */
332 char *acl_spec = NULL;
335 /* XXX: Depend on ai_family */
343 * Use a temporary acl spec copy so we can log
344 * the unmodified original in case of parse errors.
346 acl_spec = strdup_or_die(aspec);
348 if ((p = strchr(acl_spec, '/')) != NULL)
351 if (privoxy_isdigit(*p) == 0)
356 masklength = atoi(p);
359 if ((masklength < 0) ||
371 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
374 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
383 p = strchr(acl_spec, ':');
393 memset(&hints, 0, sizeof(struct addrinfo));
394 hints.ai_family = AF_UNSPEC;
395 hints.ai_socktype = SOCK_STREAM;
397 i = getaddrinfo(acl_spec, p, &hints, &result);
401 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
402 acl_spec, p, gai_strerror(i));
408 /* TODO: Allow multihomed hostnames */
409 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
410 freeaddrinfo(result);
416 port = strtol(p, &endptr, 10);
418 if (port <= 0 || port > 65535 || *endptr != '\0')
425 aca->port = (unsigned long)port;
427 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
430 if (aca->addr == INADDR_NONE)
432 /* XXX: This will be logged as parse error. */
435 #endif /* def HAVE_RFC2553 */
437 /* build the netmask */
439 /* Clip masklength according to current family. */
440 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
445 aca->mask.ss_family = aca->addr.ss_family;
446 sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port);
450 /* ACL contains a port number, check ports in the future. */
455 * XXX: This could be optimized to operate on whole words instead
456 * of octets (128-bit CPU could do it in one iteration).
459 * Octets after prefix can be omitted because of
460 * previous initialization to zeros.
462 for (i = 0; (i < addr_len) && masklength; i++)
472 * XXX: This assumes MSB of octet is on the left side.
473 * This should be true for all architectures or solved
476 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
483 for (i=1; i <= masklength ; i++)
485 aca->mask |= (1U << (32 - i));
488 /* now mask off the host portion of the ip address
489 * (i.e. save on the network portion of the address).
491 aca->addr = aca->addr & aca->mask;
492 #endif /* def HAVE_RFC2553 */
497 #endif /* def FEATURE_ACL */
500 /*********************************************************************
502 * Function : connect_port_is_forbidden
504 * Description : Check to see if CONNECT requests to the destination
505 * port of this request are forbidden. The check is
506 * independent of the actual request method.
509 * 1 : csp = Current client state (buffers, headers, etc...)
511 * Returns : True if yes, false otherwise.
513 *********************************************************************/
514 int connect_port_is_forbidden(const struct client_state *csp)
516 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
517 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
522 /*********************************************************************
524 * Function : block_url
526 * Description : Called from `chat'. Check to see if we need to block this.
529 * 1 : csp = Current client state (buffers, headers, etc...)
531 * Returns : NULL => unblocked, else HTTP block response
533 *********************************************************************/
534 struct http_response *block_url(struct client_state *csp)
536 struct http_response *rsp;
537 const char *new_content_type = NULL;
540 * If it's not blocked, don't block it ;-)
542 if ((csp->action->flags & ACTION_BLOCK) == 0)
546 if (csp->action->flags & ACTION_REDIRECT)
548 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
551 * Else, prepare a response
553 if (NULL == (rsp = alloc_http_response()))
555 return cgi_error_memory();
558 #ifdef FEATURE_EXTENDED_STATISTICS
559 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
561 increment_block_reason_counter(csp->action->string[ACTION_STRING_BLOCK]);
566 * If it's an image-url, send back an image or redirect
567 * as specified by the relevant +image action
569 #ifdef FEATURE_IMAGE_BLOCKING
570 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
574 /* determine HOW images should be blocked */
575 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
577 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
579 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
582 /* and handle accordingly: */
583 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
585 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
586 rsp->body = bindup(image_pattern_data, image_pattern_length);
587 if (rsp->body == NULL)
589 free_http_response(rsp);
590 return cgi_error_memory();
592 rsp->content_length = image_pattern_length;
594 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
596 free_http_response(rsp);
597 return cgi_error_memory();
600 else if (0 == strcmpic(p, "blank"))
602 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
603 rsp->body = bindup(image_blank_data, image_blank_length);
604 if (rsp->body == NULL)
606 free_http_response(rsp);
607 return cgi_error_memory();
609 rsp->content_length = image_blank_length;
611 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
613 free_http_response(rsp);
614 return cgi_error_memory();
619 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
621 if (enlist_unique_header(rsp->headers, "Location", p))
623 free_http_response(rsp);
624 return cgi_error_memory();
630 #endif /* def FEATURE_IMAGE_BLOCKING */
631 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
634 * Send empty document.
636 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
639 rsp->body = strdup_or_die(" ");
640 rsp->content_length = 1;
642 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
645 * Workaround for firefox bug 492459
646 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
647 * Return a 200 OK status for pages blocked with +handle-as-empty-document
648 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
650 rsp->status = strdup_or_die("200 Request blocked by Privoxy");
654 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
657 if (new_content_type != 0)
659 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
660 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
662 free_http_response(rsp);
663 return cgi_error_memory();
670 * Else, generate an HTML "blocked" message:
674 struct map * exports;
676 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
678 exports = default_exports(csp, NULL);
681 free_http_response(rsp);
682 return cgi_error_memory();
685 #ifdef FEATURE_FORCE_LOAD
686 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
688 * Export the force conditional block killer if
690 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
691 * - Privoxy is configured to enforce blocks, or
692 * - it's a CONNECT request and enforcing wouldn't work anyway.
694 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
695 || (0 == strcmpic(csp->http->gpc, "connect")))
696 #endif /* ndef FEATURE_FORCE_LOAD */
698 err = map_block_killer(exports, "force-support");
701 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
702 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
703 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
704 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
707 const char *block_reason;
708 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
710 block_reason = csp->action->string[ACTION_STRING_BLOCK];
714 assert(connect_port_is_forbidden(csp));
715 block_reason = "Forbidden CONNECT port.";
717 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
722 free_http_response(rsp);
723 return cgi_error_memory();
726 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
729 free_http_response(rsp);
730 return cgi_error_memory();
733 rsp->crunch_reason = BLOCKED;
735 return finish_http_response(csp, rsp);
741 /*********************************************************************
743 * Function : trust_url FIXME: I should be called distrust_url
745 * Description : Calls is_untrusted_url to determine if the URL is trusted
746 * and if not, returns a HTTP 403 response with a reject message.
749 * 1 : csp = Current client state (buffers, headers, etc...)
751 * Returns : NULL => trusted, else http_response.
753 *********************************************************************/
754 struct http_response *trust_url(struct client_state *csp)
756 struct http_response *rsp;
757 struct map * exports;
758 char buf[BUFFER_SIZE];
760 struct pattern_spec **tl;
761 struct pattern_spec *t;
765 * Don't bother to work on trusted URLs
767 if (!is_untrusted_url(csp))
773 * Else, prepare a response:
775 if (NULL == (rsp = alloc_http_response()))
777 return cgi_error_memory();
780 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
781 exports = default_exports(csp, NULL);
784 free_http_response(rsp);
785 return cgi_error_memory();
789 * Export the protocol, host, port, and referrer information
791 err = map(exports, "hostport", 1, csp->http->hostport, 1);
792 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
793 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
795 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
797 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
801 if (!err) err = map(exports, "referrer", 1, "none set", 1);
807 free_http_response(rsp);
808 return cgi_error_memory();
812 * Export the trust list
814 p = strdup_or_die("");
815 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
817 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
818 string_append(&p, buf);
820 err = map(exports, "trusted-referrers", 1, p, 0);
825 free_http_response(rsp);
826 return cgi_error_memory();
830 * Export the trust info, if available
832 if (csp->config->trust_info->first)
834 struct list_entry *l;
836 p = strdup_or_die("");
837 for (l = csp->config->trust_info->first; l ; l = l->next)
839 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
840 string_append(&p, buf);
842 err = map(exports, "trust-info", 1, p, 0);
846 err = map_block_killer(exports, "have-trust-info");
852 free_http_response(rsp);
853 return cgi_error_memory();
857 * Export the force conditional block killer if
859 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
860 * - Privoxy is configured to enforce blocks, or
861 * - it's a CONNECT request and enforcing wouldn't work anyway.
863 #ifdef FEATURE_FORCE_LOAD
864 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
865 || (0 == strcmpic(csp->http->gpc, "connect")))
867 err = map_block_killer(exports, "force-support");
871 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
873 #else /* ifndef FEATURE_FORCE_LOAD */
874 err = map_block_killer(exports, "force-support");
875 #endif /* ndef FEATURE_FORCE_LOAD */
880 free_http_response(rsp);
881 return cgi_error_memory();
887 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
890 free_http_response(rsp);
891 return cgi_error_memory();
893 rsp->crunch_reason = UNTRUSTED;
895 return finish_http_response(csp, rsp);
897 #endif /* def FEATURE_TRUST */
900 /*********************************************************************
902 * Function : compile_dynamic_pcrs_job_list
904 * Description : Compiles a dynamic pcrs job list (one with variables
905 * resolved at request time)
908 * 1 : csp = Current client state (buffers, headers, etc...)
909 * 2 : b = The filter list to compile
911 * Returns : NULL in case of errors, otherwise the
914 *********************************************************************/
915 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
917 struct list_entry *pattern;
918 pcrs_job *job_list = NULL;
919 pcrs_job *dummy = NULL;
920 pcrs_job *lastjob = NULL;
923 const struct pcrs_variable variables[] =
925 {"url", csp->http->url, 1},
926 {"path", csp->http->path, 1},
927 {"host", csp->http->host, 1},
928 {"origin", csp->ip_addr_str, 1},
929 {"listen-address", csp->listen_addr_str, 1},
933 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
935 assert(pattern->str != NULL);
937 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
940 log_error(LOG_LEVEL_ERROR,
941 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
942 pattern->str, b->name, error, pcrs_strerror(error));
947 if (error == PCRS_WARN_TRUNCATION)
949 log_error(LOG_LEVEL_ERROR,
950 "At least one of the variables in \'%s\' had to "
951 "be truncated before compilation", pattern->str);
953 if (job_list == NULL)
959 lastjob->next = dummy;
969 /*********************************************************************
971 * Function : rewrite_url
973 * Description : Rewrites a URL with a single pcrs command
974 * and returns the result if it differs from the
975 * original and isn't obviously invalid.
978 * 1 : old_url = URL to rewrite.
979 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
982 * Returns : NULL if the pcrs_command didn't change the url, or
983 * the result of the modification.
985 *********************************************************************/
986 char *rewrite_url(char *old_url, const char *pcrs_command)
988 char *new_url = NULL;
992 assert(pcrs_command);
994 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
998 log_error(LOG_LEVEL_REDIRECTS,
999 "pcrs command \"%s\" didn't change \"%s\".",
1000 pcrs_command, old_url);
1005 log_error(LOG_LEVEL_REDIRECTS,
1006 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1007 pcrs_command, old_url, pcrs_strerror(hits));
1010 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1012 log_error(LOG_LEVEL_ERROR,
1013 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1014 "but the result doesn't look like a valid URL and will be ignored.",
1015 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1020 log_error(LOG_LEVEL_REDIRECTS,
1021 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1022 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1030 #ifdef FEATURE_FAST_REDIRECTS
1031 /*********************************************************************
1033 * Function : get_last_url
1035 * Description : Search for the last URL inside a string.
1036 * If the string already is a URL, it will
1037 * be the first URL found.
1040 * 1 : subject = the string to check
1041 * 2 : redirect_mode = +fast-redirect{} mode
1043 * Returns : NULL if no URL was found, or
1044 * the last URL found.
1046 *********************************************************************/
1047 static char *get_last_url(char *subject, const char *redirect_mode)
1049 char *new_url = NULL;
1053 assert(redirect_mode);
1055 subject = strdup(subject);
1056 if (subject == NULL)
1058 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1062 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1064 char *url_segment = NULL;
1065 char **url_segments;
1066 size_t max_segments;
1069 log_error(LOG_LEVEL_REDIRECTS,
1070 "Checking \"%s\" for encoded redirects.", subject);
1073 * Check each parameter in the URL separately.
1074 * Sectionize the URL at "?" and "&",
1075 * go backwards through the segments, URL-decode them
1076 * and look for a URL in the decoded result.
1077 * Stop the search after the first match.
1079 * XXX: This estimate is guaranteed to be high enough as we
1080 * let ssplit() ignore empty fields, but also a bit wasteful.
1082 max_segments = strlen(subject) / 2;
1083 url_segments = malloc(max_segments * sizeof(char *));
1085 if (NULL == url_segments)
1087 log_error(LOG_LEVEL_ERROR,
1088 "Out of memory while decoding URL: %s", subject);
1093 segments = ssplit(subject, "?&", url_segments, max_segments);
1095 while (segments-- > 0)
1097 char *dtoken = url_decode(url_segments[segments]);
1100 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1103 url_segment = strstr(dtoken, "http://");
1104 if (NULL == url_segment)
1106 url_segment = strstr(dtoken, "https://");
1108 if (NULL != url_segment)
1110 url_segment = strdup_or_die(url_segment);
1117 freez(url_segments);
1119 if (url_segment == NULL)
1123 subject = url_segment;
1127 /* Look for a URL inside this one, without decoding anything. */
1128 log_error(LOG_LEVEL_REDIRECTS,
1129 "Checking \"%s\" for unencoded redirects.", subject);
1133 * Find the last URL encoded in the request
1136 while ((tmp = strstr(tmp, "http://")) != NULL)
1140 tmp = (new_url != NULL) ? new_url : subject;
1141 while ((tmp = strstr(tmp, "https://")) != NULL)
1146 if ((new_url != NULL)
1147 && ( (new_url != subject)
1148 || (0 == strncmpic(subject, "http://", 7))
1149 || (0 == strncmpic(subject, "https://", 8))
1153 * Return new URL if we found a redirect
1154 * or if the subject already was a URL.
1156 * The second case makes sure that we can
1157 * chain get_last_url after another redirection check
1158 * (like rewrite_url) without losing earlier redirects.
1160 new_url = strdup(new_url);
1169 #endif /* def FEATURE_FAST_REDIRECTS */
1172 /*********************************************************************
1174 * Function : redirect_url
1176 * Description : Checks if Privoxy should answer the request with
1177 * a HTTP redirect and generates the redirect if
1181 * 1 : csp = Current client state (buffers, headers, etc...)
1183 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1185 *********************************************************************/
1186 struct http_response *redirect_url(struct client_state *csp)
1188 struct http_response *rsp;
1189 #ifdef FEATURE_FAST_REDIRECTS
1191 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1192 * as compile-time option? The user can easily disable
1193 * it in his action file.
1195 char * redirect_mode;
1196 #endif /* def FEATURE_FAST_REDIRECTS */
1197 char *old_url = NULL;
1198 char *new_url = NULL;
1199 char *redirection_string;
1201 if ((csp->action->flags & ACTION_REDIRECT))
1203 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1206 * If the redirection string begins with 's',
1207 * assume it's a pcrs command, otherwise treat it as
1208 * properly formatted URL and use it for the redirection
1211 * According to (the now obsolete) RFC 2616 section 14.30
1212 * the URL has to be absolute and if the user tries:
1213 * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
1214 * she would get undefined results anyway.
1216 * RFC 7231 7.1.2 actually allows relative references,
1217 * but those start with a leading slash (RFC 3986 4.2) and
1218 * thus can't be mistaken for pcrs commands either.
1221 if (*redirection_string == 's')
1223 old_url = csp->http->url;
1224 new_url = rewrite_url(old_url, redirection_string);
1228 log_error(LOG_LEVEL_REDIRECTS,
1229 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1230 redirection_string);
1231 new_url = strdup(redirection_string);
1235 #ifdef FEATURE_FAST_REDIRECTS
1236 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1238 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1241 * If it exists, use the previously rewritten URL as input
1242 * otherwise just use the old path.
1244 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1245 new_url = get_last_url(old_url, redirect_mode);
1250 * Disable redirect checkers, so that they
1251 * will be only run more than once if the user
1252 * also enables them through tags.
1254 * From a performance point of view
1255 * it doesn't matter, but the duplicated
1256 * log messages are annoying.
1258 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1259 #endif /* def FEATURE_FAST_REDIRECTS */
1260 csp->action->flags &= ~ACTION_REDIRECT;
1262 /* Did any redirect action trigger? */
1265 if (url_requires_percent_encoding(new_url))
1268 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1269 strlen(new_url), new_url);
1270 encoded_url = percent_encode_url(new_url);
1272 if (encoded_url == NULL)
1274 return cgi_error_memory();
1276 new_url = encoded_url;
1277 assert(FALSE == url_requires_percent_encoding(new_url));
1280 if (0 == strcmpic(new_url, csp->http->url))
1282 log_error(LOG_LEVEL_ERROR,
1283 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1284 csp->http->url, new_url);
1289 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1291 if (NULL == (rsp = alloc_http_response()))
1294 return cgi_error_memory();
1297 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
1298 if (enlist_unique_header(rsp->headers, "Location", new_url))
1301 free_http_response(rsp);
1302 return cgi_error_memory();
1304 rsp->crunch_reason = REDIRECTED;
1307 return finish_http_response(csp, rsp);
1311 /* Only reached if no redirect is required */
1317 #ifdef FEATURE_IMAGE_BLOCKING
1318 /*********************************************************************
1320 * Function : is_imageurl
1322 * Description : Given a URL, decide whether it should be treated
1323 * as image URL or not.
1326 * 1 : csp = Current client state (buffers, headers, etc...)
1328 * Returns : True (nonzero) if URL is an image URL, false (0)
1331 *********************************************************************/
1332 int is_imageurl(const struct client_state *csp)
1334 return ((csp->action->flags & ACTION_IMAGE) != 0);
1337 #endif /* def FEATURE_IMAGE_BLOCKING */
1340 #ifdef FEATURE_TRUST
1341 /*********************************************************************
1343 * Function : is_untrusted_url
1345 * Description : Should we "distrust" this URL (and block it)?
1347 * Yes if it matches a line in the trustfile, or if the
1348 * referrer matches a line starting with "+" in the
1353 * 1 : csp = Current client state (buffers, headers, etc...)
1355 * Returns : 0 => trusted, 1 => untrusted
1357 *********************************************************************/
1358 int is_untrusted_url(const struct client_state *csp)
1360 struct file_list *fl;
1361 struct block_spec *b;
1362 struct pattern_spec **trusted_url;
1363 struct http_request rhttp[1];
1364 const char * referer;
1368 * If we don't have a trustlist, we trust everybody
1370 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1375 memset(rhttp, '\0', sizeof(*rhttp));
1378 * Do we trust the request URL itself?
1380 for (b = b->next; b ; b = b->next)
1382 if (url_match(b->url, csp->http))
1388 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1390 /* no referrer was supplied */
1396 * If not, do we maybe trust its referrer?
1398 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1404 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1406 if (url_match(*trusted_url, rhttp))
1408 /* if the URL's referrer is from a trusted referrer, then
1409 * add the target spec to the trustfile as an unblocked
1410 * domain and return 0 (which means it's OK).
1415 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1419 char * new_entry = strdup_or_die("~");
1421 string_append(&new_entry, csp->http->hostport);
1423 path = csp->http->path;
1424 if ( (path[0] == '/')
1426 && ((path_end = strchr(path + 2, '/')) != NULL))
1428 /* since this path points into a user's home space
1429 * be sure to include this spec in the trustfile.
1431 long path_len = path_end - path; /* save offset */
1432 path = strdup(path); /* Copy string */
1435 path_end = path + path_len; /* regenerate ptr to new buffer */
1436 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1438 string_join(&new_entry, path);
1442 * Give a reason for generating this entry.
1444 string_append(&new_entry, " # Trusted referrer was: ");
1445 string_append(&new_entry, referer);
1447 if (new_entry != NULL)
1449 if (-1 == fprintf(fp, "%s\n", new_entry))
1451 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1452 new_entry, csp->config->trustfile);
1458 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1459 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1466 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1467 csp->http->hostport, csp->config->trustfile);
1475 #endif /* def FEATURE_TRUST */
1478 /*********************************************************************
1480 * Function : get_filter
1482 * Description : Get a filter with a given name and type.
1483 * Note that taggers are filters, too.
1486 * 1 : csp = Current client state (buffers, headers, etc...)
1487 * 2 : requested_name = Name of the content filter to get
1488 * 3 : requested_type = Type of the filter to tagger to lookup
1490 * Returns : A pointer to the requested filter
1491 * or NULL if the filter wasn't found
1493 *********************************************************************/
1494 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1495 const char *requested_name,
1496 enum filter_type requested_type)
1499 struct re_filterfile_spec *b;
1500 struct file_list *fl;
1502 for (i = 0; i < MAX_AF_FILES; i++)
1505 if ((NULL == fl) || (NULL == fl->f))
1508 * Either there are no filter files left or this
1509 * filter file just contains no valid filters.
1511 * Continue to be sure we don't miss valid filter
1512 * files that are chained after empty or invalid ones.
1517 for (b = fl->f; b != NULL; b = b->next)
1519 if (b->type != requested_type)
1521 /* The callers isn't interested in this filter type. */
1524 if (strcmp(b->name, requested_name) == 0)
1526 /* The requested filter has been found. Abort search. */
1532 /* No filter with the given name and type exists. */
1538 /*********************************************************************
1540 * Function : pcrs_filter_response
1542 * Description : Execute all text substitutions from all applying
1543 * +filter actions on the text buffer that's been
1544 * accumulated in csp->iob->buf.
1547 * 1 : csp = Current client state (buffers, headers, etc...)
1549 * Returns : a pointer to the (newly allocated) modified buffer.
1550 * or NULL if there were no hits or something went wrong
1552 *********************************************************************/
1553 static char *pcrs_filter_response(struct client_state *csp)
1556 size_t size, prev_size;
1562 struct re_filterfile_spec *b;
1563 struct list_entry *filtername;
1568 if (csp->iob->cur >= csp->iob->eod)
1573 if (filters_available(csp) == FALSE)
1575 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1576 "content filtering enabled, but no content filters available.");
1580 size = (size_t)(csp->iob->eod - csp->iob->cur);
1581 old = csp->iob->cur;
1584 * For all applying +filter actions, look if a filter by that
1585 * name exists and if yes, execute it's pcrs_joblist on the
1588 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1589 filtername != NULL; filtername = filtername->next)
1591 int current_hits = 0; /* Number of hits caused by this filter */
1592 int job_number = 0; /* Which job we're currently executing */
1593 int job_hits = 0; /* How many hits the current job caused */
1596 b = get_filter(csp, filtername->str, FT_CONTENT_FILTER);
1602 joblist = b->joblist;
1604 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1606 if (NULL == joblist)
1608 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1613 /* Apply all jobs from the joblist */
1614 for (job = joblist; NULL != job; job = job->next)
1617 job_hits = pcrs_execute(job, old, size, &new, &size);
1622 * That went well. Continue filtering
1623 * and use the result of this job as
1624 * input for the next one.
1626 current_hits += job_hits;
1627 if (old != csp->iob->cur)
1636 * This job caused an unexpected error. Inform the user
1637 * and skip the rest of the jobs in this filter. We could
1638 * continue with the next job, but usually the jobs
1639 * depend on each other or are similar enough to
1640 * fail for the same reason.
1642 * At the moment our pcrs expects the error codes of pcre 3.4,
1643 * but newer pcre versions can return additional error codes.
1644 * As a result pcrs_strerror()'s error message might be
1645 * "Unknown error ...", therefore we print the numerical value
1648 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1649 * should we use LOG_LEVEL_RE_FILTER instead?
1651 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1652 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1657 if (b->dynamic) pcrs_free_joblist(joblist);
1659 log_error(LOG_LEVEL_RE_FILTER,
1660 "filtering %s%s (size %lu) with \'%s\' produced %d hits (new size %lu).",
1661 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1662 #ifdef FEATURE_EXTENDED_STATISTICS
1663 update_filter_statistics(b->name, current_hits);
1665 hits += current_hits;
1669 * If there were no hits, destroy our copy and let
1670 * chat() use the original in csp->iob
1678 csp->flags |= CSP_FLAG_MODIFIED;
1679 csp->content_length = size;
1680 clear_iob(csp->iob);
1687 #ifdef FEATURE_EXTERNAL_FILTERS
1688 /*********************************************************************
1690 * Function : get_external_filter
1692 * Description : Lookup the code to execute for an external filter.
1693 * Masks the misuse of the re_filterfile_spec.
1696 * 1 : csp = Current client state (buffers, headers, etc...)
1697 * 2 : name = Name of the content filter to get
1699 * Returns : A pointer to the requested code
1700 * or NULL if the filter wasn't found
1702 *********************************************************************/
1703 static const char *get_external_filter(const struct client_state *csp,
1706 struct re_filterfile_spec *external_filter;
1708 external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
1709 if (external_filter == NULL)
1711 log_error(LOG_LEVEL_FATAL,
1712 "Didn't find stuff to execute for external filter: %s",
1716 return external_filter->patterns->first->str;
1721 /*********************************************************************
1723 * Function : set_privoxy_variables
1725 * Description : Sets a couple of privoxy-specific environment variables
1728 * 1 : csp = Current client state (buffers, headers, etc...)
1732 *********************************************************************/
1733 static void set_privoxy_variables(const struct client_state *csp)
1740 { "PRIVOXY_URL", csp->http->url },
1741 { "PRIVOXY_PATH", csp->http->path },
1742 { "PRIVOXY_HOST", csp->http->host },
1743 { "PRIVOXY_ORIGIN", csp->ip_addr_str },
1744 { "PRIVOXY_LISTEN_ADDRESS", csp->listen_addr_str },
1747 for (i = 0; i < SZ(env); i++)
1749 if (setenv(env[i].name, env[i].value, 1))
1751 log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
1752 env[i].name, env[i].value);
1758 /*********************************************************************
1760 * Function : execute_external_filter
1762 * Description : Pipe content into external filter and return the output
1765 * 1 : csp = Current client state (buffers, headers, etc...)
1766 * 2 : name = Name of the external filter to execute
1767 * 3 : content = The original content to filter
1768 * 4 : size = The size of the content buffer
1770 * Returns : a pointer to the (newly allocated) modified buffer.
1771 * or NULL if there were no hits or something went wrong
1773 *********************************************************************/
1774 static char *execute_external_filter(const struct client_state *csp,
1775 const char *name, char *content, size_t *size)
1778 char file_name[FILENAME_MAX];
1780 char *filter_output;
1784 const char *external_filter;
1786 if (csp->config->temporary_directory == NULL)
1788 log_error(LOG_LEVEL_ERROR,
1789 "No temporary-directory configured. Can't execute filter: %s",
1794 external_filter = get_external_filter(csp, name);
1796 if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
1797 "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
1799 log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
1803 fd = mkstemp(file_name);
1806 log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
1810 fp = fdopen(fd, "w");
1813 log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
1819 * The size may be zero if a previous filter discarded everything.
1821 * This isn't necessary unintentional, so we just don't try
1822 * to fwrite() nothing and let the user deal with the rest.
1824 if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
1826 log_error(LOG_LEVEL_ERROR, "fwrite(..., %d, 1, ..) failed: %E", *size);
1833 if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
1835 log_error(LOG_LEVEL_ERROR,
1836 "temporary-directory or external filter path too long");
1841 log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
1844 * The locking is necessary to prevent other threads
1845 * from overwriting the environment variables before
1846 * the popen fork. Afterwards this no longer matters.
1848 privoxy_mutex_lock(&external_filter_mutex);
1849 set_privoxy_variables(csp);
1850 fp = popen(cmd, "r");
1851 privoxy_mutex_unlock(&external_filter_mutex);
1854 log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
1859 /* Allocate at least one byte */
1860 filter_output = malloc_or_die(*size + 1);
1863 while (!feof(fp) && !ferror(fp))
1866 /* Could be bigger ... */
1867 enum { READ_LENGTH = 2048 };
1869 if (new_size + READ_LENGTH >= *size)
1873 /* Could be considered wasteful if the content is 'large'. */
1874 *size += (*size >= READ_LENGTH) ? *size : READ_LENGTH;
1876 p = realloc(filter_output, *size);
1879 log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
1880 "external filter output. Using what we got so far.");
1885 assert(new_size + READ_LENGTH < *size);
1886 len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
1896 log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
1900 log_error(LOG_LEVEL_RE_FILTER,
1901 "Executing '%s' resulted in return value %d. "
1902 "Read %d of up to %d bytes.", name, (ret >> 8), new_size, *size);
1908 return filter_output;
1911 #endif /* def FEATURE_EXTERNAL_FILTERS */
1914 /*********************************************************************
1916 * Function : gif_deanimate_response
1918 * Description : Deanimate the GIF image that has been accumulated in
1919 * csp->iob->buf, set csp->content_length to the modified
1920 * size and raise the CSP_FLAG_MODIFIED flag.
1923 * 1 : csp = Current client state (buffers, headers, etc...)
1925 * Returns : a pointer to the (newly allocated) modified buffer.
1926 * or NULL in case something went wrong.
1928 *********************************************************************/
1930 char *gif_deanimate_response(struct client_state *csp)
1932 static char *gif_deanimate_response(struct client_state *csp)
1935 struct binbuffer *in, *out;
1939 size = (size_t)(csp->iob->eod - csp->iob->cur);
1941 in = zalloc_or_die(sizeof(*in));
1942 out = zalloc_or_die(sizeof(*out));
1944 in->buffer = csp->iob->cur;
1947 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1949 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1956 if ((int)size == out->offset)
1958 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1962 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1964 csp->content_length = out->offset;
1965 csp->flags |= CSP_FLAG_MODIFIED;
1975 /*********************************************************************
1977 * Function : get_filter_function
1979 * Description : Decides which content filter function has
1980 * to be applied (if any). Only considers functions
1981 * for internal filters which are mutually-exclusive.
1984 * 1 : csp = Current client state (buffers, headers, etc...)
1986 * Returns : The content filter function to run, or
1987 * NULL if no content filter is active
1989 *********************************************************************/
1990 static filter_function_ptr get_filter_function(const struct client_state *csp)
1992 filter_function_ptr filter_function = NULL;
1995 * Choose the applying filter function based on
1996 * the content type and action settings.
1998 if ((csp->content_type & CT_TEXT) &&
1999 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2001 filter_function = pcrs_filter_response;
2003 else if ((csp->content_type & CT_GIF) &&
2004 (csp->action->flags & ACTION_DEANIMATE))
2006 filter_function = gif_deanimate_response;
2009 return filter_function;
2013 /*********************************************************************
2015 * Function : remove_chunked_transfer_coding
2017 * Description : In-situ remove the "chunked" transfer coding as defined
2018 * in RFC 7230 4.1 from a buffer. XXX: The implementation
2019 * is neither complete nor compliant (TODO #129).
2022 * 1 : buffer = Pointer to the text buffer
2023 * 2 : size = In: Number of bytes to be processed,
2024 * Out: Number of bytes after de-chunking.
2025 * (undefined in case of errors)
2027 * Returns : JB_ERR_OK for success,
2028 * JB_ERR_PARSE otherwise
2030 *********************************************************************/
2032 extern jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2034 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2038 unsigned int chunksize = 0;
2039 char *from_p, *to_p;
2040 const char *end_of_buffer = buffer + *size;
2044 log_error(LOG_LEVEL_FATAL, "Invalid chunked input. Buffer is empty.");
2045 return JB_ERR_PARSE;
2049 from_p = to_p = buffer;
2051 if (sscanf(buffer, "%x", &chunksize) != 1)
2053 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2054 return JB_ERR_PARSE;
2057 while (chunksize > 0U)
2060 * If the chunk-size is valid, we should have at least
2061 * chunk-size bytes of chunk-data and five bytes of
2062 * meta data (chunk-size, CRLF, CRLF) left in the buffer.
2064 if (chunksize + 5 >= *size - newsize)
2066 log_error(LOG_LEVEL_ERROR,
2067 "Chunk size %u exceeds buffered data left. "
2068 "Already digested %u of %u buffered bytes.",
2069 chunksize, (unsigned int)newsize, (unsigned int)*size);
2070 return JB_ERR_PARSE;
2074 * Skip the chunk-size, the optional chunk-ext and the CRLF
2075 * that is supposed to be located directly before the start
2078 if (NULL == (from_p = strstr(from_p, "\r\n")))
2080 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2081 return JB_ERR_PARSE;
2086 * The previous strstr() does not enforce chunk-validity
2087 * and is sattisfied as long a CRLF is left in the buffer.
2089 * Make sure the bytes we consider chunk-data are within
2092 if (from_p + chunksize >= end_of_buffer)
2094 log_error(LOG_LEVEL_ERROR,
2095 "End of chunk is beyond the end of the buffer.");
2096 return JB_ERR_PARSE;
2099 memmove(to_p, from_p, (size_t) chunksize);
2100 newsize += chunksize;
2101 to_p = buffer + newsize;
2102 from_p += chunksize;
2105 * Not merging this check with the previous one allows us
2106 * to keep chunks without trailing CRLF. It's not clear
2107 * if we actually have to care about those, though.
2109 if (from_p + 2 >= end_of_buffer)
2111 log_error(LOG_LEVEL_ERROR, "Not enough room for trailing CRLF.");
2112 return JB_ERR_PARSE;
2115 if (sscanf(from_p, "%x", &chunksize) != 1)
2117 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2122 /* XXX: Should get its own loglevel. */
2123 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
2132 /*********************************************************************
2134 * Function : prepare_for_filtering
2136 * Description : If necessary, de-chunks and decompresses
2137 * the content so it can get filterd.
2140 * 1 : csp = Current client state (buffers, headers, etc...)
2142 * Returns : JB_ERR_OK for success,
2143 * JB_ERR_PARSE otherwise
2145 *********************************************************************/
2146 static jb_err prepare_for_filtering(struct client_state *csp)
2148 jb_err err = JB_ERR_OK;
2151 * If the body has a "chunked" transfer-encoding,
2152 * get rid of it, adjusting size and iob->eod
2154 if (csp->flags & CSP_FLAG_CHUNKED)
2156 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2158 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2159 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2160 if (JB_ERR_OK == err)
2162 csp->iob->eod = csp->iob->cur + size;
2163 csp->flags |= CSP_FLAG_MODIFIED;
2167 return JB_ERR_PARSE;
2173 * If the body has a supported transfer-encoding,
2174 * decompress it, adjusting size and iob->eod.
2176 if ((csp->content_type & (CT_GZIP|CT_DEFLATE))
2177 #ifdef FEATURE_BROTLI
2178 || (csp->content_type & CT_BROTLI)
2182 if (0 == csp->iob->eod - csp->iob->cur)
2184 /* Nothing left after de-chunking. */
2188 err = decompress_iob(csp);
2190 if (JB_ERR_OK == err)
2192 csp->flags |= CSP_FLAG_MODIFIED;
2193 csp->content_type &= ~CT_TABOO;
2198 * Unset content types to remember not to
2199 * modify the Content-Encoding header later.
2201 csp->content_type &= ~CT_GZIP;
2202 csp->content_type &= ~CT_DEFLATE;
2203 #ifdef FEATURE_BROTLI
2204 csp->content_type &= ~CT_BROTLI;
2214 /*********************************************************************
2216 * Function : execute_content_filters
2218 * Description : Executes a given content filter.
2221 * 1 : csp = Current client state (buffers, headers, etc...)
2223 * Returns : Pointer to the modified buffer, or
2224 * NULL if filtering failed or wasn't necessary.
2226 *********************************************************************/
2227 char *execute_content_filters(struct client_state *csp)
2230 filter_function_ptr content_filter;
2232 assert(content_filters_enabled(csp->action));
2234 if (0 == csp->iob->eod - csp->iob->cur)
2237 * No content (probably status code 301, 302 ...),
2238 * no filtering necessary.
2243 if (JB_ERR_OK != prepare_for_filtering(csp))
2246 * failed to de-chunk or decompress.
2251 if (0 == csp->iob->eod - csp->iob->cur)
2254 * Clown alarm: chunked and/or compressed nothing delivered.
2259 content_filter = get_filter_function(csp);
2260 content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
2262 #ifdef FEATURE_EXTERNAL_FILTERS
2263 if ((csp->content_type & CT_TEXT) &&
2264 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
2266 struct list_entry *filtername;
2267 size_t size = (size_t)csp->content_length;
2269 if (content == NULL)
2271 content = csp->iob->cur;
2272 size = (size_t)(csp->iob->eod - csp->iob->cur);
2275 for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
2276 filtername ; filtername = filtername->next)
2278 char *result = execute_external_filter(csp, filtername->str, content, &size);
2281 if (content != csp->iob->cur)
2288 csp->flags |= CSP_FLAG_MODIFIED;
2289 csp->content_length = size;
2291 #endif /* def FEATURE_EXTERNAL_FILTERS */
2298 /*********************************************************************
2300 * Function : get_url_actions
2302 * Description : Gets the actions for this URL.
2305 * 1 : csp = Current client state (buffers, headers, etc...)
2306 * 2 : http = http_request request for blocked URLs
2310 *********************************************************************/
2311 void get_url_actions(struct client_state *csp, struct http_request *http)
2313 struct file_list *fl;
2314 struct url_actions *b;
2317 init_current_action(csp->action);
2319 for (i = 0; i < MAX_AF_FILES; i++)
2321 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2326 #ifdef FEATURE_CLIENT_TAGS
2327 apply_url_actions(csp->action, http, csp->client_tags, b);
2329 apply_url_actions(csp->action, http, b);
2336 /*********************************************************************
2338 * Function : apply_url_actions
2340 * Description : Applies a list of URL actions.
2343 * 1 : action = Destination.
2344 * 2 : http = Current URL
2345 * 3 : client_tags = list of client tags
2346 * 4 : b = list of URL actions to apply
2350 *********************************************************************/
2351 static void apply_url_actions(struct current_action_spec *action,
2352 struct http_request *http,
2353 #ifdef FEATURE_CLIENT_TAGS
2354 const struct list *client_tags,
2356 struct url_actions *b)
2360 /* Should never happen */
2364 for (b = b->next; NULL != b; b = b->next)
2366 if (url_match(b->url, http))
2368 merge_current_action(action, b->action);
2370 #ifdef FEATURE_CLIENT_TAGS
2371 if (client_tag_match(b->url, client_tags))
2373 merge_current_action(action, b->action);
2380 /*********************************************************************
2382 * Function : get_forward_override_settings
2384 * Description : Returns forward settings as specified with the
2385 * forward-override{} action. forward-override accepts
2386 * forward lines similar to the one used in the
2387 * configuration file, but without the URL pattern.
2393 * in the configuration file can be replaced with
2394 * the action section:
2396 * {+forward-override{forward .}}
2400 * 1 : csp = Current client state (buffers, headers, etc...)
2402 * Returns : Pointer to forwarding structure in case of success.
2403 * Invalid syntax is fatal.
2405 *********************************************************************/
2406 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2408 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2409 char forward_settings[BUFFER_SIZE];
2410 char *http_parent = NULL;
2411 /* variable names were chosen for consistency reasons. */
2412 struct forward_spec *fwd = NULL;
2416 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2417 /* Should be enforced by load_one_actions_file() */
2418 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2420 /* Create a copy ssplit can modify */
2421 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2423 if (NULL != csp->fwd)
2426 * XXX: Currently necessary to prevent memory
2427 * leaks when the show-url-info cgi page is visited.
2429 unload_forward_spec(csp->fwd);
2433 * allocate a new forward node, valid only for
2434 * the lifetime of this request. Save its location
2435 * in csp as well, so sweep() can free it later on.
2437 fwd = csp->fwd = zalloc_or_die(sizeof(*fwd));
2439 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2440 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2442 fwd->type = SOCKS_NONE;
2444 /* Parse the parent HTTP proxy host:port */
2445 http_parent = vec[1];
2448 else if ((vec_count == 2) && !strcasecmp(vec[0], "forward-webserver"))
2450 fwd->type = FORWARD_WEBSERVER;
2452 /* Parse the parent HTTP server host:port */
2453 http_parent = vec[1];
2456 else if (vec_count == 3)
2458 char *socks_proxy = NULL;
2460 if (!strcasecmp(vec[0], "forward-socks4"))
2462 fwd->type = SOCKS_4;
2463 socks_proxy = vec[1];
2465 else if (!strcasecmp(vec[0], "forward-socks4a"))
2467 fwd->type = SOCKS_4A;
2468 socks_proxy = vec[1];
2470 else if (!strcasecmp(vec[0], "forward-socks5"))
2472 fwd->type = SOCKS_5;
2473 socks_proxy = vec[1];
2475 else if (!strcasecmp(vec[0], "forward-socks5t"))
2477 fwd->type = SOCKS_5T;
2478 socks_proxy = vec[1];
2481 if (NULL != socks_proxy)
2483 /* Parse the SOCKS proxy [user:pass@]host[:port] */
2484 fwd->gateway_port = 1080;
2485 parse_forwarder_address(socks_proxy,
2486 &fwd->gateway_host, &fwd->gateway_port,
2487 &fwd->auth_username, &fwd->auth_password);
2489 http_parent = vec[2];
2493 if (NULL == http_parent)
2495 log_error(LOG_LEVEL_FATAL,
2496 "Invalid forward-override syntax in: %s", forward_override_line);
2497 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2500 /* Parse http forwarding settings */
2501 if (strcmp(http_parent, ".") != 0)
2503 fwd->forward_port = 8000;
2504 parse_forwarder_address(http_parent,
2505 &fwd->forward_host, &fwd->forward_port,
2509 assert (NULL != fwd);
2511 log_error(LOG_LEVEL_CONNECT,
2512 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2518 /*********************************************************************
2520 * Function : forward_url
2522 * Description : Should we forward this to another proxy?
2525 * 1 : csp = Current client state (buffers, headers, etc...)
2526 * 2 : http = http_request request for current URL
2528 * Returns : Pointer to forwarding information.
2530 *********************************************************************/
2531 const struct forward_spec *forward_url(struct client_state *csp,
2532 const struct http_request *http)
2534 static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
2535 struct forward_spec *fwd = csp->config->forward;
2537 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2539 return get_forward_override_settings(csp);
2549 if (url_match(fwd->url, http))
2560 /*********************************************************************
2562 * Function : direct_response
2564 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2565 * request and if so, return a HTTP 501 to the client.
2567 * FIXME: I have a stupid name and I should handle the
2568 * requests properly. Still, what we do here is rfc-
2569 * compliant, whereas ignoring or forwarding are not.
2572 * 1 : csp = Current client state (buffers, headers, etc...)
2574 * Returns : http_response if , NULL if nonmatch or handler fail
2576 *********************************************************************/
2577 struct http_response *direct_response(struct client_state *csp)
2579 struct http_response *rsp;
2580 struct list_entry *p;
2582 if ((0 == strcmpic(csp->http->gpc, "trace"))
2583 || (0 == strcmpic(csp->http->gpc, "options")))
2585 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2587 if (!strncmpic(p->str, "Max-Forwards:", 13))
2589 unsigned int max_forwards;
2592 * If it's a Max-Forwards value of zero,
2593 * we have to intercept the request.
2595 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2598 * FIXME: We could handle at least TRACE here,
2599 * but that would require a verbatim copy of
2600 * the request which we don't have anymore
2602 log_error(LOG_LEVEL_HEADER,
2603 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2606 /* Get mem for response or fail*/
2607 if (NULL == (rsp = alloc_http_response()))
2609 return cgi_error_memory();
2612 rsp->status = strdup_or_die("501 Not Implemented");
2614 rsp->crunch_reason = UNSUPPORTED;
2616 return(finish_http_response(csp, rsp));
2625 /*********************************************************************
2627 * Function : content_requires_filtering
2629 * Description : Checks whether there are any content filters
2630 * enabled for the current request and if they
2631 * can actually be applied..
2634 * 1 : csp = Current client state (buffers, headers, etc...)
2636 * Returns : TRUE for yes, FALSE otherwise
2638 *********************************************************************/
2639 int content_requires_filtering(struct client_state *csp)
2641 if ((csp->content_type & CT_TABOO)
2642 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2648 * Are we enabling text mode by force?
2650 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2653 * Do we really have to?
2655 if (csp->content_type & CT_TEXT)
2657 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2661 csp->content_type |= CT_TEXT;
2662 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2666 if (!(csp->content_type & CT_DECLARED))
2669 * The server didn't bother to declare a MIME-Type.
2670 * Assume it's text that can be filtered.
2672 * This also regulary happens with 304 responses,
2673 * therefore logging anything here would cause
2676 csp->content_type |= CT_TEXT;
2680 * Choose the applying filter function based on
2681 * the content type and action settings.
2683 if ((csp->content_type & CT_TEXT) &&
2684 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
2685 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
2689 else if ((csp->content_type & CT_GIF) &&
2690 (csp->action->flags & ACTION_DEANIMATE))
2700 /*********************************************************************
2702 * Function : content_filters_enabled
2704 * Description : Checks whether there are any content filters
2705 * enabled for the current request.
2708 * 1 : action = Action spec to check.
2710 * Returns : TRUE for yes, FALSE otherwise
2712 *********************************************************************/
2713 int content_filters_enabled(const struct current_action_spec *action)
2715 return ((action->flags & ACTION_DEANIMATE) ||
2716 !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
2717 !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
2721 /*********************************************************************
2723 * Function : filters_available
2725 * Description : Checks whether there are any filters available.
2728 * 1 : csp = Current client state (buffers, headers, etc...)
2730 * Returns : TRUE for yes, FALSE otherwise.
2732 *********************************************************************/
2733 int filters_available(const struct client_state *csp)
2736 for (i = 0; i < MAX_AF_FILES; i++)
2738 const struct file_list *fl = csp->rlist[i];
2739 if ((NULL != fl) && (NULL != fl->f))
2747 #ifdef FEATURE_EXTENDED_STATISTICS
2749 struct filter_statistics_entry
2752 unsigned long long executions;
2753 unsigned long long response_bodies_modified;
2754 unsigned long long hits;
2756 struct filter_statistics_entry *next;
2759 static struct filter_statistics_entry *filter_statistics = NULL;
2762 /*********************************************************************
2764 * Function : register_filter_for_statistics
2766 * Description : Registers a filter so we can gather statistics for
2767 * it unless the filter has already been registered
2771 * 1 : filter = Name of the filter to register
2775 *********************************************************************/
2776 void register_filter_for_statistics(const char *filter)
2778 struct filter_statistics_entry *entry;
2780 privoxy_mutex_lock(&filter_statistics_mutex);
2782 if (filter_statistics == NULL)
2784 filter_statistics = zalloc_or_die(sizeof(struct filter_statistics_entry));
2785 entry = filter_statistics;
2786 entry->filter = strdup_or_die(filter);
2787 privoxy_mutex_unlock(&filter_statistics_mutex);
2790 entry = filter_statistics;
2791 while (entry != NULL)
2793 if (!strcmp(entry->filter, filter))
2795 /* Already registered, nothing to do. */
2798 if (entry->next == NULL)
2800 entry->next = zalloc_or_die(sizeof(struct filter_statistics_entry));
2801 entry->next->filter = strdup_or_die(filter);
2804 entry = entry->next;
2807 privoxy_mutex_unlock(&filter_statistics_mutex);
2812 /*********************************************************************
2814 * Function : update_filter_statistics
2816 * Description : Updates the statistics for a filter.
2819 * 1 : filter = Name of the filter to update
2820 * 2 : hits = Hit count.
2824 *********************************************************************/
2825 void update_filter_statistics(const char *filter, int hits)
2827 struct filter_statistics_entry *entry;
2829 privoxy_mutex_lock(&filter_statistics_mutex);
2831 entry = filter_statistics;
2832 while (entry != NULL)
2834 if (!strcmp(entry->filter, filter))
2836 entry->executions++;
2839 entry->response_bodies_modified++;
2840 entry->hits += (unsigned)hits;
2844 entry = entry->next;
2847 privoxy_mutex_unlock(&filter_statistics_mutex);
2852 /*********************************************************************
2854 * Function : get_filter_statistics
2856 * Description : Gets the statistics for a filter.
2859 * 1 : filter = Name of the filter to get statistics for.
2860 * 2 : executions = Storage for the execution count.
2861 * 3 : response_bodies_modified = Storage for the number
2862 * of modified response bodies.
2863 * 4 : hits = Storage for the number of hits.
2867 *********************************************************************/
2868 void get_filter_statistics(const char *filter, unsigned long long *executions,
2869 unsigned long long *response_bodies_modified,
2870 unsigned long long *hits)
2872 struct filter_statistics_entry *entry;
2874 privoxy_mutex_lock(&filter_statistics_mutex);
2876 entry = filter_statistics;
2877 while (entry != NULL)
2879 if (!strcmp(entry->filter, filter))
2881 *executions = entry->executions;
2882 *response_bodies_modified = entry->response_bodies_modified;
2883 *hits = entry->hits;
2886 entry = entry->next;
2889 privoxy_mutex_unlock(&filter_statistics_mutex);
2894 struct block_statistics_entry
2897 unsigned long long count;
2899 struct block_statistics_entry *next;
2902 static struct block_statistics_entry *block_statistics = NULL;
2904 /*********************************************************************
2906 * Function : register_block_reason_for_statistics
2908 * Description : Registers a block reason so we can gather statistics
2909 * for it unless the block reason has already been
2910 * registered before.
2913 * 1 : block_reason = Block reason to register
2917 *********************************************************************/
2918 void register_block_reason_for_statistics(const char *block_reason)
2920 struct block_statistics_entry *entry;
2922 privoxy_mutex_lock(&block_statistics_mutex);
2924 if (block_statistics == NULL)
2926 block_statistics = zalloc_or_die(sizeof(struct block_statistics_entry));
2927 entry = block_statistics;
2928 entry->block_reason = strdup_or_die(block_reason);
2929 privoxy_mutex_unlock(&block_statistics_mutex);
2932 entry = block_statistics;
2933 while (entry != NULL)
2935 if (!strcmp(entry->block_reason, block_reason))
2937 /* Already registered, nothing to do. */
2940 if (entry->next == NULL)
2942 entry->next = zalloc_or_die(sizeof(struct block_statistics_entry));
2943 entry->next->block_reason = strdup_or_die(block_reason);
2946 entry = entry->next;
2949 privoxy_mutex_unlock(&block_statistics_mutex);
2954 /*********************************************************************
2956 * Function : increment_block_reason_counter
2958 * Description : Updates the counter for a block reason.
2961 * 1 : block_reason = Block reason to count
2965 *********************************************************************/
2966 static void increment_block_reason_counter(const char *block_reason)
2968 struct block_statistics_entry *entry;
2970 privoxy_mutex_lock(&block_statistics_mutex);
2972 entry = block_statistics;
2973 while (entry != NULL)
2975 if (!strcmp(entry->block_reason, block_reason))
2980 entry = entry->next;
2983 privoxy_mutex_unlock(&block_statistics_mutex);
2988 /*********************************************************************
2990 * Function : get_block_reason_count
2992 * Description : Gets number of times a block reason was used.
2995 * 1 : block_reason = Block reason to get statistics for.
2996 * 2 : count = Storage for the number of times the block
3001 *********************************************************************/
3002 void get_block_reason_count(const char *block_reason, unsigned long long *count)
3004 struct block_statistics_entry *entry;
3006 privoxy_mutex_lock(&block_statistics_mutex);
3008 entry = block_statistics;
3009 while (entry != NULL)
3011 if (!strcmp(entry->block_reason, block_reason))
3013 *count = entry->count;
3016 entry = entry->next;
3019 privoxy_mutex_unlock(&block_statistics_mutex);
3023 #endif /* def FEATURE_EXTENDED_STATISTICS */