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