1 const char parsers_rcs[] = "$Id: parsers.c,v 1.125 2008/04/17 14:40:49 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
48 * Provide get_http_time() with the buffer size so it doesn't
49 * have to blindly assume that the buffer is big enough.
51 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
52 * Don't pass the whole csp structure to flush_socket()
53 * when it only needs a file descriptor and a buffer.
55 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
56 * Remove send-wafer and send-vanilla-wafer actions.
58 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
59 * Remove inspect-jpegs action.
61 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
62 * Let client_range() also handle Request-Range headers
63 * which apparently are still supported by many servers.
65 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
66 * Improve the warning messages that get logged if the action files
67 * "enable" filters but no filters of that type have been loaded.
69 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
70 * In server_content_type():
71 * - Don't require leading white space when detecting image content types.
72 * - Change '... not replaced ...' message to sound less crazy if the text
73 * type actually is 'text/plain'.
74 * - Mark the 'text/plain == binary data' assumption for removal.
75 * - Remove a bunch of trailing white space.
77 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
78 * Minor server_content_disposition() changes:
79 * - Don't regenerate the header name all lower-case.
80 * - Some white space fixes.
81 * - Remove useless log message in case of ENOMEM.
83 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
84 * Garbage-collect the code to add a X-Forwarded-For
85 * header as it seems to be mostly used by accident.
87 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
88 * Fix a crash on mingw32 with some Last Modified times in the future.
90 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
91 * Remove a "can't happen" error block which, over
92 * time, mutated into a "guaranteed to happen" block.
94 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
95 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
96 * - Use shiny new content_filters_enabled() in client_range().
98 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
99 * I forgot about Poland.
101 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
102 * Remove Range and If-Range headers if content filtering is enabled.
104 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
105 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
106 * client_cookie_adder() to make sure send-vanilla-wafer can be
107 * controlled through tags (and thus regression-tested).
109 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
110 * - Remove "scanning headers for" log message again.
111 * - Some more whitespace fixes.
113 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
114 * Refactor client_referrer() and add conditional-forge parameter.
116 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
117 * A bunch of whitespace fixes, pointy hat to me.
119 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
120 * Fix possible memory corruption in server_http, make sure it's not
121 * executed for ordinary server headers and mark some problems for later.
123 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
124 * Let content-type-overwrite{} honour force-text-mode again.
126 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
127 * - Add prototpyes for the header parsers and make them static.
128 * - Comment out client_accept_encoding_adder() which isn't used right now.
130 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
131 * Move the ACTION_FORCE_TEXT_MODE check out of
132 * server_content_type(). Signal other functions
133 * whether or not a content type has been declared.
134 * Part of the fix for BR#1750917.
136 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
137 * Change sed() to return a jb_err in preparation for forward-override{}.
139 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
140 * Adjust "X-Filter: No" to disable dedicated header filters.
142 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
143 * Streamline client_cookie_adder().
145 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
146 * Make sure filters with dynamic jobs actually use them.
148 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
149 * - Introduce dynamic pcrs jobs that can resolve variables.
150 * - Remove unnecessary update_action_bits_for_all_tags() call.
152 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
153 * - Make tagging based on tags set by earlier taggers
154 * of the same kind possible.
155 * - Log whether or not new tags cause action bits updates
156 * (in which case a matching tag-pattern section exists).
157 * - Log if the user tries to set a tag that is already set.
159 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
160 * Introduce tags as alternative way to specify which
161 * actions apply to a request. At the moment tags can be
162 * created based on client and server headers.
164 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
165 * Log a warning if the content is compressed, filtering is
166 * enabled and Privoxy was compiled without zlib support.
169 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
170 * - Fix warnings when compiled with glibc.
171 * - Don't use crumble() for cookie crunching.
172 * - Move cookie time parsing into parse_header_time().
173 * - Let parse_header_time() return a jb_err code
174 * instead of a pointer that can only be used to
175 * check for NULL anyway.
177 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
178 * - Add better protection against malicious gzip headers.
179 * - Stop logging the first hundred bytes of decompressed content.
180 * It looks like it's working and there is always debug 16.
181 * - Log the content size after decompression in decompress_iob()
182 * instead of pcrs_filter_response().
184 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
185 * - Use dedicated header filter actions instead of abusing "filter".
186 * Replace "filter-client-headers" and "filter-client-headers"
187 * with "server-header-filter" and "client-header-filter".
188 * - Remove filter_client_header() and filter_client_header(),
189 * filter_header() now checks the shiny new
190 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
192 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
193 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
194 * - Handle "Cookie:" and "Connection:" headers a bit smarter
195 * (don't crunch them just to recreate them later on).
196 * - Add another non-standard time format for the cookie
197 * expiration date detection.
198 * - Fix a valgrind warning.
200 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
201 * Improve cookie expiration date detection.
203 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
204 * Don't run server_content_length() the first time
205 * sed() parses server headers; only adjust the
206 * Content-Length header if the page was modified.
208 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
209 * Fix log messages regarding the cookie time format
210 * (cookie and request URL were mixed up).
212 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
213 * - Let decompress_iob()
214 * - not corrupt the content if decompression fails
215 * early. (the first byte(s) were lost).
216 * - use pointer arithmetics with defined outcome for
218 * - Use a different kludge to remember a failed decompression.
220 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
221 * Search for Max-Forwards headers case-insensitive,
222 * don't generate the "501 unsupported" message for invalid
223 * Max-Forwards values and don't increase negative ones.
225 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
226 * - Let server_set_cookie() check the expiration date
227 * of cookies and don't touch the ones that are already
228 * expired. Fixes problems with low quality web applications
229 * as described in BR 932612.
231 * - Adjust comment in client_max_forwards to reality;
232 * remove invalid Max-Forwards headers.
234 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
235 * Stop filter_header() from unintentionally removing
236 * empty header lines that were enlisted by the continue
239 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
240 * - Repeat the request URL before logging any headers.
241 * Makes reading the log easier in case of simultaneous requests.
242 * - If there are more than one Content-Type headers in one request,
243 * use the first one and remove the others.
244 * - Remove "newval" variable in server_content_type().
245 * It's only used once.
247 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
248 * Correct a cast, check inflateEnd() exit code
249 * to see if we have to, replace sprintf calls
252 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
253 * Integrate a modified version of Wil Mahan's
254 * zlib patch (PR #895531).
256 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
257 * Skip empty filter files in filter_header()
258 * but don't ignore the ones that come afterwards.
259 * Fixes BR 1619208, this time for real.
261 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
262 * Reverted parts of my last commit
263 * to keep error handling working.
265 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
266 * Fixed gcc43 conversion warnings.
268 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
269 * Bringing back the "useless" localtime() call
270 * I removed in revision 1.67. On some platforms
271 * it's necessary to prevent time zone offsets.
273 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
274 * Rebuild request URL in get_destination_from_headers()
275 * to make sure redirect{pcrs command} works as expected
276 * for intercepted requests.
278 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
279 * Added get_destination_from_headers().
281 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
282 * Make pthread mutex locking more generic. Instead of
283 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
284 * and use mutex locking unless there is an _r function
285 * available. Better safe than sorry.
287 * Fixes "./configure --disable-pthread" and should result
288 * in less threading-related problems on pthread-using platforms,
289 * but it still doesn't fix BR#1122404.
291 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
292 * The special header "X-Filter: No" now disables
293 * header filtering as well.
295 * Revision 1.73 2006/09/23 13:26:38 roro
296 * Replace TABs by spaces in source code.
298 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
299 * Don't print a log message every time filter_headers is
300 * entered or left. It only creates noise without any real
303 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
304 * Fix +hide-if-modified-since{-n}.
306 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
307 * Have hide-if-modified-since interpret the random
308 * range value as minutes instead of hours. Allows
309 * more fine-grained configuration.
311 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
312 * Always have parse_header_time return a pointer
313 * that actual makes sense, even though we currently
314 * only need it to detect problems.
316 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
317 * Added config option enable-remote-http-toggle
318 * to specify if Privoxy should recognize special
319 * headers (currently only X-Filter) to change its
320 * behaviour. Disabled by default.
322 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
323 * After filtering de-chunked instances, remove
324 * "Transfer-Encoding" header entirely instead of changing
325 * it to "Transfer-Encoding: identity", which is invalid.
326 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
328 * Don't use localtime in parse_header_time. An empty time struct
329 * is good enough, it gets overwritten by strptime anyway.
331 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
332 * Use gmtime_r if available, fallback to gmtime with mutex
333 * protection for MacOSX and use vanilla gmtime for the rest.
335 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
336 * Changed client_referrer to use the right type (size_t) for
337 * hostlenght and to shorten the temporary referrer string with
338 * '\0' instead of adding a useless line break.
340 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
341 * - Back to timegm() using GnuPG's replacement if necessary.
342 * Using mktime() and localtime() could add a on hour offset if
343 * the randomize factor was big enough to lead to a summer/wintertime
346 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
348 * - Moved randomization code into pick_from_range().
350 * - Changed parse_header_time definition.
351 * time_t isn't guaranteed to be signed and
352 * if it isn't, -1 isn't available as error code.
353 * Changed some variable types in client_if_modified_since()
354 * because of the same reason.
356 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
357 * OS/2 compilation compatibility fixups
359 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
360 * Changed include from strptime.c to strptime.h
362 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
363 * Split filter-headers{} into filter-client-headers{}
364 * and filter-server-headers{}.
365 * Added parse_header_time() to share some code.
366 * Replaced timegm() with mktime().
368 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
369 * Windows service integration
371 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
372 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
374 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
375 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
376 * with what was really the latest development (the v_3_0_branch branch)
378 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
379 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
381 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
382 * Add the ability to check jpeg images for invalid
383 * lengths of comment blocks. Defensive strategy
384 * against the exploit:
385 * Microsoft Security Bulletin MS04-028
386 * Buffer Overrun in JPEG Processing (GDI+) Could
387 * Allow Code Execution (833987)
388 * Enabled with +inspect-jpegs in actions files.
390 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
391 * Excluded text/plain objects from filtering. This fixes a
392 * couple of client-crashing, download corruption and
393 * Privoxy performance issues, whose root cause lies in
394 * web servers labelling content of unknown type as text/plain.
396 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
397 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
399 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
400 * Completing the previous change
402 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
403 * Added temporary workaround for bug in PHP < 4.2.3
405 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
406 * Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX. Hopefully this will take care of all of those pesky crash reports.
408 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
409 * Fix typo: supressed -> suppressed
411 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
412 * Improved cookie logging
414 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
415 * Added basic support for OPTIONS and TRACE HTTP methods:
416 * - New parser function client_max_forwards which decrements
417 * the Max-Forwards HTTP header field of OPTIONS and TRACE
418 * requests by one before forwarding
419 * - New parser function client_host which extracts the host
420 * and port information from the HTTP header field if the
421 * request URI was not absolute
422 * - Don't crumble and re-add the Host: header, but only generate
423 * and append if missing
425 * Revision 1.56 2002/05/12 15:34:22 jongfoster
426 * Fixing typo in a comment
428 * Revision 1.55 2002/05/08 16:01:07 oes
429 * Optimized add_to_iob:
430 * - Use realloc instead of malloc(), memcpy(), free()
431 * - Expand to powers of two if possible, to get
432 * O(log n) reallocs instead of O(n).
433 * - Moved check for buffer limit here from chat
434 * - Report failure via returncode
436 * Revision 1.54 2002/04/02 15:03:16 oes
437 * Tiny code cosmetics
439 * Revision 1.53 2002/03/26 22:29:55 swa
440 * we have a new homepage!
442 * Revision 1.52 2002/03/24 13:25:43 swa
443 * name change related issues
445 * Revision 1.51 2002/03/13 00:27:05 jongfoster
448 * Revision 1.50 2002/03/12 01:45:35 oes
449 * More verbose logging
451 * Revision 1.49 2002/03/09 20:03:52 jongfoster
452 * - Making various functions return int rather than size_t.
453 * (Undoing a recent change). Since size_t is unsigned on
454 * Windows, functions like read_socket that return -1 on
455 * error cannot return a size_t.
457 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
458 * crashes, and also frequently caused JB to jump to 100%
459 * CPU and stay there. (Because it thought it had just
460 * read ((unsigned)-1) == 4Gb of data...)
462 * - The signature of write_socket has changed, it now simply
463 * returns success=0/failure=nonzero.
465 * - Trying to get rid of a few warnings --with-debug on
466 * Windows, I've introduced a new type "jb_socket". This is
467 * used for the socket file descriptors. On Windows, this
468 * is SOCKET (a typedef for unsigned). Everywhere else, it's
469 * an int. The error value can't be -1 any more, so it's
470 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
471 * Windows it maps to the #define INVALID_SOCKET.)
473 * - The signature of bind_port has changed.
475 * Revision 1.48 2002/03/07 03:46:53 oes
476 * Fixed compiler warnings etc
478 * Revision 1.47 2002/02/20 23:15:13 jongfoster
479 * Parsing functions now handle out-of-memory gracefully by returning
482 * Revision 1.46 2002/01/17 21:03:47 jongfoster
483 * Moving all our URL and URL pattern parsing code to urlmatch.c.
485 * Revision 1.45 2002/01/09 14:33:03 oes
486 * Added support for localtime_r.
488 * Revision 1.44 2001/12/14 01:22:54 steudten
489 * Remove 'user:pass@' from 'proto://user:pass@host' for the
490 * new added header 'Host: ..'. (See Req ID 491818)
492 * Revision 1.43 2001/11/23 00:26:38 jongfoster
493 * Fixing two really stupid errors in my previous commit
495 * Revision 1.42 2001/11/22 21:59:30 jongfoster
496 * Adding code to handle +no-cookies-keep
498 * Revision 1.41 2001/11/05 23:43:05 steudten
499 * Add time+date to log files.
501 * Revision 1.40 2001/10/26 20:13:09 jongfoster
502 * ctype.h is needed in Windows, too.
504 * Revision 1.39 2001/10/26 17:40:04 oes
505 * Introduced get_header_value()
506 * Removed http->user_agent, csp->referrer and csp->accept_types
507 * Removed client_accept()
509 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
510 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
511 * threads to call select() simultaneously. So, it's time to do a real, live,
512 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
513 * (native). Both versions will work, but using __OS2__ offers multi-threading.
515 * Revision 1.37 2001/10/23 21:36:02 jongfoster
516 * Documenting sed()'s error behaviou (doc change only)
518 * Revision 1.36 2001/10/13 12:51:51 joergs
519 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
520 * force-load), instead crumble Host: and add it (again) in client_host_adder
521 * (in case we get a HTTP/1.0 request without Host: header and forward it to
522 * a HTTP/1.1 server/proxy).
524 * Revision 1.35 2001/10/09 22:39:21 jongfoster
525 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
528 * Revision 1.34 2001/10/07 18:50:55 oes
529 * Added server_content_encoding, renamed server_transfer_encoding
531 * Revision 1.33 2001/10/07 18:04:49 oes
532 * Changed server_http11 to server_http and its pattern to "HTTP".
533 * Additional functionality: it now saves the HTTP status into
534 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
536 * Revision 1.32 2001/10/07 15:43:28 oes
537 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
538 * client_te and client_accept_encoding_adder, triggered by the new
539 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
540 * changed to allow only identity and chunked, and the TE header is
541 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
543 * parse_http_request no longer does anything than parsing. The rewriting
544 * of http->cmd and version mangling are gone. It now also recognizes
545 * the put and delete methods and saves the url in http->url. Removed
548 * renamed content_type and content_length to have the server_ prefix
550 * server_content_type now only works if csp->content_type != CT_TABOO
552 * added server_transfer_encoding, which
553 * - Sets CT_TABOO to prohibit filtering if encoding compresses
554 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
555 * - Change from "chunked" to "identity" if body was chunked
556 * but has been de-chunked for filtering.
558 * added server_content_md5 which crunches any Content-MD5 headers
559 * if the body was modified.
561 * made server_http11 conditional on +downgrade action
563 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
565 * Revision 1.31 2001/10/05 14:25:02 oes
566 * Crumble Keep-Alive from Server
568 * Revision 1.30 2001/09/29 12:56:03 joergs
569 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
571 * Revision 1.29 2001/09/24 21:09:24 jongfoster
572 * Fixing 2 memory leaks that Guy spotted, where the paramater to
573 * enlist() was not being free()d.
575 * Revision 1.28 2001/09/22 16:32:28 jongfoster
576 * Removing unused #includes.
578 * Revision 1.27 2001/09/20 15:45:25 steudten
580 * add casting from size_t to int for printf()
581 * remove local variable shadow s2
583 * Revision 1.26 2001/09/16 17:05:14 jongfoster
584 * Removing unused #include showarg.h
586 * Revision 1.25 2001/09/16 13:21:27 jongfoster
587 * Changes to use new list functions.
589 * Revision 1.24 2001/09/13 23:05:50 jongfoster
590 * Changing the string paramater to the header parsers a "const".
592 * Revision 1.23 2001/09/12 18:08:19 steudten
594 * In parse_http_request() header rewriting miss the host value, so
595 * from http://www.mydomain.com the result was just " / " not
596 * http://www.mydomain.com/ in case we forward.
598 * Revision 1.22 2001/09/10 10:58:53 oes
599 * Silenced compiler warnings
601 * Revision 1.21 2001/07/31 14:46:00 oes
602 * - Persistant connections now suppressed
603 * - sed() no longer appends empty header to csp->headers
605 * Revision 1.20 2001/07/30 22:08:36 jongfoster
606 * Tidying up #defines:
607 * - All feature #defines are now of the form FEATURE_xxx
608 * - Permanently turned off WIN_GUI_EDIT
609 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
611 * Revision 1.19 2001/07/25 17:21:54 oes
612 * client_uagent now saves copy of User-Agent: header value
614 * Revision 1.18 2001/07/13 14:02:46 oes
615 * - Included fix to repair broken HTTP requests that
616 * don't contain a path, not even '/'.
617 * - Removed all #ifdef PCRS
618 * - content_type now always inspected and classified as
619 * text, gif or other.
620 * - formatting / comments
622 * Revision 1.17 2001/06/29 21:45:41 oes
623 * Indentation, CRLF->LF, Tab-> Space
625 * Revision 1.16 2001/06/29 13:32:42 oes
627 * - Adapted free_http_request
628 * - Removed logentry from cancelled commit
630 * Revision 1.15 2001/06/03 19:12:38 oes
631 * deleted const struct interceptors
633 * Revision 1.14 2001/06/01 18:49:17 jongfoster
634 * Replaced "list_share" with "list" - the tiny memory gain was not
635 * worth the extra complexity.
637 * Revision 1.13 2001/05/31 21:30:33 jongfoster
638 * Removed list code - it's now in list.[ch]
639 * Renamed "permission" to "action", and changed many features
640 * to use the actions file rather than the global config.
642 * Revision 1.12 2001/05/31 17:33:13 oes
646 * Revision 1.11 2001/05/29 20:11:19 joergs
647 * '/ * inside comment' warning removed.
649 * Revision 1.10 2001/05/29 09:50:24 jongfoster
650 * Unified blocklist/imagelist/permissionslist.
651 * File format is still under discussion, but the internal changes
654 * Also modified interceptor behaviour:
655 * - We now intercept all URLs beginning with one of the following
656 * prefixes (and *only* these prefixes):
658 * * http://ijbswa.sf.net/config/
659 * * http://ijbswa.sourceforge.net/config/
660 * - New interceptors "home page" - go to http://i.j.b/ to see it.
661 * - Internal changes so that intercepted and fast redirect pages
662 * are not replaced with an image.
663 * - Interceptors now have the option to send a binary page direct
664 * to the client. (i.e. ijb-send-banner uses this)
665 * - Implemented show-url-info interceptor. (Which is why I needed
666 * the above interceptors changes - a typical URL is
667 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
668 * The previous mechanism would not have intercepted that, and
669 * if it had been intercepted then it then it would have replaced
672 * Revision 1.9 2001/05/28 17:26:33 jongfoster
673 * Fixing segfault if last header was crunched.
674 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
675 * can use the cross-platform sprintf() instead.)
677 * Revision 1.8 2001/05/27 22:17:04 oes
679 * - re_process_buffer no longer writes the modified buffer
680 * to the client, which was very ugly. It now returns the
681 * buffer, which it is then written by chat.
683 * - content_length now adjusts the Content-Length: header
684 * for modified documents rather than crunch()ing it.
685 * (Length info in csp->content_length, which is 0 for
686 * unmodified documents)
688 * - For this to work, sed() is called twice when filtering.
690 * Revision 1.7 2001/05/27 13:19:06 oes
691 * Patched Joergs solution for the content-length in.
693 * Revision 1.6 2001/05/26 13:39:32 jongfoster
694 * Only crunches Content-Length header if applying RE filtering.
695 * Without this fix, Microsoft Windows Update wouldn't work.
697 * Revision 1.5 2001/05/26 00:28:36 jongfoster
698 * Automatic reloading of config file.
699 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
700 * Most of the global variables have been moved to a new
701 * struct configuration_spec, accessed through csp->config->globalname
702 * Most of the globals remaining are used by the Win32 GUI.
704 * Revision 1.4 2001/05/22 18:46:04 oes
706 * - Enabled filtering banners by size rather than URL
707 * by adding patterns that replace all standard banner
708 * sizes with the "Junkbuster" gif to the re_filterfile
710 * - Enabled filtering WebBugs by providing a pattern
711 * which kills all 1x1 images
713 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
714 * which is selected by the (nonstandard and therefore
715 * capital) letter 'U' in the option string.
716 * It causes the quantifiers to be ungreedy by default.
717 * Appending a ? turns back to greedy (!).
719 * - Added a new interceptor ijb-send-banner, which
720 * sends back the "Junkbuster" gif. Without imagelist or
721 * MSIE detection support, or if tinygif = 1, or the
722 * URL isn't recognized as an imageurl, a lame HTML
723 * explanation is sent instead.
725 * - Added new feature, which permits blocking remote
726 * script redirects and firing back a local redirect
728 * The feature is conditionally compiled, i.e. it
729 * can be disabled with --disable-fast-redirects,
730 * plus it must be activated by a "fast-redirects"
731 * line in the config file, has its own log level
732 * and of course wants to be displayed by show-proxy-args
733 * Note: Boy, all the #ifdefs in 1001 locations and
734 * all the fumbling with configure.in and acconfig.h
735 * were *way* more work than the feature itself :-(
737 * - Because a generic redirect template was needed for
738 * this, tinygif = 3 now uses the same.
740 * - Moved GIFs, and other static HTTP response templates
745 * - Removed some >400 CRs again (Jon, you really worked
748 * Revision 1.3 2001/05/20 01:21:20 jongfoster
749 * Version 2.9.4 checkin.
750 * - Merged popupfile and cookiefile, and added control over PCRS
751 * filtering, in new "permissionsfile".
752 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
753 * file error you now get a message box (in the Win32 GUI) rather
754 * than the program exiting with no explanation.
755 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
757 * - Removed tabs from "config"
758 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
759 * - Bumped up version number.
761 * Revision 1.2 2001/05/17 23:02:36 oes
762 * - Made referrer option accept 'L' as a substitute for '§'
764 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
765 * Initial import of version 2.9.3 source tree
768 *********************************************************************/
775 #include <sys/types.h>
785 * Convince GNU's libc to provide a strptime prototype.
788 #endif /*__GLIBC__ */
795 #if !defined(_WIN32) && !defined(__OS2__)
801 #ifdef FEATURE_PTHREAD
803 /* jcc.h is for mutex semapores only */
804 #endif /* def FEATURE_PTHREAD */
810 #include "jbsockets.h"
811 #include "miscutil.h"
816 #ifndef HAVE_STRPTIME
817 #include "strptime.h"
820 const char parsers_h_rcs[] = PARSERS_H_VERSION;
822 /* Fix a problem with Solaris. There should be no effect on other
824 * Solaris's isspace() is a macro which uses its argument directly
825 * as an array index. Therefore we need to make sure that high-bit
826 * characters generate +ve values, and ideally we also want to make
827 * the argument match the declared parameter type of "int".
829 * Why did they write a character function that can't take a simple
830 * "char" argument? Doh!
832 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
833 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
835 static jb_err scan_headers(struct client_state *csp);
836 static jb_err header_tagger(struct client_state *csp, char *header);
837 static jb_err parse_header_time(const char *header_time, time_t *result);
839 static jb_err crumble (struct client_state *csp, char **header);
840 static jb_err connection (struct client_state *csp, char **header);
841 static jb_err filter_header (struct client_state *csp, char **header);
842 static jb_err client_referrer (struct client_state *csp, char **header);
843 static jb_err client_uagent (struct client_state *csp, char **header);
844 static jb_err client_ua (struct client_state *csp, char **header);
845 static jb_err client_from (struct client_state *csp, char **header);
846 static jb_err client_send_cookie (struct client_state *csp, char **header);
847 static jb_err client_x_forwarded (struct client_state *csp, char **header);
848 static jb_err client_accept_encoding (struct client_state *csp, char **header);
849 static jb_err client_te (struct client_state *csp, char **header);
850 static jb_err client_max_forwards (struct client_state *csp, char **header);
851 static jb_err client_host (struct client_state *csp, char **header);
852 static jb_err client_if_modified_since (struct client_state *csp, char **header);
853 static jb_err client_accept_language (struct client_state *csp, char **header);
854 static jb_err client_if_none_match (struct client_state *csp, char **header);
855 static jb_err crunch_client_header (struct client_state *csp, char **header);
856 static jb_err client_x_filter (struct client_state *csp, char **header);
857 static jb_err client_range (struct client_state *csp, char **header);
858 static jb_err server_set_cookie (struct client_state *csp, char **header);
859 static jb_err server_content_type (struct client_state *csp, char **header);
860 static jb_err server_content_length (struct client_state *csp, char **header);
861 static jb_err server_content_md5 (struct client_state *csp, char **header);
862 static jb_err server_content_encoding (struct client_state *csp, char **header);
863 static jb_err server_transfer_coding (struct client_state *csp, char **header);
864 static jb_err server_http (struct client_state *csp, char **header);
865 static jb_err crunch_server_header (struct client_state *csp, char **header);
866 static jb_err server_last_modified (struct client_state *csp, char **header);
867 static jb_err server_content_disposition(struct client_state *csp, char **header);
869 static jb_err client_host_adder (struct client_state *csp);
870 static jb_err client_xtra_adder (struct client_state *csp);
871 static jb_err connection_close_adder (struct client_state *csp);
873 static jb_err create_forged_referrer(char **header, const char *hostport);
874 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
875 static jb_err handle_conditional_hide_referrer_parameter(char **header,
876 const char *host, const int parameter_conditional_block);
878 const struct parsers client_patterns[] = {
879 { "referer:", 8, client_referrer },
880 { "user-agent:", 11, client_uagent },
881 { "ua-", 3, client_ua },
882 { "from:", 5, client_from },
883 { "cookie:", 7, client_send_cookie },
884 { "x-forwarded-for:", 16, client_x_forwarded },
885 { "Accept-Encoding:", 16, client_accept_encoding },
886 { "TE:", 3, client_te },
887 { "Host:", 5, client_host },
888 { "if-modified-since:", 18, client_if_modified_since },
889 { "Keep-Alive:", 11, crumble },
890 { "connection:", 11, connection },
891 { "proxy-connection:", 17, crumble },
892 { "max-forwards:", 13, client_max_forwards },
893 { "Accept-Language:", 16, client_accept_language },
894 { "if-none-match:", 14, client_if_none_match },
895 { "Range:", 6, client_range },
896 { "Request-Range:", 14, client_range },
897 { "If-Range:", 9, client_range },
898 { "X-Filter:", 9, client_x_filter },
899 { "*", 0, crunch_client_header },
900 { "*", 0, filter_header },
904 const struct parsers server_patterns[] = {
905 { "HTTP/", 5, server_http },
906 { "set-cookie:", 11, server_set_cookie },
907 { "connection:", 11, connection },
908 { "Content-Type:", 13, server_content_type },
909 { "Content-MD5:", 12, server_content_md5 },
910 { "Content-Encoding:", 17, server_content_encoding },
911 { "Transfer-Encoding:", 18, server_transfer_coding },
912 { "Keep-Alive:", 11, crumble },
913 { "content-disposition:", 20, server_content_disposition },
914 { "Last-Modified:", 14, server_last_modified },
915 { "*", 0, crunch_server_header },
916 { "*", 0, filter_header },
920 const struct parsers server_patterns_light[] = {
921 { "Content-Length:", 15, server_content_length },
922 { "Transfer-Encoding:", 18, server_transfer_coding },
924 { "Content-Encoding:", 17, server_content_encoding },
925 #endif /* def FEATURE_ZLIB */
929 const add_header_func_ptr add_client_headers[] = {
932 /* Temporarily disabled: client_accept_encoding_adder, */
933 connection_close_adder,
937 const add_header_func_ptr add_server_headers[] = {
938 connection_close_adder,
942 /*********************************************************************
944 * Function : flush_socket
946 * Description : Write any pending "buffered" content.
949 * 1 : fd = file descriptor of the socket to read
950 * 2 : iob = The I/O buffer to flush, usually csp->iob.
952 * Returns : On success, the number of bytes written are returned (zero
953 * indicates nothing was written). On error, -1 is returned,
954 * and errno is set appropriately. If count is zero and the
955 * file descriptor refers to a regular file, 0 will be
956 * returned without causing any other effect. For a special
957 * file, the results are not portable.
959 *********************************************************************/
960 int flush_socket(jb_socket fd, struct iob *iob)
962 int len = iob->eod - iob->cur;
969 if (write_socket(fd, iob->cur, (size_t)len))
973 iob->eod = iob->cur = iob->buf;
979 /*********************************************************************
981 * Function : add_to_iob
983 * Description : Add content to the buffered page, expanding the
984 * buffer if necessary.
987 * 1 : csp = Current client state (buffers, headers, etc...)
988 * 2 : buf = holds the content to be added to the page
989 * 3 : n = number of bytes to be added
991 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
992 * or buffer limit reached.
994 *********************************************************************/
995 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
997 struct iob *iob = csp->iob;
998 size_t used, offset, need, want;
1001 if (n <= 0) return JB_ERR_OK;
1003 used = (size_t)(iob->eod - iob->buf);
1004 offset = (size_t)(iob->cur - iob->buf);
1005 need = used + (size_t)n + 1;
1008 * If the buffer can't hold the new data, extend it first.
1009 * Use the next power of two if possible, else use the actual need.
1011 if (need > csp->config->buffer_limit)
1013 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1014 return JB_ERR_MEMORY;
1017 if (need > iob->size)
1019 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1021 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1025 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1031 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1032 return JB_ERR_MEMORY;
1035 /* Update the iob pointers */
1036 iob->cur = p + offset;
1037 iob->eod = p + used;
1041 /* copy the new data into the iob buffer */
1042 memcpy(iob->eod, buf, (size_t)n);
1044 /* point to the end of the data */
1047 /* null terminate == cheap insurance */
1056 /*********************************************************************
1058 * Function : decompress_iob
1060 * Description : Decompress buffered page, expanding the
1061 * buffer as necessary. csp->iob->cur
1062 * should point to the the beginning of the
1063 * compressed data block.
1066 * 1 : csp = Current client state (buffers, headers, etc...)
1068 * Returns : JB_ERR_OK on success,
1069 * JB_ERR_MEMORY if out-of-memory limit reached, and
1070 * JB_ERR_COMPRESS if error decompressing buffer.
1072 *********************************************************************/
1073 jb_err decompress_iob(struct client_state *csp)
1075 char *buf; /* new, uncompressed buffer */
1076 char *cur; /* Current iob position (to keep the original
1077 * iob->cur unmodified if we return early) */
1078 size_t bufsize; /* allocated size of the new buffer */
1079 size_t old_size; /* Content size before decompression */
1080 size_t skip_size; /* Number of bytes at the beginning of the iob
1081 that we should NOT decompress. */
1082 int status; /* return status of the inflate() call */
1083 z_stream zstr; /* used by calls to zlib */
1085 assert(csp->iob->cur - csp->iob->buf > 0);
1086 assert(csp->iob->eod - csp->iob->cur > 0);
1088 bufsize = csp->iob->size;
1089 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1090 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1092 cur = csp->iob->cur;
1097 * This is to protect the parsing of gzipped data,
1098 * but it should(?) be valid for deflated data also.
1100 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1101 return JB_ERR_COMPRESS;
1104 if (csp->content_type & CT_GZIP)
1107 * Our task is slightly complicated by the facts that data
1108 * compressed by gzip does not include a zlib header, and
1109 * that there is no easily accessible interface in zlib to
1110 * handle a gzip header. We strip off the gzip header by
1111 * hand, and later inform zlib not to expect a header.
1115 * Strip off the gzip header. Please see RFC 1952 for more
1116 * explanation of the appropriate fields.
1118 if ((*cur++ != (char)0x1f)
1119 || (*cur++ != (char)0x8b)
1120 || (*cur++ != Z_DEFLATED))
1122 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1123 return JB_ERR_COMPRESS;
1129 * XXX: These magic numbers should be replaced
1130 * with macros to give a better idea what they do.
1134 /* The gzip header has reserved bits set; bail out. */
1135 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1136 return JB_ERR_COMPRESS;
1140 /* Skip extra fields if necessary. */
1144 * Skip a given number of bytes, specified
1145 * as a 16-bit little-endian value.
1148 * XXX: This code used to be:
1150 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1152 * which I had to change into:
1154 * cur += *cur++ + (*cur++ << 8);
1156 * at which point gcc43 finally noticed that the value
1157 * of cur is undefined (it depends on which of the
1158 * summands is evaluated first).
1160 * I haven't come across a site where this
1161 * code is actually executed yet, but I hope
1165 skip_bytes = *cur++;
1166 skip_bytes = *cur++ << 8;
1168 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1171 * The number of bytes to skip should be positive
1172 * and we'd like to stay in the buffer.
1174 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1176 log_error(LOG_LEVEL_ERROR,
1177 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1179 return JB_ERR_COMPRESS;
1181 log_error(LOG_LEVEL_INFO,
1182 "Skipping %d bytes for gzip compression. Does this sound right?",
1187 /* Skip the filename if necessary. */
1190 /* A null-terminated string is supposed to follow. */
1191 while (*cur++ && (cur < csp->iob->eod));
1195 /* Skip the comment if necessary. */
1198 /* A null-terminated string is supposed to follow. */
1199 while (*cur++ && (cur < csp->iob->eod));
1202 /* Skip the CRC if necessary. */
1208 if (cur >= csp->iob->eod)
1211 * If the current position pointer reached or passed
1212 * the buffer end, we were obviously tricked to skip
1215 log_error(LOG_LEVEL_ERROR,
1216 "Malformed gzip header detected. Aborting decompression.");
1217 return JB_ERR_COMPRESS;
1221 else if (csp->content_type & CT_DEFLATE)
1224 * XXX: The debug level should be lowered
1225 * before the next stable release.
1227 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1229 * In theory (that is, according to RFC 1950), deflate-compressed
1230 * data should begin with a two-byte zlib header and have an
1231 * adler32 checksum at the end. It seems that in practice only
1232 * the raw compressed data is sent. Note that this means that
1233 * we are not RFC 1950-compliant here, but the advantage is that
1234 * this actually works. :)
1236 * We add a dummy null byte to tell zlib where the data ends,
1237 * and later inform it not to expect a header.
1239 * Fortunately, add_to_iob() has thoughtfully null-terminated
1240 * the buffer; we can just increment the end pointer to include
1247 log_error(LOG_LEVEL_ERROR,
1248 "Unable to determine compression format for decompression");
1249 return JB_ERR_COMPRESS;
1252 /* Set up the fields required by zlib. */
1253 zstr.next_in = (Bytef *)cur;
1254 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1255 zstr.zalloc = Z_NULL;
1256 zstr.zfree = Z_NULL;
1257 zstr.opaque = Z_NULL;
1260 * Passing -MAX_WBITS to inflateInit2 tells the library
1261 * that there is no zlib header.
1263 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1265 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1266 return JB_ERR_COMPRESS;
1270 * Next, we allocate new storage for the inflated data.
1271 * We don't modify the existing iob yet, so in case there
1272 * is error in decompression we can recover gracefully.
1274 buf = zalloc(bufsize);
1277 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1278 return JB_ERR_MEMORY;
1281 assert(bufsize >= skip_size);
1282 memcpy(buf, csp->iob->buf, skip_size);
1283 zstr.avail_out = bufsize - skip_size;
1284 zstr.next_out = (Bytef *)buf + skip_size;
1286 /* Try to decompress the whole stream in one shot. */
1287 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1289 /* We need to allocate more memory for the output buffer. */
1291 char *tmpbuf; /* used for realloc'ing the buffer */
1292 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1295 * If zlib wants more data then there's a problem, because
1296 * the complete compressed file should have been buffered.
1298 if (0 == zstr.avail_in)
1300 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1301 return JB_ERR_COMPRESS;
1305 * If we tried the limit and still didn't have enough
1306 * memory, just give up.
1308 if (bufsize == csp->config->buffer_limit)
1310 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1311 return JB_ERR_MEMORY;
1314 /* Try doubling the buffer size each time. */
1317 /* Don't exceed the buffer limit. */
1318 if (bufsize > csp->config->buffer_limit)
1320 bufsize = csp->config->buffer_limit;
1323 /* Try to allocate the new buffer. */
1324 tmpbuf = realloc(buf, bufsize);
1327 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1329 return JB_ERR_MEMORY;
1333 char *oldnext_out = (char *)zstr.next_out;
1336 * Update the fields for inflate() to use the new
1337 * buffer, which may be in a location different from
1340 zstr.avail_out += bufsize - oldbufsize;
1341 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1344 * Compare with an uglier method of calculating these values
1345 * that doesn't require the extra oldbufsize variable.
1347 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1348 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1349 assert(zstr.avail_out > 0);
1355 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1357 log_error(LOG_LEVEL_ERROR,
1358 "Inconsistent stream state after decompression: %s", zstr.msg);
1360 * XXX: Intentionally no return.
1362 * According to zlib.h, Z_STREAM_ERROR is returned
1363 * "if the stream state was inconsistent".
1365 * I assume in this case inflate()'s status
1366 * would also be something different than Z_STREAM_END
1367 * so this check should be redundant, but lets see.
1371 if (status != Z_STREAM_END)
1373 /* We failed to decompress the stream. */
1374 log_error(LOG_LEVEL_ERROR,
1375 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1376 return JB_ERR_COMPRESS;
1380 * Finally, we can actually update the iob, since the
1381 * decompression was successful. First, free the old
1384 freez(csp->iob->buf);
1386 /* Now, update the iob to use the new buffer. */
1387 csp->iob->buf = buf;
1388 csp->iob->cur = csp->iob->buf + skip_size;
1389 csp->iob->eod = (char *)zstr.next_out;
1390 csp->iob->size = bufsize;
1393 * Make sure the new uncompressed iob obeys some minimal
1394 * consistency conditions.
1396 if ((csp->iob->buf < csp->iob->cur)
1397 && (csp->iob->cur <= csp->iob->eod)
1398 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1400 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1403 log_error(LOG_LEVEL_RE_FILTER,
1404 "Decompression successful. Old size: %d, new size: %d.",
1405 old_size, new_size);
1409 /* zlib thinks this is OK, so lets do the same. */
1410 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1415 /* It seems that zlib did something weird. */
1416 log_error(LOG_LEVEL_ERROR,
1417 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1418 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1419 csp->iob->eod, csp->iob->buf + csp->iob->size);
1420 return JB_ERR_COMPRESS;
1426 #endif /* defined(FEATURE_ZLIB) */
1429 /*********************************************************************
1431 * Function : get_header
1433 * Description : This (odd) routine will parse the csp->iob
1436 * 1 : csp = Current client state (buffers, headers, etc...)
1438 * Returns : Any one of the following:
1440 * 1) a pointer to a dynamically allocated string that contains a header line
1441 * 2) NULL indicating that the end of the header was reached
1442 * 3) "" indicating that the end of the iob was reached before finding
1443 * a complete header line.
1445 *********************************************************************/
1446 char *get_header(struct client_state *csp)
1452 if ((iob->cur == NULL)
1453 || ((p = strchr(iob->cur, '\n')) == NULL))
1455 return(""); /* couldn't find a complete header */
1460 ret = strdup(iob->cur);
1463 /* FIXME No way to handle error properly */
1464 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1469 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1471 /* is this a blank line (i.e. the end of the header) ? */
1483 /*********************************************************************
1485 * Function : get_header_value
1487 * Description : Get the value of a given header from a chained list
1488 * of header lines or return NULL if no such header is
1489 * present in the list.
1492 * 1 : header_list = pointer to list
1493 * 2 : header_name = string with name of header to look for.
1494 * Trailing colon required, capitalization
1497 * Returns : NULL if not found, else value of header
1499 *********************************************************************/
1500 char *get_header_value(const struct list *header_list, const char *header_name)
1502 struct list_entry *cur_entry;
1506 assert(header_list);
1507 assert(header_name);
1508 length = strlen(header_name);
1510 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1514 if (!strncmpic(cur_entry->str, header_name, length))
1517 * Found: return pointer to start of value
1519 ret = (char *) (cur_entry->str + length);
1520 while (*ret && ijb_isspace(*ret)) ret++;
1534 /*********************************************************************
1536 * Function : scan_headers
1538 * Description : Scans headers, applies tags and updates action bits.
1541 * 1 : csp = Current client state (buffers, headers, etc...)
1543 * Returns : JB_ERR_OK
1545 *********************************************************************/
1546 static jb_err scan_headers(struct client_state *csp)
1548 struct list_entry *h; /* Header */
1549 jb_err err = JB_ERR_OK;
1551 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1553 /* Header crunch()ed in previous run? -> ignore */
1554 if (h->str == NULL) continue;
1555 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1556 err = header_tagger(csp, h->str);
1563 /*********************************************************************
1567 * Description : add, delete or modify lines in the HTTP header streams.
1568 * On entry, it receives a linked list of headers space
1569 * that was allocated dynamically (both the list nodes
1570 * and the header contents).
1572 * As a side effect it frees the space used by the original
1575 * XXX: should be split to remove the first_run hack.
1578 * 1 : pats = list of patterns to match against headers
1579 * 2 : more_headers = list of functions to add more
1580 * headers (client or server)
1581 * 3 : csp = Current client state (buffers, headers, etc...)
1583 * Returns : JB_ERR_OK in case off success, or
1584 * JB_ERR_MEMORY on out-of-memory error.
1586 *********************************************************************/
1587 jb_err sed(const struct parsers pats[],
1588 const add_header_func_ptr more_headers[],
1589 struct client_state *csp)
1591 struct list_entry *p;
1592 const struct parsers *v;
1593 const add_header_func_ptr *f;
1594 jb_err err = JB_ERR_OK;
1598 * If filtering is enabled, sed is run twice,
1599 * but most of the work needs to be done only once.
1601 first_run = (more_headers != NULL ) ? 1 : 0;
1603 if (first_run) /* Parse and print */
1607 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1609 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1611 /* Header crunch()ed in previous run? -> ignore */
1612 if (p->str == NULL) continue;
1614 /* Does the current parser handle this header? */
1615 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1617 err = v->parser(csp, (char **)&(p->str));
1621 /* place any additional headers on the csp->headers list */
1622 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1627 else /* Parse only */
1630 * The second run is only needed if the body was modified
1631 * and the content-lenght has changed.
1633 if (strncmpic(csp->http->cmd, "HEAD", 4))
1635 /*XXX: Code duplication */
1636 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1638 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1640 /* Header crunch()ed in previous run? -> ignore */
1641 if (p->str == NULL) continue;
1643 /* Does the current parser handle this header? */
1644 if (strncmpic(p->str, v->str, v->len) == 0)
1646 err = v->parser(csp, (char **)&(p->str));
1658 /*********************************************************************
1660 * Function : header_tagger
1662 * Description : Executes all text substitutions from applying
1663 * tag actions and saves the result as tag.
1665 * XXX: Shares enough code with filter_header() and
1666 * pcrs_filter_response() to warrant some helper functions.
1669 * 1 : csp = Current client state (buffers, headers, etc...)
1670 * 2 : header = Header that is used as tagger input
1672 * Returns : JB_ERR_OK on success and always succeeds
1674 *********************************************************************/
1675 static jb_err header_tagger(struct client_state *csp, char *header)
1677 int wanted_filter_type;
1678 int multi_action_index;
1682 struct file_list *fl;
1683 struct re_filterfile_spec *b;
1684 struct list_entry *tag_name;
1686 int found_filters = 0;
1687 const size_t header_length = strlen(header);
1689 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1691 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1692 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1696 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1697 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1700 /* Check if there are any filters */
1701 for (i = 0; i < MAX_AF_FILES; i++)
1714 if (0 == found_filters)
1716 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1717 "tagging enabled, but no taggers available.");
1721 for (i = 0; i < MAX_AF_FILES; i++)
1724 if ((NULL == fl) || (NULL == fl->f))
1727 * Either there are no filter files
1728 * left, or this filter file just
1729 * contains no valid filters.
1731 * Continue to be sure we don't miss
1732 * valid filter files that are chained
1733 * after empty or invalid ones.
1738 /* For all filters, */
1739 for (b = fl->f; b; b = b->next)
1741 if (b->type != wanted_filter_type)
1743 /* skip the ones we don't care about, */
1746 /* leaving only taggers that could apply, of which we use the ones, */
1747 for (tag_name = csp->action->multi[multi_action_index]->first;
1748 NULL != tag_name; tag_name = tag_name->next)
1750 /* that do apply, and */
1751 if (strcmp(b->name, tag_name->str) == 0)
1753 char *modified_tag = NULL;
1755 size_t size = header_length;
1756 pcrs_job *joblist = b->joblist;
1758 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1760 if (NULL == joblist)
1762 log_error(LOG_LEVEL_RE_FILTER,
1763 "Tagger %s has empty joblist. Nothing to do.", b->name);
1767 /* execute their pcrs_joblist on the header. */
1768 for (job = joblist; NULL != job; job = job->next)
1770 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1774 /* Success, continue with the modified version. */
1783 /* Tagger doesn't match */
1786 /* Regex failure, log it but continue anyway. */
1787 log_error(LOG_LEVEL_ERROR,
1788 "Problems with tagger \'%s\' and header \'%s\': %s",
1789 b->name, *header, pcrs_strerror(hits));
1791 freez(modified_tag);
1795 if (b->dynamic) pcrs_free_joblist(joblist);
1797 /* If this tagger matched */
1803 * There is to technical limitation which makes
1804 * it impossible to use empty tags, but I assume
1805 * no one would do it intentionally.
1808 log_error(LOG_LEVEL_INFO,
1809 "Tagger \'%s\' created an empty tag. Ignored.",
1814 if (!list_contains_item(csp->tags, tag))
1816 if (JB_ERR_OK != enlist(csp->tags, tag))
1818 log_error(LOG_LEVEL_ERROR,
1819 "Insufficient memory to add tag \'%s\', "
1820 "based on tagger \'%s\' and header \'%s\'",
1821 tag, b->name, *header);
1825 char *action_message;
1827 * update the action bits right away, to make
1828 * tagging based on tags set by earlier taggers
1829 * of the same kind possible.
1831 if (update_action_bits_for_tag(csp, tag))
1833 action_message = "Action bits updated accordingly.";
1837 action_message = "No action bits update necessary.";
1840 log_error(LOG_LEVEL_HEADER,
1841 "Tagger \'%s\' added tag \'%s\'. %s",
1842 b->name, tag, action_message);
1847 /* XXX: Is this log-worthy? */
1848 log_error(LOG_LEVEL_HEADER,
1849 "Tagger \'%s\' didn't add tag \'%s\'. "
1850 "Tag already present", b->name, tag);
1853 } /* if the tagger matched */
1854 } /* if the tagger applies */
1855 } /* for every tagger that could apply */
1856 } /* for all filters */
1857 } /* for all filter files */
1862 /* here begins the family of parser functions that reformat header lines */
1864 /*********************************************************************
1866 * Function : filter_header
1868 * Description : Executes all text substitutions from all applying
1869 * +(server|client)-header-filter actions on the header.
1870 * Most of the code was copied from pcrs_filter_response,
1871 * including the rather short variable names
1874 * 1 : csp = Current client state (buffers, headers, etc...)
1875 * 2 : header = On input, pointer to header to modify.
1876 * On output, pointer to the modified header, or NULL
1877 * to remove the header. This function frees the
1878 * original string if necessary.
1880 * Returns : JB_ERR_OK on success and always succeeds
1882 *********************************************************************/
1883 static jb_err filter_header(struct client_state *csp, char **header)
1887 size_t size = strlen(*header);
1889 char *newheader = NULL;
1892 struct file_list *fl;
1893 struct re_filterfile_spec *b;
1894 struct list_entry *filtername;
1896 int i, found_filters = 0;
1897 int wanted_filter_type;
1898 int multi_action_index;
1900 if (csp->flags & CSP_FLAG_NO_FILTERING)
1905 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1907 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1908 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1912 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1913 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1917 * Need to check the set of re_filterfiles...
1919 for (i = 0; i < MAX_AF_FILES; i++)
1932 if (0 == found_filters)
1934 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1935 "header filtering enabled, but no matching filters available.");
1939 for (i = 0; i < MAX_AF_FILES; i++)
1942 if ((NULL == fl) || (NULL == fl->f))
1945 * Either there are no filter files
1946 * left, or this filter file just
1947 * contains no valid filters.
1949 * Continue to be sure we don't miss
1950 * valid filter files that are chained
1951 * after empty or invalid ones.
1956 * For all applying +filter actions, look if a filter by that
1957 * name exists and if yes, execute its pcrs_joblist on the
1960 for (b = fl->f; b; b = b->next)
1962 if (b->type != wanted_filter_type)
1964 /* Skip other filter types */
1968 for (filtername = csp->action->multi[multi_action_index]->first;
1969 filtername ; filtername = filtername->next)
1971 if (strcmp(b->name, filtername->str) == 0)
1973 int current_hits = 0;
1974 pcrs_job *joblist = b->joblist;
1976 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1978 if (NULL == joblist)
1980 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1984 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1985 *header, size, b->name);
1987 /* Apply all jobs from the joblist */
1988 for (job = joblist; NULL != job; job = job->next)
1990 matches = pcrs_execute(job, *header, size, &newheader, &size);
1993 current_hits += matches;
1994 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1996 *header = newheader;
1998 else if ( 0 == matches )
2000 /* Filter doesn't change header */
2006 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2007 *header, b->name, pcrs_strerror(matches));
2008 if (newheader != NULL)
2010 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2016 if (b->dynamic) pcrs_free_joblist(joblist);
2018 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2019 hits += current_hits;
2026 * Additionally checking for hits is important because if
2027 * the continue hack is triggered, server headers can
2028 * arrive empty to separate multiple heads from each other.
2030 if ((0 == size) && hits)
2032 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2040 /*********************************************************************
2042 * Function : connection
2044 * Description : Makes sure that the value of the Connection: header
2045 * is "close" and signals connection_close_adder
2049 * 1 : csp = Current client state (buffers, headers, etc...)
2050 * 2 : header = On input, pointer to header to modify.
2051 * On output, pointer to the modified header, or NULL
2052 * to remove the header. This function frees the
2053 * original string if necessary.
2055 * Returns : JB_ERR_OK on success, or
2056 * JB_ERR_MEMORY on out-of-memory error.
2058 *********************************************************************/
2059 static jb_err connection(struct client_state *csp, char **header)
2061 char *old_header = *header;
2063 /* Do we have a 'Connection: close' header? */
2064 if (strcmpic(*header, "Connection: close"))
2066 /* No, create one */
2067 *header = strdup("Connection: close");
2070 return JB_ERR_MEMORY;
2072 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2076 /* Signal connection_close_adder() to return early. */
2077 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2079 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2083 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2090 /*********************************************************************
2092 * Function : crumble
2094 * Description : This is called if a header matches a pattern to "crunch"
2097 * 1 : csp = Current client state (buffers, headers, etc...)
2098 * 2 : header = On input, pointer to header to modify.
2099 * On output, pointer to the modified header, or NULL
2100 * to remove the header. This function frees the
2101 * original string if necessary.
2103 * Returns : JB_ERR_OK on success, or
2104 * JB_ERR_MEMORY on out-of-memory error.
2106 *********************************************************************/
2107 static jb_err crumble(struct client_state *csp, char **header)
2109 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2115 /*********************************************************************
2117 * Function : crunch_server_header
2119 * Description : Crunch server header if it matches a string supplied by the
2120 * user. Called from `sed'.
2123 * 1 : csp = Current client state (buffers, headers, etc...)
2124 * 2 : header = On input, pointer to header to modify.
2125 * On output, pointer to the modified header, or NULL
2126 * to remove the header. This function frees the
2127 * original string if necessary.
2129 * Returns : JB_ERR_OK on success and always succeeds
2131 *********************************************************************/
2132 static jb_err crunch_server_header(struct client_state *csp, char **header)
2134 const char *crunch_pattern;
2136 /* Do we feel like crunching? */
2137 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2139 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2141 /* Is the current header the lucky one? */
2142 if (strstr(*header, crunch_pattern))
2144 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2153 /*********************************************************************
2155 * Function : server_content_type
2157 * Description : Set the content-type for filterable types (text/.*,
2158 * .*xml.*, javascript and image/gif) unless filtering has been
2159 * forbidden (CT_TABOO) while parsing earlier headers.
2160 * NOTE: Since text/plain is commonly used by web servers
2161 * for files whose correct type is unknown, we don't
2162 * set CT_TEXT for it.
2165 * 1 : csp = Current client state (buffers, headers, etc...)
2166 * 2 : header = On input, pointer to header to modify.
2167 * On output, pointer to the modified header, or NULL
2168 * to remove the header. This function frees the
2169 * original string if necessary.
2171 * Returns : JB_ERR_OK on success, or
2172 * JB_ERR_MEMORY on out-of-memory error.
2174 *********************************************************************/
2175 static jb_err server_content_type(struct client_state *csp, char **header)
2177 /* Remove header if it isn't the first Content-Type header */
2178 if ((csp->content_type & CT_DECLARED))
2181 * Another, slightly slower, way to see if
2182 * we already parsed another Content-Type header.
2184 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2186 log_error(LOG_LEVEL_ERROR,
2187 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2195 * Signal that the Content-Type has been set.
2197 csp->content_type |= CT_DECLARED;
2199 if (!(csp->content_type & CT_TABOO))
2202 * XXX: The assumption that text/plain is a sign of
2203 * binary data seems to be somewhat unreasonable nowadays
2204 * and should be dropped after 3.0.8 is out.
2206 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2207 || strstr(*header, "xml")
2208 || strstr(*header, "application/x-javascript"))
2210 csp->content_type |= CT_TEXT;
2212 else if (strstr(*header, "image/gif"))
2214 csp->content_type |= CT_GIF;
2219 * Are we messing with the content type?
2221 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2224 * Make sure the user doesn't accidently
2225 * change the content type of binary documents.
2227 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2230 *header = strdup("Content-Type: ");
2231 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2235 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2236 return JB_ERR_MEMORY;
2238 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2242 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2243 "It doesn't look like a content type that should be filtered. "
2244 "Enable force-text-mode if you know what you're doing.", *header);
2252 /*********************************************************************
2254 * Function : server_transfer_coding
2256 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2257 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2258 * - Remove header if body was chunked but has been
2259 * de-chunked for filtering.
2262 * 1 : csp = Current client state (buffers, headers, etc...)
2263 * 2 : header = On input, pointer to header to modify.
2264 * On output, pointer to the modified header, or NULL
2265 * to remove the header. This function frees the
2266 * original string if necessary.
2268 * Returns : JB_ERR_OK on success, or
2269 * JB_ERR_MEMORY on out-of-memory error.
2271 *********************************************************************/
2272 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2275 * Turn off pcrs and gif filtering if body compressed
2277 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2281 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2283 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2284 csp->http->cmd, *header);
2285 #endif /* def FEATURE_ZLIB */
2286 csp->content_type = CT_TABOO;
2290 * Raise flag if body chunked
2292 if (strstr(*header, "chunked"))
2294 csp->flags |= CSP_FLAG_CHUNKED;
2297 * If the body was modified, it has been de-chunked first
2298 * and the header must be removed.
2300 * FIXME: If there is more than one transfer encoding,
2301 * only the "chunked" part should be removed here.
2303 if (csp->flags & CSP_FLAG_MODIFIED)
2305 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2314 /*********************************************************************
2316 * Function : server_content_encoding
2318 * Description : This function is run twice for each request,
2319 * unless FEATURE_ZLIB and filtering are disabled.
2321 * The first run is used to check if the content
2322 * is compressed, if FEATURE_ZLIB is disabled
2323 * filtering is then disabled as well, if FEATURE_ZLIB
2324 * is enabled the content is marked for decompression.
2326 * The second run is used to remove the Content-Encoding
2327 * header if the decompression was successful.
2330 * 1 : csp = Current client state (buffers, headers, etc...)
2331 * 2 : header = On input, pointer to header to modify.
2332 * On output, pointer to the modified header, or NULL
2333 * to remove the header. This function frees the
2334 * original string if necessary.
2336 * Returns : JB_ERR_OK on success, or
2337 * JB_ERR_MEMORY on out-of-memory error.
2339 *********************************************************************/
2340 static jb_err server_content_encoding(struct client_state *csp, char **header)
2343 if ((csp->flags & CSP_FLAG_MODIFIED)
2344 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2347 * We successfully decompressed the content,
2348 * and have to clean the header now, so the
2349 * client no longer expects compressed data..
2351 * XXX: There is a difference between cleaning
2352 * and removing it completely.
2354 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2357 else if (strstr(*header, "gzip"))
2359 /* Mark for gzip decompression */
2360 csp->content_type |= CT_GZIP;
2362 else if (strstr(*header, "deflate"))
2364 /* Mark for zlib decompression */
2365 csp->content_type |= CT_DEFLATE;
2367 else if (strstr(*header, "compress"))
2370 * We can't decompress this; therefore we can't filter
2373 csp->content_type |= CT_TABOO;
2375 #else /* !defined(FEATURE_ZLIB) */
2376 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2379 * Body is compressed, turn off pcrs and gif filtering.
2381 csp->content_type |= CT_TABOO;
2384 * Log a warning if the user expects the content to be filtered.
2386 if ((csp->rlist != NULL) &&
2387 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2389 log_error(LOG_LEVEL_INFO,
2390 "Compressed content detected, content filtering disabled. "
2391 "Consider recompiling Privoxy with zlib support or "
2392 "enable the prevent-compression action.");
2395 #endif /* defined(FEATURE_ZLIB) */
2402 /*********************************************************************
2404 * Function : server_content_length
2406 * Description : Adjust Content-Length header if we modified
2410 * 1 : csp = Current client state (buffers, headers, etc...)
2411 * 2 : header = On input, pointer to header to modify.
2412 * On output, pointer to the modified header, or NULL
2413 * to remove the header. This function frees the
2414 * original string if necessary.
2416 * Returns : JB_ERR_OK on success, or
2417 * JB_ERR_MEMORY on out-of-memory error.
2419 *********************************************************************/
2420 static jb_err server_content_length(struct client_state *csp, char **header)
2422 const size_t max_header_length = 80;
2424 /* Regenerate header if the content was modified. */
2425 if (csp->flags & CSP_FLAG_MODIFIED)
2428 *header = (char *) zalloc(max_header_length);
2429 if (*header == NULL)
2431 return JB_ERR_MEMORY;
2434 snprintf(*header, max_header_length, "Content-Length: %d",
2435 (int)csp->content_length);
2436 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2437 (int)csp->content_length);
2444 /*********************************************************************
2446 * Function : server_content_md5
2448 * Description : Crumble any Content-MD5 headers if the document was
2449 * modified. FIXME: Should we re-compute instead?
2452 * 1 : csp = Current client state (buffers, headers, etc...)
2453 * 2 : header = On input, pointer to header to modify.
2454 * On output, pointer to the modified header, or NULL
2455 * to remove the header. This function frees the
2456 * original string if necessary.
2458 * Returns : JB_ERR_OK on success, or
2459 * JB_ERR_MEMORY on out-of-memory error.
2461 *********************************************************************/
2462 static jb_err server_content_md5(struct client_state *csp, char **header)
2464 if (csp->flags & CSP_FLAG_MODIFIED)
2466 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2474 /*********************************************************************
2476 * Function : server_content_disposition
2478 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2479 * Called from `sed'.
2482 * 1 : csp = Current client state (buffers, headers, etc...)
2483 * 2 : header = On input, pointer to header to modify.
2484 * On output, pointer to the modified header, or NULL
2485 * to remove the header. This function frees the
2486 * original string if necessary.
2488 * Returns : JB_ERR_OK on success, or
2489 * JB_ERR_MEMORY on out-of-memory error.
2491 *********************************************************************/
2492 static jb_err server_content_disposition(struct client_state *csp, char **header)
2497 * Are we messing with the Content-Disposition header?
2499 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2505 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2507 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2510 * Blocking content-disposition header
2512 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2519 * Replacing Content-Disposition header
2522 *header = strdup("Content-Disposition: ");
2523 string_append(header, newval);
2525 if (*header != NULL)
2527 log_error(LOG_LEVEL_HEADER,
2528 "Content-Disposition header crunched and replaced with: %s", *header);
2531 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2535 /*********************************************************************
2537 * Function : server_last_modified
2539 * Description : Changes Last-Modified header to the actual date
2540 * to help hide-if-modified-since.
2541 * Called from `sed'.
2544 * 1 : csp = Current client state (buffers, headers, etc...)
2545 * 2 : header = On input, pointer to header to modify.
2546 * On output, pointer to the modified header, or NULL
2547 * to remove the header. This function frees the
2548 * original string if necessary.
2550 * Returns : JB_ERR_OK on success, or
2551 * JB_ERR_MEMORY on out-of-memory error.
2553 *********************************************************************/
2554 static jb_err server_last_modified(struct client_state *csp, char **header)
2557 char buf[BUFFER_SIZE];
2560 #ifdef HAVE_GMTIME_R
2563 struct tm *timeptr = NULL;
2564 time_t now, last_modified;
2566 long int days, hours, minutes, seconds;
2569 * Are we messing with the Last-Modified header?
2571 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2577 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2579 if (0 == strcmpic(newval, "block") )
2582 * Blocking Last-Modified header. Useless but why not.
2584 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2588 else if (0 == strcmpic(newval, "reset-to-request-time"))
2591 * Setting Last-Modified Header to now.
2593 get_http_time(0, buf, sizeof(buf));
2595 *header = strdup("Last-Modified: ");
2596 string_append(header, buf);
2598 if (*header == NULL)
2600 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2604 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2607 else if (0 == strcmpic(newval, "randomize"))
2609 const char *header_time = *header + sizeof("Last-Modified:");
2611 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2613 #ifdef HAVE_GMTIME_R
2614 timeptr = gmtime_r(&now, &gmt);
2615 #elif FEATURE_PTHREAD
2616 pthread_mutex_lock(&gmtime_mutex);
2617 timeptr = gmtime(&now);
2618 pthread_mutex_unlock(&gmtime_mutex);
2620 timeptr = gmtime(&now);
2622 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2624 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2629 rtime = (long int)difftime(now, last_modified);
2638 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2640 rtime = pick_from_range(rtime);
2641 if (negative) rtime *= -1;
2642 last_modified += rtime;
2643 #ifdef HAVE_GMTIME_R
2644 timeptr = gmtime_r(&last_modified, &gmt);
2645 #elif FEATURE_PTHREAD
2646 pthread_mutex_lock(&gmtime_mutex);
2647 timeptr = gmtime(&last_modified);
2648 pthread_mutex_unlock(&gmtime_mutex);
2650 timeptr = gmtime(&last_modified);
2652 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2654 *header = strdup("Last-Modified: ");
2655 string_append(header, newheader);
2657 if (*header == NULL)
2659 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2660 return JB_ERR_MEMORY;
2663 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2665 days = rtime / (3600 * 24);
2666 hours = rtime / 3600 % 24;
2667 minutes = rtime / 60 % 60;
2668 seconds = rtime % 60;
2670 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2671 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2672 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2677 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2686 /*********************************************************************
2688 * Function : client_accept_encoding
2690 * Description : Rewrite the client's Accept-Encoding header so that
2691 * if doesn't allow compression, if the action applies.
2692 * Note: For HTTP/1.0 the absence of the header is enough.
2695 * 1 : csp = Current client state (buffers, headers, etc...)
2696 * 2 : header = On input, pointer to header to modify.
2697 * On output, pointer to the modified header, or NULL
2698 * to remove the header. This function frees the
2699 * original string if necessary.
2701 * Returns : JB_ERR_OK on success, or
2702 * JB_ERR_MEMORY on out-of-memory error.
2704 *********************************************************************/
2705 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2707 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2709 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2713 /* Temporarily disable the correct behaviour to
2714 * work around a PHP bug.
2716 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2718 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2719 * if (*header == NULL)
2721 * return JB_ERR_MEMORY;
2732 /*********************************************************************
2734 * Function : client_te
2736 * Description : Rewrite the client's TE header so that
2737 * if doesn't allow compression, if the action applies.
2740 * 1 : csp = Current client state (buffers, headers, etc...)
2741 * 2 : header = On input, pointer to header to modify.
2742 * On output, pointer to the modified header, or NULL
2743 * to remove the header. This function frees the
2744 * original string if necessary.
2746 * Returns : JB_ERR_OK on success, or
2747 * JB_ERR_MEMORY on out-of-memory error.
2749 *********************************************************************/
2750 static jb_err client_te(struct client_state *csp, char **header)
2752 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2755 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2762 /*********************************************************************
2764 * Function : client_referrer
2766 * Description : Handle the "referer" config setting properly.
2767 * Called from `sed'.
2770 * 1 : csp = Current client state (buffers, headers, etc...)
2771 * 2 : header = On input, pointer to header to modify.
2772 * On output, pointer to the modified header, or NULL
2773 * to remove the header. This function frees the
2774 * original string if necessary.
2776 * Returns : JB_ERR_OK on success, or
2777 * JB_ERR_MEMORY on out-of-memory error.
2779 *********************************************************************/
2780 static jb_err client_referrer(struct client_state *csp, char **header)
2782 const char *parameter;
2783 /* booleans for parameters we have to check multiple times */
2784 int parameter_conditional_block;
2785 int parameter_conditional_forge;
2787 #ifdef FEATURE_FORCE_LOAD
2789 * Since the referrer can include the prefix even
2790 * if the request itself is non-forced, we must
2791 * clean it unconditionally.
2793 * XXX: strclean is too broad
2795 strclean(*header, FORCE_PREFIX);
2796 #endif /* def FEATURE_FORCE_LOAD */
2798 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2800 /* Nothing left to do */
2804 parameter = csp->action->string[ACTION_STRING_REFERER];
2805 assert(parameter != NULL);
2806 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2807 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2809 if (!parameter_conditional_block && !parameter_conditional_forge)
2812 * As conditional-block and conditional-forge are the only
2813 * parameters that rely on the original referrer, we can
2814 * remove it now for all the others.
2819 if (0 == strcmpic(parameter, "block"))
2821 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2824 else if (parameter_conditional_block || parameter_conditional_forge)
2826 return handle_conditional_hide_referrer_parameter(header,
2827 csp->http->hostport, parameter_conditional_block);
2829 else if (0 == strcmpic(parameter, "forge"))
2831 return create_forged_referrer(header, csp->http->hostport);
2835 /* interpret parameter as user-supplied referer to fake */
2836 return create_fake_referrer(header, parameter);
2841 /*********************************************************************
2843 * Function : client_accept_language
2845 * Description : Handle the "Accept-Language" config setting properly.
2846 * Called from `sed'.
2849 * 1 : csp = Current client state (buffers, headers, etc...)
2850 * 2 : header = On input, pointer to header to modify.
2851 * On output, pointer to the modified header, or NULL
2852 * to remove the header. This function frees the
2853 * original string if necessary.
2855 * Returns : JB_ERR_OK on success, or
2856 * JB_ERR_MEMORY on out-of-memory error.
2858 *********************************************************************/
2859 static jb_err client_accept_language(struct client_state *csp, char **header)
2864 * Are we messing with the Accept-Language?
2866 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2868 /*I don't think so*/
2872 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2874 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2877 * Blocking Accept-Language header
2879 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2886 * Replacing Accept-Language header
2889 *header = strdup("Accept-Language: ");
2890 string_append(header, newval);
2892 if (*header == NULL)
2894 log_error(LOG_LEVEL_ERROR,
2895 "Insufficent memory. Accept-Language header crunched without replacement.");
2899 log_error(LOG_LEVEL_HEADER,
2900 "Accept-Language header crunched and replaced with: %s", *header);
2903 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2907 /*********************************************************************
2909 * Function : crunch_client_header
2911 * Description : Crunch client header if it matches a string supplied by the
2912 * user. Called from `sed'.
2915 * 1 : csp = Current client state (buffers, headers, etc...)
2916 * 2 : header = On input, pointer to header to modify.
2917 * On output, pointer to the modified header, or NULL
2918 * to remove the header. This function frees the
2919 * original string if necessary.
2921 * Returns : JB_ERR_OK on success and always succeeds
2923 *********************************************************************/
2924 static jb_err crunch_client_header(struct client_state *csp, char **header)
2926 const char *crunch_pattern;
2928 /* Do we feel like crunching? */
2929 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2931 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2933 /* Is the current header the lucky one? */
2934 if (strstr(*header, crunch_pattern))
2936 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2944 /*********************************************************************
2946 * Function : client_uagent
2948 * Description : Handle the "user-agent" config setting properly
2949 * and remember its original value to enable browser
2950 * bug workarounds. Called from `sed'.
2953 * 1 : csp = Current client state (buffers, headers, etc...)
2954 * 2 : header = On input, pointer to header to modify.
2955 * On output, pointer to the modified header, or NULL
2956 * to remove the header. This function frees the
2957 * original string if necessary.
2959 * Returns : JB_ERR_OK on success, or
2960 * JB_ERR_MEMORY on out-of-memory error.
2962 *********************************************************************/
2963 static jb_err client_uagent(struct client_state *csp, char **header)
2967 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2972 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2979 *header = strdup("User-Agent: ");
2980 string_append(header, newval);
2982 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2984 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2988 /*********************************************************************
2990 * Function : client_ua
2992 * Description : Handle "ua-" headers properly. Called from `sed'.
2995 * 1 : csp = Current client state (buffers, headers, etc...)
2996 * 2 : header = On input, pointer to header to modify.
2997 * On output, pointer to the modified header, or NULL
2998 * to remove the header. This function frees the
2999 * original string if necessary.
3001 * Returns : JB_ERR_OK on success, or
3002 * JB_ERR_MEMORY on out-of-memory error.
3004 *********************************************************************/
3005 static jb_err client_ua(struct client_state *csp, char **header)
3007 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3009 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3017 /*********************************************************************
3019 * Function : client_from
3021 * Description : Handle the "from" config setting properly.
3022 * Called from `sed'.
3025 * 1 : csp = Current client state (buffers, headers, etc...)
3026 * 2 : header = On input, pointer to header to modify.
3027 * On output, pointer to the modified header, or NULL
3028 * to remove the header. This function frees the
3029 * original string if necessary.
3031 * Returns : JB_ERR_OK on success, or
3032 * JB_ERR_MEMORY on out-of-memory error.
3034 *********************************************************************/
3035 static jb_err client_from(struct client_state *csp, char **header)
3039 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3046 newval = csp->action->string[ACTION_STRING_FROM];
3049 * Are we blocking the e-mail address?
3051 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3053 log_error(LOG_LEVEL_HEADER, "crunched From!");
3057 log_error(LOG_LEVEL_HEADER, " modified");
3059 *header = strdup("From: ");
3060 string_append(header, newval);
3062 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3066 /*********************************************************************
3068 * Function : client_send_cookie
3070 * Description : Crunches the "cookie" header if necessary.
3071 * Called from `sed'.
3073 * XXX: Stupid name, doesn't send squat.
3076 * 1 : csp = Current client state (buffers, headers, etc...)
3077 * 2 : header = On input, pointer to header to modify.
3078 * On output, pointer to the modified header, or NULL
3079 * to remove the header. This function frees the
3080 * original string if necessary.
3082 * Returns : JB_ERR_OK on success, or
3083 * JB_ERR_MEMORY on out-of-memory error.
3085 *********************************************************************/
3086 static jb_err client_send_cookie(struct client_state *csp, char **header)
3088 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3090 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3098 /*********************************************************************
3100 * Function : client_x_forwarded
3102 * Description : Handle the "x-forwarded-for" config setting properly,
3103 * also used in the add_client_headers list. Called from `sed'.
3106 * 1 : csp = Current client state (buffers, headers, etc...)
3107 * 2 : header = On input, pointer to header to modify.
3108 * On output, pointer to the modified header, or NULL
3109 * to remove the header. This function frees the
3110 * original string if necessary.
3112 * Returns : JB_ERR_OK on success, or
3113 * JB_ERR_MEMORY on out-of-memory error.
3115 *********************************************************************/
3116 jb_err client_x_forwarded(struct client_state *csp, char **header)
3118 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3121 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3128 /*********************************************************************
3130 * Function : client_max_forwards
3132 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3133 * from the value of the Max-Forwards header field.
3136 * 1 : csp = Current client state (buffers, headers, etc...)
3137 * 2 : header = On input, pointer to header to modify.
3138 * On output, pointer to the modified header, or NULL
3139 * to remove the header. This function frees the
3140 * original string if necessary.
3142 * Returns : JB_ERR_OK on success, or
3143 * JB_ERR_MEMORY on out-of-memory error.
3145 *********************************************************************/
3146 static jb_err client_max_forwards(struct client_state *csp, char **header)
3150 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3151 (0 == strcmpic(csp->http->gpc, "options")))
3153 assert(*(*header+12) == ':');
3154 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3156 if (max_forwards > 0)
3158 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3159 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3160 csp->http->gpc, max_forwards);
3162 else if (max_forwards < 0)
3164 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3170 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3179 /*********************************************************************
3181 * Function : client_host
3183 * Description : If the request URI did not contain host and
3184 * port information, parse and evaluate the Host
3187 * Also, kill ill-formed HOST: headers as sent by
3188 * Apple's iTunes software when used with a proxy.
3191 * 1 : csp = Current client state (buffers, headers, etc...)
3192 * 2 : header = On input, pointer to header to modify.
3193 * On output, pointer to the modified header, or NULL
3194 * to remove the header. This function frees the
3195 * original string if necessary.
3197 * Returns : JB_ERR_OK on success, or
3198 * JB_ERR_MEMORY on out-of-memory error.
3200 *********************************************************************/
3201 static jb_err client_host(struct client_state *csp, char **header)
3206 * If the header field name is all upper-case, chances are that it's
3207 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3208 * not a problem -- they are regenerated later.
3210 if ((*header)[1] == 'O')
3212 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3217 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3218 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3221 if (NULL == (p = strdup((*header)+6)))
3223 return JB_ERR_MEMORY;
3226 if (NULL == (q = strdup(p)))
3229 return JB_ERR_MEMORY;
3232 freez(csp->http->hostport);
3233 csp->http->hostport = p;
3234 freez(csp->http->host);
3235 csp->http->host = q;
3236 q = strchr(csp->http->host, ':');
3239 /* Terminate hostname and evaluate port string */
3241 csp->http->port = atoi(q);
3245 csp->http->port = csp->http->ssl ? 443 : 80;
3248 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3249 csp->http->hostport, csp->http->host, csp->http->port);
3252 /* Signal client_host_adder() to return right away */
3253 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3259 /*********************************************************************
3261 * Function : client_if_modified_since
3263 * Description : Remove or modify the If-Modified-Since header.
3266 * 1 : csp = Current client state (buffers, headers, etc...)
3267 * 2 : header = On input, pointer to header to modify.
3268 * On output, pointer to the modified header, or NULL
3269 * to remove the header. This function frees the
3270 * original string if necessary.
3272 * Returns : JB_ERR_OK on success, or
3273 * JB_ERR_MEMORY on out-of-memory error.
3275 *********************************************************************/
3276 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3279 #ifdef HAVE_GMTIME_R
3282 struct tm *timeptr = NULL;
3286 long int hours, minutes, seconds;
3290 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3293 * The client got an error message because of a temporary problem,
3294 * the problem is gone and the client now tries to revalidate our
3295 * error message on the real server. The revalidation would always
3296 * end with the transmission of the whole document and there is
3297 * no need to expose the bogus If-Modified-Since header.
3299 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3302 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3304 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3306 if ((0 == strcmpic(newval, "block")))
3308 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3311 else /* add random value */
3313 const char *header_time = *header + sizeof("If-Modified-Since:");
3315 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3317 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3322 rtime = strtol(newval, &endptr, 0);
3325 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3326 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3333 rtime = pick_from_range(rtime);
3337 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3340 tm += rtime * (negative ? -1 : 1);
3341 #ifdef HAVE_GMTIME_R
3342 timeptr = gmtime_r(&tm, &gmt);
3343 #elif FEATURE_PTHREAD
3344 pthread_mutex_lock(&gmtime_mutex);
3345 timeptr = gmtime(&tm);
3346 pthread_mutex_unlock(&gmtime_mutex);
3348 timeptr = gmtime(&tm);
3350 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3353 *header = strdup("If-Modified-Since: ");
3354 string_append(header, newheader);
3356 if (*header == NULL)
3358 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3359 return JB_ERR_MEMORY;
3362 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3364 hours = rtime / 3600;
3365 minutes = rtime / 60 % 60;
3366 seconds = rtime % 60;
3368 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3369 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3370 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3380 /*********************************************************************
3382 * Function : client_if_none_match
3384 * Description : Remove the If-None-Match header.
3387 * 1 : csp = Current client state (buffers, headers, etc...)
3388 * 2 : header = On input, pointer to header to modify.
3389 * On output, pointer to the modified header, or NULL
3390 * to remove the header. This function frees the
3391 * original string if necessary.
3393 * Returns : JB_ERR_OK on success, or
3394 * JB_ERR_MEMORY on out-of-memory error.
3396 *********************************************************************/
3397 static jb_err client_if_none_match(struct client_state *csp, char **header)
3399 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3401 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3409 /*********************************************************************
3411 * Function : client_x_filter
3413 * Description : Disables filtering if the client set "X-Filter: No".
3414 * Called from `sed'.
3417 * 1 : csp = Current client state (buffers, headers, etc...)
3418 * 2 : header = On input, pointer to header to modify.
3419 * On output, pointer to the modified header, or NULL
3420 * to remove the header. This function frees the
3421 * original string if necessary.
3423 * Returns : JB_ERR_OK on success
3425 *********************************************************************/
3426 jb_err client_x_filter(struct client_state *csp, char **header)
3428 if ( 0 == strcmpic(*header, "X-Filter: No"))
3430 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3432 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3436 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3438 log_error(LOG_LEVEL_HEADER,
3439 "force-text-mode overruled the client's request to fetch without filtering!");
3443 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3444 csp->flags |= CSP_FLAG_NO_FILTERING;
3445 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3447 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3455 /*********************************************************************
3457 * Function : client_range
3459 * Description : Removes Range, Request-Range and If-Range headers if
3460 * content filtering is enabled. If the client's version
3461 * of the document has been altered by Privoxy, the server
3462 * could interpret the range differently than the client
3463 * intended in which case the user could end up with
3464 * corrupted content.
3467 * 1 : csp = Current client state (buffers, headers, etc...)
3468 * 2 : header = On input, pointer to header to modify.
3469 * On output, pointer to the modified header, or NULL
3470 * to remove the header. This function frees the
3471 * original string if necessary.
3473 * Returns : JB_ERR_OK
3475 *********************************************************************/
3476 static jb_err client_range(struct client_state *csp, char **header)
3478 if (content_filters_enabled(csp->action))
3480 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3481 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3488 /* the following functions add headers directly to the header list */
3490 /*********************************************************************
3492 * Function : client_host_adder
3494 * Description : Adds the Host: header field if it is missing.
3495 * Called from `sed'.
3498 * 1 : csp = Current client state (buffers, headers, etc...)
3500 * Returns : JB_ERR_OK on success, or
3501 * JB_ERR_MEMORY on out-of-memory error.
3503 *********************************************************************/
3504 static jb_err client_host_adder(struct client_state *csp)
3509 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3511 /* Header already set by the client, nothing to do. */
3515 if ( !csp->http->hostport || !*(csp->http->hostport))
3517 /* XXX: When does this happen and why is it OK? */
3518 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3523 * remove 'user:pass@' from 'proto://user:pass@host'
3525 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3531 p = csp->http->hostport;
3534 /* XXX: Just add it, we already made sure that it will be unique */
3535 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3536 err = enlist_unique_header(csp->headers, "Host", p);
3543 /*********************************************************************
3545 * Function : client_accept_encoding_adder
3547 * Description : Add an Accept-Encoding header to the client's request
3548 * that disables compression if the action applies, and
3549 * the header is not already there. Called from `sed'.
3550 * Note: For HTTP/1.0, the absence of the header is enough.
3553 * 1 : csp = Current client state (buffers, headers, etc...)
3555 * Returns : JB_ERR_OK on success, or
3556 * JB_ERR_MEMORY on out-of-memory error.
3558 *********************************************************************/
3559 static jb_err client_accept_encoding_adder(struct client_state *csp)
3561 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3562 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3564 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3572 /*********************************************************************
3574 * Function : client_xtra_adder
3576 * Description : Used in the add_client_headers list. Called from `sed'.
3579 * 1 : csp = Current client state (buffers, headers, etc...)
3581 * Returns : JB_ERR_OK on success, or
3582 * JB_ERR_MEMORY on out-of-memory error.
3584 *********************************************************************/
3585 static jb_err client_xtra_adder(struct client_state *csp)
3587 struct list_entry *lst;
3590 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3591 lst ; lst = lst->next)
3593 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3594 err = enlist(csp->headers, lst->str);
3606 /*********************************************************************
3608 * Function : connection_close_adder
3610 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3611 * support. Adds a "Connection: close" header to csp->headers
3612 * unless the header was already present. Called from `sed'.
3614 * FIXME: This whole function shouldn't be neccessary!
3617 * 1 : csp = Current client state (buffers, headers, etc...)
3619 * Returns : JB_ERR_OK on success, or
3620 * JB_ERR_MEMORY on out-of-memory error.
3622 *********************************************************************/
3623 static jb_err connection_close_adder(struct client_state *csp)
3625 const unsigned int flags = csp->flags;
3628 * Return right away if
3630 * - we're parsing server headers and the server header
3631 * "Connection: close" is already set, or if
3633 * - we're parsing client headers and the client header
3634 * "Connection: close" is already set.
3636 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3637 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3638 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3639 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3644 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3646 return enlist(csp->headers, "Connection: close");
3650 /*********************************************************************
3652 * Function : server_http
3654 * Description : - Save the HTTP Status into csp->http->status
3655 * - Set CT_TABOO to prevent filtering if the answer
3656 * is a partial range (HTTP status 206)
3657 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3661 * 1 : csp = Current client state (buffers, headers, etc...)
3662 * 2 : header = On input, pointer to header to modify.
3663 * On output, pointer to the modified header, or NULL
3664 * to remove the header. This function frees the
3665 * original string if necessary.
3667 * Returns : JB_ERR_OK on success, or
3668 * JB_ERR_MEMORY on out-of-memory error.
3670 *********************************************************************/
3671 static jb_err server_http(struct client_state *csp, char **header)
3673 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3674 if (csp->http->status == 206)
3676 csp->content_type = CT_TABOO;
3679 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3681 /* XXX: Should we do a real validity check here? */
3682 if (strlen(*header) > 8)
3685 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3690 * XXX: Should we block the request or
3691 * enlist a valid status code line here?
3693 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3694 "Downgrading to HTTP/1.0 impossible.");
3702 /*********************************************************************
3704 * Function : server_set_cookie
3706 * Description : Handle the server "cookie" header properly.
3707 * Log cookie to the jar file. Then "crunch",
3708 * accept or rewrite it to a session cookie.
3709 * Called from `sed'.
3711 * TODO: Allow the user to specify a new expiration
3712 * time to cause the cookie to expire even before the
3713 * browser is closed.
3716 * 1 : csp = Current client state (buffers, headers, etc...)
3717 * 2 : header = On input, pointer to header to modify.
3718 * On output, pointer to the modified header, or NULL
3719 * to remove the header. This function frees the
3720 * original string if necessary.
3722 * Returns : JB_ERR_OK on success, or
3723 * JB_ERR_MEMORY on out-of-memory error.
3725 *********************************************************************/
3726 static jb_err server_set_cookie(struct client_state *csp, char **header)
3733 #ifdef FEATURE_COOKIE_JAR
3734 if (csp->config->jar)
3737 * Write timestamp into outbuf.
3739 * Complex because not all OSs have tm_gmtoff or
3740 * the %z field in strftime()
3742 char tempbuf[ BUFFER_SIZE ];
3744 #ifdef HAVE_LOCALTIME_R
3745 tm_now = *localtime_r(&now, &tm_now);
3746 #elif FEATURE_PTHREAD
3747 pthread_mutex_lock(&localtime_mutex);
3748 tm_now = *localtime (&now);
3749 pthread_mutex_unlock(&localtime_mutex);
3751 tm_now = *localtime (&now);
3753 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3755 /* strlen("set-cookie: ") = 12 */
3756 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3758 #endif /* def FEATURE_COOKIE_JAR */
3760 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3762 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3765 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3767 /* Flag whether or not to log a message */
3770 /* A variable to store the tag we're working on */
3773 /* Skip "Set-Cookie:" (11 characters) in header */
3774 cur_tag = *header + 11;
3776 /* skip whitespace between "Set-Cookie:" and value */
3777 while (*cur_tag && ijb_isspace(*cur_tag))
3782 /* Loop through each tag in the cookie */
3786 char *next_tag = strchr(cur_tag, ';');
3787 if (next_tag != NULL)
3789 /* Skip the ';' character itself */
3792 /* skip whitespace ";" and start of tag */
3793 while (*next_tag && ijb_isspace(*next_tag))
3800 /* "Next tag" is the end of the string */
3801 next_tag = cur_tag + strlen(cur_tag);
3805 * Check the expiration date to see
3806 * if the cookie is still valid, if yes,
3807 * rewrite it to a session cookie.
3809 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3811 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3813 /* Did we detect the date properly? */
3814 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3817 * Nope, treat it as if it was still valid.
3819 * XXX: Should we remove the whole cookie instead?
3821 log_error(LOG_LEVEL_ERROR,
3822 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3823 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3829 * Yes. Check if the cookie is still valid.
3831 * If the cookie is already expired it's probably
3832 * a delete cookie and even if it isn't, the browser
3833 * will discard it anyway.
3837 * XXX: timegm() isn't available on some AmigaOS
3838 * versions and our replacement doesn't work.
3840 * Our options are to either:
3842 * - disable session-cookies-only completely if timegm
3845 * - to simply remove all expired tags, like it has
3846 * been done until Privoxy 3.0.6 and to live with
3847 * the consequence that it can cause login/logout
3848 * problems on servers that don't validate their
3849 * input properly, or
3851 * - to replace it with mktime in which
3852 * case there is a slight chance of valid cookies
3853 * passing as already expired.
3855 * This is the way it's currently done and it's not
3856 * as bad as it sounds. If the missing GMT offset is
3857 * enough to change the result of the expiration check
3858 * the cookie will be only valid for a few hours
3859 * anyway, which in many cases will be shorter
3860 * than a browser session.
3862 if (cookie_time - now < 0)
3864 log_error(LOG_LEVEL_HEADER,
3865 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3866 /* Just in case some clown sets more then one expiration date */
3872 * Still valid, delete expiration date by copying
3873 * the rest of the string over it.
3875 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3876 * since the behaviour of strcpy is undefined for overlapping
3879 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3881 /* That changed the header, need to issue a log message */
3885 * Note that the next tag has now been moved to *cur_tag,
3886 * so we do not need to update the cur_tag pointer.
3894 /* Move on to next cookie tag */
3901 assert(NULL != *header);
3902 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3911 #ifdef FEATURE_FORCE_LOAD
3912 /*********************************************************************
3914 * Function : strclean
3916 * Description : In-Situ-Eliminate all occurances of substring in
3920 * 1 : string = string to clean
3921 * 2 : substring = substring to eliminate
3923 * Returns : Number of eliminations
3925 *********************************************************************/
3926 int strclean(const char *string, const char *substring)
3932 len = strlen(substring);
3934 while((pos = strstr(string, substring)) != NULL)
3941 while (*p++ != '\0');
3948 #endif /* def FEATURE_FORCE_LOAD */
3951 /*********************************************************************
3953 * Function : parse_header_time
3955 * Description : Parses time formats used in HTTP header strings
3956 * to get the numerical respresentation.
3959 * 1 : header_time = HTTP header time as string.
3960 * 2 : result = storage for header_time in seconds
3962 * Returns : JB_ERR_OK if the time format was recognized, or
3963 * JB_ERR_PARSE otherwise.
3965 *********************************************************************/
3966 static jb_err parse_header_time(const char *header_time, time_t *result)
3971 * Zero out gmt to prevent time zone offsets.
3973 * While this is only necessary on some platforms
3974 * (mingw32 for example), I don't know how to
3975 * detect these automatically and doing it everywhere
3978 memset(&gmt, 0, sizeof(gmt));
3980 /* Tue, 02 Jun 2037 20:00:00 */
3981 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3982 /* Tue, 02-Jun-2037 20:00:00 */
3983 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3984 /* Tue, 02-Jun-37 20:00:00 */
3985 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3986 /* Tuesday, 02-Jun-2037 20:00:00 */
3987 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3988 /* Tuesday Jun 02 20:00:00 2037 */
3989 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3991 return JB_ERR_PARSE;
3994 *result = timegm(&gmt);
4001 /*********************************************************************
4003 * Function : get_destination_from_headers
4005 * Description : Parse the "Host:" header to get the request's destination.
4006 * Only needed if the client's request was forcefully
4007 * redirected into Privoxy.
4009 * Code mainly copied from client_host() which is currently
4010 * run too late for this purpose.
4013 * 1 : headers = List of headers (one of them hopefully being
4014 * the "Host:" header)
4015 * 2 : http = storage for the result (host, port and hostport).
4017 * Returns : JB_ERR_MEMORY in case of memory problems,
4018 * JB_ERR_PARSE if the host header couldn't be found,
4019 * JB_ERR_OK otherwise.
4021 *********************************************************************/
4022 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4028 host = get_header_value(headers, "Host:");
4032 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4033 return JB_ERR_PARSE;
4036 if (NULL == (p = strdup((host))))
4038 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4039 return JB_ERR_MEMORY;
4042 if (NULL == (q = strdup(p)))
4045 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4046 return JB_ERR_MEMORY;
4049 freez(http->hostport);
4053 q = strchr(http->host, ':');
4056 /* Terminate hostname and evaluate port string */
4058 http->port = atoi(q);
4062 http->port = http->ssl ? 443 : 80;
4065 /* Rebuild request URL */
4067 http->url = strdup(http->ssl ? "https://" : "http://");
4068 string_append(&http->url, http->hostport);
4069 string_append(&http->url, http->path);
4070 if (http->url == NULL)
4072 return JB_ERR_MEMORY;
4075 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4083 /*********************************************************************
4085 * Function : create_forged_referrer
4087 * Description : Helper for client_referrer to forge a referer as
4088 * 'http://[hostname:port/' to fool stupid
4089 * checks for in-site links
4092 * 1 : header = Pointer to header pointer
4093 * 2 : hostport = Host and optionally port as string
4095 * Returns : JB_ERR_OK in case of success, or
4096 * JB_ERR_MEMORY in case of memory problems.
4098 *********************************************************************/
4099 static jb_err create_forged_referrer(char **header, const char *hostport)
4101 assert(NULL == *header);
4103 *header = strdup("Referer: http://");
4104 string_append(header, hostport);
4105 string_append(header, "/");
4107 if (NULL == *header)
4109 return JB_ERR_MEMORY;
4112 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4119 /*********************************************************************
4121 * Function : create_fake_referrer
4123 * Description : Helper for client_referrer to create a fake referrer
4124 * based on a string supplied by the user.
4127 * 1 : header = Pointer to header pointer
4128 * 2 : hosthost = Referrer to fake
4130 * Returns : JB_ERR_OK in case of success, or
4131 * JB_ERR_MEMORY in case of memory problems.
4133 *********************************************************************/
4134 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4136 assert(NULL == *header);
4138 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4140 log_error(LOG_LEVEL_HEADER,
4141 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4143 *header = strdup("Referer: ");
4144 string_append(header, fake_referrer);
4146 if (NULL == *header)
4148 return JB_ERR_MEMORY;
4151 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4158 /*********************************************************************
4160 * Function : handle_conditional_hide_referrer_parameter
4162 * Description : Helper for client_referrer to crunch or forge
4163 * the referrer header if the host has changed.
4166 * 1 : header = Pointer to header pointer
4167 * 2 : host = The target host (may include the port)
4168 * 3 : parameter_conditional_block = Boolean to signal
4169 * if we're in conditional-block mode. If not set,
4170 * we're in conditional-forge mode.
4172 * Returns : JB_ERR_OK in case of success, or
4173 * JB_ERR_MEMORY in case of memory problems.
4175 *********************************************************************/
4176 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4177 const char *host, const int parameter_conditional_block)
4179 char *referer = strdup(*header);
4180 const size_t hostlenght = strlen(host);
4182 if (NULL == referer)
4185 return JB_ERR_MEMORY;
4188 /* referer begins with 'Referer: http[s]://' */
4189 if (hostlenght < (strlen(referer)-17))
4192 * Shorten referer to make sure the referer is blocked
4193 * if www.example.org/www.example.com-shall-see-the-referer/
4194 * links to www.example.com/
4196 referer[hostlenght+17] = '\0';
4198 if (NULL == strstr(referer, host))
4200 /* Host has changed */
4201 if (parameter_conditional_block)
4203 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4210 return create_forged_referrer(header, host);