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