1 const char parsers_rcs[] = "$Id: parsers.c,v 1.131 2008/05/20 20:13:30 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.131 2008/05/20 20:13:30 fabiankeil
48 * Factor update_server_headers() out of sed(), ditch the
49 * first_run hack and make server_patterns_light static.
51 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
52 * Wrap memmove() calls in string_move()
53 * to document the purpose in one place.
55 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
56 * Normalize linear header white space.
58 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
59 * If a header is split across multiple lines,
60 * merge them to a single line before parsing them.
62 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
63 * Don't provide get_header() with the whole client state
64 * structure when it only needs access to csp->iob.
66 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
67 * Change content_filters_enabled()'s parameter from
68 * csp->action to action so it can be also used in the
69 * CGI code. Don't bother checking if there are filters
70 * loaded, as that's somewhat besides the point.
72 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
73 * Provide get_http_time() with the buffer size so it doesn't
74 * have to blindly assume that the buffer is big enough.
76 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
77 * Don't pass the whole csp structure to flush_socket()
78 * when it only needs a file descriptor and a buffer.
80 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
81 * Remove send-wafer and send-vanilla-wafer actions.
83 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
84 * Remove inspect-jpegs action.
86 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
87 * Let client_range() also handle Request-Range headers
88 * which apparently are still supported by many servers.
90 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
91 * Improve the warning messages that get logged if the action files
92 * "enable" filters but no filters of that type have been loaded.
94 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
95 * In server_content_type():
96 * - Don't require leading white space when detecting image content types.
97 * - Change '... not replaced ...' message to sound less crazy if the text
98 * type actually is 'text/plain'.
99 * - Mark the 'text/plain == binary data' assumption for removal.
100 * - Remove a bunch of trailing white space.
102 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
103 * Minor server_content_disposition() changes:
104 * - Don't regenerate the header name all lower-case.
105 * - Some white space fixes.
106 * - Remove useless log message in case of ENOMEM.
108 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
109 * Garbage-collect the code to add a X-Forwarded-For
110 * header as it seems to be mostly used by accident.
112 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
113 * Fix a crash on mingw32 with some Last Modified times in the future.
115 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
116 * Remove a "can't happen" error block which, over
117 * time, mutated into a "guaranteed to happen" block.
119 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
120 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
121 * - Use shiny new content_filters_enabled() in client_range().
123 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
124 * I forgot about Poland.
126 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
127 * Remove Range and If-Range headers if content filtering is enabled.
129 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
130 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
131 * client_cookie_adder() to make sure send-vanilla-wafer can be
132 * controlled through tags (and thus regression-tested).
134 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
135 * - Remove "scanning headers for" log message again.
136 * - Some more whitespace fixes.
138 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
139 * Refactor client_referrer() and add conditional-forge parameter.
141 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
142 * A bunch of whitespace fixes, pointy hat to me.
144 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
145 * Fix possible memory corruption in server_http, make sure it's not
146 * executed for ordinary server headers and mark some problems for later.
148 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
149 * Let content-type-overwrite{} honour force-text-mode again.
151 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
152 * - Add prototpyes for the header parsers and make them static.
153 * - Comment out client_accept_encoding_adder() which isn't used right now.
155 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
156 * Move the ACTION_FORCE_TEXT_MODE check out of
157 * server_content_type(). Signal other functions
158 * whether or not a content type has been declared.
159 * Part of the fix for BR#1750917.
161 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
162 * Change sed() to return a jb_err in preparation for forward-override{}.
164 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
165 * Adjust "X-Filter: No" to disable dedicated header filters.
167 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
168 * Streamline client_cookie_adder().
170 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
171 * Make sure filters with dynamic jobs actually use them.
173 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
174 * - Introduce dynamic pcrs jobs that can resolve variables.
175 * - Remove unnecessary update_action_bits_for_all_tags() call.
177 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
178 * - Make tagging based on tags set by earlier taggers
179 * of the same kind possible.
180 * - Log whether or not new tags cause action bits updates
181 * (in which case a matching tag-pattern section exists).
182 * - Log if the user tries to set a tag that is already set.
184 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
185 * Introduce tags as alternative way to specify which
186 * actions apply to a request. At the moment tags can be
187 * created based on client and server headers.
189 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
190 * Log a warning if the content is compressed, filtering is
191 * enabled and Privoxy was compiled without zlib support.
194 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
195 * - Fix warnings when compiled with glibc.
196 * - Don't use crumble() for cookie crunching.
197 * - Move cookie time parsing into parse_header_time().
198 * - Let parse_header_time() return a jb_err code
199 * instead of a pointer that can only be used to
200 * check for NULL anyway.
202 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
203 * - Add better protection against malicious gzip headers.
204 * - Stop logging the first hundred bytes of decompressed content.
205 * It looks like it's working and there is always debug 16.
206 * - Log the content size after decompression in decompress_iob()
207 * instead of pcrs_filter_response().
209 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
210 * - Use dedicated header filter actions instead of abusing "filter".
211 * Replace "filter-client-headers" and "filter-client-headers"
212 * with "server-header-filter" and "client-header-filter".
213 * - Remove filter_client_header() and filter_client_header(),
214 * filter_header() now checks the shiny new
215 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
217 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
218 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
219 * - Handle "Cookie:" and "Connection:" headers a bit smarter
220 * (don't crunch them just to recreate them later on).
221 * - Add another non-standard time format for the cookie
222 * expiration date detection.
223 * - Fix a valgrind warning.
225 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
226 * Improve cookie expiration date detection.
228 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
229 * Don't run server_content_length() the first time
230 * sed() parses server headers; only adjust the
231 * Content-Length header if the page was modified.
233 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
234 * Fix log messages regarding the cookie time format
235 * (cookie and request URL were mixed up).
237 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
238 * - Let decompress_iob()
239 * - not corrupt the content if decompression fails
240 * early. (the first byte(s) were lost).
241 * - use pointer arithmetics with defined outcome for
243 * - Use a different kludge to remember a failed decompression.
245 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
246 * Search for Max-Forwards headers case-insensitive,
247 * don't generate the "501 unsupported" message for invalid
248 * Max-Forwards values and don't increase negative ones.
250 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
251 * - Let server_set_cookie() check the expiration date
252 * of cookies and don't touch the ones that are already
253 * expired. Fixes problems with low quality web applications
254 * as described in BR 932612.
256 * - Adjust comment in client_max_forwards to reality;
257 * remove invalid Max-Forwards headers.
259 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
260 * Stop filter_header() from unintentionally removing
261 * empty header lines that were enlisted by the continue
264 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
265 * - Repeat the request URL before logging any headers.
266 * Makes reading the log easier in case of simultaneous requests.
267 * - If there are more than one Content-Type headers in one request,
268 * use the first one and remove the others.
269 * - Remove "newval" variable in server_content_type().
270 * It's only used once.
272 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
273 * Correct a cast, check inflateEnd() exit code
274 * to see if we have to, replace sprintf calls
277 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
278 * Integrate a modified version of Wil Mahan's
279 * zlib patch (PR #895531).
281 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
282 * Skip empty filter files in filter_header()
283 * but don't ignore the ones that come afterwards.
284 * Fixes BR 1619208, this time for real.
286 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
287 * Reverted parts of my last commit
288 * to keep error handling working.
290 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
291 * Fixed gcc43 conversion warnings.
293 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
294 * Bringing back the "useless" localtime() call
295 * I removed in revision 1.67. On some platforms
296 * it's necessary to prevent time zone offsets.
298 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
299 * Rebuild request URL in get_destination_from_headers()
300 * to make sure redirect{pcrs command} works as expected
301 * for intercepted requests.
303 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
304 * Added get_destination_from_headers().
306 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
307 * Make pthread mutex locking more generic. Instead of
308 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
309 * and use mutex locking unless there is an _r function
310 * available. Better safe than sorry.
312 * Fixes "./configure --disable-pthread" and should result
313 * in less threading-related problems on pthread-using platforms,
314 * but it still doesn't fix BR#1122404.
316 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
317 * The special header "X-Filter: No" now disables
318 * header filtering as well.
320 * Revision 1.73 2006/09/23 13:26:38 roro
321 * Replace TABs by spaces in source code.
323 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
324 * Don't print a log message every time filter_headers is
325 * entered or left. It only creates noise without any real
328 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
329 * Fix +hide-if-modified-since{-n}.
331 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
332 * Have hide-if-modified-since interpret the random
333 * range value as minutes instead of hours. Allows
334 * more fine-grained configuration.
336 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
337 * Always have parse_header_time return a pointer
338 * that actual makes sense, even though we currently
339 * only need it to detect problems.
341 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
342 * Added config option enable-remote-http-toggle
343 * to specify if Privoxy should recognize special
344 * headers (currently only X-Filter) to change its
345 * behaviour. Disabled by default.
347 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
348 * After filtering de-chunked instances, remove
349 * "Transfer-Encoding" header entirely instead of changing
350 * it to "Transfer-Encoding: identity", which is invalid.
351 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
353 * Don't use localtime in parse_header_time. An empty time struct
354 * is good enough, it gets overwritten by strptime anyway.
356 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
357 * Use gmtime_r if available, fallback to gmtime with mutex
358 * protection for MacOSX and use vanilla gmtime for the rest.
360 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
361 * Changed client_referrer to use the right type (size_t) for
362 * hostlenght and to shorten the temporary referrer string with
363 * '\0' instead of adding a useless line break.
365 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
366 * - Back to timegm() using GnuPG's replacement if necessary.
367 * Using mktime() and localtime() could add a on hour offset if
368 * the randomize factor was big enough to lead to a summer/wintertime
371 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
373 * - Moved randomization code into pick_from_range().
375 * - Changed parse_header_time definition.
376 * time_t isn't guaranteed to be signed and
377 * if it isn't, -1 isn't available as error code.
378 * Changed some variable types in client_if_modified_since()
379 * because of the same reason.
381 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
382 * OS/2 compilation compatibility fixups
384 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
385 * Changed include from strptime.c to strptime.h
387 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
388 * Split filter-headers{} into filter-client-headers{}
389 * and filter-server-headers{}.
390 * Added parse_header_time() to share some code.
391 * Replaced timegm() with mktime().
393 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
394 * Windows service integration
396 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
397 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
399 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
400 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
401 * with what was really the latest development (the v_3_0_branch branch)
403 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
404 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
406 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
407 * Add the ability to check jpeg images for invalid
408 * lengths of comment blocks. Defensive strategy
409 * against the exploit:
410 * Microsoft Security Bulletin MS04-028
411 * Buffer Overrun in JPEG Processing (GDI+) Could
412 * Allow Code Execution (833987)
413 * Enabled with +inspect-jpegs in actions files.
415 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
416 * Excluded text/plain objects from filtering. This fixes a
417 * couple of client-crashing, download corruption and
418 * Privoxy performance issues, whose root cause lies in
419 * web servers labelling content of unknown type as text/plain.
421 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
422 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
424 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
425 * Completing the previous change
427 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
428 * Added temporary workaround for bug in PHP < 4.2.3
430 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
431 * 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.
433 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
434 * Fix typo: supressed -> suppressed
436 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
437 * Improved cookie logging
439 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
440 * Added basic support for OPTIONS and TRACE HTTP methods:
441 * - New parser function client_max_forwards which decrements
442 * the Max-Forwards HTTP header field of OPTIONS and TRACE
443 * requests by one before forwarding
444 * - New parser function client_host which extracts the host
445 * and port information from the HTTP header field if the
446 * request URI was not absolute
447 * - Don't crumble and re-add the Host: header, but only generate
448 * and append if missing
450 * Revision 1.56 2002/05/12 15:34:22 jongfoster
451 * Fixing typo in a comment
453 * Revision 1.55 2002/05/08 16:01:07 oes
454 * Optimized add_to_iob:
455 * - Use realloc instead of malloc(), memcpy(), free()
456 * - Expand to powers of two if possible, to get
457 * O(log n) reallocs instead of O(n).
458 * - Moved check for buffer limit here from chat
459 * - Report failure via returncode
461 * Revision 1.54 2002/04/02 15:03:16 oes
462 * Tiny code cosmetics
464 * Revision 1.53 2002/03/26 22:29:55 swa
465 * we have a new homepage!
467 * Revision 1.52 2002/03/24 13:25:43 swa
468 * name change related issues
470 * Revision 1.51 2002/03/13 00:27:05 jongfoster
473 * Revision 1.50 2002/03/12 01:45:35 oes
474 * More verbose logging
476 * Revision 1.49 2002/03/09 20:03:52 jongfoster
477 * - Making various functions return int rather than size_t.
478 * (Undoing a recent change). Since size_t is unsigned on
479 * Windows, functions like read_socket that return -1 on
480 * error cannot return a size_t.
482 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
483 * crashes, and also frequently caused JB to jump to 100%
484 * CPU and stay there. (Because it thought it had just
485 * read ((unsigned)-1) == 4Gb of data...)
487 * - The signature of write_socket has changed, it now simply
488 * returns success=0/failure=nonzero.
490 * - Trying to get rid of a few warnings --with-debug on
491 * Windows, I've introduced a new type "jb_socket". This is
492 * used for the socket file descriptors. On Windows, this
493 * is SOCKET (a typedef for unsigned). Everywhere else, it's
494 * an int. The error value can't be -1 any more, so it's
495 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
496 * Windows it maps to the #define INVALID_SOCKET.)
498 * - The signature of bind_port has changed.
500 * Revision 1.48 2002/03/07 03:46:53 oes
501 * Fixed compiler warnings etc
503 * Revision 1.47 2002/02/20 23:15:13 jongfoster
504 * Parsing functions now handle out-of-memory gracefully by returning
507 * Revision 1.46 2002/01/17 21:03:47 jongfoster
508 * Moving all our URL and URL pattern parsing code to urlmatch.c.
510 * Revision 1.45 2002/01/09 14:33:03 oes
511 * Added support for localtime_r.
513 * Revision 1.44 2001/12/14 01:22:54 steudten
514 * Remove 'user:pass@' from 'proto://user:pass@host' for the
515 * new added header 'Host: ..'. (See Req ID 491818)
517 * Revision 1.43 2001/11/23 00:26:38 jongfoster
518 * Fixing two really stupid errors in my previous commit
520 * Revision 1.42 2001/11/22 21:59:30 jongfoster
521 * Adding code to handle +no-cookies-keep
523 * Revision 1.41 2001/11/05 23:43:05 steudten
524 * Add time+date to log files.
526 * Revision 1.40 2001/10/26 20:13:09 jongfoster
527 * ctype.h is needed in Windows, too.
529 * Revision 1.39 2001/10/26 17:40:04 oes
530 * Introduced get_header_value()
531 * Removed http->user_agent, csp->referrer and csp->accept_types
532 * Removed client_accept()
534 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
535 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
536 * threads to call select() simultaneously. So, it's time to do a real, live,
537 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
538 * (native). Both versions will work, but using __OS2__ offers multi-threading.
540 * Revision 1.37 2001/10/23 21:36:02 jongfoster
541 * Documenting sed()'s error behaviou (doc change only)
543 * Revision 1.36 2001/10/13 12:51:51 joergs
544 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
545 * force-load), instead crumble Host: and add it (again) in client_host_adder
546 * (in case we get a HTTP/1.0 request without Host: header and forward it to
547 * a HTTP/1.1 server/proxy).
549 * Revision 1.35 2001/10/09 22:39:21 jongfoster
550 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
553 * Revision 1.34 2001/10/07 18:50:55 oes
554 * Added server_content_encoding, renamed server_transfer_encoding
556 * Revision 1.33 2001/10/07 18:04:49 oes
557 * Changed server_http11 to server_http and its pattern to "HTTP".
558 * Additional functionality: it now saves the HTTP status into
559 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
561 * Revision 1.32 2001/10/07 15:43:28 oes
562 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
563 * client_te and client_accept_encoding_adder, triggered by the new
564 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
565 * changed to allow only identity and chunked, and the TE header is
566 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
568 * parse_http_request no longer does anything than parsing. The rewriting
569 * of http->cmd and version mangling are gone. It now also recognizes
570 * the put and delete methods and saves the url in http->url. Removed
573 * renamed content_type and content_length to have the server_ prefix
575 * server_content_type now only works if csp->content_type != CT_TABOO
577 * added server_transfer_encoding, which
578 * - Sets CT_TABOO to prohibit filtering if encoding compresses
579 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
580 * - Change from "chunked" to "identity" if body was chunked
581 * but has been de-chunked for filtering.
583 * added server_content_md5 which crunches any Content-MD5 headers
584 * if the body was modified.
586 * made server_http11 conditional on +downgrade action
588 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
590 * Revision 1.31 2001/10/05 14:25:02 oes
591 * Crumble Keep-Alive from Server
593 * Revision 1.30 2001/09/29 12:56:03 joergs
594 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
596 * Revision 1.29 2001/09/24 21:09:24 jongfoster
597 * Fixing 2 memory leaks that Guy spotted, where the paramater to
598 * enlist() was not being free()d.
600 * Revision 1.28 2001/09/22 16:32:28 jongfoster
601 * Removing unused #includes.
603 * Revision 1.27 2001/09/20 15:45:25 steudten
605 * add casting from size_t to int for printf()
606 * remove local variable shadow s2
608 * Revision 1.26 2001/09/16 17:05:14 jongfoster
609 * Removing unused #include showarg.h
611 * Revision 1.25 2001/09/16 13:21:27 jongfoster
612 * Changes to use new list functions.
614 * Revision 1.24 2001/09/13 23:05:50 jongfoster
615 * Changing the string paramater to the header parsers a "const".
617 * Revision 1.23 2001/09/12 18:08:19 steudten
619 * In parse_http_request() header rewriting miss the host value, so
620 * from http://www.mydomain.com the result was just " / " not
621 * http://www.mydomain.com/ in case we forward.
623 * Revision 1.22 2001/09/10 10:58:53 oes
624 * Silenced compiler warnings
626 * Revision 1.21 2001/07/31 14:46:00 oes
627 * - Persistant connections now suppressed
628 * - sed() no longer appends empty header to csp->headers
630 * Revision 1.20 2001/07/30 22:08:36 jongfoster
631 * Tidying up #defines:
632 * - All feature #defines are now of the form FEATURE_xxx
633 * - Permanently turned off WIN_GUI_EDIT
634 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
636 * Revision 1.19 2001/07/25 17:21:54 oes
637 * client_uagent now saves copy of User-Agent: header value
639 * Revision 1.18 2001/07/13 14:02:46 oes
640 * - Included fix to repair broken HTTP requests that
641 * don't contain a path, not even '/'.
642 * - Removed all #ifdef PCRS
643 * - content_type now always inspected and classified as
644 * text, gif or other.
645 * - formatting / comments
647 * Revision 1.17 2001/06/29 21:45:41 oes
648 * Indentation, CRLF->LF, Tab-> Space
650 * Revision 1.16 2001/06/29 13:32:42 oes
652 * - Adapted free_http_request
653 * - Removed logentry from cancelled commit
655 * Revision 1.15 2001/06/03 19:12:38 oes
656 * deleted const struct interceptors
658 * Revision 1.14 2001/06/01 18:49:17 jongfoster
659 * Replaced "list_share" with "list" - the tiny memory gain was not
660 * worth the extra complexity.
662 * Revision 1.13 2001/05/31 21:30:33 jongfoster
663 * Removed list code - it's now in list.[ch]
664 * Renamed "permission" to "action", and changed many features
665 * to use the actions file rather than the global config.
667 * Revision 1.12 2001/05/31 17:33:13 oes
671 * Revision 1.11 2001/05/29 20:11:19 joergs
672 * '/ * inside comment' warning removed.
674 * Revision 1.10 2001/05/29 09:50:24 jongfoster
675 * Unified blocklist/imagelist/permissionslist.
676 * File format is still under discussion, but the internal changes
679 * Also modified interceptor behaviour:
680 * - We now intercept all URLs beginning with one of the following
681 * prefixes (and *only* these prefixes):
683 * * http://ijbswa.sf.net/config/
684 * * http://ijbswa.sourceforge.net/config/
685 * - New interceptors "home page" - go to http://i.j.b/ to see it.
686 * - Internal changes so that intercepted and fast redirect pages
687 * are not replaced with an image.
688 * - Interceptors now have the option to send a binary page direct
689 * to the client. (i.e. ijb-send-banner uses this)
690 * - Implemented show-url-info interceptor. (Which is why I needed
691 * the above interceptors changes - a typical URL is
692 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
693 * The previous mechanism would not have intercepted that, and
694 * if it had been intercepted then it then it would have replaced
697 * Revision 1.9 2001/05/28 17:26:33 jongfoster
698 * Fixing segfault if last header was crunched.
699 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
700 * can use the cross-platform sprintf() instead.)
702 * Revision 1.8 2001/05/27 22:17:04 oes
704 * - re_process_buffer no longer writes the modified buffer
705 * to the client, which was very ugly. It now returns the
706 * buffer, which it is then written by chat.
708 * - content_length now adjusts the Content-Length: header
709 * for modified documents rather than crunch()ing it.
710 * (Length info in csp->content_length, which is 0 for
711 * unmodified documents)
713 * - For this to work, sed() is called twice when filtering.
715 * Revision 1.7 2001/05/27 13:19:06 oes
716 * Patched Joergs solution for the content-length in.
718 * Revision 1.6 2001/05/26 13:39:32 jongfoster
719 * Only crunches Content-Length header if applying RE filtering.
720 * Without this fix, Microsoft Windows Update wouldn't work.
722 * Revision 1.5 2001/05/26 00:28:36 jongfoster
723 * Automatic reloading of config file.
724 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
725 * Most of the global variables have been moved to a new
726 * struct configuration_spec, accessed through csp->config->globalname
727 * Most of the globals remaining are used by the Win32 GUI.
729 * Revision 1.4 2001/05/22 18:46:04 oes
731 * - Enabled filtering banners by size rather than URL
732 * by adding patterns that replace all standard banner
733 * sizes with the "Junkbuster" gif to the re_filterfile
735 * - Enabled filtering WebBugs by providing a pattern
736 * which kills all 1x1 images
738 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
739 * which is selected by the (nonstandard and therefore
740 * capital) letter 'U' in the option string.
741 * It causes the quantifiers to be ungreedy by default.
742 * Appending a ? turns back to greedy (!).
744 * - Added a new interceptor ijb-send-banner, which
745 * sends back the "Junkbuster" gif. Without imagelist or
746 * MSIE detection support, or if tinygif = 1, or the
747 * URL isn't recognized as an imageurl, a lame HTML
748 * explanation is sent instead.
750 * - Added new feature, which permits blocking remote
751 * script redirects and firing back a local redirect
753 * The feature is conditionally compiled, i.e. it
754 * can be disabled with --disable-fast-redirects,
755 * plus it must be activated by a "fast-redirects"
756 * line in the config file, has its own log level
757 * and of course wants to be displayed by show-proxy-args
758 * Note: Boy, all the #ifdefs in 1001 locations and
759 * all the fumbling with configure.in and acconfig.h
760 * were *way* more work than the feature itself :-(
762 * - Because a generic redirect template was needed for
763 * this, tinygif = 3 now uses the same.
765 * - Moved GIFs, and other static HTTP response templates
770 * - Removed some >400 CRs again (Jon, you really worked
773 * Revision 1.3 2001/05/20 01:21:20 jongfoster
774 * Version 2.9.4 checkin.
775 * - Merged popupfile and cookiefile, and added control over PCRS
776 * filtering, in new "permissionsfile".
777 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
778 * file error you now get a message box (in the Win32 GUI) rather
779 * than the program exiting with no explanation.
780 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
782 * - Removed tabs from "config"
783 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
784 * - Bumped up version number.
786 * Revision 1.2 2001/05/17 23:02:36 oes
787 * - Made referrer option accept 'L' as a substitute for '§'
789 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
790 * Initial import of version 2.9.3 source tree
793 *********************************************************************/
800 #include <sys/types.h>
810 * Convince GNU's libc to provide a strptime prototype.
813 #endif /*__GLIBC__ */
820 #if !defined(_WIN32) && !defined(__OS2__)
826 #ifdef FEATURE_PTHREAD
828 /* jcc.h is for mutex semapores only */
829 #endif /* def FEATURE_PTHREAD */
835 #include "jbsockets.h"
836 #include "miscutil.h"
841 #ifndef HAVE_STRPTIME
842 #include "strptime.h"
845 const char parsers_h_rcs[] = PARSERS_H_VERSION;
847 /* Fix a problem with Solaris. There should be no effect on other
849 * Solaris's isspace() is a macro which uses its argument directly
850 * as an array index. Therefore we need to make sure that high-bit
851 * characters generate +ve values, and ideally we also want to make
852 * the argument match the declared parameter type of "int".
854 * Why did they write a character function that can't take a simple
855 * "char" argument? Doh!
857 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
858 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
860 static char *get_header_line(struct iob *iob);
861 static jb_err scan_headers(struct client_state *csp);
862 static jb_err header_tagger(struct client_state *csp, char *header);
863 static jb_err parse_header_time(const char *header_time, time_t *result);
865 static jb_err crumble (struct client_state *csp, char **header);
866 static jb_err connection (struct client_state *csp, char **header);
867 static jb_err filter_header (struct client_state *csp, char **header);
868 static jb_err client_referrer (struct client_state *csp, char **header);
869 static jb_err client_uagent (struct client_state *csp, char **header);
870 static jb_err client_ua (struct client_state *csp, char **header);
871 static jb_err client_from (struct client_state *csp, char **header);
872 static jb_err client_send_cookie (struct client_state *csp, char **header);
873 static jb_err client_x_forwarded (struct client_state *csp, char **header);
874 static jb_err client_accept_encoding (struct client_state *csp, char **header);
875 static jb_err client_te (struct client_state *csp, char **header);
876 static jb_err client_max_forwards (struct client_state *csp, char **header);
877 static jb_err client_host (struct client_state *csp, char **header);
878 static jb_err client_if_modified_since (struct client_state *csp, char **header);
879 static jb_err client_accept_language (struct client_state *csp, char **header);
880 static jb_err client_if_none_match (struct client_state *csp, char **header);
881 static jb_err crunch_client_header (struct client_state *csp, char **header);
882 static jb_err client_x_filter (struct client_state *csp, char **header);
883 static jb_err client_range (struct client_state *csp, char **header);
884 static jb_err server_set_cookie (struct client_state *csp, char **header);
885 static jb_err server_content_type (struct client_state *csp, char **header);
886 static jb_err server_content_length (struct client_state *csp, char **header);
887 static jb_err server_content_md5 (struct client_state *csp, char **header);
888 static jb_err server_content_encoding (struct client_state *csp, char **header);
889 static jb_err server_transfer_coding (struct client_state *csp, char **header);
890 static jb_err server_http (struct client_state *csp, char **header);
891 static jb_err crunch_server_header (struct client_state *csp, char **header);
892 static jb_err server_last_modified (struct client_state *csp, char **header);
893 static jb_err server_content_disposition(struct client_state *csp, char **header);
895 static jb_err client_host_adder (struct client_state *csp);
896 static jb_err client_xtra_adder (struct client_state *csp);
897 static jb_err connection_close_adder (struct client_state *csp);
899 static jb_err create_forged_referrer(char **header, const char *hostport);
900 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
901 static jb_err handle_conditional_hide_referrer_parameter(char **header,
902 const char *host, const int parameter_conditional_block);
905 * List of functions to run on a list of headers.
909 /** The header prefix to match */
912 /** The length of the prefix to match */
915 /** The function to apply to this line */
916 const parser_func_ptr parser;
919 static const struct parsers client_patterns[] = {
920 { "referer:", 8, client_referrer },
921 { "user-agent:", 11, client_uagent },
922 { "ua-", 3, client_ua },
923 { "from:", 5, client_from },
924 { "cookie:", 7, client_send_cookie },
925 { "x-forwarded-for:", 16, client_x_forwarded },
926 { "Accept-Encoding:", 16, client_accept_encoding },
927 { "TE:", 3, client_te },
928 { "Host:", 5, client_host },
929 { "if-modified-since:", 18, client_if_modified_since },
930 { "Keep-Alive:", 11, crumble },
931 { "connection:", 11, connection },
932 { "proxy-connection:", 17, crumble },
933 { "max-forwards:", 13, client_max_forwards },
934 { "Accept-Language:", 16, client_accept_language },
935 { "if-none-match:", 14, client_if_none_match },
936 { "Range:", 6, client_range },
937 { "Request-Range:", 14, client_range },
938 { "If-Range:", 9, client_range },
939 { "X-Filter:", 9, client_x_filter },
940 { "*", 0, crunch_client_header },
941 { "*", 0, filter_header },
945 static const struct parsers server_patterns[] = {
946 { "HTTP/", 5, server_http },
947 { "set-cookie:", 11, server_set_cookie },
948 { "connection:", 11, connection },
949 { "Content-Type:", 13, server_content_type },
950 { "Content-MD5:", 12, server_content_md5 },
951 { "Content-Encoding:", 17, server_content_encoding },
952 { "Transfer-Encoding:", 18, server_transfer_coding },
953 { "Keep-Alive:", 11, crumble },
954 { "content-disposition:", 20, server_content_disposition },
955 { "Last-Modified:", 14, server_last_modified },
956 { "*", 0, crunch_server_header },
957 { "*", 0, filter_header },
961 static const add_header_func_ptr add_client_headers[] = {
964 /* Temporarily disabled: client_accept_encoding_adder, */
965 connection_close_adder,
969 static const add_header_func_ptr add_server_headers[] = {
970 connection_close_adder,
974 /*********************************************************************
976 * Function : flush_socket
978 * Description : Write any pending "buffered" content.
981 * 1 : fd = file descriptor of the socket to read
982 * 2 : iob = The I/O buffer to flush, usually csp->iob.
984 * Returns : On success, the number of bytes written are returned (zero
985 * indicates nothing was written). On error, -1 is returned,
986 * and errno is set appropriately. If count is zero and the
987 * file descriptor refers to a regular file, 0 will be
988 * returned without causing any other effect. For a special
989 * file, the results are not portable.
991 *********************************************************************/
992 int flush_socket(jb_socket fd, struct iob *iob)
994 int len = iob->eod - iob->cur;
1001 if (write_socket(fd, iob->cur, (size_t)len))
1005 iob->eod = iob->cur = iob->buf;
1011 /*********************************************************************
1013 * Function : add_to_iob
1015 * Description : Add content to the buffered page, expanding the
1016 * buffer if necessary.
1019 * 1 : csp = Current client state (buffers, headers, etc...)
1020 * 2 : buf = holds the content to be added to the page
1021 * 3 : n = number of bytes to be added
1023 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1024 * or buffer limit reached.
1026 *********************************************************************/
1027 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1029 struct iob *iob = csp->iob;
1030 size_t used, offset, need, want;
1033 if (n <= 0) return JB_ERR_OK;
1035 used = (size_t)(iob->eod - iob->buf);
1036 offset = (size_t)(iob->cur - iob->buf);
1037 need = used + (size_t)n + 1;
1040 * If the buffer can't hold the new data, extend it first.
1041 * Use the next power of two if possible, else use the actual need.
1043 if (need > csp->config->buffer_limit)
1045 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1046 return JB_ERR_MEMORY;
1049 if (need > iob->size)
1051 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1053 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1057 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1063 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1064 return JB_ERR_MEMORY;
1067 /* Update the iob pointers */
1068 iob->cur = p + offset;
1069 iob->eod = p + used;
1073 /* copy the new data into the iob buffer */
1074 memcpy(iob->eod, buf, (size_t)n);
1076 /* point to the end of the data */
1079 /* null terminate == cheap insurance */
1088 /*********************************************************************
1090 * Function : decompress_iob
1092 * Description : Decompress buffered page, expanding the
1093 * buffer as necessary. csp->iob->cur
1094 * should point to the the beginning of the
1095 * compressed data block.
1098 * 1 : csp = Current client state (buffers, headers, etc...)
1100 * Returns : JB_ERR_OK on success,
1101 * JB_ERR_MEMORY if out-of-memory limit reached, and
1102 * JB_ERR_COMPRESS if error decompressing buffer.
1104 *********************************************************************/
1105 jb_err decompress_iob(struct client_state *csp)
1107 char *buf; /* new, uncompressed buffer */
1108 char *cur; /* Current iob position (to keep the original
1109 * iob->cur unmodified if we return early) */
1110 size_t bufsize; /* allocated size of the new buffer */
1111 size_t old_size; /* Content size before decompression */
1112 size_t skip_size; /* Number of bytes at the beginning of the iob
1113 that we should NOT decompress. */
1114 int status; /* return status of the inflate() call */
1115 z_stream zstr; /* used by calls to zlib */
1117 assert(csp->iob->cur - csp->iob->buf > 0);
1118 assert(csp->iob->eod - csp->iob->cur > 0);
1120 bufsize = csp->iob->size;
1121 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1122 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1124 cur = csp->iob->cur;
1129 * This is to protect the parsing of gzipped data,
1130 * but it should(?) be valid for deflated data also.
1132 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1133 return JB_ERR_COMPRESS;
1136 if (csp->content_type & CT_GZIP)
1139 * Our task is slightly complicated by the facts that data
1140 * compressed by gzip does not include a zlib header, and
1141 * that there is no easily accessible interface in zlib to
1142 * handle a gzip header. We strip off the gzip header by
1143 * hand, and later inform zlib not to expect a header.
1147 * Strip off the gzip header. Please see RFC 1952 for more
1148 * explanation of the appropriate fields.
1150 if ((*cur++ != (char)0x1f)
1151 || (*cur++ != (char)0x8b)
1152 || (*cur++ != Z_DEFLATED))
1154 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1155 return JB_ERR_COMPRESS;
1161 * XXX: These magic numbers should be replaced
1162 * with macros to give a better idea what they do.
1166 /* The gzip header has reserved bits set; bail out. */
1167 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1168 return JB_ERR_COMPRESS;
1172 /* Skip extra fields if necessary. */
1176 * Skip a given number of bytes, specified
1177 * as a 16-bit little-endian value.
1180 * XXX: This code used to be:
1182 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1184 * which I had to change into:
1186 * cur += *cur++ + (*cur++ << 8);
1188 * at which point gcc43 finally noticed that the value
1189 * of cur is undefined (it depends on which of the
1190 * summands is evaluated first).
1192 * I haven't come across a site where this
1193 * code is actually executed yet, but I hope
1197 skip_bytes = *cur++;
1198 skip_bytes = *cur++ << 8;
1200 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1203 * The number of bytes to skip should be positive
1204 * and we'd like to stay in the buffer.
1206 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1208 log_error(LOG_LEVEL_ERROR,
1209 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1211 return JB_ERR_COMPRESS;
1213 log_error(LOG_LEVEL_INFO,
1214 "Skipping %d bytes for gzip compression. Does this sound right?",
1219 /* Skip the filename if necessary. */
1222 /* A null-terminated string is supposed to follow. */
1223 while (*cur++ && (cur < csp->iob->eod));
1227 /* Skip the comment if necessary. */
1230 /* A null-terminated string is supposed to follow. */
1231 while (*cur++ && (cur < csp->iob->eod));
1234 /* Skip the CRC if necessary. */
1240 if (cur >= csp->iob->eod)
1243 * If the current position pointer reached or passed
1244 * the buffer end, we were obviously tricked to skip
1247 log_error(LOG_LEVEL_ERROR,
1248 "Malformed gzip header detected. Aborting decompression.");
1249 return JB_ERR_COMPRESS;
1253 else if (csp->content_type & CT_DEFLATE)
1256 * XXX: The debug level should be lowered
1257 * before the next stable release.
1259 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1261 * In theory (that is, according to RFC 1950), deflate-compressed
1262 * data should begin with a two-byte zlib header and have an
1263 * adler32 checksum at the end. It seems that in practice only
1264 * the raw compressed data is sent. Note that this means that
1265 * we are not RFC 1950-compliant here, but the advantage is that
1266 * this actually works. :)
1268 * We add a dummy null byte to tell zlib where the data ends,
1269 * and later inform it not to expect a header.
1271 * Fortunately, add_to_iob() has thoughtfully null-terminated
1272 * the buffer; we can just increment the end pointer to include
1279 log_error(LOG_LEVEL_ERROR,
1280 "Unable to determine compression format for decompression");
1281 return JB_ERR_COMPRESS;
1284 /* Set up the fields required by zlib. */
1285 zstr.next_in = (Bytef *)cur;
1286 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1287 zstr.zalloc = Z_NULL;
1288 zstr.zfree = Z_NULL;
1289 zstr.opaque = Z_NULL;
1292 * Passing -MAX_WBITS to inflateInit2 tells the library
1293 * that there is no zlib header.
1295 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1297 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1298 return JB_ERR_COMPRESS;
1302 * Next, we allocate new storage for the inflated data.
1303 * We don't modify the existing iob yet, so in case there
1304 * is error in decompression we can recover gracefully.
1306 buf = zalloc(bufsize);
1309 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1310 return JB_ERR_MEMORY;
1313 assert(bufsize >= skip_size);
1314 memcpy(buf, csp->iob->buf, skip_size);
1315 zstr.avail_out = bufsize - skip_size;
1316 zstr.next_out = (Bytef *)buf + skip_size;
1318 /* Try to decompress the whole stream in one shot. */
1319 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1321 /* We need to allocate more memory for the output buffer. */
1323 char *tmpbuf; /* used for realloc'ing the buffer */
1324 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1327 * If zlib wants more data then there's a problem, because
1328 * the complete compressed file should have been buffered.
1330 if (0 == zstr.avail_in)
1332 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1333 return JB_ERR_COMPRESS;
1337 * If we tried the limit and still didn't have enough
1338 * memory, just give up.
1340 if (bufsize == csp->config->buffer_limit)
1342 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1343 return JB_ERR_MEMORY;
1346 /* Try doubling the buffer size each time. */
1349 /* Don't exceed the buffer limit. */
1350 if (bufsize > csp->config->buffer_limit)
1352 bufsize = csp->config->buffer_limit;
1355 /* Try to allocate the new buffer. */
1356 tmpbuf = realloc(buf, bufsize);
1359 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1361 return JB_ERR_MEMORY;
1365 char *oldnext_out = (char *)zstr.next_out;
1368 * Update the fields for inflate() to use the new
1369 * buffer, which may be in a location different from
1372 zstr.avail_out += bufsize - oldbufsize;
1373 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1376 * Compare with an uglier method of calculating these values
1377 * that doesn't require the extra oldbufsize variable.
1379 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1380 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1381 assert(zstr.avail_out > 0);
1387 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1389 log_error(LOG_LEVEL_ERROR,
1390 "Inconsistent stream state after decompression: %s", zstr.msg);
1392 * XXX: Intentionally no return.
1394 * According to zlib.h, Z_STREAM_ERROR is returned
1395 * "if the stream state was inconsistent".
1397 * I assume in this case inflate()'s status
1398 * would also be something different than Z_STREAM_END
1399 * so this check should be redundant, but lets see.
1403 if (status != Z_STREAM_END)
1405 /* We failed to decompress the stream. */
1406 log_error(LOG_LEVEL_ERROR,
1407 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1408 return JB_ERR_COMPRESS;
1412 * Finally, we can actually update the iob, since the
1413 * decompression was successful. First, free the old
1416 freez(csp->iob->buf);
1418 /* Now, update the iob to use the new buffer. */
1419 csp->iob->buf = buf;
1420 csp->iob->cur = csp->iob->buf + skip_size;
1421 csp->iob->eod = (char *)zstr.next_out;
1422 csp->iob->size = bufsize;
1425 * Make sure the new uncompressed iob obeys some minimal
1426 * consistency conditions.
1428 if ((csp->iob->buf < csp->iob->cur)
1429 && (csp->iob->cur <= csp->iob->eod)
1430 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1432 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1435 log_error(LOG_LEVEL_RE_FILTER,
1436 "Decompression successful. Old size: %d, new size: %d.",
1437 old_size, new_size);
1441 /* zlib thinks this is OK, so lets do the same. */
1442 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1447 /* It seems that zlib did something weird. */
1448 log_error(LOG_LEVEL_ERROR,
1449 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1450 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1451 csp->iob->eod, csp->iob->buf + csp->iob->size);
1452 return JB_ERR_COMPRESS;
1458 #endif /* defined(FEATURE_ZLIB) */
1461 /*********************************************************************
1463 * Function : string_move
1465 * Description : memmove wrapper to move the last part of a string
1466 * towards the beginning, overwriting the part in
1467 * the middle. strlcpy() can't be used here as the
1471 * 1 : dst = Destination to overwrite
1472 * 2 : src = Source to move.
1476 *********************************************************************/
1477 static void string_move(char *dst, char *src)
1481 /* +1 to copy the terminating nul as well. */
1482 memmove(dst, src, strlen(src)+1);
1486 /*********************************************************************
1488 * Function : normalize_lws
1490 * Description : Reduces unquoted linear white space in headers
1491 * to a single space in accordance with RFC 2616 2.2.
1492 * This simplifies parsing and filtering later on.
1494 * XXX: Remove log messages before
1495 * the next stable release?
1498 * 1 : header = A header with linear white space to reduce.
1502 *********************************************************************/
1503 static void normalize_lws(char *header)
1509 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1513 while (ijb_isspace(*q))
1517 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1518 string_move(p+1, q);
1523 log_error(LOG_LEVEL_HEADER,
1524 "Converting tab to space in '%s'", header);
1529 char *end_of_token = strstr(p+1, "\"");
1531 if (NULL != end_of_token)
1533 /* Don't mess with quoted text. */
1538 log_error(LOG_LEVEL_HEADER,
1539 "Ignoring single quote in '%s'", header);
1545 p = strchr(header, ':');
1546 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1549 * There's still space before the colon.
1552 string_move(p-1, p);
1557 /*********************************************************************
1559 * Function : get_header
1561 * Description : This (odd) routine will parse the csp->iob
1562 * to get the next complete header.
1565 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1567 * Returns : Any one of the following:
1569 * 1) a pointer to a dynamically allocated string that contains a header line
1570 * 2) NULL indicating that the end of the header was reached
1571 * 3) "" indicating that the end of the iob was reached before finding
1572 * a complete header line.
1574 *********************************************************************/
1575 char *get_header(struct iob *iob)
1579 header = get_header_line(iob);
1581 if ((header == NULL) || (*header == '\0'))
1584 * No complete header read yet, tell the client.
1589 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1592 * Header spans multiple lines, append the next one.
1594 char *continued_header;
1596 continued_header = get_header_line(iob);
1597 if ((continued_header == NULL) || (*continued_header == '\0'))
1600 * No complete header read yet, return what we got.
1601 * XXX: Should "unread" header instead.
1603 log_error(LOG_LEVEL_INFO,
1604 "Failed to read a multi-line header properly: '%s'",
1609 if (JB_ERR_OK != string_join(&header, continued_header))
1611 log_error(LOG_LEVEL_FATAL,
1612 "Out of memory while appending multiple headers.");
1616 /* XXX: remove before next stable release. */
1617 log_error(LOG_LEVEL_HEADER,
1618 "Merged multiple header lines to: '%s'",
1623 normalize_lws(header);
1630 /*********************************************************************
1632 * Function : get_header_line
1634 * Description : This (odd) routine will parse the csp->iob
1635 * to get the next header line.
1638 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1640 * Returns : Any one of the following:
1642 * 1) a pointer to a dynamically allocated string that contains a header line
1643 * 2) NULL indicating that the end of the header was reached
1644 * 3) "" indicating that the end of the iob was reached before finding
1645 * a complete header line.
1647 *********************************************************************/
1648 static char *get_header_line(struct iob *iob)
1652 if ((iob->cur == NULL)
1653 || ((p = strchr(iob->cur, '\n')) == NULL))
1655 return(""); /* couldn't find a complete header */
1660 ret = strdup(iob->cur);
1663 /* FIXME No way to handle error properly */
1664 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1669 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1671 /* is this a blank line (i.e. the end of the header) ? */
1683 /*********************************************************************
1685 * Function : get_header_value
1687 * Description : Get the value of a given header from a chained list
1688 * of header lines or return NULL if no such header is
1689 * present in the list.
1692 * 1 : header_list = pointer to list
1693 * 2 : header_name = string with name of header to look for.
1694 * Trailing colon required, capitalization
1697 * Returns : NULL if not found, else value of header
1699 *********************************************************************/
1700 char *get_header_value(const struct list *header_list, const char *header_name)
1702 struct list_entry *cur_entry;
1706 assert(header_list);
1707 assert(header_name);
1708 length = strlen(header_name);
1710 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1714 if (!strncmpic(cur_entry->str, header_name, length))
1717 * Found: return pointer to start of value
1719 ret = (char *) (cur_entry->str + length);
1720 while (*ret && ijb_isspace(*ret)) ret++;
1734 /*********************************************************************
1736 * Function : scan_headers
1738 * Description : Scans headers, applies tags and updates action bits.
1741 * 1 : csp = Current client state (buffers, headers, etc...)
1743 * Returns : JB_ERR_OK
1745 *********************************************************************/
1746 static jb_err scan_headers(struct client_state *csp)
1748 struct list_entry *h; /* Header */
1749 jb_err err = JB_ERR_OK;
1751 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1753 /* Header crunch()ed in previous run? -> ignore */
1754 if (h->str == NULL) continue;
1755 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1756 err = header_tagger(csp, h->str);
1763 /*********************************************************************
1767 * Description : add, delete or modify lines in the HTTP header streams.
1768 * On entry, it receives a linked list of headers space
1769 * that was allocated dynamically (both the list nodes
1770 * and the header contents).
1772 * As a side effect it frees the space used by the original
1776 * 1 : csp = Current client state (buffers, headers, etc...)
1777 * 2 : filter_server_headers = Boolean to switch between
1778 * server and header filtering.
1780 * Returns : JB_ERR_OK in case off success, or
1781 * JB_ERR_MEMORY on out-of-memory error.
1783 *********************************************************************/
1784 jb_err sed(struct client_state *csp, int filter_server_headers)
1786 /* XXX: use more descriptive names. */
1787 struct list_entry *p;
1788 const struct parsers *v;
1789 const add_header_func_ptr *f;
1790 jb_err err = JB_ERR_OK;
1792 if (filter_server_headers)
1794 v = server_patterns;
1795 f = add_server_headers;
1799 v = client_patterns;
1800 f = add_client_headers;
1805 while ((err == JB_ERR_OK) && (v->str != NULL))
1807 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1809 /* Header crunch()ed in previous run? -> ignore */
1810 if (p->str == NULL) continue;
1812 /* Does the current parser handle this header? */
1813 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1814 (v->len == CHECK_EVERY_HEADER_REMAINING))
1816 err = v->parser(csp, (char **)&(p->str));
1822 /* place additional headers on the csp->headers list */
1823 while ((err == JB_ERR_OK) && (*f))
1833 /*********************************************************************
1835 * Function : update_server_headers
1837 * Description : Updates server headers after the body has been modified.
1840 * 1 : csp = Current client state (buffers, headers, etc...)
1842 * Returns : JB_ERR_OK in case off success, or
1843 * JB_ERR_MEMORY on out-of-memory error.
1845 *********************************************************************/
1846 jb_err update_server_headers(struct client_state *csp)
1848 jb_err err = JB_ERR_OK;
1850 static const struct parsers server_patterns_light[] = {
1851 { "Content-Length:", 15, server_content_length },
1852 { "Transfer-Encoding:", 18, server_transfer_coding },
1854 { "Content-Encoding:", 17, server_content_encoding },
1855 #endif /* def FEATURE_ZLIB */
1859 if (strncmpic(csp->http->cmd, "HEAD", 4))
1861 const struct parsers *v;
1862 struct list_entry *p;
1864 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1866 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1868 /* Header crunch()ed in previous run? -> ignore */
1869 if (p->str == NULL) continue;
1871 /* Does the current parser handle this header? */
1872 if (strncmpic(p->str, v->str, v->len) == 0)
1874 err = v->parser(csp, (char **)&(p->str));
1884 /*********************************************************************
1886 * Function : header_tagger
1888 * Description : Executes all text substitutions from applying
1889 * tag actions and saves the result as tag.
1891 * XXX: Shares enough code with filter_header() and
1892 * pcrs_filter_response() to warrant some helper functions.
1895 * 1 : csp = Current client state (buffers, headers, etc...)
1896 * 2 : header = Header that is used as tagger input
1898 * Returns : JB_ERR_OK on success and always succeeds
1900 *********************************************************************/
1901 static jb_err header_tagger(struct client_state *csp, char *header)
1903 int wanted_filter_type;
1904 int multi_action_index;
1908 struct file_list *fl;
1909 struct re_filterfile_spec *b;
1910 struct list_entry *tag_name;
1912 int found_filters = 0;
1913 const size_t header_length = strlen(header);
1915 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1917 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1918 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1922 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1923 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1926 /* Check if there are any filters */
1927 for (i = 0; i < MAX_AF_FILES; i++)
1940 if (0 == found_filters)
1942 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1943 "tagging enabled, but no taggers available.");
1947 for (i = 0; i < MAX_AF_FILES; i++)
1950 if ((NULL == fl) || (NULL == fl->f))
1953 * Either there are no filter files
1954 * left, or this filter file just
1955 * contains no valid filters.
1957 * Continue to be sure we don't miss
1958 * valid filter files that are chained
1959 * after empty or invalid ones.
1964 /* For all filters, */
1965 for (b = fl->f; b; b = b->next)
1967 if (b->type != wanted_filter_type)
1969 /* skip the ones we don't care about, */
1972 /* leaving only taggers that could apply, of which we use the ones, */
1973 for (tag_name = csp->action->multi[multi_action_index]->first;
1974 NULL != tag_name; tag_name = tag_name->next)
1976 /* that do apply, and */
1977 if (strcmp(b->name, tag_name->str) == 0)
1979 char *modified_tag = NULL;
1981 size_t size = header_length;
1982 pcrs_job *joblist = b->joblist;
1984 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1986 if (NULL == joblist)
1988 log_error(LOG_LEVEL_RE_FILTER,
1989 "Tagger %s has empty joblist. Nothing to do.", b->name);
1993 /* execute their pcrs_joblist on the header. */
1994 for (job = joblist; NULL != job; job = job->next)
1996 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2000 /* Success, continue with the modified version. */
2009 /* Tagger doesn't match */
2012 /* Regex failure, log it but continue anyway. */
2013 log_error(LOG_LEVEL_ERROR,
2014 "Problems with tagger \'%s\' and header \'%s\': %s",
2015 b->name, *header, pcrs_strerror(hits));
2017 freez(modified_tag);
2021 if (b->dynamic) pcrs_free_joblist(joblist);
2023 /* If this tagger matched */
2029 * There is to technical limitation which makes
2030 * it impossible to use empty tags, but I assume
2031 * no one would do it intentionally.
2034 log_error(LOG_LEVEL_INFO,
2035 "Tagger \'%s\' created an empty tag. Ignored.",
2040 if (!list_contains_item(csp->tags, tag))
2042 if (JB_ERR_OK != enlist(csp->tags, tag))
2044 log_error(LOG_LEVEL_ERROR,
2045 "Insufficient memory to add tag \'%s\', "
2046 "based on tagger \'%s\' and header \'%s\'",
2047 tag, b->name, *header);
2051 char *action_message;
2053 * update the action bits right away, to make
2054 * tagging based on tags set by earlier taggers
2055 * of the same kind possible.
2057 if (update_action_bits_for_tag(csp, tag))
2059 action_message = "Action bits updated accordingly.";
2063 action_message = "No action bits update necessary.";
2066 log_error(LOG_LEVEL_HEADER,
2067 "Tagger \'%s\' added tag \'%s\'. %s",
2068 b->name, tag, action_message);
2073 /* XXX: Is this log-worthy? */
2074 log_error(LOG_LEVEL_HEADER,
2075 "Tagger \'%s\' didn't add tag \'%s\'. "
2076 "Tag already present", b->name, tag);
2079 } /* if the tagger matched */
2080 } /* if the tagger applies */
2081 } /* for every tagger that could apply */
2082 } /* for all filters */
2083 } /* for all filter files */
2088 /* here begins the family of parser functions that reformat header lines */
2090 /*********************************************************************
2092 * Function : filter_header
2094 * Description : Executes all text substitutions from all applying
2095 * +(server|client)-header-filter actions on the header.
2096 * Most of the code was copied from pcrs_filter_response,
2097 * including the rather short variable names
2100 * 1 : csp = Current client state (buffers, headers, etc...)
2101 * 2 : header = On input, pointer to header to modify.
2102 * On output, pointer to the modified header, or NULL
2103 * to remove the header. This function frees the
2104 * original string if necessary.
2106 * Returns : JB_ERR_OK on success and always succeeds
2108 *********************************************************************/
2109 static jb_err filter_header(struct client_state *csp, char **header)
2113 size_t size = strlen(*header);
2115 char *newheader = NULL;
2118 struct file_list *fl;
2119 struct re_filterfile_spec *b;
2120 struct list_entry *filtername;
2122 int i, found_filters = 0;
2123 int wanted_filter_type;
2124 int multi_action_index;
2126 if (csp->flags & CSP_FLAG_NO_FILTERING)
2131 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2133 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2134 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2138 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2139 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2143 * Need to check the set of re_filterfiles...
2145 for (i = 0; i < MAX_AF_FILES; i++)
2158 if (0 == found_filters)
2160 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2161 "header filtering enabled, but no matching filters available.");
2165 for (i = 0; i < MAX_AF_FILES; i++)
2168 if ((NULL == fl) || (NULL == fl->f))
2171 * Either there are no filter files
2172 * left, or this filter file just
2173 * contains no valid filters.
2175 * Continue to be sure we don't miss
2176 * valid filter files that are chained
2177 * after empty or invalid ones.
2182 * For all applying +filter actions, look if a filter by that
2183 * name exists and if yes, execute its pcrs_joblist on the
2186 for (b = fl->f; b; b = b->next)
2188 if (b->type != wanted_filter_type)
2190 /* Skip other filter types */
2194 for (filtername = csp->action->multi[multi_action_index]->first;
2195 filtername ; filtername = filtername->next)
2197 if (strcmp(b->name, filtername->str) == 0)
2199 int current_hits = 0;
2200 pcrs_job *joblist = b->joblist;
2202 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2204 if (NULL == joblist)
2206 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2210 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2211 *header, size, b->name);
2213 /* Apply all jobs from the joblist */
2214 for (job = joblist; NULL != job; job = job->next)
2216 matches = pcrs_execute(job, *header, size, &newheader, &size);
2219 current_hits += matches;
2220 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2222 *header = newheader;
2224 else if ( 0 == matches )
2226 /* Filter doesn't change header */
2232 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2233 *header, b->name, pcrs_strerror(matches));
2234 if (newheader != NULL)
2236 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2242 if (b->dynamic) pcrs_free_joblist(joblist);
2244 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2245 hits += current_hits;
2252 * Additionally checking for hits is important because if
2253 * the continue hack is triggered, server headers can
2254 * arrive empty to separate multiple heads from each other.
2256 if ((0 == size) && hits)
2258 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2266 /*********************************************************************
2268 * Function : connection
2270 * Description : Makes sure that the value of the Connection: header
2271 * is "close" and signals connection_close_adder
2275 * 1 : csp = Current client state (buffers, headers, etc...)
2276 * 2 : header = On input, pointer to header to modify.
2277 * On output, pointer to the modified header, or NULL
2278 * to remove the header. This function frees the
2279 * original string if necessary.
2281 * Returns : JB_ERR_OK on success, or
2282 * JB_ERR_MEMORY on out-of-memory error.
2284 *********************************************************************/
2285 static jb_err connection(struct client_state *csp, char **header)
2287 char *old_header = *header;
2289 /* Do we have a 'Connection: close' header? */
2290 if (strcmpic(*header, "Connection: close"))
2292 /* No, create one */
2293 *header = strdup("Connection: close");
2296 return JB_ERR_MEMORY;
2298 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2302 /* Signal connection_close_adder() to return early. */
2303 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2305 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2309 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2316 /*********************************************************************
2318 * Function : crumble
2320 * Description : This is called if a header matches a pattern to "crunch"
2323 * 1 : csp = Current client state (buffers, headers, etc...)
2324 * 2 : header = On input, pointer to header to modify.
2325 * On output, pointer to the modified header, or NULL
2326 * to remove the header. This function frees the
2327 * original string if necessary.
2329 * Returns : JB_ERR_OK on success, or
2330 * JB_ERR_MEMORY on out-of-memory error.
2332 *********************************************************************/
2333 static jb_err crumble(struct client_state *csp, char **header)
2335 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2341 /*********************************************************************
2343 * Function : crunch_server_header
2345 * Description : Crunch server header if it matches a string supplied by the
2346 * user. Called from `sed'.
2349 * 1 : csp = Current client state (buffers, headers, etc...)
2350 * 2 : header = On input, pointer to header to modify.
2351 * On output, pointer to the modified header, or NULL
2352 * to remove the header. This function frees the
2353 * original string if necessary.
2355 * Returns : JB_ERR_OK on success and always succeeds
2357 *********************************************************************/
2358 static jb_err crunch_server_header(struct client_state *csp, char **header)
2360 const char *crunch_pattern;
2362 /* Do we feel like crunching? */
2363 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2365 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2367 /* Is the current header the lucky one? */
2368 if (strstr(*header, crunch_pattern))
2370 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2379 /*********************************************************************
2381 * Function : server_content_type
2383 * Description : Set the content-type for filterable types (text/.*,
2384 * .*xml.*, javascript and image/gif) unless filtering has been
2385 * forbidden (CT_TABOO) while parsing earlier headers.
2386 * NOTE: Since text/plain is commonly used by web servers
2387 * for files whose correct type is unknown, we don't
2388 * set CT_TEXT for it.
2391 * 1 : csp = Current client state (buffers, headers, etc...)
2392 * 2 : header = On input, pointer to header to modify.
2393 * On output, pointer to the modified header, or NULL
2394 * to remove the header. This function frees the
2395 * original string if necessary.
2397 * Returns : JB_ERR_OK on success, or
2398 * JB_ERR_MEMORY on out-of-memory error.
2400 *********************************************************************/
2401 static jb_err server_content_type(struct client_state *csp, char **header)
2403 /* Remove header if it isn't the first Content-Type header */
2404 if ((csp->content_type & CT_DECLARED))
2407 * Another, slightly slower, way to see if
2408 * we already parsed another Content-Type header.
2410 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2412 log_error(LOG_LEVEL_ERROR,
2413 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2421 * Signal that the Content-Type has been set.
2423 csp->content_type |= CT_DECLARED;
2425 if (!(csp->content_type & CT_TABOO))
2428 * XXX: The assumption that text/plain is a sign of
2429 * binary data seems to be somewhat unreasonable nowadays
2430 * and should be dropped after 3.0.8 is out.
2432 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2433 || strstr(*header, "xml")
2434 || strstr(*header, "application/x-javascript"))
2436 csp->content_type |= CT_TEXT;
2438 else if (strstr(*header, "image/gif"))
2440 csp->content_type |= CT_GIF;
2445 * Are we messing with the content type?
2447 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2450 * Make sure the user doesn't accidently
2451 * change the content type of binary documents.
2453 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2456 *header = strdup("Content-Type: ");
2457 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2461 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2462 return JB_ERR_MEMORY;
2464 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2468 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2469 "It doesn't look like a content type that should be filtered. "
2470 "Enable force-text-mode if you know what you're doing.", *header);
2478 /*********************************************************************
2480 * Function : server_transfer_coding
2482 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2483 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2484 * - Remove header if body was chunked but has been
2485 * de-chunked for filtering.
2488 * 1 : csp = Current client state (buffers, headers, etc...)
2489 * 2 : header = On input, pointer to header to modify.
2490 * On output, pointer to the modified header, or NULL
2491 * to remove the header. This function frees the
2492 * original string if necessary.
2494 * Returns : JB_ERR_OK on success, or
2495 * JB_ERR_MEMORY on out-of-memory error.
2497 *********************************************************************/
2498 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2501 * Turn off pcrs and gif filtering if body compressed
2503 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2507 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2509 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2510 csp->http->cmd, *header);
2511 #endif /* def FEATURE_ZLIB */
2512 csp->content_type = CT_TABOO;
2516 * Raise flag if body chunked
2518 if (strstr(*header, "chunked"))
2520 csp->flags |= CSP_FLAG_CHUNKED;
2523 * If the body was modified, it has been de-chunked first
2524 * and the header must be removed.
2526 * FIXME: If there is more than one transfer encoding,
2527 * only the "chunked" part should be removed here.
2529 if (csp->flags & CSP_FLAG_MODIFIED)
2531 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2540 /*********************************************************************
2542 * Function : server_content_encoding
2544 * Description : This function is run twice for each request,
2545 * unless FEATURE_ZLIB and filtering are disabled.
2547 * The first run is used to check if the content
2548 * is compressed, if FEATURE_ZLIB is disabled
2549 * filtering is then disabled as well, if FEATURE_ZLIB
2550 * is enabled the content is marked for decompression.
2552 * The second run is used to remove the Content-Encoding
2553 * header if the decompression was successful.
2556 * 1 : csp = Current client state (buffers, headers, etc...)
2557 * 2 : header = On input, pointer to header to modify.
2558 * On output, pointer to the modified header, or NULL
2559 * to remove the header. This function frees the
2560 * original string if necessary.
2562 * Returns : JB_ERR_OK on success, or
2563 * JB_ERR_MEMORY on out-of-memory error.
2565 *********************************************************************/
2566 static jb_err server_content_encoding(struct client_state *csp, char **header)
2569 if ((csp->flags & CSP_FLAG_MODIFIED)
2570 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2573 * We successfully decompressed the content,
2574 * and have to clean the header now, so the
2575 * client no longer expects compressed data..
2577 * XXX: There is a difference between cleaning
2578 * and removing it completely.
2580 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2583 else if (strstr(*header, "gzip"))
2585 /* Mark for gzip decompression */
2586 csp->content_type |= CT_GZIP;
2588 else if (strstr(*header, "deflate"))
2590 /* Mark for zlib decompression */
2591 csp->content_type |= CT_DEFLATE;
2593 else if (strstr(*header, "compress"))
2596 * We can't decompress this; therefore we can't filter
2599 csp->content_type |= CT_TABOO;
2601 #else /* !defined(FEATURE_ZLIB) */
2602 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2605 * Body is compressed, turn off pcrs and gif filtering.
2607 csp->content_type |= CT_TABOO;
2610 * Log a warning if the user expects the content to be filtered.
2612 if ((csp->rlist != NULL) &&
2613 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2615 log_error(LOG_LEVEL_INFO,
2616 "Compressed content detected, content filtering disabled. "
2617 "Consider recompiling Privoxy with zlib support or "
2618 "enable the prevent-compression action.");
2621 #endif /* defined(FEATURE_ZLIB) */
2628 /*********************************************************************
2630 * Function : server_content_length
2632 * Description : Adjust Content-Length header if we modified
2636 * 1 : csp = Current client state (buffers, headers, etc...)
2637 * 2 : header = On input, pointer to header to modify.
2638 * On output, pointer to the modified header, or NULL
2639 * to remove the header. This function frees the
2640 * original string if necessary.
2642 * Returns : JB_ERR_OK on success, or
2643 * JB_ERR_MEMORY on out-of-memory error.
2645 *********************************************************************/
2646 static jb_err server_content_length(struct client_state *csp, char **header)
2648 const size_t max_header_length = 80;
2650 /* Regenerate header if the content was modified. */
2651 if (csp->flags & CSP_FLAG_MODIFIED)
2654 *header = (char *) zalloc(max_header_length);
2655 if (*header == NULL)
2657 return JB_ERR_MEMORY;
2660 snprintf(*header, max_header_length, "Content-Length: %d",
2661 (int)csp->content_length);
2662 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2663 (int)csp->content_length);
2670 /*********************************************************************
2672 * Function : server_content_md5
2674 * Description : Crumble any Content-MD5 headers if the document was
2675 * modified. FIXME: Should we re-compute instead?
2678 * 1 : csp = Current client state (buffers, headers, etc...)
2679 * 2 : header = On input, pointer to header to modify.
2680 * On output, pointer to the modified header, or NULL
2681 * to remove the header. This function frees the
2682 * original string if necessary.
2684 * Returns : JB_ERR_OK on success, or
2685 * JB_ERR_MEMORY on out-of-memory error.
2687 *********************************************************************/
2688 static jb_err server_content_md5(struct client_state *csp, char **header)
2690 if (csp->flags & CSP_FLAG_MODIFIED)
2692 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2700 /*********************************************************************
2702 * Function : server_content_disposition
2704 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2705 * Called from `sed'.
2708 * 1 : csp = Current client state (buffers, headers, etc...)
2709 * 2 : header = On input, pointer to header to modify.
2710 * On output, pointer to the modified header, or NULL
2711 * to remove the header. This function frees the
2712 * original string if necessary.
2714 * Returns : JB_ERR_OK on success, or
2715 * JB_ERR_MEMORY on out-of-memory error.
2717 *********************************************************************/
2718 static jb_err server_content_disposition(struct client_state *csp, char **header)
2723 * Are we messing with the Content-Disposition header?
2725 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2731 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2733 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2736 * Blocking content-disposition header
2738 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2745 * Replacing Content-Disposition header
2748 *header = strdup("Content-Disposition: ");
2749 string_append(header, newval);
2751 if (*header != NULL)
2753 log_error(LOG_LEVEL_HEADER,
2754 "Content-Disposition header crunched and replaced with: %s", *header);
2757 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2761 /*********************************************************************
2763 * Function : server_last_modified
2765 * Description : Changes Last-Modified header to the actual date
2766 * to help hide-if-modified-since.
2767 * Called from `sed'.
2770 * 1 : csp = Current client state (buffers, headers, etc...)
2771 * 2 : header = On input, pointer to header to modify.
2772 * On output, pointer to the modified header, or NULL
2773 * to remove the header. This function frees the
2774 * original string if necessary.
2776 * Returns : JB_ERR_OK on success, or
2777 * JB_ERR_MEMORY on out-of-memory error.
2779 *********************************************************************/
2780 static jb_err server_last_modified(struct client_state *csp, char **header)
2783 char buf[BUFFER_SIZE];
2786 #ifdef HAVE_GMTIME_R
2789 struct tm *timeptr = NULL;
2790 time_t now, last_modified;
2792 long int days, hours, minutes, seconds;
2795 * Are we messing with the Last-Modified header?
2797 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2803 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2805 if (0 == strcmpic(newval, "block") )
2808 * Blocking Last-Modified header. Useless but why not.
2810 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2814 else if (0 == strcmpic(newval, "reset-to-request-time"))
2817 * Setting Last-Modified Header to now.
2819 get_http_time(0, buf, sizeof(buf));
2821 *header = strdup("Last-Modified: ");
2822 string_append(header, buf);
2824 if (*header == NULL)
2826 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2830 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2833 else if (0 == strcmpic(newval, "randomize"))
2835 const char *header_time = *header + sizeof("Last-Modified:");
2837 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2839 #ifdef HAVE_GMTIME_R
2840 timeptr = gmtime_r(&now, &gmt);
2841 #elif FEATURE_PTHREAD
2842 pthread_mutex_lock(&gmtime_mutex);
2843 timeptr = gmtime(&now);
2844 pthread_mutex_unlock(&gmtime_mutex);
2846 timeptr = gmtime(&now);
2848 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2850 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2855 rtime = (long int)difftime(now, last_modified);
2864 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2866 rtime = pick_from_range(rtime);
2867 if (negative) rtime *= -1;
2868 last_modified += rtime;
2869 #ifdef HAVE_GMTIME_R
2870 timeptr = gmtime_r(&last_modified, &gmt);
2871 #elif FEATURE_PTHREAD
2872 pthread_mutex_lock(&gmtime_mutex);
2873 timeptr = gmtime(&last_modified);
2874 pthread_mutex_unlock(&gmtime_mutex);
2876 timeptr = gmtime(&last_modified);
2878 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2880 *header = strdup("Last-Modified: ");
2881 string_append(header, newheader);
2883 if (*header == NULL)
2885 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2886 return JB_ERR_MEMORY;
2889 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2891 days = rtime / (3600 * 24);
2892 hours = rtime / 3600 % 24;
2893 minutes = rtime / 60 % 60;
2894 seconds = rtime % 60;
2896 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2897 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2898 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2903 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2912 /*********************************************************************
2914 * Function : client_accept_encoding
2916 * Description : Rewrite the client's Accept-Encoding header so that
2917 * if doesn't allow compression, if the action applies.
2918 * Note: For HTTP/1.0 the absence of the header is enough.
2921 * 1 : csp = Current client state (buffers, headers, etc...)
2922 * 2 : header = On input, pointer to header to modify.
2923 * On output, pointer to the modified header, or NULL
2924 * to remove the header. This function frees the
2925 * original string if necessary.
2927 * Returns : JB_ERR_OK on success, or
2928 * JB_ERR_MEMORY on out-of-memory error.
2930 *********************************************************************/
2931 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2933 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2935 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2939 /* Temporarily disable the correct behaviour to
2940 * work around a PHP bug.
2942 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2944 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2945 * if (*header == NULL)
2947 * return JB_ERR_MEMORY;
2958 /*********************************************************************
2960 * Function : client_te
2962 * Description : Rewrite the client's TE header so that
2963 * if doesn't allow compression, if the action applies.
2966 * 1 : csp = Current client state (buffers, headers, etc...)
2967 * 2 : header = On input, pointer to header to modify.
2968 * On output, pointer to the modified header, or NULL
2969 * to remove the header. This function frees the
2970 * original string if necessary.
2972 * Returns : JB_ERR_OK on success, or
2973 * JB_ERR_MEMORY on out-of-memory error.
2975 *********************************************************************/
2976 static jb_err client_te(struct client_state *csp, char **header)
2978 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2981 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2988 /*********************************************************************
2990 * Function : client_referrer
2992 * Description : Handle the "referer" config setting properly.
2993 * Called from `sed'.
2996 * 1 : csp = Current client state (buffers, headers, etc...)
2997 * 2 : header = On input, pointer to header to modify.
2998 * On output, pointer to the modified header, or NULL
2999 * to remove the header. This function frees the
3000 * original string if necessary.
3002 * Returns : JB_ERR_OK on success, or
3003 * JB_ERR_MEMORY on out-of-memory error.
3005 *********************************************************************/
3006 static jb_err client_referrer(struct client_state *csp, char **header)
3008 const char *parameter;
3009 /* booleans for parameters we have to check multiple times */
3010 int parameter_conditional_block;
3011 int parameter_conditional_forge;
3013 #ifdef FEATURE_FORCE_LOAD
3015 * Since the referrer can include the prefix even
3016 * if the request itself is non-forced, we must
3017 * clean it unconditionally.
3019 * XXX: strclean is too broad
3021 strclean(*header, FORCE_PREFIX);
3022 #endif /* def FEATURE_FORCE_LOAD */
3024 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3026 /* Nothing left to do */
3030 parameter = csp->action->string[ACTION_STRING_REFERER];
3031 assert(parameter != NULL);
3032 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3033 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3035 if (!parameter_conditional_block && !parameter_conditional_forge)
3038 * As conditional-block and conditional-forge are the only
3039 * parameters that rely on the original referrer, we can
3040 * remove it now for all the others.
3045 if (0 == strcmpic(parameter, "block"))
3047 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3050 else if (parameter_conditional_block || parameter_conditional_forge)
3052 return handle_conditional_hide_referrer_parameter(header,
3053 csp->http->hostport, parameter_conditional_block);
3055 else if (0 == strcmpic(parameter, "forge"))
3057 return create_forged_referrer(header, csp->http->hostport);
3061 /* interpret parameter as user-supplied referer to fake */
3062 return create_fake_referrer(header, parameter);
3067 /*********************************************************************
3069 * Function : client_accept_language
3071 * Description : Handle the "Accept-Language" config setting properly.
3072 * Called from `sed'.
3075 * 1 : csp = Current client state (buffers, headers, etc...)
3076 * 2 : header = On input, pointer to header to modify.
3077 * On output, pointer to the modified header, or NULL
3078 * to remove the header. This function frees the
3079 * original string if necessary.
3081 * Returns : JB_ERR_OK on success, or
3082 * JB_ERR_MEMORY on out-of-memory error.
3084 *********************************************************************/
3085 static jb_err client_accept_language(struct client_state *csp, char **header)
3090 * Are we messing with the Accept-Language?
3092 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3094 /*I don't think so*/
3098 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3100 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3103 * Blocking Accept-Language header
3105 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3112 * Replacing Accept-Language header
3115 *header = strdup("Accept-Language: ");
3116 string_append(header, newval);
3118 if (*header == NULL)
3120 log_error(LOG_LEVEL_ERROR,
3121 "Insufficent memory. Accept-Language header crunched without replacement.");
3125 log_error(LOG_LEVEL_HEADER,
3126 "Accept-Language header crunched and replaced with: %s", *header);
3129 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3133 /*********************************************************************
3135 * Function : crunch_client_header
3137 * Description : Crunch client header if it matches a string supplied by the
3138 * user. Called from `sed'.
3141 * 1 : csp = Current client state (buffers, headers, etc...)
3142 * 2 : header = On input, pointer to header to modify.
3143 * On output, pointer to the modified header, or NULL
3144 * to remove the header. This function frees the
3145 * original string if necessary.
3147 * Returns : JB_ERR_OK on success and always succeeds
3149 *********************************************************************/
3150 static jb_err crunch_client_header(struct client_state *csp, char **header)
3152 const char *crunch_pattern;
3154 /* Do we feel like crunching? */
3155 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3157 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3159 /* Is the current header the lucky one? */
3160 if (strstr(*header, crunch_pattern))
3162 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3170 /*********************************************************************
3172 * Function : client_uagent
3174 * Description : Handle the "user-agent" config setting properly
3175 * and remember its original value to enable browser
3176 * bug workarounds. Called from `sed'.
3179 * 1 : csp = Current client state (buffers, headers, etc...)
3180 * 2 : header = On input, pointer to header to modify.
3181 * On output, pointer to the modified header, or NULL
3182 * to remove the header. This function frees the
3183 * original string if necessary.
3185 * Returns : JB_ERR_OK on success, or
3186 * JB_ERR_MEMORY on out-of-memory error.
3188 *********************************************************************/
3189 static jb_err client_uagent(struct client_state *csp, char **header)
3193 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3198 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3205 *header = strdup("User-Agent: ");
3206 string_append(header, newval);
3208 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3210 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3214 /*********************************************************************
3216 * Function : client_ua
3218 * Description : Handle "ua-" headers properly. Called from `sed'.
3221 * 1 : csp = Current client state (buffers, headers, etc...)
3222 * 2 : header = On input, pointer to header to modify.
3223 * On output, pointer to the modified header, or NULL
3224 * to remove the header. This function frees the
3225 * original string if necessary.
3227 * Returns : JB_ERR_OK on success, or
3228 * JB_ERR_MEMORY on out-of-memory error.
3230 *********************************************************************/
3231 static jb_err client_ua(struct client_state *csp, char **header)
3233 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3235 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3243 /*********************************************************************
3245 * Function : client_from
3247 * Description : Handle the "from" config setting properly.
3248 * Called from `sed'.
3251 * 1 : csp = Current client state (buffers, headers, etc...)
3252 * 2 : header = On input, pointer to header to modify.
3253 * On output, pointer to the modified header, or NULL
3254 * to remove the header. This function frees the
3255 * original string if necessary.
3257 * Returns : JB_ERR_OK on success, or
3258 * JB_ERR_MEMORY on out-of-memory error.
3260 *********************************************************************/
3261 static jb_err client_from(struct client_state *csp, char **header)
3265 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3272 newval = csp->action->string[ACTION_STRING_FROM];
3275 * Are we blocking the e-mail address?
3277 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3279 log_error(LOG_LEVEL_HEADER, "crunched From!");
3283 log_error(LOG_LEVEL_HEADER, " modified");
3285 *header = strdup("From: ");
3286 string_append(header, newval);
3288 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3292 /*********************************************************************
3294 * Function : client_send_cookie
3296 * Description : Crunches the "cookie" header if necessary.
3297 * Called from `sed'.
3299 * XXX: Stupid name, doesn't send squat.
3302 * 1 : csp = Current client state (buffers, headers, etc...)
3303 * 2 : header = On input, pointer to header to modify.
3304 * On output, pointer to the modified header, or NULL
3305 * to remove the header. This function frees the
3306 * original string if necessary.
3308 * Returns : JB_ERR_OK on success, or
3309 * JB_ERR_MEMORY on out-of-memory error.
3311 *********************************************************************/
3312 static jb_err client_send_cookie(struct client_state *csp, char **header)
3314 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3316 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3324 /*********************************************************************
3326 * Function : client_x_forwarded
3328 * Description : Handle the "x-forwarded-for" config setting properly,
3329 * also used in the add_client_headers list. Called from `sed'.
3332 * 1 : csp = Current client state (buffers, headers, etc...)
3333 * 2 : header = On input, pointer to header to modify.
3334 * On output, pointer to the modified header, or NULL
3335 * to remove the header. This function frees the
3336 * original string if necessary.
3338 * Returns : JB_ERR_OK on success, or
3339 * JB_ERR_MEMORY on out-of-memory error.
3341 *********************************************************************/
3342 jb_err client_x_forwarded(struct client_state *csp, char **header)
3344 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3347 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3354 /*********************************************************************
3356 * Function : client_max_forwards
3358 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3359 * from the value of the Max-Forwards header field.
3362 * 1 : csp = Current client state (buffers, headers, etc...)
3363 * 2 : header = On input, pointer to header to modify.
3364 * On output, pointer to the modified header, or NULL
3365 * to remove the header. This function frees the
3366 * original string if necessary.
3368 * Returns : JB_ERR_OK on success, or
3369 * JB_ERR_MEMORY on out-of-memory error.
3371 *********************************************************************/
3372 static jb_err client_max_forwards(struct client_state *csp, char **header)
3376 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3377 (0 == strcmpic(csp->http->gpc, "options")))
3379 assert(*(*header+12) == ':');
3380 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3382 if (max_forwards > 0)
3384 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3385 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3386 csp->http->gpc, max_forwards);
3388 else if (max_forwards < 0)
3390 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3396 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3405 /*********************************************************************
3407 * Function : client_host
3409 * Description : If the request URI did not contain host and
3410 * port information, parse and evaluate the Host
3413 * Also, kill ill-formed HOST: headers as sent by
3414 * Apple's iTunes software when used with a proxy.
3417 * 1 : csp = Current client state (buffers, headers, etc...)
3418 * 2 : header = On input, pointer to header to modify.
3419 * On output, pointer to the modified header, or NULL
3420 * to remove the header. This function frees the
3421 * original string if necessary.
3423 * Returns : JB_ERR_OK on success, or
3424 * JB_ERR_MEMORY on out-of-memory error.
3426 *********************************************************************/
3427 static jb_err client_host(struct client_state *csp, char **header)
3432 * If the header field name is all upper-case, chances are that it's
3433 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3434 * not a problem -- they are regenerated later.
3436 if ((*header)[1] == 'O')
3438 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3443 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3444 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3447 if (NULL == (p = strdup((*header)+6)))
3449 return JB_ERR_MEMORY;
3452 if (NULL == (q = strdup(p)))
3455 return JB_ERR_MEMORY;
3458 freez(csp->http->hostport);
3459 csp->http->hostport = p;
3460 freez(csp->http->host);
3461 csp->http->host = q;
3462 q = strchr(csp->http->host, ':');
3465 /* Terminate hostname and evaluate port string */
3467 csp->http->port = atoi(q);
3471 csp->http->port = csp->http->ssl ? 443 : 80;
3474 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3475 csp->http->hostport, csp->http->host, csp->http->port);
3478 /* Signal client_host_adder() to return right away */
3479 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3485 /*********************************************************************
3487 * Function : client_if_modified_since
3489 * Description : Remove or modify the If-Modified-Since header.
3492 * 1 : csp = Current client state (buffers, headers, etc...)
3493 * 2 : header = On input, pointer to header to modify.
3494 * On output, pointer to the modified header, or NULL
3495 * to remove the header. This function frees the
3496 * original string if necessary.
3498 * Returns : JB_ERR_OK on success, or
3499 * JB_ERR_MEMORY on out-of-memory error.
3501 *********************************************************************/
3502 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3505 #ifdef HAVE_GMTIME_R
3508 struct tm *timeptr = NULL;
3512 long int hours, minutes, seconds;
3516 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3519 * The client got an error message because of a temporary problem,
3520 * the problem is gone and the client now tries to revalidate our
3521 * error message on the real server. The revalidation would always
3522 * end with the transmission of the whole document and there is
3523 * no need to expose the bogus If-Modified-Since header.
3525 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3528 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3530 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3532 if ((0 == strcmpic(newval, "block")))
3534 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3537 else /* add random value */
3539 const char *header_time = *header + sizeof("If-Modified-Since:");
3541 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3543 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3548 rtime = strtol(newval, &endptr, 0);
3551 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3552 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3559 rtime = pick_from_range(rtime);
3563 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3566 tm += rtime * (negative ? -1 : 1);
3567 #ifdef HAVE_GMTIME_R
3568 timeptr = gmtime_r(&tm, &gmt);
3569 #elif FEATURE_PTHREAD
3570 pthread_mutex_lock(&gmtime_mutex);
3571 timeptr = gmtime(&tm);
3572 pthread_mutex_unlock(&gmtime_mutex);
3574 timeptr = gmtime(&tm);
3576 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3579 *header = strdup("If-Modified-Since: ");
3580 string_append(header, newheader);
3582 if (*header == NULL)
3584 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3585 return JB_ERR_MEMORY;
3588 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3590 hours = rtime / 3600;
3591 minutes = rtime / 60 % 60;
3592 seconds = rtime % 60;
3594 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3595 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3596 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3606 /*********************************************************************
3608 * Function : client_if_none_match
3610 * Description : Remove the If-None-Match header.
3613 * 1 : csp = Current client state (buffers, headers, etc...)
3614 * 2 : header = On input, pointer to header to modify.
3615 * On output, pointer to the modified header, or NULL
3616 * to remove the header. This function frees the
3617 * original string if necessary.
3619 * Returns : JB_ERR_OK on success, or
3620 * JB_ERR_MEMORY on out-of-memory error.
3622 *********************************************************************/
3623 static jb_err client_if_none_match(struct client_state *csp, char **header)
3625 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3627 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3635 /*********************************************************************
3637 * Function : client_x_filter
3639 * Description : Disables filtering if the client set "X-Filter: No".
3640 * Called from `sed'.
3643 * 1 : csp = Current client state (buffers, headers, etc...)
3644 * 2 : header = On input, pointer to header to modify.
3645 * On output, pointer to the modified header, or NULL
3646 * to remove the header. This function frees the
3647 * original string if necessary.
3649 * Returns : JB_ERR_OK on success
3651 *********************************************************************/
3652 jb_err client_x_filter(struct client_state *csp, char **header)
3654 if ( 0 == strcmpic(*header, "X-Filter: No"))
3656 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3658 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3662 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3664 log_error(LOG_LEVEL_HEADER,
3665 "force-text-mode overruled the client's request to fetch without filtering!");
3669 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3670 csp->flags |= CSP_FLAG_NO_FILTERING;
3671 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3673 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3681 /*********************************************************************
3683 * Function : client_range
3685 * Description : Removes Range, Request-Range and If-Range headers if
3686 * content filtering is enabled. If the client's version
3687 * of the document has been altered by Privoxy, the server
3688 * could interpret the range differently than the client
3689 * intended in which case the user could end up with
3690 * corrupted content.
3693 * 1 : csp = Current client state (buffers, headers, etc...)
3694 * 2 : header = On input, pointer to header to modify.
3695 * On output, pointer to the modified header, or NULL
3696 * to remove the header. This function frees the
3697 * original string if necessary.
3699 * Returns : JB_ERR_OK
3701 *********************************************************************/
3702 static jb_err client_range(struct client_state *csp, char **header)
3704 if (content_filters_enabled(csp->action))
3706 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3707 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3714 /* the following functions add headers directly to the header list */
3716 /*********************************************************************
3718 * Function : client_host_adder
3720 * Description : Adds the Host: header field if it is missing.
3721 * Called from `sed'.
3724 * 1 : csp = Current client state (buffers, headers, etc...)
3726 * Returns : JB_ERR_OK on success, or
3727 * JB_ERR_MEMORY on out-of-memory error.
3729 *********************************************************************/
3730 static jb_err client_host_adder(struct client_state *csp)
3735 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3737 /* Header already set by the client, nothing to do. */
3741 if ( !csp->http->hostport || !*(csp->http->hostport))
3743 /* XXX: When does this happen and why is it OK? */
3744 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3749 * remove 'user:pass@' from 'proto://user:pass@host'
3751 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3757 p = csp->http->hostport;
3760 /* XXX: Just add it, we already made sure that it will be unique */
3761 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3762 err = enlist_unique_header(csp->headers, "Host", p);
3769 /*********************************************************************
3771 * Function : client_accept_encoding_adder
3773 * Description : Add an Accept-Encoding header to the client's request
3774 * that disables compression if the action applies, and
3775 * the header is not already there. Called from `sed'.
3776 * Note: For HTTP/1.0, the absence of the header is enough.
3779 * 1 : csp = Current client state (buffers, headers, etc...)
3781 * Returns : JB_ERR_OK on success, or
3782 * JB_ERR_MEMORY on out-of-memory error.
3784 *********************************************************************/
3785 static jb_err client_accept_encoding_adder(struct client_state *csp)
3787 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3788 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3790 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3798 /*********************************************************************
3800 * Function : client_xtra_adder
3802 * Description : Used in the add_client_headers list. Called from `sed'.
3805 * 1 : csp = Current client state (buffers, headers, etc...)
3807 * Returns : JB_ERR_OK on success, or
3808 * JB_ERR_MEMORY on out-of-memory error.
3810 *********************************************************************/
3811 static jb_err client_xtra_adder(struct client_state *csp)
3813 struct list_entry *lst;
3816 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3817 lst ; lst = lst->next)
3819 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3820 err = enlist(csp->headers, lst->str);
3832 /*********************************************************************
3834 * Function : connection_close_adder
3836 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3837 * support. Adds a "Connection: close" header to csp->headers
3838 * unless the header was already present. Called from `sed'.
3840 * FIXME: This whole function shouldn't be neccessary!
3843 * 1 : csp = Current client state (buffers, headers, etc...)
3845 * Returns : JB_ERR_OK on success, or
3846 * JB_ERR_MEMORY on out-of-memory error.
3848 *********************************************************************/
3849 static jb_err connection_close_adder(struct client_state *csp)
3851 const unsigned int flags = csp->flags;
3854 * Return right away if
3856 * - we're parsing server headers and the server header
3857 * "Connection: close" is already set, or if
3859 * - we're parsing client headers and the client header
3860 * "Connection: close" is already set.
3862 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3863 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3864 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3865 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3870 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3872 return enlist(csp->headers, "Connection: close");
3876 /*********************************************************************
3878 * Function : server_http
3880 * Description : - Save the HTTP Status into csp->http->status
3881 * - Set CT_TABOO to prevent filtering if the answer
3882 * is a partial range (HTTP status 206)
3883 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3887 * 1 : csp = Current client state (buffers, headers, etc...)
3888 * 2 : header = On input, pointer to header to modify.
3889 * On output, pointer to the modified header, or NULL
3890 * to remove the header. This function frees the
3891 * original string if necessary.
3893 * Returns : JB_ERR_OK on success, or
3894 * JB_ERR_MEMORY on out-of-memory error.
3896 *********************************************************************/
3897 static jb_err server_http(struct client_state *csp, char **header)
3899 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3900 if (csp->http->status == 206)
3902 csp->content_type = CT_TABOO;
3905 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3907 /* XXX: Should we do a real validity check here? */
3908 if (strlen(*header) > 8)
3911 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3916 * XXX: Should we block the request or
3917 * enlist a valid status code line here?
3919 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3920 "Downgrading to HTTP/1.0 impossible.");
3928 /*********************************************************************
3930 * Function : server_set_cookie
3932 * Description : Handle the server "cookie" header properly.
3933 * Log cookie to the jar file. Then "crunch",
3934 * accept or rewrite it to a session cookie.
3935 * Called from `sed'.
3937 * TODO: Allow the user to specify a new expiration
3938 * time to cause the cookie to expire even before the
3939 * browser is closed.
3942 * 1 : csp = Current client state (buffers, headers, etc...)
3943 * 2 : header = On input, pointer to header to modify.
3944 * On output, pointer to the modified header, or NULL
3945 * to remove the header. This function frees the
3946 * original string if necessary.
3948 * Returns : JB_ERR_OK on success, or
3949 * JB_ERR_MEMORY on out-of-memory error.
3951 *********************************************************************/
3952 static jb_err server_set_cookie(struct client_state *csp, char **header)
3959 #ifdef FEATURE_COOKIE_JAR
3960 if (csp->config->jar)
3963 * Write timestamp into outbuf.
3965 * Complex because not all OSs have tm_gmtoff or
3966 * the %z field in strftime()
3968 char tempbuf[ BUFFER_SIZE ];
3970 #ifdef HAVE_LOCALTIME_R
3971 tm_now = *localtime_r(&now, &tm_now);
3972 #elif FEATURE_PTHREAD
3973 pthread_mutex_lock(&localtime_mutex);
3974 tm_now = *localtime (&now);
3975 pthread_mutex_unlock(&localtime_mutex);
3977 tm_now = *localtime (&now);
3979 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3981 /* strlen("set-cookie: ") = 12 */
3982 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3984 #endif /* def FEATURE_COOKIE_JAR */
3986 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3988 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3991 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3993 /* Flag whether or not to log a message */
3996 /* A variable to store the tag we're working on */
3999 /* Skip "Set-Cookie:" (11 characters) in header */
4000 cur_tag = *header + 11;
4002 /* skip whitespace between "Set-Cookie:" and value */
4003 while (*cur_tag && ijb_isspace(*cur_tag))
4008 /* Loop through each tag in the cookie */
4012 char *next_tag = strchr(cur_tag, ';');
4013 if (next_tag != NULL)
4015 /* Skip the ';' character itself */
4018 /* skip whitespace ";" and start of tag */
4019 while (*next_tag && ijb_isspace(*next_tag))
4026 /* "Next tag" is the end of the string */
4027 next_tag = cur_tag + strlen(cur_tag);
4031 * Check the expiration date to see
4032 * if the cookie is still valid, if yes,
4033 * rewrite it to a session cookie.
4035 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4037 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4039 /* Did we detect the date properly? */
4040 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4043 * Nope, treat it as if it was still valid.
4045 * XXX: Should we remove the whole cookie instead?
4047 log_error(LOG_LEVEL_ERROR,
4048 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4049 string_move(cur_tag, next_tag);
4055 * Yes. Check if the cookie is still valid.
4057 * If the cookie is already expired it's probably
4058 * a delete cookie and even if it isn't, the browser
4059 * will discard it anyway.
4063 * XXX: timegm() isn't available on some AmigaOS
4064 * versions and our replacement doesn't work.
4066 * Our options are to either:
4068 * - disable session-cookies-only completely if timegm
4071 * - to simply remove all expired tags, like it has
4072 * been done until Privoxy 3.0.6 and to live with
4073 * the consequence that it can cause login/logout
4074 * problems on servers that don't validate their
4075 * input properly, or
4077 * - to replace it with mktime in which
4078 * case there is a slight chance of valid cookies
4079 * passing as already expired.
4081 * This is the way it's currently done and it's not
4082 * as bad as it sounds. If the missing GMT offset is
4083 * enough to change the result of the expiration check
4084 * the cookie will be only valid for a few hours
4085 * anyway, which in many cases will be shorter
4086 * than a browser session.
4088 if (cookie_time - now < 0)
4090 log_error(LOG_LEVEL_HEADER,
4091 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4092 /* Just in case some clown sets more then one expiration date */
4098 * Still valid, delete expiration date by copying
4099 * the rest of the string over it.
4101 string_move(cur_tag, next_tag);
4103 /* That changed the header, need to issue a log message */
4107 * Note that the next tag has now been moved to *cur_tag,
4108 * so we do not need to update the cur_tag pointer.
4116 /* Move on to next cookie tag */
4123 assert(NULL != *header);
4124 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4133 #ifdef FEATURE_FORCE_LOAD
4134 /*********************************************************************
4136 * Function : strclean
4138 * Description : In-Situ-Eliminate all occurances of substring in
4142 * 1 : string = string to clean
4143 * 2 : substring = substring to eliminate
4145 * Returns : Number of eliminations
4147 *********************************************************************/
4148 int strclean(const char *string, const char *substring)
4154 len = strlen(substring);
4156 while((pos = strstr(string, substring)) != NULL)
4163 while (*p++ != '\0');
4170 #endif /* def FEATURE_FORCE_LOAD */
4173 /*********************************************************************
4175 * Function : parse_header_time
4177 * Description : Parses time formats used in HTTP header strings
4178 * to get the numerical respresentation.
4181 * 1 : header_time = HTTP header time as string.
4182 * 2 : result = storage for header_time in seconds
4184 * Returns : JB_ERR_OK if the time format was recognized, or
4185 * JB_ERR_PARSE otherwise.
4187 *********************************************************************/
4188 static jb_err parse_header_time(const char *header_time, time_t *result)
4193 * Zero out gmt to prevent time zone offsets.
4195 * While this is only necessary on some platforms
4196 * (mingw32 for example), I don't know how to
4197 * detect these automatically and doing it everywhere
4200 memset(&gmt, 0, sizeof(gmt));
4202 /* Tue, 02 Jun 2037 20:00:00 */
4203 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4204 /* Tue, 02-Jun-2037 20:00:00 */
4205 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4206 /* Tue, 02-Jun-37 20:00:00 */
4207 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4208 /* Tuesday, 02-Jun-2037 20:00:00 */
4209 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4210 /* Tuesday Jun 02 20:00:00 2037 */
4211 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4213 return JB_ERR_PARSE;
4216 *result = timegm(&gmt);
4223 /*********************************************************************
4225 * Function : get_destination_from_headers
4227 * Description : Parse the "Host:" header to get the request's destination.
4228 * Only needed if the client's request was forcefully
4229 * redirected into Privoxy.
4231 * Code mainly copied from client_host() which is currently
4232 * run too late for this purpose.
4235 * 1 : headers = List of headers (one of them hopefully being
4236 * the "Host:" header)
4237 * 2 : http = storage for the result (host, port and hostport).
4239 * Returns : JB_ERR_MEMORY in case of memory problems,
4240 * JB_ERR_PARSE if the host header couldn't be found,
4241 * JB_ERR_OK otherwise.
4243 *********************************************************************/
4244 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4250 host = get_header_value(headers, "Host:");
4254 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4255 return JB_ERR_PARSE;
4258 if (NULL == (p = strdup((host))))
4260 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4261 return JB_ERR_MEMORY;
4264 if (NULL == (q = strdup(p)))
4267 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4268 return JB_ERR_MEMORY;
4271 freez(http->hostport);
4275 q = strchr(http->host, ':');
4278 /* Terminate hostname and evaluate port string */
4280 http->port = atoi(q);
4284 http->port = http->ssl ? 443 : 80;
4287 /* Rebuild request URL */
4289 http->url = strdup(http->ssl ? "https://" : "http://");
4290 string_append(&http->url, http->hostport);
4291 string_append(&http->url, http->path);
4292 if (http->url == NULL)
4294 return JB_ERR_MEMORY;
4297 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4305 /*********************************************************************
4307 * Function : create_forged_referrer
4309 * Description : Helper for client_referrer to forge a referer as
4310 * 'http://[hostname:port/' to fool stupid
4311 * checks for in-site links
4314 * 1 : header = Pointer to header pointer
4315 * 2 : hostport = Host and optionally port as string
4317 * Returns : JB_ERR_OK in case of success, or
4318 * JB_ERR_MEMORY in case of memory problems.
4320 *********************************************************************/
4321 static jb_err create_forged_referrer(char **header, const char *hostport)
4323 assert(NULL == *header);
4325 *header = strdup("Referer: http://");
4326 string_append(header, hostport);
4327 string_append(header, "/");
4329 if (NULL == *header)
4331 return JB_ERR_MEMORY;
4334 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4341 /*********************************************************************
4343 * Function : create_fake_referrer
4345 * Description : Helper for client_referrer to create a fake referrer
4346 * based on a string supplied by the user.
4349 * 1 : header = Pointer to header pointer
4350 * 2 : hosthost = Referrer to fake
4352 * Returns : JB_ERR_OK in case of success, or
4353 * JB_ERR_MEMORY in case of memory problems.
4355 *********************************************************************/
4356 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4358 assert(NULL == *header);
4360 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4362 log_error(LOG_LEVEL_HEADER,
4363 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4365 *header = strdup("Referer: ");
4366 string_append(header, fake_referrer);
4368 if (NULL == *header)
4370 return JB_ERR_MEMORY;
4373 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4380 /*********************************************************************
4382 * Function : handle_conditional_hide_referrer_parameter
4384 * Description : Helper for client_referrer to crunch or forge
4385 * the referrer header if the host has changed.
4388 * 1 : header = Pointer to header pointer
4389 * 2 : host = The target host (may include the port)
4390 * 3 : parameter_conditional_block = Boolean to signal
4391 * if we're in conditional-block mode. If not set,
4392 * we're in conditional-forge mode.
4394 * Returns : JB_ERR_OK in case of success, or
4395 * JB_ERR_MEMORY in case of memory problems.
4397 *********************************************************************/
4398 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4399 const char *host, const int parameter_conditional_block)
4401 char *referer = strdup(*header);
4402 const size_t hostlenght = strlen(host);
4404 if (NULL == referer)
4407 return JB_ERR_MEMORY;
4410 /* referer begins with 'Referer: http[s]://' */
4411 if (hostlenght < (strlen(referer)-17))
4414 * Shorten referer to make sure the referer is blocked
4415 * if www.example.org/www.example.com-shall-see-the-referer/
4416 * links to www.example.com/
4418 referer[hostlenght+17] = '\0';
4420 if (NULL == strstr(referer, host))
4422 /* Host has changed */
4423 if (parameter_conditional_block)
4425 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4432 return create_forged_referrer(header, host);