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