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;
350 /* XXX: Depend on ai_family */
358 * Use a temporary acl spec copy so we can log
359 * the unmodified original in case of parse errors.
361 acl_spec = strdup_or_die(aspec);
363 if ((p = strchr(acl_spec, '/')) != NULL)
366 if (privoxy_isdigit(*p) == 0)
371 masklength = atoi(p);
374 if ((masklength < 0) ||
386 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
389 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
398 p = strchr(acl_spec, ':');
408 memset(&hints, 0, sizeof(struct addrinfo));
409 hints.ai_family = AF_UNSPEC;
410 hints.ai_socktype = SOCK_STREAM;
412 i = getaddrinfo(acl_spec, p, &hints, &result);
416 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
417 acl_spec, p, gai_strerror(i));
423 /* TODO: Allow multihomed hostnames */
424 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
425 freeaddrinfo(result);
431 port = strtol(p, &endptr, 10);
433 if (port <= 0 || port > 65535 || *endptr != '\0')
440 aca->port = (unsigned long)port;
442 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
445 if (aca->addr == INADDR_NONE)
447 /* XXX: This will be logged as parse error. */
450 #endif /* def HAVE_RFC2553 */
452 /* build the netmask */
454 /* Clip masklength according to current family. */
455 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
460 aca->mask.ss_family = aca->addr.ss_family;
461 sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port);
465 /* ACL contains a port number, check ports in the future. */
470 * XXX: This could be optimized to operate on whole words instead
471 * of octets (128-bit CPU could do it in one iteration).
474 * Octets after prefix can be omitted because of
475 * previous initialization to zeros.
477 for (i = 0; (i < addr_len) && masklength; i++)
487 * XXX: This assumes MSB of octet is on the left side.
488 * This should be true for all architectures or solved
491 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
498 for (i=1; i <= masklength ; i++)
500 aca->mask |= (1U << (32 - i));
503 /* now mask off the host portion of the ip address
504 * (i.e. save on the network portion of the address).
506 aca->addr = aca->addr & aca->mask;
507 #endif /* def HAVE_RFC2553 */
512 #endif /* def FEATURE_ACL */
515 /*********************************************************************
517 * Function : connect_port_is_forbidden
519 * Description : Check to see if CONNECT requests to the destination
520 * port of this request are forbidden. The check is
521 * independent of the actual request method.
524 * 1 : csp = Current client state (buffers, headers, etc...)
526 * Returns : True if yes, false otherwise.
528 *********************************************************************/
529 int connect_port_is_forbidden(const struct client_state *csp)
531 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
532 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
537 /*********************************************************************
539 * Function : block_url
541 * Description : Called from `chat'. Check to see if we need to block this.
544 * 1 : csp = Current client state (buffers, headers, etc...)
546 * Returns : NULL => unblocked, else HTTP block response
548 *********************************************************************/
549 struct http_response *block_url(struct client_state *csp)
551 struct http_response *rsp;
552 const char *new_content_type = NULL;
555 * If it's not blocked, don't block it ;-)
557 if ((csp->action->flags & ACTION_BLOCK) == 0)
561 if (csp->action->flags & ACTION_REDIRECT)
563 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
566 * Else, prepare a response
568 if (NULL == (rsp = alloc_http_response()))
570 return cgi_error_memory();
573 #ifdef FEATURE_EXTENDED_STATISTICS
574 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
576 increment_block_reason_counter(csp->action->string[ACTION_STRING_BLOCK]);
581 * If it's an image-url, send back an image or redirect
582 * as specified by the relevant +image action
584 #ifdef FEATURE_IMAGE_BLOCKING
585 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
589 /* determine HOW images should be blocked */
590 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
592 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
594 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
597 /* and handle accordingly: */
598 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
600 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
601 rsp->body = bindup(image_pattern_data, image_pattern_length);
602 if (rsp->body == NULL)
604 free_http_response(rsp);
605 return cgi_error_memory();
607 rsp->content_length = image_pattern_length;
609 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
611 free_http_response(rsp);
612 return cgi_error_memory();
615 else if (0 == strcmpic(p, "blank"))
617 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
618 rsp->body = bindup(image_blank_data, image_blank_length);
619 if (rsp->body == NULL)
621 free_http_response(rsp);
622 return cgi_error_memory();
624 rsp->content_length = image_blank_length;
626 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
628 free_http_response(rsp);
629 return cgi_error_memory();
634 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
636 if (enlist_unique_header(rsp->headers, "Location", p))
638 free_http_response(rsp);
639 return cgi_error_memory();
645 #endif /* def FEATURE_IMAGE_BLOCKING */
646 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
649 * Send empty document.
651 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
654 rsp->body = strdup_or_die(" ");
655 rsp->content_length = 1;
657 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
660 * Workaround for firefox bug 492459
661 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
662 * Return a 200 OK status for pages blocked with +handle-as-empty-document
663 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
665 rsp->status = strdup_or_die("200 Request blocked by Privoxy");
669 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
672 if (new_content_type != 0)
674 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
675 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
677 free_http_response(rsp);
678 return cgi_error_memory();
685 * Else, generate an HTML "blocked" message:
689 struct map * exports;
691 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
693 exports = default_exports(csp, NULL);
696 free_http_response(rsp);
697 return cgi_error_memory();
700 #ifdef FEATURE_FORCE_LOAD
701 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
703 * Export the force conditional block killer if
705 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
706 * - Privoxy is configured to enforce blocks, or
707 * - it's a CONNECT request and enforcing wouldn't work anyway.
709 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
710 || (0 == strcmpic(csp->http->gpc, "connect")))
711 #endif /* ndef FEATURE_FORCE_LOAD */
713 err = map_block_killer(exports, "force-support");
716 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
717 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
718 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
719 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
722 const char *block_reason;
723 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
725 block_reason = csp->action->string[ACTION_STRING_BLOCK];
729 assert(connect_port_is_forbidden(csp));
730 block_reason = "Forbidden CONNECT port.";
732 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
737 free_http_response(rsp);
738 return cgi_error_memory();
741 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
744 free_http_response(rsp);
745 return cgi_error_memory();
748 rsp->crunch_reason = BLOCKED;
750 return finish_http_response(csp, rsp);
756 /*********************************************************************
758 * Function : trust_url FIXME: I should be called distrust_url
760 * Description : Calls is_untrusted_url to determine if the URL is trusted
761 * and if not, returns a HTTP 403 response with a reject message.
764 * 1 : csp = Current client state (buffers, headers, etc...)
766 * Returns : NULL => trusted, else http_response.
768 *********************************************************************/
769 struct http_response *trust_url(struct client_state *csp)
771 struct http_response *rsp;
772 struct map * exports;
773 char buf[BUFFER_SIZE];
775 struct pattern_spec **tl;
776 struct pattern_spec *t;
780 * Don't bother to work on trusted URLs
782 if (!is_untrusted_url(csp))
788 * Else, prepare a response:
790 if (NULL == (rsp = alloc_http_response()))
792 return cgi_error_memory();
795 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
796 exports = default_exports(csp, NULL);
799 free_http_response(rsp);
800 return cgi_error_memory();
804 * Export the protocol, host, port, and referrer information
806 err = map(exports, "hostport", 1, csp->http->hostport, 1);
807 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
808 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
810 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
812 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
816 if (!err) err = map(exports, "referrer", 1, "none set", 1);
822 free_http_response(rsp);
823 return cgi_error_memory();
827 * Export the trust list
829 p = strdup_or_die("");
830 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
832 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
833 string_append(&p, buf);
835 err = map(exports, "trusted-referrers", 1, p, 0);
840 free_http_response(rsp);
841 return cgi_error_memory();
845 * Export the trust info, if available
847 if (csp->config->trust_info->first)
849 struct list_entry *l;
851 p = strdup_or_die("");
852 for (l = csp->config->trust_info->first; l ; l = l->next)
854 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
855 string_append(&p, buf);
857 err = map(exports, "trust-info", 1, p, 0);
861 err = map_block_killer(exports, "have-trust-info");
867 free_http_response(rsp);
868 return cgi_error_memory();
872 * Export the force conditional block killer if
874 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
875 * - Privoxy is configured to enforce blocks, or
876 * - it's a CONNECT request and enforcing wouldn't work anyway.
878 #ifdef FEATURE_FORCE_LOAD
879 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
880 || (0 == strcmpic(csp->http->gpc, "connect")))
882 err = map_block_killer(exports, "force-support");
886 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
888 #else /* ifndef FEATURE_FORCE_LOAD */
889 err = map_block_killer(exports, "force-support");
890 #endif /* ndef FEATURE_FORCE_LOAD */
895 free_http_response(rsp);
896 return cgi_error_memory();
902 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
905 free_http_response(rsp);
906 return cgi_error_memory();
908 rsp->crunch_reason = UNTRUSTED;
910 return finish_http_response(csp, rsp);
912 #endif /* def FEATURE_TRUST */
915 /*********************************************************************
917 * Function : compile_dynamic_pcrs_job_list
919 * Description : Compiles a dynamic pcrs job list (one with variables
920 * resolved at request time)
923 * 1 : csp = Current client state (buffers, headers, etc...)
924 * 2 : b = The filter list to compile
926 * Returns : NULL in case of errors, otherwise the
929 *********************************************************************/
930 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
932 struct list_entry *pattern;
933 pcrs_job *job_list = NULL;
934 pcrs_job *dummy = NULL;
935 pcrs_job *lastjob = NULL;
938 const struct pcrs_variable variables[] =
940 {"url", csp->http->url, 1},
941 {"path", csp->http->path, 1},
942 {"host", csp->http->host, 1},
943 {"origin", csp->ip_addr_str, 1},
944 {"listen-address", csp->listen_addr_str, 1},
948 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
950 assert(pattern->str != NULL);
952 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
955 log_error(LOG_LEVEL_ERROR,
956 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
957 pattern->str, b->name, error, pcrs_strerror(error));
962 if (error == PCRS_WARN_TRUNCATION)
964 log_error(LOG_LEVEL_ERROR,
965 "At least one of the variables in \'%s\' had to "
966 "be truncated before compilation", pattern->str);
968 if (job_list == NULL)
974 lastjob->next = dummy;
984 /*********************************************************************
986 * Function : rewrite_url
988 * Description : Rewrites a URL with a single pcrs command
989 * and returns the result if it differs from the
990 * original and isn't obviously invalid.
993 * 1 : old_url = URL to rewrite.
994 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
997 * Returns : NULL if the pcrs_command didn't change the url, or
998 * the result of the modification.
1000 *********************************************************************/
1001 char *rewrite_url(char *old_url, const char *pcrs_command)
1003 char *new_url = NULL;
1007 assert(pcrs_command);
1009 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1013 log_error(LOG_LEVEL_REDIRECTS,
1014 "pcrs command \"%s\" didn't change \"%s\".",
1015 pcrs_command, old_url);
1020 log_error(LOG_LEVEL_REDIRECTS,
1021 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1022 pcrs_command, old_url, pcrs_strerror(hits));
1025 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1027 log_error(LOG_LEVEL_ERROR,
1028 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1029 "but the result doesn't look like a valid URL and will be ignored.",
1030 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1035 log_error(LOG_LEVEL_REDIRECTS,
1036 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1037 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1045 #ifdef FEATURE_FAST_REDIRECTS
1046 /*********************************************************************
1048 * Function : get_last_url
1050 * Description : Search for the last URL inside a string.
1051 * If the string already is a URL, it will
1052 * be the first URL found.
1055 * 1 : subject = the string to check
1056 * 2 : redirect_mode = +fast-redirect{} mode
1058 * Returns : NULL if no URL was found, or
1059 * the last URL found.
1061 *********************************************************************/
1062 static char *get_last_url(char *subject, const char *redirect_mode)
1064 char *new_url = NULL;
1068 assert(redirect_mode);
1070 subject = strdup(subject);
1071 if (subject == NULL)
1073 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1077 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1079 char *url_segment = NULL;
1080 char **url_segments;
1081 size_t max_segments;
1084 log_error(LOG_LEVEL_REDIRECTS,
1085 "Checking \"%s\" for encoded redirects.", subject);
1088 * Check each parameter in the URL separately.
1089 * Sectionize the URL at "?" and "&",
1090 * go backwards through the segments, URL-decode them
1091 * and look for a URL in the decoded result.
1092 * Stop the search after the first match.
1094 * XXX: This estimate is guaranteed to be high enough as we
1095 * let ssplit() ignore empty fields, but also a bit wasteful.
1097 max_segments = strlen(subject) / 2;
1098 url_segments = malloc(max_segments * sizeof(char *));
1100 if (NULL == url_segments)
1102 log_error(LOG_LEVEL_ERROR,
1103 "Out of memory while decoding URL: %s", subject);
1108 segments = ssplit(subject, "?&", url_segments, max_segments);
1110 while (segments-- > 0)
1112 char *dtoken = url_decode(url_segments[segments]);
1115 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1118 url_segment = strstr(dtoken, "http://");
1119 if (NULL == url_segment)
1121 url_segment = strstr(dtoken, "https://");
1123 if (NULL != url_segment)
1125 url_segment = strdup_or_die(url_segment);
1132 freez(url_segments);
1134 if (url_segment == NULL)
1138 subject = url_segment;
1142 /* Look for a URL inside this one, without decoding anything. */
1143 log_error(LOG_LEVEL_REDIRECTS,
1144 "Checking \"%s\" for unencoded redirects.", subject);
1148 * Find the last URL encoded in the request
1151 while ((tmp = strstr(tmp, "http://")) != NULL)
1155 tmp = (new_url != NULL) ? new_url : subject;
1156 while ((tmp = strstr(tmp, "https://")) != NULL)
1161 if ((new_url != NULL)
1162 && ( (new_url != subject)
1163 || (0 == strncmpic(subject, "http://", 7))
1164 || (0 == strncmpic(subject, "https://", 8))
1168 * Return new URL if we found a redirect
1169 * or if the subject already was a URL.
1171 * The second case makes sure that we can
1172 * chain get_last_url after another redirection check
1173 * (like rewrite_url) without losing earlier redirects.
1175 new_url = strdup(new_url);
1184 #endif /* def FEATURE_FAST_REDIRECTS */
1187 /*********************************************************************
1189 * Function : redirect_url
1191 * Description : Checks if Privoxy should answer the request with
1192 * a HTTP redirect and generates the redirect if
1196 * 1 : csp = Current client state (buffers, headers, etc...)
1198 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1200 *********************************************************************/
1201 struct http_response *redirect_url(struct client_state *csp)
1203 struct http_response *rsp;
1204 #ifdef FEATURE_FAST_REDIRECTS
1206 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1207 * as compile-time option? The user can easily disable
1208 * it in his action file.
1210 char * redirect_mode;
1211 #endif /* def FEATURE_FAST_REDIRECTS */
1212 char *new_url = NULL;
1213 char *redirection_string;
1215 if ((csp->action->flags & ACTION_REDIRECT))
1217 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1220 * If the redirection string begins with 's',
1221 * assume it's a pcrs command, otherwise treat it as
1222 * properly formatted URL and use it for the redirection
1225 * According to (the now obsolete) RFC 2616 section 14.30
1226 * the URL has to be absolute and if the user tries:
1227 * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
1228 * she would get undefined results anyway.
1230 * RFC 7231 7.1.2 actually allows relative references,
1231 * but those start with a leading slash (RFC 3986 4.2) and
1232 * thus can't be mistaken for pcrs commands either.
1235 if (*redirection_string == 's')
1237 char *requested_url;
1239 #ifdef FEATURE_HTTPS_INSPECTION
1240 if (client_use_ssl(csp))
1244 requested_url = strdup_or_die("https://");
1245 err = string_append(&requested_url, csp->http->hostport);
1246 if (!err) err = string_append(&requested_url, csp->http->path);
1249 log_error(LOG_LEVEL_FATAL,
1250 "Failed to rebuild URL 'https://%s%s'",
1251 csp->http->hostport, csp->http->path);
1257 requested_url = csp->http->url;
1259 new_url = rewrite_url(requested_url, redirection_string);
1260 #ifdef FEATURE_HTTPS_INSPECTION
1261 if (requested_url != csp->http->url)
1263 assert(client_use_ssl(csp));
1264 freez(requested_url);
1270 log_error(LOG_LEVEL_REDIRECTS,
1271 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1272 redirection_string);
1273 new_url = strdup(redirection_string);
1277 #ifdef FEATURE_FAST_REDIRECTS
1278 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1282 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1285 * If it exists, use the previously rewritten URL as input
1286 * otherwise just use the old path.
1288 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1289 new_url = get_last_url(old_url, redirect_mode);
1292 #endif /* def FEATURE_FAST_REDIRECTS */
1294 /* Did any redirect action trigger? */
1297 if (url_requires_percent_encoding(new_url))
1300 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1301 strlen(new_url), new_url);
1302 encoded_url = percent_encode_url(new_url);
1304 if (encoded_url == NULL)
1306 return cgi_error_memory();
1308 new_url = encoded_url;
1309 assert(FALSE == url_requires_percent_encoding(new_url));
1312 if (0 == strcmpic(new_url, csp->http->url))
1314 log_error(LOG_LEVEL_ERROR,
1315 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1316 csp->http->url, new_url);
1321 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1323 if (NULL == (rsp = alloc_http_response()))
1326 return cgi_error_memory();
1329 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
1330 if (enlist_unique_header(rsp->headers, "Location", new_url))
1333 free_http_response(rsp);
1334 return cgi_error_memory();
1336 rsp->crunch_reason = REDIRECTED;
1339 return finish_http_response(csp, rsp);
1343 /* Only reached if no redirect is required */
1349 #ifdef FEATURE_IMAGE_BLOCKING
1350 /*********************************************************************
1352 * Function : is_imageurl
1354 * Description : Given a URL, decide whether it should be treated
1355 * as image URL or not.
1358 * 1 : csp = Current client state (buffers, headers, etc...)
1360 * Returns : True (nonzero) if URL is an image URL, false (0)
1363 *********************************************************************/
1364 int is_imageurl(const struct client_state *csp)
1366 return ((csp->action->flags & ACTION_IMAGE) != 0);
1369 #endif /* def FEATURE_IMAGE_BLOCKING */
1372 #ifdef FEATURE_TRUST
1373 /*********************************************************************
1375 * Function : is_untrusted_url
1377 * Description : Should we "distrust" this URL (and block it)?
1379 * Yes if it matches a line in the trustfile, or if the
1380 * referrer matches a line starting with "+" in the
1385 * 1 : csp = Current client state (buffers, headers, etc...)
1387 * Returns : 0 => trusted, 1 => untrusted
1389 *********************************************************************/
1390 int is_untrusted_url(const struct client_state *csp)
1392 struct file_list *fl;
1393 struct block_spec *b;
1394 struct pattern_spec **trusted_url;
1395 struct http_request rhttp[1];
1396 const char * referer;
1400 * If we don't have a trustlist, we trust everybody
1402 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1407 memset(rhttp, '\0', sizeof(*rhttp));
1410 * Do we trust the request URL itself?
1412 for (b = b->next; b ; b = b->next)
1414 if (url_match(b->url, csp->http))
1420 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1422 /* no referrer was supplied */
1428 * If not, do we maybe trust its referrer?
1430 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1436 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1438 if (url_match(*trusted_url, rhttp))
1440 /* if the URL's referrer is from a trusted referrer, then
1441 * add the target spec to the trustfile as an unblocked
1442 * domain and return 0 (which means it's OK).
1447 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1451 char * new_entry = strdup_or_die("~");
1453 string_append(&new_entry, csp->http->hostport);
1455 path = csp->http->path;
1456 if ( (path[0] == '/')
1458 && ((path_end = strchr(path + 2, '/')) != NULL))
1460 /* since this path points into a user's home space
1461 * be sure to include this spec in the trustfile.
1463 long path_len = path_end - path; /* save offset */
1464 path = strdup(path); /* Copy string */
1467 path_end = path + path_len; /* regenerate ptr to new buffer */
1468 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1470 string_join(&new_entry, path);
1474 * Give a reason for generating this entry.
1476 string_append(&new_entry, " # Trusted referrer was: ");
1477 string_append(&new_entry, referer);
1479 if (new_entry != NULL)
1481 if (-1 == fprintf(fp, "%s\n", new_entry))
1483 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1484 new_entry, csp->config->trustfile);
1490 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1491 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1498 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1499 csp->http->hostport, csp->config->trustfile);
1507 #endif /* def FEATURE_TRUST */
1510 /*********************************************************************
1512 * Function : get_filter
1514 * Description : Get a filter with a given name and type.
1515 * Note that taggers are filters, too.
1518 * 1 : csp = Current client state (buffers, headers, etc...)
1519 * 2 : requested_name = Name of the content filter to get
1520 * 3 : requested_type = Type of the filter to tagger to lookup
1522 * Returns : A pointer to the requested filter
1523 * or NULL if the filter wasn't found
1525 *********************************************************************/
1526 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1527 const char *requested_name,
1528 enum filter_type requested_type)
1531 struct re_filterfile_spec *b;
1532 struct file_list *fl;
1534 for (i = 0; i < MAX_AF_FILES; i++)
1537 if ((NULL == fl) || (NULL == fl->f))
1540 * Either there are no filter files left or this
1541 * filter file just contains no valid filters.
1543 * Continue to be sure we don't miss valid filter
1544 * files that are chained after empty or invalid ones.
1549 for (b = fl->f; b != NULL; b = b->next)
1551 if (b->type != requested_type)
1553 /* The callers isn't interested in this filter type. */
1556 if (strcmp(b->name, requested_name) == 0)
1558 /* The requested filter has been found. Abort search. */
1564 /* No filter with the given name and type exists. */
1570 /*********************************************************************
1572 * Function : pcrs_filter_impl
1574 * Description : Execute all text substitutions from all applying
1575 * (based on filter_response_body value) +filter
1576 * or +client_body_filter actions on the given buffer.
1579 * 1 : csp = Current client state (buffers, headers, etc...)
1580 * 2 : filter_response_body = when TRUE execute +filter
1581 * actions; execute +client_body_filter actions otherwise
1582 * 3 : data = Target data
1583 * 4 : data_len = Target data len
1585 * Returns : a pointer to the (newly allocated) modified buffer.
1586 * or NULL if there were no hits or something went wrong
1588 *********************************************************************/
1589 static char *pcrs_filter_impl(const struct client_state *csp, int filter_response_body,
1590 const char *data, size_t *data_len)
1593 size_t size, prev_size;
1594 const int filters_idx =
1595 filter_response_body ? ACTION_MULTI_FILTER : ACTION_MULTI_CLIENT_BODY_FILTER;
1596 const enum filter_type filter_type =
1597 filter_response_body ? FT_CONTENT_FILTER : FT_CLIENT_BODY_FILTER;
1599 const char *old = NULL;
1603 struct re_filterfile_spec *b;
1604 struct list_entry *filtername;
1614 if (filters_available(csp) == FALSE)
1616 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1617 "content filtering enabled, but no content filters available.");
1625 * For all applying actions, look if a filter by that
1626 * name exists and if yes, execute it's pcrs_joblist on the
1629 for (filtername = csp->action->multi[filters_idx]->first;
1630 filtername != NULL; filtername = filtername->next)
1632 int current_hits = 0; /* Number of hits caused by this filter */
1633 int job_number = 0; /* Which job we're currently executing */
1634 int job_hits = 0; /* How many hits the current job caused */
1637 b = get_filter(csp, filtername->str, filter_type);
1643 joblist = b->joblist;
1645 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1647 if (NULL == joblist)
1649 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1654 /* Apply all jobs from the joblist */
1655 for (job = joblist; NULL != job; job = job->next)
1658 job_hits = pcrs_execute(job, old, size, &new, &size);
1663 * That went well. Continue filtering
1664 * and use the result of this job as
1665 * input for the next one.
1667 current_hits += job_hits;
1677 * This job caused an unexpected error. Inform the user
1678 * and skip the rest of the jobs in this filter. We could
1679 * continue with the next job, but usually the jobs
1680 * depend on each other or are similar enough to
1681 * fail for the same reason.
1683 * At the moment our pcrs expects the error codes of pcre 3.4,
1684 * but newer pcre versions can return additional error codes.
1685 * As a result pcrs_strerror()'s error message might be
1686 * "Unknown error ...", therefore we print the numerical value
1689 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1690 * should we use LOG_LEVEL_RE_FILTER instead?
1692 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1693 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1698 if (b->dynamic) pcrs_free_joblist(joblist);
1700 if (filter_response_body)
1702 log_error(LOG_LEVEL_RE_FILTER,
1703 "filtering %s%s (size %lu) with \'%s\' produced %d hits (new size %lu).",
1704 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1708 log_error(LOG_LEVEL_RE_FILTER, "filtering request body from client %s "
1709 "(size %lu) with \'%s\' produced %d hits (new size %lu).",
1710 csp->ip_addr_str, prev_size, b->name, current_hits, size);
1712 #ifdef FEATURE_EXTENDED_STATISTICS
1713 update_filter_statistics(b->name, current_hits);
1715 hits += current_hits;
1719 * If there were no hits, destroy our copy and let
1720 * chat() use the original content
1724 if (old != data && old != new)
1737 /*********************************************************************
1739 * Function : pcrs_filter_response_body
1741 * Description : Execute all text substitutions from all applying
1742 * +filter actions on the text buffer that's been
1743 * accumulated in csp->iob->buf.
1746 * 1 : csp = Current client state (buffers, headers, etc...)
1748 * Returns : a pointer to the (newly allocated) modified buffer.
1749 * or NULL if there were no hits or something went wrong
1751 *********************************************************************/
1752 static char *pcrs_filter_response_body(struct client_state *csp)
1754 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1761 if (csp->iob->cur >= csp->iob->eod)
1766 new = pcrs_filter_impl(csp, TRUE, csp->iob->cur, &size);
1770 csp->flags |= CSP_FLAG_MODIFIED;
1771 csp->content_length = size;
1772 clear_iob(csp->iob);
1779 #ifdef FEATURE_EXTERNAL_FILTERS
1780 /*********************************************************************
1782 * Function : get_external_filter
1784 * Description : Lookup the code to execute for an external filter.
1785 * Masks the misuse of the re_filterfile_spec.
1788 * 1 : csp = Current client state (buffers, headers, etc...)
1789 * 2 : name = Name of the content filter to get
1791 * Returns : A pointer to the requested code
1792 * or NULL if the filter wasn't found
1794 *********************************************************************/
1795 static const char *get_external_filter(const struct client_state *csp,
1798 struct re_filterfile_spec *external_filter;
1800 external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
1801 if (external_filter == NULL)
1803 log_error(LOG_LEVEL_FATAL,
1804 "Didn't find stuff to execute for external filter: %s",
1808 return external_filter->patterns->first->str;
1813 /*********************************************************************
1815 * Function : set_privoxy_variables
1817 * Description : Sets a couple of privoxy-specific environment variables
1820 * 1 : csp = Current client state (buffers, headers, etc...)
1824 *********************************************************************/
1825 static void set_privoxy_variables(const struct client_state *csp)
1832 { "PRIVOXY_URL", csp->http->url },
1833 { "PRIVOXY_PATH", csp->http->path },
1834 { "PRIVOXY_HOST", csp->http->host },
1835 { "PRIVOXY_ORIGIN", csp->ip_addr_str },
1836 { "PRIVOXY_LISTEN_ADDRESS", csp->listen_addr_str },
1839 for (i = 0; i < SZ(env); i++)
1841 if (setenv(env[i].name, env[i].value, 1))
1843 log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
1844 env[i].name, env[i].value);
1850 /*********************************************************************
1852 * Function : execute_external_filter
1854 * Description : Pipe content into external filter and return the output
1857 * 1 : csp = Current client state (buffers, headers, etc...)
1858 * 2 : name = Name of the external filter to execute
1859 * 3 : content = The original content to filter
1860 * 4 : size = The size of the content buffer
1862 * Returns : a pointer to the (newly allocated) modified buffer.
1863 * or NULL if there were no hits or something went wrong
1865 *********************************************************************/
1866 static char *execute_external_filter(const struct client_state *csp,
1867 const char *name, char *content, size_t *size)
1870 char file_name[FILENAME_MAX];
1872 char *filter_output;
1876 const char *external_filter;
1878 if (csp->config->temporary_directory == NULL)
1880 log_error(LOG_LEVEL_ERROR,
1881 "No temporary-directory configured. Can't execute filter: %s",
1886 external_filter = get_external_filter(csp, name);
1888 if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
1889 "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
1891 log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
1895 fd = mkstemp(file_name);
1898 log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
1902 fp = fdopen(fd, "w");
1905 log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
1911 * The size may be zero if a previous filter discarded everything.
1913 * This isn't necessary unintentional, so we just don't try
1914 * to fwrite() nothing and let the user deal with the rest.
1916 if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
1918 log_error(LOG_LEVEL_ERROR, "fwrite(..., %lu, 1, ..) failed: %E", *size);
1925 if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
1927 log_error(LOG_LEVEL_ERROR,
1928 "temporary-directory or external filter path too long");
1933 log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
1936 * The locking is necessary to prevent other threads
1937 * from overwriting the environment variables before
1938 * the popen fork. Afterwards this no longer matters.
1940 privoxy_mutex_lock(&external_filter_mutex);
1941 set_privoxy_variables(csp);
1942 fp = popen(cmd, "r");
1943 privoxy_mutex_unlock(&external_filter_mutex);
1946 log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
1951 /* Allocate at least one byte */
1952 filter_output = malloc_or_die(*size + 1);
1955 while (!feof(fp) && !ferror(fp))
1958 /* Could be bigger ... */
1959 enum { READ_LENGTH = 2048 };
1961 if (new_size + READ_LENGTH >= *size)
1965 /* Could be considered wasteful if the content is 'large'. */
1966 *size += (*size >= READ_LENGTH) ? *size : READ_LENGTH;
1968 p = realloc(filter_output, *size);
1971 log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
1972 "external filter output. Using what we got so far.");
1977 assert(new_size + READ_LENGTH < *size);
1978 len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
1988 log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
1992 log_error(LOG_LEVEL_RE_FILTER,
1993 "Executing '%s' resulted in return value %d. "
1994 "Read %lu of up to %lu bytes.", name, (ret >> 8), new_size, *size);
2000 return filter_output;
2003 #endif /* def FEATURE_EXTERNAL_FILTERS */
2006 /*********************************************************************
2008 * Function : pcrs_filter_request_body
2010 * Description : Execute all text substitutions from all applying
2011 * +client_body_filter actions on the given text buffer.
2014 * 1 : csp = Current client state (buffers, headers, etc...)
2015 * 2 : data = Target data
2016 * 3 : data_len = Target data len
2018 * Returns : a pointer to the (newly allocated) modified buffer.
2019 * or NULL if there were no hits or something went wrong
2021 *********************************************************************/
2022 static char *pcrs_filter_request_body(const struct client_state *csp, const char *data, size_t *data_len)
2024 return pcrs_filter_impl(csp, FALSE, data, data_len);
2028 /*********************************************************************
2030 * Function : gif_deanimate_response
2032 * Description : Deanimate the GIF image that has been accumulated in
2033 * csp->iob->buf, set csp->content_length to the modified
2034 * size and raise the CSP_FLAG_MODIFIED flag.
2037 * 1 : csp = Current client state (buffers, headers, etc...)
2039 * Returns : a pointer to the (newly allocated) modified buffer.
2040 * or NULL in case something went wrong.
2042 *********************************************************************/
2044 char *gif_deanimate_response(struct client_state *csp)
2046 static char *gif_deanimate_response(struct client_state *csp)
2049 struct binbuffer *in, *out;
2053 size = (size_t)(csp->iob->eod - csp->iob->cur);
2055 in = zalloc_or_die(sizeof(*in));
2056 out = zalloc_or_die(sizeof(*out));
2058 in->buffer = csp->iob->cur;
2061 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
2063 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
2070 if ((int)size == out->offset)
2072 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
2076 log_error(LOG_LEVEL_DEANIMATE,
2077 "Success! GIF shrunk from %lu bytes to %lu.", size, out->offset);
2079 csp->content_length = out->offset;
2080 csp->flags |= CSP_FLAG_MODIFIED;
2090 /*********************************************************************
2092 * Function : get_filter_function
2094 * Description : Decides which content filter function has
2095 * to be applied (if any). Only considers functions
2096 * for internal filters which are mutually-exclusive.
2099 * 1 : csp = Current client state (buffers, headers, etc...)
2101 * Returns : The content filter function to run, or
2102 * NULL if no content filter is active
2104 *********************************************************************/
2105 static filter_function_ptr get_filter_function(const struct client_state *csp)
2107 filter_function_ptr filter_function = NULL;
2110 * Choose the applying filter function based on
2111 * the content type and action settings.
2113 if ((csp->content_type & CT_TEXT) &&
2114 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2116 filter_function = pcrs_filter_response_body;
2118 else if ((csp->content_type & CT_GIF) &&
2119 (csp->action->flags & ACTION_DEANIMATE))
2121 filter_function = gif_deanimate_response;
2124 return filter_function;
2128 /*********************************************************************
2130 * Function : get_bytes_to_next_chunk_start
2132 * Description : Returns the number of bytes to the start of the
2133 * next chunk in the buffer.
2136 * 1 : buffer = Pointer to the text buffer
2137 * 2 : size = Number of bytes in the buffer.
2138 * 3 : offset = Where to expect the beginning of the next chunk.
2140 * Returns : -1 if the size can't be determined or data is missing,
2141 * otherwise the number of bytes to the start of the next chunk
2142 * or 0 if the last chunk has been fully buffered.
2144 *********************************************************************/
2145 static int get_bytes_to_next_chunk_start(char *buffer, size_t size, size_t offset)
2149 unsigned int chunk_size = 0;
2152 if (size <= offset || size < 5)
2155 * Not enough bytes bufferd to figure
2156 * out the size of the next chunk.
2161 chunk_start = buffer + offset;
2163 p = strstr(chunk_start, "\r\n");
2167 * The line with the chunk-size hasn't been completely received
2168 * yet (or is invalid).
2170 log_error(LOG_LEVEL_RE_FILTER,
2171 "Not enough or invalid data in buffer in chunk size line.");
2175 if (sscanf(chunk_start, "%x", &chunk_size) != 1)
2177 /* XXX: Write test case to trigger this. */
2178 log_error(LOG_LEVEL_ERROR, "Failed to parse chunk size. "
2179 "Size: %lu, offset: %lu. Chunk size start: %N", size, offset,
2180 (size - offset), chunk_start);
2185 * To get to the start of the next chunk size we have to skip
2186 * the line with the current chunk size followed by "\r\n" followd
2187 * by the actual data and another "\r\n" following the data.
2189 bytes_to_skip = (int)(p - chunk_start) + 2 + (int)chunk_size + 2;
2191 if (bytes_to_skip <= 0)
2193 log_error(LOG_LEVEL_ERROR,
2194 "Failed to figure out chunk offset. %u and %d seem dubious.",
2195 chunk_size, bytes_to_skip);
2198 if (chunk_size == 0)
2200 if (bytes_to_skip <= (size - offset))
2206 log_error(LOG_LEVEL_INFO,
2207 "Last chunk detected but we're still missing data.");
2212 return bytes_to_skip;
2216 /*********************************************************************
2218 * Function : get_bytes_missing_from_chunked_data
2220 * Description : Figures out how many bytes of data we need to get
2221 * to the start of the next chunk of data (XXX: terminology).
2222 * Due to the nature of chunk-encoded data we can only see
2223 * how many data is missing according to the last chunk size
2227 * 1 : buffer = Pointer to the text buffer
2228 * 2 : size = Number of bytes in the buffer.
2229 * 3 : offset = Where to expect the beginning of the next chunk.
2231 * Returns : -1 if the data can't be parsed (yet),
2232 * 0 if the buffer is complete or a
2233 * number of bytes that is missing.
2235 *********************************************************************/
2236 int get_bytes_missing_from_chunked_data(char *buffer, size_t size, size_t offset)
2239 int last_valid_offset = -1;
2241 if (size < offset || size < 5)
2243 /* Not enough data buffered yet */
2249 ret = get_bytes_to_next_chunk_start(buffer, size, offset);
2252 return last_valid_offset;
2260 last_valid_offset = (int)offset;
2262 offset += (size_t)ret;
2263 } while (offset < size);
2270 /*********************************************************************
2272 * Function : chunked_data_is_complete
2274 * Description : Detects if a buffer with chunk-encoded data looks
2278 * 1 : buffer = Pointer to the text buffer
2279 * 2 : size = Number of bytes in the buffer.
2280 * 3 : offset = Where to expect the beginning of the
2281 * first complete chunk.
2283 * Returns : TRUE if it looks like the data is complete,
2286 *********************************************************************/
2287 int chunked_data_is_complete(char *buffer, size_t size, size_t offset)
2289 return (0 == get_bytes_missing_from_chunked_data(buffer, size, offset));
2294 /*********************************************************************
2296 * Function : remove_chunked_transfer_coding
2298 * Description : In-situ remove the "chunked" transfer coding as defined
2299 * in RFC 7230 4.1 from a buffer. XXX: The implementation
2300 * is neither complete nor compliant (TODO #129).
2303 * 1 : buffer = Pointer to the text buffer
2304 * 2 : size = In: Number of bytes to be processed,
2305 * Out: Number of bytes after de-chunking.
2306 * (undefined in case of errors)
2308 * Returns : JB_ERR_OK for success,
2309 * JB_ERR_PARSE otherwise
2311 *********************************************************************/
2313 extern jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2315 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2319 unsigned int chunksize = 0;
2320 char *from_p, *to_p;
2321 const char *end_of_buffer = buffer + *size;
2325 log_error(LOG_LEVEL_FATAL, "Invalid chunked input. Buffer is empty.");
2326 return JB_ERR_PARSE;
2330 from_p = to_p = buffer;
2334 * Refuse to de-chunk invalid or incomplete data unless we're fuzzing.
2336 if (!chunked_data_is_complete(buffer, *size, 0))
2338 log_error(LOG_LEVEL_ERROR,
2339 "Chunk-encoding appears to be invalid. Content can't be filtered.");
2340 return JB_ERR_PARSE;
2344 if (sscanf(buffer, "%x", &chunksize) != 1)
2346 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2347 return JB_ERR_PARSE;
2350 while (chunksize > 0U)
2353 * If the chunk-size is valid, we should have at least
2354 * chunk-size bytes of chunk-data and five bytes of
2355 * meta data (chunk-size, CRLF, CRLF) left in the buffer.
2357 if (chunksize + 5 >= *size - newsize)
2359 log_error(LOG_LEVEL_ERROR,
2360 "Chunk size %u exceeds buffered data left. "
2361 "Already digested %lu of %lu buffered bytes.",
2362 chunksize, newsize, *size);
2363 return JB_ERR_PARSE;
2367 * Skip the chunk-size, the optional chunk-ext and the CRLF
2368 * that is supposed to be located directly before the start
2371 if (NULL == (from_p = strstr(from_p, "\r\n")))
2373 log_error(LOG_LEVEL_ERROR,
2374 "Failed to strip \"chunked\" transfer coding. "
2375 "Line with chunk size doesn't seem to end properly.");
2376 return JB_ERR_PARSE;
2381 * The previous strstr() does not enforce chunk-validity
2382 * and is sattisfied as long a CRLF is left in the buffer.
2384 * Make sure the bytes we consider chunk-data are within
2387 if (from_p + chunksize >= end_of_buffer)
2389 log_error(LOG_LEVEL_ERROR,
2390 "Failed to decode content for filtering. "
2391 "One chunk end is beyond the end of the buffer.");
2392 return JB_ERR_PARSE;
2395 memmove(to_p, from_p, (size_t) chunksize);
2396 newsize += chunksize;
2397 to_p = buffer + newsize;
2398 from_p += chunksize;
2401 * Not merging this check with the previous one allows us
2402 * to keep chunks without trailing CRLF. It's not clear
2403 * if we actually have to care about those, though.
2405 if (from_p + 2 >= end_of_buffer)
2407 log_error(LOG_LEVEL_ERROR, "Not enough room for trailing CRLF.");
2408 return JB_ERR_PARSE;
2411 if (sscanf(from_p, "%x", &chunksize) != 1)
2413 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2418 /* XXX: Should get its own loglevel. */
2419 log_error(LOG_LEVEL_RE_FILTER,
2420 "De-chunking successful. Shrunk from %lu to %lu", *size, newsize);
2429 /*********************************************************************
2431 * Function : prepare_for_filtering
2433 * Description : If necessary, de-chunks and decompresses
2434 * the content so it can get filterd.
2437 * 1 : csp = Current client state (buffers, headers, etc...)
2439 * Returns : JB_ERR_OK for success,
2440 * JB_ERR_PARSE otherwise
2442 *********************************************************************/
2443 static jb_err prepare_for_filtering(struct client_state *csp)
2445 jb_err err = JB_ERR_OK;
2448 * If the body has a "chunked" transfer-encoding,
2449 * get rid of it, adjusting size and iob->eod
2451 if (csp->flags & CSP_FLAG_CHUNKED)
2453 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2455 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2456 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2457 if (JB_ERR_OK == err)
2459 csp->iob->eod = csp->iob->cur + size;
2460 csp->flags |= CSP_FLAG_MODIFIED;
2464 return JB_ERR_PARSE;
2470 * If the body has a supported transfer-encoding,
2471 * decompress it, adjusting size and iob->eod.
2473 if ((csp->content_type & (CT_GZIP|CT_DEFLATE))
2474 #ifdef FEATURE_BROTLI
2475 || (csp->content_type & CT_BROTLI)
2479 if (0 == csp->iob->eod - csp->iob->cur)
2481 /* Nothing left after de-chunking. */
2485 err = decompress_iob(csp);
2487 if (JB_ERR_OK == err)
2489 csp->flags |= CSP_FLAG_MODIFIED;
2490 csp->content_type &= ~CT_TABOO;
2495 * Unset content types to remember not to
2496 * modify the Content-Encoding header later.
2498 csp->content_type &= ~CT_GZIP;
2499 csp->content_type &= ~CT_DEFLATE;
2500 #ifdef FEATURE_BROTLI
2501 csp->content_type &= ~CT_BROTLI;
2511 /*********************************************************************
2513 * Function : execute_content_filters
2515 * Description : Executes a given content filter.
2518 * 1 : csp = Current client state (buffers, headers, etc...)
2520 * Returns : Pointer to the modified buffer, or
2521 * NULL if filtering failed or wasn't necessary.
2523 *********************************************************************/
2524 char *execute_content_filters(struct client_state *csp)
2527 filter_function_ptr content_filter;
2529 assert(content_filters_enabled(csp->action));
2531 if (0 == csp->iob->eod - csp->iob->cur)
2534 * No content (probably status code 301, 302 ...),
2535 * no filtering necessary.
2540 if (JB_ERR_OK != prepare_for_filtering(csp))
2543 * We failed to de-chunk or decompress, don't accept
2544 * another request on the client connection.
2546 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2550 if (0 == csp->iob->eod - csp->iob->cur)
2553 * Clown alarm: chunked and/or compressed nothing delivered.
2558 content_filter = get_filter_function(csp);
2559 content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
2561 #ifdef FEATURE_EXTERNAL_FILTERS
2562 if ((csp->content_type & CT_TEXT) &&
2563 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
2565 struct list_entry *filtername;
2566 size_t size = (size_t)csp->content_length;
2568 if (content == NULL)
2570 content = csp->iob->cur;
2571 size = (size_t)(csp->iob->eod - csp->iob->cur);
2574 for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
2575 filtername ; filtername = filtername->next)
2577 char *result = execute_external_filter(csp, filtername->str, content, &size);
2580 if (content != csp->iob->cur)
2587 csp->flags |= CSP_FLAG_MODIFIED;
2588 csp->content_length = size;
2590 #endif /* def FEATURE_EXTERNAL_FILTERS */
2597 /*********************************************************************
2599 * Function : execute_client_body_filters
2601 * Description : Executes client body filters for the request that is buffered
2602 * in the client_iob. The client_iob is updated with the filtered
2606 * 1 : csp = Current client state (buffers, headers, etc...)
2607 * 2 : content_length = content length. Upon successful filtering
2608 * the passed value is updated with the new content length.
2610 * Returns : 1 if the content has been filterd. 0 if it hasn't.
2612 *********************************************************************/
2613 int execute_client_body_filters(struct client_state *csp, size_t *content_length)
2615 char *filtered_content;
2617 assert(client_body_filters_enabled(csp->action));
2619 if (content_length == 0)
2622 * No content, no filtering necessary.
2627 filtered_content = pcrs_filter_request_body(csp, csp->client_iob->cur, content_length);
2628 if (filtered_content != NULL)
2630 freez(csp->client_iob->buf);
2631 csp->client_iob->buf = filtered_content;
2632 csp->client_iob->cur = csp->client_iob->buf;
2633 csp->client_iob->eod = csp->client_iob->cur + *content_length;
2634 csp->client_iob->size = *content_length;
2643 /*********************************************************************
2645 * Function : execute_client_body_taggers
2647 * Description : Executes client body taggers for the request that is
2648 * buffered in the client_iob.
2649 * XXX: Lots of code shared with header_tagger
2652 * 1 : csp = Current client state (buffers, headers, etc...)
2653 * 2 : content_length = content length.
2657 *********************************************************************/
2658 jb_err execute_client_body_taggers(struct client_state *csp, size_t content_length)
2660 enum filter_type wanted_filter_type = FT_CLIENT_BODY_TAGGER;
2661 int multi_action_index = ACTION_MULTI_CLIENT_BODY_TAGGER;
2664 struct re_filterfile_spec *b;
2665 struct list_entry *tag_name;
2667 assert(client_body_taggers_enabled(csp->action));
2669 if (content_length == 0)
2672 * No content, no tagging necessary.
2677 log_error(LOG_LEVEL_INFO, "Got to execute tagger on %N",
2678 content_length, csp->client_iob->cur);
2680 if (list_is_empty(csp->action->multi[multi_action_index])
2681 || filters_available(csp) == FALSE)
2683 /* Return early if no taggers apply or if none are available. */
2687 /* Execute all applying taggers */
2688 for (tag_name = csp->action->multi[multi_action_index]->first;
2689 NULL != tag_name; tag_name = tag_name->next)
2691 char *modified_tag = NULL;
2692 char *tag = csp->client_iob->cur;
2693 size_t size = content_length;
2696 b = get_filter(csp, tag_name->str, wanted_filter_type);
2702 joblist = b->joblist;
2704 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2706 if (NULL == joblist)
2708 log_error(LOG_LEVEL_TAGGING,
2709 "Tagger %s has empty joblist. Nothing to do.", b->name);
2713 /* execute their pcrs_joblist on the body. */
2714 for (job = joblist; NULL != job; job = job->next)
2716 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2720 /* Success, continue with the modified version. */
2721 if (tag != csp->client_iob->cur)
2729 /* Tagger doesn't match */
2732 /* Regex failure, log it but continue anyway. */
2733 log_error(LOG_LEVEL_ERROR,
2734 "Problems with tagger \'%s\': %s",
2735 b->name, pcrs_strerror(hits));
2737 freez(modified_tag);
2741 if (b->dynamic) pcrs_free_joblist(joblist);
2743 /* If this tagger matched */
2744 if (tag != csp->client_iob->cur)
2749 * There is no technical limitation which makes
2750 * it impossible to use empty tags, but I assume
2751 * no one would do it intentionally.
2754 log_error(LOG_LEVEL_TAGGING,
2755 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
2759 if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
2761 log_error(LOG_LEVEL_TAGGING,
2762 "Tagger \'%s\' didn't add tag \'%s\': suppressed",
2768 if (!list_contains_item(csp->tags, tag))
2770 if (JB_ERR_OK != enlist(csp->tags, tag))
2772 log_error(LOG_LEVEL_ERROR,
2773 "Insufficient memory to add tag \'%s\', "
2774 "based on tagger \'%s\'",
2779 char *action_message;
2781 * update the action bits right away, to make
2782 * tagging based on tags set by earlier taggers
2783 * of the same kind possible.
2785 if (update_action_bits_for_tag(csp, tag))
2787 action_message = "Action bits updated accordingly.";
2791 action_message = "No action bits update necessary.";
2794 log_error(LOG_LEVEL_TAGGING,
2795 "Tagger \'%s\' added tag \'%s\'. %s",
2796 b->name, tag, action_message);
2801 /* XXX: Is this log-worthy? */
2802 log_error(LOG_LEVEL_TAGGING,
2803 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
2814 /*********************************************************************
2816 * Function : get_url_actions
2818 * Description : Gets the actions for this URL.
2821 * 1 : csp = Current client state (buffers, headers, etc...)
2822 * 2 : http = http_request request for blocked URLs
2826 *********************************************************************/
2827 void get_url_actions(struct client_state *csp, struct http_request *http)
2829 struct file_list *fl;
2830 struct url_actions *b;
2833 init_current_action(csp->action);
2835 for (i = 0; i < MAX_AF_FILES; i++)
2837 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2842 #ifdef FEATURE_CLIENT_TAGS
2843 apply_url_actions(csp->action, http, csp->client_tags, b);
2845 apply_url_actions(csp->action, http, b);
2852 /*********************************************************************
2854 * Function : apply_url_actions
2856 * Description : Applies a list of URL actions.
2859 * 1 : action = Destination.
2860 * 2 : http = Current URL
2861 * 3 : client_tags = list of client tags
2862 * 4 : b = list of URL actions to apply
2866 *********************************************************************/
2867 static void apply_url_actions(struct current_action_spec *action,
2868 struct http_request *http,
2869 #ifdef FEATURE_CLIENT_TAGS
2870 const struct list *client_tags,
2872 struct url_actions *b)
2876 /* Should never happen */
2880 for (b = b->next; NULL != b; b = b->next)
2882 if (url_match(b->url, http))
2884 merge_current_action(action, b->action);
2886 #ifdef FEATURE_CLIENT_TAGS
2887 if (client_tag_match(b->url, client_tags))
2889 merge_current_action(action, b->action);
2896 /*********************************************************************
2898 * Function : get_forward_override_settings
2900 * Description : Returns forward settings as specified with the
2901 * forward-override{} action. forward-override accepts
2902 * forward lines similar to the one used in the
2903 * configuration file, but without the URL pattern.
2909 * in the configuration file can be replaced with
2910 * the action section:
2912 * {+forward-override{forward .}}
2916 * 1 : csp = Current client state (buffers, headers, etc...)
2918 * Returns : Pointer to forwarding structure in case of success.
2919 * Invalid syntax is fatal.
2921 *********************************************************************/
2922 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2924 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2925 char forward_settings[BUFFER_SIZE];
2926 char *http_parent = NULL;
2927 /* variable names were chosen for consistency reasons. */
2928 struct forward_spec *fwd = NULL;
2932 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2933 /* Should be enforced by load_one_actions_file() */
2934 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2936 /* Create a copy ssplit can modify */
2937 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2939 if (NULL != csp->fwd)
2942 * XXX: Currently necessary to prevent memory
2943 * leaks when the show-url-info cgi page is visited.
2945 unload_forward_spec(csp->fwd);
2949 * allocate a new forward node, valid only for
2950 * the lifetime of this request. Save its location
2951 * in csp as well, so sweep() can free it later on.
2953 fwd = csp->fwd = zalloc_or_die(sizeof(*fwd));
2955 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2956 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2958 fwd->type = SOCKS_NONE;
2960 /* Parse the parent HTTP proxy host:port */
2961 http_parent = vec[1];
2964 else if ((vec_count == 2) && !strcasecmp(vec[0], "forward-webserver"))
2966 fwd->type = FORWARD_WEBSERVER;
2968 /* Parse the parent HTTP server host:port */
2969 http_parent = vec[1];
2972 else if (vec_count == 3)
2974 char *socks_proxy = NULL;
2976 if (!strcasecmp(vec[0], "forward-socks4"))
2978 fwd->type = SOCKS_4;
2979 socks_proxy = vec[1];
2981 else if (!strcasecmp(vec[0], "forward-socks4a"))
2983 fwd->type = SOCKS_4A;
2984 socks_proxy = vec[1];
2986 else if (!strcasecmp(vec[0], "forward-socks5"))
2988 fwd->type = SOCKS_5;
2989 socks_proxy = vec[1];
2991 else if (!strcasecmp(vec[0], "forward-socks5t"))
2993 fwd->type = SOCKS_5T;
2994 socks_proxy = vec[1];
2997 if (NULL != socks_proxy)
2999 /* Parse the SOCKS proxy [user:pass@]host[:port] */
3000 fwd->gateway_port = 1080;
3001 parse_forwarder_address(socks_proxy,
3002 &fwd->gateway_host, &fwd->gateway_port,
3003 &fwd->auth_username, &fwd->auth_password);
3005 http_parent = vec[2];
3009 if (NULL == http_parent)
3011 log_error(LOG_LEVEL_FATAL,
3012 "Invalid forward-override syntax in: %s", forward_override_line);
3013 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3016 /* Parse http forwarding settings */
3017 if (strcmp(http_parent, ".") != 0)
3019 fwd->forward_port = 8000;
3020 parse_forwarder_address(http_parent,
3021 &fwd->forward_host, &fwd->forward_port,
3025 assert (NULL != fwd);
3027 log_error(LOG_LEVEL_CONNECT,
3028 "Overriding forwarding settings based on \'%s\'", forward_override_line);
3034 /*********************************************************************
3036 * Function : forward_url
3038 * Description : Should we forward this to another proxy?
3041 * 1 : csp = Current client state (buffers, headers, etc...)
3042 * 2 : http = http_request request for current URL
3044 * Returns : Pointer to forwarding information.
3046 *********************************************************************/
3047 const struct forward_spec *forward_url(struct client_state *csp,
3048 const struct http_request *http)
3050 static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
3051 struct forward_spec *fwd = csp->config->forward;
3053 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
3055 return get_forward_override_settings(csp);
3065 if (url_match(fwd->url, http))
3076 /*********************************************************************
3078 * Function : direct_response
3080 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
3081 * request and if so, return a HTTP 501 to the client.
3083 * FIXME: I have a stupid name and I should handle the
3084 * requests properly. Still, what we do here is rfc-
3085 * compliant, whereas ignoring or forwarding are not.
3088 * 1 : csp = Current client state (buffers, headers, etc...)
3090 * Returns : http_response if , NULL if nonmatch or handler fail
3092 *********************************************************************/
3093 struct http_response *direct_response(struct client_state *csp)
3095 struct http_response *rsp;
3096 struct list_entry *p;
3098 if ((0 == strcmpic(csp->http->gpc, "trace"))
3099 || (0 == strcmpic(csp->http->gpc, "options")))
3101 for (p = csp->headers->first; (p != NULL) ; p = p->next)
3103 if (!strncmpic(p->str, "Max-Forwards:", 13))
3105 unsigned int max_forwards;
3108 * If it's a Max-Forwards value of zero,
3109 * we have to intercept the request.
3111 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
3114 * FIXME: We could handle at least TRACE here,
3115 * but that would require a verbatim copy of
3116 * the request which we don't have anymore
3118 log_error(LOG_LEVEL_HEADER,
3119 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
3122 /* Get mem for response or fail*/
3123 if (NULL == (rsp = alloc_http_response()))
3125 return cgi_error_memory();
3128 rsp->status = strdup_or_die("501 Not Implemented");
3130 rsp->crunch_reason = UNSUPPORTED;
3132 return(finish_http_response(csp, rsp));
3141 /*********************************************************************
3143 * Function : content_requires_filtering
3145 * Description : Checks whether there are any content filters
3146 * enabled for the current request and if they
3147 * can actually be applied..
3150 * 1 : csp = Current client state (buffers, headers, etc...)
3152 * Returns : TRUE for yes, FALSE otherwise
3154 *********************************************************************/
3155 int content_requires_filtering(struct client_state *csp)
3157 if ((csp->content_type & CT_TABOO)
3158 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
3164 * Are we enabling text mode by force?
3166 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3169 * Do we really have to?
3171 if (csp->content_type & CT_TEXT)
3173 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
3177 csp->content_type |= CT_TEXT;
3178 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
3182 if (!(csp->content_type & CT_DECLARED))
3185 * The server didn't bother to declare a MIME-Type.
3186 * Assume it's text that can be filtered.
3188 * This also regularly happens with 304 responses,
3189 * therefore logging anything here would cause
3192 csp->content_type |= CT_TEXT;
3196 * Choose the applying filter function based on
3197 * the content type and action settings.
3199 if ((csp->content_type & CT_TEXT) &&
3200 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
3201 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
3205 else if ((csp->content_type & CT_GIF) &&
3206 (csp->action->flags & ACTION_DEANIMATE))
3216 /*********************************************************************
3218 * Function : content_filters_enabled
3220 * Description : Checks whether there are any content filters
3221 * enabled for the current request.
3224 * 1 : action = Action spec to check.
3226 * Returns : TRUE for yes, FALSE otherwise
3228 *********************************************************************/
3229 int content_filters_enabled(const struct current_action_spec *action)
3231 return ((action->flags & ACTION_DEANIMATE) ||
3232 !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
3233 !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
3237 /*********************************************************************
3239 * Function : client_body_filters_enabled
3241 * Description : Checks whether there are any client body filters
3242 * enabled for the current request.
3245 * 1 : action = Action spec to check.
3247 * Returns : TRUE for yes, FALSE otherwise
3249 *********************************************************************/
3250 int client_body_filters_enabled(const struct current_action_spec *action)
3252 return !list_is_empty(action->multi[ACTION_MULTI_CLIENT_BODY_FILTER]);
3256 /*********************************************************************
3258 * Function : client_body_taggers_enabled
3260 * Description : Checks whether there are any client body taggers
3261 * enabled for the current request.
3264 * 1 : action = Action spec to check.
3266 * Returns : TRUE for yes, FALSE otherwise
3268 *********************************************************************/
3269 int client_body_taggers_enabled(const struct current_action_spec *action)
3271 return !list_is_empty(action->multi[ACTION_MULTI_CLIENT_BODY_TAGGER]);
3274 /*********************************************************************
3276 * Function : filters_available
3278 * Description : Checks whether there are any filters available.
3281 * 1 : csp = Current client state (buffers, headers, etc...)
3283 * Returns : TRUE for yes, FALSE otherwise.
3285 *********************************************************************/
3286 int filters_available(const struct client_state *csp)
3289 for (i = 0; i < MAX_AF_FILES; i++)
3291 const struct file_list *fl = csp->rlist[i];
3292 if ((NULL != fl) && (NULL != fl->f))
3300 #ifdef FEATURE_EXTENDED_STATISTICS
3302 struct filter_statistics_entry
3305 unsigned long long executions;
3306 unsigned long long response_bodies_modified;
3307 unsigned long long hits;
3309 struct filter_statistics_entry *next;
3312 static struct filter_statistics_entry *filter_statistics = NULL;
3315 /*********************************************************************
3317 * Function : register_filter_for_statistics
3319 * Description : Registers a filter so we can gather statistics for
3320 * it unless the filter has already been registered
3324 * 1 : filter = Name of the filter to register
3328 *********************************************************************/
3329 void register_filter_for_statistics(const char *filter)
3331 struct filter_statistics_entry *entry;
3333 privoxy_mutex_lock(&filter_statistics_mutex);
3335 if (filter_statistics == NULL)
3337 filter_statistics = zalloc_or_die(sizeof(struct filter_statistics_entry));
3338 entry = filter_statistics;
3339 entry->filter = strdup_or_die(filter);
3340 privoxy_mutex_unlock(&filter_statistics_mutex);
3343 entry = filter_statistics;
3344 while (entry != NULL)
3346 if (!strcmp(entry->filter, filter))
3348 /* Already registered, nothing to do. */
3351 if (entry->next == NULL)
3353 entry->next = zalloc_or_die(sizeof(struct filter_statistics_entry));
3354 entry->next->filter = strdup_or_die(filter);
3357 entry = entry->next;
3360 privoxy_mutex_unlock(&filter_statistics_mutex);
3365 /*********************************************************************
3367 * Function : update_filter_statistics
3369 * Description : Updates the statistics for a filter.
3372 * 1 : filter = Name of the filter to update
3373 * 2 : hits = Hit count.
3377 *********************************************************************/
3378 void update_filter_statistics(const char *filter, int hits)
3380 struct filter_statistics_entry *entry;
3382 privoxy_mutex_lock(&filter_statistics_mutex);
3384 entry = filter_statistics;
3385 while (entry != NULL)
3387 if (!strcmp(entry->filter, filter))
3389 entry->executions++;
3392 entry->response_bodies_modified++;
3393 entry->hits += (unsigned)hits;
3397 entry = entry->next;
3400 privoxy_mutex_unlock(&filter_statistics_mutex);
3405 /*********************************************************************
3407 * Function : get_filter_statistics
3409 * Description : Gets the statistics for a filter.
3412 * 1 : filter = Name of the filter to get statistics for.
3413 * 2 : executions = Storage for the execution count.
3414 * 3 : response_bodies_modified = Storage for the number
3415 * of modified response bodies.
3416 * 4 : hits = Storage for the number of hits.
3420 *********************************************************************/
3421 void get_filter_statistics(const char *filter, unsigned long long *executions,
3422 unsigned long long *response_bodies_modified,
3423 unsigned long long *hits)
3425 struct filter_statistics_entry *entry;
3427 privoxy_mutex_lock(&filter_statistics_mutex);
3429 entry = filter_statistics;
3430 while (entry != NULL)
3432 if (!strcmp(entry->filter, filter))
3434 *executions = entry->executions;
3435 *response_bodies_modified = entry->response_bodies_modified;
3436 *hits = entry->hits;
3439 entry = entry->next;
3442 privoxy_mutex_unlock(&filter_statistics_mutex);
3447 struct block_statistics_entry
3450 unsigned long long count;
3452 struct block_statistics_entry *next;
3455 static struct block_statistics_entry *block_statistics = NULL;
3457 /*********************************************************************
3459 * Function : register_block_reason_for_statistics
3461 * Description : Registers a block reason so we can gather statistics
3462 * for it unless the block reason has already been
3463 * registered before.
3466 * 1 : block_reason = Block reason to register
3470 *********************************************************************/
3471 void register_block_reason_for_statistics(const char *block_reason)
3473 struct block_statistics_entry *entry;
3475 privoxy_mutex_lock(&block_reason_statistics_mutex);
3477 if (block_statistics == NULL)
3479 block_statistics = zalloc_or_die(sizeof(struct block_statistics_entry));
3480 entry = block_statistics;
3481 entry->block_reason = strdup_or_die(block_reason);
3482 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3485 entry = block_statistics;
3486 while (entry != NULL)
3488 if (!strcmp(entry->block_reason, block_reason))
3490 /* Already registered, nothing to do. */
3493 if (entry->next == NULL)
3495 entry->next = zalloc_or_die(sizeof(struct block_statistics_entry));
3496 entry->next->block_reason = strdup_or_die(block_reason);
3499 entry = entry->next;
3502 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3507 /*********************************************************************
3509 * Function : increment_block_reason_counter
3511 * Description : Updates the counter for a block reason.
3514 * 1 : block_reason = Block reason to count
3518 *********************************************************************/
3519 static void increment_block_reason_counter(const char *block_reason)
3521 struct block_statistics_entry *entry;
3523 privoxy_mutex_lock(&block_reason_statistics_mutex);
3525 entry = block_statistics;
3526 while (entry != NULL)
3528 if (!strcmp(entry->block_reason, block_reason))
3533 entry = entry->next;
3536 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3541 /*********************************************************************
3543 * Function : get_block_reason_count
3545 * Description : Gets number of times a block reason was used.
3548 * 1 : block_reason = Block reason to get statistics for.
3549 * 2 : count = Storage for the number of times the block
3554 *********************************************************************/
3555 void get_block_reason_count(const char *block_reason, unsigned long long *count)
3557 struct block_statistics_entry *entry;
3559 privoxy_mutex_lock(&block_reason_statistics_mutex);
3561 entry = block_statistics;
3562 while (entry != NULL)
3564 if (!strcmp(entry->block_reason, block_reason))
3566 *count = entry->count;
3569 entry = entry->next;
3572 privoxy_mutex_unlock(&block_reason_statistics_mutex);
3576 #endif /* def FEATURE_EXTENDED_STATISTICS */