1 const char filters_rcs[] = "$Id: filters.c,v 1.124 2009/08/19 15:24:30 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-2009 the
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 static int sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
123 uint8_t **ip, unsigned int *len,
131 switch (addr->ss_family)
141 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
145 *port = &((struct sockaddr_in *)addr)->sin_port;
156 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
160 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
165 /* Unsupported address family */
173 /*********************************************************************
175 * Function : match_sockaddr
177 * Description : Check whether address matches network (IP address and port)
180 * 1 : network = socket address of subnework
181 * 2 : netmask = network mask as socket address
182 * 3 : address = checked socket address against given network
184 * Returns : 0 = doesn't match; 1 = does match
186 *********************************************************************/
187 static int match_sockaddr(const struct sockaddr_storage *network,
188 const struct sockaddr_storage *netmask,
189 const struct sockaddr_storage *address)
191 uint8_t *network_addr, *netmask_addr, *address_addr;
192 unsigned int addr_len;
193 in_port_t *network_port, *netmask_port, *address_port;
196 if (network->ss_family != netmask->ss_family)
198 /* This should never happen */
199 log_error(LOG_LEVEL_ERROR,
200 "Internal error at %s:%llu: network and netmask differ in family",
205 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
206 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
207 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
209 /* Check for family */
210 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
211 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
213 /* Map AF_INET6 V4MAPPED address into AF_INET */
217 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
218 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
220 /* Map AF_INET6 V4MAPPED network into AF_INET */
225 else if (network->ss_family != address->ss_family)
230 /* XXX: Port check is signaled in netmask */
231 if (*netmask_port && *network_port != *address_port)
236 /* TODO: Optimize by checking by words insted of octets */
237 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
239 if ((network_addr[i] & netmask_addr[i]) !=
240 (address_addr[i] & netmask_addr[i]))
248 #endif /* def HAVE_RFC2553 */
251 /*********************************************************************
253 * Function : block_acl
255 * Description : Block this request?
256 * Decide yes or no based on ACL file.
259 * 1 : dst = The proxy or gateway address this is going to.
260 * Or NULL to check all possible targets.
261 * 2 : csp = Current client state (buffers, headers, etc...)
262 * Also includes the client IP address.
264 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
266 *********************************************************************/
267 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
269 struct access_control_list *acl = csp->config->acl;
271 /* if not using an access control list, then permit the connection */
277 /* search the list */
282 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
284 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
290 /* Just want to check if they have any access */
291 if (acl->action == ACL_PERMIT)
299 * XXX: An undefined acl->dst is full of zeros and should be
300 * considered a wildcard address. sockaddr_storage_to_ip()
301 * fails on such destinations because of unknown sa_familly
302 * (glibc only?). However this test is not portable.
304 * So, we signal the acl->dst is wildcard in wildcard_dst.
307 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
309 ((dst->addr & acl->dst->mask) == acl->dst->addr)
310 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
314 if (acl->action == ACL_PERMIT)
332 /*********************************************************************
334 * Function : acl_addr
336 * Description : Called from `load_config' to parse an ACL address.
339 * 1 : aspec = String specifying ACL address.
340 * 2 : aca = struct access_control_addr to fill in.
342 * Returns : 0 => Ok, everything else is an error.
344 *********************************************************************/
345 int acl_addr(const char *aspec, struct access_control_addr *aca)
349 struct addrinfo hints, *result;
351 in_port_t *mask_port;
352 unsigned int addr_len;
355 #endif /* def HAVE_RFC2553 */
357 char *acl_spec = NULL;
360 /* XXX: Depend on ai_family */
368 * Use a temporary acl spec copy so we can log
369 * the unmodified original in case of parse errors.
371 acl_spec = strdup(aspec);
372 if (acl_spec == NULL)
374 /* XXX: This will be logged as parse error. */
378 if ((p = strchr(acl_spec, '/')) != NULL)
381 if (ijb_isdigit(*p) == 0)
386 masklength = atoi(p);
389 if ((masklength < 0) ||
401 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
404 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
413 p = strchr(acl_spec, ':');
417 memset(&hints, 0, sizeof(struct addrinfo));
418 hints.ai_family = AF_UNSPEC;
419 hints.ai_socktype = SOCK_STREAM;
421 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));
432 /* TODO: Allow multihomed hostnames */
433 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
434 freeaddrinfo(result);
441 port = strtol(p, &endptr, 10);
443 if (port <= 0 || port > 65535 || *endptr != '\0')
450 aca->port = (unsigned long)port;
452 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
455 if (aca->addr == INADDR_NONE)
457 /* XXX: This will be logged as parse error. */
460 #endif /* def HAVE_RFC2553 */
462 /* build the netmask */
464 /* Clip masklength according to current family. */
465 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
470 aca->mask.ss_family = aca->addr.ss_family;
471 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
478 /* ACL contains a port number, check ports in the future. */
483 * XXX: This could be optimized to operate on whole words instead
484 * of octets (128-bit CPU could do it in one iteration).
487 * Octets after prefix can be ommitted because of
488 * previous initialization to zeros.
490 for (i = 0; (i < addr_len) && masklength; i++)
500 * XXX: This assumes MSB of octet is on the left side.
501 * This should be true for all architectures or solved
504 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
511 for (i=1; i <= masklength ; i++)
513 aca->mask |= (1U << (32 - i));
516 /* now mask off the host portion of the ip address
517 * (i.e. save on the network portion of the address).
519 aca->addr = aca->addr & aca->mask;
520 #endif /* def HAVE_RFC2553 */
525 #endif /* def FEATURE_ACL */
528 /*********************************************************************
530 * Function : connect_port_is_forbidden
532 * Description : Check to see if CONNECT requests to the destination
533 * port of this request are forbidden. The check is
534 * independend of the actual request method.
537 * 1 : csp = Current client state (buffers, headers, etc...)
539 * Returns : True if yes, false otherwise.
541 *********************************************************************/
542 int connect_port_is_forbidden(const struct client_state *csp)
544 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
545 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
550 /*********************************************************************
552 * Function : block_url
554 * Description : Called from `chat'. Check to see if we need to block this.
557 * 1 : csp = Current client state (buffers, headers, etc...)
559 * Returns : NULL => unblocked, else HTTP block response
561 *********************************************************************/
562 struct http_response *block_url(struct client_state *csp)
564 struct http_response *rsp;
565 const char *new_content_type = NULL;
568 * If it's not blocked, don't block it ;-)
570 if ((csp->action->flags & ACTION_BLOCK) == 0)
574 if (csp->action->flags & ACTION_REDIRECT)
576 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
579 * Else, prepare a response
581 if (NULL == (rsp = alloc_http_response()))
583 return cgi_error_memory();
587 * If it's an image-url, send back an image or redirect
588 * as specified by the relevant +image action
590 #ifdef FEATURE_IMAGE_BLOCKING
591 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
595 /* determine HOW images should be blocked */
596 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
598 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
600 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
602 #if 1 /* Two alternative strategies, use this one for now: */
604 /* and handle accordingly: */
605 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
607 rsp->status = strdup("403 Request blocked by Privoxy");
608 if (rsp->status == NULL)
610 free_http_response(rsp);
611 return cgi_error_memory();
613 rsp->body = bindup(image_pattern_data, image_pattern_length);
614 if (rsp->body == NULL)
616 free_http_response(rsp);
617 return cgi_error_memory();
619 rsp->content_length = image_pattern_length;
621 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
623 free_http_response(rsp);
624 return cgi_error_memory();
628 else if (0 == strcmpic(p, "blank"))
630 rsp->status = strdup("403 Request blocked by Privoxy");
631 if (rsp->status == NULL)
633 free_http_response(rsp);
634 return cgi_error_memory();
636 rsp->body = bindup(image_blank_data, image_blank_length);
637 if (rsp->body == NULL)
639 free_http_response(rsp);
640 return cgi_error_memory();
642 rsp->content_length = image_blank_length;
644 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
646 free_http_response(rsp);
647 return cgi_error_memory();
653 rsp->status = strdup("302 Local Redirect from Privoxy");
654 if (rsp->status == NULL)
656 free_http_response(rsp);
657 return cgi_error_memory();
660 if (enlist_unique_header(rsp->headers, "Location", p))
662 free_http_response(rsp);
663 return cgi_error_memory();
667 #else /* Following code is disabled for now */
669 /* and handle accordingly: */
670 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
672 p = CGI_PREFIX "send-banner?type=pattern";
674 else if (0 == strcmpic(p, "blank"))
676 p = CGI_PREFIX "send-banner?type=blank";
678 rsp->status = strdup("302 Local Redirect from Privoxy");
679 if (rsp->status == NULL)
681 free_http_response(rsp);
682 return cgi_error_memory();
685 if (enlist_unique_header(rsp->headers, "Location", p))
687 free_http_response(rsp);
688 return cgi_error_memory();
690 #endif /* Preceeding code is disabled for now */
693 #endif /* def FEATURE_IMAGE_BLOCKING */
694 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
697 * Send empty document.
699 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
702 rsp->body = strdup(" ");
703 rsp->content_length = 1;
705 rsp->status = strdup("403 Request blocked by Privoxy");
706 if (rsp->status == NULL)
708 free_http_response(rsp);
709 return cgi_error_memory();
711 if (new_content_type != 0)
713 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
714 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
716 free_http_response(rsp);
717 return cgi_error_memory();
724 * Else, generate an HTML "blocked" message:
728 struct map * exports;
732 * Workaround for stupid Netscape bug which prevents
733 * pages from being displayed if loading a referenced
734 * JavaScript or style sheet fails. So make it appear
735 * as if it succeeded.
737 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
738 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
739 && !strstr(p, "Gecko") /* save Mozilla, */
740 && !strstr(p, "compatible") /* MSIE */
741 && !strstr(p, "Opera")) /* and Opera. */
743 rsp->status = strdup("200 Request for blocked URL");
747 rsp->status = strdup("403 Request for blocked URL");
750 if (rsp->status == NULL)
752 free_http_response(rsp);
753 return cgi_error_memory();
756 exports = default_exports(csp, NULL);
759 free_http_response(rsp);
760 return cgi_error_memory();
763 #ifdef FEATURE_FORCE_LOAD
764 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
766 * Export the force conditional block killer if
768 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
769 * - Privoxy is configured to enforce blocks, or
770 * - it's a CONNECT request and enforcing wouldn't work anyway.
772 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
773 || (0 == strcmpic(csp->http->gpc, "connect")))
774 #endif /* ndef FEATURE_FORCE_LOAD */
776 err = map_block_killer(exports, "force-support");
779 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
780 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
781 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
782 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
785 const char *block_reason;
786 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
788 block_reason = csp->action->string[ACTION_STRING_BLOCK];
792 assert(connect_port_is_forbidden(csp));
793 block_reason = "Forbidden CONNECT port.";
795 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
800 free_http_response(rsp);
801 return cgi_error_memory();
804 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
807 free_http_response(rsp);
808 return cgi_error_memory();
811 rsp->reason = RSP_REASON_BLOCKED;
813 return finish_http_response(csp, rsp);
819 /*********************************************************************
821 * Function : trust_url FIXME: I should be called distrust_url
823 * Description : Calls is_untrusted_url to determine if the URL is trusted
824 * and if not, returns a HTTP 403 response with a reject message.
827 * 1 : csp = Current client state (buffers, headers, etc...)
829 * Returns : NULL => trusted, else http_response.
831 *********************************************************************/
832 struct http_response *trust_url(struct client_state *csp)
834 struct http_response *rsp;
835 struct map * exports;
836 char buf[BUFFER_SIZE];
838 struct url_spec **tl;
843 * Don't bother to work on trusted URLs
845 if (!is_untrusted_url(csp))
851 * Else, prepare a response:
853 if (NULL == (rsp = alloc_http_response()))
855 return cgi_error_memory();
858 rsp->status = strdup("403 Request blocked by Privoxy");
859 exports = default_exports(csp, NULL);
860 if (exports == NULL || rsp->status == NULL)
862 free_http_response(rsp);
863 return cgi_error_memory();
867 * Export the protocol, host, port, and referrer information
869 err = map(exports, "hostport", 1, csp->http->hostport, 1);
870 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
871 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
873 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
875 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
879 if (!err) err = map(exports, "referrer", 1, "none set", 1);
885 free_http_response(rsp);
886 return cgi_error_memory();
890 * Export the trust list
893 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
895 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
896 string_append(&p, buf);
898 err = map(exports, "trusted-referrers", 1, p, 0);
903 free_http_response(rsp);
904 return cgi_error_memory();
908 * Export the trust info, if available
910 if (csp->config->trust_info->first)
912 struct list_entry *l;
915 for (l = csp->config->trust_info->first; l ; l = l->next)
917 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
918 string_append(&p, buf);
920 err = map(exports, "trust-info", 1, p, 0);
924 err = map_block_killer(exports, "have-trust-info");
930 free_http_response(rsp);
931 return cgi_error_memory();
935 * Export the force conditional block killer if
937 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
938 * - Privoxy is configured to enforce blocks, or
939 * - it's a CONNECT request and enforcing wouldn't work anyway.
941 #ifdef FEATURE_FORCE_LOAD
942 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
943 || (0 == strcmpic(csp->http->gpc, "connect")))
945 err = map_block_killer(exports, "force-support");
949 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
951 #else /* ifndef FEATURE_FORCE_LOAD */
952 err = map_block_killer(exports, "force-support");
953 #endif /* ndef FEATURE_FORCE_LOAD */
958 free_http_response(rsp);
959 return cgi_error_memory();
965 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
968 free_http_response(rsp);
969 return cgi_error_memory();
971 rsp->reason = RSP_REASON_UNTRUSTED;
973 return finish_http_response(csp, rsp);
975 #endif /* def FEATURE_TRUST */
978 /*********************************************************************
980 * Function : compile_dynamic_pcrs_job_list
982 * Description : Compiles a dynamic pcrs job list (one with variables
983 * resolved at request time)
986 * 1 : csp = Current client state (buffers, headers, etc...)
987 * 2 : b = The filter list to compile
989 * Returns : NULL in case of errors, otherwise the
992 *********************************************************************/
993 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
995 struct list_entry *pattern;
996 pcrs_job *job_list = NULL;
997 pcrs_job *dummy = NULL;
998 pcrs_job *lastjob = NULL;
1001 const struct pcrs_variable variables[] =
1003 {"url", csp->http->url, 1},
1004 {"path", csp->http->path, 1},
1005 {"host", csp->http->host, 1},
1006 {"origin", csp->ip_addr_str, 1},
1010 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
1012 assert(pattern->str != NULL);
1014 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
1018 log_error(LOG_LEVEL_ERROR,
1019 "Adding filter job \'%s\' to dynamic filter %s failed: %s",
1020 pattern->str, b->name, pcrs_strerror(error));
1025 if (error == PCRS_WARN_TRUNCATION)
1027 log_error(LOG_LEVEL_ERROR,
1028 "At least one of the variables in \'%s\' had to "
1029 "be truncated before compilation", pattern->str);
1031 if (job_list == NULL)
1037 lastjob->next = dummy;
1047 /*********************************************************************
1049 * Function : rewrite_url
1051 * Description : Rewrites a URL with a single pcrs command
1052 * and returns the result if it differs from the
1053 * original and isn't obviously invalid.
1056 * 1 : old_url = URL to rewrite.
1057 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1060 * Returns : NULL if the pcrs_command didn't change the url, or
1061 * the result of the modification.
1063 *********************************************************************/
1064 char *rewrite_url(char *old_url, const char *pcrs_command)
1066 char *new_url = NULL;
1070 assert(pcrs_command);
1072 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1076 log_error(LOG_LEVEL_REDIRECTS,
1077 "pcrs command \"%s\" didn't change \"%s\".",
1078 pcrs_command, old_url);
1083 log_error(LOG_LEVEL_REDIRECTS,
1084 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1085 pcrs_command, old_url, pcrs_strerror(hits));
1088 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1090 log_error(LOG_LEVEL_ERROR,
1091 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1092 "but the result doesn't look like a valid URL and will be ignored.",
1093 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1098 log_error(LOG_LEVEL_REDIRECTS,
1099 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1100 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1108 #ifdef FEATURE_FAST_REDIRECTS
1109 /*********************************************************************
1111 * Function : get_last_url
1113 * Description : Search for the last URL inside a string.
1114 * If the string already is a URL, it will
1115 * be the first URL found.
1118 * 1 : subject = the string to check
1119 * 2 : redirect_mode = +fast-redirect{} mode
1121 * Returns : NULL if no URL was found, or
1122 * the last URL found.
1124 *********************************************************************/
1125 char *get_last_url(char *subject, const char *redirect_mode)
1127 char *new_url = NULL;
1131 assert(redirect_mode);
1133 subject = strdup(subject);
1134 if (subject == NULL)
1136 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1140 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1142 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1143 new_url = url_decode(subject);
1144 if (new_url != NULL)
1151 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1155 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1158 * Find the last URL encoded in the request
1161 while ((tmp = strstr(tmp, "http://")) != NULL)
1165 tmp = (new_url != NULL) ? new_url : subject;
1166 while ((tmp = strstr(tmp, "https://")) != NULL)
1171 if ((new_url != NULL)
1172 && ( (new_url != subject)
1173 || (0 == strncmpic(subject, "http://", 7))
1174 || (0 == strncmpic(subject, "https://", 8))
1178 * Return new URL if we found a redirect
1179 * or if the subject already was a URL.
1181 * The second case makes sure that we can
1182 * chain get_last_url after another redirection check
1183 * (like rewrite_url) without losing earlier redirects.
1185 new_url = strdup(new_url);
1194 #endif /* def FEATURE_FAST_REDIRECTS */
1197 /*********************************************************************
1199 * Function : redirect_url
1201 * Description : Checks if Privoxy should answer the request with
1202 * a HTTP redirect and generates the redirect if
1206 * 1 : csp = Current client state (buffers, headers, etc...)
1208 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1210 *********************************************************************/
1211 struct http_response *redirect_url(struct client_state *csp)
1213 struct http_response *rsp;
1214 #ifdef FEATURE_FAST_REDIRECTS
1216 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1217 * as compile-time option? The user can easily disable
1218 * it in his action file.
1220 char * redirect_mode;
1221 #endif /* def FEATURE_FAST_REDIRECTS */
1222 char *old_url = NULL;
1223 char *new_url = NULL;
1224 char *redirection_string;
1226 if ((csp->action->flags & ACTION_REDIRECT))
1228 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1231 * If the redirection string begins with 's',
1232 * assume it's a pcrs command, otherwise treat it as
1233 * properly formatted URL and use it for the redirection
1236 * According to RFC 2616 section 14.30 the URL
1237 * has to be absolute and if the user tries:
1238 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1239 * she would get undefined results anyway.
1243 if (*redirection_string == 's')
1245 old_url = csp->http->url;
1246 new_url = rewrite_url(old_url, redirection_string);
1250 log_error(LOG_LEVEL_REDIRECTS,
1251 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1252 redirection_string);
1253 new_url = strdup(redirection_string);
1257 #ifdef FEATURE_FAST_REDIRECTS
1258 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1260 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1263 * If it exists, use the previously rewritten URL as input
1264 * otherwise just use the old path.
1266 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1267 new_url = get_last_url(old_url, redirect_mode);
1272 * Disable redirect checkers, so that they
1273 * will be only run more than once if the user
1274 * also enables them through tags.
1276 * From a performance point of view
1277 * it doesn't matter, but the duplicated
1278 * log messages are annoying.
1280 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1281 #endif /* def FEATURE_FAST_REDIRECTS */
1282 csp->action->flags &= ~ACTION_REDIRECT;
1284 /* Did any redirect action trigger? */
1287 if (0 == strcmpic(new_url, csp->http->url))
1289 log_error(LOG_LEVEL_ERROR,
1290 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1291 csp->http->url, new_url);
1296 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1298 if (NULL == (rsp = alloc_http_response()))
1301 return cgi_error_memory();
1304 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1305 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1308 free_http_response(rsp);
1309 return cgi_error_memory();
1311 rsp->reason = RSP_REASON_REDIRECTED;
1314 return finish_http_response(csp, rsp);
1318 /* Only reached if no redirect is required */
1324 #ifdef FEATURE_IMAGE_BLOCKING
1325 /*********************************************************************
1327 * Function : is_imageurl
1329 * Description : Given a URL, decide whether it is an image or not,
1330 * using either the info from a previous +image action
1331 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1332 * is MSIE and not on a Mac, tell from the browser's accept
1336 * 1 : csp = Current client state (buffers, headers, etc...)
1338 * Returns : True (nonzero) if URL is an image, false (0)
1341 *********************************************************************/
1342 int is_imageurl(const struct client_state *csp)
1344 #ifdef FEATURE_IMAGE_DETECT_MSIE
1347 tmp = get_header_value(csp->headers, "User-Agent:");
1348 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1350 tmp = get_header_value(csp->headers, "Accept:");
1351 if (tmp && strstr(tmp, "image/gif"))
1353 /* Client will accept HTML. If this seems counterintuitive,
1363 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1365 return ((csp->action->flags & ACTION_IMAGE) != 0);
1368 #endif /* def FEATURE_IMAGE_BLOCKING */
1371 #ifdef FEATURE_TRUST
1372 /*********************************************************************
1374 * Function : is_untrusted_url
1376 * Description : Should we "distrust" this URL (and block it)?
1378 * Yes if it matches a line in the trustfile, or if the
1379 * referrer matches a line starting with "+" in the
1384 * 1 : csp = Current client state (buffers, headers, etc...)
1386 * Returns : 0 => trusted, 1 => untrusted
1388 *********************************************************************/
1389 int is_untrusted_url(const struct client_state *csp)
1391 struct file_list *fl;
1392 struct block_spec *b;
1393 struct url_spec **trusted_url;
1394 struct http_request rhttp[1];
1395 const char * referer;
1399 * If we don't have a trustlist, we trust everybody
1401 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1406 memset(rhttp, '\0', sizeof(*rhttp));
1409 * Do we trust the request URL itself?
1411 for (b = b->next; b ; b = b->next)
1413 if (url_match(b->url, csp->http))
1419 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1421 /* no referrer was supplied */
1427 * If not, do we maybe trust its referrer?
1429 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1435 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1437 if (url_match(*trusted_url, rhttp))
1439 /* if the URL's referrer is from a trusted referrer, then
1440 * add the target spec to the trustfile as an unblocked
1441 * domain and return 0 (which means it's OK).
1446 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1450 char * new_entry = strdup("~");
1452 string_append(&new_entry, csp->http->hostport);
1454 path = csp->http->path;
1455 if ( (path[0] == '/')
1457 && ((path_end = strchr(path + 2, '/')) != NULL))
1459 /* since this path points into a user's home space
1460 * be sure to include this spec in the trustfile.
1462 long path_len = path_end - path; /* save offset */
1463 path = strdup(path); /* Copy string */
1466 path_end = path + path_len; /* regenerate ptr to new buffer */
1467 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1469 string_join(&new_entry, path);
1473 * Give a reason for generating this entry.
1475 string_append(&new_entry, " # Trusted referrer was: ");
1476 string_append(&new_entry, referer);
1478 if (new_entry != NULL)
1480 if (-1 == fprintf(fp, "%s\n", new_entry))
1482 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1483 new_entry, csp->config->trustfile);
1489 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1490 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1497 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1498 csp->http->hostport, csp->config->trustfile);
1506 #endif /* def FEATURE_TRUST */
1509 /*********************************************************************
1511 * Function : pcrs_filter_response
1513 * Description : Execute all text substitutions from all applying
1514 * +filter actions on the text buffer that's been
1515 * accumulated in csp->iob->buf.
1518 * 1 : csp = Current client state (buffers, headers, etc...)
1520 * Returns : a pointer to the (newly allocated) modified buffer.
1521 * or NULL if there were no hits or something went wrong
1523 *********************************************************************/
1524 static char *pcrs_filter_response(struct client_state *csp)
1527 size_t size, prev_size;
1533 struct file_list *fl;
1534 struct re_filterfile_spec *b;
1535 struct list_entry *filtername;
1537 int i, found_filters = 0;
1542 if (csp->iob->cur >= csp->iob->eod)
1548 * Need to check the set of re_filterfiles...
1550 for (i = 0; i < MAX_AF_FILES; i++)
1563 if (0 == found_filters)
1565 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1566 "content filtering enabled, but no content filters available.");
1570 size = (size_t)(csp->iob->eod - csp->iob->cur);
1571 old = csp->iob->cur;
1573 for (i = 0; i < MAX_AF_FILES; i++)
1576 if ((NULL == fl) || (NULL == fl->f))
1579 * Either there are no filter files
1580 * left, or this filter file just
1581 * contains no valid filters.
1583 * Continue to be sure we don't miss
1584 * valid filter files that are chained
1585 * after empty or invalid ones.
1590 * For all applying +filter actions, look if a filter by that
1591 * name exists and if yes, execute it's pcrs_joblist on the
1594 for (b = fl->f; b; b = b->next)
1596 if (b->type != FT_CONTENT_FILTER)
1598 /* Skip header filters */
1602 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1603 filtername ; filtername = filtername->next)
1605 if (strcmp(b->name, filtername->str) == 0)
1607 int current_hits = 0; /* Number of hits caused by this filter */
1608 int job_number = 0; /* Which job we're currently executing */
1609 int job_hits = 0; /* How many hits the current job caused */
1610 pcrs_job *joblist = b->joblist;
1612 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1614 if (NULL == joblist)
1616 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1621 /* Apply all jobs from the joblist */
1622 for (job = joblist; NULL != job; job = job->next)
1625 job_hits = pcrs_execute(job, old, size, &new, &size);
1630 * That went well. Continue filtering
1631 * and use the result of this job as
1632 * input for the next one.
1634 current_hits += job_hits;
1635 if (old != csp->iob->cur)
1644 * This job caused an unexpected error. Inform the user
1645 * and skip the rest of the jobs in this filter. We could
1646 * continue with the next job, but usually the jobs
1647 * depend on each other or are similar enough to
1648 * fail for the same reason.
1650 * At the moment our pcrs expects the error codes of pcre 3.4,
1651 * but newer pcre versions can return additional error codes.
1652 * As a result pcrs_strerror()'s error message might be
1653 * "Unknown error ...", therefore we print the numerical value
1656 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1657 * should we use LOG_LEVEL_RE_FILTER instead?
1659 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1660 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1665 if (b->dynamic) pcrs_free_joblist(joblist);
1667 log_error(LOG_LEVEL_RE_FILTER,
1668 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1669 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1671 hits += current_hits;
1678 * If there were no hits, destroy our copy and let
1679 * chat() use the original in csp->iob
1687 csp->flags |= CSP_FLAG_MODIFIED;
1688 csp->content_length = size;
1696 /*********************************************************************
1698 * Function : gif_deanimate_response
1700 * Description : Deanimate the GIF image that has been accumulated in
1701 * csp->iob->buf, set csp->content_length to the modified
1702 * size and raise the CSP_FLAG_MODIFIED flag.
1705 * 1 : csp = Current client state (buffers, headers, etc...)
1707 * Returns : a pointer to the (newly allocated) modified buffer.
1708 * or NULL in case something went wrong.
1710 *********************************************************************/
1711 static char *gif_deanimate_response(struct client_state *csp)
1713 struct binbuffer *in, *out;
1717 size = (size_t)(csp->iob->eod - csp->iob->cur);
1719 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1720 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1722 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1726 in->buffer = csp->iob->cur;
1729 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1731 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1738 if ((int)size == out->offset)
1740 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1744 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1746 csp->content_length = out->offset;
1747 csp->flags |= CSP_FLAG_MODIFIED;
1757 /*********************************************************************
1759 * Function : get_filter_function
1761 * Description : Decides which content filter function has
1762 * to be applied (if any).
1765 * 1 : csp = Current client state (buffers, headers, etc...)
1767 * Returns : The content filter function to run, or
1768 * NULL if no content filter is active
1770 *********************************************************************/
1771 filter_function_ptr get_filter_function(struct client_state *csp)
1773 filter_function_ptr filter_function = NULL;
1775 if ((csp->content_type & CT_TABOO)
1776 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
1782 * Are we enabling text mode by force?
1784 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1787 * Do we really have to?
1789 if (csp->content_type & CT_TEXT)
1791 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1795 csp->content_type |= CT_TEXT;
1796 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1800 if (!(csp->content_type & CT_DECLARED))
1803 * The server didn't bother to declare a MIME-Type.
1804 * Assume it's text that can be filtered.
1806 * This also regulary happens with 304 responses,
1807 * therefore logging anything here would cause
1810 csp->content_type |= CT_TEXT;
1814 * Choose the applying filter function based on
1815 * the content type and action settings.
1817 if ((csp->content_type & CT_TEXT) &&
1818 (csp->rlist != NULL) &&
1819 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1821 filter_function = pcrs_filter_response;
1823 else if ((csp->content_type & CT_GIF) &&
1824 (csp->action->flags & ACTION_DEANIMATE))
1826 filter_function = gif_deanimate_response;
1829 return filter_function;
1833 /*********************************************************************
1835 * Function : remove_chunked_transfer_coding
1837 * Description : In-situ remove the "chunked" transfer coding as defined
1838 * in rfc2616 from a buffer.
1841 * 1 : buffer = Pointer to the text buffer
1842 * 2 : size = In: Number of bytes to be processed,
1843 * Out: Number of bytes after de-chunking.
1844 * (undefined in case of errors)
1846 * Returns : JB_ERR_OK for success,
1847 * JB_ERR_PARSE otherwise
1849 *********************************************************************/
1850 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1853 unsigned int chunksize = 0;
1854 char *from_p, *to_p;
1857 from_p = to_p = buffer;
1859 if (sscanf(buffer, "%x", &chunksize) != 1)
1861 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1862 return JB_ERR_PARSE;
1865 while (chunksize > 0U)
1867 if (NULL == (from_p = strstr(from_p, "\r\n")))
1869 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1870 return JB_ERR_PARSE;
1873 if ((newsize += chunksize) >= *size)
1875 log_error(LOG_LEVEL_ERROR,
1876 "Chunk size %d exceeds buffer size %d in \"chunked\" transfer coding",
1878 return JB_ERR_PARSE;
1882 memmove(to_p, from_p, (size_t) chunksize);
1883 to_p = buffer + newsize;
1884 from_p += chunksize + 2;
1886 if (sscanf(from_p, "%x", &chunksize) != 1)
1888 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1893 /* XXX: Should get its own loglevel. */
1894 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1903 /*********************************************************************
1905 * Function : prepare_for_filtering
1907 * Description : If necessary, de-chunks and decompresses
1908 * the content so it can get filterd.
1911 * 1 : csp = Current client state (buffers, headers, etc...)
1913 * Returns : JB_ERR_OK for success,
1914 * JB_ERR_PARSE otherwise
1916 *********************************************************************/
1917 static jb_err prepare_for_filtering(struct client_state *csp)
1919 jb_err err = JB_ERR_OK;
1922 * If the body has a "chunked" transfer-encoding,
1923 * get rid of it, adjusting size and iob->eod
1925 if (csp->flags & CSP_FLAG_CHUNKED)
1927 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1929 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1930 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1931 if (JB_ERR_OK == err)
1933 csp->iob->eod = csp->iob->cur + size;
1934 csp->flags |= CSP_FLAG_MODIFIED;
1938 return JB_ERR_PARSE;
1944 * If the body has a supported transfer-encoding,
1945 * decompress it, adjusting size and iob->eod.
1947 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1949 if (0 == csp->iob->eod - csp->iob->cur)
1951 /* Nothing left after de-chunking. */
1955 err = decompress_iob(csp);
1957 if (JB_ERR_OK == err)
1959 csp->flags |= CSP_FLAG_MODIFIED;
1960 csp->content_type &= ~CT_TABOO;
1965 * Unset CT_GZIP and CT_DEFLATE to remember not
1966 * to modify the Content-Encoding header later.
1968 csp->content_type &= ~CT_GZIP;
1969 csp->content_type &= ~CT_DEFLATE;
1978 /*********************************************************************
1980 * Function : execute_content_filter
1982 * Description : Executes a given content filter.
1985 * 1 : csp = Current client state (buffers, headers, etc...)
1986 * 2 : content_filter = The filter function to execute
1988 * Returns : Pointer to the modified buffer, or
1989 * NULL if filtering failed or wasn't necessary.
1991 *********************************************************************/
1992 char *execute_content_filter(struct client_state *csp, filter_function_ptr content_filter)
1994 if (0 == csp->iob->eod - csp->iob->cur)
1997 * No content (probably status code 301, 302 ...),
1998 * no filtering necessary.
2003 if (JB_ERR_OK != prepare_for_filtering(csp))
2006 * failed to de-chunk or decompress.
2011 if (0 == csp->iob->eod - csp->iob->cur)
2014 * Clown alarm: chunked and/or compressed nothing delivered.
2019 return ((*content_filter)(csp));
2023 /*********************************************************************
2025 * Function : get_url_actions
2027 * Description : Gets the actions for this URL.
2030 * 1 : csp = Current client state (buffers, headers, etc...)
2031 * 2 : http = http_request request for blocked URLs
2035 *********************************************************************/
2036 void get_url_actions(struct client_state *csp, struct http_request *http)
2038 struct file_list *fl;
2039 struct url_actions *b;
2042 init_current_action(csp->action);
2044 for (i = 0; i < MAX_AF_FILES; i++)
2046 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2051 apply_url_actions(csp->action, http, b);
2058 /*********************************************************************
2060 * Function : apply_url_actions
2062 * Description : Applies a list of URL actions.
2065 * 1 : action = Destination.
2066 * 2 : http = Current URL
2067 * 3 : b = list of URL actions to apply
2071 *********************************************************************/
2072 void apply_url_actions(struct current_action_spec *action,
2073 struct http_request *http,
2074 struct url_actions *b)
2078 /* Should never happen */
2082 for (b = b->next; NULL != b; b = b->next)
2084 if (url_match(b->url, http))
2086 merge_current_action(action, b->action);
2092 /*********************************************************************
2094 * Function : get_forward_override_settings
2096 * Description : Returns forward settings as specified with the
2097 * forward-override{} action. forward-override accepts
2098 * forward lines similar to the one used in the
2099 * configuration file, but without the URL pattern.
2105 * in the configuration file can be replaced with
2106 * the action section:
2108 * {+forward-override{forward .}}
2112 * 1 : csp = Current client state (buffers, headers, etc...)
2114 * Returns : Pointer to forwarding structure in case of success.
2115 * Invalid syntax is fatal.
2117 *********************************************************************/
2118 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2120 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2121 char forward_settings[BUFFER_SIZE];
2122 char *http_parent = NULL;
2123 /* variable names were chosen for consistency reasons. */
2124 struct forward_spec *fwd = NULL;
2128 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2129 /* Should be enforced by load_one_actions_file() */
2130 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2132 /* Create a copy ssplit can modify */
2133 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2135 if (NULL != csp->fwd)
2138 * XXX: Currently necessary to prevent memory
2139 * leaks when the show-url-info cgi page is visited.
2141 unload_forward_spec(csp->fwd);
2145 * allocate a new forward node, valid only for
2146 * the lifetime of this request. Save its location
2147 * in csp as well, so sweep() can free it later on.
2149 fwd = csp->fwd = zalloc(sizeof(*fwd));
2152 log_error(LOG_LEVEL_FATAL,
2153 "can't allocate memory for forward-override{%s}", forward_override_line);
2154 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2158 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2159 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2161 fwd->type = SOCKS_NONE;
2163 /* Parse the parent HTTP proxy host:port */
2164 http_parent = vec[1];
2167 else if (vec_count == 3)
2169 char *socks_proxy = NULL;
2171 if (!strcasecmp(vec[0], "forward-socks4"))
2173 fwd->type = SOCKS_4;
2174 socks_proxy = vec[1];
2176 else if (!strcasecmp(vec[0], "forward-socks4a"))
2178 fwd->type = SOCKS_4A;
2179 socks_proxy = vec[1];
2181 else if (!strcasecmp(vec[0], "forward-socks5"))
2183 fwd->type = SOCKS_5;
2184 socks_proxy = vec[1];
2187 if (NULL != socks_proxy)
2189 /* Parse the SOCKS proxy host[:port] */
2190 fwd->gateway_port = 1080;
2191 parse_forwarder_address(socks_proxy,
2192 &fwd->gateway_host, &fwd->gateway_port);
2194 http_parent = vec[2];
2198 if (NULL == http_parent)
2200 log_error(LOG_LEVEL_FATAL,
2201 "Invalid forward-override syntax in: %s", forward_override_line);
2202 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2205 /* Parse http forwarding settings */
2206 if (strcmp(http_parent, ".") != 0)
2208 fwd->forward_port = 8000;
2209 parse_forwarder_address(http_parent,
2210 &fwd->forward_host, &fwd->forward_port);
2213 assert (NULL != fwd);
2215 log_error(LOG_LEVEL_CONNECT,
2216 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2222 /*********************************************************************
2224 * Function : forward_url
2226 * Description : Should we forward this to another proxy?
2229 * 1 : csp = Current client state (buffers, headers, etc...)
2230 * 2 : http = http_request request for current URL
2232 * Returns : Pointer to forwarding information.
2234 *********************************************************************/
2235 const struct forward_spec *forward_url(struct client_state *csp,
2236 const struct http_request *http)
2238 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2239 struct forward_spec *fwd = csp->config->forward;
2241 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2243 return get_forward_override_settings(csp);
2253 if (url_match(fwd->url, http))
2264 /*********************************************************************
2266 * Function : direct_response
2268 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2269 * request and if so, return a HTTP 501 to the client.
2271 * FIXME: I have a stupid name and I should handle the
2272 * requests properly. Still, what we do here is rfc-
2273 * compliant, whereas ignoring or forwarding are not.
2276 * 1 : csp = Current client state (buffers, headers, etc...)
2278 * Returns : http_response if , NULL if nonmatch or handler fail
2280 *********************************************************************/
2281 struct http_response *direct_response(struct client_state *csp)
2283 struct http_response *rsp;
2284 struct list_entry *p;
2286 if ((0 == strcmpic(csp->http->gpc, "trace"))
2287 || (0 == strcmpic(csp->http->gpc, "options")))
2289 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2291 if (!strncmpic("Max-Forwards:", p->str, 13))
2293 unsigned int max_forwards;
2296 * If it's a Max-Forwards value of zero,
2297 * we have to intercept the request.
2299 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2302 * FIXME: We could handle at least TRACE here,
2303 * but that would require a verbatim copy of
2304 * the request which we don't have anymore
2306 log_error(LOG_LEVEL_HEADER,
2307 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2310 /* Get mem for response or fail*/
2311 if (NULL == (rsp = alloc_http_response()))
2313 return cgi_error_memory();
2316 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2318 free_http_response(rsp);
2319 return cgi_error_memory();
2323 rsp->reason = RSP_REASON_UNSUPPORTED;
2325 return(finish_http_response(csp, rsp));
2334 /*********************************************************************
2336 * Function : content_filters_enabled
2338 * Description : Checks whether there are any content filters
2339 * enabled for the current request.
2342 * 1 : action = Action spec to check.
2344 * Returns : TRUE for yes, FALSE otherwise
2346 *********************************************************************/
2347 int content_filters_enabled(const struct current_action_spec *action)
2349 return ((action->flags & ACTION_DEANIMATE) ||
2350 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));