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