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