Follow-up fixes for the previous white-space changes
[privoxy.git] / filters.c
1 const char filters_rcs[] = "$Id: filters.c,v 1.169 2012/03/09 16:24:36 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, "Out of memory while decoding URL: %s", new_url);
1113          freez(subject);
1114          return NULL;
1115       }
1116
1117       segments = ssplit(subject, "?&", url_segments, max_segments, 1, 1);
1118
1119       while (segments-- > 0)
1120       {
1121          char *dtoken = url_decode(url_segments[segments]);
1122          if (NULL == dtoken)
1123          {
1124             log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
1125             continue;
1126          }
1127          url_segment = strstr(dtoken, "http://");
1128          if (NULL == url_segment)
1129          {
1130             url_segment = strstr(dtoken, "https://");
1131          }
1132          if (NULL != url_segment)
1133          {
1134             url_segment = strdup(url_segment);
1135             freez(dtoken);
1136             if (url_segment == NULL)
1137             {
1138                log_error(LOG_LEVEL_ERROR,
1139                   "Out of memory while searching for redirects.");
1140                return NULL;
1141             }
1142             break;
1143          }
1144          freez(dtoken);
1145       }
1146       freez(subject);
1147       freez(url_segments);
1148
1149       if (url_segment == NULL)
1150       {
1151          return NULL;
1152       }
1153       subject = url_segment;
1154    }
1155    else
1156    {
1157       /* Look for a URL inside this one, without decoding anything. */
1158       log_error(LOG_LEVEL_REDIRECTS,
1159          "Checking \"%s\" for unencoded redirects.", subject);
1160    }
1161
1162    /*
1163     * Find the last URL encoded in the request
1164     */
1165    tmp = subject;
1166    while ((tmp = strstr(tmp, "http://")) != NULL)
1167    {
1168       new_url = tmp++;
1169    }
1170    tmp = (new_url != NULL) ? new_url : subject;
1171    while ((tmp = strstr(tmp, "https://")) != NULL)
1172    {
1173       new_url = tmp++;
1174    }
1175
1176    if ((new_url != NULL)
1177       && (  (new_url != subject)
1178          || (0 == strncmpic(subject, "http://", 7))
1179          || (0 == strncmpic(subject, "https://", 8))
1180          ))
1181    {
1182       /*
1183        * Return new URL if we found a redirect
1184        * or if the subject already was a URL.
1185        *
1186        * The second case makes sure that we can
1187        * chain get_last_url after another redirection check
1188        * (like rewrite_url) without losing earlier redirects.
1189        */
1190       new_url = strdup(new_url);
1191       freez(subject);
1192       return new_url;
1193    }
1194
1195    freez(subject);
1196    return NULL;
1197
1198 }
1199 #endif /* def FEATURE_FAST_REDIRECTS */
1200
1201
1202 /*********************************************************************
1203  *
1204  * Function    :  redirect_url
1205  *
1206  * Description :  Checks if Privoxy should answer the request with
1207  *                a HTTP redirect and generates the redirect if
1208  *                necessary.
1209  *
1210  * Parameters  :
1211  *          1  :  csp = Current client state (buffers, headers, etc...)
1212  *
1213  * Returns     :  NULL if the request can pass, HTTP redirect otherwise.
1214  *
1215  *********************************************************************/
1216 struct http_response *redirect_url(struct client_state *csp)
1217 {
1218    struct http_response *rsp;
1219 #ifdef FEATURE_FAST_REDIRECTS
1220    /*
1221     * XXX: Do we still need FEATURE_FAST_REDIRECTS
1222     * as compile-time option? The user can easily disable
1223     * it in his action file.
1224     */
1225    char * redirect_mode;
1226 #endif /* def FEATURE_FAST_REDIRECTS */
1227    char *old_url = NULL;
1228    char *new_url = NULL;
1229    char *redirection_string;
1230
1231    if ((csp->action->flags & ACTION_REDIRECT))
1232    {
1233       redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
1234
1235       /*
1236        * If the redirection string begins with 's',
1237        * assume it's a pcrs command, otherwise treat it as
1238        * properly formatted URL and use it for the redirection
1239        * directly.
1240        *
1241        * According to RFC 2616 section 14.30 the URL
1242        * has to be absolute and if the user tries:
1243        * +redirect{shit/this/will/be/parsed/as/pcrs_command.html}
1244        * she would get undefined results anyway.
1245        *
1246        */
1247
1248       if (*redirection_string == 's')
1249       {
1250          old_url = csp->http->url;
1251          new_url = rewrite_url(old_url, redirection_string);
1252       }
1253       else
1254       {
1255          log_error(LOG_LEVEL_REDIRECTS,
1256             "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
1257             redirection_string);
1258          new_url = strdup(redirection_string);
1259       }
1260    }
1261
1262 #ifdef FEATURE_FAST_REDIRECTS
1263    if ((csp->action->flags & ACTION_FAST_REDIRECTS))
1264    {
1265       redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
1266
1267       /*
1268        * If it exists, use the previously rewritten URL as input
1269        * otherwise just use the old path.
1270        */
1271       old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
1272       new_url = get_last_url(old_url, redirect_mode);
1273       freez(old_url);
1274    }
1275
1276    /*
1277     * Disable redirect checkers, so that they
1278     * will be only run more than once if the user
1279     * also enables them through tags.
1280     *
1281     * From a performance point of view
1282     * it doesn't matter, but the duplicated
1283     * log messages are annoying.
1284     */
1285    csp->action->flags &= ~ACTION_FAST_REDIRECTS;
1286 #endif /* def FEATURE_FAST_REDIRECTS */
1287    csp->action->flags &= ~ACTION_REDIRECT;
1288
1289    /* Did any redirect action trigger? */
1290    if (new_url)
1291    {
1292       if (url_requires_percent_encoding(new_url))
1293       {
1294          char *encoded_url;
1295          log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
1296             strlen(new_url), new_url);
1297          encoded_url = percent_encode_url(new_url);
1298          freez(new_url);
1299          if (encoded_url == NULL)
1300          {
1301             return cgi_error_memory();
1302          }
1303          new_url = encoded_url;
1304          assert(FALSE == url_requires_percent_encoding(new_url));
1305       }
1306
1307       if (0 == strcmpic(new_url, csp->http->url))
1308       {
1309          log_error(LOG_LEVEL_ERROR,
1310             "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
1311             csp->http->url, new_url);
1312             freez(new_url);
1313       }
1314       else
1315       {
1316          log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
1317
1318          if (NULL == (rsp = alloc_http_response()))
1319          {
1320             freez(new_url);
1321             return cgi_error_memory();
1322          }
1323
1324          if (enlist_unique_header(rsp->headers, "Location", new_url)
1325            || (NULL == (rsp->status = strdup("302 Local Redirect from Privoxy"))))
1326          {
1327             freez(new_url);
1328             free_http_response(rsp);
1329             return cgi_error_memory();
1330          }
1331          rsp->crunch_reason = REDIRECTED;
1332          freez(new_url);
1333
1334          return finish_http_response(csp, rsp);
1335       }
1336    }
1337
1338    /* Only reached if no redirect is required */
1339    return NULL;
1340
1341 }
1342
1343
1344 #ifdef FEATURE_IMAGE_BLOCKING
1345 /*********************************************************************
1346  *
1347  * Function    :  is_imageurl
1348  *
1349  * Description :  Given a URL, decide whether it is an image or not,
1350  *                using either the info from a previous +image action
1351  *                or, #ifdef FEATURE_IMAGE_DETECT_MSIE, and the browser
1352  *                is MSIE and not on a Mac, tell from the browser's accept
1353  *                header.
1354  *
1355  * Parameters  :
1356  *          1  :  csp = Current client state (buffers, headers, etc...)
1357  *
1358  * Returns     :  True (nonzero) if URL is an image, false (0)
1359  *                otherwise
1360  *
1361  *********************************************************************/
1362 int is_imageurl(const struct client_state *csp)
1363 {
1364 #ifdef FEATURE_IMAGE_DETECT_MSIE
1365    char *tmp;
1366
1367    tmp = get_header_value(csp->headers, "User-Agent:");
1368    if (tmp && strstr(tmp, "MSIE") && !strstr(tmp, "Mac_"))
1369    {
1370       tmp = get_header_value(csp->headers, "Accept:");
1371       if (tmp && strstr(tmp, "image/gif"))
1372       {
1373          /* Client will accept HTML.  If this seems counterintuitive,
1374           * blame Microsoft.
1375           */
1376          return(0);
1377       }
1378       else
1379       {
1380          return(1);
1381       }
1382    }
1383 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1384
1385    return ((csp->action->flags & ACTION_IMAGE) != 0);
1386
1387 }
1388 #endif /* def FEATURE_IMAGE_BLOCKING */
1389
1390
1391 #ifdef FEATURE_TRUST
1392 /*********************************************************************
1393  *
1394  * Function    :  is_untrusted_url
1395  *
1396  * Description :  Should we "distrust" this URL (and block it)?
1397  *
1398  *                Yes if it matches a line in the trustfile, or if the
1399  *                    referrer matches a line starting with "+" in the
1400  *                    trustfile.
1401  *                No  otherwise.
1402  *
1403  * Parameters  :
1404  *          1  :  csp = Current client state (buffers, headers, etc...)
1405  *
1406  * Returns     :  0 => trusted, 1 => untrusted
1407  *
1408  *********************************************************************/
1409 int is_untrusted_url(const struct client_state *csp)
1410 {
1411    struct file_list *fl;
1412    struct block_spec *b;
1413    struct url_spec **trusted_url;
1414    struct http_request rhttp[1];
1415    const char * referer;
1416    jb_err err;
1417
1418    /*
1419     * If we don't have a trustlist, we trust everybody
1420     */
1421    if (((fl = csp->tlist) == NULL) || ((b  = fl->f) == NULL))
1422    {
1423       return 0;
1424    }
1425
1426    memset(rhttp, '\0', sizeof(*rhttp));
1427
1428    /*
1429     * Do we trust the request URL itself?
1430     */
1431    for (b = b->next; b ; b = b->next)
1432    {
1433       if (url_match(b->url, csp->http))
1434       {
1435          return b->reject;
1436       }
1437    }
1438
1439    if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
1440    {
1441       /* no referrer was supplied */
1442       return 1;
1443    }
1444
1445
1446    /*
1447     * If not, do we maybe trust its referrer?
1448     */
1449    err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
1450    if (err)
1451    {
1452       return 1;
1453    }
1454
1455    for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1456    {
1457       if (url_match(*trusted_url, rhttp))
1458       {
1459          /* if the URL's referrer is from a trusted referrer, then
1460           * add the target spec to the trustfile as an unblocked
1461           * domain and return 0 (which means it's OK).
1462           */
1463
1464          FILE *fp;
1465
1466          if (NULL != (fp = fopen(csp->config->trustfile, "a")))
1467          {
1468             char * path;
1469             char * path_end;
1470             char * new_entry = strdup("~");
1471
1472             string_append(&new_entry, csp->http->hostport);
1473
1474             path = csp->http->path;
1475             if ( (path[0] == '/')
1476               && (path[1] == '~')
1477               && ((path_end = strchr(path + 2, '/')) != NULL))
1478             {
1479                /* since this path points into a user's home space
1480                 * be sure to include this spec in the trustfile.
1481                 */
1482                long path_len = path_end - path; /* save offset */
1483                path = strdup(path); /* Copy string */
1484                if (path != NULL)
1485                {
1486                   path_end = path + path_len; /* regenerate ptr to new buffer */
1487                   *(path_end + 1) = '\0'; /* Truncate path after '/' */
1488                }
1489                string_join(&new_entry, path);
1490             }
1491
1492             /*
1493              * Give a reason for generating this entry.
1494              */
1495             string_append(&new_entry, " # Trusted referrer was: ");
1496             string_append(&new_entry, referer);
1497
1498             if (new_entry != NULL)
1499             {
1500                if (-1 == fprintf(fp, "%s\n", new_entry))
1501                {
1502                   log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
1503                      new_entry, csp->config->trustfile);
1504                }
1505                freez(new_entry);
1506             }
1507             else
1508             {
1509                /* FIXME: No way to handle out-of memory, so mostly ignoring it */
1510                log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
1511             }
1512
1513             fclose(fp);
1514          }
1515          else
1516          {
1517             log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
1518                csp->http->hostport, csp->config->trustfile);
1519          }
1520          return 0;
1521       }
1522    }
1523
1524    return 1;
1525 }
1526 #endif /* def FEATURE_TRUST */
1527
1528
1529 /*********************************************************************
1530  *
1531  * Function    :  pcrs_filter_response
1532  *
1533  * Description :  Execute all text substitutions from all applying
1534  *                +filter actions on the text buffer that's been
1535  *                accumulated in csp->iob->buf.
1536  *
1537  * Parameters  :
1538  *          1  :  csp = Current client state (buffers, headers, etc...)
1539  *
1540  * Returns     :  a pointer to the (newly allocated) modified buffer.
1541  *                or NULL if there were no hits or something went wrong
1542  *
1543  *********************************************************************/
1544 static char *pcrs_filter_response(struct client_state *csp)
1545 {
1546    int hits = 0;
1547    int i;
1548    size_t size, prev_size;
1549
1550    char *old = NULL;
1551    char *new = NULL;
1552    pcrs_job *job;
1553
1554    struct file_list *fl;
1555    struct re_filterfile_spec *b;
1556    struct list_entry *filtername;
1557
1558    /*
1559     * Sanity first
1560     */
1561    if (csp->iob->cur >= csp->iob->eod)
1562    {
1563       return(NULL);
1564    }
1565
1566    if (filters_available(csp) == FALSE)
1567    {
1568       log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1569          "content filtering enabled, but no content filters available.");
1570       return(NULL);
1571    }
1572
1573    size = (size_t)(csp->iob->eod - csp->iob->cur);
1574    old = csp->iob->cur;
1575
1576    for (i = 0; i < MAX_AF_FILES; i++)
1577    {
1578      fl = csp->rlist[i];
1579      if ((NULL == fl) || (NULL == fl->f))
1580      {
1581         /*
1582          * Either there are no filter files
1583          * left, or this filter file just
1584          * contains no valid filters.
1585          *
1586          * Continue to be sure we don't miss
1587          * valid filter files that are chained
1588          * after empty or invalid ones.
1589          */
1590         continue;
1591      }
1592    /*
1593     * For all applying +filter actions, look if a filter by that
1594     * name exists and if yes, execute it's pcrs_joblist on the
1595     * buffer.
1596     */
1597    for (b = fl->f; b; b = b->next)
1598    {
1599       if (b->type != FT_CONTENT_FILTER)
1600       {
1601          /* Skip header filters */
1602          continue;
1603       }
1604
1605       for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1606            filtername ; filtername = filtername->next)
1607       {
1608          if (strcmp(b->name, filtername->str) == 0)
1609          {
1610             int current_hits = 0; /* Number of hits caused by this filter */
1611             int job_number   = 0; /* Which job we're currently executing  */
1612             int job_hits     = 0; /* How many hits the current job caused */
1613             pcrs_job *joblist = b->joblist;
1614
1615             if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1616
1617             if (NULL == joblist)
1618             {
1619                log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1620                continue;
1621             }
1622
1623             prev_size = size;
1624             /* Apply all jobs from the joblist */
1625             for (job = joblist; NULL != job; job = job->next)
1626             {
1627                job_number++;
1628                job_hits = pcrs_execute(job, old, size, &new, &size);
1629
1630                if (job_hits >= 0)
1631                {
1632                   /*
1633                    * That went well. Continue filtering
1634                    * and use the result of this job as
1635                    * input for the next one.
1636                    */
1637                   current_hits += job_hits;
1638                   if (old != csp->iob->cur)
1639                   {
1640                      freez(old);
1641                   }
1642                   old = new;
1643                }
1644                else
1645                {
1646                   /*
1647                    * This job caused an unexpected error. Inform the user
1648                    * and skip the rest of the jobs in this filter. We could
1649                    * continue with the next job, but usually the jobs
1650                    * depend on each other or are similar enough to
1651                    * fail for the same reason.
1652                    *
1653                    * At the moment our pcrs expects the error codes of pcre 3.4,
1654                    * but newer pcre versions can return additional error codes.
1655                    * As a result pcrs_strerror()'s error message might be
1656                    * "Unknown error ...", therefore we print the numerical value
1657                    * as well.
1658                    *
1659                    * XXX: Is this important enough for LOG_LEVEL_ERROR or
1660                    * should we use LOG_LEVEL_RE_FILTER instead?
1661                    */
1662                   log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
1663                      b->name, job_number, pcrs_strerror(job_hits), job_hits);
1664                   break;
1665                }
1666             }
1667
1668             if (b->dynamic) pcrs_free_joblist(joblist);
1669
1670             log_error(LOG_LEVEL_RE_FILTER,
1671                "filtering %s%s (size %d) with \'%s\' produced %d hits (new size %d).",
1672                csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
1673
1674             hits += current_hits;
1675          }
1676       }
1677    }
1678    }
1679
1680    /*
1681     * If there were no hits, destroy our copy and let
1682     * chat() use the original in csp->iob
1683     */
1684    if (!hits)
1685    {
1686       freez(new);
1687       return(NULL);
1688    }
1689
1690    csp->flags |= CSP_FLAG_MODIFIED;
1691    csp->content_length = size;
1692    IOB_RESET(csp);
1693
1694    return(new);
1695
1696 }
1697
1698
1699 /*********************************************************************
1700  *
1701  * Function    :  gif_deanimate_response
1702  *
1703  * Description :  Deanimate the GIF image that has been accumulated in
1704  *                csp->iob->buf, set csp->content_length to the modified
1705  *                size and raise the CSP_FLAG_MODIFIED flag.
1706  *
1707  * Parameters  :
1708  *          1  :  csp = Current client state (buffers, headers, etc...)
1709  *
1710  * Returns     :  a pointer to the (newly allocated) modified buffer.
1711  *                or NULL in case something went wrong.
1712  *
1713  *********************************************************************/
1714 static char *gif_deanimate_response(struct client_state *csp)
1715 {
1716    struct binbuffer *in, *out;
1717    char *p;
1718    size_t size;
1719
1720    size = (size_t)(csp->iob->eod - csp->iob->cur);
1721
1722    if (  (NULL == (in =  (struct binbuffer *)zalloc(sizeof *in )))
1723       || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1724    {
1725       log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1726       return NULL;
1727    }
1728
1729    in->buffer = csp->iob->cur;
1730    in->size = size;
1731
1732    if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1733    {
1734       log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1735       freez(in);
1736       buf_free(out);
1737       return(NULL);
1738    }
1739    else
1740    {
1741       if ((int)size == out->offset)
1742       {
1743          log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
1744       }
1745       else
1746       {
1747          log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1748       }
1749       csp->content_length = out->offset;
1750       csp->flags |= CSP_FLAG_MODIFIED;
1751       p = out->buffer;
1752       freez(in);
1753       freez(out);
1754       return(p);
1755    }
1756
1757 }
1758
1759
1760 /*********************************************************************
1761  *
1762  * Function    :  get_filter_function
1763  *
1764  * Description :  Decides which content filter function has
1765  *                to be applied (if any).
1766  *
1767  * Parameters  :
1768  *          1  :  csp = Current client state (buffers, headers, etc...)
1769  *
1770  * Returns     :  The content filter function to run, or
1771  *                NULL if no content filter is active
1772  *
1773  *********************************************************************/
1774 static filter_function_ptr get_filter_function(const struct client_state *csp)
1775 {
1776    filter_function_ptr filter_function = NULL;
1777
1778    /*
1779     * Choose the applying filter function based on
1780     * the content type and action settings.
1781     */
1782    if ((csp->content_type & CT_TEXT) &&
1783        (csp->rlist != NULL) &&
1784        (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1785    {
1786       filter_function = pcrs_filter_response;
1787    }
1788    else if ((csp->content_type & CT_GIF)  &&
1789             (csp->action->flags & ACTION_DEANIMATE))
1790    {
1791       filter_function = gif_deanimate_response;
1792    }
1793
1794    return filter_function;
1795 }
1796
1797
1798 /*********************************************************************
1799  *
1800  * Function    :  remove_chunked_transfer_coding
1801  *
1802  * Description :  In-situ remove the "chunked" transfer coding as defined
1803  *                in rfc2616 from a buffer.
1804  *
1805  * Parameters  :
1806  *          1  :  buffer = Pointer to the text buffer
1807  *          2  :  size =  In: Number of bytes to be processed,
1808  *                       Out: Number of bytes after de-chunking.
1809  *                       (undefined in case of errors)
1810  *
1811  * Returns     :  JB_ERR_OK for success,
1812  *                JB_ERR_PARSE otherwise
1813  *
1814  *********************************************************************/
1815 static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
1816 {
1817    size_t newsize = 0;
1818    unsigned int chunksize = 0;
1819    char *from_p, *to_p;
1820
1821    assert(buffer);
1822    from_p = to_p = buffer;
1823
1824    if (sscanf(buffer, "%x", &chunksize) != 1)
1825    {
1826       log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1827       return JB_ERR_PARSE;
1828    }
1829
1830    while (chunksize > 0U)
1831    {
1832       if (NULL == (from_p = strstr(from_p, "\r\n")))
1833       {
1834          log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1835          return JB_ERR_PARSE;
1836       }
1837
1838       if (chunksize >= *size - newsize)
1839       {
1840          log_error(LOG_LEVEL_ERROR,
1841             "Chunk size %u exceeds buffered data left. "
1842             "Already digested %u of %u buffered bytes.",
1843             chunksize, (unsigned int)newsize, (unsigned int)*size);
1844          return JB_ERR_PARSE;
1845       }
1846       newsize += chunksize;
1847       from_p += 2;
1848
1849       memmove(to_p, from_p, (size_t) chunksize);
1850       to_p = buffer + newsize;
1851       from_p += chunksize + 2;
1852
1853       if (sscanf(from_p, "%x", &chunksize) != 1)
1854       {
1855          log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
1856          break;
1857       }
1858    }
1859
1860    /* XXX: Should get its own loglevel. */
1861    log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d", *size, newsize);
1862
1863    *size = newsize;
1864
1865    return JB_ERR_OK;
1866
1867 }
1868
1869
1870 /*********************************************************************
1871  *
1872  * Function    :  prepare_for_filtering
1873  *
1874  * Description :  If necessary, de-chunks and decompresses
1875  *                the content so it can get filterd.
1876  *
1877  * Parameters  :
1878  *          1  :  csp = Current client state (buffers, headers, etc...)
1879  *
1880  * Returns     :  JB_ERR_OK for success,
1881  *                JB_ERR_PARSE otherwise
1882  *
1883  *********************************************************************/
1884 static jb_err prepare_for_filtering(struct client_state *csp)
1885 {
1886    jb_err err = JB_ERR_OK;
1887
1888    /*
1889     * If the body has a "chunked" transfer-encoding,
1890     * get rid of it, adjusting size and iob->eod
1891     */
1892    if (csp->flags & CSP_FLAG_CHUNKED)
1893    {
1894       size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1895
1896       log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1897       err = remove_chunked_transfer_coding(csp->iob->cur, &size);
1898       if (JB_ERR_OK == err)
1899       {
1900          csp->iob->eod = csp->iob->cur + size;
1901          csp->flags |= CSP_FLAG_MODIFIED;
1902       }
1903       else
1904       {
1905          return JB_ERR_PARSE;
1906       }
1907    }
1908
1909 #ifdef FEATURE_ZLIB
1910    /*
1911     * If the body has a supported transfer-encoding,
1912     * decompress it, adjusting size and iob->eod.
1913     */
1914    if (csp->content_type & (CT_GZIP|CT_DEFLATE))
1915    {
1916       if (0 == csp->iob->eod - csp->iob->cur)
1917       {
1918          /* Nothing left after de-chunking. */
1919          return JB_ERR_OK;
1920       }
1921
1922       err = decompress_iob(csp);
1923
1924       if (JB_ERR_OK == err)
1925       {
1926          csp->flags |= CSP_FLAG_MODIFIED;
1927          csp->content_type &= ~CT_TABOO;
1928       }
1929       else
1930       {
1931          /*
1932           * Unset CT_GZIP and CT_DEFLATE to remember not
1933           * to modify the Content-Encoding header later.
1934           */
1935          csp->content_type &= ~CT_GZIP;
1936          csp->content_type &= ~CT_DEFLATE;
1937       }
1938    }
1939 #endif
1940
1941    return err;
1942 }
1943
1944
1945 /*********************************************************************
1946  *
1947  * Function    :  execute_content_filters
1948  *
1949  * Description :  Executes a given content filter.
1950  *
1951  * Parameters  :
1952  *          1  :  csp = Current client state (buffers, headers, etc...)
1953  *
1954  * Returns     :  Pointer to the modified buffer, or
1955  *                NULL if filtering failed or wasn't necessary.
1956  *
1957  *********************************************************************/
1958 char *execute_content_filters(struct client_state *csp)
1959 {
1960    filter_function_ptr content_filter;
1961
1962    assert(content_filters_enabled(csp->action));
1963
1964    if (0 == csp->iob->eod - csp->iob->cur)
1965    {
1966       /*
1967        * No content (probably status code 301, 302 ...),
1968        * no filtering necessary.
1969        */
1970       return NULL;
1971    }
1972
1973    if (JB_ERR_OK != prepare_for_filtering(csp))
1974    {
1975       /*
1976        * failed to de-chunk or decompress.
1977        */
1978       return NULL;
1979    }
1980
1981    if (0 == csp->iob->eod - csp->iob->cur)
1982    {
1983       /*
1984        * Clown alarm: chunked and/or compressed nothing delivered.
1985        */
1986       return NULL;
1987    }
1988
1989    content_filter = get_filter_function(csp);
1990
1991    return ((*content_filter)(csp));
1992 }
1993
1994
1995 /*********************************************************************
1996  *
1997  * Function    :  get_url_actions
1998  *
1999  * Description :  Gets the actions for this URL.
2000  *
2001  * Parameters  :
2002  *          1  :  csp = Current client state (buffers, headers, etc...)
2003  *          2  :  http = http_request request for blocked URLs
2004  *
2005  * Returns     :  N/A
2006  *
2007  *********************************************************************/
2008 void get_url_actions(struct client_state *csp, struct http_request *http)
2009 {
2010    struct file_list *fl;
2011    struct url_actions *b;
2012    int i;
2013
2014    init_current_action(csp->action);
2015
2016    for (i = 0; i < MAX_AF_FILES; i++)
2017    {
2018       if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
2019       {
2020          return;
2021       }
2022
2023       apply_url_actions(csp->action, http, b);
2024    }
2025
2026    return;
2027 }
2028
2029
2030 /*********************************************************************
2031  *
2032  * Function    :  apply_url_actions
2033  *
2034  * Description :  Applies a list of URL actions.
2035  *
2036  * Parameters  :
2037  *          1  :  action = Destination.
2038  *          2  :  http = Current URL
2039  *          3  :  b = list of URL actions to apply
2040  *
2041  * Returns     :  N/A
2042  *
2043  *********************************************************************/
2044 void apply_url_actions(struct current_action_spec *action,
2045                        struct http_request *http,
2046                        struct url_actions *b)
2047 {
2048    if (b == NULL)
2049    {
2050       /* Should never happen */
2051       return;
2052    }
2053
2054    for (b = b->next; NULL != b; b = b->next)
2055    {
2056       if (url_match(b->url, http))
2057       {
2058          merge_current_action(action, b->action);
2059       }
2060    }
2061 }
2062
2063
2064 /*********************************************************************
2065  *
2066  * Function    :  get_forward_override_settings
2067  *
2068  * Description :  Returns forward settings as specified with the
2069  *                forward-override{} action. forward-override accepts
2070  *                forward lines similar to the one used in the
2071  *                configuration file, but without the URL pattern.
2072  *
2073  *                For example:
2074  *
2075  *                   forward / .
2076  *
2077  *                in the configuration file can be replaced with
2078  *                the action section:
2079  *
2080  *                 {+forward-override{forward .}}
2081  *                 /
2082  *
2083  * Parameters  :
2084  *          1  :  csp = Current client state (buffers, headers, etc...)
2085  *
2086  * Returns     :  Pointer to forwarding structure in case of success.
2087  *                Invalid syntax is fatal.
2088  *
2089  *********************************************************************/
2090 const static struct forward_spec *get_forward_override_settings(struct client_state *csp)
2091 {
2092    const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
2093    char forward_settings[BUFFER_SIZE];
2094    char *http_parent = NULL;
2095    /* variable names were chosen for consistency reasons. */
2096    struct forward_spec *fwd = NULL;
2097    int vec_count;
2098    char *vec[3];
2099
2100    assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
2101    /* Should be enforced by load_one_actions_file() */
2102    assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
2103
2104    /* Create a copy ssplit can modify */
2105    strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
2106
2107    if (NULL != csp->fwd)
2108    {
2109       /*
2110        * XXX: Currently necessary to prevent memory
2111        * leaks when the show-url-info cgi page is visited.
2112        */
2113       unload_forward_spec(csp->fwd);
2114    }
2115
2116    /*
2117     * allocate a new forward node, valid only for
2118     * the lifetime of this request. Save its location
2119     * in csp as well, so sweep() can free it later on.
2120     */
2121    fwd = csp->fwd = zalloc(sizeof(*fwd));
2122    if (NULL == fwd)
2123    {
2124       log_error(LOG_LEVEL_FATAL,
2125          "can't allocate memory for forward-override{%s}", forward_override_line);
2126       /* Never get here - LOG_LEVEL_FATAL causes program exit */
2127       return NULL;
2128    }
2129
2130    vec_count = ssplit(forward_settings, " \t", vec, SZ(vec), 1, 1);
2131    if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
2132    {
2133       fwd->type = SOCKS_NONE;
2134
2135       /* Parse the parent HTTP proxy host:port */
2136       http_parent = vec[1];
2137
2138    }
2139    else if (vec_count == 3)
2140    {
2141       char *socks_proxy = NULL;
2142
2143       if  (!strcasecmp(vec[0], "forward-socks4"))
2144       {
2145          fwd->type = SOCKS_4;
2146          socks_proxy = vec[1];
2147       }
2148       else if (!strcasecmp(vec[0], "forward-socks4a"))
2149       {
2150          fwd->type = SOCKS_4A;
2151          socks_proxy = vec[1];
2152       }
2153       else if (!strcasecmp(vec[0], "forward-socks5"))
2154       {
2155          fwd->type = SOCKS_5;
2156          socks_proxy = vec[1];
2157       }
2158
2159       if (NULL != socks_proxy)
2160       {
2161          /* Parse the SOCKS proxy host[:port] */
2162          fwd->gateway_port = 1080;
2163          parse_forwarder_address(socks_proxy,
2164             &fwd->gateway_host, &fwd->gateway_port);
2165
2166          http_parent = vec[2];
2167       }
2168    }
2169
2170    if (NULL == http_parent)
2171    {
2172       log_error(LOG_LEVEL_FATAL,
2173          "Invalid forward-override syntax in: %s", forward_override_line);
2174       /* Never get here - LOG_LEVEL_FATAL causes program exit */
2175    }
2176
2177    /* Parse http forwarding settings */
2178    if (strcmp(http_parent, ".") != 0)
2179    {
2180       fwd->forward_port = 8000;
2181       parse_forwarder_address(http_parent,
2182          &fwd->forward_host, &fwd->forward_port);
2183    }
2184
2185    assert (NULL != fwd);
2186
2187    log_error(LOG_LEVEL_CONNECT,
2188       "Overriding forwarding settings based on \'%s\'", forward_override_line);
2189
2190    return fwd;
2191 }
2192
2193
2194 /*********************************************************************
2195  *
2196  * Function    :  forward_url
2197  *
2198  * Description :  Should we forward this to another proxy?
2199  *
2200  * Parameters  :
2201  *          1  :  csp = Current client state (buffers, headers, etc...)
2202  *          2  :  http = http_request request for current URL
2203  *
2204  * Returns     :  Pointer to forwarding information.
2205  *
2206  *********************************************************************/
2207 const struct forward_spec *forward_url(struct client_state *csp,
2208                                        const struct http_request *http)
2209 {
2210    static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
2211    struct forward_spec *fwd = csp->config->forward;
2212
2213    if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
2214    {
2215       return get_forward_override_settings(csp);
2216    }
2217
2218    if (fwd == NULL)
2219    {
2220       return fwd_default;
2221    }
2222
2223    while (fwd != NULL)
2224    {
2225       if (url_match(fwd->url, http))
2226       {
2227          return fwd;
2228       }
2229       fwd = fwd->next;
2230    }
2231
2232    return fwd_default;
2233 }
2234
2235
2236 /*********************************************************************
2237  *
2238  * Function    :  direct_response
2239  *
2240  * Description :  Check if Max-Forwards == 0 for an OPTIONS or TRACE
2241  *                request and if so, return a HTTP 501 to the client.
2242  *
2243  *                FIXME: I have a stupid name and I should handle the
2244  *                requests properly. Still, what we do here is rfc-
2245  *                compliant, whereas ignoring or forwarding are not.
2246  *
2247  * Parameters  :
2248  *          1  :  csp = Current client state (buffers, headers, etc...)
2249  *
2250  * Returns     :  http_response if , NULL if nonmatch or handler fail
2251  *
2252  *********************************************************************/
2253 struct http_response *direct_response(struct client_state *csp)
2254 {
2255    struct http_response *rsp;
2256    struct list_entry *p;
2257
2258    if ((0 == strcmpic(csp->http->gpc, "trace"))
2259       || (0 == strcmpic(csp->http->gpc, "options")))
2260    {
2261       for (p = csp->headers->first; (p != NULL) ; p = p->next)
2262       {
2263          if (!strncmpic(p->str, "Max-Forwards:", 13))
2264          {
2265             unsigned int max_forwards;
2266
2267             /*
2268              * If it's a Max-Forwards value of zero,
2269              * we have to intercept the request.
2270              */
2271             if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
2272             {
2273                /*
2274                 * FIXME: We could handle at least TRACE here,
2275                 * but that would require a verbatim copy of
2276                 * the request which we don't have anymore
2277                 */
2278                 log_error(LOG_LEVEL_HEADER,
2279                   "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
2280                   p->str);
2281
2282                /* Get mem for response or fail*/
2283                if (NULL == (rsp = alloc_http_response()))
2284                {
2285                   return cgi_error_memory();
2286                }
2287
2288                if (NULL == (rsp->status = strdup("501 Not Implemented")))
2289                {
2290                   free_http_response(rsp);
2291                   return cgi_error_memory();
2292                }
2293
2294                rsp->is_static = 1;
2295                rsp->crunch_reason = UNSUPPORTED;
2296
2297                return(finish_http_response(csp, rsp));
2298             }
2299          }
2300       }
2301    }
2302    return NULL;
2303 }
2304
2305
2306 /*********************************************************************
2307  *
2308  * Function    :  content_requires_filtering
2309  *
2310  * Description :  Checks whether there are any content filters
2311  *                enabled for the current request and if they
2312  *                can actually be applied..
2313  *
2314  * Parameters  :
2315  *          1  :  csp = Current client state (buffers, headers, etc...)
2316  *
2317  * Returns     :  TRUE for yes, FALSE otherwise
2318  *
2319  *********************************************************************/
2320 int content_requires_filtering(struct client_state *csp)
2321 {
2322    if ((csp->content_type & CT_TABOO)
2323       && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
2324    {
2325       return FALSE;
2326    }
2327
2328    /*
2329     * Are we enabling text mode by force?
2330     */
2331    if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2332    {
2333       /*
2334        * Do we really have to?
2335        */
2336       if (csp->content_type & CT_TEXT)
2337       {
2338          log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2339       }
2340       else
2341       {
2342          csp->content_type |= CT_TEXT;
2343          log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2344       }
2345    }
2346
2347    if (!(csp->content_type & CT_DECLARED))
2348    {
2349       /*
2350        * The server didn't bother to declare a MIME-Type.
2351        * Assume it's text that can be filtered.
2352        *
2353        * This also regulary happens with 304 responses,
2354        * therefore logging anything here would cause
2355        * too much noise.
2356        */
2357       csp->content_type |= CT_TEXT;
2358    }
2359
2360    /*
2361     * Choose the applying filter function based on
2362     * the content type and action settings.
2363     */
2364    if ((csp->content_type & CT_TEXT) &&
2365        (csp->rlist != NULL) &&
2366        (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2367    {
2368       return TRUE;
2369    }
2370    else if ((csp->content_type & CT_GIF)  &&
2371             (csp->action->flags & ACTION_DEANIMATE))
2372    {
2373       return TRUE;
2374    }
2375
2376    return FALSE;
2377
2378 }
2379
2380
2381 /*********************************************************************
2382  *
2383  * Function    :  content_filters_enabled
2384  *
2385  * Description :  Checks whether there are any content filters
2386  *                enabled for the current request.
2387  *
2388  * Parameters  :
2389  *          1  :  action = Action spec to check.
2390  *
2391  * Returns     :  TRUE for yes, FALSE otherwise
2392  *
2393  *********************************************************************/
2394 int content_filters_enabled(const struct current_action_spec *action)
2395 {
2396    return ((action->flags & ACTION_DEANIMATE) ||
2397       !list_is_empty(action->multi[ACTION_MULTI_FILTER]));
2398 }
2399
2400
2401 /*********************************************************************
2402  *
2403  * Function    :  filters_available
2404  *
2405  * Description :  Checks whether there are any filters available.
2406  *
2407  * Parameters  :
2408  *          1  :  csp = Current client state (buffers, headers, etc...)
2409  *
2410  * Returns     :  TRUE for yes, FALSE otherwise.
2411  *
2412  *********************************************************************/
2413 int filters_available(const struct client_state *csp)
2414 {
2415    int i;
2416    for (i = 0; i < MAX_AF_FILES; i++)
2417    {
2418       const struct file_list *fl = csp->rlist[i];
2419       if ((NULL != fl) && (NULL != fl->f))
2420       {
2421          return TRUE;
2422       }
2423    }
2424    return FALSE;
2425 }
2426
2427
2428 /*
2429   Local Variables:
2430   tab-width: 3
2431   end:
2432 */