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-2016 the
8 * Privoxy team. http://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>
47 #endif /* ndef __OS2__ */
48 #include <netinet/in.h>
51 #endif /* ndef _WIN32 */
55 #endif /* def __OS2__ */
63 #include "jbsockets.h"
69 #include "deanimate.h"
72 #ifdef FEATURE_CLIENT_TAGS
73 #include "client-tags.h"
80 typedef char *(*filter_function_ptr)();
81 static filter_function_ptr get_filter_function(const struct client_state *csp);
82 static jb_err prepare_for_filtering(struct client_state *csp);
83 static void apply_url_actions(struct current_action_spec *action,
84 struct http_request *http,
85 #ifdef FEATURE_CLIENT_TAGS
86 const struct list *client_tags,
88 struct url_actions *b);
92 /*********************************************************************
94 * Function : sockaddr_storage_to_ip
96 * Description : Access internal structure of sockaddr_storage
99 * 1 : addr = socket address
100 * 2 : ip = IP address as array of octets in network order
101 * (it points into addr)
102 * 3 : len = length of IP address in octets
103 * 4 : port = port number in network order;
107 *********************************************************************/
108 static void sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
109 uint8_t **ip, unsigned int *len,
112 assert(NULL != addr);
113 assert(addr->ss_family == AF_INET || addr->ss_family == AF_INET6);
115 switch (addr->ss_family)
125 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
129 *port = &((struct sockaddr_in *)addr)->sin_port;
140 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
144 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
152 /*********************************************************************
154 * Function : match_sockaddr
156 * Description : Check whether address matches network (IP address and port)
159 * 1 : network = socket address of subnework
160 * 2 : netmask = network mask as socket address
161 * 3 : address = checked socket address against given network
163 * Returns : 0 = doesn't match; 1 = does match
165 *********************************************************************/
166 static int match_sockaddr(const struct sockaddr_storage *network,
167 const struct sockaddr_storage *netmask,
168 const struct sockaddr_storage *address)
170 uint8_t *network_addr, *netmask_addr, *address_addr;
171 unsigned int addr_len;
172 in_port_t *network_port, *netmask_port, *address_port;
175 if (network->ss_family != netmask->ss_family)
177 /* This should never happen */
178 assert(network->ss_family == netmask->ss_family);
179 log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
182 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
183 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
184 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
186 /* Check for family */
187 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
188 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
190 /* Map AF_INET6 V4MAPPED address into AF_INET */
194 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
195 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
197 /* Map AF_INET6 V4MAPPED network into AF_INET */
203 /* XXX: Port check is signaled in netmask */
204 if (*netmask_port && *network_port != *address_port)
209 /* TODO: Optimize by checking by words insted of octets */
210 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
212 if ((network_addr[i] & netmask_addr[i]) !=
213 (address_addr[i] & netmask_addr[i]))
221 #endif /* def HAVE_RFC2553 */
224 /*********************************************************************
226 * Function : block_acl
228 * Description : Block this request?
229 * Decide yes or no based on ACL file.
232 * 1 : dst = The proxy or gateway address this is going to.
233 * Or NULL to check all possible targets.
234 * 2 : csp = Current client state (buffers, headers, etc...)
235 * Also includes the client IP address.
237 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
239 *********************************************************************/
240 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
242 struct access_control_list *acl = csp->config->acl;
244 /* if not using an access control list, then permit the connection */
250 /* search the list */
255 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
257 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
263 /* Just want to check if they have any access */
264 if (acl->action == ACL_PERMIT)
276 * XXX: An undefined acl->dst is full of zeros and should be
277 * considered a wildcard address. sockaddr_storage_to_ip()
278 * fails on such destinations because of unknown sa_familly
279 * (glibc only?). However this test is not portable.
281 * So, we signal the acl->dst is wildcard in wildcard_dst.
284 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
286 ((dst->addr & acl->dst->mask) == acl->dst->addr)
287 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
291 if (acl->action == ACL_PERMIT)
309 /*********************************************************************
311 * Function : acl_addr
313 * Description : Called from `load_config' to parse an ACL address.
316 * 1 : aspec = String specifying ACL address.
317 * 2 : aca = struct access_control_addr to fill in.
319 * Returns : 0 => Ok, everything else is an error.
321 *********************************************************************/
322 int acl_addr(const char *aspec, struct access_control_addr *aca)
326 struct addrinfo hints, *result;
328 in_port_t *mask_port;
329 unsigned int addr_len;
332 #endif /* def HAVE_RFC2553 */
334 char *acl_spec = NULL;
337 /* XXX: Depend on ai_family */
345 * Use a temporary acl spec copy so we can log
346 * the unmodified original in case of parse errors.
348 acl_spec = strdup_or_die(aspec);
350 if ((p = strchr(acl_spec, '/')) != NULL)
353 if (privoxy_isdigit(*p) == 0)
358 masklength = atoi(p);
361 if ((masklength < 0) ||
373 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
376 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
385 p = strchr(acl_spec, ':');
395 memset(&hints, 0, sizeof(struct addrinfo));
396 hints.ai_family = AF_UNSPEC;
397 hints.ai_socktype = SOCK_STREAM;
399 i = getaddrinfo(acl_spec, p, &hints, &result);
403 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
404 acl_spec, p, gai_strerror(i));
410 /* TODO: Allow multihomed hostnames */
411 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
412 freeaddrinfo(result);
418 port = strtol(p, &endptr, 10);
420 if (port <= 0 || port > 65535 || *endptr != '\0')
427 aca->port = (unsigned long)port;
429 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
432 if (aca->addr == INADDR_NONE)
434 /* XXX: This will be logged as parse error. */
437 #endif /* def HAVE_RFC2553 */
439 /* build the netmask */
441 /* Clip masklength according to current family. */
442 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
447 aca->mask.ss_family = aca->addr.ss_family;
448 sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port);
452 /* ACL contains a port number, check ports in the future. */
457 * XXX: This could be optimized to operate on whole words instead
458 * of octets (128-bit CPU could do it in one iteration).
461 * Octets after prefix can be omitted because of
462 * previous initialization to zeros.
464 for (i = 0; (i < addr_len) && masklength; i++)
474 * XXX: This assumes MSB of octet is on the left side.
475 * This should be true for all architectures or solved
478 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
485 for (i=1; i <= masklength ; i++)
487 aca->mask |= (1U << (32 - i));
490 /* now mask off the host portion of the ip address
491 * (i.e. save on the network portion of the address).
493 aca->addr = aca->addr & aca->mask;
494 #endif /* def HAVE_RFC2553 */
499 #endif /* def FEATURE_ACL */
502 /*********************************************************************
504 * Function : connect_port_is_forbidden
506 * Description : Check to see if CONNECT requests to the destination
507 * port of this request are forbidden. The check is
508 * independend of the actual request method.
511 * 1 : csp = Current client state (buffers, headers, etc...)
513 * Returns : True if yes, false otherwise.
515 *********************************************************************/
516 int connect_port_is_forbidden(const struct client_state *csp)
518 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
519 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
524 /*********************************************************************
526 * Function : block_url
528 * Description : Called from `chat'. Check to see if we need to block this.
531 * 1 : csp = Current client state (buffers, headers, etc...)
533 * Returns : NULL => unblocked, else HTTP block response
535 *********************************************************************/
536 struct http_response *block_url(struct client_state *csp)
538 struct http_response *rsp;
539 const char *new_content_type = NULL;
542 * If it's not blocked, don't block it ;-)
544 if ((csp->action->flags & ACTION_BLOCK) == 0)
548 if (csp->action->flags & ACTION_REDIRECT)
550 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
553 * Else, prepare a response
555 if (NULL == (rsp = alloc_http_response()))
557 return cgi_error_memory();
561 * If it's an image-url, send back an image or redirect
562 * as specified by the relevant +image action
564 #ifdef FEATURE_IMAGE_BLOCKING
565 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
569 /* determine HOW images should be blocked */
570 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
572 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
574 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
577 /* and handle accordingly: */
578 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
580 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
581 rsp->body = bindup(image_pattern_data, image_pattern_length);
582 if (rsp->body == NULL)
584 free_http_response(rsp);
585 return cgi_error_memory();
587 rsp->content_length = image_pattern_length;
589 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
591 free_http_response(rsp);
592 return cgi_error_memory();
595 else if (0 == strcmpic(p, "blank"))
597 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
598 rsp->body = bindup(image_blank_data, image_blank_length);
599 if (rsp->body == NULL)
601 free_http_response(rsp);
602 return cgi_error_memory();
604 rsp->content_length = image_blank_length;
606 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
608 free_http_response(rsp);
609 return cgi_error_memory();
614 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
616 if (enlist_unique_header(rsp->headers, "Location", p))
618 free_http_response(rsp);
619 return cgi_error_memory();
625 #endif /* def FEATURE_IMAGE_BLOCKING */
626 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
629 * Send empty document.
631 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
634 rsp->body = strdup_or_die(" ");
635 rsp->content_length = 1;
637 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
640 * Workaround for firefox bug 492459
641 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
642 * Return a 200 OK status for pages blocked with +handle-as-empty-document
643 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
645 rsp->status = strdup_or_die("200 Request blocked by Privoxy");
649 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
652 if (new_content_type != 0)
654 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
655 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
657 free_http_response(rsp);
658 return cgi_error_memory();
665 * Else, generate an HTML "blocked" message:
669 struct map * exports;
671 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
673 exports = default_exports(csp, NULL);
676 free_http_response(rsp);
677 return cgi_error_memory();
680 #ifdef FEATURE_FORCE_LOAD
681 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
683 * Export the force conditional block killer if
685 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
686 * - Privoxy is configured to enforce blocks, or
687 * - it's a CONNECT request and enforcing wouldn't work anyway.
689 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
690 || (0 == strcmpic(csp->http->gpc, "connect")))
691 #endif /* ndef FEATURE_FORCE_LOAD */
693 err = map_block_killer(exports, "force-support");
696 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
697 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
698 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
699 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
702 const char *block_reason;
703 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
705 block_reason = csp->action->string[ACTION_STRING_BLOCK];
709 assert(connect_port_is_forbidden(csp));
710 block_reason = "Forbidden CONNECT port.";
712 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
717 free_http_response(rsp);
718 return cgi_error_memory();
721 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
724 free_http_response(rsp);
725 return cgi_error_memory();
728 rsp->crunch_reason = BLOCKED;
730 return finish_http_response(csp, rsp);
736 /*********************************************************************
738 * Function : trust_url FIXME: I should be called distrust_url
740 * Description : Calls is_untrusted_url to determine if the URL is trusted
741 * and if not, returns a HTTP 403 response with a reject message.
744 * 1 : csp = Current client state (buffers, headers, etc...)
746 * Returns : NULL => trusted, else http_response.
748 *********************************************************************/
749 struct http_response *trust_url(struct client_state *csp)
751 struct http_response *rsp;
752 struct map * exports;
753 char buf[BUFFER_SIZE];
755 struct pattern_spec **tl;
756 struct pattern_spec *t;
760 * Don't bother to work on trusted URLs
762 if (!is_untrusted_url(csp))
768 * Else, prepare a response:
770 if (NULL == (rsp = alloc_http_response()))
772 return cgi_error_memory();
775 rsp->status = strdup_or_die("403 Request blocked by Privoxy");
776 exports = default_exports(csp, NULL);
779 free_http_response(rsp);
780 return cgi_error_memory();
784 * Export the protocol, host, port, and referrer information
786 err = map(exports, "hostport", 1, csp->http->hostport, 1);
787 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
788 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
790 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
792 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
796 if (!err) err = map(exports, "referrer", 1, "none set", 1);
802 free_http_response(rsp);
803 return cgi_error_memory();
807 * Export the trust list
809 p = strdup_or_die("");
810 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
812 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
813 string_append(&p, buf);
815 err = map(exports, "trusted-referrers", 1, p, 0);
820 free_http_response(rsp);
821 return cgi_error_memory();
825 * Export the trust info, if available
827 if (csp->config->trust_info->first)
829 struct list_entry *l;
831 p = strdup_or_die("");
832 for (l = csp->config->trust_info->first; l ; l = l->next)
834 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
835 string_append(&p, buf);
837 err = map(exports, "trust-info", 1, p, 0);
841 err = map_block_killer(exports, "have-trust-info");
847 free_http_response(rsp);
848 return cgi_error_memory();
852 * Export the force conditional block killer if
854 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
855 * - Privoxy is configured to enforce blocks, or
856 * - it's a CONNECT request and enforcing wouldn't work anyway.
858 #ifdef FEATURE_FORCE_LOAD
859 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
860 || (0 == strcmpic(csp->http->gpc, "connect")))
862 err = map_block_killer(exports, "force-support");
866 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
868 #else /* ifndef FEATURE_FORCE_LOAD */
869 err = map_block_killer(exports, "force-support");
870 #endif /* ndef FEATURE_FORCE_LOAD */
875 free_http_response(rsp);
876 return cgi_error_memory();
882 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
885 free_http_response(rsp);
886 return cgi_error_memory();
888 rsp->crunch_reason = UNTRUSTED;
890 return finish_http_response(csp, rsp);
892 #endif /* def FEATURE_TRUST */
895 /*********************************************************************
897 * Function : compile_dynamic_pcrs_job_list
899 * Description : Compiles a dynamic pcrs job list (one with variables
900 * resolved at request time)
903 * 1 : csp = Current client state (buffers, headers, etc...)
904 * 2 : b = The filter list to compile
906 * Returns : NULL in case of errors, otherwise the
909 *********************************************************************/
910 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
912 struct list_entry *pattern;
913 pcrs_job *job_list = NULL;
914 pcrs_job *dummy = NULL;
915 pcrs_job *lastjob = NULL;
918 const struct pcrs_variable variables[] =
920 {"url", csp->http->url, 1},
921 {"path", csp->http->path, 1},
922 {"host", csp->http->host, 1},
923 {"origin", csp->ip_addr_str, 1},
924 {"listen-address", csp->listen_addr_str, 1},
928 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
930 assert(pattern->str != NULL);
932 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
935 log_error(LOG_LEVEL_ERROR,
936 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
937 pattern->str, b->name, error, pcrs_strerror(error));
942 if (error == PCRS_WARN_TRUNCATION)
944 log_error(LOG_LEVEL_ERROR,
945 "At least one of the variables in \'%s\' had to "
946 "be truncated before compilation", pattern->str);
948 if (job_list == NULL)
954 lastjob->next = dummy;
964 /*********************************************************************
966 * Function : rewrite_url
968 * Description : Rewrites a URL with a single pcrs command
969 * and returns the result if it differs from the
970 * original and isn't obviously invalid.
973 * 1 : old_url = URL to rewrite.
974 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
977 * Returns : NULL if the pcrs_command didn't change the url, or
978 * the result of the modification.
980 *********************************************************************/
981 char *rewrite_url(char *old_url, const char *pcrs_command)
983 char *new_url = NULL;
987 assert(pcrs_command);
989 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
993 log_error(LOG_LEVEL_REDIRECTS,
994 "pcrs command \"%s\" didn't change \"%s\".",
995 pcrs_command, old_url);
1000 log_error(LOG_LEVEL_REDIRECTS,
1001 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1002 pcrs_command, old_url, pcrs_strerror(hits));
1005 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1007 log_error(LOG_LEVEL_ERROR,
1008 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1009 "but the result doesn't look like a valid URL and will be ignored.",
1010 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1015 log_error(LOG_LEVEL_REDIRECTS,
1016 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1017 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1025 #ifdef FEATURE_FAST_REDIRECTS
1026 /*********************************************************************
1028 * Function : get_last_url
1030 * Description : Search for the last URL inside a string.
1031 * If the string already is a URL, it will
1032 * be the first URL found.
1035 * 1 : subject = the string to check
1036 * 2 : redirect_mode = +fast-redirect{} mode
1038 * Returns : NULL if no URL was found, or
1039 * the last URL found.
1041 *********************************************************************/
1042 char *get_last_url(char *subject, const char *redirect_mode)
1044 char *new_url = NULL;
1048 assert(redirect_mode);
1050 subject = strdup(subject);
1051 if (subject == NULL)
1053 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1057 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1059 char *url_segment = NULL;
1060 char **url_segments;
1061 size_t max_segments;
1064 log_error(LOG_LEVEL_REDIRECTS,
1065 "Checking \"%s\" for encoded redirects.", subject);
1068 * Check each parameter in the URL separately.
1069 * Sectionize the URL at "?" and "&",
1070 * go backwards through the segments, URL-decode them
1071 * and look for a URL in the decoded result.
1072 * Stop the search after the first match.
1074 * XXX: This estimate is guaranteed to be high enough as we
1075 * let ssplit() ignore empty fields, but also a bit wasteful.
1077 max_segments = strlen(subject) / 2;
1078 url_segments = malloc(max_segments * sizeof(char *));
1080 if (NULL == url_segments)
1082 log_error(LOG_LEVEL_ERROR,
1083 "Out of memory while decoding URL: %s", subject);
1088 segments = ssplit(subject, "?&", url_segments, max_segments);
1090 while (segments-- > 0)
1092 char *dtoken = url_decode(url_segments[segments]);
1095 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1098 url_segment = strstr(dtoken, "http://");
1099 if (NULL == url_segment)
1101 url_segment = strstr(dtoken, "https://");
1103 if (NULL != url_segment)
1105 url_segment = strdup_or_die(url_segment);
1112 freez(url_segments);
1114 if (url_segment == NULL)
1118 subject = url_segment;
1122 /* Look for a URL inside this one, without decoding anything. */
1123 log_error(LOG_LEVEL_REDIRECTS,
1124 "Checking \"%s\" for unencoded redirects.", subject);
1128 * Find the last URL encoded in the request
1131 while ((tmp = strstr(tmp, "http://")) != NULL)
1135 tmp = (new_url != NULL) ? new_url : subject;
1136 while ((tmp = strstr(tmp, "https://")) != NULL)
1141 if ((new_url != NULL)
1142 && ( (new_url != subject)
1143 || (0 == strncmpic(subject, "http://", 7))
1144 || (0 == strncmpic(subject, "https://", 8))
1148 * Return new URL if we found a redirect
1149 * or if the subject already was a URL.
1151 * The second case makes sure that we can
1152 * chain get_last_url after another redirection check
1153 * (like rewrite_url) without losing earlier redirects.
1155 new_url = strdup(new_url);
1164 #endif /* def FEATURE_FAST_REDIRECTS */
1167 /*********************************************************************
1169 * Function : redirect_url
1171 * Description : Checks if Privoxy should answer the request with
1172 * a HTTP redirect and generates the redirect if
1176 * 1 : csp = Current client state (buffers, headers, etc...)
1178 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1180 *********************************************************************/
1181 struct http_response *redirect_url(struct client_state *csp)
1183 struct http_response *rsp;
1184 #ifdef FEATURE_FAST_REDIRECTS
1186 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1187 * as compile-time option? The user can easily disable
1188 * it in his action file.
1190 char * redirect_mode;
1191 #endif /* def FEATURE_FAST_REDIRECTS */
1192 char *old_url = NULL;
1193 char *new_url = NULL;
1194 char *redirection_string;
1196 if ((csp->action->flags & ACTION_REDIRECT))
1198 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1201 * If the redirection string begins with 's',
1202 * assume it's a pcrs command, otherwise treat it as
1203 * properly formatted URL and use it for the redirection
1206 * According to (the now obsolete) RFC 2616 section 14.30
1207 * the URL has to be absolute and if the user tries:
1208 * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
1209 * she would get undefined results anyway.
1211 * RFC 7231 7.1.2 actually allows relative references,
1212 * but those start with a leading slash (RFC 3986 4.2) and
1213 * thus can't be mistaken for pcrs commands either.
1216 if (*redirection_string == 's')
1218 old_url = csp->http->url;
1219 new_url = rewrite_url(old_url, redirection_string);
1223 log_error(LOG_LEVEL_REDIRECTS,
1224 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1225 redirection_string);
1226 new_url = strdup(redirection_string);
1230 #ifdef FEATURE_FAST_REDIRECTS
1231 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1233 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1236 * If it exists, use the previously rewritten URL as input
1237 * otherwise just use the old path.
1239 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1240 new_url = get_last_url(old_url, redirect_mode);
1245 * Disable redirect checkers, so that they
1246 * will be only run more than once if the user
1247 * also enables them through tags.
1249 * From a performance point of view
1250 * it doesn't matter, but the duplicated
1251 * log messages are annoying.
1253 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1254 #endif /* def FEATURE_FAST_REDIRECTS */
1255 csp->action->flags &= ~ACTION_REDIRECT;
1257 /* Did any redirect action trigger? */
1260 if (url_requires_percent_encoding(new_url))
1263 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1264 strlen(new_url), new_url);
1265 encoded_url = percent_encode_url(new_url);
1267 if (encoded_url == NULL)
1269 return cgi_error_memory();
1271 new_url = encoded_url;
1272 assert(FALSE == url_requires_percent_encoding(new_url));
1275 if (0 == strcmpic(new_url, csp->http->url))
1277 log_error(LOG_LEVEL_ERROR,
1278 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1279 csp->http->url, new_url);
1284 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1286 if (NULL == (rsp = alloc_http_response()))
1289 return cgi_error_memory();
1292 rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
1293 if (enlist_unique_header(rsp->headers, "Location", new_url))
1296 free_http_response(rsp);
1297 return cgi_error_memory();
1299 rsp->crunch_reason = REDIRECTED;
1302 return finish_http_response(csp, rsp);
1306 /* Only reached if no redirect is required */
1312 #ifdef FEATURE_IMAGE_BLOCKING
1313 /*********************************************************************
1315 * Function : is_imageurl
1317 * Description : Given a URL, decide whether it should be treated
1318 * as image URL or not.
1321 * 1 : csp = Current client state (buffers, headers, etc...)
1323 * Returns : True (nonzero) if URL is an image URL, false (0)
1326 *********************************************************************/
1327 int is_imageurl(const struct client_state *csp)
1329 return ((csp->action->flags & ACTION_IMAGE) != 0);
1332 #endif /* def FEATURE_IMAGE_BLOCKING */
1335 #ifdef FEATURE_TRUST
1336 /*********************************************************************
1338 * Function : is_untrusted_url
1340 * Description : Should we "distrust" this URL (and block it)?
1342 * Yes if it matches a line in the trustfile, or if the
1343 * referrer matches a line starting with "+" in the
1348 * 1 : csp = Current client state (buffers, headers, etc...)
1350 * Returns : 0 => trusted, 1 => untrusted
1352 *********************************************************************/
1353 int is_untrusted_url(const struct client_state *csp)
1355 struct file_list *fl;
1356 struct block_spec *b;
1357 struct pattern_spec **trusted_url;
1358 struct http_request rhttp[1];
1359 const char * referer;
1363 * If we don't have a trustlist, we trust everybody
1365 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1370 memset(rhttp, '\0', sizeof(*rhttp));
1373 * Do we trust the request URL itself?
1375 for (b = b->next; b ; b = b->next)
1377 if (url_match(b->url, csp->http))
1383 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1385 /* no referrer was supplied */
1391 * If not, do we maybe trust its referrer?
1393 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1399 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1401 if (url_match(*trusted_url, rhttp))
1403 /* if the URL's referrer is from a trusted referrer, then
1404 * add the target spec to the trustfile as an unblocked
1405 * domain and return 0 (which means it's OK).
1410 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1414 char * new_entry = strdup_or_die("~");
1416 string_append(&new_entry, csp->http->hostport);
1418 path = csp->http->path;
1419 if ( (path[0] == '/')
1421 && ((path_end = strchr(path + 2, '/')) != NULL))
1423 /* since this path points into a user's home space
1424 * be sure to include this spec in the trustfile.
1426 long path_len = path_end - path; /* save offset */
1427 path = strdup(path); /* Copy string */
1430 path_end = path + path_len; /* regenerate ptr to new buffer */
1431 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1433 string_join(&new_entry, path);
1437 * Give a reason for generating this entry.
1439 string_append(&new_entry, " # Trusted referrer was: ");
1440 string_append(&new_entry, referer);
1442 if (new_entry != NULL)
1444 if (-1 == fprintf(fp, "%s\n", new_entry))
1446 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1447 new_entry, csp->config->trustfile);
1453 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1454 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1461 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1462 csp->http->hostport, csp->config->trustfile);
1470 #endif /* def FEATURE_TRUST */
1473 /*********************************************************************
1475 * Function : get_filter
1477 * Description : Get a filter with a given name and type.
1478 * Note that taggers are filters, too.
1481 * 1 : csp = Current client state (buffers, headers, etc...)
1482 * 2 : requested_name = Name of the content filter to get
1483 * 3 : requested_type = Type of the filter to tagger to lookup
1485 * Returns : A pointer to the requested filter
1486 * or NULL if the filter wasn't found
1488 *********************************************************************/
1489 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1490 const char *requested_name,
1491 enum filter_type requested_type)
1494 struct re_filterfile_spec *b;
1495 struct file_list *fl;
1497 for (i = 0; i < MAX_AF_FILES; i++)
1500 if ((NULL == fl) || (NULL == fl->f))
1503 * Either there are no filter files left or this
1504 * filter file just contains no valid filters.
1506 * Continue to be sure we don't miss valid filter
1507 * files that are chained after empty or invalid ones.
1512 for (b = fl->f; b != NULL; b = b->next)
1514 if (b->type != requested_type)
1516 /* The callers isn't interested in this filter type. */
1519 if (strcmp(b->name, requested_name) == 0)
1521 /* The requested filter has been found. Abort search. */
1527 /* No filter with the given name and type exists. */
1533 /*********************************************************************
1535 * Function : pcrs_filter_response
1537 * Description : Execute all text substitutions from all applying
1538 * +filter actions on the text buffer that's been
1539 * accumulated in csp->iob->buf.
1542 * 1 : csp = Current client state (buffers, headers, etc...)
1544 * Returns : a pointer to the (newly allocated) modified buffer.
1545 * or NULL if there were no hits or something went wrong
1547 *********************************************************************/
1548 static char *pcrs_filter_response(struct client_state *csp)
1551 size_t size, prev_size;
1557 struct re_filterfile_spec *b;
1558 struct list_entry *filtername;
1563 if (csp->iob->cur >= csp->iob->eod)
1568 if (filters_available(csp) == FALSE)
1570 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1571 "content filtering enabled, but no content filters available.");
1575 size = (size_t)(csp->iob->eod - csp->iob->cur);
1576 old = csp->iob->cur;
1579 * For all applying +filter actions, look if a filter by that
1580 * name exists and if yes, execute it's pcrs_joblist on the
1583 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1584 filtername != NULL; filtername = filtername->next)
1586 int current_hits = 0; /* Number of hits caused by this filter */
1587 int job_number = 0; /* Which job we're currently executing */
1588 int job_hits = 0; /* How many hits the current job caused */
1591 b = get_filter(csp, filtername->str, FT_CONTENT_FILTER);
1597 joblist = b->joblist;
1599 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1601 if (NULL == joblist)
1603 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1608 /* Apply all jobs from the joblist */
1609 for (job = joblist; NULL != job; job = job->next)
1612 job_hits = pcrs_execute(job, old, size, &new, &size);
1617 * That went well. Continue filtering
1618 * and use the result of this job as
1619 * input for the next one.
1621 current_hits += job_hits;
1622 if (old != csp->iob->cur)
1631 * This job caused an unexpected error. Inform the user
1632 * and skip the rest of the jobs in this filter. We could
1633 * continue with the next job, but usually the jobs
1634 * depend on each other or are similar enough to
1635 * fail for the same reason.
1637 * At the moment our pcrs expects the error codes of pcre 3.4,
1638 * but newer pcre versions can return additional error codes.
1639 * As a result pcrs_strerror()'s error message might be
1640 * "Unknown error ...", therefore we print the numerical value
1643 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1644 * should we use LOG_LEVEL_RE_FILTER instead?
1646 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1647 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1652 if (b->dynamic) pcrs_free_joblist(joblist);
1654 log_error(LOG_LEVEL_RE_FILTER,
1655 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1656 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1658 hits += current_hits;
1662 * If there were no hits, destroy our copy and let
1663 * chat() use the original in csp->iob
1671 csp->flags |= CSP_FLAG_MODIFIED;
1672 csp->content_length = size;
1673 clear_iob(csp->iob);
1680 #ifdef FEATURE_EXTERNAL_FILTERS
1681 /*********************************************************************
1683 * Function : get_external_filter
1685 * Description : Lookup the code to execute for an external filter.
1686 * Masks the misuse of the re_filterfile_spec.
1689 * 1 : csp = Current client state (buffers, headers, etc...)
1690 * 2 : name = Name of the content filter to get
1692 * Returns : A pointer to the requested code
1693 * or NULL if the filter wasn't found
1695 *********************************************************************/
1696 static const char *get_external_filter(const struct client_state *csp,
1699 struct re_filterfile_spec *external_filter;
1701 external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
1702 if (external_filter == NULL)
1704 log_error(LOG_LEVEL_FATAL,
1705 "Didn't find stuff to execute for external filter: %s",
1709 return external_filter->patterns->first->str;
1714 /*********************************************************************
1716 * Function : set_privoxy_variables
1718 * Description : Sets a couple of privoxy-specific environment variables
1721 * 1 : csp = Current client state (buffers, headers, etc...)
1725 *********************************************************************/
1726 static void set_privoxy_variables(const struct client_state *csp)
1733 { "PRIVOXY_URL", csp->http->url },
1734 { "PRIVOXY_PATH", csp->http->path },
1735 { "PRIVOXY_HOST", csp->http->host },
1736 { "PRIVOXY_ORIGIN", csp->ip_addr_str },
1737 { "PRIVOXY_LISTEN_ADDRESS", csp->listen_addr_str },
1740 for (i = 0; i < SZ(env); i++)
1742 if (setenv(env[i].name, env[i].value, 1))
1744 log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
1745 env[i].name, env[i].value);
1751 /*********************************************************************
1753 * Function : execute_external_filter
1755 * Description : Pipe content into external filter and return the output
1758 * 1 : csp = Current client state (buffers, headers, etc...)
1759 * 2 : name = Name of the external filter to execute
1760 * 3 : content = The original content to filter
1761 * 4 : size = The size of the content buffer
1763 * Returns : a pointer to the (newly allocated) modified buffer.
1764 * or NULL if there were no hits or something went wrong
1766 *********************************************************************/
1767 static char *execute_external_filter(const struct client_state *csp,
1768 const char *name, char *content, size_t *size)
1771 char file_name[FILENAME_MAX];
1773 char *filter_output;
1777 const char *external_filter;
1779 if (csp->config->temporary_directory == NULL)
1781 log_error(LOG_LEVEL_ERROR,
1782 "No temporary-directory configured. Can't execute filter: %s",
1787 external_filter = get_external_filter(csp, name);
1789 if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
1790 "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
1792 log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
1796 fd = mkstemp(file_name);
1799 log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
1803 fp = fdopen(fd, "w");
1806 log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
1812 * The size may be zero if a previous filter discarded everything.
1814 * This isn't necessary unintentional, so we just don't try
1815 * to fwrite() nothing and let the user deal with the rest.
1817 if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
1819 log_error(LOG_LEVEL_ERROR, "fwrite(..., %d, 1, ..) failed: %E", *size);
1826 if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
1828 log_error(LOG_LEVEL_ERROR,
1829 "temporary-directory or external filter path too long");
1834 log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
1837 * The locking is necessary to prevent other threads
1838 * from overwriting the environment variables before
1839 * the popen fork. Afterwards this no longer matters.
1841 privoxy_mutex_lock(&external_filter_mutex);
1842 set_privoxy_variables(csp);
1843 fp = popen(cmd, "r");
1844 privoxy_mutex_unlock(&external_filter_mutex);
1847 log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
1852 /* Allocate at least one byte */
1853 filter_output = malloc_or_die(*size + 1);
1856 while (!feof(fp) && !ferror(fp))
1859 /* Could be bigger ... */
1860 enum { READ_LENGTH = 2048 };
1862 if (new_size + READ_LENGTH >= *size)
1866 /* Could be considered wasteful if the content is 'large'. */
1867 *size += (*size >= READ_LENGTH) ? *size : READ_LENGTH;
1869 p = realloc(filter_output, *size);
1872 log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
1873 "external filter output. Using what we got so far.");
1878 assert(new_size + READ_LENGTH < *size);
1879 len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
1889 log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
1893 log_error(LOG_LEVEL_RE_FILTER,
1894 "Executing '%s' resulted in return value %d. "
1895 "Read %d of up to %d bytes.", name, (ret >> 8), new_size, *size);
1901 return filter_output;
1904 #endif /* def FEATURE_EXTERNAL_FILTERS */
1907 /*********************************************************************
1909 * Function : gif_deanimate_response
1911 * Description : Deanimate the GIF image that has been accumulated in
1912 * csp->iob->buf, set csp->content_length to the modified
1913 * size and raise the CSP_FLAG_MODIFIED flag.
1916 * 1 : csp = Current client state (buffers, headers, etc...)
1918 * Returns : a pointer to the (newly allocated) modified buffer.
1919 * or NULL in case something went wrong.
1921 *********************************************************************/
1923 char *gif_deanimate_response(struct client_state *csp)
1925 static char *gif_deanimate_response(struct client_state *csp)
1928 struct binbuffer *in, *out;
1932 size = (size_t)(csp->iob->eod - csp->iob->cur);
1934 in = zalloc_or_die(sizeof(*in));
1935 out = zalloc_or_die(sizeof(*out));
1937 in->buffer = csp->iob->cur;
1940 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1942 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1949 if ((int)size == out->offset)
1951 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1955 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1957 csp->content_length = out->offset;
1958 csp->flags |= CSP_FLAG_MODIFIED;
1968 /*********************************************************************
1970 * Function : get_filter_function
1972 * Description : Decides which content filter function has
1973 * to be applied (if any). Only considers functions
1974 * for internal filters which are mutually-exclusive.
1977 * 1 : csp = Current client state (buffers, headers, etc...)
1979 * Returns : The content filter function to run, or
1980 * NULL if no content filter is active
1982 *********************************************************************/
1983 static filter_function_ptr get_filter_function(const struct client_state *csp)
1985 filter_function_ptr filter_function = NULL;
1988 * Choose the applying filter function based on
1989 * the content type and action settings.
1991 if ((csp->content_type & CT_TEXT) &&
1992 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1994 filter_function = pcrs_filter_response;
1996 else if ((csp->content_type & CT_GIF) &&
1997 (csp->action->flags & ACTION_DEANIMATE))
1999 filter_function = gif_deanimate_response;
2002 return filter_function;
2006 /*********************************************************************
2008 * Function : remove_chunked_transfer_coding
2010 * Description : In-situ remove the "chunked" transfer coding as defined
2011 * in RFC 7230 4.1 from a buffer. XXX: The implementation
2012 * is neither complete nor compliant (TODO #129).
2015 * 1 : buffer = Pointer to the text buffer
2016 * 2 : size = In: Number of bytes to be processed,
2017 * Out: Number of bytes after de-chunking.
2018 * (undefined in case of errors)
2020 * Returns : JB_ERR_OK for success,
2021 * JB_ERR_PARSE otherwise
2023 *********************************************************************/
2025 extern jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2027 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2031 unsigned int chunksize = 0;
2032 char *from_p, *to_p;
2033 const char *end_of_buffer = buffer + *size;
2037 log_error(LOG_LEVEL_FATAL, "Invalid chunked input. Buffer is empty.");
2038 return JB_ERR_PARSE;
2042 from_p = to_p = buffer;
2044 if (sscanf(buffer, "%x", &chunksize) != 1)
2046 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2047 return JB_ERR_PARSE;
2050 while (chunksize > 0U)
2053 * If the chunk-size is valid, we should have at least
2054 * chunk-size bytes of chunk-data and five bytes of
2055 * meta data (chunk-size, CRLF, CRLF) left in the buffer.
2057 if (chunksize + 5 >= *size - newsize)
2059 log_error(LOG_LEVEL_ERROR,
2060 "Chunk size %u exceeds buffered data left. "
2061 "Already digested %u of %u buffered bytes.",
2062 chunksize, (unsigned int)newsize, (unsigned int)*size);
2063 return JB_ERR_PARSE;
2067 * Skip the chunk-size, the optional chunk-ext and the CRLF
2068 * that is supposed to be located directly before the start
2071 if (NULL == (from_p = strstr(from_p, "\r\n")))
2073 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
2074 return JB_ERR_PARSE;
2079 * The previous strstr() does not enforce chunk-validity
2080 * and is sattisfied as long a CRLF is left in the buffer.
2082 * Make sure the bytes we consider chunk-data are within
2085 if (from_p + chunksize >= end_of_buffer)
2087 log_error(LOG_LEVEL_ERROR,
2088 "End of chunk is beyond the end of the buffer.");
2089 return JB_ERR_PARSE;
2092 memmove(to_p, from_p, (size_t) chunksize);
2093 newsize += chunksize;
2094 to_p = buffer + newsize;
2095 from_p += chunksize;
2098 * Not merging this check with the previous one allows us
2099 * to keep chunks without trailing CRLF. It's not clear
2100 * if we actually have to care about those, though.
2102 if (from_p + 2 >= end_of_buffer)
2104 log_error(LOG_LEVEL_ERROR, "Not enough room for trailing CRLF.");
2105 return JB_ERR_PARSE;
2108 if (sscanf(from_p, "%x", &chunksize) != 1)
2110 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2115 /* XXX: Should get its own loglevel. */
2116 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
2125 /*********************************************************************
2127 * Function : prepare_for_filtering
2129 * Description : If necessary, de-chunks and decompresses
2130 * the content so it can get filterd.
2133 * 1 : csp = Current client state (buffers, headers, etc...)
2135 * Returns : JB_ERR_OK for success,
2136 * JB_ERR_PARSE otherwise
2138 *********************************************************************/
2139 static jb_err prepare_for_filtering(struct client_state *csp)
2141 jb_err err = JB_ERR_OK;
2144 * If the body has a "chunked" transfer-encoding,
2145 * get rid of it, adjusting size and iob->eod
2147 if (csp->flags & CSP_FLAG_CHUNKED)
2149 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2151 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2152 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2153 if (JB_ERR_OK == err)
2155 csp->iob->eod = csp->iob->cur + size;
2156 csp->flags |= CSP_FLAG_MODIFIED;
2160 return JB_ERR_PARSE;
2166 * If the body has a supported transfer-encoding,
2167 * decompress it, adjusting size and iob->eod.
2169 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
2171 if (0 == csp->iob->eod - csp->iob->cur)
2173 /* Nothing left after de-chunking. */
2177 err = decompress_iob(csp);
2179 if (JB_ERR_OK == err)
2181 csp->flags |= CSP_FLAG_MODIFIED;
2182 csp->content_type &= ~CT_TABOO;
2187 * Unset CT_GZIP and CT_DEFLATE to remember not
2188 * to modify the Content-Encoding header later.
2190 csp->content_type &= ~CT_GZIP;
2191 csp->content_type &= ~CT_DEFLATE;
2200 /*********************************************************************
2202 * Function : execute_content_filters
2204 * Description : Executes a given content filter.
2207 * 1 : csp = Current client state (buffers, headers, etc...)
2209 * Returns : Pointer to the modified buffer, or
2210 * NULL if filtering failed or wasn't necessary.
2212 *********************************************************************/
2213 char *execute_content_filters(struct client_state *csp)
2216 filter_function_ptr content_filter;
2218 assert(content_filters_enabled(csp->action));
2220 if (0 == csp->iob->eod - csp->iob->cur)
2223 * No content (probably status code 301, 302 ...),
2224 * no filtering necessary.
2229 if (JB_ERR_OK != prepare_for_filtering(csp))
2232 * failed to de-chunk or decompress.
2237 if (0 == csp->iob->eod - csp->iob->cur)
2240 * Clown alarm: chunked and/or compressed nothing delivered.
2245 content_filter = get_filter_function(csp);
2246 content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
2248 #ifdef FEATURE_EXTERNAL_FILTERS
2249 if ((csp->content_type & CT_TEXT) &&
2250 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
2252 struct list_entry *filtername;
2253 size_t size = (size_t)csp->content_length;
2255 if (content == NULL)
2257 content = csp->iob->cur;
2258 size = (size_t)(csp->iob->eod - csp->iob->cur);
2261 for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
2262 filtername ; filtername = filtername->next)
2264 char *result = execute_external_filter(csp, filtername->str, content, &size);
2267 if (content != csp->iob->cur)
2274 csp->flags |= CSP_FLAG_MODIFIED;
2275 csp->content_length = size;
2277 #endif /* def FEATURE_EXTERNAL_FILTERS */
2284 /*********************************************************************
2286 * Function : get_url_actions
2288 * Description : Gets the actions for this URL.
2291 * 1 : csp = Current client state (buffers, headers, etc...)
2292 * 2 : http = http_request request for blocked URLs
2296 *********************************************************************/
2297 void get_url_actions(struct client_state *csp, struct http_request *http)
2299 struct file_list *fl;
2300 struct url_actions *b;
2303 init_current_action(csp->action);
2305 for (i = 0; i < MAX_AF_FILES; i++)
2307 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2312 #ifdef FEATURE_CLIENT_TAGS
2313 apply_url_actions(csp->action, http, csp->client_tags, b);
2315 apply_url_actions(csp->action, http, b);
2322 /*********************************************************************
2324 * Function : apply_url_actions
2326 * Description : Applies a list of URL actions.
2329 * 1 : action = Destination.
2330 * 2 : http = Current URL
2331 * 3 : client_tags = list of client tags
2332 * 4 : b = list of URL actions to apply
2336 *********************************************************************/
2337 static void apply_url_actions(struct current_action_spec *action,
2338 struct http_request *http,
2339 #ifdef FEATURE_CLIENT_TAGS
2340 const struct list *client_tags,
2342 struct url_actions *b)
2346 /* Should never happen */
2350 for (b = b->next; NULL != b; b = b->next)
2352 if (url_match(b->url, http))
2354 merge_current_action(action, b->action);
2356 #ifdef FEATURE_CLIENT_TAGS
2357 if (client_tag_match(b->url, client_tags))
2359 merge_current_action(action, b->action);
2366 /*********************************************************************
2368 * Function : get_forward_override_settings
2370 * Description : Returns forward settings as specified with the
2371 * forward-override{} action. forward-override accepts
2372 * forward lines similar to the one used in the
2373 * configuration file, but without the URL pattern.
2379 * in the configuration file can be replaced with
2380 * the action section:
2382 * {+forward-override{forward .}}
2386 * 1 : csp = Current client state (buffers, headers, etc...)
2388 * Returns : Pointer to forwarding structure in case of success.
2389 * Invalid syntax is fatal.
2391 *********************************************************************/
2392 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2394 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2395 char forward_settings[BUFFER_SIZE];
2396 char *http_parent = NULL;
2397 /* variable names were chosen for consistency reasons. */
2398 struct forward_spec *fwd = NULL;
2402 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2403 /* Should be enforced by load_one_actions_file() */
2404 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2406 /* Create a copy ssplit can modify */
2407 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2409 if (NULL != csp->fwd)
2412 * XXX: Currently necessary to prevent memory
2413 * leaks when the show-url-info cgi page is visited.
2415 unload_forward_spec(csp->fwd);
2419 * allocate a new forward node, valid only for
2420 * the lifetime of this request. Save its location
2421 * in csp as well, so sweep() can free it later on.
2423 fwd = csp->fwd = zalloc_or_die(sizeof(*fwd));
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 == 2) && !strcasecmp(vec[0], "forward-webserver"))
2436 fwd->type = FORWARD_WEBSERVER;
2438 /* Parse the parent HTTP server host:port */
2439 http_parent = vec[1];
2442 else if (vec_count == 3)
2444 char *socks_proxy = NULL;
2446 if (!strcasecmp(vec[0], "forward-socks4"))
2448 fwd->type = SOCKS_4;
2449 socks_proxy = vec[1];
2451 else if (!strcasecmp(vec[0], "forward-socks4a"))
2453 fwd->type = SOCKS_4A;
2454 socks_proxy = vec[1];
2456 else if (!strcasecmp(vec[0], "forward-socks5"))
2458 fwd->type = SOCKS_5;
2459 socks_proxy = vec[1];
2461 else if (!strcasecmp(vec[0], "forward-socks5t"))
2463 fwd->type = SOCKS_5T;
2464 socks_proxy = vec[1];
2467 if (NULL != socks_proxy)
2469 /* Parse the SOCKS proxy host[:port] */
2470 fwd->gateway_port = 1080;
2471 parse_forwarder_address(socks_proxy,
2472 &fwd->gateway_host, &fwd->gateway_port);
2474 http_parent = vec[2];
2478 if (NULL == http_parent)
2480 log_error(LOG_LEVEL_FATAL,
2481 "Invalid forward-override syntax in: %s", forward_override_line);
2482 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2485 /* Parse http forwarding settings */
2486 if (strcmp(http_parent, ".") != 0)
2488 fwd->forward_port = 8000;
2489 parse_forwarder_address(http_parent,
2490 &fwd->forward_host, &fwd->forward_port);
2493 assert (NULL != fwd);
2495 log_error(LOG_LEVEL_CONNECT,
2496 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2502 /*********************************************************************
2504 * Function : forward_url
2506 * Description : Should we forward this to another proxy?
2509 * 1 : csp = Current client state (buffers, headers, etc...)
2510 * 2 : http = http_request request for current URL
2512 * Returns : Pointer to forwarding information.
2514 *********************************************************************/
2515 const struct forward_spec *forward_url(struct client_state *csp,
2516 const struct http_request *http)
2518 static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
2519 struct forward_spec *fwd = csp->config->forward;
2521 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2523 return get_forward_override_settings(csp);
2533 if (url_match(fwd->url, http))
2544 /*********************************************************************
2546 * Function : direct_response
2548 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2549 * request and if so, return a HTTP 501 to the client.
2551 * FIXME: I have a stupid name and I should handle the
2552 * requests properly. Still, what we do here is rfc-
2553 * compliant, whereas ignoring or forwarding are not.
2556 * 1 : csp = Current client state (buffers, headers, etc...)
2558 * Returns : http_response if , NULL if nonmatch or handler fail
2560 *********************************************************************/
2561 struct http_response *direct_response(struct client_state *csp)
2563 struct http_response *rsp;
2564 struct list_entry *p;
2566 if ((0 == strcmpic(csp->http->gpc, "trace"))
2567 || (0 == strcmpic(csp->http->gpc, "options")))
2569 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2571 if (!strncmpic(p->str, "Max-Forwards:", 13))
2573 unsigned int max_forwards;
2576 * If it's a Max-Forwards value of zero,
2577 * we have to intercept the request.
2579 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2582 * FIXME: We could handle at least TRACE here,
2583 * but that would require a verbatim copy of
2584 * the request which we don't have anymore
2586 log_error(LOG_LEVEL_HEADER,
2587 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2590 /* Get mem for response or fail*/
2591 if (NULL == (rsp = alloc_http_response()))
2593 return cgi_error_memory();
2596 rsp->status = strdup_or_die("501 Not Implemented");
2598 rsp->crunch_reason = UNSUPPORTED;
2600 return(finish_http_response(csp, rsp));
2609 /*********************************************************************
2611 * Function : content_requires_filtering
2613 * Description : Checks whether there are any content filters
2614 * enabled for the current request and if they
2615 * can actually be applied..
2618 * 1 : csp = Current client state (buffers, headers, etc...)
2620 * Returns : TRUE for yes, FALSE otherwise
2622 *********************************************************************/
2623 int content_requires_filtering(struct client_state *csp)
2625 if ((csp->content_type & CT_TABOO)
2626 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2632 * Are we enabling text mode by force?
2634 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2637 * Do we really have to?
2639 if (csp->content_type & CT_TEXT)
2641 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2645 csp->content_type |= CT_TEXT;
2646 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2650 if (!(csp->content_type & CT_DECLARED))
2653 * The server didn't bother to declare a MIME-Type.
2654 * Assume it's text that can be filtered.
2656 * This also regulary happens with 304 responses,
2657 * therefore logging anything here would cause
2660 csp->content_type |= CT_TEXT;
2664 * Choose the applying filter function based on
2665 * the content type and action settings.
2667 if ((csp->content_type & CT_TEXT) &&
2668 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
2669 !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
2673 else if ((csp->content_type & CT_GIF) &&
2674 (csp->action->flags & ACTION_DEANIMATE))
2684 /*********************************************************************
2686 * Function : content_filters_enabled
2688 * Description : Checks whether there are any content filters
2689 * enabled for the current request.
2692 * 1 : action = Action spec to check.
2694 * Returns : TRUE for yes, FALSE otherwise
2696 *********************************************************************/
2697 int content_filters_enabled(const struct current_action_spec *action)
2699 return ((action->flags & ACTION_DEANIMATE) ||
2700 !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
2701 !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
2705 /*********************************************************************
2707 * Function : filters_available
2709 * Description : Checks whether there are any filters available.
2712 * 1 : csp = Current client state (buffers, headers, etc...)
2714 * Returns : TRUE for yes, FALSE otherwise.
2716 *********************************************************************/
2717 int filters_available(const struct client_state *csp)
2720 for (i = 0; i < MAX_AF_FILES; i++)
2722 const struct file_list *fl = csp->rlist[i];
2723 if ((NULL != fl) && (NULL != fl->f))