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