1 const char parsers_rcs[] = "$Id: parsers.c,v 1.119 2007/12/28 18:32:51 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.119 2007/12/28 18:32:51 fabiankeil
48 * In server_content_type():
49 * - Don't require leading white space when detecting image content types.
50 * - Change '... not replaced ...' message to sound less crazy if the text
51 * type actually is 'text/plain'.
52 * - Mark the 'text/plain == binary data' assumption for removal.
53 * - Remove a bunch of trailing white space.
55 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
56 * Minor server_content_disposition() changes:
57 * - Don't regenerate the header name all lower-case.
58 * - Some white space fixes.
59 * - Remove useless log message in case of ENOMEM.
61 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
62 * Garbage-collect the code to add a X-Forwarded-For
63 * header as it seems to be mostly used by accident.
65 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
66 * Fix a crash on mingw32 with some Last Modified times in the future.
68 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
69 * Remove a "can't happen" error block which, over
70 * time, mutated into a "guaranteed to happen" block.
72 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
73 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
74 * - Use shiny new content_filters_enabled() in client_range().
76 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
77 * I forgot about Poland.
79 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
80 * Remove Range and If-Range headers if content filtering is enabled.
82 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
83 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
84 * client_cookie_adder() to make sure send-vanilla-wafer can be
85 * controlled through tags (and thus regression-tested).
87 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
88 * - Remove "scanning headers for" log message again.
89 * - Some more whitespace fixes.
91 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
92 * Refactor client_referrer() and add conditional-forge parameter.
94 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
95 * A bunch of whitespace fixes, pointy hat to me.
97 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
98 * Fix possible memory corruption in server_http, make sure it's not
99 * executed for ordinary server headers and mark some problems for later.
101 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
102 * Let content-type-overwrite{} honour force-text-mode again.
104 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
105 * - Add prototpyes for the header parsers and make them static.
106 * - Comment out client_accept_encoding_adder() which isn't used right now.
108 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
109 * Move the ACTION_FORCE_TEXT_MODE check out of
110 * server_content_type(). Signal other functions
111 * whether or not a content type has been declared.
112 * Part of the fix for BR#1750917.
114 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
115 * Change sed() to return a jb_err in preparation for forward-override{}.
117 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
118 * Adjust "X-Filter: No" to disable dedicated header filters.
120 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
121 * Streamline client_cookie_adder().
123 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
124 * Make sure filters with dynamic jobs actually use them.
126 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
127 * - Introduce dynamic pcrs jobs that can resolve variables.
128 * - Remove unnecessary update_action_bits_for_all_tags() call.
130 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
131 * - Make tagging based on tags set by earlier taggers
132 * of the same kind possible.
133 * - Log whether or not new tags cause action bits updates
134 * (in which case a matching tag-pattern section exists).
135 * - Log if the user tries to set a tag that is already set.
137 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
138 * Introduce tags as alternative way to specify which
139 * actions apply to a request. At the moment tags can be
140 * created based on client and server headers.
142 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
143 * Log a warning if the content is compressed, filtering is
144 * enabled and Privoxy was compiled without zlib support.
147 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
148 * - Fix warnings when compiled with glibc.
149 * - Don't use crumble() for cookie crunching.
150 * - Move cookie time parsing into parse_header_time().
151 * - Let parse_header_time() return a jb_err code
152 * instead of a pointer that can only be used to
153 * check for NULL anyway.
155 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
156 * - Add better protection against malicious gzip headers.
157 * - Stop logging the first hundred bytes of decompressed content.
158 * It looks like it's working and there is always debug 16.
159 * - Log the content size after decompression in decompress_iob()
160 * instead of pcrs_filter_response().
162 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
163 * - Use dedicated header filter actions instead of abusing "filter".
164 * Replace "filter-client-headers" and "filter-client-headers"
165 * with "server-header-filter" and "client-header-filter".
166 * - Remove filter_client_header() and filter_client_header(),
167 * filter_header() now checks the shiny new
168 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
170 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
171 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
172 * - Handle "Cookie:" and "Connection:" headers a bit smarter
173 * (don't crunch them just to recreate them later on).
174 * - Add another non-standard time format for the cookie
175 * expiration date detection.
176 * - Fix a valgrind warning.
178 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
179 * Improve cookie expiration date detection.
181 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
182 * Don't run server_content_length() the first time
183 * sed() parses server headers; only adjust the
184 * Content-Length header if the page was modified.
186 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
187 * Fix log messages regarding the cookie time format
188 * (cookie and request URL were mixed up).
190 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
191 * - Let decompress_iob()
192 * - not corrupt the content if decompression fails
193 * early. (the first byte(s) were lost).
194 * - use pointer arithmetics with defined outcome for
196 * - Use a different kludge to remember a failed decompression.
198 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
199 * Search for Max-Forwards headers case-insensitive,
200 * don't generate the "501 unsupported" message for invalid
201 * Max-Forwards values and don't increase negative ones.
203 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
204 * - Let server_set_cookie() check the expiration date
205 * of cookies and don't touch the ones that are already
206 * expired. Fixes problems with low quality web applications
207 * as described in BR 932612.
209 * - Adjust comment in client_max_forwards to reality;
210 * remove invalid Max-Forwards headers.
212 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
213 * Stop filter_header() from unintentionally removing
214 * empty header lines that were enlisted by the continue
217 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
218 * - Repeat the request URL before logging any headers.
219 * Makes reading the log easier in case of simultaneous requests.
220 * - If there are more than one Content-Type headers in one request,
221 * use the first one and remove the others.
222 * - Remove "newval" variable in server_content_type().
223 * It's only used once.
225 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
226 * Correct a cast, check inflateEnd() exit code
227 * to see if we have to, replace sprintf calls
230 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
231 * Integrate a modified version of Wil Mahan's
232 * zlib patch (PR #895531).
234 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
235 * Skip empty filter files in filter_header()
236 * but don't ignore the ones that come afterwards.
237 * Fixes BR 1619208, this time for real.
239 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
240 * Reverted parts of my last commit
241 * to keep error handling working.
243 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
244 * Fixed gcc43 conversion warnings.
246 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
247 * Bringing back the "useless" localtime() call
248 * I removed in revision 1.67. On some platforms
249 * it's necessary to prevent time zone offsets.
251 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
252 * Rebuild request URL in get_destination_from_headers()
253 * to make sure redirect{pcrs command} works as expected
254 * for intercepted requests.
256 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
257 * Added get_destination_from_headers().
259 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
260 * Make pthread mutex locking more generic. Instead of
261 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
262 * and use mutex locking unless there is an _r function
263 * available. Better safe than sorry.
265 * Fixes "./configure --disable-pthread" and should result
266 * in less threading-related problems on pthread-using platforms,
267 * but it still doesn't fix BR#1122404.
269 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
270 * The special header "X-Filter: No" now disables
271 * header filtering as well.
273 * Revision 1.73 2006/09/23 13:26:38 roro
274 * Replace TABs by spaces in source code.
276 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
277 * Don't print a log message every time filter_headers is
278 * entered or left. It only creates noise without any real
281 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
282 * Fix +hide-if-modified-since{-n}.
284 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
285 * Have hide-if-modified-since interpret the random
286 * range value as minutes instead of hours. Allows
287 * more fine-grained configuration.
289 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
290 * Always have parse_header_time return a pointer
291 * that actual makes sense, even though we currently
292 * only need it to detect problems.
294 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
295 * Added config option enable-remote-http-toggle
296 * to specify if Privoxy should recognize special
297 * headers (currently only X-Filter) to change its
298 * behaviour. Disabled by default.
300 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
301 * After filtering de-chunked instances, remove
302 * "Transfer-Encoding" header entirely instead of changing
303 * it to "Transfer-Encoding: identity", which is invalid.
304 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
306 * Don't use localtime in parse_header_time. An empty time struct
307 * is good enough, it gets overwritten by strptime anyway.
309 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
310 * Use gmtime_r if available, fallback to gmtime with mutex
311 * protection for MacOSX and use vanilla gmtime for the rest.
313 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
314 * Changed client_referrer to use the right type (size_t) for
315 * hostlenght and to shorten the temporary referrer string with
316 * '\0' instead of adding a useless line break.
318 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
319 * - Back to timegm() using GnuPG's replacement if necessary.
320 * Using mktime() and localtime() could add a on hour offset if
321 * the randomize factor was big enough to lead to a summer/wintertime
324 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
326 * - Moved randomization code into pick_from_range().
328 * - Changed parse_header_time definition.
329 * time_t isn't guaranteed to be signed and
330 * if it isn't, -1 isn't available as error code.
331 * Changed some variable types in client_if_modified_since()
332 * because of the same reason.
334 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
335 * OS/2 compilation compatibility fixups
337 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
338 * Changed include from strptime.c to strptime.h
340 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
341 * Split filter-headers{} into filter-client-headers{}
342 * and filter-server-headers{}.
343 * Added parse_header_time() to share some code.
344 * Replaced timegm() with mktime().
346 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
347 * Windows service integration
349 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
350 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
352 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
353 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
354 * with what was really the latest development (the v_3_0_branch branch)
356 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
357 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
359 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
360 * Add the ability to check jpeg images for invalid
361 * lengths of comment blocks. Defensive strategy
362 * against the exploit:
363 * Microsoft Security Bulletin MS04-028
364 * Buffer Overrun in JPEG Processing (GDI+) Could
365 * Allow Code Execution (833987)
366 * Enabled with +inspect-jpegs in actions files.
368 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
369 * Excluded text/plain objects from filtering. This fixes a
370 * couple of client-crashing, download corruption and
371 * Privoxy performance issues, whose root cause lies in
372 * web servers labelling content of unknown type as text/plain.
374 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
375 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
377 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
378 * Completing the previous change
380 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
381 * Added temporary workaround for bug in PHP < 4.2.3
383 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
384 * 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.
386 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
387 * Fix typo: supressed -> suppressed
389 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
390 * Improved cookie logging
392 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
393 * Added basic support for OPTIONS and TRACE HTTP methods:
394 * - New parser function client_max_forwards which decrements
395 * the Max-Forwards HTTP header field of OPTIONS and TRACE
396 * requests by one before forwarding
397 * - New parser function client_host which extracts the host
398 * and port information from the HTTP header field if the
399 * request URI was not absolute
400 * - Don't crumble and re-add the Host: header, but only generate
401 * and append if missing
403 * Revision 1.56 2002/05/12 15:34:22 jongfoster
404 * Fixing typo in a comment
406 * Revision 1.55 2002/05/08 16:01:07 oes
407 * Optimized add_to_iob:
408 * - Use realloc instead of malloc(), memcpy(), free()
409 * - Expand to powers of two if possible, to get
410 * O(log n) reallocs instead of O(n).
411 * - Moved check for buffer limit here from chat
412 * - Report failure via returncode
414 * Revision 1.54 2002/04/02 15:03:16 oes
415 * Tiny code cosmetics
417 * Revision 1.53 2002/03/26 22:29:55 swa
418 * we have a new homepage!
420 * Revision 1.52 2002/03/24 13:25:43 swa
421 * name change related issues
423 * Revision 1.51 2002/03/13 00:27:05 jongfoster
426 * Revision 1.50 2002/03/12 01:45:35 oes
427 * More verbose logging
429 * Revision 1.49 2002/03/09 20:03:52 jongfoster
430 * - Making various functions return int rather than size_t.
431 * (Undoing a recent change). Since size_t is unsigned on
432 * Windows, functions like read_socket that return -1 on
433 * error cannot return a size_t.
435 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
436 * crashes, and also frequently caused JB to jump to 100%
437 * CPU and stay there. (Because it thought it had just
438 * read ((unsigned)-1) == 4Gb of data...)
440 * - The signature of write_socket has changed, it now simply
441 * returns success=0/failure=nonzero.
443 * - Trying to get rid of a few warnings --with-debug on
444 * Windows, I've introduced a new type "jb_socket". This is
445 * used for the socket file descriptors. On Windows, this
446 * is SOCKET (a typedef for unsigned). Everywhere else, it's
447 * an int. The error value can't be -1 any more, so it's
448 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
449 * Windows it maps to the #define INVALID_SOCKET.)
451 * - The signature of bind_port has changed.
453 * Revision 1.48 2002/03/07 03:46:53 oes
454 * Fixed compiler warnings etc
456 * Revision 1.47 2002/02/20 23:15:13 jongfoster
457 * Parsing functions now handle out-of-memory gracefully by returning
460 * Revision 1.46 2002/01/17 21:03:47 jongfoster
461 * Moving all our URL and URL pattern parsing code to urlmatch.c.
463 * Revision 1.45 2002/01/09 14:33:03 oes
464 * Added support for localtime_r.
466 * Revision 1.44 2001/12/14 01:22:54 steudten
467 * Remove 'user:pass@' from 'proto://user:pass@host' for the
468 * new added header 'Host: ..'. (See Req ID 491818)
470 * Revision 1.43 2001/11/23 00:26:38 jongfoster
471 * Fixing two really stupid errors in my previous commit
473 * Revision 1.42 2001/11/22 21:59:30 jongfoster
474 * Adding code to handle +no-cookies-keep
476 * Revision 1.41 2001/11/05 23:43:05 steudten
477 * Add time+date to log files.
479 * Revision 1.40 2001/10/26 20:13:09 jongfoster
480 * ctype.h is needed in Windows, too.
482 * Revision 1.39 2001/10/26 17:40:04 oes
483 * Introduced get_header_value()
484 * Removed http->user_agent, csp->referrer and csp->accept_types
485 * Removed client_accept()
487 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
488 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
489 * threads to call select() simultaneously. So, it's time to do a real, live,
490 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
491 * (native). Both versions will work, but using __OS2__ offers multi-threading.
493 * Revision 1.37 2001/10/23 21:36:02 jongfoster
494 * Documenting sed()'s error behaviou (doc change only)
496 * Revision 1.36 2001/10/13 12:51:51 joergs
497 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
498 * force-load), instead crumble Host: and add it (again) in client_host_adder
499 * (in case we get a HTTP/1.0 request without Host: header and forward it to
500 * a HTTP/1.1 server/proxy).
502 * Revision 1.35 2001/10/09 22:39:21 jongfoster
503 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
506 * Revision 1.34 2001/10/07 18:50:55 oes
507 * Added server_content_encoding, renamed server_transfer_encoding
509 * Revision 1.33 2001/10/07 18:04:49 oes
510 * Changed server_http11 to server_http and its pattern to "HTTP".
511 * Additional functionality: it now saves the HTTP status into
512 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
514 * Revision 1.32 2001/10/07 15:43:28 oes
515 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
516 * client_te and client_accept_encoding_adder, triggered by the new
517 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
518 * changed to allow only identity and chunked, and the TE header is
519 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
521 * parse_http_request no longer does anything than parsing. The rewriting
522 * of http->cmd and version mangling are gone. It now also recognizes
523 * the put and delete methods and saves the url in http->url. Removed
526 * renamed content_type and content_length to have the server_ prefix
528 * server_content_type now only works if csp->content_type != CT_TABOO
530 * added server_transfer_encoding, which
531 * - Sets CT_TABOO to prohibit filtering if encoding compresses
532 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
533 * - Change from "chunked" to "identity" if body was chunked
534 * but has been de-chunked for filtering.
536 * added server_content_md5 which crunches any Content-MD5 headers
537 * if the body was modified.
539 * made server_http11 conditional on +downgrade action
541 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
543 * Revision 1.31 2001/10/05 14:25:02 oes
544 * Crumble Keep-Alive from Server
546 * Revision 1.30 2001/09/29 12:56:03 joergs
547 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
549 * Revision 1.29 2001/09/24 21:09:24 jongfoster
550 * Fixing 2 memory leaks that Guy spotted, where the paramater to
551 * enlist() was not being free()d.
553 * Revision 1.28 2001/09/22 16:32:28 jongfoster
554 * Removing unused #includes.
556 * Revision 1.27 2001/09/20 15:45:25 steudten
558 * add casting from size_t to int for printf()
559 * remove local variable shadow s2
561 * Revision 1.26 2001/09/16 17:05:14 jongfoster
562 * Removing unused #include showarg.h
564 * Revision 1.25 2001/09/16 13:21:27 jongfoster
565 * Changes to use new list functions.
567 * Revision 1.24 2001/09/13 23:05:50 jongfoster
568 * Changing the string paramater to the header parsers a "const".
570 * Revision 1.23 2001/09/12 18:08:19 steudten
572 * In parse_http_request() header rewriting miss the host value, so
573 * from http://www.mydomain.com the result was just " / " not
574 * http://www.mydomain.com/ in case we forward.
576 * Revision 1.22 2001/09/10 10:58:53 oes
577 * Silenced compiler warnings
579 * Revision 1.21 2001/07/31 14:46:00 oes
580 * - Persistant connections now suppressed
581 * - sed() no longer appends empty header to csp->headers
583 * Revision 1.20 2001/07/30 22:08:36 jongfoster
584 * Tidying up #defines:
585 * - All feature #defines are now of the form FEATURE_xxx
586 * - Permanently turned off WIN_GUI_EDIT
587 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
589 * Revision 1.19 2001/07/25 17:21:54 oes
590 * client_uagent now saves copy of User-Agent: header value
592 * Revision 1.18 2001/07/13 14:02:46 oes
593 * - Included fix to repair broken HTTP requests that
594 * don't contain a path, not even '/'.
595 * - Removed all #ifdef PCRS
596 * - content_type now always inspected and classified as
597 * text, gif or other.
598 * - formatting / comments
600 * Revision 1.17 2001/06/29 21:45:41 oes
601 * Indentation, CRLF->LF, Tab-> Space
603 * Revision 1.16 2001/06/29 13:32:42 oes
605 * - Adapted free_http_request
606 * - Removed logentry from cancelled commit
608 * Revision 1.15 2001/06/03 19:12:38 oes
609 * deleted const struct interceptors
611 * Revision 1.14 2001/06/01 18:49:17 jongfoster
612 * Replaced "list_share" with "list" - the tiny memory gain was not
613 * worth the extra complexity.
615 * Revision 1.13 2001/05/31 21:30:33 jongfoster
616 * Removed list code - it's now in list.[ch]
617 * Renamed "permission" to "action", and changed many features
618 * to use the actions file rather than the global config.
620 * Revision 1.12 2001/05/31 17:33:13 oes
624 * Revision 1.11 2001/05/29 20:11:19 joergs
625 * '/ * inside comment' warning removed.
627 * Revision 1.10 2001/05/29 09:50:24 jongfoster
628 * Unified blocklist/imagelist/permissionslist.
629 * File format is still under discussion, but the internal changes
632 * Also modified interceptor behaviour:
633 * - We now intercept all URLs beginning with one of the following
634 * prefixes (and *only* these prefixes):
636 * * http://ijbswa.sf.net/config/
637 * * http://ijbswa.sourceforge.net/config/
638 * - New interceptors "home page" - go to http://i.j.b/ to see it.
639 * - Internal changes so that intercepted and fast redirect pages
640 * are not replaced with an image.
641 * - Interceptors now have the option to send a binary page direct
642 * to the client. (i.e. ijb-send-banner uses this)
643 * - Implemented show-url-info interceptor. (Which is why I needed
644 * the above interceptors changes - a typical URL is
645 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
646 * The previous mechanism would not have intercepted that, and
647 * if it had been intercepted then it then it would have replaced
650 * Revision 1.9 2001/05/28 17:26:33 jongfoster
651 * Fixing segfault if last header was crunched.
652 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
653 * can use the cross-platform sprintf() instead.)
655 * Revision 1.8 2001/05/27 22:17:04 oes
657 * - re_process_buffer no longer writes the modified buffer
658 * to the client, which was very ugly. It now returns the
659 * buffer, which it is then written by chat.
661 * - content_length now adjusts the Content-Length: header
662 * for modified documents rather than crunch()ing it.
663 * (Length info in csp->content_length, which is 0 for
664 * unmodified documents)
666 * - For this to work, sed() is called twice when filtering.
668 * Revision 1.7 2001/05/27 13:19:06 oes
669 * Patched Joergs solution for the content-length in.
671 * Revision 1.6 2001/05/26 13:39:32 jongfoster
672 * Only crunches Content-Length header if applying RE filtering.
673 * Without this fix, Microsoft Windows Update wouldn't work.
675 * Revision 1.5 2001/05/26 00:28:36 jongfoster
676 * Automatic reloading of config file.
677 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
678 * Most of the global variables have been moved to a new
679 * struct configuration_spec, accessed through csp->config->globalname
680 * Most of the globals remaining are used by the Win32 GUI.
682 * Revision 1.4 2001/05/22 18:46:04 oes
684 * - Enabled filtering banners by size rather than URL
685 * by adding patterns that replace all standard banner
686 * sizes with the "Junkbuster" gif to the re_filterfile
688 * - Enabled filtering WebBugs by providing a pattern
689 * which kills all 1x1 images
691 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
692 * which is selected by the (nonstandard and therefore
693 * capital) letter 'U' in the option string.
694 * It causes the quantifiers to be ungreedy by default.
695 * Appending a ? turns back to greedy (!).
697 * - Added a new interceptor ijb-send-banner, which
698 * sends back the "Junkbuster" gif. Without imagelist or
699 * MSIE detection support, or if tinygif = 1, or the
700 * URL isn't recognized as an imageurl, a lame HTML
701 * explanation is sent instead.
703 * - Added new feature, which permits blocking remote
704 * script redirects and firing back a local redirect
706 * The feature is conditionally compiled, i.e. it
707 * can be disabled with --disable-fast-redirects,
708 * plus it must be activated by a "fast-redirects"
709 * line in the config file, has its own log level
710 * and of course wants to be displayed by show-proxy-args
711 * Note: Boy, all the #ifdefs in 1001 locations and
712 * all the fumbling with configure.in and acconfig.h
713 * were *way* more work than the feature itself :-(
715 * - Because a generic redirect template was needed for
716 * this, tinygif = 3 now uses the same.
718 * - Moved GIFs, and other static HTTP response templates
723 * - Removed some >400 CRs again (Jon, you really worked
726 * Revision 1.3 2001/05/20 01:21:20 jongfoster
727 * Version 2.9.4 checkin.
728 * - Merged popupfile and cookiefile, and added control over PCRS
729 * filtering, in new "permissionsfile".
730 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
731 * file error you now get a message box (in the Win32 GUI) rather
732 * than the program exiting with no explanation.
733 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
735 * - Removed tabs from "config"
736 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
737 * - Bumped up version number.
739 * Revision 1.2 2001/05/17 23:02:36 oes
740 * - Made referrer option accept 'L' as a substitute for '§'
742 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
743 * Initial import of version 2.9.3 source tree
746 *********************************************************************/
753 #include <sys/types.h>
763 * Convince GNU's libc to provide a strptime prototype.
766 #endif /*__GLIBC__ */
773 #if !defined(_WIN32) && !defined(__OS2__)
779 #ifdef FEATURE_PTHREAD
781 /* jcc.h is for mutex semapores only */
782 #endif /* def FEATURE_PTHREAD */
788 #include "jbsockets.h"
789 #include "miscutil.h"
794 #ifndef HAVE_STRPTIME
795 #include "strptime.h"
798 const char parsers_h_rcs[] = PARSERS_H_VERSION;
800 /* Fix a problem with Solaris. There should be no effect on other
802 * Solaris's isspace() is a macro which uses its argument directly
803 * as an array index. Therefore we need to make sure that high-bit
804 * characters generate +ve values, and ideally we also want to make
805 * the argument match the declared parameter type of "int".
807 * Why did they write a character function that can't take a simple
808 * "char" argument? Doh!
810 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
811 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
813 static jb_err scan_headers(struct client_state *csp);
814 static jb_err header_tagger(struct client_state *csp, char *header);
815 static jb_err parse_header_time(const char *header_time, time_t *result);
817 static jb_err crumble (struct client_state *csp, char **header);
818 static jb_err connection (struct client_state *csp, char **header);
819 static jb_err filter_header (struct client_state *csp, char **header);
820 static jb_err client_referrer (struct client_state *csp, char **header);
821 static jb_err client_uagent (struct client_state *csp, char **header);
822 static jb_err client_ua (struct client_state *csp, char **header);
823 static jb_err client_from (struct client_state *csp, char **header);
824 static jb_err client_send_cookie (struct client_state *csp, char **header);
825 static jb_err client_x_forwarded (struct client_state *csp, char **header);
826 static jb_err client_accept_encoding (struct client_state *csp, char **header);
827 static jb_err client_te (struct client_state *csp, char **header);
828 static jb_err client_max_forwards (struct client_state *csp, char **header);
829 static jb_err client_host (struct client_state *csp, char **header);
830 static jb_err client_if_modified_since (struct client_state *csp, char **header);
831 static jb_err client_accept_language (struct client_state *csp, char **header);
832 static jb_err client_if_none_match (struct client_state *csp, char **header);
833 static jb_err crunch_client_header (struct client_state *csp, char **header);
834 static jb_err client_x_filter (struct client_state *csp, char **header);
835 static jb_err client_range (struct client_state *csp, char **header);
836 static jb_err server_set_cookie (struct client_state *csp, char **header);
837 static jb_err server_content_type (struct client_state *csp, char **header);
838 static jb_err server_content_length (struct client_state *csp, char **header);
839 static jb_err server_content_md5 (struct client_state *csp, char **header);
840 static jb_err server_content_encoding (struct client_state *csp, char **header);
841 static jb_err server_transfer_coding (struct client_state *csp, char **header);
842 static jb_err server_http (struct client_state *csp, char **header);
843 static jb_err crunch_server_header (struct client_state *csp, char **header);
844 static jb_err server_last_modified (struct client_state *csp, char **header);
845 static jb_err server_content_disposition(struct client_state *csp, char **header);
847 static jb_err client_host_adder (struct client_state *csp);
848 static jb_err client_cookie_adder (struct client_state *csp);
849 static jb_err client_xtra_adder (struct client_state *csp);
850 static jb_err connection_close_adder (struct client_state *csp);
852 static jb_err create_forged_referrer(char **header, const char *hostport);
853 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
854 static jb_err handle_conditional_hide_referrer_parameter(char **header,
855 const char *host, const int parameter_conditional_block);
857 const struct parsers client_patterns[] = {
858 { "referer:", 8, client_referrer },
859 { "user-agent:", 11, client_uagent },
860 { "ua-", 3, client_ua },
861 { "from:", 5, client_from },
862 { "cookie:", 7, client_send_cookie },
863 { "x-forwarded-for:", 16, client_x_forwarded },
864 { "Accept-Encoding:", 16, client_accept_encoding },
865 { "TE:", 3, client_te },
866 { "Host:", 5, client_host },
867 { "if-modified-since:", 18, client_if_modified_since },
868 { "Keep-Alive:", 11, crumble },
869 { "connection:", 11, connection },
870 { "proxy-connection:", 17, crumble },
871 { "max-forwards:", 13, client_max_forwards },
872 { "Accept-Language:", 16, client_accept_language },
873 { "if-none-match:", 14, client_if_none_match },
874 { "Range:", 6, client_range },
875 { "If-Range:", 9, client_range },
876 { "X-Filter:", 9, client_x_filter },
877 { "*", 0, crunch_client_header },
878 { "*", 0, filter_header },
882 const struct parsers server_patterns[] = {
883 { "HTTP/", 5, server_http },
884 { "set-cookie:", 11, server_set_cookie },
885 { "connection:", 11, connection },
886 { "Content-Type:", 13, server_content_type },
887 { "Content-MD5:", 12, server_content_md5 },
888 { "Content-Encoding:", 17, server_content_encoding },
889 { "Transfer-Encoding:", 18, server_transfer_coding },
890 { "Keep-Alive:", 11, crumble },
891 { "content-disposition:", 20, server_content_disposition },
892 { "Last-Modified:", 14, server_last_modified },
893 { "*", 0, crunch_server_header },
894 { "*", 0, filter_header },
898 const struct parsers server_patterns_light[] = {
899 { "Content-Length:", 15, server_content_length },
900 { "Transfer-Encoding:", 18, server_transfer_coding },
902 { "Content-Encoding:", 17, server_content_encoding },
903 #endif /* def FEATURE_ZLIB */
907 const add_header_func_ptr add_client_headers[] = {
911 /* Temporarily disabled: client_accept_encoding_adder, */
912 connection_close_adder,
916 const add_header_func_ptr add_server_headers[] = {
917 connection_close_adder,
921 /* The vanilla wafer. */
922 static const char VANILLA_WAFER[] =
923 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
924 "Do_not_send_me_any_copyrighted_information_other_than_the_"
925 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
926 "In_particular_do_not_send_me_any_cookies_that_"
927 "are_subject_to_a_claim_of_copyright_by_anybody._"
928 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
929 "(copyright_or_otherwise)_applying_to_any_cookie._";
931 /*********************************************************************
933 * Function : flush_socket
935 * Description : Write any pending "buffered" content.
938 * 1 : fd = file descriptor of the socket to read
939 * 2 : csp = Current client state (buffers, headers, etc...)
941 * Returns : On success, the number of bytes written are returned (zero
942 * indicates nothing was written). On error, -1 is returned,
943 * and errno is set appropriately. If count is zero and the
944 * file descriptor refers to a regular file, 0 will be
945 * returned without causing any other effect. For a special
946 * file, the results are not portable.
948 *********************************************************************/
949 int flush_socket(jb_socket fd, struct client_state *csp)
951 struct iob *iob = csp->iob;
952 int len = iob->eod - iob->cur;
959 if (write_socket(fd, iob->cur, (size_t)len))
963 iob->eod = iob->cur = iob->buf;
969 /*********************************************************************
971 * Function : add_to_iob
973 * Description : Add content to the buffered page, expanding the
974 * buffer if necessary.
977 * 1 : csp = Current client state (buffers, headers, etc...)
978 * 2 : buf = holds the content to be added to the page
979 * 3 : n = number of bytes to be added
981 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
982 * or buffer limit reached.
984 *********************************************************************/
985 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
987 struct iob *iob = csp->iob;
988 size_t used, offset, need, want;
991 if (n <= 0) return JB_ERR_OK;
993 used = (size_t)(iob->eod - iob->buf);
994 offset = (size_t)(iob->cur - iob->buf);
995 need = used + (size_t)n + 1;
998 * If the buffer can't hold the new data, extend it first.
999 * Use the next power of two if possible, else use the actual need.
1001 if (need > csp->config->buffer_limit)
1003 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1004 return JB_ERR_MEMORY;
1007 if (need > iob->size)
1009 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1011 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1015 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1021 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1022 return JB_ERR_MEMORY;
1025 /* Update the iob pointers */
1026 iob->cur = p + offset;
1027 iob->eod = p + used;
1031 /* copy the new data into the iob buffer */
1032 memcpy(iob->eod, buf, (size_t)n);
1034 /* point to the end of the data */
1037 /* null terminate == cheap insurance */
1046 /*********************************************************************
1048 * Function : decompress_iob
1050 * Description : Decompress buffered page, expanding the
1051 * buffer as necessary. csp->iob->cur
1052 * should point to the the beginning of the
1053 * compressed data block.
1056 * 1 : csp = Current client state (buffers, headers, etc...)
1058 * Returns : JB_ERR_OK on success,
1059 * JB_ERR_MEMORY if out-of-memory limit reached, and
1060 * JB_ERR_COMPRESS if error decompressing buffer.
1062 *********************************************************************/
1063 jb_err decompress_iob(struct client_state *csp)
1065 char *buf; /* new, uncompressed buffer */
1066 char *cur; /* Current iob position (to keep the original
1067 * iob->cur unmodified if we return early) */
1068 size_t bufsize; /* allocated size of the new buffer */
1069 size_t old_size; /* Content size before decompression */
1070 size_t skip_size; /* Number of bytes at the beginning of the iob
1071 that we should NOT decompress. */
1072 int status; /* return status of the inflate() call */
1073 z_stream zstr; /* used by calls to zlib */
1075 assert(csp->iob->cur - csp->iob->buf > 0);
1076 assert(csp->iob->eod - csp->iob->cur > 0);
1078 bufsize = csp->iob->size;
1079 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1080 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1082 cur = csp->iob->cur;
1087 * This is to protect the parsing of gzipped data,
1088 * but it should(?) be valid for deflated data also.
1090 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1091 return JB_ERR_COMPRESS;
1094 if (csp->content_type & CT_GZIP)
1097 * Our task is slightly complicated by the facts that data
1098 * compressed by gzip does not include a zlib header, and
1099 * that there is no easily accessible interface in zlib to
1100 * handle a gzip header. We strip off the gzip header by
1101 * hand, and later inform zlib not to expect a header.
1105 * Strip off the gzip header. Please see RFC 1952 for more
1106 * explanation of the appropriate fields.
1108 if ((*cur++ != (char)0x1f)
1109 || (*cur++ != (char)0x8b)
1110 || (*cur++ != Z_DEFLATED))
1112 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1113 return JB_ERR_COMPRESS;
1119 * XXX: These magic numbers should be replaced
1120 * with macros to give a better idea what they do.
1124 /* The gzip header has reserved bits set; bail out. */
1125 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1126 return JB_ERR_COMPRESS;
1130 /* Skip extra fields if necessary. */
1134 * Skip a given number of bytes, specified
1135 * as a 16-bit little-endian value.
1138 * XXX: This code used to be:
1140 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1142 * which I had to change into:
1144 * cur += *cur++ + (*cur++ << 8);
1146 * at which point gcc43 finally noticed that the value
1147 * of cur is undefined (it depends on which of the
1148 * summands is evaluated first).
1150 * I haven't come across a site where this
1151 * code is actually executed yet, but I hope
1155 skip_bytes = *cur++;
1156 skip_bytes = *cur++ << 8;
1158 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1161 * The number of bytes to skip should be positive
1162 * and we'd like to stay in the buffer.
1164 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1166 log_error(LOG_LEVEL_ERROR,
1167 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1169 return JB_ERR_COMPRESS;
1171 log_error(LOG_LEVEL_INFO,
1172 "Skipping %d bytes for gzip compression. Does this sound right?",
1177 /* Skip the filename if necessary. */
1180 /* A null-terminated string is supposed to follow. */
1181 while (*cur++ && (cur < csp->iob->eod));
1185 /* Skip the comment if necessary. */
1188 /* A null-terminated string is supposed to follow. */
1189 while (*cur++ && (cur < csp->iob->eod));
1192 /* Skip the CRC if necessary. */
1198 if (cur >= csp->iob->eod)
1201 * If the current position pointer reached or passed
1202 * the buffer end, we were obviously tricked to skip
1205 log_error(LOG_LEVEL_ERROR,
1206 "Malformed gzip header detected. Aborting decompression.");
1207 return JB_ERR_COMPRESS;
1211 else if (csp->content_type & CT_DEFLATE)
1214 * XXX: The debug level should be lowered
1215 * before the next stable release.
1217 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1219 * In theory (that is, according to RFC 1950), deflate-compressed
1220 * data should begin with a two-byte zlib header and have an
1221 * adler32 checksum at the end. It seems that in practice only
1222 * the raw compressed data is sent. Note that this means that
1223 * we are not RFC 1950-compliant here, but the advantage is that
1224 * this actually works. :)
1226 * We add a dummy null byte to tell zlib where the data ends,
1227 * and later inform it not to expect a header.
1229 * Fortunately, add_to_iob() has thoughtfully null-terminated
1230 * the buffer; we can just increment the end pointer to include
1237 log_error(LOG_LEVEL_ERROR,
1238 "Unable to determine compression format for decompression");
1239 return JB_ERR_COMPRESS;
1242 /* Set up the fields required by zlib. */
1243 zstr.next_in = (Bytef *)cur;
1244 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1245 zstr.zalloc = Z_NULL;
1246 zstr.zfree = Z_NULL;
1247 zstr.opaque = Z_NULL;
1250 * Passing -MAX_WBITS to inflateInit2 tells the library
1251 * that there is no zlib header.
1253 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1255 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1256 return JB_ERR_COMPRESS;
1260 * Next, we allocate new storage for the inflated data.
1261 * We don't modify the existing iob yet, so in case there
1262 * is error in decompression we can recover gracefully.
1264 buf = zalloc(bufsize);
1267 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1268 return JB_ERR_MEMORY;
1271 assert(bufsize >= skip_size);
1272 memcpy(buf, csp->iob->buf, skip_size);
1273 zstr.avail_out = bufsize - skip_size;
1274 zstr.next_out = (Bytef *)buf + skip_size;
1276 /* Try to decompress the whole stream in one shot. */
1277 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1279 /* We need to allocate more memory for the output buffer. */
1281 char *tmpbuf; /* used for realloc'ing the buffer */
1282 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1285 * If zlib wants more data then there's a problem, because
1286 * the complete compressed file should have been buffered.
1288 if (0 == zstr.avail_in)
1290 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1291 return JB_ERR_COMPRESS;
1295 * If we tried the limit and still didn't have enough
1296 * memory, just give up.
1298 if (bufsize == csp->config->buffer_limit)
1300 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1301 return JB_ERR_MEMORY;
1304 /* Try doubling the buffer size each time. */
1307 /* Don't exceed the buffer limit. */
1308 if (bufsize > csp->config->buffer_limit)
1310 bufsize = csp->config->buffer_limit;
1313 /* Try to allocate the new buffer. */
1314 tmpbuf = realloc(buf, bufsize);
1317 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1319 return JB_ERR_MEMORY;
1323 char *oldnext_out = (char *)zstr.next_out;
1326 * Update the fields for inflate() to use the new
1327 * buffer, which may be in a location different from
1330 zstr.avail_out += bufsize - oldbufsize;
1331 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1334 * Compare with an uglier method of calculating these values
1335 * that doesn't require the extra oldbufsize variable.
1337 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1338 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1339 assert(zstr.avail_out > 0);
1345 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1347 log_error(LOG_LEVEL_ERROR,
1348 "Inconsistent stream state after decompression: %s", zstr.msg);
1350 * XXX: Intentionally no return.
1352 * According to zlib.h, Z_STREAM_ERROR is returned
1353 * "if the stream state was inconsistent".
1355 * I assume in this case inflate()'s status
1356 * would also be something different than Z_STREAM_END
1357 * so this check should be redundant, but lets see.
1361 if (status != Z_STREAM_END)
1363 /* We failed to decompress the stream. */
1364 log_error(LOG_LEVEL_ERROR,
1365 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1366 return JB_ERR_COMPRESS;
1370 * Finally, we can actually update the iob, since the
1371 * decompression was successful. First, free the old
1374 freez(csp->iob->buf);
1376 /* Now, update the iob to use the new buffer. */
1377 csp->iob->buf = buf;
1378 csp->iob->cur = csp->iob->buf + skip_size;
1379 csp->iob->eod = (char *)zstr.next_out;
1380 csp->iob->size = bufsize;
1383 * Make sure the new uncompressed iob obeys some minimal
1384 * consistency conditions.
1386 if ((csp->iob->buf < csp->iob->cur)
1387 && (csp->iob->cur <= csp->iob->eod)
1388 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1390 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1393 log_error(LOG_LEVEL_RE_FILTER,
1394 "Decompression successful. Old size: %d, new size: %d.",
1395 old_size, new_size);
1399 /* zlib thinks this is OK, so lets do the same. */
1400 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1405 /* It seems that zlib did something weird. */
1406 log_error(LOG_LEVEL_ERROR,
1407 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1408 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1409 csp->iob->eod, csp->iob->buf + csp->iob->size);
1410 return JB_ERR_COMPRESS;
1416 #endif /* defined(FEATURE_ZLIB) */
1419 /*********************************************************************
1421 * Function : get_header
1423 * Description : This (odd) routine will parse the csp->iob
1426 * 1 : csp = Current client state (buffers, headers, etc...)
1428 * Returns : Any one of the following:
1430 * 1) a pointer to a dynamically allocated string that contains a header line
1431 * 2) NULL indicating that the end of the header was reached
1432 * 3) "" indicating that the end of the iob was reached before finding
1433 * a complete header line.
1435 *********************************************************************/
1436 char *get_header(struct client_state *csp)
1442 if ((iob->cur == NULL)
1443 || ((p = strchr(iob->cur, '\n')) == NULL))
1445 return(""); /* couldn't find a complete header */
1450 ret = strdup(iob->cur);
1453 /* FIXME No way to handle error properly */
1454 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1459 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1461 /* is this a blank line (i.e. the end of the header) ? */
1473 /*********************************************************************
1475 * Function : get_header_value
1477 * Description : Get the value of a given header from a chained list
1478 * of header lines or return NULL if no such header is
1479 * present in the list.
1482 * 1 : header_list = pointer to list
1483 * 2 : header_name = string with name of header to look for.
1484 * Trailing colon required, capitalization
1487 * Returns : NULL if not found, else value of header
1489 *********************************************************************/
1490 char *get_header_value(const struct list *header_list, const char *header_name)
1492 struct list_entry *cur_entry;
1496 assert(header_list);
1497 assert(header_name);
1498 length = strlen(header_name);
1500 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1504 if (!strncmpic(cur_entry->str, header_name, length))
1507 * Found: return pointer to start of value
1509 ret = (char *) (cur_entry->str + length);
1510 while (*ret && ijb_isspace(*ret)) ret++;
1524 /*********************************************************************
1526 * Function : scan_headers
1528 * Description : Scans headers, applies tags and updates action bits.
1531 * 1 : csp = Current client state (buffers, headers, etc...)
1533 * Returns : JB_ERR_OK
1535 *********************************************************************/
1536 static jb_err scan_headers(struct client_state *csp)
1538 struct list_entry *h; /* Header */
1539 jb_err err = JB_ERR_OK;
1541 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1543 /* Header crunch()ed in previous run? -> ignore */
1544 if (h->str == NULL) continue;
1545 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1546 err = header_tagger(csp, h->str);
1553 /*********************************************************************
1557 * Description : add, delete or modify lines in the HTTP header streams.
1558 * On entry, it receives a linked list of headers space
1559 * that was allocated dynamically (both the list nodes
1560 * and the header contents).
1562 * As a side effect it frees the space used by the original
1565 * XXX: should be split to remove the first_run hack.
1568 * 1 : pats = list of patterns to match against headers
1569 * 2 : more_headers = list of functions to add more
1570 * headers (client or server)
1571 * 3 : csp = Current client state (buffers, headers, etc...)
1573 * Returns : JB_ERR_OK in case off success, or
1574 * JB_ERR_MEMORY on out-of-memory error.
1576 *********************************************************************/
1577 jb_err sed(const struct parsers pats[],
1578 const add_header_func_ptr more_headers[],
1579 struct client_state *csp)
1581 struct list_entry *p;
1582 const struct parsers *v;
1583 const add_header_func_ptr *f;
1584 jb_err err = JB_ERR_OK;
1588 * If filtering is enabled, sed is run twice,
1589 * but most of the work needs to be done only once.
1591 first_run = (more_headers != NULL ) ? 1 : 0;
1593 if (first_run) /* Parse and print */
1597 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1599 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1601 /* Header crunch()ed in previous run? -> ignore */
1602 if (p->str == NULL) continue;
1604 /* Does the current parser handle this header? */
1605 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1607 err = v->parser(csp, (char **)&(p->str));
1611 /* place any additional headers on the csp->headers list */
1612 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1617 else /* Parse only */
1620 * The second run is only needed if the body was modified
1621 * and the content-lenght has changed.
1623 if (strncmpic(csp->http->cmd, "HEAD", 4))
1625 /*XXX: Code duplication */
1626 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1628 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1630 /* Header crunch()ed in previous run? -> ignore */
1631 if (p->str == NULL) continue;
1633 /* Does the current parser handle this header? */
1634 if (strncmpic(p->str, v->str, v->len) == 0)
1636 err = v->parser(csp, (char **)&(p->str));
1648 /*********************************************************************
1650 * Function : header_tagger
1652 * Description : Executes all text substitutions from applying
1653 * tag actions and saves the result as tag.
1655 * XXX: Shares enough code with filter_header() and
1656 * pcrs_filter_response() to warrant some helper functions.
1659 * 1 : csp = Current client state (buffers, headers, etc...)
1660 * 2 : header = Header that is used as tagger input
1662 * Returns : JB_ERR_OK on success and always succeeds
1664 *********************************************************************/
1665 static jb_err header_tagger(struct client_state *csp, char *header)
1667 int wanted_filter_type;
1668 int multi_action_index;
1672 struct file_list *fl;
1673 struct re_filterfile_spec *b;
1674 struct list_entry *tag_name;
1676 int found_filters = 0;
1677 const size_t header_length = strlen(header);
1679 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1681 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1682 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1686 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1687 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1690 /* Check if there are any filters */
1691 for (i = 0; i < MAX_AF_FILES; i++)
1704 if (0 == found_filters)
1706 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1707 "tagging enabled, but no taggers available.");
1711 for (i = 0; i < MAX_AF_FILES; i++)
1714 if ((NULL == fl) || (NULL == fl->f))
1717 * Either there are no filter files
1718 * left, or this filter file just
1719 * contains no valid filters.
1721 * Continue to be sure we don't miss
1722 * valid filter files that are chained
1723 * after empty or invalid ones.
1728 /* For all filters, */
1729 for (b = fl->f; b; b = b->next)
1731 if (b->type != wanted_filter_type)
1733 /* skip the ones we don't care about, */
1736 /* leaving only taggers that could apply, of which we use the ones, */
1737 for (tag_name = csp->action->multi[multi_action_index]->first;
1738 NULL != tag_name; tag_name = tag_name->next)
1740 /* that do apply, and */
1741 if (strcmp(b->name, tag_name->str) == 0)
1743 char *modified_tag = NULL;
1745 size_t size = header_length;
1746 pcrs_job *joblist = b->joblist;
1748 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1750 if (NULL == joblist)
1752 log_error(LOG_LEVEL_RE_FILTER,
1753 "Tagger %s has empty joblist. Nothing to do.", b->name);
1757 /* execute their pcrs_joblist on the header. */
1758 for (job = joblist; NULL != job; job = job->next)
1760 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1764 /* Success, continue with the modified version. */
1773 /* Tagger doesn't match */
1776 /* Regex failure, log it but continue anyway. */
1777 log_error(LOG_LEVEL_ERROR,
1778 "Problems with tagger \'%s\' and header \'%s\': %s",
1779 b->name, *header, pcrs_strerror(hits));
1781 freez(modified_tag);
1785 if (b->dynamic) pcrs_free_joblist(joblist);
1787 /* If this tagger matched */
1793 * There is to technical limitation which makes
1794 * it impossible to use empty tags, but I assume
1795 * no one would do it intentionally.
1798 log_error(LOG_LEVEL_INFO,
1799 "Tagger \'%s\' created an empty tag. Ignored.",
1804 if (!list_contains_item(csp->tags, tag))
1806 if (JB_ERR_OK != enlist(csp->tags, tag))
1808 log_error(LOG_LEVEL_ERROR,
1809 "Insufficient memory to add tag \'%s\', "
1810 "based on tagger \'%s\' and header \'%s\'",
1811 tag, b->name, *header);
1815 char *action_message;
1817 * update the action bits right away, to make
1818 * tagging based on tags set by earlier taggers
1819 * of the same kind possible.
1821 if (update_action_bits_for_tag(csp, tag))
1823 action_message = "Action bits updated accordingly.";
1827 action_message = "No action bits update necessary.";
1830 log_error(LOG_LEVEL_HEADER,
1831 "Tagger \'%s\' added tag \'%s\'. %s",
1832 b->name, tag, action_message);
1837 /* XXX: Is this log-worthy? */
1838 log_error(LOG_LEVEL_HEADER,
1839 "Tagger \'%s\' didn't add tag \'%s\'. "
1840 "Tag already present", b->name, tag);
1843 } /* if the tagger matched */
1844 } /* if the tagger applies */
1845 } /* for every tagger that could apply */
1846 } /* for all filters */
1847 } /* for all filter files */
1852 /* here begins the family of parser functions that reformat header lines */
1854 /*********************************************************************
1856 * Function : filter_header
1858 * Description : Executes all text substitutions from all applying
1859 * +(server|client)-header-filter actions on the header.
1860 * Most of the code was copied from pcrs_filter_response,
1861 * including the rather short variable names
1864 * 1 : csp = Current client state (buffers, headers, etc...)
1865 * 2 : header = On input, pointer to header to modify.
1866 * On output, pointer to the modified header, or NULL
1867 * to remove the header. This function frees the
1868 * original string if necessary.
1870 * Returns : JB_ERR_OK on success and always succeeds
1872 *********************************************************************/
1873 static jb_err filter_header(struct client_state *csp, char **header)
1877 size_t size = strlen(*header);
1879 char *newheader = NULL;
1882 struct file_list *fl;
1883 struct re_filterfile_spec *b;
1884 struct list_entry *filtername;
1886 int i, found_filters = 0;
1887 int wanted_filter_type;
1888 int multi_action_index;
1890 if (csp->flags & CSP_FLAG_NO_FILTERING)
1895 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1897 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1898 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1902 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1903 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1907 * Need to check the set of re_filterfiles...
1909 for (i = 0; i < MAX_AF_FILES; i++)
1922 if (0 == found_filters)
1924 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1925 "header filtering enabled, but no matching filters available.");
1929 for (i = 0; i < MAX_AF_FILES; i++)
1932 if ((NULL == fl) || (NULL == fl->f))
1935 * Either there are no filter files
1936 * left, or this filter file just
1937 * contains no valid filters.
1939 * Continue to be sure we don't miss
1940 * valid filter files that are chained
1941 * after empty or invalid ones.
1946 * For all applying +filter actions, look if a filter by that
1947 * name exists and if yes, execute its pcrs_joblist on the
1950 for (b = fl->f; b; b = b->next)
1952 if (b->type != wanted_filter_type)
1954 /* Skip other filter types */
1958 for (filtername = csp->action->multi[multi_action_index]->first;
1959 filtername ; filtername = filtername->next)
1961 if (strcmp(b->name, filtername->str) == 0)
1963 int current_hits = 0;
1964 pcrs_job *joblist = b->joblist;
1966 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1968 if (NULL == joblist)
1970 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1974 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1975 *header, size, b->name);
1977 /* Apply all jobs from the joblist */
1978 for (job = joblist; NULL != job; job = job->next)
1980 matches = pcrs_execute(job, *header, size, &newheader, &size);
1983 current_hits += matches;
1984 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1986 *header = newheader;
1988 else if ( 0 == matches )
1990 /* Filter doesn't change header */
1996 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1997 *header, b->name, pcrs_strerror(matches));
1998 if (newheader != NULL)
2000 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2006 if (b->dynamic) pcrs_free_joblist(joblist);
2008 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2009 hits += current_hits;
2016 * Additionally checking for hits is important because if
2017 * the continue hack is triggered, server headers can
2018 * arrive empty to separate multiple heads from each other.
2020 if ((0 == size) && hits)
2022 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2030 /*********************************************************************
2032 * Function : connection
2034 * Description : Makes sure that the value of the Connection: header
2035 * is "close" and signals connection_close_adder
2039 * 1 : csp = Current client state (buffers, headers, etc...)
2040 * 2 : header = On input, pointer to header to modify.
2041 * On output, pointer to the modified header, or NULL
2042 * to remove the header. This function frees the
2043 * original string if necessary.
2045 * Returns : JB_ERR_OK on success, or
2046 * JB_ERR_MEMORY on out-of-memory error.
2048 *********************************************************************/
2049 static jb_err connection(struct client_state *csp, char **header)
2051 char *old_header = *header;
2053 /* Do we have a 'Connection: close' header? */
2054 if (strcmpic(*header, "Connection: close"))
2056 /* No, create one */
2057 *header = strdup("Connection: close");
2060 return JB_ERR_MEMORY;
2062 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2066 /* Signal connection_close_adder() to return early. */
2067 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2069 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2073 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2080 /*********************************************************************
2082 * Function : crumble
2084 * Description : This is called if a header matches a pattern to "crunch"
2087 * 1 : csp = Current client state (buffers, headers, etc...)
2088 * 2 : header = On input, pointer to header to modify.
2089 * On output, pointer to the modified header, or NULL
2090 * to remove the header. This function frees the
2091 * original string if necessary.
2093 * Returns : JB_ERR_OK on success, or
2094 * JB_ERR_MEMORY on out-of-memory error.
2096 *********************************************************************/
2097 static jb_err crumble(struct client_state *csp, char **header)
2099 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2105 /*********************************************************************
2107 * Function : crunch_server_header
2109 * Description : Crunch server header if it matches a string supplied by the
2110 * user. Called from `sed'.
2113 * 1 : csp = Current client state (buffers, headers, etc...)
2114 * 2 : header = On input, pointer to header to modify.
2115 * On output, pointer to the modified header, or NULL
2116 * to remove the header. This function frees the
2117 * original string if necessary.
2119 * Returns : JB_ERR_OK on success and always succeeds
2121 *********************************************************************/
2122 static jb_err crunch_server_header(struct client_state *csp, char **header)
2124 const char *crunch_pattern;
2126 /* Do we feel like crunching? */
2127 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2129 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2131 /* Is the current header the lucky one? */
2132 if (strstr(*header, crunch_pattern))
2134 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2143 /*********************************************************************
2145 * Function : server_content_type
2147 * Description : Set the content-type for filterable types (text/.*,
2148 * .*xml.*, javascript and image/gif) unless filtering has been
2149 * forbidden (CT_TABOO) while parsing earlier headers.
2150 * NOTE: Since text/plain is commonly used by web servers
2151 * for files whose correct type is unknown, we don't
2152 * set CT_TEXT for it.
2155 * 1 : csp = Current client state (buffers, headers, etc...)
2156 * 2 : header = On input, pointer to header to modify.
2157 * On output, pointer to the modified header, or NULL
2158 * to remove the header. This function frees the
2159 * original string if necessary.
2161 * Returns : JB_ERR_OK on success, or
2162 * JB_ERR_MEMORY on out-of-memory error.
2164 *********************************************************************/
2165 static jb_err server_content_type(struct client_state *csp, char **header)
2167 /* Remove header if it isn't the first Content-Type header */
2168 if ((csp->content_type & CT_DECLARED))
2171 * Another, slightly slower, way to see if
2172 * we already parsed another Content-Type header.
2174 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2176 log_error(LOG_LEVEL_ERROR,
2177 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2185 * Signal that the Content-Type has been set.
2187 csp->content_type |= CT_DECLARED;
2189 if (!(csp->content_type & CT_TABOO))
2192 * XXX: The assumption that text/plain is a sign of
2193 * binary data seems to be somewhat unreasonable nowadays
2194 * and should be dropped after 3.0.8 is out.
2196 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2197 || strstr(*header, "xml")
2198 || strstr(*header, "application/x-javascript"))
2200 csp->content_type |= CT_TEXT;
2202 else if (strstr(*header, "image/gif"))
2204 csp->content_type |= CT_GIF;
2206 else if (strstr(*header, "image/jpeg"))
2208 csp->content_type |= CT_JPEG;
2213 * Are we messing with the content type?
2215 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2218 * Make sure the user doesn't accidently
2219 * change the content type of binary documents.
2221 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2224 *header = strdup("Content-Type: ");
2225 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2229 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2230 return JB_ERR_MEMORY;
2232 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2236 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2237 "It doesn't look like a content type that should be filtered. "
2238 "Enable force-text-mode if you know what you're doing.", *header);
2246 /*********************************************************************
2248 * Function : server_transfer_coding
2250 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2251 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2252 * - Remove header if body was chunked but has been
2253 * de-chunked for filtering.
2256 * 1 : csp = Current client state (buffers, headers, etc...)
2257 * 2 : header = On input, pointer to header to modify.
2258 * On output, pointer to the modified header, or NULL
2259 * to remove the header. This function frees the
2260 * original string if necessary.
2262 * Returns : JB_ERR_OK on success, or
2263 * JB_ERR_MEMORY on out-of-memory error.
2265 *********************************************************************/
2266 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2269 * Turn off pcrs and gif filtering if body compressed
2271 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2275 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2277 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2278 csp->http->cmd, *header);
2279 #endif /* def FEATURE_ZLIB */
2280 csp->content_type = CT_TABOO;
2284 * Raise flag if body chunked
2286 if (strstr(*header, "chunked"))
2288 csp->flags |= CSP_FLAG_CHUNKED;
2291 * If the body was modified, it has been de-chunked first
2292 * and the header must be removed.
2294 * FIXME: If there is more than one transfer encoding,
2295 * only the "chunked" part should be removed here.
2297 if (csp->flags & CSP_FLAG_MODIFIED)
2299 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2308 /*********************************************************************
2310 * Function : server_content_encoding
2312 * Description : This function is run twice for each request,
2313 * unless FEATURE_ZLIB and filtering are disabled.
2315 * The first run is used to check if the content
2316 * is compressed, if FEATURE_ZLIB is disabled
2317 * filtering is then disabled as well, if FEATURE_ZLIB
2318 * is enabled the content is marked for decompression.
2320 * The second run is used to remove the Content-Encoding
2321 * header if the decompression was successful.
2324 * 1 : csp = Current client state (buffers, headers, etc...)
2325 * 2 : header = On input, pointer to header to modify.
2326 * On output, pointer to the modified header, or NULL
2327 * to remove the header. This function frees the
2328 * original string if necessary.
2330 * Returns : JB_ERR_OK on success, or
2331 * JB_ERR_MEMORY on out-of-memory error.
2333 *********************************************************************/
2334 static jb_err server_content_encoding(struct client_state *csp, char **header)
2337 if ((csp->flags & CSP_FLAG_MODIFIED)
2338 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2341 * We successfully decompressed the content,
2342 * and have to clean the header now, so the
2343 * client no longer expects compressed data..
2345 * XXX: There is a difference between cleaning
2346 * and removing it completely.
2348 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2351 else if (strstr(*header, "gzip"))
2353 /* Mark for gzip decompression */
2354 csp->content_type |= CT_GZIP;
2356 else if (strstr(*header, "deflate"))
2358 /* Mark for zlib decompression */
2359 csp->content_type |= CT_DEFLATE;
2361 else if (strstr(*header, "compress"))
2364 * We can't decompress this; therefore we can't filter
2367 csp->content_type |= CT_TABOO;
2369 #else /* !defined(FEATURE_ZLIB) */
2370 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2373 * Body is compressed, turn off pcrs and gif filtering.
2375 csp->content_type |= CT_TABOO;
2378 * Log a warning if the user expects the content to be filtered.
2380 if ((csp->rlist != NULL) &&
2381 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2383 log_error(LOG_LEVEL_INFO,
2384 "Compressed content detected, content filtering disabled. "
2385 "Consider recompiling Privoxy with zlib support or "
2386 "enable the prevent-compression action.");
2389 #endif /* defined(FEATURE_ZLIB) */
2396 /*********************************************************************
2398 * Function : server_content_length
2400 * Description : Adjust Content-Length header if we modified
2404 * 1 : csp = Current client state (buffers, headers, etc...)
2405 * 2 : header = On input, pointer to header to modify.
2406 * On output, pointer to the modified header, or NULL
2407 * to remove the header. This function frees the
2408 * original string if necessary.
2410 * Returns : JB_ERR_OK on success, or
2411 * JB_ERR_MEMORY on out-of-memory error.
2413 *********************************************************************/
2414 static jb_err server_content_length(struct client_state *csp, char **header)
2416 const size_t max_header_length = 80;
2418 /* Regenerate header if the content was modified. */
2419 if (csp->flags & CSP_FLAG_MODIFIED)
2422 *header = (char *) zalloc(max_header_length);
2423 if (*header == NULL)
2425 return JB_ERR_MEMORY;
2428 snprintf(*header, max_header_length, "Content-Length: %d",
2429 (int)csp->content_length);
2430 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2431 (int)csp->content_length);
2438 /*********************************************************************
2440 * Function : server_content_md5
2442 * Description : Crumble any Content-MD5 headers if the document was
2443 * modified. FIXME: Should we re-compute instead?
2446 * 1 : csp = Current client state (buffers, headers, etc...)
2447 * 2 : header = On input, pointer to header to modify.
2448 * On output, pointer to the modified header, or NULL
2449 * to remove the header. This function frees the
2450 * original string if necessary.
2452 * Returns : JB_ERR_OK on success, or
2453 * JB_ERR_MEMORY on out-of-memory error.
2455 *********************************************************************/
2456 static jb_err server_content_md5(struct client_state *csp, char **header)
2458 if (csp->flags & CSP_FLAG_MODIFIED)
2460 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2468 /*********************************************************************
2470 * Function : server_content_disposition
2472 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2473 * Called from `sed'.
2476 * 1 : csp = Current client state (buffers, headers, etc...)
2477 * 2 : header = On input, pointer to header to modify.
2478 * On output, pointer to the modified header, or NULL
2479 * to remove the header. This function frees the
2480 * original string if necessary.
2482 * Returns : JB_ERR_OK on success, or
2483 * JB_ERR_MEMORY on out-of-memory error.
2485 *********************************************************************/
2486 static jb_err server_content_disposition(struct client_state *csp, char **header)
2491 * Are we messing with the Content-Disposition header?
2493 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2499 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2501 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2504 * Blocking content-disposition header
2506 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2513 * Replacing Content-Disposition header
2516 *header = strdup("Content-Disposition: ");
2517 string_append(header, newval);
2519 if (*header != NULL)
2521 log_error(LOG_LEVEL_HEADER,
2522 "Content-Disposition header crunched and replaced with: %s", *header);
2525 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2529 /*********************************************************************
2531 * Function : server_last_modified
2533 * Description : Changes Last-Modified header to the actual date
2534 * to help hide-if-modified-since.
2535 * Called from `sed'.
2538 * 1 : csp = Current client state (buffers, headers, etc...)
2539 * 2 : header = On input, pointer to header to modify.
2540 * On output, pointer to the modified header, or NULL
2541 * to remove the header. This function frees the
2542 * original string if necessary.
2544 * Returns : JB_ERR_OK on success, or
2545 * JB_ERR_MEMORY on out-of-memory error.
2547 *********************************************************************/
2548 static jb_err server_last_modified(struct client_state *csp, char **header)
2551 char buf[BUFFER_SIZE];
2554 #ifdef HAVE_GMTIME_R
2557 struct tm *timeptr = NULL;
2558 time_t now, last_modified;
2560 long int days, hours, minutes, seconds;
2563 * Are we messing with the Last-Modified header?
2565 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2571 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2573 if (0 == strcmpic(newval, "block") )
2576 * Blocking Last-Modified header. Useless but why not.
2578 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2582 else if (0 == strcmpic(newval, "reset-to-request-time"))
2585 * Setting Last-Modified Header to now.
2587 get_http_time(0, buf);
2589 *header = strdup("Last-Modified: ");
2590 string_append(header, buf);
2592 if (*header == NULL)
2594 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2598 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2601 else if (0 == strcmpic(newval, "randomize"))
2603 const char *header_time = *header + sizeof("Last-Modified:");
2605 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2607 #ifdef HAVE_GMTIME_R
2608 timeptr = gmtime_r(&now, &gmt);
2609 #elif FEATURE_PTHREAD
2610 pthread_mutex_lock(&gmtime_mutex);
2611 timeptr = gmtime(&now);
2612 pthread_mutex_unlock(&gmtime_mutex);
2614 timeptr = gmtime(&now);
2616 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2618 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2623 rtime = (long int)difftime(now, last_modified);
2632 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2634 rtime = pick_from_range(rtime);
2635 if (negative) rtime *= -1;
2636 last_modified += rtime;
2637 #ifdef HAVE_GMTIME_R
2638 timeptr = gmtime_r(&last_modified, &gmt);
2639 #elif FEATURE_PTHREAD
2640 pthread_mutex_lock(&gmtime_mutex);
2641 timeptr = gmtime(&last_modified);
2642 pthread_mutex_unlock(&gmtime_mutex);
2644 timeptr = gmtime(&last_modified);
2646 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2648 *header = strdup("Last-Modified: ");
2649 string_append(header, newheader);
2651 if (*header == NULL)
2653 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2654 return JB_ERR_MEMORY;
2657 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2659 days = rtime / (3600 * 24);
2660 hours = rtime / 3600 % 24;
2661 minutes = rtime / 60 % 60;
2662 seconds = rtime % 60;
2664 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2665 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2666 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2671 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2680 /*********************************************************************
2682 * Function : client_accept_encoding
2684 * Description : Rewrite the client's Accept-Encoding header so that
2685 * if doesn't allow compression, if the action applies.
2686 * Note: For HTTP/1.0 the absence of the header is enough.
2689 * 1 : csp = Current client state (buffers, headers, etc...)
2690 * 2 : header = On input, pointer to header to modify.
2691 * On output, pointer to the modified header, or NULL
2692 * to remove the header. This function frees the
2693 * original string if necessary.
2695 * Returns : JB_ERR_OK on success, or
2696 * JB_ERR_MEMORY on out-of-memory error.
2698 *********************************************************************/
2699 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2701 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2703 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2707 /* Temporarily disable the correct behaviour to
2708 * work around a PHP bug.
2710 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2712 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2713 * if (*header == NULL)
2715 * return JB_ERR_MEMORY;
2726 /*********************************************************************
2728 * Function : client_te
2730 * Description : Rewrite the client's TE header so that
2731 * if doesn't allow compression, if the action applies.
2734 * 1 : csp = Current client state (buffers, headers, etc...)
2735 * 2 : header = On input, pointer to header to modify.
2736 * On output, pointer to the modified header, or NULL
2737 * to remove the header. This function frees the
2738 * original string if necessary.
2740 * Returns : JB_ERR_OK on success, or
2741 * JB_ERR_MEMORY on out-of-memory error.
2743 *********************************************************************/
2744 static jb_err client_te(struct client_state *csp, char **header)
2746 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2749 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2756 /*********************************************************************
2758 * Function : client_referrer
2760 * Description : Handle the "referer" config setting properly.
2761 * Called from `sed'.
2764 * 1 : csp = Current client state (buffers, headers, etc...)
2765 * 2 : header = On input, pointer to header to modify.
2766 * On output, pointer to the modified header, or NULL
2767 * to remove the header. This function frees the
2768 * original string if necessary.
2770 * Returns : JB_ERR_OK on success, or
2771 * JB_ERR_MEMORY on out-of-memory error.
2773 *********************************************************************/
2774 static jb_err client_referrer(struct client_state *csp, char **header)
2776 const char *parameter;
2777 /* booleans for parameters we have to check multiple times */
2778 int parameter_conditional_block;
2779 int parameter_conditional_forge;
2781 #ifdef FEATURE_FORCE_LOAD
2783 * Since the referrer can include the prefix even
2784 * if the request itself is non-forced, we must
2785 * clean it unconditionally.
2787 * XXX: strclean is too broad
2789 strclean(*header, FORCE_PREFIX);
2790 #endif /* def FEATURE_FORCE_LOAD */
2792 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2794 /* Nothing left to do */
2798 parameter = csp->action->string[ACTION_STRING_REFERER];
2799 assert(parameter != NULL);
2800 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2801 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2803 if (!parameter_conditional_block && !parameter_conditional_forge)
2806 * As conditional-block and conditional-forge are the only
2807 * parameters that rely on the original referrer, we can
2808 * remove it now for all the others.
2813 if (0 == strcmpic(parameter, "block"))
2815 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2818 else if (parameter_conditional_block || parameter_conditional_forge)
2820 return handle_conditional_hide_referrer_parameter(header,
2821 csp->http->hostport, parameter_conditional_block);
2823 else if (0 == strcmpic(parameter, "forge"))
2825 return create_forged_referrer(header, csp->http->hostport);
2829 /* interpret parameter as user-supplied referer to fake */
2830 return create_fake_referrer(header, parameter);
2835 /*********************************************************************
2837 * Function : client_accept_language
2839 * Description : Handle the "Accept-Language" config setting properly.
2840 * Called from `sed'.
2843 * 1 : csp = Current client state (buffers, headers, etc...)
2844 * 2 : header = On input, pointer to header to modify.
2845 * On output, pointer to the modified header, or NULL
2846 * to remove the header. This function frees the
2847 * original string if necessary.
2849 * Returns : JB_ERR_OK on success, or
2850 * JB_ERR_MEMORY on out-of-memory error.
2852 *********************************************************************/
2853 static jb_err client_accept_language(struct client_state *csp, char **header)
2858 * Are we messing with the Accept-Language?
2860 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2862 /*I don't think so*/
2866 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2868 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2871 * Blocking Accept-Language header
2873 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2880 * Replacing Accept-Language header
2883 *header = strdup("Accept-Language: ");
2884 string_append(header, newval);
2886 if (*header == NULL)
2888 log_error(LOG_LEVEL_ERROR,
2889 "Insufficent memory. Accept-Language header crunched without replacement.");
2893 log_error(LOG_LEVEL_HEADER,
2894 "Accept-Language header crunched and replaced with: %s", *header);
2897 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2901 /*********************************************************************
2903 * Function : crunch_client_header
2905 * Description : Crunch client header if it matches a string supplied by the
2906 * user. Called from `sed'.
2909 * 1 : csp = Current client state (buffers, headers, etc...)
2910 * 2 : header = On input, pointer to header to modify.
2911 * On output, pointer to the modified header, or NULL
2912 * to remove the header. This function frees the
2913 * original string if necessary.
2915 * Returns : JB_ERR_OK on success and always succeeds
2917 *********************************************************************/
2918 static jb_err crunch_client_header(struct client_state *csp, char **header)
2920 const char *crunch_pattern;
2922 /* Do we feel like crunching? */
2923 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2925 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2927 /* Is the current header the lucky one? */
2928 if (strstr(*header, crunch_pattern))
2930 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2938 /*********************************************************************
2940 * Function : client_uagent
2942 * Description : Handle the "user-agent" config setting properly
2943 * and remember its original value to enable browser
2944 * bug workarounds. Called from `sed'.
2947 * 1 : csp = Current client state (buffers, headers, etc...)
2948 * 2 : header = On input, pointer to header to modify.
2949 * On output, pointer to the modified header, or NULL
2950 * to remove the header. This function frees the
2951 * original string if necessary.
2953 * Returns : JB_ERR_OK on success, or
2954 * JB_ERR_MEMORY on out-of-memory error.
2956 *********************************************************************/
2957 static jb_err client_uagent(struct client_state *csp, char **header)
2961 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2966 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2973 *header = strdup("User-Agent: ");
2974 string_append(header, newval);
2976 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2978 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2982 /*********************************************************************
2984 * Function : client_ua
2986 * Description : Handle "ua-" headers properly. Called from `sed'.
2989 * 1 : csp = Current client state (buffers, headers, etc...)
2990 * 2 : header = On input, pointer to header to modify.
2991 * On output, pointer to the modified header, or NULL
2992 * to remove the header. This function frees the
2993 * original string if necessary.
2995 * Returns : JB_ERR_OK on success, or
2996 * JB_ERR_MEMORY on out-of-memory error.
2998 *********************************************************************/
2999 static jb_err client_ua(struct client_state *csp, char **header)
3001 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3003 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3011 /*********************************************************************
3013 * Function : client_from
3015 * Description : Handle the "from" config setting properly.
3016 * Called from `sed'.
3019 * 1 : csp = Current client state (buffers, headers, etc...)
3020 * 2 : header = On input, pointer to header to modify.
3021 * On output, pointer to the modified header, or NULL
3022 * to remove the header. This function frees the
3023 * original string if necessary.
3025 * Returns : JB_ERR_OK on success, or
3026 * JB_ERR_MEMORY on out-of-memory error.
3028 *********************************************************************/
3029 static jb_err client_from(struct client_state *csp, char **header)
3033 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3040 newval = csp->action->string[ACTION_STRING_FROM];
3043 * Are we blocking the e-mail address?
3045 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3047 log_error(LOG_LEVEL_HEADER, "crunched From!");
3051 log_error(LOG_LEVEL_HEADER, " modified");
3053 *header = strdup("From: ");
3054 string_append(header, newval);
3056 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3060 /*********************************************************************
3062 * Function : client_send_cookie
3064 * Description : Crunches the "cookie" header if necessary.
3065 * Called from `sed'.
3067 * XXX: Stupid name, doesn't send squat.
3070 * 1 : csp = Current client state (buffers, headers, etc...)
3071 * 2 : header = On input, pointer to header to modify.
3072 * On output, pointer to the modified header, or NULL
3073 * to remove the header. This function frees the
3074 * original string if necessary.
3076 * Returns : JB_ERR_OK on success, or
3077 * JB_ERR_MEMORY on out-of-memory error.
3079 *********************************************************************/
3080 static jb_err client_send_cookie(struct client_state *csp, char **header)
3082 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3084 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3092 /*********************************************************************
3094 * Function : client_x_forwarded
3096 * Description : Handle the "x-forwarded-for" config setting properly,
3097 * also used in the add_client_headers list. Called from `sed'.
3100 * 1 : csp = Current client state (buffers, headers, etc...)
3101 * 2 : header = On input, pointer to header to modify.
3102 * On output, pointer to the modified header, or NULL
3103 * to remove the header. This function frees the
3104 * original string if necessary.
3106 * Returns : JB_ERR_OK on success, or
3107 * JB_ERR_MEMORY on out-of-memory error.
3109 *********************************************************************/
3110 jb_err client_x_forwarded(struct client_state *csp, char **header)
3112 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3115 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3122 /*********************************************************************
3124 * Function : client_max_forwards
3126 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3127 * from the value of the Max-Forwards header field.
3130 * 1 : csp = Current client state (buffers, headers, etc...)
3131 * 2 : header = On input, pointer to header to modify.
3132 * On output, pointer to the modified header, or NULL
3133 * to remove the header. This function frees the
3134 * original string if necessary.
3136 * Returns : JB_ERR_OK on success, or
3137 * JB_ERR_MEMORY on out-of-memory error.
3139 *********************************************************************/
3140 static jb_err client_max_forwards(struct client_state *csp, char **header)
3144 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3145 (0 == strcmpic(csp->http->gpc, "options")))
3147 assert(*(*header+12) == ':');
3148 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3150 if (max_forwards > 0)
3152 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3153 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3154 csp->http->gpc, max_forwards);
3156 else if (max_forwards < 0)
3158 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3164 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3173 /*********************************************************************
3175 * Function : client_host
3177 * Description : If the request URI did not contain host and
3178 * port information, parse and evaluate the Host
3181 * Also, kill ill-formed HOST: headers as sent by
3182 * Apple's iTunes software when used with a proxy.
3185 * 1 : csp = Current client state (buffers, headers, etc...)
3186 * 2 : header = On input, pointer to header to modify.
3187 * On output, pointer to the modified header, or NULL
3188 * to remove the header. This function frees the
3189 * original string if necessary.
3191 * Returns : JB_ERR_OK on success, or
3192 * JB_ERR_MEMORY on out-of-memory error.
3194 *********************************************************************/
3195 static jb_err client_host(struct client_state *csp, char **header)
3200 * If the header field name is all upper-case, chances are that it's
3201 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3202 * not a problem -- they are regenerated later.
3204 if ((*header)[1] == 'O')
3206 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3211 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3212 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3215 if (NULL == (p = strdup((*header)+6)))
3217 return JB_ERR_MEMORY;
3220 if (NULL == (q = strdup(p)))
3223 return JB_ERR_MEMORY;
3226 freez(csp->http->hostport);
3227 csp->http->hostport = p;
3228 freez(csp->http->host);
3229 csp->http->host = q;
3230 q = strchr(csp->http->host, ':');
3233 /* Terminate hostname and evaluate port string */
3235 csp->http->port = atoi(q);
3239 csp->http->port = csp->http->ssl ? 443 : 80;
3242 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3243 csp->http->hostport, csp->http->host, csp->http->port);
3246 /* Signal client_host_adder() to return right away */
3247 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3253 /*********************************************************************
3255 * Function : client_if_modified_since
3257 * Description : Remove or modify the If-Modified-Since header.
3260 * 1 : csp = Current client state (buffers, headers, etc...)
3261 * 2 : header = On input, pointer to header to modify.
3262 * On output, pointer to the modified header, or NULL
3263 * to remove the header. This function frees the
3264 * original string if necessary.
3266 * Returns : JB_ERR_OK on success, or
3267 * JB_ERR_MEMORY on out-of-memory error.
3269 *********************************************************************/
3270 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3273 #ifdef HAVE_GMTIME_R
3276 struct tm *timeptr = NULL;
3280 long int hours, minutes, seconds;
3284 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3287 * The client got an error message because of a temporary problem,
3288 * the problem is gone and the client now tries to revalidate our
3289 * error message on the real server. The revalidation would always
3290 * end with the transmission of the whole document and there is
3291 * no need to expose the bogus If-Modified-Since header.
3293 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3296 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3298 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3300 if ((0 == strcmpic(newval, "block")))
3302 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3305 else /* add random value */
3307 const char *header_time = *header + sizeof("If-Modified-Since:");
3309 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3311 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3316 rtime = strtol(newval, &endptr, 0);
3319 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3320 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3327 rtime = pick_from_range(rtime);
3331 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3334 tm += rtime * (negative ? -1 : 1);
3335 #ifdef HAVE_GMTIME_R
3336 timeptr = gmtime_r(&tm, &gmt);
3337 #elif FEATURE_PTHREAD
3338 pthread_mutex_lock(&gmtime_mutex);
3339 timeptr = gmtime(&tm);
3340 pthread_mutex_unlock(&gmtime_mutex);
3342 timeptr = gmtime(&tm);
3344 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3347 *header = strdup("If-Modified-Since: ");
3348 string_append(header, newheader);
3350 if (*header == NULL)
3352 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3353 return JB_ERR_MEMORY;
3356 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3358 hours = rtime / 3600;
3359 minutes = rtime / 60 % 60;
3360 seconds = rtime % 60;
3362 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3363 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3364 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3374 /*********************************************************************
3376 * Function : client_if_none_match
3378 * Description : Remove the If-None-Match header.
3381 * 1 : csp = Current client state (buffers, headers, etc...)
3382 * 2 : header = On input, pointer to header to modify.
3383 * On output, pointer to the modified header, or NULL
3384 * to remove the header. This function frees the
3385 * original string if necessary.
3387 * Returns : JB_ERR_OK on success, or
3388 * JB_ERR_MEMORY on out-of-memory error.
3390 *********************************************************************/
3391 static jb_err client_if_none_match(struct client_state *csp, char **header)
3393 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3395 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3403 /*********************************************************************
3405 * Function : client_x_filter
3407 * Description : Disables filtering if the client set "X-Filter: No".
3408 * Called from `sed'.
3411 * 1 : csp = Current client state (buffers, headers, etc...)
3412 * 2 : header = On input, pointer to header to modify.
3413 * On output, pointer to the modified header, or NULL
3414 * to remove the header. This function frees the
3415 * original string if necessary.
3417 * Returns : JB_ERR_OK on success
3419 *********************************************************************/
3420 jb_err client_x_filter(struct client_state *csp, char **header)
3422 if ( 0 == strcmpic(*header, "X-Filter: No"))
3424 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3426 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3430 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3432 log_error(LOG_LEVEL_HEADER,
3433 "force-text-mode overruled the client's request to fetch without filtering!");
3437 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3438 csp->flags |= CSP_FLAG_NO_FILTERING;
3439 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3441 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3449 /*********************************************************************
3451 * Function : client_range
3453 * Description : Removes Range and If-Range headers if content
3454 * filtering is enabled. If the client's version of
3455 * the document has been altered by Privoxy, the server
3456 * could interpret the range differently than the client
3457 * intended in which case the user could end up with
3458 * corrupted content.
3461 * 1 : csp = Current client state (buffers, headers, etc...)
3462 * 2 : header = On input, pointer to header to modify.
3463 * On output, pointer to the modified header, or NULL
3464 * to remove the header. This function frees the
3465 * original string if necessary.
3467 * Returns : JB_ERR_OK
3469 *********************************************************************/
3470 static jb_err client_range(struct client_state *csp, char **header)
3472 if (content_filters_enabled(csp))
3474 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3475 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3482 /* the following functions add headers directly to the header list */
3484 /*********************************************************************
3486 * Function : client_host_adder
3488 * Description : Adds the Host: header field if it is missing.
3489 * Called from `sed'.
3492 * 1 : csp = Current client state (buffers, headers, etc...)
3494 * Returns : JB_ERR_OK on success, or
3495 * JB_ERR_MEMORY on out-of-memory error.
3497 *********************************************************************/
3498 static jb_err client_host_adder(struct client_state *csp)
3503 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3505 /* Header already set by the client, nothing to do. */
3509 if ( !csp->http->hostport || !*(csp->http->hostport))
3511 /* XXX: When does this happen and why is it OK? */
3512 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3517 * remove 'user:pass@' from 'proto://user:pass@host'
3519 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3525 p = csp->http->hostport;
3528 /* XXX: Just add it, we already made sure that it will be unique */
3529 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3530 err = enlist_unique_header(csp->headers, "Host", p);
3536 /*********************************************************************
3538 * Function : client_cookie_adder
3540 * Description : Used in the add_client_headers list to add "wafers".
3541 * Called from `sed'.
3544 * 1 : csp = Current client state (buffers, headers, etc...)
3546 * Returns : JB_ERR_OK on success, or
3547 * JB_ERR_MEMORY on out-of-memory error.
3549 *********************************************************************/
3550 jb_err client_cookie_adder(struct client_state *csp)
3553 struct list_entry *wafer;
3554 struct list_entry *wafer_list;
3558 * If the user has not supplied any wafers, and the user has not
3559 * told us to suppress the vanilla wafer, then send the vanilla wafer.
3561 if ((0 != (csp->action->flags & ACTION_VANILLA_WAFER))
3562 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER]))
3564 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
3567 wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3569 if (NULL == wafer_list)
3575 tmp = strdup("Cookie: ");
3577 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3579 if (wafer != wafer_list)
3581 /* As this isn't the first wafer, we need a delimiter. */
3582 string_append(&tmp, "; ");
3584 string_join(&tmp, cookie_encode(wafer->str));
3589 return JB_ERR_MEMORY;
3592 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3593 err = enlist(csp->headers, tmp);
3600 /*********************************************************************
3602 * Function : client_accept_encoding_adder
3604 * Description : Add an Accept-Encoding header to the client's request
3605 * that disables compression if the action applies, and
3606 * the header is not already there. Called from `sed'.
3607 * Note: For HTTP/1.0, the absence of the header is enough.
3610 * 1 : csp = Current client state (buffers, headers, etc...)
3612 * Returns : JB_ERR_OK on success, or
3613 * JB_ERR_MEMORY on out-of-memory error.
3615 *********************************************************************/
3616 static jb_err client_accept_encoding_adder(struct client_state *csp)
3618 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3619 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3621 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3629 /*********************************************************************
3631 * Function : client_xtra_adder
3633 * Description : Used in the add_client_headers list. Called from `sed'.
3636 * 1 : csp = Current client state (buffers, headers, etc...)
3638 * Returns : JB_ERR_OK on success, or
3639 * JB_ERR_MEMORY on out-of-memory error.
3641 *********************************************************************/
3642 static jb_err client_xtra_adder(struct client_state *csp)
3644 struct list_entry *lst;
3647 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3648 lst ; lst = lst->next)
3650 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3651 err = enlist(csp->headers, lst->str);
3663 /*********************************************************************
3665 * Function : connection_close_adder
3667 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3668 * support. Adds a "Connection: close" header to csp->headers
3669 * unless the header was already present. Called from `sed'.
3671 * FIXME: This whole function shouldn't be neccessary!
3674 * 1 : csp = Current client state (buffers, headers, etc...)
3676 * Returns : JB_ERR_OK on success, or
3677 * JB_ERR_MEMORY on out-of-memory error.
3679 *********************************************************************/
3680 static jb_err connection_close_adder(struct client_state *csp)
3682 const unsigned int flags = csp->flags;
3685 * Return right away if
3687 * - we're parsing server headers and the server header
3688 * "Connection: close" is already set, or if
3690 * - we're parsing client headers and the client header
3691 * "Connection: close" is already set.
3693 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3694 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3695 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3696 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3701 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3703 return enlist(csp->headers, "Connection: close");
3707 /*********************************************************************
3709 * Function : server_http
3711 * Description : - Save the HTTP Status into csp->http->status
3712 * - Set CT_TABOO to prevent filtering if the answer
3713 * is a partial range (HTTP status 206)
3714 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3718 * 1 : csp = Current client state (buffers, headers, etc...)
3719 * 2 : header = On input, pointer to header to modify.
3720 * On output, pointer to the modified header, or NULL
3721 * to remove the header. This function frees the
3722 * original string if necessary.
3724 * Returns : JB_ERR_OK on success, or
3725 * JB_ERR_MEMORY on out-of-memory error.
3727 *********************************************************************/
3728 static jb_err server_http(struct client_state *csp, char **header)
3730 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3731 if (csp->http->status == 206)
3733 csp->content_type = CT_TABOO;
3736 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3738 /* XXX: Should we do a real validity check here? */
3739 if (strlen(*header) > 8)
3742 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3747 * XXX: Should we block the request or
3748 * enlist a valid status code line here?
3750 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3751 "Downgrading to HTTP/1.0 impossible.");
3759 /*********************************************************************
3761 * Function : server_set_cookie
3763 * Description : Handle the server "cookie" header properly.
3764 * Log cookie to the jar file. Then "crunch",
3765 * accept or rewrite it to a session cookie.
3766 * Called from `sed'.
3768 * TODO: Allow the user to specify a new expiration
3769 * time to cause the cookie to expire even before the
3770 * browser is closed.
3773 * 1 : csp = Current client state (buffers, headers, etc...)
3774 * 2 : header = On input, pointer to header to modify.
3775 * On output, pointer to the modified header, or NULL
3776 * to remove the header. This function frees the
3777 * original string if necessary.
3779 * Returns : JB_ERR_OK on success, or
3780 * JB_ERR_MEMORY on out-of-memory error.
3782 *********************************************************************/
3783 static jb_err server_set_cookie(struct client_state *csp, char **header)
3790 #ifdef FEATURE_COOKIE_JAR
3791 if (csp->config->jar)
3794 * Write timestamp into outbuf.
3796 * Complex because not all OSs have tm_gmtoff or
3797 * the %z field in strftime()
3799 char tempbuf[ BUFFER_SIZE ];
3801 #ifdef HAVE_LOCALTIME_R
3802 tm_now = *localtime_r(&now, &tm_now);
3803 #elif FEATURE_PTHREAD
3804 pthread_mutex_lock(&localtime_mutex);
3805 tm_now = *localtime (&now);
3806 pthread_mutex_unlock(&localtime_mutex);
3808 tm_now = *localtime (&now);
3810 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3812 /* strlen("set-cookie: ") = 12 */
3813 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3815 #endif /* def FEATURE_COOKIE_JAR */
3817 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3819 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3822 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3824 /* Flag whether or not to log a message */
3827 /* A variable to store the tag we're working on */
3830 /* Skip "Set-Cookie:" (11 characters) in header */
3831 cur_tag = *header + 11;
3833 /* skip whitespace between "Set-Cookie:" and value */
3834 while (*cur_tag && ijb_isspace(*cur_tag))
3839 /* Loop through each tag in the cookie */
3843 char *next_tag = strchr(cur_tag, ';');
3844 if (next_tag != NULL)
3846 /* Skip the ';' character itself */
3849 /* skip whitespace ";" and start of tag */
3850 while (*next_tag && ijb_isspace(*next_tag))
3857 /* "Next tag" is the end of the string */
3858 next_tag = cur_tag + strlen(cur_tag);
3862 * Check the expiration date to see
3863 * if the cookie is still valid, if yes,
3864 * rewrite it to a session cookie.
3866 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3868 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3870 /* Did we detect the date properly? */
3871 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3874 * Nope, treat it as if it was still valid.
3876 * XXX: Should we remove the whole cookie instead?
3878 log_error(LOG_LEVEL_ERROR,
3879 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3880 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3886 * Yes. Check if the cookie is still valid.
3888 * If the cookie is already expired it's probably
3889 * a delete cookie and even if it isn't, the browser
3890 * will discard it anyway.
3894 * XXX: timegm() isn't available on some AmigaOS
3895 * versions and our replacement doesn't work.
3897 * Our options are to either:
3899 * - disable session-cookies-only completely if timegm
3902 * - to simply remove all expired tags, like it has
3903 * been done until Privoxy 3.0.6 and to live with
3904 * the consequence that it can cause login/logout
3905 * problems on servers that don't validate their
3906 * input properly, or
3908 * - to replace it with mktime in which
3909 * case there is a slight chance of valid cookies
3910 * passing as already expired.
3912 * This is the way it's currently done and it's not
3913 * as bad as it sounds. If the missing GMT offset is
3914 * enough to change the result of the expiration check
3915 * the cookie will be only valid for a few hours
3916 * anyway, which in many cases will be shorter
3917 * than a browser session.
3919 if (cookie_time - now < 0)
3921 log_error(LOG_LEVEL_HEADER,
3922 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3923 /* Just in case some clown sets more then one expiration date */
3929 * Still valid, delete expiration date by copying
3930 * the rest of the string over it.
3932 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3933 * since the behaviour of strcpy is undefined for overlapping
3936 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3938 /* That changed the header, need to issue a log message */
3942 * Note that the next tag has now been moved to *cur_tag,
3943 * so we do not need to update the cur_tag pointer.
3951 /* Move on to next cookie tag */
3958 assert(NULL != *header);
3959 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3968 #ifdef FEATURE_FORCE_LOAD
3969 /*********************************************************************
3971 * Function : strclean
3973 * Description : In-Situ-Eliminate all occurances of substring in
3977 * 1 : string = string to clean
3978 * 2 : substring = substring to eliminate
3980 * Returns : Number of eliminations
3982 *********************************************************************/
3983 int strclean(const char *string, const char *substring)
3989 len = strlen(substring);
3991 while((pos = strstr(string, substring)) != NULL)
3998 while (*p++ != '\0');
4005 #endif /* def FEATURE_FORCE_LOAD */
4008 /*********************************************************************
4010 * Function : parse_header_time
4012 * Description : Parses time formats used in HTTP header strings
4013 * to get the numerical respresentation.
4016 * 1 : header_time = HTTP header time as string.
4017 * 2 : result = storage for header_time in seconds
4019 * Returns : JB_ERR_OK if the time format was recognized, or
4020 * JB_ERR_PARSE otherwise.
4022 *********************************************************************/
4023 static jb_err parse_header_time(const char *header_time, time_t *result)
4028 * Zero out gmt to prevent time zone offsets.
4030 * While this is only necessary on some platforms
4031 * (mingw32 for example), I don't know how to
4032 * detect these automatically and doing it everywhere
4035 memset(&gmt, 0, sizeof(gmt));
4037 /* Tue, 02 Jun 2037 20:00:00 */
4038 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4039 /* Tue, 02-Jun-2037 20:00:00 */
4040 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4041 /* Tue, 02-Jun-37 20:00:00 */
4042 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4043 /* Tuesday, 02-Jun-2037 20:00:00 */
4044 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4045 /* Tuesday Jun 02 20:00:00 2037 */
4046 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4048 return JB_ERR_PARSE;
4051 *result = timegm(&gmt);
4058 /*********************************************************************
4060 * Function : get_destination_from_headers
4062 * Description : Parse the "Host:" header to get the request's destination.
4063 * Only needed if the client's request was forcefully
4064 * redirected into Privoxy.
4066 * Code mainly copied from client_host() which is currently
4067 * run too late for this purpose.
4070 * 1 : headers = List of headers (one of them hopefully being
4071 * the "Host:" header)
4072 * 2 : http = storage for the result (host, port and hostport).
4074 * Returns : JB_ERR_MEMORY in case of memory problems,
4075 * JB_ERR_PARSE if the host header couldn't be found,
4076 * JB_ERR_OK otherwise.
4078 *********************************************************************/
4079 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4085 host = get_header_value(headers, "Host:");
4089 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4090 return JB_ERR_PARSE;
4093 if (NULL == (p = strdup((host))))
4095 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4096 return JB_ERR_MEMORY;
4099 if (NULL == (q = strdup(p)))
4102 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4103 return JB_ERR_MEMORY;
4106 freez(http->hostport);
4110 q = strchr(http->host, ':');
4113 /* Terminate hostname and evaluate port string */
4115 http->port = atoi(q);
4119 http->port = http->ssl ? 443 : 80;
4122 /* Rebuild request URL */
4124 http->url = strdup(http->ssl ? "https://" : "http://");
4125 string_append(&http->url, http->hostport);
4126 string_append(&http->url, http->path);
4127 if (http->url == NULL)
4129 return JB_ERR_MEMORY;
4132 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4140 /*********************************************************************
4142 * Function : create_forged_referrer
4144 * Description : Helper for client_referrer to forge a referer as
4145 * 'http://[hostname:port/' to fool stupid
4146 * checks for in-site links
4149 * 1 : header = Pointer to header pointer
4150 * 2 : hostport = Host and optionally port as string
4152 * Returns : JB_ERR_OK in case of success, or
4153 * JB_ERR_MEMORY in case of memory problems.
4155 *********************************************************************/
4156 static jb_err create_forged_referrer(char **header, const char *hostport)
4158 assert(NULL == *header);
4160 *header = strdup("Referer: http://");
4161 string_append(header, hostport);
4162 string_append(header, "/");
4164 if (NULL == *header)
4166 return JB_ERR_MEMORY;
4169 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4176 /*********************************************************************
4178 * Function : create_fake_referrer
4180 * Description : Helper for client_referrer to create a fake referrer
4181 * based on a string supplied by the user.
4184 * 1 : header = Pointer to header pointer
4185 * 2 : hosthost = Referrer to fake
4187 * Returns : JB_ERR_OK in case of success, or
4188 * JB_ERR_MEMORY in case of memory problems.
4190 *********************************************************************/
4191 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4193 assert(NULL == *header);
4195 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4197 log_error(LOG_LEVEL_HEADER,
4198 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4200 *header = strdup("Referer: ");
4201 string_append(header, fake_referrer);
4203 if (NULL == *header)
4205 return JB_ERR_MEMORY;
4208 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4215 /*********************************************************************
4217 * Function : handle_conditional_hide_referrer_parameter
4219 * Description : Helper for client_referrer to crunch or forge
4220 * the referrer header if the host has changed.
4223 * 1 : header = Pointer to header pointer
4224 * 2 : host = The target host (may include the port)
4225 * 3 : parameter_conditional_block = Boolean to signal
4226 * if we're in conditional-block mode. If not set,
4227 * we're in conditional-forge mode.
4229 * Returns : JB_ERR_OK in case of success, or
4230 * JB_ERR_MEMORY in case of memory problems.
4232 *********************************************************************/
4233 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4234 const char *host, const int parameter_conditional_block)
4236 char *referer = strdup(*header);
4237 const size_t hostlenght = strlen(host);
4239 if (NULL == referer)
4242 return JB_ERR_MEMORY;
4245 /* referer begins with 'Referer: http[s]://' */
4246 if (hostlenght < (strlen(referer)-17))
4249 * Shorten referer to make sure the referer is blocked
4250 * if www.example.org/www.example.com-shall-see-the-referer/
4251 * links to www.example.com/
4253 referer[hostlenght+17] = '\0';
4255 if (NULL == strstr(referer, host))
4257 /* Host has changed */
4258 if (parameter_conditional_block)
4260 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4267 return create_forged_referrer(header, host);