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