1 const char parsers_rcs[] = "$Id: parsers.c,v 1.128 2008/05/16 16:39:03 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-2008 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.128 2008/05/16 16:39:03 fabiankeil
48 * If a header is split across multiple lines,
49 * merge them to a single line before parsing them.
51 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
52 * Don't provide get_header() with the whole client state
53 * structure when it only needs access to csp->iob.
55 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
56 * Change content_filters_enabled()'s parameter from
57 * csp->action to action so it can be also used in the
58 * CGI code. Don't bother checking if there are filters
59 * loaded, as that's somewhat besides the point.
61 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
62 * Provide get_http_time() with the buffer size so it doesn't
63 * have to blindly assume that the buffer is big enough.
65 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
66 * Don't pass the whole csp structure to flush_socket()
67 * when it only needs a file descriptor and a buffer.
69 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
70 * Remove send-wafer and send-vanilla-wafer actions.
72 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
73 * Remove inspect-jpegs action.
75 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
76 * Let client_range() also handle Request-Range headers
77 * which apparently are still supported by many servers.
79 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
80 * Improve the warning messages that get logged if the action files
81 * "enable" filters but no filters of that type have been loaded.
83 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
84 * In server_content_type():
85 * - Don't require leading white space when detecting image content types.
86 * - Change '... not replaced ...' message to sound less crazy if the text
87 * type actually is 'text/plain'.
88 * - Mark the 'text/plain == binary data' assumption for removal.
89 * - Remove a bunch of trailing white space.
91 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
92 * Minor server_content_disposition() changes:
93 * - Don't regenerate the header name all lower-case.
94 * - Some white space fixes.
95 * - Remove useless log message in case of ENOMEM.
97 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
98 * Garbage-collect the code to add a X-Forwarded-For
99 * header as it seems to be mostly used by accident.
101 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
102 * Fix a crash on mingw32 with some Last Modified times in the future.
104 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
105 * Remove a "can't happen" error block which, over
106 * time, mutated into a "guaranteed to happen" block.
108 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
109 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
110 * - Use shiny new content_filters_enabled() in client_range().
112 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
113 * I forgot about Poland.
115 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
116 * Remove Range and If-Range headers if content filtering is enabled.
118 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
119 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
120 * client_cookie_adder() to make sure send-vanilla-wafer can be
121 * controlled through tags (and thus regression-tested).
123 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
124 * - Remove "scanning headers for" log message again.
125 * - Some more whitespace fixes.
127 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
128 * Refactor client_referrer() and add conditional-forge parameter.
130 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
131 * A bunch of whitespace fixes, pointy hat to me.
133 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
134 * Fix possible memory corruption in server_http, make sure it's not
135 * executed for ordinary server headers and mark some problems for later.
137 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
138 * Let content-type-overwrite{} honour force-text-mode again.
140 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
141 * - Add prototpyes for the header parsers and make them static.
142 * - Comment out client_accept_encoding_adder() which isn't used right now.
144 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
145 * Move the ACTION_FORCE_TEXT_MODE check out of
146 * server_content_type(). Signal other functions
147 * whether or not a content type has been declared.
148 * Part of the fix for BR#1750917.
150 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
151 * Change sed() to return a jb_err in preparation for forward-override{}.
153 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
154 * Adjust "X-Filter: No" to disable dedicated header filters.
156 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
157 * Streamline client_cookie_adder().
159 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
160 * Make sure filters with dynamic jobs actually use them.
162 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
163 * - Introduce dynamic pcrs jobs that can resolve variables.
164 * - Remove unnecessary update_action_bits_for_all_tags() call.
166 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
167 * - Make tagging based on tags set by earlier taggers
168 * of the same kind possible.
169 * - Log whether or not new tags cause action bits updates
170 * (in which case a matching tag-pattern section exists).
171 * - Log if the user tries to set a tag that is already set.
173 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
174 * Introduce tags as alternative way to specify which
175 * actions apply to a request. At the moment tags can be
176 * created based on client and server headers.
178 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
179 * Log a warning if the content is compressed, filtering is
180 * enabled and Privoxy was compiled without zlib support.
183 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
184 * - Fix warnings when compiled with glibc.
185 * - Don't use crumble() for cookie crunching.
186 * - Move cookie time parsing into parse_header_time().
187 * - Let parse_header_time() return a jb_err code
188 * instead of a pointer that can only be used to
189 * check for NULL anyway.
191 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
192 * - Add better protection against malicious gzip headers.
193 * - Stop logging the first hundred bytes of decompressed content.
194 * It looks like it's working and there is always debug 16.
195 * - Log the content size after decompression in decompress_iob()
196 * instead of pcrs_filter_response().
198 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
199 * - Use dedicated header filter actions instead of abusing "filter".
200 * Replace "filter-client-headers" and "filter-client-headers"
201 * with "server-header-filter" and "client-header-filter".
202 * - Remove filter_client_header() and filter_client_header(),
203 * filter_header() now checks the shiny new
204 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
206 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
207 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
208 * - Handle "Cookie:" and "Connection:" headers a bit smarter
209 * (don't crunch them just to recreate them later on).
210 * - Add another non-standard time format for the cookie
211 * expiration date detection.
212 * - Fix a valgrind warning.
214 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
215 * Improve cookie expiration date detection.
217 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
218 * Don't run server_content_length() the first time
219 * sed() parses server headers; only adjust the
220 * Content-Length header if the page was modified.
222 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
223 * Fix log messages regarding the cookie time format
224 * (cookie and request URL were mixed up).
226 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
227 * - Let decompress_iob()
228 * - not corrupt the content if decompression fails
229 * early. (the first byte(s) were lost).
230 * - use pointer arithmetics with defined outcome for
232 * - Use a different kludge to remember a failed decompression.
234 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
235 * Search for Max-Forwards headers case-insensitive,
236 * don't generate the "501 unsupported" message for invalid
237 * Max-Forwards values and don't increase negative ones.
239 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
240 * - Let server_set_cookie() check the expiration date
241 * of cookies and don't touch the ones that are already
242 * expired. Fixes problems with low quality web applications
243 * as described in BR 932612.
245 * - Adjust comment in client_max_forwards to reality;
246 * remove invalid Max-Forwards headers.
248 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
249 * Stop filter_header() from unintentionally removing
250 * empty header lines that were enlisted by the continue
253 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
254 * - Repeat the request URL before logging any headers.
255 * Makes reading the log easier in case of simultaneous requests.
256 * - If there are more than one Content-Type headers in one request,
257 * use the first one and remove the others.
258 * - Remove "newval" variable in server_content_type().
259 * It's only used once.
261 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
262 * Correct a cast, check inflateEnd() exit code
263 * to see if we have to, replace sprintf calls
266 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
267 * Integrate a modified version of Wil Mahan's
268 * zlib patch (PR #895531).
270 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
271 * Skip empty filter files in filter_header()
272 * but don't ignore the ones that come afterwards.
273 * Fixes BR 1619208, this time for real.
275 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
276 * Reverted parts of my last commit
277 * to keep error handling working.
279 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
280 * Fixed gcc43 conversion warnings.
282 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
283 * Bringing back the "useless" localtime() call
284 * I removed in revision 1.67. On some platforms
285 * it's necessary to prevent time zone offsets.
287 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
288 * Rebuild request URL in get_destination_from_headers()
289 * to make sure redirect{pcrs command} works as expected
290 * for intercepted requests.
292 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
293 * Added get_destination_from_headers().
295 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
296 * Make pthread mutex locking more generic. Instead of
297 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
298 * and use mutex locking unless there is an _r function
299 * available. Better safe than sorry.
301 * Fixes "./configure --disable-pthread" and should result
302 * in less threading-related problems on pthread-using platforms,
303 * but it still doesn't fix BR#1122404.
305 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
306 * The special header "X-Filter: No" now disables
307 * header filtering as well.
309 * Revision 1.73 2006/09/23 13:26:38 roro
310 * Replace TABs by spaces in source code.
312 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
313 * Don't print a log message every time filter_headers is
314 * entered or left. It only creates noise without any real
317 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
318 * Fix +hide-if-modified-since{-n}.
320 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
321 * Have hide-if-modified-since interpret the random
322 * range value as minutes instead of hours. Allows
323 * more fine-grained configuration.
325 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
326 * Always have parse_header_time return a pointer
327 * that actual makes sense, even though we currently
328 * only need it to detect problems.
330 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
331 * Added config option enable-remote-http-toggle
332 * to specify if Privoxy should recognize special
333 * headers (currently only X-Filter) to change its
334 * behaviour. Disabled by default.
336 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
337 * After filtering de-chunked instances, remove
338 * "Transfer-Encoding" header entirely instead of changing
339 * it to "Transfer-Encoding: identity", which is invalid.
340 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
342 * Don't use localtime in parse_header_time. An empty time struct
343 * is good enough, it gets overwritten by strptime anyway.
345 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
346 * Use gmtime_r if available, fallback to gmtime with mutex
347 * protection for MacOSX and use vanilla gmtime for the rest.
349 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
350 * Changed client_referrer to use the right type (size_t) for
351 * hostlenght and to shorten the temporary referrer string with
352 * '\0' instead of adding a useless line break.
354 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
355 * - Back to timegm() using GnuPG's replacement if necessary.
356 * Using mktime() and localtime() could add a on hour offset if
357 * the randomize factor was big enough to lead to a summer/wintertime
360 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
362 * - Moved randomization code into pick_from_range().
364 * - Changed parse_header_time definition.
365 * time_t isn't guaranteed to be signed and
366 * if it isn't, -1 isn't available as error code.
367 * Changed some variable types in client_if_modified_since()
368 * because of the same reason.
370 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
371 * OS/2 compilation compatibility fixups
373 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
374 * Changed include from strptime.c to strptime.h
376 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
377 * Split filter-headers{} into filter-client-headers{}
378 * and filter-server-headers{}.
379 * Added parse_header_time() to share some code.
380 * Replaced timegm() with mktime().
382 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
383 * Windows service integration
385 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
386 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
388 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
389 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
390 * with what was really the latest development (the v_3_0_branch branch)
392 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
393 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
395 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
396 * Add the ability to check jpeg images for invalid
397 * lengths of comment blocks. Defensive strategy
398 * against the exploit:
399 * Microsoft Security Bulletin MS04-028
400 * Buffer Overrun in JPEG Processing (GDI+) Could
401 * Allow Code Execution (833987)
402 * Enabled with +inspect-jpegs in actions files.
404 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
405 * Excluded text/plain objects from filtering. This fixes a
406 * couple of client-crashing, download corruption and
407 * Privoxy performance issues, whose root cause lies in
408 * web servers labelling content of unknown type as text/plain.
410 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
411 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
413 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
414 * Completing the previous change
416 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
417 * Added temporary workaround for bug in PHP < 4.2.3
419 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
420 * 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.
422 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
423 * Fix typo: supressed -> suppressed
425 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
426 * Improved cookie logging
428 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
429 * Added basic support for OPTIONS and TRACE HTTP methods:
430 * - New parser function client_max_forwards which decrements
431 * the Max-Forwards HTTP header field of OPTIONS and TRACE
432 * requests by one before forwarding
433 * - New parser function client_host which extracts the host
434 * and port information from the HTTP header field if the
435 * request URI was not absolute
436 * - Don't crumble and re-add the Host: header, but only generate
437 * and append if missing
439 * Revision 1.56 2002/05/12 15:34:22 jongfoster
440 * Fixing typo in a comment
442 * Revision 1.55 2002/05/08 16:01:07 oes
443 * Optimized add_to_iob:
444 * - Use realloc instead of malloc(), memcpy(), free()
445 * - Expand to powers of two if possible, to get
446 * O(log n) reallocs instead of O(n).
447 * - Moved check for buffer limit here from chat
448 * - Report failure via returncode
450 * Revision 1.54 2002/04/02 15:03:16 oes
451 * Tiny code cosmetics
453 * Revision 1.53 2002/03/26 22:29:55 swa
454 * we have a new homepage!
456 * Revision 1.52 2002/03/24 13:25:43 swa
457 * name change related issues
459 * Revision 1.51 2002/03/13 00:27:05 jongfoster
462 * Revision 1.50 2002/03/12 01:45:35 oes
463 * More verbose logging
465 * Revision 1.49 2002/03/09 20:03:52 jongfoster
466 * - Making various functions return int rather than size_t.
467 * (Undoing a recent change). Since size_t is unsigned on
468 * Windows, functions like read_socket that return -1 on
469 * error cannot return a size_t.
471 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
472 * crashes, and also frequently caused JB to jump to 100%
473 * CPU and stay there. (Because it thought it had just
474 * read ((unsigned)-1) == 4Gb of data...)
476 * - The signature of write_socket has changed, it now simply
477 * returns success=0/failure=nonzero.
479 * - Trying to get rid of a few warnings --with-debug on
480 * Windows, I've introduced a new type "jb_socket". This is
481 * used for the socket file descriptors. On Windows, this
482 * is SOCKET (a typedef for unsigned). Everywhere else, it's
483 * an int. The error value can't be -1 any more, so it's
484 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
485 * Windows it maps to the #define INVALID_SOCKET.)
487 * - The signature of bind_port has changed.
489 * Revision 1.48 2002/03/07 03:46:53 oes
490 * Fixed compiler warnings etc
492 * Revision 1.47 2002/02/20 23:15:13 jongfoster
493 * Parsing functions now handle out-of-memory gracefully by returning
496 * Revision 1.46 2002/01/17 21:03:47 jongfoster
497 * Moving all our URL and URL pattern parsing code to urlmatch.c.
499 * Revision 1.45 2002/01/09 14:33:03 oes
500 * Added support for localtime_r.
502 * Revision 1.44 2001/12/14 01:22:54 steudten
503 * Remove 'user:pass@' from 'proto://user:pass@host' for the
504 * new added header 'Host: ..'. (See Req ID 491818)
506 * Revision 1.43 2001/11/23 00:26:38 jongfoster
507 * Fixing two really stupid errors in my previous commit
509 * Revision 1.42 2001/11/22 21:59:30 jongfoster
510 * Adding code to handle +no-cookies-keep
512 * Revision 1.41 2001/11/05 23:43:05 steudten
513 * Add time+date to log files.
515 * Revision 1.40 2001/10/26 20:13:09 jongfoster
516 * ctype.h is needed in Windows, too.
518 * Revision 1.39 2001/10/26 17:40:04 oes
519 * Introduced get_header_value()
520 * Removed http->user_agent, csp->referrer and csp->accept_types
521 * Removed client_accept()
523 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
524 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
525 * threads to call select() simultaneously. So, it's time to do a real, live,
526 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
527 * (native). Both versions will work, but using __OS2__ offers multi-threading.
529 * Revision 1.37 2001/10/23 21:36:02 jongfoster
530 * Documenting sed()'s error behaviou (doc change only)
532 * Revision 1.36 2001/10/13 12:51:51 joergs
533 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
534 * force-load), instead crumble Host: and add it (again) in client_host_adder
535 * (in case we get a HTTP/1.0 request without Host: header and forward it to
536 * a HTTP/1.1 server/proxy).
538 * Revision 1.35 2001/10/09 22:39:21 jongfoster
539 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
542 * Revision 1.34 2001/10/07 18:50:55 oes
543 * Added server_content_encoding, renamed server_transfer_encoding
545 * Revision 1.33 2001/10/07 18:04:49 oes
546 * Changed server_http11 to server_http and its pattern to "HTTP".
547 * Additional functionality: it now saves the HTTP status into
548 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
550 * Revision 1.32 2001/10/07 15:43:28 oes
551 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
552 * client_te and client_accept_encoding_adder, triggered by the new
553 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
554 * changed to allow only identity and chunked, and the TE header is
555 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
557 * parse_http_request no longer does anything than parsing. The rewriting
558 * of http->cmd and version mangling are gone. It now also recognizes
559 * the put and delete methods and saves the url in http->url. Removed
562 * renamed content_type and content_length to have the server_ prefix
564 * server_content_type now only works if csp->content_type != CT_TABOO
566 * added server_transfer_encoding, which
567 * - Sets CT_TABOO to prohibit filtering if encoding compresses
568 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
569 * - Change from "chunked" to "identity" if body was chunked
570 * but has been de-chunked for filtering.
572 * added server_content_md5 which crunches any Content-MD5 headers
573 * if the body was modified.
575 * made server_http11 conditional on +downgrade action
577 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
579 * Revision 1.31 2001/10/05 14:25:02 oes
580 * Crumble Keep-Alive from Server
582 * Revision 1.30 2001/09/29 12:56:03 joergs
583 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
585 * Revision 1.29 2001/09/24 21:09:24 jongfoster
586 * Fixing 2 memory leaks that Guy spotted, where the paramater to
587 * enlist() was not being free()d.
589 * Revision 1.28 2001/09/22 16:32:28 jongfoster
590 * Removing unused #includes.
592 * Revision 1.27 2001/09/20 15:45:25 steudten
594 * add casting from size_t to int for printf()
595 * remove local variable shadow s2
597 * Revision 1.26 2001/09/16 17:05:14 jongfoster
598 * Removing unused #include showarg.h
600 * Revision 1.25 2001/09/16 13:21:27 jongfoster
601 * Changes to use new list functions.
603 * Revision 1.24 2001/09/13 23:05:50 jongfoster
604 * Changing the string paramater to the header parsers a "const".
606 * Revision 1.23 2001/09/12 18:08:19 steudten
608 * In parse_http_request() header rewriting miss the host value, so
609 * from http://www.mydomain.com the result was just " / " not
610 * http://www.mydomain.com/ in case we forward.
612 * Revision 1.22 2001/09/10 10:58:53 oes
613 * Silenced compiler warnings
615 * Revision 1.21 2001/07/31 14:46:00 oes
616 * - Persistant connections now suppressed
617 * - sed() no longer appends empty header to csp->headers
619 * Revision 1.20 2001/07/30 22:08:36 jongfoster
620 * Tidying up #defines:
621 * - All feature #defines are now of the form FEATURE_xxx
622 * - Permanently turned off WIN_GUI_EDIT
623 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
625 * Revision 1.19 2001/07/25 17:21:54 oes
626 * client_uagent now saves copy of User-Agent: header value
628 * Revision 1.18 2001/07/13 14:02:46 oes
629 * - Included fix to repair broken HTTP requests that
630 * don't contain a path, not even '/'.
631 * - Removed all #ifdef PCRS
632 * - content_type now always inspected and classified as
633 * text, gif or other.
634 * - formatting / comments
636 * Revision 1.17 2001/06/29 21:45:41 oes
637 * Indentation, CRLF->LF, Tab-> Space
639 * Revision 1.16 2001/06/29 13:32:42 oes
641 * - Adapted free_http_request
642 * - Removed logentry from cancelled commit
644 * Revision 1.15 2001/06/03 19:12:38 oes
645 * deleted const struct interceptors
647 * Revision 1.14 2001/06/01 18:49:17 jongfoster
648 * Replaced "list_share" with "list" - the tiny memory gain was not
649 * worth the extra complexity.
651 * Revision 1.13 2001/05/31 21:30:33 jongfoster
652 * Removed list code - it's now in list.[ch]
653 * Renamed "permission" to "action", and changed many features
654 * to use the actions file rather than the global config.
656 * Revision 1.12 2001/05/31 17:33:13 oes
660 * Revision 1.11 2001/05/29 20:11:19 joergs
661 * '/ * inside comment' warning removed.
663 * Revision 1.10 2001/05/29 09:50:24 jongfoster
664 * Unified blocklist/imagelist/permissionslist.
665 * File format is still under discussion, but the internal changes
668 * Also modified interceptor behaviour:
669 * - We now intercept all URLs beginning with one of the following
670 * prefixes (and *only* these prefixes):
672 * * http://ijbswa.sf.net/config/
673 * * http://ijbswa.sourceforge.net/config/
674 * - New interceptors "home page" - go to http://i.j.b/ to see it.
675 * - Internal changes so that intercepted and fast redirect pages
676 * are not replaced with an image.
677 * - Interceptors now have the option to send a binary page direct
678 * to the client. (i.e. ijb-send-banner uses this)
679 * - Implemented show-url-info interceptor. (Which is why I needed
680 * the above interceptors changes - a typical URL is
681 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
682 * The previous mechanism would not have intercepted that, and
683 * if it had been intercepted then it then it would have replaced
686 * Revision 1.9 2001/05/28 17:26:33 jongfoster
687 * Fixing segfault if last header was crunched.
688 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
689 * can use the cross-platform sprintf() instead.)
691 * Revision 1.8 2001/05/27 22:17:04 oes
693 * - re_process_buffer no longer writes the modified buffer
694 * to the client, which was very ugly. It now returns the
695 * buffer, which it is then written by chat.
697 * - content_length now adjusts the Content-Length: header
698 * for modified documents rather than crunch()ing it.
699 * (Length info in csp->content_length, which is 0 for
700 * unmodified documents)
702 * - For this to work, sed() is called twice when filtering.
704 * Revision 1.7 2001/05/27 13:19:06 oes
705 * Patched Joergs solution for the content-length in.
707 * Revision 1.6 2001/05/26 13:39:32 jongfoster
708 * Only crunches Content-Length header if applying RE filtering.
709 * Without this fix, Microsoft Windows Update wouldn't work.
711 * Revision 1.5 2001/05/26 00:28:36 jongfoster
712 * Automatic reloading of config file.
713 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
714 * Most of the global variables have been moved to a new
715 * struct configuration_spec, accessed through csp->config->globalname
716 * Most of the globals remaining are used by the Win32 GUI.
718 * Revision 1.4 2001/05/22 18:46:04 oes
720 * - Enabled filtering banners by size rather than URL
721 * by adding patterns that replace all standard banner
722 * sizes with the "Junkbuster" gif to the re_filterfile
724 * - Enabled filtering WebBugs by providing a pattern
725 * which kills all 1x1 images
727 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
728 * which is selected by the (nonstandard and therefore
729 * capital) letter 'U' in the option string.
730 * It causes the quantifiers to be ungreedy by default.
731 * Appending a ? turns back to greedy (!).
733 * - Added a new interceptor ijb-send-banner, which
734 * sends back the "Junkbuster" gif. Without imagelist or
735 * MSIE detection support, or if tinygif = 1, or the
736 * URL isn't recognized as an imageurl, a lame HTML
737 * explanation is sent instead.
739 * - Added new feature, which permits blocking remote
740 * script redirects and firing back a local redirect
742 * The feature is conditionally compiled, i.e. it
743 * can be disabled with --disable-fast-redirects,
744 * plus it must be activated by a "fast-redirects"
745 * line in the config file, has its own log level
746 * and of course wants to be displayed by show-proxy-args
747 * Note: Boy, all the #ifdefs in 1001 locations and
748 * all the fumbling with configure.in and acconfig.h
749 * were *way* more work than the feature itself :-(
751 * - Because a generic redirect template was needed for
752 * this, tinygif = 3 now uses the same.
754 * - Moved GIFs, and other static HTTP response templates
759 * - Removed some >400 CRs again (Jon, you really worked
762 * Revision 1.3 2001/05/20 01:21:20 jongfoster
763 * Version 2.9.4 checkin.
764 * - Merged popupfile and cookiefile, and added control over PCRS
765 * filtering, in new "permissionsfile".
766 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
767 * file error you now get a message box (in the Win32 GUI) rather
768 * than the program exiting with no explanation.
769 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
771 * - Removed tabs from "config"
772 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
773 * - Bumped up version number.
775 * Revision 1.2 2001/05/17 23:02:36 oes
776 * - Made referrer option accept 'L' as a substitute for '§'
778 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
779 * Initial import of version 2.9.3 source tree
782 *********************************************************************/
789 #include <sys/types.h>
799 * Convince GNU's libc to provide a strptime prototype.
802 #endif /*__GLIBC__ */
809 #if !defined(_WIN32) && !defined(__OS2__)
815 #ifdef FEATURE_PTHREAD
817 /* jcc.h is for mutex semapores only */
818 #endif /* def FEATURE_PTHREAD */
824 #include "jbsockets.h"
825 #include "miscutil.h"
830 #ifndef HAVE_STRPTIME
831 #include "strptime.h"
834 const char parsers_h_rcs[] = PARSERS_H_VERSION;
836 /* Fix a problem with Solaris. There should be no effect on other
838 * Solaris's isspace() is a macro which uses its argument directly
839 * as an array index. Therefore we need to make sure that high-bit
840 * characters generate +ve values, and ideally we also want to make
841 * the argument match the declared parameter type of "int".
843 * Why did they write a character function that can't take a simple
844 * "char" argument? Doh!
846 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
847 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
849 static char *get_header_line(struct iob *iob);
850 static jb_err scan_headers(struct client_state *csp);
851 static jb_err header_tagger(struct client_state *csp, char *header);
852 static jb_err parse_header_time(const char *header_time, time_t *result);
854 static jb_err crumble (struct client_state *csp, char **header);
855 static jb_err connection (struct client_state *csp, char **header);
856 static jb_err filter_header (struct client_state *csp, char **header);
857 static jb_err client_referrer (struct client_state *csp, char **header);
858 static jb_err client_uagent (struct client_state *csp, char **header);
859 static jb_err client_ua (struct client_state *csp, char **header);
860 static jb_err client_from (struct client_state *csp, char **header);
861 static jb_err client_send_cookie (struct client_state *csp, char **header);
862 static jb_err client_x_forwarded (struct client_state *csp, char **header);
863 static jb_err client_accept_encoding (struct client_state *csp, char **header);
864 static jb_err client_te (struct client_state *csp, char **header);
865 static jb_err client_max_forwards (struct client_state *csp, char **header);
866 static jb_err client_host (struct client_state *csp, char **header);
867 static jb_err client_if_modified_since (struct client_state *csp, char **header);
868 static jb_err client_accept_language (struct client_state *csp, char **header);
869 static jb_err client_if_none_match (struct client_state *csp, char **header);
870 static jb_err crunch_client_header (struct client_state *csp, char **header);
871 static jb_err client_x_filter (struct client_state *csp, char **header);
872 static jb_err client_range (struct client_state *csp, char **header);
873 static jb_err server_set_cookie (struct client_state *csp, char **header);
874 static jb_err server_content_type (struct client_state *csp, char **header);
875 static jb_err server_content_length (struct client_state *csp, char **header);
876 static jb_err server_content_md5 (struct client_state *csp, char **header);
877 static jb_err server_content_encoding (struct client_state *csp, char **header);
878 static jb_err server_transfer_coding (struct client_state *csp, char **header);
879 static jb_err server_http (struct client_state *csp, char **header);
880 static jb_err crunch_server_header (struct client_state *csp, char **header);
881 static jb_err server_last_modified (struct client_state *csp, char **header);
882 static jb_err server_content_disposition(struct client_state *csp, char **header);
884 static jb_err client_host_adder (struct client_state *csp);
885 static jb_err client_xtra_adder (struct client_state *csp);
886 static jb_err connection_close_adder (struct client_state *csp);
888 static jb_err create_forged_referrer(char **header, const char *hostport);
889 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
890 static jb_err handle_conditional_hide_referrer_parameter(char **header,
891 const char *host, const int parameter_conditional_block);
893 const struct parsers client_patterns[] = {
894 { "referer:", 8, client_referrer },
895 { "user-agent:", 11, client_uagent },
896 { "ua-", 3, client_ua },
897 { "from:", 5, client_from },
898 { "cookie:", 7, client_send_cookie },
899 { "x-forwarded-for:", 16, client_x_forwarded },
900 { "Accept-Encoding:", 16, client_accept_encoding },
901 { "TE:", 3, client_te },
902 { "Host:", 5, client_host },
903 { "if-modified-since:", 18, client_if_modified_since },
904 { "Keep-Alive:", 11, crumble },
905 { "connection:", 11, connection },
906 { "proxy-connection:", 17, crumble },
907 { "max-forwards:", 13, client_max_forwards },
908 { "Accept-Language:", 16, client_accept_language },
909 { "if-none-match:", 14, client_if_none_match },
910 { "Range:", 6, client_range },
911 { "Request-Range:", 14, client_range },
912 { "If-Range:", 9, client_range },
913 { "X-Filter:", 9, client_x_filter },
914 { "*", 0, crunch_client_header },
915 { "*", 0, filter_header },
919 const struct parsers server_patterns[] = {
920 { "HTTP/", 5, server_http },
921 { "set-cookie:", 11, server_set_cookie },
922 { "connection:", 11, connection },
923 { "Content-Type:", 13, server_content_type },
924 { "Content-MD5:", 12, server_content_md5 },
925 { "Content-Encoding:", 17, server_content_encoding },
926 { "Transfer-Encoding:", 18, server_transfer_coding },
927 { "Keep-Alive:", 11, crumble },
928 { "content-disposition:", 20, server_content_disposition },
929 { "Last-Modified:", 14, server_last_modified },
930 { "*", 0, crunch_server_header },
931 { "*", 0, filter_header },
935 const struct parsers server_patterns_light[] = {
936 { "Content-Length:", 15, server_content_length },
937 { "Transfer-Encoding:", 18, server_transfer_coding },
939 { "Content-Encoding:", 17, server_content_encoding },
940 #endif /* def FEATURE_ZLIB */
944 const add_header_func_ptr add_client_headers[] = {
947 /* Temporarily disabled: client_accept_encoding_adder, */
948 connection_close_adder,
952 const add_header_func_ptr add_server_headers[] = {
953 connection_close_adder,
957 /*********************************************************************
959 * Function : flush_socket
961 * Description : Write any pending "buffered" content.
964 * 1 : fd = file descriptor of the socket to read
965 * 2 : iob = The I/O buffer to flush, usually csp->iob.
967 * Returns : On success, the number of bytes written are returned (zero
968 * indicates nothing was written). On error, -1 is returned,
969 * and errno is set appropriately. If count is zero and the
970 * file descriptor refers to a regular file, 0 will be
971 * returned without causing any other effect. For a special
972 * file, the results are not portable.
974 *********************************************************************/
975 int flush_socket(jb_socket fd, struct iob *iob)
977 int len = iob->eod - iob->cur;
984 if (write_socket(fd, iob->cur, (size_t)len))
988 iob->eod = iob->cur = iob->buf;
994 /*********************************************************************
996 * Function : add_to_iob
998 * Description : Add content to the buffered page, expanding the
999 * buffer if necessary.
1002 * 1 : csp = Current client state (buffers, headers, etc...)
1003 * 2 : buf = holds the content to be added to the page
1004 * 3 : n = number of bytes to be added
1006 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1007 * or buffer limit reached.
1009 *********************************************************************/
1010 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1012 struct iob *iob = csp->iob;
1013 size_t used, offset, need, want;
1016 if (n <= 0) return JB_ERR_OK;
1018 used = (size_t)(iob->eod - iob->buf);
1019 offset = (size_t)(iob->cur - iob->buf);
1020 need = used + (size_t)n + 1;
1023 * If the buffer can't hold the new data, extend it first.
1024 * Use the next power of two if possible, else use the actual need.
1026 if (need > csp->config->buffer_limit)
1028 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1029 return JB_ERR_MEMORY;
1032 if (need > iob->size)
1034 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1036 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1040 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1046 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1047 return JB_ERR_MEMORY;
1050 /* Update the iob pointers */
1051 iob->cur = p + offset;
1052 iob->eod = p + used;
1056 /* copy the new data into the iob buffer */
1057 memcpy(iob->eod, buf, (size_t)n);
1059 /* point to the end of the data */
1062 /* null terminate == cheap insurance */
1071 /*********************************************************************
1073 * Function : decompress_iob
1075 * Description : Decompress buffered page, expanding the
1076 * buffer as necessary. csp->iob->cur
1077 * should point to the the beginning of the
1078 * compressed data block.
1081 * 1 : csp = Current client state (buffers, headers, etc...)
1083 * Returns : JB_ERR_OK on success,
1084 * JB_ERR_MEMORY if out-of-memory limit reached, and
1085 * JB_ERR_COMPRESS if error decompressing buffer.
1087 *********************************************************************/
1088 jb_err decompress_iob(struct client_state *csp)
1090 char *buf; /* new, uncompressed buffer */
1091 char *cur; /* Current iob position (to keep the original
1092 * iob->cur unmodified if we return early) */
1093 size_t bufsize; /* allocated size of the new buffer */
1094 size_t old_size; /* Content size before decompression */
1095 size_t skip_size; /* Number of bytes at the beginning of the iob
1096 that we should NOT decompress. */
1097 int status; /* return status of the inflate() call */
1098 z_stream zstr; /* used by calls to zlib */
1100 assert(csp->iob->cur - csp->iob->buf > 0);
1101 assert(csp->iob->eod - csp->iob->cur > 0);
1103 bufsize = csp->iob->size;
1104 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1105 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1107 cur = csp->iob->cur;
1112 * This is to protect the parsing of gzipped data,
1113 * but it should(?) be valid for deflated data also.
1115 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1116 return JB_ERR_COMPRESS;
1119 if (csp->content_type & CT_GZIP)
1122 * Our task is slightly complicated by the facts that data
1123 * compressed by gzip does not include a zlib header, and
1124 * that there is no easily accessible interface in zlib to
1125 * handle a gzip header. We strip off the gzip header by
1126 * hand, and later inform zlib not to expect a header.
1130 * Strip off the gzip header. Please see RFC 1952 for more
1131 * explanation of the appropriate fields.
1133 if ((*cur++ != (char)0x1f)
1134 || (*cur++ != (char)0x8b)
1135 || (*cur++ != Z_DEFLATED))
1137 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1138 return JB_ERR_COMPRESS;
1144 * XXX: These magic numbers should be replaced
1145 * with macros to give a better idea what they do.
1149 /* The gzip header has reserved bits set; bail out. */
1150 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1151 return JB_ERR_COMPRESS;
1155 /* Skip extra fields if necessary. */
1159 * Skip a given number of bytes, specified
1160 * as a 16-bit little-endian value.
1163 * XXX: This code used to be:
1165 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1167 * which I had to change into:
1169 * cur += *cur++ + (*cur++ << 8);
1171 * at which point gcc43 finally noticed that the value
1172 * of cur is undefined (it depends on which of the
1173 * summands is evaluated first).
1175 * I haven't come across a site where this
1176 * code is actually executed yet, but I hope
1180 skip_bytes = *cur++;
1181 skip_bytes = *cur++ << 8;
1183 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1186 * The number of bytes to skip should be positive
1187 * and we'd like to stay in the buffer.
1189 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1191 log_error(LOG_LEVEL_ERROR,
1192 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1194 return JB_ERR_COMPRESS;
1196 log_error(LOG_LEVEL_INFO,
1197 "Skipping %d bytes for gzip compression. Does this sound right?",
1202 /* Skip the filename if necessary. */
1205 /* A null-terminated string is supposed to follow. */
1206 while (*cur++ && (cur < csp->iob->eod));
1210 /* Skip the comment if necessary. */
1213 /* A null-terminated string is supposed to follow. */
1214 while (*cur++ && (cur < csp->iob->eod));
1217 /* Skip the CRC if necessary. */
1223 if (cur >= csp->iob->eod)
1226 * If the current position pointer reached or passed
1227 * the buffer end, we were obviously tricked to skip
1230 log_error(LOG_LEVEL_ERROR,
1231 "Malformed gzip header detected. Aborting decompression.");
1232 return JB_ERR_COMPRESS;
1236 else if (csp->content_type & CT_DEFLATE)
1239 * XXX: The debug level should be lowered
1240 * before the next stable release.
1242 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1244 * In theory (that is, according to RFC 1950), deflate-compressed
1245 * data should begin with a two-byte zlib header and have an
1246 * adler32 checksum at the end. It seems that in practice only
1247 * the raw compressed data is sent. Note that this means that
1248 * we are not RFC 1950-compliant here, but the advantage is that
1249 * this actually works. :)
1251 * We add a dummy null byte to tell zlib where the data ends,
1252 * and later inform it not to expect a header.
1254 * Fortunately, add_to_iob() has thoughtfully null-terminated
1255 * the buffer; we can just increment the end pointer to include
1262 log_error(LOG_LEVEL_ERROR,
1263 "Unable to determine compression format for decompression");
1264 return JB_ERR_COMPRESS;
1267 /* Set up the fields required by zlib. */
1268 zstr.next_in = (Bytef *)cur;
1269 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1270 zstr.zalloc = Z_NULL;
1271 zstr.zfree = Z_NULL;
1272 zstr.opaque = Z_NULL;
1275 * Passing -MAX_WBITS to inflateInit2 tells the library
1276 * that there is no zlib header.
1278 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1280 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1281 return JB_ERR_COMPRESS;
1285 * Next, we allocate new storage for the inflated data.
1286 * We don't modify the existing iob yet, so in case there
1287 * is error in decompression we can recover gracefully.
1289 buf = zalloc(bufsize);
1292 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1293 return JB_ERR_MEMORY;
1296 assert(bufsize >= skip_size);
1297 memcpy(buf, csp->iob->buf, skip_size);
1298 zstr.avail_out = bufsize - skip_size;
1299 zstr.next_out = (Bytef *)buf + skip_size;
1301 /* Try to decompress the whole stream in one shot. */
1302 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1304 /* We need to allocate more memory for the output buffer. */
1306 char *tmpbuf; /* used for realloc'ing the buffer */
1307 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1310 * If zlib wants more data then there's a problem, because
1311 * the complete compressed file should have been buffered.
1313 if (0 == zstr.avail_in)
1315 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1316 return JB_ERR_COMPRESS;
1320 * If we tried the limit and still didn't have enough
1321 * memory, just give up.
1323 if (bufsize == csp->config->buffer_limit)
1325 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1326 return JB_ERR_MEMORY;
1329 /* Try doubling the buffer size each time. */
1332 /* Don't exceed the buffer limit. */
1333 if (bufsize > csp->config->buffer_limit)
1335 bufsize = csp->config->buffer_limit;
1338 /* Try to allocate the new buffer. */
1339 tmpbuf = realloc(buf, bufsize);
1342 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1344 return JB_ERR_MEMORY;
1348 char *oldnext_out = (char *)zstr.next_out;
1351 * Update the fields for inflate() to use the new
1352 * buffer, which may be in a location different from
1355 zstr.avail_out += bufsize - oldbufsize;
1356 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1359 * Compare with an uglier method of calculating these values
1360 * that doesn't require the extra oldbufsize variable.
1362 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1363 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1364 assert(zstr.avail_out > 0);
1370 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1372 log_error(LOG_LEVEL_ERROR,
1373 "Inconsistent stream state after decompression: %s", zstr.msg);
1375 * XXX: Intentionally no return.
1377 * According to zlib.h, Z_STREAM_ERROR is returned
1378 * "if the stream state was inconsistent".
1380 * I assume in this case inflate()'s status
1381 * would also be something different than Z_STREAM_END
1382 * so this check should be redundant, but lets see.
1386 if (status != Z_STREAM_END)
1388 /* We failed to decompress the stream. */
1389 log_error(LOG_LEVEL_ERROR,
1390 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1391 return JB_ERR_COMPRESS;
1395 * Finally, we can actually update the iob, since the
1396 * decompression was successful. First, free the old
1399 freez(csp->iob->buf);
1401 /* Now, update the iob to use the new buffer. */
1402 csp->iob->buf = buf;
1403 csp->iob->cur = csp->iob->buf + skip_size;
1404 csp->iob->eod = (char *)zstr.next_out;
1405 csp->iob->size = bufsize;
1408 * Make sure the new uncompressed iob obeys some minimal
1409 * consistency conditions.
1411 if ((csp->iob->buf < csp->iob->cur)
1412 && (csp->iob->cur <= csp->iob->eod)
1413 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1415 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1418 log_error(LOG_LEVEL_RE_FILTER,
1419 "Decompression successful. Old size: %d, new size: %d.",
1420 old_size, new_size);
1424 /* zlib thinks this is OK, so lets do the same. */
1425 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1430 /* It seems that zlib did something weird. */
1431 log_error(LOG_LEVEL_ERROR,
1432 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1433 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1434 csp->iob->eod, csp->iob->buf + csp->iob->size);
1435 return JB_ERR_COMPRESS;
1441 #endif /* defined(FEATURE_ZLIB) */
1444 /*********************************************************************
1446 * Function : normalize_lws
1448 * Description : Reduces unquoted linear white space in headers
1449 * to a single space in accordance with RFC 2616 2.2.
1450 * This simplifies parsing and filtering later on.
1452 * XXX: Remove log messages before
1453 * the next stable release?
1456 * 1 : header = A header with linear white space to reduce.
1460 *********************************************************************/
1461 static void normalize_lws(char *header)
1467 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1471 while (ijb_isspace(*q))
1475 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1476 memmove(p+1, q, strlen(q)+1);
1481 log_error(LOG_LEVEL_HEADER,
1482 "Converting tab to space in '%s'", header);
1487 char *end_of_token = strstr(p+1, "\"");
1489 if (NULL != end_of_token)
1491 /* Don't mess with quoted text. */
1496 log_error(LOG_LEVEL_HEADER,
1497 "Ignoring single quote in '%s'", header);
1503 p = strchr(header, ':');
1504 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1507 * There's still space before the colon.
1510 memmove(p-1, p, strlen(p)+1);
1515 /*********************************************************************
1517 * Function : get_header
1519 * Description : This (odd) routine will parse the csp->iob
1520 * to get the next complete header.
1523 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1525 * Returns : Any one of the following:
1527 * 1) a pointer to a dynamically allocated string that contains a header line
1528 * 2) NULL indicating that the end of the header was reached
1529 * 3) "" indicating that the end of the iob was reached before finding
1530 * a complete header line.
1532 *********************************************************************/
1533 char *get_header(struct iob *iob)
1537 header = get_header_line(iob);
1539 if ((header == NULL) || (*header == '\0'))
1542 * No complete header read yet, tell the client.
1547 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1550 * Header spans multiple lines, append the next one.
1552 char *continued_header;
1554 continued_header = get_header_line(iob);
1555 if ((continued_header == NULL) || (*continued_header == '\0'))
1558 * No complete header read yet, return what we got.
1559 * XXX: Should "unread" header instead.
1561 log_error(LOG_LEVEL_INFO,
1562 "Failed to read a multi-line header properly: '%s'",
1567 if (JB_ERR_OK != string_join(&header, continued_header))
1569 log_error(LOG_LEVEL_FATAL,
1570 "Out of memory while appending multiple headers.");
1574 /* XXX: remove before next stable release. */
1575 log_error(LOG_LEVEL_HEADER,
1576 "Merged multiple header lines to: '%s'",
1581 normalize_lws(header);
1588 /*********************************************************************
1590 * Function : get_header_line
1592 * Description : This (odd) routine will parse the csp->iob
1593 * to get the next header line.
1596 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1598 * Returns : Any one of the following:
1600 * 1) a pointer to a dynamically allocated string that contains a header line
1601 * 2) NULL indicating that the end of the header was reached
1602 * 3) "" indicating that the end of the iob was reached before finding
1603 * a complete header line.
1605 *********************************************************************/
1606 static char *get_header_line(struct iob *iob)
1610 if ((iob->cur == NULL)
1611 || ((p = strchr(iob->cur, '\n')) == NULL))
1613 return(""); /* couldn't find a complete header */
1618 ret = strdup(iob->cur);
1621 /* FIXME No way to handle error properly */
1622 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1627 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1629 /* is this a blank line (i.e. the end of the header) ? */
1641 /*********************************************************************
1643 * Function : get_header_value
1645 * Description : Get the value of a given header from a chained list
1646 * of header lines or return NULL if no such header is
1647 * present in the list.
1650 * 1 : header_list = pointer to list
1651 * 2 : header_name = string with name of header to look for.
1652 * Trailing colon required, capitalization
1655 * Returns : NULL if not found, else value of header
1657 *********************************************************************/
1658 char *get_header_value(const struct list *header_list, const char *header_name)
1660 struct list_entry *cur_entry;
1664 assert(header_list);
1665 assert(header_name);
1666 length = strlen(header_name);
1668 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1672 if (!strncmpic(cur_entry->str, header_name, length))
1675 * Found: return pointer to start of value
1677 ret = (char *) (cur_entry->str + length);
1678 while (*ret && ijb_isspace(*ret)) ret++;
1692 /*********************************************************************
1694 * Function : scan_headers
1696 * Description : Scans headers, applies tags and updates action bits.
1699 * 1 : csp = Current client state (buffers, headers, etc...)
1701 * Returns : JB_ERR_OK
1703 *********************************************************************/
1704 static jb_err scan_headers(struct client_state *csp)
1706 struct list_entry *h; /* Header */
1707 jb_err err = JB_ERR_OK;
1709 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1711 /* Header crunch()ed in previous run? -> ignore */
1712 if (h->str == NULL) continue;
1713 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1714 err = header_tagger(csp, h->str);
1721 /*********************************************************************
1725 * Description : add, delete or modify lines in the HTTP header streams.
1726 * On entry, it receives a linked list of headers space
1727 * that was allocated dynamically (both the list nodes
1728 * and the header contents).
1730 * As a side effect it frees the space used by the original
1733 * XXX: should be split to remove the first_run hack.
1736 * 1 : pats = list of patterns to match against headers
1737 * 2 : more_headers = list of functions to add more
1738 * headers (client or server)
1739 * 3 : csp = Current client state (buffers, headers, etc...)
1741 * Returns : JB_ERR_OK in case off success, or
1742 * JB_ERR_MEMORY on out-of-memory error.
1744 *********************************************************************/
1745 jb_err sed(const struct parsers pats[],
1746 const add_header_func_ptr more_headers[],
1747 struct client_state *csp)
1749 struct list_entry *p;
1750 const struct parsers *v;
1751 const add_header_func_ptr *f;
1752 jb_err err = JB_ERR_OK;
1756 * If filtering is enabled, sed is run twice,
1757 * but most of the work needs to be done only once.
1759 first_run = (more_headers != NULL ) ? 1 : 0;
1761 if (first_run) /* Parse and print */
1765 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1767 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1769 /* Header crunch()ed in previous run? -> ignore */
1770 if (p->str == NULL) continue;
1772 /* Does the current parser handle this header? */
1773 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1775 err = v->parser(csp, (char **)&(p->str));
1779 /* place any additional headers on the csp->headers list */
1780 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1785 else /* Parse only */
1788 * The second run is only needed if the body was modified
1789 * and the content-lenght has changed.
1791 if (strncmpic(csp->http->cmd, "HEAD", 4))
1793 /*XXX: Code duplication */
1794 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1796 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1798 /* Header crunch()ed in previous run? -> ignore */
1799 if (p->str == NULL) continue;
1801 /* Does the current parser handle this header? */
1802 if (strncmpic(p->str, v->str, v->len) == 0)
1804 err = v->parser(csp, (char **)&(p->str));
1816 /*********************************************************************
1818 * Function : header_tagger
1820 * Description : Executes all text substitutions from applying
1821 * tag actions and saves the result as tag.
1823 * XXX: Shares enough code with filter_header() and
1824 * pcrs_filter_response() to warrant some helper functions.
1827 * 1 : csp = Current client state (buffers, headers, etc...)
1828 * 2 : header = Header that is used as tagger input
1830 * Returns : JB_ERR_OK on success and always succeeds
1832 *********************************************************************/
1833 static jb_err header_tagger(struct client_state *csp, char *header)
1835 int wanted_filter_type;
1836 int multi_action_index;
1840 struct file_list *fl;
1841 struct re_filterfile_spec *b;
1842 struct list_entry *tag_name;
1844 int found_filters = 0;
1845 const size_t header_length = strlen(header);
1847 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1849 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1850 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1854 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1855 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1858 /* Check if there are any filters */
1859 for (i = 0; i < MAX_AF_FILES; i++)
1872 if (0 == found_filters)
1874 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1875 "tagging enabled, but no taggers available.");
1879 for (i = 0; i < MAX_AF_FILES; i++)
1882 if ((NULL == fl) || (NULL == fl->f))
1885 * Either there are no filter files
1886 * left, or this filter file just
1887 * contains no valid filters.
1889 * Continue to be sure we don't miss
1890 * valid filter files that are chained
1891 * after empty or invalid ones.
1896 /* For all filters, */
1897 for (b = fl->f; b; b = b->next)
1899 if (b->type != wanted_filter_type)
1901 /* skip the ones we don't care about, */
1904 /* leaving only taggers that could apply, of which we use the ones, */
1905 for (tag_name = csp->action->multi[multi_action_index]->first;
1906 NULL != tag_name; tag_name = tag_name->next)
1908 /* that do apply, and */
1909 if (strcmp(b->name, tag_name->str) == 0)
1911 char *modified_tag = NULL;
1913 size_t size = header_length;
1914 pcrs_job *joblist = b->joblist;
1916 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1918 if (NULL == joblist)
1920 log_error(LOG_LEVEL_RE_FILTER,
1921 "Tagger %s has empty joblist. Nothing to do.", b->name);
1925 /* execute their pcrs_joblist on the header. */
1926 for (job = joblist; NULL != job; job = job->next)
1928 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1932 /* Success, continue with the modified version. */
1941 /* Tagger doesn't match */
1944 /* Regex failure, log it but continue anyway. */
1945 log_error(LOG_LEVEL_ERROR,
1946 "Problems with tagger \'%s\' and header \'%s\': %s",
1947 b->name, *header, pcrs_strerror(hits));
1949 freez(modified_tag);
1953 if (b->dynamic) pcrs_free_joblist(joblist);
1955 /* If this tagger matched */
1961 * There is to technical limitation which makes
1962 * it impossible to use empty tags, but I assume
1963 * no one would do it intentionally.
1966 log_error(LOG_LEVEL_INFO,
1967 "Tagger \'%s\' created an empty tag. Ignored.",
1972 if (!list_contains_item(csp->tags, tag))
1974 if (JB_ERR_OK != enlist(csp->tags, tag))
1976 log_error(LOG_LEVEL_ERROR,
1977 "Insufficient memory to add tag \'%s\', "
1978 "based on tagger \'%s\' and header \'%s\'",
1979 tag, b->name, *header);
1983 char *action_message;
1985 * update the action bits right away, to make
1986 * tagging based on tags set by earlier taggers
1987 * of the same kind possible.
1989 if (update_action_bits_for_tag(csp, tag))
1991 action_message = "Action bits updated accordingly.";
1995 action_message = "No action bits update necessary.";
1998 log_error(LOG_LEVEL_HEADER,
1999 "Tagger \'%s\' added tag \'%s\'. %s",
2000 b->name, tag, action_message);
2005 /* XXX: Is this log-worthy? */
2006 log_error(LOG_LEVEL_HEADER,
2007 "Tagger \'%s\' didn't add tag \'%s\'. "
2008 "Tag already present", b->name, tag);
2011 } /* if the tagger matched */
2012 } /* if the tagger applies */
2013 } /* for every tagger that could apply */
2014 } /* for all filters */
2015 } /* for all filter files */
2020 /* here begins the family of parser functions that reformat header lines */
2022 /*********************************************************************
2024 * Function : filter_header
2026 * Description : Executes all text substitutions from all applying
2027 * +(server|client)-header-filter actions on the header.
2028 * Most of the code was copied from pcrs_filter_response,
2029 * including the rather short variable names
2032 * 1 : csp = Current client state (buffers, headers, etc...)
2033 * 2 : header = On input, pointer to header to modify.
2034 * On output, pointer to the modified header, or NULL
2035 * to remove the header. This function frees the
2036 * original string if necessary.
2038 * Returns : JB_ERR_OK on success and always succeeds
2040 *********************************************************************/
2041 static jb_err filter_header(struct client_state *csp, char **header)
2045 size_t size = strlen(*header);
2047 char *newheader = NULL;
2050 struct file_list *fl;
2051 struct re_filterfile_spec *b;
2052 struct list_entry *filtername;
2054 int i, found_filters = 0;
2055 int wanted_filter_type;
2056 int multi_action_index;
2058 if (csp->flags & CSP_FLAG_NO_FILTERING)
2063 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2065 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2066 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2070 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2071 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2075 * Need to check the set of re_filterfiles...
2077 for (i = 0; i < MAX_AF_FILES; i++)
2090 if (0 == found_filters)
2092 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2093 "header filtering enabled, but no matching filters available.");
2097 for (i = 0; i < MAX_AF_FILES; i++)
2100 if ((NULL == fl) || (NULL == fl->f))
2103 * Either there are no filter files
2104 * left, or this filter file just
2105 * contains no valid filters.
2107 * Continue to be sure we don't miss
2108 * valid filter files that are chained
2109 * after empty or invalid ones.
2114 * For all applying +filter actions, look if a filter by that
2115 * name exists and if yes, execute its pcrs_joblist on the
2118 for (b = fl->f; b; b = b->next)
2120 if (b->type != wanted_filter_type)
2122 /* Skip other filter types */
2126 for (filtername = csp->action->multi[multi_action_index]->first;
2127 filtername ; filtername = filtername->next)
2129 if (strcmp(b->name, filtername->str) == 0)
2131 int current_hits = 0;
2132 pcrs_job *joblist = b->joblist;
2134 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2136 if (NULL == joblist)
2138 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2142 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2143 *header, size, b->name);
2145 /* Apply all jobs from the joblist */
2146 for (job = joblist; NULL != job; job = job->next)
2148 matches = pcrs_execute(job, *header, size, &newheader, &size);
2151 current_hits += matches;
2152 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2154 *header = newheader;
2156 else if ( 0 == matches )
2158 /* Filter doesn't change header */
2164 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2165 *header, b->name, pcrs_strerror(matches));
2166 if (newheader != NULL)
2168 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2174 if (b->dynamic) pcrs_free_joblist(joblist);
2176 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2177 hits += current_hits;
2184 * Additionally checking for hits is important because if
2185 * the continue hack is triggered, server headers can
2186 * arrive empty to separate multiple heads from each other.
2188 if ((0 == size) && hits)
2190 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2198 /*********************************************************************
2200 * Function : connection
2202 * Description : Makes sure that the value of the Connection: header
2203 * is "close" and signals connection_close_adder
2207 * 1 : csp = Current client state (buffers, headers, etc...)
2208 * 2 : header = On input, pointer to header to modify.
2209 * On output, pointer to the modified header, or NULL
2210 * to remove the header. This function frees the
2211 * original string if necessary.
2213 * Returns : JB_ERR_OK on success, or
2214 * JB_ERR_MEMORY on out-of-memory error.
2216 *********************************************************************/
2217 static jb_err connection(struct client_state *csp, char **header)
2219 char *old_header = *header;
2221 /* Do we have a 'Connection: close' header? */
2222 if (strcmpic(*header, "Connection: close"))
2224 /* No, create one */
2225 *header = strdup("Connection: close");
2228 return JB_ERR_MEMORY;
2230 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2234 /* Signal connection_close_adder() to return early. */
2235 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2237 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2241 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2248 /*********************************************************************
2250 * Function : crumble
2252 * Description : This is called if a header matches a pattern to "crunch"
2255 * 1 : csp = Current client state (buffers, headers, etc...)
2256 * 2 : header = On input, pointer to header to modify.
2257 * On output, pointer to the modified header, or NULL
2258 * to remove the header. This function frees the
2259 * original string if necessary.
2261 * Returns : JB_ERR_OK on success, or
2262 * JB_ERR_MEMORY on out-of-memory error.
2264 *********************************************************************/
2265 static jb_err crumble(struct client_state *csp, char **header)
2267 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2273 /*********************************************************************
2275 * Function : crunch_server_header
2277 * Description : Crunch server header if it matches a string supplied by the
2278 * user. Called from `sed'.
2281 * 1 : csp = Current client state (buffers, headers, etc...)
2282 * 2 : header = On input, pointer to header to modify.
2283 * On output, pointer to the modified header, or NULL
2284 * to remove the header. This function frees the
2285 * original string if necessary.
2287 * Returns : JB_ERR_OK on success and always succeeds
2289 *********************************************************************/
2290 static jb_err crunch_server_header(struct client_state *csp, char **header)
2292 const char *crunch_pattern;
2294 /* Do we feel like crunching? */
2295 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2297 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2299 /* Is the current header the lucky one? */
2300 if (strstr(*header, crunch_pattern))
2302 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2311 /*********************************************************************
2313 * Function : server_content_type
2315 * Description : Set the content-type for filterable types (text/.*,
2316 * .*xml.*, javascript and image/gif) unless filtering has been
2317 * forbidden (CT_TABOO) while parsing earlier headers.
2318 * NOTE: Since text/plain is commonly used by web servers
2319 * for files whose correct type is unknown, we don't
2320 * set CT_TEXT for it.
2323 * 1 : csp = Current client state (buffers, headers, etc...)
2324 * 2 : header = On input, pointer to header to modify.
2325 * On output, pointer to the modified header, or NULL
2326 * to remove the header. This function frees the
2327 * original string if necessary.
2329 * Returns : JB_ERR_OK on success, or
2330 * JB_ERR_MEMORY on out-of-memory error.
2332 *********************************************************************/
2333 static jb_err server_content_type(struct client_state *csp, char **header)
2335 /* Remove header if it isn't the first Content-Type header */
2336 if ((csp->content_type & CT_DECLARED))
2339 * Another, slightly slower, way to see if
2340 * we already parsed another Content-Type header.
2342 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2344 log_error(LOG_LEVEL_ERROR,
2345 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2353 * Signal that the Content-Type has been set.
2355 csp->content_type |= CT_DECLARED;
2357 if (!(csp->content_type & CT_TABOO))
2360 * XXX: The assumption that text/plain is a sign of
2361 * binary data seems to be somewhat unreasonable nowadays
2362 * and should be dropped after 3.0.8 is out.
2364 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2365 || strstr(*header, "xml")
2366 || strstr(*header, "application/x-javascript"))
2368 csp->content_type |= CT_TEXT;
2370 else if (strstr(*header, "image/gif"))
2372 csp->content_type |= CT_GIF;
2377 * Are we messing with the content type?
2379 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2382 * Make sure the user doesn't accidently
2383 * change the content type of binary documents.
2385 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2388 *header = strdup("Content-Type: ");
2389 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2393 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2394 return JB_ERR_MEMORY;
2396 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2400 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2401 "It doesn't look like a content type that should be filtered. "
2402 "Enable force-text-mode if you know what you're doing.", *header);
2410 /*********************************************************************
2412 * Function : server_transfer_coding
2414 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2415 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2416 * - Remove header if body was chunked but has been
2417 * de-chunked for filtering.
2420 * 1 : csp = Current client state (buffers, headers, etc...)
2421 * 2 : header = On input, pointer to header to modify.
2422 * On output, pointer to the modified header, or NULL
2423 * to remove the header. This function frees the
2424 * original string if necessary.
2426 * Returns : JB_ERR_OK on success, or
2427 * JB_ERR_MEMORY on out-of-memory error.
2429 *********************************************************************/
2430 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2433 * Turn off pcrs and gif filtering if body compressed
2435 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2439 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2441 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2442 csp->http->cmd, *header);
2443 #endif /* def FEATURE_ZLIB */
2444 csp->content_type = CT_TABOO;
2448 * Raise flag if body chunked
2450 if (strstr(*header, "chunked"))
2452 csp->flags |= CSP_FLAG_CHUNKED;
2455 * If the body was modified, it has been de-chunked first
2456 * and the header must be removed.
2458 * FIXME: If there is more than one transfer encoding,
2459 * only the "chunked" part should be removed here.
2461 if (csp->flags & CSP_FLAG_MODIFIED)
2463 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2472 /*********************************************************************
2474 * Function : server_content_encoding
2476 * Description : This function is run twice for each request,
2477 * unless FEATURE_ZLIB and filtering are disabled.
2479 * The first run is used to check if the content
2480 * is compressed, if FEATURE_ZLIB is disabled
2481 * filtering is then disabled as well, if FEATURE_ZLIB
2482 * is enabled the content is marked for decompression.
2484 * The second run is used to remove the Content-Encoding
2485 * header if the decompression was successful.
2488 * 1 : csp = Current client state (buffers, headers, etc...)
2489 * 2 : header = On input, pointer to header to modify.
2490 * On output, pointer to the modified header, or NULL
2491 * to remove the header. This function frees the
2492 * original string if necessary.
2494 * Returns : JB_ERR_OK on success, or
2495 * JB_ERR_MEMORY on out-of-memory error.
2497 *********************************************************************/
2498 static jb_err server_content_encoding(struct client_state *csp, char **header)
2501 if ((csp->flags & CSP_FLAG_MODIFIED)
2502 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2505 * We successfully decompressed the content,
2506 * and have to clean the header now, so the
2507 * client no longer expects compressed data..
2509 * XXX: There is a difference between cleaning
2510 * and removing it completely.
2512 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2515 else if (strstr(*header, "gzip"))
2517 /* Mark for gzip decompression */
2518 csp->content_type |= CT_GZIP;
2520 else if (strstr(*header, "deflate"))
2522 /* Mark for zlib decompression */
2523 csp->content_type |= CT_DEFLATE;
2525 else if (strstr(*header, "compress"))
2528 * We can't decompress this; therefore we can't filter
2531 csp->content_type |= CT_TABOO;
2533 #else /* !defined(FEATURE_ZLIB) */
2534 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2537 * Body is compressed, turn off pcrs and gif filtering.
2539 csp->content_type |= CT_TABOO;
2542 * Log a warning if the user expects the content to be filtered.
2544 if ((csp->rlist != NULL) &&
2545 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2547 log_error(LOG_LEVEL_INFO,
2548 "Compressed content detected, content filtering disabled. "
2549 "Consider recompiling Privoxy with zlib support or "
2550 "enable the prevent-compression action.");
2553 #endif /* defined(FEATURE_ZLIB) */
2560 /*********************************************************************
2562 * Function : server_content_length
2564 * Description : Adjust Content-Length header if we modified
2568 * 1 : csp = Current client state (buffers, headers, etc...)
2569 * 2 : header = On input, pointer to header to modify.
2570 * On output, pointer to the modified header, or NULL
2571 * to remove the header. This function frees the
2572 * original string if necessary.
2574 * Returns : JB_ERR_OK on success, or
2575 * JB_ERR_MEMORY on out-of-memory error.
2577 *********************************************************************/
2578 static jb_err server_content_length(struct client_state *csp, char **header)
2580 const size_t max_header_length = 80;
2582 /* Regenerate header if the content was modified. */
2583 if (csp->flags & CSP_FLAG_MODIFIED)
2586 *header = (char *) zalloc(max_header_length);
2587 if (*header == NULL)
2589 return JB_ERR_MEMORY;
2592 snprintf(*header, max_header_length, "Content-Length: %d",
2593 (int)csp->content_length);
2594 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2595 (int)csp->content_length);
2602 /*********************************************************************
2604 * Function : server_content_md5
2606 * Description : Crumble any Content-MD5 headers if the document was
2607 * modified. FIXME: Should we re-compute instead?
2610 * 1 : csp = Current client state (buffers, headers, etc...)
2611 * 2 : header = On input, pointer to header to modify.
2612 * On output, pointer to the modified header, or NULL
2613 * to remove the header. This function frees the
2614 * original string if necessary.
2616 * Returns : JB_ERR_OK on success, or
2617 * JB_ERR_MEMORY on out-of-memory error.
2619 *********************************************************************/
2620 static jb_err server_content_md5(struct client_state *csp, char **header)
2622 if (csp->flags & CSP_FLAG_MODIFIED)
2624 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2632 /*********************************************************************
2634 * Function : server_content_disposition
2636 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2637 * Called from `sed'.
2640 * 1 : csp = Current client state (buffers, headers, etc...)
2641 * 2 : header = On input, pointer to header to modify.
2642 * On output, pointer to the modified header, or NULL
2643 * to remove the header. This function frees the
2644 * original string if necessary.
2646 * Returns : JB_ERR_OK on success, or
2647 * JB_ERR_MEMORY on out-of-memory error.
2649 *********************************************************************/
2650 static jb_err server_content_disposition(struct client_state *csp, char **header)
2655 * Are we messing with the Content-Disposition header?
2657 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2663 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2665 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2668 * Blocking content-disposition header
2670 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2677 * Replacing Content-Disposition header
2680 *header = strdup("Content-Disposition: ");
2681 string_append(header, newval);
2683 if (*header != NULL)
2685 log_error(LOG_LEVEL_HEADER,
2686 "Content-Disposition header crunched and replaced with: %s", *header);
2689 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2693 /*********************************************************************
2695 * Function : server_last_modified
2697 * Description : Changes Last-Modified header to the actual date
2698 * to help hide-if-modified-since.
2699 * Called from `sed'.
2702 * 1 : csp = Current client state (buffers, headers, etc...)
2703 * 2 : header = On input, pointer to header to modify.
2704 * On output, pointer to the modified header, or NULL
2705 * to remove the header. This function frees the
2706 * original string if necessary.
2708 * Returns : JB_ERR_OK on success, or
2709 * JB_ERR_MEMORY on out-of-memory error.
2711 *********************************************************************/
2712 static jb_err server_last_modified(struct client_state *csp, char **header)
2715 char buf[BUFFER_SIZE];
2718 #ifdef HAVE_GMTIME_R
2721 struct tm *timeptr = NULL;
2722 time_t now, last_modified;
2724 long int days, hours, minutes, seconds;
2727 * Are we messing with the Last-Modified header?
2729 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2735 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2737 if (0 == strcmpic(newval, "block") )
2740 * Blocking Last-Modified header. Useless but why not.
2742 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2746 else if (0 == strcmpic(newval, "reset-to-request-time"))
2749 * Setting Last-Modified Header to now.
2751 get_http_time(0, buf, sizeof(buf));
2753 *header = strdup("Last-Modified: ");
2754 string_append(header, buf);
2756 if (*header == NULL)
2758 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2762 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2765 else if (0 == strcmpic(newval, "randomize"))
2767 const char *header_time = *header + sizeof("Last-Modified:");
2769 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2771 #ifdef HAVE_GMTIME_R
2772 timeptr = gmtime_r(&now, &gmt);
2773 #elif FEATURE_PTHREAD
2774 pthread_mutex_lock(&gmtime_mutex);
2775 timeptr = gmtime(&now);
2776 pthread_mutex_unlock(&gmtime_mutex);
2778 timeptr = gmtime(&now);
2780 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2782 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2787 rtime = (long int)difftime(now, last_modified);
2796 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2798 rtime = pick_from_range(rtime);
2799 if (negative) rtime *= -1;
2800 last_modified += rtime;
2801 #ifdef HAVE_GMTIME_R
2802 timeptr = gmtime_r(&last_modified, &gmt);
2803 #elif FEATURE_PTHREAD
2804 pthread_mutex_lock(&gmtime_mutex);
2805 timeptr = gmtime(&last_modified);
2806 pthread_mutex_unlock(&gmtime_mutex);
2808 timeptr = gmtime(&last_modified);
2810 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2812 *header = strdup("Last-Modified: ");
2813 string_append(header, newheader);
2815 if (*header == NULL)
2817 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2818 return JB_ERR_MEMORY;
2821 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2823 days = rtime / (3600 * 24);
2824 hours = rtime / 3600 % 24;
2825 minutes = rtime / 60 % 60;
2826 seconds = rtime % 60;
2828 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2829 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2830 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2835 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2844 /*********************************************************************
2846 * Function : client_accept_encoding
2848 * Description : Rewrite the client's Accept-Encoding header so that
2849 * if doesn't allow compression, if the action applies.
2850 * Note: For HTTP/1.0 the absence of the header is enough.
2853 * 1 : csp = Current client state (buffers, headers, etc...)
2854 * 2 : header = On input, pointer to header to modify.
2855 * On output, pointer to the modified header, or NULL
2856 * to remove the header. This function frees the
2857 * original string if necessary.
2859 * Returns : JB_ERR_OK on success, or
2860 * JB_ERR_MEMORY on out-of-memory error.
2862 *********************************************************************/
2863 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2865 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2867 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2871 /* Temporarily disable the correct behaviour to
2872 * work around a PHP bug.
2874 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2876 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2877 * if (*header == NULL)
2879 * return JB_ERR_MEMORY;
2890 /*********************************************************************
2892 * Function : client_te
2894 * Description : Rewrite the client's TE header so that
2895 * if doesn't allow compression, if the action applies.
2898 * 1 : csp = Current client state (buffers, headers, etc...)
2899 * 2 : header = On input, pointer to header to modify.
2900 * On output, pointer to the modified header, or NULL
2901 * to remove the header. This function frees the
2902 * original string if necessary.
2904 * Returns : JB_ERR_OK on success, or
2905 * JB_ERR_MEMORY on out-of-memory error.
2907 *********************************************************************/
2908 static jb_err client_te(struct client_state *csp, char **header)
2910 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2913 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2920 /*********************************************************************
2922 * Function : client_referrer
2924 * Description : Handle the "referer" config setting properly.
2925 * Called from `sed'.
2928 * 1 : csp = Current client state (buffers, headers, etc...)
2929 * 2 : header = On input, pointer to header to modify.
2930 * On output, pointer to the modified header, or NULL
2931 * to remove the header. This function frees the
2932 * original string if necessary.
2934 * Returns : JB_ERR_OK on success, or
2935 * JB_ERR_MEMORY on out-of-memory error.
2937 *********************************************************************/
2938 static jb_err client_referrer(struct client_state *csp, char **header)
2940 const char *parameter;
2941 /* booleans for parameters we have to check multiple times */
2942 int parameter_conditional_block;
2943 int parameter_conditional_forge;
2945 #ifdef FEATURE_FORCE_LOAD
2947 * Since the referrer can include the prefix even
2948 * if the request itself is non-forced, we must
2949 * clean it unconditionally.
2951 * XXX: strclean is too broad
2953 strclean(*header, FORCE_PREFIX);
2954 #endif /* def FEATURE_FORCE_LOAD */
2956 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2958 /* Nothing left to do */
2962 parameter = csp->action->string[ACTION_STRING_REFERER];
2963 assert(parameter != NULL);
2964 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2965 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2967 if (!parameter_conditional_block && !parameter_conditional_forge)
2970 * As conditional-block and conditional-forge are the only
2971 * parameters that rely on the original referrer, we can
2972 * remove it now for all the others.
2977 if (0 == strcmpic(parameter, "block"))
2979 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2982 else if (parameter_conditional_block || parameter_conditional_forge)
2984 return handle_conditional_hide_referrer_parameter(header,
2985 csp->http->hostport, parameter_conditional_block);
2987 else if (0 == strcmpic(parameter, "forge"))
2989 return create_forged_referrer(header, csp->http->hostport);
2993 /* interpret parameter as user-supplied referer to fake */
2994 return create_fake_referrer(header, parameter);
2999 /*********************************************************************
3001 * Function : client_accept_language
3003 * Description : Handle the "Accept-Language" config setting properly.
3004 * Called from `sed'.
3007 * 1 : csp = Current client state (buffers, headers, etc...)
3008 * 2 : header = On input, pointer to header to modify.
3009 * On output, pointer to the modified header, or NULL
3010 * to remove the header. This function frees the
3011 * original string if necessary.
3013 * Returns : JB_ERR_OK on success, or
3014 * JB_ERR_MEMORY on out-of-memory error.
3016 *********************************************************************/
3017 static jb_err client_accept_language(struct client_state *csp, char **header)
3022 * Are we messing with the Accept-Language?
3024 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3026 /*I don't think so*/
3030 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3032 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3035 * Blocking Accept-Language header
3037 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3044 * Replacing Accept-Language header
3047 *header = strdup("Accept-Language: ");
3048 string_append(header, newval);
3050 if (*header == NULL)
3052 log_error(LOG_LEVEL_ERROR,
3053 "Insufficent memory. Accept-Language header crunched without replacement.");
3057 log_error(LOG_LEVEL_HEADER,
3058 "Accept-Language header crunched and replaced with: %s", *header);
3061 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3065 /*********************************************************************
3067 * Function : crunch_client_header
3069 * Description : Crunch client header if it matches a string supplied by the
3070 * user. Called from `sed'.
3073 * 1 : csp = Current client state (buffers, headers, etc...)
3074 * 2 : header = On input, pointer to header to modify.
3075 * On output, pointer to the modified header, or NULL
3076 * to remove the header. This function frees the
3077 * original string if necessary.
3079 * Returns : JB_ERR_OK on success and always succeeds
3081 *********************************************************************/
3082 static jb_err crunch_client_header(struct client_state *csp, char **header)
3084 const char *crunch_pattern;
3086 /* Do we feel like crunching? */
3087 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3089 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3091 /* Is the current header the lucky one? */
3092 if (strstr(*header, crunch_pattern))
3094 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3102 /*********************************************************************
3104 * Function : client_uagent
3106 * Description : Handle the "user-agent" config setting properly
3107 * and remember its original value to enable browser
3108 * bug workarounds. Called from `sed'.
3111 * 1 : csp = Current client state (buffers, headers, etc...)
3112 * 2 : header = On input, pointer to header to modify.
3113 * On output, pointer to the modified header, or NULL
3114 * to remove the header. This function frees the
3115 * original string if necessary.
3117 * Returns : JB_ERR_OK on success, or
3118 * JB_ERR_MEMORY on out-of-memory error.
3120 *********************************************************************/
3121 static jb_err client_uagent(struct client_state *csp, char **header)
3125 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3130 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3137 *header = strdup("User-Agent: ");
3138 string_append(header, newval);
3140 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3142 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3146 /*********************************************************************
3148 * Function : client_ua
3150 * Description : Handle "ua-" headers properly. Called from `sed'.
3153 * 1 : csp = Current client state (buffers, headers, etc...)
3154 * 2 : header = On input, pointer to header to modify.
3155 * On output, pointer to the modified header, or NULL
3156 * to remove the header. This function frees the
3157 * original string if necessary.
3159 * Returns : JB_ERR_OK on success, or
3160 * JB_ERR_MEMORY on out-of-memory error.
3162 *********************************************************************/
3163 static jb_err client_ua(struct client_state *csp, char **header)
3165 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3167 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3175 /*********************************************************************
3177 * Function : client_from
3179 * Description : Handle the "from" config setting properly.
3180 * Called from `sed'.
3183 * 1 : csp = Current client state (buffers, headers, etc...)
3184 * 2 : header = On input, pointer to header to modify.
3185 * On output, pointer to the modified header, or NULL
3186 * to remove the header. This function frees the
3187 * original string if necessary.
3189 * Returns : JB_ERR_OK on success, or
3190 * JB_ERR_MEMORY on out-of-memory error.
3192 *********************************************************************/
3193 static jb_err client_from(struct client_state *csp, char **header)
3197 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3204 newval = csp->action->string[ACTION_STRING_FROM];
3207 * Are we blocking the e-mail address?
3209 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3211 log_error(LOG_LEVEL_HEADER, "crunched From!");
3215 log_error(LOG_LEVEL_HEADER, " modified");
3217 *header = strdup("From: ");
3218 string_append(header, newval);
3220 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3224 /*********************************************************************
3226 * Function : client_send_cookie
3228 * Description : Crunches the "cookie" header if necessary.
3229 * Called from `sed'.
3231 * XXX: Stupid name, doesn't send squat.
3234 * 1 : csp = Current client state (buffers, headers, etc...)
3235 * 2 : header = On input, pointer to header to modify.
3236 * On output, pointer to the modified header, or NULL
3237 * to remove the header. This function frees the
3238 * original string if necessary.
3240 * Returns : JB_ERR_OK on success, or
3241 * JB_ERR_MEMORY on out-of-memory error.
3243 *********************************************************************/
3244 static jb_err client_send_cookie(struct client_state *csp, char **header)
3246 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3248 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3256 /*********************************************************************
3258 * Function : client_x_forwarded
3260 * Description : Handle the "x-forwarded-for" config setting properly,
3261 * also used in the add_client_headers list. Called from `sed'.
3264 * 1 : csp = Current client state (buffers, headers, etc...)
3265 * 2 : header = On input, pointer to header to modify.
3266 * On output, pointer to the modified header, or NULL
3267 * to remove the header. This function frees the
3268 * original string if necessary.
3270 * Returns : JB_ERR_OK on success, or
3271 * JB_ERR_MEMORY on out-of-memory error.
3273 *********************************************************************/
3274 jb_err client_x_forwarded(struct client_state *csp, char **header)
3276 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3279 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3286 /*********************************************************************
3288 * Function : client_max_forwards
3290 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3291 * from the value of the Max-Forwards header field.
3294 * 1 : csp = Current client state (buffers, headers, etc...)
3295 * 2 : header = On input, pointer to header to modify.
3296 * On output, pointer to the modified header, or NULL
3297 * to remove the header. This function frees the
3298 * original string if necessary.
3300 * Returns : JB_ERR_OK on success, or
3301 * JB_ERR_MEMORY on out-of-memory error.
3303 *********************************************************************/
3304 static jb_err client_max_forwards(struct client_state *csp, char **header)
3308 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3309 (0 == strcmpic(csp->http->gpc, "options")))
3311 assert(*(*header+12) == ':');
3312 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3314 if (max_forwards > 0)
3316 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3317 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3318 csp->http->gpc, max_forwards);
3320 else if (max_forwards < 0)
3322 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3328 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3337 /*********************************************************************
3339 * Function : client_host
3341 * Description : If the request URI did not contain host and
3342 * port information, parse and evaluate the Host
3345 * Also, kill ill-formed HOST: headers as sent by
3346 * Apple's iTunes software when used with a proxy.
3349 * 1 : csp = Current client state (buffers, headers, etc...)
3350 * 2 : header = On input, pointer to header to modify.
3351 * On output, pointer to the modified header, or NULL
3352 * to remove the header. This function frees the
3353 * original string if necessary.
3355 * Returns : JB_ERR_OK on success, or
3356 * JB_ERR_MEMORY on out-of-memory error.
3358 *********************************************************************/
3359 static jb_err client_host(struct client_state *csp, char **header)
3364 * If the header field name is all upper-case, chances are that it's
3365 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3366 * not a problem -- they are regenerated later.
3368 if ((*header)[1] == 'O')
3370 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3375 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3376 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3379 if (NULL == (p = strdup((*header)+6)))
3381 return JB_ERR_MEMORY;
3384 if (NULL == (q = strdup(p)))
3387 return JB_ERR_MEMORY;
3390 freez(csp->http->hostport);
3391 csp->http->hostport = p;
3392 freez(csp->http->host);
3393 csp->http->host = q;
3394 q = strchr(csp->http->host, ':');
3397 /* Terminate hostname and evaluate port string */
3399 csp->http->port = atoi(q);
3403 csp->http->port = csp->http->ssl ? 443 : 80;
3406 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3407 csp->http->hostport, csp->http->host, csp->http->port);
3410 /* Signal client_host_adder() to return right away */
3411 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3417 /*********************************************************************
3419 * Function : client_if_modified_since
3421 * Description : Remove or modify the If-Modified-Since header.
3424 * 1 : csp = Current client state (buffers, headers, etc...)
3425 * 2 : header = On input, pointer to header to modify.
3426 * On output, pointer to the modified header, or NULL
3427 * to remove the header. This function frees the
3428 * original string if necessary.
3430 * Returns : JB_ERR_OK on success, or
3431 * JB_ERR_MEMORY on out-of-memory error.
3433 *********************************************************************/
3434 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3437 #ifdef HAVE_GMTIME_R
3440 struct tm *timeptr = NULL;
3444 long int hours, minutes, seconds;
3448 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3451 * The client got an error message because of a temporary problem,
3452 * the problem is gone and the client now tries to revalidate our
3453 * error message on the real server. The revalidation would always
3454 * end with the transmission of the whole document and there is
3455 * no need to expose the bogus If-Modified-Since header.
3457 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3460 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3462 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3464 if ((0 == strcmpic(newval, "block")))
3466 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3469 else /* add random value */
3471 const char *header_time = *header + sizeof("If-Modified-Since:");
3473 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3475 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3480 rtime = strtol(newval, &endptr, 0);
3483 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3484 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3491 rtime = pick_from_range(rtime);
3495 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3498 tm += rtime * (negative ? -1 : 1);
3499 #ifdef HAVE_GMTIME_R
3500 timeptr = gmtime_r(&tm, &gmt);
3501 #elif FEATURE_PTHREAD
3502 pthread_mutex_lock(&gmtime_mutex);
3503 timeptr = gmtime(&tm);
3504 pthread_mutex_unlock(&gmtime_mutex);
3506 timeptr = gmtime(&tm);
3508 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3511 *header = strdup("If-Modified-Since: ");
3512 string_append(header, newheader);
3514 if (*header == NULL)
3516 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3517 return JB_ERR_MEMORY;
3520 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3522 hours = rtime / 3600;
3523 minutes = rtime / 60 % 60;
3524 seconds = rtime % 60;
3526 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3527 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3528 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3538 /*********************************************************************
3540 * Function : client_if_none_match
3542 * Description : Remove the If-None-Match header.
3545 * 1 : csp = Current client state (buffers, headers, etc...)
3546 * 2 : header = On input, pointer to header to modify.
3547 * On output, pointer to the modified header, or NULL
3548 * to remove the header. This function frees the
3549 * original string if necessary.
3551 * Returns : JB_ERR_OK on success, or
3552 * JB_ERR_MEMORY on out-of-memory error.
3554 *********************************************************************/
3555 static jb_err client_if_none_match(struct client_state *csp, char **header)
3557 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3559 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3567 /*********************************************************************
3569 * Function : client_x_filter
3571 * Description : Disables filtering if the client set "X-Filter: No".
3572 * Called from `sed'.
3575 * 1 : csp = Current client state (buffers, headers, etc...)
3576 * 2 : header = On input, pointer to header to modify.
3577 * On output, pointer to the modified header, or NULL
3578 * to remove the header. This function frees the
3579 * original string if necessary.
3581 * Returns : JB_ERR_OK on success
3583 *********************************************************************/
3584 jb_err client_x_filter(struct client_state *csp, char **header)
3586 if ( 0 == strcmpic(*header, "X-Filter: No"))
3588 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3590 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3594 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3596 log_error(LOG_LEVEL_HEADER,
3597 "force-text-mode overruled the client's request to fetch without filtering!");
3601 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3602 csp->flags |= CSP_FLAG_NO_FILTERING;
3603 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3605 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3613 /*********************************************************************
3615 * Function : client_range
3617 * Description : Removes Range, Request-Range and If-Range headers if
3618 * content filtering is enabled. If the client's version
3619 * of the document has been altered by Privoxy, the server
3620 * could interpret the range differently than the client
3621 * intended in which case the user could end up with
3622 * corrupted content.
3625 * 1 : csp = Current client state (buffers, headers, etc...)
3626 * 2 : header = On input, pointer to header to modify.
3627 * On output, pointer to the modified header, or NULL
3628 * to remove the header. This function frees the
3629 * original string if necessary.
3631 * Returns : JB_ERR_OK
3633 *********************************************************************/
3634 static jb_err client_range(struct client_state *csp, char **header)
3636 if (content_filters_enabled(csp->action))
3638 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3639 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3646 /* the following functions add headers directly to the header list */
3648 /*********************************************************************
3650 * Function : client_host_adder
3652 * Description : Adds the Host: header field if it is missing.
3653 * Called from `sed'.
3656 * 1 : csp = Current client state (buffers, headers, etc...)
3658 * Returns : JB_ERR_OK on success, or
3659 * JB_ERR_MEMORY on out-of-memory error.
3661 *********************************************************************/
3662 static jb_err client_host_adder(struct client_state *csp)
3667 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3669 /* Header already set by the client, nothing to do. */
3673 if ( !csp->http->hostport || !*(csp->http->hostport))
3675 /* XXX: When does this happen and why is it OK? */
3676 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3681 * remove 'user:pass@' from 'proto://user:pass@host'
3683 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3689 p = csp->http->hostport;
3692 /* XXX: Just add it, we already made sure that it will be unique */
3693 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3694 err = enlist_unique_header(csp->headers, "Host", p);
3701 /*********************************************************************
3703 * Function : client_accept_encoding_adder
3705 * Description : Add an Accept-Encoding header to the client's request
3706 * that disables compression if the action applies, and
3707 * the header is not already there. Called from `sed'.
3708 * Note: For HTTP/1.0, the absence of the header is enough.
3711 * 1 : csp = Current client state (buffers, headers, etc...)
3713 * Returns : JB_ERR_OK on success, or
3714 * JB_ERR_MEMORY on out-of-memory error.
3716 *********************************************************************/
3717 static jb_err client_accept_encoding_adder(struct client_state *csp)
3719 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3720 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3722 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3730 /*********************************************************************
3732 * Function : client_xtra_adder
3734 * Description : Used in the add_client_headers list. Called from `sed'.
3737 * 1 : csp = Current client state (buffers, headers, etc...)
3739 * Returns : JB_ERR_OK on success, or
3740 * JB_ERR_MEMORY on out-of-memory error.
3742 *********************************************************************/
3743 static jb_err client_xtra_adder(struct client_state *csp)
3745 struct list_entry *lst;
3748 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3749 lst ; lst = lst->next)
3751 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3752 err = enlist(csp->headers, lst->str);
3764 /*********************************************************************
3766 * Function : connection_close_adder
3768 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3769 * support. Adds a "Connection: close" header to csp->headers
3770 * unless the header was already present. Called from `sed'.
3772 * FIXME: This whole function shouldn't be neccessary!
3775 * 1 : csp = Current client state (buffers, headers, etc...)
3777 * Returns : JB_ERR_OK on success, or
3778 * JB_ERR_MEMORY on out-of-memory error.
3780 *********************************************************************/
3781 static jb_err connection_close_adder(struct client_state *csp)
3783 const unsigned int flags = csp->flags;
3786 * Return right away if
3788 * - we're parsing server headers and the server header
3789 * "Connection: close" is already set, or if
3791 * - we're parsing client headers and the client header
3792 * "Connection: close" is already set.
3794 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3795 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3796 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3797 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3802 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3804 return enlist(csp->headers, "Connection: close");
3808 /*********************************************************************
3810 * Function : server_http
3812 * Description : - Save the HTTP Status into csp->http->status
3813 * - Set CT_TABOO to prevent filtering if the answer
3814 * is a partial range (HTTP status 206)
3815 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3819 * 1 : csp = Current client state (buffers, headers, etc...)
3820 * 2 : header = On input, pointer to header to modify.
3821 * On output, pointer to the modified header, or NULL
3822 * to remove the header. This function frees the
3823 * original string if necessary.
3825 * Returns : JB_ERR_OK on success, or
3826 * JB_ERR_MEMORY on out-of-memory error.
3828 *********************************************************************/
3829 static jb_err server_http(struct client_state *csp, char **header)
3831 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3832 if (csp->http->status == 206)
3834 csp->content_type = CT_TABOO;
3837 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3839 /* XXX: Should we do a real validity check here? */
3840 if (strlen(*header) > 8)
3843 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3848 * XXX: Should we block the request or
3849 * enlist a valid status code line here?
3851 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3852 "Downgrading to HTTP/1.0 impossible.");
3860 /*********************************************************************
3862 * Function : server_set_cookie
3864 * Description : Handle the server "cookie" header properly.
3865 * Log cookie to the jar file. Then "crunch",
3866 * accept or rewrite it to a session cookie.
3867 * Called from `sed'.
3869 * TODO: Allow the user to specify a new expiration
3870 * time to cause the cookie to expire even before the
3871 * browser is closed.
3874 * 1 : csp = Current client state (buffers, headers, etc...)
3875 * 2 : header = On input, pointer to header to modify.
3876 * On output, pointer to the modified header, or NULL
3877 * to remove the header. This function frees the
3878 * original string if necessary.
3880 * Returns : JB_ERR_OK on success, or
3881 * JB_ERR_MEMORY on out-of-memory error.
3883 *********************************************************************/
3884 static jb_err server_set_cookie(struct client_state *csp, char **header)
3891 #ifdef FEATURE_COOKIE_JAR
3892 if (csp->config->jar)
3895 * Write timestamp into outbuf.
3897 * Complex because not all OSs have tm_gmtoff or
3898 * the %z field in strftime()
3900 char tempbuf[ BUFFER_SIZE ];
3902 #ifdef HAVE_LOCALTIME_R
3903 tm_now = *localtime_r(&now, &tm_now);
3904 #elif FEATURE_PTHREAD
3905 pthread_mutex_lock(&localtime_mutex);
3906 tm_now = *localtime (&now);
3907 pthread_mutex_unlock(&localtime_mutex);
3909 tm_now = *localtime (&now);
3911 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3913 /* strlen("set-cookie: ") = 12 */
3914 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3916 #endif /* def FEATURE_COOKIE_JAR */
3918 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3920 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3923 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3925 /* Flag whether or not to log a message */
3928 /* A variable to store the tag we're working on */
3931 /* Skip "Set-Cookie:" (11 characters) in header */
3932 cur_tag = *header + 11;
3934 /* skip whitespace between "Set-Cookie:" and value */
3935 while (*cur_tag && ijb_isspace(*cur_tag))
3940 /* Loop through each tag in the cookie */
3944 char *next_tag = strchr(cur_tag, ';');
3945 if (next_tag != NULL)
3947 /* Skip the ';' character itself */
3950 /* skip whitespace ";" and start of tag */
3951 while (*next_tag && ijb_isspace(*next_tag))
3958 /* "Next tag" is the end of the string */
3959 next_tag = cur_tag + strlen(cur_tag);
3963 * Check the expiration date to see
3964 * if the cookie is still valid, if yes,
3965 * rewrite it to a session cookie.
3967 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3969 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3971 /* Did we detect the date properly? */
3972 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3975 * Nope, treat it as if it was still valid.
3977 * XXX: Should we remove the whole cookie instead?
3979 log_error(LOG_LEVEL_ERROR,
3980 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3981 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3987 * Yes. Check if the cookie is still valid.
3989 * If the cookie is already expired it's probably
3990 * a delete cookie and even if it isn't, the browser
3991 * will discard it anyway.
3995 * XXX: timegm() isn't available on some AmigaOS
3996 * versions and our replacement doesn't work.
3998 * Our options are to either:
4000 * - disable session-cookies-only completely if timegm
4003 * - to simply remove all expired tags, like it has
4004 * been done until Privoxy 3.0.6 and to live with
4005 * the consequence that it can cause login/logout
4006 * problems on servers that don't validate their
4007 * input properly, or
4009 * - to replace it with mktime in which
4010 * case there is a slight chance of valid cookies
4011 * passing as already expired.
4013 * This is the way it's currently done and it's not
4014 * as bad as it sounds. If the missing GMT offset is
4015 * enough to change the result of the expiration check
4016 * the cookie will be only valid for a few hours
4017 * anyway, which in many cases will be shorter
4018 * than a browser session.
4020 if (cookie_time - now < 0)
4022 log_error(LOG_LEVEL_HEADER,
4023 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4024 /* Just in case some clown sets more then one expiration date */
4030 * Still valid, delete expiration date by copying
4031 * the rest of the string over it.
4033 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
4034 * since the behaviour of strcpy is undefined for overlapping
4037 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
4039 /* That changed the header, need to issue a log message */
4043 * Note that the next tag has now been moved to *cur_tag,
4044 * so we do not need to update the cur_tag pointer.
4052 /* Move on to next cookie tag */
4059 assert(NULL != *header);
4060 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4069 #ifdef FEATURE_FORCE_LOAD
4070 /*********************************************************************
4072 * Function : strclean
4074 * Description : In-Situ-Eliminate all occurances of substring in
4078 * 1 : string = string to clean
4079 * 2 : substring = substring to eliminate
4081 * Returns : Number of eliminations
4083 *********************************************************************/
4084 int strclean(const char *string, const char *substring)
4090 len = strlen(substring);
4092 while((pos = strstr(string, substring)) != NULL)
4099 while (*p++ != '\0');
4106 #endif /* def FEATURE_FORCE_LOAD */
4109 /*********************************************************************
4111 * Function : parse_header_time
4113 * Description : Parses time formats used in HTTP header strings
4114 * to get the numerical respresentation.
4117 * 1 : header_time = HTTP header time as string.
4118 * 2 : result = storage for header_time in seconds
4120 * Returns : JB_ERR_OK if the time format was recognized, or
4121 * JB_ERR_PARSE otherwise.
4123 *********************************************************************/
4124 static jb_err parse_header_time(const char *header_time, time_t *result)
4129 * Zero out gmt to prevent time zone offsets.
4131 * While this is only necessary on some platforms
4132 * (mingw32 for example), I don't know how to
4133 * detect these automatically and doing it everywhere
4136 memset(&gmt, 0, sizeof(gmt));
4138 /* Tue, 02 Jun 2037 20:00:00 */
4139 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4140 /* Tue, 02-Jun-2037 20:00:00 */
4141 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4142 /* Tue, 02-Jun-37 20:00:00 */
4143 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4144 /* Tuesday, 02-Jun-2037 20:00:00 */
4145 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4146 /* Tuesday Jun 02 20:00:00 2037 */
4147 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4149 return JB_ERR_PARSE;
4152 *result = timegm(&gmt);
4159 /*********************************************************************
4161 * Function : get_destination_from_headers
4163 * Description : Parse the "Host:" header to get the request's destination.
4164 * Only needed if the client's request was forcefully
4165 * redirected into Privoxy.
4167 * Code mainly copied from client_host() which is currently
4168 * run too late for this purpose.
4171 * 1 : headers = List of headers (one of them hopefully being
4172 * the "Host:" header)
4173 * 2 : http = storage for the result (host, port and hostport).
4175 * Returns : JB_ERR_MEMORY in case of memory problems,
4176 * JB_ERR_PARSE if the host header couldn't be found,
4177 * JB_ERR_OK otherwise.
4179 *********************************************************************/
4180 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4186 host = get_header_value(headers, "Host:");
4190 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4191 return JB_ERR_PARSE;
4194 if (NULL == (p = strdup((host))))
4196 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4197 return JB_ERR_MEMORY;
4200 if (NULL == (q = strdup(p)))
4203 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4204 return JB_ERR_MEMORY;
4207 freez(http->hostport);
4211 q = strchr(http->host, ':');
4214 /* Terminate hostname and evaluate port string */
4216 http->port = atoi(q);
4220 http->port = http->ssl ? 443 : 80;
4223 /* Rebuild request URL */
4225 http->url = strdup(http->ssl ? "https://" : "http://");
4226 string_append(&http->url, http->hostport);
4227 string_append(&http->url, http->path);
4228 if (http->url == NULL)
4230 return JB_ERR_MEMORY;
4233 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4241 /*********************************************************************
4243 * Function : create_forged_referrer
4245 * Description : Helper for client_referrer to forge a referer as
4246 * 'http://[hostname:port/' to fool stupid
4247 * checks for in-site links
4250 * 1 : header = Pointer to header pointer
4251 * 2 : hostport = Host and optionally port as string
4253 * Returns : JB_ERR_OK in case of success, or
4254 * JB_ERR_MEMORY in case of memory problems.
4256 *********************************************************************/
4257 static jb_err create_forged_referrer(char **header, const char *hostport)
4259 assert(NULL == *header);
4261 *header = strdup("Referer: http://");
4262 string_append(header, hostport);
4263 string_append(header, "/");
4265 if (NULL == *header)
4267 return JB_ERR_MEMORY;
4270 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4277 /*********************************************************************
4279 * Function : create_fake_referrer
4281 * Description : Helper for client_referrer to create a fake referrer
4282 * based on a string supplied by the user.
4285 * 1 : header = Pointer to header pointer
4286 * 2 : hosthost = Referrer to fake
4288 * Returns : JB_ERR_OK in case of success, or
4289 * JB_ERR_MEMORY in case of memory problems.
4291 *********************************************************************/
4292 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4294 assert(NULL == *header);
4296 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4298 log_error(LOG_LEVEL_HEADER,
4299 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4301 *header = strdup("Referer: ");
4302 string_append(header, fake_referrer);
4304 if (NULL == *header)
4306 return JB_ERR_MEMORY;
4309 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4316 /*********************************************************************
4318 * Function : handle_conditional_hide_referrer_parameter
4320 * Description : Helper for client_referrer to crunch or forge
4321 * the referrer header if the host has changed.
4324 * 1 : header = Pointer to header pointer
4325 * 2 : host = The target host (may include the port)
4326 * 3 : parameter_conditional_block = Boolean to signal
4327 * if we're in conditional-block mode. If not set,
4328 * we're in conditional-forge mode.
4330 * Returns : JB_ERR_OK in case of success, or
4331 * JB_ERR_MEMORY in case of memory problems.
4333 *********************************************************************/
4334 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4335 const char *host, const int parameter_conditional_block)
4337 char *referer = strdup(*header);
4338 const size_t hostlenght = strlen(host);
4340 if (NULL == referer)
4343 return JB_ERR_MEMORY;
4346 /* referer begins with 'Referer: http[s]://' */
4347 if (hostlenght < (strlen(referer)-17))
4350 * Shorten referer to make sure the referer is blocked
4351 * if www.example.org/www.example.com-shall-see-the-referer/
4352 * links to www.example.com/
4354 referer[hostlenght+17] = '\0';
4356 if (NULL == strstr(referer, host))
4358 /* Host has changed */
4359 if (parameter_conditional_block)
4361 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4368 return create_forged_referrer(header, host);