1 const char parsers_rcs[] = "$Id: parsers.c,v 1.116 2007/12/01 13:04:22 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.116 2007/12/01 13:04:22 fabiankeil
48 * Fix a crash on mingw32 with some Last Modified times in the future.
50 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
51 * Remove a "can't happen" error block which, over
52 * time, mutated into a "guaranteed to happen" block.
54 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
55 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
56 * - Use shiny new content_filters_enabled() in client_range().
58 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
59 * I forgot about Poland.
61 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
62 * Remove Range and If-Range headers if content filtering is enabled.
64 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
65 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
66 * client_cookie_adder() to make sure send-vanilla-wafer can be
67 * controlled through tags (and thus regression-tested).
69 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
70 * - Remove "scanning headers for" log message again.
71 * - Some more whitespace fixes.
73 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
74 * Refactor client_referrer() and add conditional-forge parameter.
76 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
77 * A bunch of whitespace fixes, pointy hat to me.
79 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
80 * Fix possible memory corruption in server_http, make sure it's not
81 * executed for ordinary server headers and mark some problems for later.
83 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
84 * Let content-type-overwrite{} honour force-text-mode again.
86 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
87 * - Add prototpyes for the header parsers and make them static.
88 * - Comment out client_accept_encoding_adder() which isn't used right now.
90 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
91 * Move the ACTION_FORCE_TEXT_MODE check out of
92 * server_content_type(). Signal other functions
93 * whether or not a content type has been declared.
94 * Part of the fix for BR#1750917.
96 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
97 * Change sed() to return a jb_err in preparation for forward-override{}.
99 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
100 * Adjust "X-Filter: No" to disable dedicated header filters.
102 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
103 * Streamline client_cookie_adder().
105 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
106 * Make sure filters with dynamic jobs actually use them.
108 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
109 * - Introduce dynamic pcrs jobs that can resolve variables.
110 * - Remove unnecessary update_action_bits_for_all_tags() call.
112 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
113 * - Make tagging based on tags set by earlier taggers
114 * of the same kind possible.
115 * - Log whether or not new tags cause action bits updates
116 * (in which case a matching tag-pattern section exists).
117 * - Log if the user tries to set a tag that is already set.
119 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
120 * Introduce tags as alternative way to specify which
121 * actions apply to a request. At the moment tags can be
122 * created based on client and server headers.
124 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
125 * Log a warning if the content is compressed, filtering is
126 * enabled and Privoxy was compiled without zlib support.
129 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
130 * - Fix warnings when compiled with glibc.
131 * - Don't use crumble() for cookie crunching.
132 * - Move cookie time parsing into parse_header_time().
133 * - Let parse_header_time() return a jb_err code
134 * instead of a pointer that can only be used to
135 * check for NULL anyway.
137 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
138 * - Add better protection against malicious gzip headers.
139 * - Stop logging the first hundred bytes of decompressed content.
140 * It looks like it's working and there is always debug 16.
141 * - Log the content size after decompression in decompress_iob()
142 * instead of pcrs_filter_response().
144 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
145 * - Use dedicated header filter actions instead of abusing "filter".
146 * Replace "filter-client-headers" and "filter-client-headers"
147 * with "server-header-filter" and "client-header-filter".
148 * - Remove filter_client_header() and filter_client_header(),
149 * filter_header() now checks the shiny new
150 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
152 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
153 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
154 * - Handle "Cookie:" and "Connection:" headers a bit smarter
155 * (don't crunch them just to recreate them later on).
156 * - Add another non-standard time format for the cookie
157 * expiration date detection.
158 * - Fix a valgrind warning.
160 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
161 * Improve cookie expiration date detection.
163 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
164 * Don't run server_content_length() the first time
165 * sed() parses server headers; only adjust the
166 * Content-Length header if the page was modified.
168 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
169 * Fix log messages regarding the cookie time format
170 * (cookie and request URL were mixed up).
172 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
173 * - Let decompress_iob()
174 * - not corrupt the content if decompression fails
175 * early. (the first byte(s) were lost).
176 * - use pointer arithmetics with defined outcome for
178 * - Use a different kludge to remember a failed decompression.
180 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
181 * Search for Max-Forwards headers case-insensitive,
182 * don't generate the "501 unsupported" message for invalid
183 * Max-Forwards values and don't increase negative ones.
185 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
186 * - Let server_set_cookie() check the expiration date
187 * of cookies and don't touch the ones that are already
188 * expired. Fixes problems with low quality web applications
189 * as described in BR 932612.
191 * - Adjust comment in client_max_forwards to reality;
192 * remove invalid Max-Forwards headers.
194 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
195 * Stop filter_header() from unintentionally removing
196 * empty header lines that were enlisted by the continue
199 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
200 * - Repeat the request URL before logging any headers.
201 * Makes reading the log easier in case of simultaneous requests.
202 * - If there are more than one Content-Type headers in one request,
203 * use the first one and remove the others.
204 * - Remove "newval" variable in server_content_type().
205 * It's only used once.
207 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
208 * Correct a cast, check inflateEnd() exit code
209 * to see if we have to, replace sprintf calls
212 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
213 * Integrate a modified version of Wil Mahan's
214 * zlib patch (PR #895531).
216 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
217 * Skip empty filter files in filter_header()
218 * but don't ignore the ones that come afterwards.
219 * Fixes BR 1619208, this time for real.
221 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
222 * Reverted parts of my last commit
223 * to keep error handling working.
225 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
226 * Fixed gcc43 conversion warnings.
228 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
229 * Bringing back the "useless" localtime() call
230 * I removed in revision 1.67. On some platforms
231 * it's necessary to prevent time zone offsets.
233 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
234 * Rebuild request URL in get_destination_from_headers()
235 * to make sure redirect{pcrs command} works as expected
236 * for intercepted requests.
238 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
239 * Added get_destination_from_headers().
241 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
242 * Make pthread mutex locking more generic. Instead of
243 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
244 * and use mutex locking unless there is an _r function
245 * available. Better safe than sorry.
247 * Fixes "./configure --disable-pthread" and should result
248 * in less threading-related problems on pthread-using platforms,
249 * but it still doesn't fix BR#1122404.
251 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
252 * The special header "X-Filter: No" now disables
253 * header filtering as well.
255 * Revision 1.73 2006/09/23 13:26:38 roro
256 * Replace TABs by spaces in source code.
258 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
259 * Don't print a log message every time filter_headers is
260 * entered or left. It only creates noise without any real
263 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
264 * Fix +hide-if-modified-since{-n}.
266 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
267 * Have hide-if-modified-since interpret the random
268 * range value as minutes instead of hours. Allows
269 * more fine-grained configuration.
271 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
272 * Always have parse_header_time return a pointer
273 * that actual makes sense, even though we currently
274 * only need it to detect problems.
276 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
277 * Added config option enable-remote-http-toggle
278 * to specify if Privoxy should recognize special
279 * headers (currently only X-Filter) to change its
280 * behaviour. Disabled by default.
282 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
283 * After filtering de-chunked instances, remove
284 * "Transfer-Encoding" header entirely instead of changing
285 * it to "Transfer-Encoding: identity", which is invalid.
286 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
288 * Don't use localtime in parse_header_time. An empty time struct
289 * is good enough, it gets overwritten by strptime anyway.
291 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
292 * Use gmtime_r if available, fallback to gmtime with mutex
293 * protection for MacOSX and use vanilla gmtime for the rest.
295 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
296 * Changed client_referrer to use the right type (size_t) for
297 * hostlenght and to shorten the temporary referrer string with
298 * '\0' instead of adding a useless line break.
300 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
301 * - Back to timegm() using GnuPG's replacement if necessary.
302 * Using mktime() and localtime() could add a on hour offset if
303 * the randomize factor was big enough to lead to a summer/wintertime
306 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
308 * - Moved randomization code into pick_from_range().
310 * - Changed parse_header_time definition.
311 * time_t isn't guaranteed to be signed and
312 * if it isn't, -1 isn't available as error code.
313 * Changed some variable types in client_if_modified_since()
314 * because of the same reason.
316 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
317 * OS/2 compilation compatibility fixups
319 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
320 * Changed include from strptime.c to strptime.h
322 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
323 * Split filter-headers{} into filter-client-headers{}
324 * and filter-server-headers{}.
325 * Added parse_header_time() to share some code.
326 * Replaced timegm() with mktime().
328 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
329 * Windows service integration
331 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
332 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
334 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
335 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
336 * with what was really the latest development (the v_3_0_branch branch)
338 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
339 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
341 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
342 * Add the ability to check jpeg images for invalid
343 * lengths of comment blocks. Defensive strategy
344 * against the exploit:
345 * Microsoft Security Bulletin MS04-028
346 * Buffer Overrun in JPEG Processing (GDI+) Could
347 * Allow Code Execution (833987)
348 * Enabled with +inspect-jpegs in actions files.
350 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
351 * Excluded text/plain objects from filtering. This fixes a
352 * couple of client-crashing, download corruption and
353 * Privoxy performance issues, whose root cause lies in
354 * web servers labelling content of unknown type as text/plain.
356 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
357 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
359 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
360 * Completing the previous change
362 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
363 * Added temporary workaround for bug in PHP < 4.2.3
365 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
366 * 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.
368 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
369 * Fix typo: supressed -> suppressed
371 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
372 * Improved cookie logging
374 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
375 * Added basic support for OPTIONS and TRACE HTTP methods:
376 * - New parser function client_max_forwards which decrements
377 * the Max-Forwards HTTP header field of OPTIONS and TRACE
378 * requests by one before forwarding
379 * - New parser function client_host which extracts the host
380 * and port information from the HTTP header field if the
381 * request URI was not absolute
382 * - Don't crumble and re-add the Host: header, but only generate
383 * and append if missing
385 * Revision 1.56 2002/05/12 15:34:22 jongfoster
386 * Fixing typo in a comment
388 * Revision 1.55 2002/05/08 16:01:07 oes
389 * Optimized add_to_iob:
390 * - Use realloc instead of malloc(), memcpy(), free()
391 * - Expand to powers of two if possible, to get
392 * O(log n) reallocs instead of O(n).
393 * - Moved check for buffer limit here from chat
394 * - Report failure via returncode
396 * Revision 1.54 2002/04/02 15:03:16 oes
397 * Tiny code cosmetics
399 * Revision 1.53 2002/03/26 22:29:55 swa
400 * we have a new homepage!
402 * Revision 1.52 2002/03/24 13:25:43 swa
403 * name change related issues
405 * Revision 1.51 2002/03/13 00:27:05 jongfoster
408 * Revision 1.50 2002/03/12 01:45:35 oes
409 * More verbose logging
411 * Revision 1.49 2002/03/09 20:03:52 jongfoster
412 * - Making various functions return int rather than size_t.
413 * (Undoing a recent change). Since size_t is unsigned on
414 * Windows, functions like read_socket that return -1 on
415 * error cannot return a size_t.
417 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
418 * crashes, and also frequently caused JB to jump to 100%
419 * CPU and stay there. (Because it thought it had just
420 * read ((unsigned)-1) == 4Gb of data...)
422 * - The signature of write_socket has changed, it now simply
423 * returns success=0/failure=nonzero.
425 * - Trying to get rid of a few warnings --with-debug on
426 * Windows, I've introduced a new type "jb_socket". This is
427 * used for the socket file descriptors. On Windows, this
428 * is SOCKET (a typedef for unsigned). Everywhere else, it's
429 * an int. The error value can't be -1 any more, so it's
430 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
431 * Windows it maps to the #define INVALID_SOCKET.)
433 * - The signature of bind_port has changed.
435 * Revision 1.48 2002/03/07 03:46:53 oes
436 * Fixed compiler warnings etc
438 * Revision 1.47 2002/02/20 23:15:13 jongfoster
439 * Parsing functions now handle out-of-memory gracefully by returning
442 * Revision 1.46 2002/01/17 21:03:47 jongfoster
443 * Moving all our URL and URL pattern parsing code to urlmatch.c.
445 * Revision 1.45 2002/01/09 14:33:03 oes
446 * Added support for localtime_r.
448 * Revision 1.44 2001/12/14 01:22:54 steudten
449 * Remove 'user:pass@' from 'proto://user:pass@host' for the
450 * new added header 'Host: ..'. (See Req ID 491818)
452 * Revision 1.43 2001/11/23 00:26:38 jongfoster
453 * Fixing two really stupid errors in my previous commit
455 * Revision 1.42 2001/11/22 21:59:30 jongfoster
456 * Adding code to handle +no-cookies-keep
458 * Revision 1.41 2001/11/05 23:43:05 steudten
459 * Add time+date to log files.
461 * Revision 1.40 2001/10/26 20:13:09 jongfoster
462 * ctype.h is needed in Windows, too.
464 * Revision 1.39 2001/10/26 17:40:04 oes
465 * Introduced get_header_value()
466 * Removed http->user_agent, csp->referrer and csp->accept_types
467 * Removed client_accept()
469 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
470 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
471 * threads to call select() simultaneously. So, it's time to do a real, live,
472 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
473 * (native). Both versions will work, but using __OS2__ offers multi-threading.
475 * Revision 1.37 2001/10/23 21:36:02 jongfoster
476 * Documenting sed()'s error behaviou (doc change only)
478 * Revision 1.36 2001/10/13 12:51:51 joergs
479 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
480 * force-load), instead crumble Host: and add it (again) in client_host_adder
481 * (in case we get a HTTP/1.0 request without Host: header and forward it to
482 * a HTTP/1.1 server/proxy).
484 * Revision 1.35 2001/10/09 22:39:21 jongfoster
485 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
488 * Revision 1.34 2001/10/07 18:50:55 oes
489 * Added server_content_encoding, renamed server_transfer_encoding
491 * Revision 1.33 2001/10/07 18:04:49 oes
492 * Changed server_http11 to server_http and its pattern to "HTTP".
493 * Additional functionality: it now saves the HTTP status into
494 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
496 * Revision 1.32 2001/10/07 15:43:28 oes
497 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
498 * client_te and client_accept_encoding_adder, triggered by the new
499 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
500 * changed to allow only identity and chunked, and the TE header is
501 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
503 * parse_http_request no longer does anything than parsing. The rewriting
504 * of http->cmd and version mangling are gone. It now also recognizes
505 * the put and delete methods and saves the url in http->url. Removed
508 * renamed content_type and content_length to have the server_ prefix
510 * server_content_type now only works if csp->content_type != CT_TABOO
512 * added server_transfer_encoding, which
513 * - Sets CT_TABOO to prohibit filtering if encoding compresses
514 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
515 * - Change from "chunked" to "identity" if body was chunked
516 * but has been de-chunked for filtering.
518 * added server_content_md5 which crunches any Content-MD5 headers
519 * if the body was modified.
521 * made server_http11 conditional on +downgrade action
523 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
525 * Revision 1.31 2001/10/05 14:25:02 oes
526 * Crumble Keep-Alive from Server
528 * Revision 1.30 2001/09/29 12:56:03 joergs
529 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
531 * Revision 1.29 2001/09/24 21:09:24 jongfoster
532 * Fixing 2 memory leaks that Guy spotted, where the paramater to
533 * enlist() was not being free()d.
535 * Revision 1.28 2001/09/22 16:32:28 jongfoster
536 * Removing unused #includes.
538 * Revision 1.27 2001/09/20 15:45:25 steudten
540 * add casting from size_t to int for printf()
541 * remove local variable shadow s2
543 * Revision 1.26 2001/09/16 17:05:14 jongfoster
544 * Removing unused #include showarg.h
546 * Revision 1.25 2001/09/16 13:21:27 jongfoster
547 * Changes to use new list functions.
549 * Revision 1.24 2001/09/13 23:05:50 jongfoster
550 * Changing the string paramater to the header parsers a "const".
552 * Revision 1.23 2001/09/12 18:08:19 steudten
554 * In parse_http_request() header rewriting miss the host value, so
555 * from http://www.mydomain.com the result was just " / " not
556 * http://www.mydomain.com/ in case we forward.
558 * Revision 1.22 2001/09/10 10:58:53 oes
559 * Silenced compiler warnings
561 * Revision 1.21 2001/07/31 14:46:00 oes
562 * - Persistant connections now suppressed
563 * - sed() no longer appends empty header to csp->headers
565 * Revision 1.20 2001/07/30 22:08:36 jongfoster
566 * Tidying up #defines:
567 * - All feature #defines are now of the form FEATURE_xxx
568 * - Permanently turned off WIN_GUI_EDIT
569 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
571 * Revision 1.19 2001/07/25 17:21:54 oes
572 * client_uagent now saves copy of User-Agent: header value
574 * Revision 1.18 2001/07/13 14:02:46 oes
575 * - Included fix to repair broken HTTP requests that
576 * don't contain a path, not even '/'.
577 * - Removed all #ifdef PCRS
578 * - content_type now always inspected and classified as
579 * text, gif or other.
580 * - formatting / comments
582 * Revision 1.17 2001/06/29 21:45:41 oes
583 * Indentation, CRLF->LF, Tab-> Space
585 * Revision 1.16 2001/06/29 13:32:42 oes
587 * - Adapted free_http_request
588 * - Removed logentry from cancelled commit
590 * Revision 1.15 2001/06/03 19:12:38 oes
591 * deleted const struct interceptors
593 * Revision 1.14 2001/06/01 18:49:17 jongfoster
594 * Replaced "list_share" with "list" - the tiny memory gain was not
595 * worth the extra complexity.
597 * Revision 1.13 2001/05/31 21:30:33 jongfoster
598 * Removed list code - it's now in list.[ch]
599 * Renamed "permission" to "action", and changed many features
600 * to use the actions file rather than the global config.
602 * Revision 1.12 2001/05/31 17:33:13 oes
606 * Revision 1.11 2001/05/29 20:11:19 joergs
607 * '/ * inside comment' warning removed.
609 * Revision 1.10 2001/05/29 09:50:24 jongfoster
610 * Unified blocklist/imagelist/permissionslist.
611 * File format is still under discussion, but the internal changes
614 * Also modified interceptor behaviour:
615 * - We now intercept all URLs beginning with one of the following
616 * prefixes (and *only* these prefixes):
618 * * http://ijbswa.sf.net/config/
619 * * http://ijbswa.sourceforge.net/config/
620 * - New interceptors "home page" - go to http://i.j.b/ to see it.
621 * - Internal changes so that intercepted and fast redirect pages
622 * are not replaced with an image.
623 * - Interceptors now have the option to send a binary page direct
624 * to the client. (i.e. ijb-send-banner uses this)
625 * - Implemented show-url-info interceptor. (Which is why I needed
626 * the above interceptors changes - a typical URL is
627 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
628 * The previous mechanism would not have intercepted that, and
629 * if it had been intercepted then it then it would have replaced
632 * Revision 1.9 2001/05/28 17:26:33 jongfoster
633 * Fixing segfault if last header was crunched.
634 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
635 * can use the cross-platform sprintf() instead.)
637 * Revision 1.8 2001/05/27 22:17:04 oes
639 * - re_process_buffer no longer writes the modified buffer
640 * to the client, which was very ugly. It now returns the
641 * buffer, which it is then written by chat.
643 * - content_length now adjusts the Content-Length: header
644 * for modified documents rather than crunch()ing it.
645 * (Length info in csp->content_length, which is 0 for
646 * unmodified documents)
648 * - For this to work, sed() is called twice when filtering.
650 * Revision 1.7 2001/05/27 13:19:06 oes
651 * Patched Joergs solution for the content-length in.
653 * Revision 1.6 2001/05/26 13:39:32 jongfoster
654 * Only crunches Content-Length header if applying RE filtering.
655 * Without this fix, Microsoft Windows Update wouldn't work.
657 * Revision 1.5 2001/05/26 00:28:36 jongfoster
658 * Automatic reloading of config file.
659 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
660 * Most of the global variables have been moved to a new
661 * struct configuration_spec, accessed through csp->config->globalname
662 * Most of the globals remaining are used by the Win32 GUI.
664 * Revision 1.4 2001/05/22 18:46:04 oes
666 * - Enabled filtering banners by size rather than URL
667 * by adding patterns that replace all standard banner
668 * sizes with the "Junkbuster" gif to the re_filterfile
670 * - Enabled filtering WebBugs by providing a pattern
671 * which kills all 1x1 images
673 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
674 * which is selected by the (nonstandard and therefore
675 * capital) letter 'U' in the option string.
676 * It causes the quantifiers to be ungreedy by default.
677 * Appending a ? turns back to greedy (!).
679 * - Added a new interceptor ijb-send-banner, which
680 * sends back the "Junkbuster" gif. Without imagelist or
681 * MSIE detection support, or if tinygif = 1, or the
682 * URL isn't recognized as an imageurl, a lame HTML
683 * explanation is sent instead.
685 * - Added new feature, which permits blocking remote
686 * script redirects and firing back a local redirect
688 * The feature is conditionally compiled, i.e. it
689 * can be disabled with --disable-fast-redirects,
690 * plus it must be activated by a "fast-redirects"
691 * line in the config file, has its own log level
692 * and of course wants to be displayed by show-proxy-args
693 * Note: Boy, all the #ifdefs in 1001 locations and
694 * all the fumbling with configure.in and acconfig.h
695 * were *way* more work than the feature itself :-(
697 * - Because a generic redirect template was needed for
698 * this, tinygif = 3 now uses the same.
700 * - Moved GIFs, and other static HTTP response templates
705 * - Removed some >400 CRs again (Jon, you really worked
708 * Revision 1.3 2001/05/20 01:21:20 jongfoster
709 * Version 2.9.4 checkin.
710 * - Merged popupfile and cookiefile, and added control over PCRS
711 * filtering, in new "permissionsfile".
712 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
713 * file error you now get a message box (in the Win32 GUI) rather
714 * than the program exiting with no explanation.
715 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
717 * - Removed tabs from "config"
718 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
719 * - Bumped up version number.
721 * Revision 1.2 2001/05/17 23:02:36 oes
722 * - Made referrer option accept 'L' as a substitute for '§'
724 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
725 * Initial import of version 2.9.3 source tree
728 *********************************************************************/
735 #include <sys/types.h>
745 * Convince GNU's libc to provide a strptime prototype.
748 #endif /*__GLIBC__ */
755 #if !defined(_WIN32) && !defined(__OS2__)
761 #ifdef FEATURE_PTHREAD
763 /* jcc.h is for mutex semapores only */
764 #endif /* def FEATURE_PTHREAD */
770 #include "jbsockets.h"
771 #include "miscutil.h"
776 #ifndef HAVE_STRPTIME
777 #include "strptime.h"
780 const char parsers_h_rcs[] = PARSERS_H_VERSION;
782 /* Fix a problem with Solaris. There should be no effect on other
784 * Solaris's isspace() is a macro which uses its argument directly
785 * as an array index. Therefore we need to make sure that high-bit
786 * characters generate +ve values, and ideally we also want to make
787 * the argument match the declared parameter type of "int".
789 * Why did they write a character function that can't take a simple
790 * "char" argument? Doh!
792 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
793 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
795 static jb_err scan_headers(struct client_state *csp);
796 static jb_err header_tagger(struct client_state *csp, char *header);
797 static jb_err parse_header_time(const char *header_time, time_t *result);
799 static jb_err crumble (struct client_state *csp, char **header);
800 static jb_err connection (struct client_state *csp, char **header);
801 static jb_err filter_header (struct client_state *csp, char **header);
802 static jb_err client_referrer (struct client_state *csp, char **header);
803 static jb_err client_uagent (struct client_state *csp, char **header);
804 static jb_err client_ua (struct client_state *csp, char **header);
805 static jb_err client_from (struct client_state *csp, char **header);
806 static jb_err client_send_cookie (struct client_state *csp, char **header);
807 static jb_err client_x_forwarded (struct client_state *csp, char **header);
808 static jb_err client_accept_encoding (struct client_state *csp, char **header);
809 static jb_err client_te (struct client_state *csp, char **header);
810 static jb_err client_max_forwards (struct client_state *csp, char **header);
811 static jb_err client_host (struct client_state *csp, char **header);
812 static jb_err client_if_modified_since (struct client_state *csp, char **header);
813 static jb_err client_accept_language (struct client_state *csp, char **header);
814 static jb_err client_if_none_match (struct client_state *csp, char **header);
815 static jb_err crunch_client_header (struct client_state *csp, char **header);
816 static jb_err client_x_filter (struct client_state *csp, char **header);
817 static jb_err client_range (struct client_state *csp, char **header);
818 static jb_err server_set_cookie (struct client_state *csp, char **header);
819 static jb_err server_content_type (struct client_state *csp, char **header);
820 static jb_err server_content_length (struct client_state *csp, char **header);
821 static jb_err server_content_md5 (struct client_state *csp, char **header);
822 static jb_err server_content_encoding (struct client_state *csp, char **header);
823 static jb_err server_transfer_coding (struct client_state *csp, char **header);
824 static jb_err server_http (struct client_state *csp, char **header);
825 static jb_err crunch_server_header (struct client_state *csp, char **header);
826 static jb_err server_last_modified (struct client_state *csp, char **header);
827 static jb_err server_content_disposition(struct client_state *csp, char **header);
829 static jb_err client_host_adder (struct client_state *csp);
830 static jb_err client_cookie_adder (struct client_state *csp);
831 static jb_err client_xtra_adder (struct client_state *csp);
832 static jb_err connection_close_adder (struct client_state *csp);
834 static jb_err create_forged_referrer(char **header, const char *hostport);
835 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
836 static jb_err handle_conditional_hide_referrer_parameter(char **header,
837 const char *host, const int parameter_conditional_block);
839 const struct parsers client_patterns[] = {
840 { "referer:", 8, client_referrer },
841 { "user-agent:", 11, client_uagent },
842 { "ua-", 3, client_ua },
843 { "from:", 5, client_from },
844 { "cookie:", 7, client_send_cookie },
845 { "x-forwarded-for:", 16, client_x_forwarded },
846 { "Accept-Encoding:", 16, client_accept_encoding },
847 { "TE:", 3, client_te },
848 { "Host:", 5, client_host },
849 { "if-modified-since:", 18, client_if_modified_since },
850 { "Keep-Alive:", 11, crumble },
851 { "connection:", 11, connection },
852 { "proxy-connection:", 17, crumble },
853 { "max-forwards:", 13, client_max_forwards },
854 { "Accept-Language:", 16, client_accept_language },
855 { "if-none-match:", 14, client_if_none_match },
856 { "Range:", 6, client_range },
857 { "If-Range:", 9, client_range },
858 { "X-Filter:", 9, client_x_filter },
859 { "*", 0, crunch_client_header },
860 { "*", 0, filter_header },
864 const struct parsers server_patterns[] = {
865 { "HTTP/", 5, server_http },
866 { "set-cookie:", 11, server_set_cookie },
867 { "connection:", 11, connection },
868 { "Content-Type:", 13, server_content_type },
869 { "Content-MD5:", 12, server_content_md5 },
870 { "Content-Encoding:", 17, server_content_encoding },
871 { "Transfer-Encoding:", 18, server_transfer_coding },
872 { "Keep-Alive:", 11, crumble },
873 { "content-disposition:", 20, server_content_disposition },
874 { "Last-Modified:", 14, server_last_modified },
875 { "*", 0, crunch_server_header },
876 { "*", 0, filter_header },
880 const struct parsers server_patterns_light[] = {
881 { "Content-Length:", 15, server_content_length },
882 { "Transfer-Encoding:", 18, server_transfer_coding },
884 { "Content-Encoding:", 17, server_content_encoding },
885 #endif /* def FEATURE_ZLIB */
889 const add_header_func_ptr add_client_headers[] = {
893 /* Temporarily disabled: client_accept_encoding_adder, */
894 connection_close_adder,
898 const add_header_func_ptr add_server_headers[] = {
899 connection_close_adder,
903 /* The vanilla wafer. */
904 static const char VANILLA_WAFER[] =
905 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
906 "Do_not_send_me_any_copyrighted_information_other_than_the_"
907 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
908 "In_particular_do_not_send_me_any_cookies_that_"
909 "are_subject_to_a_claim_of_copyright_by_anybody._"
910 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
911 "(copyright_or_otherwise)_applying_to_any_cookie._";
913 /*********************************************************************
915 * Function : flush_socket
917 * Description : Write any pending "buffered" content.
920 * 1 : fd = file descriptor of the socket to read
921 * 2 : csp = Current client state (buffers, headers, etc...)
923 * Returns : On success, the number of bytes written are returned (zero
924 * indicates nothing was written). On error, -1 is returned,
925 * and errno is set appropriately. If count is zero and the
926 * file descriptor refers to a regular file, 0 will be
927 * returned without causing any other effect. For a special
928 * file, the results are not portable.
930 *********************************************************************/
931 int flush_socket(jb_socket fd, struct client_state *csp)
933 struct iob *iob = csp->iob;
934 int len = iob->eod - iob->cur;
941 if (write_socket(fd, iob->cur, (size_t)len))
945 iob->eod = iob->cur = iob->buf;
951 /*********************************************************************
953 * Function : add_to_iob
955 * Description : Add content to the buffered page, expanding the
956 * buffer if necessary.
959 * 1 : csp = Current client state (buffers, headers, etc...)
960 * 2 : buf = holds the content to be added to the page
961 * 3 : n = number of bytes to be added
963 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
964 * or buffer limit reached.
966 *********************************************************************/
967 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
969 struct iob *iob = csp->iob;
970 size_t used, offset, need, want;
973 if (n <= 0) return JB_ERR_OK;
975 used = (size_t)(iob->eod - iob->buf);
976 offset = (size_t)(iob->cur - iob->buf);
977 need = used + (size_t)n + 1;
980 * If the buffer can't hold the new data, extend it first.
981 * Use the next power of two if possible, else use the actual need.
983 if (need > csp->config->buffer_limit)
985 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
986 return JB_ERR_MEMORY;
989 if (need > iob->size)
991 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
993 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
997 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1003 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1004 return JB_ERR_MEMORY;
1007 /* Update the iob pointers */
1008 iob->cur = p + offset;
1009 iob->eod = p + used;
1013 /* copy the new data into the iob buffer */
1014 memcpy(iob->eod, buf, (size_t)n);
1016 /* point to the end of the data */
1019 /* null terminate == cheap insurance */
1028 /*********************************************************************
1030 * Function : decompress_iob
1032 * Description : Decompress buffered page, expanding the
1033 * buffer as necessary. csp->iob->cur
1034 * should point to the the beginning of the
1035 * compressed data block.
1038 * 1 : csp = Current client state (buffers, headers, etc...)
1040 * Returns : JB_ERR_OK on success,
1041 * JB_ERR_MEMORY if out-of-memory limit reached, and
1042 * JB_ERR_COMPRESS if error decompressing buffer.
1044 *********************************************************************/
1045 jb_err decompress_iob(struct client_state *csp)
1047 char *buf; /* new, uncompressed buffer */
1048 char *cur; /* Current iob position (to keep the original
1049 * iob->cur unmodified if we return early) */
1050 size_t bufsize; /* allocated size of the new buffer */
1051 size_t old_size; /* Content size before decompression */
1052 size_t skip_size; /* Number of bytes at the beginning of the iob
1053 that we should NOT decompress. */
1054 int status; /* return status of the inflate() call */
1055 z_stream zstr; /* used by calls to zlib */
1057 assert(csp->iob->cur - csp->iob->buf > 0);
1058 assert(csp->iob->eod - csp->iob->cur > 0);
1060 bufsize = csp->iob->size;
1061 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1062 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1064 cur = csp->iob->cur;
1069 * This is to protect the parsing of gzipped data,
1070 * but it should(?) be valid for deflated data also.
1072 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1073 return JB_ERR_COMPRESS;
1076 if (csp->content_type & CT_GZIP)
1079 * Our task is slightly complicated by the facts that data
1080 * compressed by gzip does not include a zlib header, and
1081 * that there is no easily accessible interface in zlib to
1082 * handle a gzip header. We strip off the gzip header by
1083 * hand, and later inform zlib not to expect a header.
1087 * Strip off the gzip header. Please see RFC 1952 for more
1088 * explanation of the appropriate fields.
1090 if ((*cur++ != (char)0x1f)
1091 || (*cur++ != (char)0x8b)
1092 || (*cur++ != Z_DEFLATED))
1094 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1095 return JB_ERR_COMPRESS;
1101 * XXX: These magic numbers should be replaced
1102 * with macros to give a better idea what they do.
1106 /* The gzip header has reserved bits set; bail out. */
1107 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1108 return JB_ERR_COMPRESS;
1112 /* Skip extra fields if necessary. */
1116 * Skip a given number of bytes, specified
1117 * as a 16-bit little-endian value.
1120 * XXX: This code used to be:
1122 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1124 * which I had to change into:
1126 * cur += *cur++ + (*cur++ << 8);
1128 * at which point gcc43 finally noticed that the value
1129 * of cur is undefined (it depends on which of the
1130 * summands is evaluated first).
1132 * I haven't come across a site where this
1133 * code is actually executed yet, but I hope
1137 skip_bytes = *cur++;
1138 skip_bytes = *cur++ << 8;
1140 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1143 * The number of bytes to skip should be positive
1144 * and we'd like to stay in the buffer.
1146 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1148 log_error(LOG_LEVEL_ERROR,
1149 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1151 return JB_ERR_COMPRESS;
1153 log_error(LOG_LEVEL_INFO,
1154 "Skipping %d bytes for gzip compression. Does this sound right?",
1159 /* Skip the filename if necessary. */
1162 /* A null-terminated string is supposed to follow. */
1163 while (*cur++ && (cur < csp->iob->eod));
1167 /* Skip the comment if necessary. */
1170 /* A null-terminated string is supposed to follow. */
1171 while (*cur++ && (cur < csp->iob->eod));
1174 /* Skip the CRC if necessary. */
1180 if (cur >= csp->iob->eod)
1183 * If the current position pointer reached or passed
1184 * the buffer end, we were obviously tricked to skip
1187 log_error(LOG_LEVEL_ERROR,
1188 "Malformed gzip header detected. Aborting decompression.");
1189 return JB_ERR_COMPRESS;
1193 else if (csp->content_type & CT_DEFLATE)
1196 * XXX: The debug level should be lowered
1197 * before the next stable release.
1199 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1201 * In theory (that is, according to RFC 1950), deflate-compressed
1202 * data should begin with a two-byte zlib header and have an
1203 * adler32 checksum at the end. It seems that in practice only
1204 * the raw compressed data is sent. Note that this means that
1205 * we are not RFC 1950-compliant here, but the advantage is that
1206 * this actually works. :)
1208 * We add a dummy null byte to tell zlib where the data ends,
1209 * and later inform it not to expect a header.
1211 * Fortunately, add_to_iob() has thoughtfully null-terminated
1212 * the buffer; we can just increment the end pointer to include
1219 log_error(LOG_LEVEL_ERROR,
1220 "Unable to determine compression format for decompression");
1221 return JB_ERR_COMPRESS;
1224 /* Set up the fields required by zlib. */
1225 zstr.next_in = (Bytef *)cur;
1226 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1227 zstr.zalloc = Z_NULL;
1228 zstr.zfree = Z_NULL;
1229 zstr.opaque = Z_NULL;
1232 * Passing -MAX_WBITS to inflateInit2 tells the library
1233 * that there is no zlib header.
1235 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1237 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1238 return JB_ERR_COMPRESS;
1242 * Next, we allocate new storage for the inflated data.
1243 * We don't modify the existing iob yet, so in case there
1244 * is error in decompression we can recover gracefully.
1246 buf = zalloc(bufsize);
1249 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1250 return JB_ERR_MEMORY;
1253 assert(bufsize >= skip_size);
1254 memcpy(buf, csp->iob->buf, skip_size);
1255 zstr.avail_out = bufsize - skip_size;
1256 zstr.next_out = (Bytef *)buf + skip_size;
1258 /* Try to decompress the whole stream in one shot. */
1259 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1261 /* We need to allocate more memory for the output buffer. */
1263 char *tmpbuf; /* used for realloc'ing the buffer */
1264 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1267 * If zlib wants more data then there's a problem, because
1268 * the complete compressed file should have been buffered.
1270 if (0 == zstr.avail_in)
1272 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1273 return JB_ERR_COMPRESS;
1277 * If we tried the limit and still didn't have enough
1278 * memory, just give up.
1280 if (bufsize == csp->config->buffer_limit)
1282 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1283 return JB_ERR_MEMORY;
1286 /* Try doubling the buffer size each time. */
1289 /* Don't exceed the buffer limit. */
1290 if (bufsize > csp->config->buffer_limit)
1292 bufsize = csp->config->buffer_limit;
1295 /* Try to allocate the new buffer. */
1296 tmpbuf = realloc(buf, bufsize);
1299 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1301 return JB_ERR_MEMORY;
1305 char *oldnext_out = (char *)zstr.next_out;
1308 * Update the fields for inflate() to use the new
1309 * buffer, which may be in a location different from
1312 zstr.avail_out += bufsize - oldbufsize;
1313 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1316 * Compare with an uglier method of calculating these values
1317 * that doesn't require the extra oldbufsize variable.
1319 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1320 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1321 assert(zstr.avail_out > 0);
1327 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1329 log_error(LOG_LEVEL_ERROR,
1330 "Inconsistent stream state after decompression: %s", zstr.msg);
1332 * XXX: Intentionally no return.
1334 * According to zlib.h, Z_STREAM_ERROR is returned
1335 * "if the stream state was inconsistent".
1337 * I assume in this case inflate()'s status
1338 * would also be something different than Z_STREAM_END
1339 * so this check should be redundant, but lets see.
1343 if (status != Z_STREAM_END)
1345 /* We failed to decompress the stream. */
1346 log_error(LOG_LEVEL_ERROR,
1347 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1348 return JB_ERR_COMPRESS;
1352 * Finally, we can actually update the iob, since the
1353 * decompression was successful. First, free the old
1356 freez(csp->iob->buf);
1358 /* Now, update the iob to use the new buffer. */
1359 csp->iob->buf = buf;
1360 csp->iob->cur = csp->iob->buf + skip_size;
1361 csp->iob->eod = (char *)zstr.next_out;
1362 csp->iob->size = bufsize;
1365 * Make sure the new uncompressed iob obeys some minimal
1366 * consistency conditions.
1368 if ((csp->iob->buf < csp->iob->cur)
1369 && (csp->iob->cur <= csp->iob->eod)
1370 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1372 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1375 log_error(LOG_LEVEL_RE_FILTER,
1376 "Decompression successful. Old size: %d, new size: %d.",
1377 old_size, new_size);
1381 /* zlib thinks this is OK, so lets do the same. */
1382 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1387 /* It seems that zlib did something weird. */
1388 log_error(LOG_LEVEL_ERROR,
1389 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1390 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1391 csp->iob->eod, csp->iob->buf + csp->iob->size);
1392 return JB_ERR_COMPRESS;
1398 #endif /* defined(FEATURE_ZLIB) */
1401 /*********************************************************************
1403 * Function : get_header
1405 * Description : This (odd) routine will parse the csp->iob
1408 * 1 : csp = Current client state (buffers, headers, etc...)
1410 * Returns : Any one of the following:
1412 * 1) a pointer to a dynamically allocated string that contains a header line
1413 * 2) NULL indicating that the end of the header was reached
1414 * 3) "" indicating that the end of the iob was reached before finding
1415 * a complete header line.
1417 *********************************************************************/
1418 char *get_header(struct client_state *csp)
1424 if ((iob->cur == NULL)
1425 || ((p = strchr(iob->cur, '\n')) == NULL))
1427 return(""); /* couldn't find a complete header */
1432 ret = strdup(iob->cur);
1435 /* FIXME No way to handle error properly */
1436 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1441 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1443 /* is this a blank line (i.e. the end of the header) ? */
1455 /*********************************************************************
1457 * Function : get_header_value
1459 * Description : Get the value of a given header from a chained list
1460 * of header lines or return NULL if no such header is
1461 * present in the list.
1464 * 1 : header_list = pointer to list
1465 * 2 : header_name = string with name of header to look for.
1466 * Trailing colon required, capitalization
1469 * Returns : NULL if not found, else value of header
1471 *********************************************************************/
1472 char *get_header_value(const struct list *header_list, const char *header_name)
1474 struct list_entry *cur_entry;
1478 assert(header_list);
1479 assert(header_name);
1480 length = strlen(header_name);
1482 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1486 if (!strncmpic(cur_entry->str, header_name, length))
1489 * Found: return pointer to start of value
1491 ret = (char *) (cur_entry->str + length);
1492 while (*ret && ijb_isspace(*ret)) ret++;
1506 /*********************************************************************
1508 * Function : scan_headers
1510 * Description : Scans headers, applies tags and updates action bits.
1513 * 1 : csp = Current client state (buffers, headers, etc...)
1515 * Returns : JB_ERR_OK
1517 *********************************************************************/
1518 static jb_err scan_headers(struct client_state *csp)
1520 struct list_entry *h; /* Header */
1521 jb_err err = JB_ERR_OK;
1523 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1525 /* Header crunch()ed in previous run? -> ignore */
1526 if (h->str == NULL) continue;
1527 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1528 err = header_tagger(csp, h->str);
1535 /*********************************************************************
1539 * Description : add, delete or modify lines in the HTTP header streams.
1540 * On entry, it receives a linked list of headers space
1541 * that was allocated dynamically (both the list nodes
1542 * and the header contents).
1544 * As a side effect it frees the space used by the original
1547 * XXX: should be split to remove the first_run hack.
1550 * 1 : pats = list of patterns to match against headers
1551 * 2 : more_headers = list of functions to add more
1552 * headers (client or server)
1553 * 3 : csp = Current client state (buffers, headers, etc...)
1555 * Returns : JB_ERR_OK in case off success, or
1556 * JB_ERR_MEMORY on out-of-memory error.
1558 *********************************************************************/
1559 jb_err sed(const struct parsers pats[],
1560 const add_header_func_ptr more_headers[],
1561 struct client_state *csp)
1563 struct list_entry *p;
1564 const struct parsers *v;
1565 const add_header_func_ptr *f;
1566 jb_err err = JB_ERR_OK;
1570 * If filtering is enabled, sed is run twice,
1571 * but most of the work needs to be done only once.
1573 first_run = (more_headers != NULL ) ? 1 : 0;
1575 if (first_run) /* Parse and print */
1579 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1581 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1583 /* Header crunch()ed in previous run? -> ignore */
1584 if (p->str == NULL) continue;
1586 /* Does the current parser handle this header? */
1587 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1589 err = v->parser(csp, (char **)&(p->str));
1593 /* place any additional headers on the csp->headers list */
1594 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1599 else /* Parse only */
1602 * The second run is only needed if the body was modified
1603 * and the content-lenght has changed.
1605 if (strncmpic(csp->http->cmd, "HEAD", 4))
1607 /*XXX: Code duplication */
1608 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1610 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1612 /* Header crunch()ed in previous run? -> ignore */
1613 if (p->str == NULL) continue;
1615 /* Does the current parser handle this header? */
1616 if (strncmpic(p->str, v->str, v->len) == 0)
1618 err = v->parser(csp, (char **)&(p->str));
1630 /*********************************************************************
1632 * Function : header_tagger
1634 * Description : Executes all text substitutions from applying
1635 * tag actions and saves the result as tag.
1637 * XXX: Shares enough code with filter_header() and
1638 * pcrs_filter_response() to warrant some helper functions.
1641 * 1 : csp = Current client state (buffers, headers, etc...)
1642 * 2 : header = Header that is used as tagger input
1644 * Returns : JB_ERR_OK on success and always succeeds
1646 *********************************************************************/
1647 static jb_err header_tagger(struct client_state *csp, char *header)
1649 int wanted_filter_type;
1650 int multi_action_index;
1654 struct file_list *fl;
1655 struct re_filterfile_spec *b;
1656 struct list_entry *tag_name;
1658 int found_filters = 0;
1659 const size_t header_length = strlen(header);
1661 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1663 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1664 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1668 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1669 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1672 /* Check if there are any filters */
1673 for (i = 0; i < MAX_AF_FILES; i++)
1686 if (0 == found_filters)
1688 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1692 for (i = 0; i < MAX_AF_FILES; i++)
1695 if ((NULL == fl) || (NULL == fl->f))
1698 * Either there are no filter files
1699 * left, or this filter file just
1700 * contains no valid filters.
1702 * Continue to be sure we don't miss
1703 * valid filter files that are chained
1704 * after empty or invalid ones.
1709 /* For all filters, */
1710 for (b = fl->f; b; b = b->next)
1712 if (b->type != wanted_filter_type)
1714 /* skip the ones we don't care about, */
1717 /* leaving only taggers that could apply, of which we use the ones, */
1718 for (tag_name = csp->action->multi[multi_action_index]->first;
1719 NULL != tag_name; tag_name = tag_name->next)
1721 /* that do apply, and */
1722 if (strcmp(b->name, tag_name->str) == 0)
1724 char *modified_tag = NULL;
1726 size_t size = header_length;
1727 pcrs_job *joblist = b->joblist;
1729 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1731 if (NULL == joblist)
1733 log_error(LOG_LEVEL_RE_FILTER,
1734 "Tagger %s has empty joblist. Nothing to do.", b->name);
1738 /* execute their pcrs_joblist on the header. */
1739 for (job = joblist; NULL != job; job = job->next)
1741 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1745 /* Success, continue with the modified version. */
1754 /* Tagger doesn't match */
1757 /* Regex failure, log it but continue anyway. */
1758 log_error(LOG_LEVEL_ERROR,
1759 "Problems with tagger \'%s\' and header \'%s\': %s",
1760 b->name, *header, pcrs_strerror(hits));
1762 freez(modified_tag);
1766 if (b->dynamic) pcrs_free_joblist(joblist);
1768 /* If this tagger matched */
1774 * There is to technical limitation which makes
1775 * it impossible to use empty tags, but I assume
1776 * no one would do it intentionally.
1779 log_error(LOG_LEVEL_INFO,
1780 "Tagger \'%s\' created an empty tag. Ignored.",
1785 if (!list_contains_item(csp->tags, tag))
1787 if (JB_ERR_OK != enlist(csp->tags, tag))
1789 log_error(LOG_LEVEL_ERROR,
1790 "Insufficient memory to add tag \'%s\', "
1791 "based on tagger \'%s\' and header \'%s\'",
1792 tag, b->name, *header);
1796 char *action_message;
1798 * update the action bits right away, to make
1799 * tagging based on tags set by earlier taggers
1800 * of the same kind possible.
1802 if (update_action_bits_for_tag(csp, tag))
1804 action_message = "Action bits updated accordingly.";
1808 action_message = "No action bits update necessary.";
1811 log_error(LOG_LEVEL_HEADER,
1812 "Tagger \'%s\' added tag \'%s\'. %s",
1813 b->name, tag, action_message);
1818 /* XXX: Is this log-worthy? */
1819 log_error(LOG_LEVEL_HEADER,
1820 "Tagger \'%s\' didn't add tag \'%s\'. "
1821 "Tag already present", b->name, tag);
1824 } /* if the tagger matched */
1825 } /* if the tagger applies */
1826 } /* for every tagger that could apply */
1827 } /* for all filters */
1828 } /* for all filter files */
1833 /* here begins the family of parser functions that reformat header lines */
1835 /*********************************************************************
1837 * Function : filter_header
1839 * Description : Executes all text substitutions from all applying
1840 * +(server|client)-header-filter actions on the header.
1841 * Most of the code was copied from pcrs_filter_response,
1842 * including the rather short variable names
1845 * 1 : csp = Current client state (buffers, headers, etc...)
1846 * 2 : header = On input, pointer to header to modify.
1847 * On output, pointer to the modified header, or NULL
1848 * to remove the header. This function frees the
1849 * original string if necessary.
1851 * Returns : JB_ERR_OK on success and always succeeds
1853 *********************************************************************/
1854 static jb_err filter_header(struct client_state *csp, char **header)
1858 size_t size = strlen(*header);
1860 char *newheader = NULL;
1863 struct file_list *fl;
1864 struct re_filterfile_spec *b;
1865 struct list_entry *filtername;
1867 int i, found_filters = 0;
1868 int wanted_filter_type;
1869 int multi_action_index;
1871 if (csp->flags & CSP_FLAG_NO_FILTERING)
1876 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1878 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1879 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1883 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1884 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1888 * Need to check the set of re_filterfiles...
1890 for (i = 0; i < MAX_AF_FILES; i++)
1903 if (0 == found_filters)
1905 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1909 for (i = 0; i < MAX_AF_FILES; i++)
1912 if ((NULL == fl) || (NULL == fl->f))
1915 * Either there are no filter files
1916 * left, or this filter file just
1917 * contains no valid filters.
1919 * Continue to be sure we don't miss
1920 * valid filter files that are chained
1921 * after empty or invalid ones.
1926 * For all applying +filter actions, look if a filter by that
1927 * name exists and if yes, execute its pcrs_joblist on the
1930 for (b = fl->f; b; b = b->next)
1932 if (b->type != wanted_filter_type)
1934 /* Skip other filter types */
1938 for (filtername = csp->action->multi[multi_action_index]->first;
1939 filtername ; filtername = filtername->next)
1941 if (strcmp(b->name, filtername->str) == 0)
1943 int current_hits = 0;
1944 pcrs_job *joblist = b->joblist;
1946 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1948 if (NULL == joblist)
1950 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1954 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1955 *header, size, b->name);
1957 /* Apply all jobs from the joblist */
1958 for (job = joblist; NULL != job; job = job->next)
1960 matches = pcrs_execute(job, *header, size, &newheader, &size);
1963 current_hits += matches;
1964 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1966 *header = newheader;
1968 else if ( 0 == matches )
1970 /* Filter doesn't change header */
1976 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1977 *header, b->name, pcrs_strerror(matches));
1978 if (newheader != NULL)
1980 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1986 if (b->dynamic) pcrs_free_joblist(joblist);
1988 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1989 hits += current_hits;
1996 * Additionally checking for hits is important because if
1997 * the continue hack is triggered, server headers can
1998 * arrive empty to separate multiple heads from each other.
2000 if ((0 == size) && hits)
2002 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2010 /*********************************************************************
2012 * Function : connection
2014 * Description : Makes sure that the value of the Connection: header
2015 * is "close" and signals connection_close_adder
2019 * 1 : csp = Current client state (buffers, headers, etc...)
2020 * 2 : header = On input, pointer to header to modify.
2021 * On output, pointer to the modified header, or NULL
2022 * to remove the header. This function frees the
2023 * original string if necessary.
2025 * Returns : JB_ERR_OK on success, or
2026 * JB_ERR_MEMORY on out-of-memory error.
2028 *********************************************************************/
2029 static jb_err connection(struct client_state *csp, char **header)
2031 char *old_header = *header;
2033 /* Do we have a 'Connection: close' header? */
2034 if (strcmpic(*header, "Connection: close"))
2036 /* No, create one */
2037 *header = strdup("Connection: close");
2040 return JB_ERR_MEMORY;
2042 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2046 /* Signal connection_close_adder() to return early. */
2047 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2049 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2053 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2060 /*********************************************************************
2062 * Function : crumble
2064 * Description : This is called if a header matches a pattern to "crunch"
2067 * 1 : csp = Current client state (buffers, headers, etc...)
2068 * 2 : header = On input, pointer to header to modify.
2069 * On output, pointer to the modified header, or NULL
2070 * to remove the header. This function frees the
2071 * original string if necessary.
2073 * Returns : JB_ERR_OK on success, or
2074 * JB_ERR_MEMORY on out-of-memory error.
2076 *********************************************************************/
2077 static jb_err crumble(struct client_state *csp, char **header)
2079 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2085 /*********************************************************************
2087 * Function : crunch_server_header
2089 * Description : Crunch server header if it matches a string supplied by the
2090 * user. Called from `sed'.
2093 * 1 : csp = Current client state (buffers, headers, etc...)
2094 * 2 : header = On input, pointer to header to modify.
2095 * On output, pointer to the modified header, or NULL
2096 * to remove the header. This function frees the
2097 * original string if necessary.
2099 * Returns : JB_ERR_OK on success and always succeeds
2101 *********************************************************************/
2102 static jb_err crunch_server_header(struct client_state *csp, char **header)
2104 const char *crunch_pattern;
2106 /* Do we feel like crunching? */
2107 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2109 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2111 /* Is the current header the lucky one? */
2112 if (strstr(*header, crunch_pattern))
2114 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2123 /*********************************************************************
2125 * Function : server_content_type
2127 * Description : Set the content-type for filterable types (text/.*,
2128 * .*xml.*, javascript and image/gif) unless filtering has been
2129 * forbidden (CT_TABOO) while parsing earlier headers.
2130 * NOTE: Since text/plain is commonly used by web servers
2131 * for files whose correct type is unknown, we don't
2132 * set CT_TEXT for it.
2135 * 1 : csp = Current client state (buffers, headers, etc...)
2136 * 2 : header = On input, pointer to header to modify.
2137 * On output, pointer to the modified header, or NULL
2138 * to remove the header. This function frees the
2139 * original string if necessary.
2141 * Returns : JB_ERR_OK on success, or
2142 * JB_ERR_MEMORY on out-of-memory error.
2144 *********************************************************************/
2145 static jb_err server_content_type(struct client_state *csp, char **header)
2147 /* Remove header if it isn't the first Content-Type header */
2148 if ((csp->content_type & CT_DECLARED))
2151 * Another, slightly slower, way to see if
2152 * we already parsed another Content-Type header.
2154 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2156 log_error(LOG_LEVEL_ERROR,
2157 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2165 * Signal that the Content-Type has been set.
2167 csp->content_type |= CT_DECLARED;
2169 if (!(csp->content_type & CT_TABOO))
2171 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2172 || strstr(*header, "xml")
2173 || strstr(*header, "application/x-javascript"))
2175 csp->content_type |= CT_TEXT;
2177 else if (strstr(*header, " image/gif"))
2179 csp->content_type |= CT_GIF;
2181 else if (strstr(*header, " image/jpeg"))
2183 csp->content_type |= CT_JPEG;
2188 * Are we messing with the content type?
2190 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2193 * Make sure the user doesn't accidently
2194 * change the content type of binary documents.
2196 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2199 *header = strdup("Content-Type: ");
2200 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2204 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2205 return JB_ERR_MEMORY;
2207 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2211 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2212 "Enable force-text-mode if you know what you're doing.", *header);
2220 /*********************************************************************
2222 * Function : server_transfer_coding
2224 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2225 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2226 * - Remove header if body was chunked but has been
2227 * de-chunked for filtering.
2230 * 1 : csp = Current client state (buffers, headers, etc...)
2231 * 2 : header = On input, pointer to header to modify.
2232 * On output, pointer to the modified header, or NULL
2233 * to remove the header. This function frees the
2234 * original string if necessary.
2236 * Returns : JB_ERR_OK on success, or
2237 * JB_ERR_MEMORY on out-of-memory error.
2239 *********************************************************************/
2240 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2243 * Turn off pcrs and gif filtering if body compressed
2245 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2249 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2251 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2252 csp->http->cmd, *header);
2253 #endif /* def FEATURE_ZLIB */
2254 csp->content_type = CT_TABOO;
2258 * Raise flag if body chunked
2260 if (strstr(*header, "chunked"))
2262 csp->flags |= CSP_FLAG_CHUNKED;
2265 * If the body was modified, it has been de-chunked first
2266 * and the header must be removed.
2268 * FIXME: If there is more than one transfer encoding,
2269 * only the "chunked" part should be removed here.
2271 if (csp->flags & CSP_FLAG_MODIFIED)
2273 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2282 /*********************************************************************
2284 * Function : server_content_encoding
2286 * Description : This function is run twice for each request,
2287 * unless FEATURE_ZLIB and filtering are disabled.
2289 * The first run is used to check if the content
2290 * is compressed, if FEATURE_ZLIB is disabled
2291 * filtering is then disabled as well, if FEATURE_ZLIB
2292 * is enabled the content is marked for decompression.
2294 * The second run is used to remove the Content-Encoding
2295 * header if the decompression was successful.
2298 * 1 : csp = Current client state (buffers, headers, etc...)
2299 * 2 : header = On input, pointer to header to modify.
2300 * On output, pointer to the modified header, or NULL
2301 * to remove the header. This function frees the
2302 * original string if necessary.
2304 * Returns : JB_ERR_OK on success, or
2305 * JB_ERR_MEMORY on out-of-memory error.
2307 *********************************************************************/
2308 static jb_err server_content_encoding(struct client_state *csp, char **header)
2311 if ((csp->flags & CSP_FLAG_MODIFIED)
2312 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2315 * We successfully decompressed the content,
2316 * and have to clean the header now, so the
2317 * client no longer expects compressed data..
2319 * XXX: There is a difference between cleaning
2320 * and removing it completely.
2322 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2325 else if (strstr(*header, "gzip"))
2327 /* Mark for gzip decompression */
2328 csp->content_type |= CT_GZIP;
2330 else if (strstr(*header, "deflate"))
2332 /* Mark for zlib decompression */
2333 csp->content_type |= CT_DEFLATE;
2335 else if (strstr(*header, "compress"))
2338 * We can't decompress this; therefore we can't filter
2341 csp->content_type |= CT_TABOO;
2343 #else /* !defined(FEATURE_ZLIB) */
2344 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2347 * Body is compressed, turn off pcrs and gif filtering.
2349 csp->content_type |= CT_TABOO;
2352 * Log a warning if the user expects the content to be filtered.
2354 if ((csp->rlist != NULL) &&
2355 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2357 log_error(LOG_LEVEL_INFO,
2358 "Compressed content detected, content filtering disabled. "
2359 "Consider recompiling Privoxy with zlib support or "
2360 "enable the prevent-compression action.");
2363 #endif /* defined(FEATURE_ZLIB) */
2370 /*********************************************************************
2372 * Function : server_content_length
2374 * Description : Adjust Content-Length header if we modified
2378 * 1 : csp = Current client state (buffers, headers, etc...)
2379 * 2 : header = On input, pointer to header to modify.
2380 * On output, pointer to the modified header, or NULL
2381 * to remove the header. This function frees the
2382 * original string if necessary.
2384 * Returns : JB_ERR_OK on success, or
2385 * JB_ERR_MEMORY on out-of-memory error.
2387 *********************************************************************/
2388 static jb_err server_content_length(struct client_state *csp, char **header)
2390 const size_t max_header_length = 80;
2392 /* Regenerate header if the content was modified. */
2393 if (csp->flags & CSP_FLAG_MODIFIED)
2396 *header = (char *) zalloc(max_header_length);
2397 if (*header == NULL)
2399 return JB_ERR_MEMORY;
2402 snprintf(*header, max_header_length, "Content-Length: %d",
2403 (int)csp->content_length);
2404 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2405 (int)csp->content_length);
2412 /*********************************************************************
2414 * Function : server_content_md5
2416 * Description : Crumble any Content-MD5 headers if the document was
2417 * modified. FIXME: Should we re-compute instead?
2420 * 1 : csp = Current client state (buffers, headers, etc...)
2421 * 2 : header = On input, pointer to header to modify.
2422 * On output, pointer to the modified header, or NULL
2423 * to remove the header. This function frees the
2424 * original string if necessary.
2426 * Returns : JB_ERR_OK on success, or
2427 * JB_ERR_MEMORY on out-of-memory error.
2429 *********************************************************************/
2430 static jb_err server_content_md5(struct client_state *csp, char **header)
2432 if (csp->flags & CSP_FLAG_MODIFIED)
2434 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2442 /*********************************************************************
2444 * Function : server_content_disposition
2446 * Description : If enabled, blocks or modifies the "content-disposition" header.
2447 * Called from `sed'.
2450 * 1 : csp = Current client state (buffers, headers, etc...)
2451 * 2 : header = On input, pointer to header to modify.
2452 * On output, pointer to the modified header, or NULL
2453 * to remove the header. This function frees the
2454 * original string if necessary.
2456 * Returns : JB_ERR_OK on success, or
2457 * JB_ERR_MEMORY on out-of-memory error.
2459 *********************************************************************/
2460 static jb_err server_content_disposition(struct client_state *csp, char **header)
2465 * Are we messing with the content-disposition header?
2467 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2473 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2475 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2478 * Blocking content-disposition header
2480 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2487 * Replacing content-disposition header
2490 *header = strdup("content-disposition: ");
2491 string_append(header, newval);
2493 if (*header == NULL)
2495 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2499 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2502 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2506 /*********************************************************************
2508 * Function : server_last_modified
2510 * Description : Changes Last-Modified header to the actual date
2511 * to help hide-if-modified-since.
2512 * Called from `sed'.
2515 * 1 : csp = Current client state (buffers, headers, etc...)
2516 * 2 : header = On input, pointer to header to modify.
2517 * On output, pointer to the modified header, or NULL
2518 * to remove the header. This function frees the
2519 * original string if necessary.
2521 * Returns : JB_ERR_OK on success, or
2522 * JB_ERR_MEMORY on out-of-memory error.
2524 *********************************************************************/
2525 static jb_err server_last_modified(struct client_state *csp, char **header)
2528 char buf[BUFFER_SIZE];
2531 #ifdef HAVE_GMTIME_R
2534 struct tm *timeptr = NULL;
2535 time_t now, last_modified;
2537 long int days, hours, minutes, seconds;
2540 * Are we messing with the Last-Modified header?
2542 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2548 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2550 if (0 == strcmpic(newval, "block") )
2553 * Blocking Last-Modified header. Useless but why not.
2555 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2559 else if (0 == strcmpic(newval, "reset-to-request-time"))
2562 * Setting Last-Modified Header to now.
2564 get_http_time(0, buf);
2566 *header = strdup("Last-Modified: ");
2567 string_append(header, buf);
2569 if (*header == NULL)
2571 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2575 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2578 else if (0 == strcmpic(newval, "randomize"))
2580 const char *header_time = *header + sizeof("Last-Modified:");
2582 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2584 #ifdef HAVE_GMTIME_R
2585 timeptr = gmtime_r(&now, &gmt);
2586 #elif FEATURE_PTHREAD
2587 pthread_mutex_lock(&gmtime_mutex);
2588 timeptr = gmtime(&now);
2589 pthread_mutex_unlock(&gmtime_mutex);
2591 timeptr = gmtime(&now);
2593 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2595 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2600 rtime = (long int)difftime(now, last_modified);
2609 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2611 rtime = pick_from_range(rtime);
2612 if (negative) rtime *= -1;
2613 last_modified += rtime;
2614 #ifdef HAVE_GMTIME_R
2615 timeptr = gmtime_r(&last_modified, &gmt);
2616 #elif FEATURE_PTHREAD
2617 pthread_mutex_lock(&gmtime_mutex);
2618 timeptr = gmtime(&last_modified);
2619 pthread_mutex_unlock(&gmtime_mutex);
2621 timeptr = gmtime(&last_modified);
2623 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2625 *header = strdup("Last-Modified: ");
2626 string_append(header, newheader);
2628 if (*header == NULL)
2630 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2631 return JB_ERR_MEMORY;
2634 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2636 days = rtime / (3600 * 24);
2637 hours = rtime / 3600 % 24;
2638 minutes = rtime / 60 % 60;
2639 seconds = rtime % 60;
2641 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2642 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2643 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2648 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2657 /*********************************************************************
2659 * Function : client_accept_encoding
2661 * Description : Rewrite the client's Accept-Encoding header so that
2662 * if doesn't allow compression, if the action applies.
2663 * Note: For HTTP/1.0 the absence of the header is enough.
2666 * 1 : csp = Current client state (buffers, headers, etc...)
2667 * 2 : header = On input, pointer to header to modify.
2668 * On output, pointer to the modified header, or NULL
2669 * to remove the header. This function frees the
2670 * original string if necessary.
2672 * Returns : JB_ERR_OK on success, or
2673 * JB_ERR_MEMORY on out-of-memory error.
2675 *********************************************************************/
2676 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2678 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2680 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2684 /* Temporarily disable the correct behaviour to
2685 * work around a PHP bug.
2687 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2689 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2690 * if (*header == NULL)
2692 * return JB_ERR_MEMORY;
2703 /*********************************************************************
2705 * Function : client_te
2707 * Description : Rewrite the client's TE header so that
2708 * if doesn't allow compression, if the action applies.
2711 * 1 : csp = Current client state (buffers, headers, etc...)
2712 * 2 : header = On input, pointer to header to modify.
2713 * On output, pointer to the modified header, or NULL
2714 * to remove the header. This function frees the
2715 * original string if necessary.
2717 * Returns : JB_ERR_OK on success, or
2718 * JB_ERR_MEMORY on out-of-memory error.
2720 *********************************************************************/
2721 static jb_err client_te(struct client_state *csp, char **header)
2723 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2726 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2733 /*********************************************************************
2735 * Function : client_referrer
2737 * Description : Handle the "referer" config setting properly.
2738 * Called from `sed'.
2741 * 1 : csp = Current client state (buffers, headers, etc...)
2742 * 2 : header = On input, pointer to header to modify.
2743 * On output, pointer to the modified header, or NULL
2744 * to remove the header. This function frees the
2745 * original string if necessary.
2747 * Returns : JB_ERR_OK on success, or
2748 * JB_ERR_MEMORY on out-of-memory error.
2750 *********************************************************************/
2751 static jb_err client_referrer(struct client_state *csp, char **header)
2753 const char *parameter;
2754 /* booleans for parameters we have to check multiple times */
2755 int parameter_conditional_block;
2756 int parameter_conditional_forge;
2758 #ifdef FEATURE_FORCE_LOAD
2760 * Since the referrer can include the prefix even
2761 * if the request itself is non-forced, we must
2762 * clean it unconditionally.
2764 * XXX: strclean is too broad
2766 strclean(*header, FORCE_PREFIX);
2767 #endif /* def FEATURE_FORCE_LOAD */
2769 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2771 /* Nothing left to do */
2775 parameter = csp->action->string[ACTION_STRING_REFERER];
2776 assert(parameter != NULL);
2777 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2778 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2780 if (!parameter_conditional_block && !parameter_conditional_forge)
2783 * As conditional-block and conditional-forge are the only
2784 * parameters that rely on the original referrer, we can
2785 * remove it now for all the others.
2790 if (0 == strcmpic(parameter, "block"))
2792 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2795 else if (parameter_conditional_block || parameter_conditional_forge)
2797 return handle_conditional_hide_referrer_parameter(header,
2798 csp->http->hostport, parameter_conditional_block);
2800 else if (0 == strcmpic(parameter, "forge"))
2802 return create_forged_referrer(header, csp->http->hostport);
2806 /* interpret parameter as user-supplied referer to fake */
2807 return create_fake_referrer(header, parameter);
2812 /*********************************************************************
2814 * Function : client_accept_language
2816 * Description : Handle the "Accept-Language" config setting properly.
2817 * Called from `sed'.
2820 * 1 : csp = Current client state (buffers, headers, etc...)
2821 * 2 : header = On input, pointer to header to modify.
2822 * On output, pointer to the modified header, or NULL
2823 * to remove the header. This function frees the
2824 * original string if necessary.
2826 * Returns : JB_ERR_OK on success, or
2827 * JB_ERR_MEMORY on out-of-memory error.
2829 *********************************************************************/
2830 static jb_err client_accept_language(struct client_state *csp, char **header)
2835 * Are we messing with the Accept-Language?
2837 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2839 /*I don't think so*/
2843 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2845 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2848 * Blocking Accept-Language header
2850 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2857 * Replacing Accept-Language header
2860 *header = strdup("Accept-Language: ");
2861 string_append(header, newval);
2863 if (*header == NULL)
2865 log_error(LOG_LEVEL_ERROR,
2866 "Insufficent memory. Accept-Language header crunched without replacement.");
2870 log_error(LOG_LEVEL_HEADER,
2871 "Accept-Language header crunched and replaced with: %s", *header);
2874 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2878 /*********************************************************************
2880 * Function : crunch_client_header
2882 * Description : Crunch client header if it matches a string supplied by the
2883 * user. Called from `sed'.
2886 * 1 : csp = Current client state (buffers, headers, etc...)
2887 * 2 : header = On input, pointer to header to modify.
2888 * On output, pointer to the modified header, or NULL
2889 * to remove the header. This function frees the
2890 * original string if necessary.
2892 * Returns : JB_ERR_OK on success and always succeeds
2894 *********************************************************************/
2895 static jb_err crunch_client_header(struct client_state *csp, char **header)
2897 const char *crunch_pattern;
2899 /* Do we feel like crunching? */
2900 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2902 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2904 /* Is the current header the lucky one? */
2905 if (strstr(*header, crunch_pattern))
2907 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2915 /*********************************************************************
2917 * Function : client_uagent
2919 * Description : Handle the "user-agent" config setting properly
2920 * and remember its original value to enable browser
2921 * bug workarounds. Called from `sed'.
2924 * 1 : csp = Current client state (buffers, headers, etc...)
2925 * 2 : header = On input, pointer to header to modify.
2926 * On output, pointer to the modified header, or NULL
2927 * to remove the header. This function frees the
2928 * original string if necessary.
2930 * Returns : JB_ERR_OK on success, or
2931 * JB_ERR_MEMORY on out-of-memory error.
2933 *********************************************************************/
2934 static jb_err client_uagent(struct client_state *csp, char **header)
2938 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2943 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2950 *header = strdup("User-Agent: ");
2951 string_append(header, newval);
2953 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2955 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2959 /*********************************************************************
2961 * Function : client_ua
2963 * Description : Handle "ua-" headers properly. Called from `sed'.
2966 * 1 : csp = Current client state (buffers, headers, etc...)
2967 * 2 : header = On input, pointer to header to modify.
2968 * On output, pointer to the modified header, or NULL
2969 * to remove the header. This function frees the
2970 * original string if necessary.
2972 * Returns : JB_ERR_OK on success, or
2973 * JB_ERR_MEMORY on out-of-memory error.
2975 *********************************************************************/
2976 static jb_err client_ua(struct client_state *csp, char **header)
2978 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2980 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2988 /*********************************************************************
2990 * Function : client_from
2992 * Description : Handle the "from" config setting properly.
2993 * Called from `sed'.
2996 * 1 : csp = Current client state (buffers, headers, etc...)
2997 * 2 : header = On input, pointer to header to modify.
2998 * On output, pointer to the modified header, or NULL
2999 * to remove the header. This function frees the
3000 * original string if necessary.
3002 * Returns : JB_ERR_OK on success, or
3003 * JB_ERR_MEMORY on out-of-memory error.
3005 *********************************************************************/
3006 static jb_err client_from(struct client_state *csp, char **header)
3010 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3017 newval = csp->action->string[ACTION_STRING_FROM];
3020 * Are we blocking the e-mail address?
3022 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3024 log_error(LOG_LEVEL_HEADER, "crunched From!");
3028 log_error(LOG_LEVEL_HEADER, " modified");
3030 *header = strdup("From: ");
3031 string_append(header, newval);
3033 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3037 /*********************************************************************
3039 * Function : client_send_cookie
3041 * Description : Crunches the "cookie" header if necessary.
3042 * Called from `sed'.
3044 * XXX: Stupid name, doesn't send squat.
3047 * 1 : csp = Current client state (buffers, headers, etc...)
3048 * 2 : header = On input, pointer to header to modify.
3049 * On output, pointer to the modified header, or NULL
3050 * to remove the header. This function frees the
3051 * original string if necessary.
3053 * Returns : JB_ERR_OK on success, or
3054 * JB_ERR_MEMORY on out-of-memory error.
3056 *********************************************************************/
3057 static jb_err client_send_cookie(struct client_state *csp, char **header)
3059 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3061 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3069 /*********************************************************************
3071 * Function : client_x_forwarded
3073 * Description : Handle the "x-forwarded-for" config setting properly,
3074 * also used in the add_client_headers list. Called from `sed'.
3077 * 1 : csp = Current client state (buffers, headers, etc...)
3078 * 2 : header = On input, pointer to header to modify.
3079 * On output, pointer to the modified header, or NULL
3080 * to remove the header. This function frees the
3081 * original string if necessary.
3083 * Returns : JB_ERR_OK on success, or
3084 * JB_ERR_MEMORY on out-of-memory error.
3086 *********************************************************************/
3087 jb_err client_x_forwarded(struct client_state *csp, char **header)
3089 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3092 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3099 /*********************************************************************
3101 * Function : client_max_forwards
3103 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3104 * from the value of the Max-Forwards header field.
3107 * 1 : csp = Current client state (buffers, headers, etc...)
3108 * 2 : header = On input, pointer to header to modify.
3109 * On output, pointer to the modified header, or NULL
3110 * to remove the header. This function frees the
3111 * original string if necessary.
3113 * Returns : JB_ERR_OK on success, or
3114 * JB_ERR_MEMORY on out-of-memory error.
3116 *********************************************************************/
3117 static jb_err client_max_forwards(struct client_state *csp, char **header)
3121 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3122 (0 == strcmpic(csp->http->gpc, "options")))
3124 assert(*(*header+12) == ':');
3125 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3127 if (max_forwards > 0)
3129 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3130 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3131 csp->http->gpc, max_forwards);
3133 else if (max_forwards < 0)
3135 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3141 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3150 /*********************************************************************
3152 * Function : client_host
3154 * Description : If the request URI did not contain host and
3155 * port information, parse and evaluate the Host
3158 * Also, kill ill-formed HOST: headers as sent by
3159 * Apple's iTunes software when used with a proxy.
3162 * 1 : csp = Current client state (buffers, headers, etc...)
3163 * 2 : header = On input, pointer to header to modify.
3164 * On output, pointer to the modified header, or NULL
3165 * to remove the header. This function frees the
3166 * original string if necessary.
3168 * Returns : JB_ERR_OK on success, or
3169 * JB_ERR_MEMORY on out-of-memory error.
3171 *********************************************************************/
3172 static jb_err client_host(struct client_state *csp, char **header)
3177 * If the header field name is all upper-case, chances are that it's
3178 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3179 * not a problem -- they are regenerated later.
3181 if ((*header)[1] == 'O')
3183 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3188 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3189 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3192 if (NULL == (p = strdup((*header)+6)))
3194 return JB_ERR_MEMORY;
3197 if (NULL == (q = strdup(p)))
3200 return JB_ERR_MEMORY;
3203 freez(csp->http->hostport);
3204 csp->http->hostport = p;
3205 freez(csp->http->host);
3206 csp->http->host = q;
3207 q = strchr(csp->http->host, ':');
3210 /* Terminate hostname and evaluate port string */
3212 csp->http->port = atoi(q);
3216 csp->http->port = csp->http->ssl ? 443 : 80;
3219 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3220 csp->http->hostport, csp->http->host, csp->http->port);
3223 /* Signal client_host_adder() to return right away */
3224 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3230 /*********************************************************************
3232 * Function : client_if_modified_since
3234 * Description : Remove or modify the If-Modified-Since header.
3237 * 1 : csp = Current client state (buffers, headers, etc...)
3238 * 2 : header = On input, pointer to header to modify.
3239 * On output, pointer to the modified header, or NULL
3240 * to remove the header. This function frees the
3241 * original string if necessary.
3243 * Returns : JB_ERR_OK on success, or
3244 * JB_ERR_MEMORY on out-of-memory error.
3246 *********************************************************************/
3247 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3250 #ifdef HAVE_GMTIME_R
3253 struct tm *timeptr = NULL;
3257 long int hours, minutes, seconds;
3261 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3264 * The client got an error message because of a temporary problem,
3265 * the problem is gone and the client now tries to revalidate our
3266 * error message on the real server. The revalidation would always
3267 * end with the transmission of the whole document and there is
3268 * no need to expose the bogus If-Modified-Since header.
3270 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3273 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3275 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3277 if ((0 == strcmpic(newval, "block")))
3279 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3282 else /* add random value */
3284 const char *header_time = *header + sizeof("If-Modified-Since:");
3286 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3288 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3293 rtime = strtol(newval, &endptr, 0);
3296 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3297 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3304 rtime = pick_from_range(rtime);
3308 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3311 tm += rtime * (negative ? -1 : 1);
3312 #ifdef HAVE_GMTIME_R
3313 timeptr = gmtime_r(&tm, &gmt);
3314 #elif FEATURE_PTHREAD
3315 pthread_mutex_lock(&gmtime_mutex);
3316 timeptr = gmtime(&tm);
3317 pthread_mutex_unlock(&gmtime_mutex);
3319 timeptr = gmtime(&tm);
3321 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3324 *header = strdup("If-Modified-Since: ");
3325 string_append(header, newheader);
3327 if (*header == NULL)
3329 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3330 return JB_ERR_MEMORY;
3333 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3335 hours = rtime / 3600;
3336 minutes = rtime / 60 % 60;
3337 seconds = rtime % 60;
3339 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3340 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3341 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3351 /*********************************************************************
3353 * Function : client_if_none_match
3355 * Description : Remove the If-None-Match header.
3358 * 1 : csp = Current client state (buffers, headers, etc...)
3359 * 2 : header = On input, pointer to header to modify.
3360 * On output, pointer to the modified header, or NULL
3361 * to remove the header. This function frees the
3362 * original string if necessary.
3364 * Returns : JB_ERR_OK on success, or
3365 * JB_ERR_MEMORY on out-of-memory error.
3367 *********************************************************************/
3368 static jb_err client_if_none_match(struct client_state *csp, char **header)
3370 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3372 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3380 /*********************************************************************
3382 * Function : client_x_filter
3384 * Description : Disables filtering if the client set "X-Filter: No".
3385 * Called from `sed'.
3388 * 1 : csp = Current client state (buffers, headers, etc...)
3389 * 2 : header = On input, pointer to header to modify.
3390 * On output, pointer to the modified header, or NULL
3391 * to remove the header. This function frees the
3392 * original string if necessary.
3394 * Returns : JB_ERR_OK on success
3396 *********************************************************************/
3397 jb_err client_x_filter(struct client_state *csp, char **header)
3399 if ( 0 == strcmpic(*header, "X-Filter: No"))
3401 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3403 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3407 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3409 log_error(LOG_LEVEL_HEADER,
3410 "force-text-mode overruled the client's request to fetch without filtering!");
3414 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3415 csp->flags |= CSP_FLAG_NO_FILTERING;
3416 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3418 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3426 /*********************************************************************
3428 * Function : client_range
3430 * Description : Removes Range and If-Range headers if content
3431 * filtering is enabled. If the client's version of
3432 * the document has been altered by Privoxy, the server
3433 * could interpret the range differently than the client
3434 * intended in which case the user could end up with
3435 * corrupted content.
3438 * 1 : csp = Current client state (buffers, headers, etc...)
3439 * 2 : header = On input, pointer to header to modify.
3440 * On output, pointer to the modified header, or NULL
3441 * to remove the header. This function frees the
3442 * original string if necessary.
3444 * Returns : JB_ERR_OK
3446 *********************************************************************/
3447 static jb_err client_range(struct client_state *csp, char **header)
3449 if (content_filters_enabled(csp))
3451 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3452 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3459 /* the following functions add headers directly to the header list */
3461 /*********************************************************************
3463 * Function : client_host_adder
3465 * Description : Adds the Host: header field if it is missing.
3466 * Called from `sed'.
3469 * 1 : csp = Current client state (buffers, headers, etc...)
3471 * Returns : JB_ERR_OK on success, or
3472 * JB_ERR_MEMORY on out-of-memory error.
3474 *********************************************************************/
3475 static jb_err client_host_adder(struct client_state *csp)
3480 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3482 /* Header already set by the client, nothing to do. */
3486 if ( !csp->http->hostport || !*(csp->http->hostport))
3488 /* XXX: When does this happen and why is it OK? */
3489 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3494 * remove 'user:pass@' from 'proto://user:pass@host'
3496 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3502 p = csp->http->hostport;
3505 /* XXX: Just add it, we already made sure that it will be unique */
3506 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3507 err = enlist_unique_header(csp->headers, "Host", p);
3513 /*********************************************************************
3515 * Function : client_cookie_adder
3517 * Description : Used in the add_client_headers list to add "wafers".
3518 * Called from `sed'.
3521 * 1 : csp = Current client state (buffers, headers, etc...)
3523 * Returns : JB_ERR_OK on success, or
3524 * JB_ERR_MEMORY on out-of-memory error.
3526 *********************************************************************/
3527 jb_err client_cookie_adder(struct client_state *csp)
3530 struct list_entry *wafer;
3531 struct list_entry *wafer_list;
3535 * If the user has not supplied any wafers, and the user has not
3536 * told us to suppress the vanilla wafer, then send the vanilla wafer.
3538 if ((0 != (csp->action->flags & ACTION_VANILLA_WAFER))
3539 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER]))
3541 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
3544 wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3546 if (NULL == wafer_list)
3552 tmp = strdup("Cookie: ");
3554 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3556 if (wafer != wafer_list)
3558 /* As this isn't the first wafer, we need a delimiter. */
3559 string_append(&tmp, "; ");
3561 string_join(&tmp, cookie_encode(wafer->str));
3566 return JB_ERR_MEMORY;
3569 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3570 err = enlist(csp->headers, tmp);
3577 /*********************************************************************
3579 * Function : client_accept_encoding_adder
3581 * Description : Add an Accept-Encoding header to the client's request
3582 * that disables compression if the action applies, and
3583 * the header is not already there. Called from `sed'.
3584 * Note: For HTTP/1.0, the absence of the header is enough.
3587 * 1 : csp = Current client state (buffers, headers, etc...)
3589 * Returns : JB_ERR_OK on success, or
3590 * JB_ERR_MEMORY on out-of-memory error.
3592 *********************************************************************/
3593 static jb_err client_accept_encoding_adder(struct client_state *csp)
3595 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3596 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3598 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3606 /*********************************************************************
3608 * Function : client_xtra_adder
3610 * Description : Used in the add_client_headers list. Called from `sed'.
3613 * 1 : csp = Current client state (buffers, headers, etc...)
3615 * Returns : JB_ERR_OK on success, or
3616 * JB_ERR_MEMORY on out-of-memory error.
3618 *********************************************************************/
3619 static jb_err client_xtra_adder(struct client_state *csp)
3621 struct list_entry *lst;
3624 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3625 lst ; lst = lst->next)
3627 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3628 err = enlist(csp->headers, lst->str);
3640 /*********************************************************************
3642 * Function : connection_close_adder
3644 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3645 * support. Adds a "Connection: close" header to csp->headers
3646 * unless the header was already present. Called from `sed'.
3648 * FIXME: This whole function shouldn't be neccessary!
3651 * 1 : csp = Current client state (buffers, headers, etc...)
3653 * Returns : JB_ERR_OK on success, or
3654 * JB_ERR_MEMORY on out-of-memory error.
3656 *********************************************************************/
3657 static jb_err connection_close_adder(struct client_state *csp)
3659 const unsigned int flags = csp->flags;
3662 * Return right away if
3664 * - we're parsing server headers and the server header
3665 * "Connection: close" is already set, or if
3667 * - we're parsing client headers and the client header
3668 * "Connection: close" is already set.
3670 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3671 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3672 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3673 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3678 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3680 return enlist(csp->headers, "Connection: close");
3684 /*********************************************************************
3686 * Function : server_http
3688 * Description : - Save the HTTP Status into csp->http->status
3689 * - Set CT_TABOO to prevent filtering if the answer
3690 * is a partial range (HTTP status 206)
3691 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3695 * 1 : csp = Current client state (buffers, headers, etc...)
3696 * 2 : header = On input, pointer to header to modify.
3697 * On output, pointer to the modified header, or NULL
3698 * to remove the header. This function frees the
3699 * original string if necessary.
3701 * Returns : JB_ERR_OK on success, or
3702 * JB_ERR_MEMORY on out-of-memory error.
3704 *********************************************************************/
3705 static jb_err server_http(struct client_state *csp, char **header)
3707 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3708 if (csp->http->status == 206)
3710 csp->content_type = CT_TABOO;
3713 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3715 /* XXX: Should we do a real validity check here? */
3716 if (strlen(*header) > 8)
3719 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3724 * XXX: Should we block the request or
3725 * enlist a valid status code line here?
3727 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3728 "Downgrading to HTTP/1.0 impossible.");
3736 /*********************************************************************
3738 * Function : server_set_cookie
3740 * Description : Handle the server "cookie" header properly.
3741 * Log cookie to the jar file. Then "crunch",
3742 * accept or rewrite it to a session cookie.
3743 * Called from `sed'.
3745 * TODO: Allow the user to specify a new expiration
3746 * time to cause the cookie to expire even before the
3747 * browser is closed.
3750 * 1 : csp = Current client state (buffers, headers, etc...)
3751 * 2 : header = On input, pointer to header to modify.
3752 * On output, pointer to the modified header, or NULL
3753 * to remove the header. This function frees the
3754 * original string if necessary.
3756 * Returns : JB_ERR_OK on success, or
3757 * JB_ERR_MEMORY on out-of-memory error.
3759 *********************************************************************/
3760 static jb_err server_set_cookie(struct client_state *csp, char **header)
3767 #ifdef FEATURE_COOKIE_JAR
3768 if (csp->config->jar)
3771 * Write timestamp into outbuf.
3773 * Complex because not all OSs have tm_gmtoff or
3774 * the %z field in strftime()
3776 char tempbuf[ BUFFER_SIZE ];
3778 #ifdef HAVE_LOCALTIME_R
3779 tm_now = *localtime_r(&now, &tm_now);
3780 #elif FEATURE_PTHREAD
3781 pthread_mutex_lock(&localtime_mutex);
3782 tm_now = *localtime (&now);
3783 pthread_mutex_unlock(&localtime_mutex);
3785 tm_now = *localtime (&now);
3787 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3789 /* strlen("set-cookie: ") = 12 */
3790 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3792 #endif /* def FEATURE_COOKIE_JAR */
3794 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3796 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3799 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3801 /* Flag whether or not to log a message */
3804 /* A variable to store the tag we're working on */
3807 /* Skip "Set-Cookie:" (11 characters) in header */
3808 cur_tag = *header + 11;
3810 /* skip whitespace between "Set-Cookie:" and value */
3811 while (*cur_tag && ijb_isspace(*cur_tag))
3816 /* Loop through each tag in the cookie */
3820 char *next_tag = strchr(cur_tag, ';');
3821 if (next_tag != NULL)
3823 /* Skip the ';' character itself */
3826 /* skip whitespace ";" and start of tag */
3827 while (*next_tag && ijb_isspace(*next_tag))
3834 /* "Next tag" is the end of the string */
3835 next_tag = cur_tag + strlen(cur_tag);
3839 * Check the expiration date to see
3840 * if the cookie is still valid, if yes,
3841 * rewrite it to a session cookie.
3843 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3845 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3847 /* Did we detect the date properly? */
3848 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3851 * Nope, treat it as if it was still valid.
3853 * XXX: Should we remove the whole cookie instead?
3855 log_error(LOG_LEVEL_ERROR,
3856 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3857 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3863 * Yes. Check if the cookie is still valid.
3865 * If the cookie is already expired it's probably
3866 * a delete cookie and even if it isn't, the browser
3867 * will discard it anyway.
3871 * XXX: timegm() isn't available on some AmigaOS
3872 * versions and our replacement doesn't work.
3874 * Our options are to either:
3876 * - disable session-cookies-only completely if timegm
3879 * - to simply remove all expired tags, like it has
3880 * been done until Privoxy 3.0.6 and to live with
3881 * the consequence that it can cause login/logout
3882 * problems on servers that don't validate their
3883 * input properly, or
3885 * - to replace it with mktime in which
3886 * case there is a slight chance of valid cookies
3887 * passing as already expired.
3889 * This is the way it's currently done and it's not
3890 * as bad as it sounds. If the missing GMT offset is
3891 * enough to change the result of the expiration check
3892 * the cookie will be only valid for a few hours
3893 * anyway, which in many cases will be shorter
3894 * than a browser session.
3896 if (cookie_time - now < 0)
3898 log_error(LOG_LEVEL_HEADER,
3899 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3900 /* Just in case some clown sets more then one expiration date */
3906 * Still valid, delete expiration date by copying
3907 * the rest of the string over it.
3909 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3910 * since the behaviour of strcpy is undefined for overlapping
3913 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3915 /* That changed the header, need to issue a log message */
3919 * Note that the next tag has now been moved to *cur_tag,
3920 * so we do not need to update the cur_tag pointer.
3928 /* Move on to next cookie tag */
3935 assert(NULL != *header);
3936 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3945 #ifdef FEATURE_FORCE_LOAD
3946 /*********************************************************************
3948 * Function : strclean
3950 * Description : In-Situ-Eliminate all occurances of substring in
3954 * 1 : string = string to clean
3955 * 2 : substring = substring to eliminate
3957 * Returns : Number of eliminations
3959 *********************************************************************/
3960 int strclean(const char *string, const char *substring)
3966 len = strlen(substring);
3968 while((pos = strstr(string, substring)) != NULL)
3975 while (*p++ != '\0');
3982 #endif /* def FEATURE_FORCE_LOAD */
3985 /*********************************************************************
3987 * Function : parse_header_time
3989 * Description : Parses time formats used in HTTP header strings
3990 * to get the numerical respresentation.
3993 * 1 : header_time = HTTP header time as string.
3994 * 2 : result = storage for header_time in seconds
3996 * Returns : JB_ERR_OK if the time format was recognized, or
3997 * JB_ERR_PARSE otherwise.
3999 *********************************************************************/
4000 static jb_err parse_header_time(const char *header_time, time_t *result)
4005 * Zero out gmt to prevent time zone offsets.
4007 * While this is only necessary on some platforms
4008 * (mingw32 for example), I don't know how to
4009 * detect these automatically and doing it everywhere
4012 memset(&gmt, 0, sizeof(gmt));
4014 /* Tue, 02 Jun 2037 20:00:00 */
4015 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4016 /* Tue, 02-Jun-2037 20:00:00 */
4017 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4018 /* Tue, 02-Jun-37 20:00:00 */
4019 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4020 /* Tuesday, 02-Jun-2037 20:00:00 */
4021 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4022 /* Tuesday Jun 02 20:00:00 2037 */
4023 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4025 return JB_ERR_PARSE;
4028 *result = timegm(&gmt);
4035 /*********************************************************************
4037 * Function : get_destination_from_headers
4039 * Description : Parse the "Host:" header to get the request's destination.
4040 * Only needed if the client's request was forcefully
4041 * redirected into Privoxy.
4043 * Code mainly copied from client_host() which is currently
4044 * run too late for this purpose.
4047 * 1 : headers = List of headers (one of them hopefully being
4048 * the "Host:" header)
4049 * 2 : http = storage for the result (host, port and hostport).
4051 * Returns : JB_ERR_MEMORY in case of memory problems,
4052 * JB_ERR_PARSE if the host header couldn't be found,
4053 * JB_ERR_OK otherwise.
4055 *********************************************************************/
4056 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4062 host = get_header_value(headers, "Host:");
4066 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4067 return JB_ERR_PARSE;
4070 if (NULL == (p = strdup((host))))
4072 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4073 return JB_ERR_MEMORY;
4076 if (NULL == (q = strdup(p)))
4079 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4080 return JB_ERR_MEMORY;
4083 freez(http->hostport);
4087 q = strchr(http->host, ':');
4090 /* Terminate hostname and evaluate port string */
4092 http->port = atoi(q);
4096 http->port = http->ssl ? 443 : 80;
4099 /* Rebuild request URL */
4101 http->url = strdup(http->ssl ? "https://" : "http://");
4102 string_append(&http->url, http->hostport);
4103 string_append(&http->url, http->path);
4104 if (http->url == NULL)
4106 return JB_ERR_MEMORY;
4109 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4117 /*********************************************************************
4119 * Function : create_forged_referrer
4121 * Description : Helper for client_referrer to forge a referer as
4122 * 'http://[hostname:port/' to fool stupid
4123 * checks for in-site links
4126 * 1 : header = Pointer to header pointer
4127 * 2 : hostport = Host and optionally port as string
4129 * Returns : JB_ERR_OK in case of success, or
4130 * JB_ERR_MEMORY in case of memory problems.
4132 *********************************************************************/
4133 static jb_err create_forged_referrer(char **header, const char *hostport)
4135 assert(NULL == *header);
4137 *header = strdup("Referer: http://");
4138 string_append(header, hostport);
4139 string_append(header, "/");
4141 if (NULL == *header)
4143 return JB_ERR_MEMORY;
4146 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4153 /*********************************************************************
4155 * Function : create_fake_referrer
4157 * Description : Helper for client_referrer to create a fake referrer
4158 * based on a string supplied by the user.
4161 * 1 : header = Pointer to header pointer
4162 * 2 : hosthost = Referrer to fake
4164 * Returns : JB_ERR_OK in case of success, or
4165 * JB_ERR_MEMORY in case of memory problems.
4167 *********************************************************************/
4168 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4170 assert(NULL == *header);
4172 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4174 log_error(LOG_LEVEL_HEADER,
4175 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4177 *header = strdup("Referer: ");
4178 string_append(header, fake_referrer);
4180 if (NULL == *header)
4182 return JB_ERR_MEMORY;
4185 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4192 /*********************************************************************
4194 * Function : handle_conditional_hide_referrer_parameter
4196 * Description : Helper for client_referrer to crunch or forge
4197 * the referrer header if the host has changed.
4200 * 1 : header = Pointer to header pointer
4201 * 2 : host = The target host (may include the port)
4202 * 3 : parameter_conditional_block = Boolean to signal
4203 * if we're in conditional-block mode. If not set,
4204 * we're in conditional-forge mode.
4206 * Returns : JB_ERR_OK in case of success, or
4207 * JB_ERR_MEMORY in case of memory problems.
4209 *********************************************************************/
4210 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4211 const char *host, const int parameter_conditional_block)
4213 char *referer = strdup(*header);
4214 const size_t hostlenght = strlen(host);
4216 if (NULL == referer)
4219 return JB_ERR_MEMORY;
4222 /* referer begins with 'Referer: http[s]://' */
4223 if (hostlenght < (strlen(referer)-17))
4226 * Shorten referer to make sure the referer is blocked
4227 * if www.example.org/www.example.com-shall-see-the-referer/
4228 * links to www.example.com/
4230 referer[hostlenght+17] = '\0';
4232 if (NULL == strstr(referer, host))
4234 /* Host has changed */
4235 if (parameter_conditional_block)
4237 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4244 return create_forged_referrer(header, host);