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