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