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