Bump copyright
[privoxy.git] / filters.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/filters.c,v $
4  *
5  * Purpose     :  Declares functions to parse/crunch headers and pages.
6  *
7  * Copyright   :  Written by and Copyright (C) 2001-2024 the
8  *                Privoxy team. https://www.privoxy.org/
9  *
10  *                Based on the Internet Junkbuster originally written
11  *                by and Copyright (C) 1997 Anonymous Coders and
12  *                Junkbusters Corporation.  http://www.junkbusters.com
13  *
14  *                This program is free software; you can redistribute it
15  *                and/or modify it under the terms of the GNU General
16  *                Public License as published by the Free Software
17  *                Foundation; either version 2 of the License, or (at
18  *                your option) any later version.
19  *
20  *                This program is distributed in the hope that it will
21  *                be useful, but WITHOUT ANY WARRANTY; without even the
22  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
23  *                PARTICULAR PURPOSE.  See the GNU General Public
24  *                License for more details.
25  *
26  *                The GNU General Public License should be included with
27  *                this file.  If not, you can view it at
28  *                http://www.gnu.org/copyleft/gpl.html
29  *                or write to the Free Software Foundation, Inc., 59
30  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
31  *
32  *********************************************************************/
33
34
35 #include "config.h"
36
37 #include <stdio.h>
38 #include <sys/types.h>
39 #include <stdlib.h>
40 #include <ctype.h>
41 #include <string.h>
42 #include <assert.h>
43
44 #ifndef _WIN32
45 #include <unistd.h>
46 #include <netinet/in.h>
47 #else
48 #include <winsock2.h>
49 #endif /* ndef _WIN32 */
50
51 #include "project.h"
52 #include "filters.h"
53 #include "encode.h"
54 #include "parsers.h"
55 #include "ssplit.h"
56 #include "errlog.h"
57 #include "jbsockets.h"
58 #include "miscutil.h"
59 #include "actions.h"
60 #include "cgi.h"
61 #include "jcc.h"
62 #include "list.h"
63 #include "deanimate.h"
64 #include "urlmatch.h"
65 #include "loaders.h"
66 #ifdef FEATURE_CLIENT_TAGS
67 #include "client-tags.h"
68 #endif
69 #ifdef FEATURE_HTTPS_INSPECTION
70 #include "ssl.h"
71 #endif
72
73 #ifdef _WIN32
74 #include "win32.h"
75 #endif
76
77 typedef char *(*filter_function_ptr)(struct client_state *csp);
78 static filter_function_ptr get_filter_function(const struct client_state *csp);
79 static jb_err prepare_for_filtering(struct client_state *csp);
80 static void apply_url_actions(struct current_action_spec *action,
81                               struct http_request *http,
82 #ifdef FEATURE_CLIENT_TAGS
83                               const struct list *client_tags,
84 #endif
85                               struct url_actions *b);
86
87 #ifdef FEATURE_EXTENDED_STATISTICS
88 static void increment_block_reason_counter(const char *block_reason);
89 #endif
90
91 #ifdef FEATURE_ACL
92 #ifdef HAVE_RFC2553
93 /*********************************************************************
94  *
95  * Function    :  sockaddr_storage_to_ip
96  *
97  * Description :  Access internal structure of sockaddr_storage
98  *
99  * Parameters  :
100  *          1  :  addr = socket address
101  *          2  :  ip   = IP address as array of octets in network order
102  *                       (it points into addr)
103  *          3  :  len  = length of IP address in octets
104  *          4  :  port = port number in network order;
105  *
106  * Returns     :  void
107  *
108  *********************************************************************/
109 static void sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
110                                    uint8_t **ip, unsigned int *len,
111                                    in_port_t **port)
112 {
113    assert(NULL != addr);
114    assert(addr->ss_family == AF_INET || addr->ss_family == AF_INET6);
115
116    switch (addr->ss_family)
117    {
118       case AF_INET:
119          if (NULL != len)
120          {
121             *len = 4;
122          }
123          if (NULL != ip)
124          {
125             *ip = (uint8_t *)
126                &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
127          }
128          if (NULL != port)
129          {
130             *port = &((struct sockaddr_in *)addr)->sin_port;
131          }
132          break;
133
134       case AF_INET6:
135          if (NULL != len)
136          {
137             *len = 16;
138          }
139          if (NULL != ip)
140          {
141             *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
142          }
143          if (NULL != port)
144          {
145             *port = &((struct sockaddr_in6 *)addr)->sin6_port;
146          }
147          break;
148
149    }
150 }
151
152
153 /*********************************************************************
154  *
155  * Function    :  match_sockaddr
156  *
157  * Description :  Check whether address matches network (IP address and port)
158  *
159  * Parameters  :
160  *          1  :  network = socket address of subnework
161  *          2  :  netmask = network mask as socket address
162  *          3  :  address = checked socket address against given network
163  *
164  * Returns     :  0 = doesn't match; 1 = does match
165  *
166  *********************************************************************/
167 static int match_sockaddr(const struct sockaddr_storage *network,
168                           const struct sockaddr_storage *netmask,
169                           const struct sockaddr_storage *address)
170 {
171    uint8_t *network_addr, *netmask_addr, *address_addr;
172    unsigned int addr_len;
173    in_port_t *network_port, *netmask_port, *address_port;
174    int i;
175
176    network_addr = NULL;
177    netmask_addr = NULL;
178    address_addr = NULL;
179    addr_len = 0;
180    network_port = NULL;
181    netmask_port = NULL;
182    address_port = NULL;
183
184    if (network->ss_family != netmask->ss_family)
185    {
186       /* This should never happen */
187       assert(network->ss_family == netmask->ss_family);
188       log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
189    }
190
191    sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
192    sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
193    sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
194
195    /* Check for family */
196    if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
197       && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
198    {
199       /* Map AF_INET6 V4MAPPED address into AF_INET */
200       address_addr += 12;
201       addr_len = 4;
202    }
203    else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
204       && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
205    {
206       /* Map AF_INET6 V4MAPPED network into AF_INET */
207       network_addr += 12;
208       netmask_addr += 12;
209       addr_len = 4;
210    }
211
212    /* XXX: Port check is signaled in netmask */
213    if (*netmask_port && *network_port != *address_port)
214    {
215       return 0;
216    }
217
218    /* TODO: Optimize by checking by words instead of octets */
219    for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
220    {
221       if ((network_addr[i] & netmask_addr[i]) !=
222           (address_addr[i] & netmask_addr[i]))
223       {
224          return 0;
225       }
226    }
227
228    return 1;
229 }
230 #endif /* def HAVE_RFC2553 */
231
232
233 /*********************************************************************
234  *
235  * Function    :  block_acl
236  *
237  * Description :  Block this request?
238  *                Decide yes or no based on ACL file.
239  *
240  * Parameters  :
241  *          1  :  dst = The proxy or gateway address this is going to.
242  *                      Or NULL to check all possible targets.
243  *          2  :  csp = Current client state (buffers, headers, etc...)
244  *                      Also includes the client IP address.
245  *
246  * Returns     : 0 = FALSE (don't block) and 1 = TRUE (do block)
247  *
248  *********************************************************************/
249 int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
250 {
251    struct access_control_list *acl = csp->config->acl;
252
253    /* if not using an access control list, then permit the connection */
254    if (acl == NULL)
255    {
256       return(0);
257    }
258
259    /* search the list */
260    while (acl != NULL)
261    {
262       if (
263 #ifdef HAVE_RFC2553
264             match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
265 #else
266             (csp->ip_addr_long & acl->src->mask) == acl->src->addr
267 #endif
268             )
269       {
270          if (dst == NULL)
271          {
272             /* Just want to check if they have any access */
273             if (acl->action == ACL_PERMIT)
274             {
275                return(0);
276             }
277             else
278             {
279                return(1);
280             }
281          }
282          else if (
283 #ifdef HAVE_RFC2553
284                /*
285                 * XXX: An undefined acl->dst is full of zeros and should be
286                 * considered a wildcard address. sockaddr_storage_to_ip()
287                 * fails on such destinations because of unknown sa_familly
288                 * (glibc only?). However this test is not portable.
289                 *
290                 * So, we signal the acl->dst is wildcard in wildcard_dst.
291                 */
292                acl->wildcard_dst ||
293                   match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
294 #else
295                ((dst->addr & acl->dst->mask) == acl->dst->addr)
296            && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
297 #endif
298            )
299          {
300             if (acl->action == ACL_PERMIT)
301             {
302                return(0);
303             }
304             else
305             {
306                return(1);
307             }
308          }
309       }
310       acl = acl->next;
311    }
312
313    return(1);
314
315 }
316
317
318 /*********************************************************************
319  *
320  * Function    :  acl_addr
321  *
322  * Description :  Called from `load_config' to parse an ACL address.
323  *
324  * Parameters  :
325  *          1  :  aspec = String specifying ACL address.
326  *          2  :  aca = struct access_control_addr to fill in.
327  *
328  * Returns     :  0 => Ok, everything else is an error.
329  *
330  *********************************************************************/
331 int acl_addr(const char *aspec, struct access_control_addr *aca)
332 {
333    int i, masklength;
334 #ifdef HAVE_RFC2553
335    struct addrinfo hints, *result;
336    uint8_t *mask_data;
337    in_port_t *mask_port;
338    unsigned int addr_len;
339 #else
340    long port;
341 #endif /* def HAVE_RFC2553 */
342    char *p;
343    char *acl_spec = NULL;
344
345    mask_data = NULL;
346    mask_port = NULL;
347    addr_len = 0;
348
349 #ifdef HAVE_RFC2553
350    /* XXX: Depend on ai_family */
351    masklength = 128;
352 #else
353    masklength = 32;
354    port       =  0;
355 #endif
356
357    /*
358     * Use a temporary acl spec copy so we can log
359     * the unmodified original in case of parse errors.
360     */
361    acl_spec = strdup_or_die(aspec);
362
363    if ((p = strchr(acl_spec, '/')) != NULL)
364    {
365       *p++ = '\0';
366       if (privoxy_isdigit(*p) == 0)
367       {
368          freez(acl_spec);
369          return(-1);
370       }
371       masklength = atoi(p);
372    }
373
374    if ((masklength < 0) ||
375 #ifdef HAVE_RFC2553
376          (masklength > 128)
377 #else
378          (masklength > 32)
379 #endif
380          )
381    {
382       freez(acl_spec);
383       return(-1);
384    }
385
386    if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
387    {
388       *p = '\0';
389       memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
390
391       if (*++p != ':')
392       {
393          p = NULL;
394       }
395    }
396    else
397    {
398       p = strchr(acl_spec, ':');
399    }
400    if (p != NULL)
401    {
402       assert(*p == ':');
403       *p = '\0';
404       p++;
405    }
406
407 #ifdef HAVE_RFC2553
408    memset(&hints, 0, sizeof(struct addrinfo));
409    hints.ai_family = AF_UNSPEC;
410    hints.ai_socktype = SOCK_STREAM;
411
412    i = getaddrinfo(acl_spec, p, &hints, &result);
413
414    if (i != 0)
415    {
416       log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
417          acl_spec, p, gai_strerror(i));
418       freez(acl_spec);
419       return(-1);
420    }
421    freez(acl_spec);
422
423    /* TODO: Allow multihomed hostnames */
424    memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
425    freeaddrinfo(result);
426 #else
427    if (p != NULL)
428    {
429       char *endptr;
430
431       port = strtol(p, &endptr, 10);
432
433       if (port <= 0 || port > 65535 || *endptr != '\0')
434       {
435          freez(acl_spec);
436          return(-1);
437       }
438    }
439
440    aca->port = (unsigned long)port;
441
442    aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
443    freez(acl_spec);
444
445    if (aca->addr == INADDR_NONE)
446    {
447       /* XXX: This will be logged as parse error. */
448       return(-1);
449    }
450 #endif /* def HAVE_RFC2553 */
451
452    /* build the netmask */
453 #ifdef HAVE_RFC2553
454    /* Clip masklength according to current family. */
455    if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
456    {
457       masklength = 32;
458    }
459
460    aca->mask.ss_family = aca->addr.ss_family;
461    sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port);
462
463    if (p)
464    {
465       /* ACL contains a port number, check ports in the future. */
466       *mask_port = 1;
467    }
468
469    /*
470     * XXX: This could be optimized to operate on whole words instead
471     * of octets (128-bit CPU could do it in one iteration).
472     */
473    /*
474     * Octets after prefix can be omitted because of
475     * previous initialization to zeros.
476     */
477    for (i = 0; (i < addr_len) && masklength; i++)
478    {
479       if (masklength >= 8)
480       {
481          mask_data[i] = 0xFF;
482          masklength -= 8;
483       }
484       else
485       {
486          /*
487           * XXX: This assumes MSB of octet is on the left side.
488           * This should be true for all architectures or solved
489           * by the link layer.
490           */
491          mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
492          masklength = 0;
493       }
494    }
495
496 #else
497    aca->mask = 0;
498    for (i=1; i <= masklength ; i++)
499    {
500       aca->mask |= (1U << (32 - i));
501    }
502
503    /* now mask off the host portion of the ip address
504     * (i.e. save on the network portion of the address).
505     */
506    aca->addr = aca->addr & aca->mask;
507 #endif /* def HAVE_RFC2553 */
508
509    return(0);
510
511 }
512 #endif /* def FEATURE_ACL */
513
514
515 /*********************************************************************
516  *
517  * Function    :  connect_port_is_forbidden
518  *
519  * Description :  Check to see if CONNECT requests to the destination
520  *                port of this request are forbidden. The check is
521  *                independent of the actual request method.
522  *
523  * Parameters  :
524  *          1  :  csp = Current client state (buffers, headers, etc...)
525  *
526  * Returns     :  True if yes, false otherwise.
527  *
528  *********************************************************************/
529 int connect_port_is_forbidden(const struct client_state *csp)
530 {
531    return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
532      !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
533         csp->http->port));
534 }
535
536
537 /*********************************************************************
538  *
539  * Function    :  block_url
540  *
541  * Description :  Called from `chat'.  Check to see if we need to block this.
542  *
543  * Parameters  :
544  *          1  :  csp = Current client state (buffers, headers, etc...)
545  *
546  * Returns     :  NULL => unblocked, else HTTP block response
547  *
548  *********************************************************************/
549 struct http_response *block_url(struct client_state *csp)
550 {
551    struct http_response *rsp;
552    const char *new_content_type = NULL;
553
554    /*
555     * If it's not blocked, don't block it ;-)
556     */
557    if ((csp->action->flags & ACTION_BLOCK) == 0)
558    {
559       return NULL;
560    }
561    if (csp->action->flags & ACTION_REDIRECT)
562    {
563       log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
564    }
565    /*
566     * Else, prepare a response
567     */
568    if (NULL == (rsp = alloc_http_response()))
569    {
570       return cgi_error_memory();
571    }
572
573 #ifdef FEATURE_EXTENDED_STATISTICS
574    if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
575    {
576       increment_block_reason_counter(csp->action->string[ACTION_STRING_BLOCK]);
577    }
578 #endif
579
580    /*
581     * If it's an image-url, send back an image or redirect
582     * as specified by the relevant +image action
583     */
584 #ifdef FEATURE_IMAGE_BLOCKING
585    if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
586         && is_imageurl(csp))
587    {
588       char *p;
589       /* determine HOW images should be blocked */
590       p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
591
592       if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
593       {
594          log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
595       }
596
597       /* and handle accordingly: */
598       if ((p == NULL) || (0 == strcmpic(p, "pattern")))
599       {
600          rsp->status = strdup_or_die("403 Request blocked by Privoxy");
601          rsp->body = bindup(image_pattern_data, image_pattern_length);
602          if (rsp->body == NULL)
603          {
604             free_http_response(rsp);
605             return cgi_error_memory();
606          }
607          rsp->content_length = image_pattern_length;
608
609          if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
610          {
611             free_http_response(rsp);
612             return cgi_error_memory();
613          }
614       }
615       else if (0 == strcmpic(p, "blank"))
616       {
617          rsp->status = strdup_or_die("403 Request blocked by Privoxy");
618          rsp->body = bindup(image_blank_data, image_blank_length);
619          if (rsp->body == NULL)
620          {
621             free_http_response(rsp);
622             return cgi_error_memory();
623          }
624          rsp->content_length = image_blank_length;
625
626          if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
627          {
628             free_http_response(rsp);
629             return cgi_error_memory();
630          }
631       }
632       else
633       {
634          rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
635
636          if (enlist_unique_header(rsp->headers, "Location", p))
637          {
638             free_http_response(rsp);
639             return cgi_error_memory();
640          }
641       }
642
643    }
644    else
645 #endif /* def FEATURE_IMAGE_BLOCKING */
646    if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
647    {
648      /*
649       *  Send empty document.
650       */
651       new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
652
653       freez(rsp->body);
654       rsp->body = strdup_or_die(" ");
655       rsp->content_length = 1;
656
657       if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
658       {
659          /*
660           * Workaround for firefox bug 492459
661           *   https://bugzilla.mozilla.org/show_bug.cgi?id=492459
662           * Return a 200 OK status for pages blocked with +handle-as-empty-document
663           * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
664           */
665          rsp->status = strdup_or_die("200 Request blocked by Privoxy");
666       }
667       else
668       {
669          rsp->status = strdup_or_die("403 Request blocked by Privoxy");
670       }
671
672       if (new_content_type != 0)
673       {
674          log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
675          if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
676          {
677             free_http_response(rsp);
678             return cgi_error_memory();
679          }
680       }
681    }
682    else
683
684    /*
685     * Else, generate an HTML "blocked" message:
686     */
687    {
688       jb_err err;
689       struct map * exports;
690
691       rsp->status = strdup_or_die("403 Request blocked by Privoxy");
692
693       exports = default_exports(csp, NULL);
694       if (exports == NULL)
695       {
696          free_http_response(rsp);
697          return cgi_error_memory();
698       }
699
700 #ifdef FEATURE_FORCE_LOAD
701       err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
702       /*
703        * Export the force conditional block killer if
704        *
705        * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
706        * - Privoxy is configured to enforce blocks, or
707        * - it's a CONNECT request and enforcing wouldn't work anyway.
708        */
709       if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
710        || (0 == strcmpic(csp->http->gpc, "connect")))
711 #endif /* ndef FEATURE_FORCE_LOAD */
712       {
713          err = map_block_killer(exports, "force-support");
714       }
715
716       if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
717       if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
718       if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
719       if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
720       if (!err)
721       {
722          const char *block_reason;
723          if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
724          {
725             block_reason = csp->action->string[ACTION_STRING_BLOCK];
726          }
727          else
728          {
729             assert(connect_port_is_forbidden(csp));
730             block_reason = "Forbidden CONNECT port.";
731          }
732          err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
733       }
734       if (err)
735       {
736          free_map(exports);
737          free_http_response(rsp);
738          return cgi_error_memory();
739       }
740
741       err = template_fill_for_cgi(csp, "blocked", exports, rsp);
742       if (err)
743       {
744          free_http_response(rsp);
745          return cgi_error_memory();
746       }
747    }
748    rsp->crunch_reason = BLOCKED;
749
750    return finish_http_response(csp, rsp);
751
752 }
753
754
755 #ifdef FEATURE_TRUST
756 /*********************************************************************
757  *
758  * Function    :  trust_url FIXME: I should be called distrust_url
759  *
760  * Description :  Calls is_untrusted_url to determine if the URL is trusted
761  *                and if not, returns a HTTP 403 response with a reject message.
762  *
763  * Parameters  :
764  *          1  :  csp = Current client state (buffers, headers, etc...)
765  *
766  * Returns     :  NULL => trusted, else http_response.
767  *
768  *********************************************************************/
769 struct http_response *trust_url(struct client_state *csp)
770 {
771    struct http_response *rsp;
772    struct map * exports;
773    char buf[BUFFER_SIZE];
774    char *p;
775    struct pattern_spec **tl;
776    struct pattern_spec *t;
777    jb_err err;
778
779    /*
780     * Don't bother to work on trusted URLs
781     */
782    if (!is_untrusted_url(csp))
783    {
784       return NULL;
785    }
786
787    /*
788     * Else, prepare a response:
789     */
790    if (NULL == (rsp = alloc_http_response()))
791    {
792       return cgi_error_memory();
793    }
794
795    rsp->status = strdup_or_die("403 Request blocked by Privoxy");
796    exports = default_exports(csp, NULL);
797    if (exports == NULL)
798    {
799       free_http_response(rsp);
800       return cgi_error_memory();
801    }
802
803    /*
804     * Export the protocol, host, port, and referrer information
805     */
806    err = map(exports, "hostport", 1, csp->http->hostport, 1);
807    if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
808    if (!err) err = map(exports, "path", 1, csp->http->path, 1);
809
810    if (NULL != (p = get_header_value(csp->headers, "Referer:")))
811    {
812       if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
813    }
814    else
815    {
816       if (!err) err = map(exports, "referrer", 1, "none set", 1);
817    }
818
819    if (err)
820    {
821       free_map(exports);
822       free_http_response(rsp);
823       return cgi_error_memory();
824    }
825
826    /*
827     * Export the trust list
828     */
829    p = strdup_or_die("");
830    for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
831    {
832       snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
833       string_append(&p, buf);
834    }
835    err = map(exports, "trusted-referrers", 1, p, 0);
836
837    if (err)
838    {
839       free_map(exports);
840       free_http_response(rsp);
841       return cgi_error_memory();
842    }
843
844    /*
845     * Export the trust info, if available
846     */
847    if (csp->config->trust_info->first)
848    {
849       struct list_entry *l;
850
851       p = strdup_or_die("");
852       for (l = csp->config->trust_info->first; l ; l = l->next)
853       {
854          snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
855          string_append(&p, buf);
856       }
857       err = map(exports, "trust-info", 1, p, 0);
858    }
859    else
860    {
861       err = map_block_killer(exports, "have-trust-info");
862    }
863
864    if (err)
865    {
866       free_map(exports);
867       free_http_response(rsp);
868       return cgi_error_memory();
869    }
870
871    /*
872     * Export the force conditional block killer if
873     *
874     * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
875     * - Privoxy is configured to enforce blocks, or
876     * - it's a CONNECT request and enforcing wouldn't work anyway.
877     */
878 #ifdef FEATURE_FORCE_LOAD
879    if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
880     || (0 == strcmpic(csp->http->gpc, "connect")))
881    {
882       err = map_block_killer(exports, "force-support");
883    }
884    else
885    {
886       err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
887    }
888 #else /* ifndef FEATURE_FORCE_LOAD */
889    err = map_block_killer(exports, "force-support");
890 #endif /* ndef FEATURE_FORCE_LOAD */
891
892    if (err)
893    {
894       free_map(exports);
895       free_http_response(rsp);
896       return cgi_error_memory();
897    }
898
899    /*
900     * Build the response
901     */
902    err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
903    if (err)
904    {
905       free_http_response(rsp);
906       return cgi_error_memory();
907    }
908    rsp->crunch_reason = UNTRUSTED;
909
910    return finish_http_response(csp, rsp);
911 }
912 #endif /* def FEATURE_TRUST */
913
914
915 /*********************************************************************
916  *
917  * Function    :  compile_dynamic_pcrs_job_list
918  *
919  * Description :  Compiles a dynamic pcrs job list (one with variables
920  *                resolved at request time)
921  *
922  * Parameters  :
923  *          1  :  csp = Current client state (buffers, headers, etc...)
924  *          2  :  b = The filter list to compile
925  *
926  * Returns     :  NULL in case of errors, otherwise the
927  *                pcrs job list.
928  *
929  *********************************************************************/
930 pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
931 {
932    struct list_entry *pattern;
933    pcrs_job *job_list = NULL;
934    pcrs_job *dummy = NULL;
935    pcrs_job *lastjob = NULL;
936    int error = 0;
937
938    const struct pcrs_variable variables[] =
939    {
940       {"url",    csp->http->url,   1},
941       {"path",   csp->http->path,  1},
942       {"host",   csp->http->host,  1},
943       {"origin", csp->ip_addr_str, 1},
944       {"listen-address", csp->listen_addr_str, 1},
945       {NULL,     NULL,             1}
946    };
947
948    for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
949    {
950       assert(pattern->str != NULL);
951
952       dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
953       if (NULL == dummy)
954       {
955          log_error(LOG_LEVEL_ERROR,
956             "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
957             pattern->str, b->name, error, pcrs_strerror(error));
958          continue;
959       }
960       else
961       {
962          if (error == PCRS_WARN_TRUNCATION)
963          {
964             log_error(LOG_LEVEL_ERROR,
965                "At least one of the variables in \'%s\' had to "
966                "be truncated before compilation", pattern->str);
967          }
968          if (job_list == NULL)
969          {
970             job_list = dummy;
971          }
972          else
973          {
974             lastjob->next = dummy;
975          }
976          lastjob = dummy;
977       }
978    }
979
980    return job_list;
981 }
982
983
984 /*********************************************************************
985  *
986  * Function    :  rewrite_url
987  *
988  * Description :  Rewrites a URL with a single pcrs command
989  *                and returns the result if it differs from the
990  *                original and isn't obviously invalid.
991  *
992  * Parameters  :
993  *          1  :  old_url = URL to rewrite.
994  *          2  :  pcrs_command = pcrs command formatted as string (s@foo@bar@)
995  *
996  *
997  * Returns     :  NULL if the pcrs_command didn't change the url, or
998  *                the result of the modification.
999  *
1000  *********************************************************************/
1001 char *rewrite_url(char *old_url, const char *pcrs_command)
1002 {
1003    char *new_url = NULL;
1004    int hits;
1005
1006    assert(old_url);
1007    assert(pcrs_command);
1008
1009    new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
1010
1011    if (hits == 0)
1012    {
1013       log_error(LOG_LEVEL_REDIRECTS,
1014          "pcrs command \"%s\" didn't change \"%s\".",
1015          pcrs_command, old_url);
1016       freez(new_url);
1017    }
1018    else if (hits < 0)
1019    {
1020       log_error(LOG_LEVEL_REDIRECTS,
1021          "executing pcrs command \"%s\" to rewrite %s failed: %s",
1022          pcrs_command, old_url, pcrs_strerror(hits));
1023       freez(new_url);
1024    }
1025    else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
1026    {
1027       log_error(LOG_LEVEL_ERROR,
1028          "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
1029          "but the result doesn't look like a valid URL and will be ignored.",
1030          pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1031       freez(new_url);
1032    }
1033    else
1034    {
1035       log_error(LOG_LEVEL_REDIRECTS,
1036          "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
1037          pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
1038    }
1039
1040    return new_url;
1041
1042 }
1043
1044
1045 #ifdef FEATURE_FAST_REDIRECTS
1046 /*********************************************************************
1047  *
1048  * Function    :  get_last_url
1049  *
1050  * Description :  Search for the last URL inside a string.
1051  *                If the string already is a URL, it will
1052  *                be the first URL found.
1053  *
1054  * Parameters  :
1055  *          1  :  subject = the string to check
1056  *          2  :  redirect_mode = +fast-redirect{} mode
1057  *
1058  * Returns     :  NULL if no URL was found, or
1059  *                the last URL found.
1060  *
1061  *********************************************************************/
1062 static char *get_last_url(char *subject, const char *redirect_mode)
1063 {
1064    char *new_url = NULL;
1065    char *tmp;
1066
1067    assert(subject);
1068    assert(redirect_mode);
1069
1070    subject = strdup(subject);
1071    if (subject == NULL)
1072    {
1073       log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
1074       return NULL;
1075    }
1076
1077    if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
1078    {
1079       char *url_segment = NULL;
1080       char **url_segments;
1081       size_t max_segments;
1082       int segments;
1083
1084       log_error(LOG_LEVEL_REDIRECTS,
1085          "Checking \"%s\" for encoded redirects.", subject);
1086
1087       /*
1088        * Check each parameter in the URL separately.
1089        * Sectionize the URL at "?" and "&",
1090        * go backwards through the segments, URL-decode them
1091        * and look for a URL in the decoded result.
1092        * Stop the search after the first match.
1093        *
1094        * XXX: This estimate is guaranteed to be high enough as we
1095        *      let ssplit() ignore empty fields, but also a bit wasteful.
1096        */
1097       max_segments = strlen(subject) / 2;
1098       url_segments = malloc(max_segments * sizeof(char *));
1099
1100       if (NULL == url_segments)
1101       {
1102          log_error(LOG_LEVEL_ERROR,
1103             "Out of memory while decoding URL: %s", subject);
1104          freez(subject);
1105          return NULL;
1106       }
1107
1108       segments = ssplit(subject, "?&", url_segments, max_segments);
1109
1110       while (segments-- > 0)
1111       {
1112          char *dtoken = url_decode(url_segments[segments]);
1113          if (NULL == dtoken)
1114          {
1115             log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1116             continue;
1117          }
1118          url_segment = strstr(dtoken, "http://");
1119          if (NULL == url_segment)
1120          {
1121             url_segment = strstr(dtoken, "https://");
1122          }
1123          if (NULL != url_segment)
1124          {
1125             url_segment = strdup_or_die(url_segment);
1126             freez(dtoken);
1127             break;
1128          }
1129          freez(dtoken);
1130       }
1131       freez(subject);
1132       freez(url_segments);
1133
1134       if (url_segment == NULL)
1135       {
1136          return NULL;
1137       }
1138       subject = url_segment;
1139    }
1140    else
1141    {
1142       /* Look for a URL inside this one, without decoding anything. */
1143       log_error(LOG_LEVEL_REDIRECTS,
1144          "Checking \"%s\" for unencoded redirects.", subject);
1145    }
1146
1147    /*
1148     * Find the last URL encoded in the request
1149     */
1150    tmp = subject;
1151    while ((tmp = strstr(tmp, "http://")) != NULL)
1152    {
1153       new_url = tmp++;
1154    }
1155    tmp = (new_url != NULL) ? new_url : subject;
1156    while ((tmp = strstr(tmp, "https://")) != NULL)
1157    {
1158       new_url = tmp++;
1159    }
1160
1161    if ((new_url != NULL)
1162       && (  (new_url != subject)
1163          || (0 == strncmpic(subject, "http://", 7))
1164          || (0 == strncmpic(subject, "https://", 8))
1165          ))
1166    {
1167       /*
1168        * Return new URL if we found a redirect
1169        * or if the subject already was a URL.
1170        *
1171        * The second case makes sure that we can
1172        * chain get_last_url after another redirection check
1173        * (like rewrite_url) without losing earlier redirects.
1174        */
1175       new_url = strdup(new_url);
1176       freez(subject);
1177       return new_url;
1178    }
1179
1180    freez(subject);
1181    return NULL;
1182
1183 }
1184 #endif /* def FEATURE_FAST_REDIRECTS */
1185
1186
1187 /*********************************************************************
1188  *
1189  * Function    :  redirect_url
1190  *
1191  * Description :  Checks if Privoxy should answer the request with
1192  *                a HTTP redirect and generates the redirect if
1193  *                necessary.
1194  *
1195  * Parameters  :
1196  *          1  :  csp = Current client state (buffers, headers, etc...)
1197  *
1198  * Returns     :  NULL if the request can pass, HTTP redirect otherwise.
1199  *
1200  *********************************************************************/
1201 struct http_response *redirect_url(struct client_state *csp)
1202 {
1203    struct http_response *rsp;
1204 #ifdef FEATURE_FAST_REDIRECTS
1205    /*
1206     * XXX: Do we still need FEATURE_FAST_REDIRECTS
1207     * as compile-time option? The user can easily disable
1208     * it in his action file.
1209     */
1210    char * redirect_mode;
1211 #endif /* def FEATURE_FAST_REDIRECTS */
1212    char *new_url = NULL;
1213    char *redirection_string;
1214
1215    if ((csp->action->flags & ACTION_REDIRECT))
1216    {
1217       redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1218
1219       /*
1220        * If the redirection string begins with 's',
1221        * assume it's a pcrs command, otherwise treat it as
1222        * properly formatted URL and use it for the redirection
1223        * directly.
1224        *
1225        * According to (the now obsolete) RFC 2616 section 14.30
1226        * the URL has to be absolute and if the user tries:
1227        * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
1228        * she would get undefined results anyway.
1229        *
1230        * RFC 7231 7.1.2 actually allows relative references,
1231        * but those start with a leading slash (RFC 3986 4.2) and
1232        * thus can't be mistaken for pcrs commands either.
1233        */
1234
1235       if (*redirection_string == 's')
1236       {
1237          char *requested_url;
1238
1239 #ifdef FEATURE_HTTPS_INSPECTION
1240          if (client_use_ssl(csp))
1241          {
1242             jb_err err;
1243
1244             requested_url = strdup_or_die("https://");
1245             err = string_append(&requested_url, csp->http->hostport);
1246             if (!err) err = string_append(&requested_url, csp->http->path);
1247             if (err)
1248             {
1249                log_error(LOG_LEVEL_FATAL,
1250                   "Failed to rebuild URL 'https://%s%s'",
1251                   csp->http->hostport, csp->http->path);
1252             }
1253          }
1254          else
1255 #endif
1256          {
1257             requested_url = csp->http->url;
1258          }
1259          new_url = rewrite_url(requested_url, redirection_string);
1260 #ifdef FEATURE_HTTPS_INSPECTION
1261          if (requested_url != csp->http->url)
1262          {
1263             assert(client_use_ssl(csp));
1264             freez(requested_url);
1265          }
1266 #endif
1267       }
1268       else
1269       {
1270          log_error(LOG_LEVEL_REDIRECTS,
1271             "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1272             redirection_string);
1273          new_url = strdup(redirection_string);
1274       }
1275    }
1276
1277 #ifdef FEATURE_FAST_REDIRECTS
1278    if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1279    {
1280       char *old_url;
1281
1282       redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1283
1284       /*
1285        * If it exists, use the previously rewritten URL as input
1286        * otherwise just use the old path.
1287        */
1288       old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1289       new_url = get_last_url(old_url, redirect_mode);
1290       freez(old_url);
1291    }
1292 #endif /* def FEATURE_FAST_REDIRECTS */
1293
1294    /* Did any redirect action trigger? */
1295    if (new_url)
1296    {
1297       if (url_requires_percent_encoding(new_url))
1298       {
1299          char *encoded_url;
1300          log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1301             strlen(new_url), new_url);
1302          encoded_url = percent_encode_url(new_url);
1303          freez(new_url);
1304          if (encoded_url == NULL)
1305          {
1306             return cgi_error_memory();
1307          }
1308          new_url = encoded_url;
1309          assert(FALSE == url_requires_percent_encoding(new_url));
1310       }
1311
1312       if (0 == strcmpic(new_url, csp->http->url))
1313       {
1314          log_error(LOG_LEVEL_ERROR,
1315             "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1316             csp->http->url, new_url);
1317             freez(new_url);
1318       }
1319       else
1320       {
1321          log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1322
1323          if (NULL == (rsp = alloc_http_response()))
1324          {
1325             freez(new_url);
1326             return cgi_error_memory();
1327          }
1328
1329          rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
1330          if (enlist_unique_header(rsp->headers, "Location", new_url))
1331          {
1332             freez(new_url);
1333             free_http_response(rsp);
1334             return cgi_error_memory();
1335          }
1336          rsp->crunch_reason = REDIRECTED;
1337          freez(new_url);
1338
1339          return finish_http_response(csp, rsp);
1340       }
1341    }
1342
1343    /* Only reached if no redirect is required */
1344    return NULL;
1345
1346 }
1347
1348
1349 #ifdef FEATURE_IMAGE_BLOCKING
1350 /*********************************************************************
1351  *
1352  * Function    :  is_imageurl
1353  *
1354  * Description :  Given a URL, decide whether it should be treated
1355  *                as image URL or not.
1356  *
1357  * Parameters  :
1358  *          1  :  csp = Current client state (buffers, headers, etc...)
1359  *
1360  * Returns     :  True (nonzero) if URL is an image URL, false (0)
1361  *                otherwise
1362  *
1363  *********************************************************************/
1364 int is_imageurl(const struct client_state *csp)
1365 {
1366    return ((csp->action->flags & ACTION_IMAGE) != 0);
1367
1368 }
1369 #endif /* def FEATURE_IMAGE_BLOCKING */
1370
1371
1372 #ifdef FEATURE_TRUST
1373 /*********************************************************************
1374  *
1375  * Function    :  is_untrusted_url
1376  *
1377  * Description :  Should we "distrust" this URL (and block it)?
1378  *
1379  *                Yes if it matches a line in the trustfile, or if the
1380  *                    referrer matches a line starting with "+" in the
1381  *                    trustfile.
1382  *                No  otherwise.
1383  *
1384  * Parameters  :
1385  *          1  :  csp = Current client state (buffers, headers, etc...)
1386  *
1387  * Returns     :  0 => trusted, 1 => untrusted
1388  *
1389  *********************************************************************/
1390 int is_untrusted_url(const struct client_state *csp)
1391 {
1392    struct file_list *fl;
1393    struct block_spec *b;
1394    struct pattern_spec **trusted_url;
1395    struct http_request rhttp[1];
1396    const char *referer;
1397    jb_err err;
1398
1399    /*
1400     * If we don't have a trustlist, we trust everybody
1401     */
1402    if (((fl = csp->tlist) == NULL) || ((b  = fl->f) == NULL))
1403    {
1404       return 0;
1405    }
1406
1407    memset(rhttp, '\0', sizeof(*rhttp));
1408
1409    /*
1410     * Do we trust the request URL itself?
1411     */
1412    for (b = b->next; b ; b = b->next)
1413    {
1414       if (url_match(b->url, csp->http))
1415       {
1416          return b->reject;
1417       }
1418    }
1419
1420 #ifdef FEATURE_HTTPS_INSPECTION
1421    if (client_use_ssl(csp))
1422    {
1423       if (NULL == (referer = get_header_value(csp->https_headers, "Referer:")))
1424       {
1425          /* no referrer was supplied */
1426          return 1;
1427       }
1428    }
1429    else
1430 #endif
1431    {
1432       if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1433       {
1434          /* no referrer was supplied */
1435          return 1;
1436       }
1437    }
1438
1439    /*
1440     * If not, do we maybe trust its referrer?
1441     */
1442    err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1443    if (err)
1444    {
1445       return 1;
1446    }
1447
1448    for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1449    {
1450       if (url_match(*trusted_url, rhttp))
1451       {
1452          /* if the URL's referrer is from a trusted referrer, then
1453           * add the target spec to the trustfile as an unblocked
1454           * domain and return 0 (which means it's OK).
1455           */
1456
1457          FILE *fp;
1458
1459          if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1460          {
1461             char * path;
1462             char * path_end;
1463             char * new_entry = strdup_or_die("~");
1464
1465             string_append(&new_entry, csp->http->hostport);
1466
1467             path = csp->http->path;
1468             if ( (path[0] == '/')
1469               && (path[1] == '~')
1470               && ((path_end = strchr(path + 2, '/')) != NULL))
1471             {
1472                /* since this path points into a user's home space
1473                 * be sure to include this spec in the trustfile.
1474                 */
1475                long path_len = path_end - path; /* save offset */
1476                path = strdup(path); /* Copy string */
1477                if (path != NULL)
1478                {
1479                   path_end = path + path_len; /* regenerate ptr to new buffer */
1480                   *(path_end + 1) = '\0'; /* Truncate path after '/' */
1481                }
1482                string_join(&new_entry, path);
1483             }
1484
1485             /*
1486              * Give a reason for generating this entry.
1487              */
1488             string_append(&new_entry, " # Trusted referrer was: ");
1489             string_append(&new_entry, referer);
1490
1491             if (new_entry != NULL)
1492             {
1493                if (-1 == fprintf(fp, "%s\n", new_entry))
1494                {
1495                   log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1496                      new_entry, csp->config->trustfile);
1497                }
1498                freez(new_entry);
1499             }
1500             else
1501             {
1502                /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1503                log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1504             }
1505
1506             fclose(fp);
1507          }
1508          else
1509          {
1510             log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1511                csp->http->hostport, csp->config->trustfile);
1512          }
1513          return 0;
1514       }
1515    }
1516
1517    return 1;
1518 }
1519 #endif /* def FEATURE_TRUST */
1520
1521
1522 /*********************************************************************
1523  *
1524  * Function    :  get_filter
1525  *
1526  * Description :  Get a filter with a given name and type.
1527  *                Note that taggers are filters, too.
1528  *
1529  * Parameters  :
1530  *          1  :  csp = Current client state (buffers, headers, etc...)
1531  *          2  :  requested_name = Name of the content filter to get
1532  *          3  :  requested_type = Type of the filter to tagger to lookup
1533  *
1534  * Returns     :  A pointer to the requested filter
1535  *                or NULL if the filter wasn't found
1536  *
1537  *********************************************************************/
1538 struct re_filterfile_spec *get_filter(const struct client_state *csp,
1539                                       const char *requested_name,
1540                                       enum filter_type requested_type)
1541 {
1542    int i;
1543    struct re_filterfile_spec *b;
1544    struct file_list *fl;
1545
1546    for (i = 0; i < MAX_AF_FILES; i++)
1547    {
1548      fl = csp->rlist[i];
1549      if ((NULL == fl) || (NULL == fl->f))
1550      {
1551         /*
1552          * Either there are no filter files left or this
1553          * filter file just contains no valid filters.
1554          *
1555          * Continue to be sure we don't miss valid filter
1556          * files that are chained after empty or invalid ones.
1557          */
1558         continue;
1559      }
1560
1561      for (b = fl->f; b != NULL; b = b->next)
1562      {
1563         if (b->type != requested_type)
1564         {
1565            /* The callers isn't interested in this filter type. */
1566            continue;
1567         }
1568         if (strcmp(b->name, requested_name) == 0)
1569         {
1570            /* The requested filter has been found. Abort search. */
1571            return b;
1572         }
1573      }
1574    }
1575
1576    /* No filter with the given name and type exists. */
1577    return NULL;
1578
1579 }
1580
1581
1582 /*********************************************************************
1583  *
1584  * Function    :  pcrs_filter_impl
1585  *
1586  * Description :  Execute all text substitutions from all applying
1587  *                (based on filter_response_body value) +filter
1588  *                or +client_body_filter actions on the given buffer.
1589  *
1590  * Parameters  :
1591  *          1  :  csp = Current client state (buffers, headers, etc...)
1592  *          2  :  filter_response_body = when TRUE execute +filter
1593  *                actions; execute +client_body_filter actions otherwise
1594  *          3  :  data = Target data
1595  *          4  :  data_len = Target data len
1596  *
1597  * Returns     :  a pointer to the (newly allocated) modified buffer.
1598  *                or NULL if there were no hits or something went wrong
1599  *
1600  *********************************************************************/
1601 static char *pcrs_filter_impl(const struct client_state *csp, int filter_response_body,
1602                               const char *data, size_t *data_len)
1603 {
1604    int hits = 0;
1605    size_t size, prev_size;
1606    const int filters_idx =
1607       filter_response_body ? ACTION_MULTI_FILTER : ACTION_MULTI_CLIENT_BODY_FILTER;
1608    const enum filter_type filter_type =
1609       filter_response_body ? FT_CONTENT_FILTER : FT_CLIENT_BODY_FILTER;
1610
1611    const char *old = NULL;
1612    char *new = NULL;
1613    pcrs_job *job;
1614
1615    struct re_filterfile_spec *b;
1616    struct list_entry *filtername;
1617
1618    /*
1619     * Sanity first
1620     */
1621    if (*data_len == 0)
1622    {
1623       return(NULL);
1624    }
1625
1626    if (filters_available(csp) == FALSE)
1627    {
1628       log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1629          "content filtering enabled, but no content filters available.");
1630       return(NULL);
1631    }
1632
1633    size = *data_len;
1634    old = data;
1635
1636    /*
1637     * For all applying actions, look if a filter by that
1638     * name exists and if yes, execute it's pcrs_joblist on the
1639     * buffer.
1640     */
1641    for (filtername = csp->action->multi[filters_idx]->first;
1642         filtername != NULL; filtername = filtername->next)
1643    {
1644       int current_hits = 0; /* Number of hits caused by this filter */
1645       int job_number   = 0; /* Which job we're currently executing  */
1646       int job_hits     = 0; /* How many hits the current job caused */
1647       pcrs_job *joblist;
1648
1649       b = get_filter(csp, filtername->str, filter_type);
1650       if (b == NULL)
1651       {
1652          continue;
1653       }
1654
1655       joblist = b->joblist;
1656
1657       if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1658
1659       if (NULL == joblist)
1660       {
1661          log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1662          continue;
1663       }
1664
1665       prev_size = size;
1666       /* Apply all jobs from the joblist */
1667       for (job = joblist; NULL != job; job = job->next)
1668       {
1669          job_number++;
1670          job_hits = pcrs_execute(job, old, size, &new, &size);
1671
1672          if (job_hits >= 0)
1673          {
1674             /*
1675              * That went well. Continue filtering
1676              * and use the result of this job as
1677              * input for the next one.
1678              */
1679             current_hits += job_hits;
1680             if (old != data)
1681             {
1682                freez(old);
1683             }
1684             old = new;
1685          }
1686          else
1687          {
1688             /*
1689              * This job caused an unexpected error. Inform the user
1690              * and skip the rest of the jobs in this filter. We could
1691              * continue with the next job, but usually the jobs
1692              * depend on each other or are similar enough to
1693              * fail for the same reason.
1694              *
1695              * At the moment our pcrs expects the error codes of pcre 3.4,
1696              * but newer pcre versions can return additional error codes.
1697              * As a result pcrs_strerror()'s error message might be
1698              * "Unknown error ...", therefore we print the numerical value
1699              * as well.
1700              *
1701              * XXX: Is this important enough for LOG_LEVEL_ERROR or
1702              * should we use LOG_LEVEL_RE_FILTER instead?
1703              */
1704             log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1705                b->name, job_number, pcrs_strerror(job_hits), job_hits);
1706             break;
1707          }
1708       }
1709
1710       if (b->dynamic) pcrs_free_joblist(joblist);
1711
1712       if (filter_response_body)
1713       {
1714          log_error(LOG_LEVEL_RE_FILTER,
1715             "filtering %s%s (size %lu) with \'%s\' produced %d hits (new size %lu).",
1716             csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1717       }
1718       else
1719       {
1720          log_error(LOG_LEVEL_RE_FILTER, "filtering request body from client %s "
1721             "(size %lu) with \'%s\' produced %d hits (new size %lu).",
1722             csp->ip_addr_str, prev_size, b->name, current_hits, size);
1723       }
1724 #ifdef FEATURE_EXTENDED_STATISTICS
1725       update_filter_statistics(b->name, current_hits);
1726 #endif
1727       hits += current_hits;
1728    }
1729
1730    /*
1731     * If there were no hits, destroy our copy and let
1732     * chat() use the original content
1733     */
1734    if (!hits)
1735    {
1736       if (old != data && old != new)
1737       {
1738          freez(old);
1739       }
1740       freez(new);
1741       return(NULL);
1742    }
1743
1744    *data_len = size;
1745    return(new);
1746 }
1747
1748
1749 /*********************************************************************
1750  *
1751  * Function    :  pcrs_filter_response_body
1752  *
1753  * Description :  Execute all text substitutions from all applying
1754  *                +filter actions on the text buffer that's been
1755  *                accumulated in csp->iob->buf.
1756  *
1757  * Parameters  :
1758  *          1  :  csp = Current client state (buffers, headers, etc...)
1759  *
1760  * Returns     :  a pointer to the (newly allocated) modified buffer.
1761  *                or NULL if there were no hits or something went wrong
1762  *
1763  *********************************************************************/
1764 static char *pcrs_filter_response_body(struct client_state *csp)
1765 {
1766    size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1767
1768    char *new = NULL;
1769
1770    /*
1771     * Sanity first
1772     */
1773    if (csp->iob->cur >= csp->iob->eod)
1774    {
1775       return NULL;
1776    }
1777
1778    new = pcrs_filter_impl(csp, TRUE, csp->iob->cur, &size);
1779
1780    if (new != NULL)
1781    {
1782       csp->flags |= CSP_FLAG_MODIFIED;
1783       csp->content_length = size;
1784       clear_iob(csp->iob);
1785    }
1786
1787    return new;
1788 }
1789
1790
1791 #ifdef FEATURE_EXTERNAL_FILTERS
1792 /*********************************************************************
1793  *
1794  * Function    :  get_external_filter
1795  *
1796  * Description :  Lookup the code to execute for an external filter.
1797  *                Masks the misuse of the re_filterfile_spec.
1798  *
1799  * Parameters  :
1800  *          1  :  csp = Current client state (buffers, headers, etc...)
1801  *          2  :  name = Name of the content filter to get
1802  *
1803  * Returns     :  A pointer to the requested code
1804  *                or NULL if the filter wasn't found
1805  *
1806  *********************************************************************/
1807 static const char *get_external_filter(const struct client_state *csp,
1808                                 const char *name)
1809 {
1810    struct re_filterfile_spec *external_filter;
1811
1812    external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
1813    if (external_filter == NULL)
1814    {
1815       log_error(LOG_LEVEL_FATAL,
1816          "Didn't find stuff to execute for external filter: %s",
1817          name);
1818    }
1819
1820    return external_filter->patterns->first->str;
1821
1822 }
1823
1824
1825 /*********************************************************************
1826  *
1827  * Function    :  set_privoxy_variables
1828  *
1829  * Description :  Sets a couple of privoxy-specific environment variables
1830  *
1831  * Parameters  :
1832  *          1  :  csp = Current client state (buffers, headers, etc...)
1833  *
1834  * Returns     :  N/A
1835  *
1836  *********************************************************************/
1837 static void set_privoxy_variables(const struct client_state *csp)
1838 {
1839    int i;
1840    struct {
1841       const char *name;
1842       const char *value;
1843    } env[] = {
1844       { "PRIVOXY_URL",    csp->http->url   },
1845       { "PRIVOXY_PATH",   csp->http->path  },
1846       { "PRIVOXY_HOST",   csp->http->host  },
1847       { "PRIVOXY_ORIGIN", csp->ip_addr_str },
1848       { "PRIVOXY_LISTEN_ADDRESS", csp->listen_addr_str },
1849    };
1850
1851    for (i = 0; i < SZ(env); i++)
1852    {
1853       if (setenv(env[i].name, env[i].value, 1))
1854       {
1855          log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
1856             env[i].name, env[i].value);
1857       }
1858    }
1859 }
1860
1861
1862 /*********************************************************************
1863  *
1864  * Function    :  execute_external_filter
1865  *
1866  * Description :  Pipe content into external filter and return the output
1867  *
1868  * Parameters  :
1869  *          1  :  csp = Current client state (buffers, headers, etc...)
1870  *          2  :  name = Name of the external filter to execute
1871  *          3  :  content = The original content to filter
1872  *          4  :  size = The size of the content buffer
1873  *
1874  * Returns     :  a pointer to the (newly allocated) modified buffer.
1875  *                or NULL if there were no hits or something went wrong
1876  *
1877  *********************************************************************/
1878 static char *execute_external_filter(const struct client_state *csp,
1879    const char *name, char *content, size_t *size)
1880 {
1881    char cmd[200];
1882    char file_name[FILENAME_MAX];
1883    FILE *fp;
1884    char *filter_output;
1885    int fd;
1886    int ret;
1887    size_t new_size;
1888    const char *external_filter;
1889
1890    if (csp->config->temporary_directory == NULL)
1891    {
1892       log_error(LOG_LEVEL_ERROR,
1893          "No temporary-directory configured. Can't execute filter: %s",
1894          name);
1895       return NULL;
1896    }
1897
1898    external_filter = get_external_filter(csp, name);
1899
1900    if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
1901          "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
1902    {
1903       log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
1904       return NULL;
1905    }
1906
1907    fd = mkstemp(file_name);
1908    if (fd == -1)
1909    {
1910       log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
1911       return NULL;
1912    }
1913
1914    fp = fdopen(fd, "w");
1915    if (fp == NULL)
1916    {
1917       log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
1918       unlink(file_name);
1919       return NULL;
1920    }
1921
1922    /*
1923     * The size may be zero if a previous filter discarded everything.
1924     *
1925     * This isn't necessary unintentional, so we just don't try
1926     * to fwrite() nothing and let the user deal with the rest.
1927     */
1928    if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
1929    {
1930       log_error(LOG_LEVEL_ERROR, "fwrite(..., %lu, 1, ..) failed: %E", *size);
1931       unlink(file_name);
1932       fclose(fp);
1933       return NULL;
1934    }
1935    fclose(fp);
1936
1937    if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
1938    {
1939       log_error(LOG_LEVEL_ERROR,
1940          "temporary-directory or external filter path too long");
1941       unlink(file_name);
1942       return NULL;
1943    }
1944
1945    log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
1946
1947    /*
1948     * The locking is necessary to prevent other threads
1949     * from overwriting the environment variables before
1950     * the popen fork. Afterwards this no longer matters.
1951     */
1952    privoxy_mutex_lock(&external_filter_mutex);
1953    set_privoxy_variables(csp);
1954    fp = popen(cmd, "r");
1955    privoxy_mutex_unlock(&external_filter_mutex);
1956    if (fp == NULL)
1957    {
1958       log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
1959       unlink(file_name);
1960       return NULL;
1961    }
1962
1963    /* Allocate at least one byte */
1964    filter_output = malloc_or_die(*size + 1);
1965
1966    new_size = 0;
1967    while (!feof(fp) && !ferror(fp))
1968    {
1969       size_t len;
1970       /* Could be bigger ... */
1971       enum { READ_LENGTH = 2048 };
1972
1973       if (new_size + READ_LENGTH >= *size)
1974       {
1975          char *p;
1976
1977          /* Could be considered wasteful if the content is 'large'. */
1978          *size += (*size >= READ_LENGTH) ? *size : READ_LENGTH;
1979
1980          p = realloc(filter_output, *size);
1981          if (p == NULL)
1982          {
1983             log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
1984                "external filter output. Using what we got so far.");
1985             break;
1986          }
1987          filter_output = p;
1988       }
1989       assert(new_size + READ_LENGTH < *size);
1990       len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
1991       if (len > 0)
1992       {
1993          new_size += len;
1994       }
1995    }
1996
1997    ret = pclose(fp);
1998    if (ret == -1)
1999    {
2000       log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
2001    }
2002    else
2003    {
2004       log_error(LOG_LEVEL_RE_FILTER,
2005          "Executing '%s' resulted in return value %d. "
2006          "Read %lu of up to %lu bytes.", name, (ret >> 8), new_size, *size);
2007    }
2008
2009    unlink(file_name);
2010    *size = new_size;
2011
2012    return filter_output;
2013
2014 }
2015 #endif /* def FEATURE_EXTERNAL_FILTERS */
2016
2017
2018 /*********************************************************************
2019  *
2020  * Function    :  pcrs_filter_request_body
2021  *
2022  * Description :  Execute all text substitutions from all applying
2023  *                +client_body_filter actions on the given text buffer.
2024  *
2025  * Parameters  :
2026  *          1  :  csp = Current client state (buffers, headers, etc...)
2027  *          2  :  data = Target data
2028  *          3  :  data_len = Target data len
2029  *
2030  * Returns     :  a pointer to the (newly allocated) modified buffer.
2031  *                or NULL if there were no hits or something went wrong
2032  *
2033  *********************************************************************/
2034 static char *pcrs_filter_request_body(const struct client_state *csp, const char *data, size_t *data_len)
2035 {
2036    return pcrs_filter_impl(csp, FALSE, data, data_len);
2037 }
2038
2039
2040 /*********************************************************************
2041  *
2042  * Function    :  gif_deanimate_response
2043  *
2044  * Description :  Deanimate the GIF image that has been accumulated in
2045  *                csp->iob->buf, set csp->content_length to the modified
2046  *                size and raise the CSP_FLAG_MODIFIED flag.
2047  *
2048  * Parameters  :
2049  *          1  :  csp = Current client state (buffers, headers, etc...)
2050  *
2051  * Returns     :  a pointer to the (newly allocated) modified buffer.
2052  *                or NULL in case something went wrong.
2053  *
2054  *********************************************************************/
2055 #ifdef FUZZ
2056 char *gif_deanimate_response(struct client_state *csp)
2057 #else
2058 static char *gif_deanimate_response(struct client_state *csp)
2059 #endif
2060 {
2061    struct binbuffer *in, *out;
2062    char *p;
2063    size_t size;
2064
2065    size = (size_t)(csp->iob->eod - csp->iob->cur);
2066
2067    in =  zalloc_or_die(sizeof(*in));
2068    out = zalloc_or_die(sizeof(*out));
2069
2070    in->buffer = csp->iob->cur;
2071    in->size = size;
2072
2073    if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
2074    {
2075       log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
2076       freez(in);
2077       buf_free(out);
2078       return(NULL);
2079    }
2080    else
2081    {
2082       if ((int)size == out->offset)
2083       {
2084          log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
2085       }
2086       else
2087       {
2088          log_error(LOG_LEVEL_DEANIMATE,
2089             "Success! GIF shrunk from %lu bytes to %lu.", size, out->offset);
2090       }
2091       csp->content_length = out->offset;
2092       csp->flags |= CSP_FLAG_MODIFIED;
2093       p = out->buffer;
2094       freez(in);
2095       freez(out);
2096       return(p);
2097    }
2098
2099 }
2100
2101
2102 /*********************************************************************
2103  *
2104  * Function    :  get_filter_function
2105  *
2106  * Description :  Decides which content filter function has
2107  *                to be applied (if any). Only considers functions
2108  *                for internal filters which are mutually-exclusive.
2109  *
2110  * Parameters  :
2111  *          1  :  csp = Current client state (buffers, headers, etc...)
2112  *
2113  * Returns     :  The content filter function to run, or
2114  *                NULL if no content filter is active
2115  *
2116  *********************************************************************/
2117 static filter_function_ptr get_filter_function(const struct client_state *csp)
2118 {
2119    filter_function_ptr filter_function = NULL;
2120
2121    /*
2122     * Choose the applying filter function based on
2123     * the content type and action settings.
2124     */
2125    if ((csp->content_type & CT_TEXT) &&
2126        (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2127    {
2128       filter_function = pcrs_filter_response_body;
2129    }
2130    else if ((csp->content_type & CT_GIF) &&
2131             (csp->action->flags & ACTION_DEANIMATE))
2132    {
2133       filter_function = gif_deanimate_response;
2134    }
2135
2136    return filter_function;
2137 }
2138
2139
2140 /*********************************************************************
2141  *
2142  * Function    :  get_bytes_to_next_chunk_start
2143  *
2144  * Description :  Returns the number of bytes to the start of the
2145  *                next chunk in the buffer.
2146  *
2147  * Parameters  :
2148  *          1  :  buffer = Pointer to the text buffer
2149  *          2  :  size = Number of bytes in the buffer.
2150  *          3  :  offset = Where to expect the beginning of the next chunk.
2151  *
2152  * Returns     :  -1 if the size can't be determined or data is missing,
2153  *                otherwise the number of bytes to the start of the next chunk
2154  *                or 0 if the last chunk has been fully buffered.
2155  *
2156  *********************************************************************/
2157 static int get_bytes_to_next_chunk_start(char *buffer, size_t size, size_t offset)
2158 {
2159    char *chunk_start;
2160    char *p;
2161    unsigned int chunk_size = 0;
2162    int bytes_to_skip;
2163
2164    if (size <= offset || size < 5)
2165    {
2166       /*
2167        * Not enough bytes bufferd to figure
2168        * out the size of the next chunk.
2169        */
2170       return -1;
2171    }
2172
2173    chunk_start = buffer + offset;
2174
2175    p = strstr(chunk_start, "\r\n");
2176    if (NULL == p)
2177    {
2178       /*
2179        * The line with the chunk-size hasn't been completely received
2180        * yet (or is invalid).
2181        */
2182       log_error(LOG_LEVEL_RE_FILTER,
2183          "Not enough or invalid data in buffer in chunk size line.");
2184       return -1;
2185    }
2186
2187    if (sscanf(chunk_start, "%x", &chunk_size) != 1)
2188    {
2189       /* XXX: Write test case to trigger this. */
2190       log_error(LOG_LEVEL_ERROR, "Failed to parse chunk size. "
2191          "Size: %lu, offset: %lu. Chunk size start: %N", size, offset,
2192          (size - offset), chunk_start);
2193       return -1;
2194    }
2195
2196    /*
2197     * To get to the start of the next chunk size we have to skip
2198     * the line with the current chunk size followed by "\r\n" followd
2199     * by the actual data and another "\r\n" following the data.
2200     */
2201    bytes_to_skip = (int)(p - chunk_start) + 2 + (int)chunk_size + 2;
2202
2203    if (bytes_to_skip <= 0)
2204    {
2205       log_error(LOG_LEVEL_ERROR,
2206          "Failed to figure out chunk offset. %u and %d seem dubious.",
2207          chunk_size, bytes_to_skip);
2208       return -1;
2209    }
2210    if (chunk_size == 0)
2211    {
2212       if (bytes_to_skip <= (size - offset))
2213       {
2214          return 0;
2215       }
2216       else
2217       {
2218          log_error(LOG_LEVEL_INFO,
2219             "Last chunk detected but we're still missing data.");
2220          return -1;
2221       }
2222    }
2223
2224    return bytes_to_skip;
2225 }
2226
2227
2228 /*********************************************************************
2229  *
2230  * Function    :  get_bytes_missing_from_chunked_data
2231  *
2232  * Description :  Figures out how many bytes of data we need to get
2233  *                to the start of the next chunk of data (XXX: terminology).
2234  *                Due to the nature of chunk-encoded data we can only see
2235  *                how many data is missing according to the last chunk size
2236  *                buffered.
2237  *
2238  * Parameters  :
2239  *          1  :  buffer = Pointer to the text buffer
2240  *          2  :  size = Number of bytes in the buffer.
2241  *          3  :  offset = Where to expect the beginning of the next chunk.
2242  *
2243  * Returns     :  -1 if the data can't be parsed (yet),
2244  *                 0 if the buffer is complete or a
2245  *                 number of bytes that is missing.
2246  *
2247  *********************************************************************/
2248 int get_bytes_missing_from_chunked_data(char *buffer, size_t size, size_t offset)
2249 {
2250    int ret = -1;
2251    int last_valid_offset = -1;
2252
2253    if (size < offset || size < 5)
2254    {
2255       /* Not enough data buffered yet */
2256       return -1;
2257    }
2258
2259    do
2260    {
2261       ret = get_bytes_to_next_chunk_start(buffer, size, offset);
2262       if (ret == -1)
2263       {
2264          return last_valid_offset;
2265       }
2266       if (ret == 0)
2267       {
2268          return 0;
2269       }
2270       if (offset != 0)
2271       {
2272          last_valid_offset = (int)offset;
2273       }
2274       offset += (size_t)ret;
2275    } while (offset < size);
2276
2277    return (int)offset;
2278
2279 }
2280
2281
2282 /*********************************************************************
2283  *
2284  * Function    :  chunked_data_is_complete
2285  *
2286  * Description :  Detects if a buffer with chunk-encoded data looks
2287  *                complete.
2288  *
2289  * Parameters  :
2290  *          1  :  buffer = Pointer to the text buffer
2291  *          2  :  size = Number of bytes in the buffer.
2292  *          3  :  offset = Where to expect the beginning of the
2293  *                         first complete chunk.
2294  *
2295  * Returns     :  TRUE if it looks like the data is complete,
2296  *                FALSE otherwise.
2297  *
2298  *********************************************************************/
2299 int chunked_data_is_complete(char *buffer, size_t size, size_t offset)
2300 {
2301    return (0 == get_bytes_missing_from_chunked_data(buffer, size, offset));
2302
2303 }
2304
2305
2306 /*********************************************************************
2307  *
2308  * Function    :  remove_chunked_transfer_coding
2309  *
2310  * Description :  In-situ remove the "chunked" transfer coding as defined
2311  *                in RFC 7230 4.1 from a buffer. XXX: The implementation
2312  *                is neither complete nor compliant (TODO #129).
2313  *
2314  * Parameters  :
2315  *          1  :  buffer = Pointer to the text buffer
2316  *          2  :  size =  In: Number of bytes to be processed,
2317  *                       Out: Number of bytes after de-chunking.
2318  *                       (undefined in case of errors)
2319  *
2320  * Returns     :  JB_ERR_OK for success,
2321  *                JB_ERR_PARSE otherwise
2322  *
2323  *********************************************************************/
2324 #ifdef FUZZ
2325 extern jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2326 #else
2327 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
2328 #endif
2329 {
2330    size_t newsize = 0;
2331    unsigned int chunksize = 0;
2332    char *from_p, *to_p;
2333    const char *end_of_buffer = buffer + *size;
2334
2335    if (*size == 0)
2336    {
2337       log_error(LOG_LEVEL_FATAL, "Invalid chunked input. Buffer is empty.");
2338       return JB_ERR_PARSE;
2339    }
2340
2341    assert(buffer);
2342    from_p = to_p = buffer;
2343
2344 #ifndef FUZZ
2345    /*
2346     * Refuse to de-chunk invalid or incomplete data unless we're fuzzing.
2347     */
2348    if (!chunked_data_is_complete(buffer, *size, 0))
2349    {
2350       log_error(LOG_LEVEL_ERROR,
2351          "Chunk-encoding appears to be invalid. Content can't be filtered.");
2352       return JB_ERR_PARSE;
2353    }
2354 #endif
2355
2356    if (sscanf(buffer, "%x", &chunksize) != 1)
2357    {
2358       log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
2359       return JB_ERR_PARSE;
2360    }
2361
2362    while (chunksize > 0U)
2363    {
2364       /*
2365        * If the chunk-size is valid, we should have at least
2366        * chunk-size bytes of chunk-data and five bytes of
2367        * meta data (chunk-size, CRLF, CRLF) left in the buffer.
2368        */
2369       if (chunksize + 5 >= *size - newsize)
2370       {
2371          log_error(LOG_LEVEL_ERROR,
2372             "Chunk size %u exceeds buffered data left. "
2373             "Already digested %lu of %lu buffered bytes.",
2374             chunksize, newsize, *size);
2375          return JB_ERR_PARSE;
2376       }
2377
2378       /*
2379        * Skip the chunk-size, the optional chunk-ext and the CRLF
2380        * that is supposed to be located directly before the start
2381        * of chunk-data.
2382        */
2383       if (NULL == (from_p = strstr(from_p, "\r\n")))
2384       {
2385          log_error(LOG_LEVEL_ERROR,
2386             "Failed to strip \"chunked\" transfer coding. "
2387             "Line with chunk size doesn't seem to end properly.");
2388          return JB_ERR_PARSE;
2389       }
2390       from_p += 2;
2391
2392       /*
2393        * The previous strstr() does not enforce chunk-validity
2394        * and is sattisfied as long a CRLF is left in the buffer.
2395        *
2396        * Make sure the bytes we consider chunk-data are within
2397        * the valid range.
2398        */
2399       if (from_p + chunksize >= end_of_buffer)
2400       {
2401          log_error(LOG_LEVEL_ERROR,
2402             "Failed to decode content for filtering. "
2403             "One chunk end is beyond the end of the buffer.");
2404          return JB_ERR_PARSE;
2405       }
2406
2407       memmove(to_p, from_p, (size_t) chunksize);
2408       newsize += chunksize;
2409       to_p = buffer + newsize;
2410       from_p += chunksize;
2411
2412       /*
2413        * Not merging this check with the previous one allows us
2414        * to keep chunks without trailing CRLF. It's not clear
2415        * if we actually have to care about those, though.
2416        */
2417       if (from_p + 2 >= end_of_buffer)
2418       {
2419          log_error(LOG_LEVEL_ERROR, "Not enough room for trailing CRLF.");
2420          return JB_ERR_PARSE;
2421       }
2422       from_p += 2;
2423       if (sscanf(from_p, "%x", &chunksize) != 1)
2424       {
2425          log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
2426          break;
2427       }
2428    }
2429
2430    /* XXX: Should get its own loglevel. */
2431    log_error(LOG_LEVEL_RE_FILTER,
2432       "De-chunking successful. Shrunk from %lu to %lu", *size, newsize);
2433
2434    *size = newsize;
2435
2436    return JB_ERR_OK;
2437
2438 }
2439
2440
2441 /*********************************************************************
2442  *
2443  * Function    :  prepare_for_filtering
2444  *
2445  * Description :  If necessary, de-chunks and decompresses
2446  *                the content so it can get filterd.
2447  *
2448  * Parameters  :
2449  *          1  :  csp = Current client state (buffers, headers, etc...)
2450  *
2451  * Returns     :  JB_ERR_OK for success,
2452  *                JB_ERR_PARSE otherwise
2453  *
2454  *********************************************************************/
2455 static jb_err prepare_for_filtering(struct client_state *csp)
2456 {
2457    jb_err err = JB_ERR_OK;
2458
2459    /*
2460     * If the body has a "chunked" transfer-encoding,
2461     * get rid of it, adjusting size and iob->eod
2462     */
2463    if (csp->flags & CSP_FLAG_CHUNKED)
2464    {
2465       size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
2466
2467       log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
2468       err = remove_chunked_transfer_coding(csp->iob->cur, &size);
2469       if (JB_ERR_OK == err)
2470       {
2471          csp->iob->eod = csp->iob->cur + size;
2472          csp->flags |= CSP_FLAG_MODIFIED;
2473       }
2474       else
2475       {
2476          return JB_ERR_PARSE;
2477       }
2478    }
2479
2480 #ifdef FEATURE_ZLIB
2481    /*
2482     * If the body has a supported transfer-encoding,
2483     * decompress it, adjusting size and iob->eod.
2484     */
2485    if ((csp->content_type & (CT_GZIP|CT_DEFLATE))
2486 #ifdef FEATURE_BROTLI
2487       || (csp->content_type & CT_BROTLI)
2488 #endif
2489        )
2490    {
2491       if (0 == csp->iob->eod - csp->iob->cur)
2492       {
2493          /* Nothing left after de-chunking. */
2494          return JB_ERR_OK;
2495       }
2496
2497       err = decompress_iob(csp);
2498
2499       if (JB_ERR_OK == err)
2500       {
2501          csp->flags |= CSP_FLAG_MODIFIED;
2502          csp->content_type &= ~CT_TABOO;
2503       }
2504       else
2505       {
2506          /*
2507           * Unset content types to remember not to
2508           * modify the Content-Encoding header later.
2509           */
2510          csp->content_type &= ~CT_GZIP;
2511          csp->content_type &= ~CT_DEFLATE;
2512 #ifdef FEATURE_BROTLI
2513          csp->content_type &= ~CT_BROTLI;
2514 #endif
2515       }
2516    }
2517 #endif
2518
2519    return err;
2520 }
2521
2522
2523 /*********************************************************************
2524  *
2525  * Function    :  execute_content_filters
2526  *
2527  * Description :  Executes a given content filter.
2528  *
2529  * Parameters  :
2530  *          1  :  csp = Current client state (buffers, headers, etc...)
2531  *
2532  * Returns     :  Pointer to the modified buffer, or
2533  *                NULL if filtering failed or wasn't necessary.
2534  *
2535  *********************************************************************/
2536 char *execute_content_filters(struct client_state *csp)
2537 {
2538    char *content;
2539    filter_function_ptr content_filter;
2540
2541    assert(content_filters_enabled(csp->action));
2542
2543    if (0 == csp->iob->eod - csp->iob->cur)
2544    {
2545       /*
2546        * No content (probably status code 301, 302 ...),
2547        * no filtering necessary.
2548        */
2549       return NULL;
2550    }
2551
2552    if (JB_ERR_OK != prepare_for_filtering(csp))
2553    {
2554       /*
2555        * We failed to de-chunk or decompress, don't accept
2556        * another request on the client connection.
2557        */
2558       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2559       return NULL;
2560    }
2561
2562    if (0 == csp->iob->eod - csp->iob->cur)
2563    {
2564       /*
2565        * Clown alarm: chunked and/or compressed nothing delivered.
2566        */
2567       return NULL;
2568    }
2569
2570    content_filter = get_filter_function(csp);
2571    content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
2572
2573 #ifdef FEATURE_EXTERNAL_FILTERS
2574    if ((csp->content_type & CT_TEXT) &&
2575        !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
2576    {
2577       struct list_entry *filtername;
2578       size_t size = (size_t)csp->content_length;
2579
2580       if (content == NULL)
2581       {
2582          content = csp->iob->cur;
2583          size = (size_t)(csp->iob->eod - csp->iob->cur);
2584       }
2585
2586       for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
2587            filtername ; filtername = filtername->next)
2588       {
2589          char *result = execute_external_filter(csp, filtername->str, content, &size);
2590          if (result != NULL)
2591          {
2592             if (content != csp->iob->cur)
2593             {
2594                free(content);
2595             }
2596             content = result;
2597          }
2598       }
2599       csp->flags |= CSP_FLAG_MODIFIED;
2600       csp->content_length = size;
2601    }
2602 #endif /* def FEATURE_EXTERNAL_FILTERS */
2603
2604    return content;
2605
2606 }
2607
2608
2609 /*********************************************************************
2610  *
2611  * Function    :  execute_client_body_filters
2612  *
2613  * Description :  Executes client body filters for the request that is buffered
2614  *                in the client_iob. The client_iob is updated with the filtered
2615  *                content.
2616  *
2617  * Parameters  :
2618  *          1  :  csp = Current client state (buffers, headers, etc...)
2619  *          2  :  content_length = content length. Upon successful filtering
2620  *                the passed value is updated with the new content length.
2621  *
2622  * Returns     :  1 if the content has been filterd. 0 if it hasn't.
2623  *
2624  *********************************************************************/
2625 int execute_client_body_filters(struct client_state *csp, size_t *content_length)
2626 {
2627    char *filtered_content;
2628
2629    assert(client_body_filters_enabled(csp->action));
2630
2631    if (content_length == 0)
2632    {
2633       /*
2634        * No content, no filtering necessary.
2635        */
2636       return 0;
2637    }
2638
2639    filtered_content = pcrs_filter_request_body(csp, csp->client_iob->cur, content_length);
2640    if (filtered_content != NULL)
2641    {
2642       freez(csp->client_iob->buf);
2643       csp->client_iob->buf  = filtered_content;
2644       csp->client_iob->cur  = csp->client_iob->buf;
2645       csp->client_iob->eod  = csp->client_iob->cur + *content_length;
2646       csp->client_iob->size = *content_length;
2647
2648       return 1;
2649    }
2650    
2651    return 0;
2652 }
2653
2654
2655 /*********************************************************************
2656  *
2657  * Function    :  execute_client_body_taggers
2658  *
2659  * Description :  Executes client body taggers for the request that is
2660  *                buffered in the client_iob.
2661  *                XXX: Lots of code shared with header_tagger
2662  *
2663  * Parameters  :
2664  *          1  :  csp = Current client state (buffers, headers, etc...)
2665  *          2  :  content_length = content length.
2666  *
2667  * Returns     :  XXX
2668  *
2669  *********************************************************************/
2670 jb_err execute_client_body_taggers(struct client_state *csp, size_t content_length)
2671 {
2672    enum filter_type wanted_filter_type = FT_CLIENT_BODY_TAGGER;
2673    int multi_action_index = ACTION_MULTI_CLIENT_BODY_TAGGER;
2674    pcrs_job *job;
2675
2676    struct re_filterfile_spec *b;
2677    struct list_entry *tag_name;
2678
2679    assert(client_body_taggers_enabled(csp->action));
2680
2681    if (content_length == 0)
2682    {
2683       /*
2684        * No content, no tagging necessary.
2685        */
2686       return JB_ERR_OK;
2687    }
2688
2689    log_error(LOG_LEVEL_INFO, "Got to execute tagger on %N",
2690       content_length, csp->client_iob->cur);
2691
2692    if (list_is_empty(csp->action->multi[multi_action_index])
2693       || filters_available(csp) == FALSE)
2694    {
2695       /* Return early if no taggers apply or if none are available. */
2696       return JB_ERR_OK;
2697    }
2698
2699    /* Execute all applying taggers */
2700    for (tag_name = csp->action->multi[multi_action_index]->first;
2701         NULL != tag_name; tag_name = tag_name->next)
2702    {
2703       char *modified_tag = NULL;
2704       char *tag = csp->client_iob->cur;
2705       size_t size = content_length;
2706       pcrs_job *joblist;
2707
2708       b = get_filter(csp, tag_name->str, wanted_filter_type);
2709       if (b == NULL)
2710       {
2711          continue;
2712       }
2713
2714       joblist = b->joblist;
2715
2716       if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2717
2718       if (NULL == joblist)
2719       {
2720          log_error(LOG_LEVEL_TAGGING,
2721             "Tagger %s has empty joblist. Nothing to do.", b->name);
2722          continue;
2723       }
2724
2725       /* execute their pcrs_joblist on the body. */
2726       for (job = joblist; NULL != job; job = job->next)
2727       {
2728          const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2729
2730          if (0 < hits)
2731          {
2732             /* Success, continue with the modified version. */
2733             if (tag != csp->client_iob->cur)
2734             {
2735                freez(tag);
2736             }
2737             tag = modified_tag;
2738          }
2739          else
2740          {
2741             /* Tagger doesn't match */
2742             if (0 > hits)
2743             {
2744                /* Regex failure, log it but continue anyway. */
2745                log_error(LOG_LEVEL_ERROR,
2746                   "Problems with tagger \'%s\': %s",
2747                   b->name, pcrs_strerror(hits));
2748             }
2749             freez(modified_tag);
2750          }
2751       }
2752
2753       if (b->dynamic) pcrs_free_joblist(joblist);
2754
2755       /* If this tagger matched */
2756       if (tag != csp->client_iob->cur)
2757       {
2758          if (0 == size)
2759          {
2760             /*
2761              * There is no technical limitation which makes
2762              * it impossible to use empty tags, but I assume
2763              * no one would do it intentionally.
2764              */
2765             freez(tag);
2766             log_error(LOG_LEVEL_TAGGING,
2767                "Tagger \'%s\' created an empty tag. Ignored.", b->name);
2768             continue;
2769          }
2770
2771          if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
2772          {
2773             log_error(LOG_LEVEL_TAGGING,
2774                "Tagger \'%s\' didn't add tag \'%s\': suppressed",
2775                b->name, tag);
2776             freez(tag);
2777             continue;
2778          }
2779
2780          if (!list_contains_item(csp->tags, tag))
2781          {
2782             if (JB_ERR_OK != enlist(csp->tags, tag))
2783             {
2784                log_error(LOG_LEVEL_ERROR,
2785                   "Insufficient memory to add tag \'%s\', "
2786                   "based on tagger \'%s\'",
2787                   tag, b->name);
2788             }
2789             else
2790             {
2791                char *action_message;
2792                /*
2793                 * update the action bits right away, to make
2794                 * tagging based on tags set by earlier taggers
2795                 * of the same kind possible.
2796                 */
2797                if (update_action_bits_for_tag(csp, tag))
2798                {
2799                   action_message = "Action bits updated accordingly.";
2800                }
2801                else
2802                {
2803                   action_message = "No action bits update necessary.";
2804                }
2805
2806                log_error(LOG_LEVEL_TAGGING,
2807                   "Tagger \'%s\' added tag \'%s\'. %s",
2808                   b->name, tag, action_message);
2809             }
2810          }
2811          else
2812          {
2813             /* XXX: Is this log-worthy? */
2814             log_error(LOG_LEVEL_TAGGING,
2815                "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
2816                b->name, tag);
2817          }
2818          freez(tag);
2819       }
2820    }
2821
2822    return JB_ERR_OK;
2823 }
2824
2825
2826 /*********************************************************************
2827  *
2828  * Function    :  get_url_actions
2829  *
2830  * Description :  Gets the actions for this URL.
2831  *
2832  * Parameters  :
2833  *          1  :  csp = Current client state (buffers, headers, etc...)
2834  *          2  :  http = http_request request for blocked URLs
2835  *
2836  * Returns     :  N/A
2837  *
2838  *********************************************************************/
2839 void get_url_actions(struct client_state *csp, struct http_request *http)
2840 {
2841    struct file_list *fl;
2842    struct url_actions *b;
2843    int i;
2844
2845    init_current_action(csp->action);
2846
2847    for (i = 0; i < MAX_AF_FILES; i++)
2848    {
2849       if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2850       {
2851          return;
2852       }
2853
2854 #ifdef FEATURE_CLIENT_TAGS
2855       apply_url_actions(csp->action, http, csp->client_tags, b);
2856 #else
2857       apply_url_actions(csp->action, http, b);
2858 #endif
2859    }
2860
2861    return;
2862 }
2863
2864 /*********************************************************************
2865  *
2866  * Function    :  apply_url_actions
2867  *
2868  * Description :  Applies a list of URL actions.
2869  *
2870  * Parameters  :
2871  *          1  :  action = Destination.
2872  *          2  :  http = Current URL
2873  *          3  :  client_tags = list of client tags
2874  *          4  :  b = list of URL actions to apply
2875  *
2876  * Returns     :  N/A
2877  *
2878  *********************************************************************/
2879 static void apply_url_actions(struct current_action_spec *action,
2880                               struct http_request *http,
2881 #ifdef FEATURE_CLIENT_TAGS
2882                               const struct list *client_tags,
2883 #endif
2884                               struct url_actions *b)
2885 {
2886    if (b == NULL)
2887    {
2888       /* Should never happen */
2889       return;
2890    }
2891
2892    for (b = b->next; NULL != b; b = b->next)
2893    {
2894       if (url_match(b->url, http))
2895       {
2896          merge_current_action(action, b->action);
2897       }
2898 #ifdef FEATURE_CLIENT_TAGS
2899       if (client_tag_match(b->url, client_tags))
2900       {
2901          merge_current_action(action, b->action);
2902       }
2903 #endif
2904    }
2905 }
2906
2907
2908 /*********************************************************************
2909  *
2910  * Function    :  get_forward_override_settings
2911  *
2912  * Description :  Returns forward settings as specified with the
2913  *                forward-override{} action. forward-override accepts
2914  *                forward lines similar to the one used in the
2915  *                configuration file, but without the URL pattern.
2916  *
2917  *                For example:
2918  *
2919  *                   forward / .
2920  *
2921  *                in the configuration file can be replaced with
2922  *                the action section:
2923  *
2924  *                 {+forward-override{forward .}}
2925  *                 /
2926  *
2927  * Parameters  :
2928  *          1  :  csp = Current client state (buffers, headers, etc...)
2929  *
2930  * Returns     :  Pointer to forwarding structure in case of success.
2931  *                Invalid syntax is fatal.
2932  *
2933  *********************************************************************/
2934 static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
2935 {
2936    const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2937    char forward_settings[BUFFER_SIZE];
2938    char *http_parent = NULL;
2939    /* variable names were chosen for consistency reasons. */
2940    struct forward_spec *fwd = NULL;
2941    int vec_count;
2942    char *vec[3];
2943
2944    assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2945    /* Should be enforced by load_one_actions_file() */
2946    assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2947
2948    /* Create a copy ssplit can modify */
2949    strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2950
2951    if (NULL != csp->fwd)
2952    {
2953       /*
2954        * XXX: Currently necessary to prevent memory
2955        * leaks when the show-url-info cgi page is visited.
2956        */
2957       unload_forward_spec(csp->fwd);
2958    }
2959
2960    /*
2961     * allocate a new forward node, valid only for
2962     * the lifetime of this request. Save its location
2963     * in csp as well, so sweep() can free it later on.
2964     */
2965    fwd = csp->fwd = zalloc_or_die(sizeof(*fwd));
2966
2967    vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
2968    if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2969    {
2970       fwd->type = SOCKS_NONE;
2971
2972       /* Parse the parent HTTP proxy host:port */
2973       http_parent = vec[1];
2974
2975    }
2976    else if ((vec_count == 2) && !strcasecmp(vec[0], "forward-webserver"))
2977    {
2978       fwd->type = FORWARD_WEBSERVER;
2979
2980       /* Parse the parent HTTP server host:port */
2981       http_parent = vec[1];
2982
2983    }
2984    else if (vec_count == 3)
2985    {
2986       char *socks_proxy = NULL;
2987
2988       if  (!strcasecmp(vec[0], "forward-socks4"))
2989       {
2990          fwd->type = SOCKS_4;
2991          socks_proxy = vec[1];
2992       }
2993       else if (!strcasecmp(vec[0], "forward-socks4a"))
2994       {
2995          fwd->type = SOCKS_4A;
2996          socks_proxy = vec[1];
2997       }
2998       else if (!strcasecmp(vec[0], "forward-socks5"))
2999       {
3000          fwd->type = SOCKS_5;
3001          socks_proxy = vec[1];
3002       }
3003       else if (!strcasecmp(vec[0], "forward-socks5t"))
3004       {
3005          fwd->type = SOCKS_5T;
3006          socks_proxy = vec[1];
3007       }
3008
3009       if (NULL != socks_proxy)
3010       {
3011          /* Parse the SOCKS proxy [user:pass@]host[:port] */
3012          fwd->gateway_port = 1080;
3013          parse_forwarder_address(socks_proxy,
3014             &fwd->gateway_host, &fwd->gateway_port,
3015             &fwd->auth_username, &fwd->auth_password);
3016
3017          http_parent = vec[2];
3018       }
3019    }
3020
3021    if (NULL == http_parent)
3022    {
3023       log_error(LOG_LEVEL_FATAL,
3024          "Invalid forward-override syntax in: %s", forward_override_line);
3025       /* Never get here - LOG_LEVEL_FATAL causes program exit */
3026    }
3027
3028    /* Parse http forwarding settings */
3029    if (strcmp(http_parent, ".") != 0)
3030    {
3031       fwd->forward_port = 8000;
3032       parse_forwarder_address(http_parent,
3033          &fwd->forward_host, &fwd->forward_port,
3034          NULL, NULL);
3035    }
3036
3037    assert (NULL != fwd);
3038
3039    log_error(LOG_LEVEL_CONNECT,
3040       "Overriding forwarding settings based on \'%s\'", forward_override_line);
3041
3042    return fwd;
3043 }
3044
3045
3046 /*********************************************************************
3047  *
3048  * Function    :  forward_url
3049  *
3050  * Description :  Should we forward this to another proxy?
3051  *
3052  * Parameters  :
3053  *          1  :  csp = Current client state (buffers, headers, etc...)
3054  *          2  :  http = http_request request for current URL
3055  *
3056  * Returns     :  Pointer to forwarding information.
3057  *
3058  *********************************************************************/
3059 const struct forward_spec *forward_url(struct client_state *csp,
3060                                        const struct http_request *http)
3061 {
3062    static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
3063    struct forward_spec *fwd = csp->config->forward;
3064
3065    if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
3066    {
3067       return get_forward_override_settings(csp);
3068    }
3069
3070    if (fwd == NULL)
3071    {
3072       return fwd_default;
3073    }
3074
3075    while (fwd != NULL)
3076    {
3077       if (url_match(fwd->url, http))
3078       {
3079          return fwd;
3080       }
3081       fwd = fwd->next;
3082    }
3083
3084    return fwd_default;
3085 }
3086
3087
3088 /*********************************************************************
3089  *
3090  * Function    :  direct_response
3091  *
3092  * Description :  Check if Max-Forwards == 0 for an OPTIONS or TRACE
3093  *                request and if so, return a HTTP 501 to the client.
3094  *
3095  *                FIXME: I have a stupid name and I should handle the
3096  *                requests properly. Still, what we do here is rfc-
3097  *                compliant, whereas ignoring or forwarding are not.
3098  *
3099  * Parameters  :
3100  *          1  :  csp = Current client state (buffers, headers, etc...)
3101  *
3102  * Returns     :  http_response if , NULL if nonmatch or handler fail
3103  *
3104  *********************************************************************/
3105 struct http_response *direct_response(struct client_state *csp)
3106 {
3107    struct http_response *rsp;
3108    struct list_entry *p;
3109
3110    if ((0 == strcmpic(csp->http->gpc, "trace"))
3111       || (0 == strcmpic(csp->http->gpc, "options")))
3112    {
3113       for (p = csp->headers->first; (p != NULL) ; p = p->next)
3114       {
3115          if (!strncmpic(p->str, "Max-Forwards:", 13))
3116          {
3117             unsigned int max_forwards;
3118
3119             /*
3120              * If it's a Max-Forwards value of zero,
3121              * we have to intercept the request.
3122              */
3123             if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
3124             {
3125                /*
3126                 * FIXME: We could handle at least TRACE here,
3127                 * but that would require a verbatim copy of
3128                 * the request which we don't have anymore
3129                 */
3130                 log_error(LOG_LEVEL_HEADER,
3131                   "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
3132                   p->str);
3133
3134                /* Get mem for response or fail*/
3135                if (NULL == (rsp = alloc_http_response()))
3136                {
3137                   return cgi_error_memory();
3138                }
3139
3140                rsp->status = strdup_or_die("501 Not Implemented");
3141                rsp->is_static = 1;
3142                rsp->crunch_reason = UNSUPPORTED;
3143
3144                return(finish_http_response(csp, rsp));
3145             }
3146          }
3147       }
3148    }
3149    return NULL;
3150 }
3151
3152
3153 /*********************************************************************
3154  *
3155  * Function    :  content_requires_filtering
3156  *
3157  * Description :  Checks whether there are any content filters
3158  *                enabled for the current request and if they
3159  *                can actually be applied..
3160  *
3161  * Parameters  :
3162  *          1  :  csp = Current client state (buffers, headers, etc...)
3163  *
3164  * Returns     :  TRUE for yes, FALSE otherwise
3165  *
3166  *********************************************************************/
3167 int content_requires_filtering(struct client_state *csp)
3168 {
3169    if ((csp->content_type & CT_TABOO)
3170       && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
3171    {
3172       return FALSE;
3173    }
3174
3175    /*
3176     * Are we enabling text mode by force?
3177     */
3178    if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3179    {
3180       /*
3181        * Do we really have to?
3182        */
3183       if (csp->content_type & CT_TEXT)
3184       {
3185          log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
3186       }
3187       else
3188       {
3189          csp->content_type |= CT_TEXT;
3190          log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
3191       }
3192    }
3193
3194    if (!(csp->content_type & CT_DECLARED))
3195    {
3196       /*
3197        * The server didn't bother to declare a MIME-Type.
3198        * Assume it's text that can be filtered.
3199        *
3200        * This also regularly happens with 304 responses,
3201        * therefore logging anything here would cause
3202        * too much noise.
3203        */
3204       csp->content_type |= CT_TEXT;
3205    }
3206
3207    /*
3208     * Choose the applying filter function based on
3209     * the content type and action settings.
3210     */
3211    if ((csp->content_type & CT_TEXT) &&
3212        (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
3213         !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
3214    {
3215       return TRUE;
3216    }
3217    else if ((csp->content_type & CT_GIF)  &&
3218             (csp->action->flags & ACTION_DEANIMATE))
3219    {
3220       return TRUE;
3221    }
3222
3223    return FALSE;
3224
3225 }
3226
3227
3228 /*********************************************************************
3229  *
3230  * Function    :  content_filters_enabled
3231  *
3232  * Description :  Checks whether there are any content filters
3233  *                enabled for the current request.
3234  *
3235  * Parameters  :
3236  *          1  :  action = Action spec to check.
3237  *
3238  * Returns     :  TRUE for yes, FALSE otherwise
3239  *
3240  *********************************************************************/
3241 int content_filters_enabled(const struct current_action_spec *action)
3242 {
3243    return ((action->flags & ACTION_DEANIMATE) ||
3244       !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
3245       !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
3246 }
3247
3248
3249 /*********************************************************************
3250  *
3251  * Function    :  client_body_filters_enabled
3252  *
3253  * Description :  Checks whether there are any client body filters
3254  *                enabled for the current request.
3255  *
3256  * Parameters  :
3257  *          1  :  action = Action spec to check.
3258  *
3259  * Returns     :  TRUE for yes, FALSE otherwise
3260  *
3261  *********************************************************************/
3262 int client_body_filters_enabled(const struct current_action_spec *action)
3263 {
3264    return !list_is_empty(action->multi[ACTION_MULTI_CLIENT_BODY_FILTER]);
3265 }
3266
3267
3268 /*********************************************************************
3269  *
3270  * Function    :  client_body_taggers_enabled
3271  *
3272  * Description :  Checks whether there are any client body taggers
3273  *                enabled for the current request.
3274  *
3275  * Parameters  :
3276  *          1  :  action = Action spec to check.
3277  *
3278  * Returns     :  TRUE for yes, FALSE otherwise
3279  *
3280  *********************************************************************/
3281 int client_body_taggers_enabled(const struct current_action_spec *action)
3282 {
3283    return !list_is_empty(action->multi[ACTION_MULTI_CLIENT_BODY_TAGGER]);
3284 }
3285
3286 /*********************************************************************
3287  *
3288  * Function    :  filters_available
3289  *
3290  * Description :  Checks whether there are any filters available.
3291  *
3292  * Parameters  :
3293  *          1  :  csp = Current client state (buffers, headers, etc...)
3294  *
3295  * Returns     :  TRUE for yes, FALSE otherwise.
3296  *
3297  *********************************************************************/
3298 int filters_available(const struct client_state *csp)
3299 {
3300    int i;
3301    for (i = 0; i < MAX_AF_FILES; i++)
3302    {
3303       const struct file_list *fl = csp->rlist[i];
3304       if ((NULL != fl) && (NULL != fl->f))
3305       {
3306          return TRUE;
3307       }
3308    }
3309    return FALSE;
3310 }
3311
3312 #ifdef FEATURE_EXTENDED_STATISTICS
3313
3314 struct filter_statistics_entry
3315 {
3316    char *filter;
3317    unsigned long long executions;
3318    unsigned long long response_bodies_modified;
3319    unsigned long long hits;
3320
3321    struct filter_statistics_entry *next;
3322 };
3323
3324 static struct filter_statistics_entry *filter_statistics = NULL;
3325
3326
3327 /*********************************************************************
3328  *
3329  * Function    :  register_filter_for_statistics
3330  *
3331  * Description :  Registers a filter so we can gather statistics for
3332  *                it unless the filter has already been registered
3333  *                before.
3334  *
3335  * Parameters  :
3336  *          1  :  filter = Name of the filter to register
3337  *
3338  * Returns     :  void
3339  *
3340  *********************************************************************/
3341 void register_filter_for_statistics(const char *filter)
3342 {
3343    struct filter_statistics_entry *entry;
3344
3345    privoxy_mutex_lock(&filter_statistics_mutex);
3346
3347    if (filter_statistics == NULL)
3348    {
3349       filter_statistics = zalloc_or_die(sizeof(struct filter_statistics_entry));
3350       entry = filter_statistics;
3351       entry->filter = strdup_or_die(filter);
3352       privoxy_mutex_unlock(&filter_statistics_mutex);
3353       return;
3354    }
3355    entry = filter_statistics;
3356    while (entry != NULL)
3357    {
3358       if (!strcmp(entry->filter, filter))
3359       {
3360          /* Already registered, nothing to do. */
3361          break;
3362       }
3363       if (entry->next == NULL)
3364       {
3365          entry->next = zalloc_or_die(sizeof(struct filter_statistics_entry));
3366          entry->next->filter = strdup_or_die(filter);
3367          break;
3368       }
3369       entry = entry->next;
3370    }
3371
3372    privoxy_mutex_unlock(&filter_statistics_mutex);
3373
3374 }
3375
3376
3377 /*********************************************************************
3378  *
3379  * Function    :  update_filter_statistics
3380  *
3381  * Description :  Updates the statistics for a filter.
3382  *
3383  * Parameters  :
3384  *          1  :  filter = Name of the filter to update
3385  *          2  :  hits = Hit count.
3386  *
3387  * Returns     :  void
3388  *
3389  *********************************************************************/
3390 void update_filter_statistics(const char *filter, int hits)
3391 {
3392    struct filter_statistics_entry *entry;
3393
3394    privoxy_mutex_lock(&filter_statistics_mutex);
3395
3396    entry = filter_statistics;
3397    while (entry != NULL)
3398    {
3399       if (!strcmp(entry->filter, filter))
3400       {
3401          entry->executions++;
3402          if (hits != 0)
3403          {
3404             entry->response_bodies_modified++;
3405             entry->hits += (unsigned)hits;
3406          }
3407          break;
3408       }
3409       entry = entry->next;
3410    }
3411
3412    privoxy_mutex_unlock(&filter_statistics_mutex);
3413
3414 }
3415
3416
3417 /*********************************************************************
3418  *
3419  * Function    :  get_filter_statistics
3420  *
3421  * Description :  Gets the statistics for a filter.
3422  *
3423  * Parameters  :
3424  *          1  :  filter = Name of the filter to get statistics for.
3425  *          2  :  executions = Storage for the execution count.
3426  *          3  :  response_bodies_modified = Storage for the number
3427  *                of modified response bodies.
3428  *          4  :  hits = Storage for the number of hits.
3429  *
3430  * Returns     :  void
3431  *
3432  *********************************************************************/
3433 void get_filter_statistics(const char *filter, unsigned long long *executions,
3434                            unsigned long long *response_bodies_modified,
3435                            unsigned long long *hits)
3436 {
3437    struct filter_statistics_entry *entry;
3438
3439    privoxy_mutex_lock(&filter_statistics_mutex);
3440
3441    entry = filter_statistics;
3442    while (entry != NULL)
3443    {
3444       if (!strcmp(entry->filter, filter))
3445       {
3446          *executions = entry->executions;
3447          *response_bodies_modified = entry->response_bodies_modified;
3448          *hits = entry->hits;
3449          break;
3450       }
3451       entry = entry->next;
3452    }
3453
3454    privoxy_mutex_unlock(&filter_statistics_mutex);
3455
3456 }
3457
3458
3459 struct block_statistics_entry
3460 {
3461    char *block_reason;
3462    unsigned long long count;
3463
3464    struct block_statistics_entry *next;
3465 };
3466
3467 static struct block_statistics_entry *block_statistics = NULL;
3468
3469 /*********************************************************************
3470  *
3471  * Function    :  register_block_reason_for_statistics
3472  *
3473  * Description :  Registers a block reason so we can gather statistics
3474  *                for it unless the block reason has already been
3475  *                registered before.
3476  *
3477  * Parameters  :
3478  *          1  :  block_reason = Block reason to register
3479  *
3480  * Returns     :  void
3481  *
3482  *********************************************************************/
3483 void register_block_reason_for_statistics(const char *block_reason)
3484 {
3485    struct block_statistics_entry *entry;
3486
3487    privoxy_mutex_lock(&block_reason_statistics_mutex);
3488
3489    if (block_statistics == NULL)
3490    {
3491       block_statistics = zalloc_or_die(sizeof(struct block_statistics_entry));
3492       entry = block_statistics;
3493       entry->block_reason = strdup_or_die(block_reason);
3494       privoxy_mutex_unlock(&block_reason_statistics_mutex);
3495       return;
3496    }
3497    entry = block_statistics;
3498    while (entry != NULL)
3499    {
3500       if (!strcmp(entry->block_reason, block_reason))
3501       {
3502          /* Already registered, nothing to do. */
3503          break;
3504       }
3505       if (entry->next == NULL)
3506       {
3507          entry->next = zalloc_or_die(sizeof(struct block_statistics_entry));
3508          entry->next->block_reason = strdup_or_die(block_reason);
3509          break;
3510       }
3511       entry = entry->next;
3512    }
3513
3514    privoxy_mutex_unlock(&block_reason_statistics_mutex);
3515
3516 }
3517
3518
3519 /*********************************************************************
3520  *
3521  * Function    :  increment_block_reason_counter
3522  *
3523  * Description :  Updates the counter for a block reason.
3524  *
3525  * Parameters  :
3526  *          1  :  block_reason = Block reason to count
3527  *
3528  * Returns     :  void
3529  *
3530  *********************************************************************/
3531 static void increment_block_reason_counter(const char *block_reason)
3532 {
3533    struct block_statistics_entry *entry;
3534
3535    privoxy_mutex_lock(&block_reason_statistics_mutex);
3536
3537    entry = block_statistics;
3538    while (entry != NULL)
3539    {
3540       if (!strcmp(entry->block_reason, block_reason))
3541       {
3542          entry->count++;
3543          break;
3544       }
3545       entry = entry->next;
3546    }
3547
3548    privoxy_mutex_unlock(&block_reason_statistics_mutex);
3549
3550 }
3551
3552
3553 /*********************************************************************
3554  *
3555  * Function    :  get_block_reason_count
3556  *
3557  * Description :  Gets number of times a block reason was used.
3558  *
3559  * Parameters  :
3560  *          1  :  block_reason = Block reason to get statistics for.
3561  *          2  :  count = Storage for the number of times the block
3562  *                        reason was used.
3563  *
3564  * Returns     :  void
3565  *
3566  *********************************************************************/
3567 void get_block_reason_count(const char *block_reason, unsigned long long *count)
3568 {
3569    struct block_statistics_entry *entry;
3570
3571    privoxy_mutex_lock(&block_reason_statistics_mutex);
3572
3573    entry = block_statistics;
3574    while (entry != NULL)
3575    {
3576       if (!strcmp(entry->block_reason, block_reason))
3577       {
3578          *count = entry->count;
3579          break;
3580       }
3581       entry = entry->next;
3582    }
3583
3584    privoxy_mutex_unlock(&block_reason_statistics_mutex);
3585
3586 }
3587
3588 #endif /* def FEATURE_EXTENDED_STATISTICS */
3589
3590 /*
3591   Local Variables:
3592   tab-width: 3
3593   end:
3594 */