1 const char parsers_rcs[] = "$Id: parsers.c,v 1.114 2007/10/19 16:56:26 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.114 2007/10/19 16:56:26 fabiankeil
48 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
49 * - Use shiny new content_filters_enabled() in client_range().
51 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
52 * I forgot about Poland.
54 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
55 * Remove Range and If-Range headers if content filtering is enabled.
57 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
58 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
59 * client_cookie_adder() to make sure send-vanilla-wafer can be
60 * controlled through tags (and thus regression-tested).
62 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
63 * - Remove "scanning headers for" log message again.
64 * - Some more whitespace fixes.
66 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
67 * Refactor client_referrer() and add conditional-forge parameter.
69 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
70 * A bunch of whitespace fixes, pointy hat to me.
72 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
73 * Fix possible memory corruption in server_http, make sure it's not
74 * executed for ordinary server headers and mark some problems for later.
76 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
77 * Let content-type-overwrite{} honour force-text-mode again.
79 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
80 * - Add prototpyes for the header parsers and make them static.
81 * - Comment out client_accept_encoding_adder() which isn't used right now.
83 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
84 * Move the ACTION_FORCE_TEXT_MODE check out of
85 * server_content_type(). Signal other functions
86 * whether or not a content type has been declared.
87 * Part of the fix for BR#1750917.
89 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
90 * Change sed() to return a jb_err in preparation for forward-override{}.
92 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
93 * Adjust "X-Filter: No" to disable dedicated header filters.
95 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
96 * Streamline client_cookie_adder().
98 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
99 * Make sure filters with dynamic jobs actually use them.
101 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
102 * - Introduce dynamic pcrs jobs that can resolve variables.
103 * - Remove unnecessary update_action_bits_for_all_tags() call.
105 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
106 * - Make tagging based on tags set by earlier taggers
107 * of the same kind possible.
108 * - Log whether or not new tags cause action bits updates
109 * (in which case a matching tag-pattern section exists).
110 * - Log if the user tries to set a tag that is already set.
112 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
113 * Introduce tags as alternative way to specify which
114 * actions apply to a request. At the moment tags can be
115 * created based on client and server headers.
117 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
118 * Log a warning if the content is compressed, filtering is
119 * enabled and Privoxy was compiled without zlib support.
122 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
123 * - Fix warnings when compiled with glibc.
124 * - Don't use crumble() for cookie crunching.
125 * - Move cookie time parsing into parse_header_time().
126 * - Let parse_header_time() return a jb_err code
127 * instead of a pointer that can only be used to
128 * check for NULL anyway.
130 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
131 * - Add better protection against malicious gzip headers.
132 * - Stop logging the first hundred bytes of decompressed content.
133 * It looks like it's working and there is always debug 16.
134 * - Log the content size after decompression in decompress_iob()
135 * instead of pcrs_filter_response().
137 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
138 * - Use dedicated header filter actions instead of abusing "filter".
139 * Replace "filter-client-headers" and "filter-client-headers"
140 * with "server-header-filter" and "client-header-filter".
141 * - Remove filter_client_header() and filter_client_header(),
142 * filter_header() now checks the shiny new
143 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
145 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
146 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
147 * - Handle "Cookie:" and "Connection:" headers a bit smarter
148 * (don't crunch them just to recreate them later on).
149 * - Add another non-standard time format for the cookie
150 * expiration date detection.
151 * - Fix a valgrind warning.
153 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
154 * Improve cookie expiration date detection.
156 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
157 * Don't run server_content_length() the first time
158 * sed() parses server headers; only adjust the
159 * Content-Length header if the page was modified.
161 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
162 * Fix log messages regarding the cookie time format
163 * (cookie and request URL were mixed up).
165 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
166 * - Let decompress_iob()
167 * - not corrupt the content if decompression fails
168 * early. (the first byte(s) were lost).
169 * - use pointer arithmetics with defined outcome for
171 * - Use a different kludge to remember a failed decompression.
173 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
174 * Search for Max-Forwards headers case-insensitive,
175 * don't generate the "501 unsupported" message for invalid
176 * Max-Forwards values and don't increase negative ones.
178 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
179 * - Let server_set_cookie() check the expiration date
180 * of cookies and don't touch the ones that are already
181 * expired. Fixes problems with low quality web applications
182 * as described in BR 932612.
184 * - Adjust comment in client_max_forwards to reality;
185 * remove invalid Max-Forwards headers.
187 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
188 * Stop filter_header() from unintentionally removing
189 * empty header lines that were enlisted by the continue
192 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
193 * - Repeat the request URL before logging any headers.
194 * Makes reading the log easier in case of simultaneous requests.
195 * - If there are more than one Content-Type headers in one request,
196 * use the first one and remove the others.
197 * - Remove "newval" variable in server_content_type().
198 * It's only used once.
200 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
201 * Correct a cast, check inflateEnd() exit code
202 * to see if we have to, replace sprintf calls
205 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
206 * Integrate a modified version of Wil Mahan's
207 * zlib patch (PR #895531).
209 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
210 * Skip empty filter files in filter_header()
211 * but don't ignore the ones that come afterwards.
212 * Fixes BR 1619208, this time for real.
214 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
215 * Reverted parts of my last commit
216 * to keep error handling working.
218 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
219 * Fixed gcc43 conversion warnings.
221 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
222 * Bringing back the "useless" localtime() call
223 * I removed in revision 1.67. On some platforms
224 * it's necessary to prevent time zone offsets.
226 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
227 * Rebuild request URL in get_destination_from_headers()
228 * to make sure redirect{pcrs command} works as expected
229 * for intercepted requests.
231 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
232 * Added get_destination_from_headers().
234 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
235 * Make pthread mutex locking more generic. Instead of
236 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
237 * and use mutex locking unless there is an _r function
238 * available. Better safe than sorry.
240 * Fixes "./configure --disable-pthread" and should result
241 * in less threading-related problems on pthread-using platforms,
242 * but it still doesn't fix BR#1122404.
244 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
245 * The special header "X-Filter: No" now disables
246 * header filtering as well.
248 * Revision 1.73 2006/09/23 13:26:38 roro
249 * Replace TABs by spaces in source code.
251 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
252 * Don't print a log message every time filter_headers is
253 * entered or left. It only creates noise without any real
256 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
257 * Fix +hide-if-modified-since{-n}.
259 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
260 * Have hide-if-modified-since interpret the random
261 * range value as minutes instead of hours. Allows
262 * more fine-grained configuration.
264 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
265 * Always have parse_header_time return a pointer
266 * that actual makes sense, even though we currently
267 * only need it to detect problems.
269 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
270 * Added config option enable-remote-http-toggle
271 * to specify if Privoxy should recognize special
272 * headers (currently only X-Filter) to change its
273 * behaviour. Disabled by default.
275 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
276 * After filtering de-chunked instances, remove
277 * "Transfer-Encoding" header entirely instead of changing
278 * it to "Transfer-Encoding: identity", which is invalid.
279 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
281 * Don't use localtime in parse_header_time. An empty time struct
282 * is good enough, it gets overwritten by strptime anyway.
284 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
285 * Use gmtime_r if available, fallback to gmtime with mutex
286 * protection for MacOSX and use vanilla gmtime for the rest.
288 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
289 * Changed client_referrer to use the right type (size_t) for
290 * hostlenght and to shorten the temporary referrer string with
291 * '\0' instead of adding a useless line break.
293 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
294 * - Back to timegm() using GnuPG's replacement if necessary.
295 * Using mktime() and localtime() could add a on hour offset if
296 * the randomize factor was big enough to lead to a summer/wintertime
299 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
301 * - Moved randomization code into pick_from_range().
303 * - Changed parse_header_time definition.
304 * time_t isn't guaranteed to be signed and
305 * if it isn't, -1 isn't available as error code.
306 * Changed some variable types in client_if_modified_since()
307 * because of the same reason.
309 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
310 * OS/2 compilation compatibility fixups
312 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
313 * Changed include from strptime.c to strptime.h
315 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
316 * Split filter-headers{} into filter-client-headers{}
317 * and filter-server-headers{}.
318 * Added parse_header_time() to share some code.
319 * Replaced timegm() with mktime().
321 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
322 * Windows service integration
324 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
325 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
327 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
328 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
329 * with what was really the latest development (the v_3_0_branch branch)
331 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
332 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
334 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
335 * Add the ability to check jpeg images for invalid
336 * lengths of comment blocks. Defensive strategy
337 * against the exploit:
338 * Microsoft Security Bulletin MS04-028
339 * Buffer Overrun in JPEG Processing (GDI+) Could
340 * Allow Code Execution (833987)
341 * Enabled with +inspect-jpegs in actions files.
343 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
344 * Excluded text/plain objects from filtering. This fixes a
345 * couple of client-crashing, download corruption and
346 * Privoxy performance issues, whose root cause lies in
347 * web servers labelling content of unknown type as text/plain.
349 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
350 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
352 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
353 * Completing the previous change
355 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
356 * Added temporary workaround for bug in PHP < 4.2.3
358 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
359 * 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.
361 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
362 * Fix typo: supressed -> suppressed
364 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
365 * Improved cookie logging
367 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
368 * Added basic support for OPTIONS and TRACE HTTP methods:
369 * - New parser function client_max_forwards which decrements
370 * the Max-Forwards HTTP header field of OPTIONS and TRACE
371 * requests by one before forwarding
372 * - New parser function client_host which extracts the host
373 * and port information from the HTTP header field if the
374 * request URI was not absolute
375 * - Don't crumble and re-add the Host: header, but only generate
376 * and append if missing
378 * Revision 1.56 2002/05/12 15:34:22 jongfoster
379 * Fixing typo in a comment
381 * Revision 1.55 2002/05/08 16:01:07 oes
382 * Optimized add_to_iob:
383 * - Use realloc instead of malloc(), memcpy(), free()
384 * - Expand to powers of two if possible, to get
385 * O(log n) reallocs instead of O(n).
386 * - Moved check for buffer limit here from chat
387 * - Report failure via returncode
389 * Revision 1.54 2002/04/02 15:03:16 oes
390 * Tiny code cosmetics
392 * Revision 1.53 2002/03/26 22:29:55 swa
393 * we have a new homepage!
395 * Revision 1.52 2002/03/24 13:25:43 swa
396 * name change related issues
398 * Revision 1.51 2002/03/13 00:27:05 jongfoster
401 * Revision 1.50 2002/03/12 01:45:35 oes
402 * More verbose logging
404 * Revision 1.49 2002/03/09 20:03:52 jongfoster
405 * - Making various functions return int rather than size_t.
406 * (Undoing a recent change). Since size_t is unsigned on
407 * Windows, functions like read_socket that return -1 on
408 * error cannot return a size_t.
410 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
411 * crashes, and also frequently caused JB to jump to 100%
412 * CPU and stay there. (Because it thought it had just
413 * read ((unsigned)-1) == 4Gb of data...)
415 * - The signature of write_socket has changed, it now simply
416 * returns success=0/failure=nonzero.
418 * - Trying to get rid of a few warnings --with-debug on
419 * Windows, I've introduced a new type "jb_socket". This is
420 * used for the socket file descriptors. On Windows, this
421 * is SOCKET (a typedef for unsigned). Everywhere else, it's
422 * an int. The error value can't be -1 any more, so it's
423 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
424 * Windows it maps to the #define INVALID_SOCKET.)
426 * - The signature of bind_port has changed.
428 * Revision 1.48 2002/03/07 03:46:53 oes
429 * Fixed compiler warnings etc
431 * Revision 1.47 2002/02/20 23:15:13 jongfoster
432 * Parsing functions now handle out-of-memory gracefully by returning
435 * Revision 1.46 2002/01/17 21:03:47 jongfoster
436 * Moving all our URL and URL pattern parsing code to urlmatch.c.
438 * Revision 1.45 2002/01/09 14:33:03 oes
439 * Added support for localtime_r.
441 * Revision 1.44 2001/12/14 01:22:54 steudten
442 * Remove 'user:pass@' from 'proto://user:pass@host' for the
443 * new added header 'Host: ..'. (See Req ID 491818)
445 * Revision 1.43 2001/11/23 00:26:38 jongfoster
446 * Fixing two really stupid errors in my previous commit
448 * Revision 1.42 2001/11/22 21:59:30 jongfoster
449 * Adding code to handle +no-cookies-keep
451 * Revision 1.41 2001/11/05 23:43:05 steudten
452 * Add time+date to log files.
454 * Revision 1.40 2001/10/26 20:13:09 jongfoster
455 * ctype.h is needed in Windows, too.
457 * Revision 1.39 2001/10/26 17:40:04 oes
458 * Introduced get_header_value()
459 * Removed http->user_agent, csp->referrer and csp->accept_types
460 * Removed client_accept()
462 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
463 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
464 * threads to call select() simultaneously. So, it's time to do a real, live,
465 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
466 * (native). Both versions will work, but using __OS2__ offers multi-threading.
468 * Revision 1.37 2001/10/23 21:36:02 jongfoster
469 * Documenting sed()'s error behaviou (doc change only)
471 * Revision 1.36 2001/10/13 12:51:51 joergs
472 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
473 * force-load), instead crumble Host: and add it (again) in client_host_adder
474 * (in case we get a HTTP/1.0 request without Host: header and forward it to
475 * a HTTP/1.1 server/proxy).
477 * Revision 1.35 2001/10/09 22:39:21 jongfoster
478 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
481 * Revision 1.34 2001/10/07 18:50:55 oes
482 * Added server_content_encoding, renamed server_transfer_encoding
484 * Revision 1.33 2001/10/07 18:04:49 oes
485 * Changed server_http11 to server_http and its pattern to "HTTP".
486 * Additional functionality: it now saves the HTTP status into
487 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
489 * Revision 1.32 2001/10/07 15:43:28 oes
490 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
491 * client_te and client_accept_encoding_adder, triggered by the new
492 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
493 * changed to allow only identity and chunked, and the TE header is
494 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
496 * parse_http_request no longer does anything than parsing. The rewriting
497 * of http->cmd and version mangling are gone. It now also recognizes
498 * the put and delete methods and saves the url in http->url. Removed
501 * renamed content_type and content_length to have the server_ prefix
503 * server_content_type now only works if csp->content_type != CT_TABOO
505 * added server_transfer_encoding, which
506 * - Sets CT_TABOO to prohibit filtering if encoding compresses
507 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
508 * - Change from "chunked" to "identity" if body was chunked
509 * but has been de-chunked for filtering.
511 * added server_content_md5 which crunches any Content-MD5 headers
512 * if the body was modified.
514 * made server_http11 conditional on +downgrade action
516 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
518 * Revision 1.31 2001/10/05 14:25:02 oes
519 * Crumble Keep-Alive from Server
521 * Revision 1.30 2001/09/29 12:56:03 joergs
522 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
524 * Revision 1.29 2001/09/24 21:09:24 jongfoster
525 * Fixing 2 memory leaks that Guy spotted, where the paramater to
526 * enlist() was not being free()d.
528 * Revision 1.28 2001/09/22 16:32:28 jongfoster
529 * Removing unused #includes.
531 * Revision 1.27 2001/09/20 15:45:25 steudten
533 * add casting from size_t to int for printf()
534 * remove local variable shadow s2
536 * Revision 1.26 2001/09/16 17:05:14 jongfoster
537 * Removing unused #include showarg.h
539 * Revision 1.25 2001/09/16 13:21:27 jongfoster
540 * Changes to use new list functions.
542 * Revision 1.24 2001/09/13 23:05:50 jongfoster
543 * Changing the string paramater to the header parsers a "const".
545 * Revision 1.23 2001/09/12 18:08:19 steudten
547 * In parse_http_request() header rewriting miss the host value, so
548 * from http://www.mydomain.com the result was just " / " not
549 * http://www.mydomain.com/ in case we forward.
551 * Revision 1.22 2001/09/10 10:58:53 oes
552 * Silenced compiler warnings
554 * Revision 1.21 2001/07/31 14:46:00 oes
555 * - Persistant connections now suppressed
556 * - sed() no longer appends empty header to csp->headers
558 * Revision 1.20 2001/07/30 22:08:36 jongfoster
559 * Tidying up #defines:
560 * - All feature #defines are now of the form FEATURE_xxx
561 * - Permanently turned off WIN_GUI_EDIT
562 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
564 * Revision 1.19 2001/07/25 17:21:54 oes
565 * client_uagent now saves copy of User-Agent: header value
567 * Revision 1.18 2001/07/13 14:02:46 oes
568 * - Included fix to repair broken HTTP requests that
569 * don't contain a path, not even '/'.
570 * - Removed all #ifdef PCRS
571 * - content_type now always inspected and classified as
572 * text, gif or other.
573 * - formatting / comments
575 * Revision 1.17 2001/06/29 21:45:41 oes
576 * Indentation, CRLF->LF, Tab-> Space
578 * Revision 1.16 2001/06/29 13:32:42 oes
580 * - Adapted free_http_request
581 * - Removed logentry from cancelled commit
583 * Revision 1.15 2001/06/03 19:12:38 oes
584 * deleted const struct interceptors
586 * Revision 1.14 2001/06/01 18:49:17 jongfoster
587 * Replaced "list_share" with "list" - the tiny memory gain was not
588 * worth the extra complexity.
590 * Revision 1.13 2001/05/31 21:30:33 jongfoster
591 * Removed list code - it's now in list.[ch]
592 * Renamed "permission" to "action", and changed many features
593 * to use the actions file rather than the global config.
595 * Revision 1.12 2001/05/31 17:33:13 oes
599 * Revision 1.11 2001/05/29 20:11:19 joergs
600 * '/ * inside comment' warning removed.
602 * Revision 1.10 2001/05/29 09:50:24 jongfoster
603 * Unified blocklist/imagelist/permissionslist.
604 * File format is still under discussion, but the internal changes
607 * Also modified interceptor behaviour:
608 * - We now intercept all URLs beginning with one of the following
609 * prefixes (and *only* these prefixes):
611 * * http://ijbswa.sf.net/config/
612 * * http://ijbswa.sourceforge.net/config/
613 * - New interceptors "home page" - go to http://i.j.b/ to see it.
614 * - Internal changes so that intercepted and fast redirect pages
615 * are not replaced with an image.
616 * - Interceptors now have the option to send a binary page direct
617 * to the client. (i.e. ijb-send-banner uses this)
618 * - Implemented show-url-info interceptor. (Which is why I needed
619 * the above interceptors changes - a typical URL is
620 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
621 * The previous mechanism would not have intercepted that, and
622 * if it had been intercepted then it then it would have replaced
625 * Revision 1.9 2001/05/28 17:26:33 jongfoster
626 * Fixing segfault if last header was crunched.
627 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
628 * can use the cross-platform sprintf() instead.)
630 * Revision 1.8 2001/05/27 22:17:04 oes
632 * - re_process_buffer no longer writes the modified buffer
633 * to the client, which was very ugly. It now returns the
634 * buffer, which it is then written by chat.
636 * - content_length now adjusts the Content-Length: header
637 * for modified documents rather than crunch()ing it.
638 * (Length info in csp->content_length, which is 0 for
639 * unmodified documents)
641 * - For this to work, sed() is called twice when filtering.
643 * Revision 1.7 2001/05/27 13:19:06 oes
644 * Patched Joergs solution for the content-length in.
646 * Revision 1.6 2001/05/26 13:39:32 jongfoster
647 * Only crunches Content-Length header if applying RE filtering.
648 * Without this fix, Microsoft Windows Update wouldn't work.
650 * Revision 1.5 2001/05/26 00:28:36 jongfoster
651 * Automatic reloading of config file.
652 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
653 * Most of the global variables have been moved to a new
654 * struct configuration_spec, accessed through csp->config->globalname
655 * Most of the globals remaining are used by the Win32 GUI.
657 * Revision 1.4 2001/05/22 18:46:04 oes
659 * - Enabled filtering banners by size rather than URL
660 * by adding patterns that replace all standard banner
661 * sizes with the "Junkbuster" gif to the re_filterfile
663 * - Enabled filtering WebBugs by providing a pattern
664 * which kills all 1x1 images
666 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
667 * which is selected by the (nonstandard and therefore
668 * capital) letter 'U' in the option string.
669 * It causes the quantifiers to be ungreedy by default.
670 * Appending a ? turns back to greedy (!).
672 * - Added a new interceptor ijb-send-banner, which
673 * sends back the "Junkbuster" gif. Without imagelist or
674 * MSIE detection support, or if tinygif = 1, or the
675 * URL isn't recognized as an imageurl, a lame HTML
676 * explanation is sent instead.
678 * - Added new feature, which permits blocking remote
679 * script redirects and firing back a local redirect
681 * The feature is conditionally compiled, i.e. it
682 * can be disabled with --disable-fast-redirects,
683 * plus it must be activated by a "fast-redirects"
684 * line in the config file, has its own log level
685 * and of course wants to be displayed by show-proxy-args
686 * Note: Boy, all the #ifdefs in 1001 locations and
687 * all the fumbling with configure.in and acconfig.h
688 * were *way* more work than the feature itself :-(
690 * - Because a generic redirect template was needed for
691 * this, tinygif = 3 now uses the same.
693 * - Moved GIFs, and other static HTTP response templates
698 * - Removed some >400 CRs again (Jon, you really worked
701 * Revision 1.3 2001/05/20 01:21:20 jongfoster
702 * Version 2.9.4 checkin.
703 * - Merged popupfile and cookiefile, and added control over PCRS
704 * filtering, in new "permissionsfile".
705 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
706 * file error you now get a message box (in the Win32 GUI) rather
707 * than the program exiting with no explanation.
708 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
710 * - Removed tabs from "config"
711 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
712 * - Bumped up version number.
714 * Revision 1.2 2001/05/17 23:02:36 oes
715 * - Made referrer option accept 'L' as a substitute for '§'
717 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
718 * Initial import of version 2.9.3 source tree
721 *********************************************************************/
728 #include <sys/types.h>
738 * Convince GNU's libc to provide a strptime prototype.
741 #endif /*__GLIBC__ */
748 #if !defined(_WIN32) && !defined(__OS2__)
754 #ifdef FEATURE_PTHREAD
756 /* jcc.h is for mutex semapores only */
757 #endif /* def FEATURE_PTHREAD */
763 #include "jbsockets.h"
764 #include "miscutil.h"
769 #ifndef HAVE_STRPTIME
770 #include "strptime.h"
773 const char parsers_h_rcs[] = PARSERS_H_VERSION;
775 /* Fix a problem with Solaris. There should be no effect on other
777 * Solaris's isspace() is a macro which uses its argument directly
778 * as an array index. Therefore we need to make sure that high-bit
779 * characters generate +ve values, and ideally we also want to make
780 * the argument match the declared parameter type of "int".
782 * Why did they write a character function that can't take a simple
783 * "char" argument? Doh!
785 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
786 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
788 static jb_err scan_headers(struct client_state *csp);
789 static jb_err header_tagger(struct client_state *csp, char *header);
790 static jb_err parse_header_time(const char *header_time, time_t *result);
792 static jb_err crumble (struct client_state *csp, char **header);
793 static jb_err connection (struct client_state *csp, char **header);
794 static jb_err filter_header (struct client_state *csp, char **header);
795 static jb_err client_referrer (struct client_state *csp, char **header);
796 static jb_err client_uagent (struct client_state *csp, char **header);
797 static jb_err client_ua (struct client_state *csp, char **header);
798 static jb_err client_from (struct client_state *csp, char **header);
799 static jb_err client_send_cookie (struct client_state *csp, char **header);
800 static jb_err client_x_forwarded (struct client_state *csp, char **header);
801 static jb_err client_accept_encoding (struct client_state *csp, char **header);
802 static jb_err client_te (struct client_state *csp, char **header);
803 static jb_err client_max_forwards (struct client_state *csp, char **header);
804 static jb_err client_host (struct client_state *csp, char **header);
805 static jb_err client_if_modified_since (struct client_state *csp, char **header);
806 static jb_err client_accept_language (struct client_state *csp, char **header);
807 static jb_err client_if_none_match (struct client_state *csp, char **header);
808 static jb_err crunch_client_header (struct client_state *csp, char **header);
809 static jb_err client_x_filter (struct client_state *csp, char **header);
810 static jb_err client_range (struct client_state *csp, char **header);
811 static jb_err server_set_cookie (struct client_state *csp, char **header);
812 static jb_err server_content_type (struct client_state *csp, char **header);
813 static jb_err server_content_length (struct client_state *csp, char **header);
814 static jb_err server_content_md5 (struct client_state *csp, char **header);
815 static jb_err server_content_encoding (struct client_state *csp, char **header);
816 static jb_err server_transfer_coding (struct client_state *csp, char **header);
817 static jb_err server_http (struct client_state *csp, char **header);
818 static jb_err crunch_server_header (struct client_state *csp, char **header);
819 static jb_err server_last_modified (struct client_state *csp, char **header);
820 static jb_err server_content_disposition(struct client_state *csp, char **header);
822 static jb_err client_host_adder (struct client_state *csp);
823 static jb_err client_cookie_adder (struct client_state *csp);
824 static jb_err client_xtra_adder (struct client_state *csp);
825 static jb_err client_x_forwarded_adder(struct client_state *csp);
826 static jb_err connection_close_adder (struct client_state *csp);
828 static jb_err create_forged_referrer(char **header, const char *hostport);
829 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
830 static jb_err handle_conditional_hide_referrer_parameter(char **header,
831 const char *host, const int parameter_conditional_block);
833 const struct parsers client_patterns[] = {
834 { "referer:", 8, client_referrer },
835 { "user-agent:", 11, client_uagent },
836 { "ua-", 3, client_ua },
837 { "from:", 5, client_from },
838 { "cookie:", 7, client_send_cookie },
839 { "x-forwarded-for:", 16, client_x_forwarded },
840 { "Accept-Encoding:", 16, client_accept_encoding },
841 { "TE:", 3, client_te },
842 { "Host:", 5, client_host },
843 { "if-modified-since:", 18, client_if_modified_since },
844 { "Keep-Alive:", 11, crumble },
845 { "connection:", 11, connection },
846 { "proxy-connection:", 17, crumble },
847 { "max-forwards:", 13, client_max_forwards },
848 { "Accept-Language:", 16, client_accept_language },
849 { "if-none-match:", 14, client_if_none_match },
850 { "Range:", 6, client_range },
851 { "If-Range:", 9, client_range },
852 { "X-Filter:", 9, client_x_filter },
853 { "*", 0, crunch_client_header },
854 { "*", 0, filter_header },
858 const struct parsers server_patterns[] = {
859 { "HTTP/", 5, server_http },
860 { "set-cookie:", 11, server_set_cookie },
861 { "connection:", 11, connection },
862 { "Content-Type:", 13, server_content_type },
863 { "Content-MD5:", 12, server_content_md5 },
864 { "Content-Encoding:", 17, server_content_encoding },
865 { "Transfer-Encoding:", 18, server_transfer_coding },
866 { "Keep-Alive:", 11, crumble },
867 { "content-disposition:", 20, server_content_disposition },
868 { "Last-Modified:", 14, server_last_modified },
869 { "*", 0, crunch_server_header },
870 { "*", 0, filter_header },
874 const struct parsers server_patterns_light[] = {
875 { "Content-Length:", 15, server_content_length },
876 { "Transfer-Encoding:", 18, server_transfer_coding },
878 { "Content-Encoding:", 17, server_content_encoding },
879 #endif /* def FEATURE_ZLIB */
883 const add_header_func_ptr add_client_headers[] = {
886 client_x_forwarded_adder,
888 /* Temporarily disabled: client_accept_encoding_adder, */
889 connection_close_adder,
893 const add_header_func_ptr add_server_headers[] = {
894 connection_close_adder,
898 /* The vanilla wafer. */
899 static const char VANILLA_WAFER[] =
900 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
901 "Do_not_send_me_any_copyrighted_information_other_than_the_"
902 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
903 "In_particular_do_not_send_me_any_cookies_that_"
904 "are_subject_to_a_claim_of_copyright_by_anybody._"
905 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
906 "(copyright_or_otherwise)_applying_to_any_cookie._";
908 /*********************************************************************
910 * Function : flush_socket
912 * Description : Write any pending "buffered" content.
915 * 1 : fd = file descriptor of the socket to read
916 * 2 : csp = Current client state (buffers, headers, etc...)
918 * Returns : On success, the number of bytes written are returned (zero
919 * indicates nothing was written). On error, -1 is returned,
920 * and errno is set appropriately. If count is zero and the
921 * file descriptor refers to a regular file, 0 will be
922 * returned without causing any other effect. For a special
923 * file, the results are not portable.
925 *********************************************************************/
926 int flush_socket(jb_socket fd, struct client_state *csp)
928 struct iob *iob = csp->iob;
929 int len = iob->eod - iob->cur;
936 if (write_socket(fd, iob->cur, (size_t)len))
940 iob->eod = iob->cur = iob->buf;
946 /*********************************************************************
948 * Function : add_to_iob
950 * Description : Add content to the buffered page, expanding the
951 * buffer if necessary.
954 * 1 : csp = Current client state (buffers, headers, etc...)
955 * 2 : buf = holds the content to be added to the page
956 * 3 : n = number of bytes to be added
958 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
959 * or buffer limit reached.
961 *********************************************************************/
962 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
964 struct iob *iob = csp->iob;
965 size_t used, offset, need, want;
968 if (n <= 0) return JB_ERR_OK;
970 used = (size_t)(iob->eod - iob->buf);
971 offset = (size_t)(iob->cur - iob->buf);
972 need = used + (size_t)n + 1;
975 * If the buffer can't hold the new data, extend it first.
976 * Use the next power of two if possible, else use the actual need.
978 if (need > csp->config->buffer_limit)
980 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
981 return JB_ERR_MEMORY;
984 if (need > iob->size)
986 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
988 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
992 else if (NULL != (p = (char *)realloc(iob->buf, need)))
998 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
999 return JB_ERR_MEMORY;
1002 /* Update the iob pointers */
1003 iob->cur = p + offset;
1004 iob->eod = p + used;
1008 /* copy the new data into the iob buffer */
1009 memcpy(iob->eod, buf, (size_t)n);
1011 /* point to the end of the data */
1014 /* null terminate == cheap insurance */
1023 /*********************************************************************
1025 * Function : decompress_iob
1027 * Description : Decompress buffered page, expanding the
1028 * buffer as necessary. csp->iob->cur
1029 * should point to the the beginning of the
1030 * compressed data block.
1033 * 1 : csp = Current client state (buffers, headers, etc...)
1035 * Returns : JB_ERR_OK on success,
1036 * JB_ERR_MEMORY if out-of-memory limit reached, and
1037 * JB_ERR_COMPRESS if error decompressing buffer.
1039 *********************************************************************/
1040 jb_err decompress_iob(struct client_state *csp)
1042 char *buf; /* new, uncompressed buffer */
1043 char *cur; /* Current iob position (to keep the original
1044 * iob->cur unmodified if we return early) */
1045 size_t bufsize; /* allocated size of the new buffer */
1046 size_t old_size; /* Content size before decompression */
1047 size_t skip_size; /* Number of bytes at the beginning of the iob
1048 that we should NOT decompress. */
1049 int status; /* return status of the inflate() call */
1050 z_stream zstr; /* used by calls to zlib */
1052 assert(csp->iob->cur - csp->iob->buf > 0);
1053 assert(csp->iob->eod - csp->iob->cur > 0);
1055 bufsize = csp->iob->size;
1056 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1057 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1059 cur = csp->iob->cur;
1064 * This is to protect the parsing of gzipped data,
1065 * but it should(?) be valid for deflated data also.
1067 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1068 return JB_ERR_COMPRESS;
1071 if (csp->content_type & CT_GZIP)
1074 * Our task is slightly complicated by the facts that data
1075 * compressed by gzip does not include a zlib header, and
1076 * that there is no easily accessible interface in zlib to
1077 * handle a gzip header. We strip off the gzip header by
1078 * hand, and later inform zlib not to expect a header.
1082 * Strip off the gzip header. Please see RFC 1952 for more
1083 * explanation of the appropriate fields.
1085 if ((*cur++ != (char)0x1f)
1086 || (*cur++ != (char)0x8b)
1087 || (*cur++ != Z_DEFLATED))
1089 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1090 return JB_ERR_COMPRESS;
1096 * XXX: These magic numbers should be replaced
1097 * with macros to give a better idea what they do.
1101 /* The gzip header has reserved bits set; bail out. */
1102 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1103 return JB_ERR_COMPRESS;
1107 /* Skip extra fields if necessary. */
1111 * Skip a given number of bytes, specified
1112 * as a 16-bit little-endian value.
1115 * XXX: This code used to be:
1117 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1119 * which I had to change into:
1121 * cur += *cur++ + (*cur++ << 8);
1123 * at which point gcc43 finally noticed that the value
1124 * of cur is undefined (it depends on which of the
1125 * summands is evaluated first).
1127 * I haven't come across a site where this
1128 * code is actually executed yet, but I hope
1132 skip_bytes = *cur++;
1133 skip_bytes = *cur++ << 8;
1135 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1138 * The number of bytes to skip should be positive
1139 * and we'd like to stay in the buffer.
1141 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1143 log_error(LOG_LEVEL_ERROR,
1144 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1146 return JB_ERR_COMPRESS;
1148 log_error(LOG_LEVEL_INFO,
1149 "Skipping %d bytes for gzip compression. Does this sound right?",
1154 /* Skip the filename if necessary. */
1157 /* A null-terminated string is supposed to follow. */
1158 while (*cur++ && (cur < csp->iob->eod));
1162 /* Skip the comment if necessary. */
1165 /* A null-terminated string is supposed to follow. */
1166 while (*cur++ && (cur < csp->iob->eod));
1169 /* Skip the CRC if necessary. */
1175 if (cur >= csp->iob->eod)
1178 * If the current position pointer reached or passed
1179 * the buffer end, we were obviously tricked to skip
1182 log_error(LOG_LEVEL_ERROR,
1183 "Malformed gzip header detected. Aborting decompression.");
1184 return JB_ERR_COMPRESS;
1188 else if (csp->content_type & CT_DEFLATE)
1191 * XXX: The debug level should be lowered
1192 * before the next stable release.
1194 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1196 * In theory (that is, according to RFC 1950), deflate-compressed
1197 * data should begin with a two-byte zlib header and have an
1198 * adler32 checksum at the end. It seems that in practice only
1199 * the raw compressed data is sent. Note that this means that
1200 * we are not RFC 1950-compliant here, but the advantage is that
1201 * this actually works. :)
1203 * We add a dummy null byte to tell zlib where the data ends,
1204 * and later inform it not to expect a header.
1206 * Fortunately, add_to_iob() has thoughtfully null-terminated
1207 * the buffer; we can just increment the end pointer to include
1214 log_error(LOG_LEVEL_ERROR,
1215 "Unable to determine compression format for decompression");
1216 return JB_ERR_COMPRESS;
1219 /* Set up the fields required by zlib. */
1220 zstr.next_in = (Bytef *)cur;
1221 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1222 zstr.zalloc = Z_NULL;
1223 zstr.zfree = Z_NULL;
1224 zstr.opaque = Z_NULL;
1227 * Passing -MAX_WBITS to inflateInit2 tells the library
1228 * that there is no zlib header.
1230 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1232 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1233 return JB_ERR_COMPRESS;
1237 * Next, we allocate new storage for the inflated data.
1238 * We don't modify the existing iob yet, so in case there
1239 * is error in decompression we can recover gracefully.
1241 buf = zalloc(bufsize);
1244 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1245 return JB_ERR_MEMORY;
1248 assert(bufsize >= skip_size);
1249 memcpy(buf, csp->iob->buf, skip_size);
1250 zstr.avail_out = bufsize - skip_size;
1251 zstr.next_out = (Bytef *)buf + skip_size;
1253 /* Try to decompress the whole stream in one shot. */
1254 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1256 /* We need to allocate more memory for the output buffer. */
1258 char *tmpbuf; /* used for realloc'ing the buffer */
1259 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1262 * If zlib wants more data then there's a problem, because
1263 * the complete compressed file should have been buffered.
1265 if (0 == zstr.avail_in)
1267 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1268 return JB_ERR_COMPRESS;
1272 * If we tried the limit and still didn't have enough
1273 * memory, just give up.
1275 if (bufsize == csp->config->buffer_limit)
1277 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1278 return JB_ERR_MEMORY;
1281 /* Try doubling the buffer size each time. */
1284 /* Don't exceed the buffer limit. */
1285 if (bufsize > csp->config->buffer_limit)
1287 bufsize = csp->config->buffer_limit;
1290 /* Try to allocate the new buffer. */
1291 tmpbuf = realloc(buf, bufsize);
1294 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1296 return JB_ERR_MEMORY;
1300 char *oldnext_out = (char *)zstr.next_out;
1303 * Update the fields for inflate() to use the new
1304 * buffer, which may be in a location different from
1307 zstr.avail_out += bufsize - oldbufsize;
1308 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1311 * Compare with an uglier method of calculating these values
1312 * that doesn't require the extra oldbufsize variable.
1314 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1315 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1316 assert(zstr.avail_out > 0);
1322 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1324 log_error(LOG_LEVEL_ERROR,
1325 "Inconsistent stream state after decompression: %s", zstr.msg);
1327 * XXX: Intentionally no return.
1329 * According to zlib.h, Z_STREAM_ERROR is returned
1330 * "if the stream state was inconsistent".
1332 * I assume in this case inflate()'s status
1333 * would also be something different than Z_STREAM_END
1334 * so this check should be redundant, but lets see.
1338 if (status != Z_STREAM_END)
1340 /* We failed to decompress the stream. */
1341 log_error(LOG_LEVEL_ERROR,
1342 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1343 return JB_ERR_COMPRESS;
1347 * Finally, we can actually update the iob, since the
1348 * decompression was successful. First, free the old
1351 freez(csp->iob->buf);
1353 /* Now, update the iob to use the new buffer. */
1354 csp->iob->buf = buf;
1355 csp->iob->cur = csp->iob->buf + skip_size;
1356 csp->iob->eod = (char *)zstr.next_out;
1357 csp->iob->size = bufsize;
1360 * Make sure the new uncompressed iob obeys some minimal
1361 * consistency conditions.
1363 if ((csp->iob->buf < csp->iob->cur)
1364 && (csp->iob->cur <= csp->iob->eod)
1365 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1367 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1370 log_error(LOG_LEVEL_RE_FILTER,
1371 "Decompression successful. Old size: %d, new size: %d.",
1372 old_size, new_size);
1376 /* zlib thinks this is OK, so lets do the same. */
1377 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1382 /* It seems that zlib did something weird. */
1383 log_error(LOG_LEVEL_ERROR,
1384 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1385 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1386 csp->iob->eod, csp->iob->buf + csp->iob->size);
1387 return JB_ERR_COMPRESS;
1393 #endif /* defined(FEATURE_ZLIB) */
1396 /*********************************************************************
1398 * Function : get_header
1400 * Description : This (odd) routine will parse the csp->iob
1403 * 1 : csp = Current client state (buffers, headers, etc...)
1405 * Returns : Any one of the following:
1407 * 1) a pointer to a dynamically allocated string that contains a header line
1408 * 2) NULL indicating that the end of the header was reached
1409 * 3) "" indicating that the end of the iob was reached before finding
1410 * a complete header line.
1412 *********************************************************************/
1413 char *get_header(struct client_state *csp)
1419 if ((iob->cur == NULL)
1420 || ((p = strchr(iob->cur, '\n')) == NULL))
1422 return(""); /* couldn't find a complete header */
1427 ret = strdup(iob->cur);
1430 /* FIXME No way to handle error properly */
1431 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1436 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1438 /* is this a blank line (i.e. the end of the header) ? */
1450 /*********************************************************************
1452 * Function : get_header_value
1454 * Description : Get the value of a given header from a chained list
1455 * of header lines or return NULL if no such header is
1456 * present in the list.
1459 * 1 : header_list = pointer to list
1460 * 2 : header_name = string with name of header to look for.
1461 * Trailing colon required, capitalization
1464 * Returns : NULL if not found, else value of header
1466 *********************************************************************/
1467 char *get_header_value(const struct list *header_list, const char *header_name)
1469 struct list_entry *cur_entry;
1473 assert(header_list);
1474 assert(header_name);
1475 length = strlen(header_name);
1477 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1481 if (!strncmpic(cur_entry->str, header_name, length))
1484 * Found: return pointer to start of value
1486 ret = (char *) (cur_entry->str + length);
1487 while (*ret && ijb_isspace(*ret)) ret++;
1501 /*********************************************************************
1503 * Function : scan_headers
1505 * Description : Scans headers, applies tags and updates action bits.
1508 * 1 : csp = Current client state (buffers, headers, etc...)
1510 * Returns : JB_ERR_OK
1512 *********************************************************************/
1513 static jb_err scan_headers(struct client_state *csp)
1515 struct list_entry *h; /* Header */
1516 jb_err err = JB_ERR_OK;
1518 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1520 /* Header crunch()ed in previous run? -> ignore */
1521 if (h->str == NULL) continue;
1522 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1523 err = header_tagger(csp, h->str);
1530 /*********************************************************************
1534 * Description : add, delete or modify lines in the HTTP header streams.
1535 * On entry, it receives a linked list of headers space
1536 * that was allocated dynamically (both the list nodes
1537 * and the header contents).
1539 * As a side effect it frees the space used by the original
1542 * XXX: should be split to remove the first_run hack.
1545 * 1 : pats = list of patterns to match against headers
1546 * 2 : more_headers = list of functions to add more
1547 * headers (client or server)
1548 * 3 : csp = Current client state (buffers, headers, etc...)
1550 * Returns : JB_ERR_OK in case off success, or
1551 * JB_ERR_MEMORY on out-of-memory error.
1553 *********************************************************************/
1554 jb_err sed(const struct parsers pats[],
1555 const add_header_func_ptr more_headers[],
1556 struct client_state *csp)
1558 struct list_entry *p;
1559 const struct parsers *v;
1560 const add_header_func_ptr *f;
1561 jb_err err = JB_ERR_OK;
1565 * If filtering is enabled, sed is run twice,
1566 * but most of the work needs to be done only once.
1568 first_run = (more_headers != NULL ) ? 1 : 0;
1570 if (first_run) /* Parse and print */
1574 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1576 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1578 /* Header crunch()ed in previous run? -> ignore */
1579 if (p->str == NULL) continue;
1581 /* Does the current parser handle this header? */
1582 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1584 err = v->parser(csp, (char **)&(p->str));
1588 /* place any additional headers on the csp->headers list */
1589 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1594 else /* Parse only */
1597 * The second run is only needed if the body was modified
1598 * and the content-lenght has changed.
1600 if (strncmpic(csp->http->cmd, "HEAD", 4))
1602 /*XXX: Code duplication */
1603 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1605 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1607 /* Header crunch()ed in previous run? -> ignore */
1608 if (p->str == NULL) continue;
1610 /* Does the current parser handle this header? */
1611 if (strncmpic(p->str, v->str, v->len) == 0)
1613 err = v->parser(csp, (char **)&(p->str));
1625 /*********************************************************************
1627 * Function : header_tagger
1629 * Description : Executes all text substitutions from applying
1630 * tag actions and saves the result as tag.
1632 * XXX: Shares enough code with filter_header() and
1633 * pcrs_filter_response() to warrant some helper functions.
1636 * 1 : csp = Current client state (buffers, headers, etc...)
1637 * 2 : header = Header that is used as tagger input
1639 * Returns : JB_ERR_OK on success and always succeeds
1641 *********************************************************************/
1642 static jb_err header_tagger(struct client_state *csp, char *header)
1644 int wanted_filter_type;
1645 int multi_action_index;
1649 struct file_list *fl;
1650 struct re_filterfile_spec *b;
1651 struct list_entry *tag_name;
1653 int found_filters = 0;
1654 const size_t header_length = strlen(header);
1656 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1658 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1659 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1663 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1664 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1667 /* Check if there are any filters */
1668 for (i = 0; i < MAX_AF_FILES; i++)
1681 if (0 == found_filters)
1683 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1687 for (i = 0; i < MAX_AF_FILES; i++)
1690 if ((NULL == fl) || (NULL == fl->f))
1693 * Either there are no filter files
1694 * left, or this filter file just
1695 * contains no valid filters.
1697 * Continue to be sure we don't miss
1698 * valid filter files that are chained
1699 * after empty or invalid ones.
1704 /* For all filters, */
1705 for (b = fl->f; b; b = b->next)
1707 if (b->type != wanted_filter_type)
1709 /* skip the ones we don't care about, */
1712 /* leaving only taggers that could apply, of which we use the ones, */
1713 for (tag_name = csp->action->multi[multi_action_index]->first;
1714 NULL != tag_name; tag_name = tag_name->next)
1716 /* that do apply, and */
1717 if (strcmp(b->name, tag_name->str) == 0)
1719 char *modified_tag = NULL;
1721 size_t size = header_length;
1722 pcrs_job *joblist = b->joblist;
1724 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1726 if (NULL == joblist)
1728 log_error(LOG_LEVEL_RE_FILTER,
1729 "Tagger %s has empty joblist. Nothing to do.", b->name);
1733 /* execute their pcrs_joblist on the header. */
1734 for (job = joblist; NULL != job; job = job->next)
1736 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1740 /* Success, continue with the modified version. */
1749 /* Tagger doesn't match */
1752 /* Regex failure, log it but continue anyway. */
1753 log_error(LOG_LEVEL_ERROR,
1754 "Problems with tagger \'%s\' and header \'%s\': %s",
1755 b->name, *header, pcrs_strerror(hits));
1757 freez(modified_tag);
1761 if (b->dynamic) pcrs_free_joblist(joblist);
1763 /* If this tagger matched */
1769 * There is to technical limitation which makes
1770 * it impossible to use empty tags, but I assume
1771 * no one would do it intentionally.
1774 log_error(LOG_LEVEL_INFO,
1775 "Tagger \'%s\' created an empty tag. Ignored.",
1780 if (!list_contains_item(csp->tags, tag))
1782 if (JB_ERR_OK != enlist(csp->tags, tag))
1784 log_error(LOG_LEVEL_ERROR,
1785 "Insufficient memory to add tag \'%s\', "
1786 "based on tagger \'%s\' and header \'%s\'",
1787 tag, b->name, *header);
1791 char *action_message;
1793 * update the action bits right away, to make
1794 * tagging based on tags set by earlier taggers
1795 * of the same kind possible.
1797 if (update_action_bits_for_tag(csp, tag))
1799 action_message = "Action bits updated accordingly.";
1803 action_message = "No action bits update necessary.";
1806 log_error(LOG_LEVEL_HEADER,
1807 "Tagger \'%s\' added tag \'%s\'. %s",
1808 b->name, tag, action_message);
1813 /* XXX: Is this log-worthy? */
1814 log_error(LOG_LEVEL_HEADER,
1815 "Tagger \'%s\' didn't add tag \'%s\'. "
1816 "Tag already present", b->name, tag);
1819 } /* if the tagger matched */
1820 } /* if the tagger applies */
1821 } /* for every tagger that could apply */
1822 } /* for all filters */
1823 } /* for all filter files */
1828 /* here begins the family of parser functions that reformat header lines */
1830 /*********************************************************************
1832 * Function : filter_header
1834 * Description : Executes all text substitutions from all applying
1835 * +(server|client)-header-filter actions on the header.
1836 * Most of the code was copied from pcrs_filter_response,
1837 * including the rather short variable names
1840 * 1 : csp = Current client state (buffers, headers, etc...)
1841 * 2 : header = On input, pointer to header to modify.
1842 * On output, pointer to the modified header, or NULL
1843 * to remove the header. This function frees the
1844 * original string if necessary.
1846 * Returns : JB_ERR_OK on success and always succeeds
1848 *********************************************************************/
1849 static jb_err filter_header(struct client_state *csp, char **header)
1853 size_t size = strlen(*header);
1855 char *newheader = NULL;
1858 struct file_list *fl;
1859 struct re_filterfile_spec *b;
1860 struct list_entry *filtername;
1862 int i, found_filters = 0;
1863 int wanted_filter_type;
1864 int multi_action_index;
1866 if (csp->flags & CSP_FLAG_NO_FILTERING)
1871 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1873 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1874 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1878 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1879 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1883 * Need to check the set of re_filterfiles...
1885 for (i = 0; i < MAX_AF_FILES; i++)
1898 if (0 == found_filters)
1900 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1904 for (i = 0; i < MAX_AF_FILES; i++)
1907 if ((NULL == fl) || (NULL == fl->f))
1910 * Either there are no filter files
1911 * left, or this filter file just
1912 * contains no valid filters.
1914 * Continue to be sure we don't miss
1915 * valid filter files that are chained
1916 * after empty or invalid ones.
1921 * For all applying +filter actions, look if a filter by that
1922 * name exists and if yes, execute its pcrs_joblist on the
1925 for (b = fl->f; b; b = b->next)
1927 if (b->type != wanted_filter_type)
1929 /* Skip other filter types */
1933 for (filtername = csp->action->multi[multi_action_index]->first;
1934 filtername ; filtername = filtername->next)
1936 if (strcmp(b->name, filtername->str) == 0)
1938 int current_hits = 0;
1939 pcrs_job *joblist = b->joblist;
1941 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1943 if (NULL == joblist)
1945 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1949 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1950 *header, size, b->name);
1952 /* Apply all jobs from the joblist */
1953 for (job = joblist; NULL != job; job = job->next)
1955 matches = pcrs_execute(job, *header, size, &newheader, &size);
1958 current_hits += matches;
1959 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1961 *header = newheader;
1963 else if ( 0 == matches )
1965 /* Filter doesn't change header */
1971 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1972 *header, b->name, pcrs_strerror(matches));
1973 if (newheader != NULL)
1975 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1981 if (b->dynamic) pcrs_free_joblist(joblist);
1983 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1984 hits += current_hits;
1991 * Additionally checking for hits is important because if
1992 * the continue hack is triggered, server headers can
1993 * arrive empty to separate multiple heads from each other.
1995 if ((0 == size) && hits)
1997 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2005 /*********************************************************************
2007 * Function : connection
2009 * Description : Makes sure that the value of the Connection: header
2010 * is "close" and signals connection_close_adder
2014 * 1 : csp = Current client state (buffers, headers, etc...)
2015 * 2 : header = On input, pointer to header to modify.
2016 * On output, pointer to the modified header, or NULL
2017 * to remove the header. This function frees the
2018 * original string if necessary.
2020 * Returns : JB_ERR_OK on success, or
2021 * JB_ERR_MEMORY on out-of-memory error.
2023 *********************************************************************/
2024 static jb_err connection(struct client_state *csp, char **header)
2026 char *old_header = *header;
2028 /* Do we have a 'Connection: close' header? */
2029 if (strcmpic(*header, "Connection: close"))
2031 /* No, create one */
2032 *header = strdup("Connection: close");
2035 return JB_ERR_MEMORY;
2037 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2041 /* Signal connection_close_adder() to return early. */
2042 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2044 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2048 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2055 /*********************************************************************
2057 * Function : crumble
2059 * Description : This is called if a header matches a pattern to "crunch"
2062 * 1 : csp = Current client state (buffers, headers, etc...)
2063 * 2 : header = On input, pointer to header to modify.
2064 * On output, pointer to the modified header, or NULL
2065 * to remove the header. This function frees the
2066 * original string if necessary.
2068 * Returns : JB_ERR_OK on success, or
2069 * JB_ERR_MEMORY on out-of-memory error.
2071 *********************************************************************/
2072 static jb_err crumble(struct client_state *csp, char **header)
2074 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2080 /*********************************************************************
2082 * Function : crunch_server_header
2084 * Description : Crunch server header if it matches a string supplied by the
2085 * user. Called from `sed'.
2088 * 1 : csp = Current client state (buffers, headers, etc...)
2089 * 2 : header = On input, pointer to header to modify.
2090 * On output, pointer to the modified header, or NULL
2091 * to remove the header. This function frees the
2092 * original string if necessary.
2094 * Returns : JB_ERR_OK on success and always succeeds
2096 *********************************************************************/
2097 static jb_err crunch_server_header(struct client_state *csp, char **header)
2099 const char *crunch_pattern;
2101 /* Do we feel like crunching? */
2102 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2104 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2106 /* Is the current header the lucky one? */
2107 if (strstr(*header, crunch_pattern))
2109 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2118 /*********************************************************************
2120 * Function : server_content_type
2122 * Description : Set the content-type for filterable types (text/.*,
2123 * .*xml.*, javascript and image/gif) unless filtering has been
2124 * forbidden (CT_TABOO) while parsing earlier headers.
2125 * NOTE: Since text/plain is commonly used by web servers
2126 * for files whose correct type is unknown, we don't
2127 * set CT_TEXT for it.
2130 * 1 : csp = Current client state (buffers, headers, etc...)
2131 * 2 : header = On input, pointer to header to modify.
2132 * On output, pointer to the modified header, or NULL
2133 * to remove the header. This function frees the
2134 * original string if necessary.
2136 * Returns : JB_ERR_OK on success, or
2137 * JB_ERR_MEMORY on out-of-memory error.
2139 *********************************************************************/
2140 static jb_err server_content_type(struct client_state *csp, char **header)
2142 /* Remove header if it isn't the first Content-Type header */
2143 if ((csp->content_type & CT_DECLARED))
2146 * Another, slightly slower, way to see if
2147 * we already parsed another Content-Type header.
2149 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2151 log_error(LOG_LEVEL_ERROR,
2152 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2160 * Signal that the Content-Type has been set.
2162 csp->content_type |= CT_DECLARED;
2164 if (!(csp->content_type & CT_TABOO))
2166 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2167 || strstr(*header, "xml")
2168 || strstr(*header, "application/x-javascript"))
2170 csp->content_type |= CT_TEXT;
2172 else if (strstr(*header, " image/gif"))
2174 csp->content_type |= CT_GIF;
2176 else if (strstr(*header, " image/jpeg"))
2178 csp->content_type |= CT_JPEG;
2183 * Are we messing with the content type?
2185 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2188 * Make sure the user doesn't accidently
2189 * change the content type of binary documents.
2191 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2194 *header = strdup("Content-Type: ");
2195 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2199 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2200 return JB_ERR_MEMORY;
2202 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2206 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2207 "Enable force-text-mode if you know what you're doing.", *header);
2215 /*********************************************************************
2217 * Function : server_transfer_coding
2219 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2220 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2221 * - Remove header if body was chunked but has been
2222 * de-chunked for filtering.
2225 * 1 : csp = Current client state (buffers, headers, etc...)
2226 * 2 : header = On input, pointer to header to modify.
2227 * On output, pointer to the modified header, or NULL
2228 * to remove the header. This function frees the
2229 * original string if necessary.
2231 * Returns : JB_ERR_OK on success, or
2232 * JB_ERR_MEMORY on out-of-memory error.
2234 *********************************************************************/
2235 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2238 * Turn off pcrs and gif filtering if body compressed
2240 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2244 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2246 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2247 csp->http->cmd, *header);
2248 #endif /* def FEATURE_ZLIB */
2249 csp->content_type = CT_TABOO;
2253 * Raise flag if body chunked
2255 if (strstr(*header, "chunked"))
2257 csp->flags |= CSP_FLAG_CHUNKED;
2260 * If the body was modified, it has been de-chunked first
2261 * and the header must be removed.
2263 * FIXME: If there is more than one transfer encoding,
2264 * only the "chunked" part should be removed here.
2266 if (csp->flags & CSP_FLAG_MODIFIED)
2268 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2277 /*********************************************************************
2279 * Function : server_content_encoding
2281 * Description : This function is run twice for each request,
2282 * unless FEATURE_ZLIB and filtering are disabled.
2284 * The first run is used to check if the content
2285 * is compressed, if FEATURE_ZLIB is disabled
2286 * filtering is then disabled as well, if FEATURE_ZLIB
2287 * is enabled the content is marked for decompression.
2289 * The second run is used to remove the Content-Encoding
2290 * header if the decompression was successful.
2293 * 1 : csp = Current client state (buffers, headers, etc...)
2294 * 2 : header = On input, pointer to header to modify.
2295 * On output, pointer to the modified header, or NULL
2296 * to remove the header. This function frees the
2297 * original string if necessary.
2299 * Returns : JB_ERR_OK on success, or
2300 * JB_ERR_MEMORY on out-of-memory error.
2302 *********************************************************************/
2303 static jb_err server_content_encoding(struct client_state *csp, char **header)
2306 if ((csp->flags & CSP_FLAG_MODIFIED)
2307 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2310 * We successfully decompressed the content,
2311 * and have to clean the header now, so the
2312 * client no longer expects compressed data..
2314 * XXX: There is a difference between cleaning
2315 * and removing it completely.
2317 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2320 else if (strstr(*header, "gzip"))
2322 /* Mark for gzip decompression */
2323 csp->content_type |= CT_GZIP;
2325 else if (strstr(*header, "deflate"))
2327 /* Mark for zlib decompression */
2328 csp->content_type |= CT_DEFLATE;
2330 else if (strstr(*header, "compress"))
2333 * We can't decompress this; therefore we can't filter
2336 csp->content_type |= CT_TABOO;
2338 #else /* !defined(FEATURE_ZLIB) */
2339 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2342 * Body is compressed, turn off pcrs and gif filtering.
2344 csp->content_type |= CT_TABOO;
2347 * Log a warning if the user expects the content to be filtered.
2349 if ((csp->rlist != NULL) &&
2350 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2352 log_error(LOG_LEVEL_INFO,
2353 "Compressed content detected, content filtering disabled. "
2354 "Consider recompiling Privoxy with zlib support or "
2355 "enable the prevent-compression action.");
2358 #endif /* defined(FEATURE_ZLIB) */
2365 /*********************************************************************
2367 * Function : server_content_length
2369 * Description : Adjust Content-Length header if we modified
2373 * 1 : csp = Current client state (buffers, headers, etc...)
2374 * 2 : header = On input, pointer to header to modify.
2375 * On output, pointer to the modified header, or NULL
2376 * to remove the header. This function frees the
2377 * original string if necessary.
2379 * Returns : JB_ERR_OK on success, or
2380 * JB_ERR_MEMORY on out-of-memory error.
2382 *********************************************************************/
2383 static jb_err server_content_length(struct client_state *csp, char **header)
2385 const size_t max_header_length = 80;
2387 /* Regenerate header if the content was modified. */
2388 if (csp->flags & CSP_FLAG_MODIFIED)
2391 *header = (char *) zalloc(max_header_length);
2392 if (*header == NULL)
2394 return JB_ERR_MEMORY;
2397 snprintf(*header, max_header_length, "Content-Length: %d",
2398 (int)csp->content_length);
2399 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2400 (int)csp->content_length);
2407 /*********************************************************************
2409 * Function : server_content_md5
2411 * Description : Crumble any Content-MD5 headers if the document was
2412 * modified. FIXME: Should we re-compute instead?
2415 * 1 : csp = Current client state (buffers, headers, etc...)
2416 * 2 : header = On input, pointer to header to modify.
2417 * On output, pointer to the modified header, or NULL
2418 * to remove the header. This function frees the
2419 * original string if necessary.
2421 * Returns : JB_ERR_OK on success, or
2422 * JB_ERR_MEMORY on out-of-memory error.
2424 *********************************************************************/
2425 static jb_err server_content_md5(struct client_state *csp, char **header)
2427 if (csp->flags & CSP_FLAG_MODIFIED)
2429 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2437 /*********************************************************************
2439 * Function : server_content_disposition
2441 * Description : If enabled, blocks or modifies the "content-disposition" header.
2442 * Called from `sed'.
2445 * 1 : csp = Current client state (buffers, headers, etc...)
2446 * 2 : header = On input, pointer to header to modify.
2447 * On output, pointer to the modified header, or NULL
2448 * to remove the header. This function frees the
2449 * original string if necessary.
2451 * Returns : JB_ERR_OK on success, or
2452 * JB_ERR_MEMORY on out-of-memory error.
2454 *********************************************************************/
2455 static jb_err server_content_disposition(struct client_state *csp, char **header)
2460 * Are we messing with the content-disposition header?
2462 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2468 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2470 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2473 * Blocking content-disposition header
2475 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2482 * Replacing content-disposition header
2485 *header = strdup("content-disposition: ");
2486 string_append(header, newval);
2488 if (*header == NULL)
2490 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2494 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2497 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2501 /*********************************************************************
2503 * Function : server_last_modified
2505 * Description : Changes Last-Modified header to the actual date
2506 * to help hide-if-modified-since.
2507 * Called from `sed'.
2510 * 1 : csp = Current client state (buffers, headers, etc...)
2511 * 2 : header = On input, pointer to header to modify.
2512 * On output, pointer to the modified header, or NULL
2513 * to remove the header. This function frees the
2514 * original string if necessary.
2516 * Returns : JB_ERR_OK on success, or
2517 * JB_ERR_MEMORY on out-of-memory error.
2519 *********************************************************************/
2520 static jb_err server_last_modified(struct client_state *csp, char **header)
2523 char buf[BUFFER_SIZE];
2526 #ifdef HAVE_GMTIME_R
2529 struct tm *timeptr = NULL;
2530 time_t now, last_modified;
2532 long int days, hours, minutes, seconds;
2535 * Are we messing with the Last-Modified header?
2537 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2543 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2545 if (0 == strcmpic(newval, "block") )
2548 * Blocking Last-Modified header. Useless but why not.
2550 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2554 else if (0 == strcmpic(newval, "reset-to-request-time"))
2557 * Setting Last-Modified Header to now.
2559 get_http_time(0, buf);
2561 *header = strdup("Last-Modified: ");
2562 string_append(header, buf);
2564 if (*header == NULL)
2566 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2570 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2573 else if (0 == strcmpic(newval, "randomize"))
2575 const char *header_time = *header + sizeof("Last-Modified:");
2577 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2579 #ifdef HAVE_GMTIME_R
2580 timeptr = gmtime_r(&now, &gmt);
2581 #elif FEATURE_PTHREAD
2582 pthread_mutex_lock(&gmtime_mutex);
2583 timeptr = gmtime(&now);
2584 pthread_mutex_unlock(&gmtime_mutex);
2586 timeptr = gmtime(&now);
2588 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2590 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2595 rtime = (long int)difftime(now, last_modified);
2598 rtime = pick_from_range(rtime);
2599 last_modified += rtime;
2600 #ifdef HAVE_GMTIME_R
2601 timeptr = gmtime_r(&last_modified, &gmt);
2602 #elif FEATURE_PTHREAD
2603 pthread_mutex_lock(&gmtime_mutex);
2604 timeptr = gmtime(&last_modified);
2605 pthread_mutex_unlock(&gmtime_mutex);
2607 timeptr = gmtime(&last_modified);
2609 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2611 *header = strdup("Last-Modified: ");
2612 string_append(header, newheader);
2614 if (*header == NULL)
2616 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2617 return JB_ERR_MEMORY;
2620 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2622 days = rtime / (3600 * 24);
2623 hours = rtime / 3600 % 24;
2624 minutes = rtime / 60 % 60;
2625 seconds = rtime % 60;
2627 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2628 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2629 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2634 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2643 /*********************************************************************
2645 * Function : client_accept_encoding
2647 * Description : Rewrite the client's Accept-Encoding header so that
2648 * if doesn't allow compression, if the action applies.
2649 * Note: For HTTP/1.0 the absence of the header is enough.
2652 * 1 : csp = Current client state (buffers, headers, etc...)
2653 * 2 : header = On input, pointer to header to modify.
2654 * On output, pointer to the modified header, or NULL
2655 * to remove the header. This function frees the
2656 * original string if necessary.
2658 * Returns : JB_ERR_OK on success, or
2659 * JB_ERR_MEMORY on out-of-memory error.
2661 *********************************************************************/
2662 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2664 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2666 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2670 /* Temporarily disable the correct behaviour to
2671 * work around a PHP bug.
2673 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2675 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2676 * if (*header == NULL)
2678 * return JB_ERR_MEMORY;
2689 /*********************************************************************
2691 * Function : client_te
2693 * Description : Rewrite the client's TE header so that
2694 * if doesn't allow compression, if the action applies.
2697 * 1 : csp = Current client state (buffers, headers, etc...)
2698 * 2 : header = On input, pointer to header to modify.
2699 * On output, pointer to the modified header, or NULL
2700 * to remove the header. This function frees the
2701 * original string if necessary.
2703 * Returns : JB_ERR_OK on success, or
2704 * JB_ERR_MEMORY on out-of-memory error.
2706 *********************************************************************/
2707 static jb_err client_te(struct client_state *csp, char **header)
2709 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2712 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2719 /*********************************************************************
2721 * Function : client_referrer
2723 * Description : Handle the "referer" config setting properly.
2724 * Called from `sed'.
2727 * 1 : csp = Current client state (buffers, headers, etc...)
2728 * 2 : header = On input, pointer to header to modify.
2729 * On output, pointer to the modified header, or NULL
2730 * to remove the header. This function frees the
2731 * original string if necessary.
2733 * Returns : JB_ERR_OK on success, or
2734 * JB_ERR_MEMORY on out-of-memory error.
2736 *********************************************************************/
2737 static jb_err client_referrer(struct client_state *csp, char **header)
2739 const char *parameter;
2740 /* booleans for parameters we have to check multiple times */
2741 int parameter_conditional_block;
2742 int parameter_conditional_forge;
2744 #ifdef FEATURE_FORCE_LOAD
2746 * Since the referrer can include the prefix even
2747 * if the request itself is non-forced, we must
2748 * clean it unconditionally.
2750 * XXX: strclean is too broad
2752 strclean(*header, FORCE_PREFIX);
2753 #endif /* def FEATURE_FORCE_LOAD */
2755 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2757 /* Nothing left to do */
2761 parameter = csp->action->string[ACTION_STRING_REFERER];
2762 assert(parameter != NULL);
2763 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2764 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2766 if (!parameter_conditional_block && !parameter_conditional_forge)
2769 * As conditional-block and conditional-forge are the only
2770 * parameters that rely on the original referrer, we can
2771 * remove it now for all the others.
2776 if (0 == strcmpic(parameter, "block"))
2778 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2781 else if (parameter_conditional_block || parameter_conditional_forge)
2783 return handle_conditional_hide_referrer_parameter(header,
2784 csp->http->hostport, parameter_conditional_block);
2786 else if (0 == strcmpic(parameter, "forge"))
2788 return create_forged_referrer(header, csp->http->hostport);
2792 /* interpret parameter as user-supplied referer to fake */
2793 return create_fake_referrer(header, parameter);
2798 /*********************************************************************
2800 * Function : client_accept_language
2802 * Description : Handle the "Accept-Language" config setting properly.
2803 * Called from `sed'.
2806 * 1 : csp = Current client state (buffers, headers, etc...)
2807 * 2 : header = On input, pointer to header to modify.
2808 * On output, pointer to the modified header, or NULL
2809 * to remove the header. This function frees the
2810 * original string if necessary.
2812 * Returns : JB_ERR_OK on success, or
2813 * JB_ERR_MEMORY on out-of-memory error.
2815 *********************************************************************/
2816 static jb_err client_accept_language(struct client_state *csp, char **header)
2821 * Are we messing with the Accept-Language?
2823 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2825 /*I don't think so*/
2829 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2831 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2834 * Blocking Accept-Language header
2836 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2843 * Replacing Accept-Language header
2846 *header = strdup("Accept-Language: ");
2847 string_append(header, newval);
2849 if (*header == NULL)
2851 log_error(LOG_LEVEL_ERROR,
2852 "Insufficent memory. Accept-Language header crunched without replacement.");
2856 log_error(LOG_LEVEL_HEADER,
2857 "Accept-Language header crunched and replaced with: %s", *header);
2860 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2864 /*********************************************************************
2866 * Function : crunch_client_header
2868 * Description : Crunch client header if it matches a string supplied by the
2869 * user. Called from `sed'.
2872 * 1 : csp = Current client state (buffers, headers, etc...)
2873 * 2 : header = On input, pointer to header to modify.
2874 * On output, pointer to the modified header, or NULL
2875 * to remove the header. This function frees the
2876 * original string if necessary.
2878 * Returns : JB_ERR_OK on success and always succeeds
2880 *********************************************************************/
2881 static jb_err crunch_client_header(struct client_state *csp, char **header)
2883 const char *crunch_pattern;
2885 /* Do we feel like crunching? */
2886 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2888 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2890 /* Is the current header the lucky one? */
2891 if (strstr(*header, crunch_pattern))
2893 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2901 /*********************************************************************
2903 * Function : client_uagent
2905 * Description : Handle the "user-agent" config setting properly
2906 * and remember its original value to enable browser
2907 * bug workarounds. Called from `sed'.
2910 * 1 : csp = Current client state (buffers, headers, etc...)
2911 * 2 : header = On input, pointer to header to modify.
2912 * On output, pointer to the modified header, or NULL
2913 * to remove the header. This function frees the
2914 * original string if necessary.
2916 * Returns : JB_ERR_OK on success, or
2917 * JB_ERR_MEMORY on out-of-memory error.
2919 *********************************************************************/
2920 static jb_err client_uagent(struct client_state *csp, char **header)
2924 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2929 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2936 *header = strdup("User-Agent: ");
2937 string_append(header, newval);
2939 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2941 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2945 /*********************************************************************
2947 * Function : client_ua
2949 * Description : Handle "ua-" headers properly. Called from `sed'.
2952 * 1 : csp = Current client state (buffers, headers, etc...)
2953 * 2 : header = On input, pointer to header to modify.
2954 * On output, pointer to the modified header, or NULL
2955 * to remove the header. This function frees the
2956 * original string if necessary.
2958 * Returns : JB_ERR_OK on success, or
2959 * JB_ERR_MEMORY on out-of-memory error.
2961 *********************************************************************/
2962 static jb_err client_ua(struct client_state *csp, char **header)
2964 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2966 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2974 /*********************************************************************
2976 * Function : client_from
2978 * Description : Handle the "from" config setting properly.
2979 * Called from `sed'.
2982 * 1 : csp = Current client state (buffers, headers, etc...)
2983 * 2 : header = On input, pointer to header to modify.
2984 * On output, pointer to the modified header, or NULL
2985 * to remove the header. This function frees the
2986 * original string if necessary.
2988 * Returns : JB_ERR_OK on success, or
2989 * JB_ERR_MEMORY on out-of-memory error.
2991 *********************************************************************/
2992 static jb_err client_from(struct client_state *csp, char **header)
2996 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3003 newval = csp->action->string[ACTION_STRING_FROM];
3006 * Are we blocking the e-mail address?
3008 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3010 log_error(LOG_LEVEL_HEADER, "crunched From!");
3014 log_error(LOG_LEVEL_HEADER, " modified");
3016 *header = strdup("From: ");
3017 string_append(header, newval);
3019 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3023 /*********************************************************************
3025 * Function : client_send_cookie
3027 * Description : Crunches the "cookie" header if necessary.
3028 * Called from `sed'.
3030 * XXX: Stupid name, doesn't send squat.
3033 * 1 : csp = Current client state (buffers, headers, etc...)
3034 * 2 : header = On input, pointer to header to modify.
3035 * On output, pointer to the modified header, or NULL
3036 * to remove the header. This function frees the
3037 * original string if necessary.
3039 * Returns : JB_ERR_OK on success, or
3040 * JB_ERR_MEMORY on out-of-memory error.
3042 *********************************************************************/
3043 static jb_err client_send_cookie(struct client_state *csp, char **header)
3045 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3047 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3055 /*********************************************************************
3057 * Function : client_x_forwarded
3059 * Description : Handle the "x-forwarded-for" config setting properly,
3060 * also used in the add_client_headers list. Called from `sed'.
3063 * 1 : csp = Current client state (buffers, headers, etc...)
3064 * 2 : header = On input, pointer to header to modify.
3065 * On output, pointer to the modified header, or NULL
3066 * to remove the header. This function frees the
3067 * original string if necessary.
3069 * Returns : JB_ERR_OK on success, or
3070 * JB_ERR_MEMORY on out-of-memory error.
3072 *********************************************************************/
3073 jb_err client_x_forwarded(struct client_state *csp, char **header)
3075 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3077 /* Save it so we can re-add it later */
3078 freez(csp->x_forwarded);
3079 csp->x_forwarded = *header;
3082 * Always set *header = NULL, since this information
3083 * will be sent at the end of the header.
3090 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3097 /*********************************************************************
3099 * Function : client_max_forwards
3101 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3102 * from the value of the Max-Forwards header field.
3105 * 1 : csp = Current client state (buffers, headers, etc...)
3106 * 2 : header = On input, pointer to header to modify.
3107 * On output, pointer to the modified header, or NULL
3108 * to remove the header. This function frees the
3109 * original string if necessary.
3111 * Returns : JB_ERR_OK on success, or
3112 * JB_ERR_MEMORY on out-of-memory error.
3114 *********************************************************************/
3115 static jb_err client_max_forwards(struct client_state *csp, char **header)
3119 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3120 (0 == strcmpic(csp->http->gpc, "options")))
3122 assert(*(*header+12) == ':');
3123 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3125 if (max_forwards > 0)
3127 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3128 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3129 csp->http->gpc, max_forwards);
3131 else if (max_forwards < 0)
3133 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3139 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3148 /*********************************************************************
3150 * Function : client_host
3152 * Description : If the request URI did not contain host and
3153 * port information, parse and evaluate the Host
3156 * Also, kill ill-formed HOST: headers as sent by
3157 * Apple's iTunes software when used with a proxy.
3160 * 1 : csp = Current client state (buffers, headers, etc...)
3161 * 2 : header = On input, pointer to header to modify.
3162 * On output, pointer to the modified header, or NULL
3163 * to remove the header. This function frees the
3164 * original string if necessary.
3166 * Returns : JB_ERR_OK on success, or
3167 * JB_ERR_MEMORY on out-of-memory error.
3169 *********************************************************************/
3170 static jb_err client_host(struct client_state *csp, char **header)
3175 * If the header field name is all upper-case, chances are that it's
3176 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3177 * not a problem -- they are regenerated later.
3179 if ((*header)[1] == 'O')
3181 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3186 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3187 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3190 if (NULL == (p = strdup((*header)+6)))
3192 return JB_ERR_MEMORY;
3195 if (NULL == (q = strdup(p)))
3198 return JB_ERR_MEMORY;
3201 freez(csp->http->hostport);
3202 csp->http->hostport = p;
3203 freez(csp->http->host);
3204 csp->http->host = q;
3205 q = strchr(csp->http->host, ':');
3208 /* Terminate hostname and evaluate port string */
3210 csp->http->port = atoi(q);
3214 csp->http->port = csp->http->ssl ? 443 : 80;
3217 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3218 csp->http->hostport, csp->http->host, csp->http->port);
3221 /* Signal client_host_adder() to return right away */
3222 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3228 /*********************************************************************
3230 * Function : client_if_modified_since
3232 * Description : Remove or modify the If-Modified-Since header.
3235 * 1 : csp = Current client state (buffers, headers, etc...)
3236 * 2 : header = On input, pointer to header to modify.
3237 * On output, pointer to the modified header, or NULL
3238 * to remove the header. This function frees the
3239 * original string if necessary.
3241 * Returns : JB_ERR_OK on success, or
3242 * JB_ERR_MEMORY on out-of-memory error.
3244 *********************************************************************/
3245 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3248 #ifdef HAVE_GMTIME_R
3251 struct tm *timeptr = NULL;
3255 long int hours, minutes, seconds;
3259 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3262 * The client got an error message because of a temporary problem,
3263 * the problem is gone and the client now tries to revalidate our
3264 * error message on the real server. The revalidation would always
3265 * end with the transmission of the whole document and there is
3266 * no need to expose the bogus If-Modified-Since header.
3268 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3271 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3273 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3275 if ((0 == strcmpic(newval, "block")))
3277 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3280 else /* add random value */
3282 const char *header_time = *header + sizeof("If-Modified-Since:");
3284 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3286 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3291 rtime = strtol(newval, &endptr, 0);
3294 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3295 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3302 rtime = pick_from_range(rtime);
3306 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3309 tm += rtime * (negative ? -1 : 1);
3310 #ifdef HAVE_GMTIME_R
3311 timeptr = gmtime_r(&tm, &gmt);
3312 #elif FEATURE_PTHREAD
3313 pthread_mutex_lock(&gmtime_mutex);
3314 timeptr = gmtime(&tm);
3315 pthread_mutex_unlock(&gmtime_mutex);
3317 timeptr = gmtime(&tm);
3319 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3322 *header = strdup("If-Modified-Since: ");
3323 string_append(header, newheader);
3325 if (*header == NULL)
3327 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3328 return JB_ERR_MEMORY;
3331 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3333 hours = rtime / 3600;
3334 minutes = rtime / 60 % 60;
3335 seconds = rtime % 60;
3337 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3338 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3339 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3349 /*********************************************************************
3351 * Function : client_if_none_match
3353 * Description : Remove the If-None-Match header.
3356 * 1 : csp = Current client state (buffers, headers, etc...)
3357 * 2 : header = On input, pointer to header to modify.
3358 * On output, pointer to the modified header, or NULL
3359 * to remove the header. This function frees the
3360 * original string if necessary.
3362 * Returns : JB_ERR_OK on success, or
3363 * JB_ERR_MEMORY on out-of-memory error.
3365 *********************************************************************/
3366 static jb_err client_if_none_match(struct client_state *csp, char **header)
3368 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3370 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3378 /*********************************************************************
3380 * Function : client_x_filter
3382 * Description : Disables filtering if the client set "X-Filter: No".
3383 * Called from `sed'.
3386 * 1 : csp = Current client state (buffers, headers, etc...)
3387 * 2 : header = On input, pointer to header to modify.
3388 * On output, pointer to the modified header, or NULL
3389 * to remove the header. This function frees the
3390 * original string if necessary.
3392 * Returns : JB_ERR_OK on success
3394 *********************************************************************/
3395 jb_err client_x_filter(struct client_state *csp, char **header)
3397 if ( 0 == strcmpic(*header, "X-Filter: No"))
3399 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3401 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3405 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3407 log_error(LOG_LEVEL_HEADER,
3408 "force-text-mode overruled the client's request to fetch without filtering!");
3412 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3413 csp->flags |= CSP_FLAG_NO_FILTERING;
3414 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3416 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3424 /*********************************************************************
3426 * Function : client_range
3428 * Description : Removes Range and If-Range headers if content
3429 * filtering is enabled. If the client's version of
3430 * the document has been altered by Privoxy, the server
3431 * could interpret the range differently than the client
3432 * intended in which case the user could end up with
3433 * corrupted content.
3436 * 1 : csp = Current client state (buffers, headers, etc...)
3437 * 2 : header = On input, pointer to header to modify.
3438 * On output, pointer to the modified header, or NULL
3439 * to remove the header. This function frees the
3440 * original string if necessary.
3442 * Returns : JB_ERR_OK
3444 *********************************************************************/
3445 static jb_err client_range(struct client_state *csp, char **header)
3447 if (content_filters_enabled(csp))
3449 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3450 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3457 /* the following functions add headers directly to the header list */
3459 /*********************************************************************
3461 * Function : client_host_adder
3463 * Description : Adds the Host: header field if it is missing.
3464 * Called from `sed'.
3467 * 1 : csp = Current client state (buffers, headers, etc...)
3469 * Returns : JB_ERR_OK on success, or
3470 * JB_ERR_MEMORY on out-of-memory error.
3472 *********************************************************************/
3473 static jb_err client_host_adder(struct client_state *csp)
3478 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3480 /* Header already set by the client, nothing to do. */
3484 if ( !csp->http->hostport || !*(csp->http->hostport))
3486 /* XXX: When does this happen and why is it OK? */
3487 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3492 * remove 'user:pass@' from 'proto://user:pass@host'
3494 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3500 p = csp->http->hostport;
3503 /* XXX: Just add it, we already made sure that it will be unique */
3504 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3505 err = enlist_unique_header(csp->headers, "Host", p);
3511 /*********************************************************************
3513 * Function : client_cookie_adder
3515 * Description : Used in the add_client_headers list to add "wafers".
3516 * Called from `sed'.
3519 * 1 : csp = Current client state (buffers, headers, etc...)
3521 * Returns : JB_ERR_OK on success, or
3522 * JB_ERR_MEMORY on out-of-memory error.
3524 *********************************************************************/
3525 jb_err client_cookie_adder(struct client_state *csp)
3528 struct list_entry *wafer;
3529 struct list_entry *wafer_list;
3533 * If the user has not supplied any wafers, and the user has not
3534 * told us to suppress the vanilla wafer, then send the vanilla wafer.
3536 if ((0 != (csp->action->flags & ACTION_VANILLA_WAFER))
3537 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER]))
3539 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
3542 wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3544 if (NULL == wafer_list)
3550 tmp = strdup("Cookie: ");
3552 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3554 if (wafer != wafer_list)
3556 /* As this isn't the first wafer, we need a delimiter. */
3557 string_append(&tmp, "; ");
3559 string_join(&tmp, cookie_encode(wafer->str));
3564 return JB_ERR_MEMORY;
3567 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3568 err = enlist(csp->headers, tmp);
3575 /*********************************************************************
3577 * Function : client_accept_encoding_adder
3579 * Description : Add an Accept-Encoding header to the client's request
3580 * that disables compression if the action applies, and
3581 * the header is not already there. Called from `sed'.
3582 * Note: For HTTP/1.0, the absence of the header is enough.
3585 * 1 : csp = Current client state (buffers, headers, etc...)
3587 * Returns : JB_ERR_OK on success, or
3588 * JB_ERR_MEMORY on out-of-memory error.
3590 *********************************************************************/
3591 static jb_err client_accept_encoding_adder(struct client_state *csp)
3593 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3594 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3596 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3604 /*********************************************************************
3606 * Function : client_xtra_adder
3608 * Description : Used in the add_client_headers list. Called from `sed'.
3611 * 1 : csp = Current client state (buffers, headers, etc...)
3613 * Returns : JB_ERR_OK on success, or
3614 * JB_ERR_MEMORY on out-of-memory error.
3616 *********************************************************************/
3617 static jb_err client_xtra_adder(struct client_state *csp)
3619 struct list_entry *lst;
3622 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3623 lst ; lst = lst->next)
3625 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3626 err = enlist(csp->headers, lst->str);
3638 /*********************************************************************
3640 * Function : client_x_forwarded_adder
3642 * Description : Used in the add_client_headers list. Called from `sed'.
3645 * 1 : csp = Current client state (buffers, headers, etc...)
3647 * Returns : JB_ERR_OK on success, or
3648 * JB_ERR_MEMORY on out-of-memory error.
3650 *********************************************************************/
3651 static jb_err client_x_forwarded_adder(struct client_state *csp)
3656 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3661 if (csp->x_forwarded)
3663 p = strdup(csp->x_forwarded);
3664 string_append(&p, ", ");
3668 p = strdup("X-Forwarded-For: ");
3670 string_append(&p, csp->ip_addr_str);
3674 return JB_ERR_MEMORY;
3677 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3678 err = enlist(csp->headers, p);
3685 /*********************************************************************
3687 * Function : connection_close_adder
3689 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3690 * support. Adds a "Connection: close" header to csp->headers
3691 * unless the header was already present. Called from `sed'.
3693 * FIXME: This whole function shouldn't be neccessary!
3696 * 1 : csp = Current client state (buffers, headers, etc...)
3698 * Returns : JB_ERR_OK on success, or
3699 * JB_ERR_MEMORY on out-of-memory error.
3701 *********************************************************************/
3702 static jb_err connection_close_adder(struct client_state *csp)
3704 const unsigned int flags = csp->flags;
3707 * Return right away if
3709 * - we're parsing server headers and the server header
3710 * "Connection: close" is already set, or if
3712 * - we're parsing client headers and the client header
3713 * "Connection: close" is already set.
3715 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3716 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3717 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3718 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3723 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3725 return enlist(csp->headers, "Connection: close");
3729 /*********************************************************************
3731 * Function : server_http
3733 * Description : - Save the HTTP Status into csp->http->status
3734 * - Set CT_TABOO to prevent filtering if the answer
3735 * is a partial range (HTTP status 206)
3736 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3740 * 1 : csp = Current client state (buffers, headers, etc...)
3741 * 2 : header = On input, pointer to header to modify.
3742 * On output, pointer to the modified header, or NULL
3743 * to remove the header. This function frees the
3744 * original string if necessary.
3746 * Returns : JB_ERR_OK on success, or
3747 * JB_ERR_MEMORY on out-of-memory error.
3749 *********************************************************************/
3750 static jb_err server_http(struct client_state *csp, char **header)
3752 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3753 if (csp->http->status == 206)
3755 csp->content_type = CT_TABOO;
3758 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3760 /* XXX: Should we do a real validity check here? */
3761 if (strlen(*header) > 8)
3764 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3769 * XXX: Should we block the request or
3770 * enlist a valid status code line here?
3772 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3773 "Downgrading to HTTP/1.0 impossible.");
3781 /*********************************************************************
3783 * Function : server_set_cookie
3785 * Description : Handle the server "cookie" header properly.
3786 * Log cookie to the jar file. Then "crunch",
3787 * accept or rewrite it to a session cookie.
3788 * Called from `sed'.
3790 * TODO: Allow the user to specify a new expiration
3791 * time to cause the cookie to expire even before the
3792 * browser is closed.
3795 * 1 : csp = Current client state (buffers, headers, etc...)
3796 * 2 : header = On input, pointer to header to modify.
3797 * On output, pointer to the modified header, or NULL
3798 * to remove the header. This function frees the
3799 * original string if necessary.
3801 * Returns : JB_ERR_OK on success, or
3802 * JB_ERR_MEMORY on out-of-memory error.
3804 *********************************************************************/
3805 static jb_err server_set_cookie(struct client_state *csp, char **header)
3812 #ifdef FEATURE_COOKIE_JAR
3813 if (csp->config->jar)
3816 * Write timestamp into outbuf.
3818 * Complex because not all OSs have tm_gmtoff or
3819 * the %z field in strftime()
3821 char tempbuf[ BUFFER_SIZE ];
3823 #ifdef HAVE_LOCALTIME_R
3824 tm_now = *localtime_r(&now, &tm_now);
3825 #elif FEATURE_PTHREAD
3826 pthread_mutex_lock(&localtime_mutex);
3827 tm_now = *localtime (&now);
3828 pthread_mutex_unlock(&localtime_mutex);
3830 tm_now = *localtime (&now);
3832 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3834 /* strlen("set-cookie: ") = 12 */
3835 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3837 #endif /* def FEATURE_COOKIE_JAR */
3839 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3841 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3844 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3846 /* Flag whether or not to log a message */
3849 /* A variable to store the tag we're working on */
3852 /* Skip "Set-Cookie:" (11 characters) in header */
3853 cur_tag = *header + 11;
3855 /* skip whitespace between "Set-Cookie:" and value */
3856 while (*cur_tag && ijb_isspace(*cur_tag))
3861 /* Loop through each tag in the cookie */
3865 char *next_tag = strchr(cur_tag, ';');
3866 if (next_tag != NULL)
3868 /* Skip the ';' character itself */
3871 /* skip whitespace ";" and start of tag */
3872 while (*next_tag && ijb_isspace(*next_tag))
3879 /* "Next tag" is the end of the string */
3880 next_tag = cur_tag + strlen(cur_tag);
3884 * Check the expiration date to see
3885 * if the cookie is still valid, if yes,
3886 * rewrite it to a session cookie.
3888 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3890 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3892 /* Did we detect the date properly? */
3893 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3896 * Nope, treat it as if it was still valid.
3898 * XXX: Should we remove the whole cookie instead?
3900 log_error(LOG_LEVEL_ERROR,
3901 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3902 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3908 * Yes. Check if the cookie is still valid.
3910 * If the cookie is already expired it's probably
3911 * a delete cookie and even if it isn't, the browser
3912 * will discard it anyway.
3916 * XXX: timegm() isn't available on some AmigaOS
3917 * versions and our replacement doesn't work.
3919 * Our options are to either:
3921 * - disable session-cookies-only completely if timegm
3924 * - to simply remove all expired tags, like it has
3925 * been done until Privoxy 3.0.6 and to live with
3926 * the consequence that it can cause login/logout
3927 * problems on servers that don't validate their
3928 * input properly, or
3930 * - to replace it with mktime in which
3931 * case there is a slight chance of valid cookies
3932 * passing as already expired.
3934 * This is the way it's currently done and it's not
3935 * as bad as it sounds. If the missing GMT offset is
3936 * enough to change the result of the expiration check
3937 * the cookie will be only valid for a few hours
3938 * anyway, which in many cases will be shorter
3939 * than a browser session.
3941 if (cookie_time - now < 0)
3943 log_error(LOG_LEVEL_HEADER,
3944 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3945 /* Just in case some clown sets more then one expiration date */
3951 * Still valid, delete expiration date by copying
3952 * the rest of the string over it.
3954 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3955 * since the behaviour of strcpy is undefined for overlapping
3958 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3960 /* That changed the header, need to issue a log message */
3964 * Note that the next tag has now been moved to *cur_tag,
3965 * so we do not need to update the cur_tag pointer.
3973 /* Move on to next cookie tag */
3980 assert(NULL != *header);
3981 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3990 #ifdef FEATURE_FORCE_LOAD
3991 /*********************************************************************
3993 * Function : strclean
3995 * Description : In-Situ-Eliminate all occurances of substring in
3999 * 1 : string = string to clean
4000 * 2 : substring = substring to eliminate
4002 * Returns : Number of eliminations
4004 *********************************************************************/
4005 int strclean(const char *string, const char *substring)
4011 len = strlen(substring);
4013 while((pos = strstr(string, substring)) != NULL)
4020 while (*p++ != '\0');
4027 #endif /* def FEATURE_FORCE_LOAD */
4030 /*********************************************************************
4032 * Function : parse_header_time
4034 * Description : Parses time formats used in HTTP header strings
4035 * to get the numerical respresentation.
4038 * 1 : header_time = HTTP header time as string.
4039 * 2 : result = storage for header_time in seconds
4041 * Returns : JB_ERR_OK if the time format was recognized, or
4042 * JB_ERR_PARSE otherwise.
4044 *********************************************************************/
4045 static jb_err parse_header_time(const char *header_time, time_t *result)
4050 * Zero out gmt to prevent time zone offsets.
4052 * While this is only necessary on some platforms
4053 * (mingw32 for example), I don't know how to
4054 * detect these automatically and doing it everywhere
4057 memset(&gmt, 0, sizeof(gmt));
4059 /* Tue, 02 Jun 2037 20:00:00 */
4060 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4061 /* Tue, 02-Jun-2037 20:00:00 */
4062 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4063 /* Tue, 02-Jun-37 20:00:00 */
4064 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4065 /* Tuesday, 02-Jun-2037 20:00:00 */
4066 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4067 /* Tuesday Jun 02 20:00:00 2037 */
4068 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4070 return JB_ERR_PARSE;
4073 *result = timegm(&gmt);
4080 /*********************************************************************
4082 * Function : get_destination_from_headers
4084 * Description : Parse the "Host:" header to get the request's destination.
4085 * Only needed if the client's request was forcefully
4086 * redirected into Privoxy.
4088 * Code mainly copied from client_host() which is currently
4089 * run too late for this purpose.
4092 * 1 : headers = List of headers (one of them hopefully being
4093 * the "Host:" header)
4094 * 2 : http = storage for the result (host, port and hostport).
4096 * Returns : JB_ERR_MEMORY in case of memory problems,
4097 * JB_ERR_PARSE if the host header couldn't be found,
4098 * JB_ERR_OK otherwise.
4100 *********************************************************************/
4101 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4107 host = get_header_value(headers, "Host:");
4111 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4112 return JB_ERR_PARSE;
4115 if (NULL == (p = strdup((host))))
4117 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4118 return JB_ERR_MEMORY;
4121 if (NULL == (q = strdup(p)))
4124 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4125 return JB_ERR_MEMORY;
4128 freez(http->hostport);
4132 q = strchr(http->host, ':');
4135 /* Terminate hostname and evaluate port string */
4137 http->port = atoi(q);
4141 http->port = http->ssl ? 443 : 80;
4144 /* Rebuild request URL */
4146 http->url = strdup(http->ssl ? "https://" : "http://");
4147 string_append(&http->url, http->hostport);
4148 string_append(&http->url, http->path);
4149 if (http->url == NULL)
4151 return JB_ERR_MEMORY;
4154 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4162 /*********************************************************************
4164 * Function : create_forged_referrer
4166 * Description : Helper for client_referrer to forge a referer as
4167 * 'http://[hostname:port/' to fool stupid
4168 * checks for in-site links
4171 * 1 : header = Pointer to header pointer
4172 * 2 : hostport = Host and optionally port as string
4174 * Returns : JB_ERR_OK in case of success, or
4175 * JB_ERR_MEMORY in case of memory problems.
4177 *********************************************************************/
4178 static jb_err create_forged_referrer(char **header, const char *hostport)
4180 assert(NULL == *header);
4182 *header = strdup("Referer: http://");
4183 string_append(header, hostport);
4184 string_append(header, "/");
4186 if (NULL == *header)
4188 return JB_ERR_MEMORY;
4191 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4198 /*********************************************************************
4200 * Function : create_fake_referrer
4202 * Description : Helper for client_referrer to create a fake referrer
4203 * based on a string supplied by the user.
4206 * 1 : header = Pointer to header pointer
4207 * 2 : hosthost = Referrer to fake
4209 * Returns : JB_ERR_OK in case of success, or
4210 * JB_ERR_MEMORY in case of memory problems.
4212 *********************************************************************/
4213 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4215 assert(NULL == *header);
4217 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4219 log_error(LOG_LEVEL_HEADER,
4220 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4222 *header = strdup("Referer: ");
4223 string_append(header, fake_referrer);
4225 if (NULL == *header)
4227 return JB_ERR_MEMORY;
4230 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4237 /*********************************************************************
4239 * Function : handle_conditional_hide_referrer_parameter
4241 * Description : Helper for client_referrer to crunch or forge
4242 * the referrer header if the host has changed.
4245 * 1 : header = Pointer to header pointer
4246 * 2 : host = The target host (may include the port)
4247 * 3 : parameter_conditional_block = Boolean to signal
4248 * if we're in conditional-block mode. If not set,
4249 * we're in conditional-forge mode.
4251 * Returns : JB_ERR_OK in case of success, or
4252 * JB_ERR_MEMORY in case of memory problems.
4254 *********************************************************************/
4255 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4256 const char *host, const int parameter_conditional_block)
4258 char *referer = strdup(*header);
4259 const size_t hostlenght = strlen(host);
4261 if (NULL == referer)
4264 return JB_ERR_MEMORY;
4267 /* referer begins with 'Referer: http[s]://' */
4268 if (hostlenght < (strlen(referer)-17))
4271 * Shorten referer to make sure the referer is blocked
4272 * if www.example.org/www.example.com-shall-see-the-referer/
4273 * links to www.example.com/
4275 referer[hostlenght+17] = '\0';
4277 if (NULL == strstr(referer, host))
4279 /* Host has changed */
4280 if (parameter_conditional_block)
4282 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4289 return create_forged_referrer(header, host);