1 const char parsers_rcs[] = "$Id: parsers.c,v 1.136 2008/05/26 16:02:24 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.136 2008/05/26 16:02:24 fabiankeil
48 * s@Insufficent@Insufficient@
50 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
51 * The whole point of strclean() is to modify the
52 * first parameter, so don't mark it immutable,
53 * even though the compiler lets us get away with it.
55 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
56 * As the wafer actions are gone, we can stop including encode.h.
58 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
59 * Ditch cast from (char **) to (char **).
61 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
62 * Streamline sed()'s prototype and declare
63 * the header parse and add structures static.
65 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
66 * Factor update_server_headers() out of sed(), ditch the
67 * first_run hack and make server_patterns_light static.
69 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
70 * Wrap memmove() calls in string_move()
71 * to document the purpose in one place.
73 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
74 * Normalize linear header white space.
76 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
77 * If a header is split across multiple lines,
78 * merge them to a single line before parsing them.
80 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
81 * Don't provide get_header() with the whole client state
82 * structure when it only needs access to csp->iob.
84 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
85 * Change content_filters_enabled()'s parameter from
86 * csp->action to action so it can be also used in the
87 * CGI code. Don't bother checking if there are filters
88 * loaded, as that's somewhat besides the point.
90 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
91 * Provide get_http_time() with the buffer size so it doesn't
92 * have to blindly assume that the buffer is big enough.
94 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
95 * Don't pass the whole csp structure to flush_socket()
96 * when it only needs a file descriptor and a buffer.
98 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
99 * Remove send-wafer and send-vanilla-wafer actions.
101 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
102 * Remove inspect-jpegs action.
104 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
105 * Let client_range() also handle Request-Range headers
106 * which apparently are still supported by many servers.
108 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
109 * Improve the warning messages that get logged if the action files
110 * "enable" filters but no filters of that type have been loaded.
112 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
113 * In server_content_type():
114 * - Don't require leading white space when detecting image content types.
115 * - Change '... not replaced ...' message to sound less crazy if the text
116 * type actually is 'text/plain'.
117 * - Mark the 'text/plain == binary data' assumption for removal.
118 * - Remove a bunch of trailing white space.
120 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
121 * Minor server_content_disposition() changes:
122 * - Don't regenerate the header name all lower-case.
123 * - Some white space fixes.
124 * - Remove useless log message in case of ENOMEM.
126 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
127 * Garbage-collect the code to add a X-Forwarded-For
128 * header as it seems to be mostly used by accident.
130 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
131 * Fix a crash on mingw32 with some Last Modified times in the future.
133 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
134 * Remove a "can't happen" error block which, over
135 * time, mutated into a "guaranteed to happen" block.
137 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
138 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
139 * - Use shiny new content_filters_enabled() in client_range().
141 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
142 * I forgot about Poland.
144 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
145 * Remove Range and If-Range headers if content filtering is enabled.
147 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
148 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
149 * client_cookie_adder() to make sure send-vanilla-wafer can be
150 * controlled through tags (and thus regression-tested).
152 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
153 * - Remove "scanning headers for" log message again.
154 * - Some more whitespace fixes.
156 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
157 * Refactor client_referrer() and add conditional-forge parameter.
159 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
160 * A bunch of whitespace fixes, pointy hat to me.
162 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
163 * Fix possible memory corruption in server_http, make sure it's not
164 * executed for ordinary server headers and mark some problems for later.
166 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
167 * Let content-type-overwrite{} honour force-text-mode again.
169 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
170 * - Add prototpyes for the header parsers and make them static.
171 * - Comment out client_accept_encoding_adder() which isn't used right now.
173 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
174 * Move the ACTION_FORCE_TEXT_MODE check out of
175 * server_content_type(). Signal other functions
176 * whether or not a content type has been declared.
177 * Part of the fix for BR#1750917.
179 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
180 * Change sed() to return a jb_err in preparation for forward-override{}.
182 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
183 * Adjust "X-Filter: No" to disable dedicated header filters.
185 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
186 * Streamline client_cookie_adder().
188 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
189 * Make sure filters with dynamic jobs actually use them.
191 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
192 * - Introduce dynamic pcrs jobs that can resolve variables.
193 * - Remove unnecessary update_action_bits_for_all_tags() call.
195 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
196 * - Make tagging based on tags set by earlier taggers
197 * of the same kind possible.
198 * - Log whether or not new tags cause action bits updates
199 * (in which case a matching tag-pattern section exists).
200 * - Log if the user tries to set a tag that is already set.
202 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
203 * Introduce tags as alternative way to specify which
204 * actions apply to a request. At the moment tags can be
205 * created based on client and server headers.
207 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
208 * Log a warning if the content is compressed, filtering is
209 * enabled and Privoxy was compiled without zlib support.
212 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
213 * - Fix warnings when compiled with glibc.
214 * - Don't use crumble() for cookie crunching.
215 * - Move cookie time parsing into parse_header_time().
216 * - Let parse_header_time() return a jb_err code
217 * instead of a pointer that can only be used to
218 * check for NULL anyway.
220 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
221 * - Add better protection against malicious gzip headers.
222 * - Stop logging the first hundred bytes of decompressed content.
223 * It looks like it's working and there is always debug 16.
224 * - Log the content size after decompression in decompress_iob()
225 * instead of pcrs_filter_response().
227 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
228 * - Use dedicated header filter actions instead of abusing "filter".
229 * Replace "filter-client-headers" and "filter-client-headers"
230 * with "server-header-filter" and "client-header-filter".
231 * - Remove filter_client_header() and filter_client_header(),
232 * filter_header() now checks the shiny new
233 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
235 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
236 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
237 * - Handle "Cookie:" and "Connection:" headers a bit smarter
238 * (don't crunch them just to recreate them later on).
239 * - Add another non-standard time format for the cookie
240 * expiration date detection.
241 * - Fix a valgrind warning.
243 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
244 * Improve cookie expiration date detection.
246 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
247 * Don't run server_content_length() the first time
248 * sed() parses server headers; only adjust the
249 * Content-Length header if the page was modified.
251 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
252 * Fix log messages regarding the cookie time format
253 * (cookie and request URL were mixed up).
255 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
256 * - Let decompress_iob()
257 * - not corrupt the content if decompression fails
258 * early. (the first byte(s) were lost).
259 * - use pointer arithmetics with defined outcome for
261 * - Use a different kludge to remember a failed decompression.
263 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
264 * Search for Max-Forwards headers case-insensitive,
265 * don't generate the "501 unsupported" message for invalid
266 * Max-Forwards values and don't increase negative ones.
268 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
269 * - Let server_set_cookie() check the expiration date
270 * of cookies and don't touch the ones that are already
271 * expired. Fixes problems with low quality web applications
272 * as described in BR 932612.
274 * - Adjust comment in client_max_forwards to reality;
275 * remove invalid Max-Forwards headers.
277 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
278 * Stop filter_header() from unintentionally removing
279 * empty header lines that were enlisted by the continue
282 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
283 * - Repeat the request URL before logging any headers.
284 * Makes reading the log easier in case of simultaneous requests.
285 * - If there are more than one Content-Type headers in one request,
286 * use the first one and remove the others.
287 * - Remove "newval" variable in server_content_type().
288 * It's only used once.
290 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
291 * Correct a cast, check inflateEnd() exit code
292 * to see if we have to, replace sprintf calls
295 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
296 * Integrate a modified version of Wil Mahan's
297 * zlib patch (PR #895531).
299 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
300 * Skip empty filter files in filter_header()
301 * but don't ignore the ones that come afterwards.
302 * Fixes BR 1619208, this time for real.
304 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
305 * Reverted parts of my last commit
306 * to keep error handling working.
308 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
309 * Fixed gcc43 conversion warnings.
311 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
312 * Bringing back the "useless" localtime() call
313 * I removed in revision 1.67. On some platforms
314 * it's necessary to prevent time zone offsets.
316 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
317 * Rebuild request URL in get_destination_from_headers()
318 * to make sure redirect{pcrs command} works as expected
319 * for intercepted requests.
321 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
322 * Added get_destination_from_headers().
324 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
325 * Make pthread mutex locking more generic. Instead of
326 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
327 * and use mutex locking unless there is an _r function
328 * available. Better safe than sorry.
330 * Fixes "./configure --disable-pthread" and should result
331 * in less threading-related problems on pthread-using platforms,
332 * but it still doesn't fix BR#1122404.
334 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
335 * The special header "X-Filter: No" now disables
336 * header filtering as well.
338 * Revision 1.73 2006/09/23 13:26:38 roro
339 * Replace TABs by spaces in source code.
341 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
342 * Don't print a log message every time filter_headers is
343 * entered or left. It only creates noise without any real
346 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
347 * Fix +hide-if-modified-since{-n}.
349 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
350 * Have hide-if-modified-since interpret the random
351 * range value as minutes instead of hours. Allows
352 * more fine-grained configuration.
354 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
355 * Always have parse_header_time return a pointer
356 * that actual makes sense, even though we currently
357 * only need it to detect problems.
359 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
360 * Added config option enable-remote-http-toggle
361 * to specify if Privoxy should recognize special
362 * headers (currently only X-Filter) to change its
363 * behaviour. Disabled by default.
365 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
366 * After filtering de-chunked instances, remove
367 * "Transfer-Encoding" header entirely instead of changing
368 * it to "Transfer-Encoding: identity", which is invalid.
369 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
371 * Don't use localtime in parse_header_time. An empty time struct
372 * is good enough, it gets overwritten by strptime anyway.
374 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
375 * Use gmtime_r if available, fallback to gmtime with mutex
376 * protection for MacOSX and use vanilla gmtime for the rest.
378 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
379 * Changed client_referrer to use the right type (size_t) for
380 * hostlenght and to shorten the temporary referrer string with
381 * '\0' instead of adding a useless line break.
383 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
384 * - Back to timegm() using GnuPG's replacement if necessary.
385 * Using mktime() and localtime() could add a on hour offset if
386 * the randomize factor was big enough to lead to a summer/wintertime
389 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
391 * - Moved randomization code into pick_from_range().
393 * - Changed parse_header_time definition.
394 * time_t isn't guaranteed to be signed and
395 * if it isn't, -1 isn't available as error code.
396 * Changed some variable types in client_if_modified_since()
397 * because of the same reason.
399 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
400 * OS/2 compilation compatibility fixups
402 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
403 * Changed include from strptime.c to strptime.h
405 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
406 * Split filter-headers{} into filter-client-headers{}
407 * and filter-server-headers{}.
408 * Added parse_header_time() to share some code.
409 * Replaced timegm() with mktime().
411 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
412 * Windows service integration
414 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
415 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
417 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
418 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
419 * with what was really the latest development (the v_3_0_branch branch)
421 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
422 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
424 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
425 * Add the ability to check jpeg images for invalid
426 * lengths of comment blocks. Defensive strategy
427 * against the exploit:
428 * Microsoft Security Bulletin MS04-028
429 * Buffer Overrun in JPEG Processing (GDI+) Could
430 * Allow Code Execution (833987)
431 * Enabled with +inspect-jpegs in actions files.
433 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
434 * Excluded text/plain objects from filtering. This fixes a
435 * couple of client-crashing, download corruption and
436 * Privoxy performance issues, whose root cause lies in
437 * web servers labelling content of unknown type as text/plain.
439 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
440 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
442 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
443 * Completing the previous change
445 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
446 * Added temporary workaround for bug in PHP < 4.2.3
448 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
449 * 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.
451 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
452 * Fix typo: supressed -> suppressed
454 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
455 * Improved cookie logging
457 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
458 * Added basic support for OPTIONS and TRACE HTTP methods:
459 * - New parser function client_max_forwards which decrements
460 * the Max-Forwards HTTP header field of OPTIONS and TRACE
461 * requests by one before forwarding
462 * - New parser function client_host which extracts the host
463 * and port information from the HTTP header field if the
464 * request URI was not absolute
465 * - Don't crumble and re-add the Host: header, but only generate
466 * and append if missing
468 * Revision 1.56 2002/05/12 15:34:22 jongfoster
469 * Fixing typo in a comment
471 * Revision 1.55 2002/05/08 16:01:07 oes
472 * Optimized add_to_iob:
473 * - Use realloc instead of malloc(), memcpy(), free()
474 * - Expand to powers of two if possible, to get
475 * O(log n) reallocs instead of O(n).
476 * - Moved check for buffer limit here from chat
477 * - Report failure via returncode
479 * Revision 1.54 2002/04/02 15:03:16 oes
480 * Tiny code cosmetics
482 * Revision 1.53 2002/03/26 22:29:55 swa
483 * we have a new homepage!
485 * Revision 1.52 2002/03/24 13:25:43 swa
486 * name change related issues
488 * Revision 1.51 2002/03/13 00:27:05 jongfoster
491 * Revision 1.50 2002/03/12 01:45:35 oes
492 * More verbose logging
494 * Revision 1.49 2002/03/09 20:03:52 jongfoster
495 * - Making various functions return int rather than size_t.
496 * (Undoing a recent change). Since size_t is unsigned on
497 * Windows, functions like read_socket that return -1 on
498 * error cannot return a size_t.
500 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
501 * crashes, and also frequently caused JB to jump to 100%
502 * CPU and stay there. (Because it thought it had just
503 * read ((unsigned)-1) == 4Gb of data...)
505 * - The signature of write_socket has changed, it now simply
506 * returns success=0/failure=nonzero.
508 * - Trying to get rid of a few warnings --with-debug on
509 * Windows, I've introduced a new type "jb_socket". This is
510 * used for the socket file descriptors. On Windows, this
511 * is SOCKET (a typedef for unsigned). Everywhere else, it's
512 * an int. The error value can't be -1 any more, so it's
513 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
514 * Windows it maps to the #define INVALID_SOCKET.)
516 * - The signature of bind_port has changed.
518 * Revision 1.48 2002/03/07 03:46:53 oes
519 * Fixed compiler warnings etc
521 * Revision 1.47 2002/02/20 23:15:13 jongfoster
522 * Parsing functions now handle out-of-memory gracefully by returning
525 * Revision 1.46 2002/01/17 21:03:47 jongfoster
526 * Moving all our URL and URL pattern parsing code to urlmatch.c.
528 * Revision 1.45 2002/01/09 14:33:03 oes
529 * Added support for localtime_r.
531 * Revision 1.44 2001/12/14 01:22:54 steudten
532 * Remove 'user:pass@' from 'proto://user:pass@host' for the
533 * new added header 'Host: ..'. (See Req ID 491818)
535 * Revision 1.43 2001/11/23 00:26:38 jongfoster
536 * Fixing two really stupid errors in my previous commit
538 * Revision 1.42 2001/11/22 21:59:30 jongfoster
539 * Adding code to handle +no-cookies-keep
541 * Revision 1.41 2001/11/05 23:43:05 steudten
542 * Add time+date to log files.
544 * Revision 1.40 2001/10/26 20:13:09 jongfoster
545 * ctype.h is needed in Windows, too.
547 * Revision 1.39 2001/10/26 17:40:04 oes
548 * Introduced get_header_value()
549 * Removed http->user_agent, csp->referrer and csp->accept_types
550 * Removed client_accept()
552 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
553 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
554 * threads to call select() simultaneously. So, it's time to do a real, live,
555 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
556 * (native). Both versions will work, but using __OS2__ offers multi-threading.
558 * Revision 1.37 2001/10/23 21:36:02 jongfoster
559 * Documenting sed()'s error behaviou (doc change only)
561 * Revision 1.36 2001/10/13 12:51:51 joergs
562 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
563 * force-load), instead crumble Host: and add it (again) in client_host_adder
564 * (in case we get a HTTP/1.0 request without Host: header and forward it to
565 * a HTTP/1.1 server/proxy).
567 * Revision 1.35 2001/10/09 22:39:21 jongfoster
568 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
571 * Revision 1.34 2001/10/07 18:50:55 oes
572 * Added server_content_encoding, renamed server_transfer_encoding
574 * Revision 1.33 2001/10/07 18:04:49 oes
575 * Changed server_http11 to server_http and its pattern to "HTTP".
576 * Additional functionality: it now saves the HTTP status into
577 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
579 * Revision 1.32 2001/10/07 15:43:28 oes
580 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
581 * client_te and client_accept_encoding_adder, triggered by the new
582 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
583 * changed to allow only identity and chunked, and the TE header is
584 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
586 * parse_http_request no longer does anything than parsing. The rewriting
587 * of http->cmd and version mangling are gone. It now also recognizes
588 * the put and delete methods and saves the url in http->url. Removed
591 * renamed content_type and content_length to have the server_ prefix
593 * server_content_type now only works if csp->content_type != CT_TABOO
595 * added server_transfer_encoding, which
596 * - Sets CT_TABOO to prohibit filtering if encoding compresses
597 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
598 * - Change from "chunked" to "identity" if body was chunked
599 * but has been de-chunked for filtering.
601 * added server_content_md5 which crunches any Content-MD5 headers
602 * if the body was modified.
604 * made server_http11 conditional on +downgrade action
606 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
608 * Revision 1.31 2001/10/05 14:25:02 oes
609 * Crumble Keep-Alive from Server
611 * Revision 1.30 2001/09/29 12:56:03 joergs
612 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
614 * Revision 1.29 2001/09/24 21:09:24 jongfoster
615 * Fixing 2 memory leaks that Guy spotted, where the paramater to
616 * enlist() was not being free()d.
618 * Revision 1.28 2001/09/22 16:32:28 jongfoster
619 * Removing unused #includes.
621 * Revision 1.27 2001/09/20 15:45:25 steudten
623 * add casting from size_t to int for printf()
624 * remove local variable shadow s2
626 * Revision 1.26 2001/09/16 17:05:14 jongfoster
627 * Removing unused #include showarg.h
629 * Revision 1.25 2001/09/16 13:21:27 jongfoster
630 * Changes to use new list functions.
632 * Revision 1.24 2001/09/13 23:05:50 jongfoster
633 * Changing the string paramater to the header parsers a "const".
635 * Revision 1.23 2001/09/12 18:08:19 steudten
637 * In parse_http_request() header rewriting miss the host value, so
638 * from http://www.mydomain.com the result was just " / " not
639 * http://www.mydomain.com/ in case we forward.
641 * Revision 1.22 2001/09/10 10:58:53 oes
642 * Silenced compiler warnings
644 * Revision 1.21 2001/07/31 14:46:00 oes
645 * - Persistant connections now suppressed
646 * - sed() no longer appends empty header to csp->headers
648 * Revision 1.20 2001/07/30 22:08:36 jongfoster
649 * Tidying up #defines:
650 * - All feature #defines are now of the form FEATURE_xxx
651 * - Permanently turned off WIN_GUI_EDIT
652 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
654 * Revision 1.19 2001/07/25 17:21:54 oes
655 * client_uagent now saves copy of User-Agent: header value
657 * Revision 1.18 2001/07/13 14:02:46 oes
658 * - Included fix to repair broken HTTP requests that
659 * don't contain a path, not even '/'.
660 * - Removed all #ifdef PCRS
661 * - content_type now always inspected and classified as
662 * text, gif or other.
663 * - formatting / comments
665 * Revision 1.17 2001/06/29 21:45:41 oes
666 * Indentation, CRLF->LF, Tab-> Space
668 * Revision 1.16 2001/06/29 13:32:42 oes
670 * - Adapted free_http_request
671 * - Removed logentry from cancelled commit
673 * Revision 1.15 2001/06/03 19:12:38 oes
674 * deleted const struct interceptors
676 * Revision 1.14 2001/06/01 18:49:17 jongfoster
677 * Replaced "list_share" with "list" - the tiny memory gain was not
678 * worth the extra complexity.
680 * Revision 1.13 2001/05/31 21:30:33 jongfoster
681 * Removed list code - it's now in list.[ch]
682 * Renamed "permission" to "action", and changed many features
683 * to use the actions file rather than the global config.
685 * Revision 1.12 2001/05/31 17:33:13 oes
689 * Revision 1.11 2001/05/29 20:11:19 joergs
690 * '/ * inside comment' warning removed.
692 * Revision 1.10 2001/05/29 09:50:24 jongfoster
693 * Unified blocklist/imagelist/permissionslist.
694 * File format is still under discussion, but the internal changes
697 * Also modified interceptor behaviour:
698 * - We now intercept all URLs beginning with one of the following
699 * prefixes (and *only* these prefixes):
701 * * http://ijbswa.sf.net/config/
702 * * http://ijbswa.sourceforge.net/config/
703 * - New interceptors "home page" - go to http://i.j.b/ to see it.
704 * - Internal changes so that intercepted and fast redirect pages
705 * are not replaced with an image.
706 * - Interceptors now have the option to send a binary page direct
707 * to the client. (i.e. ijb-send-banner uses this)
708 * - Implemented show-url-info interceptor. (Which is why I needed
709 * the above interceptors changes - a typical URL is
710 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
711 * The previous mechanism would not have intercepted that, and
712 * if it had been intercepted then it then it would have replaced
715 * Revision 1.9 2001/05/28 17:26:33 jongfoster
716 * Fixing segfault if last header was crunched.
717 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
718 * can use the cross-platform sprintf() instead.)
720 * Revision 1.8 2001/05/27 22:17:04 oes
722 * - re_process_buffer no longer writes the modified buffer
723 * to the client, which was very ugly. It now returns the
724 * buffer, which it is then written by chat.
726 * - content_length now adjusts the Content-Length: header
727 * for modified documents rather than crunch()ing it.
728 * (Length info in csp->content_length, which is 0 for
729 * unmodified documents)
731 * - For this to work, sed() is called twice when filtering.
733 * Revision 1.7 2001/05/27 13:19:06 oes
734 * Patched Joergs solution for the content-length in.
736 * Revision 1.6 2001/05/26 13:39:32 jongfoster
737 * Only crunches Content-Length header if applying RE filtering.
738 * Without this fix, Microsoft Windows Update wouldn't work.
740 * Revision 1.5 2001/05/26 00:28:36 jongfoster
741 * Automatic reloading of config file.
742 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
743 * Most of the global variables have been moved to a new
744 * struct configuration_spec, accessed through csp->config->globalname
745 * Most of the globals remaining are used by the Win32 GUI.
747 * Revision 1.4 2001/05/22 18:46:04 oes
749 * - Enabled filtering banners by size rather than URL
750 * by adding patterns that replace all standard banner
751 * sizes with the "Junkbuster" gif to the re_filterfile
753 * - Enabled filtering WebBugs by providing a pattern
754 * which kills all 1x1 images
756 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
757 * which is selected by the (nonstandard and therefore
758 * capital) letter 'U' in the option string.
759 * It causes the quantifiers to be ungreedy by default.
760 * Appending a ? turns back to greedy (!).
762 * - Added a new interceptor ijb-send-banner, which
763 * sends back the "Junkbuster" gif. Without imagelist or
764 * MSIE detection support, or if tinygif = 1, or the
765 * URL isn't recognized as an imageurl, a lame HTML
766 * explanation is sent instead.
768 * - Added new feature, which permits blocking remote
769 * script redirects and firing back a local redirect
771 * The feature is conditionally compiled, i.e. it
772 * can be disabled with --disable-fast-redirects,
773 * plus it must be activated by a "fast-redirects"
774 * line in the config file, has its own log level
775 * and of course wants to be displayed by show-proxy-args
776 * Note: Boy, all the #ifdefs in 1001 locations and
777 * all the fumbling with configure.in and acconfig.h
778 * were *way* more work than the feature itself :-(
780 * - Because a generic redirect template was needed for
781 * this, tinygif = 3 now uses the same.
783 * - Moved GIFs, and other static HTTP response templates
788 * - Removed some >400 CRs again (Jon, you really worked
791 * Revision 1.3 2001/05/20 01:21:20 jongfoster
792 * Version 2.9.4 checkin.
793 * - Merged popupfile and cookiefile, and added control over PCRS
794 * filtering, in new "permissionsfile".
795 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
796 * file error you now get a message box (in the Win32 GUI) rather
797 * than the program exiting with no explanation.
798 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
800 * - Removed tabs from "config"
801 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
802 * - Bumped up version number.
804 * Revision 1.2 2001/05/17 23:02:36 oes
805 * - Made referrer option accept 'L' as a substitute for '§'
807 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
808 * Initial import of version 2.9.3 source tree
811 *********************************************************************/
818 #include <sys/types.h>
828 * Convince GNU's libc to provide a strptime prototype.
831 #endif /*__GLIBC__ */
838 #if !defined(_WIN32) && !defined(__OS2__)
844 #ifdef FEATURE_PTHREAD
846 /* jcc.h is for mutex semapores only */
847 #endif /* def FEATURE_PTHREAD */
852 #include "jbsockets.h"
853 #include "miscutil.h"
858 #ifndef HAVE_STRPTIME
859 #include "strptime.h"
862 const char parsers_h_rcs[] = PARSERS_H_VERSION;
864 /* Fix a problem with Solaris. There should be no effect on other
866 * Solaris's isspace() is a macro which uses its argument directly
867 * as an array index. Therefore we need to make sure that high-bit
868 * characters generate +ve values, and ideally we also want to make
869 * the argument match the declared parameter type of "int".
871 * Why did they write a character function that can't take a simple
872 * "char" argument? Doh!
874 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
875 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
877 static char *get_header_line(struct iob *iob);
878 static jb_err scan_headers(struct client_state *csp);
879 static jb_err header_tagger(struct client_state *csp, char *header);
880 static jb_err parse_header_time(const char *header_time, time_t *result);
882 static jb_err crumble (struct client_state *csp, char **header);
883 static jb_err connection (struct client_state *csp, char **header);
884 static jb_err filter_header (struct client_state *csp, char **header);
885 static jb_err client_referrer (struct client_state *csp, char **header);
886 static jb_err client_uagent (struct client_state *csp, char **header);
887 static jb_err client_ua (struct client_state *csp, char **header);
888 static jb_err client_from (struct client_state *csp, char **header);
889 static jb_err client_send_cookie (struct client_state *csp, char **header);
890 static jb_err client_x_forwarded (struct client_state *csp, char **header);
891 static jb_err client_accept_encoding (struct client_state *csp, char **header);
892 static jb_err client_te (struct client_state *csp, char **header);
893 static jb_err client_max_forwards (struct client_state *csp, char **header);
894 static jb_err client_host (struct client_state *csp, char **header);
895 static jb_err client_if_modified_since (struct client_state *csp, char **header);
896 static jb_err client_accept_language (struct client_state *csp, char **header);
897 static jb_err client_if_none_match (struct client_state *csp, char **header);
898 static jb_err crunch_client_header (struct client_state *csp, char **header);
899 static jb_err client_x_filter (struct client_state *csp, char **header);
900 static jb_err client_range (struct client_state *csp, char **header);
901 static jb_err server_set_cookie (struct client_state *csp, char **header);
902 static jb_err server_content_type (struct client_state *csp, char **header);
903 static jb_err server_content_length (struct client_state *csp, char **header);
904 static jb_err server_content_md5 (struct client_state *csp, char **header);
905 static jb_err server_content_encoding (struct client_state *csp, char **header);
906 static jb_err server_transfer_coding (struct client_state *csp, char **header);
907 static jb_err server_http (struct client_state *csp, char **header);
908 static jb_err crunch_server_header (struct client_state *csp, char **header);
909 static jb_err server_last_modified (struct client_state *csp, char **header);
910 static jb_err server_content_disposition(struct client_state *csp, char **header);
912 static jb_err client_host_adder (struct client_state *csp);
913 static jb_err client_xtra_adder (struct client_state *csp);
914 static jb_err connection_close_adder (struct client_state *csp);
916 static jb_err create_forged_referrer(char **header, const char *hostport);
917 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
918 static jb_err handle_conditional_hide_referrer_parameter(char **header,
919 const char *host, const int parameter_conditional_block);
922 * List of functions to run on a list of headers.
926 /** The header prefix to match */
929 /** The length of the prefix to match */
932 /** The function to apply to this line */
933 const parser_func_ptr parser;
936 static const struct parsers client_patterns[] = {
937 { "referer:", 8, client_referrer },
938 { "user-agent:", 11, client_uagent },
939 { "ua-", 3, client_ua },
940 { "from:", 5, client_from },
941 { "cookie:", 7, client_send_cookie },
942 { "x-forwarded-for:", 16, client_x_forwarded },
943 { "Accept-Encoding:", 16, client_accept_encoding },
944 { "TE:", 3, client_te },
945 { "Host:", 5, client_host },
946 { "if-modified-since:", 18, client_if_modified_since },
947 { "Keep-Alive:", 11, crumble },
948 { "connection:", 11, connection },
949 { "proxy-connection:", 17, crumble },
950 { "max-forwards:", 13, client_max_forwards },
951 { "Accept-Language:", 16, client_accept_language },
952 { "if-none-match:", 14, client_if_none_match },
953 { "Range:", 6, client_range },
954 { "Request-Range:", 14, client_range },
955 { "If-Range:", 9, client_range },
956 { "X-Filter:", 9, client_x_filter },
957 { "*", 0, crunch_client_header },
958 { "*", 0, filter_header },
962 static const struct parsers server_patterns[] = {
963 { "HTTP/", 5, server_http },
964 { "set-cookie:", 11, server_set_cookie },
965 { "connection:", 11, connection },
966 { "Content-Type:", 13, server_content_type },
967 { "Content-MD5:", 12, server_content_md5 },
968 { "Content-Encoding:", 17, server_content_encoding },
969 { "Transfer-Encoding:", 18, server_transfer_coding },
970 { "Keep-Alive:", 11, crumble },
971 { "content-disposition:", 20, server_content_disposition },
972 { "Last-Modified:", 14, server_last_modified },
973 { "*", 0, crunch_server_header },
974 { "*", 0, filter_header },
978 static const add_header_func_ptr add_client_headers[] = {
981 /* Temporarily disabled: client_accept_encoding_adder, */
982 connection_close_adder,
986 static const add_header_func_ptr add_server_headers[] = {
987 connection_close_adder,
991 /*********************************************************************
993 * Function : flush_socket
995 * Description : Write any pending "buffered" content.
998 * 1 : fd = file descriptor of the socket to read
999 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1001 * Returns : On success, the number of bytes written are returned (zero
1002 * indicates nothing was written). On error, -1 is returned,
1003 * and errno is set appropriately. If count is zero and the
1004 * file descriptor refers to a regular file, 0 will be
1005 * returned without causing any other effect. For a special
1006 * file, the results are not portable.
1008 *********************************************************************/
1009 int flush_socket(jb_socket fd, struct iob *iob)
1011 int len = iob->eod - iob->cur;
1018 if (write_socket(fd, iob->cur, (size_t)len))
1022 iob->eod = iob->cur = iob->buf;
1028 /*********************************************************************
1030 * Function : add_to_iob
1032 * Description : Add content to the buffered page, expanding the
1033 * buffer if necessary.
1036 * 1 : csp = Current client state (buffers, headers, etc...)
1037 * 2 : buf = holds the content to be added to the page
1038 * 3 : n = number of bytes to be added
1040 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1041 * or buffer limit reached.
1043 *********************************************************************/
1044 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1046 struct iob *iob = csp->iob;
1047 size_t used, offset, need, want;
1050 if (n <= 0) return JB_ERR_OK;
1052 used = (size_t)(iob->eod - iob->buf);
1053 offset = (size_t)(iob->cur - iob->buf);
1054 need = used + (size_t)n + 1;
1057 * If the buffer can't hold the new data, extend it first.
1058 * Use the next power of two if possible, else use the actual need.
1060 if (need > csp->config->buffer_limit)
1062 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1063 return JB_ERR_MEMORY;
1066 if (need > iob->size)
1068 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1070 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1074 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1080 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1081 return JB_ERR_MEMORY;
1084 /* Update the iob pointers */
1085 iob->cur = p + offset;
1086 iob->eod = p + used;
1090 /* copy the new data into the iob buffer */
1091 memcpy(iob->eod, buf, (size_t)n);
1093 /* point to the end of the data */
1096 /* null terminate == cheap insurance */
1105 /*********************************************************************
1107 * Function : decompress_iob
1109 * Description : Decompress buffered page, expanding the
1110 * buffer as necessary. csp->iob->cur
1111 * should point to the the beginning of the
1112 * compressed data block.
1115 * 1 : csp = Current client state (buffers, headers, etc...)
1117 * Returns : JB_ERR_OK on success,
1118 * JB_ERR_MEMORY if out-of-memory limit reached, and
1119 * JB_ERR_COMPRESS if error decompressing buffer.
1121 *********************************************************************/
1122 jb_err decompress_iob(struct client_state *csp)
1124 char *buf; /* new, uncompressed buffer */
1125 char *cur; /* Current iob position (to keep the original
1126 * iob->cur unmodified if we return early) */
1127 size_t bufsize; /* allocated size of the new buffer */
1128 size_t old_size; /* Content size before decompression */
1129 size_t skip_size; /* Number of bytes at the beginning of the iob
1130 that we should NOT decompress. */
1131 int status; /* return status of the inflate() call */
1132 z_stream zstr; /* used by calls to zlib */
1134 assert(csp->iob->cur - csp->iob->buf > 0);
1135 assert(csp->iob->eod - csp->iob->cur > 0);
1137 bufsize = csp->iob->size;
1138 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1139 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1141 cur = csp->iob->cur;
1146 * This is to protect the parsing of gzipped data,
1147 * but it should(?) be valid for deflated data also.
1149 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1150 return JB_ERR_COMPRESS;
1153 if (csp->content_type & CT_GZIP)
1156 * Our task is slightly complicated by the facts that data
1157 * compressed by gzip does not include a zlib header, and
1158 * that there is no easily accessible interface in zlib to
1159 * handle a gzip header. We strip off the gzip header by
1160 * hand, and later inform zlib not to expect a header.
1164 * Strip off the gzip header. Please see RFC 1952 for more
1165 * explanation of the appropriate fields.
1167 if ((*cur++ != (char)0x1f)
1168 || (*cur++ != (char)0x8b)
1169 || (*cur++ != Z_DEFLATED))
1171 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1172 return JB_ERR_COMPRESS;
1178 * XXX: These magic numbers should be replaced
1179 * with macros to give a better idea what they do.
1183 /* The gzip header has reserved bits set; bail out. */
1184 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1185 return JB_ERR_COMPRESS;
1189 /* Skip extra fields if necessary. */
1193 * Skip a given number of bytes, specified
1194 * as a 16-bit little-endian value.
1197 * XXX: This code used to be:
1199 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1201 * which I had to change into:
1203 * cur += *cur++ + (*cur++ << 8);
1205 * at which point gcc43 finally noticed that the value
1206 * of cur is undefined (it depends on which of the
1207 * summands is evaluated first).
1209 * I haven't come across a site where this
1210 * code is actually executed yet, but I hope
1214 skip_bytes = *cur++;
1215 skip_bytes = *cur++ << 8;
1217 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1220 * The number of bytes to skip should be positive
1221 * and we'd like to stay in the buffer.
1223 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1225 log_error(LOG_LEVEL_ERROR,
1226 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1228 return JB_ERR_COMPRESS;
1230 log_error(LOG_LEVEL_INFO,
1231 "Skipping %d bytes for gzip compression. Does this sound right?",
1236 /* Skip the filename if necessary. */
1239 /* A null-terminated string is supposed to follow. */
1240 while (*cur++ && (cur < csp->iob->eod));
1244 /* Skip the comment if necessary. */
1247 /* A null-terminated string is supposed to follow. */
1248 while (*cur++ && (cur < csp->iob->eod));
1251 /* Skip the CRC if necessary. */
1257 if (cur >= csp->iob->eod)
1260 * If the current position pointer reached or passed
1261 * the buffer end, we were obviously tricked to skip
1264 log_error(LOG_LEVEL_ERROR,
1265 "Malformed gzip header detected. Aborting decompression.");
1266 return JB_ERR_COMPRESS;
1270 else if (csp->content_type & CT_DEFLATE)
1273 * XXX: The debug level should be lowered
1274 * before the next stable release.
1276 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1278 * In theory (that is, according to RFC 1950), deflate-compressed
1279 * data should begin with a two-byte zlib header and have an
1280 * adler32 checksum at the end. It seems that in practice only
1281 * the raw compressed data is sent. Note that this means that
1282 * we are not RFC 1950-compliant here, but the advantage is that
1283 * this actually works. :)
1285 * We add a dummy null byte to tell zlib where the data ends,
1286 * and later inform it not to expect a header.
1288 * Fortunately, add_to_iob() has thoughtfully null-terminated
1289 * the buffer; we can just increment the end pointer to include
1296 log_error(LOG_LEVEL_ERROR,
1297 "Unable to determine compression format for decompression");
1298 return JB_ERR_COMPRESS;
1301 /* Set up the fields required by zlib. */
1302 zstr.next_in = (Bytef *)cur;
1303 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1304 zstr.zalloc = Z_NULL;
1305 zstr.zfree = Z_NULL;
1306 zstr.opaque = Z_NULL;
1309 * Passing -MAX_WBITS to inflateInit2 tells the library
1310 * that there is no zlib header.
1312 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1314 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1315 return JB_ERR_COMPRESS;
1319 * Next, we allocate new storage for the inflated data.
1320 * We don't modify the existing iob yet, so in case there
1321 * is error in decompression we can recover gracefully.
1323 buf = zalloc(bufsize);
1326 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1327 return JB_ERR_MEMORY;
1330 assert(bufsize >= skip_size);
1331 memcpy(buf, csp->iob->buf, skip_size);
1332 zstr.avail_out = bufsize - skip_size;
1333 zstr.next_out = (Bytef *)buf + skip_size;
1335 /* Try to decompress the whole stream in one shot. */
1336 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1338 /* We need to allocate more memory for the output buffer. */
1340 char *tmpbuf; /* used for realloc'ing the buffer */
1341 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1344 * If zlib wants more data then there's a problem, because
1345 * the complete compressed file should have been buffered.
1347 if (0 == zstr.avail_in)
1349 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1350 return JB_ERR_COMPRESS;
1354 * If we tried the limit and still didn't have enough
1355 * memory, just give up.
1357 if (bufsize == csp->config->buffer_limit)
1359 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1360 return JB_ERR_MEMORY;
1363 /* Try doubling the buffer size each time. */
1366 /* Don't exceed the buffer limit. */
1367 if (bufsize > csp->config->buffer_limit)
1369 bufsize = csp->config->buffer_limit;
1372 /* Try to allocate the new buffer. */
1373 tmpbuf = realloc(buf, bufsize);
1376 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1378 return JB_ERR_MEMORY;
1382 char *oldnext_out = (char *)zstr.next_out;
1385 * Update the fields for inflate() to use the new
1386 * buffer, which may be in a location different from
1389 zstr.avail_out += bufsize - oldbufsize;
1390 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1393 * Compare with an uglier method of calculating these values
1394 * that doesn't require the extra oldbufsize variable.
1396 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1397 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1398 assert(zstr.avail_out > 0);
1404 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1406 log_error(LOG_LEVEL_ERROR,
1407 "Inconsistent stream state after decompression: %s", zstr.msg);
1409 * XXX: Intentionally no return.
1411 * According to zlib.h, Z_STREAM_ERROR is returned
1412 * "if the stream state was inconsistent".
1414 * I assume in this case inflate()'s status
1415 * would also be something different than Z_STREAM_END
1416 * so this check should be redundant, but lets see.
1420 if (status != Z_STREAM_END)
1422 /* We failed to decompress the stream. */
1423 log_error(LOG_LEVEL_ERROR,
1424 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1425 return JB_ERR_COMPRESS;
1429 * Finally, we can actually update the iob, since the
1430 * decompression was successful. First, free the old
1433 freez(csp->iob->buf);
1435 /* Now, update the iob to use the new buffer. */
1436 csp->iob->buf = buf;
1437 csp->iob->cur = csp->iob->buf + skip_size;
1438 csp->iob->eod = (char *)zstr.next_out;
1439 csp->iob->size = bufsize;
1442 * Make sure the new uncompressed iob obeys some minimal
1443 * consistency conditions.
1445 if ((csp->iob->buf < csp->iob->cur)
1446 && (csp->iob->cur <= csp->iob->eod)
1447 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1449 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1452 log_error(LOG_LEVEL_RE_FILTER,
1453 "Decompression successful. Old size: %d, new size: %d.",
1454 old_size, new_size);
1458 /* zlib thinks this is OK, so lets do the same. */
1459 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1464 /* It seems that zlib did something weird. */
1465 log_error(LOG_LEVEL_ERROR,
1466 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1467 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1468 csp->iob->eod, csp->iob->buf + csp->iob->size);
1469 return JB_ERR_COMPRESS;
1475 #endif /* defined(FEATURE_ZLIB) */
1478 /*********************************************************************
1480 * Function : string_move
1482 * Description : memmove wrapper to move the last part of a string
1483 * towards the beginning, overwriting the part in
1484 * the middle. strlcpy() can't be used here as the
1488 * 1 : dst = Destination to overwrite
1489 * 2 : src = Source to move.
1493 *********************************************************************/
1494 static void string_move(char *dst, char *src)
1498 /* +1 to copy the terminating nul as well. */
1499 memmove(dst, src, strlen(src)+1);
1503 /*********************************************************************
1505 * Function : normalize_lws
1507 * Description : Reduces unquoted linear white space in headers
1508 * to a single space in accordance with RFC 2616 2.2.
1509 * This simplifies parsing and filtering later on.
1511 * XXX: Remove log messages before
1512 * the next stable release?
1515 * 1 : header = A header with linear white space to reduce.
1519 *********************************************************************/
1520 static void normalize_lws(char *header)
1526 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1530 while (ijb_isspace(*q))
1534 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1535 string_move(p+1, q);
1540 log_error(LOG_LEVEL_HEADER,
1541 "Converting tab to space in '%s'", header);
1546 char *end_of_token = strstr(p+1, "\"");
1548 if (NULL != end_of_token)
1550 /* Don't mess with quoted text. */
1555 log_error(LOG_LEVEL_HEADER,
1556 "Ignoring single quote in '%s'", header);
1562 p = strchr(header, ':');
1563 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1566 * There's still space before the colon.
1569 string_move(p-1, p);
1574 /*********************************************************************
1576 * Function : get_header
1578 * Description : This (odd) routine will parse the csp->iob
1579 * to get the next complete header.
1582 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1584 * Returns : Any one of the following:
1586 * 1) a pointer to a dynamically allocated string that contains a header line
1587 * 2) NULL indicating that the end of the header was reached
1588 * 3) "" indicating that the end of the iob was reached before finding
1589 * a complete header line.
1591 *********************************************************************/
1592 char *get_header(struct iob *iob)
1596 header = get_header_line(iob);
1598 if ((header == NULL) || (*header == '\0'))
1601 * No complete header read yet, tell the client.
1606 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1609 * Header spans multiple lines, append the next one.
1611 char *continued_header;
1613 continued_header = get_header_line(iob);
1614 if ((continued_header == NULL) || (*continued_header == '\0'))
1617 * No complete header read yet, return what we got.
1618 * XXX: Should "unread" header instead.
1620 log_error(LOG_LEVEL_INFO,
1621 "Failed to read a multi-line header properly: '%s'",
1626 if (JB_ERR_OK != string_join(&header, continued_header))
1628 log_error(LOG_LEVEL_FATAL,
1629 "Out of memory while appending multiple headers.");
1633 /* XXX: remove before next stable release. */
1634 log_error(LOG_LEVEL_HEADER,
1635 "Merged multiple header lines to: '%s'",
1640 normalize_lws(header);
1647 /*********************************************************************
1649 * Function : get_header_line
1651 * Description : This (odd) routine will parse the csp->iob
1652 * to get the next header line.
1655 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1657 * Returns : Any one of the following:
1659 * 1) a pointer to a dynamically allocated string that contains a header line
1660 * 2) NULL indicating that the end of the header was reached
1661 * 3) "" indicating that the end of the iob was reached before finding
1662 * a complete header line.
1664 *********************************************************************/
1665 static char *get_header_line(struct iob *iob)
1669 if ((iob->cur == NULL)
1670 || ((p = strchr(iob->cur, '\n')) == NULL))
1672 return(""); /* couldn't find a complete header */
1677 ret = strdup(iob->cur);
1680 /* FIXME No way to handle error properly */
1681 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1686 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1688 /* is this a blank line (i.e. the end of the header) ? */
1700 /*********************************************************************
1702 * Function : get_header_value
1704 * Description : Get the value of a given header from a chained list
1705 * of header lines or return NULL if no such header is
1706 * present in the list.
1709 * 1 : header_list = pointer to list
1710 * 2 : header_name = string with name of header to look for.
1711 * Trailing colon required, capitalization
1714 * Returns : NULL if not found, else value of header
1716 *********************************************************************/
1717 char *get_header_value(const struct list *header_list, const char *header_name)
1719 struct list_entry *cur_entry;
1723 assert(header_list);
1724 assert(header_name);
1725 length = strlen(header_name);
1727 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1731 if (!strncmpic(cur_entry->str, header_name, length))
1734 * Found: return pointer to start of value
1736 ret = (char *) (cur_entry->str + length);
1737 while (*ret && ijb_isspace(*ret)) ret++;
1751 /*********************************************************************
1753 * Function : scan_headers
1755 * Description : Scans headers, applies tags and updates action bits.
1758 * 1 : csp = Current client state (buffers, headers, etc...)
1760 * Returns : JB_ERR_OK
1762 *********************************************************************/
1763 static jb_err scan_headers(struct client_state *csp)
1765 struct list_entry *h; /* Header */
1766 jb_err err = JB_ERR_OK;
1768 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1770 /* Header crunch()ed in previous run? -> ignore */
1771 if (h->str == NULL) continue;
1772 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1773 err = header_tagger(csp, h->str);
1780 /*********************************************************************
1784 * Description : add, delete or modify lines in the HTTP header streams.
1785 * On entry, it receives a linked list of headers space
1786 * that was allocated dynamically (both the list nodes
1787 * and the header contents).
1789 * As a side effect it frees the space used by the original
1793 * 1 : csp = Current client state (buffers, headers, etc...)
1794 * 2 : filter_server_headers = Boolean to switch between
1795 * server and header filtering.
1797 * Returns : JB_ERR_OK in case off success, or
1798 * JB_ERR_MEMORY on out-of-memory error.
1800 *********************************************************************/
1801 jb_err sed(struct client_state *csp, int filter_server_headers)
1803 /* XXX: use more descriptive names. */
1804 struct list_entry *p;
1805 const struct parsers *v;
1806 const add_header_func_ptr *f;
1807 jb_err err = JB_ERR_OK;
1809 if (filter_server_headers)
1811 v = server_patterns;
1812 f = add_server_headers;
1816 v = client_patterns;
1817 f = add_client_headers;
1822 while ((err == JB_ERR_OK) && (v->str != NULL))
1824 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1826 /* Header crunch()ed in previous run? -> ignore */
1827 if (p->str == NULL) continue;
1829 /* Does the current parser handle this header? */
1830 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1831 (v->len == CHECK_EVERY_HEADER_REMAINING))
1833 err = v->parser(csp, &(p->str));
1839 /* place additional headers on the csp->headers list */
1840 while ((err == JB_ERR_OK) && (*f))
1850 /*********************************************************************
1852 * Function : update_server_headers
1854 * Description : Updates server headers after the body has been modified.
1857 * 1 : csp = Current client state (buffers, headers, etc...)
1859 * Returns : JB_ERR_OK in case off success, or
1860 * JB_ERR_MEMORY on out-of-memory error.
1862 *********************************************************************/
1863 jb_err update_server_headers(struct client_state *csp)
1865 jb_err err = JB_ERR_OK;
1867 static const struct parsers server_patterns_light[] = {
1868 { "Content-Length:", 15, server_content_length },
1869 { "Transfer-Encoding:", 18, server_transfer_coding },
1871 { "Content-Encoding:", 17, server_content_encoding },
1872 #endif /* def FEATURE_ZLIB */
1876 if (strncmpic(csp->http->cmd, "HEAD", 4))
1878 const struct parsers *v;
1879 struct list_entry *p;
1881 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1883 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1885 /* Header crunch()ed in previous run? -> ignore */
1886 if (p->str == NULL) continue;
1888 /* Does the current parser handle this header? */
1889 if (strncmpic(p->str, v->str, v->len) == 0)
1891 err = v->parser(csp, (char **)&(p->str));
1901 /*********************************************************************
1903 * Function : header_tagger
1905 * Description : Executes all text substitutions from applying
1906 * tag actions and saves the result as tag.
1908 * XXX: Shares enough code with filter_header() and
1909 * pcrs_filter_response() to warrant some helper functions.
1912 * 1 : csp = Current client state (buffers, headers, etc...)
1913 * 2 : header = Header that is used as tagger input
1915 * Returns : JB_ERR_OK on success and always succeeds
1917 *********************************************************************/
1918 static jb_err header_tagger(struct client_state *csp, char *header)
1920 int wanted_filter_type;
1921 int multi_action_index;
1925 struct file_list *fl;
1926 struct re_filterfile_spec *b;
1927 struct list_entry *tag_name;
1929 int found_filters = 0;
1930 const size_t header_length = strlen(header);
1932 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1934 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1935 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1939 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1940 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1943 /* Check if there are any filters */
1944 for (i = 0; i < MAX_AF_FILES; i++)
1957 if (0 == found_filters)
1959 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1960 "tagging enabled, but no taggers available.");
1964 for (i = 0; i < MAX_AF_FILES; i++)
1967 if ((NULL == fl) || (NULL == fl->f))
1970 * Either there are no filter files
1971 * left, or this filter file just
1972 * contains no valid filters.
1974 * Continue to be sure we don't miss
1975 * valid filter files that are chained
1976 * after empty or invalid ones.
1981 /* For all filters, */
1982 for (b = fl->f; b; b = b->next)
1984 if (b->type != wanted_filter_type)
1986 /* skip the ones we don't care about, */
1989 /* leaving only taggers that could apply, of which we use the ones, */
1990 for (tag_name = csp->action->multi[multi_action_index]->first;
1991 NULL != tag_name; tag_name = tag_name->next)
1993 /* that do apply, and */
1994 if (strcmp(b->name, tag_name->str) == 0)
1996 char *modified_tag = NULL;
1998 size_t size = header_length;
1999 pcrs_job *joblist = b->joblist;
2001 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2003 if (NULL == joblist)
2005 log_error(LOG_LEVEL_RE_FILTER,
2006 "Tagger %s has empty joblist. Nothing to do.", b->name);
2010 /* execute their pcrs_joblist on the header. */
2011 for (job = joblist; NULL != job; job = job->next)
2013 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2017 /* Success, continue with the modified version. */
2026 /* Tagger doesn't match */
2029 /* Regex failure, log it but continue anyway. */
2030 log_error(LOG_LEVEL_ERROR,
2031 "Problems with tagger \'%s\' and header \'%s\': %s",
2032 b->name, *header, pcrs_strerror(hits));
2034 freez(modified_tag);
2038 if (b->dynamic) pcrs_free_joblist(joblist);
2040 /* If this tagger matched */
2046 * There is to technical limitation which makes
2047 * it impossible to use empty tags, but I assume
2048 * no one would do it intentionally.
2051 log_error(LOG_LEVEL_INFO,
2052 "Tagger \'%s\' created an empty tag. Ignored.",
2057 if (!list_contains_item(csp->tags, tag))
2059 if (JB_ERR_OK != enlist(csp->tags, tag))
2061 log_error(LOG_LEVEL_ERROR,
2062 "Insufficient memory to add tag \'%s\', "
2063 "based on tagger \'%s\' and header \'%s\'",
2064 tag, b->name, *header);
2068 char *action_message;
2070 * update the action bits right away, to make
2071 * tagging based on tags set by earlier taggers
2072 * of the same kind possible.
2074 if (update_action_bits_for_tag(csp, tag))
2076 action_message = "Action bits updated accordingly.";
2080 action_message = "No action bits update necessary.";
2083 log_error(LOG_LEVEL_HEADER,
2084 "Tagger \'%s\' added tag \'%s\'. %s",
2085 b->name, tag, action_message);
2090 /* XXX: Is this log-worthy? */
2091 log_error(LOG_LEVEL_HEADER,
2092 "Tagger \'%s\' didn't add tag \'%s\'. "
2093 "Tag already present", b->name, tag);
2096 } /* if the tagger matched */
2097 } /* if the tagger applies */
2098 } /* for every tagger that could apply */
2099 } /* for all filters */
2100 } /* for all filter files */
2105 /* here begins the family of parser functions that reformat header lines */
2107 /*********************************************************************
2109 * Function : filter_header
2111 * Description : Executes all text substitutions from all applying
2112 * +(server|client)-header-filter actions on the header.
2113 * Most of the code was copied from pcrs_filter_response,
2114 * including the rather short variable names
2117 * 1 : csp = Current client state (buffers, headers, etc...)
2118 * 2 : header = On input, pointer to header to modify.
2119 * On output, pointer to the modified header, or NULL
2120 * to remove the header. This function frees the
2121 * original string if necessary.
2123 * Returns : JB_ERR_OK on success and always succeeds
2125 *********************************************************************/
2126 static jb_err filter_header(struct client_state *csp, char **header)
2130 size_t size = strlen(*header);
2132 char *newheader = NULL;
2135 struct file_list *fl;
2136 struct re_filterfile_spec *b;
2137 struct list_entry *filtername;
2139 int i, found_filters = 0;
2140 int wanted_filter_type;
2141 int multi_action_index;
2143 if (csp->flags & CSP_FLAG_NO_FILTERING)
2148 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2150 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2151 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2155 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2156 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2160 * Need to check the set of re_filterfiles...
2162 for (i = 0; i < MAX_AF_FILES; i++)
2175 if (0 == found_filters)
2177 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2178 "header filtering enabled, but no matching filters available.");
2182 for (i = 0; i < MAX_AF_FILES; i++)
2185 if ((NULL == fl) || (NULL == fl->f))
2188 * Either there are no filter files
2189 * left, or this filter file just
2190 * contains no valid filters.
2192 * Continue to be sure we don't miss
2193 * valid filter files that are chained
2194 * after empty or invalid ones.
2199 * For all applying +filter actions, look if a filter by that
2200 * name exists and if yes, execute its pcrs_joblist on the
2203 for (b = fl->f; b; b = b->next)
2205 if (b->type != wanted_filter_type)
2207 /* Skip other filter types */
2211 for (filtername = csp->action->multi[multi_action_index]->first;
2212 filtername ; filtername = filtername->next)
2214 if (strcmp(b->name, filtername->str) == 0)
2216 int current_hits = 0;
2217 pcrs_job *joblist = b->joblist;
2219 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2221 if (NULL == joblist)
2223 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2227 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2228 *header, size, b->name);
2230 /* Apply all jobs from the joblist */
2231 for (job = joblist; NULL != job; job = job->next)
2233 matches = pcrs_execute(job, *header, size, &newheader, &size);
2236 current_hits += matches;
2237 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2239 *header = newheader;
2241 else if ( 0 == matches )
2243 /* Filter doesn't change header */
2249 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2250 *header, b->name, pcrs_strerror(matches));
2251 if (newheader != NULL)
2253 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2259 if (b->dynamic) pcrs_free_joblist(joblist);
2261 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2262 hits += current_hits;
2269 * Additionally checking for hits is important because if
2270 * the continue hack is triggered, server headers can
2271 * arrive empty to separate multiple heads from each other.
2273 if ((0 == size) && hits)
2275 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2283 /*********************************************************************
2285 * Function : connection
2287 * Description : Makes sure that the value of the Connection: header
2288 * is "close" and signals connection_close_adder
2292 * 1 : csp = Current client state (buffers, headers, etc...)
2293 * 2 : header = On input, pointer to header to modify.
2294 * On output, pointer to the modified header, or NULL
2295 * to remove the header. This function frees the
2296 * original string if necessary.
2298 * Returns : JB_ERR_OK on success, or
2299 * JB_ERR_MEMORY on out-of-memory error.
2301 *********************************************************************/
2302 static jb_err connection(struct client_state *csp, char **header)
2304 char *old_header = *header;
2306 /* Do we have a 'Connection: close' header? */
2307 if (strcmpic(*header, "Connection: close"))
2309 /* No, create one */
2310 *header = strdup("Connection: close");
2313 return JB_ERR_MEMORY;
2315 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2319 /* Signal connection_close_adder() to return early. */
2320 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2322 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2326 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2333 /*********************************************************************
2335 * Function : crumble
2337 * Description : This is called if a header matches a pattern to "crunch"
2340 * 1 : csp = Current client state (buffers, headers, etc...)
2341 * 2 : header = On input, pointer to header to modify.
2342 * On output, pointer to the modified header, or NULL
2343 * to remove the header. This function frees the
2344 * original string if necessary.
2346 * Returns : JB_ERR_OK on success, or
2347 * JB_ERR_MEMORY on out-of-memory error.
2349 *********************************************************************/
2350 static jb_err crumble(struct client_state *csp, char **header)
2352 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2358 /*********************************************************************
2360 * Function : crunch_server_header
2362 * Description : Crunch server header if it matches a string supplied by the
2363 * user. Called from `sed'.
2366 * 1 : csp = Current client state (buffers, headers, etc...)
2367 * 2 : header = On input, pointer to header to modify.
2368 * On output, pointer to the modified header, or NULL
2369 * to remove the header. This function frees the
2370 * original string if necessary.
2372 * Returns : JB_ERR_OK on success and always succeeds
2374 *********************************************************************/
2375 static jb_err crunch_server_header(struct client_state *csp, char **header)
2377 const char *crunch_pattern;
2379 /* Do we feel like crunching? */
2380 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2382 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2384 /* Is the current header the lucky one? */
2385 if (strstr(*header, crunch_pattern))
2387 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2396 /*********************************************************************
2398 * Function : server_content_type
2400 * Description : Set the content-type for filterable types (text/.*,
2401 * .*xml.*, javascript and image/gif) unless filtering has been
2402 * forbidden (CT_TABOO) while parsing earlier headers.
2403 * NOTE: Since text/plain is commonly used by web servers
2404 * for files whose correct type is unknown, we don't
2405 * set CT_TEXT for it.
2408 * 1 : csp = Current client state (buffers, headers, etc...)
2409 * 2 : header = On input, pointer to header to modify.
2410 * On output, pointer to the modified header, or NULL
2411 * to remove the header. This function frees the
2412 * original string if necessary.
2414 * Returns : JB_ERR_OK on success, or
2415 * JB_ERR_MEMORY on out-of-memory error.
2417 *********************************************************************/
2418 static jb_err server_content_type(struct client_state *csp, char **header)
2420 /* Remove header if it isn't the first Content-Type header */
2421 if ((csp->content_type & CT_DECLARED))
2424 * Another, slightly slower, way to see if
2425 * we already parsed another Content-Type header.
2427 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2429 log_error(LOG_LEVEL_ERROR,
2430 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2438 * Signal that the Content-Type has been set.
2440 csp->content_type |= CT_DECLARED;
2442 if (!(csp->content_type & CT_TABOO))
2445 * XXX: The assumption that text/plain is a sign of
2446 * binary data seems to be somewhat unreasonable nowadays
2447 * and should be dropped after 3.0.8 is out.
2449 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2450 || strstr(*header, "xml")
2451 || strstr(*header, "application/x-javascript"))
2453 csp->content_type |= CT_TEXT;
2455 else if (strstr(*header, "image/gif"))
2457 csp->content_type |= CT_GIF;
2462 * Are we messing with the content type?
2464 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2467 * Make sure the user doesn't accidently
2468 * change the content type of binary documents.
2470 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2473 *header = strdup("Content-Type: ");
2474 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2478 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2479 return JB_ERR_MEMORY;
2481 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2485 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2486 "It doesn't look like a content type that should be filtered. "
2487 "Enable force-text-mode if you know what you're doing.", *header);
2495 /*********************************************************************
2497 * Function : server_transfer_coding
2499 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2500 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2501 * - Remove header if body was chunked but has been
2502 * de-chunked for filtering.
2505 * 1 : csp = Current client state (buffers, headers, etc...)
2506 * 2 : header = On input, pointer to header to modify.
2507 * On output, pointer to the modified header, or NULL
2508 * to remove the header. This function frees the
2509 * original string if necessary.
2511 * Returns : JB_ERR_OK on success, or
2512 * JB_ERR_MEMORY on out-of-memory error.
2514 *********************************************************************/
2515 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2518 * Turn off pcrs and gif filtering if body compressed
2520 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2524 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2526 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2527 csp->http->cmd, *header);
2528 #endif /* def FEATURE_ZLIB */
2529 csp->content_type = CT_TABOO;
2533 * Raise flag if body chunked
2535 if (strstr(*header, "chunked"))
2537 csp->flags |= CSP_FLAG_CHUNKED;
2540 * If the body was modified, it has been de-chunked first
2541 * and the header must be removed.
2543 * FIXME: If there is more than one transfer encoding,
2544 * only the "chunked" part should be removed here.
2546 if (csp->flags & CSP_FLAG_MODIFIED)
2548 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2557 /*********************************************************************
2559 * Function : server_content_encoding
2561 * Description : This function is run twice for each request,
2562 * unless FEATURE_ZLIB and filtering are disabled.
2564 * The first run is used to check if the content
2565 * is compressed, if FEATURE_ZLIB is disabled
2566 * filtering is then disabled as well, if FEATURE_ZLIB
2567 * is enabled the content is marked for decompression.
2569 * The second run is used to remove the Content-Encoding
2570 * header if the decompression was successful.
2573 * 1 : csp = Current client state (buffers, headers, etc...)
2574 * 2 : header = On input, pointer to header to modify.
2575 * On output, pointer to the modified header, or NULL
2576 * to remove the header. This function frees the
2577 * original string if necessary.
2579 * Returns : JB_ERR_OK on success, or
2580 * JB_ERR_MEMORY on out-of-memory error.
2582 *********************************************************************/
2583 static jb_err server_content_encoding(struct client_state *csp, char **header)
2586 if ((csp->flags & CSP_FLAG_MODIFIED)
2587 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2590 * We successfully decompressed the content,
2591 * and have to clean the header now, so the
2592 * client no longer expects compressed data..
2594 * XXX: There is a difference between cleaning
2595 * and removing it completely.
2597 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2600 else if (strstr(*header, "gzip"))
2602 /* Mark for gzip decompression */
2603 csp->content_type |= CT_GZIP;
2605 else if (strstr(*header, "deflate"))
2607 /* Mark for zlib decompression */
2608 csp->content_type |= CT_DEFLATE;
2610 else if (strstr(*header, "compress"))
2613 * We can't decompress this; therefore we can't filter
2616 csp->content_type |= CT_TABOO;
2618 #else /* !defined(FEATURE_ZLIB) */
2619 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2622 * Body is compressed, turn off pcrs and gif filtering.
2624 csp->content_type |= CT_TABOO;
2627 * Log a warning if the user expects the content to be filtered.
2629 if ((csp->rlist != NULL) &&
2630 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2632 log_error(LOG_LEVEL_INFO,
2633 "Compressed content detected, content filtering disabled. "
2634 "Consider recompiling Privoxy with zlib support or "
2635 "enable the prevent-compression action.");
2638 #endif /* defined(FEATURE_ZLIB) */
2645 /*********************************************************************
2647 * Function : server_content_length
2649 * Description : Adjust Content-Length header if we modified
2653 * 1 : csp = Current client state (buffers, headers, etc...)
2654 * 2 : header = On input, pointer to header to modify.
2655 * On output, pointer to the modified header, or NULL
2656 * to remove the header. This function frees the
2657 * original string if necessary.
2659 * Returns : JB_ERR_OK on success, or
2660 * JB_ERR_MEMORY on out-of-memory error.
2662 *********************************************************************/
2663 static jb_err server_content_length(struct client_state *csp, char **header)
2665 const size_t max_header_length = 80;
2667 /* Regenerate header if the content was modified. */
2668 if (csp->flags & CSP_FLAG_MODIFIED)
2671 *header = (char *) zalloc(max_header_length);
2672 if (*header == NULL)
2674 return JB_ERR_MEMORY;
2677 snprintf(*header, max_header_length, "Content-Length: %d",
2678 (int)csp->content_length);
2679 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2680 (int)csp->content_length);
2687 /*********************************************************************
2689 * Function : server_content_md5
2691 * Description : Crumble any Content-MD5 headers if the document was
2692 * modified. FIXME: Should we re-compute instead?
2695 * 1 : csp = Current client state (buffers, headers, etc...)
2696 * 2 : header = On input, pointer to header to modify.
2697 * On output, pointer to the modified header, or NULL
2698 * to remove the header. This function frees the
2699 * original string if necessary.
2701 * Returns : JB_ERR_OK on success, or
2702 * JB_ERR_MEMORY on out-of-memory error.
2704 *********************************************************************/
2705 static jb_err server_content_md5(struct client_state *csp, char **header)
2707 if (csp->flags & CSP_FLAG_MODIFIED)
2709 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2717 /*********************************************************************
2719 * Function : server_content_disposition
2721 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2722 * Called from `sed'.
2725 * 1 : csp = Current client state (buffers, headers, etc...)
2726 * 2 : header = On input, pointer to header to modify.
2727 * On output, pointer to the modified header, or NULL
2728 * to remove the header. This function frees the
2729 * original string if necessary.
2731 * Returns : JB_ERR_OK on success, or
2732 * JB_ERR_MEMORY on out-of-memory error.
2734 *********************************************************************/
2735 static jb_err server_content_disposition(struct client_state *csp, char **header)
2740 * Are we messing with the Content-Disposition header?
2742 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2748 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2750 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2753 * Blocking content-disposition header
2755 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2762 * Replacing Content-Disposition header
2765 *header = strdup("Content-Disposition: ");
2766 string_append(header, newval);
2768 if (*header != NULL)
2770 log_error(LOG_LEVEL_HEADER,
2771 "Content-Disposition header crunched and replaced with: %s", *header);
2774 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2778 /*********************************************************************
2780 * Function : server_last_modified
2782 * Description : Changes Last-Modified header to the actual date
2783 * to help hide-if-modified-since.
2784 * Called from `sed'.
2787 * 1 : csp = Current client state (buffers, headers, etc...)
2788 * 2 : header = On input, pointer to header to modify.
2789 * On output, pointer to the modified header, or NULL
2790 * to remove the header. This function frees the
2791 * original string if necessary.
2793 * Returns : JB_ERR_OK on success, or
2794 * JB_ERR_MEMORY on out-of-memory error.
2796 *********************************************************************/
2797 static jb_err server_last_modified(struct client_state *csp, char **header)
2800 char buf[BUFFER_SIZE];
2803 #ifdef HAVE_GMTIME_R
2806 struct tm *timeptr = NULL;
2807 time_t now, last_modified;
2809 long int days, hours, minutes, seconds;
2812 * Are we messing with the Last-Modified header?
2814 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2820 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2822 if (0 == strcmpic(newval, "block") )
2825 * Blocking Last-Modified header. Useless but why not.
2827 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2831 else if (0 == strcmpic(newval, "reset-to-request-time"))
2834 * Setting Last-Modified Header to now.
2836 get_http_time(0, buf, sizeof(buf));
2838 *header = strdup("Last-Modified: ");
2839 string_append(header, buf);
2841 if (*header == NULL)
2843 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2847 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2850 else if (0 == strcmpic(newval, "randomize"))
2852 const char *header_time = *header + sizeof("Last-Modified:");
2854 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2856 #ifdef HAVE_GMTIME_R
2857 timeptr = gmtime_r(&now, &gmt);
2858 #elif FEATURE_PTHREAD
2859 pthread_mutex_lock(&gmtime_mutex);
2860 timeptr = gmtime(&now);
2861 pthread_mutex_unlock(&gmtime_mutex);
2863 timeptr = gmtime(&now);
2865 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2867 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2872 rtime = (long int)difftime(now, last_modified);
2881 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2883 rtime = pick_from_range(rtime);
2884 if (negative) rtime *= -1;
2885 last_modified += rtime;
2886 #ifdef HAVE_GMTIME_R
2887 timeptr = gmtime_r(&last_modified, &gmt);
2888 #elif FEATURE_PTHREAD
2889 pthread_mutex_lock(&gmtime_mutex);
2890 timeptr = gmtime(&last_modified);
2891 pthread_mutex_unlock(&gmtime_mutex);
2893 timeptr = gmtime(&last_modified);
2895 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2897 *header = strdup("Last-Modified: ");
2898 string_append(header, newheader);
2900 if (*header == NULL)
2902 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2903 return JB_ERR_MEMORY;
2906 days = rtime / (3600 * 24);
2907 hours = rtime / 3600 % 24;
2908 minutes = rtime / 60 % 60;
2909 seconds = rtime % 60;
2911 log_error(LOG_LEVEL_HEADER,
2912 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2913 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2914 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2918 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2927 /*********************************************************************
2929 * Function : client_accept_encoding
2931 * Description : Rewrite the client's Accept-Encoding header so that
2932 * if doesn't allow compression, if the action applies.
2933 * Note: For HTTP/1.0 the absence of the header is enough.
2936 * 1 : csp = Current client state (buffers, headers, etc...)
2937 * 2 : header = On input, pointer to header to modify.
2938 * On output, pointer to the modified header, or NULL
2939 * to remove the header. This function frees the
2940 * original string if necessary.
2942 * Returns : JB_ERR_OK on success, or
2943 * JB_ERR_MEMORY on out-of-memory error.
2945 *********************************************************************/
2946 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2948 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2950 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2954 /* Temporarily disable the correct behaviour to
2955 * work around a PHP bug.
2957 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2959 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2960 * if (*header == NULL)
2962 * return JB_ERR_MEMORY;
2973 /*********************************************************************
2975 * Function : client_te
2977 * Description : Rewrite the client's TE header so that
2978 * if doesn't allow compression, if the action applies.
2981 * 1 : csp = Current client state (buffers, headers, etc...)
2982 * 2 : header = On input, pointer to header to modify.
2983 * On output, pointer to the modified header, or NULL
2984 * to remove the header. This function frees the
2985 * original string if necessary.
2987 * Returns : JB_ERR_OK on success, or
2988 * JB_ERR_MEMORY on out-of-memory error.
2990 *********************************************************************/
2991 static jb_err client_te(struct client_state *csp, char **header)
2993 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2996 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3003 /*********************************************************************
3005 * Function : client_referrer
3007 * Description : Handle the "referer" config setting properly.
3008 * Called from `sed'.
3011 * 1 : csp = Current client state (buffers, headers, etc...)
3012 * 2 : header = On input, pointer to header to modify.
3013 * On output, pointer to the modified header, or NULL
3014 * to remove the header. This function frees the
3015 * original string if necessary.
3017 * Returns : JB_ERR_OK on success, or
3018 * JB_ERR_MEMORY on out-of-memory error.
3020 *********************************************************************/
3021 static jb_err client_referrer(struct client_state *csp, char **header)
3023 const char *parameter;
3024 /* booleans for parameters we have to check multiple times */
3025 int parameter_conditional_block;
3026 int parameter_conditional_forge;
3028 #ifdef FEATURE_FORCE_LOAD
3030 * Since the referrer can include the prefix even
3031 * if the request itself is non-forced, we must
3032 * clean it unconditionally.
3034 * XXX: strclean is too broad
3036 strclean(*header, FORCE_PREFIX);
3037 #endif /* def FEATURE_FORCE_LOAD */
3039 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3041 /* Nothing left to do */
3045 parameter = csp->action->string[ACTION_STRING_REFERER];
3046 assert(parameter != NULL);
3047 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3048 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3050 if (!parameter_conditional_block && !parameter_conditional_forge)
3053 * As conditional-block and conditional-forge are the only
3054 * parameters that rely on the original referrer, we can
3055 * remove it now for all the others.
3060 if (0 == strcmpic(parameter, "block"))
3062 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3065 else if (parameter_conditional_block || parameter_conditional_forge)
3067 return handle_conditional_hide_referrer_parameter(header,
3068 csp->http->hostport, parameter_conditional_block);
3070 else if (0 == strcmpic(parameter, "forge"))
3072 return create_forged_referrer(header, csp->http->hostport);
3076 /* interpret parameter as user-supplied referer to fake */
3077 return create_fake_referrer(header, parameter);
3082 /*********************************************************************
3084 * Function : client_accept_language
3086 * Description : Handle the "Accept-Language" config setting properly.
3087 * Called from `sed'.
3090 * 1 : csp = Current client state (buffers, headers, etc...)
3091 * 2 : header = On input, pointer to header to modify.
3092 * On output, pointer to the modified header, or NULL
3093 * to remove the header. This function frees the
3094 * original string if necessary.
3096 * Returns : JB_ERR_OK on success, or
3097 * JB_ERR_MEMORY on out-of-memory error.
3099 *********************************************************************/
3100 static jb_err client_accept_language(struct client_state *csp, char **header)
3105 * Are we messing with the Accept-Language?
3107 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3109 /*I don't think so*/
3113 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3115 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3118 * Blocking Accept-Language header
3120 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3127 * Replacing Accept-Language header
3130 *header = strdup("Accept-Language: ");
3131 string_append(header, newval);
3133 if (*header == NULL)
3135 log_error(LOG_LEVEL_ERROR,
3136 "Insufficient memory. Accept-Language header crunched without replacement.");
3140 log_error(LOG_LEVEL_HEADER,
3141 "Accept-Language header crunched and replaced with: %s", *header);
3144 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3148 /*********************************************************************
3150 * Function : crunch_client_header
3152 * Description : Crunch client header if it matches a string supplied by the
3153 * user. Called from `sed'.
3156 * 1 : csp = Current client state (buffers, headers, etc...)
3157 * 2 : header = On input, pointer to header to modify.
3158 * On output, pointer to the modified header, or NULL
3159 * to remove the header. This function frees the
3160 * original string if necessary.
3162 * Returns : JB_ERR_OK on success and always succeeds
3164 *********************************************************************/
3165 static jb_err crunch_client_header(struct client_state *csp, char **header)
3167 const char *crunch_pattern;
3169 /* Do we feel like crunching? */
3170 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3172 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3174 /* Is the current header the lucky one? */
3175 if (strstr(*header, crunch_pattern))
3177 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3185 /*********************************************************************
3187 * Function : client_uagent
3189 * Description : Handle the "user-agent" config setting properly
3190 * and remember its original value to enable browser
3191 * bug workarounds. Called from `sed'.
3194 * 1 : csp = Current client state (buffers, headers, etc...)
3195 * 2 : header = On input, pointer to header to modify.
3196 * On output, pointer to the modified header, or NULL
3197 * to remove the header. This function frees the
3198 * original string if necessary.
3200 * Returns : JB_ERR_OK on success, or
3201 * JB_ERR_MEMORY on out-of-memory error.
3203 *********************************************************************/
3204 static jb_err client_uagent(struct client_state *csp, char **header)
3208 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3213 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3220 *header = strdup("User-Agent: ");
3221 string_append(header, newval);
3223 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3225 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3229 /*********************************************************************
3231 * Function : client_ua
3233 * Description : Handle "ua-" headers properly. Called from `sed'.
3236 * 1 : csp = Current client state (buffers, headers, etc...)
3237 * 2 : header = On input, pointer to header to modify.
3238 * On output, pointer to the modified header, or NULL
3239 * to remove the header. This function frees the
3240 * original string if necessary.
3242 * Returns : JB_ERR_OK on success, or
3243 * JB_ERR_MEMORY on out-of-memory error.
3245 *********************************************************************/
3246 static jb_err client_ua(struct client_state *csp, char **header)
3248 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3250 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3258 /*********************************************************************
3260 * Function : client_from
3262 * Description : Handle the "from" config setting properly.
3263 * Called from `sed'.
3266 * 1 : csp = Current client state (buffers, headers, etc...)
3267 * 2 : header = On input, pointer to header to modify.
3268 * On output, pointer to the modified header, or NULL
3269 * to remove the header. This function frees the
3270 * original string if necessary.
3272 * Returns : JB_ERR_OK on success, or
3273 * JB_ERR_MEMORY on out-of-memory error.
3275 *********************************************************************/
3276 static jb_err client_from(struct client_state *csp, char **header)
3280 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3287 newval = csp->action->string[ACTION_STRING_FROM];
3290 * Are we blocking the e-mail address?
3292 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3294 log_error(LOG_LEVEL_HEADER, "crunched From!");
3298 log_error(LOG_LEVEL_HEADER, " modified");
3300 *header = strdup("From: ");
3301 string_append(header, newval);
3303 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3307 /*********************************************************************
3309 * Function : client_send_cookie
3311 * Description : Crunches the "cookie" header if necessary.
3312 * Called from `sed'.
3314 * XXX: Stupid name, doesn't send squat.
3317 * 1 : csp = Current client state (buffers, headers, etc...)
3318 * 2 : header = On input, pointer to header to modify.
3319 * On output, pointer to the modified header, or NULL
3320 * to remove the header. This function frees the
3321 * original string if necessary.
3323 * Returns : JB_ERR_OK on success, or
3324 * JB_ERR_MEMORY on out-of-memory error.
3326 *********************************************************************/
3327 static jb_err client_send_cookie(struct client_state *csp, char **header)
3329 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3331 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3339 /*********************************************************************
3341 * Function : client_x_forwarded
3343 * Description : Handle the "x-forwarded-for" config setting properly,
3344 * also used in the add_client_headers list. Called from `sed'.
3347 * 1 : csp = Current client state (buffers, headers, etc...)
3348 * 2 : header = On input, pointer to header to modify.
3349 * On output, pointer to the modified header, or NULL
3350 * to remove the header. This function frees the
3351 * original string if necessary.
3353 * Returns : JB_ERR_OK on success, or
3354 * JB_ERR_MEMORY on out-of-memory error.
3356 *********************************************************************/
3357 jb_err client_x_forwarded(struct client_state *csp, char **header)
3359 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3362 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3369 /*********************************************************************
3371 * Function : client_max_forwards
3373 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3374 * from the value of the Max-Forwards header field.
3377 * 1 : csp = Current client state (buffers, headers, etc...)
3378 * 2 : header = On input, pointer to header to modify.
3379 * On output, pointer to the modified header, or NULL
3380 * to remove the header. This function frees the
3381 * original string if necessary.
3383 * Returns : JB_ERR_OK on success, or
3384 * JB_ERR_MEMORY on out-of-memory error.
3386 *********************************************************************/
3387 static jb_err client_max_forwards(struct client_state *csp, char **header)
3391 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3392 (0 == strcmpic(csp->http->gpc, "options")))
3394 assert(*(*header+12) == ':');
3395 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3397 if (max_forwards > 0)
3399 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3400 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3401 csp->http->gpc, max_forwards);
3403 else if (max_forwards < 0)
3405 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3411 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3420 /*********************************************************************
3422 * Function : client_host
3424 * Description : If the request URI did not contain host and
3425 * port information, parse and evaluate the Host
3428 * Also, kill ill-formed HOST: headers as sent by
3429 * Apple's iTunes software when used with a proxy.
3432 * 1 : csp = Current client state (buffers, headers, etc...)
3433 * 2 : header = On input, pointer to header to modify.
3434 * On output, pointer to the modified header, or NULL
3435 * to remove the header. This function frees the
3436 * original string if necessary.
3438 * Returns : JB_ERR_OK on success, or
3439 * JB_ERR_MEMORY on out-of-memory error.
3441 *********************************************************************/
3442 static jb_err client_host(struct client_state *csp, char **header)
3447 * If the header field name is all upper-case, chances are that it's
3448 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3449 * not a problem -- they are regenerated later.
3451 if ((*header)[1] == 'O')
3453 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3458 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3459 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3462 if (NULL == (p = strdup((*header)+6)))
3464 return JB_ERR_MEMORY;
3467 if (NULL == (q = strdup(p)))
3470 return JB_ERR_MEMORY;
3473 freez(csp->http->hostport);
3474 csp->http->hostport = p;
3475 freez(csp->http->host);
3476 csp->http->host = q;
3477 q = strchr(csp->http->host, ':');
3480 /* Terminate hostname and evaluate port string */
3482 csp->http->port = atoi(q);
3486 csp->http->port = csp->http->ssl ? 443 : 80;
3489 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3490 csp->http->hostport, csp->http->host, csp->http->port);
3493 /* Signal client_host_adder() to return right away */
3494 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3500 /*********************************************************************
3502 * Function : client_if_modified_since
3504 * Description : Remove or modify the If-Modified-Since header.
3507 * 1 : csp = Current client state (buffers, headers, etc...)
3508 * 2 : header = On input, pointer to header to modify.
3509 * On output, pointer to the modified header, or NULL
3510 * to remove the header. This function frees the
3511 * original string if necessary.
3513 * Returns : JB_ERR_OK on success, or
3514 * JB_ERR_MEMORY on out-of-memory error.
3516 *********************************************************************/
3517 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3520 #ifdef HAVE_GMTIME_R
3523 struct tm *timeptr = NULL;
3527 long int hours, minutes, seconds;
3531 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3534 * The client got an error message because of a temporary problem,
3535 * the problem is gone and the client now tries to revalidate our
3536 * error message on the real server. The revalidation would always
3537 * end with the transmission of the whole document and there is
3538 * no need to expose the bogus If-Modified-Since header.
3540 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3543 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3545 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3547 if ((0 == strcmpic(newval, "block")))
3549 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3552 else /* add random value */
3554 const char *header_time = *header + sizeof("If-Modified-Since:");
3556 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3558 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3563 rtime = strtol(newval, &endptr, 0);
3566 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3567 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3574 rtime = pick_from_range(rtime);
3578 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3581 tm += rtime * (negative ? -1 : 1);
3582 #ifdef HAVE_GMTIME_R
3583 timeptr = gmtime_r(&tm, &gmt);
3584 #elif FEATURE_PTHREAD
3585 pthread_mutex_lock(&gmtime_mutex);
3586 timeptr = gmtime(&tm);
3587 pthread_mutex_unlock(&gmtime_mutex);
3589 timeptr = gmtime(&tm);
3591 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3594 *header = strdup("If-Modified-Since: ");
3595 string_append(header, newheader);
3597 if (*header == NULL)
3599 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3600 return JB_ERR_MEMORY;
3603 hours = rtime / 3600;
3604 minutes = rtime / 60 % 60;
3605 seconds = rtime % 60;
3607 log_error(LOG_LEVEL_HEADER,
3608 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3609 *header, (negative) ? "subtracted" : "added", hours,
3610 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3611 seconds, (seconds == 1) ? ")" : "s)");
3620 /*********************************************************************
3622 * Function : client_if_none_match
3624 * Description : Remove the If-None-Match header.
3627 * 1 : csp = Current client state (buffers, headers, etc...)
3628 * 2 : header = On input, pointer to header to modify.
3629 * On output, pointer to the modified header, or NULL
3630 * to remove the header. This function frees the
3631 * original string if necessary.
3633 * Returns : JB_ERR_OK on success, or
3634 * JB_ERR_MEMORY on out-of-memory error.
3636 *********************************************************************/
3637 static jb_err client_if_none_match(struct client_state *csp, char **header)
3639 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3641 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3649 /*********************************************************************
3651 * Function : client_x_filter
3653 * Description : Disables filtering if the client set "X-Filter: No".
3654 * Called from `sed'.
3657 * 1 : csp = Current client state (buffers, headers, etc...)
3658 * 2 : header = On input, pointer to header to modify.
3659 * On output, pointer to the modified header, or NULL
3660 * to remove the header. This function frees the
3661 * original string if necessary.
3663 * Returns : JB_ERR_OK on success
3665 *********************************************************************/
3666 jb_err client_x_filter(struct client_state *csp, char **header)
3668 if ( 0 == strcmpic(*header, "X-Filter: No"))
3670 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3672 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3676 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3678 log_error(LOG_LEVEL_HEADER,
3679 "force-text-mode overruled the client's request to fetch without filtering!");
3683 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3684 csp->flags |= CSP_FLAG_NO_FILTERING;
3685 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3687 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3695 /*********************************************************************
3697 * Function : client_range
3699 * Description : Removes Range, Request-Range and If-Range headers if
3700 * content filtering is enabled. If the client's version
3701 * of the document has been altered by Privoxy, the server
3702 * could interpret the range differently than the client
3703 * intended in which case the user could end up with
3704 * corrupted content.
3707 * 1 : csp = Current client state (buffers, headers, etc...)
3708 * 2 : header = On input, pointer to header to modify.
3709 * On output, pointer to the modified header, or NULL
3710 * to remove the header. This function frees the
3711 * original string if necessary.
3713 * Returns : JB_ERR_OK
3715 *********************************************************************/
3716 static jb_err client_range(struct client_state *csp, char **header)
3718 if (content_filters_enabled(csp->action))
3720 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3721 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3728 /* the following functions add headers directly to the header list */
3730 /*********************************************************************
3732 * Function : client_host_adder
3734 * Description : Adds the Host: header field if it is missing.
3735 * Called from `sed'.
3738 * 1 : csp = Current client state (buffers, headers, etc...)
3740 * Returns : JB_ERR_OK on success, or
3741 * JB_ERR_MEMORY on out-of-memory error.
3743 *********************************************************************/
3744 static jb_err client_host_adder(struct client_state *csp)
3749 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3751 /* Header already set by the client, nothing to do. */
3755 if ( !csp->http->hostport || !*(csp->http->hostport))
3757 /* XXX: When does this happen and why is it OK? */
3758 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3763 * remove 'user:pass@' from 'proto://user:pass@host'
3765 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3771 p = csp->http->hostport;
3774 /* XXX: Just add it, we already made sure that it will be unique */
3775 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3776 err = enlist_unique_header(csp->headers, "Host", p);
3783 /*********************************************************************
3785 * Function : client_accept_encoding_adder
3787 * Description : Add an Accept-Encoding header to the client's request
3788 * that disables compression if the action applies, and
3789 * the header is not already there. Called from `sed'.
3790 * Note: For HTTP/1.0, the absence of the header is enough.
3793 * 1 : csp = Current client state (buffers, headers, etc...)
3795 * Returns : JB_ERR_OK on success, or
3796 * JB_ERR_MEMORY on out-of-memory error.
3798 *********************************************************************/
3799 static jb_err client_accept_encoding_adder(struct client_state *csp)
3801 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3802 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3804 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3812 /*********************************************************************
3814 * Function : client_xtra_adder
3816 * Description : Used in the add_client_headers list. Called from `sed'.
3819 * 1 : csp = Current client state (buffers, headers, etc...)
3821 * Returns : JB_ERR_OK on success, or
3822 * JB_ERR_MEMORY on out-of-memory error.
3824 *********************************************************************/
3825 static jb_err client_xtra_adder(struct client_state *csp)
3827 struct list_entry *lst;
3830 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3831 lst ; lst = lst->next)
3833 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3834 err = enlist(csp->headers, lst->str);
3846 /*********************************************************************
3848 * Function : connection_close_adder
3850 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3851 * support. Adds a "Connection: close" header to csp->headers
3852 * unless the header was already present. Called from `sed'.
3854 * FIXME: This whole function shouldn't be neccessary!
3857 * 1 : csp = Current client state (buffers, headers, etc...)
3859 * Returns : JB_ERR_OK on success, or
3860 * JB_ERR_MEMORY on out-of-memory error.
3862 *********************************************************************/
3863 static jb_err connection_close_adder(struct client_state *csp)
3865 const unsigned int flags = csp->flags;
3868 * Return right away if
3870 * - we're parsing server headers and the server header
3871 * "Connection: close" is already set, or if
3873 * - we're parsing client headers and the client header
3874 * "Connection: close" is already set.
3876 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3877 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3878 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3879 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3884 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3886 return enlist(csp->headers, "Connection: close");
3890 /*********************************************************************
3892 * Function : server_http
3894 * Description : - Save the HTTP Status into csp->http->status
3895 * - Set CT_TABOO to prevent filtering if the answer
3896 * is a partial range (HTTP status 206)
3897 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3901 * 1 : csp = Current client state (buffers, headers, etc...)
3902 * 2 : header = On input, pointer to header to modify.
3903 * On output, pointer to the modified header, or NULL
3904 * to remove the header. This function frees the
3905 * original string if necessary.
3907 * Returns : JB_ERR_OK on success, or
3908 * JB_ERR_MEMORY on out-of-memory error.
3910 *********************************************************************/
3911 static jb_err server_http(struct client_state *csp, char **header)
3913 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3914 if (csp->http->status == 206)
3916 csp->content_type = CT_TABOO;
3919 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3921 /* XXX: Should we do a real validity check here? */
3922 if (strlen(*header) > 8)
3925 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3930 * XXX: Should we block the request or
3931 * enlist a valid status code line here?
3933 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3934 "Downgrading to HTTP/1.0 impossible.");
3942 /*********************************************************************
3944 * Function : server_set_cookie
3946 * Description : Handle the server "cookie" header properly.
3947 * Log cookie to the jar file. Then "crunch",
3948 * accept or rewrite it to a session cookie.
3949 * Called from `sed'.
3951 * TODO: Allow the user to specify a new expiration
3952 * time to cause the cookie to expire even before the
3953 * browser is closed.
3956 * 1 : csp = Current client state (buffers, headers, etc...)
3957 * 2 : header = On input, pointer to header to modify.
3958 * On output, pointer to the modified header, or NULL
3959 * to remove the header. This function frees the
3960 * original string if necessary.
3962 * Returns : JB_ERR_OK on success, or
3963 * JB_ERR_MEMORY on out-of-memory error.
3965 *********************************************************************/
3966 static jb_err server_set_cookie(struct client_state *csp, char **header)
3973 #ifdef FEATURE_COOKIE_JAR
3974 if (csp->config->jar)
3977 * Write timestamp into outbuf.
3979 * Complex because not all OSs have tm_gmtoff or
3980 * the %z field in strftime()
3982 char tempbuf[ BUFFER_SIZE ];
3984 #ifdef HAVE_LOCALTIME_R
3985 tm_now = *localtime_r(&now, &tm_now);
3986 #elif FEATURE_PTHREAD
3987 pthread_mutex_lock(&localtime_mutex);
3988 tm_now = *localtime (&now);
3989 pthread_mutex_unlock(&localtime_mutex);
3991 tm_now = *localtime (&now);
3993 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3995 /* strlen("set-cookie: ") = 12 */
3996 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3998 #endif /* def FEATURE_COOKIE_JAR */
4000 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4002 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4005 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4007 /* Flag whether or not to log a message */
4010 /* A variable to store the tag we're working on */
4013 /* Skip "Set-Cookie:" (11 characters) in header */
4014 cur_tag = *header + 11;
4016 /* skip whitespace between "Set-Cookie:" and value */
4017 while (*cur_tag && ijb_isspace(*cur_tag))
4022 /* Loop through each tag in the cookie */
4026 char *next_tag = strchr(cur_tag, ';');
4027 if (next_tag != NULL)
4029 /* Skip the ';' character itself */
4032 /* skip whitespace ";" and start of tag */
4033 while (*next_tag && ijb_isspace(*next_tag))
4040 /* "Next tag" is the end of the string */
4041 next_tag = cur_tag + strlen(cur_tag);
4045 * Check the expiration date to see
4046 * if the cookie is still valid, if yes,
4047 * rewrite it to a session cookie.
4049 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4051 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4053 /* Did we detect the date properly? */
4054 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4057 * Nope, treat it as if it was still valid.
4059 * XXX: Should we remove the whole cookie instead?
4061 log_error(LOG_LEVEL_ERROR,
4062 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4063 string_move(cur_tag, next_tag);
4069 * Yes. Check if the cookie is still valid.
4071 * If the cookie is already expired it's probably
4072 * a delete cookie and even if it isn't, the browser
4073 * will discard it anyway.
4077 * XXX: timegm() isn't available on some AmigaOS
4078 * versions and our replacement doesn't work.
4080 * Our options are to either:
4082 * - disable session-cookies-only completely if timegm
4085 * - to simply remove all expired tags, like it has
4086 * been done until Privoxy 3.0.6 and to live with
4087 * the consequence that it can cause login/logout
4088 * problems on servers that don't validate their
4089 * input properly, or
4091 * - to replace it with mktime in which
4092 * case there is a slight chance of valid cookies
4093 * passing as already expired.
4095 * This is the way it's currently done and it's not
4096 * as bad as it sounds. If the missing GMT offset is
4097 * enough to change the result of the expiration check
4098 * the cookie will be only valid for a few hours
4099 * anyway, which in many cases will be shorter
4100 * than a browser session.
4102 if (cookie_time - now < 0)
4104 log_error(LOG_LEVEL_HEADER,
4105 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4106 /* Just in case some clown sets more then one expiration date */
4112 * Still valid, delete expiration date by copying
4113 * the rest of the string over it.
4115 string_move(cur_tag, next_tag);
4117 /* That changed the header, need to issue a log message */
4121 * Note that the next tag has now been moved to *cur_tag,
4122 * so we do not need to update the cur_tag pointer.
4130 /* Move on to next cookie tag */
4137 assert(NULL != *header);
4138 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4147 #ifdef FEATURE_FORCE_LOAD
4148 /*********************************************************************
4150 * Function : strclean
4152 * Description : In-Situ-Eliminate all occurances of substring in
4156 * 1 : string = string to clean
4157 * 2 : substring = substring to eliminate
4159 * Returns : Number of eliminations
4161 *********************************************************************/
4162 int strclean(char *string, const char *substring)
4168 len = strlen(substring);
4170 while((pos = strstr(string, substring)) != NULL)
4177 while (*p++ != '\0');
4184 #endif /* def FEATURE_FORCE_LOAD */
4187 /*********************************************************************
4189 * Function : parse_header_time
4191 * Description : Parses time formats used in HTTP header strings
4192 * to get the numerical respresentation.
4195 * 1 : header_time = HTTP header time as string.
4196 * 2 : result = storage for header_time in seconds
4198 * Returns : JB_ERR_OK if the time format was recognized, or
4199 * JB_ERR_PARSE otherwise.
4201 *********************************************************************/
4202 static jb_err parse_header_time(const char *header_time, time_t *result)
4207 * Zero out gmt to prevent time zone offsets.
4209 * While this is only necessary on some platforms
4210 * (mingw32 for example), I don't know how to
4211 * detect these automatically and doing it everywhere
4214 memset(&gmt, 0, sizeof(gmt));
4216 /* Tue, 02 Jun 2037 20:00:00 */
4217 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4218 /* Tue, 02-Jun-2037 20:00:00 */
4219 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4220 /* Tue, 02-Jun-37 20:00:00 */
4221 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4222 /* Tuesday, 02-Jun-2037 20:00:00 */
4223 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4224 /* Tuesday Jun 02 20:00:00 2037 */
4225 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4227 return JB_ERR_PARSE;
4230 *result = timegm(&gmt);
4237 /*********************************************************************
4239 * Function : get_destination_from_headers
4241 * Description : Parse the "Host:" header to get the request's destination.
4242 * Only needed if the client's request was forcefully
4243 * redirected into Privoxy.
4245 * Code mainly copied from client_host() which is currently
4246 * run too late for this purpose.
4249 * 1 : headers = List of headers (one of them hopefully being
4250 * the "Host:" header)
4251 * 2 : http = storage for the result (host, port and hostport).
4253 * Returns : JB_ERR_MEMORY in case of memory problems,
4254 * JB_ERR_PARSE if the host header couldn't be found,
4255 * JB_ERR_OK otherwise.
4257 *********************************************************************/
4258 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4264 host = get_header_value(headers, "Host:");
4268 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4269 return JB_ERR_PARSE;
4272 if (NULL == (p = strdup((host))))
4274 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4275 return JB_ERR_MEMORY;
4278 if (NULL == (q = strdup(p)))
4281 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4282 return JB_ERR_MEMORY;
4285 freez(http->hostport);
4289 q = strchr(http->host, ':');
4292 /* Terminate hostname and evaluate port string */
4294 http->port = atoi(q);
4298 http->port = http->ssl ? 443 : 80;
4301 /* Rebuild request URL */
4303 http->url = strdup(http->ssl ? "https://" : "http://");
4304 string_append(&http->url, http->hostport);
4305 string_append(&http->url, http->path);
4306 if (http->url == NULL)
4308 return JB_ERR_MEMORY;
4311 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4319 /*********************************************************************
4321 * Function : create_forged_referrer
4323 * Description : Helper for client_referrer to forge a referer as
4324 * 'http://[hostname:port/' to fool stupid
4325 * checks for in-site links
4328 * 1 : header = Pointer to header pointer
4329 * 2 : hostport = Host and optionally port as string
4331 * Returns : JB_ERR_OK in case of success, or
4332 * JB_ERR_MEMORY in case of memory problems.
4334 *********************************************************************/
4335 static jb_err create_forged_referrer(char **header, const char *hostport)
4337 assert(NULL == *header);
4339 *header = strdup("Referer: http://");
4340 string_append(header, hostport);
4341 string_append(header, "/");
4343 if (NULL == *header)
4345 return JB_ERR_MEMORY;
4348 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4355 /*********************************************************************
4357 * Function : create_fake_referrer
4359 * Description : Helper for client_referrer to create a fake referrer
4360 * based on a string supplied by the user.
4363 * 1 : header = Pointer to header pointer
4364 * 2 : hosthost = Referrer to fake
4366 * Returns : JB_ERR_OK in case of success, or
4367 * JB_ERR_MEMORY in case of memory problems.
4369 *********************************************************************/
4370 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4372 assert(NULL == *header);
4374 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4376 log_error(LOG_LEVEL_HEADER,
4377 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4379 *header = strdup("Referer: ");
4380 string_append(header, fake_referrer);
4382 if (NULL == *header)
4384 return JB_ERR_MEMORY;
4387 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4394 /*********************************************************************
4396 * Function : handle_conditional_hide_referrer_parameter
4398 * Description : Helper for client_referrer to crunch or forge
4399 * the referrer header if the host has changed.
4402 * 1 : header = Pointer to header pointer
4403 * 2 : host = The target host (may include the port)
4404 * 3 : parameter_conditional_block = Boolean to signal
4405 * if we're in conditional-block mode. If not set,
4406 * we're in conditional-forge mode.
4408 * Returns : JB_ERR_OK in case of success, or
4409 * JB_ERR_MEMORY in case of memory problems.
4411 *********************************************************************/
4412 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4413 const char *host, const int parameter_conditional_block)
4415 char *referer = strdup(*header);
4416 const size_t hostlenght = strlen(host);
4418 if (NULL == referer)
4421 return JB_ERR_MEMORY;
4424 /* referer begins with 'Referer: http[s]://' */
4425 if (hostlenght < (strlen(referer)-17))
4428 * Shorten referer to make sure the referer is blocked
4429 * if www.example.org/www.example.com-shall-see-the-referer/
4430 * links to www.example.com/
4432 referer[hostlenght+17] = '\0';
4434 if (NULL == strstr(referer, host))
4436 /* Host has changed */
4437 if (parameter_conditional_block)
4439 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4446 return create_forged_referrer(header, host);