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