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