1 const char filters_rcs[] = "$Id: filters.c,v 1.176 2012/12/07 12:45:20 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-2011 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"
69 #include "deanimate.h"
77 const char filters_h_rcs[] = FILTERS_H_VERSION;
79 typedef char *(*filter_function_ptr)();
80 static filter_function_ptr get_filter_function(const struct client_state *csp);
81 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
82 static jb_err prepare_for_filtering(struct client_state *csp);
86 /*********************************************************************
88 * Function : sockaddr_storage_to_ip
90 * Description : Access internal structure of sockaddr_storage
93 * 1 : addr = socket address
94 * 2 : ip = IP address as array of octets in network order
95 * (it points into addr)
96 * 3 : len = length of IP address in octets
97 * 4 : port = port number in network order;
99 * Returns : 0 = no errror; -1 otherwise.
101 *********************************************************************/
102 static int sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
103 uint8_t **ip, unsigned int *len,
111 switch (addr->ss_family)
121 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
125 *port = &((struct sockaddr_in *)addr)->sin_port;
136 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
140 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
145 /* Unsupported address family */
153 /*********************************************************************
155 * Function : match_sockaddr
157 * Description : Check whether address matches network (IP address and port)
160 * 1 : network = socket address of subnework
161 * 2 : netmask = network mask as socket address
162 * 3 : address = checked socket address against given network
164 * Returns : 0 = doesn't match; 1 = does match
166 *********************************************************************/
167 static int match_sockaddr(const struct sockaddr_storage *network,
168 const struct sockaddr_storage *netmask,
169 const struct sockaddr_storage *address)
171 uint8_t *network_addr, *netmask_addr, *address_addr;
172 unsigned int addr_len;
173 in_port_t *network_port, *netmask_port, *address_port;
176 if (network->ss_family != netmask->ss_family)
178 /* This should never happen */
179 assert(network->ss_family == netmask->ss_family);
180 log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
183 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
184 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
185 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
187 /* Check for family */
188 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
189 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
191 /* Map AF_INET6 V4MAPPED address into AF_INET */
195 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
196 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
198 /* Map AF_INET6 V4MAPPED network into AF_INET */
204 /* XXX: Port check is signaled in netmask */
205 if (*netmask_port && *network_port != *address_port)
210 /* TODO: Optimize by checking by words insted of octets */
211 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
213 if ((network_addr[i] & netmask_addr[i]) !=
214 (address_addr[i] & netmask_addr[i]))
222 #endif /* def HAVE_RFC2553 */
225 /*********************************************************************
227 * Function : block_acl
229 * Description : Block this request?
230 * Decide yes or no based on ACL file.
233 * 1 : dst = The proxy or gateway address this is going to.
234 * Or NULL to check all possible targets.
235 * 2 : csp = Current client state (buffers, headers, etc...)
236 * Also includes the client IP address.
238 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
240 *********************************************************************/
241 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
243 struct access_control_list *acl = csp->config->acl;
245 /* if not using an access control list, then permit the connection */
251 /* search the list */
256 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
258 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
264 /* Just want to check if they have any access */
265 if (acl->action == ACL_PERMIT)
277 * XXX: An undefined acl->dst is full of zeros and should be
278 * considered a wildcard address. sockaddr_storage_to_ip()
279 * fails on such destinations because of unknown sa_familly
280 * (glibc only?). However this test is not portable.
282 * So, we signal the acl->dst is wildcard in wildcard_dst.
285 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
287 ((dst->addr & acl->dst->mask) == acl->dst->addr)
288 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
292 if (acl->action == ACL_PERMIT)
310 /*********************************************************************
312 * Function : acl_addr
314 * Description : Called from `load_config' to parse an ACL address.
317 * 1 : aspec = String specifying ACL address.
318 * 2 : aca = struct access_control_addr to fill in.
320 * Returns : 0 => Ok, everything else is an error.
322 *********************************************************************/
323 int acl_addr(const char *aspec, struct access_control_addr *aca)
327 struct addrinfo hints, *result;
329 in_port_t *mask_port;
330 unsigned int addr_len;
333 #endif /* def HAVE_RFC2553 */
335 char *acl_spec = NULL;
338 /* XXX: Depend on ai_family */
346 * Use a temporary acl spec copy so we can log
347 * the unmodified original in case of parse errors.
349 acl_spec = strdup(aspec);
350 if (acl_spec == NULL)
352 /* XXX: This will be logged as parse error. */
356 if ((p = strchr(acl_spec, '/')) != NULL)
359 if (privoxy_isdigit(*p) == 0)
364 masklength = atoi(p);
367 if ((masklength < 0) ||
379 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
382 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
391 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) ? ++p : NULL), &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);
419 port = strtol(p, &endptr, 10);
421 if (port <= 0 || port > 65535 || *endptr != '\0')
428 aca->port = (unsigned long)port;
430 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
433 if (aca->addr == INADDR_NONE)
435 /* XXX: This will be logged as parse error. */
438 #endif /* def HAVE_RFC2553 */
440 /* build the netmask */
442 /* Clip masklength according to current family. */
443 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
448 aca->mask.ss_family = aca->addr.ss_family;
449 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
456 /* ACL contains a port number, check ports in the future. */
461 * XXX: This could be optimized to operate on whole words instead
462 * of octets (128-bit CPU could do it in one iteration).
465 * Octets after prefix can be omitted because of
466 * previous initialization to zeros.
468 for (i = 0; (i < addr_len) && masklength; i++)
478 * XXX: This assumes MSB of octet is on the left side.
479 * This should be true for all architectures or solved
482 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
489 for (i=1; i <= masklength ; i++)
491 aca->mask |= (1U << (32 - i));
494 /* now mask off the host portion of the ip address
495 * (i.e. save on the network portion of the address).
497 aca->addr = aca->addr & aca->mask;
498 #endif /* def HAVE_RFC2553 */
503 #endif /* def FEATURE_ACL */
506 /*********************************************************************
508 * Function : connect_port_is_forbidden
510 * Description : Check to see if CONNECT requests to the destination
511 * port of this request are forbidden. The check is
512 * independend of the actual request method.
515 * 1 : csp = Current client state (buffers, headers, etc...)
517 * Returns : True if yes, false otherwise.
519 *********************************************************************/
520 int connect_port_is_forbidden(const struct client_state *csp)
522 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
523 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
528 /*********************************************************************
530 * Function : block_url
532 * Description : Called from `chat'. Check to see if we need to block this.
535 * 1 : csp = Current client state (buffers, headers, etc...)
537 * Returns : NULL => unblocked, else HTTP block response
539 *********************************************************************/
540 struct http_response *block_url(struct client_state *csp)
542 struct http_response *rsp;
543 const char *new_content_type = NULL;
546 * If it's not blocked, don't block it ;-)
548 if ((csp->action->flags & ACTION_BLOCK) == 0)
552 if (csp->action->flags & ACTION_REDIRECT)
554 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
557 * Else, prepare a response
559 if (NULL == (rsp = alloc_http_response()))
561 return cgi_error_memory();
565 * If it's an image-url, send back an image or redirect
566 * as specified by the relevant +image action
568 #ifdef FEATURE_IMAGE_BLOCKING
569 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
573 /* determine HOW images should be blocked */
574 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
576 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
578 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
581 /* and handle accordingly: */
582 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
584 rsp->status = strdup("403 Request blocked by Privoxy");
585 if (rsp->status == NULL)
587 free_http_response(rsp);
588 return cgi_error_memory();
590 rsp->body = bindup(image_pattern_data, image_pattern_length);
591 if (rsp->body == NULL)
593 free_http_response(rsp);
594 return cgi_error_memory();
596 rsp->content_length = image_pattern_length;
598 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
600 free_http_response(rsp);
601 return cgi_error_memory();
604 else if (0 == strcmpic(p, "blank"))
606 rsp->status = strdup("403 Request blocked by Privoxy");
607 if (rsp->status == NULL)
609 free_http_response(rsp);
610 return cgi_error_memory();
612 rsp->body = bindup(image_blank_data, image_blank_length);
613 if (rsp->body == NULL)
615 free_http_response(rsp);
616 return cgi_error_memory();
618 rsp->content_length = image_blank_length;
620 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
622 free_http_response(rsp);
623 return cgi_error_memory();
628 rsp->status = strdup("302 Local Redirect from Privoxy");
629 if (rsp->status == NULL)
631 free_http_response(rsp);
632 return cgi_error_memory();
635 if (enlist_unique_header(rsp->headers, "Location", p))
637 free_http_response(rsp);
638 return cgi_error_memory();
644 #endif /* def FEATURE_IMAGE_BLOCKING */
645 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
648 * Send empty document.
650 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
653 rsp->body = strdup(" ");
654 rsp->content_length = 1;
656 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
659 * Workaround for firefox bug 492459
660 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
661 * Return a 200 OK status for pages blocked with +handle-as-empty-document
662 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
664 rsp->status = strdup("200 Request blocked by Privoxy");
668 rsp->status = strdup("403 Request blocked by Privoxy");
671 if (rsp->status == NULL)
673 free_http_response(rsp);
674 return cgi_error_memory();
676 if (new_content_type != 0)
678 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
679 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
681 free_http_response(rsp);
682 return cgi_error_memory();
689 * Else, generate an HTML "blocked" message:
693 struct map * exports;
695 rsp->status = strdup("403 Request blocked by Privoxy");
696 if (rsp->status == NULL)
698 free_http_response(rsp);
699 return cgi_error_memory();
702 exports = default_exports(csp, NULL);
705 free_http_response(rsp);
706 return cgi_error_memory();
709 #ifdef FEATURE_FORCE_LOAD
710 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
712 * Export the force conditional block killer if
714 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
715 * - Privoxy is configured to enforce blocks, or
716 * - it's a CONNECT request and enforcing wouldn't work anyway.
718 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
719 || (0 == strcmpic(csp->http->gpc, "connect")))
720 #endif /* ndef FEATURE_FORCE_LOAD */
722 err = map_block_killer(exports, "force-support");
725 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
726 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
727 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
728 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
731 const char *block_reason;
732 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
734 block_reason = csp->action->string[ACTION_STRING_BLOCK];
738 assert(connect_port_is_forbidden(csp));
739 block_reason = "Forbidden CONNECT port.";
741 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
746 free_http_response(rsp);
747 return cgi_error_memory();
750 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
753 free_http_response(rsp);
754 return cgi_error_memory();
757 rsp->crunch_reason = BLOCKED;
759 return finish_http_response(csp, rsp);
765 /*********************************************************************
767 * Function : trust_url FIXME: I should be called distrust_url
769 * Description : Calls is_untrusted_url to determine if the URL is trusted
770 * and if not, returns a HTTP 403 response with a reject message.
773 * 1 : csp = Current client state (buffers, headers, etc...)
775 * Returns : NULL => trusted, else http_response.
777 *********************************************************************/
778 struct http_response *trust_url(struct client_state *csp)
780 struct http_response *rsp;
781 struct map * exports;
782 char buf[BUFFER_SIZE];
784 struct url_spec **tl;
789 * Don't bother to work on trusted URLs
791 if (!is_untrusted_url(csp))
797 * Else, prepare a response:
799 if (NULL == (rsp = alloc_http_response()))
801 return cgi_error_memory();
804 rsp->status = strdup("403 Request blocked by Privoxy");
805 exports = default_exports(csp, NULL);
806 if (exports == NULL || rsp->status == NULL)
808 free_http_response(rsp);
809 return cgi_error_memory();
813 * Export the protocol, host, port, and referrer information
815 err = map(exports, "hostport", 1, csp->http->hostport, 1);
816 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
817 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
819 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
821 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
825 if (!err) err = map(exports, "referrer", 1, "none set", 1);
831 free_http_response(rsp);
832 return cgi_error_memory();
836 * Export the trust list
839 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
841 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
842 string_append(&p, buf);
844 err = map(exports, "trusted-referrers", 1, p, 0);
849 free_http_response(rsp);
850 return cgi_error_memory();
854 * Export the trust info, if available
856 if (csp->config->trust_info->first)
858 struct list_entry *l;
861 for (l = csp->config->trust_info->first; l ; l = l->next)
863 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
864 string_append(&p, buf);
866 err = map(exports, "trust-info", 1, p, 0);
870 err = map_block_killer(exports, "have-trust-info");
876 free_http_response(rsp);
877 return cgi_error_memory();
881 * Export the force conditional block killer if
883 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
884 * - Privoxy is configured to enforce blocks, or
885 * - it's a CONNECT request and enforcing wouldn't work anyway.
887 #ifdef FEATURE_FORCE_LOAD
888 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
889 || (0 == strcmpic(csp->http->gpc, "connect")))
891 err = map_block_killer(exports, "force-support");
895 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
897 #else /* ifndef FEATURE_FORCE_LOAD */
898 err = map_block_killer(exports, "force-support");
899 #endif /* ndef FEATURE_FORCE_LOAD */
904 free_http_response(rsp);
905 return cgi_error_memory();
911 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
914 free_http_response(rsp);
915 return cgi_error_memory();
917 rsp->crunch_reason = UNTRUSTED;
919 return finish_http_response(csp, rsp);
921 #endif /* def FEATURE_TRUST */
924 /*********************************************************************
926 * Function : compile_dynamic_pcrs_job_list
928 * Description : Compiles a dynamic pcrs job list (one with variables
929 * resolved at request time)
932 * 1 : csp = Current client state (buffers, headers, etc...)
933 * 2 : b = The filter list to compile
935 * Returns : NULL in case of errors, otherwise the
938 *********************************************************************/
939 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
941 struct list_entry *pattern;
942 pcrs_job *job_list = NULL;
943 pcrs_job *dummy = NULL;
944 pcrs_job *lastjob = NULL;
947 const struct pcrs_variable variables[] =
949 {"url", csp->http->url, 1},
950 {"path", csp->http->path, 1},
951 {"host", csp->http->host, 1},
952 {"origin", csp->ip_addr_str, 1},
956 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
958 assert(pattern->str != NULL);
960 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
963 log_error(LOG_LEVEL_ERROR,
964 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
965 pattern->str, b->name, error, pcrs_strerror(error));
970 if (error == PCRS_WARN_TRUNCATION)
972 log_error(LOG_LEVEL_ERROR,
973 "At least one of the variables in \'%s\' had to "
974 "be truncated before compilation", pattern->str);
976 if (job_list == NULL)
982 lastjob->next = dummy;
992 /*********************************************************************
994 * Function : rewrite_url
996 * Description : Rewrites a URL with a single pcrs command
997 * and returns the result if it differs from the
998 * original and isn't obviously invalid.
1001 * 1 : old_url = URL to rewrite.
1002 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1005 * Returns : NULL if the pcrs_command didn't change the url, or
1006 * the result of the modification.
1008 *********************************************************************/
1009 char *rewrite_url(char *old_url, const char *pcrs_command)
1011 char *new_url = NULL;
1015 assert(pcrs_command);
1017 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1021 log_error(LOG_LEVEL_REDIRECTS,
1022 "pcrs command \"%s\" didn't change \"%s\".",
1023 pcrs_command, old_url);
1028 log_error(LOG_LEVEL_REDIRECTS,
1029 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1030 pcrs_command, old_url, pcrs_strerror(hits));
1033 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1035 log_error(LOG_LEVEL_ERROR,
1036 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1037 "but the result doesn't look like a valid URL and will be ignored.",
1038 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1043 log_error(LOG_LEVEL_REDIRECTS,
1044 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1045 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1053 #ifdef FEATURE_FAST_REDIRECTS
1054 /*********************************************************************
1056 * Function : get_last_url
1058 * Description : Search for the last URL inside a string.
1059 * If the string already is a URL, it will
1060 * be the first URL found.
1063 * 1 : subject = the string to check
1064 * 2 : redirect_mode = +fast-redirect{} mode
1066 * Returns : NULL if no URL was found, or
1067 * the last URL found.
1069 *********************************************************************/
1070 char *get_last_url(char *subject, const char *redirect_mode)
1072 char *new_url = NULL;
1076 assert(redirect_mode);
1078 subject = strdup(subject);
1079 if (subject == NULL)
1081 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1085 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1087 char *url_segment = NULL;
1088 char **url_segments;
1089 size_t max_segments;
1092 log_error(LOG_LEVEL_REDIRECTS,
1093 "Checking \"%s\" for encoded redirects.", subject);
1096 * Check each parameter in the URL separately.
1097 * Sectionize the URL at "?" and "&",
1098 * go backwards through the segments, URL-decode them
1099 * and look for a URL in the decoded result.
1100 * Stop the search after the first match.
1102 * XXX: This estimate is guaranteed to be high enough as we
1103 * let ssplit() ignore empty fields, but also a bit wasteful.
1105 max_segments = strlen(subject) / 2;
1106 url_segments = malloc(max_segments * sizeof(char *));
1108 if (NULL == url_segments)
1110 log_error(LOG_LEVEL_ERROR,
1111 "Out of memory while decoding URL: %s", subject);
1116 segments = ssplit(subject, "?&", url_segments, max_segments);
1118 while (segments-- > 0)
1120 char *dtoken = url_decode(url_segments[segments]);
1123 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1126 url_segment = strstr(dtoken, "http://");
1127 if (NULL == url_segment)
1129 url_segment = strstr(dtoken, "https://");
1131 if (NULL != url_segment)
1133 url_segment = strdup(url_segment);
1135 if (url_segment == NULL)
1137 log_error(LOG_LEVEL_ERROR,
1138 "Out of memory while searching for redirects.");
1146 freez(url_segments);
1148 if (url_segment == NULL)
1152 subject = url_segment;
1156 /* Look for a URL inside this one, without decoding anything. */
1157 log_error(LOG_LEVEL_REDIRECTS,
1158 "Checking \"%s\" for unencoded redirects.", subject);
1162 * Find the last URL encoded in the request
1165 while ((tmp = strstr(tmp, "http://")) != NULL)
1169 tmp = (new_url != NULL) ? new_url : subject;
1170 while ((tmp = strstr(tmp, "https://")) != NULL)
1175 if ((new_url != NULL)
1176 && ( (new_url != subject)
1177 || (0 == strncmpic(subject, "http://", 7))
1178 || (0 == strncmpic(subject, "https://", 8))
1182 * Return new URL if we found a redirect
1183 * or if the subject already was a URL.
1185 * The second case makes sure that we can
1186 * chain get_last_url after another redirection check
1187 * (like rewrite_url) without losing earlier redirects.
1189 new_url = strdup(new_url);
1198 #endif /* def FEATURE_FAST_REDIRECTS */
1201 /*********************************************************************
1203 * Function : redirect_url
1205 * Description : Checks if Privoxy should answer the request with
1206 * a HTTP redirect and generates the redirect if
1210 * 1 : csp = Current client state (buffers, headers, etc...)
1212 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1214 *********************************************************************/
1215 struct http_response *redirect_url(struct client_state *csp)
1217 struct http_response *rsp;
1218 #ifdef FEATURE_FAST_REDIRECTS
1220 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1221 * as compile-time option? The user can easily disable
1222 * it in his action file.
1224 char * redirect_mode;
1225 #endif /* def FEATURE_FAST_REDIRECTS */
1226 char *old_url = NULL;
1227 char *new_url = NULL;
1228 char *redirection_string;
1230 if ((csp->action->flags & ACTION_REDIRECT))
1232 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1235 * If the redirection string begins with 's',
1236 * assume it's a pcrs command, otherwise treat it as
1237 * properly formatted URL and use it for the redirection
1240 * According to RFC 2616 section 14.30 the URL
1241 * has to be absolute and if the user tries:
1242 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1243 * she would get undefined results anyway.
1247 if (*redirection_string == 's')
1249 old_url = csp->http->url;
1250 new_url = rewrite_url(old_url, redirection_string);
1254 log_error(LOG_LEVEL_REDIRECTS,
1255 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1256 redirection_string);
1257 new_url = strdup(redirection_string);
1261 #ifdef FEATURE_FAST_REDIRECTS
1262 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1264 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1267 * If it exists, use the previously rewritten URL as input
1268 * otherwise just use the old path.
1270 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1271 new_url = get_last_url(old_url, redirect_mode);
1276 * Disable redirect checkers, so that they
1277 * will be only run more than once if the user
1278 * also enables them through tags.
1280 * From a performance point of view
1281 * it doesn't matter, but the duplicated
1282 * log messages are annoying.
1284 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1285 #endif /* def FEATURE_FAST_REDIRECTS */
1286 csp->action->flags &= ~ACTION_REDIRECT;
1288 /* Did any redirect action trigger? */
1291 if (url_requires_percent_encoding(new_url))
1294 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1295 strlen(new_url), new_url);
1296 encoded_url = percent_encode_url(new_url);
1298 if (encoded_url == NULL)
1300 return cgi_error_memory();
1302 new_url = encoded_url;
1303 assert(FALSE == url_requires_percent_encoding(new_url));
1306 if (0 == strcmpic(new_url, csp->http->url))
1308 log_error(LOG_LEVEL_ERROR,
1309 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1310 csp->http->url, new_url);
1315 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1317 if (NULL == (rsp = alloc_http_response()))
1320 return cgi_error_memory();
1323 if (enlist_unique_header(rsp->headers, "Location", new_url)
1324 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))))
1327 free_http_response(rsp);
1328 return cgi_error_memory();
1330 rsp->crunch_reason = REDIRECTED;
1333 return finish_http_response(csp, rsp);
1337 /* Only reached if no redirect is required */
1343 #ifdef FEATURE_IMAGE_BLOCKING
1344 /*********************************************************************
1346 * Function : is_imageurl
1348 * Description : Given a URL, decide whether it is an image or not,
1349 * using either the info from a previous +image action
1350 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1351 * is MSIE and not on a Mac, tell from the browser's accept
1355 * 1 : csp = Current client state (buffers, headers, etc...)
1357 * Returns : True (nonzero) if URL is an image, false (0)
1360 *********************************************************************/
1361 int is_imageurl(const struct client_state *csp)
1363 #ifdef FEATURE_IMAGE_DETECT_MSIE
1366 tmp = get_header_value(csp->headers, "User-Agent:");
1367 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1369 tmp = get_header_value(csp->headers, "Accept:");
1370 if (tmp && strstr(tmp, "image/gif"))
1372 /* Client will accept HTML. If this seems counterintuitive,
1382 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1384 return ((csp->action->flags & ACTION_IMAGE) != 0);
1387 #endif /* def FEATURE_IMAGE_BLOCKING */
1390 #ifdef FEATURE_TRUST
1391 /*********************************************************************
1393 * Function : is_untrusted_url
1395 * Description : Should we "distrust" this URL (and block it)?
1397 * Yes if it matches a line in the trustfile, or if the
1398 * referrer matches a line starting with "+" in the
1403 * 1 : csp = Current client state (buffers, headers, etc...)
1405 * Returns : 0 => trusted, 1 => untrusted
1407 *********************************************************************/
1408 int is_untrusted_url(const struct client_state *csp)
1410 struct file_list *fl;
1411 struct block_spec *b;
1412 struct url_spec **trusted_url;
1413 struct http_request rhttp[1];
1414 const char * referer;
1418 * If we don't have a trustlist, we trust everybody
1420 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1425 memset(rhttp, '\0', sizeof(*rhttp));
1428 * Do we trust the request URL itself?
1430 for (b = b->next; b ; b = b->next)
1432 if (url_match(b->url, csp->http))
1438 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1440 /* no referrer was supplied */
1446 * If not, do we maybe trust its referrer?
1448 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1454 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1456 if (url_match(*trusted_url, rhttp))
1458 /* if the URL's referrer is from a trusted referrer, then
1459 * add the target spec to the trustfile as an unblocked
1460 * domain and return 0 (which means it's OK).
1465 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1469 char * new_entry = strdup("~");
1471 string_append(&new_entry, csp->http->hostport);
1473 path = csp->http->path;
1474 if ( (path[0] == '/')
1476 && ((path_end = strchr(path + 2, '/')) != NULL))
1478 /* since this path points into a user's home space
1479 * be sure to include this spec in the trustfile.
1481 long path_len = path_end - path; /* save offset */
1482 path = strdup(path); /* Copy string */
1485 path_end = path + path_len; /* regenerate ptr to new buffer */
1486 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1488 string_join(&new_entry, path);
1492 * Give a reason for generating this entry.
1494 string_append(&new_entry, " # Trusted referrer was: ");
1495 string_append(&new_entry, referer);
1497 if (new_entry != NULL)
1499 if (-1 == fprintf(fp, "%s\n", new_entry))
1501 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1502 new_entry, csp->config->trustfile);
1508 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1509 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1516 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1517 csp->http->hostport, csp->config->trustfile);
1525 #endif /* def FEATURE_TRUST */
1528 /*********************************************************************
1530 * Function : pcrs_filter_response
1532 * Description : Execute all text substitutions from all applying
1533 * +filter actions on the text buffer that's been
1534 * accumulated in csp->iob->buf.
1537 * 1 : csp = Current client state (buffers, headers, etc...)
1539 * Returns : a pointer to the (newly allocated) modified buffer.
1540 * or NULL if there were no hits or something went wrong
1542 *********************************************************************/
1543 static char *pcrs_filter_response(struct client_state *csp)
1547 size_t size, prev_size;
1553 struct file_list *fl;
1554 struct re_filterfile_spec *b;
1555 struct list_entry *filtername;
1560 if (csp->iob->cur >= csp->iob->eod)
1565 if (filters_available(csp) == FALSE)
1567 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1568 "content filtering enabled, but no content filters available.");
1572 size = (size_t)(csp->iob->eod - csp->iob->cur);
1573 old = csp->iob->cur;
1575 for (i = 0; i < MAX_AF_FILES; i++)
1578 if ((NULL == fl) || (NULL == fl->f))
1581 * Either there are no filter files
1582 * left, or this filter file just
1583 * contains no valid filters.
1585 * Continue to be sure we don't miss
1586 * valid filter files that are chained
1587 * after empty or invalid ones.
1592 * For all applying +filter actions, look if a filter by that
1593 * name exists and if yes, execute it's pcrs_joblist on the
1596 for (b = fl->f; b; b = b->next)
1598 if (b->type != FT_CONTENT_FILTER)
1600 /* Skip header filters */
1604 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1605 filtername ; filtername = filtername->next)
1607 if (strcmp(b->name, filtername->str) == 0)
1609 int current_hits = 0; /* Number of hits caused by this filter */
1610 int job_number = 0; /* Which job we're currently executing */
1611 int job_hits = 0; /* How many hits the current job caused */
1612 pcrs_job *joblist = b->joblist;
1614 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1616 if (NULL == joblist)
1618 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1623 /* Apply all jobs from the joblist */
1624 for (job = joblist; NULL != job; job = job->next)
1627 job_hits = pcrs_execute(job, old, size, &new, &size);
1632 * That went well. Continue filtering
1633 * and use the result of this job as
1634 * input for the next one.
1636 current_hits += job_hits;
1637 if (old != csp->iob->cur)
1646 * This job caused an unexpected error. Inform the user
1647 * and skip the rest of the jobs in this filter. We could
1648 * continue with the next job, but usually the jobs
1649 * depend on each other or are similar enough to
1650 * fail for the same reason.
1652 * At the moment our pcrs expects the error codes of pcre 3.4,
1653 * but newer pcre versions can return additional error codes.
1654 * As a result pcrs_strerror()'s error message might be
1655 * "Unknown error ...", therefore we print the numerical value
1658 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1659 * should we use LOG_LEVEL_RE_FILTER instead?
1661 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1662 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1667 if (b->dynamic) pcrs_free_joblist(joblist);
1669 log_error(LOG_LEVEL_RE_FILTER,
1670 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1671 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1673 hits += current_hits;
1680 * If there were no hits, destroy our copy and let
1681 * chat() use the original in csp->iob
1689 csp->flags |= CSP_FLAG_MODIFIED;
1690 csp->content_length = size;
1691 clear_iob(csp->iob);
1698 /*********************************************************************
1700 * Function : gif_deanimate_response
1702 * Description : Deanimate the GIF image that has been accumulated in
1703 * csp->iob->buf, set csp->content_length to the modified
1704 * size and raise the CSP_FLAG_MODIFIED flag.
1707 * 1 : csp = Current client state (buffers, headers, etc...)
1709 * Returns : a pointer to the (newly allocated) modified buffer.
1710 * or NULL in case something went wrong.
1712 *********************************************************************/
1713 static char *gif_deanimate_response(struct client_state *csp)
1715 struct binbuffer *in, *out;
1719 size = (size_t)(csp->iob->eod - csp->iob->cur);
1721 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1722 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1724 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1728 in->buffer = csp->iob->cur;
1731 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1733 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1740 if ((int)size == out->offset)
1742 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1746 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1748 csp->content_length = out->offset;
1749 csp->flags |= CSP_FLAG_MODIFIED;
1759 /*********************************************************************
1761 * Function : get_filter_function
1763 * Description : Decides which content filter function has
1764 * to be applied (if any).
1767 * 1 : csp = Current client state (buffers, headers, etc...)
1769 * Returns : The content filter function to run, or
1770 * NULL if no content filter is active
1772 *********************************************************************/
1773 static filter_function_ptr get_filter_function(const struct client_state *csp)
1775 filter_function_ptr filter_function = NULL;
1778 * Choose the applying filter function based on
1779 * the content type and action settings.
1781 if ((csp->content_type & CT_TEXT) &&
1782 (csp->rlist != NULL) &&
1783 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1785 filter_function = pcrs_filter_response;
1787 else if ((csp->content_type & CT_GIF) &&
1788 (csp->action->flags & ACTION_DEANIMATE))
1790 filter_function = gif_deanimate_response;
1793 return filter_function;
1797 /*********************************************************************
1799 * Function : remove_chunked_transfer_coding
1801 * Description : In-situ remove the "chunked" transfer coding as defined
1802 * in rfc2616 from a buffer.
1805 * 1 : buffer = Pointer to the text buffer
1806 * 2 : size = In: Number of bytes to be processed,
1807 * Out: Number of bytes after de-chunking.
1808 * (undefined in case of errors)
1810 * Returns : JB_ERR_OK for success,
1811 * JB_ERR_PARSE otherwise
1813 *********************************************************************/
1814 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1817 unsigned int chunksize = 0;
1818 char *from_p, *to_p;
1821 from_p = to_p = buffer;
1823 if (sscanf(buffer, "%x", &chunksize) != 1)
1825 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1826 return JB_ERR_PARSE;
1829 while (chunksize > 0U)
1831 if (NULL == (from_p = strstr(from_p, "\r\n")))
1833 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1834 return JB_ERR_PARSE;
1837 if (chunksize >= *size - newsize)
1839 log_error(LOG_LEVEL_ERROR,
1840 "Chunk size %u exceeds buffered data left. "
1841 "Already digested %u of %u buffered bytes.",
1842 chunksize, (unsigned int)newsize, (unsigned int)*size);
1843 return JB_ERR_PARSE;
1845 newsize += chunksize;
1848 memmove(to_p, from_p, (size_t) chunksize);
1849 to_p = buffer + newsize;
1850 from_p += chunksize + 2;
1852 if (sscanf(from_p, "%x", &chunksize) != 1)
1854 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1859 /* XXX: Should get its own loglevel. */
1860 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1869 /*********************************************************************
1871 * Function : prepare_for_filtering
1873 * Description : If necessary, de-chunks and decompresses
1874 * the content so it can get filterd.
1877 * 1 : csp = Current client state (buffers, headers, etc...)
1879 * Returns : JB_ERR_OK for success,
1880 * JB_ERR_PARSE otherwise
1882 *********************************************************************/
1883 static jb_err prepare_for_filtering(struct client_state *csp)
1885 jb_err err = JB_ERR_OK;
1888 * If the body has a "chunked" transfer-encoding,
1889 * get rid of it, adjusting size and iob->eod
1891 if (csp->flags & CSP_FLAG_CHUNKED)
1893 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1895 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1896 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1897 if (JB_ERR_OK == err)
1899 csp->iob->eod = csp->iob->cur + size;
1900 csp->flags |= CSP_FLAG_MODIFIED;
1904 return JB_ERR_PARSE;
1910 * If the body has a supported transfer-encoding,
1911 * decompress it, adjusting size and iob->eod.
1913 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1915 if (0 == csp->iob->eod - csp->iob->cur)
1917 /* Nothing left after de-chunking. */
1921 err = decompress_iob(csp);
1923 if (JB_ERR_OK == err)
1925 csp->flags |= CSP_FLAG_MODIFIED;
1926 csp->content_type &= ~CT_TABOO;
1931 * Unset CT_GZIP and CT_DEFLATE to remember not
1932 * to modify the Content-Encoding header later.
1934 csp->content_type &= ~CT_GZIP;
1935 csp->content_type &= ~CT_DEFLATE;
1944 /*********************************************************************
1946 * Function : execute_content_filters
1948 * Description : Executes a given content filter.
1951 * 1 : csp = Current client state (buffers, headers, etc...)
1953 * Returns : Pointer to the modified buffer, or
1954 * NULL if filtering failed or wasn't necessary.
1956 *********************************************************************/
1957 char *execute_content_filters(struct client_state *csp)
1959 filter_function_ptr content_filter;
1961 assert(content_filters_enabled(csp->action));
1963 if (0 == csp->iob->eod - csp->iob->cur)
1966 * No content (probably status code 301, 302 ...),
1967 * no filtering necessary.
1972 if (JB_ERR_OK != prepare_for_filtering(csp))
1975 * failed to de-chunk or decompress.
1980 if (0 == csp->iob->eod - csp->iob->cur)
1983 * Clown alarm: chunked and/or compressed nothing delivered.
1988 content_filter = get_filter_function(csp);
1990 return ((*content_filter)(csp));
1994 /*********************************************************************
1996 * Function : get_url_actions
1998 * Description : Gets the actions for this URL.
2001 * 1 : csp = Current client state (buffers, headers, etc...)
2002 * 2 : http = http_request request for blocked URLs
2006 *********************************************************************/
2007 void get_url_actions(struct client_state *csp, struct http_request *http)
2009 struct file_list *fl;
2010 struct url_actions *b;
2013 init_current_action(csp->action);
2015 for (i = 0; i < MAX_AF_FILES; i++)
2017 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2022 apply_url_actions(csp->action, http, b);
2029 /*********************************************************************
2031 * Function : apply_url_actions
2033 * Description : Applies a list of URL actions.
2036 * 1 : action = Destination.
2037 * 2 : http = Current URL
2038 * 3 : b = list of URL actions to apply
2042 *********************************************************************/
2043 void apply_url_actions(struct current_action_spec *action,
2044 struct http_request *http,
2045 struct url_actions *b)
2049 /* Should never happen */
2053 for (b = b->next; NULL != b; b = b->next)
2055 if (url_match(b->url, http))
2057 merge_current_action(action, b->action);
2063 /*********************************************************************
2065 * Function : get_forward_override_settings
2067 * Description : Returns forward settings as specified with the
2068 * forward-override{} action. forward-override accepts
2069 * forward lines similar to the one used in the
2070 * configuration file, but without the URL pattern.
2076 * in the configuration file can be replaced with
2077 * the action section:
2079 * {+forward-override{forward .}}
2083 * 1 : csp = Current client state (buffers, headers, etc...)
2085 * Returns : Pointer to forwarding structure in case of success.
2086 * Invalid syntax is fatal.
2088 *********************************************************************/
2089 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2091 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2092 char forward_settings[BUFFER_SIZE];
2093 char *http_parent = NULL;
2094 /* variable names were chosen for consistency reasons. */
2095 struct forward_spec *fwd = NULL;
2099 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2100 /* Should be enforced by load_one_actions_file() */
2101 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2103 /* Create a copy ssplit can modify */
2104 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2106 if (NULL != csp->fwd)
2109 * XXX: Currently necessary to prevent memory
2110 * leaks when the show-url-info cgi page is visited.
2112 unload_forward_spec(csp->fwd);
2116 * allocate a new forward node, valid only for
2117 * the lifetime of this request. Save its location
2118 * in csp as well, so sweep() can free it later on.
2120 fwd = csp->fwd = zalloc(sizeof(*fwd));
2123 log_error(LOG_LEVEL_FATAL,
2124 "can't allocate memory for forward-override{%s}", forward_override_line);
2125 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2129 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2130 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2132 fwd->type = SOCKS_NONE;
2134 /* Parse the parent HTTP proxy host:port */
2135 http_parent = vec[1];
2138 else if (vec_count == 3)
2140 char *socks_proxy = NULL;
2142 if (!strcasecmp(vec[0], "forward-socks4"))
2144 fwd->type = SOCKS_4;
2145 socks_proxy = vec[1];
2147 else if (!strcasecmp(vec[0], "forward-socks4a"))
2149 fwd->type = SOCKS_4A;
2150 socks_proxy = vec[1];
2152 else if (!strcasecmp(vec[0], "forward-socks5"))
2154 fwd->type = SOCKS_5;
2155 socks_proxy = vec[1];
2157 else if (!strcasecmp(vec[0], "forward-socks5t"))
2159 fwd->type = SOCKS_5T;
2160 socks_proxy = vec[1];
2163 if (NULL != socks_proxy)
2165 /* Parse the SOCKS proxy host[:port] */
2166 fwd->gateway_port = 1080;
2167 parse_forwarder_address(socks_proxy,
2168 &fwd->gateway_host, &fwd->gateway_port);
2170 http_parent = vec[2];
2174 if (NULL == http_parent)
2176 log_error(LOG_LEVEL_FATAL,
2177 "Invalid forward-override syntax in: %s", forward_override_line);
2178 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2181 /* Parse http forwarding settings */
2182 if (strcmp(http_parent, ".") != 0)
2184 fwd->forward_port = 8000;
2185 parse_forwarder_address(http_parent,
2186 &fwd->forward_host, &fwd->forward_port);
2189 assert (NULL != fwd);
2191 log_error(LOG_LEVEL_CONNECT,
2192 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2198 /*********************************************************************
2200 * Function : forward_url
2202 * Description : Should we forward this to another proxy?
2205 * 1 : csp = Current client state (buffers, headers, etc...)
2206 * 2 : http = http_request request for current URL
2208 * Returns : Pointer to forwarding information.
2210 *********************************************************************/
2211 const struct forward_spec *forward_url(struct client_state *csp,
2212 const struct http_request *http)
2214 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2215 struct forward_spec *fwd = csp->config->forward;
2217 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2219 return get_forward_override_settings(csp);
2229 if (url_match(fwd->url, http))
2240 /*********************************************************************
2242 * Function : direct_response
2244 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2245 * request and if so, return a HTTP 501 to the client.
2247 * FIXME: I have a stupid name and I should handle the
2248 * requests properly. Still, what we do here is rfc-
2249 * compliant, whereas ignoring or forwarding are not.
2252 * 1 : csp = Current client state (buffers, headers, etc...)
2254 * Returns : http_response if , NULL if nonmatch or handler fail
2256 *********************************************************************/
2257 struct http_response *direct_response(struct client_state *csp)
2259 struct http_response *rsp;
2260 struct list_entry *p;
2262 if ((0 == strcmpic(csp->http->gpc, "trace"))
2263 || (0 == strcmpic(csp->http->gpc, "options")))
2265 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2267 if (!strncmpic(p->str, "Max-Forwards:", 13))
2269 unsigned int max_forwards;
2272 * If it's a Max-Forwards value of zero,
2273 * we have to intercept the request.
2275 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2278 * FIXME: We could handle at least TRACE here,
2279 * but that would require a verbatim copy of
2280 * the request which we don't have anymore
2282 log_error(LOG_LEVEL_HEADER,
2283 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2286 /* Get mem for response or fail*/
2287 if (NULL == (rsp = alloc_http_response()))
2289 return cgi_error_memory();
2292 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2294 free_http_response(rsp);
2295 return cgi_error_memory();
2299 rsp->crunch_reason = UNSUPPORTED;
2301 return(finish_http_response(csp, rsp));
2310 /*********************************************************************
2312 * Function : content_requires_filtering
2314 * Description : Checks whether there are any content filters
2315 * enabled for the current request and if they
2316 * can actually be applied..
2319 * 1 : csp = Current client state (buffers, headers, etc...)
2321 * Returns : TRUE for yes, FALSE otherwise
2323 *********************************************************************/
2324 int content_requires_filtering(struct client_state *csp)
2326 if ((csp->content_type & CT_TABOO)
2327 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2333 * Are we enabling text mode by force?
2335 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2338 * Do we really have to?
2340 if (csp->content_type & CT_TEXT)
2342 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2346 csp->content_type |= CT_TEXT;
2347 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2351 if (!(csp->content_type & CT_DECLARED))
2354 * The server didn't bother to declare a MIME-Type.
2355 * Assume it's text that can be filtered.
2357 * This also regulary happens with 304 responses,
2358 * therefore logging anything here would cause
2361 csp->content_type |= CT_TEXT;
2365 * Choose the applying filter function based on
2366 * the content type and action settings.
2368 if ((csp->content_type & CT_TEXT) &&
2369 (csp->rlist != NULL) &&
2370 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2374 else if ((csp->content_type & CT_GIF) &&
2375 (csp->action->flags & ACTION_DEANIMATE))
2385 /*********************************************************************
2387 * Function : content_filters_enabled
2389 * Description : Checks whether there are any content filters
2390 * enabled for the current request.
2393 * 1 : action = Action spec to check.
2395 * Returns : TRUE for yes, FALSE otherwise
2397 *********************************************************************/
2398 int content_filters_enabled(const struct current_action_spec *action)
2400 return ((action->flags & ACTION_DEANIMATE) ||
2401 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));
2405 /*********************************************************************
2407 * Function : filters_available
2409 * Description : Checks whether there are any filters available.
2412 * 1 : csp = Current client state (buffers, headers, etc...)
2414 * Returns : TRUE for yes, FALSE otherwise.
2416 *********************************************************************/
2417 int filters_available(const struct client_state *csp)
2420 for (i = 0; i < MAX_AF_FILES; i++)
2422 const struct file_list *fl = csp->rlist[i];
2423 if ((NULL != fl) && (NULL != fl->f))