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