1 const char filters_rcs[] = "$Id: filters.c,v 1.189 2014/10/18 11:26:18 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2014 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 #endif /* ndef __OS2__ */
49 #include <netinet/in.h>
52 #endif /* ndef _WIN32 */
56 #endif /* def __OS2__ */
64 #include "jbsockets.h"
70 #include "deanimate.h"
78 const char filters_h_rcs[] = FILTERS_H_VERSION;
80 typedef char *(*filter_function_ptr)();
81 static filter_function_ptr get_filter_function(const struct client_state *csp);
82 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
83 static jb_err prepare_for_filtering(struct client_state *csp);
87 /*********************************************************************
89 * Function : sockaddr_storage_to_ip
91 * Description : Access internal structure of sockaddr_storage
94 * 1 : addr = socket address
95 * 2 : ip = IP address as array of octets in network order
96 * (it points into addr)
97 * 3 : len = length of IP address in octets
98 * 4 : port = port number in network order;
100 * Returns : 0 = no errror; -1 otherwise.
102 *********************************************************************/
103 static int sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
104 uint8_t **ip, unsigned int *len,
112 switch (addr->ss_family)
122 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
126 *port = &((struct sockaddr_in *)addr)->sin_port;
137 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
141 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
146 /* Unsupported address family */
154 /*********************************************************************
156 * Function : match_sockaddr
158 * Description : Check whether address matches network (IP address and port)
161 * 1 : network = socket address of subnework
162 * 2 : netmask = network mask as socket address
163 * 3 : address = checked socket address against given network
165 * Returns : 0 = doesn't match; 1 = does match
167 *********************************************************************/
168 static int match_sockaddr(const struct sockaddr_storage *network,
169 const struct sockaddr_storage *netmask,
170 const struct sockaddr_storage *address)
172 uint8_t *network_addr, *netmask_addr, *address_addr;
173 unsigned int addr_len;
174 in_port_t *network_port, *netmask_port, *address_port;
177 if (network->ss_family != netmask->ss_family)
179 /* This should never happen */
180 assert(network->ss_family == netmask->ss_family);
181 log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
184 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
185 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
186 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
188 /* Check for family */
189 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
190 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
192 /* Map AF_INET6 V4MAPPED address into AF_INET */
196 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
197 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
199 /* Map AF_INET6 V4MAPPED network into AF_INET */
205 /* XXX: Port check is signaled in netmask */
206 if (*netmask_port && *network_port != *address_port)
211 /* TODO: Optimize by checking by words insted of octets */
212 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
214 if ((network_addr[i] & netmask_addr[i]) !=
215 (address_addr[i] & netmask_addr[i]))
223 #endif /* def HAVE_RFC2553 */
226 /*********************************************************************
228 * Function : block_acl
230 * Description : Block this request?
231 * Decide yes or no based on ACL file.
234 * 1 : dst = The proxy or gateway address this is going to.
235 * Or NULL to check all possible targets.
236 * 2 : csp = Current client state (buffers, headers, etc...)
237 * Also includes the client IP address.
239 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
241 *********************************************************************/
242 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
244 struct access_control_list *acl = csp->config->acl;
246 /* if not using an access control list, then permit the connection */
252 /* search the list */
257 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
259 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
265 /* Just want to check if they have any access */
266 if (acl->action == ACL_PERMIT)
278 * XXX: An undefined acl->dst is full of zeros and should be
279 * considered a wildcard address. sockaddr_storage_to_ip()
280 * fails on such destinations because of unknown sa_familly
281 * (glibc only?). However this test is not portable.
283 * So, we signal the acl->dst is wildcard in wildcard_dst.
286 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
288 ((dst->addr & acl->dst->mask) == acl->dst->addr)
289 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
293 if (acl->action == ACL_PERMIT)
311 /*********************************************************************
313 * Function : acl_addr
315 * Description : Called from `load_config' to parse an ACL address.
318 * 1 : aspec = String specifying ACL address.
319 * 2 : aca = struct access_control_addr to fill in.
321 * Returns : 0 => Ok, everything else is an error.
323 *********************************************************************/
324 int acl_addr(const char *aspec, struct access_control_addr *aca)
328 struct addrinfo hints, *result;
330 in_port_t *mask_port;
331 unsigned int addr_len;
334 #endif /* def HAVE_RFC2553 */
336 char *acl_spec = NULL;
339 /* XXX: Depend on ai_family */
347 * Use a temporary acl spec copy so we can log
348 * the unmodified original in case of parse errors.
350 acl_spec = strdup(aspec);
351 if (acl_spec == NULL)
353 /* XXX: This will be logged as parse error. */
357 if ((p = strchr(acl_spec, '/')) != NULL)
360 if (privoxy_isdigit(*p) == 0)
365 masklength = atoi(p);
368 if ((masklength < 0) ||
380 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
383 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
392 p = strchr(acl_spec, ':');
396 memset(&hints, 0, sizeof(struct addrinfo));
397 hints.ai_family = AF_UNSPEC;
398 hints.ai_socktype = SOCK_STREAM;
400 i = getaddrinfo(acl_spec, ((p) ? ++p : NULL), &hints, &result);
404 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
405 acl_spec, p, gai_strerror(i));
411 /* TODO: Allow multihomed hostnames */
412 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
413 freeaddrinfo(result);
420 port = strtol(p, &endptr, 10);
422 if (port <= 0 || port > 65535 || *endptr != '\0')
429 aca->port = (unsigned long)port;
431 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
434 if (aca->addr == INADDR_NONE)
436 /* XXX: This will be logged as parse error. */
439 #endif /* def HAVE_RFC2553 */
441 /* build the netmask */
443 /* Clip masklength according to current family. */
444 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
449 aca->mask.ss_family = aca->addr.ss_family;
450 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
457 /* ACL contains a port number, check ports in the future. */
462 * XXX: This could be optimized to operate on whole words instead
463 * of octets (128-bit CPU could do it in one iteration).
466 * Octets after prefix can be omitted because of
467 * previous initialization to zeros.
469 for (i = 0; (i < addr_len) && masklength; i++)
479 * XXX: This assumes MSB of octet is on the left side.
480 * This should be true for all architectures or solved
483 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
490 for (i=1; i <= masklength ; i++)
492 aca->mask |= (1U << (32 - i));
495 /* now mask off the host portion of the ip address
496 * (i.e. save on the network portion of the address).
498 aca->addr = aca->addr & aca->mask;
499 #endif /* def HAVE_RFC2553 */
504 #endif /* def FEATURE_ACL */
507 /*********************************************************************
509 * Function : connect_port_is_forbidden
511 * Description : Check to see if CONNECT requests to the destination
512 * port of this request are forbidden. The check is
513 * independend of the actual request method.
516 * 1 : csp = Current client state (buffers, headers, etc...)
518 * Returns : True if yes, false otherwise.
520 *********************************************************************/
521 int connect_port_is_forbidden(const struct client_state *csp)
523 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
524 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
529 /*********************************************************************
531 * Function : block_url
533 * Description : Called from `chat'. Check to see if we need to block this.
536 * 1 : csp = Current client state (buffers, headers, etc...)
538 * Returns : NULL => unblocked, else HTTP block response
540 *********************************************************************/
541 struct http_response *block_url(struct client_state *csp)
543 struct http_response *rsp;
544 const char *new_content_type = NULL;
547 * If it's not blocked, don't block it ;-)
549 if ((csp->action->flags & ACTION_BLOCK) == 0)
553 if (csp->action->flags & ACTION_REDIRECT)
555 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
558 * Else, prepare a response
560 if (NULL == (rsp = alloc_http_response()))
562 return cgi_error_memory();
566 * If it's an image-url, send back an image or redirect
567 * as specified by the relevant +image action
569 #ifdef FEATURE_IMAGE_BLOCKING
570 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
574 /* determine HOW images should be blocked */
575 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
577 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
579 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
582 /* and handle accordingly: */
583 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
585 rsp->status = strdup("403 Request blocked by Privoxy");
586 if (rsp->status == NULL)
588 free_http_response(rsp);
589 return cgi_error_memory();
591 rsp->body = bindup(image_pattern_data, image_pattern_length);
592 if (rsp->body == NULL)
594 free_http_response(rsp);
595 return cgi_error_memory();
597 rsp->content_length = image_pattern_length;
599 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
601 free_http_response(rsp);
602 return cgi_error_memory();
605 else if (0 == strcmpic(p, "blank"))
607 rsp->status = strdup("403 Request blocked by Privoxy");
608 if (rsp->status == NULL)
610 free_http_response(rsp);
611 return cgi_error_memory();
613 rsp->body = bindup(image_blank_data, image_blank_length);
614 if (rsp->body == NULL)
616 free_http_response(rsp);
617 return cgi_error_memory();
619 rsp->content_length = image_blank_length;
621 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
623 free_http_response(rsp);
624 return cgi_error_memory();
629 rsp->status = strdup("302 Local Redirect from Privoxy");
630 if (rsp->status == NULL)
632 free_http_response(rsp);
633 return cgi_error_memory();
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(" ");
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("200 Request blocked by Privoxy");
669 rsp->status = strdup("403 Request blocked by Privoxy");
672 if (rsp->status == NULL)
674 free_http_response(rsp);
675 return cgi_error_memory();
677 if (new_content_type != 0)
679 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
680 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
682 free_http_response(rsp);
683 return cgi_error_memory();
690 * Else, generate an HTML "blocked" message:
694 struct map * exports;
696 rsp->status = strdup("403 Request blocked by Privoxy");
697 if (rsp->status == NULL)
699 free_http_response(rsp);
700 return cgi_error_memory();
703 exports = default_exports(csp, NULL);
706 free_http_response(rsp);
707 return cgi_error_memory();
710 #ifdef FEATURE_FORCE_LOAD
711 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
713 * Export the force conditional block killer if
715 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
716 * - Privoxy is configured to enforce blocks, or
717 * - it's a CONNECT request and enforcing wouldn't work anyway.
719 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
720 || (0 == strcmpic(csp->http->gpc, "connect")))
721 #endif /* ndef FEATURE_FORCE_LOAD */
723 err = map_block_killer(exports, "force-support");
726 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
727 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
728 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
729 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
732 const char *block_reason;
733 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
735 block_reason = csp->action->string[ACTION_STRING_BLOCK];
739 assert(connect_port_is_forbidden(csp));
740 block_reason = "Forbidden CONNECT port.";
742 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
747 free_http_response(rsp);
748 return cgi_error_memory();
751 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
754 free_http_response(rsp);
755 return cgi_error_memory();
758 rsp->crunch_reason = BLOCKED;
760 return finish_http_response(csp, rsp);
766 /*********************************************************************
768 * Function : trust_url FIXME: I should be called distrust_url
770 * Description : Calls is_untrusted_url to determine if the URL is trusted
771 * and if not, returns a HTTP 403 response with a reject message.
774 * 1 : csp = Current client state (buffers, headers, etc...)
776 * Returns : NULL => trusted, else http_response.
778 *********************************************************************/
779 struct http_response *trust_url(struct client_state *csp)
781 struct http_response *rsp;
782 struct map * exports;
783 char buf[BUFFER_SIZE];
785 struct pattern_spec **tl;
786 struct pattern_spec *t;
790 * Don't bother to work on trusted URLs
792 if (!is_untrusted_url(csp))
798 * Else, prepare a response:
800 if (NULL == (rsp = alloc_http_response()))
802 return cgi_error_memory();
805 rsp->status = strdup("403 Request blocked by Privoxy");
806 exports = default_exports(csp, NULL);
807 if (exports == NULL || rsp->status == NULL)
809 free_http_response(rsp);
810 return cgi_error_memory();
814 * Export the protocol, host, port, and referrer information
816 err = map(exports, "hostport", 1, csp->http->hostport, 1);
817 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
818 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
820 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
822 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
826 if (!err) err = map(exports, "referrer", 1, "none set", 1);
832 free_http_response(rsp);
833 return cgi_error_memory();
837 * Export the trust list
840 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
842 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
843 string_append(&p, buf);
845 err = map(exports, "trusted-referrers", 1, p, 0);
850 free_http_response(rsp);
851 return cgi_error_memory();
855 * Export the trust info, if available
857 if (csp->config->trust_info->first)
859 struct list_entry *l;
862 for (l = csp->config->trust_info->first; l ; l = l->next)
864 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
865 string_append(&p, buf);
867 err = map(exports, "trust-info", 1, p, 0);
871 err = map_block_killer(exports, "have-trust-info");
877 free_http_response(rsp);
878 return cgi_error_memory();
882 * Export the force conditional block killer if
884 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
885 * - Privoxy is configured to enforce blocks, or
886 * - it's a CONNECT request and enforcing wouldn't work anyway.
888 #ifdef FEATURE_FORCE_LOAD
889 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
890 || (0 == strcmpic(csp->http->gpc, "connect")))
892 err = map_block_killer(exports, "force-support");
896 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
898 #else /* ifndef FEATURE_FORCE_LOAD */
899 err = map_block_killer(exports, "force-support");
900 #endif /* ndef FEATURE_FORCE_LOAD */
905 free_http_response(rsp);
906 return cgi_error_memory();
912 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
915 free_http_response(rsp);
916 return cgi_error_memory();
918 rsp->crunch_reason = UNTRUSTED;
920 return finish_http_response(csp, rsp);
922 #endif /* def FEATURE_TRUST */
925 /*********************************************************************
927 * Function : compile_dynamic_pcrs_job_list
929 * Description : Compiles a dynamic pcrs job list (one with variables
930 * resolved at request time)
933 * 1 : csp = Current client state (buffers, headers, etc...)
934 * 2 : b = The filter list to compile
936 * Returns : NULL in case of errors, otherwise the
939 *********************************************************************/
940 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
942 struct list_entry *pattern;
943 pcrs_job *job_list = NULL;
944 pcrs_job *dummy = NULL;
945 pcrs_job *lastjob = NULL;
948 const struct pcrs_variable variables[] =
950 {"url", csp->http->url, 1},
951 {"path", csp->http->path, 1},
952 {"host", csp->http->host, 1},
953 {"origin", csp->ip_addr_str, 1},
957 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
959 assert(pattern->str != NULL);
961 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
964 log_error(LOG_LEVEL_ERROR,
965 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
966 pattern->str, b->name, error, pcrs_strerror(error));
971 if (error == PCRS_WARN_TRUNCATION)
973 log_error(LOG_LEVEL_ERROR,
974 "At least one of the variables in \'%s\' had to "
975 "be truncated before compilation", pattern->str);
977 if (job_list == NULL)
983 lastjob->next = dummy;
993 /*********************************************************************
995 * Function : rewrite_url
997 * Description : Rewrites a URL with a single pcrs command
998 * and returns the result if it differs from the
999 * original and isn't obviously invalid.
1002 * 1 : old_url = URL to rewrite.
1003 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1006 * Returns : NULL if the pcrs_command didn't change the url, or
1007 * the result of the modification.
1009 *********************************************************************/
1010 char *rewrite_url(char *old_url, const char *pcrs_command)
1012 char *new_url = NULL;
1016 assert(pcrs_command);
1018 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1022 log_error(LOG_LEVEL_REDIRECTS,
1023 "pcrs command \"%s\" didn't change \"%s\".",
1024 pcrs_command, old_url);
1029 log_error(LOG_LEVEL_REDIRECTS,
1030 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1031 pcrs_command, old_url, pcrs_strerror(hits));
1034 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1036 log_error(LOG_LEVEL_ERROR,
1037 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1038 "but the result doesn't look like a valid URL and will be ignored.",
1039 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1044 log_error(LOG_LEVEL_REDIRECTS,
1045 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1046 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1054 #ifdef FEATURE_FAST_REDIRECTS
1055 /*********************************************************************
1057 * Function : get_last_url
1059 * Description : Search for the last URL inside a string.
1060 * If the string already is a URL, it will
1061 * be the first URL found.
1064 * 1 : subject = the string to check
1065 * 2 : redirect_mode = +fast-redirect{} mode
1067 * Returns : NULL if no URL was found, or
1068 * the last URL found.
1070 *********************************************************************/
1071 char *get_last_url(char *subject, const char *redirect_mode)
1073 char *new_url = NULL;
1077 assert(redirect_mode);
1079 subject = strdup(subject);
1080 if (subject == NULL)
1082 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1086 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1088 char *url_segment = NULL;
1089 char **url_segments;
1090 size_t max_segments;
1093 log_error(LOG_LEVEL_REDIRECTS,
1094 "Checking \"%s\" for encoded redirects.", subject);
1097 * Check each parameter in the URL separately.
1098 * Sectionize the URL at "?" and "&",
1099 * go backwards through the segments, URL-decode them
1100 * and look for a URL in the decoded result.
1101 * Stop the search after the first match.
1103 * XXX: This estimate is guaranteed to be high enough as we
1104 * let ssplit() ignore empty fields, but also a bit wasteful.
1106 max_segments = strlen(subject) / 2;
1107 url_segments = malloc(max_segments * sizeof(char *));
1109 if (NULL == url_segments)
1111 log_error(LOG_LEVEL_ERROR,
1112 "Out of memory while decoding URL: %s", subject);
1117 segments = ssplit(subject, "?&", url_segments, max_segments);
1119 while (segments-- > 0)
1121 char *dtoken = url_decode(url_segments[segments]);
1124 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1127 url_segment = strstr(dtoken, "http://");
1128 if (NULL == url_segment)
1130 url_segment = strstr(dtoken, "https://");
1132 if (NULL != url_segment)
1134 url_segment = strdup_or_die(url_segment);
1141 freez(url_segments);
1143 if (url_segment == NULL)
1147 subject = url_segment;
1151 /* Look for a URL inside this one, without decoding anything. */
1152 log_error(LOG_LEVEL_REDIRECTS,
1153 "Checking \"%s\" for unencoded redirects.", subject);
1157 * Find the last URL encoded in the request
1160 while ((tmp = strstr(tmp, "http://")) != NULL)
1164 tmp = (new_url != NULL) ? new_url : subject;
1165 while ((tmp = strstr(tmp, "https://")) != NULL)
1170 if ((new_url != NULL)
1171 && ( (new_url != subject)
1172 || (0 == strncmpic(subject, "http://", 7))
1173 || (0 == strncmpic(subject, "https://", 8))
1177 * Return new URL if we found a redirect
1178 * or if the subject already was a URL.
1180 * The second case makes sure that we can
1181 * chain get_last_url after another redirection check
1182 * (like rewrite_url) without losing earlier redirects.
1184 new_url = strdup(new_url);
1193 #endif /* def FEATURE_FAST_REDIRECTS */
1196 /*********************************************************************
1198 * Function : redirect_url
1200 * Description : Checks if Privoxy should answer the request with
1201 * a HTTP redirect and generates the redirect if
1205 * 1 : csp = Current client state (buffers, headers, etc...)
1207 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1209 *********************************************************************/
1210 struct http_response *redirect_url(struct client_state *csp)
1212 struct http_response *rsp;
1213 #ifdef FEATURE_FAST_REDIRECTS
1215 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1216 * as compile-time option? The user can easily disable
1217 * it in his action file.
1219 char * redirect_mode;
1220 #endif /* def FEATURE_FAST_REDIRECTS */
1221 char *old_url = NULL;
1222 char *new_url = NULL;
1223 char *redirection_string;
1225 if ((csp->action->flags & ACTION_REDIRECT))
1227 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1230 * If the redirection string begins with 's',
1231 * assume it's a pcrs command, otherwise treat it as
1232 * properly formatted URL and use it for the redirection
1235 * According to (the now obsolete) RFC 2616 section 14.30
1236 * the URL has to be absolute and if the user tries:
1237 * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
1238 * she would get undefined results anyway.
1240 * RFC 7231 7.1.2 actually allows relative references,
1241 * but those start with a leading slash (RFC 3986 4.2) and
1242 * thus can't be mistaken for pcrs commands either.
1245 if (*redirection_string == 's')
1247 old_url = csp->http->url;
1248 new_url = rewrite_url(old_url, redirection_string);
1252 log_error(LOG_LEVEL_REDIRECTS,
1253 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1254 redirection_string);
1255 new_url = strdup(redirection_string);
1259 #ifdef FEATURE_FAST_REDIRECTS
1260 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1262 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1265 * If it exists, use the previously rewritten URL as input
1266 * otherwise just use the old path.
1268 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1269 new_url = get_last_url(old_url, redirect_mode);
1274 * Disable redirect checkers, so that they
1275 * will be only run more than once if the user
1276 * also enables them through tags.
1278 * From a performance point of view
1279 * it doesn't matter, but the duplicated
1280 * log messages are annoying.
1282 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1283 #endif /* def FEATURE_FAST_REDIRECTS */
1284 csp->action->flags &= ~ACTION_REDIRECT;
1286 /* Did any redirect action trigger? */
1289 if (url_requires_percent_encoding(new_url))
1292 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1293 strlen(new_url), new_url);
1294 encoded_url = percent_encode_url(new_url);
1296 if (encoded_url == NULL)
1298 return cgi_error_memory();
1300 new_url = encoded_url;
1301 assert(FALSE == url_requires_percent_encoding(new_url));
1304 if (0 == strcmpic(new_url, csp->http->url))
1306 log_error(LOG_LEVEL_ERROR,
1307 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1308 csp->http->url, new_url);
1313 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1315 if (NULL == (rsp = alloc_http_response()))
1318 return cgi_error_memory();
1321 if (enlist_unique_header(rsp->headers, "Location", new_url)
1322 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))))
1325 free_http_response(rsp);
1326 return cgi_error_memory();
1328 rsp->crunch_reason = REDIRECTED;
1331 return finish_http_response(csp, rsp);
1335 /* Only reached if no redirect is required */
1341 #ifdef FEATURE_IMAGE_BLOCKING
1342 /*********************************************************************
1344 * Function : is_imageurl
1346 * Description : Given a URL, decide whether it is an image or not,
1347 * using either the info from a previous +image action
1348 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1349 * is MSIE and not on a Mac, tell from the browser's accept
1353 * 1 : csp = Current client state (buffers, headers, etc...)
1355 * Returns : True (nonzero) if URL is an image, false (0)
1358 *********************************************************************/
1359 int is_imageurl(const struct client_state *csp)
1361 #ifdef FEATURE_IMAGE_DETECT_MSIE
1364 tmp = get_header_value(csp->headers, "User-Agent:");
1365 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1367 tmp = get_header_value(csp->headers, "Accept:");
1368 if (tmp && strstr(tmp, "image/gif"))
1370 /* Client will accept HTML. If this seems counterintuitive,
1380 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1382 return ((csp->action->flags & ACTION_IMAGE) != 0);
1385 #endif /* def FEATURE_IMAGE_BLOCKING */
1388 #ifdef FEATURE_TRUST
1389 /*********************************************************************
1391 * Function : is_untrusted_url
1393 * Description : Should we "distrust" this URL (and block it)?
1395 * Yes if it matches a line in the trustfile, or if the
1396 * referrer matches a line starting with "+" in the
1401 * 1 : csp = Current client state (buffers, headers, etc...)
1403 * Returns : 0 => trusted, 1 => untrusted
1405 *********************************************************************/
1406 int is_untrusted_url(const struct client_state *csp)
1408 struct file_list *fl;
1409 struct block_spec *b;
1410 struct pattern_spec **trusted_url;
1411 struct http_request rhttp[1];
1412 const char * referer;
1416 * If we don't have a trustlist, we trust everybody
1418 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1423 memset(rhttp, '\0', sizeof(*rhttp));
1426 * Do we trust the request URL itself?
1428 for (b = b->next; b ; b = b->next)
1430 if (url_match(b->url, csp->http))
1436 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1438 /* no referrer was supplied */
1444 * If not, do we maybe trust its referrer?
1446 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1452 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1454 if (url_match(*trusted_url, rhttp))
1456 /* if the URL's referrer is from a trusted referrer, then
1457 * add the target spec to the trustfile as an unblocked
1458 * domain and return 0 (which means it's OK).
1463 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1467 char * new_entry = strdup("~");
1469 string_append(&new_entry, csp->http->hostport);
1471 path = csp->http->path;
1472 if ( (path[0] == '/')
1474 && ((path_end = strchr(path + 2, '/')) != NULL))
1476 /* since this path points into a user's home space
1477 * be sure to include this spec in the trustfile.
1479 long path_len = path_end - path; /* save offset */
1480 path = strdup(path); /* Copy string */
1483 path_end = path + path_len; /* regenerate ptr to new buffer */
1484 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1486 string_join(&new_entry, path);
1490 * Give a reason for generating this entry.
1492 string_append(&new_entry, " # Trusted referrer was: ");
1493 string_append(&new_entry, referer);
1495 if (new_entry != NULL)
1497 if (-1 == fprintf(fp, "%s\n", new_entry))
1499 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1500 new_entry, csp->config->trustfile);
1506 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1507 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1514 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1515 csp->http->hostport, csp->config->trustfile);
1523 #endif /* def FEATURE_TRUST */
1526 /*********************************************************************
1528 * Function : get_filter
1530 * Description : Get a filter with a given name and type.
1531 * Note that taggers are filters, too.
1534 * 1 : csp = Current client state (buffers, headers, etc...)
1535 * 2 : requested_name = Name of the content filter to get
1536 * 3 : requested_type = Type of the filter to tagger to lookup
1538 * Returns : A pointer to the requested filter
1539 * or NULL if the filter wasn't found
1541 *********************************************************************/
1542 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1543 const char *requested_name,
1544 enum filter_type requested_type)
1547 struct re_filterfile_spec *b;
1548 struct file_list *fl;
1550 for (i = 0; i < MAX_AF_FILES; i++)
1553 if ((NULL == fl) || (NULL == fl->f))
1556 * Either there are no filter files left or this
1557 * filter file just contains no valid filters.
1559 * Continue to be sure we don't miss valid filter
1560 * files that are chained after empty or invalid ones.
1565 for (b = fl->f; b != NULL; b = b->next)
1567 if (b->type != requested_type)
1569 /* The callers isn't interested in this filter type. */
1572 if (strcmp(b->name, requested_name) == 0)
1574 /* The requested filter has been found. Abort search. */
1580 /* No filter with the given name and type exists. */
1586 /*********************************************************************
1588 * Function : pcrs_filter_response
1590 * Description : Execute all text substitutions from all applying
1591 * +filter actions on the text buffer that's been
1592 * accumulated in csp->iob->buf.
1595 * 1 : csp = Current client state (buffers, headers, etc...)
1597 * Returns : a pointer to the (newly allocated) modified buffer.
1598 * or NULL if there were no hits or something went wrong
1600 *********************************************************************/
1601 static char *pcrs_filter_response(struct client_state *csp)
1604 size_t size, prev_size;
1610 struct re_filterfile_spec *b;
1611 struct list_entry *filtername;
1616 if (csp->iob->cur >= csp->iob->eod)
1621 if (filters_available(csp) == FALSE)
1623 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1624 "content filtering enabled, but no content filters available.");
1628 size = (size_t)(csp->iob->eod - csp->iob->cur);
1629 old = csp->iob->cur;
1632 * For all applying +filter actions, look if a filter by that
1633 * name exists and if yes, execute it's pcrs_joblist on the
1636 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1637 filtername != NULL; filtername = filtername->next)
1639 int current_hits = 0; /* Number of hits caused by this filter */
1640 int job_number = 0; /* Which job we're currently executing */
1641 int job_hits = 0; /* How many hits the current job caused */
1644 b = get_filter(csp, filtername->str, FT_CONTENT_FILTER);
1650 joblist = b->joblist;
1652 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1654 if (NULL == joblist)
1656 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1661 /* Apply all jobs from the joblist */
1662 for (job = joblist; NULL != job; job = job->next)
1665 job_hits = pcrs_execute(job, old, size, &new, &size);
1670 * That went well. Continue filtering
1671 * and use the result of this job as
1672 * input for the next one.
1674 current_hits += job_hits;
1675 if (old != csp->iob->cur)
1684 * This job caused an unexpected error. Inform the user
1685 * and skip the rest of the jobs in this filter. We could
1686 * continue with the next job, but usually the jobs
1687 * depend on each other or are similar enough to
1688 * fail for the same reason.
1690 * At the moment our pcrs expects the error codes of pcre 3.4,
1691 * but newer pcre versions can return additional error codes.
1692 * As a result pcrs_strerror()'s error message might be
1693 * "Unknown error ...", therefore we print the numerical value
1696 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1697 * should we use LOG_LEVEL_RE_FILTER instead?
1699 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1700 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1705 if (b->dynamic) pcrs_free_joblist(joblist);
1707 log_error(LOG_LEVEL_RE_FILTER,
1708 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1709 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1711 hits += current_hits;
1715 * If there were no hits, destroy our copy and let
1716 * chat() use the original in csp->iob
1724 csp->flags |= CSP_FLAG_MODIFIED;
1725 csp->content_length = size;
1726 clear_iob(csp->iob);
1733 #ifdef FEATURE_EXTERNAL_FILTERS
1734 /*********************************************************************
1736 * Function : get_external_filter
1738 * Description : Lookup the code to execute for an external filter.
1739 * Masks the misuse of the re_filterfile_spec.
1742 * 1 : csp = Current client state (buffers, headers, etc...)
1743 * 2 : name = Name of the content filter to get
1745 * Returns : A pointer to the requested code
1746 * or NULL if the filter wasn't found
1748 *********************************************************************/
1749 static const char *get_external_filter(const struct client_state *csp,
1752 struct re_filterfile_spec *external_filter;
1754 external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
1755 if (external_filter == NULL)
1757 log_error(LOG_LEVEL_FATAL,
1758 "Didn't find stuff to execute for external filter: %s",
1762 return external_filter->patterns->first->str;
1767 /*********************************************************************
1769 * Function : set_privoxy_variables
1771 * Description : Sets a couple of privoxy-specific environment variables
1774 * 1 : csp = Current client state (buffers, headers, etc...)
1778 *********************************************************************/
1779 static void set_privoxy_variables(const struct client_state *csp)
1786 { "PRIVOXY_URL", csp->http->url },
1787 { "PRIVOXY_PATH", csp->http->path },
1788 { "PRIVOXY_HOST", csp->http->host },
1789 { "PRIVOXY_ORIGIN", csp->ip_addr_str },
1792 for (i = 0; i < SZ(env); i++)
1794 if (setenv(env[i].name, env[i].value, 1))
1796 log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
1797 env[i].name, env[i].value);
1803 /*********************************************************************
1805 * Function : execute_external_filter
1807 * Description : Pipe content into external filter and return the output
1810 * 1 : csp = Current client state (buffers, headers, etc...)
1811 * 2 : name = Name of the external filter to execute
1812 * 3 : content = The original content to filter
1813 * 4 : size = The size of the content buffer
1815 * Returns : a pointer to the (newly allocated) modified buffer.
1816 * or NULL if there were no hits or something went wrong
1818 *********************************************************************/
1819 static char *execute_external_filter(const struct client_state *csp,
1820 const char *name, char *content, size_t *size)
1823 char file_name[FILENAME_MAX];
1825 char *filter_output;
1829 const char *external_filter;
1831 if (csp->config->temporary_directory == NULL)
1833 log_error(LOG_LEVEL_ERROR,
1834 "No temporary-directory configured. Can't execute filter: %s",
1839 external_filter = get_external_filter(csp, name);
1841 if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
1842 "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
1844 log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
1848 fd = mkstemp(file_name);
1851 log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
1855 fp = fdopen(fd, "w");
1858 log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
1864 * The size may be zero if a previous filter discarded everything.
1866 * This isn't necessary unintentional, so we just don't try
1867 * to fwrite() nothing and let the user deal with the rest.
1869 if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
1871 log_error(LOG_LEVEL_ERROR, "fwrite(..., %d, 1, ..) failed: %E", *size);
1878 if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
1880 log_error(LOG_LEVEL_ERROR,
1881 "temporary-directory or external filter path too long");
1886 log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
1889 * The locking is necessary to prevent other threads
1890 * from overwriting the environment variables before
1891 * the popen fork. Afterwards this no longer matters.
1893 privoxy_mutex_lock(&external_filter_mutex);
1894 set_privoxy_variables(csp);
1895 fp = popen(cmd, "r");
1896 privoxy_mutex_unlock(&external_filter_mutex);
1899 log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
1904 filter_output = malloc_or_die(*size);
1907 while (!feof(fp) && !ferror(fp))
1910 /* Could be bigger ... */
1911 enum { READ_LENGTH = 2048 };
1913 if (new_size + READ_LENGTH >= *size)
1917 /* Could be considered wasteful if the content is 'large'. */
1918 *size = (*size != 0) ? *size * 2 : READ_LENGTH;
1920 p = realloc(filter_output, *size);
1923 log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
1924 "external filter output. Using what we got so far.");
1929 len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
1939 log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
1943 log_error(LOG_LEVEL_RE_FILTER,
1944 "Executing '%s' resulted in return value %d. "
1945 "Read %d of up to %d bytes.", name, (ret >> 8), new_size, *size);
1951 return filter_output;
1954 #endif /* def FEATURE_EXTERNAL_FILTERS */
1957 /*********************************************************************
1959 * Function : gif_deanimate_response
1961 * Description : Deanimate the GIF image that has been accumulated in
1962 * csp->iob->buf, set csp->content_length to the modified
1963 * size and raise the CSP_FLAG_MODIFIED flag.
1966 * 1 : csp = Current client state (buffers, headers, etc...)
1968 * Returns : a pointer to the (newly allocated) modified buffer.
1969 * or NULL in case something went wrong.
1971 *********************************************************************/
1972 static char *gif_deanimate_response(struct client_state *csp)
1974 struct binbuffer *in, *out;
1978 size = (size_t)(csp->iob->eod - csp->iob->cur);
1980 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1981 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1983 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1987 in->buffer = csp->iob->cur;
1990 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1992 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1999 if ((int)size == out->offset)
2001 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
2005 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
2007 csp->content_length = out->offset;
2008 csp->flags |= CSP_FLAG_MODIFIED;
2018 /*********************************************************************
2020 * Function : get_filter_function
2022 * Description : Decides which content filter function has
2023 * to be applied (if any). Only considers functions
2024 * for internal filters which are mutually-exclusive.
2027 * 1 : csp = Current client state (buffers, headers, etc...)
2029 * Returns : The content filter function to run, or
2030 * NULL if no content filter is active
2032 *********************************************************************/
2033 static filter_function_ptr get_filter_function(const struct client_state *csp)
2035 filter_function_ptr filter_function = NULL;
2038 * Choose the applying filter function based on
2039 * the content type and action settings.
2041 if ((csp->content_type & CT_TEXT) &&
2042 (csp->rlist != NULL) &&
2043 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2045 filter_function = pcrs_filter_response;
2047 else if ((csp->content_type & CT_GIF) &&
2048 (csp->action->flags & ACTION_DEANIMATE))
2050 filter_function = gif_deanimate_response;
2053 return filter_function;
2057 /*********************************************************************
2059 * Function : remove_chunked_transfer_coding
2061 * Description : In-situ remove the "chunked" transfer coding as defined
2062 * in RFC 7230 4.1 from a buffer. XXX: The implementation
2063 * is neither complete nor compliant (TODO #129).
2066 * 1 : buffer = Pointer to the text buffer
2067 * 2 : size = In: Number of bytes to be processed,
2068 * Out: Number of bytes after de-chunking.
2069 * (undefined in case of errors)
2071 * Returns : JB_ERR_OK for success,
2072 * JB_ERR_PARSE otherwise
2074 *********************************************************************/
2075 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2078 unsigned int chunksize = 0;
2079 char *from_p, *to_p;
2082 from_p = to_p = buffer;
2084 if (sscanf(buffer, "%x", &chunksize) != 1)
2086 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2087 return JB_ERR_PARSE;
2090 while (chunksize > 0U)
2092 if (NULL == (from_p = strstr(from_p, "\r\n")))
2094 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2095 return JB_ERR_PARSE;
2098 if (chunksize >= *size - newsize)
2100 log_error(LOG_LEVEL_ERROR,
2101 "Chunk size %u exceeds buffered data left. "
2102 "Already digested %u of %u buffered bytes.",
2103 chunksize, (unsigned int)newsize, (unsigned int)*size);
2104 return JB_ERR_PARSE;
2106 newsize += chunksize;
2109 memmove(to_p, from_p, (size_t) chunksize);
2110 to_p = buffer + newsize;
2111 from_p += chunksize + 2;
2113 if (sscanf(from_p, "%x", &chunksize) != 1)
2115 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2120 /* XXX: Should get its own loglevel. */
2121 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
2130 /*********************************************************************
2132 * Function : prepare_for_filtering
2134 * Description : If necessary, de-chunks and decompresses
2135 * the content so it can get filterd.
2138 * 1 : csp = Current client state (buffers, headers, etc...)
2140 * Returns : JB_ERR_OK for success,
2141 * JB_ERR_PARSE otherwise
2143 *********************************************************************/
2144 static jb_err prepare_for_filtering(struct client_state *csp)
2146 jb_err err = JB_ERR_OK;
2149 * If the body has a "chunked" transfer-encoding,
2150 * get rid of it, adjusting size and iob->eod
2152 if (csp->flags & CSP_FLAG_CHUNKED)
2154 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2156 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2157 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2158 if (JB_ERR_OK == err)
2160 csp->iob->eod = csp->iob->cur + size;
2161 csp->flags |= CSP_FLAG_MODIFIED;
2165 return JB_ERR_PARSE;
2171 * If the body has a supported transfer-encoding,
2172 * decompress it, adjusting size and iob->eod.
2174 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
2176 if (0 == csp->iob->eod - csp->iob->cur)
2178 /* Nothing left after de-chunking. */
2182 err = decompress_iob(csp);
2184 if (JB_ERR_OK == err)
2186 csp->flags |= CSP_FLAG_MODIFIED;
2187 csp->content_type &= ~CT_TABOO;
2192 * Unset CT_GZIP and CT_DEFLATE to remember not
2193 * to modify the Content-Encoding header later.
2195 csp->content_type &= ~CT_GZIP;
2196 csp->content_type &= ~CT_DEFLATE;
2205 /*********************************************************************
2207 * Function : execute_content_filters
2209 * Description : Executes a given content filter.
2212 * 1 : csp = Current client state (buffers, headers, etc...)
2214 * Returns : Pointer to the modified buffer, or
2215 * NULL if filtering failed or wasn't necessary.
2217 *********************************************************************/
2218 char *execute_content_filters(struct client_state *csp)
2221 filter_function_ptr content_filter;
2223 assert(content_filters_enabled(csp->action));
2225 if (0 == csp->iob->eod - csp->iob->cur)
2228 * No content (probably status code 301, 302 ...),
2229 * no filtering necessary.
2234 if (JB_ERR_OK != prepare_for_filtering(csp))
2237 * failed to de-chunk or decompress.
2242 if (0 == csp->iob->eod - csp->iob->cur)
2245 * Clown alarm: chunked and/or compressed nothing delivered.
2250 content_filter = get_filter_function(csp);
2251 content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
2253 #ifdef FEATURE_EXTERNAL_FILTERS
2254 if ((csp->content_type & CT_TEXT) &&
2255 (csp->rlist != NULL) &&
2256 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
2258 struct list_entry *filtername;
2259 size_t size = (size_t)csp->content_length;
2261 if (content == NULL)
2263 content = csp->iob->cur;
2264 size = (size_t)(csp->iob->eod - csp->iob->cur);
2267 for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
2268 filtername ; filtername = filtername->next)
2270 char *result = execute_external_filter(csp, filtername->str, content, &size);
2273 if (content != csp->iob->cur)
2280 csp->flags |= CSP_FLAG_MODIFIED;
2281 csp->content_length = size;
2283 #endif /* def FEATURE_EXTERNAL_FILTERS */
2290 /*********************************************************************
2292 * Function : get_url_actions
2294 * Description : Gets the actions for this URL.
2297 * 1 : csp = Current client state (buffers, headers, etc...)
2298 * 2 : http = http_request request for blocked URLs
2302 *********************************************************************/
2303 void get_url_actions(struct client_state *csp, struct http_request *http)
2305 struct file_list *fl;
2306 struct url_actions *b;
2309 init_current_action(csp->action);
2311 for (i = 0; i < MAX_AF_FILES; i++)
2313 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2318 apply_url_actions(csp->action, http, b);
2325 /*********************************************************************
2327 * Function : apply_url_actions
2329 * Description : Applies a list of URL actions.
2332 * 1 : action = Destination.
2333 * 2 : http = Current URL
2334 * 3 : b = list of URL actions to apply
2338 *********************************************************************/
2339 void apply_url_actions(struct current_action_spec *action,
2340 struct http_request *http,
2341 struct url_actions *b)
2345 /* Should never happen */
2349 for (b = b->next; NULL != b; b = b->next)
2351 if (url_match(b->url, http))
2353 merge_current_action(action, b->action);
2359 /*********************************************************************
2361 * Function : get_forward_override_settings
2363 * Description : Returns forward settings as specified with the
2364 * forward-override{} action. forward-override accepts
2365 * forward lines similar to the one used in the
2366 * configuration file, but without the URL pattern.
2372 * in the configuration file can be replaced with
2373 * the action section:
2375 * {+forward-override{forward .}}
2379 * 1 : csp = Current client state (buffers, headers, etc...)
2381 * Returns : Pointer to forwarding structure in case of success.
2382 * Invalid syntax is fatal.
2384 *********************************************************************/
2385 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2387 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2388 char forward_settings[BUFFER_SIZE];
2389 char *http_parent = NULL;
2390 /* variable names were chosen for consistency reasons. */
2391 struct forward_spec *fwd = NULL;
2395 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2396 /* Should be enforced by load_one_actions_file() */
2397 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2399 /* Create a copy ssplit can modify */
2400 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2402 if (NULL != csp->fwd)
2405 * XXX: Currently necessary to prevent memory
2406 * leaks when the show-url-info cgi page is visited.
2408 unload_forward_spec(csp->fwd);
2412 * allocate a new forward node, valid only for
2413 * the lifetime of this request. Save its location
2414 * in csp as well, so sweep() can free it later on.
2416 fwd = csp->fwd = zalloc(sizeof(*fwd));
2419 log_error(LOG_LEVEL_FATAL,
2420 "can't allocate memory for forward-override{%s}", forward_override_line);
2421 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2425 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2426 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2428 fwd->type = SOCKS_NONE;
2430 /* Parse the parent HTTP proxy host:port */
2431 http_parent = vec[1];
2434 else if (vec_count == 3)
2436 char *socks_proxy = NULL;
2438 if (!strcasecmp(vec[0], "forward-socks4"))
2440 fwd->type = SOCKS_4;
2441 socks_proxy = vec[1];
2443 else if (!strcasecmp(vec[0], "forward-socks4a"))
2445 fwd->type = SOCKS_4A;
2446 socks_proxy = vec[1];
2448 else if (!strcasecmp(vec[0], "forward-socks5"))
2450 fwd->type = SOCKS_5;
2451 socks_proxy = vec[1];
2453 else if (!strcasecmp(vec[0], "forward-socks5t"))
2455 fwd->type = SOCKS_5T;
2456 socks_proxy = vec[1];
2459 if (NULL != socks_proxy)
2461 /* Parse the SOCKS proxy host[:port] */
2462 fwd->gateway_port = 1080;
2463 parse_forwarder_address(socks_proxy,
2464 &fwd->gateway_host, &fwd->gateway_port);
2466 http_parent = vec[2];
2470 if (NULL == http_parent)
2472 log_error(LOG_LEVEL_FATAL,
2473 "Invalid forward-override syntax in: %s", forward_override_line);
2474 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2477 /* Parse http forwarding settings */
2478 if (strcmp(http_parent, ".") != 0)
2480 fwd->forward_port = 8000;
2481 parse_forwarder_address(http_parent,
2482 &fwd->forward_host, &fwd->forward_port);
2485 assert (NULL != fwd);
2487 log_error(LOG_LEVEL_CONNECT,
2488 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2494 /*********************************************************************
2496 * Function : forward_url
2498 * Description : Should we forward this to another proxy?
2501 * 1 : csp = Current client state (buffers, headers, etc...)
2502 * 2 : http = http_request request for current URL
2504 * Returns : Pointer to forwarding information.
2506 *********************************************************************/
2507 const struct forward_spec *forward_url(struct client_state *csp,
2508 const struct http_request *http)
2510 static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
2511 struct forward_spec *fwd = csp->config->forward;
2513 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2515 return get_forward_override_settings(csp);
2525 if (url_match(fwd->url, http))
2536 /*********************************************************************
2538 * Function : direct_response
2540 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2541 * request and if so, return a HTTP 501 to the client.
2543 * FIXME: I have a stupid name and I should handle the
2544 * requests properly. Still, what we do here is rfc-
2545 * compliant, whereas ignoring or forwarding are not.
2548 * 1 : csp = Current client state (buffers, headers, etc...)
2550 * Returns : http_response if , NULL if nonmatch or handler fail
2552 *********************************************************************/
2553 struct http_response *direct_response(struct client_state *csp)
2555 struct http_response *rsp;
2556 struct list_entry *p;
2558 if ((0 == strcmpic(csp->http->gpc, "trace"))
2559 || (0 == strcmpic(csp->http->gpc, "options")))
2561 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2563 if (!strncmpic(p->str, "Max-Forwards:", 13))
2565 unsigned int max_forwards;
2568 * If it's a Max-Forwards value of zero,
2569 * we have to intercept the request.
2571 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2574 * FIXME: We could handle at least TRACE here,
2575 * but that would require a verbatim copy of
2576 * the request which we don't have anymore
2578 log_error(LOG_LEVEL_HEADER,
2579 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2582 /* Get mem for response or fail*/
2583 if (NULL == (rsp = alloc_http_response()))
2585 return cgi_error_memory();
2588 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2590 free_http_response(rsp);
2591 return cgi_error_memory();
2595 rsp->crunch_reason = UNSUPPORTED;
2597 return(finish_http_response(csp, rsp));
2606 /*********************************************************************
2608 * Function : content_requires_filtering
2610 * Description : Checks whether there are any content filters
2611 * enabled for the current request and if they
2612 * can actually be applied..
2615 * 1 : csp = Current client state (buffers, headers, etc...)
2617 * Returns : TRUE for yes, FALSE otherwise
2619 *********************************************************************/
2620 int content_requires_filtering(struct client_state *csp)
2622 if ((csp->content_type & CT_TABOO)
2623 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2629 * Are we enabling text mode by force?
2631 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2634 * Do we really have to?
2636 if (csp->content_type & CT_TEXT)
2638 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2642 csp->content_type |= CT_TEXT;
2643 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2647 if (!(csp->content_type & CT_DECLARED))
2650 * The server didn't bother to declare a MIME-Type.
2651 * Assume it's text that can be filtered.
2653 * This also regulary happens with 304 responses,
2654 * therefore logging anything here would cause
2657 csp->content_type |= CT_TEXT;
2661 * Choose the applying filter function based on
2662 * the content type and action settings.
2664 if ((csp->content_type & CT_TEXT) &&
2665 (csp->rlist != NULL) &&
2666 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
2667 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
2671 else if ((csp->content_type & CT_GIF) &&
2672 (csp->action->flags & ACTION_DEANIMATE))
2682 /*********************************************************************
2684 * Function : content_filters_enabled
2686 * Description : Checks whether there are any content filters
2687 * enabled for the current request.
2690 * 1 : action = Action spec to check.
2692 * Returns : TRUE for yes, FALSE otherwise
2694 *********************************************************************/
2695 int content_filters_enabled(const struct current_action_spec *action)
2697 return ((action->flags & ACTION_DEANIMATE) ||
2698 !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
2699 !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
2703 /*********************************************************************
2705 * Function : filters_available
2707 * Description : Checks whether there are any filters available.
2710 * 1 : csp = Current client state (buffers, headers, etc...)
2712 * Returns : TRUE for yes, FALSE otherwise.
2714 *********************************************************************/
2715 int filters_available(const struct client_state *csp)
2718 for (i = 0; i < MAX_AF_FILES; i++)
2720 const struct file_list *fl = csp->rlist[i];
2721 if ((NULL != fl) && (NULL != fl->f))