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