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