1 const char filters_rcs[] = "$Id: filters.c,v 1.154 2011/10/30 16:22:46 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-2010 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>
56 #endif /* ndef __OS2__ */
57 #include <netinet/in.h>
60 #endif /* ndef _WIN32 */
64 #endif /* def __OS2__ */
72 #include "jbsockets.h"
77 #include "deanimate.h"
82 /* Only used for locks */
84 #endif /* def HAVE_STRTOK */
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 typedef char *(*filter_function_ptr)();
102 static filter_function_ptr get_filter_function(const struct client_state *csp);
103 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
104 static jb_err prepare_for_filtering(struct client_state *csp);
108 /*********************************************************************
110 * Function : sockaddr_storage_to_ip
112 * Description : Access internal structure of sockaddr_storage
115 * 1 : addr = socket address
116 * 2 : ip = IP address as array of octets in network order
117 * (it points into addr)
118 * 3 : len = length of IP address in octets
119 * 4 : port = port number in network order;
121 * Returns : 0 = no errror; -1 otherwise.
123 *********************************************************************/
124 static int sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
125 uint8_t **ip, unsigned int *len,
133 switch (addr->ss_family)
143 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
147 *port = &((struct sockaddr_in *)addr)->sin_port;
158 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
162 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
167 /* Unsupported address family */
175 /*********************************************************************
177 * Function : match_sockaddr
179 * Description : Check whether address matches network (IP address and port)
182 * 1 : network = socket address of subnework
183 * 2 : netmask = network mask as socket address
184 * 3 : address = checked socket address against given network
186 * Returns : 0 = doesn't match; 1 = does match
188 *********************************************************************/
189 static int match_sockaddr(const struct sockaddr_storage *network,
190 const struct sockaddr_storage *netmask,
191 const struct sockaddr_storage *address)
193 uint8_t *network_addr, *netmask_addr, *address_addr;
194 unsigned int addr_len;
195 in_port_t *network_port, *netmask_port, *address_port;
198 if (network->ss_family != netmask->ss_family)
200 /* This should never happen */
201 log_error(LOG_LEVEL_ERROR,
202 "Internal error at %s:%llu: network and netmask differ in family",
207 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
208 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
209 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
211 /* Check for family */
212 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
213 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
215 /* Map AF_INET6 V4MAPPED address into AF_INET */
219 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
220 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
222 /* Map AF_INET6 V4MAPPED network into AF_INET */
227 else if (network->ss_family != address->ss_family)
232 /* XXX: Port check is signaled in netmask */
233 if (*netmask_port && *network_port != *address_port)
238 /* TODO: Optimize by checking by words insted of octets */
239 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
241 if ((network_addr[i] & netmask_addr[i]) !=
242 (address_addr[i] & netmask_addr[i]))
250 #endif /* def HAVE_RFC2553 */
253 /*********************************************************************
255 * Function : block_acl
257 * Description : Block this request?
258 * Decide yes or no based on ACL file.
261 * 1 : dst = The proxy or gateway address this is going to.
262 * Or NULL to check all possible targets.
263 * 2 : csp = Current client state (buffers, headers, etc...)
264 * Also includes the client IP address.
266 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
268 *********************************************************************/
269 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
271 struct access_control_list *acl = csp->config->acl;
273 /* if not using an access control list, then permit the connection */
279 /* search the list */
284 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
286 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
292 /* Just want to check if they have any access */
293 if (acl->action == ACL_PERMIT)
305 * XXX: An undefined acl->dst is full of zeros and should be
306 * considered a wildcard address. sockaddr_storage_to_ip()
307 * fails on such destinations because of unknown sa_familly
308 * (glibc only?). However this test is not portable.
310 * So, we signal the acl->dst is wildcard in wildcard_dst.
313 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
315 ((dst->addr & acl->dst->mask) == acl->dst->addr)
316 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
320 if (acl->action == ACL_PERMIT)
338 /*********************************************************************
340 * Function : acl_addr
342 * Description : Called from `load_config' to parse an ACL address.
345 * 1 : aspec = String specifying ACL address.
346 * 2 : aca = struct access_control_addr to fill in.
348 * Returns : 0 => Ok, everything else is an error.
350 *********************************************************************/
351 int acl_addr(const char *aspec, struct access_control_addr *aca)
355 struct addrinfo hints, *result;
357 in_port_t *mask_port;
358 unsigned int addr_len;
361 #endif /* def HAVE_RFC2553 */
363 char *acl_spec = NULL;
366 /* XXX: Depend on ai_family */
374 * Use a temporary acl spec copy so we can log
375 * the unmodified original in case of parse errors.
377 acl_spec = strdup(aspec);
378 if (acl_spec == NULL)
380 /* XXX: This will be logged as parse error. */
384 if ((p = strchr(acl_spec, '/')) != NULL)
387 if (ijb_isdigit(*p) == 0)
392 masklength = atoi(p);
395 if ((masklength < 0) ||
407 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
410 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
419 p = strchr(acl_spec, ':');
423 memset(&hints, 0, sizeof(struct addrinfo));
424 hints.ai_family = AF_UNSPEC;
425 hints.ai_socktype = SOCK_STREAM;
427 i = getaddrinfo(acl_spec, ((p) ? ++p : NULL), &hints, &result);
431 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
432 acl_spec, p, gai_strerror(i));
438 /* TODO: Allow multihomed hostnames */
439 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
440 freeaddrinfo(result);
447 port = strtol(p, &endptr, 10);
449 if (port <= 0 || port > 65535 || *endptr != '\0')
456 aca->port = (unsigned long)port;
458 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
461 if (aca->addr == INADDR_NONE)
463 /* XXX: This will be logged as parse error. */
466 #endif /* def HAVE_RFC2553 */
468 /* build the netmask */
470 /* Clip masklength according to current family. */
471 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
476 aca->mask.ss_family = aca->addr.ss_family;
477 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
484 /* ACL contains a port number, check ports in the future. */
489 * XXX: This could be optimized to operate on whole words instead
490 * of octets (128-bit CPU could do it in one iteration).
493 * Octets after prefix can be omitted because of
494 * previous initialization to zeros.
496 for (i = 0; (i < addr_len) && masklength; i++)
506 * XXX: This assumes MSB of octet is on the left side.
507 * This should be true for all architectures or solved
510 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
517 for (i=1; i <= masklength ; i++)
519 aca->mask |= (1U << (32 - i));
522 /* now mask off the host portion of the ip address
523 * (i.e. save on the network portion of the address).
525 aca->addr = aca->addr & aca->mask;
526 #endif /* def HAVE_RFC2553 */
531 #endif /* def FEATURE_ACL */
534 /*********************************************************************
536 * Function : connect_port_is_forbidden
538 * Description : Check to see if CONNECT requests to the destination
539 * port of this request are forbidden. The check is
540 * independend of the actual request method.
543 * 1 : csp = Current client state (buffers, headers, etc...)
545 * Returns : True if yes, false otherwise.
547 *********************************************************************/
548 int connect_port_is_forbidden(const struct client_state *csp)
550 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
551 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
556 /*********************************************************************
558 * Function : block_url
560 * Description : Called from `chat'. Check to see if we need to block this.
563 * 1 : csp = Current client state (buffers, headers, etc...)
565 * Returns : NULL => unblocked, else HTTP block response
567 *********************************************************************/
568 struct http_response *block_url(struct client_state *csp)
570 struct http_response *rsp;
571 const char *new_content_type = NULL;
574 * If it's not blocked, don't block it ;-)
576 if ((csp->action->flags & ACTION_BLOCK) == 0)
580 if (csp->action->flags & ACTION_REDIRECT)
582 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
585 * Else, prepare a response
587 if (NULL == (rsp = alloc_http_response()))
589 return cgi_error_memory();
593 * If it's an image-url, send back an image or redirect
594 * as specified by the relevant +image action
596 #ifdef FEATURE_IMAGE_BLOCKING
597 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
601 /* determine HOW images should be blocked */
602 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
604 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
606 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
609 /* and handle accordingly: */
610 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
612 rsp->status = strdup("403 Request blocked by Privoxy");
613 if (rsp->status == NULL)
615 free_http_response(rsp);
616 return cgi_error_memory();
618 rsp->body = bindup(image_pattern_data, image_pattern_length);
619 if (rsp->body == NULL)
621 free_http_response(rsp);
622 return cgi_error_memory();
624 rsp->content_length = image_pattern_length;
626 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
628 free_http_response(rsp);
629 return cgi_error_memory();
632 else if (0 == strcmpic(p, "blank"))
634 rsp->status = strdup("403 Request blocked by Privoxy");
635 if (rsp->status == NULL)
637 free_http_response(rsp);
638 return cgi_error_memory();
640 rsp->body = bindup(image_blank_data, image_blank_length);
641 if (rsp->body == NULL)
643 free_http_response(rsp);
644 return cgi_error_memory();
646 rsp->content_length = image_blank_length;
648 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
650 free_http_response(rsp);
651 return cgi_error_memory();
656 rsp->status = strdup("302 Local Redirect from Privoxy");
657 if (rsp->status == NULL)
659 free_http_response(rsp);
660 return cgi_error_memory();
663 if (enlist_unique_header(rsp->headers, "Location", p))
665 free_http_response(rsp);
666 return cgi_error_memory();
672 #endif /* def FEATURE_IMAGE_BLOCKING */
673 if(csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
676 * Send empty document.
678 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
681 rsp->body = strdup(" ");
682 rsp->content_length = 1;
684 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
687 * Workaround for firefox bug 492459
688 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
689 * Return a 200 OK status for pages blocked with +handle-as-empty-document
690 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
692 rsp->status = strdup("200 Request blocked by Privoxy");
696 rsp->status = strdup("403 Request blocked by Privoxy");
699 if (rsp->status == NULL)
701 free_http_response(rsp);
702 return cgi_error_memory();
704 if (new_content_type != 0)
706 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
707 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
709 free_http_response(rsp);
710 return cgi_error_memory();
717 * Else, generate an HTML "blocked" message:
721 struct map * exports;
723 rsp->status = strdup("403 Request blocked by Privoxy");
724 if (rsp->status == NULL)
726 free_http_response(rsp);
727 return cgi_error_memory();
730 exports = default_exports(csp, NULL);
733 free_http_response(rsp);
734 return cgi_error_memory();
737 #ifdef FEATURE_FORCE_LOAD
738 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
740 * Export the force conditional block killer if
742 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
743 * - Privoxy is configured to enforce blocks, or
744 * - it's a CONNECT request and enforcing wouldn't work anyway.
746 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
747 || (0 == strcmpic(csp->http->gpc, "connect")))
748 #endif /* ndef FEATURE_FORCE_LOAD */
750 err = map_block_killer(exports, "force-support");
753 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
754 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
755 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
756 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
759 const char *block_reason;
760 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
762 block_reason = csp->action->string[ACTION_STRING_BLOCK];
766 assert(connect_port_is_forbidden(csp));
767 block_reason = "Forbidden CONNECT port.";
769 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
774 free_http_response(rsp);
775 return cgi_error_memory();
778 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
781 free_http_response(rsp);
782 return cgi_error_memory();
785 rsp->crunch_reason = BLOCKED;
787 return finish_http_response(csp, rsp);
793 /*********************************************************************
795 * Function : trust_url FIXME: I should be called distrust_url
797 * Description : Calls is_untrusted_url to determine if the URL is trusted
798 * and if not, returns a HTTP 403 response with a reject message.
801 * 1 : csp = Current client state (buffers, headers, etc...)
803 * Returns : NULL => trusted, else http_response.
805 *********************************************************************/
806 struct http_response *trust_url(struct client_state *csp)
808 struct http_response *rsp;
809 struct map * exports;
810 char buf[BUFFER_SIZE];
812 struct url_spec **tl;
817 * Don't bother to work on trusted URLs
819 if (!is_untrusted_url(csp))
825 * Else, prepare a response:
827 if (NULL == (rsp = alloc_http_response()))
829 return cgi_error_memory();
832 rsp->status = strdup("403 Request blocked by Privoxy");
833 exports = default_exports(csp, NULL);
834 if (exports == NULL || rsp->status == NULL)
836 free_http_response(rsp);
837 return cgi_error_memory();
841 * Export the protocol, host, port, and referrer information
843 err = map(exports, "hostport", 1, csp->http->hostport, 1);
844 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
845 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
847 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
849 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
853 if (!err) err = map(exports, "referrer", 1, "none set", 1);
859 free_http_response(rsp);
860 return cgi_error_memory();
864 * Export the trust list
867 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
869 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
870 string_append(&p, buf);
872 err = map(exports, "trusted-referrers", 1, p, 0);
877 free_http_response(rsp);
878 return cgi_error_memory();
882 * Export the trust info, if available
884 if (csp->config->trust_info->first)
886 struct list_entry *l;
889 for (l = csp->config->trust_info->first; l ; l = l->next)
891 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
892 string_append(&p, buf);
894 err = map(exports, "trust-info", 1, p, 0);
898 err = map_block_killer(exports, "have-trust-info");
904 free_http_response(rsp);
905 return cgi_error_memory();
909 * Export the force conditional block killer if
911 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
912 * - Privoxy is configured to enforce blocks, or
913 * - it's a CONNECT request and enforcing wouldn't work anyway.
915 #ifdef FEATURE_FORCE_LOAD
916 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
917 || (0 == strcmpic(csp->http->gpc, "connect")))
919 err = map_block_killer(exports, "force-support");
923 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
925 #else /* ifndef FEATURE_FORCE_LOAD */
926 err = map_block_killer(exports, "force-support");
927 #endif /* ndef FEATURE_FORCE_LOAD */
932 free_http_response(rsp);
933 return cgi_error_memory();
939 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
942 free_http_response(rsp);
943 return cgi_error_memory();
945 rsp->crunch_reason = UNTRUSTED;
947 return finish_http_response(csp, rsp);
949 #endif /* def FEATURE_TRUST */
952 /*********************************************************************
954 * Function : compile_dynamic_pcrs_job_list
956 * Description : Compiles a dynamic pcrs job list (one with variables
957 * resolved at request time)
960 * 1 : csp = Current client state (buffers, headers, etc...)
961 * 2 : b = The filter list to compile
963 * Returns : NULL in case of errors, otherwise the
966 *********************************************************************/
967 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
969 struct list_entry *pattern;
970 pcrs_job *job_list = NULL;
971 pcrs_job *dummy = NULL;
972 pcrs_job *lastjob = NULL;
975 const struct pcrs_variable variables[] =
977 {"url", csp->http->url, 1},
978 {"path", csp->http->path, 1},
979 {"host", csp->http->host, 1},
980 {"origin", csp->ip_addr_str, 1},
984 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
986 assert(pattern->str != NULL);
988 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
991 log_error(LOG_LEVEL_ERROR,
992 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
993 pattern->str, b->name, error, pcrs_strerror(error));
998 if (error == PCRS_WARN_TRUNCATION)
1000 log_error(LOG_LEVEL_ERROR,
1001 "At least one of the variables in \'%s\' had to "
1002 "be truncated before compilation", pattern->str);
1004 if (job_list == NULL)
1010 lastjob->next = dummy;
1020 /*********************************************************************
1022 * Function : rewrite_url
1024 * Description : Rewrites a URL with a single pcrs command
1025 * and returns the result if it differs from the
1026 * original and isn't obviously invalid.
1029 * 1 : old_url = URL to rewrite.
1030 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1033 * Returns : NULL if the pcrs_command didn't change the url, or
1034 * the result of the modification.
1036 *********************************************************************/
1037 char *rewrite_url(char *old_url, const char *pcrs_command)
1039 char *new_url = NULL;
1043 assert(pcrs_command);
1045 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1049 log_error(LOG_LEVEL_REDIRECTS,
1050 "pcrs command \"%s\" didn't change \"%s\".",
1051 pcrs_command, old_url);
1056 log_error(LOG_LEVEL_REDIRECTS,
1057 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1058 pcrs_command, old_url, pcrs_strerror(hits));
1061 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1063 log_error(LOG_LEVEL_ERROR,
1064 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1065 "but the result doesn't look like a valid URL and will be ignored.",
1066 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1071 log_error(LOG_LEVEL_REDIRECTS,
1072 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1073 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1081 #ifdef FEATURE_FAST_REDIRECTS
1082 /*********************************************************************
1084 * Function : get_last_url
1086 * Description : Search for the last URL inside a string.
1087 * If the string already is a URL, it will
1088 * be the first URL found.
1091 * 1 : subject = the string to check
1092 * 2 : redirect_mode = +fast-redirect{} mode
1094 * Returns : NULL if no URL was found, or
1095 * the last URL found.
1097 *********************************************************************/
1098 char *get_last_url(char *subject, const char *redirect_mode)
1100 char *new_url = NULL;
1104 assert(redirect_mode);
1106 subject = strdup(subject);
1107 if (subject == NULL)
1109 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1113 if (0 == strcmpic(redirect_mode, "check-decoded-url"))
1115 log_error(LOG_LEVEL_REDIRECTS,
1116 "Checking \"%s\" for encoded redirects.", subject);
1118 #if defined(MUTEX_LOCKS_AVAILABLE) && defined(HAVE_STRTOK)
1120 * Check each parameter in the URL separately.
1121 * Sectionize the URL at "?" and "&",
1122 * then URL-decode each component,
1123 * and look for a URL in the decoded result.
1124 * Keep the last one we spot.
1128 privoxy_mutex_lock(&strtok_mutex);
1129 char *token = strtok(subject, "?&");
1132 char *dtoken = url_decode(token);
1135 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", token);
1138 char *http_url = strstr(dtoken, "http://");
1139 char *https_url = strstr(dtoken, "https://");
1140 char *last_url = (http_url && https_url
1141 ? (http_url < https_url ? http_url : https_url)
1142 : (http_url ? http_url : https_url));
1146 found = strdup(last_url);
1149 log_error(LOG_LEVEL_ERROR,
1150 "Out of memory while searching for redirects.");
1151 privoxy_mutex_unlock(&strtok_mutex);
1156 token = strtok(NULL, "?&");
1158 privoxy_mutex_unlock(&strtok_mutex);
1163 new_url = url_decode(subject);
1164 if (new_url != NULL)
1171 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", subject);
1173 #endif /* defined(MUTEX_LOCKS_AVAILABLE) && defined(HAVE_STRTOK) */
1176 /* Else, just look for a URL inside this one, without decoding anything. */
1178 log_error(LOG_LEVEL_REDIRECTS,
1179 "Checking \"%s\" for unencoded redirects.", subject);
1182 * Find the last URL encoded in the request
1185 while ((tmp = strstr(tmp, "http://")) != NULL)
1189 tmp = (new_url != NULL) ? new_url : subject;
1190 while ((tmp = strstr(tmp, "https://")) != NULL)
1195 if ((new_url != NULL)
1196 && ( (new_url != subject)
1197 || (0 == strncmpic(subject, "http://", 7))
1198 || (0 == strncmpic(subject, "https://", 8))
1202 * Return new URL if we found a redirect
1203 * or if the subject already was a URL.
1205 * The second case makes sure that we can
1206 * chain get_last_url after another redirection check
1207 * (like rewrite_url) without losing earlier redirects.
1209 new_url = strdup(new_url);
1218 #endif /* def FEATURE_FAST_REDIRECTS */
1221 /*********************************************************************
1223 * Function : redirect_url
1225 * Description : Checks if Privoxy should answer the request with
1226 * a HTTP redirect and generates the redirect if
1230 * 1 : csp = Current client state (buffers, headers, etc...)
1232 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1234 *********************************************************************/
1235 struct http_response *redirect_url(struct client_state *csp)
1237 struct http_response *rsp;
1238 #ifdef FEATURE_FAST_REDIRECTS
1240 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1241 * as compile-time option? The user can easily disable
1242 * it in his action file.
1244 char * redirect_mode;
1245 #endif /* def FEATURE_FAST_REDIRECTS */
1246 char *old_url = NULL;
1247 char *new_url = NULL;
1248 char *redirection_string;
1250 if ((csp->action->flags & ACTION_REDIRECT))
1252 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1255 * If the redirection string begins with 's',
1256 * assume it's a pcrs command, otherwise treat it as
1257 * properly formatted URL and use it for the redirection
1260 * According to RFC 2616 section 14.30 the URL
1261 * has to be absolute and if the user tries:
1262 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1263 * she would get undefined results anyway.
1267 if (*redirection_string == 's')
1269 old_url = csp->http->url;
1270 new_url = rewrite_url(old_url, redirection_string);
1274 log_error(LOG_LEVEL_REDIRECTS,
1275 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1276 redirection_string);
1277 new_url = strdup(redirection_string);
1281 #ifdef FEATURE_FAST_REDIRECTS
1282 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1284 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1287 * If it exists, use the previously rewritten URL as input
1288 * otherwise just use the old path.
1290 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1291 new_url = get_last_url(old_url, redirect_mode);
1296 * Disable redirect checkers, so that they
1297 * will be only run more than once if the user
1298 * also enables them through tags.
1300 * From a performance point of view
1301 * it doesn't matter, but the duplicated
1302 * log messages are annoying.
1304 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1305 #endif /* def FEATURE_FAST_REDIRECTS */
1306 csp->action->flags &= ~ACTION_REDIRECT;
1308 /* Did any redirect action trigger? */
1311 if (0 == strcmpic(new_url, csp->http->url))
1313 log_error(LOG_LEVEL_ERROR,
1314 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1315 csp->http->url, new_url);
1320 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1322 if (NULL == (rsp = alloc_http_response()))
1325 return cgi_error_memory();
1328 if (enlist_unique_header(rsp->headers, "Location", new_url)
1329 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))))
1332 free_http_response(rsp);
1333 return cgi_error_memory();
1335 rsp->crunch_reason = REDIRECTED;
1338 return finish_http_response(csp, rsp);
1342 /* Only reached if no redirect is required */
1348 #ifdef FEATURE_IMAGE_BLOCKING
1349 /*********************************************************************
1351 * Function : is_imageurl
1353 * Description : Given a URL, decide whether it is an image or not,
1354 * using either the info from a previous +image action
1355 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1356 * is MSIE and not on a Mac, tell from the browser's accept
1360 * 1 : csp = Current client state (buffers, headers, etc...)
1362 * Returns : True (nonzero) if URL is an image, false (0)
1365 *********************************************************************/
1366 int is_imageurl(const struct client_state *csp)
1368 #ifdef FEATURE_IMAGE_DETECT_MSIE
1371 tmp = get_header_value(csp->headers, "User-Agent:");
1372 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1374 tmp = get_header_value(csp->headers, "Accept:");
1375 if (tmp && strstr(tmp, "image/gif"))
1377 /* Client will accept HTML. If this seems counterintuitive,
1387 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1389 return ((csp->action->flags & ACTION_IMAGE) != 0);
1392 #endif /* def FEATURE_IMAGE_BLOCKING */
1395 #ifdef FEATURE_TRUST
1396 /*********************************************************************
1398 * Function : is_untrusted_url
1400 * Description : Should we "distrust" this URL (and block it)?
1402 * Yes if it matches a line in the trustfile, or if the
1403 * referrer matches a line starting with "+" in the
1408 * 1 : csp = Current client state (buffers, headers, etc...)
1410 * Returns : 0 => trusted, 1 => untrusted
1412 *********************************************************************/
1413 int is_untrusted_url(const struct client_state *csp)
1415 struct file_list *fl;
1416 struct block_spec *b;
1417 struct url_spec **trusted_url;
1418 struct http_request rhttp[1];
1419 const char * referer;
1423 * If we don't have a trustlist, we trust everybody
1425 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1430 memset(rhttp, '\0', sizeof(*rhttp));
1433 * Do we trust the request URL itself?
1435 for (b = b->next; b ; b = b->next)
1437 if (url_match(b->url, csp->http))
1443 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1445 /* no referrer was supplied */
1451 * If not, do we maybe trust its referrer?
1453 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1459 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1461 if (url_match(*trusted_url, rhttp))
1463 /* if the URL's referrer is from a trusted referrer, then
1464 * add the target spec to the trustfile as an unblocked
1465 * domain and return 0 (which means it's OK).
1470 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1474 char * new_entry = strdup("~");
1476 string_append(&new_entry, csp->http->hostport);
1478 path = csp->http->path;
1479 if ( (path[0] == '/')
1481 && ((path_end = strchr(path + 2, '/')) != NULL))
1483 /* since this path points into a user's home space
1484 * be sure to include this spec in the trustfile.
1486 long path_len = path_end - path; /* save offset */
1487 path = strdup(path); /* Copy string */
1490 path_end = path + path_len; /* regenerate ptr to new buffer */
1491 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1493 string_join(&new_entry, path);
1497 * Give a reason for generating this entry.
1499 string_append(&new_entry, " # Trusted referrer was: ");
1500 string_append(&new_entry, referer);
1502 if (new_entry != NULL)
1504 if (-1 == fprintf(fp, "%s\n", new_entry))
1506 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1507 new_entry, csp->config->trustfile);
1513 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1514 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1521 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1522 csp->http->hostport, csp->config->trustfile);
1530 #endif /* def FEATURE_TRUST */
1533 /*********************************************************************
1535 * Function : pcrs_filter_response
1537 * Description : Execute all text substitutions from all applying
1538 * +filter actions on the text buffer that's been
1539 * accumulated in csp->iob->buf.
1542 * 1 : csp = Current client state (buffers, headers, etc...)
1544 * Returns : a pointer to the (newly allocated) modified buffer.
1545 * or NULL if there were no hits or something went wrong
1547 *********************************************************************/
1548 static char *pcrs_filter_response(struct client_state *csp)
1552 size_t size, prev_size;
1558 struct file_list *fl;
1559 struct re_filterfile_spec *b;
1560 struct list_entry *filtername;
1565 if (csp->iob->cur >= csp->iob->eod)
1570 if (filters_available(csp) == FALSE)
1572 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1573 "content filtering enabled, but no content filters available.");
1577 size = (size_t)(csp->iob->eod - csp->iob->cur);
1578 old = csp->iob->cur;
1580 for (i = 0; i < MAX_AF_FILES; i++)
1583 if ((NULL == fl) || (NULL == fl->f))
1586 * Either there are no filter files
1587 * left, or this filter file just
1588 * contains no valid filters.
1590 * Continue to be sure we don't miss
1591 * valid filter files that are chained
1592 * after empty or invalid ones.
1597 * For all applying +filter actions, look if a filter by that
1598 * name exists and if yes, execute it's pcrs_joblist on the
1601 for (b = fl->f; b; b = b->next)
1603 if (b->type != FT_CONTENT_FILTER)
1605 /* Skip header filters */
1609 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1610 filtername ; filtername = filtername->next)
1612 if (strcmp(b->name, filtername->str) == 0)
1614 int current_hits = 0; /* Number of hits caused by this filter */
1615 int job_number = 0; /* Which job we're currently executing */
1616 int job_hits = 0; /* How many hits the current job caused */
1617 pcrs_job *joblist = b->joblist;
1619 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1621 if (NULL == joblist)
1623 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1628 /* Apply all jobs from the joblist */
1629 for (job = joblist; NULL != job; job = job->next)
1632 job_hits = pcrs_execute(job, old, size, &new, &size);
1637 * That went well. Continue filtering
1638 * and use the result of this job as
1639 * input for the next one.
1641 current_hits += job_hits;
1642 if (old != csp->iob->cur)
1651 * This job caused an unexpected error. Inform the user
1652 * and skip the rest of the jobs in this filter. We could
1653 * continue with the next job, but usually the jobs
1654 * depend on each other or are similar enough to
1655 * fail for the same reason.
1657 * At the moment our pcrs expects the error codes of pcre 3.4,
1658 * but newer pcre versions can return additional error codes.
1659 * As a result pcrs_strerror()'s error message might be
1660 * "Unknown error ...", therefore we print the numerical value
1663 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1664 * should we use LOG_LEVEL_RE_FILTER instead?
1666 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1667 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1672 if (b->dynamic) pcrs_free_joblist(joblist);
1674 log_error(LOG_LEVEL_RE_FILTER,
1675 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1676 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1678 hits += current_hits;
1685 * If there were no hits, destroy our copy and let
1686 * chat() use the original in csp->iob
1694 csp->flags |= CSP_FLAG_MODIFIED;
1695 csp->content_length = size;
1703 /*********************************************************************
1705 * Function : gif_deanimate_response
1707 * Description : Deanimate the GIF image that has been accumulated in
1708 * csp->iob->buf, set csp->content_length to the modified
1709 * size and raise the CSP_FLAG_MODIFIED flag.
1712 * 1 : csp = Current client state (buffers, headers, etc...)
1714 * Returns : a pointer to the (newly allocated) modified buffer.
1715 * or NULL in case something went wrong.
1717 *********************************************************************/
1718 static char *gif_deanimate_response(struct client_state *csp)
1720 struct binbuffer *in, *out;
1724 size = (size_t)(csp->iob->eod - csp->iob->cur);
1726 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1727 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1729 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1733 in->buffer = csp->iob->cur;
1736 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1738 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1745 if ((int)size == out->offset)
1747 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1751 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1753 csp->content_length = out->offset;
1754 csp->flags |= CSP_FLAG_MODIFIED;
1764 /*********************************************************************
1766 * Function : get_filter_function
1768 * Description : Decides which content filter function has
1769 * to be applied (if any).
1772 * 1 : csp = Current client state (buffers, headers, etc...)
1774 * Returns : The content filter function to run, or
1775 * NULL if no content filter is active
1777 *********************************************************************/
1778 static filter_function_ptr get_filter_function(const struct client_state *csp)
1780 filter_function_ptr filter_function = NULL;
1783 * Choose the applying filter function based on
1784 * the content type and action settings.
1786 if ((csp->content_type & CT_TEXT) &&
1787 (csp->rlist != NULL) &&
1788 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1790 filter_function = pcrs_filter_response;
1792 else if ((csp->content_type & CT_GIF) &&
1793 (csp->action->flags & ACTION_DEANIMATE))
1795 filter_function = gif_deanimate_response;
1798 return filter_function;
1802 /*********************************************************************
1804 * Function : remove_chunked_transfer_coding
1806 * Description : In-situ remove the "chunked" transfer coding as defined
1807 * in rfc2616 from a buffer.
1810 * 1 : buffer = Pointer to the text buffer
1811 * 2 : size = In: Number of bytes to be processed,
1812 * Out: Number of bytes after de-chunking.
1813 * (undefined in case of errors)
1815 * Returns : JB_ERR_OK for success,
1816 * JB_ERR_PARSE otherwise
1818 *********************************************************************/
1819 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1822 unsigned int chunksize = 0;
1823 char *from_p, *to_p;
1826 from_p = to_p = buffer;
1828 if (sscanf(buffer, "%x", &chunksize) != 1)
1830 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1831 return JB_ERR_PARSE;
1834 while (chunksize > 0U)
1836 if (NULL == (from_p = strstr(from_p, "\r\n")))
1838 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1839 return JB_ERR_PARSE;
1842 if ((newsize += chunksize) >= *size)
1845 * XXX: The message is a bit confusing. Isn't the real problem that
1846 * the specified chunk size is greater than the number of bytes
1847 * left in the buffer? This probably means the connection got
1848 * closed prematurely. To be investigated after 3.0.17 is out.
1850 log_error(LOG_LEVEL_ERROR,
1851 "Chunk size %d exceeds buffer size %d in \"chunked\" transfer coding",
1853 return JB_ERR_PARSE;
1857 memmove(to_p, from_p, (size_t) chunksize);
1858 to_p = buffer + newsize;
1859 from_p += chunksize + 2;
1861 if (sscanf(from_p, "%x", &chunksize) != 1)
1863 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1868 /* XXX: Should get its own loglevel. */
1869 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1878 /*********************************************************************
1880 * Function : prepare_for_filtering
1882 * Description : If necessary, de-chunks and decompresses
1883 * the content so it can get filterd.
1886 * 1 : csp = Current client state (buffers, headers, etc...)
1888 * Returns : JB_ERR_OK for success,
1889 * JB_ERR_PARSE otherwise
1891 *********************************************************************/
1892 static jb_err prepare_for_filtering(struct client_state *csp)
1894 jb_err err = JB_ERR_OK;
1897 * If the body has a "chunked" transfer-encoding,
1898 * get rid of it, adjusting size and iob->eod
1900 if (csp->flags & CSP_FLAG_CHUNKED)
1902 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1904 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1905 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1906 if (JB_ERR_OK == err)
1908 csp->iob->eod = csp->iob->cur + size;
1909 csp->flags |= CSP_FLAG_MODIFIED;
1913 return JB_ERR_PARSE;
1919 * If the body has a supported transfer-encoding,
1920 * decompress it, adjusting size and iob->eod.
1922 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1924 if (0 == csp->iob->eod - csp->iob->cur)
1926 /* Nothing left after de-chunking. */
1930 err = decompress_iob(csp);
1932 if (JB_ERR_OK == err)
1934 csp->flags |= CSP_FLAG_MODIFIED;
1935 csp->content_type &= ~CT_TABOO;
1940 * Unset CT_GZIP and CT_DEFLATE to remember not
1941 * to modify the Content-Encoding header later.
1943 csp->content_type &= ~CT_GZIP;
1944 csp->content_type &= ~CT_DEFLATE;
1953 /*********************************************************************
1955 * Function : execute_content_filters
1957 * Description : Executes a given content filter.
1960 * 1 : csp = Current client state (buffers, headers, etc...)
1962 * Returns : Pointer to the modified buffer, or
1963 * NULL if filtering failed or wasn't necessary.
1965 *********************************************************************/
1966 char *execute_content_filters(struct client_state *csp)
1968 filter_function_ptr content_filter;
1970 assert(content_filters_enabled(csp->action));
1972 if (0 == csp->iob->eod - csp->iob->cur)
1975 * No content (probably status code 301, 302 ...),
1976 * no filtering necessary.
1981 if (JB_ERR_OK != prepare_for_filtering(csp))
1984 * failed to de-chunk or decompress.
1989 if (0 == csp->iob->eod - csp->iob->cur)
1992 * Clown alarm: chunked and/or compressed nothing delivered.
1997 content_filter = get_filter_function(csp);
1999 return ((*content_filter)(csp));
2003 /*********************************************************************
2005 * Function : get_url_actions
2007 * Description : Gets the actions for this URL.
2010 * 1 : csp = Current client state (buffers, headers, etc...)
2011 * 2 : http = http_request request for blocked URLs
2015 *********************************************************************/
2016 void get_url_actions(struct client_state *csp, struct http_request *http)
2018 struct file_list *fl;
2019 struct url_actions *b;
2022 init_current_action(csp->action);
2024 for (i = 0; i < MAX_AF_FILES; i++)
2026 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2031 apply_url_actions(csp->action, http, b);
2038 /*********************************************************************
2040 * Function : apply_url_actions
2042 * Description : Applies a list of URL actions.
2045 * 1 : action = Destination.
2046 * 2 : http = Current URL
2047 * 3 : b = list of URL actions to apply
2051 *********************************************************************/
2052 void apply_url_actions(struct current_action_spec *action,
2053 struct http_request *http,
2054 struct url_actions *b)
2058 /* Should never happen */
2062 for (b = b->next; NULL != b; b = b->next)
2064 if (url_match(b->url, http))
2066 merge_current_action(action, b->action);
2072 /*********************************************************************
2074 * Function : get_forward_override_settings
2076 * Description : Returns forward settings as specified with the
2077 * forward-override{} action. forward-override accepts
2078 * forward lines similar to the one used in the
2079 * configuration file, but without the URL pattern.
2085 * in the configuration file can be replaced with
2086 * the action section:
2088 * {+forward-override{forward .}}
2092 * 1 : csp = Current client state (buffers, headers, etc...)
2094 * Returns : Pointer to forwarding structure in case of success.
2095 * Invalid syntax is fatal.
2097 *********************************************************************/
2098 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2100 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2101 char forward_settings[BUFFER_SIZE];
2102 char *http_parent = NULL;
2103 /* variable names were chosen for consistency reasons. */
2104 struct forward_spec *fwd = NULL;
2108 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2109 /* Should be enforced by load_one_actions_file() */
2110 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2112 /* Create a copy ssplit can modify */
2113 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2115 if (NULL != csp->fwd)
2118 * XXX: Currently necessary to prevent memory
2119 * leaks when the show-url-info cgi page is visited.
2121 unload_forward_spec(csp->fwd);
2125 * allocate a new forward node, valid only for
2126 * the lifetime of this request. Save its location
2127 * in csp as well, so sweep() can free it later on.
2129 fwd = csp->fwd = zalloc(sizeof(*fwd));
2132 log_error(LOG_LEVEL_FATAL,
2133 "can't allocate memory for forward-override{%s}", forward_override_line);
2134 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2138 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2139 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2141 fwd->type = SOCKS_NONE;
2143 /* Parse the parent HTTP proxy host:port */
2144 http_parent = vec[1];
2147 else if (vec_count == 3)
2149 char *socks_proxy = NULL;
2151 if (!strcasecmp(vec[0], "forward-socks4"))
2153 fwd->type = SOCKS_4;
2154 socks_proxy = vec[1];
2156 else if (!strcasecmp(vec[0], "forward-socks4a"))
2158 fwd->type = SOCKS_4A;
2159 socks_proxy = vec[1];
2161 else if (!strcasecmp(vec[0], "forward-socks5"))
2163 fwd->type = SOCKS_5;
2164 socks_proxy = vec[1];
2167 if (NULL != socks_proxy)
2169 /* Parse the SOCKS proxy host[:port] */
2170 fwd->gateway_port = 1080;
2171 parse_forwarder_address(socks_proxy,
2172 &fwd->gateway_host, &fwd->gateway_port);
2174 http_parent = vec[2];
2178 if (NULL == http_parent)
2180 log_error(LOG_LEVEL_FATAL,
2181 "Invalid forward-override syntax in: %s", forward_override_line);
2182 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2185 /* Parse http forwarding settings */
2186 if (strcmp(http_parent, ".") != 0)
2188 fwd->forward_port = 8000;
2189 parse_forwarder_address(http_parent,
2190 &fwd->forward_host, &fwd->forward_port);
2193 assert (NULL != fwd);
2195 log_error(LOG_LEVEL_CONNECT,
2196 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2202 /*********************************************************************
2204 * Function : forward_url
2206 * Description : Should we forward this to another proxy?
2209 * 1 : csp = Current client state (buffers, headers, etc...)
2210 * 2 : http = http_request request for current URL
2212 * Returns : Pointer to forwarding information.
2214 *********************************************************************/
2215 const struct forward_spec *forward_url(struct client_state *csp,
2216 const struct http_request *http)
2218 static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2219 struct forward_spec *fwd = csp->config->forward;
2221 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2223 return get_forward_override_settings(csp);
2233 if (url_match(fwd->url, http))
2244 /*********************************************************************
2246 * Function : direct_response
2248 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2249 * request and if so, return a HTTP 501 to the client.
2251 * FIXME: I have a stupid name and I should handle the
2252 * requests properly. Still, what we do here is rfc-
2253 * compliant, whereas ignoring or forwarding are not.
2256 * 1 : csp = Current client state (buffers, headers, etc...)
2258 * Returns : http_response if , NULL if nonmatch or handler fail
2260 *********************************************************************/
2261 struct http_response *direct_response(struct client_state *csp)
2263 struct http_response *rsp;
2264 struct list_entry *p;
2266 if ((0 == strcmpic(csp->http->gpc, "trace"))
2267 || (0 == strcmpic(csp->http->gpc, "options")))
2269 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2271 if (!strncmpic(p->str, "Max-Forwards:", 13))
2273 unsigned int max_forwards;
2276 * If it's a Max-Forwards value of zero,
2277 * we have to intercept the request.
2279 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2282 * FIXME: We could handle at least TRACE here,
2283 * but that would require a verbatim copy of
2284 * the request which we don't have anymore
2286 log_error(LOG_LEVEL_HEADER,
2287 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2290 /* Get mem for response or fail*/
2291 if (NULL == (rsp = alloc_http_response()))
2293 return cgi_error_memory();
2296 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2298 free_http_response(rsp);
2299 return cgi_error_memory();
2303 rsp->crunch_reason = UNSUPPORTED;
2305 return(finish_http_response(csp, rsp));
2314 /*********************************************************************
2316 * Function : content_requires_filtering
2318 * Description : Checks whether there are any content filters
2319 * enabled for the current request and if they
2320 * can actually be applied..
2323 * 1 : csp = Current client state (buffers, headers, etc...)
2325 * Returns : TRUE for yes, FALSE otherwise
2327 *********************************************************************/
2328 int content_requires_filtering(struct client_state *csp)
2330 if ((csp->content_type & CT_TABOO)
2331 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2337 * Are we enabling text mode by force?
2339 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2342 * Do we really have to?
2344 if (csp->content_type & CT_TEXT)
2346 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2350 csp->content_type |= CT_TEXT;
2351 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2355 if (!(csp->content_type & CT_DECLARED))
2358 * The server didn't bother to declare a MIME-Type.
2359 * Assume it's text that can be filtered.
2361 * This also regulary happens with 304 responses,
2362 * therefore logging anything here would cause
2365 csp->content_type |= CT_TEXT;
2369 * Choose the applying filter function based on
2370 * the content type and action settings.
2372 if ((csp->content_type & CT_TEXT) &&
2373 (csp->rlist != NULL) &&
2374 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2378 else if ((csp->content_type & CT_GIF) &&
2379 (csp->action->flags & ACTION_DEANIMATE))
2389 /*********************************************************************
2391 * Function : content_filters_enabled
2393 * Description : Checks whether there are any content filters
2394 * enabled for the current request.
2397 * 1 : action = Action spec to check.
2399 * Returns : TRUE for yes, FALSE otherwise
2401 *********************************************************************/
2402 int content_filters_enabled(const struct current_action_spec *action)
2404 return ((action->flags & ACTION_DEANIMATE) ||
2405 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));
2409 /*********************************************************************
2411 * Function : filters_available
2413 * Description : Checks whether there are any filters available.
2416 * 1 : csp = Current client state (buffers, headers, etc...)
2418 * Returns : TRUE for yes, FALSE otherwise.
2420 *********************************************************************/
2421 int filters_available(const struct client_state *csp)
2424 for (i = 0; i < MAX_AF_FILES; i++)
2426 const struct file_list *fl = csp->rlist[i];
2427 if ((NULL != fl) && (NULL != fl->f))