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