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)(struct client_state *csp);
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;
184 if (network->ss_family != netmask->ss_family)
186 /* This should never happen */
187 assert(network->ss_family == netmask->ss_family);
188 log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
191 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
192 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
193 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
195 /* Check for family */
196 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
197 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
199 /* Map AF_INET6 V4MAPPED address into AF_INET */
203 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
204 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
206 /* Map AF_INET6 V4MAPPED network into AF_INET */
212 /* XXX: Port check is signaled in netmask */
213 if (*netmask_port && *network_port != *address_port)
218 /* TODO: Optimize by checking by words instead of octets */
219 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
221 if ((network_addr[i] & netmask_addr[i]) !=
222 (address_addr[i] & netmask_addr[i]))
230 #endif /* def HAVE_RFC2553 */
233 /*********************************************************************
235 * Function : block_acl
237 * Description : Block this request?
238 * Decide yes or no based on ACL file.
241 * 1 : dst = The proxy or gateway address this is going to.
242 * Or NULL to check all possible targets.
243 * 2 : csp = Current client state (buffers, headers, etc...)
244 * Also includes the client IP address.
246 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
248 *********************************************************************/
249 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
251 struct access_control_list *acl = csp->config->acl;
253 /* if not using an access control list, then permit the connection */
259 /* search the list */
264 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
266 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
272 /* Just want to check if they have any access */
273 if (acl->action == ACL_PERMIT)
285 * XXX: An undefined acl->dst is full of zeros and should be
286 * considered a wildcard address. sockaddr_storage_to_ip()
287 * fails on such destinations because of unknown sa_familly
288 * (glibc only?). However this test is not portable.
290 * So, we signal the acl->dst is wildcard in wildcard_dst.
293 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
295 ((dst->addr & acl->dst->mask) == acl->dst->addr)
296 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
300 if (acl->action == ACL_PERMIT)
318 /*********************************************************************
320 * Function : acl_addr
322 * Description : Called from `load_config' to parse an ACL address.
325 * 1 : aspec = String specifying ACL address.
326 * 2 : aca = struct access_control_addr to fill in.
328 * Returns : 0 => Ok, everything else is an error.
330 *********************************************************************/
331 int acl_addr(const char *aspec, struct access_control_addr *aca)
335 struct addrinfo hints, *result;
337 in_port_t *mask_port;
338 unsigned int addr_len;
341 #endif /* def HAVE_RFC2553 */
343 char *acl_spec = NULL;
346 /* XXX: Depend on ai_family */
354 * Use a temporary acl spec copy so we can log
355 * the unmodified original in case of parse errors.
357 acl_spec = strdup_or_die(aspec);
359 if ((p = strchr(acl_spec, '/')) != NULL)
362 if (privoxy_isdigit(*p) == 0)
367 masklength = atoi(p);
370 if ((masklength < 0) ||
382 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
385 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
394 p = strchr(acl_spec, ':');
404 memset(&hints, 0, sizeof(struct addrinfo));
405 hints.ai_family = AF_UNSPEC;
406 hints.ai_socktype = SOCK_STREAM;
408 i = getaddrinfo(acl_spec, p, &hints, &result);
412 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
413 acl_spec, p, gai_strerror(i));
419 /* TODO: Allow multihomed hostnames */
420 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
421 freeaddrinfo(result);
427 port = strtol(p, &endptr, 10);
429 if (port <= 0 || port > 65535 || *endptr != '\0')
436 aca->port = (unsigned long)port;
438 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
441 if (aca->addr == INADDR_NONE)
443 /* XXX: This will be logged as parse error. */
446 #endif /* def HAVE_RFC2553 */
448 /* build the netmask */
450 /* Clip masklength according to current family. */
451 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
456 aca->mask.ss_family = aca->addr.ss_family;
457 sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port);
461 /* ACL contains a port number, check ports in the future. */
466 * XXX: This could be optimized to operate on whole words instead
467 * of octets (128-bit CPU could do it in one iteration).
470 * Octets after prefix can be omitted because of
471 * previous initialization to zeros.
473 for (i = 0; (i < addr_len) && masklength; i++)
483 * XXX: This assumes MSB of octet is on the left side.
484 * This should be true for all architectures or solved
487 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
494 for (i=1; i <= masklength ; i++)
496 aca->mask |= (1U << (32 - i));
499 /* now mask off the host portion of the ip address
500 * (i.e. save on the network portion of the address).
502 aca->addr = aca->addr & aca->mask;
503 #endif /* def HAVE_RFC2553 */
508 #endif /* def FEATURE_ACL */
511 /*********************************************************************
513 * Function : connect_port_is_forbidden
515 * Description : Check to see if CONNECT requests to the destination
516 * port of this request are forbidden. The check is
517 * independent of the actual request method.
520 * 1 : csp = Current client state (buffers, headers, etc...)
522 * Returns : True if yes, false otherwise.
524 *********************************************************************/
525 int connect_port_is_forbidden(const struct client_state *csp)
527 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
528 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
533 /*********************************************************************
535 * Function : block_url
537 * Description : Called from `chat'. Check to see if we need to block this.
540 * 1 : csp = Current client state (buffers, headers, etc...)
542 * Returns : NULL => unblocked, else HTTP block response
544 *********************************************************************/
545 struct http_response *block_url(struct client_state *csp)
547 struct http_response *rsp;
548 const char *new_content_type = NULL;
551 * If it's not blocked, don't block it ;-)
553 if ((csp->action->flags & ACTION_BLOCK) == 0)
557 if (csp->action->flags & ACTION_REDIRECT)
559 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
562 * Else, prepare a response
564 if (NULL == (rsp = alloc_http_response()))
566 return cgi_error_memory();
569 #ifdef FEATURE_EXTENDED_STATISTICS
570 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
572 increment_block_reason_counter(csp->action->string[ACTION_STRING_BLOCK]);
577 * If it's an image-url, send back an image or redirect
578 * as specified by the relevant +image action
580 #ifdef FEATURE_IMAGE_BLOCKING
581 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
585 /* determine HOW images should be blocked */
586 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
588 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
590 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
593 /* and handle accordingly: */
594 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
596 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
597 rsp->body = bindup(image_pattern_data, image_pattern_length);
598 if (rsp->body == NULL)
600 free_http_response(rsp);
601 return cgi_error_memory();
603 rsp->content_length = image_pattern_length;
605 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
607 free_http_response(rsp);
608 return cgi_error_memory();
611 else if (0 == strcmpic(p, "blank"))
613 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
614 rsp->body = bindup(image_blank_data, image_blank_length);
615 if (rsp->body == NULL)
617 free_http_response(rsp);
618 return cgi_error_memory();
620 rsp->content_length = image_blank_length;
622 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
624 free_http_response(rsp);
625 return cgi_error_memory();
630 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
632 if (enlist_unique_header(rsp->headers, "Location", p))
634 free_http_response(rsp);
635 return cgi_error_memory();
641 #endif /* def FEATURE_IMAGE_BLOCKING */
642 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
645 * Send empty document.
647 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
650 rsp->body = strdup_or_die(" ");
651 rsp->content_length = 1;
653 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
656 * Workaround for firefox bug 492459
657 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
658 * Return a 200 OK status for pages blocked with +handle-as-empty-document
659 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
661 rsp->status = strdup_or_die("200 Request blocked by Privoxy");
665 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
668 if (new_content_type != 0)
670 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
671 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
673 free_http_response(rsp);
674 return cgi_error_memory();
681 * Else, generate an HTML "blocked" message:
685 struct map * exports;
687 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
689 exports = default_exports(csp, NULL);
692 free_http_response(rsp);
693 return cgi_error_memory();
696 #ifdef FEATURE_FORCE_LOAD
697 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
699 * Export the force conditional block killer if
701 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
702 * - Privoxy is configured to enforce blocks, or
703 * - it's a CONNECT request and enforcing wouldn't work anyway.
705 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
706 || (0 == strcmpic(csp->http->gpc, "connect")))
707 #endif /* ndef FEATURE_FORCE_LOAD */
709 err = map_block_killer(exports, "force-support");
712 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
713 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
714 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
715 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
718 const char *block_reason;
719 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
721 block_reason = csp->action->string[ACTION_STRING_BLOCK];
725 assert(connect_port_is_forbidden(csp));
726 block_reason = "Forbidden CONNECT port.";
728 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
733 free_http_response(rsp);
734 return cgi_error_memory();
737 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
740 free_http_response(rsp);
741 return cgi_error_memory();
744 rsp->crunch_reason = BLOCKED;
746 return finish_http_response(csp, rsp);
752 /*********************************************************************
754 * Function : trust_url FIXME: I should be called distrust_url
756 * Description : Calls is_untrusted_url to determine if the URL is trusted
757 * and if not, returns a HTTP 403 response with a reject message.
760 * 1 : csp = Current client state (buffers, headers, etc...)
762 * Returns : NULL => trusted, else http_response.
764 *********************************************************************/
765 struct http_response *trust_url(struct client_state *csp)
767 struct http_response *rsp;
768 struct map * exports;
769 char buf[BUFFER_SIZE];
771 struct pattern_spec **tl;
772 struct pattern_spec *t;
776 * Don't bother to work on trusted URLs
778 if (!is_untrusted_url(csp))
784 * Else, prepare a response:
786 if (NULL == (rsp = alloc_http_response()))
788 return cgi_error_memory();
791 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
792 exports = default_exports(csp, NULL);
795 free_http_response(rsp);
796 return cgi_error_memory();
800 * Export the protocol, host, port, and referrer information
802 err = map(exports, "hostport", 1, csp->http->hostport, 1);
803 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
804 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
806 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
808 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
812 if (!err) err = map(exports, "referrer", 1, "none set", 1);
818 free_http_response(rsp);
819 return cgi_error_memory();
823 * Export the trust list
825 p = strdup_or_die("");
826 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
828 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
829 string_append(&p, buf);
831 err = map(exports, "trusted-referrers", 1, p, 0);
836 free_http_response(rsp);
837 return cgi_error_memory();
841 * Export the trust info, if available
843 if (csp->config->trust_info->first)
845 struct list_entry *l;
847 p = strdup_or_die("");
848 for (l = csp->config->trust_info->first; l ; l = l->next)
850 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
851 string_append(&p, buf);
853 err = map(exports, "trust-info", 1, p, 0);
857 err = map_block_killer(exports, "have-trust-info");
863 free_http_response(rsp);
864 return cgi_error_memory();
868 * Export the force conditional block killer if
870 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
871 * - Privoxy is configured to enforce blocks, or
872 * - it's a CONNECT request and enforcing wouldn't work anyway.
874 #ifdef FEATURE_FORCE_LOAD
875 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
876 || (0 == strcmpic(csp->http->gpc, "connect")))
878 err = map_block_killer(exports, "force-support");
882 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
884 #else /* ifndef FEATURE_FORCE_LOAD */
885 err = map_block_killer(exports, "force-support");
886 #endif /* ndef FEATURE_FORCE_LOAD */
891 free_http_response(rsp);
892 return cgi_error_memory();
898 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
901 free_http_response(rsp);
902 return cgi_error_memory();
904 rsp->crunch_reason = UNTRUSTED;
906 return finish_http_response(csp, rsp);
908 #endif /* def FEATURE_TRUST */
911 /*********************************************************************
913 * Function : compile_dynamic_pcrs_job_list
915 * Description : Compiles a dynamic pcrs job list (one with variables
916 * resolved at request time)
919 * 1 : csp = Current client state (buffers, headers, etc...)
920 * 2 : b = The filter list to compile
922 * Returns : NULL in case of errors, otherwise the
925 *********************************************************************/
926 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
928 struct list_entry *pattern;
929 pcrs_job *job_list = NULL;
930 pcrs_job *dummy = NULL;
931 pcrs_job *lastjob = NULL;
934 const struct pcrs_variable variables[] =
936 {"url", csp->http->url, 1},
937 {"path", csp->http->path, 1},
938 {"host", csp->http->host, 1},
939 {"origin", csp->ip_addr_str, 1},
940 {"listen-address", csp->listen_addr_str, 1},
944 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
946 assert(pattern->str != NULL);
948 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
951 log_error(LOG_LEVEL_ERROR,
952 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
953 pattern->str, b->name, error, pcrs_strerror(error));
958 if (error == PCRS_WARN_TRUNCATION)
960 log_error(LOG_LEVEL_ERROR,
961 "At least one of the variables in \'%s\' had to "
962 "be truncated before compilation", pattern->str);
964 if (job_list == NULL)
970 lastjob->next = dummy;
980 /*********************************************************************
982 * Function : rewrite_url
984 * Description : Rewrites a URL with a single pcrs command
985 * and returns the result if it differs from the
986 * original and isn't obviously invalid.
989 * 1 : old_url = URL to rewrite.
990 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
993 * Returns : NULL if the pcrs_command didn't change the url, or
994 * the result of the modification.
996 *********************************************************************/
997 char *rewrite_url(char *old_url, const char *pcrs_command)
999 char *new_url = NULL;
1003 assert(pcrs_command);
1005 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1009 log_error(LOG_LEVEL_REDIRECTS,
1010 "pcrs command \"%s\" didn't change \"%s\".",
1011 pcrs_command, old_url);
1016 log_error(LOG_LEVEL_REDIRECTS,
1017 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1018 pcrs_command, old_url, pcrs_strerror(hits));
1021 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1023 log_error(LOG_LEVEL_ERROR,
1024 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1025 "but the result doesn't look like a valid URL and will be ignored.",
1026 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1031 log_error(LOG_LEVEL_REDIRECTS,
1032 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1033 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1041 #ifdef FEATURE_FAST_REDIRECTS
1042 /*********************************************************************
1044 * Function : get_last_url
1046 * Description : Search for the last URL inside a string.
1047 * If the string already is a URL, it will
1048 * be the first URL found.
1051 * 1 : subject = the string to check
1052 * 2 : redirect_mode = +fast-redirect{} mode
1054 * Returns : NULL if no URL was found, or
1055 * the last URL found.
1057 *********************************************************************/
1058 static char *get_last_url(char *subject, const char *redirect_mode)
1060 char *new_url = NULL;
1064 assert(redirect_mode);
1066 subject = strdup(subject);
1067 if (subject == NULL)
1069 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1073 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1075 char *url_segment = NULL;
1076 char **url_segments;
1077 size_t max_segments;
1080 log_error(LOG_LEVEL_REDIRECTS,
1081 "Checking \"%s\" for encoded redirects.", subject);
1084 * Check each parameter in the URL separately.
1085 * Sectionize the URL at "?" and "&",
1086 * go backwards through the segments, URL-decode them
1087 * and look for a URL in the decoded result.
1088 * Stop the search after the first match.
1090 * XXX: This estimate is guaranteed to be high enough as we
1091 * let ssplit() ignore empty fields, but also a bit wasteful.
1093 max_segments = strlen(subject) / 2;
1094 url_segments = malloc(max_segments * sizeof(char *));
1096 if (NULL == url_segments)
1098 log_error(LOG_LEVEL_ERROR,
1099 "Out of memory while decoding URL: %s", subject);
1104 segments = ssplit(subject, "?&", url_segments, max_segments);
1106 while (segments-- > 0)
1108 char *dtoken = url_decode(url_segments[segments]);
1111 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1114 url_segment = strstr(dtoken, "http://");
1115 if (NULL == url_segment)
1117 url_segment = strstr(dtoken, "https://");
1119 if (NULL != url_segment)
1121 url_segment = strdup_or_die(url_segment);
1128 freez(url_segments);
1130 if (url_segment == NULL)
1134 subject = url_segment;
1138 /* Look for a URL inside this one, without decoding anything. */
1139 log_error(LOG_LEVEL_REDIRECTS,
1140 "Checking \"%s\" for unencoded redirects.", subject);
1144 * Find the last URL encoded in the request
1147 while ((tmp = strstr(tmp, "http://")) != NULL)
1151 tmp = (new_url != NULL) ? new_url : subject;
1152 while ((tmp = strstr(tmp, "https://")) != NULL)
1157 if ((new_url != NULL)
1158 && ( (new_url != subject)
1159 || (0 == strncmpic(subject, "http://", 7))
1160 || (0 == strncmpic(subject, "https://", 8))
1164 * Return new URL if we found a redirect
1165 * or if the subject already was a URL.
1167 * The second case makes sure that we can
1168 * chain get_last_url after another redirection check
1169 * (like rewrite_url) without losing earlier redirects.
1171 new_url = strdup(new_url);
1180 #endif /* def FEATURE_FAST_REDIRECTS */
1183 /*********************************************************************
1185 * Function : redirect_url
1187 * Description : Checks if Privoxy should answer the request with
1188 * a HTTP redirect and generates the redirect if
1192 * 1 : csp = Current client state (buffers, headers, etc...)
1194 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1196 *********************************************************************/
1197 struct http_response *redirect_url(struct client_state *csp)
1199 struct http_response *rsp;
1200 #ifdef FEATURE_FAST_REDIRECTS
1202 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1203 * as compile-time option? The user can easily disable
1204 * it in his action file.
1206 char * redirect_mode;
1207 #endif /* def FEATURE_FAST_REDIRECTS */
1208 char *new_url = NULL;
1209 char *redirection_string;
1211 if ((csp->action->flags & ACTION_REDIRECT))
1213 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1216 * If the redirection string begins with 's',
1217 * assume it's a pcrs command, otherwise treat it as
1218 * properly formatted URL and use it for the redirection
1221 * According to (the now obsolete) RFC 2616 section 14.30
1222 * the URL has to be absolute and if the user tries:
1223 * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
1224 * she would get undefined results anyway.
1226 * RFC 7231 7.1.2 actually allows relative references,
1227 * but those start with a leading slash (RFC 3986 4.2) and
1228 * thus can't be mistaken for pcrs commands either.
1231 if (*redirection_string == 's')
1233 char *requested_url;
1235 #ifdef FEATURE_HTTPS_INSPECTION
1236 if (client_use_ssl(csp))
1240 requested_url = strdup_or_die("https://");
1241 err = string_append(&requested_url, csp->http->hostport);
1242 if (!err) err = string_append(&requested_url, csp->http->path);
1245 log_error(LOG_LEVEL_FATAL,
1246 "Failed to rebuild URL 'https://%s%s'",
1247 csp->http->hostport, csp->http->path);
1253 requested_url = csp->http->url;
1255 new_url = rewrite_url(requested_url, redirection_string);
1256 #ifdef FEATURE_HTTPS_INSPECTION
1257 if (requested_url != csp->http->url)
1259 assert(client_use_ssl(csp));
1260 freez(requested_url);
1266 log_error(LOG_LEVEL_REDIRECTS,
1267 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1268 redirection_string);
1269 new_url = strdup(redirection_string);
1273 #ifdef FEATURE_FAST_REDIRECTS
1274 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1278 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1281 * If it exists, use the previously rewritten URL as input
1282 * otherwise just use the old path.
1284 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1285 new_url = get_last_url(old_url, redirect_mode);
1288 #endif /* def FEATURE_FAST_REDIRECTS */
1290 /* Did any redirect action trigger? */
1293 if (url_requires_percent_encoding(new_url))
1296 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1297 strlen(new_url), new_url);
1298 encoded_url = percent_encode_url(new_url);
1300 if (encoded_url == NULL)
1302 return cgi_error_memory();
1304 new_url = encoded_url;
1305 assert(FALSE == url_requires_percent_encoding(new_url));
1308 if (0 == strcmpic(new_url, csp->http->url))
1310 log_error(LOG_LEVEL_ERROR,
1311 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1312 csp->http->url, new_url);
1317 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1319 if (NULL == (rsp = alloc_http_response()))
1322 return cgi_error_memory();
1325 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
1326 if (enlist_unique_header(rsp->headers, "Location", new_url))
1329 free_http_response(rsp);
1330 return cgi_error_memory();
1332 rsp->crunch_reason = REDIRECTED;
1335 return finish_http_response(csp, rsp);
1339 /* Only reached if no redirect is required */
1345 #ifdef FEATURE_IMAGE_BLOCKING
1346 /*********************************************************************
1348 * Function : is_imageurl
1350 * Description : Given a URL, decide whether it should be treated
1351 * as image URL or not.
1354 * 1 : csp = Current client state (buffers, headers, etc...)
1356 * Returns : True (nonzero) if URL is an image URL, false (0)
1359 *********************************************************************/
1360 int is_imageurl(const struct client_state *csp)
1362 return ((csp->action->flags & ACTION_IMAGE) != 0);
1365 #endif /* def FEATURE_IMAGE_BLOCKING */
1368 #ifdef FEATURE_TRUST
1369 /*********************************************************************
1371 * Function : is_untrusted_url
1373 * Description : Should we "distrust" this URL (and block it)?
1375 * Yes if it matches a line in the trustfile, or if the
1376 * referrer matches a line starting with "+" in the
1381 * 1 : csp = Current client state (buffers, headers, etc...)
1383 * Returns : 0 => trusted, 1 => untrusted
1385 *********************************************************************/
1386 int is_untrusted_url(const struct client_state *csp)
1388 struct file_list *fl;
1389 struct block_spec *b;
1390 struct pattern_spec **trusted_url;
1391 struct http_request rhttp[1];
1392 const char * referer;
1396 * If we don't have a trustlist, we trust everybody
1398 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1403 memset(rhttp, '\0', sizeof(*rhttp));
1406 * Do we trust the request URL itself?
1408 for (b = b->next; b ; b = b->next)
1410 if (url_match(b->url, csp->http))
1416 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1418 /* no referrer was supplied */
1424 * If not, do we maybe trust its referrer?
1426 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1432 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1434 if (url_match(*trusted_url, rhttp))
1436 /* if the URL's referrer is from a trusted referrer, then
1437 * add the target spec to the trustfile as an unblocked
1438 * domain and return 0 (which means it's OK).
1443 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1447 char * new_entry = strdup_or_die("~");
1449 string_append(&new_entry, csp->http->hostport);
1451 path = csp->http->path;
1452 if ( (path[0] == '/')
1454 && ((path_end = strchr(path + 2, '/')) != NULL))
1456 /* since this path points into a user's home space
1457 * be sure to include this spec in the trustfile.
1459 long path_len = path_end - path; /* save offset */
1460 path = strdup(path); /* Copy string */
1463 path_end = path + path_len; /* regenerate ptr to new buffer */
1464 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1466 string_join(&new_entry, path);
1470 * Give a reason for generating this entry.
1472 string_append(&new_entry, " # Trusted referrer was: ");
1473 string_append(&new_entry, referer);
1475 if (new_entry != NULL)
1477 if (-1 == fprintf(fp, "%s\n", new_entry))
1479 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1480 new_entry, csp->config->trustfile);
1486 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1487 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1494 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1495 csp->http->hostport, csp->config->trustfile);
1503 #endif /* def FEATURE_TRUST */
1506 /*********************************************************************
1508 * Function : get_filter
1510 * Description : Get a filter with a given name and type.
1511 * Note that taggers are filters, too.
1514 * 1 : csp = Current client state (buffers, headers, etc...)
1515 * 2 : requested_name = Name of the content filter to get
1516 * 3 : requested_type = Type of the filter to tagger to lookup
1518 * Returns : A pointer to the requested filter
1519 * or NULL if the filter wasn't found
1521 *********************************************************************/
1522 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1523 const char *requested_name,
1524 enum filter_type requested_type)
1527 struct re_filterfile_spec *b;
1528 struct file_list *fl;
1530 for (i = 0; i < MAX_AF_FILES; i++)
1533 if ((NULL == fl) || (NULL == fl->f))
1536 * Either there are no filter files left or this
1537 * filter file just contains no valid filters.
1539 * Continue to be sure we don't miss valid filter
1540 * files that are chained after empty or invalid ones.
1545 for (b = fl->f; b != NULL; b = b->next)
1547 if (b->type != requested_type)
1549 /* The callers isn't interested in this filter type. */
1552 if (strcmp(b->name, requested_name) == 0)
1554 /* The requested filter has been found. Abort search. */
1560 /* No filter with the given name and type exists. */
1566 /*********************************************************************
1568 * Function : pcrs_filter_impl
1570 * Description : Execute all text substitutions from all applying
1571 * (based on filter_response_body value) +filter
1572 * or +client_body_filter actions on the given buffer.
1575 * 1 : csp = Current client state (buffers, headers, etc...)
1576 * 2 : filter_response_body = when TRUE execute +filter
1577 * actions; execute +client_body_filter actions otherwise
1578 * 3 : data = Target data
1579 * 4 : data_len = Target data len
1581 * Returns : a pointer to the (newly allocated) modified buffer.
1582 * or NULL if there were no hits or something went wrong
1584 *********************************************************************/
1585 static char *pcrs_filter_impl(const struct client_state *csp, int filter_response_body,
1586 const char *data, size_t *data_len)
1589 size_t size, prev_size;
1590 const int filters_idx =
1591 filter_response_body ? ACTION_MULTI_FILTER : ACTION_MULTI_CLIENT_BODY_FILTER;
1592 const enum filter_type filter_type =
1593 filter_response_body ? FT_CONTENT_FILTER : FT_CLIENT_BODY_FILTER;
1595 const char *old = NULL;
1599 struct re_filterfile_spec *b;
1600 struct list_entry *filtername;
1610 if (filters_available(csp) == FALSE)
1612 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1613 "content filtering enabled, but no content filters available.");
1621 * For all applying actions, look if a filter by that
1622 * name exists and if yes, execute it's pcrs_joblist on the
1625 for (filtername = csp->action->multi[filters_idx]->first;
1626 filtername != NULL; filtername = filtername->next)
1628 int current_hits = 0; /* Number of hits caused by this filter */
1629 int job_number = 0; /* Which job we're currently executing */
1630 int job_hits = 0; /* How many hits the current job caused */
1633 b = get_filter(csp, filtername->str, filter_type);
1639 joblist = b->joblist;
1641 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1643 if (NULL == joblist)
1645 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1650 /* Apply all jobs from the joblist */
1651 for (job = joblist; NULL != job; job = job->next)
1654 job_hits = pcrs_execute(job, old, size, &new, &size);
1659 * That went well. Continue filtering
1660 * and use the result of this job as
1661 * input for the next one.
1663 current_hits += job_hits;
1673 * This job caused an unexpected error. Inform the user
1674 * and skip the rest of the jobs in this filter. We could
1675 * continue with the next job, but usually the jobs
1676 * depend on each other or are similar enough to
1677 * fail for the same reason.
1679 * At the moment our pcrs expects the error codes of pcre 3.4,
1680 * but newer pcre versions can return additional error codes.
1681 * As a result pcrs_strerror()'s error message might be
1682 * "Unknown error ...", therefore we print the numerical value
1685 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1686 * should we use LOG_LEVEL_RE_FILTER instead?
1688 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1689 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1694 if (b->dynamic) pcrs_free_joblist(joblist);
1696 if (filter_response_body)
1698 log_error(LOG_LEVEL_RE_FILTER,
1699 "filtering %s%s (size %lu) with \'%s\' produced %d hits (new size %lu).",
1700 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1704 log_error(LOG_LEVEL_RE_FILTER, "filtering request body from client %s "
1705 "(size %lu) with \'%s\' produced %d hits (new size %lu).",
1706 csp->ip_addr_str, prev_size, b->name, current_hits, size);
1708 #ifdef FEATURE_EXTENDED_STATISTICS
1709 update_filter_statistics(b->name, current_hits);
1711 hits += current_hits;
1715 * If there were no hits, destroy our copy and let
1716 * chat() use the original content
1720 if (old != data && old != new)
1733 /*********************************************************************
1735 * Function : pcrs_filter_response_body
1737 * Description : Execute all text substitutions from all applying
1738 * +filter actions on the text buffer that's been
1739 * accumulated in csp->iob->buf.
1742 * 1 : csp = Current client state (buffers, headers, etc...)
1744 * Returns : a pointer to the (newly allocated) modified buffer.
1745 * or NULL if there were no hits or something went wrong
1747 *********************************************************************/
1748 static char *pcrs_filter_response_body(struct client_state *csp)
1750 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1757 if (csp->iob->cur >= csp->iob->eod)
1762 new = pcrs_filter_impl(csp, TRUE, csp->iob->cur, &size);
1766 csp->flags |= CSP_FLAG_MODIFIED;
1767 csp->content_length = size;
1768 clear_iob(csp->iob);
1775 #ifdef FEATURE_EXTERNAL_FILTERS
1776 /*********************************************************************
1778 * Function : get_external_filter
1780 * Description : Lookup the code to execute for an external filter.
1781 * Masks the misuse of the re_filterfile_spec.
1784 * 1 : csp = Current client state (buffers, headers, etc...)
1785 * 2 : name = Name of the content filter to get
1787 * Returns : A pointer to the requested code
1788 * or NULL if the filter wasn't found
1790 *********************************************************************/
1791 static const char *get_external_filter(const struct client_state *csp,
1794 struct re_filterfile_spec *external_filter;
1796 external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
1797 if (external_filter == NULL)
1799 log_error(LOG_LEVEL_FATAL,
1800 "Didn't find stuff to execute for external filter: %s",
1804 return external_filter->patterns->first->str;
1809 /*********************************************************************
1811 * Function : set_privoxy_variables
1813 * Description : Sets a couple of privoxy-specific environment variables
1816 * 1 : csp = Current client state (buffers, headers, etc...)
1820 *********************************************************************/
1821 static void set_privoxy_variables(const struct client_state *csp)
1828 { "PRIVOXY_URL", csp->http->url },
1829 { "PRIVOXY_PATH", csp->http->path },
1830 { "PRIVOXY_HOST", csp->http->host },
1831 { "PRIVOXY_ORIGIN", csp->ip_addr_str },
1832 { "PRIVOXY_LISTEN_ADDRESS", csp->listen_addr_str },
1835 for (i = 0; i < SZ(env); i++)
1837 if (setenv(env[i].name, env[i].value, 1))
1839 log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
1840 env[i].name, env[i].value);
1846 /*********************************************************************
1848 * Function : execute_external_filter
1850 * Description : Pipe content into external filter and return the output
1853 * 1 : csp = Current client state (buffers, headers, etc...)
1854 * 2 : name = Name of the external filter to execute
1855 * 3 : content = The original content to filter
1856 * 4 : size = The size of the content buffer
1858 * Returns : a pointer to the (newly allocated) modified buffer.
1859 * or NULL if there were no hits or something went wrong
1861 *********************************************************************/
1862 static char *execute_external_filter(const struct client_state *csp,
1863 const char *name, char *content, size_t *size)
1866 char file_name[FILENAME_MAX];
1868 char *filter_output;
1872 const char *external_filter;
1874 if (csp->config->temporary_directory == NULL)
1876 log_error(LOG_LEVEL_ERROR,
1877 "No temporary-directory configured. Can't execute filter: %s",
1882 external_filter = get_external_filter(csp, name);
1884 if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
1885 "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
1887 log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
1891 fd = mkstemp(file_name);
1894 log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
1898 fp = fdopen(fd, "w");
1901 log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
1907 * The size may be zero if a previous filter discarded everything.
1909 * This isn't necessary unintentional, so we just don't try
1910 * to fwrite() nothing and let the user deal with the rest.
1912 if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
1914 log_error(LOG_LEVEL_ERROR, "fwrite(..., %lu, 1, ..) failed: %E", *size);
1921 if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
1923 log_error(LOG_LEVEL_ERROR,
1924 "temporary-directory or external filter path too long");
1929 log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
1932 * The locking is necessary to prevent other threads
1933 * from overwriting the environment variables before
1934 * the popen fork. Afterwards this no longer matters.
1936 privoxy_mutex_lock(&external_filter_mutex);
1937 set_privoxy_variables(csp);
1938 fp = popen(cmd, "r");
1939 privoxy_mutex_unlock(&external_filter_mutex);
1942 log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
1947 /* Allocate at least one byte */
1948 filter_output = malloc_or_die(*size + 1);
1951 while (!feof(fp) && !ferror(fp))
1954 /* Could be bigger ... */
1955 enum { READ_LENGTH = 2048 };
1957 if (new_size + READ_LENGTH >= *size)
1961 /* Could be considered wasteful if the content is 'large'. */
1962 *size += (*size >= READ_LENGTH) ? *size : READ_LENGTH;
1964 p = realloc(filter_output, *size);
1967 log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
1968 "external filter output. Using what we got so far.");
1973 assert(new_size + READ_LENGTH < *size);
1974 len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
1984 log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
1988 log_error(LOG_LEVEL_RE_FILTER,
1989 "Executing '%s' resulted in return value %d. "
1990 "Read %lu of up to %lu bytes.", name, (ret >> 8), new_size, *size);
1996 return filter_output;
1999 #endif /* def FEATURE_EXTERNAL_FILTERS */
2002 /*********************************************************************
2004 * Function : pcrs_filter_request_body
2006 * Description : Execute all text substitutions from all applying
2007 * +client_body_filter actions on the given text buffer.
2010 * 1 : csp = Current client state (buffers, headers, etc...)
2011 * 2 : data = Target data
2012 * 3 : data_len = Target data len
2014 * Returns : a pointer to the (newly allocated) modified buffer.
2015 * or NULL if there were no hits or something went wrong
2017 *********************************************************************/
2018 static char *pcrs_filter_request_body(const struct client_state *csp, const char *data, size_t *data_len)
2020 return pcrs_filter_impl(csp, FALSE, data, data_len);
2024 /*********************************************************************
2026 * Function : gif_deanimate_response
2028 * Description : Deanimate the GIF image that has been accumulated in
2029 * csp->iob->buf, set csp->content_length to the modified
2030 * size and raise the CSP_FLAG_MODIFIED flag.
2033 * 1 : csp = Current client state (buffers, headers, etc...)
2035 * Returns : a pointer to the (newly allocated) modified buffer.
2036 * or NULL in case something went wrong.
2038 *********************************************************************/
2040 char *gif_deanimate_response(struct client_state *csp)
2042 static char *gif_deanimate_response(struct client_state *csp)
2045 struct binbuffer *in, *out;
2049 size = (size_t)(csp->iob->eod - csp->iob->cur);
2051 in = zalloc_or_die(sizeof(*in));
2052 out = zalloc_or_die(sizeof(*out));
2054 in->buffer = csp->iob->cur;
2057 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
2059 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
2066 if ((int)size == out->offset)
2068 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
2072 log_error(LOG_LEVEL_DEANIMATE,
2073 "Success! GIF shrunk from %lu bytes to %lu.", size, out->offset);
2075 csp->content_length = out->offset;
2076 csp->flags |= CSP_FLAG_MODIFIED;
2086 /*********************************************************************
2088 * Function : get_filter_function
2090 * Description : Decides which content filter function has
2091 * to be applied (if any). Only considers functions
2092 * for internal filters which are mutually-exclusive.
2095 * 1 : csp = Current client state (buffers, headers, etc...)
2097 * Returns : The content filter function to run, or
2098 * NULL if no content filter is active
2100 *********************************************************************/
2101 static filter_function_ptr get_filter_function(const struct client_state *csp)
2103 filter_function_ptr filter_function = NULL;
2106 * Choose the applying filter function based on
2107 * the content type and action settings.
2109 if ((csp->content_type & CT_TEXT) &&
2110 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2112 filter_function = pcrs_filter_response_body;
2114 else if ((csp->content_type & CT_GIF) &&
2115 (csp->action->flags & ACTION_DEANIMATE))
2117 filter_function = gif_deanimate_response;
2120 return filter_function;
2124 /*********************************************************************
2126 * Function : get_bytes_to_next_chunk_start
2128 * Description : Returns the number of bytes to the start of the
2129 * next chunk in the buffer.
2132 * 1 : buffer = Pointer to the text buffer
2133 * 2 : size = Number of bytes in the buffer.
2134 * 3 : offset = Where to expect the beginning of the next chunk.
2136 * Returns : -1 if the size can't be determined or data is missing,
2137 * otherwise the number of bytes to the start of the next chunk
2138 * or 0 if the last chunk has been fully buffered.
2140 *********************************************************************/
2141 static int get_bytes_to_next_chunk_start(char *buffer, size_t size, size_t offset)
2145 unsigned int chunk_size = 0;
2148 if (size <= offset || size < 5)
2151 * Not enough bytes bufferd to figure
2152 * out the size of the next chunk.
2157 chunk_start = buffer + offset;
2159 p = strstr(chunk_start, "\r\n");
2163 * The line with the chunk-size hasn't been completely received
2164 * yet (or is invalid).
2166 log_error(LOG_LEVEL_RE_FILTER,
2167 "Not enough or invalid data in buffer in chunk size line.");
2171 if (sscanf(chunk_start, "%x", &chunk_size) != 1)
2173 /* XXX: Write test case to trigger this. */
2174 log_error(LOG_LEVEL_ERROR, "Failed to parse chunk size. "
2175 "Size: %lu, offset: %lu. Chunk size start: %N", size, offset,
2176 (size - offset), chunk_start);
2181 * To get to the start of the next chunk size we have to skip
2182 * the line with the current chunk size followed by "\r\n" followd
2183 * by the actual data and another "\r\n" following the data.
2185 bytes_to_skip = (int)(p - chunk_start) + 2 + (int)chunk_size + 2;
2187 if (bytes_to_skip <= 0)
2189 log_error(LOG_LEVEL_ERROR,
2190 "Failed to figure out chunk offset. %u and %d seem dubious.",
2191 chunk_size, bytes_to_skip);
2194 if (chunk_size == 0)
2196 if (bytes_to_skip <= (size - offset))
2202 log_error(LOG_LEVEL_INFO,
2203 "Last chunk detected but we're still missing data.");
2208 return bytes_to_skip;
2212 /*********************************************************************
2214 * Function : get_bytes_missing_from_chunked_data
2216 * Description : Figures out how many bytes of data we need to get
2217 * to the start of the next chunk of data (XXX: terminology).
2218 * Due to the nature of chunk-encoded data we can only see
2219 * how many data is missing according to the last chunk size
2223 * 1 : buffer = Pointer to the text buffer
2224 * 2 : size = Number of bytes in the buffer.
2225 * 3 : offset = Where to expect the beginning of the next chunk.
2227 * Returns : -1 if the data can't be parsed (yet),
2228 * 0 if the buffer is complete or a
2229 * number of bytes that is missing.
2231 *********************************************************************/
2232 int get_bytes_missing_from_chunked_data(char *buffer, size_t size, size_t offset)
2235 int last_valid_offset = -1;
2237 if (size < offset || size < 5)
2239 /* Not enough data buffered yet */
2245 ret = get_bytes_to_next_chunk_start(buffer, size, offset);
2248 return last_valid_offset;
2256 last_valid_offset = (int)offset;
2258 offset += (size_t)ret;
2259 } while (offset < size);
2266 /*********************************************************************
2268 * Function : chunked_data_is_complete
2270 * Description : Detects if a buffer with chunk-encoded data looks
2274 * 1 : buffer = Pointer to the text buffer
2275 * 2 : size = Number of bytes in the buffer.
2276 * 3 : offset = Where to expect the beginning of the
2277 * first complete chunk.
2279 * Returns : TRUE if it looks like the data is complete,
2282 *********************************************************************/
2283 int chunked_data_is_complete(char *buffer, size_t size, size_t offset)
2285 return (0 == get_bytes_missing_from_chunked_data(buffer, size, offset));
2290 /*********************************************************************
2292 * Function : remove_chunked_transfer_coding
2294 * Description : In-situ remove the "chunked" transfer coding as defined
2295 * in RFC 7230 4.1 from a buffer. XXX: The implementation
2296 * is neither complete nor compliant (TODO #129).
2299 * 1 : buffer = Pointer to the text buffer
2300 * 2 : size = In: Number of bytes to be processed,
2301 * Out: Number of bytes after de-chunking.
2302 * (undefined in case of errors)
2304 * Returns : JB_ERR_OK for success,
2305 * JB_ERR_PARSE otherwise
2307 *********************************************************************/
2309 extern jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2311 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2315 unsigned int chunksize = 0;
2316 char *from_p, *to_p;
2317 const char *end_of_buffer = buffer + *size;
2321 log_error(LOG_LEVEL_FATAL, "Invalid chunked input. Buffer is empty.");
2322 return JB_ERR_PARSE;
2326 from_p = to_p = buffer;
2330 * Refuse to de-chunk invalid or incomplete data unless we're fuzzing.
2332 if (!chunked_data_is_complete(buffer, *size, 0))
2334 log_error(LOG_LEVEL_ERROR,
2335 "Chunk-encoding appears to be invalid. Content can't be filtered.");
2336 return JB_ERR_PARSE;
2340 if (sscanf(buffer, "%x", &chunksize) != 1)
2342 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2343 return JB_ERR_PARSE;
2346 while (chunksize > 0U)
2349 * If the chunk-size is valid, we should have at least
2350 * chunk-size bytes of chunk-data and five bytes of
2351 * meta data (chunk-size, CRLF, CRLF) left in the buffer.
2353 if (chunksize + 5 >= *size - newsize)
2355 log_error(LOG_LEVEL_ERROR,
2356 "Chunk size %u exceeds buffered data left. "
2357 "Already digested %lu of %lu buffered bytes.",
2358 chunksize, newsize, *size);
2359 return JB_ERR_PARSE;
2363 * Skip the chunk-size, the optional chunk-ext and the CRLF
2364 * that is supposed to be located directly before the start
2367 if (NULL == (from_p = strstr(from_p, "\r\n")))
2369 log_error(LOG_LEVEL_ERROR,
2370 "Failed to strip \"chunked\" transfer coding. "
2371 "Line with chunk size doesn't seem to end properly.");
2372 return JB_ERR_PARSE;
2377 * The previous strstr() does not enforce chunk-validity
2378 * and is sattisfied as long a CRLF is left in the buffer.
2380 * Make sure the bytes we consider chunk-data are within
2383 if (from_p + chunksize >= end_of_buffer)
2385 log_error(LOG_LEVEL_ERROR,
2386 "Failed to decode content for filtering. "
2387 "One chunk end is beyond the end of the buffer.");
2388 return JB_ERR_PARSE;
2391 memmove(to_p, from_p, (size_t) chunksize);
2392 newsize += chunksize;
2393 to_p = buffer + newsize;
2394 from_p += chunksize;
2397 * Not merging this check with the previous one allows us
2398 * to keep chunks without trailing CRLF. It's not clear
2399 * if we actually have to care about those, though.
2401 if (from_p + 2 >= end_of_buffer)
2403 log_error(LOG_LEVEL_ERROR, "Not enough room for trailing CRLF.");
2404 return JB_ERR_PARSE;
2407 if (sscanf(from_p, "%x", &chunksize) != 1)
2409 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2414 /* XXX: Should get its own loglevel. */
2415 log_error(LOG_LEVEL_RE_FILTER,
2416 "De-chunking successful. Shrunk from %lu to %lu", *size, newsize);
2425 /*********************************************************************
2427 * Function : prepare_for_filtering
2429 * Description : If necessary, de-chunks and decompresses
2430 * the content so it can get filterd.
2433 * 1 : csp = Current client state (buffers, headers, etc...)
2435 * Returns : JB_ERR_OK for success,
2436 * JB_ERR_PARSE otherwise
2438 *********************************************************************/
2439 static jb_err prepare_for_filtering(struct client_state *csp)
2441 jb_err err = JB_ERR_OK;
2444 * If the body has a "chunked" transfer-encoding,
2445 * get rid of it, adjusting size and iob->eod
2447 if (csp->flags & CSP_FLAG_CHUNKED)
2449 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2451 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2452 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2453 if (JB_ERR_OK == err)
2455 csp->iob->eod = csp->iob->cur + size;
2456 csp->flags |= CSP_FLAG_MODIFIED;
2460 return JB_ERR_PARSE;
2466 * If the body has a supported transfer-encoding,
2467 * decompress it, adjusting size and iob->eod.
2469 if ((csp->content_type & (CT_GZIP|CT_DEFLATE))
2470 #ifdef FEATURE_BROTLI
2471 || (csp->content_type & CT_BROTLI)
2475 if (0 == csp->iob->eod - csp->iob->cur)
2477 /* Nothing left after de-chunking. */
2481 err = decompress_iob(csp);
2483 if (JB_ERR_OK == err)
2485 csp->flags |= CSP_FLAG_MODIFIED;
2486 csp->content_type &= ~CT_TABOO;
2491 * Unset content types to remember not to
2492 * modify the Content-Encoding header later.
2494 csp->content_type &= ~CT_GZIP;
2495 csp->content_type &= ~CT_DEFLATE;
2496 #ifdef FEATURE_BROTLI
2497 csp->content_type &= ~CT_BROTLI;
2507 /*********************************************************************
2509 * Function : execute_content_filters
2511 * Description : Executes a given content filter.
2514 * 1 : csp = Current client state (buffers, headers, etc...)
2516 * Returns : Pointer to the modified buffer, or
2517 * NULL if filtering failed or wasn't necessary.
2519 *********************************************************************/
2520 char *execute_content_filters(struct client_state *csp)
2523 filter_function_ptr content_filter;
2525 assert(content_filters_enabled(csp->action));
2527 if (0 == csp->iob->eod - csp->iob->cur)
2530 * No content (probably status code 301, 302 ...),
2531 * no filtering necessary.
2536 if (JB_ERR_OK != prepare_for_filtering(csp))
2539 * We failed to de-chunk or decompress, don't accept
2540 * another request on the client connection.
2542 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2546 if (0 == csp->iob->eod - csp->iob->cur)
2549 * Clown alarm: chunked and/or compressed nothing delivered.
2554 content_filter = get_filter_function(csp);
2555 content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
2557 #ifdef FEATURE_EXTERNAL_FILTERS
2558 if ((csp->content_type & CT_TEXT) &&
2559 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
2561 struct list_entry *filtername;
2562 size_t size = (size_t)csp->content_length;
2564 if (content == NULL)
2566 content = csp->iob->cur;
2567 size = (size_t)(csp->iob->eod - csp->iob->cur);
2570 for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
2571 filtername ; filtername = filtername->next)
2573 char *result = execute_external_filter(csp, filtername->str, content, &size);
2576 if (content != csp->iob->cur)
2583 csp->flags |= CSP_FLAG_MODIFIED;
2584 csp->content_length = size;
2586 #endif /* def FEATURE_EXTERNAL_FILTERS */
2593 /*********************************************************************
2595 * Function : execute_client_body_filters
2597 * Description : Executes client body filters for the request that is buffered
2598 * in the client_iob. The client_iob is updated with the filtered
2602 * 1 : csp = Current client state (buffers, headers, etc...)
2603 * 2 : content_length = content length. Upon successful filtering
2604 * the passed value is updated with the new content length.
2606 * Returns : 1 if the content has been filterd. 0 if it hasn't.
2608 *********************************************************************/
2609 int execute_client_body_filters(struct client_state *csp, size_t *content_length)
2611 char *filtered_content;
2613 assert(client_body_filters_enabled(csp->action));
2615 if (content_length == 0)
2618 * No content, no filtering necessary.
2623 filtered_content = pcrs_filter_request_body(csp, csp->client_iob->cur, content_length);
2624 if (filtered_content != NULL)
2626 freez(csp->client_iob->buf);
2627 csp->client_iob->buf = filtered_content;
2628 csp->client_iob->cur = csp->client_iob->buf;
2629 csp->client_iob->eod = csp->client_iob->cur + *content_length;
2630 csp->client_iob->size = *content_length;
2639 /*********************************************************************
2641 * Function : execute_client_body_taggers
2643 * Description : Executes client body taggers for the request that is
2644 * buffered in the client_iob.
2645 * XXX: Lots of code shared with header_tagger
2648 * 1 : csp = Current client state (buffers, headers, etc...)
2649 * 2 : content_length = content length.
2653 *********************************************************************/
2654 jb_err execute_client_body_taggers(struct client_state *csp, size_t content_length)
2656 enum filter_type wanted_filter_type = FT_CLIENT_BODY_TAGGER;
2657 int multi_action_index = ACTION_MULTI_CLIENT_BODY_TAGGER;
2660 struct re_filterfile_spec *b;
2661 struct list_entry *tag_name;
2663 assert(client_body_taggers_enabled(csp->action));
2665 if (content_length == 0)
2668 * No content, no tagging necessary.
2673 log_error(LOG_LEVEL_INFO, "Got to execute tagger on %N",
2674 content_length, csp->client_iob->cur);
2676 if (list_is_empty(csp->action->multi[multi_action_index])
2677 || filters_available(csp) == FALSE)
2679 /* Return early if no taggers apply or if none are available. */
2683 /* Execute all applying taggers */
2684 for (tag_name = csp->action->multi[multi_action_index]->first;
2685 NULL != tag_name; tag_name = tag_name->next)
2687 char *modified_tag = NULL;
2688 char *tag = csp->client_iob->cur;
2689 size_t size = content_length;
2692 b = get_filter(csp, tag_name->str, wanted_filter_type);
2698 joblist = b->joblist;
2700 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2702 if (NULL == joblist)
2704 log_error(LOG_LEVEL_TAGGING,
2705 "Tagger %s has empty joblist. Nothing to do.", b->name);
2709 /* execute their pcrs_joblist on the body. */
2710 for (job = joblist; NULL != job; job = job->next)
2712 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2716 /* Success, continue with the modified version. */
2717 if (tag != csp->client_iob->cur)
2725 /* Tagger doesn't match */
2728 /* Regex failure, log it but continue anyway. */
2729 log_error(LOG_LEVEL_ERROR,
2730 "Problems with tagger \'%s\': %s",
2731 b->name, pcrs_strerror(hits));
2733 freez(modified_tag);
2737 if (b->dynamic) pcrs_free_joblist(joblist);
2739 /* If this tagger matched */
2740 if (tag != csp->client_iob->cur)
2745 * There is no technical limitation which makes
2746 * it impossible to use empty tags, but I assume
2747 * no one would do it intentionally.
2750 log_error(LOG_LEVEL_TAGGING,
2751 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
2755 if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
2757 log_error(LOG_LEVEL_TAGGING,
2758 "Tagger \'%s\' didn't add tag \'%s\': suppressed",
2764 if (!list_contains_item(csp->tags, tag))
2766 if (JB_ERR_OK != enlist(csp->tags, tag))
2768 log_error(LOG_LEVEL_ERROR,
2769 "Insufficient memory to add tag \'%s\', "
2770 "based on tagger \'%s\'",
2775 char *action_message;
2777 * update the action bits right away, to make
2778 * tagging based on tags set by earlier taggers
2779 * of the same kind possible.
2781 if (update_action_bits_for_tag(csp, tag))
2783 action_message = "Action bits updated accordingly.";
2787 action_message = "No action bits update necessary.";
2790 log_error(LOG_LEVEL_TAGGING,
2791 "Tagger \'%s\' added tag \'%s\'. %s",
2792 b->name, tag, action_message);
2797 /* XXX: Is this log-worthy? */
2798 log_error(LOG_LEVEL_TAGGING,
2799 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
2810 /*********************************************************************
2812 * Function : get_url_actions
2814 * Description : Gets the actions for this URL.
2817 * 1 : csp = Current client state (buffers, headers, etc...)
2818 * 2 : http = http_request request for blocked URLs
2822 *********************************************************************/
2823 void get_url_actions(struct client_state *csp, struct http_request *http)
2825 struct file_list *fl;
2826 struct url_actions *b;
2829 init_current_action(csp->action);
2831 for (i = 0; i < MAX_AF_FILES; i++)
2833 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2838 #ifdef FEATURE_CLIENT_TAGS
2839 apply_url_actions(csp->action, http, csp->client_tags, b);
2841 apply_url_actions(csp->action, http, b);
2848 /*********************************************************************
2850 * Function : apply_url_actions
2852 * Description : Applies a list of URL actions.
2855 * 1 : action = Destination.
2856 * 2 : http = Current URL
2857 * 3 : client_tags = list of client tags
2858 * 4 : b = list of URL actions to apply
2862 *********************************************************************/
2863 static void apply_url_actions(struct current_action_spec *action,
2864 struct http_request *http,
2865 #ifdef FEATURE_CLIENT_TAGS
2866 const struct list *client_tags,
2868 struct url_actions *b)
2872 /* Should never happen */
2876 for (b = b->next; NULL != b; b = b->next)
2878 if (url_match(b->url, http))
2880 merge_current_action(action, b->action);
2882 #ifdef FEATURE_CLIENT_TAGS
2883 if (client_tag_match(b->url, client_tags))
2885 merge_current_action(action, b->action);
2892 /*********************************************************************
2894 * Function : get_forward_override_settings
2896 * Description : Returns forward settings as specified with the
2897 * forward-override{} action. forward-override accepts
2898 * forward lines similar to the one used in the
2899 * configuration file, but without the URL pattern.
2905 * in the configuration file can be replaced with
2906 * the action section:
2908 * {+forward-override{forward .}}
2912 * 1 : csp = Current client state (buffers, headers, etc...)
2914 * Returns : Pointer to forwarding structure in case of success.
2915 * Invalid syntax is fatal.
2917 *********************************************************************/
2918 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2920 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2921 char forward_settings[BUFFER_SIZE];
2922 char *http_parent = NULL;
2923 /* variable names were chosen for consistency reasons. */
2924 struct forward_spec *fwd = NULL;
2928 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2929 /* Should be enforced by load_one_actions_file() */
2930 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2932 /* Create a copy ssplit can modify */
2933 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2935 if (NULL != csp->fwd)
2938 * XXX: Currently necessary to prevent memory
2939 * leaks when the show-url-info cgi page is visited.
2941 unload_forward_spec(csp->fwd);
2945 * allocate a new forward node, valid only for
2946 * the lifetime of this request. Save its location
2947 * in csp as well, so sweep() can free it later on.
2949 fwd = csp->fwd = zalloc_or_die(sizeof(*fwd));
2951 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2952 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2954 fwd->type = SOCKS_NONE;
2956 /* Parse the parent HTTP proxy host:port */
2957 http_parent = vec[1];
2960 else if ((vec_count == 2) && !strcasecmp(vec[0], "forward-webserver"))
2962 fwd->type = FORWARD_WEBSERVER;
2964 /* Parse the parent HTTP server host:port */
2965 http_parent = vec[1];
2968 else if (vec_count == 3)
2970 char *socks_proxy = NULL;
2972 if (!strcasecmp(vec[0], "forward-socks4"))
2974 fwd->type = SOCKS_4;
2975 socks_proxy = vec[1];
2977 else if (!strcasecmp(vec[0], "forward-socks4a"))
2979 fwd->type = SOCKS_4A;
2980 socks_proxy = vec[1];
2982 else if (!strcasecmp(vec[0], "forward-socks5"))
2984 fwd->type = SOCKS_5;
2985 socks_proxy = vec[1];
2987 else if (!strcasecmp(vec[0], "forward-socks5t"))
2989 fwd->type = SOCKS_5T;
2990 socks_proxy = vec[1];
2993 if (NULL != socks_proxy)
2995 /* Parse the SOCKS proxy [user:pass@]host[:port] */
2996 fwd->gateway_port = 1080;
2997 parse_forwarder_address(socks_proxy,
2998 &fwd->gateway_host, &fwd->gateway_port,
2999 &fwd->auth_username, &fwd->auth_password);
3001 http_parent = vec[2];
3005 if (NULL == http_parent)
3007 log_error(LOG_LEVEL_FATAL,
3008 "Invalid forward-override syntax in: %s", forward_override_line);
3009 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3012 /* Parse http forwarding settings */
3013 if (strcmp(http_parent, ".") != 0)
3015 fwd->forward_port = 8000;
3016 parse_forwarder_address(http_parent,
3017 &fwd->forward_host, &fwd->forward_port,
3021 assert (NULL != fwd);
3023 log_error(LOG_LEVEL_CONNECT,
3024 "Overriding forwarding settings based on \'%s\'", forward_override_line);
3030 /*********************************************************************
3032 * Function : forward_url
3034 * Description : Should we forward this to another proxy?
3037 * 1 : csp = Current client state (buffers, headers, etc...)
3038 * 2 : http = http_request request for current URL
3040 * Returns : Pointer to forwarding information.
3042 *********************************************************************/
3043 const struct forward_spec *forward_url(struct client_state *csp,
3044 const struct http_request *http)
3046 static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
3047 struct forward_spec *fwd = csp->config->forward;
3049 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
3051 return get_forward_override_settings(csp);
3061 if (url_match(fwd->url, http))
3072 /*********************************************************************
3074 * Function : direct_response
3076 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
3077 * request and if so, return a HTTP 501 to the client.
3079 * FIXME: I have a stupid name and I should handle the
3080 * requests properly. Still, what we do here is rfc-
3081 * compliant, whereas ignoring or forwarding are not.
3084 * 1 : csp = Current client state (buffers, headers, etc...)
3086 * Returns : http_response if , NULL if nonmatch or handler fail
3088 *********************************************************************/
3089 struct http_response *direct_response(struct client_state *csp)
3091 struct http_response *rsp;
3092 struct list_entry *p;
3094 if ((0 == strcmpic(csp->http->gpc, "trace"))
3095 || (0 == strcmpic(csp->http->gpc, "options")))
3097 for (p = csp->headers->first; (p != NULL) ; p = p->next)
3099 if (!strncmpic(p->str, "Max-Forwards:", 13))
3101 unsigned int max_forwards;
3104 * If it's a Max-Forwards value of zero,
3105 * we have to intercept the request.
3107 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
3110 * FIXME: We could handle at least TRACE here,
3111 * but that would require a verbatim copy of
3112 * the request which we don't have anymore
3114 log_error(LOG_LEVEL_HEADER,
3115 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
3118 /* Get mem for response or fail*/
3119 if (NULL == (rsp = alloc_http_response()))
3121 return cgi_error_memory();
3124 rsp->status = strdup_or_die("501 Not Implemented");
3126 rsp->crunch_reason = UNSUPPORTED;
3128 return(finish_http_response(csp, rsp));
3137 /*********************************************************************
3139 * Function : content_requires_filtering
3141 * Description : Checks whether there are any content filters
3142 * enabled for the current request and if they
3143 * can actually be applied..
3146 * 1 : csp = Current client state (buffers, headers, etc...)
3148 * Returns : TRUE for yes, FALSE otherwise
3150 *********************************************************************/
3151 int content_requires_filtering(struct client_state *csp)
3153 if ((csp->content_type & CT_TABOO)
3154 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
3160 * Are we enabling text mode by force?
3162 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3165 * Do we really have to?
3167 if (csp->content_type & CT_TEXT)
3169 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
3173 csp->content_type |= CT_TEXT;
3174 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
3178 if (!(csp->content_type & CT_DECLARED))
3181 * The server didn't bother to declare a MIME-Type.
3182 * Assume it's text that can be filtered.
3184 * This also regularly happens with 304 responses,
3185 * therefore logging anything here would cause
3188 csp->content_type |= CT_TEXT;
3192 * Choose the applying filter function based on
3193 * the content type and action settings.
3195 if ((csp->content_type & CT_TEXT) &&
3196 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
3197 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
3201 else if ((csp->content_type & CT_GIF) &&
3202 (csp->action->flags & ACTION_DEANIMATE))
3212 /*********************************************************************
3214 * Function : content_filters_enabled
3216 * Description : Checks whether there are any content filters
3217 * enabled for the current request.
3220 * 1 : action = Action spec to check.
3222 * Returns : TRUE for yes, FALSE otherwise
3224 *********************************************************************/
3225 int content_filters_enabled(const struct current_action_spec *action)
3227 return ((action->flags & ACTION_DEANIMATE) ||
3228 !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
3229 !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
3233 /*********************************************************************
3235 * Function : client_body_filters_enabled
3237 * Description : Checks whether there are any client body filters
3238 * enabled for the current request.
3241 * 1 : action = Action spec to check.
3243 * Returns : TRUE for yes, FALSE otherwise
3245 *********************************************************************/
3246 int client_body_filters_enabled(const struct current_action_spec *action)
3248 return !list_is_empty(action->multi[ACTION_MULTI_CLIENT_BODY_FILTER]);
3252 /*********************************************************************
3254 * Function : client_body_taggers_enabled
3256 * Description : Checks whether there are any client body taggers
3257 * enabled for the current request.
3260 * 1 : action = Action spec to check.
3262 * Returns : TRUE for yes, FALSE otherwise
3264 *********************************************************************/
3265 int client_body_taggers_enabled(const struct current_action_spec *action)
3267 return !list_is_empty(action->multi[ACTION_MULTI_CLIENT_BODY_TAGGER]);
3270 /*********************************************************************
3272 * Function : filters_available
3274 * Description : Checks whether there are any filters available.
3277 * 1 : csp = Current client state (buffers, headers, etc...)
3279 * Returns : TRUE for yes, FALSE otherwise.
3281 *********************************************************************/
3282 int filters_available(const struct client_state *csp)
3285 for (i = 0; i < MAX_AF_FILES; i++)
3287 const struct file_list *fl = csp->rlist[i];
3288 if ((NULL != fl) && (NULL != fl->f))
3296 #ifdef FEATURE_EXTENDED_STATISTICS
3298 struct filter_statistics_entry
3301 unsigned long long executions;
3302 unsigned long long response_bodies_modified;
3303 unsigned long long hits;
3305 struct filter_statistics_entry *next;
3308 static struct filter_statistics_entry *filter_statistics = NULL;
3311 /*********************************************************************
3313 * Function : register_filter_for_statistics
3315 * Description : Registers a filter so we can gather statistics for
3316 * it unless the filter has already been registered
3320 * 1 : filter = Name of the filter to register
3324 *********************************************************************/
3325 void register_filter_for_statistics(const char *filter)
3327 struct filter_statistics_entry *entry;
3329 privoxy_mutex_lock(&filter_statistics_mutex);
3331 if (filter_statistics == NULL)
3333 filter_statistics = zalloc_or_die(sizeof(struct filter_statistics_entry));
3334 entry = filter_statistics;
3335 entry->filter = strdup_or_die(filter);
3336 privoxy_mutex_unlock(&filter_statistics_mutex);
3339 entry = filter_statistics;
3340 while (entry != NULL)
3342 if (!strcmp(entry->filter, filter))
3344 /* Already registered, nothing to do. */
3347 if (entry->next == NULL)
3349 entry->next = zalloc_or_die(sizeof(struct filter_statistics_entry));
3350 entry->next->filter = strdup_or_die(filter);
3353 entry = entry->next;
3356 privoxy_mutex_unlock(&filter_statistics_mutex);
3361 /*********************************************************************
3363 * Function : update_filter_statistics
3365 * Description : Updates the statistics for a filter.
3368 * 1 : filter = Name of the filter to update
3369 * 2 : hits = Hit count.
3373 *********************************************************************/
3374 void update_filter_statistics(const char *filter, int hits)
3376 struct filter_statistics_entry *entry;
3378 privoxy_mutex_lock(&filter_statistics_mutex);
3380 entry = filter_statistics;
3381 while (entry != NULL)
3383 if (!strcmp(entry->filter, filter))
3385 entry->executions++;
3388 entry->response_bodies_modified++;
3389 entry->hits += (unsigned)hits;
3393 entry = entry->next;
3396 privoxy_mutex_unlock(&filter_statistics_mutex);
3401 /*********************************************************************
3403 * Function : get_filter_statistics
3405 * Description : Gets the statistics for a filter.
3408 * 1 : filter = Name of the filter to get statistics for.
3409 * 2 : executions = Storage for the execution count.
3410 * 3 : response_bodies_modified = Storage for the number
3411 * of modified response bodies.
3412 * 4 : hits = Storage for the number of hits.
3416 *********************************************************************/
3417 void get_filter_statistics(const char *filter, unsigned long long *executions,
3418 unsigned long long *response_bodies_modified,
3419 unsigned long long *hits)
3421 struct filter_statistics_entry *entry;
3423 privoxy_mutex_lock(&filter_statistics_mutex);
3425 entry = filter_statistics;
3426 while (entry != NULL)
3428 if (!strcmp(entry->filter, filter))
3430 *executions = entry->executions;
3431 *response_bodies_modified = entry->response_bodies_modified;
3432 *hits = entry->hits;
3435 entry = entry->next;
3438 privoxy_mutex_unlock(&filter_statistics_mutex);
3443 struct block_statistics_entry
3446 unsigned long long count;
3448 struct block_statistics_entry *next;
3451 static struct block_statistics_entry *block_statistics = NULL;
3453 /*********************************************************************
3455 * Function : register_block_reason_for_statistics
3457 * Description : Registers a block reason so we can gather statistics
3458 * for it unless the block reason has already been
3459 * registered before.
3462 * 1 : block_reason = Block reason to register
3466 *********************************************************************/
3467 void register_block_reason_for_statistics(const char *block_reason)
3469 struct block_statistics_entry *entry;
3471 privoxy_mutex_lock(&block_reason_statistics_mutex);
3473 if (block_statistics == NULL)
3475 block_statistics = zalloc_or_die(sizeof(struct block_statistics_entry));
3476 entry = block_statistics;
3477 entry->block_reason = strdup_or_die(block_reason);
3478 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3481 entry = block_statistics;
3482 while (entry != NULL)
3484 if (!strcmp(entry->block_reason, block_reason))
3486 /* Already registered, nothing to do. */
3489 if (entry->next == NULL)
3491 entry->next = zalloc_or_die(sizeof(struct block_statistics_entry));
3492 entry->next->block_reason = strdup_or_die(block_reason);
3495 entry = entry->next;
3498 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3503 /*********************************************************************
3505 * Function : increment_block_reason_counter
3507 * Description : Updates the counter for a block reason.
3510 * 1 : block_reason = Block reason to count
3514 *********************************************************************/
3515 static void increment_block_reason_counter(const char *block_reason)
3517 struct block_statistics_entry *entry;
3519 privoxy_mutex_lock(&block_reason_statistics_mutex);
3521 entry = block_statistics;
3522 while (entry != NULL)
3524 if (!strcmp(entry->block_reason, block_reason))
3529 entry = entry->next;
3532 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3537 /*********************************************************************
3539 * Function : get_block_reason_count
3541 * Description : Gets number of times a block reason was used.
3544 * 1 : block_reason = Block reason to get statistics for.
3545 * 2 : count = Storage for the number of times the block
3550 *********************************************************************/
3551 void get_block_reason_count(const char *block_reason, unsigned long long *count)
3553 struct block_statistics_entry *entry;
3555 privoxy_mutex_lock(&block_reason_statistics_mutex);
3557 entry = block_statistics;
3558 while (entry != NULL)
3560 if (!strcmp(entry->block_reason, block_reason))
3562 *count = entry->count;
3565 entry = entry->next;
3568 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3572 #endif /* def FEATURE_EXTENDED_STATISTICS */