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