1 const char filters_rcs[] = "$Id: filters.c,v 1.170 2012/03/09 17:55:50 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 */
203 else if (network->ss_family != address->ss_family)
208 /* XXX: Port check is signaled in netmask */
209 if (*netmask_port && *network_port != *address_port)
214 /* TODO: Optimize by checking by words insted of octets */
215 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
217 if ((network_addr[i] & netmask_addr[i]) !=
218 (address_addr[i] & netmask_addr[i]))
226 #endif /* def HAVE_RFC2553 */
229 /*********************************************************************
231 * Function : block_acl
233 * Description : Block this request?
234 * Decide yes or no based on ACL file.
237 * 1 : dst = The proxy or gateway address this is going to.
238 * Or NULL to check all possible targets.
239 * 2 : csp = Current client state (buffers, headers, etc...)
240 * Also includes the client IP address.
242 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
244 *********************************************************************/
245 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
247 struct access_control_list *acl = csp->config->acl;
249 /* if not using an access control list, then permit the connection */
255 /* search the list */
260 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
262 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
268 /* Just want to check if they have any access */
269 if (acl->action == ACL_PERMIT)
281 * XXX: An undefined acl->dst is full of zeros and should be
282 * considered a wildcard address. sockaddr_storage_to_ip()
283 * fails on such destinations because of unknown sa_familly
284 * (glibc only?). However this test is not portable.
286 * So, we signal the acl->dst is wildcard in wildcard_dst.
289 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
291 ((dst->addr & acl->dst->mask) == acl->dst->addr)
292 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
296 if (acl->action == ACL_PERMIT)
314 /*********************************************************************
316 * Function : acl_addr
318 * Description : Called from `load_config' to parse an ACL address.
321 * 1 : aspec = String specifying ACL address.
322 * 2 : aca = struct access_control_addr to fill in.
324 * Returns : 0 => Ok, everything else is an error.
326 *********************************************************************/
327 int acl_addr(const char *aspec, struct access_control_addr *aca)
331 struct addrinfo hints, *result;
333 in_port_t *mask_port;
334 unsigned int addr_len;
337 #endif /* def HAVE_RFC2553 */
339 char *acl_spec = NULL;
342 /* XXX: Depend on ai_family */
350 * Use a temporary acl spec copy so we can log
351 * the unmodified original in case of parse errors.
353 acl_spec = strdup(aspec);
354 if (acl_spec == NULL)
356 /* XXX: This will be logged as parse error. */
360 if ((p = strchr(acl_spec, '/')) != NULL)
363 if (privoxy_isdigit(*p) == 0)
368 masklength = atoi(p);
371 if ((masklength < 0) ||
383 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
386 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
395 p = strchr(acl_spec, ':');
399 memset(&hints, 0, sizeof(struct addrinfo));
400 hints.ai_family = AF_UNSPEC;
401 hints.ai_socktype = SOCK_STREAM;
403 i = getaddrinfo(acl_spec, ((p) ? ++p : NULL), &hints, &result);
407 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
408 acl_spec, p, gai_strerror(i));
414 /* TODO: Allow multihomed hostnames */
415 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
416 freeaddrinfo(result);
423 port = strtol(p, &endptr, 10);
425 if (port <= 0 || port > 65535 || *endptr != '\0')
432 aca->port = (unsigned long)port;
434 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
437 if (aca->addr == INADDR_NONE)
439 /* XXX: This will be logged as parse error. */
442 #endif /* def HAVE_RFC2553 */
444 /* build the netmask */
446 /* Clip masklength according to current family. */
447 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
452 aca->mask.ss_family = aca->addr.ss_family;
453 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
460 /* ACL contains a port number, check ports in the future. */
465 * XXX: This could be optimized to operate on whole words instead
466 * of octets (128-bit CPU could do it in one iteration).
469 * Octets after prefix can be omitted because of
470 * previous initialization to zeros.
472 for (i = 0; (i < addr_len) && masklength; i++)
482 * XXX: This assumes MSB of octet is on the left side.
483 * This should be true for all architectures or solved
486 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
493 for (i=1; i <= masklength ; i++)
495 aca->mask |= (1U << (32 - i));
498 /* now mask off the host portion of the ip address
499 * (i.e. save on the network portion of the address).
501 aca->addr = aca->addr & aca->mask;
502 #endif /* def HAVE_RFC2553 */
507 #endif /* def FEATURE_ACL */
510 /*********************************************************************
512 * Function : connect_port_is_forbidden
514 * Description : Check to see if CONNECT requests to the destination
515 * port of this request are forbidden. The check is
516 * independend of the actual request method.
519 * 1 : csp = Current client state (buffers, headers, etc...)
521 * Returns : True if yes, false otherwise.
523 *********************************************************************/
524 int connect_port_is_forbidden(const struct client_state *csp)
526 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
527 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
532 /*********************************************************************
534 * Function : block_url
536 * Description : Called from `chat'. Check to see if we need to block this.
539 * 1 : csp = Current client state (buffers, headers, etc...)
541 * Returns : NULL => unblocked, else HTTP block response
543 *********************************************************************/
544 struct http_response *block_url(struct client_state *csp)
546 struct http_response *rsp;
547 const char *new_content_type = NULL;
550 * If it's not blocked, don't block it ;-)
552 if ((csp->action->flags & ACTION_BLOCK) == 0)
556 if (csp->action->flags & ACTION_REDIRECT)
558 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
561 * Else, prepare a response
563 if (NULL == (rsp = alloc_http_response()))
565 return cgi_error_memory();
569 * If it's an image-url, send back an image or redirect
570 * as specified by the relevant +image action
572 #ifdef FEATURE_IMAGE_BLOCKING
573 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
577 /* determine HOW images should be blocked */
578 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
580 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
582 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
585 /* and handle accordingly: */
586 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
588 rsp->status = strdup("403 Request blocked by Privoxy");
589 if (rsp->status == NULL)
591 free_http_response(rsp);
592 return cgi_error_memory();
594 rsp->body = bindup(image_pattern_data, image_pattern_length);
595 if (rsp->body == NULL)
597 free_http_response(rsp);
598 return cgi_error_memory();
600 rsp->content_length = image_pattern_length;
602 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
604 free_http_response(rsp);
605 return cgi_error_memory();
608 else if (0 == strcmpic(p, "blank"))
610 rsp->status = strdup("403 Request blocked by Privoxy");
611 if (rsp->status == NULL)
613 free_http_response(rsp);
614 return cgi_error_memory();
616 rsp->body = bindup(image_blank_data, image_blank_length);
617 if (rsp->body == NULL)
619 free_http_response(rsp);
620 return cgi_error_memory();
622 rsp->content_length = image_blank_length;
624 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
626 free_http_response(rsp);
627 return cgi_error_memory();
632 rsp->status = strdup("302 Local Redirect from Privoxy");
633 if (rsp->status == NULL)
635 free_http_response(rsp);
636 return cgi_error_memory();
639 if (enlist_unique_header(rsp->headers, "Location", p))
641 free_http_response(rsp);
642 return cgi_error_memory();
648 #endif /* def FEATURE_IMAGE_BLOCKING */
649 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
652 * Send empty document.
654 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
657 rsp->body = strdup(" ");
658 rsp->content_length = 1;
660 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
663 * Workaround for firefox bug 492459
664 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
665 * Return a 200 OK status for pages blocked with +handle-as-empty-document
666 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
668 rsp->status = strdup("200 Request blocked by Privoxy");
672 rsp->status = strdup("403 Request blocked by Privoxy");
675 if (rsp->status == NULL)
677 free_http_response(rsp);
678 return cgi_error_memory();
680 if (new_content_type != 0)
682 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
683 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
685 free_http_response(rsp);
686 return cgi_error_memory();
693 * Else, generate an HTML "blocked" message:
697 struct map * exports;
699 rsp->status = strdup("403 Request blocked by Privoxy");
700 if (rsp->status == NULL)
702 free_http_response(rsp);
703 return cgi_error_memory();
706 exports = default_exports(csp, NULL);
709 free_http_response(rsp);
710 return cgi_error_memory();
713 #ifdef FEATURE_FORCE_LOAD
714 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
716 * Export the force conditional block killer if
718 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
719 * - Privoxy is configured to enforce blocks, or
720 * - it's a CONNECT request and enforcing wouldn't work anyway.
722 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
723 || (0 == strcmpic(csp->http->gpc, "connect")))
724 #endif /* ndef FEATURE_FORCE_LOAD */
726 err = map_block_killer(exports, "force-support");
729 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
730 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
731 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
732 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
735 const char *block_reason;
736 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
738 block_reason = csp->action->string[ACTION_STRING_BLOCK];
742 assert(connect_port_is_forbidden(csp));
743 block_reason = "Forbidden CONNECT port.";
745 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
750 free_http_response(rsp);
751 return cgi_error_memory();
754 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
757 free_http_response(rsp);
758 return cgi_error_memory();
761 rsp->crunch_reason = BLOCKED;
763 return finish_http_response(csp, rsp);
769 /*********************************************************************
771 * Function : trust_url FIXME: I should be called distrust_url
773 * Description : Calls is_untrusted_url to determine if the URL is trusted
774 * and if not, returns a HTTP 403 response with a reject message.
777 * 1 : csp = Current client state (buffers, headers, etc...)
779 * Returns : NULL => trusted, else http_response.
781 *********************************************************************/
782 struct http_response *trust_url(struct client_state *csp)
784 struct http_response *rsp;
785 struct map * exports;
786 char buf[BUFFER_SIZE];
788 struct url_spec **tl;
793 * Don't bother to work on trusted URLs
795 if (!is_untrusted_url(csp))
801 * Else, prepare a response:
803 if (NULL == (rsp = alloc_http_response()))
805 return cgi_error_memory();
808 rsp->status = strdup("403 Request blocked by Privoxy");
809 exports = default_exports(csp, NULL);
810 if (exports == NULL || rsp->status == NULL)
812 free_http_response(rsp);
813 return cgi_error_memory();
817 * Export the protocol, host, port, and referrer information
819 err = map(exports, "hostport", 1, csp->http->hostport, 1);
820 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
821 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
823 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
825 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
829 if (!err) err = map(exports, "referrer", 1, "none set", 1);
835 free_http_response(rsp);
836 return cgi_error_memory();
840 * Export the trust list
843 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
845 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
846 string_append(&p, buf);
848 err = map(exports, "trusted-referrers", 1, p, 0);
853 free_http_response(rsp);
854 return cgi_error_memory();
858 * Export the trust info, if available
860 if (csp->config->trust_info->first)
862 struct list_entry *l;
865 for (l = csp->config->trust_info->first; l ; l = l->next)
867 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
868 string_append(&p, buf);
870 err = map(exports, "trust-info", 1, p, 0);
874 err = map_block_killer(exports, "have-trust-info");
880 free_http_response(rsp);
881 return cgi_error_memory();
885 * Export the force conditional block killer if
887 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
888 * - Privoxy is configured to enforce blocks, or
889 * - it's a CONNECT request and enforcing wouldn't work anyway.
891 #ifdef FEATURE_FORCE_LOAD
892 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
893 || (0 == strcmpic(csp->http->gpc, "connect")))
895 err = map_block_killer(exports, "force-support");
899 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
901 #else /* ifndef FEATURE_FORCE_LOAD */
902 err = map_block_killer(exports, "force-support");
903 #endif /* ndef FEATURE_FORCE_LOAD */
908 free_http_response(rsp);
909 return cgi_error_memory();
915 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
918 free_http_response(rsp);
919 return cgi_error_memory();
921 rsp->crunch_reason = UNTRUSTED;
923 return finish_http_response(csp, rsp);
925 #endif /* def FEATURE_TRUST */
928 /*********************************************************************
930 * Function : compile_dynamic_pcrs_job_list
932 * Description : Compiles a dynamic pcrs job list (one with variables
933 * resolved at request time)
936 * 1 : csp = Current client state (buffers, headers, etc...)
937 * 2 : b = The filter list to compile
939 * Returns : NULL in case of errors, otherwise the
942 *********************************************************************/
943 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
945 struct list_entry *pattern;
946 pcrs_job *job_list = NULL;
947 pcrs_job *dummy = NULL;
948 pcrs_job *lastjob = NULL;
951 const struct pcrs_variable variables[] =
953 {"url", csp->http->url, 1},
954 {"path", csp->http->path, 1},
955 {"host", csp->http->host, 1},
956 {"origin", csp->ip_addr_str, 1},
960 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
962 assert(pattern->str != NULL);
964 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
967 log_error(LOG_LEVEL_ERROR,
968 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
969 pattern->str, b->name, error, pcrs_strerror(error));
974 if (error == PCRS_WARN_TRUNCATION)
976 log_error(LOG_LEVEL_ERROR,
977 "At least one of the variables in \'%s\' had to "
978 "be truncated before compilation", pattern->str);
980 if (job_list == NULL)
986 lastjob->next = dummy;
996 /*********************************************************************
998 * Function : rewrite_url
1000 * Description : Rewrites a URL with a single pcrs command
1001 * and returns the result if it differs from the
1002 * original and isn't obviously invalid.
1005 * 1 : old_url = URL to rewrite.
1006 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1009 * Returns : NULL if the pcrs_command didn't change the url, or
1010 * the result of the modification.
1012 *********************************************************************/
1013 char *rewrite_url(char *old_url, const char *pcrs_command)
1015 char *new_url = NULL;
1019 assert(pcrs_command);
1021 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1025 log_error(LOG_LEVEL_REDIRECTS,
1026 "pcrs command \"%s\" didn't change \"%s\".",
1027 pcrs_command, old_url);
1032 log_error(LOG_LEVEL_REDIRECTS,
1033 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1034 pcrs_command, old_url, pcrs_strerror(hits));
1037 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1039 log_error(LOG_LEVEL_ERROR,
1040 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1041 "but the result doesn't look like a valid URL and will be ignored.",
1042 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1047 log_error(LOG_LEVEL_REDIRECTS,
1048 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1049 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1057 #ifdef FEATURE_FAST_REDIRECTS
1058 /*********************************************************************
1060 * Function : get_last_url
1062 * Description : Search for the last URL inside a string.
1063 * If the string already is a URL, it will
1064 * be the first URL found.
1067 * 1 : subject = the string to check
1068 * 2 : redirect_mode = +fast-redirect{} mode
1070 * Returns : NULL if no URL was found, or
1071 * the last URL found.
1073 *********************************************************************/
1074 char *get_last_url(char *subject, const char *redirect_mode)
1076 char *new_url = NULL;
1080 assert(redirect_mode);
1082 subject = strdup(subject);
1083 if (subject == NULL)
1085 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1089 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1091 log_error(LOG_LEVEL_REDIRECTS,
1092 "Checking \"%s\" for encoded redirects.", subject);
1095 * Check each parameter in the URL separately.
1096 * Sectionize the URL at "?" and "&",
1097 * go backwards through the segments, URL-decode them
1098 * and look for a URL in the decoded result.
1099 * Stop the search after the first match.
1101 char *url_segment = NULL;
1103 * XXX: This estimate is guaranteed to be high enough as we
1104 * let ssplit() ignore empty fields, but also a bit wasteful.
1106 size_t max_segments = strlen(subject) / 2;
1107 char **url_segments = malloc(max_segments * sizeof(char *));
1110 if (NULL == url_segments)
1112 log_error(LOG_LEVEL_ERROR,
1113 "Out of memory while decoding URL: %s", subject);
1118 segments = ssplit(subject, "?&", url_segments, max_segments, 1, 1);
1120 while (segments-- > 0)
1122 char *dtoken = url_decode(url_segments[segments]);
1125 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1128 url_segment = strstr(dtoken, "http://");
1129 if (NULL == url_segment)
1131 url_segment = strstr(dtoken, "https://");
1133 if (NULL != url_segment)
1135 url_segment = strdup(url_segment);
1137 if (url_segment == NULL)
1139 log_error(LOG_LEVEL_ERROR,
1140 "Out of memory while searching for redirects.");
1148 freez(url_segments);
1150 if (url_segment == NULL)
1154 subject = url_segment;
1158 /* Look for a URL inside this one, without decoding anything. */
1159 log_error(LOG_LEVEL_REDIRECTS,
1160 "Checking \"%s\" for unencoded redirects.", subject);
1164 * Find the last URL encoded in the request
1167 while ((tmp = strstr(tmp, "http://")) != NULL)
1171 tmp = (new_url != NULL) ? new_url : subject;
1172 while ((tmp = strstr(tmp, "https://")) != NULL)
1177 if ((new_url != NULL)
1178 && ( (new_url != subject)
1179 || (0 == strncmpic(subject, "http://", 7))
1180 || (0 == strncmpic(subject, "https://", 8))
1184 * Return new URL if we found a redirect
1185 * or if the subject already was a URL.
1187 * The second case makes sure that we can
1188 * chain get_last_url after another redirection check
1189 * (like rewrite_url) without losing earlier redirects.
1191 new_url = strdup(new_url);
1200 #endif /* def FEATURE_FAST_REDIRECTS */
1203 /*********************************************************************
1205 * Function : redirect_url
1207 * Description : Checks if Privoxy should answer the request with
1208 * a HTTP redirect and generates the redirect if
1212 * 1 : csp = Current client state (buffers, headers, etc...)
1214 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1216 *********************************************************************/
1217 struct http_response *redirect_url(struct client_state *csp)
1219 struct http_response *rsp;
1220 #ifdef FEATURE_FAST_REDIRECTS
1222 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1223 * as compile-time option? The user can easily disable
1224 * it in his action file.
1226 char * redirect_mode;
1227 #endif /* def FEATURE_FAST_REDIRECTS */
1228 char *old_url = NULL;
1229 char *new_url = NULL;
1230 char *redirection_string;
1232 if ((csp->action->flags & ACTION_REDIRECT))
1234 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1237 * If the redirection string begins with 's',
1238 * assume it's a pcrs command, otherwise treat it as
1239 * properly formatted URL and use it for the redirection
1242 * According to RFC 2616 section 14.30 the URL
1243 * has to be absolute and if the user tries:
1244 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1245 * she would get undefined results anyway.
1249 if (*redirection_string == 's')
1251 old_url = csp->http->url;
1252 new_url = rewrite_url(old_url, redirection_string);
1256 log_error(LOG_LEVEL_REDIRECTS,
1257 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1258 redirection_string);
1259 new_url = strdup(redirection_string);
1263 #ifdef FEATURE_FAST_REDIRECTS
1264 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1266 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1269 * If it exists, use the previously rewritten URL as input
1270 * otherwise just use the old path.
1272 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1273 new_url = get_last_url(old_url, redirect_mode);
1278 * Disable redirect checkers, so that they
1279 * will be only run more than once if the user
1280 * also enables them through tags.
1282 * From a performance point of view
1283 * it doesn't matter, but the duplicated
1284 * log messages are annoying.
1286 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1287 #endif /* def FEATURE_FAST_REDIRECTS */
1288 csp->action->flags &= ~ACTION_REDIRECT;
1290 /* Did any redirect action trigger? */
1293 if (url_requires_percent_encoding(new_url))
1296 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1297 strlen(new_url), new_url);
1298 encoded_url = percent_encode_url(new_url);
1300 if (encoded_url == NULL)
1302 return cgi_error_memory();
1304 new_url = encoded_url;
1305 assert(FALSE == url_requires_percent_encoding(new_url));
1308 if (0 == strcmpic(new_url, csp->http->url))
1310 log_error(LOG_LEVEL_ERROR,
1311 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1312 csp->http->url, new_url);
1317 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1319 if (NULL == (rsp = alloc_http_response()))
1322 return cgi_error_memory();
1325 if (enlist_unique_header(rsp->headers, "Location", new_url)
1326 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))))
1329 free_http_response(rsp);
1330 return cgi_error_memory();
1332 rsp->crunch_reason = REDIRECTED;
1335 return finish_http_response(csp, rsp);
1339 /* Only reached if no redirect is required */
1345 #ifdef FEATURE_IMAGE_BLOCKING
1346 /*********************************************************************
1348 * Function : is_imageurl
1350 * Description : Given a URL, decide whether it is an image or not,
1351 * using either the info from a previous +image action
1352 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1353 * is MSIE and not on a Mac, tell from the browser's accept
1357 * 1 : csp = Current client state (buffers, headers, etc...)
1359 * Returns : True (nonzero) if URL is an image, false (0)
1362 *********************************************************************/
1363 int is_imageurl(const struct client_state *csp)
1365 #ifdef FEATURE_IMAGE_DETECT_MSIE
1368 tmp = get_header_value(csp->headers, "User-Agent:");
1369 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1371 tmp = get_header_value(csp->headers, "Accept:");
1372 if (tmp && strstr(tmp, "image/gif"))
1374 /* Client will accept HTML. If this seems counterintuitive,
1384 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1386 return ((csp->action->flags & ACTION_IMAGE) != 0);
1389 #endif /* def FEATURE_IMAGE_BLOCKING */
1392 #ifdef FEATURE_TRUST
1393 /*********************************************************************
1395 * Function : is_untrusted_url
1397 * Description : Should we "distrust" this URL (and block it)?
1399 * Yes if it matches a line in the trustfile, or if the
1400 * referrer matches a line starting with "+" in the
1405 * 1 : csp = Current client state (buffers, headers, etc...)
1407 * Returns : 0 => trusted, 1 => untrusted
1409 *********************************************************************/
1410 int is_untrusted_url(const struct client_state *csp)
1412 struct file_list *fl;
1413 struct block_spec *b;
1414 struct url_spec **trusted_url;
1415 struct http_request rhttp[1];
1416 const char * referer;
1420 * If we don't have a trustlist, we trust everybody
1422 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1427 memset(rhttp, '\0', sizeof(*rhttp));
1430 * Do we trust the request URL itself?
1432 for (b = b->next; b ; b = b->next)
1434 if (url_match(b->url, csp->http))
1440 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1442 /* no referrer was supplied */
1448 * If not, do we maybe trust its referrer?
1450 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1456 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1458 if (url_match(*trusted_url, rhttp))
1460 /* if the URL's referrer is from a trusted referrer, then
1461 * add the target spec to the trustfile as an unblocked
1462 * domain and return 0 (which means it's OK).
1467 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1471 char * new_entry = strdup("~");
1473 string_append(&new_entry, csp->http->hostport);
1475 path = csp->http->path;
1476 if ( (path[0] == '/')
1478 && ((path_end = strchr(path + 2, '/')) != NULL))
1480 /* since this path points into a user's home space
1481 * be sure to include this spec in the trustfile.
1483 long path_len = path_end - path; /* save offset */
1484 path = strdup(path); /* Copy string */
1487 path_end = path + path_len; /* regenerate ptr to new buffer */
1488 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1490 string_join(&new_entry, path);
1494 * Give a reason for generating this entry.
1496 string_append(&new_entry, " # Trusted referrer was: ");
1497 string_append(&new_entry, referer);
1499 if (new_entry != NULL)
1501 if (-1 == fprintf(fp, "%s\n", new_entry))
1503 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1504 new_entry, csp->config->trustfile);
1510 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1511 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1518 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1519 csp->http->hostport, csp->config->trustfile);
1527 #endif /* def FEATURE_TRUST */
1530 /*********************************************************************
1532 * Function : pcrs_filter_response
1534 * Description : Execute all text substitutions from all applying
1535 * +filter actions on the text buffer that's been
1536 * accumulated in csp->iob->buf.
1539 * 1 : csp = Current client state (buffers, headers, etc...)
1541 * Returns : a pointer to the (newly allocated) modified buffer.
1542 * or NULL if there were no hits or something went wrong
1544 *********************************************************************/
1545 static char *pcrs_filter_response(struct client_state *csp)
1549 size_t size, prev_size;
1555 struct file_list *fl;
1556 struct re_filterfile_spec *b;
1557 struct list_entry *filtername;
1562 if (csp->iob->cur >= csp->iob->eod)
1567 if (filters_available(csp) == FALSE)
1569 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1570 "content filtering enabled, but no content filters available.");
1574 size = (size_t)(csp->iob->eod - csp->iob->cur);
1575 old = csp->iob->cur;
1577 for (i = 0; i < MAX_AF_FILES; i++)
1580 if ((NULL == fl) || (NULL == fl->f))
1583 * Either there are no filter files
1584 * left, or this filter file just
1585 * contains no valid filters.
1587 * Continue to be sure we don't miss
1588 * valid filter files that are chained
1589 * after empty or invalid ones.
1594 * For all applying +filter actions, look if a filter by that
1595 * name exists and if yes, execute it's pcrs_joblist on the
1598 for (b = fl->f; b; b = b->next)
1600 if (b->type != FT_CONTENT_FILTER)
1602 /* Skip header filters */
1606 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1607 filtername ; filtername = filtername->next)
1609 if (strcmp(b->name, filtername->str) == 0)
1611 int current_hits = 0; /* Number of hits caused by this filter */
1612 int job_number = 0; /* Which job we're currently executing */
1613 int job_hits = 0; /* How many hits the current job caused */
1614 pcrs_job *joblist = b->joblist;
1616 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1618 if (NULL == joblist)
1620 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1625 /* Apply all jobs from the joblist */
1626 for (job = joblist; NULL != job; job = job->next)
1629 job_hits = pcrs_execute(job, old, size, &new, &size);
1634 * That went well. Continue filtering
1635 * and use the result of this job as
1636 * input for the next one.
1638 current_hits += job_hits;
1639 if (old != csp->iob->cur)
1648 * This job caused an unexpected error. Inform the user
1649 * and skip the rest of the jobs in this filter. We could
1650 * continue with the next job, but usually the jobs
1651 * depend on each other or are similar enough to
1652 * fail for the same reason.
1654 * At the moment our pcrs expects the error codes of pcre 3.4,
1655 * but newer pcre versions can return additional error codes.
1656 * As a result pcrs_strerror()'s error message might be
1657 * "Unknown error ...", therefore we print the numerical value
1660 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1661 * should we use LOG_LEVEL_RE_FILTER instead?
1663 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1664 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1669 if (b->dynamic) pcrs_free_joblist(joblist);
1671 log_error(LOG_LEVEL_RE_FILTER,
1672 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1673 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1675 hits += current_hits;
1682 * If there were no hits, destroy our copy and let
1683 * chat() use the original in csp->iob
1691 csp->flags |= CSP_FLAG_MODIFIED;
1692 csp->content_length = size;
1700 /*********************************************************************
1702 * Function : gif_deanimate_response
1704 * Description : Deanimate the GIF image that has been accumulated in
1705 * csp->iob->buf, set csp->content_length to the modified
1706 * size and raise the CSP_FLAG_MODIFIED flag.
1709 * 1 : csp = Current client state (buffers, headers, etc...)
1711 * Returns : a pointer to the (newly allocated) modified buffer.
1712 * or NULL in case something went wrong.
1714 *********************************************************************/
1715 static char *gif_deanimate_response(struct client_state *csp)
1717 struct binbuffer *in, *out;
1721 size = (size_t)(csp->iob->eod - csp->iob->cur);
1723 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1724 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1726 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1730 in->buffer = csp->iob->cur;
1733 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1735 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1742 if ((int)size == out->offset)
1744 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1748 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1750 csp->content_length = out->offset;
1751 csp->flags |= CSP_FLAG_MODIFIED;
1761 /*********************************************************************
1763 * Function : get_filter_function
1765 * Description : Decides which content filter function has
1766 * to be applied (if any).
1769 * 1 : csp = Current client state (buffers, headers, etc...)
1771 * Returns : The content filter function to run, or
1772 * NULL if no content filter is active
1774 *********************************************************************/
1775 static filter_function_ptr get_filter_function(const struct client_state *csp)
1777 filter_function_ptr filter_function = NULL;
1780 * Choose the applying filter function based on
1781 * the content type and action settings.
1783 if ((csp->content_type & CT_TEXT) &&
1784 (csp->rlist != NULL) &&
1785 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1787 filter_function = pcrs_filter_response;
1789 else if ((csp->content_type & CT_GIF) &&
1790 (csp->action->flags & ACTION_DEANIMATE))
1792 filter_function = gif_deanimate_response;
1795 return filter_function;
1799 /*********************************************************************
1801 * Function : remove_chunked_transfer_coding
1803 * Description : In-situ remove the "chunked" transfer coding as defined
1804 * in rfc2616 from a buffer.
1807 * 1 : buffer = Pointer to the text buffer
1808 * 2 : size = In: Number of bytes to be processed,
1809 * Out: Number of bytes after de-chunking.
1810 * (undefined in case of errors)
1812 * Returns : JB_ERR_OK for success,
1813 * JB_ERR_PARSE otherwise
1815 *********************************************************************/
1816 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1819 unsigned int chunksize = 0;
1820 char *from_p, *to_p;
1823 from_p = to_p = buffer;
1825 if (sscanf(buffer, "%x", &chunksize) != 1)
1827 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1828 return JB_ERR_PARSE;
1831 while (chunksize > 0U)
1833 if (NULL == (from_p = strstr(from_p, "\r\n")))
1835 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1836 return JB_ERR_PARSE;
1839 if (chunksize >= *size - newsize)
1841 log_error(LOG_LEVEL_ERROR,
1842 "Chunk size %u exceeds buffered data left. "
1843 "Already digested %u of %u buffered bytes.",
1844 chunksize, (unsigned int)newsize, (unsigned int)*size);
1845 return JB_ERR_PARSE;
1847 newsize += chunksize;
1850 memmove(to_p, from_p, (size_t) chunksize);
1851 to_p = buffer + newsize;
1852 from_p += chunksize + 2;
1854 if (sscanf(from_p, "%x", &chunksize) != 1)
1856 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1861 /* XXX: Should get its own loglevel. */
1862 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1871 /*********************************************************************
1873 * Function : prepare_for_filtering
1875 * Description : If necessary, de-chunks and decompresses
1876 * the content so it can get filterd.
1879 * 1 : csp = Current client state (buffers, headers, etc...)
1881 * Returns : JB_ERR_OK for success,
1882 * JB_ERR_PARSE otherwise
1884 *********************************************************************/
1885 static jb_err prepare_for_filtering(struct client_state *csp)
1887 jb_err err = JB_ERR_OK;
1890 * If the body has a "chunked" transfer-encoding,
1891 * get rid of it, adjusting size and iob->eod
1893 if (csp->flags & CSP_FLAG_CHUNKED)
1895 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1897 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1898 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1899 if (JB_ERR_OK == err)
1901 csp->iob->eod = csp->iob->cur + size;
1902 csp->flags |= CSP_FLAG_MODIFIED;
1906 return JB_ERR_PARSE;
1912 * If the body has a supported transfer-encoding,
1913 * decompress it, adjusting size and iob->eod.
1915 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1917 if (0 == csp->iob->eod - csp->iob->cur)
1919 /* Nothing left after de-chunking. */
1923 err = decompress_iob(csp);
1925 if (JB_ERR_OK == err)
1927 csp->flags |= CSP_FLAG_MODIFIED;
1928 csp->content_type &= ~CT_TABOO;
1933 * Unset CT_GZIP and CT_DEFLATE to remember not
1934 * to modify the Content-Encoding header later.
1936 csp->content_type &= ~CT_GZIP;
1937 csp->content_type &= ~CT_DEFLATE;
1946 /*********************************************************************
1948 * Function : execute_content_filters
1950 * Description : Executes a given content filter.
1953 * 1 : csp = Current client state (buffers, headers, etc...)
1955 * Returns : Pointer to the modified buffer, or
1956 * NULL if filtering failed or wasn't necessary.
1958 *********************************************************************/
1959 char *execute_content_filters(struct client_state *csp)
1961 filter_function_ptr content_filter;
1963 assert(content_filters_enabled(csp->action));
1965 if (0 == csp->iob->eod - csp->iob->cur)
1968 * No content (probably status code 301, 302 ...),
1969 * no filtering necessary.
1974 if (JB_ERR_OK != prepare_for_filtering(csp))
1977 * failed to de-chunk or decompress.
1982 if (0 == csp->iob->eod - csp->iob->cur)
1985 * Clown alarm: chunked and/or compressed nothing delivered.
1990 content_filter = get_filter_function(csp);
1992 return ((*content_filter)(csp));
1996 /*********************************************************************
1998 * Function : get_url_actions
2000 * Description : Gets the actions for this URL.
2003 * 1 : csp = Current client state (buffers, headers, etc...)
2004 * 2 : http = http_request request for blocked URLs
2008 *********************************************************************/
2009 void get_url_actions(struct client_state *csp, struct http_request *http)
2011 struct file_list *fl;
2012 struct url_actions *b;
2015 init_current_action(csp->action);
2017 for (i = 0; i < MAX_AF_FILES; i++)
2019 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2024 apply_url_actions(csp->action, http, b);
2031 /*********************************************************************
2033 * Function : apply_url_actions
2035 * Description : Applies a list of URL actions.
2038 * 1 : action = Destination.
2039 * 2 : http = Current URL
2040 * 3 : b = list of URL actions to apply
2044 *********************************************************************/
2045 void apply_url_actions(struct current_action_spec *action,
2046 struct http_request *http,
2047 struct url_actions *b)
2051 /* Should never happen */
2055 for (b = b->next; NULL != b; b = b->next)
2057 if (url_match(b->url, http))
2059 merge_current_action(action, b->action);
2065 /*********************************************************************
2067 * Function : get_forward_override_settings
2069 * Description : Returns forward settings as specified with the
2070 * forward-override{} action. forward-override accepts
2071 * forward lines similar to the one used in the
2072 * configuration file, but without the URL pattern.
2078 * in the configuration file can be replaced with
2079 * the action section:
2081 * {+forward-override{forward .}}
2085 * 1 : csp = Current client state (buffers, headers, etc...)
2087 * Returns : Pointer to forwarding structure in case of success.
2088 * Invalid syntax is fatal.
2090 *********************************************************************/
2091 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2093 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2094 char forward_settings[BUFFER_SIZE];
2095 char *http_parent = NULL;
2096 /* variable names were chosen for consistency reasons. */
2097 struct forward_spec *fwd = NULL;
2101 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2102 /* Should be enforced by load_one_actions_file() */
2103 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2105 /* Create a copy ssplit can modify */
2106 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2108 if (NULL != csp->fwd)
2111 * XXX: Currently necessary to prevent memory
2112 * leaks when the show-url-info cgi page is visited.
2114 unload_forward_spec(csp->fwd);
2118 * allocate a new forward node, valid only for
2119 * the lifetime of this request. Save its location
2120 * in csp as well, so sweep() can free it later on.
2122 fwd = csp->fwd = zalloc(sizeof(*fwd));
2125 log_error(LOG_LEVEL_FATAL,
2126 "can't allocate memory for forward-override{%s}", forward_override_line);
2127 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2131 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2132 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2134 fwd->type = SOCKS_NONE;
2136 /* Parse the parent HTTP proxy host:port */
2137 http_parent = vec[1];
2140 else if (vec_count == 3)
2142 char *socks_proxy = NULL;
2144 if (!strcasecmp(vec[0], "forward-socks4"))
2146 fwd->type = SOCKS_4;
2147 socks_proxy = vec[1];
2149 else if (!strcasecmp(vec[0], "forward-socks4a"))
2151 fwd->type = SOCKS_4A;
2152 socks_proxy = vec[1];
2154 else if (!strcasecmp(vec[0], "forward-socks5"))
2156 fwd->type = SOCKS_5;
2157 socks_proxy = vec[1];
2160 if (NULL != socks_proxy)
2162 /* Parse the SOCKS proxy host[:port] */
2163 fwd->gateway_port = 1080;
2164 parse_forwarder_address(socks_proxy,
2165 &fwd->gateway_host, &fwd->gateway_port);
2167 http_parent = vec[2];
2171 if (NULL == http_parent)
2173 log_error(LOG_LEVEL_FATAL,
2174 "Invalid forward-override syntax in: %s", forward_override_line);
2175 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2178 /* Parse http forwarding settings */
2179 if (strcmp(http_parent, ".") != 0)
2181 fwd->forward_port = 8000;
2182 parse_forwarder_address(http_parent,
2183 &fwd->forward_host, &fwd->forward_port);
2186 assert (NULL != fwd);
2188 log_error(LOG_LEVEL_CONNECT,
2189 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2195 /*********************************************************************
2197 * Function : forward_url
2199 * Description : Should we forward this to another proxy?
2202 * 1 : csp = Current client state (buffers, headers, etc...)
2203 * 2 : http = http_request request for current URL
2205 * Returns : Pointer to forwarding information.
2207 *********************************************************************/
2208 const struct forward_spec *forward_url(struct client_state *csp,
2209 const struct http_request *http)
2211 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2212 struct forward_spec *fwd = csp->config->forward;
2214 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2216 return get_forward_override_settings(csp);
2226 if (url_match(fwd->url, http))
2237 /*********************************************************************
2239 * Function : direct_response
2241 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2242 * request and if so, return a HTTP 501 to the client.
2244 * FIXME: I have a stupid name and I should handle the
2245 * requests properly. Still, what we do here is rfc-
2246 * compliant, whereas ignoring or forwarding are not.
2249 * 1 : csp = Current client state (buffers, headers, etc...)
2251 * Returns : http_response if , NULL if nonmatch or handler fail
2253 *********************************************************************/
2254 struct http_response *direct_response(struct client_state *csp)
2256 struct http_response *rsp;
2257 struct list_entry *p;
2259 if ((0 == strcmpic(csp->http->gpc, "trace"))
2260 || (0 == strcmpic(csp->http->gpc, "options")))
2262 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2264 if (!strncmpic(p->str, "Max-Forwards:", 13))
2266 unsigned int max_forwards;
2269 * If it's a Max-Forwards value of zero,
2270 * we have to intercept the request.
2272 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2275 * FIXME: We could handle at least TRACE here,
2276 * but that would require a verbatim copy of
2277 * the request which we don't have anymore
2279 log_error(LOG_LEVEL_HEADER,
2280 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2283 /* Get mem for response or fail*/
2284 if (NULL == (rsp = alloc_http_response()))
2286 return cgi_error_memory();
2289 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2291 free_http_response(rsp);
2292 return cgi_error_memory();
2296 rsp->crunch_reason = UNSUPPORTED;
2298 return(finish_http_response(csp, rsp));
2307 /*********************************************************************
2309 * Function : content_requires_filtering
2311 * Description : Checks whether there are any content filters
2312 * enabled for the current request and if they
2313 * can actually be applied..
2316 * 1 : csp = Current client state (buffers, headers, etc...)
2318 * Returns : TRUE for yes, FALSE otherwise
2320 *********************************************************************/
2321 int content_requires_filtering(struct client_state *csp)
2323 if ((csp->content_type & CT_TABOO)
2324 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2330 * Are we enabling text mode by force?
2332 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2335 * Do we really have to?
2337 if (csp->content_type & CT_TEXT)
2339 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2343 csp->content_type |= CT_TEXT;
2344 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2348 if (!(csp->content_type & CT_DECLARED))
2351 * The server didn't bother to declare a MIME-Type.
2352 * Assume it's text that can be filtered.
2354 * This also regulary happens with 304 responses,
2355 * therefore logging anything here would cause
2358 csp->content_type |= CT_TEXT;
2362 * Choose the applying filter function based on
2363 * the content type and action settings.
2365 if ((csp->content_type & CT_TEXT) &&
2366 (csp->rlist != NULL) &&
2367 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2371 else if ((csp->content_type & CT_GIF) &&
2372 (csp->action->flags & ACTION_DEANIMATE))
2382 /*********************************************************************
2384 * Function : content_filters_enabled
2386 * Description : Checks whether there are any content filters
2387 * enabled for the current request.
2390 * 1 : action = Action spec to check.
2392 * Returns : TRUE for yes, FALSE otherwise
2394 *********************************************************************/
2395 int content_filters_enabled(const struct current_action_spec *action)
2397 return ((action->flags & ACTION_DEANIMATE) ||
2398 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));
2402 /*********************************************************************
2404 * Function : filters_available
2406 * Description : Checks whether there are any filters available.
2409 * 1 : csp = Current client state (buffers, headers, etc...)
2411 * Returns : TRUE for yes, FALSE otherwise.
2413 *********************************************************************/
2414 int filters_available(const struct client_state *csp)
2417 for (i = 0; i < MAX_AF_FILES; i++)
2419 const struct file_list *fl = csp->rlist[i];
2420 if ((NULL != fl) && (NULL != fl->f))