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