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