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