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