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