1 const char parsers_rcs[] = "$Id: parsers.c,v 1.112 2007/10/09 16:38:40 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.112 2007/10/09 16:38:40 fabiankeil
48 * Remove Range and If-Range headers if content filtering is enabled.
50 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
51 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
52 * client_cookie_adder() to make sure send-vanilla-wafer can be
53 * controlled through tags (and thus regression-tested).
55 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
56 * - Remove "scanning headers for" log message again.
57 * - Some more whitespace fixes.
59 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
60 * Refactor client_referrer() and add conditional-forge parameter.
62 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
63 * A bunch of whitespace fixes, pointy hat to me.
65 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
66 * Fix possible memory corruption in server_http, make sure it's not
67 * executed for ordinary server headers and mark some problems for later.
69 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
70 * Let content-type-overwrite{} honour force-text-mode again.
72 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
73 * - Add prototpyes for the header parsers and make them static.
74 * - Comment out client_accept_encoding_adder() which isn't used right now.
76 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
77 * Move the ACTION_FORCE_TEXT_MODE check out of
78 * server_content_type(). Signal other functions
79 * whether or not a content type has been declared.
80 * Part of the fix for BR#1750917.
82 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
83 * Change sed() to return a jb_err in preparation for forward-override{}.
85 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
86 * Adjust "X-Filter: No" to disable dedicated header filters.
88 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
89 * Streamline client_cookie_adder().
91 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
92 * Make sure filters with dynamic jobs actually use them.
94 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
95 * - Introduce dynamic pcrs jobs that can resolve variables.
96 * - Remove unnecessary update_action_bits_for_all_tags() call.
98 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
99 * - Make tagging based on tags set by earlier taggers
100 * of the same kind possible.
101 * - Log whether or not new tags cause action bits updates
102 * (in which case a matching tag-pattern section exists).
103 * - Log if the user tries to set a tag that is already set.
105 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
106 * Introduce tags as alternative way to specify which
107 * actions apply to a request. At the moment tags can be
108 * created based on client and server headers.
110 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
111 * Log a warning if the content is compressed, filtering is
112 * enabled and Privoxy was compiled without zlib support.
115 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
116 * - Fix warnings when compiled with glibc.
117 * - Don't use crumble() for cookie crunching.
118 * - Move cookie time parsing into parse_header_time().
119 * - Let parse_header_time() return a jb_err code
120 * instead of a pointer that can only be used to
121 * check for NULL anyway.
123 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
124 * - Add better protection against malicious gzip headers.
125 * - Stop logging the first hundred bytes of decompressed content.
126 * It looks like it's working and there is always debug 16.
127 * - Log the content size after decompression in decompress_iob()
128 * instead of pcrs_filter_response().
130 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
131 * - Use dedicated header filter actions instead of abusing "filter".
132 * Replace "filter-client-headers" and "filter-client-headers"
133 * with "server-header-filter" and "client-header-filter".
134 * - Remove filter_client_header() and filter_client_header(),
135 * filter_header() now checks the shiny new
136 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
138 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
139 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
140 * - Handle "Cookie:" and "Connection:" headers a bit smarter
141 * (don't crunch them just to recreate them later on).
142 * - Add another non-standard time format for the cookie
143 * expiration date detection.
144 * - Fix a valgrind warning.
146 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
147 * Improve cookie expiration date detection.
149 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
150 * Don't run server_content_length() the first time
151 * sed() parses server headers; only adjust the
152 * Content-Length header if the page was modified.
154 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
155 * Fix log messages regarding the cookie time format
156 * (cookie and request URL were mixed up).
158 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
159 * - Let decompress_iob()
160 * - not corrupt the content if decompression fails
161 * early. (the first byte(s) were lost).
162 * - use pointer arithmetics with defined outcome for
164 * - Use a different kludge to remember a failed decompression.
166 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
167 * Search for Max-Forwards headers case-insensitive,
168 * don't generate the "501 unsupported" message for invalid
169 * Max-Forwards values and don't increase negative ones.
171 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
172 * - Let server_set_cookie() check the expiration date
173 * of cookies and don't touch the ones that are already
174 * expired. Fixes problems with low quality web applications
175 * as described in BR 932612.
177 * - Adjust comment in client_max_forwards to reality;
178 * remove invalid Max-Forwards headers.
180 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
181 * Stop filter_header() from unintentionally removing
182 * empty header lines that were enlisted by the continue
185 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
186 * - Repeat the request URL before logging any headers.
187 * Makes reading the log easier in case of simultaneous requests.
188 * - If there are more than one Content-Type headers in one request,
189 * use the first one and remove the others.
190 * - Remove "newval" variable in server_content_type().
191 * It's only used once.
193 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
194 * Correct a cast, check inflateEnd() exit code
195 * to see if we have to, replace sprintf calls
198 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
199 * Integrate a modified version of Wil Mahan's
200 * zlib patch (PR #895531).
202 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
203 * Skip empty filter files in filter_header()
204 * but don't ignore the ones that come afterwards.
205 * Fixes BR 1619208, this time for real.
207 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
208 * Reverted parts of my last commit
209 * to keep error handling working.
211 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
212 * Fixed gcc43 conversion warnings.
214 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
215 * Bringing back the "useless" localtime() call
216 * I removed in revision 1.67. On some platforms
217 * it's necessary to prevent time zone offsets.
219 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
220 * Rebuild request URL in get_destination_from_headers()
221 * to make sure redirect{pcrs command} works as expected
222 * for intercepted requests.
224 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
225 * Added get_destination_from_headers().
227 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
228 * Make pthread mutex locking more generic. Instead of
229 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
230 * and use mutex locking unless there is an _r function
231 * available. Better safe than sorry.
233 * Fixes "./configure --disable-pthread" and should result
234 * in less threading-related problems on pthread-using platforms,
235 * but it still doesn't fix BR#1122404.
237 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
238 * The special header "X-Filter: No" now disables
239 * header filtering as well.
241 * Revision 1.73 2006/09/23 13:26:38 roro
242 * Replace TABs by spaces in source code.
244 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
245 * Don't print a log message every time filter_headers is
246 * entered or left. It only creates noise without any real
249 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
250 * Fix +hide-if-modified-since{-n}.
252 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
253 * Have hide-if-modified-since interpret the random
254 * range value as minutes instead of hours. Allows
255 * more fine-grained configuration.
257 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
258 * Always have parse_header_time return a pointer
259 * that actual makes sense, even though we currently
260 * only need it to detect problems.
262 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
263 * Added config option enable-remote-http-toggle
264 * to specify if Privoxy should recognize special
265 * headers (currently only X-Filter) to change its
266 * behaviour. Disabled by default.
268 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
269 * After filtering de-chunked instances, remove
270 * "Transfer-Encoding" header entirely instead of changing
271 * it to "Transfer-Encoding: identity", which is invalid.
272 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
274 * Don't use localtime in parse_header_time. An empty time struct
275 * is good enough, it gets overwritten by strptime anyway.
277 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
278 * Use gmtime_r if available, fallback to gmtime with mutex
279 * protection for MacOSX and use vanilla gmtime for the rest.
281 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
282 * Changed client_referrer to use the right type (size_t) for
283 * hostlenght and to shorten the temporary referrer string with
284 * '\0' instead of adding a useless line break.
286 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
287 * - Back to timegm() using GnuPG's replacement if necessary.
288 * Using mktime() and localtime() could add a on hour offset if
289 * the randomize factor was big enough to lead to a summer/wintertime
292 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
294 * - Moved randomization code into pick_from_range().
296 * - Changed parse_header_time definition.
297 * time_t isn't guaranteed to be signed and
298 * if it isn't, -1 isn't available as error code.
299 * Changed some variable types in client_if_modified_since()
300 * because of the same reason.
302 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
303 * OS/2 compilation compatibility fixups
305 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
306 * Changed include from strptime.c to strptime.h
308 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
309 * Split filter-headers{} into filter-client-headers{}
310 * and filter-server-headers{}.
311 * Added parse_header_time() to share some code.
312 * Replaced timegm() with mktime().
314 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
315 * Windows service integration
317 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
318 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
320 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
321 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
322 * with what was really the latest development (the v_3_0_branch branch)
324 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
325 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
327 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
328 * Add the ability to check jpeg images for invalid
329 * lengths of comment blocks. Defensive strategy
330 * against the exploit:
331 * Microsoft Security Bulletin MS04-028
332 * Buffer Overrun in JPEG Processing (GDI+) Could
333 * Allow Code Execution (833987)
334 * Enabled with +inspect-jpegs in actions files.
336 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
337 * Excluded text/plain objects from filtering. This fixes a
338 * couple of client-crashing, download corruption and
339 * Privoxy performance issues, whose root cause lies in
340 * web servers labelling content of unknown type as text/plain.
342 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
343 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
345 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
346 * Completing the previous change
348 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
349 * Added temporary workaround for bug in PHP < 4.2.3
351 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
352 * 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.
354 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
355 * Fix typo: supressed -> suppressed
357 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
358 * Improved cookie logging
360 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
361 * Added basic support for OPTIONS and TRACE HTTP methods:
362 * - New parser function client_max_forwards which decrements
363 * the Max-Forwards HTTP header field of OPTIONS and TRACE
364 * requests by one before forwarding
365 * - New parser function client_host which extracts the host
366 * and port information from the HTTP header field if the
367 * request URI was not absolute
368 * - Don't crumble and re-add the Host: header, but only generate
369 * and append if missing
371 * Revision 1.56 2002/05/12 15:34:22 jongfoster
372 * Fixing typo in a comment
374 * Revision 1.55 2002/05/08 16:01:07 oes
375 * Optimized add_to_iob:
376 * - Use realloc instead of malloc(), memcpy(), free()
377 * - Expand to powers of two if possible, to get
378 * O(log n) reallocs instead of O(n).
379 * - Moved check for buffer limit here from chat
380 * - Report failure via returncode
382 * Revision 1.54 2002/04/02 15:03:16 oes
383 * Tiny code cosmetics
385 * Revision 1.53 2002/03/26 22:29:55 swa
386 * we have a new homepage!
388 * Revision 1.52 2002/03/24 13:25:43 swa
389 * name change related issues
391 * Revision 1.51 2002/03/13 00:27:05 jongfoster
394 * Revision 1.50 2002/03/12 01:45:35 oes
395 * More verbose logging
397 * Revision 1.49 2002/03/09 20:03:52 jongfoster
398 * - Making various functions return int rather than size_t.
399 * (Undoing a recent change). Since size_t is unsigned on
400 * Windows, functions like read_socket that return -1 on
401 * error cannot return a size_t.
403 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
404 * crashes, and also frequently caused JB to jump to 100%
405 * CPU and stay there. (Because it thought it had just
406 * read ((unsigned)-1) == 4Gb of data...)
408 * - The signature of write_socket has changed, it now simply
409 * returns success=0/failure=nonzero.
411 * - Trying to get rid of a few warnings --with-debug on
412 * Windows, I've introduced a new type "jb_socket". This is
413 * used for the socket file descriptors. On Windows, this
414 * is SOCKET (a typedef for unsigned). Everywhere else, it's
415 * an int. The error value can't be -1 any more, so it's
416 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
417 * Windows it maps to the #define INVALID_SOCKET.)
419 * - The signature of bind_port has changed.
421 * Revision 1.48 2002/03/07 03:46:53 oes
422 * Fixed compiler warnings etc
424 * Revision 1.47 2002/02/20 23:15:13 jongfoster
425 * Parsing functions now handle out-of-memory gracefully by returning
428 * Revision 1.46 2002/01/17 21:03:47 jongfoster
429 * Moving all our URL and URL pattern parsing code to urlmatch.c.
431 * Revision 1.45 2002/01/09 14:33:03 oes
432 * Added support for localtime_r.
434 * Revision 1.44 2001/12/14 01:22:54 steudten
435 * Remove 'user:pass@' from 'proto://user:pass@host' for the
436 * new added header 'Host: ..'. (See Req ID 491818)
438 * Revision 1.43 2001/11/23 00:26:38 jongfoster
439 * Fixing two really stupid errors in my previous commit
441 * Revision 1.42 2001/11/22 21:59:30 jongfoster
442 * Adding code to handle +no-cookies-keep
444 * Revision 1.41 2001/11/05 23:43:05 steudten
445 * Add time+date to log files.
447 * Revision 1.40 2001/10/26 20:13:09 jongfoster
448 * ctype.h is needed in Windows, too.
450 * Revision 1.39 2001/10/26 17:40:04 oes
451 * Introduced get_header_value()
452 * Removed http->user_agent, csp->referrer and csp->accept_types
453 * Removed client_accept()
455 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
456 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
457 * threads to call select() simultaneously. So, it's time to do a real, live,
458 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
459 * (native). Both versions will work, but using __OS2__ offers multi-threading.
461 * Revision 1.37 2001/10/23 21:36:02 jongfoster
462 * Documenting sed()'s error behaviou (doc change only)
464 * Revision 1.36 2001/10/13 12:51:51 joergs
465 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
466 * force-load), instead crumble Host: and add it (again) in client_host_adder
467 * (in case we get a HTTP/1.0 request without Host: header and forward it to
468 * a HTTP/1.1 server/proxy).
470 * Revision 1.35 2001/10/09 22:39:21 jongfoster
471 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
474 * Revision 1.34 2001/10/07 18:50:55 oes
475 * Added server_content_encoding, renamed server_transfer_encoding
477 * Revision 1.33 2001/10/07 18:04:49 oes
478 * Changed server_http11 to server_http and its pattern to "HTTP".
479 * Additional functionality: it now saves the HTTP status into
480 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
482 * Revision 1.32 2001/10/07 15:43:28 oes
483 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
484 * client_te and client_accept_encoding_adder, triggered by the new
485 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
486 * changed to allow only identity and chunked, and the TE header is
487 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
489 * parse_http_request no longer does anything than parsing. The rewriting
490 * of http->cmd and version mangling are gone. It now also recognizes
491 * the put and delete methods and saves the url in http->url. Removed
494 * renamed content_type and content_length to have the server_ prefix
496 * server_content_type now only works if csp->content_type != CT_TABOO
498 * added server_transfer_encoding, which
499 * - Sets CT_TABOO to prohibit filtering if encoding compresses
500 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
501 * - Change from "chunked" to "identity" if body was chunked
502 * but has been de-chunked for filtering.
504 * added server_content_md5 which crunches any Content-MD5 headers
505 * if the body was modified.
507 * made server_http11 conditional on +downgrade action
509 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
511 * Revision 1.31 2001/10/05 14:25:02 oes
512 * Crumble Keep-Alive from Server
514 * Revision 1.30 2001/09/29 12:56:03 joergs
515 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
517 * Revision 1.29 2001/09/24 21:09:24 jongfoster
518 * Fixing 2 memory leaks that Guy spotted, where the paramater to
519 * enlist() was not being free()d.
521 * Revision 1.28 2001/09/22 16:32:28 jongfoster
522 * Removing unused #includes.
524 * Revision 1.27 2001/09/20 15:45:25 steudten
526 * add casting from size_t to int for printf()
527 * remove local variable shadow s2
529 * Revision 1.26 2001/09/16 17:05:14 jongfoster
530 * Removing unused #include showarg.h
532 * Revision 1.25 2001/09/16 13:21:27 jongfoster
533 * Changes to use new list functions.
535 * Revision 1.24 2001/09/13 23:05:50 jongfoster
536 * Changing the string paramater to the header parsers a "const".
538 * Revision 1.23 2001/09/12 18:08:19 steudten
540 * In parse_http_request() header rewriting miss the host value, so
541 * from http://www.mydomain.com the result was just " / " not
542 * http://www.mydomain.com/ in case we forward.
544 * Revision 1.22 2001/09/10 10:58:53 oes
545 * Silenced compiler warnings
547 * Revision 1.21 2001/07/31 14:46:00 oes
548 * - Persistant connections now suppressed
549 * - sed() no longer appends empty header to csp->headers
551 * Revision 1.20 2001/07/30 22:08:36 jongfoster
552 * Tidying up #defines:
553 * - All feature #defines are now of the form FEATURE_xxx
554 * - Permanently turned off WIN_GUI_EDIT
555 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
557 * Revision 1.19 2001/07/25 17:21:54 oes
558 * client_uagent now saves copy of User-Agent: header value
560 * Revision 1.18 2001/07/13 14:02:46 oes
561 * - Included fix to repair broken HTTP requests that
562 * don't contain a path, not even '/'.
563 * - Removed all #ifdef PCRS
564 * - content_type now always inspected and classified as
565 * text, gif or other.
566 * - formatting / comments
568 * Revision 1.17 2001/06/29 21:45:41 oes
569 * Indentation, CRLF->LF, Tab-> Space
571 * Revision 1.16 2001/06/29 13:32:42 oes
573 * - Adapted free_http_request
574 * - Removed logentry from cancelled commit
576 * Revision 1.15 2001/06/03 19:12:38 oes
577 * deleted const struct interceptors
579 * Revision 1.14 2001/06/01 18:49:17 jongfoster
580 * Replaced "list_share" with "list" - the tiny memory gain was not
581 * worth the extra complexity.
583 * Revision 1.13 2001/05/31 21:30:33 jongfoster
584 * Removed list code - it's now in list.[ch]
585 * Renamed "permission" to "action", and changed many features
586 * to use the actions file rather than the global config.
588 * Revision 1.12 2001/05/31 17:33:13 oes
592 * Revision 1.11 2001/05/29 20:11:19 joergs
593 * '/ * inside comment' warning removed.
595 * Revision 1.10 2001/05/29 09:50:24 jongfoster
596 * Unified blocklist/imagelist/permissionslist.
597 * File format is still under discussion, but the internal changes
600 * Also modified interceptor behaviour:
601 * - We now intercept all URLs beginning with one of the following
602 * prefixes (and *only* these prefixes):
604 * * http://ijbswa.sf.net/config/
605 * * http://ijbswa.sourceforge.net/config/
606 * - New interceptors "home page" - go to http://i.j.b/ to see it.
607 * - Internal changes so that intercepted and fast redirect pages
608 * are not replaced with an image.
609 * - Interceptors now have the option to send a binary page direct
610 * to the client. (i.e. ijb-send-banner uses this)
611 * - Implemented show-url-info interceptor. (Which is why I needed
612 * the above interceptors changes - a typical URL is
613 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
614 * The previous mechanism would not have intercepted that, and
615 * if it had been intercepted then it then it would have replaced
618 * Revision 1.9 2001/05/28 17:26:33 jongfoster
619 * Fixing segfault if last header was crunched.
620 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
621 * can use the cross-platform sprintf() instead.)
623 * Revision 1.8 2001/05/27 22:17:04 oes
625 * - re_process_buffer no longer writes the modified buffer
626 * to the client, which was very ugly. It now returns the
627 * buffer, which it is then written by chat.
629 * - content_length now adjusts the Content-Length: header
630 * for modified documents rather than crunch()ing it.
631 * (Length info in csp->content_length, which is 0 for
632 * unmodified documents)
634 * - For this to work, sed() is called twice when filtering.
636 * Revision 1.7 2001/05/27 13:19:06 oes
637 * Patched Joergs solution for the content-length in.
639 * Revision 1.6 2001/05/26 13:39:32 jongfoster
640 * Only crunches Content-Length header if applying RE filtering.
641 * Without this fix, Microsoft Windows Update wouldn't work.
643 * Revision 1.5 2001/05/26 00:28:36 jongfoster
644 * Automatic reloading of config file.
645 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
646 * Most of the global variables have been moved to a new
647 * struct configuration_spec, accessed through csp->config->globalname
648 * Most of the globals remaining are used by the Win32 GUI.
650 * Revision 1.4 2001/05/22 18:46:04 oes
652 * - Enabled filtering banners by size rather than URL
653 * by adding patterns that replace all standard banner
654 * sizes with the "Junkbuster" gif to the re_filterfile
656 * - Enabled filtering WebBugs by providing a pattern
657 * which kills all 1x1 images
659 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
660 * which is selected by the (nonstandard and therefore
661 * capital) letter 'U' in the option string.
662 * It causes the quantifiers to be ungreedy by default.
663 * Appending a ? turns back to greedy (!).
665 * - Added a new interceptor ijb-send-banner, which
666 * sends back the "Junkbuster" gif. Without imagelist or
667 * MSIE detection support, or if tinygif = 1, or the
668 * URL isn't recognized as an imageurl, a lame HTML
669 * explanation is sent instead.
671 * - Added new feature, which permits blocking remote
672 * script redirects and firing back a local redirect
674 * The feature is conditionally compiled, i.e. it
675 * can be disabled with --disable-fast-redirects,
676 * plus it must be activated by a "fast-redirects"
677 * line in the config file, has its own log level
678 * and of course wants to be displayed by show-proxy-args
679 * Note: Boy, all the #ifdefs in 1001 locations and
680 * all the fumbling with configure.in and acconfig.h
681 * were *way* more work than the feature itself :-(
683 * - Because a generic redirect template was needed for
684 * this, tinygif = 3 now uses the same.
686 * - Moved GIFs, and other static HTTP response templates
691 * - Removed some >400 CRs again (Jon, you really worked
694 * Revision 1.3 2001/05/20 01:21:20 jongfoster
695 * Version 2.9.4 checkin.
696 * - Merged popupfile and cookiefile, and added control over PCRS
697 * filtering, in new "permissionsfile".
698 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
699 * file error you now get a message box (in the Win32 GUI) rather
700 * than the program exiting with no explanation.
701 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
703 * - Removed tabs from "config"
704 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
705 * - Bumped up version number.
707 * Revision 1.2 2001/05/17 23:02:36 oes
708 * - Made referrer option accept 'L' as a substitute for '§'
710 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
711 * Initial import of version 2.9.3 source tree
714 *********************************************************************/
721 #include <sys/types.h>
731 * Convince GNU's libc to provide a strptime prototype.
734 #endif /*__GLIBC__ */
741 #if !defined(_WIN32) && !defined(__OS2__)
747 #ifdef FEATURE_PTHREAD
749 /* jcc.h is for mutex semapores only */
750 #endif /* def FEATURE_PTHREAD */
756 #include "jbsockets.h"
757 #include "miscutil.h"
762 #ifndef HAVE_STRPTIME
763 #include "strptime.h"
766 const char parsers_h_rcs[] = PARSERS_H_VERSION;
768 /* Fix a problem with Solaris. There should be no effect on other
770 * Solaris's isspace() is a macro which uses its argument directly
771 * as an array index. Therefore we need to make sure that high-bit
772 * characters generate +ve values, and ideally we also want to make
773 * the argument match the declared parameter type of "int".
775 * Why did they write a character function that can't take a simple
776 * "char" argument? Doh!
778 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
779 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
781 static jb_err scan_headers(struct client_state *csp);
782 static jb_err header_tagger(struct client_state *csp, char *header);
783 static jb_err parse_header_time(const char *header_time, time_t *result);
785 static jb_err crumble (struct client_state *csp, char **header);
786 static jb_err connection (struct client_state *csp, char **header);
787 static jb_err filter_header (struct client_state *csp, char **header);
788 static jb_err client_referrer (struct client_state *csp, char **header);
789 static jb_err client_uagent (struct client_state *csp, char **header);
790 static jb_err client_ua (struct client_state *csp, char **header);
791 static jb_err client_from (struct client_state *csp, char **header);
792 static jb_err client_send_cookie (struct client_state *csp, char **header);
793 static jb_err client_x_forwarded (struct client_state *csp, char **header);
794 static jb_err client_accept_encoding (struct client_state *csp, char **header);
795 static jb_err client_te (struct client_state *csp, char **header);
796 static jb_err client_max_forwards (struct client_state *csp, char **header);
797 static jb_err client_host (struct client_state *csp, char **header);
798 static jb_err client_if_modified_since (struct client_state *csp, char **header);
799 static jb_err client_accept_language (struct client_state *csp, char **header);
800 static jb_err client_if_none_match (struct client_state *csp, char **header);
801 static jb_err crunch_client_header (struct client_state *csp, char **header);
802 static jb_err client_x_filter (struct client_state *csp, char **header);
803 static jb_err client_range (struct client_state *csp, char **header);
804 static jb_err server_set_cookie (struct client_state *csp, char **header);
805 static jb_err server_content_type (struct client_state *csp, char **header);
806 static jb_err server_content_length (struct client_state *csp, char **header);
807 static jb_err server_content_md5 (struct client_state *csp, char **header);
808 static jb_err server_content_encoding (struct client_state *csp, char **header);
809 static jb_err server_transfer_coding (struct client_state *csp, char **header);
810 static jb_err server_http (struct client_state *csp, char **header);
811 static jb_err crunch_server_header (struct client_state *csp, char **header);
812 static jb_err server_last_modified (struct client_state *csp, char **header);
813 static jb_err server_content_disposition(struct client_state *csp, char **header);
815 static jb_err client_host_adder (struct client_state *csp);
816 static jb_err client_cookie_adder (struct client_state *csp);
817 static jb_err client_xtra_adder (struct client_state *csp);
818 static jb_err client_x_forwarded_adder(struct client_state *csp);
819 static jb_err connection_close_adder (struct client_state *csp);
821 static jb_err create_forged_referrer(char **header, const char *hostport);
822 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
823 static jb_err handle_conditional_hide_referrer_parameter(char **header,
824 const char *host, const int parameter_conditional_block);
826 const struct parsers client_patterns[] = {
827 { "referer:", 8, client_referrer },
828 { "user-agent:", 11, client_uagent },
829 { "ua-", 3, client_ua },
830 { "from:", 5, client_from },
831 { "cookie:", 7, client_send_cookie },
832 { "x-forwarded-for:", 16, client_x_forwarded },
833 { "Accept-Encoding:", 16, client_accept_encoding },
834 { "TE:", 3, client_te },
835 { "Host:", 5, client_host },
836 { "if-modified-since:", 18, client_if_modified_since },
837 { "Keep-Alive:", 11, crumble },
838 { "connection:", 11, connection },
839 { "proxy-connection:", 17, crumble },
840 { "max-forwards:", 13, client_max_forwards },
841 { "Accept-Language:", 16, client_accept_language },
842 { "if-none-match:", 14, client_if_none_match },
843 { "Range:", 6, client_range },
844 { "If-Range:", 9, client_range },
845 { "X-Filter:", 9, client_x_filter },
846 { "*", 0, crunch_client_header },
847 { "*", 0, filter_header },
851 const struct parsers server_patterns[] = {
852 { "HTTP/", 5, server_http },
853 { "set-cookie:", 11, server_set_cookie },
854 { "connection:", 11, connection },
855 { "Content-Type:", 13, server_content_type },
856 { "Content-MD5:", 12, server_content_md5 },
857 { "Content-Encoding:", 17, server_content_encoding },
858 { "Transfer-Encoding:", 18, server_transfer_coding },
859 { "Keep-Alive:", 11, crumble },
860 { "content-disposition:", 20, server_content_disposition },
861 { "Last-Modified:", 14, server_last_modified },
862 { "*", 0, crunch_server_header },
863 { "*", 0, filter_header },
867 const struct parsers server_patterns_light[] = {
868 { "Content-Length:", 15, server_content_length },
869 { "Transfer-Encoding:", 18, server_transfer_coding },
871 { "Content-Encoding:", 17, server_content_encoding },
872 #endif /* def FEATURE_ZLIB */
876 const add_header_func_ptr add_client_headers[] = {
879 client_x_forwarded_adder,
881 /* Temporarily disabled: client_accept_encoding_adder, */
882 connection_close_adder,
886 const add_header_func_ptr add_server_headers[] = {
887 connection_close_adder,
891 /* The vanilla wafer. */
892 static const char VANILLA_WAFER[] =
893 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
894 "Do_not_send_me_any_copyrighted_information_other_than_the_"
895 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
896 "In_particular_do_not_send_me_any_cookies_that_"
897 "are_subject_to_a_claim_of_copyright_by_anybody._"
898 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
899 "(copyright_or_otherwise)_applying_to_any_cookie._";
901 /*********************************************************************
903 * Function : flush_socket
905 * Description : Write any pending "buffered" content.
908 * 1 : fd = file descriptor of the socket to read
909 * 2 : csp = Current client state (buffers, headers, etc...)
911 * Returns : On success, the number of bytes written are returned (zero
912 * indicates nothing was written). On error, -1 is returned,
913 * and errno is set appropriately. If count is zero and the
914 * file descriptor refers to a regular file, 0 will be
915 * returned without causing any other effect. For a special
916 * file, the results are not portable.
918 *********************************************************************/
919 int flush_socket(jb_socket fd, struct client_state *csp)
921 struct iob *iob = csp->iob;
922 int len = iob->eod - iob->cur;
929 if (write_socket(fd, iob->cur, (size_t)len))
933 iob->eod = iob->cur = iob->buf;
939 /*********************************************************************
941 * Function : add_to_iob
943 * Description : Add content to the buffered page, expanding the
944 * buffer if necessary.
947 * 1 : csp = Current client state (buffers, headers, etc...)
948 * 2 : buf = holds the content to be added to the page
949 * 3 : n = number of bytes to be added
951 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
952 * or buffer limit reached.
954 *********************************************************************/
955 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
957 struct iob *iob = csp->iob;
958 size_t used, offset, need, want;
961 if (n <= 0) return JB_ERR_OK;
963 used = (size_t)(iob->eod - iob->buf);
964 offset = (size_t)(iob->cur - iob->buf);
965 need = used + (size_t)n + 1;
968 * If the buffer can't hold the new data, extend it first.
969 * Use the next power of two if possible, else use the actual need.
971 if (need > csp->config->buffer_limit)
973 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
974 return JB_ERR_MEMORY;
977 if (need > iob->size)
979 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
981 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
985 else if (NULL != (p = (char *)realloc(iob->buf, need)))
991 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
992 return JB_ERR_MEMORY;
995 /* Update the iob pointers */
996 iob->cur = p + offset;
1001 /* copy the new data into the iob buffer */
1002 memcpy(iob->eod, buf, (size_t)n);
1004 /* point to the end of the data */
1007 /* null terminate == cheap insurance */
1016 /*********************************************************************
1018 * Function : decompress_iob
1020 * Description : Decompress buffered page, expanding the
1021 * buffer as necessary. csp->iob->cur
1022 * should point to the the beginning of the
1023 * compressed data block.
1026 * 1 : csp = Current client state (buffers, headers, etc...)
1028 * Returns : JB_ERR_OK on success,
1029 * JB_ERR_MEMORY if out-of-memory limit reached, and
1030 * JB_ERR_COMPRESS if error decompressing buffer.
1032 *********************************************************************/
1033 jb_err decompress_iob(struct client_state *csp)
1035 char *buf; /* new, uncompressed buffer */
1036 char *cur; /* Current iob position (to keep the original
1037 * iob->cur unmodified if we return early) */
1038 size_t bufsize; /* allocated size of the new buffer */
1039 size_t old_size; /* Content size before decompression */
1040 size_t skip_size; /* Number of bytes at the beginning of the iob
1041 that we should NOT decompress. */
1042 int status; /* return status of the inflate() call */
1043 z_stream zstr; /* used by calls to zlib */
1045 assert(csp->iob->cur - csp->iob->buf > 0);
1046 assert(csp->iob->eod - csp->iob->cur > 0);
1048 bufsize = csp->iob->size;
1049 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1050 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1052 cur = csp->iob->cur;
1057 * This is to protect the parsing of gzipped data,
1058 * but it should(?) be valid for deflated data also.
1060 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1061 return JB_ERR_COMPRESS;
1064 if (csp->content_type & CT_GZIP)
1067 * Our task is slightly complicated by the facts that data
1068 * compressed by gzip does not include a zlib header, and
1069 * that there is no easily accessible interface in zlib to
1070 * handle a gzip header. We strip off the gzip header by
1071 * hand, and later inform zlib not to expect a header.
1075 * Strip off the gzip header. Please see RFC 1952 for more
1076 * explanation of the appropriate fields.
1078 if ((*cur++ != (char)0x1f)
1079 || (*cur++ != (char)0x8b)
1080 || (*cur++ != Z_DEFLATED))
1082 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1083 return JB_ERR_COMPRESS;
1089 * XXX: These magic numbers should be replaced
1090 * with macros to give a better idea what they do.
1094 /* The gzip header has reserved bits set; bail out. */
1095 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1096 return JB_ERR_COMPRESS;
1100 /* Skip extra fields if necessary. */
1104 * Skip a given number of bytes, specified
1105 * as a 16-bit little-endian value.
1108 * XXX: This code used to be:
1110 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1112 * which I had to change into:
1114 * cur += *cur++ + (*cur++ << 8);
1116 * at which point gcc43 finally noticed that the value
1117 * of cur is undefined (it depends on which of the
1118 * summands is evaluated first).
1120 * I haven't come across a site where this
1121 * code is actually executed yet, but I hope
1125 skip_bytes = *cur++;
1126 skip_bytes = *cur++ << 8;
1128 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1131 * The number of bytes to skip should be positive
1132 * and we'd like to stay in the buffer.
1134 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1136 log_error(LOG_LEVEL_ERROR,
1137 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1139 return JB_ERR_COMPRESS;
1141 log_error(LOG_LEVEL_INFO,
1142 "Skipping %d bytes for gzip compression. Does this sound right?",
1147 /* Skip the filename if necessary. */
1150 /* A null-terminated string is supposed to follow. */
1151 while (*cur++ && (cur < csp->iob->eod));
1155 /* Skip the comment if necessary. */
1158 /* A null-terminated string is supposed to follow. */
1159 while (*cur++ && (cur < csp->iob->eod));
1162 /* Skip the CRC if necessary. */
1168 if (cur >= csp->iob->eod)
1171 * If the current position pointer reached or passed
1172 * the buffer end, we were obviously tricked to skip
1175 log_error(LOG_LEVEL_ERROR,
1176 "Malformed gzip header detected. Aborting decompression.");
1177 return JB_ERR_COMPRESS;
1181 else if (csp->content_type & CT_DEFLATE)
1184 * XXX: The debug level should be lowered
1185 * before the next stable release.
1187 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1189 * In theory (that is, according to RFC 1950), deflate-compressed
1190 * data should begin with a two-byte zlib header and have an
1191 * adler32 checksum at the end. It seems that in practice only
1192 * the raw compressed data is sent. Note that this means that
1193 * we are not RFC 1950-compliant here, but the advantage is that
1194 * this actually works. :)
1196 * We add a dummy null byte to tell zlib where the data ends,
1197 * and later inform it not to expect a header.
1199 * Fortunately, add_to_iob() has thoughtfully null-terminated
1200 * the buffer; we can just increment the end pointer to include
1207 log_error(LOG_LEVEL_ERROR,
1208 "Unable to determine compression format for decompression");
1209 return JB_ERR_COMPRESS;
1212 /* Set up the fields required by zlib. */
1213 zstr.next_in = (Bytef *)cur;
1214 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1215 zstr.zalloc = Z_NULL;
1216 zstr.zfree = Z_NULL;
1217 zstr.opaque = Z_NULL;
1220 * Passing -MAX_WBITS to inflateInit2 tells the library
1221 * that there is no zlib header.
1223 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1225 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1226 return JB_ERR_COMPRESS;
1230 * Next, we allocate new storage for the inflated data.
1231 * We don't modify the existing iob yet, so in case there
1232 * is error in decompression we can recover gracefully.
1234 buf = zalloc(bufsize);
1237 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1238 return JB_ERR_MEMORY;
1241 assert(bufsize >= skip_size);
1242 memcpy(buf, csp->iob->buf, skip_size);
1243 zstr.avail_out = bufsize - skip_size;
1244 zstr.next_out = (Bytef *)buf + skip_size;
1246 /* Try to decompress the whole stream in one shot. */
1247 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1249 /* We need to allocate more memory for the output buffer. */
1251 char *tmpbuf; /* used for realloc'ing the buffer */
1252 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1255 * If zlib wants more data then there's a problem, because
1256 * the complete compressed file should have been buffered.
1258 if (0 == zstr.avail_in)
1260 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1261 return JB_ERR_COMPRESS;
1265 * If we tried the limit and still didn't have enough
1266 * memory, just give up.
1268 if (bufsize == csp->config->buffer_limit)
1270 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1271 return JB_ERR_MEMORY;
1274 /* Try doubling the buffer size each time. */
1277 /* Don't exceed the buffer limit. */
1278 if (bufsize > csp->config->buffer_limit)
1280 bufsize = csp->config->buffer_limit;
1283 /* Try to allocate the new buffer. */
1284 tmpbuf = realloc(buf, bufsize);
1287 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1289 return JB_ERR_MEMORY;
1293 char *oldnext_out = (char *)zstr.next_out;
1296 * Update the fields for inflate() to use the new
1297 * buffer, which may be in a location different from
1300 zstr.avail_out += bufsize - oldbufsize;
1301 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1304 * Compare with an uglier method of calculating these values
1305 * that doesn't require the extra oldbufsize variable.
1307 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1308 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1309 assert(zstr.avail_out > 0);
1315 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1317 log_error(LOG_LEVEL_ERROR,
1318 "Inconsistent stream state after decompression: %s", zstr.msg);
1320 * XXX: Intentionally no return.
1322 * According to zlib.h, Z_STREAM_ERROR is returned
1323 * "if the stream state was inconsistent".
1325 * I assume in this case inflate()'s status
1326 * would also be something different than Z_STREAM_END
1327 * so this check should be redundant, but lets see.
1331 if (status != Z_STREAM_END)
1333 /* We failed to decompress the stream. */
1334 log_error(LOG_LEVEL_ERROR,
1335 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1336 return JB_ERR_COMPRESS;
1340 * Finally, we can actually update the iob, since the
1341 * decompression was successful. First, free the old
1344 freez(csp->iob->buf);
1346 /* Now, update the iob to use the new buffer. */
1347 csp->iob->buf = buf;
1348 csp->iob->cur = csp->iob->buf + skip_size;
1349 csp->iob->eod = (char *)zstr.next_out;
1350 csp->iob->size = bufsize;
1353 * Make sure the new uncompressed iob obeys some minimal
1354 * consistency conditions.
1356 if ((csp->iob->buf < csp->iob->cur)
1357 && (csp->iob->cur <= csp->iob->eod)
1358 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1360 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1363 log_error(LOG_LEVEL_RE_FILTER,
1364 "Decompression successful. Old size: %d, new size: %d.",
1365 old_size, new_size);
1369 /* zlib thinks this is OK, so lets do the same. */
1370 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1375 /* It seems that zlib did something weird. */
1376 log_error(LOG_LEVEL_ERROR,
1377 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1378 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1379 csp->iob->eod, csp->iob->buf + csp->iob->size);
1380 return JB_ERR_COMPRESS;
1386 #endif /* defined(FEATURE_ZLIB) */
1389 /*********************************************************************
1391 * Function : get_header
1393 * Description : This (odd) routine will parse the csp->iob
1396 * 1 : csp = Current client state (buffers, headers, etc...)
1398 * Returns : Any one of the following:
1400 * 1) a pointer to a dynamically allocated string that contains a header line
1401 * 2) NULL indicating that the end of the header was reached
1402 * 3) "" indicating that the end of the iob was reached before finding
1403 * a complete header line.
1405 *********************************************************************/
1406 char *get_header(struct client_state *csp)
1412 if ((iob->cur == NULL)
1413 || ((p = strchr(iob->cur, '\n')) == NULL))
1415 return(""); /* couldn't find a complete header */
1420 ret = strdup(iob->cur);
1423 /* FIXME No way to handle error properly */
1424 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1429 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1431 /* is this a blank line (i.e. the end of the header) ? */
1443 /*********************************************************************
1445 * Function : get_header_value
1447 * Description : Get the value of a given header from a chained list
1448 * of header lines or return NULL if no such header is
1449 * present in the list.
1452 * 1 : header_list = pointer to list
1453 * 2 : header_name = string with name of header to look for.
1454 * Trailing colon required, capitalization
1457 * Returns : NULL if not found, else value of header
1459 *********************************************************************/
1460 char *get_header_value(const struct list *header_list, const char *header_name)
1462 struct list_entry *cur_entry;
1466 assert(header_list);
1467 assert(header_name);
1468 length = strlen(header_name);
1470 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1474 if (!strncmpic(cur_entry->str, header_name, length))
1477 * Found: return pointer to start of value
1479 ret = (char *) (cur_entry->str + length);
1480 while (*ret && ijb_isspace(*ret)) ret++;
1494 /*********************************************************************
1496 * Function : scan_headers
1498 * Description : Scans headers, applies tags and updates action bits.
1501 * 1 : csp = Current client state (buffers, headers, etc...)
1503 * Returns : JB_ERR_OK
1505 *********************************************************************/
1506 static jb_err scan_headers(struct client_state *csp)
1508 struct list_entry *h; /* Header */
1509 jb_err err = JB_ERR_OK;
1511 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1513 /* Header crunch()ed in previous run? -> ignore */
1514 if (h->str == NULL) continue;
1515 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1516 err = header_tagger(csp, h->str);
1523 /*********************************************************************
1527 * Description : add, delete or modify lines in the HTTP header streams.
1528 * On entry, it receives a linked list of headers space
1529 * that was allocated dynamically (both the list nodes
1530 * and the header contents).
1532 * As a side effect it frees the space used by the original
1535 * XXX: should be split to remove the first_run hack.
1538 * 1 : pats = list of patterns to match against headers
1539 * 2 : more_headers = list of functions to add more
1540 * headers (client or server)
1541 * 3 : csp = Current client state (buffers, headers, etc...)
1543 * Returns : JB_ERR_OK in case off success, or
1544 * JB_ERR_MEMORY on out-of-memory error.
1546 *********************************************************************/
1547 jb_err sed(const struct parsers pats[],
1548 const add_header_func_ptr more_headers[],
1549 struct client_state *csp)
1551 struct list_entry *p;
1552 const struct parsers *v;
1553 const add_header_func_ptr *f;
1554 jb_err err = JB_ERR_OK;
1558 * If filtering is enabled, sed is run twice,
1559 * but most of the work needs to be done only once.
1561 first_run = (more_headers != NULL ) ? 1 : 0;
1563 if (first_run) /* Parse and print */
1567 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1569 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1571 /* Header crunch()ed in previous run? -> ignore */
1572 if (p->str == NULL) continue;
1574 /* Does the current parser handle this header? */
1575 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1577 err = v->parser(csp, (char **)&(p->str));
1581 /* place any additional headers on the csp->headers list */
1582 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1587 else /* Parse only */
1590 * The second run is only needed if the body was modified
1591 * and the content-lenght has changed.
1593 if (strncmpic(csp->http->cmd, "HEAD", 4))
1595 /*XXX: Code duplication */
1596 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1598 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1600 /* Header crunch()ed in previous run? -> ignore */
1601 if (p->str == NULL) continue;
1603 /* Does the current parser handle this header? */
1604 if (strncmpic(p->str, v->str, v->len) == 0)
1606 err = v->parser(csp, (char **)&(p->str));
1618 /*********************************************************************
1620 * Function : header_tagger
1622 * Description : Executes all text substitutions from applying
1623 * tag actions and saves the result as tag.
1625 * XXX: Shares enough code with filter_header() and
1626 * pcrs_filter_response() to warrant some helper functions.
1629 * 1 : csp = Current client state (buffers, headers, etc...)
1630 * 2 : header = Header that is used as tagger input
1632 * Returns : JB_ERR_OK on success and always succeeds
1634 *********************************************************************/
1635 static jb_err header_tagger(struct client_state *csp, char *header)
1637 int wanted_filter_type;
1638 int multi_action_index;
1642 struct file_list *fl;
1643 struct re_filterfile_spec *b;
1644 struct list_entry *tag_name;
1646 int found_filters = 0;
1647 const size_t header_length = strlen(header);
1649 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1651 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1652 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1656 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1657 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1660 /* Check if there are any filters */
1661 for (i = 0; i < MAX_AF_FILES; i++)
1674 if (0 == found_filters)
1676 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1680 for (i = 0; i < MAX_AF_FILES; i++)
1683 if ((NULL == fl) || (NULL == fl->f))
1686 * Either there are no filter files
1687 * left, or this filter file just
1688 * contains no valid filters.
1690 * Continue to be sure we don't miss
1691 * valid filter files that are chained
1692 * after empty or invalid ones.
1697 /* For all filters, */
1698 for (b = fl->f; b; b = b->next)
1700 if (b->type != wanted_filter_type)
1702 /* skip the ones we don't care about, */
1705 /* leaving only taggers that could apply, of which we use the ones, */
1706 for (tag_name = csp->action->multi[multi_action_index]->first;
1707 NULL != tag_name; tag_name = tag_name->next)
1709 /* that do apply, and */
1710 if (strcmp(b->name, tag_name->str) == 0)
1712 char *modified_tag = NULL;
1714 size_t size = header_length;
1715 pcrs_job *joblist = b->joblist;
1717 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1719 if (NULL == joblist)
1721 log_error(LOG_LEVEL_RE_FILTER,
1722 "Tagger %s has empty joblist. Nothing to do.", b->name);
1726 /* execute their pcrs_joblist on the header. */
1727 for (job = joblist; NULL != job; job = job->next)
1729 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1733 /* Success, continue with the modified version. */
1742 /* Tagger doesn't match */
1745 /* Regex failure, log it but continue anyway. */
1746 log_error(LOG_LEVEL_ERROR,
1747 "Problems with tagger \'%s\' and header \'%s\': %s",
1748 b->name, *header, pcrs_strerror(hits));
1750 freez(modified_tag);
1754 if (b->dynamic) pcrs_free_joblist(joblist);
1756 /* If this tagger matched */
1762 * There is to technical limitation which makes
1763 * it impossible to use empty tags, but I assume
1764 * no one would do it intentionally.
1767 log_error(LOG_LEVEL_INFO,
1768 "Tagger \'%s\' created an empty tag. Ignored.",
1773 if (!list_contains_item(csp->tags, tag))
1775 if (JB_ERR_OK != enlist(csp->tags, tag))
1777 log_error(LOG_LEVEL_ERROR,
1778 "Insufficient memory to add tag \'%s\', "
1779 "based on tagger \'%s\' and header \'%s\'",
1780 tag, b->name, *header);
1784 char *action_message;
1786 * update the action bits right away, to make
1787 * tagging based on tags set by earlier taggers
1788 * of the same kind possible.
1790 if (update_action_bits_for_tag(csp, tag))
1792 action_message = "Action bits updated accordingly.";
1796 action_message = "No action bits update necessary.";
1799 log_error(LOG_LEVEL_HEADER,
1800 "Tagger \'%s\' added tag \'%s\'. %s",
1801 b->name, tag, action_message);
1806 /* XXX: Is this log-worthy? */
1807 log_error(LOG_LEVEL_HEADER,
1808 "Tagger \'%s\' didn't add tag \'%s\'. "
1809 "Tag already present", b->name, tag);
1812 } /* if the tagger matched */
1813 } /* if the tagger applies */
1814 } /* for every tagger that could apply */
1815 } /* for all filters */
1816 } /* for all filter files */
1821 /* here begins the family of parser functions that reformat header lines */
1823 /*********************************************************************
1825 * Function : filter_header
1827 * Description : Executes all text substitutions from all applying
1828 * +(server|client)-header-filter actions on the header.
1829 * Most of the code was copied from pcrs_filter_response,
1830 * including the rather short variable names
1833 * 1 : csp = Current client state (buffers, headers, etc...)
1834 * 2 : header = On input, pointer to header to modify.
1835 * On output, pointer to the modified header, or NULL
1836 * to remove the header. This function frees the
1837 * original string if necessary.
1839 * Returns : JB_ERR_OK on success and always succeeds
1841 *********************************************************************/
1842 static jb_err filter_header(struct client_state *csp, char **header)
1846 size_t size = strlen(*header);
1848 char *newheader = NULL;
1851 struct file_list *fl;
1852 struct re_filterfile_spec *b;
1853 struct list_entry *filtername;
1855 int i, found_filters = 0;
1856 int wanted_filter_type;
1857 int multi_action_index;
1859 if (csp->flags & CSP_FLAG_NO_FILTERING)
1864 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1866 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1867 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1871 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1872 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1876 * Need to check the set of re_filterfiles...
1878 for (i = 0; i < MAX_AF_FILES; i++)
1891 if (0 == found_filters)
1893 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1897 for (i = 0; i < MAX_AF_FILES; i++)
1900 if ((NULL == fl) || (NULL == fl->f))
1903 * Either there are no filter files
1904 * left, or this filter file just
1905 * contains no valid filters.
1907 * Continue to be sure we don't miss
1908 * valid filter files that are chained
1909 * after empty or invalid ones.
1914 * For all applying +filter actions, look if a filter by that
1915 * name exists and if yes, execute its pcrs_joblist on the
1918 for (b = fl->f; b; b = b->next)
1920 if (b->type != wanted_filter_type)
1922 /* Skip other filter types */
1926 for (filtername = csp->action->multi[multi_action_index]->first;
1927 filtername ; filtername = filtername->next)
1929 if (strcmp(b->name, filtername->str) == 0)
1931 int current_hits = 0;
1932 pcrs_job *joblist = b->joblist;
1934 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1936 if (NULL == joblist)
1938 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1942 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1943 *header, size, b->name);
1945 /* Apply all jobs from the joblist */
1946 for (job = joblist; NULL != job; job = job->next)
1948 matches = pcrs_execute(job, *header, size, &newheader, &size);
1951 current_hits += matches;
1952 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1954 *header = newheader;
1956 else if ( 0 == matches )
1958 /* Filter doesn't change header */
1964 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1965 *header, b->name, pcrs_strerror(matches));
1966 if (newheader != NULL)
1968 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1974 if (b->dynamic) pcrs_free_joblist(joblist);
1976 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1977 hits += current_hits;
1984 * Additionally checking for hits is important because if
1985 * the continue hack is triggered, server headers can
1986 * arrive empty to separate multiple heads from each other.
1988 if ((0 == size) && hits)
1990 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1998 /*********************************************************************
2000 * Function : connection
2002 * Description : Makes sure that the value of the Connection: header
2003 * is "close" and signals connection_close_adder
2007 * 1 : csp = Current client state (buffers, headers, etc...)
2008 * 2 : header = On input, pointer to header to modify.
2009 * On output, pointer to the modified header, or NULL
2010 * to remove the header. This function frees the
2011 * original string if necessary.
2013 * Returns : JB_ERR_OK on success, or
2014 * JB_ERR_MEMORY on out-of-memory error.
2016 *********************************************************************/
2017 static jb_err connection(struct client_state *csp, char **header)
2019 char *old_header = *header;
2021 /* Do we have a 'Connection: close' header? */
2022 if (strcmpic(*header, "Connection: close"))
2024 /* No, create one */
2025 *header = strdup("Connection: close");
2028 return JB_ERR_MEMORY;
2030 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2034 /* Signal connection_close_adder() to return early. */
2035 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2037 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2041 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2048 /*********************************************************************
2050 * Function : crumble
2052 * Description : This is called if a header matches a pattern to "crunch"
2055 * 1 : csp = Current client state (buffers, headers, etc...)
2056 * 2 : header = On input, pointer to header to modify.
2057 * On output, pointer to the modified header, or NULL
2058 * to remove the header. This function frees the
2059 * original string if necessary.
2061 * Returns : JB_ERR_OK on success, or
2062 * JB_ERR_MEMORY on out-of-memory error.
2064 *********************************************************************/
2065 static jb_err crumble(struct client_state *csp, char **header)
2067 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2073 /*********************************************************************
2075 * Function : crunch_server_header
2077 * Description : Crunch server header if it matches a string supplied by the
2078 * user. Called from `sed'.
2081 * 1 : csp = Current client state (buffers, headers, etc...)
2082 * 2 : header = On input, pointer to header to modify.
2083 * On output, pointer to the modified header, or NULL
2084 * to remove the header. This function frees the
2085 * original string if necessary.
2087 * Returns : JB_ERR_OK on success and always succeeds
2089 *********************************************************************/
2090 static jb_err crunch_server_header(struct client_state *csp, char **header)
2092 const char *crunch_pattern;
2094 /* Do we feel like crunching? */
2095 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2097 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2099 /* Is the current header the lucky one? */
2100 if (strstr(*header, crunch_pattern))
2102 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2111 /*********************************************************************
2113 * Function : server_content_type
2115 * Description : Set the content-type for filterable types (text/.*,
2116 * .*xml.*, javascript and image/gif) unless filtering has been
2117 * forbidden (CT_TABOO) while parsing earlier headers.
2118 * NOTE: Since text/plain is commonly used by web servers
2119 * for files whose correct type is unknown, we don't
2120 * set CT_TEXT for it.
2123 * 1 : csp = Current client state (buffers, headers, etc...)
2124 * 2 : header = On input, pointer to header to modify.
2125 * On output, pointer to the modified header, or NULL
2126 * to remove the header. This function frees the
2127 * original string if necessary.
2129 * Returns : JB_ERR_OK on success, or
2130 * JB_ERR_MEMORY on out-of-memory error.
2132 *********************************************************************/
2133 static jb_err server_content_type(struct client_state *csp, char **header)
2135 /* Remove header if it isn't the first Content-Type header */
2136 if ((csp->content_type & CT_DECLARED))
2139 * Another, slightly slower, way to see if
2140 * we already parsed another Content-Type header.
2142 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2144 log_error(LOG_LEVEL_ERROR,
2145 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2153 * Signal that the Content-Type has been set.
2155 csp->content_type |= CT_DECLARED;
2157 if (!(csp->content_type & CT_TABOO))
2159 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2160 || strstr(*header, "xml")
2161 || strstr(*header, "application/x-javascript"))
2163 csp->content_type |= CT_TEXT;
2165 else if (strstr(*header, " image/gif"))
2167 csp->content_type |= CT_GIF;
2169 else if (strstr(*header, " image/jpeg"))
2171 csp->content_type |= CT_JPEG;
2176 * Are we messing with the content type?
2178 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2181 * Make sure the user doesn't accidently
2182 * change the content type of binary documents.
2184 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2187 *header = strdup("Content-Type: ");
2188 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2192 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2193 return JB_ERR_MEMORY;
2195 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2199 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2200 "Enable force-text-mode if you know what you're doing.", *header);
2208 /*********************************************************************
2210 * Function : server_transfer_coding
2212 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2213 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2214 * - Remove header if body was chunked but has been
2215 * de-chunked for filtering.
2218 * 1 : csp = Current client state (buffers, headers, etc...)
2219 * 2 : header = On input, pointer to header to modify.
2220 * On output, pointer to the modified header, or NULL
2221 * to remove the header. This function frees the
2222 * original string if necessary.
2224 * Returns : JB_ERR_OK on success, or
2225 * JB_ERR_MEMORY on out-of-memory error.
2227 *********************************************************************/
2228 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2231 * Turn off pcrs and gif filtering if body compressed
2233 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2237 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2239 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2240 csp->http->cmd, *header);
2241 #endif /* def FEATURE_ZLIB */
2242 csp->content_type = CT_TABOO;
2246 * Raise flag if body chunked
2248 if (strstr(*header, "chunked"))
2250 csp->flags |= CSP_FLAG_CHUNKED;
2253 * If the body was modified, it has been de-chunked first
2254 * and the header must be removed.
2256 * FIXME: If there is more than one transfer encoding,
2257 * only the "chunked" part should be removed here.
2259 if (csp->flags & CSP_FLAG_MODIFIED)
2261 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2270 /*********************************************************************
2272 * Function : server_content_encoding
2274 * Description : This function is run twice for each request,
2275 * unless FEATURE_ZLIB and filtering are disabled.
2277 * The first run is used to check if the content
2278 * is compressed, if FEATURE_ZLIB is disabled
2279 * filtering is then disabled as well, if FEATURE_ZLIB
2280 * is enabled the content is marked for decompression.
2282 * The second run is used to remove the Content-Encoding
2283 * header if the decompression was successful.
2286 * 1 : csp = Current client state (buffers, headers, etc...)
2287 * 2 : header = On input, pointer to header to modify.
2288 * On output, pointer to the modified header, or NULL
2289 * to remove the header. This function frees the
2290 * original string if necessary.
2292 * Returns : JB_ERR_OK on success, or
2293 * JB_ERR_MEMORY on out-of-memory error.
2295 *********************************************************************/
2296 static jb_err server_content_encoding(struct client_state *csp, char **header)
2299 if ((csp->flags & CSP_FLAG_MODIFIED)
2300 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2303 * We successfully decompressed the content,
2304 * and have to clean the header now, so the
2305 * client no longer expects compressed data..
2307 * XXX: There is a difference between cleaning
2308 * and removing it completely.
2310 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2313 else if (strstr(*header, "gzip"))
2315 /* Mark for gzip decompression */
2316 csp->content_type |= CT_GZIP;
2318 else if (strstr(*header, "deflate"))
2320 /* Mark for zlib decompression */
2321 csp->content_type |= CT_DEFLATE;
2323 else if (strstr(*header, "compress"))
2326 * We can't decompress this; therefore we can't filter
2329 csp->content_type |= CT_TABOO;
2331 #else /* !defined(FEATURE_ZLIB) */
2332 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2335 * Body is compressed, turn off pcrs and gif filtering.
2337 csp->content_type |= CT_TABOO;
2340 * Log a warning if the user expects the content to be filtered.
2342 if ((csp->rlist != NULL) &&
2343 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2345 log_error(LOG_LEVEL_INFO,
2346 "Compressed content detected, content filtering disabled. "
2347 "Consider recompiling Privoxy with zlib support or "
2348 "enable the prevent-compression action.");
2351 #endif /* defined(FEATURE_ZLIB) */
2358 /*********************************************************************
2360 * Function : server_content_length
2362 * Description : Adjust Content-Length header if we modified
2366 * 1 : csp = Current client state (buffers, headers, etc...)
2367 * 2 : header = On input, pointer to header to modify.
2368 * On output, pointer to the modified header, or NULL
2369 * to remove the header. This function frees the
2370 * original string if necessary.
2372 * Returns : JB_ERR_OK on success, or
2373 * JB_ERR_MEMORY on out-of-memory error.
2375 *********************************************************************/
2376 static jb_err server_content_length(struct client_state *csp, char **header)
2378 const size_t max_header_length = 80;
2380 /* Regenerate header if the content was modified. */
2381 if (csp->flags & CSP_FLAG_MODIFIED)
2384 *header = (char *) zalloc(max_header_length);
2385 if (*header == NULL)
2387 return JB_ERR_MEMORY;
2390 snprintf(*header, max_header_length, "Content-Length: %d",
2391 (int)csp->content_length);
2392 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2393 (int)csp->content_length);
2400 /*********************************************************************
2402 * Function : server_content_md5
2404 * Description : Crumble any Content-MD5 headers if the document was
2405 * modified. FIXME: Should we re-compute instead?
2408 * 1 : csp = Current client state (buffers, headers, etc...)
2409 * 2 : header = On input, pointer to header to modify.
2410 * On output, pointer to the modified header, or NULL
2411 * to remove the header. This function frees the
2412 * original string if necessary.
2414 * Returns : JB_ERR_OK on success, or
2415 * JB_ERR_MEMORY on out-of-memory error.
2417 *********************************************************************/
2418 static jb_err server_content_md5(struct client_state *csp, char **header)
2420 if (csp->flags & CSP_FLAG_MODIFIED)
2422 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2430 /*********************************************************************
2432 * Function : server_content_disposition
2434 * Description : If enabled, blocks or modifies the "content-disposition" header.
2435 * Called from `sed'.
2438 * 1 : csp = Current client state (buffers, headers, etc...)
2439 * 2 : header = On input, pointer to header to modify.
2440 * On output, pointer to the modified header, or NULL
2441 * to remove the header. This function frees the
2442 * original string if necessary.
2444 * Returns : JB_ERR_OK on success, or
2445 * JB_ERR_MEMORY on out-of-memory error.
2447 *********************************************************************/
2448 static jb_err server_content_disposition(struct client_state *csp, char **header)
2453 * Are we messing with the content-disposition header?
2455 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2461 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2463 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2466 * Blocking content-disposition header
2468 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2475 * Replacing content-disposition header
2478 *header = strdup("content-disposition: ");
2479 string_append(header, newval);
2481 if (*header == NULL)
2483 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2487 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2490 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2494 /*********************************************************************
2496 * Function : server_last_modified
2498 * Description : Changes Last-Modified header to the actual date
2499 * to help hide-if-modified-since.
2500 * Called from `sed'.
2503 * 1 : csp = Current client state (buffers, headers, etc...)
2504 * 2 : header = On input, pointer to header to modify.
2505 * On output, pointer to the modified header, or NULL
2506 * to remove the header. This function frees the
2507 * original string if necessary.
2509 * Returns : JB_ERR_OK on success, or
2510 * JB_ERR_MEMORY on out-of-memory error.
2512 *********************************************************************/
2513 static jb_err server_last_modified(struct client_state *csp, char **header)
2516 char buf[BUFFER_SIZE];
2519 #ifdef HAVE_GMTIME_R
2522 struct tm *timeptr = NULL;
2523 time_t now, last_modified;
2525 long int days, hours, minutes, seconds;
2528 * Are we messing with the Last-Modified header?
2530 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2536 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2538 if (0 == strcmpic(newval, "block") )
2541 * Blocking Last-Modified header. Useless but why not.
2543 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2547 else if (0 == strcmpic(newval, "reset-to-request-time"))
2550 * Setting Last-Modified Header to now.
2552 get_http_time(0, buf);
2554 *header = strdup("Last-Modified: ");
2555 string_append(header, buf);
2557 if (*header == NULL)
2559 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2563 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2566 else if (0 == strcmpic(newval, "randomize"))
2568 const char *header_time = *header + sizeof("Last-Modified:");
2570 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2572 #ifdef HAVE_GMTIME_R
2573 timeptr = gmtime_r(&now, &gmt);
2574 #elif FEATURE_PTHREAD
2575 pthread_mutex_lock(&gmtime_mutex);
2576 timeptr = gmtime(&now);
2577 pthread_mutex_unlock(&gmtime_mutex);
2579 timeptr = gmtime(&now);
2581 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2583 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2588 rtime = (long int)difftime(now, last_modified);
2591 rtime = pick_from_range(rtime);
2592 last_modified += rtime;
2593 #ifdef HAVE_GMTIME_R
2594 timeptr = gmtime_r(&last_modified, &gmt);
2595 #elif FEATURE_PTHREAD
2596 pthread_mutex_lock(&gmtime_mutex);
2597 timeptr = gmtime(&last_modified);
2598 pthread_mutex_unlock(&gmtime_mutex);
2600 timeptr = gmtime(&last_modified);
2602 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2604 *header = strdup("Last-Modified: ");
2605 string_append(header, newheader);
2607 if (*header == NULL)
2609 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2610 return JB_ERR_MEMORY;
2613 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2615 days = rtime / (3600 * 24);
2616 hours = rtime / 3600 % 24;
2617 minutes = rtime / 60 % 60;
2618 seconds = rtime % 60;
2620 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2621 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2622 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2627 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2636 /*********************************************************************
2638 * Function : client_accept_encoding
2640 * Description : Rewrite the client's Accept-Encoding header so that
2641 * if doesn't allow compression, if the action applies.
2642 * Note: For HTTP/1.0 the absence of the header is enough.
2645 * 1 : csp = Current client state (buffers, headers, etc...)
2646 * 2 : header = On input, pointer to header to modify.
2647 * On output, pointer to the modified header, or NULL
2648 * to remove the header. This function frees the
2649 * original string if necessary.
2651 * Returns : JB_ERR_OK on success, or
2652 * JB_ERR_MEMORY on out-of-memory error.
2654 *********************************************************************/
2655 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2657 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2659 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2663 /* Temporarily disable the correct behaviour to
2664 * work around a PHP bug.
2666 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2668 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2669 * if (*header == NULL)
2671 * return JB_ERR_MEMORY;
2682 /*********************************************************************
2684 * Function : client_te
2686 * Description : Rewrite the client's TE header so that
2687 * if doesn't allow compression, if the action applies.
2690 * 1 : csp = Current client state (buffers, headers, etc...)
2691 * 2 : header = On input, pointer to header to modify.
2692 * On output, pointer to the modified header, or NULL
2693 * to remove the header. This function frees the
2694 * original string if necessary.
2696 * Returns : JB_ERR_OK on success, or
2697 * JB_ERR_MEMORY on out-of-memory error.
2699 *********************************************************************/
2700 static jb_err client_te(struct client_state *csp, char **header)
2702 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2705 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2712 /*********************************************************************
2714 * Function : client_referrer
2716 * Description : Handle the "referer" config setting properly.
2717 * Called from `sed'.
2720 * 1 : csp = Current client state (buffers, headers, etc...)
2721 * 2 : header = On input, pointer to header to modify.
2722 * On output, pointer to the modified header, or NULL
2723 * to remove the header. This function frees the
2724 * original string if necessary.
2726 * Returns : JB_ERR_OK on success, or
2727 * JB_ERR_MEMORY on out-of-memory error.
2729 *********************************************************************/
2730 static jb_err client_referrer(struct client_state *csp, char **header)
2732 const char *parameter;
2733 /* booleans for parameters we have to check multiple times */
2734 int parameter_conditional_block;
2735 int parameter_conditional_forge;
2737 #ifdef FEATURE_FORCE_LOAD
2739 * Since the referrer can include the prefix even
2740 * if the request itself is non-forced, we must
2741 * clean it unconditionally.
2743 * XXX: strclean is too broad
2745 strclean(*header, FORCE_PREFIX);
2746 #endif /* def FEATURE_FORCE_LOAD */
2748 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2750 /* Nothing left to do */
2754 parameter = csp->action->string[ACTION_STRING_REFERER];
2755 assert(parameter != NULL);
2756 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2757 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2759 if (!parameter_conditional_block && !parameter_conditional_forge)
2762 * As conditional-block and conditional-forge are the only
2763 * parameters that rely on the original referrer, we can
2764 * remove it now for all the others.
2769 if (0 == strcmpic(parameter, "block"))
2771 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2774 else if (parameter_conditional_block || parameter_conditional_forge)
2776 return handle_conditional_hide_referrer_parameter(header,
2777 csp->http->hostport, parameter_conditional_block);
2779 else if (0 == strcmpic(parameter, "forge"))
2781 return create_forged_referrer(header, csp->http->hostport);
2785 /* interpret parameter as user-supplied referer to fake */
2786 return create_fake_referrer(header, parameter);
2791 /*********************************************************************
2793 * Function : client_accept_language
2795 * Description : Handle the "Accept-Language" config setting properly.
2796 * Called from `sed'.
2799 * 1 : csp = Current client state (buffers, headers, etc...)
2800 * 2 : header = On input, pointer to header to modify.
2801 * On output, pointer to the modified header, or NULL
2802 * to remove the header. This function frees the
2803 * original string if necessary.
2805 * Returns : JB_ERR_OK on success, or
2806 * JB_ERR_MEMORY on out-of-memory error.
2808 *********************************************************************/
2809 static jb_err client_accept_language(struct client_state *csp, char **header)
2814 * Are we messing with the Accept-Language?
2816 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2818 /*I don't think so*/
2822 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2824 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2827 * Blocking Accept-Language header
2829 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2836 * Replacing Accept-Language header
2839 *header = strdup("Accept-Language: ");
2840 string_append(header, newval);
2842 if (*header == NULL)
2844 log_error(LOG_LEVEL_ERROR,
2845 "Insufficent memory. Accept-Language header crunched without replacement.");
2849 log_error(LOG_LEVEL_HEADER,
2850 "Accept-Language header crunched and replaced with: %s", *header);
2853 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2857 /*********************************************************************
2859 * Function : crunch_client_header
2861 * Description : Crunch client header if it matches a string supplied by the
2862 * user. Called from `sed'.
2865 * 1 : csp = Current client state (buffers, headers, etc...)
2866 * 2 : header = On input, pointer to header to modify.
2867 * On output, pointer to the modified header, or NULL
2868 * to remove the header. This function frees the
2869 * original string if necessary.
2871 * Returns : JB_ERR_OK on success and always succeeds
2873 *********************************************************************/
2874 static jb_err crunch_client_header(struct client_state *csp, char **header)
2876 const char *crunch_pattern;
2878 /* Do we feel like crunching? */
2879 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2881 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2883 /* Is the current header the lucky one? */
2884 if (strstr(*header, crunch_pattern))
2886 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2894 /*********************************************************************
2896 * Function : client_uagent
2898 * Description : Handle the "user-agent" config setting properly
2899 * and remember its original value to enable browser
2900 * bug workarounds. Called from `sed'.
2903 * 1 : csp = Current client state (buffers, headers, etc...)
2904 * 2 : header = On input, pointer to header to modify.
2905 * On output, pointer to the modified header, or NULL
2906 * to remove the header. This function frees the
2907 * original string if necessary.
2909 * Returns : JB_ERR_OK on success, or
2910 * JB_ERR_MEMORY on out-of-memory error.
2912 *********************************************************************/
2913 static jb_err client_uagent(struct client_state *csp, char **header)
2917 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2922 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2929 *header = strdup("User-Agent: ");
2930 string_append(header, newval);
2932 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2934 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2938 /*********************************************************************
2940 * Function : client_ua
2942 * Description : Handle "ua-" headers properly. Called from `sed'.
2945 * 1 : csp = Current client state (buffers, headers, etc...)
2946 * 2 : header = On input, pointer to header to modify.
2947 * On output, pointer to the modified header, or NULL
2948 * to remove the header. This function frees the
2949 * original string if necessary.
2951 * Returns : JB_ERR_OK on success, or
2952 * JB_ERR_MEMORY on out-of-memory error.
2954 *********************************************************************/
2955 static jb_err client_ua(struct client_state *csp, char **header)
2957 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2959 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2967 /*********************************************************************
2969 * Function : client_from
2971 * Description : Handle the "from" config setting properly.
2972 * Called from `sed'.
2975 * 1 : csp = Current client state (buffers, headers, etc...)
2976 * 2 : header = On input, pointer to header to modify.
2977 * On output, pointer to the modified header, or NULL
2978 * to remove the header. This function frees the
2979 * original string if necessary.
2981 * Returns : JB_ERR_OK on success, or
2982 * JB_ERR_MEMORY on out-of-memory error.
2984 *********************************************************************/
2985 static jb_err client_from(struct client_state *csp, char **header)
2989 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2996 newval = csp->action->string[ACTION_STRING_FROM];
2999 * Are we blocking the e-mail address?
3001 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3003 log_error(LOG_LEVEL_HEADER, "crunched From!");
3007 log_error(LOG_LEVEL_HEADER, " modified");
3009 *header = strdup("From: ");
3010 string_append(header, newval);
3012 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3016 /*********************************************************************
3018 * Function : client_send_cookie
3020 * Description : Crunches the "cookie" header if necessary.
3021 * Called from `sed'.
3023 * XXX: Stupid name, doesn't send squat.
3026 * 1 : csp = Current client state (buffers, headers, etc...)
3027 * 2 : header = On input, pointer to header to modify.
3028 * On output, pointer to the modified header, or NULL
3029 * to remove the header. This function frees the
3030 * original string if necessary.
3032 * Returns : JB_ERR_OK on success, or
3033 * JB_ERR_MEMORY on out-of-memory error.
3035 *********************************************************************/
3036 static jb_err client_send_cookie(struct client_state *csp, char **header)
3038 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3040 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3048 /*********************************************************************
3050 * Function : client_x_forwarded
3052 * Description : Handle the "x-forwarded-for" config setting properly,
3053 * also used in the add_client_headers list. Called from `sed'.
3056 * 1 : csp = Current client state (buffers, headers, etc...)
3057 * 2 : header = On input, pointer to header to modify.
3058 * On output, pointer to the modified header, or NULL
3059 * to remove the header. This function frees the
3060 * original string if necessary.
3062 * Returns : JB_ERR_OK on success, or
3063 * JB_ERR_MEMORY on out-of-memory error.
3065 *********************************************************************/
3066 jb_err client_x_forwarded(struct client_state *csp, char **header)
3068 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3070 /* Save it so we can re-add it later */
3071 freez(csp->x_forwarded);
3072 csp->x_forwarded = *header;
3075 * Always set *header = NULL, since this information
3076 * will be sent at the end of the header.
3083 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3090 /*********************************************************************
3092 * Function : client_max_forwards
3094 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3095 * from the value of the Max-Forwards header field.
3098 * 1 : csp = Current client state (buffers, headers, etc...)
3099 * 2 : header = On input, pointer to header to modify.
3100 * On output, pointer to the modified header, or NULL
3101 * to remove the header. This function frees the
3102 * original string if necessary.
3104 * Returns : JB_ERR_OK on success, or
3105 * JB_ERR_MEMORY on out-of-memory error.
3107 *********************************************************************/
3108 static jb_err client_max_forwards(struct client_state *csp, char **header)
3112 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3113 (0 == strcmpic(csp->http->gpc, "options")))
3115 assert(*(*header+12) == ':');
3116 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3118 if (max_forwards > 0)
3120 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3121 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3122 csp->http->gpc, max_forwards);
3124 else if (max_forwards < 0)
3126 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3132 * Not supposed to be reached. direct_response() which
3133 * was already called earlier in chat() should have
3134 * intercepted the request.
3136 log_error(LOG_LEVEL_ERROR,
3137 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3138 assert(max_forwards != 0);
3143 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3152 /*********************************************************************
3154 * Function : client_host
3156 * Description : If the request URI did not contain host and
3157 * port information, parse and evaluate the Host
3160 * Also, kill ill-formed HOST: headers as sent by
3161 * Apple's iTunes software when used with a proxy.
3164 * 1 : csp = Current client state (buffers, headers, etc...)
3165 * 2 : header = On input, pointer to header to modify.
3166 * On output, pointer to the modified header, or NULL
3167 * to remove the header. This function frees the
3168 * original string if necessary.
3170 * Returns : JB_ERR_OK on success, or
3171 * JB_ERR_MEMORY on out-of-memory error.
3173 *********************************************************************/
3174 static jb_err client_host(struct client_state *csp, char **header)
3179 * If the header field name is all upper-case, chances are that it's
3180 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3181 * not a problem -- they are regenerated later.
3183 if ((*header)[1] == 'O')
3185 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3190 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3191 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3194 if (NULL == (p = strdup((*header)+6)))
3196 return JB_ERR_MEMORY;
3199 if (NULL == (q = strdup(p)))
3202 return JB_ERR_MEMORY;
3205 freez(csp->http->hostport);
3206 csp->http->hostport = p;
3207 freez(csp->http->host);
3208 csp->http->host = q;
3209 q = strchr(csp->http->host, ':');
3212 /* Terminate hostname and evaluate port string */
3214 csp->http->port = atoi(q);
3218 csp->http->port = csp->http->ssl ? 443 : 80;
3221 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3222 csp->http->hostport, csp->http->host, csp->http->port);
3225 /* Signal client_host_adder() to return right away */
3226 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3232 /*********************************************************************
3234 * Function : client_if_modified_since
3236 * Description : Remove or modify the If-Modified-Since header.
3239 * 1 : csp = Current client state (buffers, headers, etc...)
3240 * 2 : header = On input, pointer to header to modify.
3241 * On output, pointer to the modified header, or NULL
3242 * to remove the header. This function frees the
3243 * original string if necessary.
3245 * Returns : JB_ERR_OK on success, or
3246 * JB_ERR_MEMORY on out-of-memory error.
3248 *********************************************************************/
3249 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3252 #ifdef HAVE_GMTIME_R
3255 struct tm *timeptr = NULL;
3259 long int hours, minutes, seconds;
3263 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3266 * The client got an error message because of a temporary problem,
3267 * the problem is gone and the client now tries to revalidate our
3268 * error message on the real server. The revalidation would always
3269 * end with the transmission of the whole document and there is
3270 * no need to expose the bogus If-Modified-Since header.
3272 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3275 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3277 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3279 if ((0 == strcmpic(newval, "block")))
3281 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3284 else /* add random value */
3286 const char *header_time = *header + sizeof("If-Modified-Since:");
3288 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3290 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3295 rtime = strtol(newval, &endptr, 0);
3298 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3299 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3306 rtime = pick_from_range(rtime);
3310 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3313 tm += rtime * (negative ? -1 : 1);
3314 #ifdef HAVE_GMTIME_R
3315 timeptr = gmtime_r(&tm, &gmt);
3316 #elif FEATURE_PTHREAD
3317 pthread_mutex_lock(&gmtime_mutex);
3318 timeptr = gmtime(&tm);
3319 pthread_mutex_unlock(&gmtime_mutex);
3321 timeptr = gmtime(&tm);
3323 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3326 *header = strdup("If-Modified-Since: ");
3327 string_append(header, newheader);
3329 if (*header == NULL)
3331 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3332 return JB_ERR_MEMORY;
3335 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3337 hours = rtime / 3600;
3338 minutes = rtime / 60 % 60;
3339 seconds = rtime % 60;
3341 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3342 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3343 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3353 /*********************************************************************
3355 * Function : client_if_none_match
3357 * Description : Remove the If-None-Match header.
3360 * 1 : csp = Current client state (buffers, headers, etc...)
3361 * 2 : header = On input, pointer to header to modify.
3362 * On output, pointer to the modified header, or NULL
3363 * to remove the header. This function frees the
3364 * original string if necessary.
3366 * Returns : JB_ERR_OK on success, or
3367 * JB_ERR_MEMORY on out-of-memory error.
3369 *********************************************************************/
3370 static jb_err client_if_none_match(struct client_state *csp, char **header)
3372 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3374 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3382 /*********************************************************************
3384 * Function : client_x_filter
3386 * Description : Disables filtering if the client set "X-Filter: No".
3387 * Called from `sed'.
3390 * 1 : csp = Current client state (buffers, headers, etc...)
3391 * 2 : header = On input, pointer to header to modify.
3392 * On output, pointer to the modified header, or NULL
3393 * to remove the header. This function frees the
3394 * original string if necessary.
3396 * Returns : JB_ERR_OK on success
3398 *********************************************************************/
3399 jb_err client_x_filter(struct client_state *csp, char **header)
3401 if ( 0 == strcmpic(*header, "X-Filter: No"))
3403 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3405 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3409 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3411 log_error(LOG_LEVEL_HEADER,
3412 "force-text-mode overruled the client's request to fetch without filtering!");
3416 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3417 csp->flags |= CSP_FLAG_NO_FILTERING;
3418 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3420 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3428 /*********************************************************************
3430 * Function : client_range
3432 * Description : Removes Range and If-Range headers if content
3433 * filtering is enabled. If the client's version of
3434 * the document has been altered by Privoxy, the server
3435 * could interpret the range differently than the client
3436 * intended in which case the user could end up with
3437 * corrupted content.
3440 * 1 : csp = Current client state (buffers, headers, etc...)
3441 * 2 : header = On input, pointer to header to modify.
3442 * On output, pointer to the modified header, or NULL
3443 * to remove the header. This function frees the
3444 * original string if necessary.
3446 * Returns : JB_ERR_OK
3448 *********************************************************************/
3449 static jb_err client_range(struct client_state *csp, char **header)
3451 if (((csp->rlist != NULL) &&
3452 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]))) ||
3453 (csp->action->flags & (ACTION_DEANIMATE|ACTION_JPEG_INSPECT|ACTION_NO_POPUPS)))
3455 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3456 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3463 /* the following functions add headers directly to the header list */
3465 /*********************************************************************
3467 * Function : client_host_adder
3469 * Description : Adds the Host: header field if it is missing.
3470 * Called from `sed'.
3473 * 1 : csp = Current client state (buffers, headers, etc...)
3475 * Returns : JB_ERR_OK on success, or
3476 * JB_ERR_MEMORY on out-of-memory error.
3478 *********************************************************************/
3479 static jb_err client_host_adder(struct client_state *csp)
3484 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3486 /* Header already set by the client, nothing to do. */
3490 if ( !csp->http->hostport || !*(csp->http->hostport))
3492 /* XXX: When does this happen and why is it OK? */
3493 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3498 * remove 'user:pass@' from 'proto://user:pass@host'
3500 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3506 p = csp->http->hostport;
3509 /* XXX: Just add it, we already made sure that it will be unique */
3510 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3511 err = enlist_unique_header(csp->headers, "Host", p);
3517 /*********************************************************************
3519 * Function : client_cookie_adder
3521 * Description : Used in the add_client_headers list to add "wafers".
3522 * Called from `sed'.
3525 * 1 : csp = Current client state (buffers, headers, etc...)
3527 * Returns : JB_ERR_OK on success, or
3528 * JB_ERR_MEMORY on out-of-memory error.
3530 *********************************************************************/
3531 jb_err client_cookie_adder(struct client_state *csp)
3534 struct list_entry *wafer;
3535 struct list_entry *wafer_list;
3539 * If the user has not supplied any wafers, and the user has not
3540 * told us to suppress the vanilla wafer, then send the vanilla wafer.
3542 if ((0 != (csp->action->flags & ACTION_VANILLA_WAFER))
3543 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER]))
3545 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
3548 wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3550 if (NULL == wafer_list)
3556 tmp = strdup("Cookie: ");
3558 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3560 if (wafer != wafer_list)
3562 /* As this isn't the first wafer, we need a delimiter. */
3563 string_append(&tmp, "; ");
3565 string_join(&tmp, cookie_encode(wafer->str));
3570 return JB_ERR_MEMORY;
3573 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3574 err = enlist(csp->headers, tmp);
3581 /*********************************************************************
3583 * Function : client_accept_encoding_adder
3585 * Description : Add an Accept-Encoding header to the client's request
3586 * that disables compression if the action applies, and
3587 * the header is not already there. Called from `sed'.
3588 * Note: For HTTP/1.0, the absence of the header is enough.
3591 * 1 : csp = Current client state (buffers, headers, etc...)
3593 * Returns : JB_ERR_OK on success, or
3594 * JB_ERR_MEMORY on out-of-memory error.
3596 *********************************************************************/
3597 static jb_err client_accept_encoding_adder(struct client_state *csp)
3599 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3600 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3602 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3610 /*********************************************************************
3612 * Function : client_xtra_adder
3614 * Description : Used in the add_client_headers list. Called from `sed'.
3617 * 1 : csp = Current client state (buffers, headers, etc...)
3619 * Returns : JB_ERR_OK on success, or
3620 * JB_ERR_MEMORY on out-of-memory error.
3622 *********************************************************************/
3623 static jb_err client_xtra_adder(struct client_state *csp)
3625 struct list_entry *lst;
3628 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3629 lst ; lst = lst->next)
3631 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3632 err = enlist(csp->headers, lst->str);
3644 /*********************************************************************
3646 * Function : client_x_forwarded_adder
3648 * Description : Used in the add_client_headers list. Called from `sed'.
3651 * 1 : csp = Current client state (buffers, headers, etc...)
3653 * Returns : JB_ERR_OK on success, or
3654 * JB_ERR_MEMORY on out-of-memory error.
3656 *********************************************************************/
3657 static jb_err client_x_forwarded_adder(struct client_state *csp)
3662 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3667 if (csp->x_forwarded)
3669 p = strdup(csp->x_forwarded);
3670 string_append(&p, ", ");
3674 p = strdup("X-Forwarded-For: ");
3676 string_append(&p, csp->ip_addr_str);
3680 return JB_ERR_MEMORY;
3683 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3684 err = enlist(csp->headers, p);
3691 /*********************************************************************
3693 * Function : connection_close_adder
3695 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3696 * support. Adds a "Connection: close" header to csp->headers
3697 * unless the header was already present. Called from `sed'.
3699 * FIXME: This whole function shouldn't be neccessary!
3702 * 1 : csp = Current client state (buffers, headers, etc...)
3704 * Returns : JB_ERR_OK on success, or
3705 * JB_ERR_MEMORY on out-of-memory error.
3707 *********************************************************************/
3708 static jb_err connection_close_adder(struct client_state *csp)
3710 const unsigned int flags = csp->flags;
3713 * Return right away if
3715 * - we're parsing server headers and the server header
3716 * "Connection: close" is already set, or if
3718 * - we're parsing client headers and the client header
3719 * "Connection: close" is already set.
3721 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3722 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3723 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3724 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3729 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3731 return enlist(csp->headers, "Connection: close");
3735 /*********************************************************************
3737 * Function : server_http
3739 * Description : - Save the HTTP Status into csp->http->status
3740 * - Set CT_TABOO to prevent filtering if the answer
3741 * is a partial range (HTTP status 206)
3742 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3746 * 1 : csp = Current client state (buffers, headers, etc...)
3747 * 2 : header = On input, pointer to header to modify.
3748 * On output, pointer to the modified header, or NULL
3749 * to remove the header. This function frees the
3750 * original string if necessary.
3752 * Returns : JB_ERR_OK on success, or
3753 * JB_ERR_MEMORY on out-of-memory error.
3755 *********************************************************************/
3756 static jb_err server_http(struct client_state *csp, char **header)
3758 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3759 if (csp->http->status == 206)
3761 csp->content_type = CT_TABOO;
3764 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3766 /* XXX: Should we do a real validity check here? */
3767 if (strlen(*header) > 8)
3770 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3775 * XXX: Should we block the request or
3776 * enlist a valid status code line here?
3778 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3779 "Downgrading to HTTP/1.0 impossible.");
3787 /*********************************************************************
3789 * Function : server_set_cookie
3791 * Description : Handle the server "cookie" header properly.
3792 * Log cookie to the jar file. Then "crunch",
3793 * accept or rewrite it to a session cookie.
3794 * Called from `sed'.
3796 * TODO: Allow the user to specify a new expiration
3797 * time to cause the cookie to expire even before the
3798 * browser is closed.
3801 * 1 : csp = Current client state (buffers, headers, etc...)
3802 * 2 : header = On input, pointer to header to modify.
3803 * On output, pointer to the modified header, or NULL
3804 * to remove the header. This function frees the
3805 * original string if necessary.
3807 * Returns : JB_ERR_OK on success, or
3808 * JB_ERR_MEMORY on out-of-memory error.
3810 *********************************************************************/
3811 static jb_err server_set_cookie(struct client_state *csp, char **header)
3818 #ifdef FEATURE_COOKIE_JAR
3819 if (csp->config->jar)
3822 * Write timestamp into outbuf.
3824 * Complex because not all OSs have tm_gmtoff or
3825 * the %z field in strftime()
3827 char tempbuf[ BUFFER_SIZE ];
3829 #ifdef HAVE_LOCALTIME_R
3830 tm_now = *localtime_r(&now, &tm_now);
3831 #elif FEATURE_PTHREAD
3832 pthread_mutex_lock(&localtime_mutex);
3833 tm_now = *localtime (&now);
3834 pthread_mutex_unlock(&localtime_mutex);
3836 tm_now = *localtime (&now);
3838 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3840 /* strlen("set-cookie: ") = 12 */
3841 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3843 #endif /* def FEATURE_COOKIE_JAR */
3845 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3847 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3850 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3852 /* Flag whether or not to log a message */
3855 /* A variable to store the tag we're working on */
3858 /* Skip "Set-Cookie:" (11 characters) in header */
3859 cur_tag = *header + 11;
3861 /* skip whitespace between "Set-Cookie:" and value */
3862 while (*cur_tag && ijb_isspace(*cur_tag))
3867 /* Loop through each tag in the cookie */
3871 char *next_tag = strchr(cur_tag, ';');
3872 if (next_tag != NULL)
3874 /* Skip the ';' character itself */
3877 /* skip whitespace ";" and start of tag */
3878 while (*next_tag && ijb_isspace(*next_tag))
3885 /* "Next tag" is the end of the string */
3886 next_tag = cur_tag + strlen(cur_tag);
3890 * Check the expiration date to see
3891 * if the cookie is still valid, if yes,
3892 * rewrite it to a session cookie.
3894 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3896 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3898 /* Did we detect the date properly? */
3899 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3902 * Nope, treat it as if it was still valid.
3904 * XXX: Should we remove the whole cookie instead?
3906 log_error(LOG_LEVEL_ERROR,
3907 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3908 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3914 * Yes. Check if the cookie is still valid.
3916 * If the cookie is already expired it's probably
3917 * a delete cookie and even if it isn't, the browser
3918 * will discard it anyway.
3922 * XXX: timegm() isn't available on some AmigaOS
3923 * versions and our replacement doesn't work.
3925 * Our options are to either:
3927 * - disable session-cookies-only completely if timegm
3930 * - to simply remove all expired tags, like it has
3931 * been done until Privoxy 3.0.6 and to live with
3932 * the consequence that it can cause login/logout
3933 * problems on servers that don't validate their
3934 * input properly, or
3936 * - to replace it with mktime in which
3937 * case there is a slight chance of valid cookies
3938 * passing as already expired.
3940 * This is the way it's currently done and it's not
3941 * as bad as it sounds. If the missing GMT offset is
3942 * enough to change the result of the expiration check
3943 * the cookie will be only valid for a few hours
3944 * anyway, which in many cases will be shorter
3945 * than a browser session.
3947 if (cookie_time - now < 0)
3949 log_error(LOG_LEVEL_HEADER,
3950 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3951 /* Just in case some clown sets more then one expiration date */
3957 * Still valid, delete expiration date by copying
3958 * the rest of the string over it.
3960 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3961 * since the behaviour of strcpy is undefined for overlapping
3964 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3966 /* That changed the header, need to issue a log message */
3970 * Note that the next tag has now been moved to *cur_tag,
3971 * so we do not need to update the cur_tag pointer.
3979 /* Move on to next cookie tag */
3986 assert(NULL != *header);
3987 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3996 #ifdef FEATURE_FORCE_LOAD
3997 /*********************************************************************
3999 * Function : strclean
4001 * Description : In-Situ-Eliminate all occurances of substring in
4005 * 1 : string = string to clean
4006 * 2 : substring = substring to eliminate
4008 * Returns : Number of eliminations
4010 *********************************************************************/
4011 int strclean(const char *string, const char *substring)
4017 len = strlen(substring);
4019 while((pos = strstr(string, substring)) != NULL)
4026 while (*p++ != '\0');
4033 #endif /* def FEATURE_FORCE_LOAD */
4036 /*********************************************************************
4038 * Function : parse_header_time
4040 * Description : Parses time formats used in HTTP header strings
4041 * to get the numerical respresentation.
4044 * 1 : header_time = HTTP header time as string.
4045 * 2 : result = storage for header_time in seconds
4047 * Returns : JB_ERR_OK if the time format was recognized, or
4048 * JB_ERR_PARSE otherwise.
4050 *********************************************************************/
4051 static jb_err parse_header_time(const char *header_time, time_t *result)
4056 * Zero out gmt to prevent time zone offsets.
4058 * While this is only necessary on some platforms
4059 * (mingw32 for example), I don't know how to
4060 * detect these automatically and doing it everywhere
4063 memset(&gmt, 0, sizeof(gmt));
4065 /* Tue, 02 Jun 2037 20:00:00 */
4066 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4067 /* Tue, 02-Jun-2037 20:00:00 */
4068 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4069 /* Tue, 02-Jun-37 20:00:00 */
4070 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4071 /* Tuesday, 02-Jun-2037 20:00:00 */
4072 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4073 /* Tuesday Jun 02 20:00:00 2037 */
4074 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4076 return JB_ERR_PARSE;
4079 *result = timegm(&gmt);
4086 /*********************************************************************
4088 * Function : get_destination_from_headers
4090 * Description : Parse the "Host:" header to get the request's destination.
4091 * Only needed if the client's request was forcefully
4092 * redirected into Privoxy.
4094 * Code mainly copied from client_host() which is currently
4095 * run too late for this purpose.
4098 * 1 : headers = List of headers (one of them hopefully being
4099 * the "Host:" header)
4100 * 2 : http = storage for the result (host, port and hostport).
4102 * Returns : JB_ERR_MEMORY in case of memory problems,
4103 * JB_ERR_PARSE if the host header couldn't be found,
4104 * JB_ERR_OK otherwise.
4106 *********************************************************************/
4107 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4113 host = get_header_value(headers, "Host:");
4117 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4118 return JB_ERR_PARSE;
4121 if (NULL == (p = strdup((host))))
4123 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4124 return JB_ERR_MEMORY;
4127 if (NULL == (q = strdup(p)))
4130 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4131 return JB_ERR_MEMORY;
4134 freez(http->hostport);
4138 q = strchr(http->host, ':');
4141 /* Terminate hostname and evaluate port string */
4143 http->port = atoi(q);
4147 http->port = http->ssl ? 443 : 80;
4150 /* Rebuild request URL */
4152 http->url = strdup(http->ssl ? "https://" : "http://");
4153 string_append(&http->url, http->hostport);
4154 string_append(&http->url, http->path);
4155 if (http->url == NULL)
4157 return JB_ERR_MEMORY;
4160 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4168 /*********************************************************************
4170 * Function : create_forged_referrer
4172 * Description : Helper for client_referrer to forge a referer as
4173 * 'http://[hostname:port/' to fool stupid
4174 * checks for in-site links
4177 * 1 : header = Pointer to header pointer
4178 * 2 : hostport = Host and optionally port as string
4180 * Returns : JB_ERR_OK in case of success, or
4181 * JB_ERR_MEMORY in case of memory problems.
4183 *********************************************************************/
4184 static jb_err create_forged_referrer(char **header, const char *hostport)
4186 assert(NULL == *header);
4188 *header = strdup("Referer: http://");
4189 string_append(header, hostport);
4190 string_append(header, "/");
4192 if (NULL == *header)
4194 return JB_ERR_MEMORY;
4197 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4204 /*********************************************************************
4206 * Function : create_fake_referrer
4208 * Description : Helper for client_referrer to create a fake referrer
4209 * based on a string supplied by the user.
4212 * 1 : header = Pointer to header pointer
4213 * 2 : hosthost = Referrer to fake
4215 * Returns : JB_ERR_OK in case of success, or
4216 * JB_ERR_MEMORY in case of memory problems.
4218 *********************************************************************/
4219 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4221 assert(NULL == *header);
4223 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4225 log_error(LOG_LEVEL_HEADER,
4226 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4228 *header = strdup("Referer: ");
4229 string_append(header, fake_referrer);
4231 if (NULL == *header)
4233 return JB_ERR_MEMORY;
4236 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4243 /*********************************************************************
4245 * Function : handle_conditional_hide_referrer_parameter
4247 * Description : Helper for client_referrer to crunch or forge
4248 * the referrer header if the host has changed.
4251 * 1 : header = Pointer to header pointer
4252 * 2 : host = The target host (may include the port)
4253 * 3 : parameter_conditional_block = Boolean to signal
4254 * if we're in conditional-block mode. If not set,
4255 * we're in conditional-forge mode.
4257 * Returns : JB_ERR_OK in case of success, or
4258 * JB_ERR_MEMORY in case of memory problems.
4260 *********************************************************************/
4261 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4262 const char *host, const int parameter_conditional_block)
4264 char *referer = strdup(*header);
4265 const size_t hostlenght = strlen(host);
4267 if (NULL == referer)
4270 return JB_ERR_MEMORY;
4273 /* referer begins with 'Referer: http[s]://' */
4274 if (hostlenght < (strlen(referer)-17))
4277 * Shorten referer to make sure the referer is blocked
4278 * if www.example.org/www.example.com-shall-see-the-referer/
4279 * links to www.example.com/
4281 referer[hostlenght+17] = '\0';
4283 if (NULL == strstr(referer, host))
4285 /* Host has changed */
4286 if (parameter_conditional_block)
4288 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4295 return create_forged_referrer(header, host);