1 const char parsers_rcs[] = "$Id: parsers.c,v 1.117 2007/12/06 18:11:50 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.117 2007/12/06 18:11:50 fabiankeil
48 * Garbage-collect the code to add a X-Forwarded-For
49 * header as it seems to be mostly used by accident.
51 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
52 * Fix a crash on mingw32 with some Last Modified times in the future.
54 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
55 * Remove a "can't happen" error block which, over
56 * time, mutated into a "guaranteed to happen" block.
58 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
59 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
60 * - Use shiny new content_filters_enabled() in client_range().
62 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
63 * I forgot about Poland.
65 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
66 * Remove Range and If-Range headers if content filtering is enabled.
68 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
69 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
70 * client_cookie_adder() to make sure send-vanilla-wafer can be
71 * controlled through tags (and thus regression-tested).
73 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
74 * - Remove "scanning headers for" log message again.
75 * - Some more whitespace fixes.
77 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
78 * Refactor client_referrer() and add conditional-forge parameter.
80 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
81 * A bunch of whitespace fixes, pointy hat to me.
83 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
84 * Fix possible memory corruption in server_http, make sure it's not
85 * executed for ordinary server headers and mark some problems for later.
87 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
88 * Let content-type-overwrite{} honour force-text-mode again.
90 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
91 * - Add prototpyes for the header parsers and make them static.
92 * - Comment out client_accept_encoding_adder() which isn't used right now.
94 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
95 * Move the ACTION_FORCE_TEXT_MODE check out of
96 * server_content_type(). Signal other functions
97 * whether or not a content type has been declared.
98 * Part of the fix for BR#1750917.
100 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
101 * Change sed() to return a jb_err in preparation for forward-override{}.
103 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
104 * Adjust "X-Filter: No" to disable dedicated header filters.
106 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
107 * Streamline client_cookie_adder().
109 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
110 * Make sure filters with dynamic jobs actually use them.
112 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
113 * - Introduce dynamic pcrs jobs that can resolve variables.
114 * - Remove unnecessary update_action_bits_for_all_tags() call.
116 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
117 * - Make tagging based on tags set by earlier taggers
118 * of the same kind possible.
119 * - Log whether or not new tags cause action bits updates
120 * (in which case a matching tag-pattern section exists).
121 * - Log if the user tries to set a tag that is already set.
123 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
124 * Introduce tags as alternative way to specify which
125 * actions apply to a request. At the moment tags can be
126 * created based on client and server headers.
128 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
129 * Log a warning if the content is compressed, filtering is
130 * enabled and Privoxy was compiled without zlib support.
133 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
134 * - Fix warnings when compiled with glibc.
135 * - Don't use crumble() for cookie crunching.
136 * - Move cookie time parsing into parse_header_time().
137 * - Let parse_header_time() return a jb_err code
138 * instead of a pointer that can only be used to
139 * check for NULL anyway.
141 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
142 * - Add better protection against malicious gzip headers.
143 * - Stop logging the first hundred bytes of decompressed content.
144 * It looks like it's working and there is always debug 16.
145 * - Log the content size after decompression in decompress_iob()
146 * instead of pcrs_filter_response().
148 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
149 * - Use dedicated header filter actions instead of abusing "filter".
150 * Replace "filter-client-headers" and "filter-client-headers"
151 * with "server-header-filter" and "client-header-filter".
152 * - Remove filter_client_header() and filter_client_header(),
153 * filter_header() now checks the shiny new
154 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
156 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
157 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
158 * - Handle "Cookie:" and "Connection:" headers a bit smarter
159 * (don't crunch them just to recreate them later on).
160 * - Add another non-standard time format for the cookie
161 * expiration date detection.
162 * - Fix a valgrind warning.
164 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
165 * Improve cookie expiration date detection.
167 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
168 * Don't run server_content_length() the first time
169 * sed() parses server headers; only adjust the
170 * Content-Length header if the page was modified.
172 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
173 * Fix log messages regarding the cookie time format
174 * (cookie and request URL were mixed up).
176 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
177 * - Let decompress_iob()
178 * - not corrupt the content if decompression fails
179 * early. (the first byte(s) were lost).
180 * - use pointer arithmetics with defined outcome for
182 * - Use a different kludge to remember a failed decompression.
184 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
185 * Search for Max-Forwards headers case-insensitive,
186 * don't generate the "501 unsupported" message for invalid
187 * Max-Forwards values and don't increase negative ones.
189 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
190 * - Let server_set_cookie() check the expiration date
191 * of cookies and don't touch the ones that are already
192 * expired. Fixes problems with low quality web applications
193 * as described in BR 932612.
195 * - Adjust comment in client_max_forwards to reality;
196 * remove invalid Max-Forwards headers.
198 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
199 * Stop filter_header() from unintentionally removing
200 * empty header lines that were enlisted by the continue
203 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
204 * - Repeat the request URL before logging any headers.
205 * Makes reading the log easier in case of simultaneous requests.
206 * - If there are more than one Content-Type headers in one request,
207 * use the first one and remove the others.
208 * - Remove "newval" variable in server_content_type().
209 * It's only used once.
211 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
212 * Correct a cast, check inflateEnd() exit code
213 * to see if we have to, replace sprintf calls
216 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
217 * Integrate a modified version of Wil Mahan's
218 * zlib patch (PR #895531).
220 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
221 * Skip empty filter files in filter_header()
222 * but don't ignore the ones that come afterwards.
223 * Fixes BR 1619208, this time for real.
225 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
226 * Reverted parts of my last commit
227 * to keep error handling working.
229 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
230 * Fixed gcc43 conversion warnings.
232 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
233 * Bringing back the "useless" localtime() call
234 * I removed in revision 1.67. On some platforms
235 * it's necessary to prevent time zone offsets.
237 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
238 * Rebuild request URL in get_destination_from_headers()
239 * to make sure redirect{pcrs command} works as expected
240 * for intercepted requests.
242 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
243 * Added get_destination_from_headers().
245 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
246 * Make pthread mutex locking more generic. Instead of
247 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
248 * and use mutex locking unless there is an _r function
249 * available. Better safe than sorry.
251 * Fixes "./configure --disable-pthread" and should result
252 * in less threading-related problems on pthread-using platforms,
253 * but it still doesn't fix BR#1122404.
255 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
256 * The special header "X-Filter: No" now disables
257 * header filtering as well.
259 * Revision 1.73 2006/09/23 13:26:38 roro
260 * Replace TABs by spaces in source code.
262 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
263 * Don't print a log message every time filter_headers is
264 * entered or left. It only creates noise without any real
267 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
268 * Fix +hide-if-modified-since{-n}.
270 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
271 * Have hide-if-modified-since interpret the random
272 * range value as minutes instead of hours. Allows
273 * more fine-grained configuration.
275 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
276 * Always have parse_header_time return a pointer
277 * that actual makes sense, even though we currently
278 * only need it to detect problems.
280 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
281 * Added config option enable-remote-http-toggle
282 * to specify if Privoxy should recognize special
283 * headers (currently only X-Filter) to change its
284 * behaviour. Disabled by default.
286 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
287 * After filtering de-chunked instances, remove
288 * "Transfer-Encoding" header entirely instead of changing
289 * it to "Transfer-Encoding: identity", which is invalid.
290 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
292 * Don't use localtime in parse_header_time. An empty time struct
293 * is good enough, it gets overwritten by strptime anyway.
295 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
296 * Use gmtime_r if available, fallback to gmtime with mutex
297 * protection for MacOSX and use vanilla gmtime for the rest.
299 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
300 * Changed client_referrer to use the right type (size_t) for
301 * hostlenght and to shorten the temporary referrer string with
302 * '\0' instead of adding a useless line break.
304 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
305 * - Back to timegm() using GnuPG's replacement if necessary.
306 * Using mktime() and localtime() could add a on hour offset if
307 * the randomize factor was big enough to lead to a summer/wintertime
310 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
312 * - Moved randomization code into pick_from_range().
314 * - Changed parse_header_time definition.
315 * time_t isn't guaranteed to be signed and
316 * if it isn't, -1 isn't available as error code.
317 * Changed some variable types in client_if_modified_since()
318 * because of the same reason.
320 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
321 * OS/2 compilation compatibility fixups
323 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
324 * Changed include from strptime.c to strptime.h
326 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
327 * Split filter-headers{} into filter-client-headers{}
328 * and filter-server-headers{}.
329 * Added parse_header_time() to share some code.
330 * Replaced timegm() with mktime().
332 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
333 * Windows service integration
335 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
336 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
338 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
339 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
340 * with what was really the latest development (the v_3_0_branch branch)
342 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
343 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
345 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
346 * Add the ability to check jpeg images for invalid
347 * lengths of comment blocks. Defensive strategy
348 * against the exploit:
349 * Microsoft Security Bulletin MS04-028
350 * Buffer Overrun in JPEG Processing (GDI+) Could
351 * Allow Code Execution (833987)
352 * Enabled with +inspect-jpegs in actions files.
354 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
355 * Excluded text/plain objects from filtering. This fixes a
356 * couple of client-crashing, download corruption and
357 * Privoxy performance issues, whose root cause lies in
358 * web servers labelling content of unknown type as text/plain.
360 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
361 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
363 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
364 * Completing the previous change
366 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
367 * Added temporary workaround for bug in PHP < 4.2.3
369 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
370 * 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.
372 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
373 * Fix typo: supressed -> suppressed
375 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
376 * Improved cookie logging
378 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
379 * Added basic support for OPTIONS and TRACE HTTP methods:
380 * - New parser function client_max_forwards which decrements
381 * the Max-Forwards HTTP header field of OPTIONS and TRACE
382 * requests by one before forwarding
383 * - New parser function client_host which extracts the host
384 * and port information from the HTTP header field if the
385 * request URI was not absolute
386 * - Don't crumble and re-add the Host: header, but only generate
387 * and append if missing
389 * Revision 1.56 2002/05/12 15:34:22 jongfoster
390 * Fixing typo in a comment
392 * Revision 1.55 2002/05/08 16:01:07 oes
393 * Optimized add_to_iob:
394 * - Use realloc instead of malloc(), memcpy(), free()
395 * - Expand to powers of two if possible, to get
396 * O(log n) reallocs instead of O(n).
397 * - Moved check for buffer limit here from chat
398 * - Report failure via returncode
400 * Revision 1.54 2002/04/02 15:03:16 oes
401 * Tiny code cosmetics
403 * Revision 1.53 2002/03/26 22:29:55 swa
404 * we have a new homepage!
406 * Revision 1.52 2002/03/24 13:25:43 swa
407 * name change related issues
409 * Revision 1.51 2002/03/13 00:27:05 jongfoster
412 * Revision 1.50 2002/03/12 01:45:35 oes
413 * More verbose logging
415 * Revision 1.49 2002/03/09 20:03:52 jongfoster
416 * - Making various functions return int rather than size_t.
417 * (Undoing a recent change). Since size_t is unsigned on
418 * Windows, functions like read_socket that return -1 on
419 * error cannot return a size_t.
421 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
422 * crashes, and also frequently caused JB to jump to 100%
423 * CPU and stay there. (Because it thought it had just
424 * read ((unsigned)-1) == 4Gb of data...)
426 * - The signature of write_socket has changed, it now simply
427 * returns success=0/failure=nonzero.
429 * - Trying to get rid of a few warnings --with-debug on
430 * Windows, I've introduced a new type "jb_socket". This is
431 * used for the socket file descriptors. On Windows, this
432 * is SOCKET (a typedef for unsigned). Everywhere else, it's
433 * an int. The error value can't be -1 any more, so it's
434 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
435 * Windows it maps to the #define INVALID_SOCKET.)
437 * - The signature of bind_port has changed.
439 * Revision 1.48 2002/03/07 03:46:53 oes
440 * Fixed compiler warnings etc
442 * Revision 1.47 2002/02/20 23:15:13 jongfoster
443 * Parsing functions now handle out-of-memory gracefully by returning
446 * Revision 1.46 2002/01/17 21:03:47 jongfoster
447 * Moving all our URL and URL pattern parsing code to urlmatch.c.
449 * Revision 1.45 2002/01/09 14:33:03 oes
450 * Added support for localtime_r.
452 * Revision 1.44 2001/12/14 01:22:54 steudten
453 * Remove 'user:pass@' from 'proto://user:pass@host' for the
454 * new added header 'Host: ..'. (See Req ID 491818)
456 * Revision 1.43 2001/11/23 00:26:38 jongfoster
457 * Fixing two really stupid errors in my previous commit
459 * Revision 1.42 2001/11/22 21:59:30 jongfoster
460 * Adding code to handle +no-cookies-keep
462 * Revision 1.41 2001/11/05 23:43:05 steudten
463 * Add time+date to log files.
465 * Revision 1.40 2001/10/26 20:13:09 jongfoster
466 * ctype.h is needed in Windows, too.
468 * Revision 1.39 2001/10/26 17:40:04 oes
469 * Introduced get_header_value()
470 * Removed http->user_agent, csp->referrer and csp->accept_types
471 * Removed client_accept()
473 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
474 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
475 * threads to call select() simultaneously. So, it's time to do a real, live,
476 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
477 * (native). Both versions will work, but using __OS2__ offers multi-threading.
479 * Revision 1.37 2001/10/23 21:36:02 jongfoster
480 * Documenting sed()'s error behaviou (doc change only)
482 * Revision 1.36 2001/10/13 12:51:51 joergs
483 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
484 * force-load), instead crumble Host: and add it (again) in client_host_adder
485 * (in case we get a HTTP/1.0 request without Host: header and forward it to
486 * a HTTP/1.1 server/proxy).
488 * Revision 1.35 2001/10/09 22:39:21 jongfoster
489 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
492 * Revision 1.34 2001/10/07 18:50:55 oes
493 * Added server_content_encoding, renamed server_transfer_encoding
495 * Revision 1.33 2001/10/07 18:04:49 oes
496 * Changed server_http11 to server_http and its pattern to "HTTP".
497 * Additional functionality: it now saves the HTTP status into
498 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
500 * Revision 1.32 2001/10/07 15:43:28 oes
501 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
502 * client_te and client_accept_encoding_adder, triggered by the new
503 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
504 * changed to allow only identity and chunked, and the TE header is
505 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
507 * parse_http_request no longer does anything than parsing. The rewriting
508 * of http->cmd and version mangling are gone. It now also recognizes
509 * the put and delete methods and saves the url in http->url. Removed
512 * renamed content_type and content_length to have the server_ prefix
514 * server_content_type now only works if csp->content_type != CT_TABOO
516 * added server_transfer_encoding, which
517 * - Sets CT_TABOO to prohibit filtering if encoding compresses
518 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
519 * - Change from "chunked" to "identity" if body was chunked
520 * but has been de-chunked for filtering.
522 * added server_content_md5 which crunches any Content-MD5 headers
523 * if the body was modified.
525 * made server_http11 conditional on +downgrade action
527 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
529 * Revision 1.31 2001/10/05 14:25:02 oes
530 * Crumble Keep-Alive from Server
532 * Revision 1.30 2001/09/29 12:56:03 joergs
533 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
535 * Revision 1.29 2001/09/24 21:09:24 jongfoster
536 * Fixing 2 memory leaks that Guy spotted, where the paramater to
537 * enlist() was not being free()d.
539 * Revision 1.28 2001/09/22 16:32:28 jongfoster
540 * Removing unused #includes.
542 * Revision 1.27 2001/09/20 15:45:25 steudten
544 * add casting from size_t to int for printf()
545 * remove local variable shadow s2
547 * Revision 1.26 2001/09/16 17:05:14 jongfoster
548 * Removing unused #include showarg.h
550 * Revision 1.25 2001/09/16 13:21:27 jongfoster
551 * Changes to use new list functions.
553 * Revision 1.24 2001/09/13 23:05:50 jongfoster
554 * Changing the string paramater to the header parsers a "const".
556 * Revision 1.23 2001/09/12 18:08:19 steudten
558 * In parse_http_request() header rewriting miss the host value, so
559 * from http://www.mydomain.com the result was just " / " not
560 * http://www.mydomain.com/ in case we forward.
562 * Revision 1.22 2001/09/10 10:58:53 oes
563 * Silenced compiler warnings
565 * Revision 1.21 2001/07/31 14:46:00 oes
566 * - Persistant connections now suppressed
567 * - sed() no longer appends empty header to csp->headers
569 * Revision 1.20 2001/07/30 22:08:36 jongfoster
570 * Tidying up #defines:
571 * - All feature #defines are now of the form FEATURE_xxx
572 * - Permanently turned off WIN_GUI_EDIT
573 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
575 * Revision 1.19 2001/07/25 17:21:54 oes
576 * client_uagent now saves copy of User-Agent: header value
578 * Revision 1.18 2001/07/13 14:02:46 oes
579 * - Included fix to repair broken HTTP requests that
580 * don't contain a path, not even '/'.
581 * - Removed all #ifdef PCRS
582 * - content_type now always inspected and classified as
583 * text, gif or other.
584 * - formatting / comments
586 * Revision 1.17 2001/06/29 21:45:41 oes
587 * Indentation, CRLF->LF, Tab-> Space
589 * Revision 1.16 2001/06/29 13:32:42 oes
591 * - Adapted free_http_request
592 * - Removed logentry from cancelled commit
594 * Revision 1.15 2001/06/03 19:12:38 oes
595 * deleted const struct interceptors
597 * Revision 1.14 2001/06/01 18:49:17 jongfoster
598 * Replaced "list_share" with "list" - the tiny memory gain was not
599 * worth the extra complexity.
601 * Revision 1.13 2001/05/31 21:30:33 jongfoster
602 * Removed list code - it's now in list.[ch]
603 * Renamed "permission" to "action", and changed many features
604 * to use the actions file rather than the global config.
606 * Revision 1.12 2001/05/31 17:33:13 oes
610 * Revision 1.11 2001/05/29 20:11:19 joergs
611 * '/ * inside comment' warning removed.
613 * Revision 1.10 2001/05/29 09:50:24 jongfoster
614 * Unified blocklist/imagelist/permissionslist.
615 * File format is still under discussion, but the internal changes
618 * Also modified interceptor behaviour:
619 * - We now intercept all URLs beginning with one of the following
620 * prefixes (and *only* these prefixes):
622 * * http://ijbswa.sf.net/config/
623 * * http://ijbswa.sourceforge.net/config/
624 * - New interceptors "home page" - go to http://i.j.b/ to see it.
625 * - Internal changes so that intercepted and fast redirect pages
626 * are not replaced with an image.
627 * - Interceptors now have the option to send a binary page direct
628 * to the client. (i.e. ijb-send-banner uses this)
629 * - Implemented show-url-info interceptor. (Which is why I needed
630 * the above interceptors changes - a typical URL is
631 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
632 * The previous mechanism would not have intercepted that, and
633 * if it had been intercepted then it then it would have replaced
636 * Revision 1.9 2001/05/28 17:26:33 jongfoster
637 * Fixing segfault if last header was crunched.
638 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
639 * can use the cross-platform sprintf() instead.)
641 * Revision 1.8 2001/05/27 22:17:04 oes
643 * - re_process_buffer no longer writes the modified buffer
644 * to the client, which was very ugly. It now returns the
645 * buffer, which it is then written by chat.
647 * - content_length now adjusts the Content-Length: header
648 * for modified documents rather than crunch()ing it.
649 * (Length info in csp->content_length, which is 0 for
650 * unmodified documents)
652 * - For this to work, sed() is called twice when filtering.
654 * Revision 1.7 2001/05/27 13:19:06 oes
655 * Patched Joergs solution for the content-length in.
657 * Revision 1.6 2001/05/26 13:39:32 jongfoster
658 * Only crunches Content-Length header if applying RE filtering.
659 * Without this fix, Microsoft Windows Update wouldn't work.
661 * Revision 1.5 2001/05/26 00:28:36 jongfoster
662 * Automatic reloading of config file.
663 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
664 * Most of the global variables have been moved to a new
665 * struct configuration_spec, accessed through csp->config->globalname
666 * Most of the globals remaining are used by the Win32 GUI.
668 * Revision 1.4 2001/05/22 18:46:04 oes
670 * - Enabled filtering banners by size rather than URL
671 * by adding patterns that replace all standard banner
672 * sizes with the "Junkbuster" gif to the re_filterfile
674 * - Enabled filtering WebBugs by providing a pattern
675 * which kills all 1x1 images
677 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
678 * which is selected by the (nonstandard and therefore
679 * capital) letter 'U' in the option string.
680 * It causes the quantifiers to be ungreedy by default.
681 * Appending a ? turns back to greedy (!).
683 * - Added a new interceptor ijb-send-banner, which
684 * sends back the "Junkbuster" gif. Without imagelist or
685 * MSIE detection support, or if tinygif = 1, or the
686 * URL isn't recognized as an imageurl, a lame HTML
687 * explanation is sent instead.
689 * - Added new feature, which permits blocking remote
690 * script redirects and firing back a local redirect
692 * The feature is conditionally compiled, i.e. it
693 * can be disabled with --disable-fast-redirects,
694 * plus it must be activated by a "fast-redirects"
695 * line in the config file, has its own log level
696 * and of course wants to be displayed by show-proxy-args
697 * Note: Boy, all the #ifdefs in 1001 locations and
698 * all the fumbling with configure.in and acconfig.h
699 * were *way* more work than the feature itself :-(
701 * - Because a generic redirect template was needed for
702 * this, tinygif = 3 now uses the same.
704 * - Moved GIFs, and other static HTTP response templates
709 * - Removed some >400 CRs again (Jon, you really worked
712 * Revision 1.3 2001/05/20 01:21:20 jongfoster
713 * Version 2.9.4 checkin.
714 * - Merged popupfile and cookiefile, and added control over PCRS
715 * filtering, in new "permissionsfile".
716 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
717 * file error you now get a message box (in the Win32 GUI) rather
718 * than the program exiting with no explanation.
719 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
721 * - Removed tabs from "config"
722 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
723 * - Bumped up version number.
725 * Revision 1.2 2001/05/17 23:02:36 oes
726 * - Made referrer option accept 'L' as a substitute for '§'
728 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
729 * Initial import of version 2.9.3 source tree
732 *********************************************************************/
739 #include <sys/types.h>
749 * Convince GNU's libc to provide a strptime prototype.
752 #endif /*__GLIBC__ */
759 #if !defined(_WIN32) && !defined(__OS2__)
765 #ifdef FEATURE_PTHREAD
767 /* jcc.h is for mutex semapores only */
768 #endif /* def FEATURE_PTHREAD */
774 #include "jbsockets.h"
775 #include "miscutil.h"
780 #ifndef HAVE_STRPTIME
781 #include "strptime.h"
784 const char parsers_h_rcs[] = PARSERS_H_VERSION;
786 /* Fix a problem with Solaris. There should be no effect on other
788 * Solaris's isspace() is a macro which uses its argument directly
789 * as an array index. Therefore we need to make sure that high-bit
790 * characters generate +ve values, and ideally we also want to make
791 * the argument match the declared parameter type of "int".
793 * Why did they write a character function that can't take a simple
794 * "char" argument? Doh!
796 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
797 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
799 static jb_err scan_headers(struct client_state *csp);
800 static jb_err header_tagger(struct client_state *csp, char *header);
801 static jb_err parse_header_time(const char *header_time, time_t *result);
803 static jb_err crumble (struct client_state *csp, char **header);
804 static jb_err connection (struct client_state *csp, char **header);
805 static jb_err filter_header (struct client_state *csp, char **header);
806 static jb_err client_referrer (struct client_state *csp, char **header);
807 static jb_err client_uagent (struct client_state *csp, char **header);
808 static jb_err client_ua (struct client_state *csp, char **header);
809 static jb_err client_from (struct client_state *csp, char **header);
810 static jb_err client_send_cookie (struct client_state *csp, char **header);
811 static jb_err client_x_forwarded (struct client_state *csp, char **header);
812 static jb_err client_accept_encoding (struct client_state *csp, char **header);
813 static jb_err client_te (struct client_state *csp, char **header);
814 static jb_err client_max_forwards (struct client_state *csp, char **header);
815 static jb_err client_host (struct client_state *csp, char **header);
816 static jb_err client_if_modified_since (struct client_state *csp, char **header);
817 static jb_err client_accept_language (struct client_state *csp, char **header);
818 static jb_err client_if_none_match (struct client_state *csp, char **header);
819 static jb_err crunch_client_header (struct client_state *csp, char **header);
820 static jb_err client_x_filter (struct client_state *csp, char **header);
821 static jb_err client_range (struct client_state *csp, char **header);
822 static jb_err server_set_cookie (struct client_state *csp, char **header);
823 static jb_err server_content_type (struct client_state *csp, char **header);
824 static jb_err server_content_length (struct client_state *csp, char **header);
825 static jb_err server_content_md5 (struct client_state *csp, char **header);
826 static jb_err server_content_encoding (struct client_state *csp, char **header);
827 static jb_err server_transfer_coding (struct client_state *csp, char **header);
828 static jb_err server_http (struct client_state *csp, char **header);
829 static jb_err crunch_server_header (struct client_state *csp, char **header);
830 static jb_err server_last_modified (struct client_state *csp, char **header);
831 static jb_err server_content_disposition(struct client_state *csp, char **header);
833 static jb_err client_host_adder (struct client_state *csp);
834 static jb_err client_cookie_adder (struct client_state *csp);
835 static jb_err client_xtra_adder (struct client_state *csp);
836 static jb_err connection_close_adder (struct client_state *csp);
838 static jb_err create_forged_referrer(char **header, const char *hostport);
839 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
840 static jb_err handle_conditional_hide_referrer_parameter(char **header,
841 const char *host, const int parameter_conditional_block);
843 const struct parsers client_patterns[] = {
844 { "referer:", 8, client_referrer },
845 { "user-agent:", 11, client_uagent },
846 { "ua-", 3, client_ua },
847 { "from:", 5, client_from },
848 { "cookie:", 7, client_send_cookie },
849 { "x-forwarded-for:", 16, client_x_forwarded },
850 { "Accept-Encoding:", 16, client_accept_encoding },
851 { "TE:", 3, client_te },
852 { "Host:", 5, client_host },
853 { "if-modified-since:", 18, client_if_modified_since },
854 { "Keep-Alive:", 11, crumble },
855 { "connection:", 11, connection },
856 { "proxy-connection:", 17, crumble },
857 { "max-forwards:", 13, client_max_forwards },
858 { "Accept-Language:", 16, client_accept_language },
859 { "if-none-match:", 14, client_if_none_match },
860 { "Range:", 6, client_range },
861 { "If-Range:", 9, client_range },
862 { "X-Filter:", 9, client_x_filter },
863 { "*", 0, crunch_client_header },
864 { "*", 0, filter_header },
868 const struct parsers server_patterns[] = {
869 { "HTTP/", 5, server_http },
870 { "set-cookie:", 11, server_set_cookie },
871 { "connection:", 11, connection },
872 { "Content-Type:", 13, server_content_type },
873 { "Content-MD5:", 12, server_content_md5 },
874 { "Content-Encoding:", 17, server_content_encoding },
875 { "Transfer-Encoding:", 18, server_transfer_coding },
876 { "Keep-Alive:", 11, crumble },
877 { "content-disposition:", 20, server_content_disposition },
878 { "Last-Modified:", 14, server_last_modified },
879 { "*", 0, crunch_server_header },
880 { "*", 0, filter_header },
884 const struct parsers server_patterns_light[] = {
885 { "Content-Length:", 15, server_content_length },
886 { "Transfer-Encoding:", 18, server_transfer_coding },
888 { "Content-Encoding:", 17, server_content_encoding },
889 #endif /* def FEATURE_ZLIB */
893 const add_header_func_ptr add_client_headers[] = {
897 /* Temporarily disabled: client_accept_encoding_adder, */
898 connection_close_adder,
902 const add_header_func_ptr add_server_headers[] = {
903 connection_close_adder,
907 /* The vanilla wafer. */
908 static const char VANILLA_WAFER[] =
909 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
910 "Do_not_send_me_any_copyrighted_information_other_than_the_"
911 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
912 "In_particular_do_not_send_me_any_cookies_that_"
913 "are_subject_to_a_claim_of_copyright_by_anybody._"
914 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
915 "(copyright_or_otherwise)_applying_to_any_cookie._";
917 /*********************************************************************
919 * Function : flush_socket
921 * Description : Write any pending "buffered" content.
924 * 1 : fd = file descriptor of the socket to read
925 * 2 : csp = Current client state (buffers, headers, etc...)
927 * Returns : On success, the number of bytes written are returned (zero
928 * indicates nothing was written). On error, -1 is returned,
929 * and errno is set appropriately. If count is zero and the
930 * file descriptor refers to a regular file, 0 will be
931 * returned without causing any other effect. For a special
932 * file, the results are not portable.
934 *********************************************************************/
935 int flush_socket(jb_socket fd, struct client_state *csp)
937 struct iob *iob = csp->iob;
938 int len = iob->eod - iob->cur;
945 if (write_socket(fd, iob->cur, (size_t)len))
949 iob->eod = iob->cur = iob->buf;
955 /*********************************************************************
957 * Function : add_to_iob
959 * Description : Add content to the buffered page, expanding the
960 * buffer if necessary.
963 * 1 : csp = Current client state (buffers, headers, etc...)
964 * 2 : buf = holds the content to be added to the page
965 * 3 : n = number of bytes to be added
967 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
968 * or buffer limit reached.
970 *********************************************************************/
971 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
973 struct iob *iob = csp->iob;
974 size_t used, offset, need, want;
977 if (n <= 0) return JB_ERR_OK;
979 used = (size_t)(iob->eod - iob->buf);
980 offset = (size_t)(iob->cur - iob->buf);
981 need = used + (size_t)n + 1;
984 * If the buffer can't hold the new data, extend it first.
985 * Use the next power of two if possible, else use the actual need.
987 if (need > csp->config->buffer_limit)
989 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
990 return JB_ERR_MEMORY;
993 if (need > iob->size)
995 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
997 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1001 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1007 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1008 return JB_ERR_MEMORY;
1011 /* Update the iob pointers */
1012 iob->cur = p + offset;
1013 iob->eod = p + used;
1017 /* copy the new data into the iob buffer */
1018 memcpy(iob->eod, buf, (size_t)n);
1020 /* point to the end of the data */
1023 /* null terminate == cheap insurance */
1032 /*********************************************************************
1034 * Function : decompress_iob
1036 * Description : Decompress buffered page, expanding the
1037 * buffer as necessary. csp->iob->cur
1038 * should point to the the beginning of the
1039 * compressed data block.
1042 * 1 : csp = Current client state (buffers, headers, etc...)
1044 * Returns : JB_ERR_OK on success,
1045 * JB_ERR_MEMORY if out-of-memory limit reached, and
1046 * JB_ERR_COMPRESS if error decompressing buffer.
1048 *********************************************************************/
1049 jb_err decompress_iob(struct client_state *csp)
1051 char *buf; /* new, uncompressed buffer */
1052 char *cur; /* Current iob position (to keep the original
1053 * iob->cur unmodified if we return early) */
1054 size_t bufsize; /* allocated size of the new buffer */
1055 size_t old_size; /* Content size before decompression */
1056 size_t skip_size; /* Number of bytes at the beginning of the iob
1057 that we should NOT decompress. */
1058 int status; /* return status of the inflate() call */
1059 z_stream zstr; /* used by calls to zlib */
1061 assert(csp->iob->cur - csp->iob->buf > 0);
1062 assert(csp->iob->eod - csp->iob->cur > 0);
1064 bufsize = csp->iob->size;
1065 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1066 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1068 cur = csp->iob->cur;
1073 * This is to protect the parsing of gzipped data,
1074 * but it should(?) be valid for deflated data also.
1076 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1077 return JB_ERR_COMPRESS;
1080 if (csp->content_type & CT_GZIP)
1083 * Our task is slightly complicated by the facts that data
1084 * compressed by gzip does not include a zlib header, and
1085 * that there is no easily accessible interface in zlib to
1086 * handle a gzip header. We strip off the gzip header by
1087 * hand, and later inform zlib not to expect a header.
1091 * Strip off the gzip header. Please see RFC 1952 for more
1092 * explanation of the appropriate fields.
1094 if ((*cur++ != (char)0x1f)
1095 || (*cur++ != (char)0x8b)
1096 || (*cur++ != Z_DEFLATED))
1098 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1099 return JB_ERR_COMPRESS;
1105 * XXX: These magic numbers should be replaced
1106 * with macros to give a better idea what they do.
1110 /* The gzip header has reserved bits set; bail out. */
1111 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1112 return JB_ERR_COMPRESS;
1116 /* Skip extra fields if necessary. */
1120 * Skip a given number of bytes, specified
1121 * as a 16-bit little-endian value.
1124 * XXX: This code used to be:
1126 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1128 * which I had to change into:
1130 * cur += *cur++ + (*cur++ << 8);
1132 * at which point gcc43 finally noticed that the value
1133 * of cur is undefined (it depends on which of the
1134 * summands is evaluated first).
1136 * I haven't come across a site where this
1137 * code is actually executed yet, but I hope
1141 skip_bytes = *cur++;
1142 skip_bytes = *cur++ << 8;
1144 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1147 * The number of bytes to skip should be positive
1148 * and we'd like to stay in the buffer.
1150 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1152 log_error(LOG_LEVEL_ERROR,
1153 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1155 return JB_ERR_COMPRESS;
1157 log_error(LOG_LEVEL_INFO,
1158 "Skipping %d bytes for gzip compression. Does this sound right?",
1163 /* Skip the filename if necessary. */
1166 /* A null-terminated string is supposed to follow. */
1167 while (*cur++ && (cur < csp->iob->eod));
1171 /* Skip the comment if necessary. */
1174 /* A null-terminated string is supposed to follow. */
1175 while (*cur++ && (cur < csp->iob->eod));
1178 /* Skip the CRC if necessary. */
1184 if (cur >= csp->iob->eod)
1187 * If the current position pointer reached or passed
1188 * the buffer end, we were obviously tricked to skip
1191 log_error(LOG_LEVEL_ERROR,
1192 "Malformed gzip header detected. Aborting decompression.");
1193 return JB_ERR_COMPRESS;
1197 else if (csp->content_type & CT_DEFLATE)
1200 * XXX: The debug level should be lowered
1201 * before the next stable release.
1203 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1205 * In theory (that is, according to RFC 1950), deflate-compressed
1206 * data should begin with a two-byte zlib header and have an
1207 * adler32 checksum at the end. It seems that in practice only
1208 * the raw compressed data is sent. Note that this means that
1209 * we are not RFC 1950-compliant here, but the advantage is that
1210 * this actually works. :)
1212 * We add a dummy null byte to tell zlib where the data ends,
1213 * and later inform it not to expect a header.
1215 * Fortunately, add_to_iob() has thoughtfully null-terminated
1216 * the buffer; we can just increment the end pointer to include
1223 log_error(LOG_LEVEL_ERROR,
1224 "Unable to determine compression format for decompression");
1225 return JB_ERR_COMPRESS;
1228 /* Set up the fields required by zlib. */
1229 zstr.next_in = (Bytef *)cur;
1230 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1231 zstr.zalloc = Z_NULL;
1232 zstr.zfree = Z_NULL;
1233 zstr.opaque = Z_NULL;
1236 * Passing -MAX_WBITS to inflateInit2 tells the library
1237 * that there is no zlib header.
1239 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1241 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1242 return JB_ERR_COMPRESS;
1246 * Next, we allocate new storage for the inflated data.
1247 * We don't modify the existing iob yet, so in case there
1248 * is error in decompression we can recover gracefully.
1250 buf = zalloc(bufsize);
1253 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1254 return JB_ERR_MEMORY;
1257 assert(bufsize >= skip_size);
1258 memcpy(buf, csp->iob->buf, skip_size);
1259 zstr.avail_out = bufsize - skip_size;
1260 zstr.next_out = (Bytef *)buf + skip_size;
1262 /* Try to decompress the whole stream in one shot. */
1263 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1265 /* We need to allocate more memory for the output buffer. */
1267 char *tmpbuf; /* used for realloc'ing the buffer */
1268 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1271 * If zlib wants more data then there's a problem, because
1272 * the complete compressed file should have been buffered.
1274 if (0 == zstr.avail_in)
1276 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1277 return JB_ERR_COMPRESS;
1281 * If we tried the limit and still didn't have enough
1282 * memory, just give up.
1284 if (bufsize == csp->config->buffer_limit)
1286 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1287 return JB_ERR_MEMORY;
1290 /* Try doubling the buffer size each time. */
1293 /* Don't exceed the buffer limit. */
1294 if (bufsize > csp->config->buffer_limit)
1296 bufsize = csp->config->buffer_limit;
1299 /* Try to allocate the new buffer. */
1300 tmpbuf = realloc(buf, bufsize);
1303 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1305 return JB_ERR_MEMORY;
1309 char *oldnext_out = (char *)zstr.next_out;
1312 * Update the fields for inflate() to use the new
1313 * buffer, which may be in a location different from
1316 zstr.avail_out += bufsize - oldbufsize;
1317 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1320 * Compare with an uglier method of calculating these values
1321 * that doesn't require the extra oldbufsize variable.
1323 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1324 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1325 assert(zstr.avail_out > 0);
1331 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1333 log_error(LOG_LEVEL_ERROR,
1334 "Inconsistent stream state after decompression: %s", zstr.msg);
1336 * XXX: Intentionally no return.
1338 * According to zlib.h, Z_STREAM_ERROR is returned
1339 * "if the stream state was inconsistent".
1341 * I assume in this case inflate()'s status
1342 * would also be something different than Z_STREAM_END
1343 * so this check should be redundant, but lets see.
1347 if (status != Z_STREAM_END)
1349 /* We failed to decompress the stream. */
1350 log_error(LOG_LEVEL_ERROR,
1351 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1352 return JB_ERR_COMPRESS;
1356 * Finally, we can actually update the iob, since the
1357 * decompression was successful. First, free the old
1360 freez(csp->iob->buf);
1362 /* Now, update the iob to use the new buffer. */
1363 csp->iob->buf = buf;
1364 csp->iob->cur = csp->iob->buf + skip_size;
1365 csp->iob->eod = (char *)zstr.next_out;
1366 csp->iob->size = bufsize;
1369 * Make sure the new uncompressed iob obeys some minimal
1370 * consistency conditions.
1372 if ((csp->iob->buf < csp->iob->cur)
1373 && (csp->iob->cur <= csp->iob->eod)
1374 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1376 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1379 log_error(LOG_LEVEL_RE_FILTER,
1380 "Decompression successful. Old size: %d, new size: %d.",
1381 old_size, new_size);
1385 /* zlib thinks this is OK, so lets do the same. */
1386 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1391 /* It seems that zlib did something weird. */
1392 log_error(LOG_LEVEL_ERROR,
1393 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1394 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1395 csp->iob->eod, csp->iob->buf + csp->iob->size);
1396 return JB_ERR_COMPRESS;
1402 #endif /* defined(FEATURE_ZLIB) */
1405 /*********************************************************************
1407 * Function : get_header
1409 * Description : This (odd) routine will parse the csp->iob
1412 * 1 : csp = Current client state (buffers, headers, etc...)
1414 * Returns : Any one of the following:
1416 * 1) a pointer to a dynamically allocated string that contains a header line
1417 * 2) NULL indicating that the end of the header was reached
1418 * 3) "" indicating that the end of the iob was reached before finding
1419 * a complete header line.
1421 *********************************************************************/
1422 char *get_header(struct client_state *csp)
1428 if ((iob->cur == NULL)
1429 || ((p = strchr(iob->cur, '\n')) == NULL))
1431 return(""); /* couldn't find a complete header */
1436 ret = strdup(iob->cur);
1439 /* FIXME No way to handle error properly */
1440 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1445 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1447 /* is this a blank line (i.e. the end of the header) ? */
1459 /*********************************************************************
1461 * Function : get_header_value
1463 * Description : Get the value of a given header from a chained list
1464 * of header lines or return NULL if no such header is
1465 * present in the list.
1468 * 1 : header_list = pointer to list
1469 * 2 : header_name = string with name of header to look for.
1470 * Trailing colon required, capitalization
1473 * Returns : NULL if not found, else value of header
1475 *********************************************************************/
1476 char *get_header_value(const struct list *header_list, const char *header_name)
1478 struct list_entry *cur_entry;
1482 assert(header_list);
1483 assert(header_name);
1484 length = strlen(header_name);
1486 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1490 if (!strncmpic(cur_entry->str, header_name, length))
1493 * Found: return pointer to start of value
1495 ret = (char *) (cur_entry->str + length);
1496 while (*ret && ijb_isspace(*ret)) ret++;
1510 /*********************************************************************
1512 * Function : scan_headers
1514 * Description : Scans headers, applies tags and updates action bits.
1517 * 1 : csp = Current client state (buffers, headers, etc...)
1519 * Returns : JB_ERR_OK
1521 *********************************************************************/
1522 static jb_err scan_headers(struct client_state *csp)
1524 struct list_entry *h; /* Header */
1525 jb_err err = JB_ERR_OK;
1527 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1529 /* Header crunch()ed in previous run? -> ignore */
1530 if (h->str == NULL) continue;
1531 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1532 err = header_tagger(csp, h->str);
1539 /*********************************************************************
1543 * Description : add, delete or modify lines in the HTTP header streams.
1544 * On entry, it receives a linked list of headers space
1545 * that was allocated dynamically (both the list nodes
1546 * and the header contents).
1548 * As a side effect it frees the space used by the original
1551 * XXX: should be split to remove the first_run hack.
1554 * 1 : pats = list of patterns to match against headers
1555 * 2 : more_headers = list of functions to add more
1556 * headers (client or server)
1557 * 3 : csp = Current client state (buffers, headers, etc...)
1559 * Returns : JB_ERR_OK in case off success, or
1560 * JB_ERR_MEMORY on out-of-memory error.
1562 *********************************************************************/
1563 jb_err sed(const struct parsers pats[],
1564 const add_header_func_ptr more_headers[],
1565 struct client_state *csp)
1567 struct list_entry *p;
1568 const struct parsers *v;
1569 const add_header_func_ptr *f;
1570 jb_err err = JB_ERR_OK;
1574 * If filtering is enabled, sed is run twice,
1575 * but most of the work needs to be done only once.
1577 first_run = (more_headers != NULL ) ? 1 : 0;
1579 if (first_run) /* Parse and print */
1583 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1585 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1587 /* Header crunch()ed in previous run? -> ignore */
1588 if (p->str == NULL) continue;
1590 /* Does the current parser handle this header? */
1591 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1593 err = v->parser(csp, (char **)&(p->str));
1597 /* place any additional headers on the csp->headers list */
1598 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1603 else /* Parse only */
1606 * The second run is only needed if the body was modified
1607 * and the content-lenght has changed.
1609 if (strncmpic(csp->http->cmd, "HEAD", 4))
1611 /*XXX: Code duplication */
1612 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1614 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1616 /* Header crunch()ed in previous run? -> ignore */
1617 if (p->str == NULL) continue;
1619 /* Does the current parser handle this header? */
1620 if (strncmpic(p->str, v->str, v->len) == 0)
1622 err = v->parser(csp, (char **)&(p->str));
1634 /*********************************************************************
1636 * Function : header_tagger
1638 * Description : Executes all text substitutions from applying
1639 * tag actions and saves the result as tag.
1641 * XXX: Shares enough code with filter_header() and
1642 * pcrs_filter_response() to warrant some helper functions.
1645 * 1 : csp = Current client state (buffers, headers, etc...)
1646 * 2 : header = Header that is used as tagger input
1648 * Returns : JB_ERR_OK on success and always succeeds
1650 *********************************************************************/
1651 static jb_err header_tagger(struct client_state *csp, char *header)
1653 int wanted_filter_type;
1654 int multi_action_index;
1658 struct file_list *fl;
1659 struct re_filterfile_spec *b;
1660 struct list_entry *tag_name;
1662 int found_filters = 0;
1663 const size_t header_length = strlen(header);
1665 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1667 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1668 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1672 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1673 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1676 /* Check if there are any filters */
1677 for (i = 0; i < MAX_AF_FILES; i++)
1690 if (0 == found_filters)
1692 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1696 for (i = 0; i < MAX_AF_FILES; i++)
1699 if ((NULL == fl) || (NULL == fl->f))
1702 * Either there are no filter files
1703 * left, or this filter file just
1704 * contains no valid filters.
1706 * Continue to be sure we don't miss
1707 * valid filter files that are chained
1708 * after empty or invalid ones.
1713 /* For all filters, */
1714 for (b = fl->f; b; b = b->next)
1716 if (b->type != wanted_filter_type)
1718 /* skip the ones we don't care about, */
1721 /* leaving only taggers that could apply, of which we use the ones, */
1722 for (tag_name = csp->action->multi[multi_action_index]->first;
1723 NULL != tag_name; tag_name = tag_name->next)
1725 /* that do apply, and */
1726 if (strcmp(b->name, tag_name->str) == 0)
1728 char *modified_tag = NULL;
1730 size_t size = header_length;
1731 pcrs_job *joblist = b->joblist;
1733 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1735 if (NULL == joblist)
1737 log_error(LOG_LEVEL_RE_FILTER,
1738 "Tagger %s has empty joblist. Nothing to do.", b->name);
1742 /* execute their pcrs_joblist on the header. */
1743 for (job = joblist; NULL != job; job = job->next)
1745 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1749 /* Success, continue with the modified version. */
1758 /* Tagger doesn't match */
1761 /* Regex failure, log it but continue anyway. */
1762 log_error(LOG_LEVEL_ERROR,
1763 "Problems with tagger \'%s\' and header \'%s\': %s",
1764 b->name, *header, pcrs_strerror(hits));
1766 freez(modified_tag);
1770 if (b->dynamic) pcrs_free_joblist(joblist);
1772 /* If this tagger matched */
1778 * There is to technical limitation which makes
1779 * it impossible to use empty tags, but I assume
1780 * no one would do it intentionally.
1783 log_error(LOG_LEVEL_INFO,
1784 "Tagger \'%s\' created an empty tag. Ignored.",
1789 if (!list_contains_item(csp->tags, tag))
1791 if (JB_ERR_OK != enlist(csp->tags, tag))
1793 log_error(LOG_LEVEL_ERROR,
1794 "Insufficient memory to add tag \'%s\', "
1795 "based on tagger \'%s\' and header \'%s\'",
1796 tag, b->name, *header);
1800 char *action_message;
1802 * update the action bits right away, to make
1803 * tagging based on tags set by earlier taggers
1804 * of the same kind possible.
1806 if (update_action_bits_for_tag(csp, tag))
1808 action_message = "Action bits updated accordingly.";
1812 action_message = "No action bits update necessary.";
1815 log_error(LOG_LEVEL_HEADER,
1816 "Tagger \'%s\' added tag \'%s\'. %s",
1817 b->name, tag, action_message);
1822 /* XXX: Is this log-worthy? */
1823 log_error(LOG_LEVEL_HEADER,
1824 "Tagger \'%s\' didn't add tag \'%s\'. "
1825 "Tag already present", b->name, tag);
1828 } /* if the tagger matched */
1829 } /* if the tagger applies */
1830 } /* for every tagger that could apply */
1831 } /* for all filters */
1832 } /* for all filter files */
1837 /* here begins the family of parser functions that reformat header lines */
1839 /*********************************************************************
1841 * Function : filter_header
1843 * Description : Executes all text substitutions from all applying
1844 * +(server|client)-header-filter actions on the header.
1845 * Most of the code was copied from pcrs_filter_response,
1846 * including the rather short variable names
1849 * 1 : csp = Current client state (buffers, headers, etc...)
1850 * 2 : header = On input, pointer to header to modify.
1851 * On output, pointer to the modified header, or NULL
1852 * to remove the header. This function frees the
1853 * original string if necessary.
1855 * Returns : JB_ERR_OK on success and always succeeds
1857 *********************************************************************/
1858 static jb_err filter_header(struct client_state *csp, char **header)
1862 size_t size = strlen(*header);
1864 char *newheader = NULL;
1867 struct file_list *fl;
1868 struct re_filterfile_spec *b;
1869 struct list_entry *filtername;
1871 int i, found_filters = 0;
1872 int wanted_filter_type;
1873 int multi_action_index;
1875 if (csp->flags & CSP_FLAG_NO_FILTERING)
1880 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1882 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1883 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1887 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1888 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1892 * Need to check the set of re_filterfiles...
1894 for (i = 0; i < MAX_AF_FILES; i++)
1907 if (0 == found_filters)
1909 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1913 for (i = 0; i < MAX_AF_FILES; i++)
1916 if ((NULL == fl) || (NULL == fl->f))
1919 * Either there are no filter files
1920 * left, or this filter file just
1921 * contains no valid filters.
1923 * Continue to be sure we don't miss
1924 * valid filter files that are chained
1925 * after empty or invalid ones.
1930 * For all applying +filter actions, look if a filter by that
1931 * name exists and if yes, execute its pcrs_joblist on the
1934 for (b = fl->f; b; b = b->next)
1936 if (b->type != wanted_filter_type)
1938 /* Skip other filter types */
1942 for (filtername = csp->action->multi[multi_action_index]->first;
1943 filtername ; filtername = filtername->next)
1945 if (strcmp(b->name, filtername->str) == 0)
1947 int current_hits = 0;
1948 pcrs_job *joblist = b->joblist;
1950 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1952 if (NULL == joblist)
1954 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1958 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1959 *header, size, b->name);
1961 /* Apply all jobs from the joblist */
1962 for (job = joblist; NULL != job; job = job->next)
1964 matches = pcrs_execute(job, *header, size, &newheader, &size);
1967 current_hits += matches;
1968 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1970 *header = newheader;
1972 else if ( 0 == matches )
1974 /* Filter doesn't change header */
1980 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1981 *header, b->name, pcrs_strerror(matches));
1982 if (newheader != NULL)
1984 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1990 if (b->dynamic) pcrs_free_joblist(joblist);
1992 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1993 hits += current_hits;
2000 * Additionally checking for hits is important because if
2001 * the continue hack is triggered, server headers can
2002 * arrive empty to separate multiple heads from each other.
2004 if ((0 == size) && hits)
2006 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2014 /*********************************************************************
2016 * Function : connection
2018 * Description : Makes sure that the value of the Connection: header
2019 * is "close" and signals connection_close_adder
2023 * 1 : csp = Current client state (buffers, headers, etc...)
2024 * 2 : header = On input, pointer to header to modify.
2025 * On output, pointer to the modified header, or NULL
2026 * to remove the header. This function frees the
2027 * original string if necessary.
2029 * Returns : JB_ERR_OK on success, or
2030 * JB_ERR_MEMORY on out-of-memory error.
2032 *********************************************************************/
2033 static jb_err connection(struct client_state *csp, char **header)
2035 char *old_header = *header;
2037 /* Do we have a 'Connection: close' header? */
2038 if (strcmpic(*header, "Connection: close"))
2040 /* No, create one */
2041 *header = strdup("Connection: close");
2044 return JB_ERR_MEMORY;
2046 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2050 /* Signal connection_close_adder() to return early. */
2051 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2053 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2057 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2064 /*********************************************************************
2066 * Function : crumble
2068 * Description : This is called if a header matches a pattern to "crunch"
2071 * 1 : csp = Current client state (buffers, headers, etc...)
2072 * 2 : header = On input, pointer to header to modify.
2073 * On output, pointer to the modified header, or NULL
2074 * to remove the header. This function frees the
2075 * original string if necessary.
2077 * Returns : JB_ERR_OK on success, or
2078 * JB_ERR_MEMORY on out-of-memory error.
2080 *********************************************************************/
2081 static jb_err crumble(struct client_state *csp, char **header)
2083 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2089 /*********************************************************************
2091 * Function : crunch_server_header
2093 * Description : Crunch server header if it matches a string supplied by the
2094 * user. Called from `sed'.
2097 * 1 : csp = Current client state (buffers, headers, etc...)
2098 * 2 : header = On input, pointer to header to modify.
2099 * On output, pointer to the modified header, or NULL
2100 * to remove the header. This function frees the
2101 * original string if necessary.
2103 * Returns : JB_ERR_OK on success and always succeeds
2105 *********************************************************************/
2106 static jb_err crunch_server_header(struct client_state *csp, char **header)
2108 const char *crunch_pattern;
2110 /* Do we feel like crunching? */
2111 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2113 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2115 /* Is the current header the lucky one? */
2116 if (strstr(*header, crunch_pattern))
2118 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2127 /*********************************************************************
2129 * Function : server_content_type
2131 * Description : Set the content-type for filterable types (text/.*,
2132 * .*xml.*, javascript and image/gif) unless filtering has been
2133 * forbidden (CT_TABOO) while parsing earlier headers.
2134 * NOTE: Since text/plain is commonly used by web servers
2135 * for files whose correct type is unknown, we don't
2136 * set CT_TEXT for it.
2139 * 1 : csp = Current client state (buffers, headers, etc...)
2140 * 2 : header = On input, pointer to header to modify.
2141 * On output, pointer to the modified header, or NULL
2142 * to remove the header. This function frees the
2143 * original string if necessary.
2145 * Returns : JB_ERR_OK on success, or
2146 * JB_ERR_MEMORY on out-of-memory error.
2148 *********************************************************************/
2149 static jb_err server_content_type(struct client_state *csp, char **header)
2151 /* Remove header if it isn't the first Content-Type header */
2152 if ((csp->content_type & CT_DECLARED))
2155 * Another, slightly slower, way to see if
2156 * we already parsed another Content-Type header.
2158 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2160 log_error(LOG_LEVEL_ERROR,
2161 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2169 * Signal that the Content-Type has been set.
2171 csp->content_type |= CT_DECLARED;
2173 if (!(csp->content_type & CT_TABOO))
2175 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2176 || strstr(*header, "xml")
2177 || strstr(*header, "application/x-javascript"))
2179 csp->content_type |= CT_TEXT;
2181 else if (strstr(*header, " image/gif"))
2183 csp->content_type |= CT_GIF;
2185 else if (strstr(*header, " image/jpeg"))
2187 csp->content_type |= CT_JPEG;
2192 * Are we messing with the content type?
2194 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2197 * Make sure the user doesn't accidently
2198 * change the content type of binary documents.
2200 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2203 *header = strdup("Content-Type: ");
2204 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2208 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2209 return JB_ERR_MEMORY;
2211 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2215 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2216 "Enable force-text-mode if you know what you're doing.", *header);
2224 /*********************************************************************
2226 * Function : server_transfer_coding
2228 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2229 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2230 * - Remove header if body was chunked but has been
2231 * de-chunked for filtering.
2234 * 1 : csp = Current client state (buffers, headers, etc...)
2235 * 2 : header = On input, pointer to header to modify.
2236 * On output, pointer to the modified header, or NULL
2237 * to remove the header. This function frees the
2238 * original string if necessary.
2240 * Returns : JB_ERR_OK on success, or
2241 * JB_ERR_MEMORY on out-of-memory error.
2243 *********************************************************************/
2244 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2247 * Turn off pcrs and gif filtering if body compressed
2249 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2253 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2255 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2256 csp->http->cmd, *header);
2257 #endif /* def FEATURE_ZLIB */
2258 csp->content_type = CT_TABOO;
2262 * Raise flag if body chunked
2264 if (strstr(*header, "chunked"))
2266 csp->flags |= CSP_FLAG_CHUNKED;
2269 * If the body was modified, it has been de-chunked first
2270 * and the header must be removed.
2272 * FIXME: If there is more than one transfer encoding,
2273 * only the "chunked" part should be removed here.
2275 if (csp->flags & CSP_FLAG_MODIFIED)
2277 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2286 /*********************************************************************
2288 * Function : server_content_encoding
2290 * Description : This function is run twice for each request,
2291 * unless FEATURE_ZLIB and filtering are disabled.
2293 * The first run is used to check if the content
2294 * is compressed, if FEATURE_ZLIB is disabled
2295 * filtering is then disabled as well, if FEATURE_ZLIB
2296 * is enabled the content is marked for decompression.
2298 * The second run is used to remove the Content-Encoding
2299 * header if the decompression was successful.
2302 * 1 : csp = Current client state (buffers, headers, etc...)
2303 * 2 : header = On input, pointer to header to modify.
2304 * On output, pointer to the modified header, or NULL
2305 * to remove the header. This function frees the
2306 * original string if necessary.
2308 * Returns : JB_ERR_OK on success, or
2309 * JB_ERR_MEMORY on out-of-memory error.
2311 *********************************************************************/
2312 static jb_err server_content_encoding(struct client_state *csp, char **header)
2315 if ((csp->flags & CSP_FLAG_MODIFIED)
2316 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2319 * We successfully decompressed the content,
2320 * and have to clean the header now, so the
2321 * client no longer expects compressed data..
2323 * XXX: There is a difference between cleaning
2324 * and removing it completely.
2326 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2329 else if (strstr(*header, "gzip"))
2331 /* Mark for gzip decompression */
2332 csp->content_type |= CT_GZIP;
2334 else if (strstr(*header, "deflate"))
2336 /* Mark for zlib decompression */
2337 csp->content_type |= CT_DEFLATE;
2339 else if (strstr(*header, "compress"))
2342 * We can't decompress this; therefore we can't filter
2345 csp->content_type |= CT_TABOO;
2347 #else /* !defined(FEATURE_ZLIB) */
2348 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2351 * Body is compressed, turn off pcrs and gif filtering.
2353 csp->content_type |= CT_TABOO;
2356 * Log a warning if the user expects the content to be filtered.
2358 if ((csp->rlist != NULL) &&
2359 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2361 log_error(LOG_LEVEL_INFO,
2362 "Compressed content detected, content filtering disabled. "
2363 "Consider recompiling Privoxy with zlib support or "
2364 "enable the prevent-compression action.");
2367 #endif /* defined(FEATURE_ZLIB) */
2374 /*********************************************************************
2376 * Function : server_content_length
2378 * Description : Adjust Content-Length header if we modified
2382 * 1 : csp = Current client state (buffers, headers, etc...)
2383 * 2 : header = On input, pointer to header to modify.
2384 * On output, pointer to the modified header, or NULL
2385 * to remove the header. This function frees the
2386 * original string if necessary.
2388 * Returns : JB_ERR_OK on success, or
2389 * JB_ERR_MEMORY on out-of-memory error.
2391 *********************************************************************/
2392 static jb_err server_content_length(struct client_state *csp, char **header)
2394 const size_t max_header_length = 80;
2396 /* Regenerate header if the content was modified. */
2397 if (csp->flags & CSP_FLAG_MODIFIED)
2400 *header = (char *) zalloc(max_header_length);
2401 if (*header == NULL)
2403 return JB_ERR_MEMORY;
2406 snprintf(*header, max_header_length, "Content-Length: %d",
2407 (int)csp->content_length);
2408 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2409 (int)csp->content_length);
2416 /*********************************************************************
2418 * Function : server_content_md5
2420 * Description : Crumble any Content-MD5 headers if the document was
2421 * modified. FIXME: Should we re-compute instead?
2424 * 1 : csp = Current client state (buffers, headers, etc...)
2425 * 2 : header = On input, pointer to header to modify.
2426 * On output, pointer to the modified header, or NULL
2427 * to remove the header. This function frees the
2428 * original string if necessary.
2430 * Returns : JB_ERR_OK on success, or
2431 * JB_ERR_MEMORY on out-of-memory error.
2433 *********************************************************************/
2434 static jb_err server_content_md5(struct client_state *csp, char **header)
2436 if (csp->flags & CSP_FLAG_MODIFIED)
2438 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2446 /*********************************************************************
2448 * Function : server_content_disposition
2450 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2451 * Called from `sed'.
2454 * 1 : csp = Current client state (buffers, headers, etc...)
2455 * 2 : header = On input, pointer to header to modify.
2456 * On output, pointer to the modified header, or NULL
2457 * to remove the header. This function frees the
2458 * original string if necessary.
2460 * Returns : JB_ERR_OK on success, or
2461 * JB_ERR_MEMORY on out-of-memory error.
2463 *********************************************************************/
2464 static jb_err server_content_disposition(struct client_state *csp, char **header)
2469 * Are we messing with the Content-Disposition header?
2471 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2477 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2479 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2482 * Blocking content-disposition header
2484 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2491 * Replacing Content-Disposition header
2494 *header = strdup("Content-Disposition: ");
2495 string_append(header, newval);
2497 if (*header != NULL)
2499 log_error(LOG_LEVEL_HEADER,
2500 "Content-Disposition header crunched and replaced with: %s", *header);
2503 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2507 /*********************************************************************
2509 * Function : server_last_modified
2511 * Description : Changes Last-Modified header to the actual date
2512 * to help hide-if-modified-since.
2513 * Called from `sed'.
2516 * 1 : csp = Current client state (buffers, headers, etc...)
2517 * 2 : header = On input, pointer to header to modify.
2518 * On output, pointer to the modified header, or NULL
2519 * to remove the header. This function frees the
2520 * original string if necessary.
2522 * Returns : JB_ERR_OK on success, or
2523 * JB_ERR_MEMORY on out-of-memory error.
2525 *********************************************************************/
2526 static jb_err server_last_modified(struct client_state *csp, char **header)
2529 char buf[BUFFER_SIZE];
2532 #ifdef HAVE_GMTIME_R
2535 struct tm *timeptr = NULL;
2536 time_t now, last_modified;
2538 long int days, hours, minutes, seconds;
2541 * Are we messing with the Last-Modified header?
2543 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2549 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2551 if (0 == strcmpic(newval, "block") )
2554 * Blocking Last-Modified header. Useless but why not.
2556 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2560 else if (0 == strcmpic(newval, "reset-to-request-time"))
2563 * Setting Last-Modified Header to now.
2565 get_http_time(0, buf);
2567 *header = strdup("Last-Modified: ");
2568 string_append(header, buf);
2570 if (*header == NULL)
2572 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2576 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2579 else if (0 == strcmpic(newval, "randomize"))
2581 const char *header_time = *header + sizeof("Last-Modified:");
2583 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2585 #ifdef HAVE_GMTIME_R
2586 timeptr = gmtime_r(&now, &gmt);
2587 #elif FEATURE_PTHREAD
2588 pthread_mutex_lock(&gmtime_mutex);
2589 timeptr = gmtime(&now);
2590 pthread_mutex_unlock(&gmtime_mutex);
2592 timeptr = gmtime(&now);
2594 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2596 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2601 rtime = (long int)difftime(now, last_modified);
2610 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2612 rtime = pick_from_range(rtime);
2613 if (negative) rtime *= -1;
2614 last_modified += rtime;
2615 #ifdef HAVE_GMTIME_R
2616 timeptr = gmtime_r(&last_modified, &gmt);
2617 #elif FEATURE_PTHREAD
2618 pthread_mutex_lock(&gmtime_mutex);
2619 timeptr = gmtime(&last_modified);
2620 pthread_mutex_unlock(&gmtime_mutex);
2622 timeptr = gmtime(&last_modified);
2624 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2626 *header = strdup("Last-Modified: ");
2627 string_append(header, newheader);
2629 if (*header == NULL)
2631 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2632 return JB_ERR_MEMORY;
2635 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2637 days = rtime / (3600 * 24);
2638 hours = rtime / 3600 % 24;
2639 minutes = rtime / 60 % 60;
2640 seconds = rtime % 60;
2642 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2643 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2644 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2649 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2658 /*********************************************************************
2660 * Function : client_accept_encoding
2662 * Description : Rewrite the client's Accept-Encoding header so that
2663 * if doesn't allow compression, if the action applies.
2664 * Note: For HTTP/1.0 the absence of the header is enough.
2667 * 1 : csp = Current client state (buffers, headers, etc...)
2668 * 2 : header = On input, pointer to header to modify.
2669 * On output, pointer to the modified header, or NULL
2670 * to remove the header. This function frees the
2671 * original string if necessary.
2673 * Returns : JB_ERR_OK on success, or
2674 * JB_ERR_MEMORY on out-of-memory error.
2676 *********************************************************************/
2677 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2679 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2681 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2685 /* Temporarily disable the correct behaviour to
2686 * work around a PHP bug.
2688 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2690 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2691 * if (*header == NULL)
2693 * return JB_ERR_MEMORY;
2704 /*********************************************************************
2706 * Function : client_te
2708 * Description : Rewrite the client's TE header so that
2709 * if doesn't allow compression, if the action applies.
2712 * 1 : csp = Current client state (buffers, headers, etc...)
2713 * 2 : header = On input, pointer to header to modify.
2714 * On output, pointer to the modified header, or NULL
2715 * to remove the header. This function frees the
2716 * original string if necessary.
2718 * Returns : JB_ERR_OK on success, or
2719 * JB_ERR_MEMORY on out-of-memory error.
2721 *********************************************************************/
2722 static jb_err client_te(struct client_state *csp, char **header)
2724 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2727 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2734 /*********************************************************************
2736 * Function : client_referrer
2738 * Description : Handle the "referer" config setting properly.
2739 * Called from `sed'.
2742 * 1 : csp = Current client state (buffers, headers, etc...)
2743 * 2 : header = On input, pointer to header to modify.
2744 * On output, pointer to the modified header, or NULL
2745 * to remove the header. This function frees the
2746 * original string if necessary.
2748 * Returns : JB_ERR_OK on success, or
2749 * JB_ERR_MEMORY on out-of-memory error.
2751 *********************************************************************/
2752 static jb_err client_referrer(struct client_state *csp, char **header)
2754 const char *parameter;
2755 /* booleans for parameters we have to check multiple times */
2756 int parameter_conditional_block;
2757 int parameter_conditional_forge;
2759 #ifdef FEATURE_FORCE_LOAD
2761 * Since the referrer can include the prefix even
2762 * if the request itself is non-forced, we must
2763 * clean it unconditionally.
2765 * XXX: strclean is too broad
2767 strclean(*header, FORCE_PREFIX);
2768 #endif /* def FEATURE_FORCE_LOAD */
2770 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2772 /* Nothing left to do */
2776 parameter = csp->action->string[ACTION_STRING_REFERER];
2777 assert(parameter != NULL);
2778 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2779 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2781 if (!parameter_conditional_block && !parameter_conditional_forge)
2784 * As conditional-block and conditional-forge are the only
2785 * parameters that rely on the original referrer, we can
2786 * remove it now for all the others.
2791 if (0 == strcmpic(parameter, "block"))
2793 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2796 else if (parameter_conditional_block || parameter_conditional_forge)
2798 return handle_conditional_hide_referrer_parameter(header,
2799 csp->http->hostport, parameter_conditional_block);
2801 else if (0 == strcmpic(parameter, "forge"))
2803 return create_forged_referrer(header, csp->http->hostport);
2807 /* interpret parameter as user-supplied referer to fake */
2808 return create_fake_referrer(header, parameter);
2813 /*********************************************************************
2815 * Function : client_accept_language
2817 * Description : Handle the "Accept-Language" config setting properly.
2818 * Called from `sed'.
2821 * 1 : csp = Current client state (buffers, headers, etc...)
2822 * 2 : header = On input, pointer to header to modify.
2823 * On output, pointer to the modified header, or NULL
2824 * to remove the header. This function frees the
2825 * original string if necessary.
2827 * Returns : JB_ERR_OK on success, or
2828 * JB_ERR_MEMORY on out-of-memory error.
2830 *********************************************************************/
2831 static jb_err client_accept_language(struct client_state *csp, char **header)
2836 * Are we messing with the Accept-Language?
2838 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2840 /*I don't think so*/
2844 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2846 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2849 * Blocking Accept-Language header
2851 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2858 * Replacing Accept-Language header
2861 *header = strdup("Accept-Language: ");
2862 string_append(header, newval);
2864 if (*header == NULL)
2866 log_error(LOG_LEVEL_ERROR,
2867 "Insufficent memory. Accept-Language header crunched without replacement.");
2871 log_error(LOG_LEVEL_HEADER,
2872 "Accept-Language header crunched and replaced with: %s", *header);
2875 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2879 /*********************************************************************
2881 * Function : crunch_client_header
2883 * Description : Crunch client header if it matches a string supplied by the
2884 * user. Called from `sed'.
2887 * 1 : csp = Current client state (buffers, headers, etc...)
2888 * 2 : header = On input, pointer to header to modify.
2889 * On output, pointer to the modified header, or NULL
2890 * to remove the header. This function frees the
2891 * original string if necessary.
2893 * Returns : JB_ERR_OK on success and always succeeds
2895 *********************************************************************/
2896 static jb_err crunch_client_header(struct client_state *csp, char **header)
2898 const char *crunch_pattern;
2900 /* Do we feel like crunching? */
2901 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2903 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2905 /* Is the current header the lucky one? */
2906 if (strstr(*header, crunch_pattern))
2908 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2916 /*********************************************************************
2918 * Function : client_uagent
2920 * Description : Handle the "user-agent" config setting properly
2921 * and remember its original value to enable browser
2922 * bug workarounds. Called from `sed'.
2925 * 1 : csp = Current client state (buffers, headers, etc...)
2926 * 2 : header = On input, pointer to header to modify.
2927 * On output, pointer to the modified header, or NULL
2928 * to remove the header. This function frees the
2929 * original string if necessary.
2931 * Returns : JB_ERR_OK on success, or
2932 * JB_ERR_MEMORY on out-of-memory error.
2934 *********************************************************************/
2935 static jb_err client_uagent(struct client_state *csp, char **header)
2939 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2944 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2951 *header = strdup("User-Agent: ");
2952 string_append(header, newval);
2954 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2956 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2960 /*********************************************************************
2962 * Function : client_ua
2964 * Description : Handle "ua-" headers properly. Called from `sed'.
2967 * 1 : csp = Current client state (buffers, headers, etc...)
2968 * 2 : header = On input, pointer to header to modify.
2969 * On output, pointer to the modified header, or NULL
2970 * to remove the header. This function frees the
2971 * original string if necessary.
2973 * Returns : JB_ERR_OK on success, or
2974 * JB_ERR_MEMORY on out-of-memory error.
2976 *********************************************************************/
2977 static jb_err client_ua(struct client_state *csp, char **header)
2979 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2981 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2989 /*********************************************************************
2991 * Function : client_from
2993 * Description : Handle the "from" config setting properly.
2994 * Called from `sed'.
2997 * 1 : csp = Current client state (buffers, headers, etc...)
2998 * 2 : header = On input, pointer to header to modify.
2999 * On output, pointer to the modified header, or NULL
3000 * to remove the header. This function frees the
3001 * original string if necessary.
3003 * Returns : JB_ERR_OK on success, or
3004 * JB_ERR_MEMORY on out-of-memory error.
3006 *********************************************************************/
3007 static jb_err client_from(struct client_state *csp, char **header)
3011 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3018 newval = csp->action->string[ACTION_STRING_FROM];
3021 * Are we blocking the e-mail address?
3023 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3025 log_error(LOG_LEVEL_HEADER, "crunched From!");
3029 log_error(LOG_LEVEL_HEADER, " modified");
3031 *header = strdup("From: ");
3032 string_append(header, newval);
3034 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3038 /*********************************************************************
3040 * Function : client_send_cookie
3042 * Description : Crunches the "cookie" header if necessary.
3043 * Called from `sed'.
3045 * XXX: Stupid name, doesn't send squat.
3048 * 1 : csp = Current client state (buffers, headers, etc...)
3049 * 2 : header = On input, pointer to header to modify.
3050 * On output, pointer to the modified header, or NULL
3051 * to remove the header. This function frees the
3052 * original string if necessary.
3054 * Returns : JB_ERR_OK on success, or
3055 * JB_ERR_MEMORY on out-of-memory error.
3057 *********************************************************************/
3058 static jb_err client_send_cookie(struct client_state *csp, char **header)
3060 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3062 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3070 /*********************************************************************
3072 * Function : client_x_forwarded
3074 * Description : Handle the "x-forwarded-for" config setting properly,
3075 * also used in the add_client_headers list. Called from `sed'.
3078 * 1 : csp = Current client state (buffers, headers, etc...)
3079 * 2 : header = On input, pointer to header to modify.
3080 * On output, pointer to the modified header, or NULL
3081 * to remove the header. This function frees the
3082 * original string if necessary.
3084 * Returns : JB_ERR_OK on success, or
3085 * JB_ERR_MEMORY on out-of-memory error.
3087 *********************************************************************/
3088 jb_err client_x_forwarded(struct client_state *csp, char **header)
3090 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3093 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3100 /*********************************************************************
3102 * Function : client_max_forwards
3104 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3105 * from the value of the Max-Forwards header field.
3108 * 1 : csp = Current client state (buffers, headers, etc...)
3109 * 2 : header = On input, pointer to header to modify.
3110 * On output, pointer to the modified header, or NULL
3111 * to remove the header. This function frees the
3112 * original string if necessary.
3114 * Returns : JB_ERR_OK on success, or
3115 * JB_ERR_MEMORY on out-of-memory error.
3117 *********************************************************************/
3118 static jb_err client_max_forwards(struct client_state *csp, char **header)
3122 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3123 (0 == strcmpic(csp->http->gpc, "options")))
3125 assert(*(*header+12) == ':');
3126 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3128 if (max_forwards > 0)
3130 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3131 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3132 csp->http->gpc, max_forwards);
3134 else if (max_forwards < 0)
3136 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3142 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3151 /*********************************************************************
3153 * Function : client_host
3155 * Description : If the request URI did not contain host and
3156 * port information, parse and evaluate the Host
3159 * Also, kill ill-formed HOST: headers as sent by
3160 * Apple's iTunes software when used with a proxy.
3163 * 1 : csp = Current client state (buffers, headers, etc...)
3164 * 2 : header = On input, pointer to header to modify.
3165 * On output, pointer to the modified header, or NULL
3166 * to remove the header. This function frees the
3167 * original string if necessary.
3169 * Returns : JB_ERR_OK on success, or
3170 * JB_ERR_MEMORY on out-of-memory error.
3172 *********************************************************************/
3173 static jb_err client_host(struct client_state *csp, char **header)
3178 * If the header field name is all upper-case, chances are that it's
3179 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3180 * not a problem -- they are regenerated later.
3182 if ((*header)[1] == 'O')
3184 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3189 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3190 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3193 if (NULL == (p = strdup((*header)+6)))
3195 return JB_ERR_MEMORY;
3198 if (NULL == (q = strdup(p)))
3201 return JB_ERR_MEMORY;
3204 freez(csp->http->hostport);
3205 csp->http->hostport = p;
3206 freez(csp->http->host);
3207 csp->http->host = q;
3208 q = strchr(csp->http->host, ':');
3211 /* Terminate hostname and evaluate port string */
3213 csp->http->port = atoi(q);
3217 csp->http->port = csp->http->ssl ? 443 : 80;
3220 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3221 csp->http->hostport, csp->http->host, csp->http->port);
3224 /* Signal client_host_adder() to return right away */
3225 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3231 /*********************************************************************
3233 * Function : client_if_modified_since
3235 * Description : Remove or modify the If-Modified-Since header.
3238 * 1 : csp = Current client state (buffers, headers, etc...)
3239 * 2 : header = On input, pointer to header to modify.
3240 * On output, pointer to the modified header, or NULL
3241 * to remove the header. This function frees the
3242 * original string if necessary.
3244 * Returns : JB_ERR_OK on success, or
3245 * JB_ERR_MEMORY on out-of-memory error.
3247 *********************************************************************/
3248 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3251 #ifdef HAVE_GMTIME_R
3254 struct tm *timeptr = NULL;
3258 long int hours, minutes, seconds;
3262 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3265 * The client got an error message because of a temporary problem,
3266 * the problem is gone and the client now tries to revalidate our
3267 * error message on the real server. The revalidation would always
3268 * end with the transmission of the whole document and there is
3269 * no need to expose the bogus If-Modified-Since header.
3271 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3274 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3276 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3278 if ((0 == strcmpic(newval, "block")))
3280 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3283 else /* add random value */
3285 const char *header_time = *header + sizeof("If-Modified-Since:");
3287 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3289 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3294 rtime = strtol(newval, &endptr, 0);
3297 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3298 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3305 rtime = pick_from_range(rtime);
3309 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3312 tm += rtime * (negative ? -1 : 1);
3313 #ifdef HAVE_GMTIME_R
3314 timeptr = gmtime_r(&tm, &gmt);
3315 #elif FEATURE_PTHREAD
3316 pthread_mutex_lock(&gmtime_mutex);
3317 timeptr = gmtime(&tm);
3318 pthread_mutex_unlock(&gmtime_mutex);
3320 timeptr = gmtime(&tm);
3322 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3325 *header = strdup("If-Modified-Since: ");
3326 string_append(header, newheader);
3328 if (*header == NULL)
3330 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3331 return JB_ERR_MEMORY;
3334 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3336 hours = rtime / 3600;
3337 minutes = rtime / 60 % 60;
3338 seconds = rtime % 60;
3340 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3341 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3342 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3352 /*********************************************************************
3354 * Function : client_if_none_match
3356 * Description : Remove the If-None-Match header.
3359 * 1 : csp = Current client state (buffers, headers, etc...)
3360 * 2 : header = On input, pointer to header to modify.
3361 * On output, pointer to the modified header, or NULL
3362 * to remove the header. This function frees the
3363 * original string if necessary.
3365 * Returns : JB_ERR_OK on success, or
3366 * JB_ERR_MEMORY on out-of-memory error.
3368 *********************************************************************/
3369 static jb_err client_if_none_match(struct client_state *csp, char **header)
3371 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3373 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3381 /*********************************************************************
3383 * Function : client_x_filter
3385 * Description : Disables filtering if the client set "X-Filter: No".
3386 * Called from `sed'.
3389 * 1 : csp = Current client state (buffers, headers, etc...)
3390 * 2 : header = On input, pointer to header to modify.
3391 * On output, pointer to the modified header, or NULL
3392 * to remove the header. This function frees the
3393 * original string if necessary.
3395 * Returns : JB_ERR_OK on success
3397 *********************************************************************/
3398 jb_err client_x_filter(struct client_state *csp, char **header)
3400 if ( 0 == strcmpic(*header, "X-Filter: No"))
3402 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3404 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3408 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3410 log_error(LOG_LEVEL_HEADER,
3411 "force-text-mode overruled the client's request to fetch without filtering!");
3415 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3416 csp->flags |= CSP_FLAG_NO_FILTERING;
3417 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3419 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3427 /*********************************************************************
3429 * Function : client_range
3431 * Description : Removes Range and If-Range headers if content
3432 * filtering is enabled. If the client's version of
3433 * the document has been altered by Privoxy, the server
3434 * could interpret the range differently than the client
3435 * intended in which case the user could end up with
3436 * corrupted content.
3439 * 1 : csp = Current client state (buffers, headers, etc...)
3440 * 2 : header = On input, pointer to header to modify.
3441 * On output, pointer to the modified header, or NULL
3442 * to remove the header. This function frees the
3443 * original string if necessary.
3445 * Returns : JB_ERR_OK
3447 *********************************************************************/
3448 static jb_err client_range(struct client_state *csp, char **header)
3450 if (content_filters_enabled(csp))
3452 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3453 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3460 /* the following functions add headers directly to the header list */
3462 /*********************************************************************
3464 * Function : client_host_adder
3466 * Description : Adds the Host: header field if it is missing.
3467 * Called from `sed'.
3470 * 1 : csp = Current client state (buffers, headers, etc...)
3472 * Returns : JB_ERR_OK on success, or
3473 * JB_ERR_MEMORY on out-of-memory error.
3475 *********************************************************************/
3476 static jb_err client_host_adder(struct client_state *csp)
3481 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3483 /* Header already set by the client, nothing to do. */
3487 if ( !csp->http->hostport || !*(csp->http->hostport))
3489 /* XXX: When does this happen and why is it OK? */
3490 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3495 * remove 'user:pass@' from 'proto://user:pass@host'
3497 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3503 p = csp->http->hostport;
3506 /* XXX: Just add it, we already made sure that it will be unique */
3507 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3508 err = enlist_unique_header(csp->headers, "Host", p);
3514 /*********************************************************************
3516 * Function : client_cookie_adder
3518 * Description : Used in the add_client_headers list to add "wafers".
3519 * Called from `sed'.
3522 * 1 : csp = Current client state (buffers, headers, etc...)
3524 * Returns : JB_ERR_OK on success, or
3525 * JB_ERR_MEMORY on out-of-memory error.
3527 *********************************************************************/
3528 jb_err client_cookie_adder(struct client_state *csp)
3531 struct list_entry *wafer;
3532 struct list_entry *wafer_list;
3536 * If the user has not supplied any wafers, and the user has not
3537 * told us to suppress the vanilla wafer, then send the vanilla wafer.
3539 if ((0 != (csp->action->flags & ACTION_VANILLA_WAFER))
3540 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER]))
3542 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
3545 wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3547 if (NULL == wafer_list)
3553 tmp = strdup("Cookie: ");
3555 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3557 if (wafer != wafer_list)
3559 /* As this isn't the first wafer, we need a delimiter. */
3560 string_append(&tmp, "; ");
3562 string_join(&tmp, cookie_encode(wafer->str));
3567 return JB_ERR_MEMORY;
3570 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3571 err = enlist(csp->headers, tmp);
3578 /*********************************************************************
3580 * Function : client_accept_encoding_adder
3582 * Description : Add an Accept-Encoding header to the client's request
3583 * that disables compression if the action applies, and
3584 * the header is not already there. Called from `sed'.
3585 * Note: For HTTP/1.0, the absence of the header is enough.
3588 * 1 : csp = Current client state (buffers, headers, etc...)
3590 * Returns : JB_ERR_OK on success, or
3591 * JB_ERR_MEMORY on out-of-memory error.
3593 *********************************************************************/
3594 static jb_err client_accept_encoding_adder(struct client_state *csp)
3596 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3597 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3599 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3607 /*********************************************************************
3609 * Function : client_xtra_adder
3611 * Description : Used in the add_client_headers list. Called from `sed'.
3614 * 1 : csp = Current client state (buffers, headers, etc...)
3616 * Returns : JB_ERR_OK on success, or
3617 * JB_ERR_MEMORY on out-of-memory error.
3619 *********************************************************************/
3620 static jb_err client_xtra_adder(struct client_state *csp)
3622 struct list_entry *lst;
3625 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3626 lst ; lst = lst->next)
3628 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3629 err = enlist(csp->headers, lst->str);
3641 /*********************************************************************
3643 * Function : connection_close_adder
3645 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3646 * support. Adds a "Connection: close" header to csp->headers
3647 * unless the header was already present. Called from `sed'.
3649 * FIXME: This whole function shouldn't be neccessary!
3652 * 1 : csp = Current client state (buffers, headers, etc...)
3654 * Returns : JB_ERR_OK on success, or
3655 * JB_ERR_MEMORY on out-of-memory error.
3657 *********************************************************************/
3658 static jb_err connection_close_adder(struct client_state *csp)
3660 const unsigned int flags = csp->flags;
3663 * Return right away if
3665 * - we're parsing server headers and the server header
3666 * "Connection: close" is already set, or if
3668 * - we're parsing client headers and the client header
3669 * "Connection: close" is already set.
3671 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3672 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3673 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3674 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3679 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3681 return enlist(csp->headers, "Connection: close");
3685 /*********************************************************************
3687 * Function : server_http
3689 * Description : - Save the HTTP Status into csp->http->status
3690 * - Set CT_TABOO to prevent filtering if the answer
3691 * is a partial range (HTTP status 206)
3692 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3696 * 1 : csp = Current client state (buffers, headers, etc...)
3697 * 2 : header = On input, pointer to header to modify.
3698 * On output, pointer to the modified header, or NULL
3699 * to remove the header. This function frees the
3700 * original string if necessary.
3702 * Returns : JB_ERR_OK on success, or
3703 * JB_ERR_MEMORY on out-of-memory error.
3705 *********************************************************************/
3706 static jb_err server_http(struct client_state *csp, char **header)
3708 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3709 if (csp->http->status == 206)
3711 csp->content_type = CT_TABOO;
3714 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3716 /* XXX: Should we do a real validity check here? */
3717 if (strlen(*header) > 8)
3720 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3725 * XXX: Should we block the request or
3726 * enlist a valid status code line here?
3728 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3729 "Downgrading to HTTP/1.0 impossible.");
3737 /*********************************************************************
3739 * Function : server_set_cookie
3741 * Description : Handle the server "cookie" header properly.
3742 * Log cookie to the jar file. Then "crunch",
3743 * accept or rewrite it to a session cookie.
3744 * Called from `sed'.
3746 * TODO: Allow the user to specify a new expiration
3747 * time to cause the cookie to expire even before the
3748 * browser is closed.
3751 * 1 : csp = Current client state (buffers, headers, etc...)
3752 * 2 : header = On input, pointer to header to modify.
3753 * On output, pointer to the modified header, or NULL
3754 * to remove the header. This function frees the
3755 * original string if necessary.
3757 * Returns : JB_ERR_OK on success, or
3758 * JB_ERR_MEMORY on out-of-memory error.
3760 *********************************************************************/
3761 static jb_err server_set_cookie(struct client_state *csp, char **header)
3768 #ifdef FEATURE_COOKIE_JAR
3769 if (csp->config->jar)
3772 * Write timestamp into outbuf.
3774 * Complex because not all OSs have tm_gmtoff or
3775 * the %z field in strftime()
3777 char tempbuf[ BUFFER_SIZE ];
3779 #ifdef HAVE_LOCALTIME_R
3780 tm_now = *localtime_r(&now, &tm_now);
3781 #elif FEATURE_PTHREAD
3782 pthread_mutex_lock(&localtime_mutex);
3783 tm_now = *localtime (&now);
3784 pthread_mutex_unlock(&localtime_mutex);
3786 tm_now = *localtime (&now);
3788 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3790 /* strlen("set-cookie: ") = 12 */
3791 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3793 #endif /* def FEATURE_COOKIE_JAR */
3795 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3797 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3800 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3802 /* Flag whether or not to log a message */
3805 /* A variable to store the tag we're working on */
3808 /* Skip "Set-Cookie:" (11 characters) in header */
3809 cur_tag = *header + 11;
3811 /* skip whitespace between "Set-Cookie:" and value */
3812 while (*cur_tag && ijb_isspace(*cur_tag))
3817 /* Loop through each tag in the cookie */
3821 char *next_tag = strchr(cur_tag, ';');
3822 if (next_tag != NULL)
3824 /* Skip the ';' character itself */
3827 /* skip whitespace ";" and start of tag */
3828 while (*next_tag && ijb_isspace(*next_tag))
3835 /* "Next tag" is the end of the string */
3836 next_tag = cur_tag + strlen(cur_tag);
3840 * Check the expiration date to see
3841 * if the cookie is still valid, if yes,
3842 * rewrite it to a session cookie.
3844 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3846 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3848 /* Did we detect the date properly? */
3849 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3852 * Nope, treat it as if it was still valid.
3854 * XXX: Should we remove the whole cookie instead?
3856 log_error(LOG_LEVEL_ERROR,
3857 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3858 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3864 * Yes. Check if the cookie is still valid.
3866 * If the cookie is already expired it's probably
3867 * a delete cookie and even if it isn't, the browser
3868 * will discard it anyway.
3872 * XXX: timegm() isn't available on some AmigaOS
3873 * versions and our replacement doesn't work.
3875 * Our options are to either:
3877 * - disable session-cookies-only completely if timegm
3880 * - to simply remove all expired tags, like it has
3881 * been done until Privoxy 3.0.6 and to live with
3882 * the consequence that it can cause login/logout
3883 * problems on servers that don't validate their
3884 * input properly, or
3886 * - to replace it with mktime in which
3887 * case there is a slight chance of valid cookies
3888 * passing as already expired.
3890 * This is the way it's currently done and it's not
3891 * as bad as it sounds. If the missing GMT offset is
3892 * enough to change the result of the expiration check
3893 * the cookie will be only valid for a few hours
3894 * anyway, which in many cases will be shorter
3895 * than a browser session.
3897 if (cookie_time - now < 0)
3899 log_error(LOG_LEVEL_HEADER,
3900 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3901 /* Just in case some clown sets more then one expiration date */
3907 * Still valid, delete expiration date by copying
3908 * the rest of the string over it.
3910 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3911 * since the behaviour of strcpy is undefined for overlapping
3914 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3916 /* That changed the header, need to issue a log message */
3920 * Note that the next tag has now been moved to *cur_tag,
3921 * so we do not need to update the cur_tag pointer.
3929 /* Move on to next cookie tag */
3936 assert(NULL != *header);
3937 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3946 #ifdef FEATURE_FORCE_LOAD
3947 /*********************************************************************
3949 * Function : strclean
3951 * Description : In-Situ-Eliminate all occurances of substring in
3955 * 1 : string = string to clean
3956 * 2 : substring = substring to eliminate
3958 * Returns : Number of eliminations
3960 *********************************************************************/
3961 int strclean(const char *string, const char *substring)
3967 len = strlen(substring);
3969 while((pos = strstr(string, substring)) != NULL)
3976 while (*p++ != '\0');
3983 #endif /* def FEATURE_FORCE_LOAD */
3986 /*********************************************************************
3988 * Function : parse_header_time
3990 * Description : Parses time formats used in HTTP header strings
3991 * to get the numerical respresentation.
3994 * 1 : header_time = HTTP header time as string.
3995 * 2 : result = storage for header_time in seconds
3997 * Returns : JB_ERR_OK if the time format was recognized, or
3998 * JB_ERR_PARSE otherwise.
4000 *********************************************************************/
4001 static jb_err parse_header_time(const char *header_time, time_t *result)
4006 * Zero out gmt to prevent time zone offsets.
4008 * While this is only necessary on some platforms
4009 * (mingw32 for example), I don't know how to
4010 * detect these automatically and doing it everywhere
4013 memset(&gmt, 0, sizeof(gmt));
4015 /* Tue, 02 Jun 2037 20:00:00 */
4016 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4017 /* Tue, 02-Jun-2037 20:00:00 */
4018 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4019 /* Tue, 02-Jun-37 20:00:00 */
4020 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4021 /* Tuesday, 02-Jun-2037 20:00:00 */
4022 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4023 /* Tuesday Jun 02 20:00:00 2037 */
4024 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4026 return JB_ERR_PARSE;
4029 *result = timegm(&gmt);
4036 /*********************************************************************
4038 * Function : get_destination_from_headers
4040 * Description : Parse the "Host:" header to get the request's destination.
4041 * Only needed if the client's request was forcefully
4042 * redirected into Privoxy.
4044 * Code mainly copied from client_host() which is currently
4045 * run too late for this purpose.
4048 * 1 : headers = List of headers (one of them hopefully being
4049 * the "Host:" header)
4050 * 2 : http = storage for the result (host, port and hostport).
4052 * Returns : JB_ERR_MEMORY in case of memory problems,
4053 * JB_ERR_PARSE if the host header couldn't be found,
4054 * JB_ERR_OK otherwise.
4056 *********************************************************************/
4057 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4063 host = get_header_value(headers, "Host:");
4067 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4068 return JB_ERR_PARSE;
4071 if (NULL == (p = strdup((host))))
4073 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4074 return JB_ERR_MEMORY;
4077 if (NULL == (q = strdup(p)))
4080 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4081 return JB_ERR_MEMORY;
4084 freez(http->hostport);
4088 q = strchr(http->host, ':');
4091 /* Terminate hostname and evaluate port string */
4093 http->port = atoi(q);
4097 http->port = http->ssl ? 443 : 80;
4100 /* Rebuild request URL */
4102 http->url = strdup(http->ssl ? "https://" : "http://");
4103 string_append(&http->url, http->hostport);
4104 string_append(&http->url, http->path);
4105 if (http->url == NULL)
4107 return JB_ERR_MEMORY;
4110 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4118 /*********************************************************************
4120 * Function : create_forged_referrer
4122 * Description : Helper for client_referrer to forge a referer as
4123 * 'http://[hostname:port/' to fool stupid
4124 * checks for in-site links
4127 * 1 : header = Pointer to header pointer
4128 * 2 : hostport = Host and optionally port as string
4130 * Returns : JB_ERR_OK in case of success, or
4131 * JB_ERR_MEMORY in case of memory problems.
4133 *********************************************************************/
4134 static jb_err create_forged_referrer(char **header, const char *hostport)
4136 assert(NULL == *header);
4138 *header = strdup("Referer: http://");
4139 string_append(header, hostport);
4140 string_append(header, "/");
4142 if (NULL == *header)
4144 return JB_ERR_MEMORY;
4147 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4154 /*********************************************************************
4156 * Function : create_fake_referrer
4158 * Description : Helper for client_referrer to create a fake referrer
4159 * based on a string supplied by the user.
4162 * 1 : header = Pointer to header pointer
4163 * 2 : hosthost = Referrer to fake
4165 * Returns : JB_ERR_OK in case of success, or
4166 * JB_ERR_MEMORY in case of memory problems.
4168 *********************************************************************/
4169 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4171 assert(NULL == *header);
4173 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4175 log_error(LOG_LEVEL_HEADER,
4176 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4178 *header = strdup("Referer: ");
4179 string_append(header, fake_referrer);
4181 if (NULL == *header)
4183 return JB_ERR_MEMORY;
4186 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4193 /*********************************************************************
4195 * Function : handle_conditional_hide_referrer_parameter
4197 * Description : Helper for client_referrer to crunch or forge
4198 * the referrer header if the host has changed.
4201 * 1 : header = Pointer to header pointer
4202 * 2 : host = The target host (may include the port)
4203 * 3 : parameter_conditional_block = Boolean to signal
4204 * if we're in conditional-block mode. If not set,
4205 * we're in conditional-forge mode.
4207 * Returns : JB_ERR_OK in case of success, or
4208 * JB_ERR_MEMORY in case of memory problems.
4210 *********************************************************************/
4211 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4212 const char *host, const int parameter_conditional_block)
4214 char *referer = strdup(*header);
4215 const size_t hostlenght = strlen(host);
4217 if (NULL == referer)
4220 return JB_ERR_MEMORY;
4223 /* referer begins with 'Referer: http[s]://' */
4224 if (hostlenght < (strlen(referer)-17))
4227 * Shorten referer to make sure the referer is blocked
4228 * if www.example.org/www.example.com-shall-see-the-referer/
4229 * links to www.example.com/
4231 referer[hostlenght+17] = '\0';
4233 if (NULL == strstr(referer, host))
4235 /* Host has changed */
4236 if (parameter_conditional_block)
4238 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4245 return create_forged_referrer(header, host);