1 const char parsers_rcs[] = "$Id: parsers.c,v 1.129 2008/05/17 14:02:07 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.129 2008/05/17 14:02:07 fabiankeil
48 * Normalize linear header white space.
50 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
51 * If a header is split across multiple lines,
52 * merge them to a single line before parsing them.
54 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
55 * Don't provide get_header() with the whole client state
56 * structure when it only needs access to csp->iob.
58 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
59 * Change content_filters_enabled()'s parameter from
60 * csp->action to action so it can be also used in the
61 * CGI code. Don't bother checking if there are filters
62 * loaded, as that's somewhat besides the point.
64 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
65 * Provide get_http_time() with the buffer size so it doesn't
66 * have to blindly assume that the buffer is big enough.
68 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
69 * Don't pass the whole csp structure to flush_socket()
70 * when it only needs a file descriptor and a buffer.
72 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
73 * Remove send-wafer and send-vanilla-wafer actions.
75 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
76 * Remove inspect-jpegs action.
78 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
79 * Let client_range() also handle Request-Range headers
80 * which apparently are still supported by many servers.
82 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
83 * Improve the warning messages that get logged if the action files
84 * "enable" filters but no filters of that type have been loaded.
86 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
87 * In server_content_type():
88 * - Don't require leading white space when detecting image content types.
89 * - Change '... not replaced ...' message to sound less crazy if the text
90 * type actually is 'text/plain'.
91 * - Mark the 'text/plain == binary data' assumption for removal.
92 * - Remove a bunch of trailing white space.
94 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
95 * Minor server_content_disposition() changes:
96 * - Don't regenerate the header name all lower-case.
97 * - Some white space fixes.
98 * - Remove useless log message in case of ENOMEM.
100 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
101 * Garbage-collect the code to add a X-Forwarded-For
102 * header as it seems to be mostly used by accident.
104 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
105 * Fix a crash on mingw32 with some Last Modified times in the future.
107 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
108 * Remove a "can't happen" error block which, over
109 * time, mutated into a "guaranteed to happen" block.
111 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
112 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
113 * - Use shiny new content_filters_enabled() in client_range().
115 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
116 * I forgot about Poland.
118 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
119 * Remove Range and If-Range headers if content filtering is enabled.
121 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
122 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
123 * client_cookie_adder() to make sure send-vanilla-wafer can be
124 * controlled through tags (and thus regression-tested).
126 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
127 * - Remove "scanning headers for" log message again.
128 * - Some more whitespace fixes.
130 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
131 * Refactor client_referrer() and add conditional-forge parameter.
133 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
134 * A bunch of whitespace fixes, pointy hat to me.
136 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
137 * Fix possible memory corruption in server_http, make sure it's not
138 * executed for ordinary server headers and mark some problems for later.
140 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
141 * Let content-type-overwrite{} honour force-text-mode again.
143 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
144 * - Add prototpyes for the header parsers and make them static.
145 * - Comment out client_accept_encoding_adder() which isn't used right now.
147 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
148 * Move the ACTION_FORCE_TEXT_MODE check out of
149 * server_content_type(). Signal other functions
150 * whether or not a content type has been declared.
151 * Part of the fix for BR#1750917.
153 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
154 * Change sed() to return a jb_err in preparation for forward-override{}.
156 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
157 * Adjust "X-Filter: No" to disable dedicated header filters.
159 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
160 * Streamline client_cookie_adder().
162 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
163 * Make sure filters with dynamic jobs actually use them.
165 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
166 * - Introduce dynamic pcrs jobs that can resolve variables.
167 * - Remove unnecessary update_action_bits_for_all_tags() call.
169 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
170 * - Make tagging based on tags set by earlier taggers
171 * of the same kind possible.
172 * - Log whether or not new tags cause action bits updates
173 * (in which case a matching tag-pattern section exists).
174 * - Log if the user tries to set a tag that is already set.
176 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
177 * Introduce tags as alternative way to specify which
178 * actions apply to a request. At the moment tags can be
179 * created based on client and server headers.
181 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
182 * Log a warning if the content is compressed, filtering is
183 * enabled and Privoxy was compiled without zlib support.
186 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
187 * - Fix warnings when compiled with glibc.
188 * - Don't use crumble() for cookie crunching.
189 * - Move cookie time parsing into parse_header_time().
190 * - Let parse_header_time() return a jb_err code
191 * instead of a pointer that can only be used to
192 * check for NULL anyway.
194 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
195 * - Add better protection against malicious gzip headers.
196 * - Stop logging the first hundred bytes of decompressed content.
197 * It looks like it's working and there is always debug 16.
198 * - Log the content size after decompression in decompress_iob()
199 * instead of pcrs_filter_response().
201 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
202 * - Use dedicated header filter actions instead of abusing "filter".
203 * Replace "filter-client-headers" and "filter-client-headers"
204 * with "server-header-filter" and "client-header-filter".
205 * - Remove filter_client_header() and filter_client_header(),
206 * filter_header() now checks the shiny new
207 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
209 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
210 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
211 * - Handle "Cookie:" and "Connection:" headers a bit smarter
212 * (don't crunch them just to recreate them later on).
213 * - Add another non-standard time format for the cookie
214 * expiration date detection.
215 * - Fix a valgrind warning.
217 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
218 * Improve cookie expiration date detection.
220 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
221 * Don't run server_content_length() the first time
222 * sed() parses server headers; only adjust the
223 * Content-Length header if the page was modified.
225 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
226 * Fix log messages regarding the cookie time format
227 * (cookie and request URL were mixed up).
229 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
230 * - Let decompress_iob()
231 * - not corrupt the content if decompression fails
232 * early. (the first byte(s) were lost).
233 * - use pointer arithmetics with defined outcome for
235 * - Use a different kludge to remember a failed decompression.
237 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
238 * Search for Max-Forwards headers case-insensitive,
239 * don't generate the "501 unsupported" message for invalid
240 * Max-Forwards values and don't increase negative ones.
242 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
243 * - Let server_set_cookie() check the expiration date
244 * of cookies and don't touch the ones that are already
245 * expired. Fixes problems with low quality web applications
246 * as described in BR 932612.
248 * - Adjust comment in client_max_forwards to reality;
249 * remove invalid Max-Forwards headers.
251 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
252 * Stop filter_header() from unintentionally removing
253 * empty header lines that were enlisted by the continue
256 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
257 * - Repeat the request URL before logging any headers.
258 * Makes reading the log easier in case of simultaneous requests.
259 * - If there are more than one Content-Type headers in one request,
260 * use the first one and remove the others.
261 * - Remove "newval" variable in server_content_type().
262 * It's only used once.
264 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
265 * Correct a cast, check inflateEnd() exit code
266 * to see if we have to, replace sprintf calls
269 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
270 * Integrate a modified version of Wil Mahan's
271 * zlib patch (PR #895531).
273 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
274 * Skip empty filter files in filter_header()
275 * but don't ignore the ones that come afterwards.
276 * Fixes BR 1619208, this time for real.
278 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
279 * Reverted parts of my last commit
280 * to keep error handling working.
282 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
283 * Fixed gcc43 conversion warnings.
285 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
286 * Bringing back the "useless" localtime() call
287 * I removed in revision 1.67. On some platforms
288 * it's necessary to prevent time zone offsets.
290 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
291 * Rebuild request URL in get_destination_from_headers()
292 * to make sure redirect{pcrs command} works as expected
293 * for intercepted requests.
295 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
296 * Added get_destination_from_headers().
298 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
299 * Make pthread mutex locking more generic. Instead of
300 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
301 * and use mutex locking unless there is an _r function
302 * available. Better safe than sorry.
304 * Fixes "./configure --disable-pthread" and should result
305 * in less threading-related problems on pthread-using platforms,
306 * but it still doesn't fix BR#1122404.
308 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
309 * The special header "X-Filter: No" now disables
310 * header filtering as well.
312 * Revision 1.73 2006/09/23 13:26:38 roro
313 * Replace TABs by spaces in source code.
315 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
316 * Don't print a log message every time filter_headers is
317 * entered or left. It only creates noise without any real
320 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
321 * Fix +hide-if-modified-since{-n}.
323 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
324 * Have hide-if-modified-since interpret the random
325 * range value as minutes instead of hours. Allows
326 * more fine-grained configuration.
328 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
329 * Always have parse_header_time return a pointer
330 * that actual makes sense, even though we currently
331 * only need it to detect problems.
333 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
334 * Added config option enable-remote-http-toggle
335 * to specify if Privoxy should recognize special
336 * headers (currently only X-Filter) to change its
337 * behaviour. Disabled by default.
339 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
340 * After filtering de-chunked instances, remove
341 * "Transfer-Encoding" header entirely instead of changing
342 * it to "Transfer-Encoding: identity", which is invalid.
343 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
345 * Don't use localtime in parse_header_time. An empty time struct
346 * is good enough, it gets overwritten by strptime anyway.
348 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
349 * Use gmtime_r if available, fallback to gmtime with mutex
350 * protection for MacOSX and use vanilla gmtime for the rest.
352 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
353 * Changed client_referrer to use the right type (size_t) for
354 * hostlenght and to shorten the temporary referrer string with
355 * '\0' instead of adding a useless line break.
357 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
358 * - Back to timegm() using GnuPG's replacement if necessary.
359 * Using mktime() and localtime() could add a on hour offset if
360 * the randomize factor was big enough to lead to a summer/wintertime
363 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
365 * - Moved randomization code into pick_from_range().
367 * - Changed parse_header_time definition.
368 * time_t isn't guaranteed to be signed and
369 * if it isn't, -1 isn't available as error code.
370 * Changed some variable types in client_if_modified_since()
371 * because of the same reason.
373 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
374 * OS/2 compilation compatibility fixups
376 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
377 * Changed include from strptime.c to strptime.h
379 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
380 * Split filter-headers{} into filter-client-headers{}
381 * and filter-server-headers{}.
382 * Added parse_header_time() to share some code.
383 * Replaced timegm() with mktime().
385 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
386 * Windows service integration
388 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
389 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
391 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
392 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
393 * with what was really the latest development (the v_3_0_branch branch)
395 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
396 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
398 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
399 * Add the ability to check jpeg images for invalid
400 * lengths of comment blocks. Defensive strategy
401 * against the exploit:
402 * Microsoft Security Bulletin MS04-028
403 * Buffer Overrun in JPEG Processing (GDI+) Could
404 * Allow Code Execution (833987)
405 * Enabled with +inspect-jpegs in actions files.
407 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
408 * Excluded text/plain objects from filtering. This fixes a
409 * couple of client-crashing, download corruption and
410 * Privoxy performance issues, whose root cause lies in
411 * web servers labelling content of unknown type as text/plain.
413 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
414 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
416 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
417 * Completing the previous change
419 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
420 * Added temporary workaround for bug in PHP < 4.2.3
422 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
423 * 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.
425 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
426 * Fix typo: supressed -> suppressed
428 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
429 * Improved cookie logging
431 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
432 * Added basic support for OPTIONS and TRACE HTTP methods:
433 * - New parser function client_max_forwards which decrements
434 * the Max-Forwards HTTP header field of OPTIONS and TRACE
435 * requests by one before forwarding
436 * - New parser function client_host which extracts the host
437 * and port information from the HTTP header field if the
438 * request URI was not absolute
439 * - Don't crumble and re-add the Host: header, but only generate
440 * and append if missing
442 * Revision 1.56 2002/05/12 15:34:22 jongfoster
443 * Fixing typo in a comment
445 * Revision 1.55 2002/05/08 16:01:07 oes
446 * Optimized add_to_iob:
447 * - Use realloc instead of malloc(), memcpy(), free()
448 * - Expand to powers of two if possible, to get
449 * O(log n) reallocs instead of O(n).
450 * - Moved check for buffer limit here from chat
451 * - Report failure via returncode
453 * Revision 1.54 2002/04/02 15:03:16 oes
454 * Tiny code cosmetics
456 * Revision 1.53 2002/03/26 22:29:55 swa
457 * we have a new homepage!
459 * Revision 1.52 2002/03/24 13:25:43 swa
460 * name change related issues
462 * Revision 1.51 2002/03/13 00:27:05 jongfoster
465 * Revision 1.50 2002/03/12 01:45:35 oes
466 * More verbose logging
468 * Revision 1.49 2002/03/09 20:03:52 jongfoster
469 * - Making various functions return int rather than size_t.
470 * (Undoing a recent change). Since size_t is unsigned on
471 * Windows, functions like read_socket that return -1 on
472 * error cannot return a size_t.
474 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
475 * crashes, and also frequently caused JB to jump to 100%
476 * CPU and stay there. (Because it thought it had just
477 * read ((unsigned)-1) == 4Gb of data...)
479 * - The signature of write_socket has changed, it now simply
480 * returns success=0/failure=nonzero.
482 * - Trying to get rid of a few warnings --with-debug on
483 * Windows, I've introduced a new type "jb_socket". This is
484 * used for the socket file descriptors. On Windows, this
485 * is SOCKET (a typedef for unsigned). Everywhere else, it's
486 * an int. The error value can't be -1 any more, so it's
487 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
488 * Windows it maps to the #define INVALID_SOCKET.)
490 * - The signature of bind_port has changed.
492 * Revision 1.48 2002/03/07 03:46:53 oes
493 * Fixed compiler warnings etc
495 * Revision 1.47 2002/02/20 23:15:13 jongfoster
496 * Parsing functions now handle out-of-memory gracefully by returning
499 * Revision 1.46 2002/01/17 21:03:47 jongfoster
500 * Moving all our URL and URL pattern parsing code to urlmatch.c.
502 * Revision 1.45 2002/01/09 14:33:03 oes
503 * Added support for localtime_r.
505 * Revision 1.44 2001/12/14 01:22:54 steudten
506 * Remove 'user:pass@' from 'proto://user:pass@host' for the
507 * new added header 'Host: ..'. (See Req ID 491818)
509 * Revision 1.43 2001/11/23 00:26:38 jongfoster
510 * Fixing two really stupid errors in my previous commit
512 * Revision 1.42 2001/11/22 21:59:30 jongfoster
513 * Adding code to handle +no-cookies-keep
515 * Revision 1.41 2001/11/05 23:43:05 steudten
516 * Add time+date to log files.
518 * Revision 1.40 2001/10/26 20:13:09 jongfoster
519 * ctype.h is needed in Windows, too.
521 * Revision 1.39 2001/10/26 17:40:04 oes
522 * Introduced get_header_value()
523 * Removed http->user_agent, csp->referrer and csp->accept_types
524 * Removed client_accept()
526 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
527 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
528 * threads to call select() simultaneously. So, it's time to do a real, live,
529 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
530 * (native). Both versions will work, but using __OS2__ offers multi-threading.
532 * Revision 1.37 2001/10/23 21:36:02 jongfoster
533 * Documenting sed()'s error behaviou (doc change only)
535 * Revision 1.36 2001/10/13 12:51:51 joergs
536 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
537 * force-load), instead crumble Host: and add it (again) in client_host_adder
538 * (in case we get a HTTP/1.0 request without Host: header and forward it to
539 * a HTTP/1.1 server/proxy).
541 * Revision 1.35 2001/10/09 22:39:21 jongfoster
542 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
545 * Revision 1.34 2001/10/07 18:50:55 oes
546 * Added server_content_encoding, renamed server_transfer_encoding
548 * Revision 1.33 2001/10/07 18:04:49 oes
549 * Changed server_http11 to server_http and its pattern to "HTTP".
550 * Additional functionality: it now saves the HTTP status into
551 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
553 * Revision 1.32 2001/10/07 15:43:28 oes
554 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
555 * client_te and client_accept_encoding_adder, triggered by the new
556 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
557 * changed to allow only identity and chunked, and the TE header is
558 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
560 * parse_http_request no longer does anything than parsing. The rewriting
561 * of http->cmd and version mangling are gone. It now also recognizes
562 * the put and delete methods and saves the url in http->url. Removed
565 * renamed content_type and content_length to have the server_ prefix
567 * server_content_type now only works if csp->content_type != CT_TABOO
569 * added server_transfer_encoding, which
570 * - Sets CT_TABOO to prohibit filtering if encoding compresses
571 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
572 * - Change from "chunked" to "identity" if body was chunked
573 * but has been de-chunked for filtering.
575 * added server_content_md5 which crunches any Content-MD5 headers
576 * if the body was modified.
578 * made server_http11 conditional on +downgrade action
580 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
582 * Revision 1.31 2001/10/05 14:25:02 oes
583 * Crumble Keep-Alive from Server
585 * Revision 1.30 2001/09/29 12:56:03 joergs
586 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
588 * Revision 1.29 2001/09/24 21:09:24 jongfoster
589 * Fixing 2 memory leaks that Guy spotted, where the paramater to
590 * enlist() was not being free()d.
592 * Revision 1.28 2001/09/22 16:32:28 jongfoster
593 * Removing unused #includes.
595 * Revision 1.27 2001/09/20 15:45:25 steudten
597 * add casting from size_t to int for printf()
598 * remove local variable shadow s2
600 * Revision 1.26 2001/09/16 17:05:14 jongfoster
601 * Removing unused #include showarg.h
603 * Revision 1.25 2001/09/16 13:21:27 jongfoster
604 * Changes to use new list functions.
606 * Revision 1.24 2001/09/13 23:05:50 jongfoster
607 * Changing the string paramater to the header parsers a "const".
609 * Revision 1.23 2001/09/12 18:08:19 steudten
611 * In parse_http_request() header rewriting miss the host value, so
612 * from http://www.mydomain.com the result was just " / " not
613 * http://www.mydomain.com/ in case we forward.
615 * Revision 1.22 2001/09/10 10:58:53 oes
616 * Silenced compiler warnings
618 * Revision 1.21 2001/07/31 14:46:00 oes
619 * - Persistant connections now suppressed
620 * - sed() no longer appends empty header to csp->headers
622 * Revision 1.20 2001/07/30 22:08:36 jongfoster
623 * Tidying up #defines:
624 * - All feature #defines are now of the form FEATURE_xxx
625 * - Permanently turned off WIN_GUI_EDIT
626 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
628 * Revision 1.19 2001/07/25 17:21:54 oes
629 * client_uagent now saves copy of User-Agent: header value
631 * Revision 1.18 2001/07/13 14:02:46 oes
632 * - Included fix to repair broken HTTP requests that
633 * don't contain a path, not even '/'.
634 * - Removed all #ifdef PCRS
635 * - content_type now always inspected and classified as
636 * text, gif or other.
637 * - formatting / comments
639 * Revision 1.17 2001/06/29 21:45:41 oes
640 * Indentation, CRLF->LF, Tab-> Space
642 * Revision 1.16 2001/06/29 13:32:42 oes
644 * - Adapted free_http_request
645 * - Removed logentry from cancelled commit
647 * Revision 1.15 2001/06/03 19:12:38 oes
648 * deleted const struct interceptors
650 * Revision 1.14 2001/06/01 18:49:17 jongfoster
651 * Replaced "list_share" with "list" - the tiny memory gain was not
652 * worth the extra complexity.
654 * Revision 1.13 2001/05/31 21:30:33 jongfoster
655 * Removed list code - it's now in list.[ch]
656 * Renamed "permission" to "action", and changed many features
657 * to use the actions file rather than the global config.
659 * Revision 1.12 2001/05/31 17:33:13 oes
663 * Revision 1.11 2001/05/29 20:11:19 joergs
664 * '/ * inside comment' warning removed.
666 * Revision 1.10 2001/05/29 09:50:24 jongfoster
667 * Unified blocklist/imagelist/permissionslist.
668 * File format is still under discussion, but the internal changes
671 * Also modified interceptor behaviour:
672 * - We now intercept all URLs beginning with one of the following
673 * prefixes (and *only* these prefixes):
675 * * http://ijbswa.sf.net/config/
676 * * http://ijbswa.sourceforge.net/config/
677 * - New interceptors "home page" - go to http://i.j.b/ to see it.
678 * - Internal changes so that intercepted and fast redirect pages
679 * are not replaced with an image.
680 * - Interceptors now have the option to send a binary page direct
681 * to the client. (i.e. ijb-send-banner uses this)
682 * - Implemented show-url-info interceptor. (Which is why I needed
683 * the above interceptors changes - a typical URL is
684 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
685 * The previous mechanism would not have intercepted that, and
686 * if it had been intercepted then it then it would have replaced
689 * Revision 1.9 2001/05/28 17:26:33 jongfoster
690 * Fixing segfault if last header was crunched.
691 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
692 * can use the cross-platform sprintf() instead.)
694 * Revision 1.8 2001/05/27 22:17:04 oes
696 * - re_process_buffer no longer writes the modified buffer
697 * to the client, which was very ugly. It now returns the
698 * buffer, which it is then written by chat.
700 * - content_length now adjusts the Content-Length: header
701 * for modified documents rather than crunch()ing it.
702 * (Length info in csp->content_length, which is 0 for
703 * unmodified documents)
705 * - For this to work, sed() is called twice when filtering.
707 * Revision 1.7 2001/05/27 13:19:06 oes
708 * Patched Joergs solution for the content-length in.
710 * Revision 1.6 2001/05/26 13:39:32 jongfoster
711 * Only crunches Content-Length header if applying RE filtering.
712 * Without this fix, Microsoft Windows Update wouldn't work.
714 * Revision 1.5 2001/05/26 00:28:36 jongfoster
715 * Automatic reloading of config file.
716 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
717 * Most of the global variables have been moved to a new
718 * struct configuration_spec, accessed through csp->config->globalname
719 * Most of the globals remaining are used by the Win32 GUI.
721 * Revision 1.4 2001/05/22 18:46:04 oes
723 * - Enabled filtering banners by size rather than URL
724 * by adding patterns that replace all standard banner
725 * sizes with the "Junkbuster" gif to the re_filterfile
727 * - Enabled filtering WebBugs by providing a pattern
728 * which kills all 1x1 images
730 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
731 * which is selected by the (nonstandard and therefore
732 * capital) letter 'U' in the option string.
733 * It causes the quantifiers to be ungreedy by default.
734 * Appending a ? turns back to greedy (!).
736 * - Added a new interceptor ijb-send-banner, which
737 * sends back the "Junkbuster" gif. Without imagelist or
738 * MSIE detection support, or if tinygif = 1, or the
739 * URL isn't recognized as an imageurl, a lame HTML
740 * explanation is sent instead.
742 * - Added new feature, which permits blocking remote
743 * script redirects and firing back a local redirect
745 * The feature is conditionally compiled, i.e. it
746 * can be disabled with --disable-fast-redirects,
747 * plus it must be activated by a "fast-redirects"
748 * line in the config file, has its own log level
749 * and of course wants to be displayed by show-proxy-args
750 * Note: Boy, all the #ifdefs in 1001 locations and
751 * all the fumbling with configure.in and acconfig.h
752 * were *way* more work than the feature itself :-(
754 * - Because a generic redirect template was needed for
755 * this, tinygif = 3 now uses the same.
757 * - Moved GIFs, and other static HTTP response templates
762 * - Removed some >400 CRs again (Jon, you really worked
765 * Revision 1.3 2001/05/20 01:21:20 jongfoster
766 * Version 2.9.4 checkin.
767 * - Merged popupfile and cookiefile, and added control over PCRS
768 * filtering, in new "permissionsfile".
769 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
770 * file error you now get a message box (in the Win32 GUI) rather
771 * than the program exiting with no explanation.
772 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
774 * - Removed tabs from "config"
775 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
776 * - Bumped up version number.
778 * Revision 1.2 2001/05/17 23:02:36 oes
779 * - Made referrer option accept 'L' as a substitute for '§'
781 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
782 * Initial import of version 2.9.3 source tree
785 *********************************************************************/
792 #include <sys/types.h>
802 * Convince GNU's libc to provide a strptime prototype.
805 #endif /*__GLIBC__ */
812 #if !defined(_WIN32) && !defined(__OS2__)
818 #ifdef FEATURE_PTHREAD
820 /* jcc.h is for mutex semapores only */
821 #endif /* def FEATURE_PTHREAD */
827 #include "jbsockets.h"
828 #include "miscutil.h"
833 #ifndef HAVE_STRPTIME
834 #include "strptime.h"
837 const char parsers_h_rcs[] = PARSERS_H_VERSION;
839 /* Fix a problem with Solaris. There should be no effect on other
841 * Solaris's isspace() is a macro which uses its argument directly
842 * as an array index. Therefore we need to make sure that high-bit
843 * characters generate +ve values, and ideally we also want to make
844 * the argument match the declared parameter type of "int".
846 * Why did they write a character function that can't take a simple
847 * "char" argument? Doh!
849 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
850 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
852 static char *get_header_line(struct iob *iob);
853 static jb_err scan_headers(struct client_state *csp);
854 static jb_err header_tagger(struct client_state *csp, char *header);
855 static jb_err parse_header_time(const char *header_time, time_t *result);
857 static jb_err crumble (struct client_state *csp, char **header);
858 static jb_err connection (struct client_state *csp, char **header);
859 static jb_err filter_header (struct client_state *csp, char **header);
860 static jb_err client_referrer (struct client_state *csp, char **header);
861 static jb_err client_uagent (struct client_state *csp, char **header);
862 static jb_err client_ua (struct client_state *csp, char **header);
863 static jb_err client_from (struct client_state *csp, char **header);
864 static jb_err client_send_cookie (struct client_state *csp, char **header);
865 static jb_err client_x_forwarded (struct client_state *csp, char **header);
866 static jb_err client_accept_encoding (struct client_state *csp, char **header);
867 static jb_err client_te (struct client_state *csp, char **header);
868 static jb_err client_max_forwards (struct client_state *csp, char **header);
869 static jb_err client_host (struct client_state *csp, char **header);
870 static jb_err client_if_modified_since (struct client_state *csp, char **header);
871 static jb_err client_accept_language (struct client_state *csp, char **header);
872 static jb_err client_if_none_match (struct client_state *csp, char **header);
873 static jb_err crunch_client_header (struct client_state *csp, char **header);
874 static jb_err client_x_filter (struct client_state *csp, char **header);
875 static jb_err client_range (struct client_state *csp, char **header);
876 static jb_err server_set_cookie (struct client_state *csp, char **header);
877 static jb_err server_content_type (struct client_state *csp, char **header);
878 static jb_err server_content_length (struct client_state *csp, char **header);
879 static jb_err server_content_md5 (struct client_state *csp, char **header);
880 static jb_err server_content_encoding (struct client_state *csp, char **header);
881 static jb_err server_transfer_coding (struct client_state *csp, char **header);
882 static jb_err server_http (struct client_state *csp, char **header);
883 static jb_err crunch_server_header (struct client_state *csp, char **header);
884 static jb_err server_last_modified (struct client_state *csp, char **header);
885 static jb_err server_content_disposition(struct client_state *csp, char **header);
887 static jb_err client_host_adder (struct client_state *csp);
888 static jb_err client_xtra_adder (struct client_state *csp);
889 static jb_err connection_close_adder (struct client_state *csp);
891 static jb_err create_forged_referrer(char **header, const char *hostport);
892 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
893 static jb_err handle_conditional_hide_referrer_parameter(char **header,
894 const char *host, const int parameter_conditional_block);
896 const struct parsers client_patterns[] = {
897 { "referer:", 8, client_referrer },
898 { "user-agent:", 11, client_uagent },
899 { "ua-", 3, client_ua },
900 { "from:", 5, client_from },
901 { "cookie:", 7, client_send_cookie },
902 { "x-forwarded-for:", 16, client_x_forwarded },
903 { "Accept-Encoding:", 16, client_accept_encoding },
904 { "TE:", 3, client_te },
905 { "Host:", 5, client_host },
906 { "if-modified-since:", 18, client_if_modified_since },
907 { "Keep-Alive:", 11, crumble },
908 { "connection:", 11, connection },
909 { "proxy-connection:", 17, crumble },
910 { "max-forwards:", 13, client_max_forwards },
911 { "Accept-Language:", 16, client_accept_language },
912 { "if-none-match:", 14, client_if_none_match },
913 { "Range:", 6, client_range },
914 { "Request-Range:", 14, client_range },
915 { "If-Range:", 9, client_range },
916 { "X-Filter:", 9, client_x_filter },
917 { "*", 0, crunch_client_header },
918 { "*", 0, filter_header },
922 const struct parsers server_patterns[] = {
923 { "HTTP/", 5, server_http },
924 { "set-cookie:", 11, server_set_cookie },
925 { "connection:", 11, connection },
926 { "Content-Type:", 13, server_content_type },
927 { "Content-MD5:", 12, server_content_md5 },
928 { "Content-Encoding:", 17, server_content_encoding },
929 { "Transfer-Encoding:", 18, server_transfer_coding },
930 { "Keep-Alive:", 11, crumble },
931 { "content-disposition:", 20, server_content_disposition },
932 { "Last-Modified:", 14, server_last_modified },
933 { "*", 0, crunch_server_header },
934 { "*", 0, filter_header },
938 const struct parsers server_patterns_light[] = {
939 { "Content-Length:", 15, server_content_length },
940 { "Transfer-Encoding:", 18, server_transfer_coding },
942 { "Content-Encoding:", 17, server_content_encoding },
943 #endif /* def FEATURE_ZLIB */
947 const add_header_func_ptr add_client_headers[] = {
950 /* Temporarily disabled: client_accept_encoding_adder, */
951 connection_close_adder,
955 const add_header_func_ptr add_server_headers[] = {
956 connection_close_adder,
960 /*********************************************************************
962 * Function : flush_socket
964 * Description : Write any pending "buffered" content.
967 * 1 : fd = file descriptor of the socket to read
968 * 2 : iob = The I/O buffer to flush, usually csp->iob.
970 * Returns : On success, the number of bytes written are returned (zero
971 * indicates nothing was written). On error, -1 is returned,
972 * and errno is set appropriately. If count is zero and the
973 * file descriptor refers to a regular file, 0 will be
974 * returned without causing any other effect. For a special
975 * file, the results are not portable.
977 *********************************************************************/
978 int flush_socket(jb_socket fd, struct iob *iob)
980 int len = iob->eod - iob->cur;
987 if (write_socket(fd, iob->cur, (size_t)len))
991 iob->eod = iob->cur = iob->buf;
997 /*********************************************************************
999 * Function : add_to_iob
1001 * Description : Add content to the buffered page, expanding the
1002 * buffer if necessary.
1005 * 1 : csp = Current client state (buffers, headers, etc...)
1006 * 2 : buf = holds the content to be added to the page
1007 * 3 : n = number of bytes to be added
1009 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1010 * or buffer limit reached.
1012 *********************************************************************/
1013 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1015 struct iob *iob = csp->iob;
1016 size_t used, offset, need, want;
1019 if (n <= 0) return JB_ERR_OK;
1021 used = (size_t)(iob->eod - iob->buf);
1022 offset = (size_t)(iob->cur - iob->buf);
1023 need = used + (size_t)n + 1;
1026 * If the buffer can't hold the new data, extend it first.
1027 * Use the next power of two if possible, else use the actual need.
1029 if (need > csp->config->buffer_limit)
1031 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1032 return JB_ERR_MEMORY;
1035 if (need > iob->size)
1037 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1039 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1043 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1049 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1050 return JB_ERR_MEMORY;
1053 /* Update the iob pointers */
1054 iob->cur = p + offset;
1055 iob->eod = p + used;
1059 /* copy the new data into the iob buffer */
1060 memcpy(iob->eod, buf, (size_t)n);
1062 /* point to the end of the data */
1065 /* null terminate == cheap insurance */
1074 /*********************************************************************
1076 * Function : decompress_iob
1078 * Description : Decompress buffered page, expanding the
1079 * buffer as necessary. csp->iob->cur
1080 * should point to the the beginning of the
1081 * compressed data block.
1084 * 1 : csp = Current client state (buffers, headers, etc...)
1086 * Returns : JB_ERR_OK on success,
1087 * JB_ERR_MEMORY if out-of-memory limit reached, and
1088 * JB_ERR_COMPRESS if error decompressing buffer.
1090 *********************************************************************/
1091 jb_err decompress_iob(struct client_state *csp)
1093 char *buf; /* new, uncompressed buffer */
1094 char *cur; /* Current iob position (to keep the original
1095 * iob->cur unmodified if we return early) */
1096 size_t bufsize; /* allocated size of the new buffer */
1097 size_t old_size; /* Content size before decompression */
1098 size_t skip_size; /* Number of bytes at the beginning of the iob
1099 that we should NOT decompress. */
1100 int status; /* return status of the inflate() call */
1101 z_stream zstr; /* used by calls to zlib */
1103 assert(csp->iob->cur - csp->iob->buf > 0);
1104 assert(csp->iob->eod - csp->iob->cur > 0);
1106 bufsize = csp->iob->size;
1107 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1108 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1110 cur = csp->iob->cur;
1115 * This is to protect the parsing of gzipped data,
1116 * but it should(?) be valid for deflated data also.
1118 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1119 return JB_ERR_COMPRESS;
1122 if (csp->content_type & CT_GZIP)
1125 * Our task is slightly complicated by the facts that data
1126 * compressed by gzip does not include a zlib header, and
1127 * that there is no easily accessible interface in zlib to
1128 * handle a gzip header. We strip off the gzip header by
1129 * hand, and later inform zlib not to expect a header.
1133 * Strip off the gzip header. Please see RFC 1952 for more
1134 * explanation of the appropriate fields.
1136 if ((*cur++ != (char)0x1f)
1137 || (*cur++ != (char)0x8b)
1138 || (*cur++ != Z_DEFLATED))
1140 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1141 return JB_ERR_COMPRESS;
1147 * XXX: These magic numbers should be replaced
1148 * with macros to give a better idea what they do.
1152 /* The gzip header has reserved bits set; bail out. */
1153 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1154 return JB_ERR_COMPRESS;
1158 /* Skip extra fields if necessary. */
1162 * Skip a given number of bytes, specified
1163 * as a 16-bit little-endian value.
1166 * XXX: This code used to be:
1168 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1170 * which I had to change into:
1172 * cur += *cur++ + (*cur++ << 8);
1174 * at which point gcc43 finally noticed that the value
1175 * of cur is undefined (it depends on which of the
1176 * summands is evaluated first).
1178 * I haven't come across a site where this
1179 * code is actually executed yet, but I hope
1183 skip_bytes = *cur++;
1184 skip_bytes = *cur++ << 8;
1186 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1189 * The number of bytes to skip should be positive
1190 * and we'd like to stay in the buffer.
1192 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1194 log_error(LOG_LEVEL_ERROR,
1195 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1197 return JB_ERR_COMPRESS;
1199 log_error(LOG_LEVEL_INFO,
1200 "Skipping %d bytes for gzip compression. Does this sound right?",
1205 /* Skip the filename if necessary. */
1208 /* A null-terminated string is supposed to follow. */
1209 while (*cur++ && (cur < csp->iob->eod));
1213 /* Skip the comment if necessary. */
1216 /* A null-terminated string is supposed to follow. */
1217 while (*cur++ && (cur < csp->iob->eod));
1220 /* Skip the CRC if necessary. */
1226 if (cur >= csp->iob->eod)
1229 * If the current position pointer reached or passed
1230 * the buffer end, we were obviously tricked to skip
1233 log_error(LOG_LEVEL_ERROR,
1234 "Malformed gzip header detected. Aborting decompression.");
1235 return JB_ERR_COMPRESS;
1239 else if (csp->content_type & CT_DEFLATE)
1242 * XXX: The debug level should be lowered
1243 * before the next stable release.
1245 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1247 * In theory (that is, according to RFC 1950), deflate-compressed
1248 * data should begin with a two-byte zlib header and have an
1249 * adler32 checksum at the end. It seems that in practice only
1250 * the raw compressed data is sent. Note that this means that
1251 * we are not RFC 1950-compliant here, but the advantage is that
1252 * this actually works. :)
1254 * We add a dummy null byte to tell zlib where the data ends,
1255 * and later inform it not to expect a header.
1257 * Fortunately, add_to_iob() has thoughtfully null-terminated
1258 * the buffer; we can just increment the end pointer to include
1265 log_error(LOG_LEVEL_ERROR,
1266 "Unable to determine compression format for decompression");
1267 return JB_ERR_COMPRESS;
1270 /* Set up the fields required by zlib. */
1271 zstr.next_in = (Bytef *)cur;
1272 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1273 zstr.zalloc = Z_NULL;
1274 zstr.zfree = Z_NULL;
1275 zstr.opaque = Z_NULL;
1278 * Passing -MAX_WBITS to inflateInit2 tells the library
1279 * that there is no zlib header.
1281 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1283 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1284 return JB_ERR_COMPRESS;
1288 * Next, we allocate new storage for the inflated data.
1289 * We don't modify the existing iob yet, so in case there
1290 * is error in decompression we can recover gracefully.
1292 buf = zalloc(bufsize);
1295 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1296 return JB_ERR_MEMORY;
1299 assert(bufsize >= skip_size);
1300 memcpy(buf, csp->iob->buf, skip_size);
1301 zstr.avail_out = bufsize - skip_size;
1302 zstr.next_out = (Bytef *)buf + skip_size;
1304 /* Try to decompress the whole stream in one shot. */
1305 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1307 /* We need to allocate more memory for the output buffer. */
1309 char *tmpbuf; /* used for realloc'ing the buffer */
1310 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1313 * If zlib wants more data then there's a problem, because
1314 * the complete compressed file should have been buffered.
1316 if (0 == zstr.avail_in)
1318 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1319 return JB_ERR_COMPRESS;
1323 * If we tried the limit and still didn't have enough
1324 * memory, just give up.
1326 if (bufsize == csp->config->buffer_limit)
1328 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1329 return JB_ERR_MEMORY;
1332 /* Try doubling the buffer size each time. */
1335 /* Don't exceed the buffer limit. */
1336 if (bufsize > csp->config->buffer_limit)
1338 bufsize = csp->config->buffer_limit;
1341 /* Try to allocate the new buffer. */
1342 tmpbuf = realloc(buf, bufsize);
1345 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1347 return JB_ERR_MEMORY;
1351 char *oldnext_out = (char *)zstr.next_out;
1354 * Update the fields for inflate() to use the new
1355 * buffer, which may be in a location different from
1358 zstr.avail_out += bufsize - oldbufsize;
1359 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1362 * Compare with an uglier method of calculating these values
1363 * that doesn't require the extra oldbufsize variable.
1365 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1366 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1367 assert(zstr.avail_out > 0);
1373 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1375 log_error(LOG_LEVEL_ERROR,
1376 "Inconsistent stream state after decompression: %s", zstr.msg);
1378 * XXX: Intentionally no return.
1380 * According to zlib.h, Z_STREAM_ERROR is returned
1381 * "if the stream state was inconsistent".
1383 * I assume in this case inflate()'s status
1384 * would also be something different than Z_STREAM_END
1385 * so this check should be redundant, but lets see.
1389 if (status != Z_STREAM_END)
1391 /* We failed to decompress the stream. */
1392 log_error(LOG_LEVEL_ERROR,
1393 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1394 return JB_ERR_COMPRESS;
1398 * Finally, we can actually update the iob, since the
1399 * decompression was successful. First, free the old
1402 freez(csp->iob->buf);
1404 /* Now, update the iob to use the new buffer. */
1405 csp->iob->buf = buf;
1406 csp->iob->cur = csp->iob->buf + skip_size;
1407 csp->iob->eod = (char *)zstr.next_out;
1408 csp->iob->size = bufsize;
1411 * Make sure the new uncompressed iob obeys some minimal
1412 * consistency conditions.
1414 if ((csp->iob->buf < csp->iob->cur)
1415 && (csp->iob->cur <= csp->iob->eod)
1416 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1418 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1421 log_error(LOG_LEVEL_RE_FILTER,
1422 "Decompression successful. Old size: %d, new size: %d.",
1423 old_size, new_size);
1427 /* zlib thinks this is OK, so lets do the same. */
1428 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1433 /* It seems that zlib did something weird. */
1434 log_error(LOG_LEVEL_ERROR,
1435 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1436 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1437 csp->iob->eod, csp->iob->buf + csp->iob->size);
1438 return JB_ERR_COMPRESS;
1444 #endif /* defined(FEATURE_ZLIB) */
1447 /*********************************************************************
1449 * Function : string_move
1451 * Description : memmove wrapper to move the last part of a string
1452 * towards the beginning, overwriting the part in
1453 * the middle. strlcpy() can't be used here as the
1457 * 1 : dst = Destination to overwrite
1458 * 2 : src = Source to move.
1462 *********************************************************************/
1463 static void string_move(char *dst, char *src)
1467 /* +1 to copy the terminating nul as well. */
1468 memmove(dst, src, strlen(src)+1);
1472 /*********************************************************************
1474 * Function : normalize_lws
1476 * Description : Reduces unquoted linear white space in headers
1477 * to a single space in accordance with RFC 2616 2.2.
1478 * This simplifies parsing and filtering later on.
1480 * XXX: Remove log messages before
1481 * the next stable release?
1484 * 1 : header = A header with linear white space to reduce.
1488 *********************************************************************/
1489 static void normalize_lws(char *header)
1495 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1499 while (ijb_isspace(*q))
1503 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1504 string_move(p+1, q);
1509 log_error(LOG_LEVEL_HEADER,
1510 "Converting tab to space in '%s'", header);
1515 char *end_of_token = strstr(p+1, "\"");
1517 if (NULL != end_of_token)
1519 /* Don't mess with quoted text. */
1524 log_error(LOG_LEVEL_HEADER,
1525 "Ignoring single quote in '%s'", header);
1531 p = strchr(header, ':');
1532 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1535 * There's still space before the colon.
1538 string_move(p-1, p);
1543 /*********************************************************************
1545 * Function : get_header
1547 * Description : This (odd) routine will parse the csp->iob
1548 * to get the next complete header.
1551 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1553 * Returns : Any one of the following:
1555 * 1) a pointer to a dynamically allocated string that contains a header line
1556 * 2) NULL indicating that the end of the header was reached
1557 * 3) "" indicating that the end of the iob was reached before finding
1558 * a complete header line.
1560 *********************************************************************/
1561 char *get_header(struct iob *iob)
1565 header = get_header_line(iob);
1567 if ((header == NULL) || (*header == '\0'))
1570 * No complete header read yet, tell the client.
1575 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1578 * Header spans multiple lines, append the next one.
1580 char *continued_header;
1582 continued_header = get_header_line(iob);
1583 if ((continued_header == NULL) || (*continued_header == '\0'))
1586 * No complete header read yet, return what we got.
1587 * XXX: Should "unread" header instead.
1589 log_error(LOG_LEVEL_INFO,
1590 "Failed to read a multi-line header properly: '%s'",
1595 if (JB_ERR_OK != string_join(&header, continued_header))
1597 log_error(LOG_LEVEL_FATAL,
1598 "Out of memory while appending multiple headers.");
1602 /* XXX: remove before next stable release. */
1603 log_error(LOG_LEVEL_HEADER,
1604 "Merged multiple header lines to: '%s'",
1609 normalize_lws(header);
1616 /*********************************************************************
1618 * Function : get_header_line
1620 * Description : This (odd) routine will parse the csp->iob
1621 * to get the next header line.
1624 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1626 * Returns : Any one of the following:
1628 * 1) a pointer to a dynamically allocated string that contains a header line
1629 * 2) NULL indicating that the end of the header was reached
1630 * 3) "" indicating that the end of the iob was reached before finding
1631 * a complete header line.
1633 *********************************************************************/
1634 static char *get_header_line(struct iob *iob)
1638 if ((iob->cur == NULL)
1639 || ((p = strchr(iob->cur, '\n')) == NULL))
1641 return(""); /* couldn't find a complete header */
1646 ret = strdup(iob->cur);
1649 /* FIXME No way to handle error properly */
1650 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1655 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1657 /* is this a blank line (i.e. the end of the header) ? */
1669 /*********************************************************************
1671 * Function : get_header_value
1673 * Description : Get the value of a given header from a chained list
1674 * of header lines or return NULL if no such header is
1675 * present in the list.
1678 * 1 : header_list = pointer to list
1679 * 2 : header_name = string with name of header to look for.
1680 * Trailing colon required, capitalization
1683 * Returns : NULL if not found, else value of header
1685 *********************************************************************/
1686 char *get_header_value(const struct list *header_list, const char *header_name)
1688 struct list_entry *cur_entry;
1692 assert(header_list);
1693 assert(header_name);
1694 length = strlen(header_name);
1696 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1700 if (!strncmpic(cur_entry->str, header_name, length))
1703 * Found: return pointer to start of value
1705 ret = (char *) (cur_entry->str + length);
1706 while (*ret && ijb_isspace(*ret)) ret++;
1720 /*********************************************************************
1722 * Function : scan_headers
1724 * Description : Scans headers, applies tags and updates action bits.
1727 * 1 : csp = Current client state (buffers, headers, etc...)
1729 * Returns : JB_ERR_OK
1731 *********************************************************************/
1732 static jb_err scan_headers(struct client_state *csp)
1734 struct list_entry *h; /* Header */
1735 jb_err err = JB_ERR_OK;
1737 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1739 /* Header crunch()ed in previous run? -> ignore */
1740 if (h->str == NULL) continue;
1741 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1742 err = header_tagger(csp, h->str);
1749 /*********************************************************************
1753 * Description : add, delete or modify lines in the HTTP header streams.
1754 * On entry, it receives a linked list of headers space
1755 * that was allocated dynamically (both the list nodes
1756 * and the header contents).
1758 * As a side effect it frees the space used by the original
1761 * XXX: should be split to remove the first_run hack.
1764 * 1 : pats = list of patterns to match against headers
1765 * 2 : more_headers = list of functions to add more
1766 * headers (client or server)
1767 * 3 : csp = Current client state (buffers, headers, etc...)
1769 * Returns : JB_ERR_OK in case off success, or
1770 * JB_ERR_MEMORY on out-of-memory error.
1772 *********************************************************************/
1773 jb_err sed(const struct parsers pats[],
1774 const add_header_func_ptr more_headers[],
1775 struct client_state *csp)
1777 struct list_entry *p;
1778 const struct parsers *v;
1779 const add_header_func_ptr *f;
1780 jb_err err = JB_ERR_OK;
1784 * If filtering is enabled, sed is run twice,
1785 * but most of the work needs to be done only once.
1787 first_run = (more_headers != NULL ) ? 1 : 0;
1789 if (first_run) /* Parse and print */
1793 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1795 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1797 /* Header crunch()ed in previous run? -> ignore */
1798 if (p->str == NULL) continue;
1800 /* Does the current parser handle this header? */
1801 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1803 err = v->parser(csp, (char **)&(p->str));
1807 /* place any additional headers on the csp->headers list */
1808 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1813 else /* Parse only */
1816 * The second run is only needed if the body was modified
1817 * and the content-lenght has changed.
1819 if (strncmpic(csp->http->cmd, "HEAD", 4))
1821 /*XXX: Code duplication */
1822 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1824 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1826 /* Header crunch()ed in previous run? -> ignore */
1827 if (p->str == NULL) continue;
1829 /* Does the current parser handle this header? */
1830 if (strncmpic(p->str, v->str, v->len) == 0)
1832 err = v->parser(csp, (char **)&(p->str));
1844 /*********************************************************************
1846 * Function : header_tagger
1848 * Description : Executes all text substitutions from applying
1849 * tag actions and saves the result as tag.
1851 * XXX: Shares enough code with filter_header() and
1852 * pcrs_filter_response() to warrant some helper functions.
1855 * 1 : csp = Current client state (buffers, headers, etc...)
1856 * 2 : header = Header that is used as tagger input
1858 * Returns : JB_ERR_OK on success and always succeeds
1860 *********************************************************************/
1861 static jb_err header_tagger(struct client_state *csp, char *header)
1863 int wanted_filter_type;
1864 int multi_action_index;
1868 struct file_list *fl;
1869 struct re_filterfile_spec *b;
1870 struct list_entry *tag_name;
1872 int found_filters = 0;
1873 const size_t header_length = strlen(header);
1875 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1877 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1878 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1882 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1883 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1886 /* Check if there are any filters */
1887 for (i = 0; i < MAX_AF_FILES; i++)
1900 if (0 == found_filters)
1902 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1903 "tagging enabled, but no taggers available.");
1907 for (i = 0; i < MAX_AF_FILES; i++)
1910 if ((NULL == fl) || (NULL == fl->f))
1913 * Either there are no filter files
1914 * left, or this filter file just
1915 * contains no valid filters.
1917 * Continue to be sure we don't miss
1918 * valid filter files that are chained
1919 * after empty or invalid ones.
1924 /* For all filters, */
1925 for (b = fl->f; b; b = b->next)
1927 if (b->type != wanted_filter_type)
1929 /* skip the ones we don't care about, */
1932 /* leaving only taggers that could apply, of which we use the ones, */
1933 for (tag_name = csp->action->multi[multi_action_index]->first;
1934 NULL != tag_name; tag_name = tag_name->next)
1936 /* that do apply, and */
1937 if (strcmp(b->name, tag_name->str) == 0)
1939 char *modified_tag = NULL;
1941 size_t size = header_length;
1942 pcrs_job *joblist = b->joblist;
1944 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1946 if (NULL == joblist)
1948 log_error(LOG_LEVEL_RE_FILTER,
1949 "Tagger %s has empty joblist. Nothing to do.", b->name);
1953 /* execute their pcrs_joblist on the header. */
1954 for (job = joblist; NULL != job; job = job->next)
1956 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1960 /* Success, continue with the modified version. */
1969 /* Tagger doesn't match */
1972 /* Regex failure, log it but continue anyway. */
1973 log_error(LOG_LEVEL_ERROR,
1974 "Problems with tagger \'%s\' and header \'%s\': %s",
1975 b->name, *header, pcrs_strerror(hits));
1977 freez(modified_tag);
1981 if (b->dynamic) pcrs_free_joblist(joblist);
1983 /* If this tagger matched */
1989 * There is to technical limitation which makes
1990 * it impossible to use empty tags, but I assume
1991 * no one would do it intentionally.
1994 log_error(LOG_LEVEL_INFO,
1995 "Tagger \'%s\' created an empty tag. Ignored.",
2000 if (!list_contains_item(csp->tags, tag))
2002 if (JB_ERR_OK != enlist(csp->tags, tag))
2004 log_error(LOG_LEVEL_ERROR,
2005 "Insufficient memory to add tag \'%s\', "
2006 "based on tagger \'%s\' and header \'%s\'",
2007 tag, b->name, *header);
2011 char *action_message;
2013 * update the action bits right away, to make
2014 * tagging based on tags set by earlier taggers
2015 * of the same kind possible.
2017 if (update_action_bits_for_tag(csp, tag))
2019 action_message = "Action bits updated accordingly.";
2023 action_message = "No action bits update necessary.";
2026 log_error(LOG_LEVEL_HEADER,
2027 "Tagger \'%s\' added tag \'%s\'. %s",
2028 b->name, tag, action_message);
2033 /* XXX: Is this log-worthy? */
2034 log_error(LOG_LEVEL_HEADER,
2035 "Tagger \'%s\' didn't add tag \'%s\'. "
2036 "Tag already present", b->name, tag);
2039 } /* if the tagger matched */
2040 } /* if the tagger applies */
2041 } /* for every tagger that could apply */
2042 } /* for all filters */
2043 } /* for all filter files */
2048 /* here begins the family of parser functions that reformat header lines */
2050 /*********************************************************************
2052 * Function : filter_header
2054 * Description : Executes all text substitutions from all applying
2055 * +(server|client)-header-filter actions on the header.
2056 * Most of the code was copied from pcrs_filter_response,
2057 * including the rather short variable names
2060 * 1 : csp = Current client state (buffers, headers, etc...)
2061 * 2 : header = On input, pointer to header to modify.
2062 * On output, pointer to the modified header, or NULL
2063 * to remove the header. This function frees the
2064 * original string if necessary.
2066 * Returns : JB_ERR_OK on success and always succeeds
2068 *********************************************************************/
2069 static jb_err filter_header(struct client_state *csp, char **header)
2073 size_t size = strlen(*header);
2075 char *newheader = NULL;
2078 struct file_list *fl;
2079 struct re_filterfile_spec *b;
2080 struct list_entry *filtername;
2082 int i, found_filters = 0;
2083 int wanted_filter_type;
2084 int multi_action_index;
2086 if (csp->flags & CSP_FLAG_NO_FILTERING)
2091 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2093 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2094 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2098 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2099 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2103 * Need to check the set of re_filterfiles...
2105 for (i = 0; i < MAX_AF_FILES; i++)
2118 if (0 == found_filters)
2120 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2121 "header filtering enabled, but no matching filters available.");
2125 for (i = 0; i < MAX_AF_FILES; i++)
2128 if ((NULL == fl) || (NULL == fl->f))
2131 * Either there are no filter files
2132 * left, or this filter file just
2133 * contains no valid filters.
2135 * Continue to be sure we don't miss
2136 * valid filter files that are chained
2137 * after empty or invalid ones.
2142 * For all applying +filter actions, look if a filter by that
2143 * name exists and if yes, execute its pcrs_joblist on the
2146 for (b = fl->f; b; b = b->next)
2148 if (b->type != wanted_filter_type)
2150 /* Skip other filter types */
2154 for (filtername = csp->action->multi[multi_action_index]->first;
2155 filtername ; filtername = filtername->next)
2157 if (strcmp(b->name, filtername->str) == 0)
2159 int current_hits = 0;
2160 pcrs_job *joblist = b->joblist;
2162 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2164 if (NULL == joblist)
2166 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2170 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2171 *header, size, b->name);
2173 /* Apply all jobs from the joblist */
2174 for (job = joblist; NULL != job; job = job->next)
2176 matches = pcrs_execute(job, *header, size, &newheader, &size);
2179 current_hits += matches;
2180 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2182 *header = newheader;
2184 else if ( 0 == matches )
2186 /* Filter doesn't change header */
2192 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2193 *header, b->name, pcrs_strerror(matches));
2194 if (newheader != NULL)
2196 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2202 if (b->dynamic) pcrs_free_joblist(joblist);
2204 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2205 hits += current_hits;
2212 * Additionally checking for hits is important because if
2213 * the continue hack is triggered, server headers can
2214 * arrive empty to separate multiple heads from each other.
2216 if ((0 == size) && hits)
2218 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2226 /*********************************************************************
2228 * Function : connection
2230 * Description : Makes sure that the value of the Connection: header
2231 * is "close" and signals connection_close_adder
2235 * 1 : csp = Current client state (buffers, headers, etc...)
2236 * 2 : header = On input, pointer to header to modify.
2237 * On output, pointer to the modified header, or NULL
2238 * to remove the header. This function frees the
2239 * original string if necessary.
2241 * Returns : JB_ERR_OK on success, or
2242 * JB_ERR_MEMORY on out-of-memory error.
2244 *********************************************************************/
2245 static jb_err connection(struct client_state *csp, char **header)
2247 char *old_header = *header;
2249 /* Do we have a 'Connection: close' header? */
2250 if (strcmpic(*header, "Connection: close"))
2252 /* No, create one */
2253 *header = strdup("Connection: close");
2256 return JB_ERR_MEMORY;
2258 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2262 /* Signal connection_close_adder() to return early. */
2263 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2265 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2269 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2276 /*********************************************************************
2278 * Function : crumble
2280 * Description : This is called if a header matches a pattern to "crunch"
2283 * 1 : csp = Current client state (buffers, headers, etc...)
2284 * 2 : header = On input, pointer to header to modify.
2285 * On output, pointer to the modified header, or NULL
2286 * to remove the header. This function frees the
2287 * original string if necessary.
2289 * Returns : JB_ERR_OK on success, or
2290 * JB_ERR_MEMORY on out-of-memory error.
2292 *********************************************************************/
2293 static jb_err crumble(struct client_state *csp, char **header)
2295 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2301 /*********************************************************************
2303 * Function : crunch_server_header
2305 * Description : Crunch server header if it matches a string supplied by the
2306 * user. Called from `sed'.
2309 * 1 : csp = Current client state (buffers, headers, etc...)
2310 * 2 : header = On input, pointer to header to modify.
2311 * On output, pointer to the modified header, or NULL
2312 * to remove the header. This function frees the
2313 * original string if necessary.
2315 * Returns : JB_ERR_OK on success and always succeeds
2317 *********************************************************************/
2318 static jb_err crunch_server_header(struct client_state *csp, char **header)
2320 const char *crunch_pattern;
2322 /* Do we feel like crunching? */
2323 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2325 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2327 /* Is the current header the lucky one? */
2328 if (strstr(*header, crunch_pattern))
2330 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2339 /*********************************************************************
2341 * Function : server_content_type
2343 * Description : Set the content-type for filterable types (text/.*,
2344 * .*xml.*, javascript and image/gif) unless filtering has been
2345 * forbidden (CT_TABOO) while parsing earlier headers.
2346 * NOTE: Since text/plain is commonly used by web servers
2347 * for files whose correct type is unknown, we don't
2348 * set CT_TEXT for it.
2351 * 1 : csp = Current client state (buffers, headers, etc...)
2352 * 2 : header = On input, pointer to header to modify.
2353 * On output, pointer to the modified header, or NULL
2354 * to remove the header. This function frees the
2355 * original string if necessary.
2357 * Returns : JB_ERR_OK on success, or
2358 * JB_ERR_MEMORY on out-of-memory error.
2360 *********************************************************************/
2361 static jb_err server_content_type(struct client_state *csp, char **header)
2363 /* Remove header if it isn't the first Content-Type header */
2364 if ((csp->content_type & CT_DECLARED))
2367 * Another, slightly slower, way to see if
2368 * we already parsed another Content-Type header.
2370 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2372 log_error(LOG_LEVEL_ERROR,
2373 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2381 * Signal that the Content-Type has been set.
2383 csp->content_type |= CT_DECLARED;
2385 if (!(csp->content_type & CT_TABOO))
2388 * XXX: The assumption that text/plain is a sign of
2389 * binary data seems to be somewhat unreasonable nowadays
2390 * and should be dropped after 3.0.8 is out.
2392 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2393 || strstr(*header, "xml")
2394 || strstr(*header, "application/x-javascript"))
2396 csp->content_type |= CT_TEXT;
2398 else if (strstr(*header, "image/gif"))
2400 csp->content_type |= CT_GIF;
2405 * Are we messing with the content type?
2407 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2410 * Make sure the user doesn't accidently
2411 * change the content type of binary documents.
2413 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2416 *header = strdup("Content-Type: ");
2417 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2421 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2422 return JB_ERR_MEMORY;
2424 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2428 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2429 "It doesn't look like a content type that should be filtered. "
2430 "Enable force-text-mode if you know what you're doing.", *header);
2438 /*********************************************************************
2440 * Function : server_transfer_coding
2442 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2443 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2444 * - Remove header if body was chunked but has been
2445 * de-chunked for filtering.
2448 * 1 : csp = Current client state (buffers, headers, etc...)
2449 * 2 : header = On input, pointer to header to modify.
2450 * On output, pointer to the modified header, or NULL
2451 * to remove the header. This function frees the
2452 * original string if necessary.
2454 * Returns : JB_ERR_OK on success, or
2455 * JB_ERR_MEMORY on out-of-memory error.
2457 *********************************************************************/
2458 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2461 * Turn off pcrs and gif filtering if body compressed
2463 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2467 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2469 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2470 csp->http->cmd, *header);
2471 #endif /* def FEATURE_ZLIB */
2472 csp->content_type = CT_TABOO;
2476 * Raise flag if body chunked
2478 if (strstr(*header, "chunked"))
2480 csp->flags |= CSP_FLAG_CHUNKED;
2483 * If the body was modified, it has been de-chunked first
2484 * and the header must be removed.
2486 * FIXME: If there is more than one transfer encoding,
2487 * only the "chunked" part should be removed here.
2489 if (csp->flags & CSP_FLAG_MODIFIED)
2491 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2500 /*********************************************************************
2502 * Function : server_content_encoding
2504 * Description : This function is run twice for each request,
2505 * unless FEATURE_ZLIB and filtering are disabled.
2507 * The first run is used to check if the content
2508 * is compressed, if FEATURE_ZLIB is disabled
2509 * filtering is then disabled as well, if FEATURE_ZLIB
2510 * is enabled the content is marked for decompression.
2512 * The second run is used to remove the Content-Encoding
2513 * header if the decompression was successful.
2516 * 1 : csp = Current client state (buffers, headers, etc...)
2517 * 2 : header = On input, pointer to header to modify.
2518 * On output, pointer to the modified header, or NULL
2519 * to remove the header. This function frees the
2520 * original string if necessary.
2522 * Returns : JB_ERR_OK on success, or
2523 * JB_ERR_MEMORY on out-of-memory error.
2525 *********************************************************************/
2526 static jb_err server_content_encoding(struct client_state *csp, char **header)
2529 if ((csp->flags & CSP_FLAG_MODIFIED)
2530 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2533 * We successfully decompressed the content,
2534 * and have to clean the header now, so the
2535 * client no longer expects compressed data..
2537 * XXX: There is a difference between cleaning
2538 * and removing it completely.
2540 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2543 else if (strstr(*header, "gzip"))
2545 /* Mark for gzip decompression */
2546 csp->content_type |= CT_GZIP;
2548 else if (strstr(*header, "deflate"))
2550 /* Mark for zlib decompression */
2551 csp->content_type |= CT_DEFLATE;
2553 else if (strstr(*header, "compress"))
2556 * We can't decompress this; therefore we can't filter
2559 csp->content_type |= CT_TABOO;
2561 #else /* !defined(FEATURE_ZLIB) */
2562 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2565 * Body is compressed, turn off pcrs and gif filtering.
2567 csp->content_type |= CT_TABOO;
2570 * Log a warning if the user expects the content to be filtered.
2572 if ((csp->rlist != NULL) &&
2573 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2575 log_error(LOG_LEVEL_INFO,
2576 "Compressed content detected, content filtering disabled. "
2577 "Consider recompiling Privoxy with zlib support or "
2578 "enable the prevent-compression action.");
2581 #endif /* defined(FEATURE_ZLIB) */
2588 /*********************************************************************
2590 * Function : server_content_length
2592 * Description : Adjust Content-Length header if we modified
2596 * 1 : csp = Current client state (buffers, headers, etc...)
2597 * 2 : header = On input, pointer to header to modify.
2598 * On output, pointer to the modified header, or NULL
2599 * to remove the header. This function frees the
2600 * original string if necessary.
2602 * Returns : JB_ERR_OK on success, or
2603 * JB_ERR_MEMORY on out-of-memory error.
2605 *********************************************************************/
2606 static jb_err server_content_length(struct client_state *csp, char **header)
2608 const size_t max_header_length = 80;
2610 /* Regenerate header if the content was modified. */
2611 if (csp->flags & CSP_FLAG_MODIFIED)
2614 *header = (char *) zalloc(max_header_length);
2615 if (*header == NULL)
2617 return JB_ERR_MEMORY;
2620 snprintf(*header, max_header_length, "Content-Length: %d",
2621 (int)csp->content_length);
2622 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2623 (int)csp->content_length);
2630 /*********************************************************************
2632 * Function : server_content_md5
2634 * Description : Crumble any Content-MD5 headers if the document was
2635 * modified. FIXME: Should we re-compute instead?
2638 * 1 : csp = Current client state (buffers, headers, etc...)
2639 * 2 : header = On input, pointer to header to modify.
2640 * On output, pointer to the modified header, or NULL
2641 * to remove the header. This function frees the
2642 * original string if necessary.
2644 * Returns : JB_ERR_OK on success, or
2645 * JB_ERR_MEMORY on out-of-memory error.
2647 *********************************************************************/
2648 static jb_err server_content_md5(struct client_state *csp, char **header)
2650 if (csp->flags & CSP_FLAG_MODIFIED)
2652 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2660 /*********************************************************************
2662 * Function : server_content_disposition
2664 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2665 * Called from `sed'.
2668 * 1 : csp = Current client state (buffers, headers, etc...)
2669 * 2 : header = On input, pointer to header to modify.
2670 * On output, pointer to the modified header, or NULL
2671 * to remove the header. This function frees the
2672 * original string if necessary.
2674 * Returns : JB_ERR_OK on success, or
2675 * JB_ERR_MEMORY on out-of-memory error.
2677 *********************************************************************/
2678 static jb_err server_content_disposition(struct client_state *csp, char **header)
2683 * Are we messing with the Content-Disposition header?
2685 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2691 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2693 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2696 * Blocking content-disposition header
2698 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2705 * Replacing Content-Disposition header
2708 *header = strdup("Content-Disposition: ");
2709 string_append(header, newval);
2711 if (*header != NULL)
2713 log_error(LOG_LEVEL_HEADER,
2714 "Content-Disposition header crunched and replaced with: %s", *header);
2717 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2721 /*********************************************************************
2723 * Function : server_last_modified
2725 * Description : Changes Last-Modified header to the actual date
2726 * to help hide-if-modified-since.
2727 * Called from `sed'.
2730 * 1 : csp = Current client state (buffers, headers, etc...)
2731 * 2 : header = On input, pointer to header to modify.
2732 * On output, pointer to the modified header, or NULL
2733 * to remove the header. This function frees the
2734 * original string if necessary.
2736 * Returns : JB_ERR_OK on success, or
2737 * JB_ERR_MEMORY on out-of-memory error.
2739 *********************************************************************/
2740 static jb_err server_last_modified(struct client_state *csp, char **header)
2743 char buf[BUFFER_SIZE];
2746 #ifdef HAVE_GMTIME_R
2749 struct tm *timeptr = NULL;
2750 time_t now, last_modified;
2752 long int days, hours, minutes, seconds;
2755 * Are we messing with the Last-Modified header?
2757 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2763 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2765 if (0 == strcmpic(newval, "block") )
2768 * Blocking Last-Modified header. Useless but why not.
2770 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2774 else if (0 == strcmpic(newval, "reset-to-request-time"))
2777 * Setting Last-Modified Header to now.
2779 get_http_time(0, buf, sizeof(buf));
2781 *header = strdup("Last-Modified: ");
2782 string_append(header, buf);
2784 if (*header == NULL)
2786 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2790 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2793 else if (0 == strcmpic(newval, "randomize"))
2795 const char *header_time = *header + sizeof("Last-Modified:");
2797 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2799 #ifdef HAVE_GMTIME_R
2800 timeptr = gmtime_r(&now, &gmt);
2801 #elif FEATURE_PTHREAD
2802 pthread_mutex_lock(&gmtime_mutex);
2803 timeptr = gmtime(&now);
2804 pthread_mutex_unlock(&gmtime_mutex);
2806 timeptr = gmtime(&now);
2808 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2810 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2815 rtime = (long int)difftime(now, last_modified);
2824 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2826 rtime = pick_from_range(rtime);
2827 if (negative) rtime *= -1;
2828 last_modified += rtime;
2829 #ifdef HAVE_GMTIME_R
2830 timeptr = gmtime_r(&last_modified, &gmt);
2831 #elif FEATURE_PTHREAD
2832 pthread_mutex_lock(&gmtime_mutex);
2833 timeptr = gmtime(&last_modified);
2834 pthread_mutex_unlock(&gmtime_mutex);
2836 timeptr = gmtime(&last_modified);
2838 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2840 *header = strdup("Last-Modified: ");
2841 string_append(header, newheader);
2843 if (*header == NULL)
2845 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2846 return JB_ERR_MEMORY;
2849 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2851 days = rtime / (3600 * 24);
2852 hours = rtime / 3600 % 24;
2853 minutes = rtime / 60 % 60;
2854 seconds = rtime % 60;
2856 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2857 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2858 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2863 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2872 /*********************************************************************
2874 * Function : client_accept_encoding
2876 * Description : Rewrite the client's Accept-Encoding header so that
2877 * if doesn't allow compression, if the action applies.
2878 * Note: For HTTP/1.0 the absence of the header is enough.
2881 * 1 : csp = Current client state (buffers, headers, etc...)
2882 * 2 : header = On input, pointer to header to modify.
2883 * On output, pointer to the modified header, or NULL
2884 * to remove the header. This function frees the
2885 * original string if necessary.
2887 * Returns : JB_ERR_OK on success, or
2888 * JB_ERR_MEMORY on out-of-memory error.
2890 *********************************************************************/
2891 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2893 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2895 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2899 /* Temporarily disable the correct behaviour to
2900 * work around a PHP bug.
2902 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2904 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2905 * if (*header == NULL)
2907 * return JB_ERR_MEMORY;
2918 /*********************************************************************
2920 * Function : client_te
2922 * Description : Rewrite the client's TE header so that
2923 * if doesn't allow compression, if the action applies.
2926 * 1 : csp = Current client state (buffers, headers, etc...)
2927 * 2 : header = On input, pointer to header to modify.
2928 * On output, pointer to the modified header, or NULL
2929 * to remove the header. This function frees the
2930 * original string if necessary.
2932 * Returns : JB_ERR_OK on success, or
2933 * JB_ERR_MEMORY on out-of-memory error.
2935 *********************************************************************/
2936 static jb_err client_te(struct client_state *csp, char **header)
2938 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2941 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2948 /*********************************************************************
2950 * Function : client_referrer
2952 * Description : Handle the "referer" config setting properly.
2953 * Called from `sed'.
2956 * 1 : csp = Current client state (buffers, headers, etc...)
2957 * 2 : header = On input, pointer to header to modify.
2958 * On output, pointer to the modified header, or NULL
2959 * to remove the header. This function frees the
2960 * original string if necessary.
2962 * Returns : JB_ERR_OK on success, or
2963 * JB_ERR_MEMORY on out-of-memory error.
2965 *********************************************************************/
2966 static jb_err client_referrer(struct client_state *csp, char **header)
2968 const char *parameter;
2969 /* booleans for parameters we have to check multiple times */
2970 int parameter_conditional_block;
2971 int parameter_conditional_forge;
2973 #ifdef FEATURE_FORCE_LOAD
2975 * Since the referrer can include the prefix even
2976 * if the request itself is non-forced, we must
2977 * clean it unconditionally.
2979 * XXX: strclean is too broad
2981 strclean(*header, FORCE_PREFIX);
2982 #endif /* def FEATURE_FORCE_LOAD */
2984 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2986 /* Nothing left to do */
2990 parameter = csp->action->string[ACTION_STRING_REFERER];
2991 assert(parameter != NULL);
2992 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2993 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2995 if (!parameter_conditional_block && !parameter_conditional_forge)
2998 * As conditional-block and conditional-forge are the only
2999 * parameters that rely on the original referrer, we can
3000 * remove it now for all the others.
3005 if (0 == strcmpic(parameter, "block"))
3007 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3010 else if (parameter_conditional_block || parameter_conditional_forge)
3012 return handle_conditional_hide_referrer_parameter(header,
3013 csp->http->hostport, parameter_conditional_block);
3015 else if (0 == strcmpic(parameter, "forge"))
3017 return create_forged_referrer(header, csp->http->hostport);
3021 /* interpret parameter as user-supplied referer to fake */
3022 return create_fake_referrer(header, parameter);
3027 /*********************************************************************
3029 * Function : client_accept_language
3031 * Description : Handle the "Accept-Language" config setting properly.
3032 * Called from `sed'.
3035 * 1 : csp = Current client state (buffers, headers, etc...)
3036 * 2 : header = On input, pointer to header to modify.
3037 * On output, pointer to the modified header, or NULL
3038 * to remove the header. This function frees the
3039 * original string if necessary.
3041 * Returns : JB_ERR_OK on success, or
3042 * JB_ERR_MEMORY on out-of-memory error.
3044 *********************************************************************/
3045 static jb_err client_accept_language(struct client_state *csp, char **header)
3050 * Are we messing with the Accept-Language?
3052 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3054 /*I don't think so*/
3058 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3060 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3063 * Blocking Accept-Language header
3065 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3072 * Replacing Accept-Language header
3075 *header = strdup("Accept-Language: ");
3076 string_append(header, newval);
3078 if (*header == NULL)
3080 log_error(LOG_LEVEL_ERROR,
3081 "Insufficent memory. Accept-Language header crunched without replacement.");
3085 log_error(LOG_LEVEL_HEADER,
3086 "Accept-Language header crunched and replaced with: %s", *header);
3089 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3093 /*********************************************************************
3095 * Function : crunch_client_header
3097 * Description : Crunch client header if it matches a string supplied by the
3098 * user. Called from `sed'.
3101 * 1 : csp = Current client state (buffers, headers, etc...)
3102 * 2 : header = On input, pointer to header to modify.
3103 * On output, pointer to the modified header, or NULL
3104 * to remove the header. This function frees the
3105 * original string if necessary.
3107 * Returns : JB_ERR_OK on success and always succeeds
3109 *********************************************************************/
3110 static jb_err crunch_client_header(struct client_state *csp, char **header)
3112 const char *crunch_pattern;
3114 /* Do we feel like crunching? */
3115 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3117 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3119 /* Is the current header the lucky one? */
3120 if (strstr(*header, crunch_pattern))
3122 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3130 /*********************************************************************
3132 * Function : client_uagent
3134 * Description : Handle the "user-agent" config setting properly
3135 * and remember its original value to enable browser
3136 * bug workarounds. Called from `sed'.
3139 * 1 : csp = Current client state (buffers, headers, etc...)
3140 * 2 : header = On input, pointer to header to modify.
3141 * On output, pointer to the modified header, or NULL
3142 * to remove the header. This function frees the
3143 * original string if necessary.
3145 * Returns : JB_ERR_OK on success, or
3146 * JB_ERR_MEMORY on out-of-memory error.
3148 *********************************************************************/
3149 static jb_err client_uagent(struct client_state *csp, char **header)
3153 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3158 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3165 *header = strdup("User-Agent: ");
3166 string_append(header, newval);
3168 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3170 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3174 /*********************************************************************
3176 * Function : client_ua
3178 * Description : Handle "ua-" headers properly. Called from `sed'.
3181 * 1 : csp = Current client state (buffers, headers, etc...)
3182 * 2 : header = On input, pointer to header to modify.
3183 * On output, pointer to the modified header, or NULL
3184 * to remove the header. This function frees the
3185 * original string if necessary.
3187 * Returns : JB_ERR_OK on success, or
3188 * JB_ERR_MEMORY on out-of-memory error.
3190 *********************************************************************/
3191 static jb_err client_ua(struct client_state *csp, char **header)
3193 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3195 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3203 /*********************************************************************
3205 * Function : client_from
3207 * Description : Handle the "from" config setting properly.
3208 * Called from `sed'.
3211 * 1 : csp = Current client state (buffers, headers, etc...)
3212 * 2 : header = On input, pointer to header to modify.
3213 * On output, pointer to the modified header, or NULL
3214 * to remove the header. This function frees the
3215 * original string if necessary.
3217 * Returns : JB_ERR_OK on success, or
3218 * JB_ERR_MEMORY on out-of-memory error.
3220 *********************************************************************/
3221 static jb_err client_from(struct client_state *csp, char **header)
3225 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3232 newval = csp->action->string[ACTION_STRING_FROM];
3235 * Are we blocking the e-mail address?
3237 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3239 log_error(LOG_LEVEL_HEADER, "crunched From!");
3243 log_error(LOG_LEVEL_HEADER, " modified");
3245 *header = strdup("From: ");
3246 string_append(header, newval);
3248 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3252 /*********************************************************************
3254 * Function : client_send_cookie
3256 * Description : Crunches the "cookie" header if necessary.
3257 * Called from `sed'.
3259 * XXX: Stupid name, doesn't send squat.
3262 * 1 : csp = Current client state (buffers, headers, etc...)
3263 * 2 : header = On input, pointer to header to modify.
3264 * On output, pointer to the modified header, or NULL
3265 * to remove the header. This function frees the
3266 * original string if necessary.
3268 * Returns : JB_ERR_OK on success, or
3269 * JB_ERR_MEMORY on out-of-memory error.
3271 *********************************************************************/
3272 static jb_err client_send_cookie(struct client_state *csp, char **header)
3274 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3276 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3284 /*********************************************************************
3286 * Function : client_x_forwarded
3288 * Description : Handle the "x-forwarded-for" config setting properly,
3289 * also used in the add_client_headers list. Called from `sed'.
3292 * 1 : csp = Current client state (buffers, headers, etc...)
3293 * 2 : header = On input, pointer to header to modify.
3294 * On output, pointer to the modified header, or NULL
3295 * to remove the header. This function frees the
3296 * original string if necessary.
3298 * Returns : JB_ERR_OK on success, or
3299 * JB_ERR_MEMORY on out-of-memory error.
3301 *********************************************************************/
3302 jb_err client_x_forwarded(struct client_state *csp, char **header)
3304 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3307 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3314 /*********************************************************************
3316 * Function : client_max_forwards
3318 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3319 * from the value of the Max-Forwards header field.
3322 * 1 : csp = Current client state (buffers, headers, etc...)
3323 * 2 : header = On input, pointer to header to modify.
3324 * On output, pointer to the modified header, or NULL
3325 * to remove the header. This function frees the
3326 * original string if necessary.
3328 * Returns : JB_ERR_OK on success, or
3329 * JB_ERR_MEMORY on out-of-memory error.
3331 *********************************************************************/
3332 static jb_err client_max_forwards(struct client_state *csp, char **header)
3336 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3337 (0 == strcmpic(csp->http->gpc, "options")))
3339 assert(*(*header+12) == ':');
3340 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3342 if (max_forwards > 0)
3344 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3345 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3346 csp->http->gpc, max_forwards);
3348 else if (max_forwards < 0)
3350 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3356 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3365 /*********************************************************************
3367 * Function : client_host
3369 * Description : If the request URI did not contain host and
3370 * port information, parse and evaluate the Host
3373 * Also, kill ill-formed HOST: headers as sent by
3374 * Apple's iTunes software when used with a proxy.
3377 * 1 : csp = Current client state (buffers, headers, etc...)
3378 * 2 : header = On input, pointer to header to modify.
3379 * On output, pointer to the modified header, or NULL
3380 * to remove the header. This function frees the
3381 * original string if necessary.
3383 * Returns : JB_ERR_OK on success, or
3384 * JB_ERR_MEMORY on out-of-memory error.
3386 *********************************************************************/
3387 static jb_err client_host(struct client_state *csp, char **header)
3392 * If the header field name is all upper-case, chances are that it's
3393 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3394 * not a problem -- they are regenerated later.
3396 if ((*header)[1] == 'O')
3398 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3403 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3404 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3407 if (NULL == (p = strdup((*header)+6)))
3409 return JB_ERR_MEMORY;
3412 if (NULL == (q = strdup(p)))
3415 return JB_ERR_MEMORY;
3418 freez(csp->http->hostport);
3419 csp->http->hostport = p;
3420 freez(csp->http->host);
3421 csp->http->host = q;
3422 q = strchr(csp->http->host, ':');
3425 /* Terminate hostname and evaluate port string */
3427 csp->http->port = atoi(q);
3431 csp->http->port = csp->http->ssl ? 443 : 80;
3434 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3435 csp->http->hostport, csp->http->host, csp->http->port);
3438 /* Signal client_host_adder() to return right away */
3439 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3445 /*********************************************************************
3447 * Function : client_if_modified_since
3449 * Description : Remove or modify the If-Modified-Since header.
3452 * 1 : csp = Current client state (buffers, headers, etc...)
3453 * 2 : header = On input, pointer to header to modify.
3454 * On output, pointer to the modified header, or NULL
3455 * to remove the header. This function frees the
3456 * original string if necessary.
3458 * Returns : JB_ERR_OK on success, or
3459 * JB_ERR_MEMORY on out-of-memory error.
3461 *********************************************************************/
3462 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3465 #ifdef HAVE_GMTIME_R
3468 struct tm *timeptr = NULL;
3472 long int hours, minutes, seconds;
3476 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3479 * The client got an error message because of a temporary problem,
3480 * the problem is gone and the client now tries to revalidate our
3481 * error message on the real server. The revalidation would always
3482 * end with the transmission of the whole document and there is
3483 * no need to expose the bogus If-Modified-Since header.
3485 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3488 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3490 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3492 if ((0 == strcmpic(newval, "block")))
3494 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3497 else /* add random value */
3499 const char *header_time = *header + sizeof("If-Modified-Since:");
3501 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3503 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3508 rtime = strtol(newval, &endptr, 0);
3511 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3512 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3519 rtime = pick_from_range(rtime);
3523 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3526 tm += rtime * (negative ? -1 : 1);
3527 #ifdef HAVE_GMTIME_R
3528 timeptr = gmtime_r(&tm, &gmt);
3529 #elif FEATURE_PTHREAD
3530 pthread_mutex_lock(&gmtime_mutex);
3531 timeptr = gmtime(&tm);
3532 pthread_mutex_unlock(&gmtime_mutex);
3534 timeptr = gmtime(&tm);
3536 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3539 *header = strdup("If-Modified-Since: ");
3540 string_append(header, newheader);
3542 if (*header == NULL)
3544 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3545 return JB_ERR_MEMORY;
3548 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3550 hours = rtime / 3600;
3551 minutes = rtime / 60 % 60;
3552 seconds = rtime % 60;
3554 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3555 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3556 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3566 /*********************************************************************
3568 * Function : client_if_none_match
3570 * Description : Remove the If-None-Match header.
3573 * 1 : csp = Current client state (buffers, headers, etc...)
3574 * 2 : header = On input, pointer to header to modify.
3575 * On output, pointer to the modified header, or NULL
3576 * to remove the header. This function frees the
3577 * original string if necessary.
3579 * Returns : JB_ERR_OK on success, or
3580 * JB_ERR_MEMORY on out-of-memory error.
3582 *********************************************************************/
3583 static jb_err client_if_none_match(struct client_state *csp, char **header)
3585 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3587 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3595 /*********************************************************************
3597 * Function : client_x_filter
3599 * Description : Disables filtering if the client set "X-Filter: No".
3600 * Called from `sed'.
3603 * 1 : csp = Current client state (buffers, headers, etc...)
3604 * 2 : header = On input, pointer to header to modify.
3605 * On output, pointer to the modified header, or NULL
3606 * to remove the header. This function frees the
3607 * original string if necessary.
3609 * Returns : JB_ERR_OK on success
3611 *********************************************************************/
3612 jb_err client_x_filter(struct client_state *csp, char **header)
3614 if ( 0 == strcmpic(*header, "X-Filter: No"))
3616 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3618 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3622 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3624 log_error(LOG_LEVEL_HEADER,
3625 "force-text-mode overruled the client's request to fetch without filtering!");
3629 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3630 csp->flags |= CSP_FLAG_NO_FILTERING;
3631 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3633 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3641 /*********************************************************************
3643 * Function : client_range
3645 * Description : Removes Range, Request-Range and If-Range headers if
3646 * content filtering is enabled. If the client's version
3647 * of the document has been altered by Privoxy, the server
3648 * could interpret the range differently than the client
3649 * intended in which case the user could end up with
3650 * corrupted content.
3653 * 1 : csp = Current client state (buffers, headers, etc...)
3654 * 2 : header = On input, pointer to header to modify.
3655 * On output, pointer to the modified header, or NULL
3656 * to remove the header. This function frees the
3657 * original string if necessary.
3659 * Returns : JB_ERR_OK
3661 *********************************************************************/
3662 static jb_err client_range(struct client_state *csp, char **header)
3664 if (content_filters_enabled(csp->action))
3666 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3667 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3674 /* the following functions add headers directly to the header list */
3676 /*********************************************************************
3678 * Function : client_host_adder
3680 * Description : Adds the Host: header field if it is missing.
3681 * Called from `sed'.
3684 * 1 : csp = Current client state (buffers, headers, etc...)
3686 * Returns : JB_ERR_OK on success, or
3687 * JB_ERR_MEMORY on out-of-memory error.
3689 *********************************************************************/
3690 static jb_err client_host_adder(struct client_state *csp)
3695 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3697 /* Header already set by the client, nothing to do. */
3701 if ( !csp->http->hostport || !*(csp->http->hostport))
3703 /* XXX: When does this happen and why is it OK? */
3704 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3709 * remove 'user:pass@' from 'proto://user:pass@host'
3711 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3717 p = csp->http->hostport;
3720 /* XXX: Just add it, we already made sure that it will be unique */
3721 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3722 err = enlist_unique_header(csp->headers, "Host", p);
3729 /*********************************************************************
3731 * Function : client_accept_encoding_adder
3733 * Description : Add an Accept-Encoding header to the client's request
3734 * that disables compression if the action applies, and
3735 * the header is not already there. Called from `sed'.
3736 * Note: For HTTP/1.0, the absence of the header is enough.
3739 * 1 : csp = Current client state (buffers, headers, etc...)
3741 * Returns : JB_ERR_OK on success, or
3742 * JB_ERR_MEMORY on out-of-memory error.
3744 *********************************************************************/
3745 static jb_err client_accept_encoding_adder(struct client_state *csp)
3747 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3748 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3750 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3758 /*********************************************************************
3760 * Function : client_xtra_adder
3762 * Description : Used in the add_client_headers list. Called from `sed'.
3765 * 1 : csp = Current client state (buffers, headers, etc...)
3767 * Returns : JB_ERR_OK on success, or
3768 * JB_ERR_MEMORY on out-of-memory error.
3770 *********************************************************************/
3771 static jb_err client_xtra_adder(struct client_state *csp)
3773 struct list_entry *lst;
3776 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3777 lst ; lst = lst->next)
3779 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3780 err = enlist(csp->headers, lst->str);
3792 /*********************************************************************
3794 * Function : connection_close_adder
3796 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3797 * support. Adds a "Connection: close" header to csp->headers
3798 * unless the header was already present. Called from `sed'.
3800 * FIXME: This whole function shouldn't be neccessary!
3803 * 1 : csp = Current client state (buffers, headers, etc...)
3805 * Returns : JB_ERR_OK on success, or
3806 * JB_ERR_MEMORY on out-of-memory error.
3808 *********************************************************************/
3809 static jb_err connection_close_adder(struct client_state *csp)
3811 const unsigned int flags = csp->flags;
3814 * Return right away if
3816 * - we're parsing server headers and the server header
3817 * "Connection: close" is already set, or if
3819 * - we're parsing client headers and the client header
3820 * "Connection: close" is already set.
3822 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3823 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3824 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3825 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3830 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3832 return enlist(csp->headers, "Connection: close");
3836 /*********************************************************************
3838 * Function : server_http
3840 * Description : - Save the HTTP Status into csp->http->status
3841 * - Set CT_TABOO to prevent filtering if the answer
3842 * is a partial range (HTTP status 206)
3843 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3847 * 1 : csp = Current client state (buffers, headers, etc...)
3848 * 2 : header = On input, pointer to header to modify.
3849 * On output, pointer to the modified header, or NULL
3850 * to remove the header. This function frees the
3851 * original string if necessary.
3853 * Returns : JB_ERR_OK on success, or
3854 * JB_ERR_MEMORY on out-of-memory error.
3856 *********************************************************************/
3857 static jb_err server_http(struct client_state *csp, char **header)
3859 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3860 if (csp->http->status == 206)
3862 csp->content_type = CT_TABOO;
3865 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3867 /* XXX: Should we do a real validity check here? */
3868 if (strlen(*header) > 8)
3871 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3876 * XXX: Should we block the request or
3877 * enlist a valid status code line here?
3879 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3880 "Downgrading to HTTP/1.0 impossible.");
3888 /*********************************************************************
3890 * Function : server_set_cookie
3892 * Description : Handle the server "cookie" header properly.
3893 * Log cookie to the jar file. Then "crunch",
3894 * accept or rewrite it to a session cookie.
3895 * Called from `sed'.
3897 * TODO: Allow the user to specify a new expiration
3898 * time to cause the cookie to expire even before the
3899 * browser is closed.
3902 * 1 : csp = Current client state (buffers, headers, etc...)
3903 * 2 : header = On input, pointer to header to modify.
3904 * On output, pointer to the modified header, or NULL
3905 * to remove the header. This function frees the
3906 * original string if necessary.
3908 * Returns : JB_ERR_OK on success, or
3909 * JB_ERR_MEMORY on out-of-memory error.
3911 *********************************************************************/
3912 static jb_err server_set_cookie(struct client_state *csp, char **header)
3919 #ifdef FEATURE_COOKIE_JAR
3920 if (csp->config->jar)
3923 * Write timestamp into outbuf.
3925 * Complex because not all OSs have tm_gmtoff or
3926 * the %z field in strftime()
3928 char tempbuf[ BUFFER_SIZE ];
3930 #ifdef HAVE_LOCALTIME_R
3931 tm_now = *localtime_r(&now, &tm_now);
3932 #elif FEATURE_PTHREAD
3933 pthread_mutex_lock(&localtime_mutex);
3934 tm_now = *localtime (&now);
3935 pthread_mutex_unlock(&localtime_mutex);
3937 tm_now = *localtime (&now);
3939 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3941 /* strlen("set-cookie: ") = 12 */
3942 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3944 #endif /* def FEATURE_COOKIE_JAR */
3946 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3948 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3951 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3953 /* Flag whether or not to log a message */
3956 /* A variable to store the tag we're working on */
3959 /* Skip "Set-Cookie:" (11 characters) in header */
3960 cur_tag = *header + 11;
3962 /* skip whitespace between "Set-Cookie:" and value */
3963 while (*cur_tag && ijb_isspace(*cur_tag))
3968 /* Loop through each tag in the cookie */
3972 char *next_tag = strchr(cur_tag, ';');
3973 if (next_tag != NULL)
3975 /* Skip the ';' character itself */
3978 /* skip whitespace ";" and start of tag */
3979 while (*next_tag && ijb_isspace(*next_tag))
3986 /* "Next tag" is the end of the string */
3987 next_tag = cur_tag + strlen(cur_tag);
3991 * Check the expiration date to see
3992 * if the cookie is still valid, if yes,
3993 * rewrite it to a session cookie.
3995 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3997 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3999 /* Did we detect the date properly? */
4000 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4003 * Nope, treat it as if it was still valid.
4005 * XXX: Should we remove the whole cookie instead?
4007 log_error(LOG_LEVEL_ERROR,
4008 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4009 string_move(cur_tag, next_tag);
4015 * Yes. Check if the cookie is still valid.
4017 * If the cookie is already expired it's probably
4018 * a delete cookie and even if it isn't, the browser
4019 * will discard it anyway.
4023 * XXX: timegm() isn't available on some AmigaOS
4024 * versions and our replacement doesn't work.
4026 * Our options are to either:
4028 * - disable session-cookies-only completely if timegm
4031 * - to simply remove all expired tags, like it has
4032 * been done until Privoxy 3.0.6 and to live with
4033 * the consequence that it can cause login/logout
4034 * problems on servers that don't validate their
4035 * input properly, or
4037 * - to replace it with mktime in which
4038 * case there is a slight chance of valid cookies
4039 * passing as already expired.
4041 * This is the way it's currently done and it's not
4042 * as bad as it sounds. If the missing GMT offset is
4043 * enough to change the result of the expiration check
4044 * the cookie will be only valid for a few hours
4045 * anyway, which in many cases will be shorter
4046 * than a browser session.
4048 if (cookie_time - now < 0)
4050 log_error(LOG_LEVEL_HEADER,
4051 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4052 /* Just in case some clown sets more then one expiration date */
4058 * Still valid, delete expiration date by copying
4059 * the rest of the string over it.
4061 string_move(cur_tag, next_tag);
4063 /* That changed the header, need to issue a log message */
4067 * Note that the next tag has now been moved to *cur_tag,
4068 * so we do not need to update the cur_tag pointer.
4076 /* Move on to next cookie tag */
4083 assert(NULL != *header);
4084 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4093 #ifdef FEATURE_FORCE_LOAD
4094 /*********************************************************************
4096 * Function : strclean
4098 * Description : In-Situ-Eliminate all occurances of substring in
4102 * 1 : string = string to clean
4103 * 2 : substring = substring to eliminate
4105 * Returns : Number of eliminations
4107 *********************************************************************/
4108 int strclean(const char *string, const char *substring)
4114 len = strlen(substring);
4116 while((pos = strstr(string, substring)) != NULL)
4123 while (*p++ != '\0');
4130 #endif /* def FEATURE_FORCE_LOAD */
4133 /*********************************************************************
4135 * Function : parse_header_time
4137 * Description : Parses time formats used in HTTP header strings
4138 * to get the numerical respresentation.
4141 * 1 : header_time = HTTP header time as string.
4142 * 2 : result = storage for header_time in seconds
4144 * Returns : JB_ERR_OK if the time format was recognized, or
4145 * JB_ERR_PARSE otherwise.
4147 *********************************************************************/
4148 static jb_err parse_header_time(const char *header_time, time_t *result)
4153 * Zero out gmt to prevent time zone offsets.
4155 * While this is only necessary on some platforms
4156 * (mingw32 for example), I don't know how to
4157 * detect these automatically and doing it everywhere
4160 memset(&gmt, 0, sizeof(gmt));
4162 /* Tue, 02 Jun 2037 20:00:00 */
4163 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4164 /* Tue, 02-Jun-2037 20:00:00 */
4165 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4166 /* Tue, 02-Jun-37 20:00:00 */
4167 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4168 /* Tuesday, 02-Jun-2037 20:00:00 */
4169 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4170 /* Tuesday Jun 02 20:00:00 2037 */
4171 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4173 return JB_ERR_PARSE;
4176 *result = timegm(&gmt);
4183 /*********************************************************************
4185 * Function : get_destination_from_headers
4187 * Description : Parse the "Host:" header to get the request's destination.
4188 * Only needed if the client's request was forcefully
4189 * redirected into Privoxy.
4191 * Code mainly copied from client_host() which is currently
4192 * run too late for this purpose.
4195 * 1 : headers = List of headers (one of them hopefully being
4196 * the "Host:" header)
4197 * 2 : http = storage for the result (host, port and hostport).
4199 * Returns : JB_ERR_MEMORY in case of memory problems,
4200 * JB_ERR_PARSE if the host header couldn't be found,
4201 * JB_ERR_OK otherwise.
4203 *********************************************************************/
4204 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4210 host = get_header_value(headers, "Host:");
4214 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4215 return JB_ERR_PARSE;
4218 if (NULL == (p = strdup((host))))
4220 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4221 return JB_ERR_MEMORY;
4224 if (NULL == (q = strdup(p)))
4227 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4228 return JB_ERR_MEMORY;
4231 freez(http->hostport);
4235 q = strchr(http->host, ':');
4238 /* Terminate hostname and evaluate port string */
4240 http->port = atoi(q);
4244 http->port = http->ssl ? 443 : 80;
4247 /* Rebuild request URL */
4249 http->url = strdup(http->ssl ? "https://" : "http://");
4250 string_append(&http->url, http->hostport);
4251 string_append(&http->url, http->path);
4252 if (http->url == NULL)
4254 return JB_ERR_MEMORY;
4257 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4265 /*********************************************************************
4267 * Function : create_forged_referrer
4269 * Description : Helper for client_referrer to forge a referer as
4270 * 'http://[hostname:port/' to fool stupid
4271 * checks for in-site links
4274 * 1 : header = Pointer to header pointer
4275 * 2 : hostport = Host and optionally port as string
4277 * Returns : JB_ERR_OK in case of success, or
4278 * JB_ERR_MEMORY in case of memory problems.
4280 *********************************************************************/
4281 static jb_err create_forged_referrer(char **header, const char *hostport)
4283 assert(NULL == *header);
4285 *header = strdup("Referer: http://");
4286 string_append(header, hostport);
4287 string_append(header, "/");
4289 if (NULL == *header)
4291 return JB_ERR_MEMORY;
4294 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4301 /*********************************************************************
4303 * Function : create_fake_referrer
4305 * Description : Helper for client_referrer to create a fake referrer
4306 * based on a string supplied by the user.
4309 * 1 : header = Pointer to header pointer
4310 * 2 : hosthost = Referrer to fake
4312 * Returns : JB_ERR_OK in case of success, or
4313 * JB_ERR_MEMORY in case of memory problems.
4315 *********************************************************************/
4316 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4318 assert(NULL == *header);
4320 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4322 log_error(LOG_LEVEL_HEADER,
4323 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4325 *header = strdup("Referer: ");
4326 string_append(header, fake_referrer);
4328 if (NULL == *header)
4330 return JB_ERR_MEMORY;
4333 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4340 /*********************************************************************
4342 * Function : handle_conditional_hide_referrer_parameter
4344 * Description : Helper for client_referrer to crunch or forge
4345 * the referrer header if the host has changed.
4348 * 1 : header = Pointer to header pointer
4349 * 2 : host = The target host (may include the port)
4350 * 3 : parameter_conditional_block = Boolean to signal
4351 * if we're in conditional-block mode. If not set,
4352 * we're in conditional-forge mode.
4354 * Returns : JB_ERR_OK in case of success, or
4355 * JB_ERR_MEMORY in case of memory problems.
4357 *********************************************************************/
4358 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4359 const char *host, const int parameter_conditional_block)
4361 char *referer = strdup(*header);
4362 const size_t hostlenght = strlen(host);
4364 if (NULL == referer)
4367 return JB_ERR_MEMORY;
4370 /* referer begins with 'Referer: http[s]://' */
4371 if (hostlenght < (strlen(referer)-17))
4374 * Shorten referer to make sure the referer is blocked
4375 * if www.example.org/www.example.com-shall-see-the-referer/
4376 * links to www.example.com/
4378 referer[hostlenght+17] = '\0';
4380 if (NULL == strstr(referer, host))
4382 /* Host has changed */
4383 if (parameter_conditional_block)
4385 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4392 return create_forged_referrer(header, host);