1 const char filters_rcs[] = "$Id: filters.c,v 1.178 2013/11/24 14:22:51 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2011 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 #endif /* ndef __OS2__ */
49 #include <netinet/in.h>
52 #endif /* ndef _WIN32 */
56 #endif /* def __OS2__ */
64 #include "jbsockets.h"
69 #include "deanimate.h"
77 const char filters_h_rcs[] = FILTERS_H_VERSION;
79 typedef char *(*filter_function_ptr)();
80 static filter_function_ptr get_filter_function(const struct client_state *csp);
81 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size);
82 static jb_err prepare_for_filtering(struct client_state *csp);
86 /*********************************************************************
88 * Function : sockaddr_storage_to_ip
90 * Description : Access internal structure of sockaddr_storage
93 * 1 : addr = socket address
94 * 2 : ip = IP address as array of octets in network order
95 * (it points into addr)
96 * 3 : len = length of IP address in octets
97 * 4 : port = port number in network order;
99 * Returns : 0 = no errror; -1 otherwise.
101 *********************************************************************/
102 static int sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
103 uint8_t **ip, unsigned int *len,
111 switch (addr->ss_family)
121 &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
125 *port = &((struct sockaddr_in *)addr)->sin_port;
136 *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
140 *port = &((struct sockaddr_in6 *)addr)->sin6_port;
145 /* Unsupported address family */
153 /*********************************************************************
155 * Function : match_sockaddr
157 * Description : Check whether address matches network (IP address and port)
160 * 1 : network = socket address of subnework
161 * 2 : netmask = network mask as socket address
162 * 3 : address = checked socket address against given network
164 * Returns : 0 = doesn't match; 1 = does match
166 *********************************************************************/
167 static int match_sockaddr(const struct sockaddr_storage *network,
168 const struct sockaddr_storage *netmask,
169 const struct sockaddr_storage *address)
171 uint8_t *network_addr, *netmask_addr, *address_addr;
172 unsigned int addr_len;
173 in_port_t *network_port, *netmask_port, *address_port;
176 if (network->ss_family != netmask->ss_family)
178 /* This should never happen */
179 assert(network->ss_family == netmask->ss_family);
180 log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
183 sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
184 sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
185 sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
187 /* Check for family */
188 if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
189 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
191 /* Map AF_INET6 V4MAPPED address into AF_INET */
195 else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
196 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
198 /* Map AF_INET6 V4MAPPED network into AF_INET */
204 /* XXX: Port check is signaled in netmask */
205 if (*netmask_port && *network_port != *address_port)
210 /* TODO: Optimize by checking by words insted of octets */
211 for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
213 if ((network_addr[i] & netmask_addr[i]) !=
214 (address_addr[i] & netmask_addr[i]))
222 #endif /* def HAVE_RFC2553 */
225 /*********************************************************************
227 * Function : block_acl
229 * Description : Block this request?
230 * Decide yes or no based on ACL file.
233 * 1 : dst = The proxy or gateway address this is going to.
234 * Or NULL to check all possible targets.
235 * 2 : csp = Current client state (buffers, headers, etc...)
236 * Also includes the client IP address.
238 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
240 *********************************************************************/
241 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
243 struct access_control_list *acl = csp->config->acl;
245 /* if not using an access control list, then permit the connection */
251 /* search the list */
256 match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
258 (csp->ip_addr_long & acl->src->mask) == acl->src->addr
264 /* Just want to check if they have any access */
265 if (acl->action == ACL_PERMIT)
277 * XXX: An undefined acl->dst is full of zeros and should be
278 * considered a wildcard address. sockaddr_storage_to_ip()
279 * fails on such destinations because of unknown sa_familly
280 * (glibc only?). However this test is not portable.
282 * So, we signal the acl->dst is wildcard in wildcard_dst.
285 match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
287 ((dst->addr & acl->dst->mask) == acl->dst->addr)
288 && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
292 if (acl->action == ACL_PERMIT)
310 /*********************************************************************
312 * Function : acl_addr
314 * Description : Called from `load_config' to parse an ACL address.
317 * 1 : aspec = String specifying ACL address.
318 * 2 : aca = struct access_control_addr to fill in.
320 * Returns : 0 => Ok, everything else is an error.
322 *********************************************************************/
323 int acl_addr(const char *aspec, struct access_control_addr *aca)
327 struct addrinfo hints, *result;
329 in_port_t *mask_port;
330 unsigned int addr_len;
333 #endif /* def HAVE_RFC2553 */
335 char *acl_spec = NULL;
338 /* XXX: Depend on ai_family */
346 * Use a temporary acl spec copy so we can log
347 * the unmodified original in case of parse errors.
349 acl_spec = strdup(aspec);
350 if (acl_spec == NULL)
352 /* XXX: This will be logged as parse error. */
356 if ((p = strchr(acl_spec, '/')) != NULL)
359 if (privoxy_isdigit(*p) == 0)
364 masklength = atoi(p);
367 if ((masklength < 0) ||
379 if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
382 memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
391 p = strchr(acl_spec, ':');
395 memset(&hints, 0, sizeof(struct addrinfo));
396 hints.ai_family = AF_UNSPEC;
397 hints.ai_socktype = SOCK_STREAM;
399 i = getaddrinfo(acl_spec, ((p) ? ++p : NULL), &hints, &result);
403 log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
404 acl_spec, p, gai_strerror(i));
410 /* TODO: Allow multihomed hostnames */
411 memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
412 freeaddrinfo(result);
419 port = strtol(p, &endptr, 10);
421 if (port <= 0 || port > 65535 || *endptr != '\0')
428 aca->port = (unsigned long)port;
430 aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
433 if (aca->addr == INADDR_NONE)
435 /* XXX: This will be logged as parse error. */
438 #endif /* def HAVE_RFC2553 */
440 /* build the netmask */
442 /* Clip masklength according to current family. */
443 if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
448 aca->mask.ss_family = aca->addr.ss_family;
449 if (sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port))
456 /* ACL contains a port number, check ports in the future. */
461 * XXX: This could be optimized to operate on whole words instead
462 * of octets (128-bit CPU could do it in one iteration).
465 * Octets after prefix can be omitted because of
466 * previous initialization to zeros.
468 for (i = 0; (i < addr_len) && masklength; i++)
478 * XXX: This assumes MSB of octet is on the left side.
479 * This should be true for all architectures or solved
482 mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
489 for (i=1; i <= masklength ; i++)
491 aca->mask |= (1U << (32 - i));
494 /* now mask off the host portion of the ip address
495 * (i.e. save on the network portion of the address).
497 aca->addr = aca->addr & aca->mask;
498 #endif /* def HAVE_RFC2553 */
503 #endif /* def FEATURE_ACL */
506 /*********************************************************************
508 * Function : connect_port_is_forbidden
510 * Description : Check to see if CONNECT requests to the destination
511 * port of this request are forbidden. The check is
512 * independend of the actual request method.
515 * 1 : csp = Current client state (buffers, headers, etc...)
517 * Returns : True if yes, false otherwise.
519 *********************************************************************/
520 int connect_port_is_forbidden(const struct client_state *csp)
522 return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
523 !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
528 /*********************************************************************
530 * Function : block_url
532 * Description : Called from `chat'. Check to see if we need to block this.
535 * 1 : csp = Current client state (buffers, headers, etc...)
537 * Returns : NULL => unblocked, else HTTP block response
539 *********************************************************************/
540 struct http_response *block_url(struct client_state *csp)
542 struct http_response *rsp;
543 const char *new_content_type = NULL;
546 * If it's not blocked, don't block it ;-)
548 if ((csp->action->flags & ACTION_BLOCK) == 0)
552 if (csp->action->flags & ACTION_REDIRECT)
554 log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
557 * Else, prepare a response
559 if (NULL == (rsp = alloc_http_response()))
561 return cgi_error_memory();
565 * If it's an image-url, send back an image or redirect
566 * as specified by the relevant +image action
568 #ifdef FEATURE_IMAGE_BLOCKING
569 if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
573 /* determine HOW images should be blocked */
574 p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
576 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
578 log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
581 /* and handle accordingly: */
582 if ((p == NULL) || (0 == strcmpic(p, "pattern")))
584 rsp->status = strdup("403 Request blocked by Privoxy");
585 if (rsp->status == NULL)
587 free_http_response(rsp);
588 return cgi_error_memory();
590 rsp->body = bindup(image_pattern_data, image_pattern_length);
591 if (rsp->body == NULL)
593 free_http_response(rsp);
594 return cgi_error_memory();
596 rsp->content_length = image_pattern_length;
598 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
600 free_http_response(rsp);
601 return cgi_error_memory();
604 else if (0 == strcmpic(p, "blank"))
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_blank_data, image_blank_length);
613 if (rsp->body == NULL)
615 free_http_response(rsp);
616 return cgi_error_memory();
618 rsp->content_length = image_blank_length;
620 if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
622 free_http_response(rsp);
623 return cgi_error_memory();
628 rsp->status = strdup("302 Local Redirect from Privoxy");
629 if (rsp->status == NULL)
631 free_http_response(rsp);
632 return cgi_error_memory();
635 if (enlist_unique_header(rsp->headers, "Location", p))
637 free_http_response(rsp);
638 return cgi_error_memory();
644 #endif /* def FEATURE_IMAGE_BLOCKING */
645 if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
648 * Send empty document.
650 new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
653 rsp->body = strdup(" ");
654 rsp->content_length = 1;
656 if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
659 * Workaround for firefox bug 492459
660 * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
661 * Return a 200 OK status for pages blocked with +handle-as-empty-document
662 * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
664 rsp->status = strdup("200 Request blocked by Privoxy");
668 rsp->status = strdup("403 Request blocked by Privoxy");
671 if (rsp->status == NULL)
673 free_http_response(rsp);
674 return cgi_error_memory();
676 if (new_content_type != 0)
678 log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
679 if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
681 free_http_response(rsp);
682 return cgi_error_memory();
689 * Else, generate an HTML "blocked" message:
693 struct map * exports;
695 rsp->status = strdup("403 Request blocked by Privoxy");
696 if (rsp->status == NULL)
698 free_http_response(rsp);
699 return cgi_error_memory();
702 exports = default_exports(csp, NULL);
705 free_http_response(rsp);
706 return cgi_error_memory();
709 #ifdef FEATURE_FORCE_LOAD
710 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
712 * Export the force conditional block killer if
714 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
715 * - Privoxy is configured to enforce blocks, or
716 * - it's a CONNECT request and enforcing wouldn't work anyway.
718 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
719 || (0 == strcmpic(csp->http->gpc, "connect")))
720 #endif /* ndef FEATURE_FORCE_LOAD */
722 err = map_block_killer(exports, "force-support");
725 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
726 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
727 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
728 if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
731 const char *block_reason;
732 if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
734 block_reason = csp->action->string[ACTION_STRING_BLOCK];
738 assert(connect_port_is_forbidden(csp));
739 block_reason = "Forbidden CONNECT port.";
741 err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
746 free_http_response(rsp);
747 return cgi_error_memory();
750 err = template_fill_for_cgi(csp, "blocked", exports, rsp);
753 free_http_response(rsp);
754 return cgi_error_memory();
757 rsp->crunch_reason = BLOCKED;
759 return finish_http_response(csp, rsp);
765 /*********************************************************************
767 * Function : trust_url FIXME: I should be called distrust_url
769 * Description : Calls is_untrusted_url to determine if the URL is trusted
770 * and if not, returns a HTTP 403 response with a reject message.
773 * 1 : csp = Current client state (buffers, headers, etc...)
775 * Returns : NULL => trusted, else http_response.
777 *********************************************************************/
778 struct http_response *trust_url(struct client_state *csp)
780 struct http_response *rsp;
781 struct map * exports;
782 char buf[BUFFER_SIZE];
784 struct pattern_spec **tl;
785 struct pattern_spec *t;
789 * Don't bother to work on trusted URLs
791 if (!is_untrusted_url(csp))
797 * Else, prepare a response:
799 if (NULL == (rsp = alloc_http_response()))
801 return cgi_error_memory();
804 rsp->status = strdup("403 Request blocked by Privoxy");
805 exports = default_exports(csp, NULL);
806 if (exports == NULL || rsp->status == NULL)
808 free_http_response(rsp);
809 return cgi_error_memory();
813 * Export the protocol, host, port, and referrer information
815 err = map(exports, "hostport", 1, csp->http->hostport, 1);
816 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
817 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
819 if (NULL != (p = get_header_value(csp->headers, "Referer:")))
821 if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
825 if (!err) err = map(exports, "referrer", 1, "none set", 1);
831 free_http_response(rsp);
832 return cgi_error_memory();
836 * Export the trust list
839 for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
841 snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
842 string_append(&p, buf);
844 err = map(exports, "trusted-referrers", 1, p, 0);
849 free_http_response(rsp);
850 return cgi_error_memory();
854 * Export the trust info, if available
856 if (csp->config->trust_info->first)
858 struct list_entry *l;
861 for (l = csp->config->trust_info->first; l ; l = l->next)
863 snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
864 string_append(&p, buf);
866 err = map(exports, "trust-info", 1, p, 0);
870 err = map_block_killer(exports, "have-trust-info");
876 free_http_response(rsp);
877 return cgi_error_memory();
881 * Export the force conditional block killer if
883 * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
884 * - Privoxy is configured to enforce blocks, or
885 * - it's a CONNECT request and enforcing wouldn't work anyway.
887 #ifdef FEATURE_FORCE_LOAD
888 if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
889 || (0 == strcmpic(csp->http->gpc, "connect")))
891 err = map_block_killer(exports, "force-support");
895 err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
897 #else /* ifndef FEATURE_FORCE_LOAD */
898 err = map_block_killer(exports, "force-support");
899 #endif /* ndef FEATURE_FORCE_LOAD */
904 free_http_response(rsp);
905 return cgi_error_memory();
911 err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
914 free_http_response(rsp);
915 return cgi_error_memory();
917 rsp->crunch_reason = UNTRUSTED;
919 return finish_http_response(csp, rsp);
921 #endif /* def FEATURE_TRUST */
924 /*********************************************************************
926 * Function : compile_dynamic_pcrs_job_list
928 * Description : Compiles a dynamic pcrs job list (one with variables
929 * resolved at request time)
932 * 1 : csp = Current client state (buffers, headers, etc...)
933 * 2 : b = The filter list to compile
935 * Returns : NULL in case of errors, otherwise the
938 *********************************************************************/
939 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
941 struct list_entry *pattern;
942 pcrs_job *job_list = NULL;
943 pcrs_job *dummy = NULL;
944 pcrs_job *lastjob = NULL;
947 const struct pcrs_variable variables[] =
949 {"url", csp->http->url, 1},
950 {"path", csp->http->path, 1},
951 {"host", csp->http->host, 1},
952 {"origin", csp->ip_addr_str, 1},
956 for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
958 assert(pattern->str != NULL);
960 dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
963 log_error(LOG_LEVEL_ERROR,
964 "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
965 pattern->str, b->name, error, pcrs_strerror(error));
970 if (error == PCRS_WARN_TRUNCATION)
972 log_error(LOG_LEVEL_ERROR,
973 "At least one of the variables in \'%s\' had to "
974 "be truncated before compilation", pattern->str);
976 if (job_list == NULL)
982 lastjob->next = dummy;
992 /*********************************************************************
994 * Function : rewrite_url
996 * Description : Rewrites a URL with a single pcrs command
997 * and returns the result if it differs from the
998 * original and isn't obviously invalid.
1001 * 1 : old_url = URL to rewrite.
1002 * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
1005 * Returns : NULL if the pcrs_command didn't change the url, or
1006 * the result of the modification.
1008 *********************************************************************/
1009 char *rewrite_url(char *old_url, const char *pcrs_command)
1011 char *new_url = NULL;
1015 assert(pcrs_command);
1017 new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1021 log_error(LOG_LEVEL_REDIRECTS,
1022 "pcrs command \"%s\" didn't change \"%s\".",
1023 pcrs_command, old_url);
1028 log_error(LOG_LEVEL_REDIRECTS,
1029 "executing pcrs command \"%s\" to rewrite %s failed: %s",
1030 pcrs_command, old_url, pcrs_strerror(hits));
1033 else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1035 log_error(LOG_LEVEL_ERROR,
1036 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1037 "but the result doesn't look like a valid URL and will be ignored.",
1038 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1043 log_error(LOG_LEVEL_REDIRECTS,
1044 "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1045 pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1053 #ifdef FEATURE_FAST_REDIRECTS
1054 /*********************************************************************
1056 * Function : get_last_url
1058 * Description : Search for the last URL inside a string.
1059 * If the string already is a URL, it will
1060 * be the first URL found.
1063 * 1 : subject = the string to check
1064 * 2 : redirect_mode = +fast-redirect{} mode
1066 * Returns : NULL if no URL was found, or
1067 * the last URL found.
1069 *********************************************************************/
1070 char *get_last_url(char *subject, const char *redirect_mode)
1072 char *new_url = NULL;
1076 assert(redirect_mode);
1078 subject = strdup(subject);
1079 if (subject == NULL)
1081 log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1085 if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1087 char *url_segment = NULL;
1088 char **url_segments;
1089 size_t max_segments;
1092 log_error(LOG_LEVEL_REDIRECTS,
1093 "Checking \"%s\" for encoded redirects.", subject);
1096 * Check each parameter in the URL separately.
1097 * Sectionize the URL at "?" and "&",
1098 * go backwards through the segments, URL-decode them
1099 * and look for a URL in the decoded result.
1100 * Stop the search after the first match.
1102 * XXX: This estimate is guaranteed to be high enough as we
1103 * let ssplit() ignore empty fields, but also a bit wasteful.
1105 max_segments = strlen(subject) / 2;
1106 url_segments = malloc(max_segments * sizeof(char *));
1108 if (NULL == url_segments)
1110 log_error(LOG_LEVEL_ERROR,
1111 "Out of memory while decoding URL: %s", subject);
1116 segments = ssplit(subject, "?&", url_segments, max_segments);
1118 while (segments-- > 0)
1120 char *dtoken = url_decode(url_segments[segments]);
1123 log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1126 url_segment = strstr(dtoken, "http://");
1127 if (NULL == url_segment)
1129 url_segment = strstr(dtoken, "https://");
1131 if (NULL != url_segment)
1133 url_segment = strdup(url_segment);
1135 if (url_segment == NULL)
1137 log_error(LOG_LEVEL_ERROR,
1138 "Out of memory while searching for redirects.");
1146 freez(url_segments);
1148 if (url_segment == NULL)
1152 subject = url_segment;
1156 /* Look for a URL inside this one, without decoding anything. */
1157 log_error(LOG_LEVEL_REDIRECTS,
1158 "Checking \"%s\" for unencoded redirects.", subject);
1162 * Find the last URL encoded in the request
1165 while ((tmp = strstr(tmp, "http://")) != NULL)
1169 tmp = (new_url != NULL) ? new_url : subject;
1170 while ((tmp = strstr(tmp, "https://")) != NULL)
1175 if ((new_url != NULL)
1176 && ( (new_url != subject)
1177 || (0 == strncmpic(subject, "http://", 7))
1178 || (0 == strncmpic(subject, "https://", 8))
1182 * Return new URL if we found a redirect
1183 * or if the subject already was a URL.
1185 * The second case makes sure that we can
1186 * chain get_last_url after another redirection check
1187 * (like rewrite_url) without losing earlier redirects.
1189 new_url = strdup(new_url);
1198 #endif /* def FEATURE_FAST_REDIRECTS */
1201 /*********************************************************************
1203 * Function : redirect_url
1205 * Description : Checks if Privoxy should answer the request with
1206 * a HTTP redirect and generates the redirect if
1210 * 1 : csp = Current client state (buffers, headers, etc...)
1212 * Returns : NULL if the request can pass, HTTP redirect otherwise.
1214 *********************************************************************/
1215 struct http_response *redirect_url(struct client_state *csp)
1217 struct http_response *rsp;
1218 #ifdef FEATURE_FAST_REDIRECTS
1220 * XXX: Do we still need FEATURE_FAST_REDIRECTS
1221 * as compile-time option? The user can easily disable
1222 * it in his action file.
1224 char * redirect_mode;
1225 #endif /* def FEATURE_FAST_REDIRECTS */
1226 char *old_url = NULL;
1227 char *new_url = NULL;
1228 char *redirection_string;
1230 if ((csp->action->flags & ACTION_REDIRECT))
1232 redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1235 * If the redirection string begins with 's',
1236 * assume it's a pcrs command, otherwise treat it as
1237 * properly formatted URL and use it for the redirection
1240 * According to RFC 2616 section 14.30 the URL
1241 * has to be absolute and if the user tries:
1242 * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1243 * she would get undefined results anyway.
1247 if (*redirection_string == 's')
1249 old_url = csp->http->url;
1250 new_url = rewrite_url(old_url, redirection_string);
1254 log_error(LOG_LEVEL_REDIRECTS,
1255 "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1256 redirection_string);
1257 new_url = strdup(redirection_string);
1261 #ifdef FEATURE_FAST_REDIRECTS
1262 if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1264 redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1267 * If it exists, use the previously rewritten URL as input
1268 * otherwise just use the old path.
1270 old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1271 new_url = get_last_url(old_url, redirect_mode);
1276 * Disable redirect checkers, so that they
1277 * will be only run more than once if the user
1278 * also enables them through tags.
1280 * From a performance point of view
1281 * it doesn't matter, but the duplicated
1282 * log messages are annoying.
1284 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1285 #endif /* def FEATURE_FAST_REDIRECTS */
1286 csp->action->flags &= ~ACTION_REDIRECT;
1288 /* Did any redirect action trigger? */
1291 if (url_requires_percent_encoding(new_url))
1294 log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1295 strlen(new_url), new_url);
1296 encoded_url = percent_encode_url(new_url);
1298 if (encoded_url == NULL)
1300 return cgi_error_memory();
1302 new_url = encoded_url;
1303 assert(FALSE == url_requires_percent_encoding(new_url));
1306 if (0 == strcmpic(new_url, csp->http->url))
1308 log_error(LOG_LEVEL_ERROR,
1309 "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1310 csp->http->url, new_url);
1315 log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1317 if (NULL == (rsp = alloc_http_response()))
1320 return cgi_error_memory();
1323 if (enlist_unique_header(rsp->headers, "Location", new_url)
1324 || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))))
1327 free_http_response(rsp);
1328 return cgi_error_memory();
1330 rsp->crunch_reason = REDIRECTED;
1333 return finish_http_response(csp, rsp);
1337 /* Only reached if no redirect is required */
1343 #ifdef FEATURE_IMAGE_BLOCKING
1344 /*********************************************************************
1346 * Function : is_imageurl
1348 * Description : Given a URL, decide whether it is an image or not,
1349 * using either the info from a previous +image action
1350 * or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1351 * is MSIE and not on a Mac, tell from the browser's accept
1355 * 1 : csp = Current client state (buffers, headers, etc...)
1357 * Returns : True (nonzero) if URL is an image, false (0)
1360 *********************************************************************/
1361 int is_imageurl(const struct client_state *csp)
1363 #ifdef FEATURE_IMAGE_DETECT_MSIE
1366 tmp = get_header_value(csp->headers, "User-Agent:");
1367 if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1369 tmp = get_header_value(csp->headers, "Accept:");
1370 if (tmp && strstr(tmp, "image/gif"))
1372 /* Client will accept HTML. If this seems counterintuitive,
1382 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1384 return ((csp->action->flags & ACTION_IMAGE) != 0);
1387 #endif /* def FEATURE_IMAGE_BLOCKING */
1390 #ifdef FEATURE_TRUST
1391 /*********************************************************************
1393 * Function : is_untrusted_url
1395 * Description : Should we "distrust" this URL (and block it)?
1397 * Yes if it matches a line in the trustfile, or if the
1398 * referrer matches a line starting with "+" in the
1403 * 1 : csp = Current client state (buffers, headers, etc...)
1405 * Returns : 0 => trusted, 1 => untrusted
1407 *********************************************************************/
1408 int is_untrusted_url(const struct client_state *csp)
1410 struct file_list *fl;
1411 struct block_spec *b;
1412 struct pattern_spec **trusted_url;
1413 struct http_request rhttp[1];
1414 const char * referer;
1418 * If we don't have a trustlist, we trust everybody
1420 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
1425 memset(rhttp, '\0', sizeof(*rhttp));
1428 * Do we trust the request URL itself?
1430 for (b = b->next; b ; b = b->next)
1432 if (url_match(b->url, csp->http))
1438 if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1440 /* no referrer was supplied */
1446 * If not, do we maybe trust its referrer?
1448 err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1454 for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1456 if (url_match(*trusted_url, rhttp))
1458 /* if the URL's referrer is from a trusted referrer, then
1459 * add the target spec to the trustfile as an unblocked
1460 * domain and return 0 (which means it's OK).
1465 if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1469 char * new_entry = strdup("~");
1471 string_append(&new_entry, csp->http->hostport);
1473 path = csp->http->path;
1474 if ( (path[0] == '/')
1476 && ((path_end = strchr(path + 2, '/')) != NULL))
1478 /* since this path points into a user's home space
1479 * be sure to include this spec in the trustfile.
1481 long path_len = path_end - path; /* save offset */
1482 path = strdup(path); /* Copy string */
1485 path_end = path + path_len; /* regenerate ptr to new buffer */
1486 *(path_end + 1) = '\0'; /* Truncate path after '/' */
1488 string_join(&new_entry, path);
1492 * Give a reason for generating this entry.
1494 string_append(&new_entry, " # Trusted referrer was: ");
1495 string_append(&new_entry, referer);
1497 if (new_entry != NULL)
1499 if (-1 == fprintf(fp, "%s\n", new_entry))
1501 log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1502 new_entry, csp->config->trustfile);
1508 /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1509 log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1516 log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1517 csp->http->hostport, csp->config->trustfile);
1525 #endif /* def FEATURE_TRUST */
1528 /*********************************************************************
1530 * Function : get_filter
1532 * Description : Get a filter with a given name and type.
1533 * Note that taggers are filters, too.
1536 * 1 : csp = Current client state (buffers, headers, etc...)
1537 * 2 : requested_name = Name of the content filter to get
1538 * 3 : requested_type = Type of the filter to tagger to lookup
1540 * Returns : A pointer to the requested filter
1541 * or NULL if the filter wasn't found
1543 *********************************************************************/
1544 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1545 const char *requested_name,
1546 enum filter_type requested_type)
1549 struct re_filterfile_spec *b;
1550 struct file_list *fl;
1552 for (i = 0; i < MAX_AF_FILES; i++)
1555 if ((NULL == fl) || (NULL == fl->f))
1558 * Either there are no filter files left or this
1559 * filter file just contains no valid filters.
1561 * Continue to be sure we don't miss valid filter
1562 * files that are chained after empty or invalid ones.
1567 for (b = fl->f; b != NULL; b = b->next)
1569 if (b->type != requested_type)
1571 /* The callers isn't interested in this filter type. */
1574 if (strcmp(b->name, requested_name) == 0)
1576 /* The requested filter has been found. Abort search. */
1582 /* No filter with the given name and type exists. */
1588 /*********************************************************************
1590 * Function : pcrs_filter_response
1592 * Description : Execute all text substitutions from all applying
1593 * +filter actions on the text buffer that's been
1594 * accumulated in csp->iob->buf.
1597 * 1 : csp = Current client state (buffers, headers, etc...)
1599 * Returns : a pointer to the (newly allocated) modified buffer.
1600 * or NULL if there were no hits or something went wrong
1602 *********************************************************************/
1603 static char *pcrs_filter_response(struct client_state *csp)
1606 size_t size, prev_size;
1612 struct re_filterfile_spec *b;
1613 struct list_entry *filtername;
1618 if (csp->iob->cur >= csp->iob->eod)
1623 if (filters_available(csp) == FALSE)
1625 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1626 "content filtering enabled, but no content filters available.");
1630 size = (size_t)(csp->iob->eod - csp->iob->cur);
1631 old = csp->iob->cur;
1634 * For all applying +filter actions, look if a filter by that
1635 * name exists and if yes, execute it's pcrs_joblist on the
1638 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1639 filtername != NULL; filtername = filtername->next)
1641 b = get_filter(csp, filtername->str, FT_CONTENT_FILTER);
1647 int current_hits = 0; /* Number of hits caused by this filter */
1648 int job_number = 0; /* Which job we're currently executing */
1649 int job_hits = 0; /* How many hits the current job caused */
1650 pcrs_job *joblist = b->joblist;
1652 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1654 if (NULL == joblist)
1656 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1661 /* Apply all jobs from the joblist */
1662 for (job = joblist; NULL != job; job = job->next)
1665 job_hits = pcrs_execute(job, old, size, &new, &size);
1670 * That went well. Continue filtering
1671 * and use the result of this job as
1672 * input for the next one.
1674 current_hits += job_hits;
1675 if (old != csp->iob->cur)
1684 * This job caused an unexpected error. Inform the user
1685 * and skip the rest of the jobs in this filter. We could
1686 * continue with the next job, but usually the jobs
1687 * depend on each other or are similar enough to
1688 * fail for the same reason.
1690 * At the moment our pcrs expects the error codes of pcre 3.4,
1691 * but newer pcre versions can return additional error codes.
1692 * As a result pcrs_strerror()'s error message might be
1693 * "Unknown error ...", therefore we print the numerical value
1696 * XXX: Is this important enough for LOG_LEVEL_ERROR or
1697 * should we use LOG_LEVEL_RE_FILTER instead?
1699 log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1700 b->name, job_number, pcrs_strerror(job_hits), job_hits);
1705 if (b->dynamic) pcrs_free_joblist(joblist);
1707 log_error(LOG_LEVEL_RE_FILTER,
1708 "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1709 csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1711 hits += current_hits;
1717 * If there were no hits, destroy our copy and let
1718 * chat() use the original in csp->iob
1726 csp->flags |= CSP_FLAG_MODIFIED;
1727 csp->content_length = size;
1728 clear_iob(csp->iob);
1735 /*********************************************************************
1737 * Function : gif_deanimate_response
1739 * Description : Deanimate the GIF image that has been accumulated in
1740 * csp->iob->buf, set csp->content_length to the modified
1741 * size and raise the CSP_FLAG_MODIFIED flag.
1744 * 1 : csp = Current client state (buffers, headers, etc...)
1746 * Returns : a pointer to the (newly allocated) modified buffer.
1747 * or NULL in case something went wrong.
1749 *********************************************************************/
1750 static char *gif_deanimate_response(struct client_state *csp)
1752 struct binbuffer *in, *out;
1756 size = (size_t)(csp->iob->eod - csp->iob->cur);
1758 if ( (NULL == (in = (struct binbuffer *)zalloc(sizeof *in )))
1759 || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1761 log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1765 in->buffer = csp->iob->cur;
1768 if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1770 log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1777 if ((int)size == out->offset)
1779 log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1783 log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1785 csp->content_length = out->offset;
1786 csp->flags |= CSP_FLAG_MODIFIED;
1796 /*********************************************************************
1798 * Function : get_filter_function
1800 * Description : Decides which content filter function has
1801 * to be applied (if any).
1804 * 1 : csp = Current client state (buffers, headers, etc...)
1806 * Returns : The content filter function to run, or
1807 * NULL if no content filter is active
1809 *********************************************************************/
1810 static filter_function_ptr get_filter_function(const struct client_state *csp)
1812 filter_function_ptr filter_function = NULL;
1815 * Choose the applying filter function based on
1816 * the content type and action settings.
1818 if ((csp->content_type & CT_TEXT) &&
1819 (csp->rlist != NULL) &&
1820 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1822 filter_function = pcrs_filter_response;
1824 else if ((csp->content_type & CT_GIF) &&
1825 (csp->action->flags & ACTION_DEANIMATE))
1827 filter_function = gif_deanimate_response;
1830 return filter_function;
1834 /*********************************************************************
1836 * Function : remove_chunked_transfer_coding
1838 * Description : In-situ remove the "chunked" transfer coding as defined
1839 * in rfc2616 from a buffer.
1842 * 1 : buffer = Pointer to the text buffer
1843 * 2 : size = In: Number of bytes to be processed,
1844 * Out: Number of bytes after de-chunking.
1845 * (undefined in case of errors)
1847 * Returns : JB_ERR_OK for success,
1848 * JB_ERR_PARSE otherwise
1850 *********************************************************************/
1851 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1854 unsigned int chunksize = 0;
1855 char *from_p, *to_p;
1858 from_p = to_p = buffer;
1860 if (sscanf(buffer, "%x", &chunksize) != 1)
1862 log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1863 return JB_ERR_PARSE;
1866 while (chunksize > 0U)
1868 if (NULL == (from_p = strstr(from_p, "\r\n")))
1870 log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1871 return JB_ERR_PARSE;
1874 if (chunksize >= *size - newsize)
1876 log_error(LOG_LEVEL_ERROR,
1877 "Chunk size %u exceeds buffered data left. "
1878 "Already digested %u of %u buffered bytes.",
1879 chunksize, (unsigned int)newsize, (unsigned int)*size);
1880 return JB_ERR_PARSE;
1882 newsize += chunksize;
1885 memmove(to_p, from_p, (size_t) chunksize);
1886 to_p = buffer + newsize;
1887 from_p += chunksize + 2;
1889 if (sscanf(from_p, "%x", &chunksize) != 1)
1891 log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1896 /* XXX: Should get its own loglevel. */
1897 log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1906 /*********************************************************************
1908 * Function : prepare_for_filtering
1910 * Description : If necessary, de-chunks and decompresses
1911 * the content so it can get filterd.
1914 * 1 : csp = Current client state (buffers, headers, etc...)
1916 * Returns : JB_ERR_OK for success,
1917 * JB_ERR_PARSE otherwise
1919 *********************************************************************/
1920 static jb_err prepare_for_filtering(struct client_state *csp)
1922 jb_err err = JB_ERR_OK;
1925 * If the body has a "chunked" transfer-encoding,
1926 * get rid of it, adjusting size and iob->eod
1928 if (csp->flags & CSP_FLAG_CHUNKED)
1930 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1932 log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1933 err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1934 if (JB_ERR_OK == err)
1936 csp->iob->eod = csp->iob->cur + size;
1937 csp->flags |= CSP_FLAG_MODIFIED;
1941 return JB_ERR_PARSE;
1947 * If the body has a supported transfer-encoding,
1948 * decompress it, adjusting size and iob->eod.
1950 if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1952 if (0 == csp->iob->eod - csp->iob->cur)
1954 /* Nothing left after de-chunking. */
1958 err = decompress_iob(csp);
1960 if (JB_ERR_OK == err)
1962 csp->flags |= CSP_FLAG_MODIFIED;
1963 csp->content_type &= ~CT_TABOO;
1968 * Unset CT_GZIP and CT_DEFLATE to remember not
1969 * to modify the Content-Encoding header later.
1971 csp->content_type &= ~CT_GZIP;
1972 csp->content_type &= ~CT_DEFLATE;
1981 /*********************************************************************
1983 * Function : execute_content_filters
1985 * Description : Executes a given content filter.
1988 * 1 : csp = Current client state (buffers, headers, etc...)
1990 * Returns : Pointer to the modified buffer, or
1991 * NULL if filtering failed or wasn't necessary.
1993 *********************************************************************/
1994 char *execute_content_filters(struct client_state *csp)
1996 filter_function_ptr content_filter;
1998 assert(content_filters_enabled(csp->action));
2000 if (0 == csp->iob->eod - csp->iob->cur)
2003 * No content (probably status code 301, 302 ...),
2004 * no filtering necessary.
2009 if (JB_ERR_OK != prepare_for_filtering(csp))
2012 * failed to de-chunk or decompress.
2017 if (0 == csp->iob->eod - csp->iob->cur)
2020 * Clown alarm: chunked and/or compressed nothing delivered.
2025 content_filter = get_filter_function(csp);
2027 return ((*content_filter)(csp));
2031 /*********************************************************************
2033 * Function : get_url_actions
2035 * Description : Gets the actions for this URL.
2038 * 1 : csp = Current client state (buffers, headers, etc...)
2039 * 2 : http = http_request request for blocked URLs
2043 *********************************************************************/
2044 void get_url_actions(struct client_state *csp, struct http_request *http)
2046 struct file_list *fl;
2047 struct url_actions *b;
2050 init_current_action(csp->action);
2052 for (i = 0; i < MAX_AF_FILES; i++)
2054 if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2059 apply_url_actions(csp->action, http, b);
2066 /*********************************************************************
2068 * Function : apply_url_actions
2070 * Description : Applies a list of URL actions.
2073 * 1 : action = Destination.
2074 * 2 : http = Current URL
2075 * 3 : b = list of URL actions to apply
2079 *********************************************************************/
2080 void apply_url_actions(struct current_action_spec *action,
2081 struct http_request *http,
2082 struct url_actions *b)
2086 /* Should never happen */
2090 for (b = b->next; NULL != b; b = b->next)
2092 if (url_match(b->url, http))
2094 merge_current_action(action, b->action);
2100 /*********************************************************************
2102 * Function : get_forward_override_settings
2104 * Description : Returns forward settings as specified with the
2105 * forward-override{} action. forward-override accepts
2106 * forward lines similar to the one used in the
2107 * configuration file, but without the URL pattern.
2113 * in the configuration file can be replaced with
2114 * the action section:
2116 * {+forward-override{forward .}}
2120 * 1 : csp = Current client state (buffers, headers, etc...)
2122 * Returns : Pointer to forwarding structure in case of success.
2123 * Invalid syntax is fatal.
2125 *********************************************************************/
2126 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2128 const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2129 char forward_settings[BUFFER_SIZE];
2130 char *http_parent = NULL;
2131 /* variable names were chosen for consistency reasons. */
2132 struct forward_spec *fwd = NULL;
2136 assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2137 /* Should be enforced by load_one_actions_file() */
2138 assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2140 /* Create a copy ssplit can modify */
2141 strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2143 if (NULL != csp->fwd)
2146 * XXX: Currently necessary to prevent memory
2147 * leaks when the show-url-info cgi page is visited.
2149 unload_forward_spec(csp->fwd);
2153 * allocate a new forward node, valid only for
2154 * the lifetime of this request. Save its location
2155 * in csp as well, so sweep() can free it later on.
2157 fwd = csp->fwd = zalloc(sizeof(*fwd));
2160 log_error(LOG_LEVEL_FATAL,
2161 "can't allocate memory for forward-override{%s}", forward_override_line);
2162 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2166 vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2167 if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2169 fwd->type = SOCKS_NONE;
2171 /* Parse the parent HTTP proxy host:port */
2172 http_parent = vec[1];
2175 else if (vec_count == 3)
2177 char *socks_proxy = NULL;
2179 if (!strcasecmp(vec[0], "forward-socks4"))
2181 fwd->type = SOCKS_4;
2182 socks_proxy = vec[1];
2184 else if (!strcasecmp(vec[0], "forward-socks4a"))
2186 fwd->type = SOCKS_4A;
2187 socks_proxy = vec[1];
2189 else if (!strcasecmp(vec[0], "forward-socks5"))
2191 fwd->type = SOCKS_5;
2192 socks_proxy = vec[1];
2194 else if (!strcasecmp(vec[0], "forward-socks5t"))
2196 fwd->type = SOCKS_5T;
2197 socks_proxy = vec[1];
2200 if (NULL != socks_proxy)
2202 /* Parse the SOCKS proxy host[:port] */
2203 fwd->gateway_port = 1080;
2204 parse_forwarder_address(socks_proxy,
2205 &fwd->gateway_host, &fwd->gateway_port);
2207 http_parent = vec[2];
2211 if (NULL == http_parent)
2213 log_error(LOG_LEVEL_FATAL,
2214 "Invalid forward-override syntax in: %s", forward_override_line);
2215 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2218 /* Parse http forwarding settings */
2219 if (strcmp(http_parent, ".") != 0)
2221 fwd->forward_port = 8000;
2222 parse_forwarder_address(http_parent,
2223 &fwd->forward_host, &fwd->forward_port);
2226 assert (NULL != fwd);
2228 log_error(LOG_LEVEL_CONNECT,
2229 "Overriding forwarding settings based on \'%s\'", forward_override_line);
2235 /*********************************************************************
2237 * Function : forward_url
2239 * Description : Should we forward this to another proxy?
2242 * 1 : csp = Current client state (buffers, headers, etc...)
2243 * 2 : http = http_request request for current URL
2245 * Returns : Pointer to forwarding information.
2247 *********************************************************************/
2248 const struct forward_spec *forward_url(struct client_state *csp,
2249 const struct http_request *http)
2251 static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
2252 struct forward_spec *fwd = csp->config->forward;
2254 if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2256 return get_forward_override_settings(csp);
2266 if (url_match(fwd->url, http))
2277 /*********************************************************************
2279 * Function : direct_response
2281 * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
2282 * request and if so, return a HTTP 501 to the client.
2284 * FIXME: I have a stupid name and I should handle the
2285 * requests properly. Still, what we do here is rfc-
2286 * compliant, whereas ignoring or forwarding are not.
2289 * 1 : csp = Current client state (buffers, headers, etc...)
2291 * Returns : http_response if , NULL if nonmatch or handler fail
2293 *********************************************************************/
2294 struct http_response *direct_response(struct client_state *csp)
2296 struct http_response *rsp;
2297 struct list_entry *p;
2299 if ((0 == strcmpic(csp->http->gpc, "trace"))
2300 || (0 == strcmpic(csp->http->gpc, "options")))
2302 for (p = csp->headers->first; (p != NULL) ; p = p->next)
2304 if (!strncmpic(p->str, "Max-Forwards:", 13))
2306 unsigned int max_forwards;
2309 * If it's a Max-Forwards value of zero,
2310 * we have to intercept the request.
2312 if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2315 * FIXME: We could handle at least TRACE here,
2316 * but that would require a verbatim copy of
2317 * the request which we don't have anymore
2319 log_error(LOG_LEVEL_HEADER,
2320 "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2323 /* Get mem for response or fail*/
2324 if (NULL == (rsp = alloc_http_response()))
2326 return cgi_error_memory();
2329 if (NULL == (rsp->status = strdup("501 Not Implemented")))
2331 free_http_response(rsp);
2332 return cgi_error_memory();
2336 rsp->crunch_reason = UNSUPPORTED;
2338 return(finish_http_response(csp, rsp));
2347 /*********************************************************************
2349 * Function : content_requires_filtering
2351 * Description : Checks whether there are any content filters
2352 * enabled for the current request and if they
2353 * can actually be applied..
2356 * 1 : csp = Current client state (buffers, headers, etc...)
2358 * Returns : TRUE for yes, FALSE otherwise
2360 *********************************************************************/
2361 int content_requires_filtering(struct client_state *csp)
2363 if ((csp->content_type & CT_TABOO)
2364 && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2370 * Are we enabling text mode by force?
2372 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2375 * Do we really have to?
2377 if (csp->content_type & CT_TEXT)
2379 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2383 csp->content_type |= CT_TEXT;
2384 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2388 if (!(csp->content_type & CT_DECLARED))
2391 * The server didn't bother to declare a MIME-Type.
2392 * Assume it's text that can be filtered.
2394 * This also regulary happens with 304 responses,
2395 * therefore logging anything here would cause
2398 csp->content_type |= CT_TEXT;
2402 * Choose the applying filter function based on
2403 * the content type and action settings.
2405 if ((csp->content_type & CT_TEXT) &&
2406 (csp->rlist != NULL) &&
2407 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2411 else if ((csp->content_type & CT_GIF) &&
2412 (csp->action->flags & ACTION_DEANIMATE))
2422 /*********************************************************************
2424 * Function : content_filters_enabled
2426 * Description : Checks whether there are any content filters
2427 * enabled for the current request.
2430 * 1 : action = Action spec to check.
2432 * Returns : TRUE for yes, FALSE otherwise
2434 *********************************************************************/
2435 int content_filters_enabled(const struct current_action_spec *action)
2437 return ((action->flags & ACTION_DEANIMATE) ||
2438 !list_is_empty(action->multi[ACTION_MULTI_FILTER]));
2442 /*********************************************************************
2444 * Function : filters_available
2446 * Description : Checks whether there are any filters available.
2449 * 1 : csp = Current client state (buffers, headers, etc...)
2451 * Returns : TRUE for yes, FALSE otherwise.
2453 *********************************************************************/
2454 int filters_available(const struct client_state *csp)
2457 for (i = 0; i < MAX_AF_FILES; i++)
2459 const struct file_list *fl = csp->rlist[i];
2460 if ((NULL != fl) && (NULL != fl->f))