Replacing strsav() with the safer string_append() or string_join().
[privoxy.git] / filters.c
1 const char filters_rcs[] = "$Id: filters.c,v 1.41 2001/11/13 00:14:07 jongfoster Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/filters.c,v $
5  *
6  * Purpose     :  Declares functions to parse/crunch headers and pages.
7  *                Functions declared include:
8  *                   `acl_addr', `add_stats', `block_acl', `block_imageurl',
9  *                   `block_url', `url_actions', `domain_split',
10  *                   `filter_popups', `forward_url', 'redirect_url',
11  *                   `ij_untrusted_url', `intercept_url', `pcrs_filter_respose',
12  *                   'ijb_send_banner', and `trust_url'
13  *
14  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
15  *                IJBSWA team.  http://ijbswa.sourceforge.net
16  *
17  *                Based on the Internet Junkbuster originally written
18  *                by and Copyright (C) 1997 Anonymous Coders and
19  *                Junkbusters Corporation.  http://www.junkbusters.com
20  *
21  *                This program is free software; you can redistribute it
22  *                and/or modify it under the terms of the GNU General
23  *                Public License as published by the Free Software
24  *                Foundation; either version 2 of the License, or (at
25  *                your option) any later version.
26  *
27  *                This program is distributed in the hope that it will
28  *                be useful, but WITHOUT ANY WARRANTY; without even the
29  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
30  *                PARTICULAR PURPOSE.  See the GNU General Public
31  *                License for more details.
32  *
33  *                The GNU General Public License should be included with
34  *                this file.  If not, you can view it at
35  *                http://www.gnu.org/copyleft/gpl.html
36  *                or write to the Free Software Foundation, Inc., 59
37  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
38  *
39  * Revisions   :
40  *    $Log: filters.c,v $
41  *    Revision 1.41  2001/11/13 00:14:07  jongfoster
42  *    Fixing stupid bug now I've figured out what || means.
43  *    (It always returns 0 or 1, not one of it's paramaters.)
44  *
45  *    Revision 1.40  2001/10/26 17:37:55  oes
46  *    - Re-enabled Netscape 200/404 bug workaround in block_url():
47  *      - Removed OS/2 special case
48  *      - Made block_url() independant from sed() having been run
49  *    - Made trust_url independant from sed() having been run
50  *    - Made is_imageurl independant from sed() having been run.
51  *      It now checks User-Agent: and Accept: by itself.
52  *
53  *
54  *    Revision 1.39  2001/10/25 03:40:48  david__schmidt
55  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
56  *    threads to call select() simultaneously.  So, it's time to do a real, live,
57  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
58  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
59  *
60  *    Revision 1.38  2001/10/23 21:32:33  jongfoster
61  *    Adding error-checking to selected functions
62  *
63  *    Revision 1.37  2001/10/22 15:33:56  david__schmidt
64  *    Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
65  *    filters.c.  Added a FIXME in front of the offending code.  I'll gladly
66  *    put in a better/more robust fix for all parties if one is presented...
67  *    It seems that just returning 200 instead of 404 would pretty much fix
68  *    it for everyone, but I don't know all the history of the problem.
69  *
70  *    Revision 1.36  2001/10/10 16:44:16  oes
71  *    Added match_portlist function
72  *
73  *    Revision 1.35  2001/10/07 15:41:23  oes
74  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
75  *
76  *    New function remove_chunked_transfer_coding that strips chunked
77  *      transfer coding to plain and is called by pcrs_filter_response
78  *      and gif_deanimate_response if neccessary
79  *
80  *    Improved handling of zero-change re_filter runs
81  *
82  *    pcrs_filter_response and gif_deanimate_response now remove
83  *      chunked transfer codeing before processing the body.
84  *
85  *    Revision 1.34  2001/09/20 15:49:36  steudten
86  *
87  *    Fix BUG: Change int size to size_t size in pcrs_filter_response().
88  *    See cgi.c fill_template().
89  *
90  *    Revision 1.33  2001/09/16 17:05:14  jongfoster
91  *    Removing unused #include showarg.h
92  *
93  *    Revision 1.32  2001/09/16 13:21:27  jongfoster
94  *    Changes to use new list functions.
95  *
96  *    Revision 1.31  2001/09/16 11:38:02  jongfoster
97  *    Splitting fill_template() into 2 functions:
98  *    template_load() loads the file
99  *    template_fill() performs the PCRS regexps.
100  *    This is because the CGI edit interface has a "table row"
101  *    template which is used many times in the page - this
102  *    change means it's only loaded from disk once.
103  *
104  *    Revision 1.30  2001/09/16 11:00:10  jongfoster
105  *    New function alloc_http_response, for symmetry with free_http_response
106  *
107  *    Revision 1.29  2001/09/13 23:32:40  jongfoster
108  *    Moving image data to cgi.c rather than cgi.h
109  *    Fixing a GPF under Win32 (and any other OS that protects global
110  *    constants from being written to).
111  *
112  *    Revision 1.28  2001/09/10 10:18:51  oes
113  *    Silenced compiler warnings
114  *
115  *    Revision 1.27  2001/08/05 16:06:20  jongfoster
116  *    Modifiying "struct map" so that there are now separate header and
117  *    "map_entry" structures.  This means that functions which modify a
118  *    map no longer need to return a pointer to the modified map.
119  *    Also, it no longer reverses the order of the entries (which may be
120  *    important with some advanced template substitutions).
121  *
122  *    Revision 1.26  2001/07/30 22:08:36  jongfoster
123  *    Tidying up #defines:
124  *    - All feature #defines are now of the form FEATURE_xxx
125  *    - Permanently turned off WIN_GUI_EDIT
126  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
127  *
128  *    Revision 1.25  2001/07/26 10:09:46  oes
129  *    Made browser detection a little less naive
130  *
131  *    Revision 1.24  2001/07/25 17:22:51  oes
132  *    Added workaround for Netscape bug that prevents display of page when loading a component fails.
133  *
134  *    Revision 1.23  2001/07/23 13:40:12  oes
135  *    Fixed bug that caused document body to be dropped when pcrs joblist was empty.
136  *
137  *    Revision 1.22  2001/07/18 12:29:34  oes
138  *    - Made gif_deanimate_response respect
139  *      csp->action->string[ACTION_STRING_DEANIMATE]
140  *    - Logging cosmetics
141  *
142  *    Revision 1.21  2001/07/13 13:59:53  oes
143  *     - Introduced gif_deanimate_response which shares the
144  *       generic content modification interface of pcrs_filter_response
145  *       and acts as a wrapper to deanimate.c:gif_deanimate()
146  *     - Renamed re_process_buffer to pcrs_filter_response
147  *     - pcrs_filter_response now returns NULL on failiure
148  *     - Removed all #ifdef PCRS
149  *
150  *    Revision 1.20  2001/07/01 17:01:04  oes
151  *    Added comments and missing return statement in is_untrusted_url()
152  *
153  *    Revision 1.19  2001/06/29 21:45:41  oes
154  *    Indentation, CRLF->LF, Tab-> Space
155  *
156  *    Revision 1.18  2001/06/29 13:27:38  oes
157  *    - Cleaned up, renamed and reorderd functions
158  *      and improved comments
159  *
160  *    - block_url:
161  *      - Ported to CGI platform. Now delivers
162  *        http_response or NULL
163  *      - Unified HTML and GIF generation (moved image detection
164  *        and GIF generation here from jcc.c:chat())
165  *      - Fixed HTTP status to:
166  *       -  403 (Forbidden) for the "blocked" HTML message
167  *       -  200 (OK) for GIF answers
168  *       -  302 (Redirect) for redirect to GIF
169  *
170  *    - trust_url:
171  *      - Ported to CGI platform. Now delivers
172  *        http_response or NULL
173  *      - Separated detection of untrusted URL into
174  *        (bool)is_untrusted_url
175  *      - Added enforcement of untrusted requests
176  *
177  *    - Moved redirect_url() from cgi.c to here
178  *      and ported it to the CGI platform
179  *
180  *    - Removed logentry from cancelled commit
181  *
182  *    Revision 1.17  2001/06/09 10:55:28  jongfoster
183  *    Changing BUFSIZ ==> BUFFER_SIZE
184  *
185  *    Revision 1.16  2001/06/07 23:10:26  jongfoster
186  *    Allowing unanchored domain patterns to back off and retry
187  *    if they partially match.  Optimized right-anchored patterns.
188  *    Moving ACL and forward files into config file.
189  *    Replacing struct gateway with struct forward_spec
190  *
191  *    Revision 1.15  2001/06/03 19:12:00  oes
192  *    extracted-CGI relevant stuff
193  *
194  *    Revision 1.14  2001/06/01 10:30:55  oes
195  *    Added optional left-anchoring to domaincmp
196  *
197  *    Revision 1.13  2001/05/31 21:21:30  jongfoster
198  *    Permissionsfile / actions file changes:
199  *    - Changed "permission" to "action" throughout
200  *    - changes to file format to allow string parameters
201  *    - Moved helper functions to actions.c
202  *
203  *    Revision 1.12  2001/05/31 17:35:20  oes
204  *
205  *     - Enhanced domain part globbing with infix and prefix asterisk
206  *       matching and optional unanchored operation
207  *
208  *    Revision 1.11  2001/05/29 11:53:23  oes
209  *    "See why" link added to "blocked" page
210  *
211  *    Revision 1.10  2001/05/29 09:50:24  jongfoster
212  *    Unified blocklist/imagelist/permissionslist.
213  *    File format is still under discussion, but the internal changes
214  *    are (mostly) done.
215  *
216  *    Also modified interceptor behaviour:
217  *    - We now intercept all URLs beginning with one of the following
218  *      prefixes (and *only* these prefixes):
219  *        * http://i.j.b/
220  *        * http://ijbswa.sf.net/config/
221  *        * http://ijbswa.sourceforge.net/config/
222  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
223  *    - Internal changes so that intercepted and fast redirect pages
224  *      are not replaced with an image.
225  *    - Interceptors now have the option to send a binary page direct
226  *      to the client. (i.e. ijb-send-banner uses this)
227  *    - Implemented show-url-info interceptor.  (Which is why I needed
228  *      the above interceptors changes - a typical URL is
229  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
230  *      The previous mechanism would not have intercepted that, and
231  *      if it had been intercepted then it then it would have replaced
232  *      it with an image.)
233  *
234  *    Revision 1.9  2001/05/27 22:17:04  oes
235  *
236  *    - re_process_buffer no longer writes the modified buffer
237  *      to the client, which was very ugly. It now returns the
238  *      buffer, which it is then written by chat.
239  *
240  *    - content_length now adjusts the Content-Length: header
241  *      for modified documents rather than crunch()ing it.
242  *      (Length info in csp->content_length, which is 0 for
243  *      unmodified documents)
244  *
245  *    - For this to work, sed() is called twice when filtering.
246  *
247  *    Revision 1.8  2001/05/26 17:13:28  jongfoster
248  *    Filled in a function comment.
249  *
250  *    Revision 1.7  2001/05/26 15:26:15  jongfoster
251  *    ACL feature now provides more security by immediately dropping
252  *    connections from untrusted hosts.
253  *
254  *    Revision 1.6  2001/05/26 00:28:36  jongfoster
255  *    Automatic reloading of config file.
256  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
257  *    Most of the global variables have been moved to a new
258  *    struct configuration_spec, accessed through csp->config->globalname
259  *    Most of the globals remaining are used by the Win32 GUI.
260  *
261  *    Revision 1.5  2001/05/25 22:34:30  jongfoster
262  *    Hard tabs->Spaces
263  *
264  *    Revision 1.4  2001/05/22 18:46:04  oes
265  *
266  *    - Enabled filtering banners by size rather than URL
267  *      by adding patterns that replace all standard banner
268  *      sizes with the "Junkbuster" gif to the re_filterfile
269  *
270  *    - Enabled filtering WebBugs by providing a pattern
271  *      which kills all 1x1 images
272  *
273  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
274  *      which is selected by the (nonstandard and therefore
275  *      capital) letter 'U' in the option string.
276  *      It causes the quantifiers to be ungreedy by default.
277  *      Appending a ? turns back to greedy (!).
278  *
279  *    - Added a new interceptor ijb-send-banner, which
280  *      sends back the "Junkbuster" gif. Without imagelist or
281  *      MSIE detection support, or if tinygif = 1, or the
282  *      URL isn't recognized as an imageurl, a lame HTML
283  *      explanation is sent instead.
284  *
285  *    - Added new feature, which permits blocking remote
286  *      script redirects and firing back a local redirect
287  *      to the browser.
288  *      The feature is conditionally compiled, i.e. it
289  *      can be disabled with --disable-fast-redirects,
290  *      plus it must be activated by a "fast-redirects"
291  *      line in the config file, has its own log level
292  *      and of course wants to be displayed by show-proxy-args
293  *      Note: Boy, all the #ifdefs in 1001 locations and
294  *      all the fumbling with configure.in and acconfig.h
295  *      were *way* more work than the feature itself :-(
296  *
297  *    - Because a generic redirect template was needed for
298  *      this, tinygif = 3 now uses the same.
299  *
300  *    - Moved GIFs, and other static HTTP response templates
301  *      to project.h
302  *
303  *    - Some minor fixes
304  *
305  *    - Removed some >400 CRs again (Jon, you really worked
306  *      a lot! ;-)
307  *
308  *    Revision 1.3  2001/05/20 16:44:47  jongfoster
309  *    Removing last hardcoded JunkBusters.com URLs.
310  *
311  *    Revision 1.2  2001/05/20 01:21:20  jongfoster
312  *    Version 2.9.4 checkin.
313  *    - Merged popupfile and cookiefile, and added control over PCRS
314  *      filtering, in new "permissionsfile".
315  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
316  *      file error you now get a message box (in the Win32 GUI) rather
317  *      than the program exiting with no explanation.
318  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
319  *      skipping.
320  *    - Removed tabs from "config"
321  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
322  *    - Bumped up version number.
323  *
324  *    Revision 1.1.1.1  2001/05/15 13:58:52  oes
325  *    Initial import of version 2.9.3 source tree
326  *
327  *
328  *********************************************************************/
329 \f
330
331 #include "config.h"
332
333 #include <stdio.h>
334 #include <sys/types.h>
335 #include <stdlib.h>
336 #include <ctype.h>
337 #include <string.h>
338 #include <assert.h>
339
340 #ifndef _WIN32
341 #ifndef __OS2__
342 #include <unistd.h>
343 #endif /* ndef __OS2__ */
344 #include <netinet/in.h>
345 #else
346 #include <winsock2.h>
347 #endif /* ndef _WIN32 */
348
349 #ifdef __OS2__
350 #include <utils.h>
351 #endif /* def __OS2__ */
352
353 #include "project.h"
354 #include "filters.h"
355 #include "encode.h"
356 #include "parsers.h"
357 #include "ssplit.h"
358 #include "errlog.h"
359 #include "jbsockets.h"
360 #include "miscutil.h"
361 #include "actions.h"
362 #include "cgi.h"
363 #include "list.h"
364 #include "deanimate.h"
365 #include "urlmatch.h"
366
367 #ifdef _WIN32
368 #include "win32.h"
369 #endif
370
371 const char filters_h_rcs[] = FILTERS_H_VERSION;
372
373 /* Fix a problem with Solaris.  There should be no effect on other
374  * platforms.
375  * Solaris's isspace() is a macro which uses it's argument directly
376  * as an array index.  Therefore we need to make sure that high-bit
377  * characters generate +ve values, and ideally we also want to make
378  * the argument match the declared parameter type of "int".
379  */
380 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
381
382
383 #ifdef FEATURE_ACL
384 /*********************************************************************
385  *
386  * Function    :  block_acl
387  *
388  * Description :  Block this request?
389  *                Decide yes or no based on ACL file.
390  *
391  * Parameters  :
392  *          1  :  dst = The proxy or gateway address this is going to.
393  *                      Or NULL to check all possible targets.
394  *          2  :  csp = Current client state (buffers, headers, etc...)
395  *                      Also includes the client IP address.
396  *
397  * Returns     : 0 = FALSE (don't block) and 1 = TRUE (do block)
398  *
399  *********************************************************************/
400 int block_acl(struct access_control_addr *dst, struct client_state *csp)
401 {
402    struct access_control_list *acl = csp->config->acl;
403
404    /* if not using an access control list, then permit the connection */
405    if (acl == NULL)
406    {
407       return(0);
408    }
409
410    /* search the list */
411    while (acl != NULL)
412    {
413       if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
414       {
415          if (dst == NULL)
416          {
417             /* Just want to check if they have any access */
418             if (acl->action == ACL_PERMIT)
419             {
420                return(0);
421             }
422          }
423          else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
424            && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
425          {
426             if (acl->action == ACL_PERMIT)
427             {
428                return(0);
429             }
430             else
431             {
432                return(1);
433             }
434          }
435       }
436       acl = acl->next;
437    }
438
439    return(1);
440
441 }
442
443
444 /*********************************************************************
445  *
446  * Function    :  acl_addr
447  *
448  * Description :  Called from `load_aclfile' to parse an ACL address.
449  *
450  * Parameters  :
451  *          1  :  aspec = String specifying ACL address.
452  *          2  :  aca = struct access_control_addr to fill in.
453  *
454  * Returns     :  0 => Ok, everything else is an error.
455  *
456  *********************************************************************/
457 int acl_addr(char *aspec, struct access_control_addr *aca)
458 {
459    int i, masklength, port;
460    char *p;
461
462    masklength = 32;
463    port       =  0;
464
465    if ((p = strchr(aspec, '/')))
466    {
467       *p++ = '\0';
468
469       if (ijb_isdigit(*p) == 0)
470       {
471          return(-1);
472       }
473       masklength = atoi(p);
474    }
475
476    if ((masklength < 0) || (masklength > 32))
477    {
478       return(-1);
479    }
480
481    if ((p = strchr(aspec, ':')))
482    {
483       *p++ = '\0';
484
485       if (ijb_isdigit(*p) == 0)
486       {
487          return(-1);
488       }
489       port = atoi(p);
490    }
491
492    aca->port = port;
493
494    aca->addr = ntohl(resolve_hostname_to_ip(aspec));
495
496    if (aca->addr == -1)
497    {
498       log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
499       return(-1);
500    }
501
502    /* build the netmask */
503    aca->mask = 0;
504    for (i=1; i <= masklength ; i++)
505    {
506       aca->mask |= (1 << (32 - i));
507    }
508
509    /* now mask off the host portion of the ip address
510     * (i.e. save on the network portion of the address).
511     */
512    aca->addr = aca->addr & aca->mask;
513
514    return(0);
515
516 }
517 #endif /* def FEATURE_ACL */
518
519
520 /*********************************************************************
521  *
522  * Function    :  match_portlist
523  *
524  * Description :  Check if a given number is covered by a comma
525  *                separated list of numbers and ranges (a,b-c,d,..)
526  *
527  * Parameters  :
528  *          1  :  portlist = String with list
529  *          2  :  port = port to check
530  *
531  * Returns     :  0 => no match
532  *                1 => match
533  *
534  *********************************************************************/
535 int match_portlist(const char *portlist, int port)
536 {
537    char *min, *max, *next, *portlist_copy;
538
539    min = next = portlist_copy = strdup(portlist);
540
541    /*
542     * Zero-terminate first item and remember offset for next
543     */
544    if (NULL != (next = strchr(portlist_copy, (int) ',')))
545    {
546       *next++ = '\0';
547    }
548
549    /*
550     * Loop through all items, checking for match
551     */
552    while(min)
553    {
554       if (NULL == (max = strchr(min, (int) '-')))
555       {
556          /*
557           * No dash, check for equality
558           */
559          if (port == atoi(min))
560          {
561             free(portlist_copy);
562             return(1);
563          }
564       }
565       else
566       {
567          /*
568           * This is a range, so check if between min and max,
569           * or, if max was omitted, between min and 65K
570           */
571          *max++ = '\0';
572          if(port >= atoi(min) && port <= (atoi(max) ? atoi(max) : 65535))
573          {
574             free(portlist_copy);
575             return(1);
576          }
577
578       }
579
580       /*
581        * Jump to next item
582        */
583       min = next;
584
585       /*
586        * Zero-terminate next item and remember offset for n+1
587        */
588       if ((NULL != next) && (NULL != (next = strchr(next, (int) ','))))
589       {
590          *next++ = '\0';
591       }
592    }
593
594    free(portlist_copy);
595    return 0;
596
597 }
598
599
600 /*********************************************************************
601  *
602  * Function    :  block_url
603  *
604  * Description :  Called from `chat'.  Check to see if we need to block this.
605  *
606  * Parameters  :
607  *          1  :  csp = Current client state (buffers, headers, etc...)
608  *
609  * Returns     :  NULL => unblocked, else HTTP block response
610  *
611  *********************************************************************/
612 struct http_response *block_url(struct client_state *csp)
613 {
614 #ifdef FEATURE_IMAGE_BLOCKING
615    char *p;
616 #endif /* def FEATURE_IMAGE_BLOCKING */
617    struct http_response *rsp;
618
619    /*
620     * If it's not blocked, don't block it ;-)
621     */
622    if ((csp->action->flags & ACTION_BLOCK) == 0)
623    {
624       return NULL;
625    }
626
627    /*
628     * Else, prepare a response
629     */
630    if (NULL == (rsp = alloc_http_response()))
631    {
632       return cgi_error_memory();
633    }
634
635    /*
636     * If it's an image-url, send back an image or redirect
637     * as specified by the relevant +image action
638     */
639 #ifdef FEATURE_IMAGE_BLOCKING
640    if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
641         && is_imageurl(csp))
642    {
643       /* determine HOW images should be blocked */
644       p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
645
646       /* and handle accordingly: */
647       if ((p == NULL) || (0 == strcmpic(p, "logo")))
648       {
649          rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
650          if (rsp->body == NULL)
651          {
652             free_http_response(rsp);
653             return cgi_error_memory();
654          }
655          rsp->content_length = image_junkbuster_gif_length;
656
657          if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
658          {
659             free_http_response(rsp);
660             return cgi_error_memory();
661          }
662       }
663
664       else if (0 == strcmpic(p, "blank"))
665       {
666          rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
667          if (rsp->body == NULL)
668          {
669             free_http_response(rsp);
670             return cgi_error_memory();
671          }
672          rsp->content_length = image_blank_gif_length;
673
674          if (enlist_unique_header(rsp->headers, "Content-Type", "image/gif"))
675          {
676             free_http_response(rsp);
677             return cgi_error_memory();
678          }
679       }
680
681       else
682       {
683          rsp->status = strdup("302 Local Redirect from Junkbuster");
684          if (rsp->status == NULL)
685          {
686             free_http_response(rsp);
687             return cgi_error_memory();
688          }
689
690          if (enlist_unique_header(rsp->headers, "Location", p))
691          {
692             free_http_response(rsp);
693             return cgi_error_memory();
694          }
695       }
696    }
697    else
698 #endif /* def FEATURE_IMAGE_BLOCKING */
699
700    /*
701     * Else, generate an HTML "blocked" message:
702     */
703    {
704       jb_err err;
705       struct map * exports;
706
707       /*
708        * Workaround for stupid Netscape bug which prevents
709        * pages from being displayed if loading a referenced
710        * JavaScript or style sheet fails. So make it appear
711        * as if it succeeded.
712        */
713       if ( NULL != (p = get_header_value(csp->headers, "User-Agent:"))
714            && !strncmpic(p, "mozilla", 7) /* Catch Netscape but */
715            && !strstr(p, "Gecko")         /* save Mozilla, */
716            && !strstr(p, "compatible")    /* MSIE */
717            && !strstr(p, "Opera"))        /* and Opera. */
718       {
719          rsp->status = strdup("200 Request for blocked URL");
720       }
721       else
722       {
723          rsp->status = strdup("404 Request for blocked URL");
724       }
725
726       if (rsp->status == NULL)
727       {
728          free_http_response(rsp);
729          return cgi_error_memory();
730       }
731
732       exports = default_exports(csp, NULL);
733       if (exports == NULL)
734       {
735          free_http_response(rsp);
736          return cgi_error_memory();
737       }
738
739 #ifdef FEATURE_FORCE_LOAD
740       err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
741 #else /* ifndef FEATURE_FORCE_LOAD */
742       err = map_block_killer(exports, "force-support");
743 #endif /* ndef FEATURE_FORCE_LOAD */
744
745       if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
746       if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
747
748       if (err)
749       {
750          free_map(exports);
751          free_http_response(rsp);
752          return cgi_error_memory();
753       }
754
755       err = template_fill_for_cgi(csp, "blocked", exports, rsp);
756       if (err)
757       {
758          free_http_response(rsp);
759          return cgi_error_memory();
760       }
761    }
762
763    return finish_http_response(rsp);
764
765 }
766
767
768 #ifdef FEATURE_TRUST
769 /*********************************************************************
770  *
771  * Function    :  trust_url FIXME: I should be called distrust_url
772  *
773  * Description :  Calls is_untrusted_url to determine if the URL is trusted
774  *                and if not, returns a HTTP 304 response with a reject message.
775  *
776  * Parameters  :
777  *          1  :  csp = Current client state (buffers, headers, etc...)
778  *
779  * Returns     :  NULL => trusted, else http_response.
780  *
781  *********************************************************************/
782 struct http_response *trust_url(struct client_state *csp)
783 {
784    struct http_response *rsp;
785    struct map * exports;
786    char buf[BUFFER_SIZE];
787    char *p;
788    struct url_spec **tl;
789    struct url_spec *t;
790    jb_err err;
791
792    /*
793     * Don't bother to work on trusted URLs
794     */
795    if (!is_untrusted_url(csp))
796    {
797       return NULL;
798    }
799
800    /*
801     * Else, prepare a response:
802     */
803    if (NULL == (rsp = alloc_http_response()))
804    {
805       return cgi_error_memory();
806    }
807
808    exports = default_exports(csp, NULL);
809    if (exports == NULL)
810    {
811       free_http_response(rsp);
812       return cgi_error_memory();
813    }
814
815    /*
816     * Export the host, port, and referrer information
817     */
818    err = map(exports, "hostport", 1, csp->http->hostport, 1);
819    if (!err) err = map(exports, "path", 1, csp->http->path, 1);
820    if (!err) err = map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
821    if (!err) err = map(exports, "path-html", 1, html_encode(csp->http->path), 0);
822
823    if (NULL != (p = get_header_value(csp->headers, "Referer:")))
824    {
825       if (!err) err = map(exports, "referrer", 1, p, 1);
826       if (!err) err = map(exports, "referrer-html", 1, html_encode(p), 0);
827    }
828    else
829    {
830       if (!err) err = map(exports, "referrer", 1, "unknown", 1);
831       if (!err) err = map(exports, "referrer-html", 1, "unknown", 1);
832    }
833
834    if (err)
835    {
836       free_map(exports);
837       free_http_response(rsp);
838       return cgi_error_memory();
839    }
840
841    /*
842     * Export the trust list
843     */
844    p = strdup("");
845    for (tl = csp->config->trust_list; (t = *tl) ; tl++)
846    {
847       sprintf(buf, "<li>%s</li>\n", t->spec);
848       string_append(&p, buf);
849    }
850    err = map(exports, "trusted-referrers", 1, p, 0);
851
852    if (err)
853    {
854       free_map(exports);
855       free_http_response(rsp);
856       return cgi_error_memory();
857    }
858
859    /*
860     * Export the trust info, if available
861     */
862    if (csp->config->trust_info->first)
863    {
864       struct list_entry *l;
865
866       p = strdup("");
867       for (l = csp->config->trust_info->first; l ; l = l->next)
868       {
869          sprintf(buf, "<li> <a href=%s>%s</a><br>\n",l->str, l->str);
870          string_append(&p, buf);
871       }
872       err = map(exports, "trust-info", 1, p, 0);
873    }
874    else
875    {
876       err = map_block_killer(exports, "have-trust-info");
877    }
878
879    if (err)
880    {
881       free_map(exports);
882       free_http_response(rsp);
883       return cgi_error_memory();
884    }
885
886    /*
887     * Export the force prefix or the force conditional block killer
888     */
889 #ifdef FEATURE_FORCE_LOAD
890    err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
891 #else /* ifndef FEATURE_FORCE_LOAD */
892    err = map_block_killer(exports, "force-support");
893 #endif /* ndef FEATURE_FORCE_LOAD */
894
895    if (err)
896    {
897       free_map(exports);
898       free_http_response(rsp);
899       return cgi_error_memory();
900    }
901
902    /*
903     * Build the response
904     */
905    err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
906    if (err)
907    {
908       free_http_response(rsp);
909       return cgi_error_memory();
910    }
911
912    return finish_http_response(rsp);
913 }
914 #endif /* def FEATURE_TRUST */
915
916
917 #ifdef FEATURE_FAST_REDIRECTS
918 /*********************************************************************
919  *
920  * Function    :  redirect_url
921  *
922  * Description :  Checks for redirection URLs and returns a HTTP redirect
923  *                to the destination URL, if necessary
924  *
925  * Parameters  :
926  *          1  :  csp = Current client state (buffers, headers, etc...)
927  *
928  * Returns     :  NULL if URL was clean, HTTP redirect otherwise.
929  *
930  *********************************************************************/
931 struct http_response *redirect_url(struct client_state *csp)
932 {
933    char *p, *q;
934    struct http_response *rsp;
935
936    p = q = csp->http->path;
937    log_error(LOG_LEVEL_REDIRECTS, "checking path for redirects: %s", p);
938
939    /*
940     * find the last URL encoded in the request
941     */
942    while ((p = strstr(p, "http://")))
943    {
944       q = p++;
945    }
946
947    /*
948     * if there was any, generate and return a HTTP redirect
949     */
950    if (q != csp->http->path)
951    {
952       log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
953
954       if (NULL == (rsp = alloc_http_response()))
955       {
956          return cgi_error_memory();
957       }
958
959       if ( enlist_unique_header(rsp->headers, "Location", q)
960         || (NULL == (rsp->status = strdup("302 Local Redirect from Junkbuster"))) )
961       {
962          free_http_response(rsp);
963          return cgi_error_memory();
964       }
965
966       return finish_http_response(rsp);
967    }
968    else
969    {
970       return NULL;
971    }
972
973 }
974 #endif /* def FEATURE_FAST_REDIRECTS */
975
976
977 #ifdef FEATURE_IMAGE_BLOCKING
978 /*********************************************************************
979  *
980  * Function    :  is_imageurl
981  *
982  * Description :  Given a URL, decide whether it is an image or not,
983  *                using either the info from a previous +image action
984  *                or, #ifdef FEATURE_IMAGE_DETECT_MSIE, the info from
985  *                the browser's accept header.
986  *
987  * Parameters  :
988  *          1  :  csp = Current client state (buffers, headers, etc...)
989  *
990  * Returns     :  True (nonzero) if URL is an image, false (0)
991  *                otherwise
992  *
993  *********************************************************************/
994 int is_imageurl(struct client_state *csp)
995 {
996 #ifdef FEATURE_IMAGE_DETECT_MSIE
997    char *tmp;
998
999    tmp = get_header_value(csp->headers, "User-Agent:");
1000    if (tmp && strstr(tmp, "MSIE"))
1001    {
1002       tmp = get_header_value(csp->headers, "Accept:");
1003       if (tmp && strstr(tmp, "image/gif"))
1004       {
1005          /* Client will accept HTML.  If this seems counterintuitive,
1006           * blame Microsoft.
1007           */
1008          return(0);
1009       }
1010       else
1011       {
1012          return(1);
1013       }
1014    }
1015 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1016
1017    return ((csp->action->flags & ACTION_IMAGE) != 0);
1018
1019 }
1020 #endif /* def FEATURE_IMAGE_BLOCKING */
1021
1022
1023 #ifdef FEATURE_COOKIE_JAR
1024 /*********************************************************************
1025  *
1026  * Function    :  is_untrusted_url
1027  *
1028  * Description :  Should we "distrust" this URL (and block it)?
1029  *
1030  *                Yes if it matches a line in the trustfile, or if the
1031  *                    referrer matches a line starting with "+" in the
1032  *                    trustfile.
1033  *                No  otherwise.
1034  *
1035  * Parameters  :
1036  *          1  :  csp = Current client state (buffers, headers, etc...)
1037  *
1038  * Returns     :  0 => trusted, 1 => untrusted
1039  *
1040  *********************************************************************/
1041 int is_untrusted_url(struct client_state *csp)
1042 {
1043    struct file_list *fl;
1044    struct block_spec *b;
1045    struct url_spec **trusted_url;
1046    struct http_request rhttp[1];
1047    char *p, *h;
1048    jb_err err;
1049
1050    /*
1051     * If we don't have a trustlist, we trust everybody
1052     */
1053    if (((fl = csp->tlist) == NULL) || ((b  = fl->f) == NULL))
1054    {
1055       return 0;
1056    }
1057
1058    memset(rhttp, '\0', sizeof(*rhttp));
1059
1060    /*
1061     * Do we trust the request URL itself?
1062     */
1063    for (b = b->next; b ; b = b->next)
1064    {
1065       if (url_match(b->url, csp->http))
1066       {
1067          return b->reject;
1068       }
1069    }
1070
1071    if (NULL == (h = get_header_value(csp->headers, "Referer:")))
1072    {
1073       /* no referrer was supplied */
1074       return 1;
1075    }
1076
1077    /*
1078     * If not, do we maybe trust its referrer?
1079     */
1080
1081
1082    /*
1083     * Parse the URL from the referrer
1084     */
1085
1086    err = parse_http_url(h, rhttp, csp);
1087    if (err)
1088    {
1089       return 1;
1090    }
1091
1092    for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
1093    {
1094       if (url_match(*trusted_url, rhttp))
1095       {
1096          /* if the URL's referrer is from a trusted referrer, then
1097           * add the target spec to the trustfile as an unblocked
1098           * domain and return NULL (which means it's OK).
1099           */
1100
1101          FILE *fp;
1102
1103          if ((fp = fopen(csp->config->trustfile, "a")))
1104          {
1105             h = NULL;
1106
1107             h = strsav(h, "~");
1108             h = strsav(h, csp->http->hostport);
1109
1110             p = csp->http->path;
1111             if ((*p++ == '/')
1112             && (*p++ == '~'))
1113             {
1114                /* since this path points into a user's home space
1115                 * be sure to include this spec in the trustfile.
1116                 */
1117                if ((p = strchr(p, '/')))
1118                {
1119                   *p = '\0'; /* FIXME: writing to csp->http->path is a bad idea */
1120                   h = strsav(h, csp->http->path);
1121                   h = strsav(h, "/");
1122                }
1123             }
1124
1125             fprintf(fp, "%s\n", h);
1126             freez(h);
1127             fclose(fp);
1128          }
1129          return 0;
1130       }
1131    }
1132    return 1;
1133 }
1134 #endif /* def FEATURE_COOKIE_JAR */
1135
1136
1137 /*********************************************************************
1138  *
1139  * Function    :  pcrs_filter_response
1140  *
1141  * Description :  Apply all the pcrs jobs from the joblist (re_filterfile)
1142  *                to the text buffer that's been accumulated in
1143  *                csp->iob->buf and set csp->content_length to the modified
1144  *                size and raise the CSP_FLAG_MODIFIED flag if appropriate.
1145  *
1146  * Parameters  :
1147  *          1  :  csp = Current client state (buffers, headers, etc...)
1148  *
1149  * Returns     :  a pointer to the (newly allocated) modified buffer.
1150  *                or NULL in case something went wrong
1151  *
1152  *********************************************************************/
1153 char *pcrs_filter_response(struct client_state *csp)
1154 {
1155    int hits=0;
1156    size_t size;
1157
1158    char *old = csp->iob->cur, *new = NULL;
1159    pcrs_job *job;
1160
1161    struct file_list *fl;
1162    struct re_filterfile_spec *b;
1163
1164    /* Sanity first */
1165    if (csp->iob->cur >= csp->iob->eod)
1166    {
1167       return(NULL);
1168    }
1169    size = csp->iob->eod - csp->iob->cur;
1170
1171    /*
1172     * If the body has a "chunked" transfer-encoding,
1173     * get rid of it first, adjusting size and iob->eod
1174     */
1175    if (csp->flags & CSP_FLAG_CHUNKED)
1176    {
1177       log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
1178       if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1179       {
1180          return(NULL);
1181       }
1182       csp->iob->eod = csp->iob->cur + size;
1183       csp->flags |= CSP_FLAG_MODIFIED;
1184    }
1185
1186    if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
1187    {
1188       log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1189       return(NULL);
1190    }
1191
1192    if ( NULL == b->joblist )
1193    {
1194       log_error(LOG_LEVEL_RE_FILTER, "Empty joblist. Nothing to do.");
1195       return(NULL);
1196    }
1197
1198    log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
1199               csp->http->hostport, csp->http->path, size);
1200
1201    /* Apply all jobs from the joblist */
1202    for (job = b->joblist; NULL != job; job = job->next)
1203    {
1204       hits += pcrs_execute(job, old, size, &new, &size);
1205       if (old != csp->iob->cur) free(old);
1206       old=new;
1207    }
1208
1209    log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
1210
1211    /*
1212     * If there were no hits, destroy our copy and let
1213     * chat() use the original in csp->iob
1214     */
1215    if (!hits)
1216    {
1217       free(new);
1218       return(NULL);
1219    }
1220
1221    csp->flags |= CSP_FLAG_MODIFIED;
1222    csp->content_length = size;
1223    IOB_RESET(csp);
1224
1225    return(new);
1226
1227 }
1228
1229
1230 /*********************************************************************
1231  *
1232  * Function    :  gif_deanimate_response
1233  *
1234  * Description :  Deanimate the GIF image that has been accumulated in
1235  *                csp->iob->buf, set csp->content_length to the modified
1236  *                size and raise the CSP_FLAG_MODIFIED flag.
1237  *
1238  * Parameters  :
1239  *          1  :  csp = Current client state (buffers, headers, etc...)
1240  *
1241  * Returns     :  a pointer to the (newly allocated) modified buffer.
1242  *                or NULL in case something went wrong.
1243  *
1244  *********************************************************************/
1245 char *gif_deanimate_response(struct client_state *csp)
1246 {
1247    struct binbuffer *in, *out;
1248    char *p;
1249    int size = csp->iob->eod - csp->iob->cur;
1250
1251    /*
1252     * If the body has a "chunked" transfer-encoding,
1253     * get rid of it first, adjusting size and iob->eod
1254     */
1255    if (csp->flags & CSP_FLAG_CHUNKED)
1256    {
1257       log_error(LOG_LEVEL_DEANIMATE, "Need to de-chunk first");
1258       if (0 == (size = remove_chunked_transfer_coding(csp->iob->cur, size)))
1259       {
1260          return(NULL);
1261       }
1262       csp->iob->eod = csp->iob->cur + size;
1263       csp->flags |= CSP_FLAG_MODIFIED;
1264    }
1265
1266    if (  (NULL == (in =  (struct binbuffer *)zalloc(sizeof *in )))
1267       || (NULL == (out = (struct binbuffer *)zalloc(sizeof *out))) )
1268    {
1269       log_error(LOG_LEVEL_DEANIMATE, "failed! (no mem)");
1270       return NULL;
1271    }
1272
1273    in->buffer = csp->iob->cur;
1274    in->size = size;
1275
1276    if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
1277    {
1278       log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
1279       free(in);
1280       buf_free(out);
1281       return(NULL);
1282    }
1283    else
1284    {
1285       log_error(LOG_LEVEL_DEANIMATE, "Success! GIF shrunk from %d bytes to %d.", size, out->offset);
1286       csp->content_length = out->offset;
1287       csp->flags |= CSP_FLAG_MODIFIED;
1288       p = out->buffer;
1289       free(in);
1290       free(out);
1291       return(p);
1292    }
1293
1294 }
1295
1296
1297 /*********************************************************************
1298  *
1299  * Function    :  remove_chunked_transfer_coding
1300  *
1301  * Description :  In-situ remove the "chunked" transfer coding as defined
1302  *                in rfc2616 from a buffer.
1303  *
1304  * Parameters  :
1305  *          1  :  buffer = Pointer to the text buffer
1306  *          2  :  size = Number of bytes to be processed
1307  *
1308  * Returns     :  The new size, i.e. the number of bytes from buffer which
1309  *                are occupied by the stripped body, or 0 in case something
1310  *                went wrong
1311  *
1312  *********************************************************************/
1313 int remove_chunked_transfer_coding(char *buffer, const size_t size)
1314 {
1315    size_t newsize = 0;
1316    unsigned int chunksize = 0;
1317    char *from_p, *to_p;
1318
1319    assert(buffer);
1320    from_p = to_p = buffer;
1321
1322    if (sscanf(buffer, "%x", &chunksize) != 1)
1323    {
1324       log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
1325       return(0);
1326    }
1327
1328    while (chunksize > 0)
1329    {
1330       if (NULL == (from_p = strstr(from_p, "\r\n")))
1331       {
1332          log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1333          return(0);
1334       }
1335       newsize += chunksize;
1336       from_p += 2;
1337
1338       memmove(to_p, from_p, (size_t) chunksize);
1339       to_p = buffer + newsize;
1340       from_p += chunksize + 2;
1341
1342       if (sscanf(from_p, "%x", &chunksize) != 1)
1343       {
1344          log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
1345          return(0);
1346       }
1347    }
1348
1349    /* FIXME: Should this get its own loglevel? */
1350    log_error(LOG_LEVEL_RE_FILTER, "De-chunking successful. Shrunk from %d to %d\n", size, newsize);
1351    return(newsize);
1352
1353 }
1354
1355
1356 /*********************************************************************
1357  *
1358  * Function    :  url_actions
1359  *
1360  * Description :  Gets the actions for this URL.
1361  *
1362  * Parameters  :
1363  *          1  :  http = http_request request for blocked URLs
1364  *          2  :  csp = Current client state (buffers, headers, etc...)
1365  *
1366  * Returns     :  N/A
1367  *
1368  *********************************************************************/
1369 void url_actions(struct http_request *http,
1370                  struct client_state *csp)
1371 {
1372    struct file_list *fl;
1373    struct url_actions *b;
1374
1375    init_current_action(csp->action);
1376
1377    if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
1378    {
1379       return;
1380    }
1381
1382    apply_url_actions(csp->action, http, b);
1383
1384 }
1385
1386
1387 /*********************************************************************
1388  *
1389  * Function    :  apply_url_actions
1390  *
1391  * Description :  Applies a list of URL actions.
1392  *
1393  * Parameters  :
1394  *          1  :  action = Destination.
1395  *          2  :  http = Current URL
1396  *          3  :  b = list of URL actions to apply
1397  *
1398  * Returns     :  N/A
1399  *
1400  *********************************************************************/
1401 void apply_url_actions(struct current_action_spec *action,
1402                        struct http_request *http,
1403                        struct url_actions *b)
1404 {
1405    if (b == NULL)
1406    {
1407       /* Should never happen */
1408       return;
1409    }
1410
1411    for (b = b->next; NULL != b; b = b->next)
1412    {
1413       if (url_match(b->url, http))
1414       {
1415          merge_current_action(action, b->action);
1416       }
1417    }
1418 }
1419
1420
1421 /*********************************************************************
1422  *
1423  * Function    :  forward_url
1424  *
1425  * Description :  Should we forward this to another proxy?
1426  *
1427  * Parameters  :
1428  *          1  :  http = http_request request for current URL
1429  *          2  :  csp = Current client state (buffers, headers, etc...)
1430  *
1431  * Returns     :  Pointer to forwarding information.
1432  *
1433  *********************************************************************/
1434 const struct forward_spec * forward_url(struct http_request *http,
1435                                         struct client_state *csp)
1436 {
1437    static const struct forward_spec fwd_default[1] = { FORWARD_SPEC_INITIALIZER };
1438    struct forward_spec *fwd = csp->config->forward;
1439
1440    if (fwd == NULL)
1441    {
1442       return fwd_default;
1443    }
1444
1445    while (fwd != NULL)
1446    {
1447       if (url_match(fwd->url, http))
1448       {
1449          return fwd;
1450       }
1451       fwd = fwd->next;
1452    }
1453
1454    return fwd_default;
1455 }
1456
1457
1458 /*
1459   Local Variables:
1460   tab-width: 3
1461   end:
1462 */