1 const char filters_rcs[] = "$Id: filters.c,v 1.121 2009/05/16 13:27:20 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `acl_addr', `add_stats', `block_acl', `block_imageurl',
9 * `block_url', `url_actions', `domain_split',
10 * `filter_popups', `forward_url', 'redirect_url',
11 * `ij_untrusted_url', `intercept_url', `pcrs_filter_respose',
12 * `ijb_send_banner', `trust_url', `gif_deanimate_response',
13 * `execute_single_pcrs_command', `rewrite_url',
16 * Copyright : Written by and Copyright (C) 2001, 2004-2008 the SourceForge
17 * Privoxy team. http://www.privoxy.org/
19 * Based on the Internet Junkbuster originally written
20 * by and Copyright (C) 1997 Anonymous Coders and
21 * Junkbusters Corporation. http://www.junkbusters.com
23 * This program is free software; you can redistribute it
24 * and/or modify it under the terms of the GNU General
25 * Public License as published by the Free Software
26 * Foundation; either version 2 of the License, or (at
27 * your option) any later version.
29 * This program is distributed in the hope that it will
30 * be useful, but WITHOUT ANY WARRANTY; without even the
31 * implied warranty of MERCHANTABILITY or FITNESS FOR A
32 * PARTICULAR PURPOSE. See the GNU General Public
33 * License for more details.
35 * The GNU General Public License should be included with
36 * this file. If not, you can view it at
37 * http://www.gnu.org/copyleft/gpl.html
38 * or write to the Free Software Foundation, Inc., 59
39 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
41 *********************************************************************/
47 #include <sys/types.h>
55 #include <sys/socket.h>
56 #endif /* def HAVE_RFC2553 */
61 #endif /* ndef __OS2__ */
62 #include <netinet/in.h>
65 #endif /* ndef _WIN32 */
69 #endif /* def __OS2__ */
77 #include "jbsockets.h"
82 #include "deanimate.h"
90 const char filters_h_rcs[] = FILTERS_H_VERSION;
92 /* Fix a problem with Solaris. There should be no effect on other
94 * Solaris's isspace() is a macro which uses it's argument directly
95 * as an array index. Therefore we need to make sure that high-bit
96 * characters generate +ve values, and ideally we also want to make
97 * the argument match the declared parameter type of "int".
99 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
101 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
102 static jb_err prepare_for_filtering(struct client_state *csp);
106 /*********************************************************************
108 * Function : sockaddr_storage_to_ip
110 * Description : Access internal structure of sockaddr_storage
113 * 1 : addr = socket address
114 * 2 : ip = IP address as array of octets in network order
115 * (it points into addr)
116 * 3 : len = length of IP address in octets
117 * 4 : port = port number in network order;
119 * Returns : 0 = no errror; -1 otherwise.
121 *********************************************************************/
122 int sockaddr_storage_to_ip(const struct sockaddr_storage *addr, uint8_t **ip,
123 unsigned int *len, in_port_t **port)
130 switch (addr->ss_family)
140 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
144 *port = &((struct sockaddr_in *)addr)->sin_port;
155 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
159 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
164 /* Unsupported address family */
172 /*********************************************************************
174 * Function : match_sockaddr
176 * Description : Check whether address matches network (IP address and port)
179 * 1 : network = socket address of subnework
180 * 2 : netmask = network mask as socket address
181 * 3 : address = checked socket address against given network
183 * Returns : 0 = doesn't match; 1 = does match
185 *********************************************************************/
186 int match_sockaddr(const struct sockaddr_storage *network,
187 const struct sockaddr_storage *netmask,
188 const struct sockaddr_storage *address)
190 uint8_t *network_addr, *netmask_addr, *address_addr;
191 unsigned int addr_len;
192 in_port_t *network_port, *netmask_port, *address_port;
195 if (network->ss_family != netmask->ss_family)
197 /* This should never happen */
198 log_error(LOG_LEVEL_ERROR,
199 "Internal error at %s:%llu: network and netmask differ in family",
204 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
205 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
206 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
208 /* Check for family */
209 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
210 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
212 /* Map AF_INET6 V4MAPPED address into AF_INET */
216 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
217 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
219 /* Map AF_INET6 V4MAPPED network into AF_INET */
224 else if (network->ss_family != address->ss_family)
229 /* XXX: Port check is signaled in netmask */
230 if (*netmask_port && *network_port != *address_port)
235 /* TODO: Optimize by checking by words insted of octets */
236 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
238 if ((network_addr[i] & netmask_addr[i]) !=
239 (address_addr[i] & netmask_addr[i]))
247 #endif /* def HAVE_RFC2553 */
250 /*********************************************************************
252 * Function : block_acl
254 * Description : Block this request?
255 * Decide yes or no based on ACL file.
258 * 1 : dst = The proxy or gateway address this is going to.
259 * Or NULL to check all possible targets.
260 * 2 : csp = Current client state (buffers, headers, etc...)
261 * Also includes the client IP address.
263 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
265 *********************************************************************/
266 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
268 struct access_control_list *acl = csp->config->acl;
270 /* if not using an access control list, then permit the connection */
276 /* search the list */
281 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
283 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
289 /* Just want to check if they have any access */
290 if (acl->action == ACL_PERMIT)
298 * XXX: An undefined acl->dst is full of zeros and should be
299 * considered a wildcard address. sockaddr_storage_to_ip()
300 * fails on such destinations because of unknown sa_familly
301 * (glibc only?). However this test is not portable.
303 * So, we signal the acl->dst is wildcard in wildcard_dst.
306 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
308 ((dst->addr & acl->dst->mask) == acl->dst->addr)
309 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
313 if (acl->action == ACL_PERMIT)
331 /*********************************************************************
333 * Function : acl_addr
335 * Description : Called from `load_config' to parse an ACL address.
338 * 1 : aspec = String specifying ACL address.
339 * 2 : aca = struct access_control_addr to fill in.
341 * Returns : 0 => Ok, everything else is an error.
343 *********************************************************************/
344 int acl_addr(const char *aspec, struct access_control_addr *aca)
348 struct addrinfo hints, *result;
350 in_port_t *mask_port;
351 unsigned int addr_len;
354 #endif /* def HAVE_RFC2553 */
356 char *acl_spec = NULL;
359 /* XXX: Depend on ai_family */
367 * Use a temporary acl spec copy so we can log
368 * the unmodified original in case of parse errors.
370 acl_spec = strdup(aspec);
371 if (acl_spec == NULL)
373 /* XXX: This will be logged as parse error. */
377 if ((p = strchr(acl_spec, '/')) != NULL)
380 if (ijb_isdigit(*p) == 0)
385 masklength = atoi(p);
388 if ((masklength < 0) ||
400 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
403 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
412 p = strchr(acl_spec, ':');
416 memset(&hints, 0, sizeof(struct addrinfo));
417 hints.ai_family = AF_UNSPEC;
418 hints.ai_socktype = SOCK_STREAM;
420 i = getaddrinfo(acl_spec, ((p) ? ++p : NULL), &hints, &result);
425 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
426 acl_spec, p, gai_strerror(i));
430 /* TODO: Allow multihomed hostnames */
431 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
432 freeaddrinfo(result);
439 port = strtol(p, &endptr, 10);
441 if (port <= 0 || port > 65535 || *endptr != '\0')
448 aca->port = (unsigned long)port;
450 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
453 if (aca->addr == INADDR_NONE)
455 /* XXX: This will be logged as parse error. */
458 #endif /* def HAVE_RFC2553 */
460 /* build the netmask */
462 /* Clip masklength according to current family. */
463 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
468 aca->mask.ss_family = aca->addr.ss_family;
469 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
476 /* ACL contains a port number, check ports in the future. */
481 * XXX: This could be optimized to operate on whole words instead
482 * of octets (128-bit CPU could do it in one iteration).
485 * Octets after prefix can be ommitted because of
486 * previous initialization to zeros.
488 for (i = 0; (i < addr_len) && masklength; i++)
498 * XXX: This assumes MSB of octet is on the left side.
499 * This should be true for all architectures or solved
502 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
509 for (i=1; i <= masklength ; i++)
511 aca->mask |= (1U << (32 - i));
514 /* now mask off the host portion of the ip address
515 * (i.e. save on the network portion of the address).
517 aca->addr = aca->addr & aca->mask;
518 #endif /* def HAVE_RFC2553 */
523 #endif /* def FEATURE_ACL */
526 /*********************************************************************
528 * Function : connect_port_is_forbidden
530 * Description : Check to see if CONNECT requests to the destination
531 * port of this request are forbidden. The check is
532 * independend of the actual request method.
535 * 1 : csp = Current client state (buffers, headers, etc...)
537 * Returns : True if yes, false otherwise.
539 *********************************************************************/
540 int connect_port_is_forbidden(const struct client_state *csp)
542 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
543 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
548 /*********************************************************************
550 * Function : block_url
552 * Description : Called from `chat'. Check to see if we need to block this.
555 * 1 : csp = Current client state (buffers, headers, etc...)
557 * Returns : NULL => unblocked, else HTTP block response
559 *********************************************************************/
560 struct http_response *block_url(struct client_state *csp)
562 struct http_response *rsp;
563 const char *new_content_type = NULL;
566 * If it's not blocked, don't block it ;-)
568 if ((csp->action->flags & ACTION_BLOCK) == 0)
572 if (csp->action->flags & ACTION_REDIRECT)
574 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
577 * Else, prepare a response
579 if (NULL == (rsp = alloc_http_response()))
581 return cgi_error_memory();
585 * If it's an image-url, send back an image or redirect
586 * as specified by the relevant +image action
588 #ifdef FEATURE_IMAGE_BLOCKING
589 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
593 /* determine HOW images should be blocked */
594 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
596 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
598 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
600 #if 1 /* Two alternative strategies, use this one for now: */
602 /* and handle accordingly: */
603 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
605 rsp->status = strdup("403 Request blocked by Privoxy");
606 if (rsp->status == NULL)
608 free_http_response(rsp);
609 return cgi_error_memory();
611 rsp->body = bindup(image_pattern_data, image_pattern_length);
612 if (rsp->body == NULL)
614 free_http_response(rsp);
615 return cgi_error_memory();
617 rsp->content_length = image_pattern_length;
619 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
621 free_http_response(rsp);
622 return cgi_error_memory();
626 else if (0 == strcmpic(p, "blank"))
628 rsp->status = strdup("403 Request blocked by Privoxy");
629 if (rsp->status == NULL)
631 free_http_response(rsp);
632 return cgi_error_memory();
634 rsp->body = bindup(image_blank_data, image_blank_length);
635 if (rsp->body == NULL)
637 free_http_response(rsp);
638 return cgi_error_memory();
640 rsp->content_length = image_blank_length;
642 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
644 free_http_response(rsp);
645 return cgi_error_memory();
651 rsp->status = strdup("302 Local Redirect from Privoxy");
652 if (rsp->status == NULL)
654 free_http_response(rsp);
655 return cgi_error_memory();
658 if (enlist_unique_header(rsp->headers, "Location", p))
660 free_http_response(rsp);
661 return cgi_error_memory();
665 #else /* Following code is disabled for now */
667 /* and handle accordingly: */
668 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
670 p = CGI_PREFIX "send-banner?type=pattern";
672 else if (0 == strcmpic(p, "blank"))
674 p = CGI_PREFIX "send-banner?type=blank";
676 rsp->status = strdup("302 Local Redirect from Privoxy");
677 if (rsp->status == NULL)
679 free_http_response(rsp);
680 return cgi_error_memory();
683 if (enlist_unique_header(rsp->headers, "Location", p))
685 free_http_response(rsp);
686 return cgi_error_memory();
688 #endif /* Preceeding code is disabled for now */
690 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
693 * Send empty document.
695 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
698 rsp->body = strdup(" ");
699 rsp->content_length = 1;
701 rsp->status = strdup("403 Request blocked by Privoxy");
702 if (rsp->status == NULL)
704 free_http_response(rsp);
705 return cgi_error_memory();
707 if (new_content_type != 0)
709 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
710 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
712 free_http_response(rsp);
713 return cgi_error_memory();
718 #endif /* def FEATURE_IMAGE_BLOCKING */
721 * Else, generate an HTML "blocked" message:
725 struct map * exports;
729 * Workaround for stupid Netscape bug which prevents
730 * pages from being displayed if loading a referenced
731 * JavaScript or style sheet fails. So make it appear
732 * as if it succeeded.
734 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
735 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
736 && !strstr(p, "Gecko") /* save Mozilla, */
737 && !strstr(p, "compatible") /* MSIE */
738 && !strstr(p, "Opera")) /* and Opera. */
740 rsp->status = strdup("200 Request for blocked URL");
744 rsp->status = strdup("403 Request for blocked URL");
747 if (rsp->status == NULL)
749 free_http_response(rsp);
750 return cgi_error_memory();
753 exports = default_exports(csp, NULL);
756 free_http_response(rsp);
757 return cgi_error_memory();
760 #ifdef FEATURE_FORCE_LOAD
761 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
763 * Export the force conditional block killer if
765 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
766 * - Privoxy is configured to enforce blocks, or
767 * - it's a CONNECT request and enforcing wouldn't work anyway.
769 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
770 || (0 == strcmpic(csp->http->gpc, "connect")))
771 #endif /* ndef FEATURE_FORCE_LOAD */
773 err = map_block_killer(exports, "force-support");
776 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
777 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
778 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
779 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
782 const char *block_reason;
783 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
785 block_reason = csp->action->string[ACTION_STRING_BLOCK];
789 assert(connect_port_is_forbidden(csp));
790 block_reason = "Forbidden CONNECT port.";
792 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
797 free_http_response(rsp);
798 return cgi_error_memory();
801 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
804 free_http_response(rsp);
805 return cgi_error_memory();
808 rsp->reason = RSP_REASON_BLOCKED;
810 return finish_http_response(csp, rsp);
816 /*********************************************************************
818 * Function : trust_url FIXME: I should be called distrust_url
820 * Description : Calls is_untrusted_url to determine if the URL is trusted
821 * and if not, returns a HTTP 403 response with a reject message.
824 * 1 : csp = Current client state (buffers, headers, etc...)
826 * Returns : NULL => trusted, else http_response.
828 *********************************************************************/
829 struct http_response *trust_url(struct client_state *csp)
831 struct http_response *rsp;
832 struct map * exports;
833 char buf[BUFFER_SIZE];
835 struct url_spec **tl;
840 * Don't bother to work on trusted URLs
842 if (!is_untrusted_url(csp))
848 * Else, prepare a response:
850 if (NULL == (rsp = alloc_http_response()))
852 return cgi_error_memory();
855 rsp->status = strdup("403 Request blocked by Privoxy");
856 exports = default_exports(csp, NULL);
857 if (exports == NULL || rsp->status == NULL)
859 free_http_response(rsp);
860 return cgi_error_memory();
864 * Export the protocol, host, port, and referrer information
866 err = map(exports, "hostport", 1, csp->http->hostport, 1);
867 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
868 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
870 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
872 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
876 if (!err) err = map(exports, "referrer", 1, "none set", 1);
882 free_http_response(rsp);
883 return cgi_error_memory();
887 * Export the trust list
890 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
892 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
893 string_append(&p, buf);
895 err = map(exports, "trusted-referrers", 1, p, 0);
900 free_http_response(rsp);
901 return cgi_error_memory();
905 * Export the trust info, if available
907 if (csp->config->trust_info->first)
909 struct list_entry *l;
912 for (l = csp->config->trust_info->first; l ; l = l->next)
914 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
915 string_append(&p, buf);
917 err = map(exports, "trust-info", 1, p, 0);
921 err = map_block_killer(exports, "have-trust-info");
927 free_http_response(rsp);
928 return cgi_error_memory();
932 * Export the force conditional block killer if
934 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
935 * - Privoxy is configured to enforce blocks, or
936 * - it's a CONNECT request and enforcing wouldn't work anyway.
938 #ifdef FEATURE_FORCE_LOAD
939 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
940 || (0 == strcmpic(csp->http->gpc, "connect")))
942 err = map_block_killer(exports, "force-support");
946 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
948 #else /* ifndef FEATURE_FORCE_LOAD */
949 err = map_block_killer(exports, "force-support");
950 #endif /* ndef FEATURE_FORCE_LOAD */
955 free_http_response(rsp);
956 return cgi_error_memory();
962 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
965 free_http_response(rsp);
966 return cgi_error_memory();
968 rsp->reason = RSP_REASON_UNTRUSTED;
970 return finish_http_response(csp, rsp);
972 #endif /* def FEATURE_TRUST */
975 /*********************************************************************
977 * Function : compile_dynamic_pcrs_job_list
979 * Description : Compiles a dynamic pcrs job list (one with variables
980 * resolved at request time)
983 * 1 : csp = Current client state (buffers, headers, etc...)
984 * 2 : b = The filter list to compile
986 * Returns : NULL in case of errors, otherwise the
989 *********************************************************************/
990 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
992 struct list_entry *pattern;
993 pcrs_job *job_list = NULL;
994 pcrs_job *dummy = NULL;
995 pcrs_job *lastjob = NULL;
998 const struct pcrs_variable variables[] =
1000 {"url", csp->http->url, 1},
1001 {"path", csp->http->path, 1},
1002 {"host", csp->http->host, 1},
1003 {"origin", csp->ip_addr_str, 1},
1007 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
1009 assert(pattern->str != NULL);
1011 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
1015 log_error(LOG_LEVEL_ERROR,
1016 "Adding filter job \'%s\' to dynamic filter %s failed: %s",
1017 pattern->str, b->name, pcrs_strerror(error));
1022 if (error == PCRS_WARN_TRUNCATION)
1024 log_error(LOG_LEVEL_ERROR,
1025 "At least one of the variables in \'%s\' had to "
1026 "be truncated before compilation", pattern->str);
1028 if (job_list == NULL)
1034 lastjob->next = dummy;
1044 /*********************************************************************
1046 * Function : rewrite_url
1048 * Description : Rewrites a URL with a single pcrs command
1049 * and returns the result if it differs from the
1050 * original and isn't obviously invalid.
1053 * 1 : old_url = URL to rewrite.
1054 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1057 * Returns : NULL if the pcrs_command didn't change the url, or
1058 * the result of the modification.
1060 *********************************************************************/
1061 char *rewrite_url(char *old_url, const char *pcrs_command)
1063 char *new_url = NULL;
1067 assert(pcrs_command);
1069 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1073 log_error(LOG_LEVEL_REDIRECTS,
1074 "pcrs command \"%s\" didn't change \"%s\".",
1075 pcrs_command, old_url);
1080 log_error(LOG_LEVEL_REDIRECTS,
1081 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1082 pcrs_command, old_url, pcrs_strerror(hits));
1085 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1087 log_error(LOG_LEVEL_ERROR,
1088 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1089 "but the result doesn't look like a valid URL and will be ignored.",
1090 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1095 log_error(LOG_LEVEL_REDIRECTS,
1096 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1097 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1105 #ifdef FEATURE_FAST_REDIRECTS
1106 /*********************************************************************
1108 * Function : get_last_url
1110 * Description : Search for the last URL inside a string.
1111 * If the string already is a URL, it will
1112 * be the first URL found.
1115 * 1 : subject = the string to check
1116 * 2 : redirect_mode = +fast-redirect{} mode
1118 * Returns : NULL if no URL was found, or
1119 * the last URL found.
1121 *********************************************************************/
1122 char *get_last_url(char *subject, const char *redirect_mode)
1124 char *new_url = NULL;
1128 assert(redirect_mode);
1130 subject = strdup(subject);
1131 if (subject == NULL)
1133 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1137 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1139 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1140 new_url = url_decode(subject);
1141 if (new_url != NULL)
1148 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1152 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1155 * Find the last URL encoded in the request
1158 while ((tmp = strstr(tmp, "http://")) != NULL)
1162 tmp = (new_url != NULL) ? new_url : subject;
1163 while ((tmp = strstr(tmp, "https://")) != NULL)
1168 if ((new_url != NULL)
1169 && ( (new_url != subject)
1170 || (0 == strncmpic(subject, "http://", 7))
1171 || (0 == strncmpic(subject, "https://", 8))
1175 * Return new URL if we found a redirect
1176 * or if the subject already was a URL.
1178 * The second case makes sure that we can
1179 * chain get_last_url after another redirection check
1180 * (like rewrite_url) without losing earlier redirects.
1182 new_url = strdup(new_url);
1191 #endif /* def FEATURE_FAST_REDIRECTS */
1194 /*********************************************************************
1196 * Function : redirect_url
1198 * Description : Checks if Privoxy should answer the request with
1199 * a HTTP redirect and generates the redirect if
1203 * 1 : csp = Current client state (buffers, headers, etc...)
1205 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1207 *********************************************************************/
1208 struct http_response *redirect_url(struct client_state *csp)
1210 struct http_response *rsp;
1211 #ifdef FEATURE_FAST_REDIRECTS
1213 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1214 * as compile-time option? The user can easily disable
1215 * it in his action file.
1217 char * redirect_mode;
1218 #endif /* def FEATURE_FAST_REDIRECTS */
1219 char *old_url = NULL;
1220 char *new_url = NULL;
1221 char *redirection_string;
1223 if ((csp->action->flags & ACTION_REDIRECT))
1225 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1228 * If the redirection string begins with 's',
1229 * assume it's a pcrs command, otherwise treat it as
1230 * properly formatted URL and use it for the redirection
1233 * According to RFC 2616 section 14.30 the URL
1234 * has to be absolute and if the user tries:
1235 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1236 * she would get undefined results anyway.
1240 if (*redirection_string == 's')
1242 old_url = csp->http->url;
1243 new_url = rewrite_url(old_url, redirection_string);
1247 log_error(LOG_LEVEL_REDIRECTS,
1248 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1249 redirection_string);
1250 new_url = strdup(redirection_string);
1254 #ifdef FEATURE_FAST_REDIRECTS
1255 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1257 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1260 * If it exists, use the previously rewritten URL as input
1261 * otherwise just use the old path.
1263 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1264 new_url = get_last_url(old_url, redirect_mode);
1269 * Disable redirect checkers, so that they
1270 * will be only run more than once if the user
1271 * also enables them through tags.
1273 * From a performance point of view
1274 * it doesn't matter, but the duplicated
1275 * log messages are annoying.
1277 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1278 #endif /* def FEATURE_FAST_REDIRECTS */
1279 csp->action->flags &= ~ACTION_REDIRECT;
1281 /* Did any redirect action trigger? */
1284 if (0 == strcmpic(new_url, csp->http->url))
1286 log_error(LOG_LEVEL_ERROR,
1287 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1288 csp->http->url, new_url);
1293 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1295 if (NULL == (rsp = alloc_http_response()))
1298 return cgi_error_memory();
1301 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1302 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1305 free_http_response(rsp);
1306 return cgi_error_memory();
1308 rsp->reason = RSP_REASON_REDIRECTED;
1311 return finish_http_response(csp, rsp);
1315 /* Only reached if no redirect is required */
1321 #ifdef FEATURE_IMAGE_BLOCKING
1322 /*********************************************************************
1324 * Function : is_imageurl
1326 * Description : Given a URL, decide whether it is an image or not,
1327 * using either the info from a previous +image action
1328 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1329 * is MSIE and not on a Mac, tell from the browser's accept
1333 * 1 : csp = Current client state (buffers, headers, etc...)
1335 * Returns : True (nonzero) if URL is an image, false (0)
1338 *********************************************************************/
1339 int is_imageurl(const struct client_state *csp)
1341 #ifdef FEATURE_IMAGE_DETECT_MSIE
1344 tmp = get_header_value(csp->headers, "User-Agent:");
1345 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1347 tmp = get_header_value(csp->headers, "Accept:");
1348 if (tmp && strstr(tmp, "image/gif"))
1350 /* Client will accept HTML. If this seems counterintuitive,
1360 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1362 return ((csp->action->flags & ACTION_IMAGE) != 0);
1365 #endif /* def FEATURE_IMAGE_BLOCKING */
1368 #ifdef FEATURE_TRUST
1369 /*********************************************************************
1371 * Function : is_untrusted_url
1373 * Description : Should we "distrust" this URL (and block it)?
1375 * Yes if it matches a line in the trustfile, or if the
1376 * referrer matches a line starting with "+" in the
1381 * 1 : csp = Current client state (buffers, headers, etc...)
1383 * Returns : 0 => trusted, 1 => untrusted
1385 *********************************************************************/
1386 int is_untrusted_url(const struct client_state *csp)
1388 struct file_list *fl;
1389 struct block_spec *b;
1390 struct url_spec **trusted_url;
1391 struct http_request rhttp[1];
1392 const char * referer;
1396 * If we don't have a trustlist, we trust everybody
1398 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1403 memset(rhttp, '\0', sizeof(*rhttp));
1406 * Do we trust the request URL itself?
1408 for (b = b->next; b ; b = b->next)
1410 if (url_match(b->url, csp->http))
1416 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1418 /* no referrer was supplied */
1424 * If not, do we maybe trust its referrer?
1426 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1432 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1434 if (url_match(*trusted_url, rhttp))
1436 /* if the URL's referrer is from a trusted referrer, then
1437 * add the target spec to the trustfile as an unblocked
1438 * domain and return 0 (which means it's OK).
1443 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1447 char * new_entry = strdup("~");
1449 string_append(&new_entry, csp->http->hostport);
1451 path = csp->http->path;
1452 if ( (path[0] == '/')
1454 && ((path_end = strchr(path + 2, '/')) != NULL))
1456 /* since this path points into a user's home space
1457 * be sure to include this spec in the trustfile.
1459 long path_len = path_end - path; /* save offset */
1460 path = strdup(path); /* Copy string */
1463 path_end = path + path_len; /* regenerate ptr to new buffer */
1464 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1466 string_join(&new_entry, path);
1470 * Give a reason for generating this entry.
1472 string_append(&new_entry, " # Trusted referrer was: ");
1473 string_append(&new_entry, referer);
1475 if (new_entry != NULL)
1477 if (-1 == fprintf(fp, "%s\n", new_entry))
1479 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1480 new_entry, csp->config->trustfile);
1486 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1487 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1494 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1495 csp->http->hostport, csp->config->trustfile);
1503 #endif /* def FEATURE_TRUST */
1506 /*********************************************************************
1508 * Function : pcrs_filter_response
1510 * Description : Execute all text substitutions from all applying
1511 * +filter actions on the text buffer that's been
1512 * accumulated in csp->iob->buf.
1515 * 1 : csp = Current client state (buffers, headers, etc...)
1517 * Returns : a pointer to the (newly allocated) modified buffer.
1518 * or NULL if there were no hits or something went wrong
1520 *********************************************************************/
1521 static char *pcrs_filter_response(struct client_state *csp)
1524 size_t size, prev_size;
1530 struct file_list *fl;
1531 struct re_filterfile_spec *b;
1532 struct list_entry *filtername;
1534 int i, found_filters = 0;
1539 if (csp->iob->cur >= csp->iob->eod)
1545 * Need to check the set of re_filterfiles...
1547 for (i = 0; i < MAX_AF_FILES; i++)
1560 if (0 == found_filters)
1562 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1563 "content filtering enabled, but no content filters available.");
1567 size = (size_t)(csp->iob->eod - csp->iob->cur);
1568 old = csp->iob->cur;
1570 for (i = 0; i < MAX_AF_FILES; i++)
1573 if ((NULL == fl) || (NULL == fl->f))
1576 * Either there are no filter files
1577 * left, or this filter file just
1578 * contains no valid filters.
1580 * Continue to be sure we don't miss
1581 * valid filter files that are chained
1582 * after empty or invalid ones.
1587 * For all applying +filter actions, look if a filter by that
1588 * name exists and if yes, execute it's pcrs_joblist on the
1591 for (b = fl->f; b; b = b->next)
1593 if (b->type != FT_CONTENT_FILTER)
1595 /* Skip header filters */
1599 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1600 filtername ; filtername = filtername->next)
1602 if (strcmp(b->name, filtername->str) == 0)
1604 int current_hits = 0; /* Number of hits caused by this filter */
1605 int job_number = 0; /* Which job we're currently executing */
1606 int job_hits = 0; /* How many hits the current job caused */
1607 pcrs_job *joblist = b->joblist;
1609 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1611 if (NULL == joblist)
1613 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1618 /* Apply all jobs from the joblist */
1619 for (job = joblist; NULL != job; job = job->next)
1622 job_hits = pcrs_execute(job, old, size, &new, &size);
1627 * That went well. Continue filtering
1628 * and use the result of this job as
1629 * input for the next one.
1631 current_hits += job_hits;
1632 if (old != csp->iob->cur)
1641 * This job caused an unexpected error. Inform the user
1642 * and skip the rest of the jobs in this filter. We could
1643 * continue with the next job, but usually the jobs
1644 * depend on each other or are similar enough to
1645 * fail for the same reason.
1647 * At the moment our pcrs expects the error codes of pcre 3.4,
1648 * but newer pcre versions can return additional error codes.
1649 * As a result pcrs_strerror()'s error message might be
1650 * "Unknown error ...", therefore we print the numerical value
1653 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1654 * should we use LOG_LEVEL_RE_FILTER instead?
1656 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1657 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1662 if (b->dynamic) pcrs_free_joblist(joblist);
1664 log_error(LOG_LEVEL_RE_FILTER,
1665 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1666 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1668 hits += current_hits;
1675 * If there were no hits, destroy our copy and let
1676 * chat() use the original in csp->iob
1684 csp->flags |= CSP_FLAG_MODIFIED;
1685 csp->content_length = size;
1693 /*********************************************************************
1695 * Function : gif_deanimate_response
1697 * Description : Deanimate the GIF image that has been accumulated in
1698 * csp->iob->buf, set csp->content_length to the modified
1699 * size and raise the CSP_FLAG_MODIFIED flag.
1702 * 1 : csp = Current client state (buffers, headers, etc...)
1704 * Returns : a pointer to the (newly allocated) modified buffer.
1705 * or NULL in case something went wrong.
1707 *********************************************************************/
1708 static char *gif_deanimate_response(struct client_state *csp)
1710 struct binbuffer *in, *out;
1714 size = (size_t)(csp->iob->eod - csp->iob->cur);
1716 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1717 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1719 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1723 in->buffer = csp->iob->cur;
1726 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1728 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1735 if ((int)size == out->offset)
1737 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1741 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1743 csp->content_length = out->offset;
1744 csp->flags |= CSP_FLAG_MODIFIED;
1754 /*********************************************************************
1756 * Function : get_filter_function
1758 * Description : Decides which content filter function has
1759 * to be applied (if any).
1762 * 1 : csp = Current client state (buffers, headers, etc...)
1764 * Returns : The content filter function to run, or
1765 * NULL if no content filter is active
1767 *********************************************************************/
1768 filter_function_ptr get_filter_function(struct client_state *csp)
1770 filter_function_ptr filter_function = NULL;
1772 if ((csp->content_type & CT_TABOO)
1773 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
1779 * Are we enabling text mode by force?
1781 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1784 * Do we really have to?
1786 if (csp->content_type & CT_TEXT)
1788 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1792 csp->content_type |= CT_TEXT;
1793 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1797 if (!(csp->content_type & CT_DECLARED))
1800 * The server didn't bother to declare a MIME-Type.
1801 * Assume it's text that can be filtered.
1803 * This also regulary happens with 304 responses,
1804 * therefore logging anything here would cause
1807 csp->content_type |= CT_TEXT;
1811 * Choose the applying filter function based on
1812 * the content type and action settings.
1814 if ((csp->content_type & CT_TEXT) &&
1815 (csp->rlist != NULL) &&
1816 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1818 filter_function = pcrs_filter_response;
1820 else if ((csp->content_type & CT_GIF) &&
1821 (csp->action->flags & ACTION_DEANIMATE))
1823 filter_function = gif_deanimate_response;
1826 return filter_function;
1830 /*********************************************************************
1832 * Function : remove_chunked_transfer_coding
1834 * Description : In-situ remove the "chunked" transfer coding as defined
1835 * in rfc2616 from a buffer.
1838 * 1 : buffer = Pointer to the text buffer
1839 * 2 : size = In: Number of bytes to be processed,
1840 * Out: Number of bytes after de-chunking.
1841 * (undefined in case of errors)
1843 * Returns : JB_ERR_OK for success,
1844 * JB_ERR_PARSE otherwise
1846 *********************************************************************/
1847 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1850 unsigned int chunksize = 0;
1851 char *from_p, *to_p;
1854 from_p = to_p = buffer;
1856 if (sscanf(buffer, "%x", &chunksize) != 1)
1858 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1859 return JB_ERR_PARSE;
1862 while (chunksize > 0U)
1864 if (NULL == (from_p = strstr(from_p, "\r\n")))
1866 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1867 return JB_ERR_PARSE;
1870 if ((newsize += chunksize) >= *size)
1872 log_error(LOG_LEVEL_ERROR,
1873 "Chunk size %d exceeds buffer size %d in \"chunked\" transfer coding",
1875 return JB_ERR_PARSE;
1879 memmove(to_p, from_p, (size_t) chunksize);
1880 to_p = buffer + newsize;
1881 from_p += chunksize + 2;
1883 if (sscanf(from_p, "%x", &chunksize) != 1)
1885 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1890 /* XXX: Should get its own loglevel. */
1891 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1900 /*********************************************************************
1902 * Function : prepare_for_filtering
1904 * Description : If necessary, de-chunks and decompresses
1905 * the content so it can get filterd.
1908 * 1 : csp = Current client state (buffers, headers, etc...)
1910 * Returns : JB_ERR_OK for success,
1911 * JB_ERR_PARSE otherwise
1913 *********************************************************************/
1914 static jb_err prepare_for_filtering(struct client_state *csp)
1916 jb_err err = JB_ERR_OK;
1919 * If the body has a "chunked" transfer-encoding,
1920 * get rid of it, adjusting size and iob->eod
1922 if (csp->flags & CSP_FLAG_CHUNKED)
1924 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1926 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1927 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1928 if (JB_ERR_OK == err)
1930 csp->iob->eod = csp->iob->cur + size;
1931 csp->flags |= CSP_FLAG_MODIFIED;
1935 return JB_ERR_PARSE;
1941 * If the body has a supported transfer-encoding,
1942 * decompress it, adjusting size and iob->eod.
1944 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1946 if (0 == csp->iob->eod - csp->iob->cur)
1948 /* Nothing left after de-chunking. */
1952 err = decompress_iob(csp);
1954 if (JB_ERR_OK == err)
1956 csp->flags |= CSP_FLAG_MODIFIED;
1957 csp->content_type &= ~CT_TABOO;
1962 * Unset CT_GZIP and CT_DEFLATE to remember not
1963 * to modify the Content-Encoding header later.
1965 csp->content_type &= ~CT_GZIP;
1966 csp->content_type &= ~CT_DEFLATE;
1975 /*********************************************************************
1977 * Function : execute_content_filter
1979 * Description : Executes a given content filter.
1982 * 1 : csp = Current client state (buffers, headers, etc...)
1983 * 2 : content_filter = The filter function to execute
1985 * Returns : Pointer to the modified buffer, or
1986 * NULL if filtering failed or wasn't necessary.
1988 *********************************************************************/
1989 char *execute_content_filter(struct client_state *csp, filter_function_ptr content_filter)
1991 if (0 == csp->iob->eod - csp->iob->cur)
1994 * No content (probably status code 301, 302 ...),
1995 * no filtering necessary.
2000 if (JB_ERR_OK != prepare_for_filtering(csp))
2003 * failed to de-chunk or decompress.
2008 if (0 == csp->iob->eod - csp->iob->cur)
2011 * Clown alarm: chunked and/or compressed nothing delivered.
2016 return ((*content_filter)(csp));
2020 /*********************************************************************
2022 * Function : get_url_actions
2024 * Description : Gets the actions for this URL.
2027 * 1 : csp = Current client state (buffers, headers, etc...)
2028 * 2 : http = http_request request for blocked URLs
2032 *********************************************************************/
2033 void get_url_actions(struct client_state *csp, struct http_request *http)
2035 struct file_list *fl;
2036 struct url_actions *b;
2039 init_current_action(csp->action);
2041 for (i = 0; i < MAX_AF_FILES; i++)
2043 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2048 apply_url_actions(csp->action, http, b);
2055 /*********************************************************************
2057 * Function : apply_url_actions
2059 * Description : Applies a list of URL actions.
2062 * 1 : action = Destination.
2063 * 2 : http = Current URL
2064 * 3 : b = list of URL actions to apply
2068 *********************************************************************/
2069 void apply_url_actions(struct current_action_spec *action,
2070 struct http_request *http,
2071 struct url_actions *b)
2075 /* Should never happen */
2079 for (b = b->next; NULL != b; b = b->next)
2081 if (url_match(b->url, http))
2083 merge_current_action(action, b->action);
2089 /*********************************************************************
2091 * Function : get_forward_override_settings
2093 * Description : Returns forward settings as specified with the
2094 * forward-override{} action. forward-override accepts
2095 * forward lines similar to the one used in the
2096 * configuration file, but without the URL pattern.
2102 * in the configuration file can be replaced with
2103 * the action section:
2105 * {+forward-override{forward .}}
2109 * 1 : csp = Current client state (buffers, headers, etc...)
2111 * Returns : Pointer to forwarding structure in case of success.
2112 * Invalid syntax is fatal.
2114 *********************************************************************/
2115 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2117 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2118 char forward_settings[BUFFER_SIZE];
2119 char *http_parent = NULL;
2120 /* variable names were chosen for consistency reasons. */
2121 struct forward_spec *fwd = NULL;
2125 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2126 /* Should be enforced by load_one_actions_file() */
2127 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2129 /* Create a copy ssplit can modify */
2130 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2132 if (NULL != csp->fwd)
2135 * XXX: Currently necessary to prevent memory
2136 * leaks when the show-url-info cgi page is visited.
2138 unload_forward_spec(csp->fwd);
2142 * allocate a new forward node, valid only for
2143 * the lifetime of this request. Save its location
2144 * in csp as well, so sweep() can free it later on.
2146 fwd = csp->fwd = zalloc(sizeof(*fwd));
2149 log_error(LOG_LEVEL_FATAL,
2150 "can't allocate memory for forward-override{%s}", forward_override_line);
2151 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2155 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2156 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2158 fwd->type = SOCKS_NONE;
2160 /* Parse the parent HTTP proxy host:port */
2161 http_parent = vec[1];
2164 else if (vec_count == 3)
2166 char *socks_proxy = NULL;
2168 if (!strcasecmp(vec[0], "forward-socks4"))
2170 fwd->type = SOCKS_4;
2171 socks_proxy = vec[1];
2173 else if (!strcasecmp(vec[0], "forward-socks4a"))
2175 fwd->type = SOCKS_4A;
2176 socks_proxy = vec[1];
2178 else if (!strcasecmp(vec[0], "forward-socks5"))
2180 fwd->type = SOCKS_5;
2181 socks_proxy = vec[1];
2184 if (NULL != socks_proxy)
2186 /* Parse the SOCKS proxy host[:port] */
2187 fwd->gateway_port = 1080;
2188 parse_forwarder_address(socks_proxy,
2189 &fwd->gateway_host, &fwd->gateway_port);
2191 http_parent = vec[2];
2195 if (NULL == http_parent)
2197 log_error(LOG_LEVEL_FATAL,
2198 "Invalid forward-override syntax in: %s", forward_override_line);
2199 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2202 /* Parse http forwarding settings */
2203 if (strcmp(http_parent, ".") != 0)
2205 fwd->forward_port = 8000;
2206 parse_forwarder_address(http_parent,
2207 &fwd->forward_host, &fwd->forward_port);
2210 assert (NULL != fwd);
2212 log_error(LOG_LEVEL_CONNECT,
2213 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2219 /*********************************************************************
2221 * Function : forward_url
2223 * Description : Should we forward this to another proxy?
2226 * 1 : csp = Current client state (buffers, headers, etc...)
2227 * 2 : http = http_request request for current URL
2229 * Returns : Pointer to forwarding information.
2231 *********************************************************************/
2232 const struct forward_spec *forward_url(struct client_state *csp,
2233 const struct http_request *http)
2235 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2236 struct forward_spec *fwd = csp->config->forward;
2238 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2240 return get_forward_override_settings(csp);
2250 if (url_match(fwd->url, http))
2261 /*********************************************************************
2263 * Function : direct_response
2265 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2266 * request and if so, return a HTTP 501 to the client.
2268 * FIXME: I have a stupid name and I should handle the
2269 * requests properly. Still, what we do here is rfc-
2270 * compliant, whereas ignoring or forwarding are not.
2273 * 1 : csp = Current client state (buffers, headers, etc...)
2275 * Returns : http_response if , NULL if nonmatch or handler fail
2277 *********************************************************************/
2278 struct http_response *direct_response(struct client_state *csp)
2280 struct http_response *rsp;
2281 struct list_entry *p;
2283 if ((0 == strcmpic(csp->http->gpc, "trace"))
2284 || (0 == strcmpic(csp->http->gpc, "options")))
2286 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2288 if (!strncmpic("Max-Forwards:", p->str, 13))
2290 unsigned int max_forwards;
2293 * If it's a Max-Forwards value of zero,
2294 * we have to intercept the request.
2296 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2299 * FIXME: We could handle at least TRACE here,
2300 * but that would require a verbatim copy of
2301 * the request which we don't have anymore
2303 log_error(LOG_LEVEL_HEADER,
2304 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2307 /* Get mem for response or fail*/
2308 if (NULL == (rsp = alloc_http_response()))
2310 return cgi_error_memory();
2313 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2315 free_http_response(rsp);
2316 return cgi_error_memory();
2320 rsp->reason = RSP_REASON_UNSUPPORTED;
2322 return(finish_http_response(csp, rsp));
2331 /*********************************************************************
2333 * Function : content_filters_enabled
2335 * Description : Checks whether there are any content filters
2336 * enabled for the current request.
2339 * 1 : action = Action spec to check.
2341 * Returns : TRUE for yes, FALSE otherwise
2343 *********************************************************************/
2344 int content_filters_enabled(const struct current_action_spec *action)
2346 return ((action->flags & ACTION_DEANIMATE) ||
2347 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));