1 const char filters_rcs[] = "$Id: filters.c,v 1.174 2012/10/21 12:35:15 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 char *url_segment = NULL;
1092 char **url_segments;
1093 size_t max_segments;
1096 log_error(LOG_LEVEL_REDIRECTS,
1097 "Checking \"%s\" for encoded redirects.", subject);
1100 * Check each parameter in the URL separately.
1101 * Sectionize the URL at "?" and "&",
1102 * go backwards through the segments, URL-decode them
1103 * and look for a URL in the decoded result.
1104 * Stop the search after the first match.
1106 * XXX: This estimate is guaranteed to be high enough as we
1107 * let ssplit() ignore empty fields, but also a bit wasteful.
1109 max_segments = strlen(subject) / 2;
1110 url_segments = malloc(max_segments * sizeof(char *));
1112 if (NULL == url_segments)
1114 log_error(LOG_LEVEL_ERROR,
1115 "Out of memory while decoding URL: %s", subject);
1120 segments = ssplit(subject, "?&", url_segments, max_segments);
1122 while (segments-- > 0)
1124 char *dtoken = url_decode(url_segments[segments]);
1127 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1130 url_segment = strstr(dtoken, "http://");
1131 if (NULL == url_segment)
1133 url_segment = strstr(dtoken, "https://");
1135 if (NULL != url_segment)
1137 url_segment = strdup(url_segment);
1139 if (url_segment == NULL)
1141 log_error(LOG_LEVEL_ERROR,
1142 "Out of memory while searching for redirects.");
1150 freez(url_segments);
1152 if (url_segment == NULL)
1156 subject = url_segment;
1160 /* Look for a URL inside this one, without decoding anything. */
1161 log_error(LOG_LEVEL_REDIRECTS,
1162 "Checking \"%s\" for unencoded redirects.", subject);
1166 * Find the last URL encoded in the request
1169 while ((tmp = strstr(tmp, "http://")) != NULL)
1173 tmp = (new_url != NULL) ? new_url : subject;
1174 while ((tmp = strstr(tmp, "https://")) != NULL)
1179 if ((new_url != NULL)
1180 && ( (new_url != subject)
1181 || (0 == strncmpic(subject, "http://", 7))
1182 || (0 == strncmpic(subject, "https://", 8))
1186 * Return new URL if we found a redirect
1187 * or if the subject already was a URL.
1189 * The second case makes sure that we can
1190 * chain get_last_url after another redirection check
1191 * (like rewrite_url) without losing earlier redirects.
1193 new_url = strdup(new_url);
1202 #endif /* def FEATURE_FAST_REDIRECTS */
1205 /*********************************************************************
1207 * Function : redirect_url
1209 * Description : Checks if Privoxy should answer the request with
1210 * a HTTP redirect and generates the redirect if
1214 * 1 : csp = Current client state (buffers, headers, etc...)
1216 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1218 *********************************************************************/
1219 struct http_response *redirect_url(struct client_state *csp)
1221 struct http_response *rsp;
1222 #ifdef FEATURE_FAST_REDIRECTS
1224 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1225 * as compile-time option? The user can easily disable
1226 * it in his action file.
1228 char * redirect_mode;
1229 #endif /* def FEATURE_FAST_REDIRECTS */
1230 char *old_url = NULL;
1231 char *new_url = NULL;
1232 char *redirection_string;
1234 if ((csp->action->flags & ACTION_REDIRECT))
1236 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1239 * If the redirection string begins with 's',
1240 * assume it's a pcrs command, otherwise treat it as
1241 * properly formatted URL and use it for the redirection
1244 * According to RFC 2616 section 14.30 the URL
1245 * has to be absolute and if the user tries:
1246 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1247 * she would get undefined results anyway.
1251 if (*redirection_string == 's')
1253 old_url = csp->http->url;
1254 new_url = rewrite_url(old_url, redirection_string);
1258 log_error(LOG_LEVEL_REDIRECTS,
1259 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1260 redirection_string);
1261 new_url = strdup(redirection_string);
1265 #ifdef FEATURE_FAST_REDIRECTS
1266 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1268 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1271 * If it exists, use the previously rewritten URL as input
1272 * otherwise just use the old path.
1274 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1275 new_url = get_last_url(old_url, redirect_mode);
1280 * Disable redirect checkers, so that they
1281 * will be only run more than once if the user
1282 * also enables them through tags.
1284 * From a performance point of view
1285 * it doesn't matter, but the duplicated
1286 * log messages are annoying.
1288 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1289 #endif /* def FEATURE_FAST_REDIRECTS */
1290 csp->action->flags &= ~ACTION_REDIRECT;
1292 /* Did any redirect action trigger? */
1295 if (url_requires_percent_encoding(new_url))
1298 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1299 strlen(new_url), new_url);
1300 encoded_url = percent_encode_url(new_url);
1302 if (encoded_url == NULL)
1304 return cgi_error_memory();
1306 new_url = encoded_url;
1307 assert(FALSE == url_requires_percent_encoding(new_url));
1310 if (0 == strcmpic(new_url, csp->http->url))
1312 log_error(LOG_LEVEL_ERROR,
1313 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1314 csp->http->url, new_url);
1319 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1321 if (NULL == (rsp = alloc_http_response()))
1324 return cgi_error_memory();
1327 if (enlist_unique_header(rsp->headers, "Location", new_url)
1328 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))))
1331 free_http_response(rsp);
1332 return cgi_error_memory();
1334 rsp->crunch_reason = REDIRECTED;
1337 return finish_http_response(csp, rsp);
1341 /* Only reached if no redirect is required */
1347 #ifdef FEATURE_IMAGE_BLOCKING
1348 /*********************************************************************
1350 * Function : is_imageurl
1352 * Description : Given a URL, decide whether it is an image or not,
1353 * using either the info from a previous +image action
1354 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1355 * is MSIE and not on a Mac, tell from the browser's accept
1359 * 1 : csp = Current client state (buffers, headers, etc...)
1361 * Returns : True (nonzero) if URL is an image, false (0)
1364 *********************************************************************/
1365 int is_imageurl(const struct client_state *csp)
1367 #ifdef FEATURE_IMAGE_DETECT_MSIE
1370 tmp = get_header_value(csp->headers, "User-Agent:");
1371 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1373 tmp = get_header_value(csp->headers, "Accept:");
1374 if (tmp && strstr(tmp, "image/gif"))
1376 /* Client will accept HTML. If this seems counterintuitive,
1386 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1388 return ((csp->action->flags & ACTION_IMAGE) != 0);
1391 #endif /* def FEATURE_IMAGE_BLOCKING */
1394 #ifdef FEATURE_TRUST
1395 /*********************************************************************
1397 * Function : is_untrusted_url
1399 * Description : Should we "distrust" this URL (and block it)?
1401 * Yes if it matches a line in the trustfile, or if the
1402 * referrer matches a line starting with "+" in the
1407 * 1 : csp = Current client state (buffers, headers, etc...)
1409 * Returns : 0 => trusted, 1 => untrusted
1411 *********************************************************************/
1412 int is_untrusted_url(const struct client_state *csp)
1414 struct file_list *fl;
1415 struct block_spec *b;
1416 struct url_spec **trusted_url;
1417 struct http_request rhttp[1];
1418 const char * referer;
1422 * If we don't have a trustlist, we trust everybody
1424 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1429 memset(rhttp, '\0', sizeof(*rhttp));
1432 * Do we trust the request URL itself?
1434 for (b = b->next; b ; b = b->next)
1436 if (url_match(b->url, csp->http))
1442 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1444 /* no referrer was supplied */
1450 * If not, do we maybe trust its referrer?
1452 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1458 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1460 if (url_match(*trusted_url, rhttp))
1462 /* if the URL's referrer is from a trusted referrer, then
1463 * add the target spec to the trustfile as an unblocked
1464 * domain and return 0 (which means it's OK).
1469 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1473 char * new_entry = strdup("~");
1475 string_append(&new_entry, csp->http->hostport);
1477 path = csp->http->path;
1478 if ( (path[0] == '/')
1480 && ((path_end = strchr(path + 2, '/')) != NULL))
1482 /* since this path points into a user's home space
1483 * be sure to include this spec in the trustfile.
1485 long path_len = path_end - path; /* save offset */
1486 path = strdup(path); /* Copy string */
1489 path_end = path + path_len; /* regenerate ptr to new buffer */
1490 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1492 string_join(&new_entry, path);
1496 * Give a reason for generating this entry.
1498 string_append(&new_entry, " # Trusted referrer was: ");
1499 string_append(&new_entry, referer);
1501 if (new_entry != NULL)
1503 if (-1 == fprintf(fp, "%s\n", new_entry))
1505 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1506 new_entry, csp->config->trustfile);
1512 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1513 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1520 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1521 csp->http->hostport, csp->config->trustfile);
1529 #endif /* def FEATURE_TRUST */
1532 /*********************************************************************
1534 * Function : pcrs_filter_response
1536 * Description : Execute all text substitutions from all applying
1537 * +filter actions on the text buffer that's been
1538 * accumulated in csp->iob->buf.
1541 * 1 : csp = Current client state (buffers, headers, etc...)
1543 * Returns : a pointer to the (newly allocated) modified buffer.
1544 * or NULL if there were no hits or something went wrong
1546 *********************************************************************/
1547 static char *pcrs_filter_response(struct client_state *csp)
1551 size_t size, prev_size;
1557 struct file_list *fl;
1558 struct re_filterfile_spec *b;
1559 struct list_entry *filtername;
1564 if (csp->iob->cur >= csp->iob->eod)
1569 if (filters_available(csp) == FALSE)
1571 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1572 "content filtering enabled, but no content filters available.");
1576 size = (size_t)(csp->iob->eod - csp->iob->cur);
1577 old = csp->iob->cur;
1579 for (i = 0; i < MAX_AF_FILES; i++)
1582 if ((NULL == fl) || (NULL == fl->f))
1585 * Either there are no filter files
1586 * left, or this filter file just
1587 * contains no valid filters.
1589 * Continue to be sure we don't miss
1590 * valid filter files that are chained
1591 * after empty or invalid ones.
1596 * For all applying +filter actions, look if a filter by that
1597 * name exists and if yes, execute it's pcrs_joblist on the
1600 for (b = fl->f; b; b = b->next)
1602 if (b->type != FT_CONTENT_FILTER)
1604 /* Skip header filters */
1608 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1609 filtername ; filtername = filtername->next)
1611 if (strcmp(b->name, filtername->str) == 0)
1613 int current_hits = 0; /* Number of hits caused by this filter */
1614 int job_number = 0; /* Which job we're currently executing */
1615 int job_hits = 0; /* How many hits the current job caused */
1616 pcrs_job *joblist = b->joblist;
1618 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1620 if (NULL == joblist)
1622 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1627 /* Apply all jobs from the joblist */
1628 for (job = joblist; NULL != job; job = job->next)
1631 job_hits = pcrs_execute(job, old, size, &new, &size);
1636 * That went well. Continue filtering
1637 * and use the result of this job as
1638 * input for the next one.
1640 current_hits += job_hits;
1641 if (old != csp->iob->cur)
1650 * This job caused an unexpected error. Inform the user
1651 * and skip the rest of the jobs in this filter. We could
1652 * continue with the next job, but usually the jobs
1653 * depend on each other or are similar enough to
1654 * fail for the same reason.
1656 * At the moment our pcrs expects the error codes of pcre 3.4,
1657 * but newer pcre versions can return additional error codes.
1658 * As a result pcrs_strerror()'s error message might be
1659 * "Unknown error ...", therefore we print the numerical value
1662 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1663 * should we use LOG_LEVEL_RE_FILTER instead?
1665 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1666 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1671 if (b->dynamic) pcrs_free_joblist(joblist);
1673 log_error(LOG_LEVEL_RE_FILTER,
1674 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1675 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1677 hits += current_hits;
1684 * If there were no hits, destroy our copy and let
1685 * chat() use the original in csp->iob
1693 csp->flags |= CSP_FLAG_MODIFIED;
1694 csp->content_length = size;
1695 clear_iob(csp->iob);
1702 /*********************************************************************
1704 * Function : gif_deanimate_response
1706 * Description : Deanimate the GIF image that has been accumulated in
1707 * csp->iob->buf, set csp->content_length to the modified
1708 * size and raise the CSP_FLAG_MODIFIED flag.
1711 * 1 : csp = Current client state (buffers, headers, etc...)
1713 * Returns : a pointer to the (newly allocated) modified buffer.
1714 * or NULL in case something went wrong.
1716 *********************************************************************/
1717 static char *gif_deanimate_response(struct client_state *csp)
1719 struct binbuffer *in, *out;
1723 size = (size_t)(csp->iob->eod - csp->iob->cur);
1725 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1726 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1728 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1732 in->buffer = csp->iob->cur;
1735 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1737 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1744 if ((int)size == out->offset)
1746 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1750 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1752 csp->content_length = out->offset;
1753 csp->flags |= CSP_FLAG_MODIFIED;
1763 /*********************************************************************
1765 * Function : get_filter_function
1767 * Description : Decides which content filter function has
1768 * to be applied (if any).
1771 * 1 : csp = Current client state (buffers, headers, etc...)
1773 * Returns : The content filter function to run, or
1774 * NULL if no content filter is active
1776 *********************************************************************/
1777 static filter_function_ptr get_filter_function(const struct client_state *csp)
1779 filter_function_ptr filter_function = NULL;
1782 * Choose the applying filter function based on
1783 * the content type and action settings.
1785 if ((csp->content_type & CT_TEXT) &&
1786 (csp->rlist != NULL) &&
1787 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1789 filter_function = pcrs_filter_response;
1791 else if ((csp->content_type & CT_GIF) &&
1792 (csp->action->flags & ACTION_DEANIMATE))
1794 filter_function = gif_deanimate_response;
1797 return filter_function;
1801 /*********************************************************************
1803 * Function : remove_chunked_transfer_coding
1805 * Description : In-situ remove the "chunked" transfer coding as defined
1806 * in rfc2616 from a buffer.
1809 * 1 : buffer = Pointer to the text buffer
1810 * 2 : size = In: Number of bytes to be processed,
1811 * Out: Number of bytes after de-chunking.
1812 * (undefined in case of errors)
1814 * Returns : JB_ERR_OK for success,
1815 * JB_ERR_PARSE otherwise
1817 *********************************************************************/
1818 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1821 unsigned int chunksize = 0;
1822 char *from_p, *to_p;
1825 from_p = to_p = buffer;
1827 if (sscanf(buffer, "%x", &chunksize) != 1)
1829 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1830 return JB_ERR_PARSE;
1833 while (chunksize > 0U)
1835 if (NULL == (from_p = strstr(from_p, "\r\n")))
1837 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1838 return JB_ERR_PARSE;
1841 if (chunksize >= *size - newsize)
1843 log_error(LOG_LEVEL_ERROR,
1844 "Chunk size %u exceeds buffered data left. "
1845 "Already digested %u of %u buffered bytes.",
1846 chunksize, (unsigned int)newsize, (unsigned int)*size);
1847 return JB_ERR_PARSE;
1849 newsize += chunksize;
1852 memmove(to_p, from_p, (size_t) chunksize);
1853 to_p = buffer + newsize;
1854 from_p += chunksize + 2;
1856 if (sscanf(from_p, "%x", &chunksize) != 1)
1858 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1863 /* XXX: Should get its own loglevel. */
1864 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1873 /*********************************************************************
1875 * Function : prepare_for_filtering
1877 * Description : If necessary, de-chunks and decompresses
1878 * the content so it can get filterd.
1881 * 1 : csp = Current client state (buffers, headers, etc...)
1883 * Returns : JB_ERR_OK for success,
1884 * JB_ERR_PARSE otherwise
1886 *********************************************************************/
1887 static jb_err prepare_for_filtering(struct client_state *csp)
1889 jb_err err = JB_ERR_OK;
1892 * If the body has a "chunked" transfer-encoding,
1893 * get rid of it, adjusting size and iob->eod
1895 if (csp->flags & CSP_FLAG_CHUNKED)
1897 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1899 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1900 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1901 if (JB_ERR_OK == err)
1903 csp->iob->eod = csp->iob->cur + size;
1904 csp->flags |= CSP_FLAG_MODIFIED;
1908 return JB_ERR_PARSE;
1914 * If the body has a supported transfer-encoding,
1915 * decompress it, adjusting size and iob->eod.
1917 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1919 if (0 == csp->iob->eod - csp->iob->cur)
1921 /* Nothing left after de-chunking. */
1925 err = decompress_iob(csp);
1927 if (JB_ERR_OK == err)
1929 csp->flags |= CSP_FLAG_MODIFIED;
1930 csp->content_type &= ~CT_TABOO;
1935 * Unset CT_GZIP and CT_DEFLATE to remember not
1936 * to modify the Content-Encoding header later.
1938 csp->content_type &= ~CT_GZIP;
1939 csp->content_type &= ~CT_DEFLATE;
1948 /*********************************************************************
1950 * Function : execute_content_filters
1952 * Description : Executes a given content filter.
1955 * 1 : csp = Current client state (buffers, headers, etc...)
1957 * Returns : Pointer to the modified buffer, or
1958 * NULL if filtering failed or wasn't necessary.
1960 *********************************************************************/
1961 char *execute_content_filters(struct client_state *csp)
1963 filter_function_ptr content_filter;
1965 assert(content_filters_enabled(csp->action));
1967 if (0 == csp->iob->eod - csp->iob->cur)
1970 * No content (probably status code 301, 302 ...),
1971 * no filtering necessary.
1976 if (JB_ERR_OK != prepare_for_filtering(csp))
1979 * failed to de-chunk or decompress.
1984 if (0 == csp->iob->eod - csp->iob->cur)
1987 * Clown alarm: chunked and/or compressed nothing delivered.
1992 content_filter = get_filter_function(csp);
1994 return ((*content_filter)(csp));
1998 /*********************************************************************
2000 * Function : get_url_actions
2002 * Description : Gets the actions for this URL.
2005 * 1 : csp = Current client state (buffers, headers, etc...)
2006 * 2 : http = http_request request for blocked URLs
2010 *********************************************************************/
2011 void get_url_actions(struct client_state *csp, struct http_request *http)
2013 struct file_list *fl;
2014 struct url_actions *b;
2017 init_current_action(csp->action);
2019 for (i = 0; i < MAX_AF_FILES; i++)
2021 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2026 apply_url_actions(csp->action, http, b);
2033 /*********************************************************************
2035 * Function : apply_url_actions
2037 * Description : Applies a list of URL actions.
2040 * 1 : action = Destination.
2041 * 2 : http = Current URL
2042 * 3 : b = list of URL actions to apply
2046 *********************************************************************/
2047 void apply_url_actions(struct current_action_spec *action,
2048 struct http_request *http,
2049 struct url_actions *b)
2053 /* Should never happen */
2057 for (b = b->next; NULL != b; b = b->next)
2059 if (url_match(b->url, http))
2061 merge_current_action(action, b->action);
2067 /*********************************************************************
2069 * Function : get_forward_override_settings
2071 * Description : Returns forward settings as specified with the
2072 * forward-override{} action. forward-override accepts
2073 * forward lines similar to the one used in the
2074 * configuration file, but without the URL pattern.
2080 * in the configuration file can be replaced with
2081 * the action section:
2083 * {+forward-override{forward .}}
2087 * 1 : csp = Current client state (buffers, headers, etc...)
2089 * Returns : Pointer to forwarding structure in case of success.
2090 * Invalid syntax is fatal.
2092 *********************************************************************/
2093 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2095 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2096 char forward_settings[BUFFER_SIZE];
2097 char *http_parent = NULL;
2098 /* variable names were chosen for consistency reasons. */
2099 struct forward_spec *fwd = NULL;
2103 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2104 /* Should be enforced by load_one_actions_file() */
2105 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2107 /* Create a copy ssplit can modify */
2108 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2110 if (NULL != csp->fwd)
2113 * XXX: Currently necessary to prevent memory
2114 * leaks when the show-url-info cgi page is visited.
2116 unload_forward_spec(csp->fwd);
2120 * allocate a new forward node, valid only for
2121 * the lifetime of this request. Save its location
2122 * in csp as well, so sweep() can free it later on.
2124 fwd = csp->fwd = zalloc(sizeof(*fwd));
2127 log_error(LOG_LEVEL_FATAL,
2128 "can't allocate memory for forward-override{%s}", forward_override_line);
2129 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2133 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2134 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2136 fwd->type = SOCKS_NONE;
2138 /* Parse the parent HTTP proxy host:port */
2139 http_parent = vec[1];
2142 else if (vec_count == 3)
2144 char *socks_proxy = NULL;
2146 if (!strcasecmp(vec[0], "forward-socks4"))
2148 fwd->type = SOCKS_4;
2149 socks_proxy = vec[1];
2151 else if (!strcasecmp(vec[0], "forward-socks4a"))
2153 fwd->type = SOCKS_4A;
2154 socks_proxy = vec[1];
2156 else if (!strcasecmp(vec[0], "forward-socks5"))
2158 fwd->type = SOCKS_5;
2159 socks_proxy = vec[1];
2162 if (NULL != socks_proxy)
2164 /* Parse the SOCKS proxy host[:port] */
2165 fwd->gateway_port = 1080;
2166 parse_forwarder_address(socks_proxy,
2167 &fwd->gateway_host, &fwd->gateway_port);
2169 http_parent = vec[2];
2173 if (NULL == http_parent)
2175 log_error(LOG_LEVEL_FATAL,
2176 "Invalid forward-override syntax in: %s", forward_override_line);
2177 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2180 /* Parse http forwarding settings */
2181 if (strcmp(http_parent, ".") != 0)
2183 fwd->forward_port = 8000;
2184 parse_forwarder_address(http_parent,
2185 &fwd->forward_host, &fwd->forward_port);
2188 assert (NULL != fwd);
2190 log_error(LOG_LEVEL_CONNECT,
2191 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2197 /*********************************************************************
2199 * Function : forward_url
2201 * Description : Should we forward this to another proxy?
2204 * 1 : csp = Current client state (buffers, headers, etc...)
2205 * 2 : http = http_request request for current URL
2207 * Returns : Pointer to forwarding information.
2209 *********************************************************************/
2210 const struct forward_spec *forward_url(struct client_state *csp,
2211 const struct http_request *http)
2213 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2214 struct forward_spec *fwd = csp->config->forward;
2216 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2218 return get_forward_override_settings(csp);
2228 if (url_match(fwd->url, http))
2239 /*********************************************************************
2241 * Function : direct_response
2243 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2244 * request and if so, return a HTTP 501 to the client.
2246 * FIXME: I have a stupid name and I should handle the
2247 * requests properly. Still, what we do here is rfc-
2248 * compliant, whereas ignoring or forwarding are not.
2251 * 1 : csp = Current client state (buffers, headers, etc...)
2253 * Returns : http_response if , NULL if nonmatch or handler fail
2255 *********************************************************************/
2256 struct http_response *direct_response(struct client_state *csp)
2258 struct http_response *rsp;
2259 struct list_entry *p;
2261 if ((0 == strcmpic(csp->http->gpc, "trace"))
2262 || (0 == strcmpic(csp->http->gpc, "options")))
2264 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2266 if (!strncmpic(p->str, "Max-Forwards:", 13))
2268 unsigned int max_forwards;
2271 * If it's a Max-Forwards value of zero,
2272 * we have to intercept the request.
2274 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2277 * FIXME: We could handle at least TRACE here,
2278 * but that would require a verbatim copy of
2279 * the request which we don't have anymore
2281 log_error(LOG_LEVEL_HEADER,
2282 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2285 /* Get mem for response or fail*/
2286 if (NULL == (rsp = alloc_http_response()))
2288 return cgi_error_memory();
2291 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2293 free_http_response(rsp);
2294 return cgi_error_memory();
2298 rsp->crunch_reason = UNSUPPORTED;
2300 return(finish_http_response(csp, rsp));
2309 /*********************************************************************
2311 * Function : content_requires_filtering
2313 * Description : Checks whether there are any content filters
2314 * enabled for the current request and if they
2315 * can actually be applied..
2318 * 1 : csp = Current client state (buffers, headers, etc...)
2320 * Returns : TRUE for yes, FALSE otherwise
2322 *********************************************************************/
2323 int content_requires_filtering(struct client_state *csp)
2325 if ((csp->content_type & CT_TABOO)
2326 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2332 * Are we enabling text mode by force?
2334 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2337 * Do we really have to?
2339 if (csp->content_type & CT_TEXT)
2341 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2345 csp->content_type |= CT_TEXT;
2346 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2350 if (!(csp->content_type & CT_DECLARED))
2353 * The server didn't bother to declare a MIME-Type.
2354 * Assume it's text that can be filtered.
2356 * This also regulary happens with 304 responses,
2357 * therefore logging anything here would cause
2360 csp->content_type |= CT_TEXT;
2364 * Choose the applying filter function based on
2365 * the content type and action settings.
2367 if ((csp->content_type & CT_TEXT) &&
2368 (csp->rlist != NULL) &&
2369 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2373 else if ((csp->content_type & CT_GIF) &&
2374 (csp->action->flags & ACTION_DEANIMATE))
2384 /*********************************************************************
2386 * Function : content_filters_enabled
2388 * Description : Checks whether there are any content filters
2389 * enabled for the current request.
2392 * 1 : action = Action spec to check.
2394 * Returns : TRUE for yes, FALSE otherwise
2396 *********************************************************************/
2397 int content_filters_enabled(const struct current_action_spec *action)
2399 return ((action->flags & ACTION_DEANIMATE) ||
2400 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));
2404 /*********************************************************************
2406 * Function : filters_available
2408 * Description : Checks whether there are any filters available.
2411 * 1 : csp = Current client state (buffers, headers, etc...)
2413 * Returns : TRUE for yes, FALSE otherwise.
2415 *********************************************************************/
2416 int filters_available(const struct client_state *csp)
2419 for (i = 0; i < MAX_AF_FILES; i++)
2421 const struct file_list *fl = csp->rlist[i];
2422 if ((NULL != fl) && (NULL != fl->f))