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