1 const char parsers_rcs[] = "$Id: parsers.c,v 1.124 2008/04/16 16:38:21 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
48 * Don't pass the whole csp structure to flush_socket()
49 * when it only needs a file descriptor and a buffer.
51 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
52 * Remove send-wafer and send-vanilla-wafer actions.
54 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
55 * Remove inspect-jpegs action.
57 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
58 * Let client_range() also handle Request-Range headers
59 * which apparently are still supported by many servers.
61 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
62 * Improve the warning messages that get logged if the action files
63 * "enable" filters but no filters of that type have been loaded.
65 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
66 * In server_content_type():
67 * - Don't require leading white space when detecting image content types.
68 * - Change '... not replaced ...' message to sound less crazy if the text
69 * type actually is 'text/plain'.
70 * - Mark the 'text/plain == binary data' assumption for removal.
71 * - Remove a bunch of trailing white space.
73 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
74 * Minor server_content_disposition() changes:
75 * - Don't regenerate the header name all lower-case.
76 * - Some white space fixes.
77 * - Remove useless log message in case of ENOMEM.
79 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
80 * Garbage-collect the code to add a X-Forwarded-For
81 * header as it seems to be mostly used by accident.
83 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
84 * Fix a crash on mingw32 with some Last Modified times in the future.
86 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
87 * Remove a "can't happen" error block which, over
88 * time, mutated into a "guaranteed to happen" block.
90 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
91 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
92 * - Use shiny new content_filters_enabled() in client_range().
94 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
95 * I forgot about Poland.
97 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
98 * Remove Range and If-Range headers if content filtering is enabled.
100 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
101 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
102 * client_cookie_adder() to make sure send-vanilla-wafer can be
103 * controlled through tags (and thus regression-tested).
105 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
106 * - Remove "scanning headers for" log message again.
107 * - Some more whitespace fixes.
109 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
110 * Refactor client_referrer() and add conditional-forge parameter.
112 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
113 * A bunch of whitespace fixes, pointy hat to me.
115 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
116 * Fix possible memory corruption in server_http, make sure it's not
117 * executed for ordinary server headers and mark some problems for later.
119 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
120 * Let content-type-overwrite{} honour force-text-mode again.
122 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
123 * - Add prototpyes for the header parsers and make them static.
124 * - Comment out client_accept_encoding_adder() which isn't used right now.
126 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
127 * Move the ACTION_FORCE_TEXT_MODE check out of
128 * server_content_type(). Signal other functions
129 * whether or not a content type has been declared.
130 * Part of the fix for BR#1750917.
132 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
133 * Change sed() to return a jb_err in preparation for forward-override{}.
135 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
136 * Adjust "X-Filter: No" to disable dedicated header filters.
138 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
139 * Streamline client_cookie_adder().
141 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
142 * Make sure filters with dynamic jobs actually use them.
144 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
145 * - Introduce dynamic pcrs jobs that can resolve variables.
146 * - Remove unnecessary update_action_bits_for_all_tags() call.
148 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
149 * - Make tagging based on tags set by earlier taggers
150 * of the same kind possible.
151 * - Log whether or not new tags cause action bits updates
152 * (in which case a matching tag-pattern section exists).
153 * - Log if the user tries to set a tag that is already set.
155 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
156 * Introduce tags as alternative way to specify which
157 * actions apply to a request. At the moment tags can be
158 * created based on client and server headers.
160 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
161 * Log a warning if the content is compressed, filtering is
162 * enabled and Privoxy was compiled without zlib support.
165 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
166 * - Fix warnings when compiled with glibc.
167 * - Don't use crumble() for cookie crunching.
168 * - Move cookie time parsing into parse_header_time().
169 * - Let parse_header_time() return a jb_err code
170 * instead of a pointer that can only be used to
171 * check for NULL anyway.
173 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
174 * - Add better protection against malicious gzip headers.
175 * - Stop logging the first hundred bytes of decompressed content.
176 * It looks like it's working and there is always debug 16.
177 * - Log the content size after decompression in decompress_iob()
178 * instead of pcrs_filter_response().
180 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
181 * - Use dedicated header filter actions instead of abusing "filter".
182 * Replace "filter-client-headers" and "filter-client-headers"
183 * with "server-header-filter" and "client-header-filter".
184 * - Remove filter_client_header() and filter_client_header(),
185 * filter_header() now checks the shiny new
186 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
188 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
189 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
190 * - Handle "Cookie:" and "Connection:" headers a bit smarter
191 * (don't crunch them just to recreate them later on).
192 * - Add another non-standard time format for the cookie
193 * expiration date detection.
194 * - Fix a valgrind warning.
196 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
197 * Improve cookie expiration date detection.
199 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
200 * Don't run server_content_length() the first time
201 * sed() parses server headers; only adjust the
202 * Content-Length header if the page was modified.
204 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
205 * Fix log messages regarding the cookie time format
206 * (cookie and request URL were mixed up).
208 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
209 * - Let decompress_iob()
210 * - not corrupt the content if decompression fails
211 * early. (the first byte(s) were lost).
212 * - use pointer arithmetics with defined outcome for
214 * - Use a different kludge to remember a failed decompression.
216 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
217 * Search for Max-Forwards headers case-insensitive,
218 * don't generate the "501 unsupported" message for invalid
219 * Max-Forwards values and don't increase negative ones.
221 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
222 * - Let server_set_cookie() check the expiration date
223 * of cookies and don't touch the ones that are already
224 * expired. Fixes problems with low quality web applications
225 * as described in BR 932612.
227 * - Adjust comment in client_max_forwards to reality;
228 * remove invalid Max-Forwards headers.
230 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
231 * Stop filter_header() from unintentionally removing
232 * empty header lines that were enlisted by the continue
235 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
236 * - Repeat the request URL before logging any headers.
237 * Makes reading the log easier in case of simultaneous requests.
238 * - If there are more than one Content-Type headers in one request,
239 * use the first one and remove the others.
240 * - Remove "newval" variable in server_content_type().
241 * It's only used once.
243 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
244 * Correct a cast, check inflateEnd() exit code
245 * to see if we have to, replace sprintf calls
248 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
249 * Integrate a modified version of Wil Mahan's
250 * zlib patch (PR #895531).
252 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
253 * Skip empty filter files in filter_header()
254 * but don't ignore the ones that come afterwards.
255 * Fixes BR 1619208, this time for real.
257 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
258 * Reverted parts of my last commit
259 * to keep error handling working.
261 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
262 * Fixed gcc43 conversion warnings.
264 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
265 * Bringing back the "useless" localtime() call
266 * I removed in revision 1.67. On some platforms
267 * it's necessary to prevent time zone offsets.
269 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
270 * Rebuild request URL in get_destination_from_headers()
271 * to make sure redirect{pcrs command} works as expected
272 * for intercepted requests.
274 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
275 * Added get_destination_from_headers().
277 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
278 * Make pthread mutex locking more generic. Instead of
279 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
280 * and use mutex locking unless there is an _r function
281 * available. Better safe than sorry.
283 * Fixes "./configure --disable-pthread" and should result
284 * in less threading-related problems on pthread-using platforms,
285 * but it still doesn't fix BR#1122404.
287 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
288 * The special header "X-Filter: No" now disables
289 * header filtering as well.
291 * Revision 1.73 2006/09/23 13:26:38 roro
292 * Replace TABs by spaces in source code.
294 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
295 * Don't print a log message every time filter_headers is
296 * entered or left. It only creates noise without any real
299 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
300 * Fix +hide-if-modified-since{-n}.
302 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
303 * Have hide-if-modified-since interpret the random
304 * range value as minutes instead of hours. Allows
305 * more fine-grained configuration.
307 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
308 * Always have parse_header_time return a pointer
309 * that actual makes sense, even though we currently
310 * only need it to detect problems.
312 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
313 * Added config option enable-remote-http-toggle
314 * to specify if Privoxy should recognize special
315 * headers (currently only X-Filter) to change its
316 * behaviour. Disabled by default.
318 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
319 * After filtering de-chunked instances, remove
320 * "Transfer-Encoding" header entirely instead of changing
321 * it to "Transfer-Encoding: identity", which is invalid.
322 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
324 * Don't use localtime in parse_header_time. An empty time struct
325 * is good enough, it gets overwritten by strptime anyway.
327 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
328 * Use gmtime_r if available, fallback to gmtime with mutex
329 * protection for MacOSX and use vanilla gmtime for the rest.
331 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
332 * Changed client_referrer to use the right type (size_t) for
333 * hostlenght and to shorten the temporary referrer string with
334 * '\0' instead of adding a useless line break.
336 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
337 * - Back to timegm() using GnuPG's replacement if necessary.
338 * Using mktime() and localtime() could add a on hour offset if
339 * the randomize factor was big enough to lead to a summer/wintertime
342 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
344 * - Moved randomization code into pick_from_range().
346 * - Changed parse_header_time definition.
347 * time_t isn't guaranteed to be signed and
348 * if it isn't, -1 isn't available as error code.
349 * Changed some variable types in client_if_modified_since()
350 * because of the same reason.
352 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
353 * OS/2 compilation compatibility fixups
355 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
356 * Changed include from strptime.c to strptime.h
358 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
359 * Split filter-headers{} into filter-client-headers{}
360 * and filter-server-headers{}.
361 * Added parse_header_time() to share some code.
362 * Replaced timegm() with mktime().
364 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
365 * Windows service integration
367 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
368 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
370 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
371 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
372 * with what was really the latest development (the v_3_0_branch branch)
374 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
375 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
377 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
378 * Add the ability to check jpeg images for invalid
379 * lengths of comment blocks. Defensive strategy
380 * against the exploit:
381 * Microsoft Security Bulletin MS04-028
382 * Buffer Overrun in JPEG Processing (GDI+) Could
383 * Allow Code Execution (833987)
384 * Enabled with +inspect-jpegs in actions files.
386 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
387 * Excluded text/plain objects from filtering. This fixes a
388 * couple of client-crashing, download corruption and
389 * Privoxy performance issues, whose root cause lies in
390 * web servers labelling content of unknown type as text/plain.
392 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
393 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
395 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
396 * Completing the previous change
398 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
399 * Added temporary workaround for bug in PHP < 4.2.3
401 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
402 * 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.
404 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
405 * Fix typo: supressed -> suppressed
407 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
408 * Improved cookie logging
410 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
411 * Added basic support for OPTIONS and TRACE HTTP methods:
412 * - New parser function client_max_forwards which decrements
413 * the Max-Forwards HTTP header field of OPTIONS and TRACE
414 * requests by one before forwarding
415 * - New parser function client_host which extracts the host
416 * and port information from the HTTP header field if the
417 * request URI was not absolute
418 * - Don't crumble and re-add the Host: header, but only generate
419 * and append if missing
421 * Revision 1.56 2002/05/12 15:34:22 jongfoster
422 * Fixing typo in a comment
424 * Revision 1.55 2002/05/08 16:01:07 oes
425 * Optimized add_to_iob:
426 * - Use realloc instead of malloc(), memcpy(), free()
427 * - Expand to powers of two if possible, to get
428 * O(log n) reallocs instead of O(n).
429 * - Moved check for buffer limit here from chat
430 * - Report failure via returncode
432 * Revision 1.54 2002/04/02 15:03:16 oes
433 * Tiny code cosmetics
435 * Revision 1.53 2002/03/26 22:29:55 swa
436 * we have a new homepage!
438 * Revision 1.52 2002/03/24 13:25:43 swa
439 * name change related issues
441 * Revision 1.51 2002/03/13 00:27:05 jongfoster
444 * Revision 1.50 2002/03/12 01:45:35 oes
445 * More verbose logging
447 * Revision 1.49 2002/03/09 20:03:52 jongfoster
448 * - Making various functions return int rather than size_t.
449 * (Undoing a recent change). Since size_t is unsigned on
450 * Windows, functions like read_socket that return -1 on
451 * error cannot return a size_t.
453 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
454 * crashes, and also frequently caused JB to jump to 100%
455 * CPU and stay there. (Because it thought it had just
456 * read ((unsigned)-1) == 4Gb of data...)
458 * - The signature of write_socket has changed, it now simply
459 * returns success=0/failure=nonzero.
461 * - Trying to get rid of a few warnings --with-debug on
462 * Windows, I've introduced a new type "jb_socket". This is
463 * used for the socket file descriptors. On Windows, this
464 * is SOCKET (a typedef for unsigned). Everywhere else, it's
465 * an int. The error value can't be -1 any more, so it's
466 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
467 * Windows it maps to the #define INVALID_SOCKET.)
469 * - The signature of bind_port has changed.
471 * Revision 1.48 2002/03/07 03:46:53 oes
472 * Fixed compiler warnings etc
474 * Revision 1.47 2002/02/20 23:15:13 jongfoster
475 * Parsing functions now handle out-of-memory gracefully by returning
478 * Revision 1.46 2002/01/17 21:03:47 jongfoster
479 * Moving all our URL and URL pattern parsing code to urlmatch.c.
481 * Revision 1.45 2002/01/09 14:33:03 oes
482 * Added support for localtime_r.
484 * Revision 1.44 2001/12/14 01:22:54 steudten
485 * Remove 'user:pass@' from 'proto://user:pass@host' for the
486 * new added header 'Host: ..'. (See Req ID 491818)
488 * Revision 1.43 2001/11/23 00:26:38 jongfoster
489 * Fixing two really stupid errors in my previous commit
491 * Revision 1.42 2001/11/22 21:59:30 jongfoster
492 * Adding code to handle +no-cookies-keep
494 * Revision 1.41 2001/11/05 23:43:05 steudten
495 * Add time+date to log files.
497 * Revision 1.40 2001/10/26 20:13:09 jongfoster
498 * ctype.h is needed in Windows, too.
500 * Revision 1.39 2001/10/26 17:40:04 oes
501 * Introduced get_header_value()
502 * Removed http->user_agent, csp->referrer and csp->accept_types
503 * Removed client_accept()
505 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
506 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
507 * threads to call select() simultaneously. So, it's time to do a real, live,
508 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
509 * (native). Both versions will work, but using __OS2__ offers multi-threading.
511 * Revision 1.37 2001/10/23 21:36:02 jongfoster
512 * Documenting sed()'s error behaviou (doc change only)
514 * Revision 1.36 2001/10/13 12:51:51 joergs
515 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
516 * force-load), instead crumble Host: and add it (again) in client_host_adder
517 * (in case we get a HTTP/1.0 request without Host: header and forward it to
518 * a HTTP/1.1 server/proxy).
520 * Revision 1.35 2001/10/09 22:39:21 jongfoster
521 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
524 * Revision 1.34 2001/10/07 18:50:55 oes
525 * Added server_content_encoding, renamed server_transfer_encoding
527 * Revision 1.33 2001/10/07 18:04:49 oes
528 * Changed server_http11 to server_http and its pattern to "HTTP".
529 * Additional functionality: it now saves the HTTP status into
530 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
532 * Revision 1.32 2001/10/07 15:43:28 oes
533 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
534 * client_te and client_accept_encoding_adder, triggered by the new
535 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
536 * changed to allow only identity and chunked, and the TE header is
537 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
539 * parse_http_request no longer does anything than parsing. The rewriting
540 * of http->cmd and version mangling are gone. It now also recognizes
541 * the put and delete methods and saves the url in http->url. Removed
544 * renamed content_type and content_length to have the server_ prefix
546 * server_content_type now only works if csp->content_type != CT_TABOO
548 * added server_transfer_encoding, which
549 * - Sets CT_TABOO to prohibit filtering if encoding compresses
550 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
551 * - Change from "chunked" to "identity" if body was chunked
552 * but has been de-chunked for filtering.
554 * added server_content_md5 which crunches any Content-MD5 headers
555 * if the body was modified.
557 * made server_http11 conditional on +downgrade action
559 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
561 * Revision 1.31 2001/10/05 14:25:02 oes
562 * Crumble Keep-Alive from Server
564 * Revision 1.30 2001/09/29 12:56:03 joergs
565 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
567 * Revision 1.29 2001/09/24 21:09:24 jongfoster
568 * Fixing 2 memory leaks that Guy spotted, where the paramater to
569 * enlist() was not being free()d.
571 * Revision 1.28 2001/09/22 16:32:28 jongfoster
572 * Removing unused #includes.
574 * Revision 1.27 2001/09/20 15:45:25 steudten
576 * add casting from size_t to int for printf()
577 * remove local variable shadow s2
579 * Revision 1.26 2001/09/16 17:05:14 jongfoster
580 * Removing unused #include showarg.h
582 * Revision 1.25 2001/09/16 13:21:27 jongfoster
583 * Changes to use new list functions.
585 * Revision 1.24 2001/09/13 23:05:50 jongfoster
586 * Changing the string paramater to the header parsers a "const".
588 * Revision 1.23 2001/09/12 18:08:19 steudten
590 * In parse_http_request() header rewriting miss the host value, so
591 * from http://www.mydomain.com the result was just " / " not
592 * http://www.mydomain.com/ in case we forward.
594 * Revision 1.22 2001/09/10 10:58:53 oes
595 * Silenced compiler warnings
597 * Revision 1.21 2001/07/31 14:46:00 oes
598 * - Persistant connections now suppressed
599 * - sed() no longer appends empty header to csp->headers
601 * Revision 1.20 2001/07/30 22:08:36 jongfoster
602 * Tidying up #defines:
603 * - All feature #defines are now of the form FEATURE_xxx
604 * - Permanently turned off WIN_GUI_EDIT
605 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
607 * Revision 1.19 2001/07/25 17:21:54 oes
608 * client_uagent now saves copy of User-Agent: header value
610 * Revision 1.18 2001/07/13 14:02:46 oes
611 * - Included fix to repair broken HTTP requests that
612 * don't contain a path, not even '/'.
613 * - Removed all #ifdef PCRS
614 * - content_type now always inspected and classified as
615 * text, gif or other.
616 * - formatting / comments
618 * Revision 1.17 2001/06/29 21:45:41 oes
619 * Indentation, CRLF->LF, Tab-> Space
621 * Revision 1.16 2001/06/29 13:32:42 oes
623 * - Adapted free_http_request
624 * - Removed logentry from cancelled commit
626 * Revision 1.15 2001/06/03 19:12:38 oes
627 * deleted const struct interceptors
629 * Revision 1.14 2001/06/01 18:49:17 jongfoster
630 * Replaced "list_share" with "list" - the tiny memory gain was not
631 * worth the extra complexity.
633 * Revision 1.13 2001/05/31 21:30:33 jongfoster
634 * Removed list code - it's now in list.[ch]
635 * Renamed "permission" to "action", and changed many features
636 * to use the actions file rather than the global config.
638 * Revision 1.12 2001/05/31 17:33:13 oes
642 * Revision 1.11 2001/05/29 20:11:19 joergs
643 * '/ * inside comment' warning removed.
645 * Revision 1.10 2001/05/29 09:50:24 jongfoster
646 * Unified blocklist/imagelist/permissionslist.
647 * File format is still under discussion, but the internal changes
650 * Also modified interceptor behaviour:
651 * - We now intercept all URLs beginning with one of the following
652 * prefixes (and *only* these prefixes):
654 * * http://ijbswa.sf.net/config/
655 * * http://ijbswa.sourceforge.net/config/
656 * - New interceptors "home page" - go to http://i.j.b/ to see it.
657 * - Internal changes so that intercepted and fast redirect pages
658 * are not replaced with an image.
659 * - Interceptors now have the option to send a binary page direct
660 * to the client. (i.e. ijb-send-banner uses this)
661 * - Implemented show-url-info interceptor. (Which is why I needed
662 * the above interceptors changes - a typical URL is
663 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
664 * The previous mechanism would not have intercepted that, and
665 * if it had been intercepted then it then it would have replaced
668 * Revision 1.9 2001/05/28 17:26:33 jongfoster
669 * Fixing segfault if last header was crunched.
670 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
671 * can use the cross-platform sprintf() instead.)
673 * Revision 1.8 2001/05/27 22:17:04 oes
675 * - re_process_buffer no longer writes the modified buffer
676 * to the client, which was very ugly. It now returns the
677 * buffer, which it is then written by chat.
679 * - content_length now adjusts the Content-Length: header
680 * for modified documents rather than crunch()ing it.
681 * (Length info in csp->content_length, which is 0 for
682 * unmodified documents)
684 * - For this to work, sed() is called twice when filtering.
686 * Revision 1.7 2001/05/27 13:19:06 oes
687 * Patched Joergs solution for the content-length in.
689 * Revision 1.6 2001/05/26 13:39:32 jongfoster
690 * Only crunches Content-Length header if applying RE filtering.
691 * Without this fix, Microsoft Windows Update wouldn't work.
693 * Revision 1.5 2001/05/26 00:28:36 jongfoster
694 * Automatic reloading of config file.
695 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
696 * Most of the global variables have been moved to a new
697 * struct configuration_spec, accessed through csp->config->globalname
698 * Most of the globals remaining are used by the Win32 GUI.
700 * Revision 1.4 2001/05/22 18:46:04 oes
702 * - Enabled filtering banners by size rather than URL
703 * by adding patterns that replace all standard banner
704 * sizes with the "Junkbuster" gif to the re_filterfile
706 * - Enabled filtering WebBugs by providing a pattern
707 * which kills all 1x1 images
709 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
710 * which is selected by the (nonstandard and therefore
711 * capital) letter 'U' in the option string.
712 * It causes the quantifiers to be ungreedy by default.
713 * Appending a ? turns back to greedy (!).
715 * - Added a new interceptor ijb-send-banner, which
716 * sends back the "Junkbuster" gif. Without imagelist or
717 * MSIE detection support, or if tinygif = 1, or the
718 * URL isn't recognized as an imageurl, a lame HTML
719 * explanation is sent instead.
721 * - Added new feature, which permits blocking remote
722 * script redirects and firing back a local redirect
724 * The feature is conditionally compiled, i.e. it
725 * can be disabled with --disable-fast-redirects,
726 * plus it must be activated by a "fast-redirects"
727 * line in the config file, has its own log level
728 * and of course wants to be displayed by show-proxy-args
729 * Note: Boy, all the #ifdefs in 1001 locations and
730 * all the fumbling with configure.in and acconfig.h
731 * were *way* more work than the feature itself :-(
733 * - Because a generic redirect template was needed for
734 * this, tinygif = 3 now uses the same.
736 * - Moved GIFs, and other static HTTP response templates
741 * - Removed some >400 CRs again (Jon, you really worked
744 * Revision 1.3 2001/05/20 01:21:20 jongfoster
745 * Version 2.9.4 checkin.
746 * - Merged popupfile and cookiefile, and added control over PCRS
747 * filtering, in new "permissionsfile".
748 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
749 * file error you now get a message box (in the Win32 GUI) rather
750 * than the program exiting with no explanation.
751 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
753 * - Removed tabs from "config"
754 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
755 * - Bumped up version number.
757 * Revision 1.2 2001/05/17 23:02:36 oes
758 * - Made referrer option accept 'L' as a substitute for '§'
760 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
761 * Initial import of version 2.9.3 source tree
764 *********************************************************************/
771 #include <sys/types.h>
781 * Convince GNU's libc to provide a strptime prototype.
784 #endif /*__GLIBC__ */
791 #if !defined(_WIN32) && !defined(__OS2__)
797 #ifdef FEATURE_PTHREAD
799 /* jcc.h is for mutex semapores only */
800 #endif /* def FEATURE_PTHREAD */
806 #include "jbsockets.h"
807 #include "miscutil.h"
812 #ifndef HAVE_STRPTIME
813 #include "strptime.h"
816 const char parsers_h_rcs[] = PARSERS_H_VERSION;
818 /* Fix a problem with Solaris. There should be no effect on other
820 * Solaris's isspace() is a macro which uses its argument directly
821 * as an array index. Therefore we need to make sure that high-bit
822 * characters generate +ve values, and ideally we also want to make
823 * the argument match the declared parameter type of "int".
825 * Why did they write a character function that can't take a simple
826 * "char" argument? Doh!
828 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
829 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
831 static jb_err scan_headers(struct client_state *csp);
832 static jb_err header_tagger(struct client_state *csp, char *header);
833 static jb_err parse_header_time(const char *header_time, time_t *result);
835 static jb_err crumble (struct client_state *csp, char **header);
836 static jb_err connection (struct client_state *csp, char **header);
837 static jb_err filter_header (struct client_state *csp, char **header);
838 static jb_err client_referrer (struct client_state *csp, char **header);
839 static jb_err client_uagent (struct client_state *csp, char **header);
840 static jb_err client_ua (struct client_state *csp, char **header);
841 static jb_err client_from (struct client_state *csp, char **header);
842 static jb_err client_send_cookie (struct client_state *csp, char **header);
843 static jb_err client_x_forwarded (struct client_state *csp, char **header);
844 static jb_err client_accept_encoding (struct client_state *csp, char **header);
845 static jb_err client_te (struct client_state *csp, char **header);
846 static jb_err client_max_forwards (struct client_state *csp, char **header);
847 static jb_err client_host (struct client_state *csp, char **header);
848 static jb_err client_if_modified_since (struct client_state *csp, char **header);
849 static jb_err client_accept_language (struct client_state *csp, char **header);
850 static jb_err client_if_none_match (struct client_state *csp, char **header);
851 static jb_err crunch_client_header (struct client_state *csp, char **header);
852 static jb_err client_x_filter (struct client_state *csp, char **header);
853 static jb_err client_range (struct client_state *csp, char **header);
854 static jb_err server_set_cookie (struct client_state *csp, char **header);
855 static jb_err server_content_type (struct client_state *csp, char **header);
856 static jb_err server_content_length (struct client_state *csp, char **header);
857 static jb_err server_content_md5 (struct client_state *csp, char **header);
858 static jb_err server_content_encoding (struct client_state *csp, char **header);
859 static jb_err server_transfer_coding (struct client_state *csp, char **header);
860 static jb_err server_http (struct client_state *csp, char **header);
861 static jb_err crunch_server_header (struct client_state *csp, char **header);
862 static jb_err server_last_modified (struct client_state *csp, char **header);
863 static jb_err server_content_disposition(struct client_state *csp, char **header);
865 static jb_err client_host_adder (struct client_state *csp);
866 static jb_err client_xtra_adder (struct client_state *csp);
867 static jb_err connection_close_adder (struct client_state *csp);
869 static jb_err create_forged_referrer(char **header, const char *hostport);
870 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
871 static jb_err handle_conditional_hide_referrer_parameter(char **header,
872 const char *host, const int parameter_conditional_block);
874 const struct parsers client_patterns[] = {
875 { "referer:", 8, client_referrer },
876 { "user-agent:", 11, client_uagent },
877 { "ua-", 3, client_ua },
878 { "from:", 5, client_from },
879 { "cookie:", 7, client_send_cookie },
880 { "x-forwarded-for:", 16, client_x_forwarded },
881 { "Accept-Encoding:", 16, client_accept_encoding },
882 { "TE:", 3, client_te },
883 { "Host:", 5, client_host },
884 { "if-modified-since:", 18, client_if_modified_since },
885 { "Keep-Alive:", 11, crumble },
886 { "connection:", 11, connection },
887 { "proxy-connection:", 17, crumble },
888 { "max-forwards:", 13, client_max_forwards },
889 { "Accept-Language:", 16, client_accept_language },
890 { "if-none-match:", 14, client_if_none_match },
891 { "Range:", 6, client_range },
892 { "Request-Range:", 14, client_range },
893 { "If-Range:", 9, client_range },
894 { "X-Filter:", 9, client_x_filter },
895 { "*", 0, crunch_client_header },
896 { "*", 0, filter_header },
900 const struct parsers server_patterns[] = {
901 { "HTTP/", 5, server_http },
902 { "set-cookie:", 11, server_set_cookie },
903 { "connection:", 11, connection },
904 { "Content-Type:", 13, server_content_type },
905 { "Content-MD5:", 12, server_content_md5 },
906 { "Content-Encoding:", 17, server_content_encoding },
907 { "Transfer-Encoding:", 18, server_transfer_coding },
908 { "Keep-Alive:", 11, crumble },
909 { "content-disposition:", 20, server_content_disposition },
910 { "Last-Modified:", 14, server_last_modified },
911 { "*", 0, crunch_server_header },
912 { "*", 0, filter_header },
916 const struct parsers server_patterns_light[] = {
917 { "Content-Length:", 15, server_content_length },
918 { "Transfer-Encoding:", 18, server_transfer_coding },
920 { "Content-Encoding:", 17, server_content_encoding },
921 #endif /* def FEATURE_ZLIB */
925 const add_header_func_ptr add_client_headers[] = {
928 /* Temporarily disabled: client_accept_encoding_adder, */
929 connection_close_adder,
933 const add_header_func_ptr add_server_headers[] = {
934 connection_close_adder,
938 /*********************************************************************
940 * Function : flush_socket
942 * Description : Write any pending "buffered" content.
945 * 1 : fd = file descriptor of the socket to read
946 * 2 : iob = The I/O buffer to flush, usually csp->iob.
948 * Returns : On success, the number of bytes written are returned (zero
949 * indicates nothing was written). On error, -1 is returned,
950 * and errno is set appropriately. If count is zero and the
951 * file descriptor refers to a regular file, 0 will be
952 * returned without causing any other effect. For a special
953 * file, the results are not portable.
955 *********************************************************************/
956 int flush_socket(jb_socket fd, struct iob *iob)
958 int len = iob->eod - iob->cur;
965 if (write_socket(fd, iob->cur, (size_t)len))
969 iob->eod = iob->cur = iob->buf;
975 /*********************************************************************
977 * Function : add_to_iob
979 * Description : Add content to the buffered page, expanding the
980 * buffer if necessary.
983 * 1 : csp = Current client state (buffers, headers, etc...)
984 * 2 : buf = holds the content to be added to the page
985 * 3 : n = number of bytes to be added
987 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
988 * or buffer limit reached.
990 *********************************************************************/
991 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
993 struct iob *iob = csp->iob;
994 size_t used, offset, need, want;
997 if (n <= 0) return JB_ERR_OK;
999 used = (size_t)(iob->eod - iob->buf);
1000 offset = (size_t)(iob->cur - iob->buf);
1001 need = used + (size_t)n + 1;
1004 * If the buffer can't hold the new data, extend it first.
1005 * Use the next power of two if possible, else use the actual need.
1007 if (need > csp->config->buffer_limit)
1009 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1010 return JB_ERR_MEMORY;
1013 if (need > iob->size)
1015 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1017 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1021 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1027 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1028 return JB_ERR_MEMORY;
1031 /* Update the iob pointers */
1032 iob->cur = p + offset;
1033 iob->eod = p + used;
1037 /* copy the new data into the iob buffer */
1038 memcpy(iob->eod, buf, (size_t)n);
1040 /* point to the end of the data */
1043 /* null terminate == cheap insurance */
1052 /*********************************************************************
1054 * Function : decompress_iob
1056 * Description : Decompress buffered page, expanding the
1057 * buffer as necessary. csp->iob->cur
1058 * should point to the the beginning of the
1059 * compressed data block.
1062 * 1 : csp = Current client state (buffers, headers, etc...)
1064 * Returns : JB_ERR_OK on success,
1065 * JB_ERR_MEMORY if out-of-memory limit reached, and
1066 * JB_ERR_COMPRESS if error decompressing buffer.
1068 *********************************************************************/
1069 jb_err decompress_iob(struct client_state *csp)
1071 char *buf; /* new, uncompressed buffer */
1072 char *cur; /* Current iob position (to keep the original
1073 * iob->cur unmodified if we return early) */
1074 size_t bufsize; /* allocated size of the new buffer */
1075 size_t old_size; /* Content size before decompression */
1076 size_t skip_size; /* Number of bytes at the beginning of the iob
1077 that we should NOT decompress. */
1078 int status; /* return status of the inflate() call */
1079 z_stream zstr; /* used by calls to zlib */
1081 assert(csp->iob->cur - csp->iob->buf > 0);
1082 assert(csp->iob->eod - csp->iob->cur > 0);
1084 bufsize = csp->iob->size;
1085 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1086 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1088 cur = csp->iob->cur;
1093 * This is to protect the parsing of gzipped data,
1094 * but it should(?) be valid for deflated data also.
1096 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1097 return JB_ERR_COMPRESS;
1100 if (csp->content_type & CT_GZIP)
1103 * Our task is slightly complicated by the facts that data
1104 * compressed by gzip does not include a zlib header, and
1105 * that there is no easily accessible interface in zlib to
1106 * handle a gzip header. We strip off the gzip header by
1107 * hand, and later inform zlib not to expect a header.
1111 * Strip off the gzip header. Please see RFC 1952 for more
1112 * explanation of the appropriate fields.
1114 if ((*cur++ != (char)0x1f)
1115 || (*cur++ != (char)0x8b)
1116 || (*cur++ != Z_DEFLATED))
1118 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1119 return JB_ERR_COMPRESS;
1125 * XXX: These magic numbers should be replaced
1126 * with macros to give a better idea what they do.
1130 /* The gzip header has reserved bits set; bail out. */
1131 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1132 return JB_ERR_COMPRESS;
1136 /* Skip extra fields if necessary. */
1140 * Skip a given number of bytes, specified
1141 * as a 16-bit little-endian value.
1144 * XXX: This code used to be:
1146 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1148 * which I had to change into:
1150 * cur += *cur++ + (*cur++ << 8);
1152 * at which point gcc43 finally noticed that the value
1153 * of cur is undefined (it depends on which of the
1154 * summands is evaluated first).
1156 * I haven't come across a site where this
1157 * code is actually executed yet, but I hope
1161 skip_bytes = *cur++;
1162 skip_bytes = *cur++ << 8;
1164 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1167 * The number of bytes to skip should be positive
1168 * and we'd like to stay in the buffer.
1170 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1172 log_error(LOG_LEVEL_ERROR,
1173 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1175 return JB_ERR_COMPRESS;
1177 log_error(LOG_LEVEL_INFO,
1178 "Skipping %d bytes for gzip compression. Does this sound right?",
1183 /* Skip the filename if necessary. */
1186 /* A null-terminated string is supposed to follow. */
1187 while (*cur++ && (cur < csp->iob->eod));
1191 /* Skip the comment if necessary. */
1194 /* A null-terminated string is supposed to follow. */
1195 while (*cur++ && (cur < csp->iob->eod));
1198 /* Skip the CRC if necessary. */
1204 if (cur >= csp->iob->eod)
1207 * If the current position pointer reached or passed
1208 * the buffer end, we were obviously tricked to skip
1211 log_error(LOG_LEVEL_ERROR,
1212 "Malformed gzip header detected. Aborting decompression.");
1213 return JB_ERR_COMPRESS;
1217 else if (csp->content_type & CT_DEFLATE)
1220 * XXX: The debug level should be lowered
1221 * before the next stable release.
1223 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1225 * In theory (that is, according to RFC 1950), deflate-compressed
1226 * data should begin with a two-byte zlib header and have an
1227 * adler32 checksum at the end. It seems that in practice only
1228 * the raw compressed data is sent. Note that this means that
1229 * we are not RFC 1950-compliant here, but the advantage is that
1230 * this actually works. :)
1232 * We add a dummy null byte to tell zlib where the data ends,
1233 * and later inform it not to expect a header.
1235 * Fortunately, add_to_iob() has thoughtfully null-terminated
1236 * the buffer; we can just increment the end pointer to include
1243 log_error(LOG_LEVEL_ERROR,
1244 "Unable to determine compression format for decompression");
1245 return JB_ERR_COMPRESS;
1248 /* Set up the fields required by zlib. */
1249 zstr.next_in = (Bytef *)cur;
1250 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1251 zstr.zalloc = Z_NULL;
1252 zstr.zfree = Z_NULL;
1253 zstr.opaque = Z_NULL;
1256 * Passing -MAX_WBITS to inflateInit2 tells the library
1257 * that there is no zlib header.
1259 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1261 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1262 return JB_ERR_COMPRESS;
1266 * Next, we allocate new storage for the inflated data.
1267 * We don't modify the existing iob yet, so in case there
1268 * is error in decompression we can recover gracefully.
1270 buf = zalloc(bufsize);
1273 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1274 return JB_ERR_MEMORY;
1277 assert(bufsize >= skip_size);
1278 memcpy(buf, csp->iob->buf, skip_size);
1279 zstr.avail_out = bufsize - skip_size;
1280 zstr.next_out = (Bytef *)buf + skip_size;
1282 /* Try to decompress the whole stream in one shot. */
1283 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1285 /* We need to allocate more memory for the output buffer. */
1287 char *tmpbuf; /* used for realloc'ing the buffer */
1288 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1291 * If zlib wants more data then there's a problem, because
1292 * the complete compressed file should have been buffered.
1294 if (0 == zstr.avail_in)
1296 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1297 return JB_ERR_COMPRESS;
1301 * If we tried the limit and still didn't have enough
1302 * memory, just give up.
1304 if (bufsize == csp->config->buffer_limit)
1306 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1307 return JB_ERR_MEMORY;
1310 /* Try doubling the buffer size each time. */
1313 /* Don't exceed the buffer limit. */
1314 if (bufsize > csp->config->buffer_limit)
1316 bufsize = csp->config->buffer_limit;
1319 /* Try to allocate the new buffer. */
1320 tmpbuf = realloc(buf, bufsize);
1323 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1325 return JB_ERR_MEMORY;
1329 char *oldnext_out = (char *)zstr.next_out;
1332 * Update the fields for inflate() to use the new
1333 * buffer, which may be in a location different from
1336 zstr.avail_out += bufsize - oldbufsize;
1337 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1340 * Compare with an uglier method of calculating these values
1341 * that doesn't require the extra oldbufsize variable.
1343 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1344 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1345 assert(zstr.avail_out > 0);
1351 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1353 log_error(LOG_LEVEL_ERROR,
1354 "Inconsistent stream state after decompression: %s", zstr.msg);
1356 * XXX: Intentionally no return.
1358 * According to zlib.h, Z_STREAM_ERROR is returned
1359 * "if the stream state was inconsistent".
1361 * I assume in this case inflate()'s status
1362 * would also be something different than Z_STREAM_END
1363 * so this check should be redundant, but lets see.
1367 if (status != Z_STREAM_END)
1369 /* We failed to decompress the stream. */
1370 log_error(LOG_LEVEL_ERROR,
1371 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1372 return JB_ERR_COMPRESS;
1376 * Finally, we can actually update the iob, since the
1377 * decompression was successful. First, free the old
1380 freez(csp->iob->buf);
1382 /* Now, update the iob to use the new buffer. */
1383 csp->iob->buf = buf;
1384 csp->iob->cur = csp->iob->buf + skip_size;
1385 csp->iob->eod = (char *)zstr.next_out;
1386 csp->iob->size = bufsize;
1389 * Make sure the new uncompressed iob obeys some minimal
1390 * consistency conditions.
1392 if ((csp->iob->buf < csp->iob->cur)
1393 && (csp->iob->cur <= csp->iob->eod)
1394 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1396 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1399 log_error(LOG_LEVEL_RE_FILTER,
1400 "Decompression successful. Old size: %d, new size: %d.",
1401 old_size, new_size);
1405 /* zlib thinks this is OK, so lets do the same. */
1406 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1411 /* It seems that zlib did something weird. */
1412 log_error(LOG_LEVEL_ERROR,
1413 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1414 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1415 csp->iob->eod, csp->iob->buf + csp->iob->size);
1416 return JB_ERR_COMPRESS;
1422 #endif /* defined(FEATURE_ZLIB) */
1425 /*********************************************************************
1427 * Function : get_header
1429 * Description : This (odd) routine will parse the csp->iob
1432 * 1 : csp = Current client state (buffers, headers, etc...)
1434 * Returns : Any one of the following:
1436 * 1) a pointer to a dynamically allocated string that contains a header line
1437 * 2) NULL indicating that the end of the header was reached
1438 * 3) "" indicating that the end of the iob was reached before finding
1439 * a complete header line.
1441 *********************************************************************/
1442 char *get_header(struct client_state *csp)
1448 if ((iob->cur == NULL)
1449 || ((p = strchr(iob->cur, '\n')) == NULL))
1451 return(""); /* couldn't find a complete header */
1456 ret = strdup(iob->cur);
1459 /* FIXME No way to handle error properly */
1460 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1465 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1467 /* is this a blank line (i.e. the end of the header) ? */
1479 /*********************************************************************
1481 * Function : get_header_value
1483 * Description : Get the value of a given header from a chained list
1484 * of header lines or return NULL if no such header is
1485 * present in the list.
1488 * 1 : header_list = pointer to list
1489 * 2 : header_name = string with name of header to look for.
1490 * Trailing colon required, capitalization
1493 * Returns : NULL if not found, else value of header
1495 *********************************************************************/
1496 char *get_header_value(const struct list *header_list, const char *header_name)
1498 struct list_entry *cur_entry;
1502 assert(header_list);
1503 assert(header_name);
1504 length = strlen(header_name);
1506 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1510 if (!strncmpic(cur_entry->str, header_name, length))
1513 * Found: return pointer to start of value
1515 ret = (char *) (cur_entry->str + length);
1516 while (*ret && ijb_isspace(*ret)) ret++;
1530 /*********************************************************************
1532 * Function : scan_headers
1534 * Description : Scans headers, applies tags and updates action bits.
1537 * 1 : csp = Current client state (buffers, headers, etc...)
1539 * Returns : JB_ERR_OK
1541 *********************************************************************/
1542 static jb_err scan_headers(struct client_state *csp)
1544 struct list_entry *h; /* Header */
1545 jb_err err = JB_ERR_OK;
1547 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1549 /* Header crunch()ed in previous run? -> ignore */
1550 if (h->str == NULL) continue;
1551 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1552 err = header_tagger(csp, h->str);
1559 /*********************************************************************
1563 * Description : add, delete or modify lines in the HTTP header streams.
1564 * On entry, it receives a linked list of headers space
1565 * that was allocated dynamically (both the list nodes
1566 * and the header contents).
1568 * As a side effect it frees the space used by the original
1571 * XXX: should be split to remove the first_run hack.
1574 * 1 : pats = list of patterns to match against headers
1575 * 2 : more_headers = list of functions to add more
1576 * headers (client or server)
1577 * 3 : csp = Current client state (buffers, headers, etc...)
1579 * Returns : JB_ERR_OK in case off success, or
1580 * JB_ERR_MEMORY on out-of-memory error.
1582 *********************************************************************/
1583 jb_err sed(const struct parsers pats[],
1584 const add_header_func_ptr more_headers[],
1585 struct client_state *csp)
1587 struct list_entry *p;
1588 const struct parsers *v;
1589 const add_header_func_ptr *f;
1590 jb_err err = JB_ERR_OK;
1594 * If filtering is enabled, sed is run twice,
1595 * but most of the work needs to be done only once.
1597 first_run = (more_headers != NULL ) ? 1 : 0;
1599 if (first_run) /* Parse and print */
1603 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1605 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1607 /* Header crunch()ed in previous run? -> ignore */
1608 if (p->str == NULL) continue;
1610 /* Does the current parser handle this header? */
1611 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1613 err = v->parser(csp, (char **)&(p->str));
1617 /* place any additional headers on the csp->headers list */
1618 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1623 else /* Parse only */
1626 * The second run is only needed if the body was modified
1627 * and the content-lenght has changed.
1629 if (strncmpic(csp->http->cmd, "HEAD", 4))
1631 /*XXX: Code duplication */
1632 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1634 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1636 /* Header crunch()ed in previous run? -> ignore */
1637 if (p->str == NULL) continue;
1639 /* Does the current parser handle this header? */
1640 if (strncmpic(p->str, v->str, v->len) == 0)
1642 err = v->parser(csp, (char **)&(p->str));
1654 /*********************************************************************
1656 * Function : header_tagger
1658 * Description : Executes all text substitutions from applying
1659 * tag actions and saves the result as tag.
1661 * XXX: Shares enough code with filter_header() and
1662 * pcrs_filter_response() to warrant some helper functions.
1665 * 1 : csp = Current client state (buffers, headers, etc...)
1666 * 2 : header = Header that is used as tagger input
1668 * Returns : JB_ERR_OK on success and always succeeds
1670 *********************************************************************/
1671 static jb_err header_tagger(struct client_state *csp, char *header)
1673 int wanted_filter_type;
1674 int multi_action_index;
1678 struct file_list *fl;
1679 struct re_filterfile_spec *b;
1680 struct list_entry *tag_name;
1682 int found_filters = 0;
1683 const size_t header_length = strlen(header);
1685 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1687 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1688 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1692 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1693 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1696 /* Check if there are any filters */
1697 for (i = 0; i < MAX_AF_FILES; i++)
1710 if (0 == found_filters)
1712 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1713 "tagging enabled, but no taggers available.");
1717 for (i = 0; i < MAX_AF_FILES; i++)
1720 if ((NULL == fl) || (NULL == fl->f))
1723 * Either there are no filter files
1724 * left, or this filter file just
1725 * contains no valid filters.
1727 * Continue to be sure we don't miss
1728 * valid filter files that are chained
1729 * after empty or invalid ones.
1734 /* For all filters, */
1735 for (b = fl->f; b; b = b->next)
1737 if (b->type != wanted_filter_type)
1739 /* skip the ones we don't care about, */
1742 /* leaving only taggers that could apply, of which we use the ones, */
1743 for (tag_name = csp->action->multi[multi_action_index]->first;
1744 NULL != tag_name; tag_name = tag_name->next)
1746 /* that do apply, and */
1747 if (strcmp(b->name, tag_name->str) == 0)
1749 char *modified_tag = NULL;
1751 size_t size = header_length;
1752 pcrs_job *joblist = b->joblist;
1754 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1756 if (NULL == joblist)
1758 log_error(LOG_LEVEL_RE_FILTER,
1759 "Tagger %s has empty joblist. Nothing to do.", b->name);
1763 /* execute their pcrs_joblist on the header. */
1764 for (job = joblist; NULL != job; job = job->next)
1766 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1770 /* Success, continue with the modified version. */
1779 /* Tagger doesn't match */
1782 /* Regex failure, log it but continue anyway. */
1783 log_error(LOG_LEVEL_ERROR,
1784 "Problems with tagger \'%s\' and header \'%s\': %s",
1785 b->name, *header, pcrs_strerror(hits));
1787 freez(modified_tag);
1791 if (b->dynamic) pcrs_free_joblist(joblist);
1793 /* If this tagger matched */
1799 * There is to technical limitation which makes
1800 * it impossible to use empty tags, but I assume
1801 * no one would do it intentionally.
1804 log_error(LOG_LEVEL_INFO,
1805 "Tagger \'%s\' created an empty tag. Ignored.",
1810 if (!list_contains_item(csp->tags, tag))
1812 if (JB_ERR_OK != enlist(csp->tags, tag))
1814 log_error(LOG_LEVEL_ERROR,
1815 "Insufficient memory to add tag \'%s\', "
1816 "based on tagger \'%s\' and header \'%s\'",
1817 tag, b->name, *header);
1821 char *action_message;
1823 * update the action bits right away, to make
1824 * tagging based on tags set by earlier taggers
1825 * of the same kind possible.
1827 if (update_action_bits_for_tag(csp, tag))
1829 action_message = "Action bits updated accordingly.";
1833 action_message = "No action bits update necessary.";
1836 log_error(LOG_LEVEL_HEADER,
1837 "Tagger \'%s\' added tag \'%s\'. %s",
1838 b->name, tag, action_message);
1843 /* XXX: Is this log-worthy? */
1844 log_error(LOG_LEVEL_HEADER,
1845 "Tagger \'%s\' didn't add tag \'%s\'. "
1846 "Tag already present", b->name, tag);
1849 } /* if the tagger matched */
1850 } /* if the tagger applies */
1851 } /* for every tagger that could apply */
1852 } /* for all filters */
1853 } /* for all filter files */
1858 /* here begins the family of parser functions that reformat header lines */
1860 /*********************************************************************
1862 * Function : filter_header
1864 * Description : Executes all text substitutions from all applying
1865 * +(server|client)-header-filter actions on the header.
1866 * Most of the code was copied from pcrs_filter_response,
1867 * including the rather short variable names
1870 * 1 : csp = Current client state (buffers, headers, etc...)
1871 * 2 : header = On input, pointer to header to modify.
1872 * On output, pointer to the modified header, or NULL
1873 * to remove the header. This function frees the
1874 * original string if necessary.
1876 * Returns : JB_ERR_OK on success and always succeeds
1878 *********************************************************************/
1879 static jb_err filter_header(struct client_state *csp, char **header)
1883 size_t size = strlen(*header);
1885 char *newheader = NULL;
1888 struct file_list *fl;
1889 struct re_filterfile_spec *b;
1890 struct list_entry *filtername;
1892 int i, found_filters = 0;
1893 int wanted_filter_type;
1894 int multi_action_index;
1896 if (csp->flags & CSP_FLAG_NO_FILTERING)
1901 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1903 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1904 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1908 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1909 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1913 * Need to check the set of re_filterfiles...
1915 for (i = 0; i < MAX_AF_FILES; i++)
1928 if (0 == found_filters)
1930 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1931 "header filtering enabled, but no matching filters available.");
1935 for (i = 0; i < MAX_AF_FILES; i++)
1938 if ((NULL == fl) || (NULL == fl->f))
1941 * Either there are no filter files
1942 * left, or this filter file just
1943 * contains no valid filters.
1945 * Continue to be sure we don't miss
1946 * valid filter files that are chained
1947 * after empty or invalid ones.
1952 * For all applying +filter actions, look if a filter by that
1953 * name exists and if yes, execute its pcrs_joblist on the
1956 for (b = fl->f; b; b = b->next)
1958 if (b->type != wanted_filter_type)
1960 /* Skip other filter types */
1964 for (filtername = csp->action->multi[multi_action_index]->first;
1965 filtername ; filtername = filtername->next)
1967 if (strcmp(b->name, filtername->str) == 0)
1969 int current_hits = 0;
1970 pcrs_job *joblist = b->joblist;
1972 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1974 if (NULL == joblist)
1976 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1980 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1981 *header, size, b->name);
1983 /* Apply all jobs from the joblist */
1984 for (job = joblist; NULL != job; job = job->next)
1986 matches = pcrs_execute(job, *header, size, &newheader, &size);
1989 current_hits += matches;
1990 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1992 *header = newheader;
1994 else if ( 0 == matches )
1996 /* Filter doesn't change header */
2002 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2003 *header, b->name, pcrs_strerror(matches));
2004 if (newheader != NULL)
2006 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2012 if (b->dynamic) pcrs_free_joblist(joblist);
2014 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2015 hits += current_hits;
2022 * Additionally checking for hits is important because if
2023 * the continue hack is triggered, server headers can
2024 * arrive empty to separate multiple heads from each other.
2026 if ((0 == size) && hits)
2028 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2036 /*********************************************************************
2038 * Function : connection
2040 * Description : Makes sure that the value of the Connection: header
2041 * is "close" and signals connection_close_adder
2045 * 1 : csp = Current client state (buffers, headers, etc...)
2046 * 2 : header = On input, pointer to header to modify.
2047 * On output, pointer to the modified header, or NULL
2048 * to remove the header. This function frees the
2049 * original string if necessary.
2051 * Returns : JB_ERR_OK on success, or
2052 * JB_ERR_MEMORY on out-of-memory error.
2054 *********************************************************************/
2055 static jb_err connection(struct client_state *csp, char **header)
2057 char *old_header = *header;
2059 /* Do we have a 'Connection: close' header? */
2060 if (strcmpic(*header, "Connection: close"))
2062 /* No, create one */
2063 *header = strdup("Connection: close");
2066 return JB_ERR_MEMORY;
2068 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2072 /* Signal connection_close_adder() to return early. */
2073 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2075 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2079 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2086 /*********************************************************************
2088 * Function : crumble
2090 * Description : This is called if a header matches a pattern to "crunch"
2093 * 1 : csp = Current client state (buffers, headers, etc...)
2094 * 2 : header = On input, pointer to header to modify.
2095 * On output, pointer to the modified header, or NULL
2096 * to remove the header. This function frees the
2097 * original string if necessary.
2099 * Returns : JB_ERR_OK on success, or
2100 * JB_ERR_MEMORY on out-of-memory error.
2102 *********************************************************************/
2103 static jb_err crumble(struct client_state *csp, char **header)
2105 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2111 /*********************************************************************
2113 * Function : crunch_server_header
2115 * Description : Crunch server header if it matches a string supplied by the
2116 * user. Called from `sed'.
2119 * 1 : csp = Current client state (buffers, headers, etc...)
2120 * 2 : header = On input, pointer to header to modify.
2121 * On output, pointer to the modified header, or NULL
2122 * to remove the header. This function frees the
2123 * original string if necessary.
2125 * Returns : JB_ERR_OK on success and always succeeds
2127 *********************************************************************/
2128 static jb_err crunch_server_header(struct client_state *csp, char **header)
2130 const char *crunch_pattern;
2132 /* Do we feel like crunching? */
2133 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2135 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2137 /* Is the current header the lucky one? */
2138 if (strstr(*header, crunch_pattern))
2140 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2149 /*********************************************************************
2151 * Function : server_content_type
2153 * Description : Set the content-type for filterable types (text/.*,
2154 * .*xml.*, javascript and image/gif) unless filtering has been
2155 * forbidden (CT_TABOO) while parsing earlier headers.
2156 * NOTE: Since text/plain is commonly used by web servers
2157 * for files whose correct type is unknown, we don't
2158 * set CT_TEXT for it.
2161 * 1 : csp = Current client state (buffers, headers, etc...)
2162 * 2 : header = On input, pointer to header to modify.
2163 * On output, pointer to the modified header, or NULL
2164 * to remove the header. This function frees the
2165 * original string if necessary.
2167 * Returns : JB_ERR_OK on success, or
2168 * JB_ERR_MEMORY on out-of-memory error.
2170 *********************************************************************/
2171 static jb_err server_content_type(struct client_state *csp, char **header)
2173 /* Remove header if it isn't the first Content-Type header */
2174 if ((csp->content_type & CT_DECLARED))
2177 * Another, slightly slower, way to see if
2178 * we already parsed another Content-Type header.
2180 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2182 log_error(LOG_LEVEL_ERROR,
2183 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2191 * Signal that the Content-Type has been set.
2193 csp->content_type |= CT_DECLARED;
2195 if (!(csp->content_type & CT_TABOO))
2198 * XXX: The assumption that text/plain is a sign of
2199 * binary data seems to be somewhat unreasonable nowadays
2200 * and should be dropped after 3.0.8 is out.
2202 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2203 || strstr(*header, "xml")
2204 || strstr(*header, "application/x-javascript"))
2206 csp->content_type |= CT_TEXT;
2208 else if (strstr(*header, "image/gif"))
2210 csp->content_type |= CT_GIF;
2215 * Are we messing with the content type?
2217 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2220 * Make sure the user doesn't accidently
2221 * change the content type of binary documents.
2223 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2226 *header = strdup("Content-Type: ");
2227 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2231 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2232 return JB_ERR_MEMORY;
2234 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2238 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2239 "It doesn't look like a content type that should be filtered. "
2240 "Enable force-text-mode if you know what you're doing.", *header);
2248 /*********************************************************************
2250 * Function : server_transfer_coding
2252 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2253 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2254 * - Remove header if body was chunked but has been
2255 * de-chunked for filtering.
2258 * 1 : csp = Current client state (buffers, headers, etc...)
2259 * 2 : header = On input, pointer to header to modify.
2260 * On output, pointer to the modified header, or NULL
2261 * to remove the header. This function frees the
2262 * original string if necessary.
2264 * Returns : JB_ERR_OK on success, or
2265 * JB_ERR_MEMORY on out-of-memory error.
2267 *********************************************************************/
2268 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2271 * Turn off pcrs and gif filtering if body compressed
2273 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2277 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2279 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2280 csp->http->cmd, *header);
2281 #endif /* def FEATURE_ZLIB */
2282 csp->content_type = CT_TABOO;
2286 * Raise flag if body chunked
2288 if (strstr(*header, "chunked"))
2290 csp->flags |= CSP_FLAG_CHUNKED;
2293 * If the body was modified, it has been de-chunked first
2294 * and the header must be removed.
2296 * FIXME: If there is more than one transfer encoding,
2297 * only the "chunked" part should be removed here.
2299 if (csp->flags & CSP_FLAG_MODIFIED)
2301 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2310 /*********************************************************************
2312 * Function : server_content_encoding
2314 * Description : This function is run twice for each request,
2315 * unless FEATURE_ZLIB and filtering are disabled.
2317 * The first run is used to check if the content
2318 * is compressed, if FEATURE_ZLIB is disabled
2319 * filtering is then disabled as well, if FEATURE_ZLIB
2320 * is enabled the content is marked for decompression.
2322 * The second run is used to remove the Content-Encoding
2323 * header if the decompression was successful.
2326 * 1 : csp = Current client state (buffers, headers, etc...)
2327 * 2 : header = On input, pointer to header to modify.
2328 * On output, pointer to the modified header, or NULL
2329 * to remove the header. This function frees the
2330 * original string if necessary.
2332 * Returns : JB_ERR_OK on success, or
2333 * JB_ERR_MEMORY on out-of-memory error.
2335 *********************************************************************/
2336 static jb_err server_content_encoding(struct client_state *csp, char **header)
2339 if ((csp->flags & CSP_FLAG_MODIFIED)
2340 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2343 * We successfully decompressed the content,
2344 * and have to clean the header now, so the
2345 * client no longer expects compressed data..
2347 * XXX: There is a difference between cleaning
2348 * and removing it completely.
2350 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2353 else if (strstr(*header, "gzip"))
2355 /* Mark for gzip decompression */
2356 csp->content_type |= CT_GZIP;
2358 else if (strstr(*header, "deflate"))
2360 /* Mark for zlib decompression */
2361 csp->content_type |= CT_DEFLATE;
2363 else if (strstr(*header, "compress"))
2366 * We can't decompress this; therefore we can't filter
2369 csp->content_type |= CT_TABOO;
2371 #else /* !defined(FEATURE_ZLIB) */
2372 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2375 * Body is compressed, turn off pcrs and gif filtering.
2377 csp->content_type |= CT_TABOO;
2380 * Log a warning if the user expects the content to be filtered.
2382 if ((csp->rlist != NULL) &&
2383 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2385 log_error(LOG_LEVEL_INFO,
2386 "Compressed content detected, content filtering disabled. "
2387 "Consider recompiling Privoxy with zlib support or "
2388 "enable the prevent-compression action.");
2391 #endif /* defined(FEATURE_ZLIB) */
2398 /*********************************************************************
2400 * Function : server_content_length
2402 * Description : Adjust Content-Length header if we modified
2406 * 1 : csp = Current client state (buffers, headers, etc...)
2407 * 2 : header = On input, pointer to header to modify.
2408 * On output, pointer to the modified header, or NULL
2409 * to remove the header. This function frees the
2410 * original string if necessary.
2412 * Returns : JB_ERR_OK on success, or
2413 * JB_ERR_MEMORY on out-of-memory error.
2415 *********************************************************************/
2416 static jb_err server_content_length(struct client_state *csp, char **header)
2418 const size_t max_header_length = 80;
2420 /* Regenerate header if the content was modified. */
2421 if (csp->flags & CSP_FLAG_MODIFIED)
2424 *header = (char *) zalloc(max_header_length);
2425 if (*header == NULL)
2427 return JB_ERR_MEMORY;
2430 snprintf(*header, max_header_length, "Content-Length: %d",
2431 (int)csp->content_length);
2432 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2433 (int)csp->content_length);
2440 /*********************************************************************
2442 * Function : server_content_md5
2444 * Description : Crumble any Content-MD5 headers if the document was
2445 * modified. FIXME: Should we re-compute instead?
2448 * 1 : csp = Current client state (buffers, headers, etc...)
2449 * 2 : header = On input, pointer to header to modify.
2450 * On output, pointer to the modified header, or NULL
2451 * to remove the header. This function frees the
2452 * original string if necessary.
2454 * Returns : JB_ERR_OK on success, or
2455 * JB_ERR_MEMORY on out-of-memory error.
2457 *********************************************************************/
2458 static jb_err server_content_md5(struct client_state *csp, char **header)
2460 if (csp->flags & CSP_FLAG_MODIFIED)
2462 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2470 /*********************************************************************
2472 * Function : server_content_disposition
2474 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2475 * Called from `sed'.
2478 * 1 : csp = Current client state (buffers, headers, etc...)
2479 * 2 : header = On input, pointer to header to modify.
2480 * On output, pointer to the modified header, or NULL
2481 * to remove the header. This function frees the
2482 * original string if necessary.
2484 * Returns : JB_ERR_OK on success, or
2485 * JB_ERR_MEMORY on out-of-memory error.
2487 *********************************************************************/
2488 static jb_err server_content_disposition(struct client_state *csp, char **header)
2493 * Are we messing with the Content-Disposition header?
2495 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2501 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2503 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2506 * Blocking content-disposition header
2508 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2515 * Replacing Content-Disposition header
2518 *header = strdup("Content-Disposition: ");
2519 string_append(header, newval);
2521 if (*header != NULL)
2523 log_error(LOG_LEVEL_HEADER,
2524 "Content-Disposition header crunched and replaced with: %s", *header);
2527 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2531 /*********************************************************************
2533 * Function : server_last_modified
2535 * Description : Changes Last-Modified header to the actual date
2536 * to help hide-if-modified-since.
2537 * Called from `sed'.
2540 * 1 : csp = Current client state (buffers, headers, etc...)
2541 * 2 : header = On input, pointer to header to modify.
2542 * On output, pointer to the modified header, or NULL
2543 * to remove the header. This function frees the
2544 * original string if necessary.
2546 * Returns : JB_ERR_OK on success, or
2547 * JB_ERR_MEMORY on out-of-memory error.
2549 *********************************************************************/
2550 static jb_err server_last_modified(struct client_state *csp, char **header)
2553 char buf[BUFFER_SIZE];
2556 #ifdef HAVE_GMTIME_R
2559 struct tm *timeptr = NULL;
2560 time_t now, last_modified;
2562 long int days, hours, minutes, seconds;
2565 * Are we messing with the Last-Modified header?
2567 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2573 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2575 if (0 == strcmpic(newval, "block") )
2578 * Blocking Last-Modified header. Useless but why not.
2580 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2584 else if (0 == strcmpic(newval, "reset-to-request-time"))
2587 * Setting Last-Modified Header to now.
2589 get_http_time(0, buf, sizeof(buf));
2591 *header = strdup("Last-Modified: ");
2592 string_append(header, buf);
2594 if (*header == NULL)
2596 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2600 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2603 else if (0 == strcmpic(newval, "randomize"))
2605 const char *header_time = *header + sizeof("Last-Modified:");
2607 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2609 #ifdef HAVE_GMTIME_R
2610 timeptr = gmtime_r(&now, &gmt);
2611 #elif FEATURE_PTHREAD
2612 pthread_mutex_lock(&gmtime_mutex);
2613 timeptr = gmtime(&now);
2614 pthread_mutex_unlock(&gmtime_mutex);
2616 timeptr = gmtime(&now);
2618 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2620 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2625 rtime = (long int)difftime(now, last_modified);
2634 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2636 rtime = pick_from_range(rtime);
2637 if (negative) rtime *= -1;
2638 last_modified += rtime;
2639 #ifdef HAVE_GMTIME_R
2640 timeptr = gmtime_r(&last_modified, &gmt);
2641 #elif FEATURE_PTHREAD
2642 pthread_mutex_lock(&gmtime_mutex);
2643 timeptr = gmtime(&last_modified);
2644 pthread_mutex_unlock(&gmtime_mutex);
2646 timeptr = gmtime(&last_modified);
2648 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2650 *header = strdup("Last-Modified: ");
2651 string_append(header, newheader);
2653 if (*header == NULL)
2655 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2656 return JB_ERR_MEMORY;
2659 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2661 days = rtime / (3600 * 24);
2662 hours = rtime / 3600 % 24;
2663 minutes = rtime / 60 % 60;
2664 seconds = rtime % 60;
2666 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2667 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2668 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2673 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2682 /*********************************************************************
2684 * Function : client_accept_encoding
2686 * Description : Rewrite the client's Accept-Encoding header so that
2687 * if doesn't allow compression, if the action applies.
2688 * Note: For HTTP/1.0 the absence of the header is enough.
2691 * 1 : csp = Current client state (buffers, headers, etc...)
2692 * 2 : header = On input, pointer to header to modify.
2693 * On output, pointer to the modified header, or NULL
2694 * to remove the header. This function frees the
2695 * original string if necessary.
2697 * Returns : JB_ERR_OK on success, or
2698 * JB_ERR_MEMORY on out-of-memory error.
2700 *********************************************************************/
2701 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2703 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2705 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2709 /* Temporarily disable the correct behaviour to
2710 * work around a PHP bug.
2712 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2714 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2715 * if (*header == NULL)
2717 * return JB_ERR_MEMORY;
2728 /*********************************************************************
2730 * Function : client_te
2732 * Description : Rewrite the client's TE header so that
2733 * if doesn't allow compression, if the action applies.
2736 * 1 : csp = Current client state (buffers, headers, etc...)
2737 * 2 : header = On input, pointer to header to modify.
2738 * On output, pointer to the modified header, or NULL
2739 * to remove the header. This function frees the
2740 * original string if necessary.
2742 * Returns : JB_ERR_OK on success, or
2743 * JB_ERR_MEMORY on out-of-memory error.
2745 *********************************************************************/
2746 static jb_err client_te(struct client_state *csp, char **header)
2748 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2751 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2758 /*********************************************************************
2760 * Function : client_referrer
2762 * Description : Handle the "referer" config setting properly.
2763 * Called from `sed'.
2766 * 1 : csp = Current client state (buffers, headers, etc...)
2767 * 2 : header = On input, pointer to header to modify.
2768 * On output, pointer to the modified header, or NULL
2769 * to remove the header. This function frees the
2770 * original string if necessary.
2772 * Returns : JB_ERR_OK on success, or
2773 * JB_ERR_MEMORY on out-of-memory error.
2775 *********************************************************************/
2776 static jb_err client_referrer(struct client_state *csp, char **header)
2778 const char *parameter;
2779 /* booleans for parameters we have to check multiple times */
2780 int parameter_conditional_block;
2781 int parameter_conditional_forge;
2783 #ifdef FEATURE_FORCE_LOAD
2785 * Since the referrer can include the prefix even
2786 * if the request itself is non-forced, we must
2787 * clean it unconditionally.
2789 * XXX: strclean is too broad
2791 strclean(*header, FORCE_PREFIX);
2792 #endif /* def FEATURE_FORCE_LOAD */
2794 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2796 /* Nothing left to do */
2800 parameter = csp->action->string[ACTION_STRING_REFERER];
2801 assert(parameter != NULL);
2802 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2803 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2805 if (!parameter_conditional_block && !parameter_conditional_forge)
2808 * As conditional-block and conditional-forge are the only
2809 * parameters that rely on the original referrer, we can
2810 * remove it now for all the others.
2815 if (0 == strcmpic(parameter, "block"))
2817 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2820 else if (parameter_conditional_block || parameter_conditional_forge)
2822 return handle_conditional_hide_referrer_parameter(header,
2823 csp->http->hostport, parameter_conditional_block);
2825 else if (0 == strcmpic(parameter, "forge"))
2827 return create_forged_referrer(header, csp->http->hostport);
2831 /* interpret parameter as user-supplied referer to fake */
2832 return create_fake_referrer(header, parameter);
2837 /*********************************************************************
2839 * Function : client_accept_language
2841 * Description : Handle the "Accept-Language" config setting properly.
2842 * Called from `sed'.
2845 * 1 : csp = Current client state (buffers, headers, etc...)
2846 * 2 : header = On input, pointer to header to modify.
2847 * On output, pointer to the modified header, or NULL
2848 * to remove the header. This function frees the
2849 * original string if necessary.
2851 * Returns : JB_ERR_OK on success, or
2852 * JB_ERR_MEMORY on out-of-memory error.
2854 *********************************************************************/
2855 static jb_err client_accept_language(struct client_state *csp, char **header)
2860 * Are we messing with the Accept-Language?
2862 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2864 /*I don't think so*/
2868 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2870 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2873 * Blocking Accept-Language header
2875 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2882 * Replacing Accept-Language header
2885 *header = strdup("Accept-Language: ");
2886 string_append(header, newval);
2888 if (*header == NULL)
2890 log_error(LOG_LEVEL_ERROR,
2891 "Insufficent memory. Accept-Language header crunched without replacement.");
2895 log_error(LOG_LEVEL_HEADER,
2896 "Accept-Language header crunched and replaced with: %s", *header);
2899 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2903 /*********************************************************************
2905 * Function : crunch_client_header
2907 * Description : Crunch client header if it matches a string supplied by the
2908 * user. Called from `sed'.
2911 * 1 : csp = Current client state (buffers, headers, etc...)
2912 * 2 : header = On input, pointer to header to modify.
2913 * On output, pointer to the modified header, or NULL
2914 * to remove the header. This function frees the
2915 * original string if necessary.
2917 * Returns : JB_ERR_OK on success and always succeeds
2919 *********************************************************************/
2920 static jb_err crunch_client_header(struct client_state *csp, char **header)
2922 const char *crunch_pattern;
2924 /* Do we feel like crunching? */
2925 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2927 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2929 /* Is the current header the lucky one? */
2930 if (strstr(*header, crunch_pattern))
2932 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2940 /*********************************************************************
2942 * Function : client_uagent
2944 * Description : Handle the "user-agent" config setting properly
2945 * and remember its original value to enable browser
2946 * bug workarounds. Called from `sed'.
2949 * 1 : csp = Current client state (buffers, headers, etc...)
2950 * 2 : header = On input, pointer to header to modify.
2951 * On output, pointer to the modified header, or NULL
2952 * to remove the header. This function frees the
2953 * original string if necessary.
2955 * Returns : JB_ERR_OK on success, or
2956 * JB_ERR_MEMORY on out-of-memory error.
2958 *********************************************************************/
2959 static jb_err client_uagent(struct client_state *csp, char **header)
2963 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2968 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2975 *header = strdup("User-Agent: ");
2976 string_append(header, newval);
2978 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2980 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2984 /*********************************************************************
2986 * Function : client_ua
2988 * Description : Handle "ua-" headers properly. Called from `sed'.
2991 * 1 : csp = Current client state (buffers, headers, etc...)
2992 * 2 : header = On input, pointer to header to modify.
2993 * On output, pointer to the modified header, or NULL
2994 * to remove the header. This function frees the
2995 * original string if necessary.
2997 * Returns : JB_ERR_OK on success, or
2998 * JB_ERR_MEMORY on out-of-memory error.
3000 *********************************************************************/
3001 static jb_err client_ua(struct client_state *csp, char **header)
3003 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3005 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3013 /*********************************************************************
3015 * Function : client_from
3017 * Description : Handle the "from" config setting properly.
3018 * Called from `sed'.
3021 * 1 : csp = Current client state (buffers, headers, etc...)
3022 * 2 : header = On input, pointer to header to modify.
3023 * On output, pointer to the modified header, or NULL
3024 * to remove the header. This function frees the
3025 * original string if necessary.
3027 * Returns : JB_ERR_OK on success, or
3028 * JB_ERR_MEMORY on out-of-memory error.
3030 *********************************************************************/
3031 static jb_err client_from(struct client_state *csp, char **header)
3035 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3042 newval = csp->action->string[ACTION_STRING_FROM];
3045 * Are we blocking the e-mail address?
3047 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3049 log_error(LOG_LEVEL_HEADER, "crunched From!");
3053 log_error(LOG_LEVEL_HEADER, " modified");
3055 *header = strdup("From: ");
3056 string_append(header, newval);
3058 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3062 /*********************************************************************
3064 * Function : client_send_cookie
3066 * Description : Crunches the "cookie" header if necessary.
3067 * Called from `sed'.
3069 * XXX: Stupid name, doesn't send squat.
3072 * 1 : csp = Current client state (buffers, headers, etc...)
3073 * 2 : header = On input, pointer to header to modify.
3074 * On output, pointer to the modified header, or NULL
3075 * to remove the header. This function frees the
3076 * original string if necessary.
3078 * Returns : JB_ERR_OK on success, or
3079 * JB_ERR_MEMORY on out-of-memory error.
3081 *********************************************************************/
3082 static jb_err client_send_cookie(struct client_state *csp, char **header)
3084 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3086 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3094 /*********************************************************************
3096 * Function : client_x_forwarded
3098 * Description : Handle the "x-forwarded-for" config setting properly,
3099 * also used in the add_client_headers list. Called from `sed'.
3102 * 1 : csp = Current client state (buffers, headers, etc...)
3103 * 2 : header = On input, pointer to header to modify.
3104 * On output, pointer to the modified header, or NULL
3105 * to remove the header. This function frees the
3106 * original string if necessary.
3108 * Returns : JB_ERR_OK on success, or
3109 * JB_ERR_MEMORY on out-of-memory error.
3111 *********************************************************************/
3112 jb_err client_x_forwarded(struct client_state *csp, char **header)
3114 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3117 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3124 /*********************************************************************
3126 * Function : client_max_forwards
3128 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3129 * from the value of the Max-Forwards header field.
3132 * 1 : csp = Current client state (buffers, headers, etc...)
3133 * 2 : header = On input, pointer to header to modify.
3134 * On output, pointer to the modified header, or NULL
3135 * to remove the header. This function frees the
3136 * original string if necessary.
3138 * Returns : JB_ERR_OK on success, or
3139 * JB_ERR_MEMORY on out-of-memory error.
3141 *********************************************************************/
3142 static jb_err client_max_forwards(struct client_state *csp, char **header)
3146 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3147 (0 == strcmpic(csp->http->gpc, "options")))
3149 assert(*(*header+12) == ':');
3150 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3152 if (max_forwards > 0)
3154 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3155 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3156 csp->http->gpc, max_forwards);
3158 else if (max_forwards < 0)
3160 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3166 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3175 /*********************************************************************
3177 * Function : client_host
3179 * Description : If the request URI did not contain host and
3180 * port information, parse and evaluate the Host
3183 * Also, kill ill-formed HOST: headers as sent by
3184 * Apple's iTunes software when used with a proxy.
3187 * 1 : csp = Current client state (buffers, headers, etc...)
3188 * 2 : header = On input, pointer to header to modify.
3189 * On output, pointer to the modified header, or NULL
3190 * to remove the header. This function frees the
3191 * original string if necessary.
3193 * Returns : JB_ERR_OK on success, or
3194 * JB_ERR_MEMORY on out-of-memory error.
3196 *********************************************************************/
3197 static jb_err client_host(struct client_state *csp, char **header)
3202 * If the header field name is all upper-case, chances are that it's
3203 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3204 * not a problem -- they are regenerated later.
3206 if ((*header)[1] == 'O')
3208 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3213 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3214 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3217 if (NULL == (p = strdup((*header)+6)))
3219 return JB_ERR_MEMORY;
3222 if (NULL == (q = strdup(p)))
3225 return JB_ERR_MEMORY;
3228 freez(csp->http->hostport);
3229 csp->http->hostport = p;
3230 freez(csp->http->host);
3231 csp->http->host = q;
3232 q = strchr(csp->http->host, ':');
3235 /* Terminate hostname and evaluate port string */
3237 csp->http->port = atoi(q);
3241 csp->http->port = csp->http->ssl ? 443 : 80;
3244 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3245 csp->http->hostport, csp->http->host, csp->http->port);
3248 /* Signal client_host_adder() to return right away */
3249 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3255 /*********************************************************************
3257 * Function : client_if_modified_since
3259 * Description : Remove or modify the If-Modified-Since header.
3262 * 1 : csp = Current client state (buffers, headers, etc...)
3263 * 2 : header = On input, pointer to header to modify.
3264 * On output, pointer to the modified header, or NULL
3265 * to remove the header. This function frees the
3266 * original string if necessary.
3268 * Returns : JB_ERR_OK on success, or
3269 * JB_ERR_MEMORY on out-of-memory error.
3271 *********************************************************************/
3272 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3275 #ifdef HAVE_GMTIME_R
3278 struct tm *timeptr = NULL;
3282 long int hours, minutes, seconds;
3286 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3289 * The client got an error message because of a temporary problem,
3290 * the problem is gone and the client now tries to revalidate our
3291 * error message on the real server. The revalidation would always
3292 * end with the transmission of the whole document and there is
3293 * no need to expose the bogus If-Modified-Since header.
3295 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3298 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3300 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3302 if ((0 == strcmpic(newval, "block")))
3304 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3307 else /* add random value */
3309 const char *header_time = *header + sizeof("If-Modified-Since:");
3311 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3313 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3318 rtime = strtol(newval, &endptr, 0);
3321 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3322 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3329 rtime = pick_from_range(rtime);
3333 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3336 tm += rtime * (negative ? -1 : 1);
3337 #ifdef HAVE_GMTIME_R
3338 timeptr = gmtime_r(&tm, &gmt);
3339 #elif FEATURE_PTHREAD
3340 pthread_mutex_lock(&gmtime_mutex);
3341 timeptr = gmtime(&tm);
3342 pthread_mutex_unlock(&gmtime_mutex);
3344 timeptr = gmtime(&tm);
3346 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3349 *header = strdup("If-Modified-Since: ");
3350 string_append(header, newheader);
3352 if (*header == NULL)
3354 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3355 return JB_ERR_MEMORY;
3358 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3360 hours = rtime / 3600;
3361 minutes = rtime / 60 % 60;
3362 seconds = rtime % 60;
3364 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3365 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3366 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3376 /*********************************************************************
3378 * Function : client_if_none_match
3380 * Description : Remove the If-None-Match header.
3383 * 1 : csp = Current client state (buffers, headers, etc...)
3384 * 2 : header = On input, pointer to header to modify.
3385 * On output, pointer to the modified header, or NULL
3386 * to remove the header. This function frees the
3387 * original string if necessary.
3389 * Returns : JB_ERR_OK on success, or
3390 * JB_ERR_MEMORY on out-of-memory error.
3392 *********************************************************************/
3393 static jb_err client_if_none_match(struct client_state *csp, char **header)
3395 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3397 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3405 /*********************************************************************
3407 * Function : client_x_filter
3409 * Description : Disables filtering if the client set "X-Filter: No".
3410 * Called from `sed'.
3413 * 1 : csp = Current client state (buffers, headers, etc...)
3414 * 2 : header = On input, pointer to header to modify.
3415 * On output, pointer to the modified header, or NULL
3416 * to remove the header. This function frees the
3417 * original string if necessary.
3419 * Returns : JB_ERR_OK on success
3421 *********************************************************************/
3422 jb_err client_x_filter(struct client_state *csp, char **header)
3424 if ( 0 == strcmpic(*header, "X-Filter: No"))
3426 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3428 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3432 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3434 log_error(LOG_LEVEL_HEADER,
3435 "force-text-mode overruled the client's request to fetch without filtering!");
3439 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3440 csp->flags |= CSP_FLAG_NO_FILTERING;
3441 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3443 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3451 /*********************************************************************
3453 * Function : client_range
3455 * Description : Removes Range, Request-Range and If-Range headers if
3456 * content filtering is enabled. If the client's version
3457 * of the document has been altered by Privoxy, the server
3458 * could interpret the range differently than the client
3459 * intended in which case the user could end up with
3460 * corrupted content.
3463 * 1 : csp = Current client state (buffers, headers, etc...)
3464 * 2 : header = On input, pointer to header to modify.
3465 * On output, pointer to the modified header, or NULL
3466 * to remove the header. This function frees the
3467 * original string if necessary.
3469 * Returns : JB_ERR_OK
3471 *********************************************************************/
3472 static jb_err client_range(struct client_state *csp, char **header)
3474 if (content_filters_enabled(csp))
3476 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3477 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3484 /* the following functions add headers directly to the header list */
3486 /*********************************************************************
3488 * Function : client_host_adder
3490 * Description : Adds the Host: header field if it is missing.
3491 * Called from `sed'.
3494 * 1 : csp = Current client state (buffers, headers, etc...)
3496 * Returns : JB_ERR_OK on success, or
3497 * JB_ERR_MEMORY on out-of-memory error.
3499 *********************************************************************/
3500 static jb_err client_host_adder(struct client_state *csp)
3505 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3507 /* Header already set by the client, nothing to do. */
3511 if ( !csp->http->hostport || !*(csp->http->hostport))
3513 /* XXX: When does this happen and why is it OK? */
3514 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3519 * remove 'user:pass@' from 'proto://user:pass@host'
3521 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3527 p = csp->http->hostport;
3530 /* XXX: Just add it, we already made sure that it will be unique */
3531 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3532 err = enlist_unique_header(csp->headers, "Host", p);
3539 /*********************************************************************
3541 * Function : client_accept_encoding_adder
3543 * Description : Add an Accept-Encoding header to the client's request
3544 * that disables compression if the action applies, and
3545 * the header is not already there. Called from `sed'.
3546 * Note: For HTTP/1.0, the absence of the header is enough.
3549 * 1 : csp = Current client state (buffers, headers, etc...)
3551 * Returns : JB_ERR_OK on success, or
3552 * JB_ERR_MEMORY on out-of-memory error.
3554 *********************************************************************/
3555 static jb_err client_accept_encoding_adder(struct client_state *csp)
3557 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3558 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3560 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3568 /*********************************************************************
3570 * Function : client_xtra_adder
3572 * Description : Used in the add_client_headers list. Called from `sed'.
3575 * 1 : csp = Current client state (buffers, headers, etc...)
3577 * Returns : JB_ERR_OK on success, or
3578 * JB_ERR_MEMORY on out-of-memory error.
3580 *********************************************************************/
3581 static jb_err client_xtra_adder(struct client_state *csp)
3583 struct list_entry *lst;
3586 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3587 lst ; lst = lst->next)
3589 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3590 err = enlist(csp->headers, lst->str);
3602 /*********************************************************************
3604 * Function : connection_close_adder
3606 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3607 * support. Adds a "Connection: close" header to csp->headers
3608 * unless the header was already present. Called from `sed'.
3610 * FIXME: This whole function shouldn't be neccessary!
3613 * 1 : csp = Current client state (buffers, headers, etc...)
3615 * Returns : JB_ERR_OK on success, or
3616 * JB_ERR_MEMORY on out-of-memory error.
3618 *********************************************************************/
3619 static jb_err connection_close_adder(struct client_state *csp)
3621 const unsigned int flags = csp->flags;
3624 * Return right away if
3626 * - we're parsing server headers and the server header
3627 * "Connection: close" is already set, or if
3629 * - we're parsing client headers and the client header
3630 * "Connection: close" is already set.
3632 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3633 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3634 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3635 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3640 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3642 return enlist(csp->headers, "Connection: close");
3646 /*********************************************************************
3648 * Function : server_http
3650 * Description : - Save the HTTP Status into csp->http->status
3651 * - Set CT_TABOO to prevent filtering if the answer
3652 * is a partial range (HTTP status 206)
3653 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
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, or
3664 * JB_ERR_MEMORY on out-of-memory error.
3666 *********************************************************************/
3667 static jb_err server_http(struct client_state *csp, char **header)
3669 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3670 if (csp->http->status == 206)
3672 csp->content_type = CT_TABOO;
3675 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3677 /* XXX: Should we do a real validity check here? */