1 const char filters_rcs[] = "$Id: filters.c,v 1.122 2009/06/08 16:48:09 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);
426 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
427 acl_spec, p, gai_strerror(i));
431 /* TODO: Allow multihomed hostnames */
432 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
433 freeaddrinfo(result);
440 port = strtol(p, &endptr, 10);
442 if (port <= 0 || port > 65535 || *endptr != '\0')
449 aca->port = (unsigned long)port;
451 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
454 if (aca->addr == INADDR_NONE)
456 /* XXX: This will be logged as parse error. */
459 #endif /* def HAVE_RFC2553 */
461 /* build the netmask */
463 /* Clip masklength according to current family. */
464 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
469 aca->mask.ss_family = aca->addr.ss_family;
470 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
477 /* ACL contains a port number, check ports in the future. */
482 * XXX: This could be optimized to operate on whole words instead
483 * of octets (128-bit CPU could do it in one iteration).
486 * Octets after prefix can be ommitted because of
487 * previous initialization to zeros.
489 for (i = 0; (i < addr_len) && masklength; i++)
499 * XXX: This assumes MSB of octet is on the left side.
500 * This should be true for all architectures or solved
503 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
510 for (i=1; i <= masklength ; i++)
512 aca->mask |= (1U << (32 - i));
515 /* now mask off the host portion of the ip address
516 * (i.e. save on the network portion of the address).
518 aca->addr = aca->addr & aca->mask;
519 #endif /* def HAVE_RFC2553 */
524 #endif /* def FEATURE_ACL */
527 /*********************************************************************
529 * Function : connect_port_is_forbidden
531 * Description : Check to see if CONNECT requests to the destination
532 * port of this request are forbidden. The check is
533 * independend of the actual request method.
536 * 1 : csp = Current client state (buffers, headers, etc...)
538 * Returns : True if yes, false otherwise.
540 *********************************************************************/
541 int connect_port_is_forbidden(const struct client_state *csp)
543 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
544 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
549 /*********************************************************************
551 * Function : block_url
553 * Description : Called from `chat'. Check to see if we need to block this.
556 * 1 : csp = Current client state (buffers, headers, etc...)
558 * Returns : NULL => unblocked, else HTTP block response
560 *********************************************************************/
561 struct http_response *block_url(struct client_state *csp)
563 struct http_response *rsp;
564 const char *new_content_type = NULL;
567 * If it's not blocked, don't block it ;-)
569 if ((csp->action->flags & ACTION_BLOCK) == 0)
573 if (csp->action->flags & ACTION_REDIRECT)
575 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
578 * Else, prepare a response
580 if (NULL == (rsp = alloc_http_response()))
582 return cgi_error_memory();
586 * If it's an image-url, send back an image or redirect
587 * as specified by the relevant +image action
589 #ifdef FEATURE_IMAGE_BLOCKING
590 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
594 /* determine HOW images should be blocked */
595 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
597 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
599 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
601 #if 1 /* Two alternative strategies, use this one for now: */
603 /* and handle accordingly: */
604 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
606 rsp->status = strdup("403 Request blocked by Privoxy");
607 if (rsp->status == NULL)
609 free_http_response(rsp);
610 return cgi_error_memory();
612 rsp->body = bindup(image_pattern_data, image_pattern_length);
613 if (rsp->body == NULL)
615 free_http_response(rsp);
616 return cgi_error_memory();
618 rsp->content_length = image_pattern_length;
620 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
622 free_http_response(rsp);
623 return cgi_error_memory();
627 else if (0 == strcmpic(p, "blank"))
629 rsp->status = strdup("403 Request blocked by Privoxy");
630 if (rsp->status == NULL)
632 free_http_response(rsp);
633 return cgi_error_memory();
635 rsp->body = bindup(image_blank_data, image_blank_length);
636 if (rsp->body == NULL)
638 free_http_response(rsp);
639 return cgi_error_memory();
641 rsp->content_length = image_blank_length;
643 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
645 free_http_response(rsp);
646 return cgi_error_memory();
652 rsp->status = strdup("302 Local Redirect from Privoxy");
653 if (rsp->status == NULL)
655 free_http_response(rsp);
656 return cgi_error_memory();
659 if (enlist_unique_header(rsp->headers, "Location", p))
661 free_http_response(rsp);
662 return cgi_error_memory();
666 #else /* Following code is disabled for now */
668 /* and handle accordingly: */
669 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
671 p = CGI_PREFIX "send-banner?type=pattern";
673 else if (0 == strcmpic(p, "blank"))
675 p = CGI_PREFIX "send-banner?type=blank";
677 rsp->status = strdup("302 Local Redirect from Privoxy");
678 if (rsp->status == NULL)
680 free_http_response(rsp);
681 return cgi_error_memory();
684 if (enlist_unique_header(rsp->headers, "Location", p))
686 free_http_response(rsp);
687 return cgi_error_memory();
689 #endif /* Preceeding code is disabled for now */
691 else if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
694 * Send empty document.
696 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
699 rsp->body = strdup(" ");
700 rsp->content_length = 1;
702 rsp->status = strdup("403 Request blocked by Privoxy");
703 if (rsp->status == NULL)
705 free_http_response(rsp);
706 return cgi_error_memory();
708 if (new_content_type != 0)
710 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
711 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
713 free_http_response(rsp);
714 return cgi_error_memory();
719 #endif /* def FEATURE_IMAGE_BLOCKING */
722 * Else, generate an HTML "blocked" message:
726 struct map * exports;
730 * Workaround for stupid Netscape bug which prevents
731 * pages from being displayed if loading a referenced
732 * JavaScript or style sheet fails. So make it appear
733 * as if it succeeded.
735 if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
736 && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
737 && !strstr(p, "Gecko") /* save Mozilla, */
738 && !strstr(p, "compatible") /* MSIE */
739 && !strstr(p, "Opera")) /* and Opera. */
741 rsp->status = strdup("200 Request for blocked URL");
745 rsp->status = strdup("403 Request for blocked URL");
748 if (rsp->status == NULL)
750 free_http_response(rsp);
751 return cgi_error_memory();
754 exports = default_exports(csp, NULL);
757 free_http_response(rsp);
758 return cgi_error_memory();
761 #ifdef FEATURE_FORCE_LOAD
762 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
764 * Export the force conditional block killer if
766 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
767 * - Privoxy is configured to enforce blocks, or
768 * - it's a CONNECT request and enforcing wouldn't work anyway.
770 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
771 || (0 == strcmpic(csp->http->gpc, "connect")))
772 #endif /* ndef FEATURE_FORCE_LOAD */
774 err = map_block_killer(exports, "force-support");
777 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
778 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
779 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
780 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
783 const char *block_reason;
784 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
786 block_reason = csp->action->string[ACTION_STRING_BLOCK];
790 assert(connect_port_is_forbidden(csp));
791 block_reason = "Forbidden CONNECT port.";
793 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
798 free_http_response(rsp);
799 return cgi_error_memory();
802 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
805 free_http_response(rsp);
806 return cgi_error_memory();
809 rsp->reason = RSP_REASON_BLOCKED;
811 return finish_http_response(csp, rsp);
817 /*********************************************************************
819 * Function : trust_url FIXME: I should be called distrust_url
821 * Description : Calls is_untrusted_url to determine if the URL is trusted
822 * and if not, returns a HTTP 403 response with a reject message.
825 * 1 : csp = Current client state (buffers, headers, etc...)
827 * Returns : NULL => trusted, else http_response.
829 *********************************************************************/
830 struct http_response *trust_url(struct client_state *csp)
832 struct http_response *rsp;
833 struct map * exports;
834 char buf[BUFFER_SIZE];
836 struct url_spec **tl;
841 * Don't bother to work on trusted URLs
843 if (!is_untrusted_url(csp))
849 * Else, prepare a response:
851 if (NULL == (rsp = alloc_http_response()))
853 return cgi_error_memory();
856 rsp->status = strdup("403 Request blocked by Privoxy");
857 exports = default_exports(csp, NULL);
858 if (exports == NULL || rsp->status == NULL)
860 free_http_response(rsp);
861 return cgi_error_memory();
865 * Export the protocol, host, port, and referrer information
867 err = map(exports, "hostport", 1, csp->http->hostport, 1);
868 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
869 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
871 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
873 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
877 if (!err) err = map(exports, "referrer", 1, "none set", 1);
883 free_http_response(rsp);
884 return cgi_error_memory();
888 * Export the trust list
891 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
893 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
894 string_append(&p, buf);
896 err = map(exports, "trusted-referrers", 1, p, 0);
901 free_http_response(rsp);
902 return cgi_error_memory();
906 * Export the trust info, if available
908 if (csp->config->trust_info->first)
910 struct list_entry *l;
913 for (l = csp->config->trust_info->first; l ; l = l->next)
915 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
916 string_append(&p, buf);
918 err = map(exports, "trust-info", 1, p, 0);
922 err = map_block_killer(exports, "have-trust-info");
928 free_http_response(rsp);
929 return cgi_error_memory();
933 * Export the force conditional block killer if
935 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
936 * - Privoxy is configured to enforce blocks, or
937 * - it's a CONNECT request and enforcing wouldn't work anyway.
939 #ifdef FEATURE_FORCE_LOAD
940 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
941 || (0 == strcmpic(csp->http->gpc, "connect")))
943 err = map_block_killer(exports, "force-support");
947 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
949 #else /* ifndef FEATURE_FORCE_LOAD */
950 err = map_block_killer(exports, "force-support");
951 #endif /* ndef FEATURE_FORCE_LOAD */
956 free_http_response(rsp);
957 return cgi_error_memory();
963 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
966 free_http_response(rsp);
967 return cgi_error_memory();
969 rsp->reason = RSP_REASON_UNTRUSTED;
971 return finish_http_response(csp, rsp);
973 #endif /* def FEATURE_TRUST */
976 /*********************************************************************
978 * Function : compile_dynamic_pcrs_job_list
980 * Description : Compiles a dynamic pcrs job list (one with variables
981 * resolved at request time)
984 * 1 : csp = Current client state (buffers, headers, etc...)
985 * 2 : b = The filter list to compile
987 * Returns : NULL in case of errors, otherwise the
990 *********************************************************************/
991 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
993 struct list_entry *pattern;
994 pcrs_job *job_list = NULL;
995 pcrs_job *dummy = NULL;
996 pcrs_job *lastjob = NULL;
999 const struct pcrs_variable variables[] =
1001 {"url", csp->http->url, 1},
1002 {"path", csp->http->path, 1},
1003 {"host", csp->http->host, 1},
1004 {"origin", csp->ip_addr_str, 1},
1008 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
1010 assert(pattern->str != NULL);
1012 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
1016 log_error(LOG_LEVEL_ERROR,
1017 "Adding filter job \'%s\' to dynamic filter %s failed: %s",
1018 pattern->str, b->name, pcrs_strerror(error));
1023 if (error == PCRS_WARN_TRUNCATION)
1025 log_error(LOG_LEVEL_ERROR,
1026 "At least one of the variables in \'%s\' had to "
1027 "be truncated before compilation", pattern->str);
1029 if (job_list == NULL)
1035 lastjob->next = dummy;
1045 /*********************************************************************
1047 * Function : rewrite_url
1049 * Description : Rewrites a URL with a single pcrs command
1050 * and returns the result if it differs from the
1051 * original and isn't obviously invalid.
1054 * 1 : old_url = URL to rewrite.
1055 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1058 * Returns : NULL if the pcrs_command didn't change the url, or
1059 * the result of the modification.
1061 *********************************************************************/
1062 char *rewrite_url(char *old_url, const char *pcrs_command)
1064 char *new_url = NULL;
1068 assert(pcrs_command);
1070 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1074 log_error(LOG_LEVEL_REDIRECTS,
1075 "pcrs command \"%s\" didn't change \"%s\".",
1076 pcrs_command, old_url);
1081 log_error(LOG_LEVEL_REDIRECTS,
1082 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1083 pcrs_command, old_url, pcrs_strerror(hits));
1086 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1088 log_error(LOG_LEVEL_ERROR,
1089 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1090 "but the result doesn't look like a valid URL and will be ignored.",
1091 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1096 log_error(LOG_LEVEL_REDIRECTS,
1097 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1098 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1106 #ifdef FEATURE_FAST_REDIRECTS
1107 /*********************************************************************
1109 * Function : get_last_url
1111 * Description : Search for the last URL inside a string.
1112 * If the string already is a URL, it will
1113 * be the first URL found.
1116 * 1 : subject = the string to check
1117 * 2 : redirect_mode = +fast-redirect{} mode
1119 * Returns : NULL if no URL was found, or
1120 * the last URL found.
1122 *********************************************************************/
1123 char *get_last_url(char *subject, const char *redirect_mode)
1125 char *new_url = NULL;
1129 assert(redirect_mode);
1131 subject = strdup(subject);
1132 if (subject == NULL)
1134 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1138 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1140 log_error(LOG_LEVEL_REDIRECTS, "Decoding \"%s\" if necessary.", subject);
1141 new_url = url_decode(subject);
1142 if (new_url != NULL)
1149 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1153 log_error(LOG_LEVEL_REDIRECTS, "Checking \"%s\" for redirects.", subject);
1156 * Find the last URL encoded in the request
1159 while ((tmp = strstr(tmp, "http://")) != NULL)
1163 tmp = (new_url != NULL) ? new_url : subject;
1164 while ((tmp = strstr(tmp, "https://")) != NULL)
1169 if ((new_url != NULL)
1170 && ( (new_url != subject)
1171 || (0 == strncmpic(subject, "http://", 7))
1172 || (0 == strncmpic(subject, "https://", 8))
1176 * Return new URL if we found a redirect
1177 * or if the subject already was a URL.
1179 * The second case makes sure that we can
1180 * chain get_last_url after another redirection check
1181 * (like rewrite_url) without losing earlier redirects.
1183 new_url = strdup(new_url);
1192 #endif /* def FEATURE_FAST_REDIRECTS */
1195 /*********************************************************************
1197 * Function : redirect_url
1199 * Description : Checks if Privoxy should answer the request with
1200 * a HTTP redirect and generates the redirect if
1204 * 1 : csp = Current client state (buffers, headers, etc...)
1206 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1208 *********************************************************************/
1209 struct http_response *redirect_url(struct client_state *csp)
1211 struct http_response *rsp;
1212 #ifdef FEATURE_FAST_REDIRECTS
1214 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1215 * as compile-time option? The user can easily disable
1216 * it in his action file.
1218 char * redirect_mode;
1219 #endif /* def FEATURE_FAST_REDIRECTS */
1220 char *old_url = NULL;
1221 char *new_url = NULL;
1222 char *redirection_string;
1224 if ((csp->action->flags & ACTION_REDIRECT))
1226 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1229 * If the redirection string begins with 's',
1230 * assume it's a pcrs command, otherwise treat it as
1231 * properly formatted URL and use it for the redirection
1234 * According to RFC 2616 section 14.30 the URL
1235 * has to be absolute and if the user tries:
1236 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1237 * she would get undefined results anyway.
1241 if (*redirection_string == 's')
1243 old_url = csp->http->url;
1244 new_url = rewrite_url(old_url, redirection_string);
1248 log_error(LOG_LEVEL_REDIRECTS,
1249 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1250 redirection_string);
1251 new_url = strdup(redirection_string);
1255 #ifdef FEATURE_FAST_REDIRECTS
1256 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1258 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1261 * If it exists, use the previously rewritten URL as input
1262 * otherwise just use the old path.
1264 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1265 new_url = get_last_url(old_url, redirect_mode);
1270 * Disable redirect checkers, so that they
1271 * will be only run more than once if the user
1272 * also enables them through tags.
1274 * From a performance point of view
1275 * it doesn't matter, but the duplicated
1276 * log messages are annoying.
1278 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1279 #endif /* def FEATURE_FAST_REDIRECTS */
1280 csp->action->flags &= ~ACTION_REDIRECT;
1282 /* Did any redirect action trigger? */
1285 if (0 == strcmpic(new_url, csp->http->url))
1287 log_error(LOG_LEVEL_ERROR,
1288 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1289 csp->http->url, new_url);
1294 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1296 if (NULL == (rsp = alloc_http_response()))
1299 return cgi_error_memory();
1302 if ( enlist_unique_header(rsp->headers, "Location", new_url)
1303 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))) )
1306 free_http_response(rsp);
1307 return cgi_error_memory();
1309 rsp->reason = RSP_REASON_REDIRECTED;
1312 return finish_http_response(csp, rsp);
1316 /* Only reached if no redirect is required */
1322 #ifdef FEATURE_IMAGE_BLOCKING
1323 /*********************************************************************
1325 * Function : is_imageurl
1327 * Description : Given a URL, decide whether it is an image or not,
1328 * using either the info from a previous +image action
1329 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1330 * is MSIE and not on a Mac, tell from the browser's accept
1334 * 1 : csp = Current client state (buffers, headers, etc...)
1336 * Returns : True (nonzero) if URL is an image, false (0)
1339 *********************************************************************/
1340 int is_imageurl(const struct client_state *csp)
1342 #ifdef FEATURE_IMAGE_DETECT_MSIE
1345 tmp = get_header_value(csp->headers, "User-Agent:");
1346 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1348 tmp = get_header_value(csp->headers, "Accept:");
1349 if (tmp && strstr(tmp, "image/gif"))
1351 /* Client will accept HTML. If this seems counterintuitive,
1361 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1363 return ((csp->action->flags & ACTION_IMAGE) != 0);
1366 #endif /* def FEATURE_IMAGE_BLOCKING */
1369 #ifdef FEATURE_TRUST
1370 /*********************************************************************
1372 * Function : is_untrusted_url
1374 * Description : Should we "distrust" this URL (and block it)?
1376 * Yes if it matches a line in the trustfile, or if the
1377 * referrer matches a line starting with "+" in the
1382 * 1 : csp = Current client state (buffers, headers, etc...)
1384 * Returns : 0 => trusted, 1 => untrusted
1386 *********************************************************************/
1387 int is_untrusted_url(const struct client_state *csp)
1389 struct file_list *fl;
1390 struct block_spec *b;
1391 struct url_spec **trusted_url;
1392 struct http_request rhttp[1];
1393 const char * referer;
1397 * If we don't have a trustlist, we trust everybody
1399 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1404 memset(rhttp, '\0', sizeof(*rhttp));
1407 * Do we trust the request URL itself?
1409 for (b = b->next; b ; b = b->next)
1411 if (url_match(b->url, csp->http))
1417 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1419 /* no referrer was supplied */
1425 * If not, do we maybe trust its referrer?
1427 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1433 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1435 if (url_match(*trusted_url, rhttp))
1437 /* if the URL's referrer is from a trusted referrer, then
1438 * add the target spec to the trustfile as an unblocked
1439 * domain and return 0 (which means it's OK).
1444 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1448 char * new_entry = strdup("~");
1450 string_append(&new_entry, csp->http->hostport);
1452 path = csp->http->path;
1453 if ( (path[0] == '/')
1455 && ((path_end = strchr(path + 2, '/')) != NULL))
1457 /* since this path points into a user's home space
1458 * be sure to include this spec in the trustfile.
1460 long path_len = path_end - path; /* save offset */
1461 path = strdup(path); /* Copy string */
1464 path_end = path + path_len; /* regenerate ptr to new buffer */
1465 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1467 string_join(&new_entry, path);
1471 * Give a reason for generating this entry.
1473 string_append(&new_entry, " # Trusted referrer was: ");
1474 string_append(&new_entry, referer);
1476 if (new_entry != NULL)
1478 if (-1 == fprintf(fp, "%s\n", new_entry))
1480 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1481 new_entry, csp->config->trustfile);
1487 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1488 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1495 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1496 csp->http->hostport, csp->config->trustfile);
1504 #endif /* def FEATURE_TRUST */
1507 /*********************************************************************
1509 * Function : pcrs_filter_response
1511 * Description : Execute all text substitutions from all applying
1512 * +filter actions on the text buffer that's been
1513 * accumulated in csp->iob->buf.
1516 * 1 : csp = Current client state (buffers, headers, etc...)
1518 * Returns : a pointer to the (newly allocated) modified buffer.
1519 * or NULL if there were no hits or something went wrong
1521 *********************************************************************/
1522 static char *pcrs_filter_response(struct client_state *csp)
1525 size_t size, prev_size;
1531 struct file_list *fl;
1532 struct re_filterfile_spec *b;
1533 struct list_entry *filtername;
1535 int i, found_filters = 0;
1540 if (csp->iob->cur >= csp->iob->eod)
1546 * Need to check the set of re_filterfiles...
1548 for (i = 0; i < MAX_AF_FILES; i++)
1561 if (0 == found_filters)
1563 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1564 "content filtering enabled, but no content filters available.");
1568 size = (size_t)(csp->iob->eod - csp->iob->cur);
1569 old = csp->iob->cur;
1571 for (i = 0; i < MAX_AF_FILES; i++)
1574 if ((NULL == fl) || (NULL == fl->f))
1577 * Either there are no filter files
1578 * left, or this filter file just
1579 * contains no valid filters.
1581 * Continue to be sure we don't miss
1582 * valid filter files that are chained
1583 * after empty or invalid ones.
1588 * For all applying +filter actions, look if a filter by that
1589 * name exists and if yes, execute it's pcrs_joblist on the
1592 for (b = fl->f; b; b = b->next)
1594 if (b->type != FT_CONTENT_FILTER)
1596 /* Skip header filters */
1600 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1601 filtername ; filtername = filtername->next)
1603 if (strcmp(b->name, filtername->str) == 0)
1605 int current_hits = 0; /* Number of hits caused by this filter */
1606 int job_number = 0; /* Which job we're currently executing */
1607 int job_hits = 0; /* How many hits the current job caused */
1608 pcrs_job *joblist = b->joblist;
1610 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1612 if (NULL == joblist)
1614 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1619 /* Apply all jobs from the joblist */
1620 for (job = joblist; NULL != job; job = job->next)
1623 job_hits = pcrs_execute(job, old, size, &new, &size);
1628 * That went well. Continue filtering
1629 * and use the result of this job as
1630 * input for the next one.
1632 current_hits += job_hits;
1633 if (old != csp->iob->cur)
1642 * This job caused an unexpected error. Inform the user
1643 * and skip the rest of the jobs in this filter. We could
1644 * continue with the next job, but usually the jobs
1645 * depend on each other or are similar enough to
1646 * fail for the same reason.
1648 * At the moment our pcrs expects the error codes of pcre 3.4,
1649 * but newer pcre versions can return additional error codes.
1650 * As a result pcrs_strerror()'s error message might be
1651 * "Unknown error ...", therefore we print the numerical value
1654 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1655 * should we use LOG_LEVEL_RE_FILTER instead?
1657 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1658 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1663 if (b->dynamic) pcrs_free_joblist(joblist);
1665 log_error(LOG_LEVEL_RE_FILTER,
1666 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1667 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1669 hits += current_hits;
1676 * If there were no hits, destroy our copy and let
1677 * chat() use the original in csp->iob
1685 csp->flags |= CSP_FLAG_MODIFIED;
1686 csp->content_length = size;
1694 /*********************************************************************
1696 * Function : gif_deanimate_response
1698 * Description : Deanimate the GIF image that has been accumulated in
1699 * csp->iob->buf, set csp->content_length to the modified
1700 * size and raise the CSP_FLAG_MODIFIED flag.
1703 * 1 : csp = Current client state (buffers, headers, etc...)
1705 * Returns : a pointer to the (newly allocated) modified buffer.
1706 * or NULL in case something went wrong.
1708 *********************************************************************/
1709 static char *gif_deanimate_response(struct client_state *csp)
1711 struct binbuffer *in, *out;
1715 size = (size_t)(csp->iob->eod - csp->iob->cur);
1717 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1718 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1720 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1724 in->buffer = csp->iob->cur;
1727 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1729 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1736 if ((int)size == out->offset)
1738 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1742 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1744 csp->content_length = out->offset;
1745 csp->flags |= CSP_FLAG_MODIFIED;
1755 /*********************************************************************
1757 * Function : get_filter_function
1759 * Description : Decides which content filter function has
1760 * to be applied (if any).
1763 * 1 : csp = Current client state (buffers, headers, etc...)
1765 * Returns : The content filter function to run, or
1766 * NULL if no content filter is active
1768 *********************************************************************/
1769 filter_function_ptr get_filter_function(struct client_state *csp)
1771 filter_function_ptr filter_function = NULL;
1773 if ((csp->content_type & CT_TABOO)
1774 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
1780 * Are we enabling text mode by force?
1782 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1785 * Do we really have to?
1787 if (csp->content_type & CT_TEXT)
1789 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1793 csp->content_type |= CT_TEXT;
1794 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1798 if (!(csp->content_type & CT_DECLARED))
1801 * The server didn't bother to declare a MIME-Type.
1802 * Assume it's text that can be filtered.
1804 * This also regulary happens with 304 responses,
1805 * therefore logging anything here would cause
1808 csp->content_type |= CT_TEXT;
1812 * Choose the applying filter function based on
1813 * the content type and action settings.
1815 if ((csp->content_type & CT_TEXT) &&
1816 (csp->rlist != NULL) &&
1817 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1819 filter_function = pcrs_filter_response;
1821 else if ((csp->content_type & CT_GIF) &&
1822 (csp->action->flags & ACTION_DEANIMATE))
1824 filter_function = gif_deanimate_response;
1827 return filter_function;
1831 /*********************************************************************
1833 * Function : remove_chunked_transfer_coding
1835 * Description : In-situ remove the "chunked" transfer coding as defined
1836 * in rfc2616 from a buffer.
1839 * 1 : buffer = Pointer to the text buffer
1840 * 2 : size = In: Number of bytes to be processed,
1841 * Out: Number of bytes after de-chunking.
1842 * (undefined in case of errors)
1844 * Returns : JB_ERR_OK for success,
1845 * JB_ERR_PARSE otherwise
1847 *********************************************************************/
1848 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1851 unsigned int chunksize = 0;
1852 char *from_p, *to_p;
1855 from_p = to_p = buffer;
1857 if (sscanf(buffer, "%x", &chunksize) != 1)
1859 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1860 return JB_ERR_PARSE;
1863 while (chunksize > 0U)
1865 if (NULL == (from_p = strstr(from_p, "\r\n")))
1867 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1868 return JB_ERR_PARSE;
1871 if ((newsize += chunksize) >= *size)
1873 log_error(LOG_LEVEL_ERROR,
1874 "Chunk size %d exceeds buffer size %d in \"chunked\" transfer coding",
1876 return JB_ERR_PARSE;
1880 memmove(to_p, from_p, (size_t) chunksize);
1881 to_p = buffer + newsize;
1882 from_p += chunksize + 2;
1884 if (sscanf(from_p, "%x", &chunksize) != 1)
1886 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1891 /* XXX: Should get its own loglevel. */
1892 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1901 /*********************************************************************
1903 * Function : prepare_for_filtering
1905 * Description : If necessary, de-chunks and decompresses
1906 * the content so it can get filterd.
1909 * 1 : csp = Current client state (buffers, headers, etc...)
1911 * Returns : JB_ERR_OK for success,
1912 * JB_ERR_PARSE otherwise
1914 *********************************************************************/
1915 static jb_err prepare_for_filtering(struct client_state *csp)
1917 jb_err err = JB_ERR_OK;
1920 * If the body has a "chunked" transfer-encoding,
1921 * get rid of it, adjusting size and iob->eod
1923 if (csp->flags & CSP_FLAG_CHUNKED)
1925 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1927 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1928 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1929 if (JB_ERR_OK == err)
1931 csp->iob->eod = csp->iob->cur + size;
1932 csp->flags |= CSP_FLAG_MODIFIED;
1936 return JB_ERR_PARSE;
1942 * If the body has a supported transfer-encoding,
1943 * decompress it, adjusting size and iob->eod.
1945 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1947 if (0 == csp->iob->eod - csp->iob->cur)
1949 /* Nothing left after de-chunking. */
1953 err = decompress_iob(csp);
1955 if (JB_ERR_OK == err)
1957 csp->flags |= CSP_FLAG_MODIFIED;
1958 csp->content_type &= ~CT_TABOO;
1963 * Unset CT_GZIP and CT_DEFLATE to remember not
1964 * to modify the Content-Encoding header later.
1966 csp->content_type &= ~CT_GZIP;
1967 csp->content_type &= ~CT_DEFLATE;
1976 /*********************************************************************
1978 * Function : execute_content_filter
1980 * Description : Executes a given content filter.
1983 * 1 : csp = Current client state (buffers, headers, etc...)
1984 * 2 : content_filter = The filter function to execute
1986 * Returns : Pointer to the modified buffer, or
1987 * NULL if filtering failed or wasn't necessary.
1989 *********************************************************************/
1990 char *execute_content_filter(struct client_state *csp, filter_function_ptr content_filter)
1992 if (0 == csp->iob->eod - csp->iob->cur)
1995 * No content (probably status code 301, 302 ...),
1996 * no filtering necessary.
2001 if (JB_ERR_OK != prepare_for_filtering(csp))
2004 * failed to de-chunk or decompress.
2009 if (0 == csp->iob->eod - csp->iob->cur)
2012 * Clown alarm: chunked and/or compressed nothing delivered.
2017 return ((*content_filter)(csp));
2021 /*********************************************************************
2023 * Function : get_url_actions
2025 * Description : Gets the actions for this URL.
2028 * 1 : csp = Current client state (buffers, headers, etc...)
2029 * 2 : http = http_request request for blocked URLs
2033 *********************************************************************/
2034 void get_url_actions(struct client_state *csp, struct http_request *http)
2036 struct file_list *fl;
2037 struct url_actions *b;
2040 init_current_action(csp->action);
2042 for (i = 0; i < MAX_AF_FILES; i++)
2044 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2049 apply_url_actions(csp->action, http, b);
2056 /*********************************************************************
2058 * Function : apply_url_actions
2060 * Description : Applies a list of URL actions.
2063 * 1 : action = Destination.
2064 * 2 : http = Current URL
2065 * 3 : b = list of URL actions to apply
2069 *********************************************************************/
2070 void apply_url_actions(struct current_action_spec *action,
2071 struct http_request *http,
2072 struct url_actions *b)
2076 /* Should never happen */
2080 for (b = b->next; NULL != b; b = b->next)
2082 if (url_match(b->url, http))
2084 merge_current_action(action, b->action);
2090 /*********************************************************************
2092 * Function : get_forward_override_settings
2094 * Description : Returns forward settings as specified with the
2095 * forward-override{} action. forward-override accepts
2096 * forward lines similar to the one used in the
2097 * configuration file, but without the URL pattern.
2103 * in the configuration file can be replaced with
2104 * the action section:
2106 * {+forward-override{forward .}}
2110 * 1 : csp = Current client state (buffers, headers, etc...)
2112 * Returns : Pointer to forwarding structure in case of success.
2113 * Invalid syntax is fatal.
2115 *********************************************************************/
2116 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2118 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2119 char forward_settings[BUFFER_SIZE];
2120 char *http_parent = NULL;
2121 /* variable names were chosen for consistency reasons. */
2122 struct forward_spec *fwd = NULL;
2126 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2127 /* Should be enforced by load_one_actions_file() */
2128 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2130 /* Create a copy ssplit can modify */
2131 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2133 if (NULL != csp->fwd)
2136 * XXX: Currently necessary to prevent memory
2137 * leaks when the show-url-info cgi page is visited.
2139 unload_forward_spec(csp->fwd);
2143 * allocate a new forward node, valid only for
2144 * the lifetime of this request. Save its location
2145 * in csp as well, so sweep() can free it later on.
2147 fwd = csp->fwd = zalloc(sizeof(*fwd));
2150 log_error(LOG_LEVEL_FATAL,
2151 "can't allocate memory for forward-override{%s}", forward_override_line);
2152 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2156 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2157 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2159 fwd->type = SOCKS_NONE;
2161 /* Parse the parent HTTP proxy host:port */
2162 http_parent = vec[1];
2165 else if (vec_count == 3)
2167 char *socks_proxy = NULL;
2169 if (!strcasecmp(vec[0], "forward-socks4"))
2171 fwd->type = SOCKS_4;
2172 socks_proxy = vec[1];
2174 else if (!strcasecmp(vec[0], "forward-socks4a"))
2176 fwd->type = SOCKS_4A;
2177 socks_proxy = vec[1];
2179 else if (!strcasecmp(vec[0], "forward-socks5"))
2181 fwd->type = SOCKS_5;
2182 socks_proxy = vec[1];
2185 if (NULL != socks_proxy)
2187 /* Parse the SOCKS proxy host[:port] */
2188 fwd->gateway_port = 1080;
2189 parse_forwarder_address(socks_proxy,
2190 &fwd->gateway_host, &fwd->gateway_port);
2192 http_parent = vec[2];
2196 if (NULL == http_parent)
2198 log_error(LOG_LEVEL_FATAL,
2199 "Invalid forward-override syntax in: %s", forward_override_line);
2200 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2203 /* Parse http forwarding settings */
2204 if (strcmp(http_parent, ".") != 0)
2206 fwd->forward_port = 8000;
2207 parse_forwarder_address(http_parent,
2208 &fwd->forward_host, &fwd->forward_port);
2211 assert (NULL != fwd);
2213 log_error(LOG_LEVEL_CONNECT,
2214 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2220 /*********************************************************************
2222 * Function : forward_url
2224 * Description : Should we forward this to another proxy?
2227 * 1 : csp = Current client state (buffers, headers, etc...)
2228 * 2 : http = http_request request for current URL
2230 * Returns : Pointer to forwarding information.
2232 *********************************************************************/
2233 const struct forward_spec *forward_url(struct client_state *csp,
2234 const struct http_request *http)
2236 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2237 struct forward_spec *fwd = csp->config->forward;
2239 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2241 return get_forward_override_settings(csp);
2251 if (url_match(fwd->url, http))
2262 /*********************************************************************
2264 * Function : direct_response
2266 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2267 * request and if so, return a HTTP 501 to the client.
2269 * FIXME: I have a stupid name and I should handle the
2270 * requests properly. Still, what we do here is rfc-
2271 * compliant, whereas ignoring or forwarding are not.
2274 * 1 : csp = Current client state (buffers, headers, etc...)
2276 * Returns : http_response if , NULL if nonmatch or handler fail
2278 *********************************************************************/
2279 struct http_response *direct_response(struct client_state *csp)
2281 struct http_response *rsp;
2282 struct list_entry *p;
2284 if ((0 == strcmpic(csp->http->gpc, "trace"))
2285 || (0 == strcmpic(csp->http->gpc, "options")))
2287 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2289 if (!strncmpic("Max-Forwards:", p->str, 13))
2291 unsigned int max_forwards;
2294 * If it's a Max-Forwards value of zero,
2295 * we have to intercept the request.
2297 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2300 * FIXME: We could handle at least TRACE here,
2301 * but that would require a verbatim copy of
2302 * the request which we don't have anymore
2304 log_error(LOG_LEVEL_HEADER,
2305 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2308 /* Get mem for response or fail*/
2309 if (NULL == (rsp = alloc_http_response()))
2311 return cgi_error_memory();
2314 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2316 free_http_response(rsp);
2317 return cgi_error_memory();
2321 rsp->reason = RSP_REASON_UNSUPPORTED;
2323 return(finish_http_response(csp, rsp));
2332 /*********************************************************************
2334 * Function : content_filters_enabled
2336 * Description : Checks whether there are any content filters
2337 * enabled for the current request.
2340 * 1 : action = Action spec to check.
2342 * Returns : TRUE for yes, FALSE otherwise
2344 *********************************************************************/
2345 int content_filters_enabled(const struct current_action_spec *action)
2347 return ((action->flags & ACTION_DEANIMATE) ||
2348 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));