1 const char parsers_rcs[] = "$Id: parsers.c,v 1.111 2007/10/04 18:07:00 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.111 2007/10/04 18:07:00 fabiankeil
48 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
49 * client_cookie_adder() to make sure send-vanilla-wafer can be
50 * controlled through tags (and thus regression-tested).
52 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
53 * - Remove "scanning headers for" log message again.
54 * - Some more whitespace fixes.
56 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
57 * Refactor client_referrer() and add conditional-forge parameter.
59 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
60 * A bunch of whitespace fixes, pointy hat to me.
62 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
63 * Fix possible memory corruption in server_http, make sure it's not
64 * executed for ordinary server headers and mark some problems for later.
66 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
67 * Let content-type-overwrite{} honour force-text-mode again.
69 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
70 * - Add prototpyes for the header parsers and make them static.
71 * - Comment out client_accept_encoding_adder() which isn't used right now.
73 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
74 * Move the ACTION_FORCE_TEXT_MODE check out of
75 * server_content_type(). Signal other functions
76 * whether or not a content type has been declared.
77 * Part of the fix for BR#1750917.
79 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
80 * Change sed() to return a jb_err in preparation for forward-override{}.
82 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
83 * Adjust "X-Filter: No" to disable dedicated header filters.
85 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
86 * Streamline client_cookie_adder().
88 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
89 * Make sure filters with dynamic jobs actually use them.
91 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
92 * - Introduce dynamic pcrs jobs that can resolve variables.
93 * - Remove unnecessary update_action_bits_for_all_tags() call.
95 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
96 * - Make tagging based on tags set by earlier taggers
97 * of the same kind possible.
98 * - Log whether or not new tags cause action bits updates
99 * (in which case a matching tag-pattern section exists).
100 * - Log if the user tries to set a tag that is already set.
102 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
103 * Introduce tags as alternative way to specify which
104 * actions apply to a request. At the moment tags can be
105 * created based on client and server headers.
107 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
108 * Log a warning if the content is compressed, filtering is
109 * enabled and Privoxy was compiled without zlib support.
112 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
113 * - Fix warnings when compiled with glibc.
114 * - Don't use crumble() for cookie crunching.
115 * - Move cookie time parsing into parse_header_time().
116 * - Let parse_header_time() return a jb_err code
117 * instead of a pointer that can only be used to
118 * check for NULL anyway.
120 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
121 * - Add better protection against malicious gzip headers.
122 * - Stop logging the first hundred bytes of decompressed content.
123 * It looks like it's working and there is always debug 16.
124 * - Log the content size after decompression in decompress_iob()
125 * instead of pcrs_filter_response().
127 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
128 * - Use dedicated header filter actions instead of abusing "filter".
129 * Replace "filter-client-headers" and "filter-client-headers"
130 * with "server-header-filter" and "client-header-filter".
131 * - Remove filter_client_header() and filter_client_header(),
132 * filter_header() now checks the shiny new
133 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
135 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
136 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
137 * - Handle "Cookie:" and "Connection:" headers a bit smarter
138 * (don't crunch them just to recreate them later on).
139 * - Add another non-standard time format for the cookie
140 * expiration date detection.
141 * - Fix a valgrind warning.
143 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
144 * Improve cookie expiration date detection.
146 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
147 * Don't run server_content_length() the first time
148 * sed() parses server headers; only adjust the
149 * Content-Length header if the page was modified.
151 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
152 * Fix log messages regarding the cookie time format
153 * (cookie and request URL were mixed up).
155 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
156 * - Let decompress_iob()
157 * - not corrupt the content if decompression fails
158 * early. (the first byte(s) were lost).
159 * - use pointer arithmetics with defined outcome for
161 * - Use a different kludge to remember a failed decompression.
163 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
164 * Search for Max-Forwards headers case-insensitive,
165 * don't generate the "501 unsupported" message for invalid
166 * Max-Forwards values and don't increase negative ones.
168 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
169 * - Let server_set_cookie() check the expiration date
170 * of cookies and don't touch the ones that are already
171 * expired. Fixes problems with low quality web applications
172 * as described in BR 932612.
174 * - Adjust comment in client_max_forwards to reality;
175 * remove invalid Max-Forwards headers.
177 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
178 * Stop filter_header() from unintentionally removing
179 * empty header lines that were enlisted by the continue
182 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
183 * - Repeat the request URL before logging any headers.
184 * Makes reading the log easier in case of simultaneous requests.
185 * - If there are more than one Content-Type headers in one request,
186 * use the first one and remove the others.
187 * - Remove "newval" variable in server_content_type().
188 * It's only used once.
190 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
191 * Correct a cast, check inflateEnd() exit code
192 * to see if we have to, replace sprintf calls
195 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
196 * Integrate a modified version of Wil Mahan's
197 * zlib patch (PR #895531).
199 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
200 * Skip empty filter files in filter_header()
201 * but don't ignore the ones that come afterwards.
202 * Fixes BR 1619208, this time for real.
204 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
205 * Reverted parts of my last commit
206 * to keep error handling working.
208 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
209 * Fixed gcc43 conversion warnings.
211 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
212 * Bringing back the "useless" localtime() call
213 * I removed in revision 1.67. On some platforms
214 * it's necessary to prevent time zone offsets.
216 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
217 * Rebuild request URL in get_destination_from_headers()
218 * to make sure redirect{pcrs command} works as expected
219 * for intercepted requests.
221 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
222 * Added get_destination_from_headers().
224 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
225 * Make pthread mutex locking more generic. Instead of
226 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
227 * and use mutex locking unless there is an _r function
228 * available. Better safe than sorry.
230 * Fixes "./configure --disable-pthread" and should result
231 * in less threading-related problems on pthread-using platforms,
232 * but it still doesn't fix BR#1122404.
234 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
235 * The special header "X-Filter: No" now disables
236 * header filtering as well.
238 * Revision 1.73 2006/09/23 13:26:38 roro
239 * Replace TABs by spaces in source code.
241 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
242 * Don't print a log message every time filter_headers is
243 * entered or left. It only creates noise without any real
246 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
247 * Fix +hide-if-modified-since{-n}.
249 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
250 * Have hide-if-modified-since interpret the random
251 * range value as minutes instead of hours. Allows
252 * more fine-grained configuration.
254 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
255 * Always have parse_header_time return a pointer
256 * that actual makes sense, even though we currently
257 * only need it to detect problems.
259 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
260 * Added config option enable-remote-http-toggle
261 * to specify if Privoxy should recognize special
262 * headers (currently only X-Filter) to change its
263 * behaviour. Disabled by default.
265 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
266 * After filtering de-chunked instances, remove
267 * "Transfer-Encoding" header entirely instead of changing
268 * it to "Transfer-Encoding: identity", which is invalid.
269 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
271 * Don't use localtime in parse_header_time. An empty time struct
272 * is good enough, it gets overwritten by strptime anyway.
274 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
275 * Use gmtime_r if available, fallback to gmtime with mutex
276 * protection for MacOSX and use vanilla gmtime for the rest.
278 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
279 * Changed client_referrer to use the right type (size_t) for
280 * hostlenght and to shorten the temporary referrer string with
281 * '\0' instead of adding a useless line break.
283 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
284 * - Back to timegm() using GnuPG's replacement if necessary.
285 * Using mktime() and localtime() could add a on hour offset if
286 * the randomize factor was big enough to lead to a summer/wintertime
289 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
291 * - Moved randomization code into pick_from_range().
293 * - Changed parse_header_time definition.
294 * time_t isn't guaranteed to be signed and
295 * if it isn't, -1 isn't available as error code.
296 * Changed some variable types in client_if_modified_since()
297 * because of the same reason.
299 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
300 * OS/2 compilation compatibility fixups
302 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
303 * Changed include from strptime.c to strptime.h
305 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
306 * Split filter-headers{} into filter-client-headers{}
307 * and filter-server-headers{}.
308 * Added parse_header_time() to share some code.
309 * Replaced timegm() with mktime().
311 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
312 * Windows service integration
314 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
315 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
317 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
318 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
319 * with what was really the latest development (the v_3_0_branch branch)
321 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
322 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
324 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
325 * Add the ability to check jpeg images for invalid
326 * lengths of comment blocks. Defensive strategy
327 * against the exploit:
328 * Microsoft Security Bulletin MS04-028
329 * Buffer Overrun in JPEG Processing (GDI+) Could
330 * Allow Code Execution (833987)
331 * Enabled with +inspect-jpegs in actions files.
333 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
334 * Excluded text/plain objects from filtering. This fixes a
335 * couple of client-crashing, download corruption and
336 * Privoxy performance issues, whose root cause lies in
337 * web servers labelling content of unknown type as text/plain.
339 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
340 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
342 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
343 * Completing the previous change
345 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
346 * Added temporary workaround for bug in PHP < 4.2.3
348 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
349 * 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.
351 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
352 * Fix typo: supressed -> suppressed
354 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
355 * Improved cookie logging
357 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
358 * Added basic support for OPTIONS and TRACE HTTP methods:
359 * - New parser function client_max_forwards which decrements
360 * the Max-Forwards HTTP header field of OPTIONS and TRACE
361 * requests by one before forwarding
362 * - New parser function client_host which extracts the host
363 * and port information from the HTTP header field if the
364 * request URI was not absolute
365 * - Don't crumble and re-add the Host: header, but only generate
366 * and append if missing
368 * Revision 1.56 2002/05/12 15:34:22 jongfoster
369 * Fixing typo in a comment
371 * Revision 1.55 2002/05/08 16:01:07 oes
372 * Optimized add_to_iob:
373 * - Use realloc instead of malloc(), memcpy(), free()
374 * - Expand to powers of two if possible, to get
375 * O(log n) reallocs instead of O(n).
376 * - Moved check for buffer limit here from chat
377 * - Report failure via returncode
379 * Revision 1.54 2002/04/02 15:03:16 oes
380 * Tiny code cosmetics
382 * Revision 1.53 2002/03/26 22:29:55 swa
383 * we have a new homepage!
385 * Revision 1.52 2002/03/24 13:25:43 swa
386 * name change related issues
388 * Revision 1.51 2002/03/13 00:27:05 jongfoster
391 * Revision 1.50 2002/03/12 01:45:35 oes
392 * More verbose logging
394 * Revision 1.49 2002/03/09 20:03:52 jongfoster
395 * - Making various functions return int rather than size_t.
396 * (Undoing a recent change). Since size_t is unsigned on
397 * Windows, functions like read_socket that return -1 on
398 * error cannot return a size_t.
400 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
401 * crashes, and also frequently caused JB to jump to 100%
402 * CPU and stay there. (Because it thought it had just
403 * read ((unsigned)-1) == 4Gb of data...)
405 * - The signature of write_socket has changed, it now simply
406 * returns success=0/failure=nonzero.
408 * - Trying to get rid of a few warnings --with-debug on
409 * Windows, I've introduced a new type "jb_socket". This is
410 * used for the socket file descriptors. On Windows, this
411 * is SOCKET (a typedef for unsigned). Everywhere else, it's
412 * an int. The error value can't be -1 any more, so it's
413 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
414 * Windows it maps to the #define INVALID_SOCKET.)
416 * - The signature of bind_port has changed.
418 * Revision 1.48 2002/03/07 03:46:53 oes
419 * Fixed compiler warnings etc
421 * Revision 1.47 2002/02/20 23:15:13 jongfoster
422 * Parsing functions now handle out-of-memory gracefully by returning
425 * Revision 1.46 2002/01/17 21:03:47 jongfoster
426 * Moving all our URL and URL pattern parsing code to urlmatch.c.
428 * Revision 1.45 2002/01/09 14:33:03 oes
429 * Added support for localtime_r.
431 * Revision 1.44 2001/12/14 01:22:54 steudten
432 * Remove 'user:pass@' from 'proto://user:pass@host' for the
433 * new added header 'Host: ..'. (See Req ID 491818)
435 * Revision 1.43 2001/11/23 00:26:38 jongfoster
436 * Fixing two really stupid errors in my previous commit
438 * Revision 1.42 2001/11/22 21:59:30 jongfoster
439 * Adding code to handle +no-cookies-keep
441 * Revision 1.41 2001/11/05 23:43:05 steudten
442 * Add time+date to log files.
444 * Revision 1.40 2001/10/26 20:13:09 jongfoster
445 * ctype.h is needed in Windows, too.
447 * Revision 1.39 2001/10/26 17:40:04 oes
448 * Introduced get_header_value()
449 * Removed http->user_agent, csp->referrer and csp->accept_types
450 * Removed client_accept()
452 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
453 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
454 * threads to call select() simultaneously. So, it's time to do a real, live,
455 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
456 * (native). Both versions will work, but using __OS2__ offers multi-threading.
458 * Revision 1.37 2001/10/23 21:36:02 jongfoster
459 * Documenting sed()'s error behaviou (doc change only)
461 * Revision 1.36 2001/10/13 12:51:51 joergs
462 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
463 * force-load), instead crumble Host: and add it (again) in client_host_adder
464 * (in case we get a HTTP/1.0 request without Host: header and forward it to
465 * a HTTP/1.1 server/proxy).
467 * Revision 1.35 2001/10/09 22:39:21 jongfoster
468 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
471 * Revision 1.34 2001/10/07 18:50:55 oes
472 * Added server_content_encoding, renamed server_transfer_encoding
474 * Revision 1.33 2001/10/07 18:04:49 oes
475 * Changed server_http11 to server_http and its pattern to "HTTP".
476 * Additional functionality: it now saves the HTTP status into
477 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
479 * Revision 1.32 2001/10/07 15:43:28 oes
480 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
481 * client_te and client_accept_encoding_adder, triggered by the new
482 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
483 * changed to allow only identity and chunked, and the TE header is
484 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
486 * parse_http_request no longer does anything than parsing. The rewriting
487 * of http->cmd and version mangling are gone. It now also recognizes
488 * the put and delete methods and saves the url in http->url. Removed
491 * renamed content_type and content_length to have the server_ prefix
493 * server_content_type now only works if csp->content_type != CT_TABOO
495 * added server_transfer_encoding, which
496 * - Sets CT_TABOO to prohibit filtering if encoding compresses
497 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
498 * - Change from "chunked" to "identity" if body was chunked
499 * but has been de-chunked for filtering.
501 * added server_content_md5 which crunches any Content-MD5 headers
502 * if the body was modified.
504 * made server_http11 conditional on +downgrade action
506 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
508 * Revision 1.31 2001/10/05 14:25:02 oes
509 * Crumble Keep-Alive from Server
511 * Revision 1.30 2001/09/29 12:56:03 joergs
512 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
514 * Revision 1.29 2001/09/24 21:09:24 jongfoster
515 * Fixing 2 memory leaks that Guy spotted, where the paramater to
516 * enlist() was not being free()d.
518 * Revision 1.28 2001/09/22 16:32:28 jongfoster
519 * Removing unused #includes.
521 * Revision 1.27 2001/09/20 15:45:25 steudten
523 * add casting from size_t to int for printf()
524 * remove local variable shadow s2
526 * Revision 1.26 2001/09/16 17:05:14 jongfoster
527 * Removing unused #include showarg.h
529 * Revision 1.25 2001/09/16 13:21:27 jongfoster
530 * Changes to use new list functions.
532 * Revision 1.24 2001/09/13 23:05:50 jongfoster
533 * Changing the string paramater to the header parsers a "const".
535 * Revision 1.23 2001/09/12 18:08:19 steudten
537 * In parse_http_request() header rewriting miss the host value, so
538 * from http://www.mydomain.com the result was just " / " not
539 * http://www.mydomain.com/ in case we forward.
541 * Revision 1.22 2001/09/10 10:58:53 oes
542 * Silenced compiler warnings
544 * Revision 1.21 2001/07/31 14:46:00 oes
545 * - Persistant connections now suppressed
546 * - sed() no longer appends empty header to csp->headers
548 * Revision 1.20 2001/07/30 22:08:36 jongfoster
549 * Tidying up #defines:
550 * - All feature #defines are now of the form FEATURE_xxx
551 * - Permanently turned off WIN_GUI_EDIT
552 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
554 * Revision 1.19 2001/07/25 17:21:54 oes
555 * client_uagent now saves copy of User-Agent: header value
557 * Revision 1.18 2001/07/13 14:02:46 oes
558 * - Included fix to repair broken HTTP requests that
559 * don't contain a path, not even '/'.
560 * - Removed all #ifdef PCRS
561 * - content_type now always inspected and classified as
562 * text, gif or other.
563 * - formatting / comments
565 * Revision 1.17 2001/06/29 21:45:41 oes
566 * Indentation, CRLF->LF, Tab-> Space
568 * Revision 1.16 2001/06/29 13:32:42 oes
570 * - Adapted free_http_request
571 * - Removed logentry from cancelled commit
573 * Revision 1.15 2001/06/03 19:12:38 oes
574 * deleted const struct interceptors
576 * Revision 1.14 2001/06/01 18:49:17 jongfoster
577 * Replaced "list_share" with "list" - the tiny memory gain was not
578 * worth the extra complexity.
580 * Revision 1.13 2001/05/31 21:30:33 jongfoster
581 * Removed list code - it's now in list.[ch]
582 * Renamed "permission" to "action", and changed many features
583 * to use the actions file rather than the global config.
585 * Revision 1.12 2001/05/31 17:33:13 oes
589 * Revision 1.11 2001/05/29 20:11:19 joergs
590 * '/ * inside comment' warning removed.
592 * Revision 1.10 2001/05/29 09:50:24 jongfoster
593 * Unified blocklist/imagelist/permissionslist.
594 * File format is still under discussion, but the internal changes
597 * Also modified interceptor behaviour:
598 * - We now intercept all URLs beginning with one of the following
599 * prefixes (and *only* these prefixes):
601 * * http://ijbswa.sf.net/config/
602 * * http://ijbswa.sourceforge.net/config/
603 * - New interceptors "home page" - go to http://i.j.b/ to see it.
604 * - Internal changes so that intercepted and fast redirect pages
605 * are not replaced with an image.
606 * - Interceptors now have the option to send a binary page direct
607 * to the client. (i.e. ijb-send-banner uses this)
608 * - Implemented show-url-info interceptor. (Which is why I needed
609 * the above interceptors changes - a typical URL is
610 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
611 * The previous mechanism would not have intercepted that, and
612 * if it had been intercepted then it then it would have replaced
615 * Revision 1.9 2001/05/28 17:26:33 jongfoster
616 * Fixing segfault if last header was crunched.
617 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
618 * can use the cross-platform sprintf() instead.)
620 * Revision 1.8 2001/05/27 22:17:04 oes
622 * - re_process_buffer no longer writes the modified buffer
623 * to the client, which was very ugly. It now returns the
624 * buffer, which it is then written by chat.
626 * - content_length now adjusts the Content-Length: header
627 * for modified documents rather than crunch()ing it.
628 * (Length info in csp->content_length, which is 0 for
629 * unmodified documents)
631 * - For this to work, sed() is called twice when filtering.
633 * Revision 1.7 2001/05/27 13:19:06 oes
634 * Patched Joergs solution for the content-length in.
636 * Revision 1.6 2001/05/26 13:39:32 jongfoster
637 * Only crunches Content-Length header if applying RE filtering.
638 * Without this fix, Microsoft Windows Update wouldn't work.
640 * Revision 1.5 2001/05/26 00:28:36 jongfoster
641 * Automatic reloading of config file.
642 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
643 * Most of the global variables have been moved to a new
644 * struct configuration_spec, accessed through csp->config->globalname
645 * Most of the globals remaining are used by the Win32 GUI.
647 * Revision 1.4 2001/05/22 18:46:04 oes
649 * - Enabled filtering banners by size rather than URL
650 * by adding patterns that replace all standard banner
651 * sizes with the "Junkbuster" gif to the re_filterfile
653 * - Enabled filtering WebBugs by providing a pattern
654 * which kills all 1x1 images
656 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
657 * which is selected by the (nonstandard and therefore
658 * capital) letter 'U' in the option string.
659 * It causes the quantifiers to be ungreedy by default.
660 * Appending a ? turns back to greedy (!).
662 * - Added a new interceptor ijb-send-banner, which
663 * sends back the "Junkbuster" gif. Without imagelist or
664 * MSIE detection support, or if tinygif = 1, or the
665 * URL isn't recognized as an imageurl, a lame HTML
666 * explanation is sent instead.
668 * - Added new feature, which permits blocking remote
669 * script redirects and firing back a local redirect
671 * The feature is conditionally compiled, i.e. it
672 * can be disabled with --disable-fast-redirects,
673 * plus it must be activated by a "fast-redirects"
674 * line in the config file, has its own log level
675 * and of course wants to be displayed by show-proxy-args
676 * Note: Boy, all the #ifdefs in 1001 locations and
677 * all the fumbling with configure.in and acconfig.h
678 * were *way* more work than the feature itself :-(
680 * - Because a generic redirect template was needed for
681 * this, tinygif = 3 now uses the same.
683 * - Moved GIFs, and other static HTTP response templates
688 * - Removed some >400 CRs again (Jon, you really worked
691 * Revision 1.3 2001/05/20 01:21:20 jongfoster
692 * Version 2.9.4 checkin.
693 * - Merged popupfile and cookiefile, and added control over PCRS
694 * filtering, in new "permissionsfile".
695 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
696 * file error you now get a message box (in the Win32 GUI) rather
697 * than the program exiting with no explanation.
698 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
700 * - Removed tabs from "config"
701 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
702 * - Bumped up version number.
704 * Revision 1.2 2001/05/17 23:02:36 oes
705 * - Made referrer option accept 'L' as a substitute for '§'
707 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
708 * Initial import of version 2.9.3 source tree
711 *********************************************************************/
718 #include <sys/types.h>
728 * Convince GNU's libc to provide a strptime prototype.
731 #endif /*__GLIBC__ */
738 #if !defined(_WIN32) && !defined(__OS2__)
744 #ifdef FEATURE_PTHREAD
746 /* jcc.h is for mutex semapores only */
747 #endif /* def FEATURE_PTHREAD */
753 #include "jbsockets.h"
754 #include "miscutil.h"
759 #ifndef HAVE_STRPTIME
760 #include "strptime.h"
763 const char parsers_h_rcs[] = PARSERS_H_VERSION;
765 /* Fix a problem with Solaris. There should be no effect on other
767 * Solaris's isspace() is a macro which uses its argument directly
768 * as an array index. Therefore we need to make sure that high-bit
769 * characters generate +ve values, and ideally we also want to make
770 * the argument match the declared parameter type of "int".
772 * Why did they write a character function that can't take a simple
773 * "char" argument? Doh!
775 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
776 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
778 static jb_err scan_headers(struct client_state *csp);
779 static jb_err header_tagger(struct client_state *csp, char *header);
780 static jb_err parse_header_time(const char *header_time, time_t *result);
782 static jb_err crumble (struct client_state *csp, char **header);
783 static jb_err connection (struct client_state *csp, char **header);
784 static jb_err filter_header (struct client_state *csp, char **header);
785 static jb_err client_referrer (struct client_state *csp, char **header);
786 static jb_err client_uagent (struct client_state *csp, char **header);
787 static jb_err client_ua (struct client_state *csp, char **header);
788 static jb_err client_from (struct client_state *csp, char **header);
789 static jb_err client_send_cookie (struct client_state *csp, char **header);
790 static jb_err client_x_forwarded (struct client_state *csp, char **header);
791 static jb_err client_accept_encoding (struct client_state *csp, char **header);
792 static jb_err client_te (struct client_state *csp, char **header);
793 static jb_err client_max_forwards (struct client_state *csp, char **header);
794 static jb_err client_host (struct client_state *csp, char **header);
795 static jb_err client_if_modified_since (struct client_state *csp, char **header);
796 static jb_err client_accept_language (struct client_state *csp, char **header);
797 static jb_err client_if_none_match (struct client_state *csp, char **header);
798 static jb_err crunch_client_header (struct client_state *csp, char **header);
799 static jb_err client_x_filter (struct client_state *csp, char **header);
800 static jb_err client_range (struct client_state *csp, char **header);
801 static jb_err server_set_cookie (struct client_state *csp, char **header);
802 static jb_err server_content_type (struct client_state *csp, char **header);
803 static jb_err server_content_length (struct client_state *csp, char **header);
804 static jb_err server_content_md5 (struct client_state *csp, char **header);
805 static jb_err server_content_encoding (struct client_state *csp, char **header);
806 static jb_err server_transfer_coding (struct client_state *csp, char **header);
807 static jb_err server_http (struct client_state *csp, char **header);
808 static jb_err crunch_server_header (struct client_state *csp, char **header);
809 static jb_err server_last_modified (struct client_state *csp, char **header);
810 static jb_err server_content_disposition(struct client_state *csp, char **header);
812 static jb_err client_host_adder (struct client_state *csp);
813 static jb_err client_cookie_adder (struct client_state *csp);
814 static jb_err client_xtra_adder (struct client_state *csp);
815 static jb_err client_x_forwarded_adder(struct client_state *csp);
816 static jb_err connection_close_adder (struct client_state *csp);
818 static jb_err create_forged_referrer(char **header, const char *hostport);
819 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
820 static jb_err handle_conditional_hide_referrer_parameter(char **header,
821 const char *host, const int parameter_conditional_block);
823 const struct parsers client_patterns[] = {
824 { "referer:", 8, client_referrer },
825 { "user-agent:", 11, client_uagent },
826 { "ua-", 3, client_ua },
827 { "from:", 5, client_from },
828 { "cookie:", 7, client_send_cookie },
829 { "x-forwarded-for:", 16, client_x_forwarded },
830 { "Accept-Encoding:", 16, client_accept_encoding },
831 { "TE:", 3, client_te },
832 { "Host:", 5, client_host },
833 { "if-modified-since:", 18, client_if_modified_since },
834 { "Keep-Alive:", 11, crumble },
835 { "connection:", 11, connection },
836 { "proxy-connection:", 17, crumble },
837 { "max-forwards:", 13, client_max_forwards },
838 { "Accept-Language:", 16, client_accept_language },
839 { "if-none-match:", 14, client_if_none_match },
840 { "Range:", 6, client_range },
841 { "If-Range:", 9, client_range },
842 { "X-Filter:", 9, client_x_filter },
843 { "*", 0, crunch_client_header },
844 { "*", 0, filter_header },
848 const struct parsers server_patterns[] = {
849 { "HTTP/", 5, server_http },
850 { "set-cookie:", 11, server_set_cookie },
851 { "connection:", 11, connection },
852 { "Content-Type:", 13, server_content_type },
853 { "Content-MD5:", 12, server_content_md5 },
854 { "Content-Encoding:", 17, server_content_encoding },
855 { "Transfer-Encoding:", 18, server_transfer_coding },
856 { "Keep-Alive:", 11, crumble },
857 { "content-disposition:", 20, server_content_disposition },
858 { "Last-Modified:", 14, server_last_modified },
859 { "*", 0, crunch_server_header },
860 { "*", 0, filter_header },
864 const struct parsers server_patterns_light[] = {
865 { "Content-Length:", 15, server_content_length },
866 { "Transfer-Encoding:", 18, server_transfer_coding },
868 { "Content-Encoding:", 17, server_content_encoding },
869 #endif /* def FEATURE_ZLIB */
873 const add_header_func_ptr add_client_headers[] = {
876 client_x_forwarded_adder,
878 /* Temporarily disabled: client_accept_encoding_adder, */
879 connection_close_adder,
883 const add_header_func_ptr add_server_headers[] = {
884 connection_close_adder,
888 /* The vanilla wafer. */
889 static const char VANILLA_WAFER[] =
890 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
891 "Do_not_send_me_any_copyrighted_information_other_than_the_"
892 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
893 "In_particular_do_not_send_me_any_cookies_that_"
894 "are_subject_to_a_claim_of_copyright_by_anybody._"
895 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
896 "(copyright_or_otherwise)_applying_to_any_cookie._";
898 /*********************************************************************
900 * Function : flush_socket
902 * Description : Write any pending "buffered" content.
905 * 1 : fd = file descriptor of the socket to read
906 * 2 : csp = Current client state (buffers, headers, etc...)
908 * Returns : On success, the number of bytes written are returned (zero
909 * indicates nothing was written). On error, -1 is returned,
910 * and errno is set appropriately. If count is zero and the
911 * file descriptor refers to a regular file, 0 will be
912 * returned without causing any other effect. For a special
913 * file, the results are not portable.
915 *********************************************************************/
916 int flush_socket(jb_socket fd, struct client_state *csp)
918 struct iob *iob = csp->iob;
919 int len = iob->eod - iob->cur;
926 if (write_socket(fd, iob->cur, (size_t)len))
930 iob->eod = iob->cur = iob->buf;
936 /*********************************************************************
938 * Function : add_to_iob
940 * Description : Add content to the buffered page, expanding the
941 * buffer if necessary.
944 * 1 : csp = Current client state (buffers, headers, etc...)
945 * 2 : buf = holds the content to be added to the page
946 * 3 : n = number of bytes to be added
948 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
949 * or buffer limit reached.
951 *********************************************************************/
952 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
954 struct iob *iob = csp->iob;
955 size_t used, offset, need, want;
958 if (n <= 0) return JB_ERR_OK;
960 used = (size_t)(iob->eod - iob->buf);
961 offset = (size_t)(iob->cur - iob->buf);
962 need = used + (size_t)n + 1;
965 * If the buffer can't hold the new data, extend it first.
966 * Use the next power of two if possible, else use the actual need.
968 if (need > csp->config->buffer_limit)
970 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
971 return JB_ERR_MEMORY;
974 if (need > iob->size)
976 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
978 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
982 else if (NULL != (p = (char *)realloc(iob->buf, need)))
988 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
989 return JB_ERR_MEMORY;
992 /* Update the iob pointers */
993 iob->cur = p + offset;
998 /* copy the new data into the iob buffer */
999 memcpy(iob->eod, buf, (size_t)n);
1001 /* point to the end of the data */
1004 /* null terminate == cheap insurance */
1013 /*********************************************************************
1015 * Function : decompress_iob
1017 * Description : Decompress buffered page, expanding the
1018 * buffer as necessary. csp->iob->cur
1019 * should point to the the beginning of the
1020 * compressed data block.
1023 * 1 : csp = Current client state (buffers, headers, etc...)
1025 * Returns : JB_ERR_OK on success,
1026 * JB_ERR_MEMORY if out-of-memory limit reached, and
1027 * JB_ERR_COMPRESS if error decompressing buffer.
1029 *********************************************************************/
1030 jb_err decompress_iob(struct client_state *csp)
1032 char *buf; /* new, uncompressed buffer */
1033 char *cur; /* Current iob position (to keep the original
1034 * iob->cur unmodified if we return early) */
1035 size_t bufsize; /* allocated size of the new buffer */
1036 size_t old_size; /* Content size before decompression */
1037 size_t skip_size; /* Number of bytes at the beginning of the iob
1038 that we should NOT decompress. */
1039 int status; /* return status of the inflate() call */
1040 z_stream zstr; /* used by calls to zlib */
1042 assert(csp->iob->cur - csp->iob->buf > 0);
1043 assert(csp->iob->eod - csp->iob->cur > 0);
1045 bufsize = csp->iob->size;
1046 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1047 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1049 cur = csp->iob->cur;
1054 * This is to protect the parsing of gzipped data,
1055 * but it should(?) be valid for deflated data also.
1057 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1058 return JB_ERR_COMPRESS;
1061 if (csp->content_type & CT_GZIP)
1064 * Our task is slightly complicated by the facts that data
1065 * compressed by gzip does not include a zlib header, and
1066 * that there is no easily accessible interface in zlib to
1067 * handle a gzip header. We strip off the gzip header by
1068 * hand, and later inform zlib not to expect a header.
1072 * Strip off the gzip header. Please see RFC 1952 for more
1073 * explanation of the appropriate fields.
1075 if ((*cur++ != (char)0x1f)
1076 || (*cur++ != (char)0x8b)
1077 || (*cur++ != Z_DEFLATED))
1079 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1080 return JB_ERR_COMPRESS;
1086 * XXX: These magic numbers should be replaced
1087 * with macros to give a better idea what they do.
1091 /* The gzip header has reserved bits set; bail out. */
1092 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1093 return JB_ERR_COMPRESS;
1097 /* Skip extra fields if necessary. */
1101 * Skip a given number of bytes, specified
1102 * as a 16-bit little-endian value.
1105 * XXX: This code used to be:
1107 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1109 * which I had to change into:
1111 * cur += *cur++ + (*cur++ << 8);
1113 * at which point gcc43 finally noticed that the value
1114 * of cur is undefined (it depends on which of the
1115 * summands is evaluated first).
1117 * I haven't come across a site where this
1118 * code is actually executed yet, but I hope
1122 skip_bytes = *cur++;
1123 skip_bytes = *cur++ << 8;
1125 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1128 * The number of bytes to skip should be positive
1129 * and we'd like to stay in the buffer.
1131 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1133 log_error(LOG_LEVEL_ERROR,
1134 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1136 return JB_ERR_COMPRESS;
1138 log_error(LOG_LEVEL_INFO,
1139 "Skipping %d bytes for gzip compression. Does this sound right?",
1144 /* Skip the filename if necessary. */
1147 /* A null-terminated string is supposed to follow. */
1148 while (*cur++ && (cur < csp->iob->eod));
1152 /* Skip the comment if necessary. */
1155 /* A null-terminated string is supposed to follow. */
1156 while (*cur++ && (cur < csp->iob->eod));
1159 /* Skip the CRC if necessary. */
1165 if (cur >= csp->iob->eod)
1168 * If the current position pointer reached or passed
1169 * the buffer end, we were obviously tricked to skip
1172 log_error(LOG_LEVEL_ERROR,
1173 "Malformed gzip header detected. Aborting decompression.");
1174 return JB_ERR_COMPRESS;
1178 else if (csp->content_type & CT_DEFLATE)
1181 * XXX: The debug level should be lowered
1182 * before the next stable release.
1184 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1186 * In theory (that is, according to RFC 1950), deflate-compressed
1187 * data should begin with a two-byte zlib header and have an
1188 * adler32 checksum at the end. It seems that in practice only
1189 * the raw compressed data is sent. Note that this means that
1190 * we are not RFC 1950-compliant here, but the advantage is that
1191 * this actually works. :)
1193 * We add a dummy null byte to tell zlib where the data ends,
1194 * and later inform it not to expect a header.
1196 * Fortunately, add_to_iob() has thoughtfully null-terminated
1197 * the buffer; we can just increment the end pointer to include
1204 log_error(LOG_LEVEL_ERROR,
1205 "Unable to determine compression format for decompression");
1206 return JB_ERR_COMPRESS;
1209 /* Set up the fields required by zlib. */
1210 zstr.next_in = (Bytef *)cur;
1211 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1212 zstr.zalloc = Z_NULL;
1213 zstr.zfree = Z_NULL;
1214 zstr.opaque = Z_NULL;
1217 * Passing -MAX_WBITS to inflateInit2 tells the library
1218 * that there is no zlib header.
1220 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1222 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1223 return JB_ERR_COMPRESS;
1227 * Next, we allocate new storage for the inflated data.
1228 * We don't modify the existing iob yet, so in case there
1229 * is error in decompression we can recover gracefully.
1231 buf = zalloc(bufsize);
1234 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1235 return JB_ERR_MEMORY;
1238 assert(bufsize >= skip_size);
1239 memcpy(buf, csp->iob->buf, skip_size);
1240 zstr.avail_out = bufsize - skip_size;
1241 zstr.next_out = (Bytef *)buf + skip_size;
1243 /* Try to decompress the whole stream in one shot. */
1244 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1246 /* We need to allocate more memory for the output buffer. */
1248 char *tmpbuf; /* used for realloc'ing the buffer */
1249 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1252 * If zlib wants more data then there's a problem, because
1253 * the complete compressed file should have been buffered.
1255 if (0 == zstr.avail_in)
1257 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1258 return JB_ERR_COMPRESS;
1262 * If we tried the limit and still didn't have enough
1263 * memory, just give up.
1265 if (bufsize == csp->config->buffer_limit)
1267 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1268 return JB_ERR_MEMORY;
1271 /* Try doubling the buffer size each time. */
1274 /* Don't exceed the buffer limit. */
1275 if (bufsize > csp->config->buffer_limit)
1277 bufsize = csp->config->buffer_limit;
1280 /* Try to allocate the new buffer. */
1281 tmpbuf = realloc(buf, bufsize);
1284 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1286 return JB_ERR_MEMORY;
1290 char *oldnext_out = (char *)zstr.next_out;
1293 * Update the fields for inflate() to use the new
1294 * buffer, which may be in a location different from
1297 zstr.avail_out += bufsize - oldbufsize;
1298 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1301 * Compare with an uglier method of calculating these values
1302 * that doesn't require the extra oldbufsize variable.
1304 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1305 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1306 assert(zstr.avail_out > 0);
1312 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1314 log_error(LOG_LEVEL_ERROR,
1315 "Inconsistent stream state after decompression: %s", zstr.msg);
1317 * XXX: Intentionally no return.
1319 * According to zlib.h, Z_STREAM_ERROR is returned
1320 * "if the stream state was inconsistent".
1322 * I assume in this case inflate()'s status
1323 * would also be something different than Z_STREAM_END
1324 * so this check should be redundant, but lets see.
1328 if (status != Z_STREAM_END)
1330 /* We failed to decompress the stream. */
1331 log_error(LOG_LEVEL_ERROR,
1332 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1333 return JB_ERR_COMPRESS;
1337 * Finally, we can actually update the iob, since the
1338 * decompression was successful. First, free the old
1341 freez(csp->iob->buf);
1343 /* Now, update the iob to use the new buffer. */
1344 csp->iob->buf = buf;
1345 csp->iob->cur = csp->iob->buf + skip_size;
1346 csp->iob->eod = (char *)zstr.next_out;
1347 csp->iob->size = bufsize;
1350 * Make sure the new uncompressed iob obeys some minimal
1351 * consistency conditions.
1353 if ((csp->iob->buf < csp->iob->cur)
1354 && (csp->iob->cur <= csp->iob->eod)
1355 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1357 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1360 log_error(LOG_LEVEL_RE_FILTER,
1361 "Decompression successful. Old size: %d, new size: %d.",
1362 old_size, new_size);
1366 /* zlib thinks this is OK, so lets do the same. */
1367 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1372 /* It seems that zlib did something weird. */
1373 log_error(LOG_LEVEL_ERROR,
1374 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1375 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1376 csp->iob->eod, csp->iob->buf + csp->iob->size);
1377 return JB_ERR_COMPRESS;
1383 #endif /* defined(FEATURE_ZLIB) */
1386 /*********************************************************************
1388 * Function : get_header
1390 * Description : This (odd) routine will parse the csp->iob
1393 * 1 : csp = Current client state (buffers, headers, etc...)
1395 * Returns : Any one of the following:
1397 * 1) a pointer to a dynamically allocated string that contains a header line
1398 * 2) NULL indicating that the end of the header was reached
1399 * 3) "" indicating that the end of the iob was reached before finding
1400 * a complete header line.
1402 *********************************************************************/
1403 char *get_header(struct client_state *csp)
1409 if ((iob->cur == NULL)
1410 || ((p = strchr(iob->cur, '\n')) == NULL))
1412 return(""); /* couldn't find a complete header */
1417 ret = strdup(iob->cur);
1420 /* FIXME No way to handle error properly */
1421 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1426 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1428 /* is this a blank line (i.e. the end of the header) ? */
1440 /*********************************************************************
1442 * Function : get_header_value
1444 * Description : Get the value of a given header from a chained list
1445 * of header lines or return NULL if no such header is
1446 * present in the list.
1449 * 1 : header_list = pointer to list
1450 * 2 : header_name = string with name of header to look for.
1451 * Trailing colon required, capitalization
1454 * Returns : NULL if not found, else value of header
1456 *********************************************************************/
1457 char *get_header_value(const struct list *header_list, const char *header_name)
1459 struct list_entry *cur_entry;
1463 assert(header_list);
1464 assert(header_name);
1465 length = strlen(header_name);
1467 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1471 if (!strncmpic(cur_entry->str, header_name, length))
1474 * Found: return pointer to start of value
1476 ret = (char *) (cur_entry->str + length);
1477 while (*ret && ijb_isspace(*ret)) ret++;
1491 /*********************************************************************
1493 * Function : scan_headers
1495 * Description : Scans headers, applies tags and updates action bits.
1498 * 1 : csp = Current client state (buffers, headers, etc...)
1500 * Returns : JB_ERR_OK
1502 *********************************************************************/
1503 static jb_err scan_headers(struct client_state *csp)
1505 struct list_entry *h; /* Header */
1506 jb_err err = JB_ERR_OK;
1508 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1510 /* Header crunch()ed in previous run? -> ignore */
1511 if (h->str == NULL) continue;
1512 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1513 err = header_tagger(csp, h->str);
1520 /*********************************************************************
1524 * Description : add, delete or modify lines in the HTTP header streams.
1525 * On entry, it receives a linked list of headers space
1526 * that was allocated dynamically (both the list nodes
1527 * and the header contents).
1529 * As a side effect it frees the space used by the original
1532 * XXX: should be split to remove the first_run hack.
1535 * 1 : pats = list of patterns to match against headers
1536 * 2 : more_headers = list of functions to add more
1537 * headers (client or server)
1538 * 3 : csp = Current client state (buffers, headers, etc...)
1540 * Returns : JB_ERR_OK in case off success, or
1541 * JB_ERR_MEMORY on out-of-memory error.
1543 *********************************************************************/
1544 jb_err sed(const struct parsers pats[],
1545 const add_header_func_ptr more_headers[],
1546 struct client_state *csp)
1548 struct list_entry *p;
1549 const struct parsers *v;
1550 const add_header_func_ptr *f;
1551 jb_err err = JB_ERR_OK;
1555 * If filtering is enabled, sed is run twice,
1556 * but most of the work needs to be done only once.
1558 first_run = (more_headers != NULL ) ? 1 : 0;
1560 if (first_run) /* Parse and print */
1564 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1566 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1568 /* Header crunch()ed in previous run? -> ignore */
1569 if (p->str == NULL) continue;
1571 /* Does the current parser handle this header? */
1572 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1574 err = v->parser(csp, (char **)&(p->str));
1578 /* place any additional headers on the csp->headers list */
1579 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1584 else /* Parse only */
1587 * The second run is only needed if the body was modified
1588 * and the content-lenght has changed.
1590 if (strncmpic(csp->http->cmd, "HEAD", 4))
1592 /*XXX: Code duplication */
1593 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1595 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1597 /* Header crunch()ed in previous run? -> ignore */
1598 if (p->str == NULL) continue;
1600 /* Does the current parser handle this header? */
1601 if (strncmpic(p->str, v->str, v->len) == 0)
1603 err = v->parser(csp, (char **)&(p->str));
1615 /*********************************************************************
1617 * Function : header_tagger
1619 * Description : Executes all text substitutions from applying
1620 * tag actions and saves the result as tag.
1622 * XXX: Shares enough code with filter_header() and
1623 * pcrs_filter_response() to warrant some helper functions.
1626 * 1 : csp = Current client state (buffers, headers, etc...)
1627 * 2 : header = Header that is used as tagger input
1629 * Returns : JB_ERR_OK on success and always succeeds
1631 *********************************************************************/
1632 static jb_err header_tagger(struct client_state *csp, char *header)
1634 int wanted_filter_type;
1635 int multi_action_index;
1639 struct file_list *fl;
1640 struct re_filterfile_spec *b;
1641 struct list_entry *tag_name;
1643 int found_filters = 0;
1644 const size_t header_length = strlen(header);
1646 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1648 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1649 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1653 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1654 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1657 /* Check if there are any filters */
1658 for (i = 0; i < MAX_AF_FILES; i++)
1671 if (0 == found_filters)
1673 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1677 for (i = 0; i < MAX_AF_FILES; i++)
1680 if ((NULL == fl) || (NULL == fl->f))
1683 * Either there are no filter files
1684 * left, or this filter file just
1685 * contains no valid filters.
1687 * Continue to be sure we don't miss
1688 * valid filter files that are chained
1689 * after empty or invalid ones.
1694 /* For all filters, */
1695 for (b = fl->f; b; b = b->next)
1697 if (b->type != wanted_filter_type)
1699 /* skip the ones we don't care about, */
1702 /* leaving only taggers that could apply, of which we use the ones, */
1703 for (tag_name = csp->action->multi[multi_action_index]->first;
1704 NULL != tag_name; tag_name = tag_name->next)
1706 /* that do apply, and */
1707 if (strcmp(b->name, tag_name->str) == 0)
1709 char *modified_tag = NULL;
1711 size_t size = header_length;
1712 pcrs_job *joblist = b->joblist;
1714 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1716 if (NULL == joblist)
1718 log_error(LOG_LEVEL_RE_FILTER,
1719 "Tagger %s has empty joblist. Nothing to do.", b->name);
1723 /* execute their pcrs_joblist on the header. */
1724 for (job = joblist; NULL != job; job = job->next)
1726 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1730 /* Success, continue with the modified version. */
1739 /* Tagger doesn't match */
1742 /* Regex failure, log it but continue anyway. */
1743 log_error(LOG_LEVEL_ERROR,
1744 "Problems with tagger \'%s\' and header \'%s\': %s",
1745 b->name, *header, pcrs_strerror(hits));
1747 freez(modified_tag);
1751 if (b->dynamic) pcrs_free_joblist(joblist);
1753 /* If this tagger matched */
1759 * There is to technical limitation which makes
1760 * it impossible to use empty tags, but I assume
1761 * no one would do it intentionally.
1764 log_error(LOG_LEVEL_INFO,
1765 "Tagger \'%s\' created an empty tag. Ignored.",
1770 if (!list_contains_item(csp->tags, tag))
1772 if (JB_ERR_OK != enlist(csp->tags, tag))
1774 log_error(LOG_LEVEL_ERROR,
1775 "Insufficient memory to add tag \'%s\', "
1776 "based on tagger \'%s\' and header \'%s\'",
1777 tag, b->name, *header);
1781 char *action_message;
1783 * update the action bits right away, to make
1784 * tagging based on tags set by earlier taggers
1785 * of the same kind possible.
1787 if (update_action_bits_for_tag(csp, tag))
1789 action_message = "Action bits updated accordingly.";
1793 action_message = "No action bits update necessary.";
1796 log_error(LOG_LEVEL_HEADER,
1797 "Tagger \'%s\' added tag \'%s\'. %s",
1798 b->name, tag, action_message);
1803 /* XXX: Is this log-worthy? */
1804 log_error(LOG_LEVEL_HEADER,
1805 "Tagger \'%s\' didn't add tag \'%s\'. "
1806 "Tag already present", b->name, tag);
1809 } /* if the tagger matched */
1810 } /* if the tagger applies */
1811 } /* for every tagger that could apply */
1812 } /* for all filters */
1813 } /* for all filter files */
1818 /* here begins the family of parser functions that reformat header lines */
1820 /*********************************************************************
1822 * Function : filter_header
1824 * Description : Executes all text substitutions from all applying
1825 * +(server|client)-header-filter actions on the header.
1826 * Most of the code was copied from pcrs_filter_response,
1827 * including the rather short variable names
1830 * 1 : csp = Current client state (buffers, headers, etc...)
1831 * 2 : header = On input, pointer to header to modify.
1832 * On output, pointer to the modified header, or NULL
1833 * to remove the header. This function frees the
1834 * original string if necessary.
1836 * Returns : JB_ERR_OK on success and always succeeds
1838 *********************************************************************/
1839 static jb_err filter_header(struct client_state *csp, char **header)
1843 size_t size = strlen(*header);
1845 char *newheader = NULL;
1848 struct file_list *fl;
1849 struct re_filterfile_spec *b;
1850 struct list_entry *filtername;
1852 int i, found_filters = 0;
1853 int wanted_filter_type;
1854 int multi_action_index;
1856 if (csp->flags & CSP_FLAG_NO_FILTERING)
1861 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1863 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1864 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1868 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1869 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1873 * Need to check the set of re_filterfiles...
1875 for (i = 0; i < MAX_AF_FILES; i++)
1888 if (0 == found_filters)
1890 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1894 for (i = 0; i < MAX_AF_FILES; i++)
1897 if ((NULL == fl) || (NULL == fl->f))
1900 * Either there are no filter files
1901 * left, or this filter file just
1902 * contains no valid filters.
1904 * Continue to be sure we don't miss
1905 * valid filter files that are chained
1906 * after empty or invalid ones.
1911 * For all applying +filter actions, look if a filter by that
1912 * name exists and if yes, execute its pcrs_joblist on the
1915 for (b = fl->f; b; b = b->next)
1917 if (b->type != wanted_filter_type)
1919 /* Skip other filter types */
1923 for (filtername = csp->action->multi[multi_action_index]->first;
1924 filtername ; filtername = filtername->next)
1926 if (strcmp(b->name, filtername->str) == 0)
1928 int current_hits = 0;
1929 pcrs_job *joblist = b->joblist;
1931 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1933 if (NULL == joblist)
1935 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1939 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1940 *header, size, b->name);
1942 /* Apply all jobs from the joblist */
1943 for (job = joblist; NULL != job; job = job->next)
1945 matches = pcrs_execute(job, *header, size, &newheader, &size);
1948 current_hits += matches;
1949 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1951 *header = newheader;
1953 else if ( 0 == matches )
1955 /* Filter doesn't change header */
1961 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1962 *header, b->name, pcrs_strerror(matches));
1963 if (newheader != NULL)
1965 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1971 if (b->dynamic) pcrs_free_joblist(joblist);
1973 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1974 hits += current_hits;
1981 * Additionally checking for hits is important because if
1982 * the continue hack is triggered, server headers can
1983 * arrive empty to separate multiple heads from each other.
1985 if ((0 == size) && hits)
1987 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1995 /*********************************************************************
1997 * Function : connection
1999 * Description : Makes sure that the value of the Connection: header
2000 * is "close" and signals connection_close_adder
2004 * 1 : csp = Current client state (buffers, headers, etc...)
2005 * 2 : header = On input, pointer to header to modify.
2006 * On output, pointer to the modified header, or NULL
2007 * to remove the header. This function frees the
2008 * original string if necessary.
2010 * Returns : JB_ERR_OK on success, or
2011 * JB_ERR_MEMORY on out-of-memory error.
2013 *********************************************************************/
2014 static jb_err connection(struct client_state *csp, char **header)
2016 char *old_header = *header;
2018 /* Do we have a 'Connection: close' header? */
2019 if (strcmpic(*header, "Connection: close"))
2021 /* No, create one */
2022 *header = strdup("Connection: close");
2025 return JB_ERR_MEMORY;
2027 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2031 /* Signal connection_close_adder() to return early. */
2032 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2034 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2038 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2045 /*********************************************************************
2047 * Function : crumble
2049 * Description : This is called if a header matches a pattern to "crunch"
2052 * 1 : csp = Current client state (buffers, headers, etc...)
2053 * 2 : header = On input, pointer to header to modify.
2054 * On output, pointer to the modified header, or NULL
2055 * to remove the header. This function frees the
2056 * original string if necessary.
2058 * Returns : JB_ERR_OK on success, or
2059 * JB_ERR_MEMORY on out-of-memory error.
2061 *********************************************************************/
2062 static jb_err crumble(struct client_state *csp, char **header)
2064 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2070 /*********************************************************************
2072 * Function : crunch_server_header
2074 * Description : Crunch server header if it matches a string supplied by the
2075 * user. Called from `sed'.
2078 * 1 : csp = Current client state (buffers, headers, etc...)
2079 * 2 : header = On input, pointer to header to modify.
2080 * On output, pointer to the modified header, or NULL
2081 * to remove the header. This function frees the
2082 * original string if necessary.
2084 * Returns : JB_ERR_OK on success and always succeeds
2086 *********************************************************************/
2087 static jb_err crunch_server_header(struct client_state *csp, char **header)
2089 const char *crunch_pattern;
2091 /* Do we feel like crunching? */
2092 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2094 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2096 /* Is the current header the lucky one? */
2097 if (strstr(*header, crunch_pattern))
2099 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2108 /*********************************************************************
2110 * Function : server_content_type
2112 * Description : Set the content-type for filterable types (text/.*,
2113 * .*xml.*, javascript and image/gif) unless filtering has been
2114 * forbidden (CT_TABOO) while parsing earlier headers.
2115 * NOTE: Since text/plain is commonly used by web servers
2116 * for files whose correct type is unknown, we don't
2117 * set CT_TEXT for it.
2120 * 1 : csp = Current client state (buffers, headers, etc...)
2121 * 2 : header = On input, pointer to header to modify.
2122 * On output, pointer to the modified header, or NULL
2123 * to remove the header. This function frees the
2124 * original string if necessary.
2126 * Returns : JB_ERR_OK on success, or
2127 * JB_ERR_MEMORY on out-of-memory error.
2129 *********************************************************************/
2130 static jb_err server_content_type(struct client_state *csp, char **header)
2132 /* Remove header if it isn't the first Content-Type header */
2133 if ((csp->content_type & CT_DECLARED))
2136 * Another, slightly slower, way to see if
2137 * we already parsed another Content-Type header.
2139 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2141 log_error(LOG_LEVEL_ERROR,
2142 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2150 * Signal that the Content-Type has been set.
2152 csp->content_type |= CT_DECLARED;
2154 if (!(csp->content_type & CT_TABOO))
2156 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2157 || strstr(*header, "xml")
2158 || strstr(*header, "application/x-javascript"))
2160 csp->content_type |= CT_TEXT;
2162 else if (strstr(*header, " image/gif"))
2164 csp->content_type |= CT_GIF;
2166 else if (strstr(*header, " image/jpeg"))
2168 csp->content_type |= CT_JPEG;
2173 * Are we messing with the content type?
2175 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2178 * Make sure the user doesn't accidently
2179 * change the content type of binary documents.
2181 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2184 *header = strdup("Content-Type: ");
2185 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2189 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2190 return JB_ERR_MEMORY;
2192 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2196 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2197 "Enable force-text-mode if you know what you're doing.", *header);
2205 /*********************************************************************
2207 * Function : server_transfer_coding
2209 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2210 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2211 * - Remove header if body was chunked but has been
2212 * de-chunked for filtering.
2215 * 1 : csp = Current client state (buffers, headers, etc...)
2216 * 2 : header = On input, pointer to header to modify.
2217 * On output, pointer to the modified header, or NULL
2218 * to remove the header. This function frees the
2219 * original string if necessary.
2221 * Returns : JB_ERR_OK on success, or
2222 * JB_ERR_MEMORY on out-of-memory error.
2224 *********************************************************************/
2225 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2228 * Turn off pcrs and gif filtering if body compressed
2230 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2234 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2236 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2237 csp->http->cmd, *header);
2238 #endif /* def FEATURE_ZLIB */
2239 csp->content_type = CT_TABOO;
2243 * Raise flag if body chunked
2245 if (strstr(*header, "chunked"))
2247 csp->flags |= CSP_FLAG_CHUNKED;
2250 * If the body was modified, it has been de-chunked first
2251 * and the header must be removed.
2253 * FIXME: If there is more than one transfer encoding,
2254 * only the "chunked" part should be removed here.
2256 if (csp->flags & CSP_FLAG_MODIFIED)
2258 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2267 /*********************************************************************
2269 * Function : server_content_encoding
2271 * Description : This function is run twice for each request,
2272 * unless FEATURE_ZLIB and filtering are disabled.
2274 * The first run is used to check if the content
2275 * is compressed, if FEATURE_ZLIB is disabled
2276 * filtering is then disabled as well, if FEATURE_ZLIB
2277 * is enabled the content is marked for decompression.
2279 * The second run is used to remove the Content-Encoding
2280 * header if the decompression was successful.
2283 * 1 : csp = Current client state (buffers, headers, etc...)
2284 * 2 : header = On input, pointer to header to modify.
2285 * On output, pointer to the modified header, or NULL
2286 * to remove the header. This function frees the
2287 * original string if necessary.
2289 * Returns : JB_ERR_OK on success, or
2290 * JB_ERR_MEMORY on out-of-memory error.
2292 *********************************************************************/
2293 static jb_err server_content_encoding(struct client_state *csp, char **header)
2296 if ((csp->flags & CSP_FLAG_MODIFIED)
2297 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2300 * We successfully decompressed the content,
2301 * and have to clean the header now, so the
2302 * client no longer expects compressed data..
2304 * XXX: There is a difference between cleaning
2305 * and removing it completely.
2307 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2310 else if (strstr(*header, "gzip"))
2312 /* Mark for gzip decompression */
2313 csp->content_type |= CT_GZIP;
2315 else if (strstr(*header, "deflate"))
2317 /* Mark for zlib decompression */
2318 csp->content_type |= CT_DEFLATE;
2320 else if (strstr(*header, "compress"))
2323 * We can't decompress this; therefore we can't filter
2326 csp->content_type |= CT_TABOO;
2328 #else /* !defined(FEATURE_ZLIB) */
2329 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2332 * Body is compressed, turn off pcrs and gif filtering.
2334 csp->content_type |= CT_TABOO;
2337 * Log a warning if the user expects the content to be filtered.
2339 if ((csp->rlist != NULL) &&
2340 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2342 log_error(LOG_LEVEL_INFO,
2343 "Compressed content detected, content filtering disabled. "
2344 "Consider recompiling Privoxy with zlib support or "
2345 "enable the prevent-compression action.");
2348 #endif /* defined(FEATURE_ZLIB) */
2355 /*********************************************************************
2357 * Function : server_content_length
2359 * Description : Adjust Content-Length header if we modified
2363 * 1 : csp = Current client state (buffers, headers, etc...)
2364 * 2 : header = On input, pointer to header to modify.
2365 * On output, pointer to the modified header, or NULL
2366 * to remove the header. This function frees the
2367 * original string if necessary.
2369 * Returns : JB_ERR_OK on success, or
2370 * JB_ERR_MEMORY on out-of-memory error.
2372 *********************************************************************/
2373 static jb_err server_content_length(struct client_state *csp, char **header)
2375 const size_t max_header_length = 80;
2377 /* Regenerate header if the content was modified. */
2378 if (csp->flags & CSP_FLAG_MODIFIED)
2381 *header = (char *) zalloc(max_header_length);
2382 if (*header == NULL)
2384 return JB_ERR_MEMORY;
2387 snprintf(*header, max_header_length, "Content-Length: %d",
2388 (int)csp->content_length);
2389 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2390 (int)csp->content_length);
2397 /*********************************************************************
2399 * Function : server_content_md5
2401 * Description : Crumble any Content-MD5 headers if the document was
2402 * modified. FIXME: Should we re-compute instead?
2405 * 1 : csp = Current client state (buffers, headers, etc...)
2406 * 2 : header = On input, pointer to header to modify.
2407 * On output, pointer to the modified header, or NULL
2408 * to remove the header. This function frees the
2409 * original string if necessary.
2411 * Returns : JB_ERR_OK on success, or
2412 * JB_ERR_MEMORY on out-of-memory error.
2414 *********************************************************************/
2415 static jb_err server_content_md5(struct client_state *csp, char **header)
2417 if (csp->flags & CSP_FLAG_MODIFIED)
2419 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2427 /*********************************************************************
2429 * Function : server_content_disposition
2431 * Description : If enabled, blocks or modifies the "content-disposition" header.
2432 * Called from `sed'.
2435 * 1 : csp = Current client state (buffers, headers, etc...)
2436 * 2 : header = On input, pointer to header to modify.
2437 * On output, pointer to the modified header, or NULL
2438 * to remove the header. This function frees the
2439 * original string if necessary.
2441 * Returns : JB_ERR_OK on success, or
2442 * JB_ERR_MEMORY on out-of-memory error.
2444 *********************************************************************/
2445 static jb_err server_content_disposition(struct client_state *csp, char **header)
2450 * Are we messing with the content-disposition header?
2452 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2458 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2460 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2463 * Blocking content-disposition header
2465 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2472 * Replacing content-disposition header
2475 *header = strdup("content-disposition: ");
2476 string_append(header, newval);
2478 if (*header == NULL)
2480 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2484 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2487 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2491 /*********************************************************************
2493 * Function : server_last_modified
2495 * Description : Changes Last-Modified header to the actual date
2496 * to help hide-if-modified-since.
2497 * Called from `sed'.
2500 * 1 : csp = Current client state (buffers, headers, etc...)
2501 * 2 : header = On input, pointer to header to modify.
2502 * On output, pointer to the modified header, or NULL
2503 * to remove the header. This function frees the
2504 * original string if necessary.
2506 * Returns : JB_ERR_OK on success, or
2507 * JB_ERR_MEMORY on out-of-memory error.
2509 *********************************************************************/
2510 static jb_err server_last_modified(struct client_state *csp, char **header)
2513 char buf[BUFFER_SIZE];
2516 #ifdef HAVE_GMTIME_R
2519 struct tm *timeptr = NULL;
2520 time_t now, last_modified;
2522 long int days, hours, minutes, seconds;
2525 * Are we messing with the Last-Modified header?
2527 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2533 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2535 if (0 == strcmpic(newval, "block") )
2538 * Blocking Last-Modified header. Useless but why not.
2540 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2544 else if (0 == strcmpic(newval, "reset-to-request-time"))
2547 * Setting Last-Modified Header to now.
2549 get_http_time(0, buf);
2551 *header = strdup("Last-Modified: ");
2552 string_append(header, buf);
2554 if (*header == NULL)
2556 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2560 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2563 else if (0 == strcmpic(newval, "randomize"))
2565 const char *header_time = *header + sizeof("Last-Modified:");
2567 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2569 #ifdef HAVE_GMTIME_R
2570 timeptr = gmtime_r(&now, &gmt);
2571 #elif FEATURE_PTHREAD
2572 pthread_mutex_lock(&gmtime_mutex);
2573 timeptr = gmtime(&now);
2574 pthread_mutex_unlock(&gmtime_mutex);
2576 timeptr = gmtime(&now);
2578 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2580 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2585 rtime = (long int)difftime(now, last_modified);
2588 rtime = pick_from_range(rtime);
2589 last_modified += rtime;
2590 #ifdef HAVE_GMTIME_R
2591 timeptr = gmtime_r(&last_modified, &gmt);
2592 #elif FEATURE_PTHREAD
2593 pthread_mutex_lock(&gmtime_mutex);
2594 timeptr = gmtime(&last_modified);
2595 pthread_mutex_unlock(&gmtime_mutex);
2597 timeptr = gmtime(&last_modified);
2599 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2601 *header = strdup("Last-Modified: ");
2602 string_append(header, newheader);
2604 if (*header == NULL)
2606 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2607 return JB_ERR_MEMORY;
2610 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2612 days = rtime / (3600 * 24);
2613 hours = rtime / 3600 % 24;
2614 minutes = rtime / 60 % 60;
2615 seconds = rtime % 60;
2617 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2618 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2619 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2624 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2633 /*********************************************************************
2635 * Function : client_accept_encoding
2637 * Description : Rewrite the client's Accept-Encoding header so that
2638 * if doesn't allow compression, if the action applies.
2639 * Note: For HTTP/1.0 the absence of the header is enough.
2642 * 1 : csp = Current client state (buffers, headers, etc...)
2643 * 2 : header = On input, pointer to header to modify.
2644 * On output, pointer to the modified header, or NULL
2645 * to remove the header. This function frees the
2646 * original string if necessary.
2648 * Returns : JB_ERR_OK on success, or
2649 * JB_ERR_MEMORY on out-of-memory error.
2651 *********************************************************************/
2652 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2654 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2656 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2660 /* Temporarily disable the correct behaviour to
2661 * work around a PHP bug.
2663 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2665 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2666 * if (*header == NULL)
2668 * return JB_ERR_MEMORY;
2679 /*********************************************************************
2681 * Function : client_te
2683 * Description : Rewrite the client's TE header so that
2684 * if doesn't allow compression, if the action applies.
2687 * 1 : csp = Current client state (buffers, headers, etc...)
2688 * 2 : header = On input, pointer to header to modify.
2689 * On output, pointer to the modified header, or NULL
2690 * to remove the header. This function frees the
2691 * original string if necessary.
2693 * Returns : JB_ERR_OK on success, or
2694 * JB_ERR_MEMORY on out-of-memory error.
2696 *********************************************************************/
2697 static jb_err client_te(struct client_state *csp, char **header)
2699 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2702 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2709 /*********************************************************************
2711 * Function : client_referrer
2713 * Description : Handle the "referer" config setting properly.
2714 * Called from `sed'.
2717 * 1 : csp = Current client state (buffers, headers, etc...)
2718 * 2 : header = On input, pointer to header to modify.
2719 * On output, pointer to the modified header, or NULL
2720 * to remove the header. This function frees the
2721 * original string if necessary.
2723 * Returns : JB_ERR_OK on success, or
2724 * JB_ERR_MEMORY on out-of-memory error.
2726 *********************************************************************/
2727 static jb_err client_referrer(struct client_state *csp, char **header)
2729 const char *parameter;
2730 /* booleans for parameters we have to check multiple times */
2731 int parameter_conditional_block;
2732 int parameter_conditional_forge;
2734 #ifdef FEATURE_FORCE_LOAD
2736 * Since the referrer can include the prefix even
2737 * if the request itself is non-forced, we must
2738 * clean it unconditionally.
2740 * XXX: strclean is too broad
2742 strclean(*header, FORCE_PREFIX);
2743 #endif /* def FEATURE_FORCE_LOAD */
2745 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2747 /* Nothing left to do */
2751 parameter = csp->action->string[ACTION_STRING_REFERER];
2752 assert(parameter != NULL);
2753 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2754 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2756 if (!parameter_conditional_block && !parameter_conditional_forge)
2759 * As conditional-block and conditional-forge are the only
2760 * parameters that rely on the original referrer, we can
2761 * remove it now for all the others.
2766 if (0 == strcmpic(parameter, "block"))
2768 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2771 else if (parameter_conditional_block || parameter_conditional_forge)
2773 return handle_conditional_hide_referrer_parameter(header,
2774 csp->http->hostport, parameter_conditional_block);
2776 else if (0 == strcmpic(parameter, "forge"))
2778 return create_forged_referrer(header, csp->http->hostport);
2782 /* interpret parameter as user-supplied referer to fake */
2783 return create_fake_referrer(header, parameter);
2788 /*********************************************************************
2790 * Function : client_accept_language
2792 * Description : Handle the "Accept-Language" config setting properly.
2793 * Called from `sed'.
2796 * 1 : csp = Current client state (buffers, headers, etc...)
2797 * 2 : header = On input, pointer to header to modify.
2798 * On output, pointer to the modified header, or NULL
2799 * to remove the header. This function frees the
2800 * original string if necessary.
2802 * Returns : JB_ERR_OK on success, or
2803 * JB_ERR_MEMORY on out-of-memory error.
2805 *********************************************************************/
2806 static jb_err client_accept_language(struct client_state *csp, char **header)
2811 * Are we messing with the Accept-Language?
2813 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2815 /*I don't think so*/
2819 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2821 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2824 * Blocking Accept-Language header
2826 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2833 * Replacing Accept-Language header
2836 *header = strdup("Accept-Language: ");
2837 string_append(header, newval);
2839 if (*header == NULL)
2841 log_error(LOG_LEVEL_ERROR,
2842 "Insufficent memory. Accept-Language header crunched without replacement.");
2846 log_error(LOG_LEVEL_HEADER,
2847 "Accept-Language header crunched and replaced with: %s", *header);
2850 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2854 /*********************************************************************
2856 * Function : crunch_client_header
2858 * Description : Crunch client header if it matches a string supplied by the
2859 * user. Called from `sed'.
2862 * 1 : csp = Current client state (buffers, headers, etc...)
2863 * 2 : header = On input, pointer to header to modify.
2864 * On output, pointer to the modified header, or NULL
2865 * to remove the header. This function frees the
2866 * original string if necessary.
2868 * Returns : JB_ERR_OK on success and always succeeds
2870 *********************************************************************/
2871 static jb_err crunch_client_header(struct client_state *csp, char **header)
2873 const char *crunch_pattern;
2875 /* Do we feel like crunching? */
2876 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2878 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2880 /* Is the current header the lucky one? */
2881 if (strstr(*header, crunch_pattern))
2883 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2891 /*********************************************************************
2893 * Function : client_uagent
2895 * Description : Handle the "user-agent" config setting properly
2896 * and remember its original value to enable browser
2897 * bug workarounds. Called from `sed'.
2900 * 1 : csp = Current client state (buffers, headers, etc...)
2901 * 2 : header = On input, pointer to header to modify.
2902 * On output, pointer to the modified header, or NULL
2903 * to remove the header. This function frees the
2904 * original string if necessary.
2906 * Returns : JB_ERR_OK on success, or
2907 * JB_ERR_MEMORY on out-of-memory error.
2909 *********************************************************************/
2910 static jb_err client_uagent(struct client_state *csp, char **header)
2914 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2919 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2926 *header = strdup("User-Agent: ");
2927 string_append(header, newval);
2929 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2931 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2935 /*********************************************************************
2937 * Function : client_ua
2939 * Description : Handle "ua-" headers properly. Called from `sed'.
2942 * 1 : csp = Current client state (buffers, headers, etc...)
2943 * 2 : header = On input, pointer to header to modify.
2944 * On output, pointer to the modified header, or NULL
2945 * to remove the header. This function frees the
2946 * original string if necessary.
2948 * Returns : JB_ERR_OK on success, or
2949 * JB_ERR_MEMORY on out-of-memory error.
2951 *********************************************************************/
2952 static jb_err client_ua(struct client_state *csp, char **header)
2954 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2956 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2964 /*********************************************************************
2966 * Function : client_from
2968 * Description : Handle the "from" config setting properly.
2969 * Called from `sed'.
2972 * 1 : csp = Current client state (buffers, headers, etc...)
2973 * 2 : header = On input, pointer to header to modify.
2974 * On output, pointer to the modified header, or NULL
2975 * to remove the header. This function frees the
2976 * original string if necessary.
2978 * Returns : JB_ERR_OK on success, or
2979 * JB_ERR_MEMORY on out-of-memory error.
2981 *********************************************************************/
2982 static jb_err client_from(struct client_state *csp, char **header)
2986 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2993 newval = csp->action->string[ACTION_STRING_FROM];
2996 * Are we blocking the e-mail address?
2998 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3000 log_error(LOG_LEVEL_HEADER, "crunched From!");
3004 log_error(LOG_LEVEL_HEADER, " modified");
3006 *header = strdup("From: ");
3007 string_append(header, newval);
3009 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3013 /*********************************************************************
3015 * Function : client_send_cookie
3017 * Description : Crunches the "cookie" header if necessary.
3018 * Called from `sed'.
3020 * XXX: Stupid name, doesn't send squat.
3023 * 1 : csp = Current client state (buffers, headers, etc...)
3024 * 2 : header = On input, pointer to header to modify.
3025 * On output, pointer to the modified header, or NULL
3026 * to remove the header. This function frees the
3027 * original string if necessary.
3029 * Returns : JB_ERR_OK on success, or
3030 * JB_ERR_MEMORY on out-of-memory error.
3032 *********************************************************************/
3033 static jb_err client_send_cookie(struct client_state *csp, char **header)
3035 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3037 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3045 /*********************************************************************
3047 * Function : client_x_forwarded
3049 * Description : Handle the "x-forwarded-for" config setting properly,
3050 * also used in the add_client_headers list. Called from `sed'.
3053 * 1 : csp = Current client state (buffers, headers, etc...)
3054 * 2 : header = On input, pointer to header to modify.
3055 * On output, pointer to the modified header, or NULL
3056 * to remove the header. This function frees the
3057 * original string if necessary.
3059 * Returns : JB_ERR_OK on success, or
3060 * JB_ERR_MEMORY on out-of-memory error.
3062 *********************************************************************/
3063 jb_err client_x_forwarded(struct client_state *csp, char **header)
3065 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3067 /* Save it so we can re-add it later */
3068 freez(csp->x_forwarded);
3069 csp->x_forwarded = *header;
3072 * Always set *header = NULL, since this information
3073 * will be sent at the end of the header.
3080 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3087 /*********************************************************************
3089 * Function : client_max_forwards
3091 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3092 * from the value of the Max-Forwards header field.
3095 * 1 : csp = Current client state (buffers, headers, etc...)
3096 * 2 : header = On input, pointer to header to modify.
3097 * On output, pointer to the modified header, or NULL
3098 * to remove the header. This function frees the
3099 * original string if necessary.
3101 * Returns : JB_ERR_OK on success, or
3102 * JB_ERR_MEMORY on out-of-memory error.
3104 *********************************************************************/
3105 static jb_err client_max_forwards(struct client_state *csp, char **header)
3109 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3110 (0 == strcmpic(csp->http->gpc, "options")))
3112 assert(*(*header+12) == ':');
3113 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3115 if (max_forwards > 0)
3117 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3118 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3119 csp->http->gpc, max_forwards);
3121 else if (max_forwards < 0)
3123 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3129 * Not supposed to be reached. direct_response() which
3130 * was already called earlier in chat() should have
3131 * intercepted the request.
3133 log_error(LOG_LEVEL_ERROR,
3134 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3135 assert(max_forwards != 0);
3140 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3149 /*********************************************************************
3151 * Function : client_host
3153 * Description : If the request URI did not contain host and
3154 * port information, parse and evaluate the Host
3157 * Also, kill ill-formed HOST: headers as sent by
3158 * Apple's iTunes software when used with a proxy.
3161 * 1 : csp = Current client state (buffers, headers, etc...)
3162 * 2 : header = On input, pointer to header to modify.
3163 * On output, pointer to the modified header, or NULL
3164 * to remove the header. This function frees the
3165 * original string if necessary.
3167 * Returns : JB_ERR_OK on success, or
3168 * JB_ERR_MEMORY on out-of-memory error.
3170 *********************************************************************/
3171 static jb_err client_host(struct client_state *csp, char **header)
3176 * If the header field name is all upper-case, chances are that it's
3177 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3178 * not a problem -- they are regenerated later.
3180 if ((*header)[1] == 'O')
3182 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3187 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3188 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3191 if (NULL == (p = strdup((*header)+6)))
3193 return JB_ERR_MEMORY;
3196 if (NULL == (q = strdup(p)))
3199 return JB_ERR_MEMORY;
3202 freez(csp->http->hostport);
3203 csp->http->hostport = p;
3204 freez(csp->http->host);
3205 csp->http->host = q;
3206 q = strchr(csp->http->host, ':');
3209 /* Terminate hostname and evaluate port string */
3211 csp->http->port = atoi(q);
3215 csp->http->port = csp->http->ssl ? 443 : 80;
3218 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3219 csp->http->hostport, csp->http->host, csp->http->port);
3222 /* Signal client_host_adder() to return right away */
3223 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3229 /*********************************************************************
3231 * Function : client_if_modified_since
3233 * Description : Remove or modify the If-Modified-Since header.
3236 * 1 : csp = Current client state (buffers, headers, etc...)
3237 * 2 : header = On input, pointer to header to modify.
3238 * On output, pointer to the modified header, or NULL
3239 * to remove the header. This function frees the
3240 * original string if necessary.
3242 * Returns : JB_ERR_OK on success, or
3243 * JB_ERR_MEMORY on out-of-memory error.
3245 *********************************************************************/
3246 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3249 #ifdef HAVE_GMTIME_R
3252 struct tm *timeptr = NULL;
3256 long int hours, minutes, seconds;
3260 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3263 * The client got an error message because of a temporary problem,
3264 * the problem is gone and the client now tries to revalidate our
3265 * error message on the real server. The revalidation would always
3266 * end with the transmission of the whole document and there is
3267 * no need to expose the bogus If-Modified-Since header.
3269 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3272 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3274 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3276 if ((0 == strcmpic(newval, "block")))
3278 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3281 else /* add random value */
3283 const char *header_time = *header + sizeof("If-Modified-Since:");
3285 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3287 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3292 rtime = strtol(newval, &endptr, 0);
3295 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3296 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3303 rtime = pick_from_range(rtime);
3307 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3310 tm += rtime * (negative ? -1 : 1);
3311 #ifdef HAVE_GMTIME_R
3312 timeptr = gmtime_r(&tm, &gmt);
3313 #elif FEATURE_PTHREAD
3314 pthread_mutex_lock(&gmtime_mutex);
3315 timeptr = gmtime(&tm);
3316 pthread_mutex_unlock(&gmtime_mutex);
3318 timeptr = gmtime(&tm);
3320 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3323 *header = strdup("If-Modified-Since: ");
3324 string_append(header, newheader);
3326 if (*header == NULL)
3328 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3329 return JB_ERR_MEMORY;
3332 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3334 hours = rtime / 3600;
3335 minutes = rtime / 60 % 60;
3336 seconds = rtime % 60;
3338 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3339 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3340 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3350 /*********************************************************************
3352 * Function : client_if_none_match
3354 * Description : Remove the If-None-Match header.
3357 * 1 : csp = Current client state (buffers, headers, etc...)
3358 * 2 : header = On input, pointer to header to modify.
3359 * On output, pointer to the modified header, or NULL
3360 * to remove the header. This function frees the
3361 * original string if necessary.
3363 * Returns : JB_ERR_OK on success, or
3364 * JB_ERR_MEMORY on out-of-memory error.
3366 *********************************************************************/
3367 static jb_err client_if_none_match(struct client_state *csp, char **header)
3369 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3371 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3379 /*********************************************************************
3381 * Function : client_x_filter
3383 * Description : Disables filtering if the client set "X-Filter: No".
3384 * Called from `sed'.
3387 * 1 : csp = Current client state (buffers, headers, etc...)
3388 * 2 : header = On input, pointer to header to modify.
3389 * On output, pointer to the modified header, or NULL
3390 * to remove the header. This function frees the
3391 * original string if necessary.
3393 * Returns : JB_ERR_OK on success
3395 *********************************************************************/
3396 jb_err client_x_filter(struct client_state *csp, char **header)
3398 if ( 0 == strcmpic(*header, "X-Filter: No"))
3400 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3402 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3406 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3408 log_error(LOG_LEVEL_HEADER,
3409 "force-text-mode overruled the client's request to fetch without filtering!");
3413 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3414 csp->flags |= CSP_FLAG_NO_FILTERING;
3415 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3417 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3425 /*********************************************************************
3427 * Function : client_range
3429 * Description : Removes Range and If-Range headers if content
3430 * filtering is enabled. If the client's version of
3431 * the document has been altered by Privoxy, the server
3432 * could interpret the range differently than the client
3433 * intended in which case the user could end up with
3434 * corrupted content.
3437 * 1 : csp = Current client state (buffers, headers, etc...)
3438 * 2 : header = On input, pointer to header to modify.
3439 * On output, pointer to the modified header, or NULL
3440 * to remove the header. This function frees the
3441 * original string if necessary.
3443 * Returns : JB_ERR_OK
3445 *********************************************************************/
3446 static jb_err client_range(struct client_state *csp, char **header)
3448 if (((csp->rlist != NULL) &&
3449 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]))) ||
3450 (csp->action->flags & (ACTION_DEANIMATE|ACTION_JPEG_INSPECT)))
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 : client_x_forwarded_adder
3645 * Description : Used in the add_client_headers list. Called from `sed'.
3648 * 1 : csp = Current client state (buffers, headers, etc...)
3650 * Returns : JB_ERR_OK on success, or
3651 * JB_ERR_MEMORY on out-of-memory error.
3653 *********************************************************************/
3654 static jb_err client_x_forwarded_adder(struct client_state *csp)
3659 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3664 if (csp->x_forwarded)
3666 p = strdup(csp->x_forwarded);
3667 string_append(&p, ", ");
3671 p = strdup("X-Forwarded-For: ");
3673 string_append(&p, csp->ip_addr_str);
3677 return JB_ERR_MEMORY;
3680 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3681 err = enlist(csp->headers, p);
3688 /*********************************************************************
3690 * Function : connection_close_adder
3692 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3693 * support. Adds a "Connection: close" header to csp->headers
3694 * unless the header was already present. Called from `sed'.
3696 * FIXME: This whole function shouldn't be neccessary!
3699 * 1 : csp = Current client state (buffers, headers, etc...)
3701 * Returns : JB_ERR_OK on success, or
3702 * JB_ERR_MEMORY on out-of-memory error.
3704 *********************************************************************/
3705 static jb_err connection_close_adder(struct client_state *csp)
3707 const unsigned int flags = csp->flags;
3710 * Return right away if
3712 * - we're parsing server headers and the server header
3713 * "Connection: close" is already set, or if
3715 * - we're parsing client headers and the client header
3716 * "Connection: close" is already set.
3718 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3719 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3720 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3721 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3726 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3728 return enlist(csp->headers, "Connection: close");
3732 /*********************************************************************
3734 * Function : server_http
3736 * Description : - Save the HTTP Status into csp->http->status
3737 * - Set CT_TABOO to prevent filtering if the answer
3738 * is a partial range (HTTP status 206)
3739 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3743 * 1 : csp = Current client state (buffers, headers, etc...)
3744 * 2 : header = On input, pointer to header to modify.
3745 * On output, pointer to the modified header, or NULL
3746 * to remove the header. This function frees the
3747 * original string if necessary.
3749 * Returns : JB_ERR_OK on success, or
3750 * JB_ERR_MEMORY on out-of-memory error.
3752 *********************************************************************/
3753 static jb_err server_http(struct client_state *csp, char **header)
3755 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3756 if (csp->http->status == 206)
3758 csp->content_type = CT_TABOO;
3761 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3763 /* XXX: Should we do a real validity check here? */
3764 if (strlen(*header) > 8)
3767 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3772 * XXX: Should we block the request or
3773 * enlist a valid status code line here?
3775 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3776 "Downgrading to HTTP/1.0 impossible.");
3784 /*********************************************************************
3786 * Function : server_set_cookie
3788 * Description : Handle the server "cookie" header properly.
3789 * Log cookie to the jar file. Then "crunch",
3790 * accept or rewrite it to a session cookie.
3791 * Called from `sed'.
3793 * TODO: Allow the user to specify a new expiration
3794 * time to cause the cookie to expire even before the
3795 * browser is closed.
3798 * 1 : csp = Current client state (buffers, headers, etc...)
3799 * 2 : header = On input, pointer to header to modify.
3800 * On output, pointer to the modified header, or NULL
3801 * to remove the header. This function frees the
3802 * original string if necessary.
3804 * Returns : JB_ERR_OK on success, or
3805 * JB_ERR_MEMORY on out-of-memory error.
3807 *********************************************************************/
3808 static jb_err server_set_cookie(struct client_state *csp, char **header)
3815 #ifdef FEATURE_COOKIE_JAR
3816 if (csp->config->jar)
3819 * Write timestamp into outbuf.
3821 * Complex because not all OSs have tm_gmtoff or
3822 * the %z field in strftime()
3824 char tempbuf[ BUFFER_SIZE ];
3826 #ifdef HAVE_LOCALTIME_R
3827 tm_now = *localtime_r(&now, &tm_now);
3828 #elif FEATURE_PTHREAD
3829 pthread_mutex_lock(&localtime_mutex);
3830 tm_now = *localtime (&now);
3831 pthread_mutex_unlock(&localtime_mutex);
3833 tm_now = *localtime (&now);
3835 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3837 /* strlen("set-cookie: ") = 12 */
3838 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3840 #endif /* def FEATURE_COOKIE_JAR */
3842 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3844 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3847 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3849 /* Flag whether or not to log a message */
3852 /* A variable to store the tag we're working on */
3855 /* Skip "Set-Cookie:" (11 characters) in header */
3856 cur_tag = *header + 11;
3858 /* skip whitespace between "Set-Cookie:" and value */
3859 while (*cur_tag && ijb_isspace(*cur_tag))
3864 /* Loop through each tag in the cookie */
3868 char *next_tag = strchr(cur_tag, ';');
3869 if (next_tag != NULL)
3871 /* Skip the ';' character itself */
3874 /* skip whitespace ";" and start of tag */
3875 while (*next_tag && ijb_isspace(*next_tag))
3882 /* "Next tag" is the end of the string */
3883 next_tag = cur_tag + strlen(cur_tag);
3887 * Check the expiration date to see
3888 * if the cookie is still valid, if yes,
3889 * rewrite it to a session cookie.
3891 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3893 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3895 /* Did we detect the date properly? */
3896 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3899 * Nope, treat it as if it was still valid.
3901 * XXX: Should we remove the whole cookie instead?
3903 log_error(LOG_LEVEL_ERROR,
3904 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3905 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3911 * Yes. Check if the cookie is still valid.
3913 * If the cookie is already expired it's probably
3914 * a delete cookie and even if it isn't, the browser
3915 * will discard it anyway.
3919 * XXX: timegm() isn't available on some AmigaOS
3920 * versions and our replacement doesn't work.
3922 * Our options are to either:
3924 * - disable session-cookies-only completely if timegm
3927 * - to simply remove all expired tags, like it has
3928 * been done until Privoxy 3.0.6 and to live with
3929 * the consequence that it can cause login/logout
3930 * problems on servers that don't validate their
3931 * input properly, or
3933 * - to replace it with mktime in which
3934 * case there is a slight chance of valid cookies
3935 * passing as already expired.
3937 * This is the way it's currently done and it's not
3938 * as bad as it sounds. If the missing GMT offset is
3939 * enough to change the result of the expiration check
3940 * the cookie will be only valid for a few hours
3941 * anyway, which in many cases will be shorter
3942 * than a browser session.
3944 if (cookie_time - now < 0)
3946 log_error(LOG_LEVEL_HEADER,
3947 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3948 /* Just in case some clown sets more then one expiration date */
3954 * Still valid, delete expiration date by copying
3955 * the rest of the string over it.
3957 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3958 * since the behaviour of strcpy is undefined for overlapping
3961 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3963 /* That changed the header, need to issue a log message */
3967 * Note that the next tag has now been moved to *cur_tag,
3968 * so we do not need to update the cur_tag pointer.
3976 /* Move on to next cookie tag */
3983 assert(NULL != *header);
3984 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3993 #ifdef FEATURE_FORCE_LOAD
3994 /*********************************************************************
3996 * Function : strclean
3998 * Description : In-Situ-Eliminate all occurances of substring in
4002 * 1 : string = string to clean
4003 * 2 : substring = substring to eliminate
4005 * Returns : Number of eliminations
4007 *********************************************************************/
4008 int strclean(const char *string, const char *substring)
4014 len = strlen(substring);
4016 while((pos = strstr(string, substring)) != NULL)
4023 while (*p++ != '\0');
4030 #endif /* def FEATURE_FORCE_LOAD */
4033 /*********************************************************************
4035 * Function : parse_header_time
4037 * Description : Parses time formats used in HTTP header strings
4038 * to get the numerical respresentation.
4041 * 1 : header_time = HTTP header time as string.
4042 * 2 : result = storage for header_time in seconds
4044 * Returns : JB_ERR_OK if the time format was recognized, or
4045 * JB_ERR_PARSE otherwise.
4047 *********************************************************************/
4048 static jb_err parse_header_time(const char *header_time, time_t *result)
4053 * Zero out gmt to prevent time zone offsets.
4055 * While this is only necessary on some platforms
4056 * (mingw32 for example), I don't know how to
4057 * detect these automatically and doing it everywhere
4060 memset(&gmt, 0, sizeof(gmt));
4062 /* Tue, 02 Jun 2037 20:00:00 */
4063 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4064 /* Tue, 02-Jun-2037 20:00:00 */
4065 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4066 /* Tue, 02-Jun-37 20:00:00 */
4067 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4068 /* Tuesday, 02-Jun-2037 20:00:00 */
4069 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4070 /* Tuesday Jun 02 20:00:00 2037 */
4071 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4073 return JB_ERR_PARSE;
4076 *result = timegm(&gmt);
4083 /*********************************************************************
4085 * Function : get_destination_from_headers
4087 * Description : Parse the "Host:" header to get the request's destination.
4088 * Only needed if the client's request was forcefully
4089 * redirected into Privoxy.
4091 * Code mainly copied from client_host() which is currently
4092 * run too late for this purpose.
4095 * 1 : headers = List of headers (one of them hopefully being
4096 * the "Host:" header)
4097 * 2 : http = storage for the result (host, port and hostport).
4099 * Returns : JB_ERR_MEMORY in case of memory problems,
4100 * JB_ERR_PARSE if the host header couldn't be found,
4101 * JB_ERR_OK otherwise.
4103 *********************************************************************/
4104 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4110 host = get_header_value(headers, "Host:");
4114 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4115 return JB_ERR_PARSE;
4118 if (NULL == (p = strdup((host))))
4120 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4121 return JB_ERR_MEMORY;
4124 if (NULL == (q = strdup(p)))
4127 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4128 return JB_ERR_MEMORY;
4131 freez(http->hostport);
4135 q = strchr(http->host, ':');
4138 /* Terminate hostname and evaluate port string */
4140 http->port = atoi(q);
4144 http->port = http->ssl ? 443 : 80;
4147 /* Rebuild request URL */
4149 http->url = strdup(http->ssl ? "https://" : "http://");
4150 string_append(&http->url, http->hostport);
4151 string_append(&http->url, http->path);
4152 if (http->url == NULL)
4154 return JB_ERR_MEMORY;
4157 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4165 /*********************************************************************
4167 * Function : create_forged_referrer
4169 * Description : Helper for client_referrer to forge a referer as
4170 * 'http://[hostname:port/' to fool stupid
4171 * checks for in-site links
4174 * 1 : header = Pointer to header pointer
4175 * 2 : hostport = Host and optionally port as string
4177 * Returns : JB_ERR_OK in case of success, or
4178 * JB_ERR_MEMORY in case of memory problems.
4180 *********************************************************************/
4181 static jb_err create_forged_referrer(char **header, const char *hostport)
4183 assert(NULL == *header);
4185 *header = strdup("Referer: http://");
4186 string_append(header, hostport);
4187 string_append(header, "/");
4189 if (NULL == *header)
4191 return JB_ERR_MEMORY;
4194 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4201 /*********************************************************************
4203 * Function : create_fake_referrer
4205 * Description : Helper for client_referrer to create a fake referrer
4206 * based on a string supplied by the user.
4209 * 1 : header = Pointer to header pointer
4210 * 2 : hosthost = Referrer to fake
4212 * Returns : JB_ERR_OK in case of success, or
4213 * JB_ERR_MEMORY in case of memory problems.
4215 *********************************************************************/
4216 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4218 assert(NULL == *header);
4220 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4222 log_error(LOG_LEVEL_HEADER,
4223 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4225 *header = strdup("Referer: ");
4226 string_append(header, fake_referrer);
4228 if (NULL == *header)
4230 return JB_ERR_MEMORY;
4233 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4240 /*********************************************************************
4242 * Function : handle_conditional_hide_referrer_parameter
4244 * Description : Helper for client_referrer to crunch or forge
4245 * the referrer header if the host has changed.
4248 * 1 : header = Pointer to header pointer
4249 * 2 : host = The target host (may include the port)
4250 * 3 : parameter_conditional_block = Boolean to signal
4251 * if we're in conditional-block mode. If not set,
4252 * we're in conditional-forge mode.
4254 * Returns : JB_ERR_OK in case of success, or
4255 * JB_ERR_MEMORY in case of memory problems.
4257 *********************************************************************/
4258 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4259 const char *host, const int parameter_conditional_block)
4261 char *referer = strdup(*header);
4262 const size_t hostlenght = strlen(host);
4264 if (NULL == referer)
4267 return JB_ERR_MEMORY;
4270 /* referer begins with 'Referer: http[s]://' */
4271 if (hostlenght < (strlen(referer)-17))
4274 * Shorten referer to make sure the referer is blocked
4275 * if www.example.org/www.example.com-shall-see-the-referer/
4276 * links to www.example.com/
4278 referer[hostlenght+17] = '\0';
4280 if (NULL == strstr(referer, host))
4282 /* Host has changed */
4283 if (parameter_conditional_block)
4285 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4292 return create_forged_referrer(header, host);