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