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"
69 #ifdef FEATURE_HTTPS_INSPECTION
77 typedef char *(*filter_function_ptr)();
78 static filter_function_ptr get_filter_function(const struct client_state *csp);
79 static jb_err prepare_for_filtering(struct client_state *csp);
80 static void apply_url_actions(struct current_action_spec *action,
81 struct http_request *http,
82 #ifdef FEATURE_CLIENT_TAGS
83 const struct list *client_tags,
85 struct url_actions *b);
87 #ifdef FEATURE_EXTENDED_STATISTICS
88 static void increment_block_reason_counter(const char *block_reason);
93 /*********************************************************************
95 * Function : sockaddr_storage_to_ip
97 * Description : Access internal structure of sockaddr_storage
100 * 1 : addr = socket address
101 * 2 : ip = IP address as array of octets in network order
102 * (it points into addr)
103 * 3 : len = length of IP address in octets
104 * 4 : port = port number in network order;
108 *********************************************************************/
109 static void sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
110 uint8_t **ip, unsigned int *len,
113 assert(NULL != addr);
114 assert(addr->ss_family == AF_INET || addr->ss_family == AF_INET6);
116 switch (addr->ss_family)
126 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
130 *port = &((struct sockaddr_in *)addr)->sin_port;
141 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
145 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
153 /*********************************************************************
155 * Function : match_sockaddr
157 * Description : Check whether address matches network (IP address and port)
160 * 1 : network = socket address of subnework
161 * 2 : netmask = network mask as socket address
162 * 3 : address = checked socket address against given network
164 * Returns : 0 = doesn't match; 1 = does match
166 *********************************************************************/
167 static int match_sockaddr(const struct sockaddr_storage *network,
168 const struct sockaddr_storage *netmask,
169 const struct sockaddr_storage *address)
171 uint8_t *network_addr, *netmask_addr, *address_addr;
172 unsigned int addr_len;
173 in_port_t *network_port, *netmask_port, *address_port;
176 if (network->ss_family != netmask->ss_family)
178 /* This should never happen */
179 assert(network->ss_family == netmask->ss_family);
180 log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
183 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
184 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
185 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
187 /* Check for family */
188 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
189 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
191 /* Map AF_INET6 V4MAPPED address into AF_INET */
195 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
196 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
198 /* Map AF_INET6 V4MAPPED network into AF_INET */
204 /* XXX: Port check is signaled in netmask */
205 if (*netmask_port && *network_port != *address_port)
210 /* TODO: Optimize by checking by words instead of octets */
211 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
213 if ((network_addr[i] & netmask_addr[i]) !=
214 (address_addr[i] & netmask_addr[i]))
222 #endif /* def HAVE_RFC2553 */
225 /*********************************************************************
227 * Function : block_acl
229 * Description : Block this request?
230 * Decide yes or no based on ACL file.
233 * 1 : dst = The proxy or gateway address this is going to.
234 * Or NULL to check all possible targets.
235 * 2 : csp = Current client state (buffers, headers, etc...)
236 * Also includes the client IP address.
238 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
240 *********************************************************************/
241 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
243 struct access_control_list *acl = csp->config->acl;
245 /* if not using an access control list, then permit the connection */
251 /* search the list */
256 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
258 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
264 /* Just want to check if they have any access */
265 if (acl->action == ACL_PERMIT)
277 * XXX: An undefined acl->dst is full of zeros and should be
278 * considered a wildcard address. sockaddr_storage_to_ip()
279 * fails on such destinations because of unknown sa_familly
280 * (glibc only?). However this test is not portable.
282 * So, we signal the acl->dst is wildcard in wildcard_dst.
285 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
287 ((dst->addr & acl->dst->mask) == acl->dst->addr)
288 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
292 if (acl->action == ACL_PERMIT)
310 /*********************************************************************
312 * Function : acl_addr
314 * Description : Called from `load_config' to parse an ACL address.
317 * 1 : aspec = String specifying ACL address.
318 * 2 : aca = struct access_control_addr to fill in.
320 * Returns : 0 => Ok, everything else is an error.
322 *********************************************************************/
323 int acl_addr(const char *aspec, struct access_control_addr *aca)
327 struct addrinfo hints, *result;
329 in_port_t *mask_port;
330 unsigned int addr_len;
333 #endif /* def HAVE_RFC2553 */
335 char *acl_spec = NULL;
338 /* XXX: Depend on ai_family */
346 * Use a temporary acl spec copy so we can log
347 * the unmodified original in case of parse errors.
349 acl_spec = strdup_or_die(aspec);
351 if ((p = strchr(acl_spec, '/')) != NULL)
354 if (privoxy_isdigit(*p) == 0)
359 masklength = atoi(p);
362 if ((masklength < 0) ||
374 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
377 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
386 p = strchr(acl_spec, ':');
396 memset(&hints, 0, sizeof(struct addrinfo));
397 hints.ai_family = AF_UNSPEC;
398 hints.ai_socktype = SOCK_STREAM;
400 i = getaddrinfo(acl_spec, p, &hints, &result);
404 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
405 acl_spec, p, gai_strerror(i));
411 /* TODO: Allow multihomed hostnames */
412 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
413 freeaddrinfo(result);
419 port = strtol(p, &endptr, 10);
421 if (port <= 0 || port > 65535 || *endptr != '\0')
428 aca->port = (unsigned long)port;
430 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
433 if (aca->addr == INADDR_NONE)
435 /* XXX: This will be logged as parse error. */
438 #endif /* def HAVE_RFC2553 */
440 /* build the netmask */
442 /* Clip masklength according to current family. */
443 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
448 aca->mask.ss_family = aca->addr.ss_family;
449 sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port);
453 /* ACL contains a port number, check ports in the future. */
458 * XXX: This could be optimized to operate on whole words instead
459 * of octets (128-bit CPU could do it in one iteration).
462 * Octets after prefix can be omitted because of
463 * previous initialization to zeros.
465 for (i = 0; (i < addr_len) && masklength; i++)
475 * XXX: This assumes MSB of octet is on the left side.
476 * This should be true for all architectures or solved
479 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
486 for (i=1; i <= masklength ; i++)
488 aca->mask |= (1U << (32 - i));
491 /* now mask off the host portion of the ip address
492 * (i.e. save on the network portion of the address).
494 aca->addr = aca->addr & aca->mask;
495 #endif /* def HAVE_RFC2553 */
500 #endif /* def FEATURE_ACL */
503 /*********************************************************************
505 * Function : connect_port_is_forbidden
507 * Description : Check to see if CONNECT requests to the destination
508 * port of this request are forbidden. The check is
509 * independent of the actual request method.
512 * 1 : csp = Current client state (buffers, headers, etc...)
514 * Returns : True if yes, false otherwise.
516 *********************************************************************/
517 int connect_port_is_forbidden(const struct client_state *csp)
519 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
520 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
525 /*********************************************************************
527 * Function : block_url
529 * Description : Called from `chat'. Check to see if we need to block this.
532 * 1 : csp = Current client state (buffers, headers, etc...)
534 * Returns : NULL => unblocked, else HTTP block response
536 *********************************************************************/
537 struct http_response *block_url(struct client_state *csp)
539 struct http_response *rsp;
540 const char *new_content_type = NULL;
543 * If it's not blocked, don't block it ;-)
545 if ((csp->action->flags & ACTION_BLOCK) == 0)
549 if (csp->action->flags & ACTION_REDIRECT)
551 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
554 * Else, prepare a response
556 if (NULL == (rsp = alloc_http_response()))
558 return cgi_error_memory();
561 #ifdef FEATURE_EXTENDED_STATISTICS
562 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
564 increment_block_reason_counter(csp->action->string[ACTION_STRING_BLOCK]);
569 * If it's an image-url, send back an image or redirect
570 * as specified by the relevant +image action
572 #ifdef FEATURE_IMAGE_BLOCKING
573 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
577 /* determine HOW images should be blocked */
578 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
580 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
582 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
585 /* and handle accordingly: */
586 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
588 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
589 rsp->body = bindup(image_pattern_data, image_pattern_length);
590 if (rsp->body == NULL)
592 free_http_response(rsp);
593 return cgi_error_memory();
595 rsp->content_length = image_pattern_length;
597 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
599 free_http_response(rsp);
600 return cgi_error_memory();
603 else if (0 == strcmpic(p, "blank"))
605 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
606 rsp->body = bindup(image_blank_data, image_blank_length);
607 if (rsp->body == NULL)
609 free_http_response(rsp);
610 return cgi_error_memory();
612 rsp->content_length = image_blank_length;
614 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
616 free_http_response(rsp);
617 return cgi_error_memory();
622 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
624 if (enlist_unique_header(rsp->headers, "Location", p))
626 free_http_response(rsp);
627 return cgi_error_memory();
633 #endif /* def FEATURE_IMAGE_BLOCKING */
634 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
637 * Send empty document.
639 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
642 rsp->body = strdup_or_die(" ");
643 rsp->content_length = 1;
645 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
648 * Workaround for firefox bug 492459
649 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
650 * Return a 200 OK status for pages blocked with +handle-as-empty-document
651 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
653 rsp->status = strdup_or_die("200 Request blocked by Privoxy");
657 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
660 if (new_content_type != 0)
662 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
663 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
665 free_http_response(rsp);
666 return cgi_error_memory();
673 * Else, generate an HTML "blocked" message:
677 struct map * exports;
679 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
681 exports = default_exports(csp, NULL);
684 free_http_response(rsp);
685 return cgi_error_memory();
688 #ifdef FEATURE_FORCE_LOAD
689 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
691 * Export the force conditional block killer if
693 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
694 * - Privoxy is configured to enforce blocks, or
695 * - it's a CONNECT request and enforcing wouldn't work anyway.
697 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
698 || (0 == strcmpic(csp->http->gpc, "connect")))
699 #endif /* ndef FEATURE_FORCE_LOAD */
701 err = map_block_killer(exports, "force-support");
704 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
705 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
706 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
707 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
710 const char *block_reason;
711 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
713 block_reason = csp->action->string[ACTION_STRING_BLOCK];
717 assert(connect_port_is_forbidden(csp));
718 block_reason = "Forbidden CONNECT port.";
720 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
725 free_http_response(rsp);
726 return cgi_error_memory();
729 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
732 free_http_response(rsp);
733 return cgi_error_memory();
736 rsp->crunch_reason = BLOCKED;
738 return finish_http_response(csp, rsp);
744 /*********************************************************************
746 * Function : trust_url FIXME: I should be called distrust_url
748 * Description : Calls is_untrusted_url to determine if the URL is trusted
749 * and if not, returns a HTTP 403 response with a reject message.
752 * 1 : csp = Current client state (buffers, headers, etc...)
754 * Returns : NULL => trusted, else http_response.
756 *********************************************************************/
757 struct http_response *trust_url(struct client_state *csp)
759 struct http_response *rsp;
760 struct map * exports;
761 char buf[BUFFER_SIZE];
763 struct pattern_spec **tl;
764 struct pattern_spec *t;
768 * Don't bother to work on trusted URLs
770 if (!is_untrusted_url(csp))
776 * Else, prepare a response:
778 if (NULL == (rsp = alloc_http_response()))
780 return cgi_error_memory();
783 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
784 exports = default_exports(csp, NULL);
787 free_http_response(rsp);
788 return cgi_error_memory();
792 * Export the protocol, host, port, and referrer information
794 err = map(exports, "hostport", 1, csp->http->hostport, 1);
795 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
796 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
798 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
800 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
804 if (!err) err = map(exports, "referrer", 1, "none set", 1);
810 free_http_response(rsp);
811 return cgi_error_memory();
815 * Export the trust list
817 p = strdup_or_die("");
818 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
820 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
821 string_append(&p, buf);
823 err = map(exports, "trusted-referrers", 1, p, 0);
828 free_http_response(rsp);
829 return cgi_error_memory();
833 * Export the trust info, if available
835 if (csp->config->trust_info->first)
837 struct list_entry *l;
839 p = strdup_or_die("");
840 for (l = csp->config->trust_info->first; l ; l = l->next)
842 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
843 string_append(&p, buf);
845 err = map(exports, "trust-info", 1, p, 0);
849 err = map_block_killer(exports, "have-trust-info");
855 free_http_response(rsp);
856 return cgi_error_memory();
860 * Export the force conditional block killer if
862 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
863 * - Privoxy is configured to enforce blocks, or
864 * - it's a CONNECT request and enforcing wouldn't work anyway.
866 #ifdef FEATURE_FORCE_LOAD
867 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
868 || (0 == strcmpic(csp->http->gpc, "connect")))
870 err = map_block_killer(exports, "force-support");
874 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
876 #else /* ifndef FEATURE_FORCE_LOAD */
877 err = map_block_killer(exports, "force-support");
878 #endif /* ndef FEATURE_FORCE_LOAD */
883 free_http_response(rsp);
884 return cgi_error_memory();
890 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
893 free_http_response(rsp);
894 return cgi_error_memory();
896 rsp->crunch_reason = UNTRUSTED;
898 return finish_http_response(csp, rsp);
900 #endif /* def FEATURE_TRUST */
903 /*********************************************************************
905 * Function : compile_dynamic_pcrs_job_list
907 * Description : Compiles a dynamic pcrs job list (one with variables
908 * resolved at request time)
911 * 1 : csp = Current client state (buffers, headers, etc...)
912 * 2 : b = The filter list to compile
914 * Returns : NULL in case of errors, otherwise the
917 *********************************************************************/
918 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
920 struct list_entry *pattern;
921 pcrs_job *job_list = NULL;
922 pcrs_job *dummy = NULL;
923 pcrs_job *lastjob = NULL;
926 const struct pcrs_variable variables[] =
928 {"url", csp->http->url, 1},
929 {"path", csp->http->path, 1},
930 {"host", csp->http->host, 1},
931 {"origin", csp->ip_addr_str, 1},
932 {"listen-address", csp->listen_addr_str, 1},
936 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
938 assert(pattern->str != NULL);
940 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
943 log_error(LOG_LEVEL_ERROR,
944 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
945 pattern->str, b->name, error, pcrs_strerror(error));
950 if (error == PCRS_WARN_TRUNCATION)
952 log_error(LOG_LEVEL_ERROR,
953 "At least one of the variables in \'%s\' had to "
954 "be truncated before compilation", pattern->str);
956 if (job_list == NULL)
962 lastjob->next = dummy;
972 /*********************************************************************
974 * Function : rewrite_url
976 * Description : Rewrites a URL with a single pcrs command
977 * and returns the result if it differs from the
978 * original and isn't obviously invalid.
981 * 1 : old_url = URL to rewrite.
982 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
985 * Returns : NULL if the pcrs_command didn't change the url, or
986 * the result of the modification.
988 *********************************************************************/
989 char *rewrite_url(char *old_url, const char *pcrs_command)
991 char *new_url = NULL;
995 assert(pcrs_command);
997 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1001 log_error(LOG_LEVEL_REDIRECTS,
1002 "pcrs command \"%s\" didn't change \"%s\".",
1003 pcrs_command, old_url);
1008 log_error(LOG_LEVEL_REDIRECTS,
1009 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1010 pcrs_command, old_url, pcrs_strerror(hits));
1013 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1015 log_error(LOG_LEVEL_ERROR,
1016 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1017 "but the result doesn't look like a valid URL and will be ignored.",
1018 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1023 log_error(LOG_LEVEL_REDIRECTS,
1024 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1025 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1033 #ifdef FEATURE_FAST_REDIRECTS
1034 /*********************************************************************
1036 * Function : get_last_url
1038 * Description : Search for the last URL inside a string.
1039 * If the string already is a URL, it will
1040 * be the first URL found.
1043 * 1 : subject = the string to check
1044 * 2 : redirect_mode = +fast-redirect{} mode
1046 * Returns : NULL if no URL was found, or
1047 * the last URL found.
1049 *********************************************************************/
1050 static char *get_last_url(char *subject, const char *redirect_mode)
1052 char *new_url = NULL;
1056 assert(redirect_mode);
1058 subject = strdup(subject);
1059 if (subject == NULL)
1061 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1065 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1067 char *url_segment = NULL;
1068 char **url_segments;
1069 size_t max_segments;
1072 log_error(LOG_LEVEL_REDIRECTS,
1073 "Checking \"%s\" for encoded redirects.", subject);
1076 * Check each parameter in the URL separately.
1077 * Sectionize the URL at "?" and "&",
1078 * go backwards through the segments, URL-decode them
1079 * and look for a URL in the decoded result.
1080 * Stop the search after the first match.
1082 * XXX: This estimate is guaranteed to be high enough as we
1083 * let ssplit() ignore empty fields, but also a bit wasteful.
1085 max_segments = strlen(subject) / 2;
1086 url_segments = malloc(max_segments * sizeof(char *));
1088 if (NULL == url_segments)
1090 log_error(LOG_LEVEL_ERROR,
1091 "Out of memory while decoding URL: %s", subject);
1096 segments = ssplit(subject, "?&", url_segments, max_segments);
1098 while (segments-- > 0)
1100 char *dtoken = url_decode(url_segments[segments]);
1103 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1106 url_segment = strstr(dtoken, "http://");
1107 if (NULL == url_segment)
1109 url_segment = strstr(dtoken, "https://");
1111 if (NULL != url_segment)
1113 url_segment = strdup_or_die(url_segment);
1120 freez(url_segments);
1122 if (url_segment == NULL)
1126 subject = url_segment;
1130 /* Look for a URL inside this one, without decoding anything. */
1131 log_error(LOG_LEVEL_REDIRECTS,
1132 "Checking \"%s\" for unencoded redirects.", subject);
1136 * Find the last URL encoded in the request
1139 while ((tmp = strstr(tmp, "http://")) != NULL)
1143 tmp = (new_url != NULL) ? new_url : subject;
1144 while ((tmp = strstr(tmp, "https://")) != NULL)
1149 if ((new_url != NULL)
1150 && ( (new_url != subject)
1151 || (0 == strncmpic(subject, "http://", 7))
1152 || (0 == strncmpic(subject, "https://", 8))
1156 * Return new URL if we found a redirect
1157 * or if the subject already was a URL.
1159 * The second case makes sure that we can
1160 * chain get_last_url after another redirection check
1161 * (like rewrite_url) without losing earlier redirects.
1163 new_url = strdup(new_url);
1172 #endif /* def FEATURE_FAST_REDIRECTS */
1175 /*********************************************************************
1177 * Function : redirect_url
1179 * Description : Checks if Privoxy should answer the request with
1180 * a HTTP redirect and generates the redirect if
1184 * 1 : csp = Current client state (buffers, headers, etc...)
1186 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1188 *********************************************************************/
1189 struct http_response *redirect_url(struct client_state *csp)
1191 struct http_response *rsp;
1192 #ifdef FEATURE_FAST_REDIRECTS
1194 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1195 * as compile-time option? The user can easily disable
1196 * it in his action file.
1198 char * redirect_mode;
1199 #endif /* def FEATURE_FAST_REDIRECTS */
1200 char *new_url = NULL;
1201 char *redirection_string;
1203 if ((csp->action->flags & ACTION_REDIRECT))
1205 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1208 * If the redirection string begins with 's',
1209 * assume it's a pcrs command, otherwise treat it as
1210 * properly formatted URL and use it for the redirection
1213 * According to (the now obsolete) RFC 2616 section 14.30
1214 * the URL has to be absolute and if the user tries:
1215 * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
1216 * she would get undefined results anyway.
1218 * RFC 7231 7.1.2 actually allows relative references,
1219 * but those start with a leading slash (RFC 3986 4.2) and
1220 * thus can't be mistaken for pcrs commands either.
1223 if (*redirection_string == 's')
1225 char *requested_url;
1227 #ifdef FEATURE_HTTPS_INSPECTION
1228 if (client_use_ssl(csp))
1232 requested_url = strdup_or_die("https://");
1233 err = string_append(&requested_url, csp->http->hostport);
1234 if (!err) err = string_append(&requested_url, csp->http->path);
1237 log_error(LOG_LEVEL_FATAL,
1238 "Failed to rebuild URL 'https://%s%s'",
1239 csp->http->hostport, csp->http->path);
1245 requested_url = csp->http->url;
1247 new_url = rewrite_url(requested_url, redirection_string);
1248 #ifdef FEATURE_HTTPS_INSPECTION
1249 if (requested_url != csp->http->url)
1251 assert(client_use_ssl(csp));
1252 freez(requested_url);
1258 log_error(LOG_LEVEL_REDIRECTS,
1259 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1260 redirection_string);
1261 new_url = strdup(redirection_string);
1265 #ifdef FEATURE_FAST_REDIRECTS
1266 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1270 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1273 * If it exists, use the previously rewritten URL as input
1274 * otherwise just use the old path.
1276 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1277 new_url = get_last_url(old_url, redirect_mode);
1280 #endif /* def FEATURE_FAST_REDIRECTS */
1282 /* Did any redirect action trigger? */
1285 if (url_requires_percent_encoding(new_url))
1288 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1289 strlen(new_url), new_url);
1290 encoded_url = percent_encode_url(new_url);
1292 if (encoded_url == NULL)
1294 return cgi_error_memory();
1296 new_url = encoded_url;
1297 assert(FALSE == url_requires_percent_encoding(new_url));
1300 if (0 == strcmpic(new_url, csp->http->url))
1302 log_error(LOG_LEVEL_ERROR,
1303 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1304 csp->http->url, new_url);
1309 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1311 if (NULL == (rsp = alloc_http_response()))
1314 return cgi_error_memory();
1317 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
1318 if (enlist_unique_header(rsp->headers, "Location", new_url))
1321 free_http_response(rsp);
1322 return cgi_error_memory();
1324 rsp->crunch_reason = REDIRECTED;
1327 return finish_http_response(csp, rsp);
1331 /* Only reached if no redirect is required */
1337 #ifdef FEATURE_IMAGE_BLOCKING
1338 /*********************************************************************
1340 * Function : is_imageurl
1342 * Description : Given a URL, decide whether it should be treated
1343 * as image URL or not.
1346 * 1 : csp = Current client state (buffers, headers, etc...)
1348 * Returns : True (nonzero) if URL is an image URL, false (0)
1351 *********************************************************************/
1352 int is_imageurl(const struct client_state *csp)
1354 return ((csp->action->flags & ACTION_IMAGE) != 0);
1357 #endif /* def FEATURE_IMAGE_BLOCKING */
1360 #ifdef FEATURE_TRUST
1361 /*********************************************************************
1363 * Function : is_untrusted_url
1365 * Description : Should we "distrust" this URL (and block it)?
1367 * Yes if it matches a line in the trustfile, or if the
1368 * referrer matches a line starting with "+" in the
1373 * 1 : csp = Current client state (buffers, headers, etc...)
1375 * Returns : 0 => trusted, 1 => untrusted
1377 *********************************************************************/
1378 int is_untrusted_url(const struct client_state *csp)
1380 struct file_list *fl;
1381 struct block_spec *b;
1382 struct pattern_spec **trusted_url;
1383 struct http_request rhttp[1];
1384 const char * referer;
1388 * If we don't have a trustlist, we trust everybody
1390 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1395 memset(rhttp, '\0', sizeof(*rhttp));
1398 * Do we trust the request URL itself?
1400 for (b = b->next; b ; b = b->next)
1402 if (url_match(b->url, csp->http))
1408 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1410 /* no referrer was supplied */
1416 * If not, do we maybe trust its referrer?
1418 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1424 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1426 if (url_match(*trusted_url, rhttp))
1428 /* if the URL's referrer is from a trusted referrer, then
1429 * add the target spec to the trustfile as an unblocked
1430 * domain and return 0 (which means it's OK).
1435 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1439 char * new_entry = strdup_or_die("~");
1441 string_append(&new_entry, csp->http->hostport);
1443 path = csp->http->path;
1444 if ( (path[0] == '/')
1446 && ((path_end = strchr(path + 2, '/')) != NULL))
1448 /* since this path points into a user's home space
1449 * be sure to include this spec in the trustfile.
1451 long path_len = path_end - path; /* save offset */
1452 path = strdup(path); /* Copy string */
1455 path_end = path + path_len; /* regenerate ptr to new buffer */
1456 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1458 string_join(&new_entry, path);
1462 * Give a reason for generating this entry.
1464 string_append(&new_entry, " # Trusted referrer was: ");
1465 string_append(&new_entry, referer);
1467 if (new_entry != NULL)
1469 if (-1 == fprintf(fp, "%s\n", new_entry))
1471 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1472 new_entry, csp->config->trustfile);
1478 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1479 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1486 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1487 csp->http->hostport, csp->config->trustfile);
1495 #endif /* def FEATURE_TRUST */
1498 /*********************************************************************
1500 * Function : get_filter
1502 * Description : Get a filter with a given name and type.
1503 * Note that taggers are filters, too.
1506 * 1 : csp = Current client state (buffers, headers, etc...)
1507 * 2 : requested_name = Name of the content filter to get
1508 * 3 : requested_type = Type of the filter to tagger to lookup
1510 * Returns : A pointer to the requested filter
1511 * or NULL if the filter wasn't found
1513 *********************************************************************/
1514 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1515 const char *requested_name,
1516 enum filter_type requested_type)
1519 struct re_filterfile_spec *b;
1520 struct file_list *fl;
1522 for (i = 0; i < MAX_AF_FILES; i++)
1525 if ((NULL == fl) || (NULL == fl->f))
1528 * Either there are no filter files left or this
1529 * filter file just contains no valid filters.
1531 * Continue to be sure we don't miss valid filter
1532 * files that are chained after empty or invalid ones.
1537 for (b = fl->f; b != NULL; b = b->next)
1539 if (b->type != requested_type)
1541 /* The callers isn't interested in this filter type. */
1544 if (strcmp(b->name, requested_name) == 0)
1546 /* The requested filter has been found. Abort search. */
1552 /* No filter with the given name and type exists. */
1558 /*********************************************************************
1560 * Function : pcrs_filter_impl
1562 * Description : Execute all text substitutions from all applying
1563 * (based on filter_response_body value) +filter
1564 * or +client_body_filter actions on the given buffer.
1567 * 1 : csp = Current client state (buffers, headers, etc...)
1568 * 2 : filter_response_body = when TRUE execute +filter
1569 * actions; execute +client_body_filter actions otherwise
1570 * 3 : data = Target data
1571 * 4 : data_len = Target data len
1573 * Returns : a pointer to the (newly allocated) modified buffer.
1574 * or NULL if there were no hits or something went wrong
1576 *********************************************************************/
1577 static char *pcrs_filter_impl(const struct client_state *csp, int filter_response_body,
1578 const char *data, size_t *data_len)
1581 size_t size, prev_size;
1582 const int filters_idx =
1583 filter_response_body ? ACTION_MULTI_FILTER : ACTION_MULTI_CLIENT_BODY_FILTER;
1584 const enum filter_type filter_type =
1585 filter_response_body ? FT_CONTENT_FILTER : FT_CLIENT_BODY_FILTER;
1587 const char *old = NULL;
1591 struct re_filterfile_spec *b;
1592 struct list_entry *filtername;
1602 if (filters_available(csp) == FALSE)
1604 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1605 "content filtering enabled, but no content filters available.");
1613 * For all applying actions, look if a filter by that
1614 * name exists and if yes, execute it's pcrs_joblist on the
1617 for (filtername = csp->action->multi[filters_idx]->first;
1618 filtername != NULL; filtername = filtername->next)
1620 int current_hits = 0; /* Number of hits caused by this filter */
1621 int job_number = 0; /* Which job we're currently executing */
1622 int job_hits = 0; /* How many hits the current job caused */
1625 b = get_filter(csp, filtername->str, filter_type);
1631 joblist = b->joblist;
1633 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1635 if (NULL == joblist)
1637 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1642 /* Apply all jobs from the joblist */
1643 for (job = joblist; NULL != job; job = job->next)
1646 job_hits = pcrs_execute(job, old, size, &new, &size);
1651 * That went well. Continue filtering
1652 * and use the result of this job as
1653 * input for the next one.
1655 current_hits += job_hits;
1665 * This job caused an unexpected error. Inform the user
1666 * and skip the rest of the jobs in this filter. We could
1667 * continue with the next job, but usually the jobs
1668 * depend on each other or are similar enough to
1669 * fail for the same reason.
1671 * At the moment our pcrs expects the error codes of pcre 3.4,
1672 * but newer pcre versions can return additional error codes.
1673 * As a result pcrs_strerror()'s error message might be
1674 * "Unknown error ...", therefore we print the numerical value
1677 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1678 * should we use LOG_LEVEL_RE_FILTER instead?
1680 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1681 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1686 if (b->dynamic) pcrs_free_joblist(joblist);
1688 if (filter_response_body)
1690 log_error(LOG_LEVEL_RE_FILTER,
1691 "filtering %s%s (size %lu) with \'%s\' produced %d hits (new size %lu).",
1692 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1696 log_error(LOG_LEVEL_RE_FILTER, "filtering request body from client %s "
1697 "(size %lu) with \'%s\' produced %d hits (new size %lu).",
1698 csp->ip_addr_str, prev_size, b->name, current_hits, size);
1700 #ifdef FEATURE_EXTENDED_STATISTICS
1701 update_filter_statistics(b->name, current_hits);
1703 hits += current_hits;
1707 * If there were no hits, destroy our copy and let
1708 * chat() use the original content
1712 if (old != data && old != new)
1725 /*********************************************************************
1727 * Function : pcrs_filter_response_body
1729 * Description : Execute all text substitutions from all applying
1730 * +filter actions on the text buffer that's been
1731 * accumulated in csp->iob->buf.
1734 * 1 : csp = Current client state (buffers, headers, etc...)
1736 * Returns : a pointer to the (newly allocated) modified buffer.
1737 * or NULL if there were no hits or something went wrong
1739 *********************************************************************/
1740 static char *pcrs_filter_response_body(struct client_state *csp)
1742 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1749 if (csp->iob->cur >= csp->iob->eod)
1754 new = pcrs_filter_impl(csp, TRUE, csp->iob->cur, &size);
1758 csp->flags |= CSP_FLAG_MODIFIED;
1759 csp->content_length = size;
1760 clear_iob(csp->iob);
1767 #ifdef FEATURE_EXTERNAL_FILTERS
1768 /*********************************************************************
1770 * Function : get_external_filter
1772 * Description : Lookup the code to execute for an external filter.
1773 * Masks the misuse of the re_filterfile_spec.
1776 * 1 : csp = Current client state (buffers, headers, etc...)
1777 * 2 : name = Name of the content filter to get
1779 * Returns : A pointer to the requested code
1780 * or NULL if the filter wasn't found
1782 *********************************************************************/
1783 static const char *get_external_filter(const struct client_state *csp,
1786 struct re_filterfile_spec *external_filter;
1788 external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
1789 if (external_filter == NULL)
1791 log_error(LOG_LEVEL_FATAL,
1792 "Didn't find stuff to execute for external filter: %s",
1796 return external_filter->patterns->first->str;
1801 /*********************************************************************
1803 * Function : set_privoxy_variables
1805 * Description : Sets a couple of privoxy-specific environment variables
1808 * 1 : csp = Current client state (buffers, headers, etc...)
1812 *********************************************************************/
1813 static void set_privoxy_variables(const struct client_state *csp)
1820 { "PRIVOXY_URL", csp->http->url },
1821 { "PRIVOXY_PATH", csp->http->path },
1822 { "PRIVOXY_HOST", csp->http->host },
1823 { "PRIVOXY_ORIGIN", csp->ip_addr_str },
1824 { "PRIVOXY_LISTEN_ADDRESS", csp->listen_addr_str },
1827 for (i = 0; i < SZ(env); i++)
1829 if (setenv(env[i].name, env[i].value, 1))
1831 log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
1832 env[i].name, env[i].value);
1838 /*********************************************************************
1840 * Function : execute_external_filter
1842 * Description : Pipe content into external filter and return the output
1845 * 1 : csp = Current client state (buffers, headers, etc...)
1846 * 2 : name = Name of the external filter to execute
1847 * 3 : content = The original content to filter
1848 * 4 : size = The size of the content buffer
1850 * Returns : a pointer to the (newly allocated) modified buffer.
1851 * or NULL if there were no hits or something went wrong
1853 *********************************************************************/
1854 static char *execute_external_filter(const struct client_state *csp,
1855 const char *name, char *content, size_t *size)
1858 char file_name[FILENAME_MAX];
1860 char *filter_output;
1864 const char *external_filter;
1866 if (csp->config->temporary_directory == NULL)
1868 log_error(LOG_LEVEL_ERROR,
1869 "No temporary-directory configured. Can't execute filter: %s",
1874 external_filter = get_external_filter(csp, name);
1876 if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
1877 "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
1879 log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
1883 fd = mkstemp(file_name);
1886 log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
1890 fp = fdopen(fd, "w");
1893 log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
1899 * The size may be zero if a previous filter discarded everything.
1901 * This isn't necessary unintentional, so we just don't try
1902 * to fwrite() nothing and let the user deal with the rest.
1904 if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
1906 log_error(LOG_LEVEL_ERROR, "fwrite(..., %lu, 1, ..) failed: %E", *size);
1913 if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
1915 log_error(LOG_LEVEL_ERROR,
1916 "temporary-directory or external filter path too long");
1921 log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
1924 * The locking is necessary to prevent other threads
1925 * from overwriting the environment variables before
1926 * the popen fork. Afterwards this no longer matters.
1928 privoxy_mutex_lock(&external_filter_mutex);
1929 set_privoxy_variables(csp);
1930 fp = popen(cmd, "r");
1931 privoxy_mutex_unlock(&external_filter_mutex);
1934 log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
1939 /* Allocate at least one byte */
1940 filter_output = malloc_or_die(*size + 1);
1943 while (!feof(fp) && !ferror(fp))
1946 /* Could be bigger ... */
1947 enum { READ_LENGTH = 2048 };
1949 if (new_size + READ_LENGTH >= *size)
1953 /* Could be considered wasteful if the content is 'large'. */
1954 *size += (*size >= READ_LENGTH) ? *size : READ_LENGTH;
1956 p = realloc(filter_output, *size);
1959 log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
1960 "external filter output. Using what we got so far.");
1965 assert(new_size + READ_LENGTH < *size);
1966 len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
1976 log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
1980 log_error(LOG_LEVEL_RE_FILTER,
1981 "Executing '%s' resulted in return value %d. "
1982 "Read %lu of up to %lu bytes.", name, (ret >> 8), new_size, *size);
1988 return filter_output;
1991 #endif /* def FEATURE_EXTERNAL_FILTERS */
1994 /*********************************************************************
1996 * Function : pcrs_filter_request_body
1998 * Description : Execute all text substitutions from all applying
1999 * +client_body_filter actions on the given text buffer.
2002 * 1 : csp = Current client state (buffers, headers, etc...)
2003 * 2 : data = Target data
2004 * 3 : data_len = Target data len
2006 * Returns : a pointer to the (newly allocated) modified buffer.
2007 * or NULL if there were no hits or something went wrong
2009 *********************************************************************/
2010 static char *pcrs_filter_request_body(const struct client_state *csp, const char *data, size_t *data_len)
2012 return pcrs_filter_impl(csp, FALSE, data, data_len);
2016 /*********************************************************************
2018 * Function : gif_deanimate_response
2020 * Description : Deanimate the GIF image that has been accumulated in
2021 * csp->iob->buf, set csp->content_length to the modified
2022 * size and raise the CSP_FLAG_MODIFIED flag.
2025 * 1 : csp = Current client state (buffers, headers, etc...)
2027 * Returns : a pointer to the (newly allocated) modified buffer.
2028 * or NULL in case something went wrong.
2030 *********************************************************************/
2032 char *gif_deanimate_response(struct client_state *csp)
2034 static char *gif_deanimate_response(struct client_state *csp)
2037 struct binbuffer *in, *out;
2041 size = (size_t)(csp->iob->eod - csp->iob->cur);
2043 in = zalloc_or_die(sizeof(*in));
2044 out = zalloc_or_die(sizeof(*out));
2046 in->buffer = csp->iob->cur;
2049 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
2051 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
2058 if ((int)size == out->offset)
2060 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
2064 log_error(LOG_LEVEL_DEANIMATE,
2065 "Success! GIF shrunk from %lu bytes to %lu.", size, out->offset);
2067 csp->content_length = out->offset;
2068 csp->flags |= CSP_FLAG_MODIFIED;
2078 /*********************************************************************
2080 * Function : get_filter_function
2082 * Description : Decides which content filter function has
2083 * to be applied (if any). Only considers functions
2084 * for internal filters which are mutually-exclusive.
2087 * 1 : csp = Current client state (buffers, headers, etc...)
2089 * Returns : The content filter function to run, or
2090 * NULL if no content filter is active
2092 *********************************************************************/
2093 static filter_function_ptr get_filter_function(const struct client_state *csp)
2095 filter_function_ptr filter_function = NULL;
2098 * Choose the applying filter function based on
2099 * the content type and action settings.
2101 if ((csp->content_type & CT_TEXT) &&
2102 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2104 filter_function = pcrs_filter_response_body;
2106 else if ((csp->content_type & CT_GIF) &&
2107 (csp->action->flags & ACTION_DEANIMATE))
2109 filter_function = gif_deanimate_response;
2112 return filter_function;
2116 /*********************************************************************
2118 * Function : remove_chunked_transfer_coding
2120 * Description : In-situ remove the "chunked" transfer coding as defined
2121 * in RFC 7230 4.1 from a buffer. XXX: The implementation
2122 * is neither complete nor compliant (TODO #129).
2125 * 1 : buffer = Pointer to the text buffer
2126 * 2 : size = In: Number of bytes to be processed,
2127 * Out: Number of bytes after de-chunking.
2128 * (undefined in case of errors)
2130 * Returns : JB_ERR_OK for success,
2131 * JB_ERR_PARSE otherwise
2133 *********************************************************************/
2135 extern jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2137 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2141 unsigned int chunksize = 0;
2142 char *from_p, *to_p;
2143 const char *end_of_buffer = buffer + *size;
2147 log_error(LOG_LEVEL_FATAL, "Invalid chunked input. Buffer is empty.");
2148 return JB_ERR_PARSE;
2152 from_p = to_p = buffer;
2154 if (sscanf(buffer, "%x", &chunksize) != 1)
2156 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2157 return JB_ERR_PARSE;
2160 while (chunksize > 0U)
2163 * If the chunk-size is valid, we should have at least
2164 * chunk-size bytes of chunk-data and five bytes of
2165 * meta data (chunk-size, CRLF, CRLF) left in the buffer.
2167 if (chunksize + 5 >= *size - newsize)
2169 log_error(LOG_LEVEL_ERROR,
2170 "Chunk size %u exceeds buffered data left. "
2171 "Already digested %lu of %lu buffered bytes.",
2172 chunksize, newsize, *size);
2173 return JB_ERR_PARSE;
2177 * Skip the chunk-size, the optional chunk-ext and the CRLF
2178 * that is supposed to be located directly before the start
2181 if (NULL == (from_p = strstr(from_p, "\r\n")))
2183 log_error(LOG_LEVEL_ERROR,
2184 "Failed to strip \"chunked\" transfer coding. "
2185 "Line with chunk size doesn't seem to end properly.");
2186 return JB_ERR_PARSE;
2191 * The previous strstr() does not enforce chunk-validity
2192 * and is sattisfied as long a CRLF is left in the buffer.
2194 * Make sure the bytes we consider chunk-data are within
2197 if (from_p + chunksize >= end_of_buffer)
2199 log_error(LOG_LEVEL_ERROR,
2200 "Failed to decode content for filtering. "
2201 "One chunk end is beyond the end of the buffer.");
2202 return JB_ERR_PARSE;
2205 memmove(to_p, from_p, (size_t) chunksize);
2206 newsize += chunksize;
2207 to_p = buffer + newsize;
2208 from_p += chunksize;
2211 * Not merging this check with the previous one allows us
2212 * to keep chunks without trailing CRLF. It's not clear
2213 * if we actually have to care about those, though.
2215 if (from_p + 2 >= end_of_buffer)
2217 log_error(LOG_LEVEL_ERROR, "Not enough room for trailing CRLF.");
2218 return JB_ERR_PARSE;
2221 if (sscanf(from_p, "%x", &chunksize) != 1)
2223 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2228 /* XXX: Should get its own loglevel. */
2229 log_error(LOG_LEVEL_RE_FILTER,
2230 "De-chunking successful. Shrunk from %lu to %lu", *size, newsize);
2239 /*********************************************************************
2241 * Function : prepare_for_filtering
2243 * Description : If necessary, de-chunks and decompresses
2244 * the content so it can get filterd.
2247 * 1 : csp = Current client state (buffers, headers, etc...)
2249 * Returns : JB_ERR_OK for success,
2250 * JB_ERR_PARSE otherwise
2252 *********************************************************************/
2253 static jb_err prepare_for_filtering(struct client_state *csp)
2255 jb_err err = JB_ERR_OK;
2258 * If the body has a "chunked" transfer-encoding,
2259 * get rid of it, adjusting size and iob->eod
2261 if (csp->flags & CSP_FLAG_CHUNKED)
2263 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2265 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2266 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2267 if (JB_ERR_OK == err)
2269 csp->iob->eod = csp->iob->cur + size;
2270 csp->flags |= CSP_FLAG_MODIFIED;
2274 return JB_ERR_PARSE;
2280 * If the body has a supported transfer-encoding,
2281 * decompress it, adjusting size and iob->eod.
2283 if ((csp->content_type & (CT_GZIP|CT_DEFLATE))
2284 #ifdef FEATURE_BROTLI
2285 || (csp->content_type & CT_BROTLI)
2289 if (0 == csp->iob->eod - csp->iob->cur)
2291 /* Nothing left after de-chunking. */
2295 err = decompress_iob(csp);
2297 if (JB_ERR_OK == err)
2299 csp->flags |= CSP_FLAG_MODIFIED;
2300 csp->content_type &= ~CT_TABOO;
2305 * Unset content types to remember not to
2306 * modify the Content-Encoding header later.
2308 csp->content_type &= ~CT_GZIP;
2309 csp->content_type &= ~CT_DEFLATE;
2310 #ifdef FEATURE_BROTLI
2311 csp->content_type &= ~CT_BROTLI;
2321 /*********************************************************************
2323 * Function : execute_content_filters
2325 * Description : Executes a given content filter.
2328 * 1 : csp = Current client state (buffers, headers, etc...)
2330 * Returns : Pointer to the modified buffer, or
2331 * NULL if filtering failed or wasn't necessary.
2333 *********************************************************************/
2334 char *execute_content_filters(struct client_state *csp)
2337 filter_function_ptr content_filter;
2339 assert(content_filters_enabled(csp->action));
2341 if (0 == csp->iob->eod - csp->iob->cur)
2344 * No content (probably status code 301, 302 ...),
2345 * no filtering necessary.
2350 if (JB_ERR_OK != prepare_for_filtering(csp))
2353 * failed to de-chunk or decompress.
2358 if (0 == csp->iob->eod - csp->iob->cur)
2361 * Clown alarm: chunked and/or compressed nothing delivered.
2366 content_filter = get_filter_function(csp);
2367 content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
2369 #ifdef FEATURE_EXTERNAL_FILTERS
2370 if ((csp->content_type & CT_TEXT) &&
2371 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
2373 struct list_entry *filtername;
2374 size_t size = (size_t)csp->content_length;
2376 if (content == NULL)
2378 content = csp->iob->cur;
2379 size = (size_t)(csp->iob->eod - csp->iob->cur);
2382 for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
2383 filtername ; filtername = filtername->next)
2385 char *result = execute_external_filter(csp, filtername->str, content, &size);
2388 if (content != csp->iob->cur)
2395 csp->flags |= CSP_FLAG_MODIFIED;
2396 csp->content_length = size;
2398 #endif /* def FEATURE_EXTERNAL_FILTERS */
2405 /*********************************************************************
2407 * Function : execute_client_body_filters
2409 * Description : Executes client body filters for the request that is buffered
2410 * in the client_iob. The client_iob is updated with the filtered
2414 * 1 : csp = Current client state (buffers, headers, etc...)
2415 * 2 : content_length = content length. Upon successful filtering
2416 * the passed value is updated with the new content length.
2418 * Returns : 1 if the content has been filterd. 0 if it hasn't.
2420 *********************************************************************/
2421 int execute_client_body_filters(struct client_state *csp, size_t *content_length)
2423 char *filtered_content;
2425 assert(client_body_filters_enabled(csp->action));
2427 if (content_length == 0)
2430 * No content, no filtering necessary.
2435 filtered_content = pcrs_filter_request_body(csp, csp->client_iob->cur, content_length);
2436 if (filtered_content != NULL)
2438 freez(csp->client_iob->buf);
2439 csp->client_iob->buf = filtered_content;
2440 csp->client_iob->cur = csp->client_iob->buf;
2441 csp->client_iob->eod = csp->client_iob->cur + *content_length;
2442 csp->client_iob->size = *content_length;
2451 /*********************************************************************
2453 * Function : execute_client_body_taggers
2455 * Description : Executes client body taggers for the request that is
2456 * buffered in the client_iob.
2457 * XXX: Lots of code shared with header_tagger
2460 * 1 : csp = Current client state (buffers, headers, etc...)
2461 * 2 : content_length = content length.
2465 *********************************************************************/
2466 jb_err execute_client_body_taggers(struct client_state *csp, size_t content_length)
2468 enum filter_type wanted_filter_type = FT_CLIENT_BODY_TAGGER;
2469 int multi_action_index = ACTION_MULTI_CLIENT_BODY_TAGGER;
2472 struct re_filterfile_spec *b;
2473 struct list_entry *tag_name;
2475 assert(client_body_taggers_enabled(csp->action));
2477 if (content_length == 0)
2480 * No content, no tagging necessary.
2485 log_error(LOG_LEVEL_INFO, "Got to execute tagger on %N",
2486 content_length, csp->client_iob->cur);
2488 if (list_is_empty(csp->action->multi[multi_action_index])
2489 || filters_available(csp) == FALSE)
2491 /* Return early if no taggers apply or if none are available. */
2495 /* Execute all applying taggers */
2496 for (tag_name = csp->action->multi[multi_action_index]->first;
2497 NULL != tag_name; tag_name = tag_name->next)
2499 char *modified_tag = NULL;
2500 char *tag = csp->client_iob->cur;
2501 size_t size = content_length;
2504 b = get_filter(csp, tag_name->str, wanted_filter_type);
2510 joblist = b->joblist;
2512 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2514 if (NULL == joblist)
2516 log_error(LOG_LEVEL_TAGGING,
2517 "Tagger %s has empty joblist. Nothing to do.", b->name);
2521 /* execute their pcrs_joblist on the body. */
2522 for (job = joblist; NULL != job; job = job->next)
2524 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2528 /* Success, continue with the modified version. */
2529 if (tag != csp->client_iob->cur)
2537 /* Tagger doesn't match */
2540 /* Regex failure, log it but continue anyway. */
2541 log_error(LOG_LEVEL_ERROR,
2542 "Problems with tagger \'%s\': %s",
2543 b->name, pcrs_strerror(hits));
2545 freez(modified_tag);
2549 if (b->dynamic) pcrs_free_joblist(joblist);
2551 /* If this tagger matched */
2552 if (tag != csp->client_iob->cur)
2557 * There is no technical limitation which makes
2558 * it impossible to use empty tags, but I assume
2559 * no one would do it intentionally.
2562 log_error(LOG_LEVEL_TAGGING,
2563 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
2567 if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
2569 log_error(LOG_LEVEL_TAGGING,
2570 "Tagger \'%s\' didn't add tag \'%s\': suppressed",
2576 if (!list_contains_item(csp->tags, tag))
2578 if (JB_ERR_OK != enlist(csp->tags, tag))
2580 log_error(LOG_LEVEL_ERROR,
2581 "Insufficient memory to add tag \'%s\', "
2582 "based on tagger \'%s\'",
2587 char *action_message;
2589 * update the action bits right away, to make
2590 * tagging based on tags set by earlier taggers
2591 * of the same kind possible.
2593 if (update_action_bits_for_tag(csp, tag))
2595 action_message = "Action bits updated accordingly.";
2599 action_message = "No action bits update necessary.";
2602 log_error(LOG_LEVEL_TAGGING,
2603 "Tagger \'%s\' added tag \'%s\'. %s",
2604 b->name, tag, action_message);
2609 /* XXX: Is this log-worthy? */
2610 log_error(LOG_LEVEL_TAGGING,
2611 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
2622 /*********************************************************************
2624 * Function : get_url_actions
2626 * Description : Gets the actions for this URL.
2629 * 1 : csp = Current client state (buffers, headers, etc...)
2630 * 2 : http = http_request request for blocked URLs
2634 *********************************************************************/
2635 void get_url_actions(struct client_state *csp, struct http_request *http)
2637 struct file_list *fl;
2638 struct url_actions *b;
2641 init_current_action(csp->action);
2643 for (i = 0; i < MAX_AF_FILES; i++)
2645 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2650 #ifdef FEATURE_CLIENT_TAGS
2651 apply_url_actions(csp->action, http, csp->client_tags, b);
2653 apply_url_actions(csp->action, http, b);
2660 /*********************************************************************
2662 * Function : apply_url_actions
2664 * Description : Applies a list of URL actions.
2667 * 1 : action = Destination.
2668 * 2 : http = Current URL
2669 * 3 : client_tags = list of client tags
2670 * 4 : b = list of URL actions to apply
2674 *********************************************************************/
2675 static void apply_url_actions(struct current_action_spec *action,
2676 struct http_request *http,
2677 #ifdef FEATURE_CLIENT_TAGS
2678 const struct list *client_tags,
2680 struct url_actions *b)
2684 /* Should never happen */
2688 for (b = b->next; NULL != b; b = b->next)
2690 if (url_match(b->url, http))
2692 merge_current_action(action, b->action);
2694 #ifdef FEATURE_CLIENT_TAGS
2695 if (client_tag_match(b->url, client_tags))
2697 merge_current_action(action, b->action);
2704 /*********************************************************************
2706 * Function : get_forward_override_settings
2708 * Description : Returns forward settings as specified with the
2709 * forward-override{} action. forward-override accepts
2710 * forward lines similar to the one used in the
2711 * configuration file, but without the URL pattern.
2717 * in the configuration file can be replaced with
2718 * the action section:
2720 * {+forward-override{forward .}}
2724 * 1 : csp = Current client state (buffers, headers, etc...)
2726 * Returns : Pointer to forwarding structure in case of success.
2727 * Invalid syntax is fatal.
2729 *********************************************************************/
2730 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2732 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2733 char forward_settings[BUFFER_SIZE];
2734 char *http_parent = NULL;
2735 /* variable names were chosen for consistency reasons. */
2736 struct forward_spec *fwd = NULL;
2740 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2741 /* Should be enforced by load_one_actions_file() */
2742 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2744 /* Create a copy ssplit can modify */
2745 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2747 if (NULL != csp->fwd)
2750 * XXX: Currently necessary to prevent memory
2751 * leaks when the show-url-info cgi page is visited.
2753 unload_forward_spec(csp->fwd);
2757 * allocate a new forward node, valid only for
2758 * the lifetime of this request. Save its location
2759 * in csp as well, so sweep() can free it later on.
2761 fwd = csp->fwd = zalloc_or_die(sizeof(*fwd));
2763 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2764 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2766 fwd->type = SOCKS_NONE;
2768 /* Parse the parent HTTP proxy host:port */
2769 http_parent = vec[1];
2772 else if ((vec_count == 2) && !strcasecmp(vec[0], "forward-webserver"))
2774 fwd->type = FORWARD_WEBSERVER;
2776 /* Parse the parent HTTP server host:port */
2777 http_parent = vec[1];
2780 else if (vec_count == 3)
2782 char *socks_proxy = NULL;
2784 if (!strcasecmp(vec[0], "forward-socks4"))
2786 fwd->type = SOCKS_4;
2787 socks_proxy = vec[1];
2789 else if (!strcasecmp(vec[0], "forward-socks4a"))
2791 fwd->type = SOCKS_4A;
2792 socks_proxy = vec[1];
2794 else if (!strcasecmp(vec[0], "forward-socks5"))
2796 fwd->type = SOCKS_5;
2797 socks_proxy = vec[1];
2799 else if (!strcasecmp(vec[0], "forward-socks5t"))
2801 fwd->type = SOCKS_5T;
2802 socks_proxy = vec[1];
2805 if (NULL != socks_proxy)
2807 /* Parse the SOCKS proxy [user:pass@]host[:port] */
2808 fwd->gateway_port = 1080;
2809 parse_forwarder_address(socks_proxy,
2810 &fwd->gateway_host, &fwd->gateway_port,
2811 &fwd->auth_username, &fwd->auth_password);
2813 http_parent = vec[2];
2817 if (NULL == http_parent)
2819 log_error(LOG_LEVEL_FATAL,
2820 "Invalid forward-override syntax in: %s", forward_override_line);
2821 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2824 /* Parse http forwarding settings */
2825 if (strcmp(http_parent, ".") != 0)
2827 fwd->forward_port = 8000;
2828 parse_forwarder_address(http_parent,
2829 &fwd->forward_host, &fwd->forward_port,
2833 assert (NULL != fwd);
2835 log_error(LOG_LEVEL_CONNECT,
2836 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2842 /*********************************************************************
2844 * Function : forward_url
2846 * Description : Should we forward this to another proxy?
2849 * 1 : csp = Current client state (buffers, headers, etc...)
2850 * 2 : http = http_request request for current URL
2852 * Returns : Pointer to forwarding information.
2854 *********************************************************************/
2855 const struct forward_spec *forward_url(struct client_state *csp,
2856 const struct http_request *http)
2858 static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
2859 struct forward_spec *fwd = csp->config->forward;
2861 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2863 return get_forward_override_settings(csp);
2873 if (url_match(fwd->url, http))
2884 /*********************************************************************
2886 * Function : direct_response
2888 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2889 * request and if so, return a HTTP 501 to the client.
2891 * FIXME: I have a stupid name and I should handle the
2892 * requests properly. Still, what we do here is rfc-
2893 * compliant, whereas ignoring or forwarding are not.
2896 * 1 : csp = Current client state (buffers, headers, etc...)
2898 * Returns : http_response if , NULL if nonmatch or handler fail
2900 *********************************************************************/
2901 struct http_response *direct_response(struct client_state *csp)
2903 struct http_response *rsp;
2904 struct list_entry *p;
2906 if ((0 == strcmpic(csp->http->gpc, "trace"))
2907 || (0 == strcmpic(csp->http->gpc, "options")))
2909 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2911 if (!strncmpic(p->str, "Max-Forwards:", 13))
2913 unsigned int max_forwards;
2916 * If it's a Max-Forwards value of zero,
2917 * we have to intercept the request.
2919 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2922 * FIXME: We could handle at least TRACE here,
2923 * but that would require a verbatim copy of
2924 * the request which we don't have anymore
2926 log_error(LOG_LEVEL_HEADER,
2927 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2930 /* Get mem for response or fail*/
2931 if (NULL == (rsp = alloc_http_response()))
2933 return cgi_error_memory();
2936 rsp->status = strdup_or_die("501 Not Implemented");
2938 rsp->crunch_reason = UNSUPPORTED;
2940 return(finish_http_response(csp, rsp));
2949 /*********************************************************************
2951 * Function : content_requires_filtering
2953 * Description : Checks whether there are any content filters
2954 * enabled for the current request and if they
2955 * can actually be applied..
2958 * 1 : csp = Current client state (buffers, headers, etc...)
2960 * Returns : TRUE for yes, FALSE otherwise
2962 *********************************************************************/
2963 int content_requires_filtering(struct client_state *csp)
2965 if ((csp->content_type & CT_TABOO)
2966 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2972 * Are we enabling text mode by force?
2974 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2977 * Do we really have to?
2979 if (csp->content_type & CT_TEXT)
2981 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2985 csp->content_type |= CT_TEXT;
2986 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2990 if (!(csp->content_type & CT_DECLARED))
2993 * The server didn't bother to declare a MIME-Type.
2994 * Assume it's text that can be filtered.
2996 * This also regularly happens with 304 responses,
2997 * therefore logging anything here would cause
3000 csp->content_type |= CT_TEXT;
3004 * Choose the applying filter function based on
3005 * the content type and action settings.
3007 if ((csp->content_type & CT_TEXT) &&
3008 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
3009 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
3013 else if ((csp->content_type & CT_GIF) &&
3014 (csp->action->flags & ACTION_DEANIMATE))
3024 /*********************************************************************
3026 * Function : content_filters_enabled
3028 * Description : Checks whether there are any content filters
3029 * enabled for the current request.
3032 * 1 : action = Action spec to check.
3034 * Returns : TRUE for yes, FALSE otherwise
3036 *********************************************************************/
3037 int content_filters_enabled(const struct current_action_spec *action)
3039 return ((action->flags & ACTION_DEANIMATE) ||
3040 !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
3041 !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
3045 /*********************************************************************
3047 * Function : client_body_filters_enabled
3049 * Description : Checks whether there are any client body filters
3050 * enabled for the current request.
3053 * 1 : action = Action spec to check.
3055 * Returns : TRUE for yes, FALSE otherwise
3057 *********************************************************************/
3058 int client_body_filters_enabled(const struct current_action_spec *action)
3060 return !list_is_empty(action->multi[ACTION_MULTI_CLIENT_BODY_FILTER]);
3064 /*********************************************************************
3066 * Function : client_body_taggers_enabled
3068 * Description : Checks whether there are any client body taggers
3069 * enabled for the current request.
3072 * 1 : action = Action spec to check.
3074 * Returns : TRUE for yes, FALSE otherwise
3076 *********************************************************************/
3077 int client_body_taggers_enabled(const struct current_action_spec *action)
3079 return !list_is_empty(action->multi[ACTION_MULTI_CLIENT_BODY_TAGGER]);
3082 /*********************************************************************
3084 * Function : filters_available
3086 * Description : Checks whether there are any filters available.
3089 * 1 : csp = Current client state (buffers, headers, etc...)
3091 * Returns : TRUE for yes, FALSE otherwise.
3093 *********************************************************************/
3094 int filters_available(const struct client_state *csp)
3097 for (i = 0; i < MAX_AF_FILES; i++)
3099 const struct file_list *fl = csp->rlist[i];
3100 if ((NULL != fl) && (NULL != fl->f))
3108 #ifdef FEATURE_EXTENDED_STATISTICS
3110 struct filter_statistics_entry
3113 unsigned long long executions;
3114 unsigned long long response_bodies_modified;
3115 unsigned long long hits;
3117 struct filter_statistics_entry *next;
3120 static struct filter_statistics_entry *filter_statistics = NULL;
3123 /*********************************************************************
3125 * Function : register_filter_for_statistics
3127 * Description : Registers a filter so we can gather statistics for
3128 * it unless the filter has already been registered
3132 * 1 : filter = Name of the filter to register
3136 *********************************************************************/
3137 void register_filter_for_statistics(const char *filter)
3139 struct filter_statistics_entry *entry;
3141 privoxy_mutex_lock(&filter_statistics_mutex);
3143 if (filter_statistics == NULL)
3145 filter_statistics = zalloc_or_die(sizeof(struct filter_statistics_entry));
3146 entry = filter_statistics;
3147 entry->filter = strdup_or_die(filter);
3148 privoxy_mutex_unlock(&filter_statistics_mutex);
3151 entry = filter_statistics;
3152 while (entry != NULL)
3154 if (!strcmp(entry->filter, filter))
3156 /* Already registered, nothing to do. */
3159 if (entry->next == NULL)
3161 entry->next = zalloc_or_die(sizeof(struct filter_statistics_entry));
3162 entry->next->filter = strdup_or_die(filter);
3165 entry = entry->next;
3168 privoxy_mutex_unlock(&filter_statistics_mutex);
3173 /*********************************************************************
3175 * Function : update_filter_statistics
3177 * Description : Updates the statistics for a filter.
3180 * 1 : filter = Name of the filter to update
3181 * 2 : hits = Hit count.
3185 *********************************************************************/
3186 void update_filter_statistics(const char *filter, int hits)
3188 struct filter_statistics_entry *entry;
3190 privoxy_mutex_lock(&filter_statistics_mutex);
3192 entry = filter_statistics;
3193 while (entry != NULL)
3195 if (!strcmp(entry->filter, filter))
3197 entry->executions++;
3200 entry->response_bodies_modified++;
3201 entry->hits += (unsigned)hits;
3205 entry = entry->next;
3208 privoxy_mutex_unlock(&filter_statistics_mutex);
3213 /*********************************************************************
3215 * Function : get_filter_statistics
3217 * Description : Gets the statistics for a filter.
3220 * 1 : filter = Name of the filter to get statistics for.
3221 * 2 : executions = Storage for the execution count.
3222 * 3 : response_bodies_modified = Storage for the number
3223 * of modified response bodies.
3224 * 4 : hits = Storage for the number of hits.
3228 *********************************************************************/
3229 void get_filter_statistics(const char *filter, unsigned long long *executions,
3230 unsigned long long *response_bodies_modified,
3231 unsigned long long *hits)
3233 struct filter_statistics_entry *entry;
3235 privoxy_mutex_lock(&filter_statistics_mutex);
3237 entry = filter_statistics;
3238 while (entry != NULL)
3240 if (!strcmp(entry->filter, filter))
3242 *executions = entry->executions;
3243 *response_bodies_modified = entry->response_bodies_modified;
3244 *hits = entry->hits;
3247 entry = entry->next;
3250 privoxy_mutex_unlock(&filter_statistics_mutex);
3255 struct block_statistics_entry
3258 unsigned long long count;
3260 struct block_statistics_entry *next;
3263 static struct block_statistics_entry *block_statistics = NULL;
3265 /*********************************************************************
3267 * Function : register_block_reason_for_statistics
3269 * Description : Registers a block reason so we can gather statistics
3270 * for it unless the block reason has already been
3271 * registered before.
3274 * 1 : block_reason = Block reason to register
3278 *********************************************************************/
3279 void register_block_reason_for_statistics(const char *block_reason)
3281 struct block_statistics_entry *entry;
3283 privoxy_mutex_lock(&block_reason_statistics_mutex);
3285 if (block_statistics == NULL)
3287 block_statistics = zalloc_or_die(sizeof(struct block_statistics_entry));
3288 entry = block_statistics;
3289 entry->block_reason = strdup_or_die(block_reason);
3290 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3293 entry = block_statistics;
3294 while (entry != NULL)
3296 if (!strcmp(entry->block_reason, block_reason))
3298 /* Already registered, nothing to do. */
3301 if (entry->next == NULL)
3303 entry->next = zalloc_or_die(sizeof(struct block_statistics_entry));
3304 entry->next->block_reason = strdup_or_die(block_reason);
3307 entry = entry->next;
3310 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3315 /*********************************************************************
3317 * Function : increment_block_reason_counter
3319 * Description : Updates the counter for a block reason.
3322 * 1 : block_reason = Block reason to count
3326 *********************************************************************/
3327 static void increment_block_reason_counter(const char *block_reason)
3329 struct block_statistics_entry *entry;
3331 privoxy_mutex_lock(&block_reason_statistics_mutex);
3333 entry = block_statistics;
3334 while (entry != NULL)
3336 if (!strcmp(entry->block_reason, block_reason))
3341 entry = entry->next;
3344 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3349 /*********************************************************************
3351 * Function : get_block_reason_count
3353 * Description : Gets number of times a block reason was used.
3356 * 1 : block_reason = Block reason to get statistics for.
3357 * 2 : count = Storage for the number of times the block
3362 *********************************************************************/
3363 void get_block_reason_count(const char *block_reason, unsigned long long *count)
3365 struct block_statistics_entry *entry;
3367 privoxy_mutex_lock(&block_reason_statistics_mutex);
3369 entry = block_statistics;
3370 while (entry != NULL)
3372 if (!strcmp(entry->block_reason, block_reason))
3374 *count = entry->count;
3377 entry = entry->next;
3380 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3384 #endif /* def FEATURE_EXTENDED_STATISTICS */