1 const char parsers_rcs[] = "$Id: parsers.c,v 1.123 2008/03/29 12:13:46 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.123 2008/03/29 12:13:46 fabiankeil
48 * Remove send-wafer and send-vanilla-wafer actions.
50 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
51 * Remove inspect-jpegs action.
53 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
54 * Let client_range() also handle Request-Range headers
55 * which apparently are still supported by many servers.
57 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
58 * Improve the warning messages that get logged if the action files
59 * "enable" filters but no filters of that type have been loaded.
61 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
62 * In server_content_type():
63 * - Don't require leading white space when detecting image content types.
64 * - Change '... not replaced ...' message to sound less crazy if the text
65 * type actually is 'text/plain'.
66 * - Mark the 'text/plain == binary data' assumption for removal.
67 * - Remove a bunch of trailing white space.
69 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
70 * Minor server_content_disposition() changes:
71 * - Don't regenerate the header name all lower-case.
72 * - Some white space fixes.
73 * - Remove useless log message in case of ENOMEM.
75 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
76 * Garbage-collect the code to add a X-Forwarded-For
77 * header as it seems to be mostly used by accident.
79 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
80 * Fix a crash on mingw32 with some Last Modified times in the future.
82 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
83 * Remove a "can't happen" error block which, over
84 * time, mutated into a "guaranteed to happen" block.
86 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
87 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
88 * - Use shiny new content_filters_enabled() in client_range().
90 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
91 * I forgot about Poland.
93 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
94 * Remove Range and If-Range headers if content filtering is enabled.
96 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
97 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
98 * client_cookie_adder() to make sure send-vanilla-wafer can be
99 * controlled through tags (and thus regression-tested).
101 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
102 * - Remove "scanning headers for" log message again.
103 * - Some more whitespace fixes.
105 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
106 * Refactor client_referrer() and add conditional-forge parameter.
108 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
109 * A bunch of whitespace fixes, pointy hat to me.
111 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
112 * Fix possible memory corruption in server_http, make sure it's not
113 * executed for ordinary server headers and mark some problems for later.
115 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
116 * Let content-type-overwrite{} honour force-text-mode again.
118 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
119 * - Add prototpyes for the header parsers and make them static.
120 * - Comment out client_accept_encoding_adder() which isn't used right now.
122 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
123 * Move the ACTION_FORCE_TEXT_MODE check out of
124 * server_content_type(). Signal other functions
125 * whether or not a content type has been declared.
126 * Part of the fix for BR#1750917.
128 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
129 * Change sed() to return a jb_err in preparation for forward-override{}.
131 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
132 * Adjust "X-Filter: No" to disable dedicated header filters.
134 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
135 * Streamline client_cookie_adder().
137 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
138 * Make sure filters with dynamic jobs actually use them.
140 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
141 * - Introduce dynamic pcrs jobs that can resolve variables.
142 * - Remove unnecessary update_action_bits_for_all_tags() call.
144 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
145 * - Make tagging based on tags set by earlier taggers
146 * of the same kind possible.
147 * - Log whether or not new tags cause action bits updates
148 * (in which case a matching tag-pattern section exists).
149 * - Log if the user tries to set a tag that is already set.
151 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
152 * Introduce tags as alternative way to specify which
153 * actions apply to a request. At the moment tags can be
154 * created based on client and server headers.
156 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
157 * Log a warning if the content is compressed, filtering is
158 * enabled and Privoxy was compiled without zlib support.
161 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
162 * - Fix warnings when compiled with glibc.
163 * - Don't use crumble() for cookie crunching.
164 * - Move cookie time parsing into parse_header_time().
165 * - Let parse_header_time() return a jb_err code
166 * instead of a pointer that can only be used to
167 * check for NULL anyway.
169 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
170 * - Add better protection against malicious gzip headers.
171 * - Stop logging the first hundred bytes of decompressed content.
172 * It looks like it's working and there is always debug 16.
173 * - Log the content size after decompression in decompress_iob()
174 * instead of pcrs_filter_response().
176 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
177 * - Use dedicated header filter actions instead of abusing "filter".
178 * Replace "filter-client-headers" and "filter-client-headers"
179 * with "server-header-filter" and "client-header-filter".
180 * - Remove filter_client_header() and filter_client_header(),
181 * filter_header() now checks the shiny new
182 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
184 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
185 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
186 * - Handle "Cookie:" and "Connection:" headers a bit smarter
187 * (don't crunch them just to recreate them later on).
188 * - Add another non-standard time format for the cookie
189 * expiration date detection.
190 * - Fix a valgrind warning.
192 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
193 * Improve cookie expiration date detection.
195 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
196 * Don't run server_content_length() the first time
197 * sed() parses server headers; only adjust the
198 * Content-Length header if the page was modified.
200 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
201 * Fix log messages regarding the cookie time format
202 * (cookie and request URL were mixed up).
204 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
205 * - Let decompress_iob()
206 * - not corrupt the content if decompression fails
207 * early. (the first byte(s) were lost).
208 * - use pointer arithmetics with defined outcome for
210 * - Use a different kludge to remember a failed decompression.
212 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
213 * Search for Max-Forwards headers case-insensitive,
214 * don't generate the "501 unsupported" message for invalid
215 * Max-Forwards values and don't increase negative ones.
217 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
218 * - Let server_set_cookie() check the expiration date
219 * of cookies and don't touch the ones that are already
220 * expired. Fixes problems with low quality web applications
221 * as described in BR 932612.
223 * - Adjust comment in client_max_forwards to reality;
224 * remove invalid Max-Forwards headers.
226 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
227 * Stop filter_header() from unintentionally removing
228 * empty header lines that were enlisted by the continue
231 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
232 * - Repeat the request URL before logging any headers.
233 * Makes reading the log easier in case of simultaneous requests.
234 * - If there are more than one Content-Type headers in one request,
235 * use the first one and remove the others.
236 * - Remove "newval" variable in server_content_type().
237 * It's only used once.
239 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
240 * Correct a cast, check inflateEnd() exit code
241 * to see if we have to, replace sprintf calls
244 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
245 * Integrate a modified version of Wil Mahan's
246 * zlib patch (PR #895531).
248 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
249 * Skip empty filter files in filter_header()
250 * but don't ignore the ones that come afterwards.
251 * Fixes BR 1619208, this time for real.
253 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
254 * Reverted parts of my last commit
255 * to keep error handling working.
257 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
258 * Fixed gcc43 conversion warnings.
260 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
261 * Bringing back the "useless" localtime() call
262 * I removed in revision 1.67. On some platforms
263 * it's necessary to prevent time zone offsets.
265 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
266 * Rebuild request URL in get_destination_from_headers()
267 * to make sure redirect{pcrs command} works as expected
268 * for intercepted requests.
270 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
271 * Added get_destination_from_headers().
273 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
274 * Make pthread mutex locking more generic. Instead of
275 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
276 * and use mutex locking unless there is an _r function
277 * available. Better safe than sorry.
279 * Fixes "./configure --disable-pthread" and should result
280 * in less threading-related problems on pthread-using platforms,
281 * but it still doesn't fix BR#1122404.
283 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
284 * The special header "X-Filter: No" now disables
285 * header filtering as well.
287 * Revision 1.73 2006/09/23 13:26:38 roro
288 * Replace TABs by spaces in source code.
290 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
291 * Don't print a log message every time filter_headers is
292 * entered or left. It only creates noise without any real
295 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
296 * Fix +hide-if-modified-since{-n}.
298 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
299 * Have hide-if-modified-since interpret the random
300 * range value as minutes instead of hours. Allows
301 * more fine-grained configuration.
303 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
304 * Always have parse_header_time return a pointer
305 * that actual makes sense, even though we currently
306 * only need it to detect problems.
308 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
309 * Added config option enable-remote-http-toggle
310 * to specify if Privoxy should recognize special
311 * headers (currently only X-Filter) to change its
312 * behaviour. Disabled by default.
314 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
315 * After filtering de-chunked instances, remove
316 * "Transfer-Encoding" header entirely instead of changing
317 * it to "Transfer-Encoding: identity", which is invalid.
318 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
320 * Don't use localtime in parse_header_time. An empty time struct
321 * is good enough, it gets overwritten by strptime anyway.
323 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
324 * Use gmtime_r if available, fallback to gmtime with mutex
325 * protection for MacOSX and use vanilla gmtime for the rest.
327 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
328 * Changed client_referrer to use the right type (size_t) for
329 * hostlenght and to shorten the temporary referrer string with
330 * '\0' instead of adding a useless line break.
332 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
333 * - Back to timegm() using GnuPG's replacement if necessary.
334 * Using mktime() and localtime() could add a on hour offset if
335 * the randomize factor was big enough to lead to a summer/wintertime
338 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
340 * - Moved randomization code into pick_from_range().
342 * - Changed parse_header_time definition.
343 * time_t isn't guaranteed to be signed and
344 * if it isn't, -1 isn't available as error code.
345 * Changed some variable types in client_if_modified_since()
346 * because of the same reason.
348 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
349 * OS/2 compilation compatibility fixups
351 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
352 * Changed include from strptime.c to strptime.h
354 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
355 * Split filter-headers{} into filter-client-headers{}
356 * and filter-server-headers{}.
357 * Added parse_header_time() to share some code.
358 * Replaced timegm() with mktime().
360 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
361 * Windows service integration
363 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
364 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
366 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
367 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
368 * with what was really the latest development (the v_3_0_branch branch)
370 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
371 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
373 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
374 * Add the ability to check jpeg images for invalid
375 * lengths of comment blocks. Defensive strategy
376 * against the exploit:
377 * Microsoft Security Bulletin MS04-028
378 * Buffer Overrun in JPEG Processing (GDI+) Could
379 * Allow Code Execution (833987)
380 * Enabled with +inspect-jpegs in actions files.
382 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
383 * Excluded text/plain objects from filtering. This fixes a
384 * couple of client-crashing, download corruption and
385 * Privoxy performance issues, whose root cause lies in
386 * web servers labelling content of unknown type as text/plain.
388 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
389 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
391 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
392 * Completing the previous change
394 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
395 * Added temporary workaround for bug in PHP < 4.2.3
397 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
398 * 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.
400 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
401 * Fix typo: supressed -> suppressed
403 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
404 * Improved cookie logging
406 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
407 * Added basic support for OPTIONS and TRACE HTTP methods:
408 * - New parser function client_max_forwards which decrements
409 * the Max-Forwards HTTP header field of OPTIONS and TRACE
410 * requests by one before forwarding
411 * - New parser function client_host which extracts the host
412 * and port information from the HTTP header field if the
413 * request URI was not absolute
414 * - Don't crumble and re-add the Host: header, but only generate
415 * and append if missing
417 * Revision 1.56 2002/05/12 15:34:22 jongfoster
418 * Fixing typo in a comment
420 * Revision 1.55 2002/05/08 16:01:07 oes
421 * Optimized add_to_iob:
422 * - Use realloc instead of malloc(), memcpy(), free()
423 * - Expand to powers of two if possible, to get
424 * O(log n) reallocs instead of O(n).
425 * - Moved check for buffer limit here from chat
426 * - Report failure via returncode
428 * Revision 1.54 2002/04/02 15:03:16 oes
429 * Tiny code cosmetics
431 * Revision 1.53 2002/03/26 22:29:55 swa
432 * we have a new homepage!
434 * Revision 1.52 2002/03/24 13:25:43 swa
435 * name change related issues
437 * Revision 1.51 2002/03/13 00:27:05 jongfoster
440 * Revision 1.50 2002/03/12 01:45:35 oes
441 * More verbose logging
443 * Revision 1.49 2002/03/09 20:03:52 jongfoster
444 * - Making various functions return int rather than size_t.
445 * (Undoing a recent change). Since size_t is unsigned on
446 * Windows, functions like read_socket that return -1 on
447 * error cannot return a size_t.
449 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
450 * crashes, and also frequently caused JB to jump to 100%
451 * CPU and stay there. (Because it thought it had just
452 * read ((unsigned)-1) == 4Gb of data...)
454 * - The signature of write_socket has changed, it now simply
455 * returns success=0/failure=nonzero.
457 * - Trying to get rid of a few warnings --with-debug on
458 * Windows, I've introduced a new type "jb_socket". This is
459 * used for the socket file descriptors. On Windows, this
460 * is SOCKET (a typedef for unsigned). Everywhere else, it's
461 * an int. The error value can't be -1 any more, so it's
462 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
463 * Windows it maps to the #define INVALID_SOCKET.)
465 * - The signature of bind_port has changed.
467 * Revision 1.48 2002/03/07 03:46:53 oes
468 * Fixed compiler warnings etc
470 * Revision 1.47 2002/02/20 23:15:13 jongfoster
471 * Parsing functions now handle out-of-memory gracefully by returning
474 * Revision 1.46 2002/01/17 21:03:47 jongfoster
475 * Moving all our URL and URL pattern parsing code to urlmatch.c.
477 * Revision 1.45 2002/01/09 14:33:03 oes
478 * Added support for localtime_r.
480 * Revision 1.44 2001/12/14 01:22:54 steudten
481 * Remove 'user:pass@' from 'proto://user:pass@host' for the
482 * new added header 'Host: ..'. (See Req ID 491818)
484 * Revision 1.43 2001/11/23 00:26:38 jongfoster
485 * Fixing two really stupid errors in my previous commit
487 * Revision 1.42 2001/11/22 21:59:30 jongfoster
488 * Adding code to handle +no-cookies-keep
490 * Revision 1.41 2001/11/05 23:43:05 steudten
491 * Add time+date to log files.
493 * Revision 1.40 2001/10/26 20:13:09 jongfoster
494 * ctype.h is needed in Windows, too.
496 * Revision 1.39 2001/10/26 17:40:04 oes
497 * Introduced get_header_value()
498 * Removed http->user_agent, csp->referrer and csp->accept_types
499 * Removed client_accept()
501 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
502 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
503 * threads to call select() simultaneously. So, it's time to do a real, live,
504 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
505 * (native). Both versions will work, but using __OS2__ offers multi-threading.
507 * Revision 1.37 2001/10/23 21:36:02 jongfoster
508 * Documenting sed()'s error behaviou (doc change only)
510 * Revision 1.36 2001/10/13 12:51:51 joergs
511 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
512 * force-load), instead crumble Host: and add it (again) in client_host_adder
513 * (in case we get a HTTP/1.0 request without Host: header and forward it to
514 * a HTTP/1.1 server/proxy).
516 * Revision 1.35 2001/10/09 22:39:21 jongfoster
517 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
520 * Revision 1.34 2001/10/07 18:50:55 oes
521 * Added server_content_encoding, renamed server_transfer_encoding
523 * Revision 1.33 2001/10/07 18:04:49 oes
524 * Changed server_http11 to server_http and its pattern to "HTTP".
525 * Additional functionality: it now saves the HTTP status into
526 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
528 * Revision 1.32 2001/10/07 15:43:28 oes
529 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
530 * client_te and client_accept_encoding_adder, triggered by the new
531 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
532 * changed to allow only identity and chunked, and the TE header is
533 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
535 * parse_http_request no longer does anything than parsing. The rewriting
536 * of http->cmd and version mangling are gone. It now also recognizes
537 * the put and delete methods and saves the url in http->url. Removed
540 * renamed content_type and content_length to have the server_ prefix
542 * server_content_type now only works if csp->content_type != CT_TABOO
544 * added server_transfer_encoding, which
545 * - Sets CT_TABOO to prohibit filtering if encoding compresses
546 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
547 * - Change from "chunked" to "identity" if body was chunked
548 * but has been de-chunked for filtering.
550 * added server_content_md5 which crunches any Content-MD5 headers
551 * if the body was modified.
553 * made server_http11 conditional on +downgrade action
555 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
557 * Revision 1.31 2001/10/05 14:25:02 oes
558 * Crumble Keep-Alive from Server
560 * Revision 1.30 2001/09/29 12:56:03 joergs
561 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
563 * Revision 1.29 2001/09/24 21:09:24 jongfoster
564 * Fixing 2 memory leaks that Guy spotted, where the paramater to
565 * enlist() was not being free()d.
567 * Revision 1.28 2001/09/22 16:32:28 jongfoster
568 * Removing unused #includes.
570 * Revision 1.27 2001/09/20 15:45:25 steudten
572 * add casting from size_t to int for printf()
573 * remove local variable shadow s2
575 * Revision 1.26 2001/09/16 17:05:14 jongfoster
576 * Removing unused #include showarg.h
578 * Revision 1.25 2001/09/16 13:21:27 jongfoster
579 * Changes to use new list functions.
581 * Revision 1.24 2001/09/13 23:05:50 jongfoster
582 * Changing the string paramater to the header parsers a "const".
584 * Revision 1.23 2001/09/12 18:08:19 steudten
586 * In parse_http_request() header rewriting miss the host value, so
587 * from http://www.mydomain.com the result was just " / " not
588 * http://www.mydomain.com/ in case we forward.
590 * Revision 1.22 2001/09/10 10:58:53 oes
591 * Silenced compiler warnings
593 * Revision 1.21 2001/07/31 14:46:00 oes
594 * - Persistant connections now suppressed
595 * - sed() no longer appends empty header to csp->headers
597 * Revision 1.20 2001/07/30 22:08:36 jongfoster
598 * Tidying up #defines:
599 * - All feature #defines are now of the form FEATURE_xxx
600 * - Permanently turned off WIN_GUI_EDIT
601 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
603 * Revision 1.19 2001/07/25 17:21:54 oes
604 * client_uagent now saves copy of User-Agent: header value
606 * Revision 1.18 2001/07/13 14:02:46 oes
607 * - Included fix to repair broken HTTP requests that
608 * don't contain a path, not even '/'.
609 * - Removed all #ifdef PCRS
610 * - content_type now always inspected and classified as
611 * text, gif or other.
612 * - formatting / comments
614 * Revision 1.17 2001/06/29 21:45:41 oes
615 * Indentation, CRLF->LF, Tab-> Space
617 * Revision 1.16 2001/06/29 13:32:42 oes
619 * - Adapted free_http_request
620 * - Removed logentry from cancelled commit
622 * Revision 1.15 2001/06/03 19:12:38 oes
623 * deleted const struct interceptors
625 * Revision 1.14 2001/06/01 18:49:17 jongfoster
626 * Replaced "list_share" with "list" - the tiny memory gain was not
627 * worth the extra complexity.
629 * Revision 1.13 2001/05/31 21:30:33 jongfoster
630 * Removed list code - it's now in list.[ch]
631 * Renamed "permission" to "action", and changed many features
632 * to use the actions file rather than the global config.
634 * Revision 1.12 2001/05/31 17:33:13 oes
638 * Revision 1.11 2001/05/29 20:11:19 joergs
639 * '/ * inside comment' warning removed.
641 * Revision 1.10 2001/05/29 09:50:24 jongfoster
642 * Unified blocklist/imagelist/permissionslist.
643 * File format is still under discussion, but the internal changes
646 * Also modified interceptor behaviour:
647 * - We now intercept all URLs beginning with one of the following
648 * prefixes (and *only* these prefixes):
650 * * http://ijbswa.sf.net/config/
651 * * http://ijbswa.sourceforge.net/config/
652 * - New interceptors "home page" - go to http://i.j.b/ to see it.
653 * - Internal changes so that intercepted and fast redirect pages
654 * are not replaced with an image.
655 * - Interceptors now have the option to send a binary page direct
656 * to the client. (i.e. ijb-send-banner uses this)
657 * - Implemented show-url-info interceptor. (Which is why I needed
658 * the above interceptors changes - a typical URL is
659 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
660 * The previous mechanism would not have intercepted that, and
661 * if it had been intercepted then it then it would have replaced
664 * Revision 1.9 2001/05/28 17:26:33 jongfoster
665 * Fixing segfault if last header was crunched.
666 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
667 * can use the cross-platform sprintf() instead.)
669 * Revision 1.8 2001/05/27 22:17:04 oes
671 * - re_process_buffer no longer writes the modified buffer
672 * to the client, which was very ugly. It now returns the
673 * buffer, which it is then written by chat.
675 * - content_length now adjusts the Content-Length: header
676 * for modified documents rather than crunch()ing it.
677 * (Length info in csp->content_length, which is 0 for
678 * unmodified documents)
680 * - For this to work, sed() is called twice when filtering.
682 * Revision 1.7 2001/05/27 13:19:06 oes
683 * Patched Joergs solution for the content-length in.
685 * Revision 1.6 2001/05/26 13:39:32 jongfoster
686 * Only crunches Content-Length header if applying RE filtering.
687 * Without this fix, Microsoft Windows Update wouldn't work.
689 * Revision 1.5 2001/05/26 00:28:36 jongfoster
690 * Automatic reloading of config file.
691 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
692 * Most of the global variables have been moved to a new
693 * struct configuration_spec, accessed through csp->config->globalname
694 * Most of the globals remaining are used by the Win32 GUI.
696 * Revision 1.4 2001/05/22 18:46:04 oes
698 * - Enabled filtering banners by size rather than URL
699 * by adding patterns that replace all standard banner
700 * sizes with the "Junkbuster" gif to the re_filterfile
702 * - Enabled filtering WebBugs by providing a pattern
703 * which kills all 1x1 images
705 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
706 * which is selected by the (nonstandard and therefore
707 * capital) letter 'U' in the option string.
708 * It causes the quantifiers to be ungreedy by default.
709 * Appending a ? turns back to greedy (!).
711 * - Added a new interceptor ijb-send-banner, which
712 * sends back the "Junkbuster" gif. Without imagelist or
713 * MSIE detection support, or if tinygif = 1, or the
714 * URL isn't recognized as an imageurl, a lame HTML
715 * explanation is sent instead.
717 * - Added new feature, which permits blocking remote
718 * script redirects and firing back a local redirect
720 * The feature is conditionally compiled, i.e. it
721 * can be disabled with --disable-fast-redirects,
722 * plus it must be activated by a "fast-redirects"
723 * line in the config file, has its own log level
724 * and of course wants to be displayed by show-proxy-args
725 * Note: Boy, all the #ifdefs in 1001 locations and
726 * all the fumbling with configure.in and acconfig.h
727 * were *way* more work than the feature itself :-(
729 * - Because a generic redirect template was needed for
730 * this, tinygif = 3 now uses the same.
732 * - Moved GIFs, and other static HTTP response templates
737 * - Removed some >400 CRs again (Jon, you really worked
740 * Revision 1.3 2001/05/20 01:21:20 jongfoster
741 * Version 2.9.4 checkin.
742 * - Merged popupfile and cookiefile, and added control over PCRS
743 * filtering, in new "permissionsfile".
744 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
745 * file error you now get a message box (in the Win32 GUI) rather
746 * than the program exiting with no explanation.
747 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
749 * - Removed tabs from "config"
750 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
751 * - Bumped up version number.
753 * Revision 1.2 2001/05/17 23:02:36 oes
754 * - Made referrer option accept 'L' as a substitute for '§'
756 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
757 * Initial import of version 2.9.3 source tree
760 *********************************************************************/
767 #include <sys/types.h>
777 * Convince GNU's libc to provide a strptime prototype.
780 #endif /*__GLIBC__ */
787 #if !defined(_WIN32) && !defined(__OS2__)
793 #ifdef FEATURE_PTHREAD
795 /* jcc.h is for mutex semapores only */
796 #endif /* def FEATURE_PTHREAD */
802 #include "jbsockets.h"
803 #include "miscutil.h"
808 #ifndef HAVE_STRPTIME
809 #include "strptime.h"
812 const char parsers_h_rcs[] = PARSERS_H_VERSION;
814 /* Fix a problem with Solaris. There should be no effect on other
816 * Solaris's isspace() is a macro which uses its argument directly
817 * as an array index. Therefore we need to make sure that high-bit
818 * characters generate +ve values, and ideally we also want to make
819 * the argument match the declared parameter type of "int".
821 * Why did they write a character function that can't take a simple
822 * "char" argument? Doh!
824 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
825 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
827 static jb_err scan_headers(struct client_state *csp);
828 static jb_err header_tagger(struct client_state *csp, char *header);
829 static jb_err parse_header_time(const char *header_time, time_t *result);
831 static jb_err crumble (struct client_state *csp, char **header);
832 static jb_err connection (struct client_state *csp, char **header);
833 static jb_err filter_header (struct client_state *csp, char **header);
834 static jb_err client_referrer (struct client_state *csp, char **header);
835 static jb_err client_uagent (struct client_state *csp, char **header);
836 static jb_err client_ua (struct client_state *csp, char **header);
837 static jb_err client_from (struct client_state *csp, char **header);
838 static jb_err client_send_cookie (struct client_state *csp, char **header);
839 static jb_err client_x_forwarded (struct client_state *csp, char **header);
840 static jb_err client_accept_encoding (struct client_state *csp, char **header);
841 static jb_err client_te (struct client_state *csp, char **header);
842 static jb_err client_max_forwards (struct client_state *csp, char **header);
843 static jb_err client_host (struct client_state *csp, char **header);
844 static jb_err client_if_modified_since (struct client_state *csp, char **header);
845 static jb_err client_accept_language (struct client_state *csp, char **header);
846 static jb_err client_if_none_match (struct client_state *csp, char **header);
847 static jb_err crunch_client_header (struct client_state *csp, char **header);
848 static jb_err client_x_filter (struct client_state *csp, char **header);
849 static jb_err client_range (struct client_state *csp, char **header);
850 static jb_err server_set_cookie (struct client_state *csp, char **header);
851 static jb_err server_content_type (struct client_state *csp, char **header);
852 static jb_err server_content_length (struct client_state *csp, char **header);
853 static jb_err server_content_md5 (struct client_state *csp, char **header);
854 static jb_err server_content_encoding (struct client_state *csp, char **header);
855 static jb_err server_transfer_coding (struct client_state *csp, char **header);
856 static jb_err server_http (struct client_state *csp, char **header);
857 static jb_err crunch_server_header (struct client_state *csp, char **header);
858 static jb_err server_last_modified (struct client_state *csp, char **header);
859 static jb_err server_content_disposition(struct client_state *csp, char **header);
861 static jb_err client_host_adder (struct client_state *csp);
862 static jb_err client_xtra_adder (struct client_state *csp);
863 static jb_err connection_close_adder (struct client_state *csp);
865 static jb_err create_forged_referrer(char **header, const char *hostport);
866 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
867 static jb_err handle_conditional_hide_referrer_parameter(char **header,
868 const char *host, const int parameter_conditional_block);
870 const struct parsers client_patterns[] = {
871 { "referer:", 8, client_referrer },
872 { "user-agent:", 11, client_uagent },
873 { "ua-", 3, client_ua },
874 { "from:", 5, client_from },
875 { "cookie:", 7, client_send_cookie },
876 { "x-forwarded-for:", 16, client_x_forwarded },
877 { "Accept-Encoding:", 16, client_accept_encoding },
878 { "TE:", 3, client_te },
879 { "Host:", 5, client_host },
880 { "if-modified-since:", 18, client_if_modified_since },
881 { "Keep-Alive:", 11, crumble },
882 { "connection:", 11, connection },
883 { "proxy-connection:", 17, crumble },
884 { "max-forwards:", 13, client_max_forwards },
885 { "Accept-Language:", 16, client_accept_language },
886 { "if-none-match:", 14, client_if_none_match },
887 { "Range:", 6, client_range },
888 { "Request-Range:", 14, client_range },
889 { "If-Range:", 9, client_range },
890 { "X-Filter:", 9, client_x_filter },
891 { "*", 0, crunch_client_header },
892 { "*", 0, filter_header },
896 const struct parsers server_patterns[] = {
897 { "HTTP/", 5, server_http },
898 { "set-cookie:", 11, server_set_cookie },
899 { "connection:", 11, connection },
900 { "Content-Type:", 13, server_content_type },
901 { "Content-MD5:", 12, server_content_md5 },
902 { "Content-Encoding:", 17, server_content_encoding },
903 { "Transfer-Encoding:", 18, server_transfer_coding },
904 { "Keep-Alive:", 11, crumble },
905 { "content-disposition:", 20, server_content_disposition },
906 { "Last-Modified:", 14, server_last_modified },
907 { "*", 0, crunch_server_header },
908 { "*", 0, filter_header },
912 const struct parsers server_patterns_light[] = {
913 { "Content-Length:", 15, server_content_length },
914 { "Transfer-Encoding:", 18, server_transfer_coding },
916 { "Content-Encoding:", 17, server_content_encoding },
917 #endif /* def FEATURE_ZLIB */
921 const add_header_func_ptr add_client_headers[] = {
924 /* Temporarily disabled: client_accept_encoding_adder, */
925 connection_close_adder,
929 const add_header_func_ptr add_server_headers[] = {
930 connection_close_adder,
934 /*********************************************************************
936 * Function : flush_socket
938 * Description : Write any pending "buffered" content.
941 * 1 : fd = file descriptor of the socket to read
942 * 2 : iob = The I/O buffer to flush, usually csp->iob.
944 * Returns : On success, the number of bytes written are returned (zero
945 * indicates nothing was written). On error, -1 is returned,
946 * and errno is set appropriately. If count is zero and the
947 * file descriptor refers to a regular file, 0 will be
948 * returned without causing any other effect. For a special
949 * file, the results are not portable.
951 *********************************************************************/
952 int flush_socket(jb_socket fd, struct iob *iob)
954 int len = iob->eod - iob->cur;
961 if (write_socket(fd, iob->cur, (size_t)len))
965 iob->eod = iob->cur = iob->buf;
971 /*********************************************************************
973 * Function : add_to_iob
975 * Description : Add content to the buffered page, expanding the
976 * buffer if necessary.
979 * 1 : csp = Current client state (buffers, headers, etc...)
980 * 2 : buf = holds the content to be added to the page
981 * 3 : n = number of bytes to be added
983 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
984 * or buffer limit reached.
986 *********************************************************************/
987 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
989 struct iob *iob = csp->iob;
990 size_t used, offset, need, want;
993 if (n <= 0) return JB_ERR_OK;
995 used = (size_t)(iob->eod - iob->buf);
996 offset = (size_t)(iob->cur - iob->buf);
997 need = used + (size_t)n + 1;
1000 * If the buffer can't hold the new data, extend it first.
1001 * Use the next power of two if possible, else use the actual need.
1003 if (need > csp->config->buffer_limit)
1005 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1006 return JB_ERR_MEMORY;
1009 if (need > iob->size)
1011 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1013 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1017 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1023 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1024 return JB_ERR_MEMORY;
1027 /* Update the iob pointers */
1028 iob->cur = p + offset;
1029 iob->eod = p + used;
1033 /* copy the new data into the iob buffer */
1034 memcpy(iob->eod, buf, (size_t)n);
1036 /* point to the end of the data */
1039 /* null terminate == cheap insurance */
1048 /*********************************************************************
1050 * Function : decompress_iob
1052 * Description : Decompress buffered page, expanding the
1053 * buffer as necessary. csp->iob->cur
1054 * should point to the the beginning of the
1055 * compressed data block.
1058 * 1 : csp = Current client state (buffers, headers, etc...)
1060 * Returns : JB_ERR_OK on success,
1061 * JB_ERR_MEMORY if out-of-memory limit reached, and
1062 * JB_ERR_COMPRESS if error decompressing buffer.
1064 *********************************************************************/
1065 jb_err decompress_iob(struct client_state *csp)
1067 char *buf; /* new, uncompressed buffer */
1068 char *cur; /* Current iob position (to keep the original
1069 * iob->cur unmodified if we return early) */
1070 size_t bufsize; /* allocated size of the new buffer */
1071 size_t old_size; /* Content size before decompression */
1072 size_t skip_size; /* Number of bytes at the beginning of the iob
1073 that we should NOT decompress. */
1074 int status; /* return status of the inflate() call */
1075 z_stream zstr; /* used by calls to zlib */
1077 assert(csp->iob->cur - csp->iob->buf > 0);
1078 assert(csp->iob->eod - csp->iob->cur > 0);
1080 bufsize = csp->iob->size;
1081 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1082 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1084 cur = csp->iob->cur;
1089 * This is to protect the parsing of gzipped data,
1090 * but it should(?) be valid for deflated data also.
1092 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1093 return JB_ERR_COMPRESS;
1096 if (csp->content_type & CT_GZIP)
1099 * Our task is slightly complicated by the facts that data
1100 * compressed by gzip does not include a zlib header, and
1101 * that there is no easily accessible interface in zlib to
1102 * handle a gzip header. We strip off the gzip header by
1103 * hand, and later inform zlib not to expect a header.
1107 * Strip off the gzip header. Please see RFC 1952 for more
1108 * explanation of the appropriate fields.
1110 if ((*cur++ != (char)0x1f)
1111 || (*cur++ != (char)0x8b)
1112 || (*cur++ != Z_DEFLATED))
1114 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1115 return JB_ERR_COMPRESS;
1121 * XXX: These magic numbers should be replaced
1122 * with macros to give a better idea what they do.
1126 /* The gzip header has reserved bits set; bail out. */
1127 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1128 return JB_ERR_COMPRESS;
1132 /* Skip extra fields if necessary. */
1136 * Skip a given number of bytes, specified
1137 * as a 16-bit little-endian value.
1140 * XXX: This code used to be:
1142 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1144 * which I had to change into:
1146 * cur += *cur++ + (*cur++ << 8);
1148 * at which point gcc43 finally noticed that the value
1149 * of cur is undefined (it depends on which of the
1150 * summands is evaluated first).
1152 * I haven't come across a site where this
1153 * code is actually executed yet, but I hope
1157 skip_bytes = *cur++;
1158 skip_bytes = *cur++ << 8;
1160 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1163 * The number of bytes to skip should be positive
1164 * and we'd like to stay in the buffer.
1166 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1168 log_error(LOG_LEVEL_ERROR,
1169 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1171 return JB_ERR_COMPRESS;
1173 log_error(LOG_LEVEL_INFO,
1174 "Skipping %d bytes for gzip compression. Does this sound right?",
1179 /* Skip the filename if necessary. */
1182 /* A null-terminated string is supposed to follow. */
1183 while (*cur++ && (cur < csp->iob->eod));
1187 /* Skip the comment if necessary. */
1190 /* A null-terminated string is supposed to follow. */
1191 while (*cur++ && (cur < csp->iob->eod));
1194 /* Skip the CRC if necessary. */
1200 if (cur >= csp->iob->eod)
1203 * If the current position pointer reached or passed
1204 * the buffer end, we were obviously tricked to skip
1207 log_error(LOG_LEVEL_ERROR,
1208 "Malformed gzip header detected. Aborting decompression.");
1209 return JB_ERR_COMPRESS;
1213 else if (csp->content_type & CT_DEFLATE)
1216 * XXX: The debug level should be lowered
1217 * before the next stable release.
1219 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1221 * In theory (that is, according to RFC 1950), deflate-compressed
1222 * data should begin with a two-byte zlib header and have an
1223 * adler32 checksum at the end. It seems that in practice only
1224 * the raw compressed data is sent. Note that this means that
1225 * we are not RFC 1950-compliant here, but the advantage is that
1226 * this actually works. :)
1228 * We add a dummy null byte to tell zlib where the data ends,
1229 * and later inform it not to expect a header.
1231 * Fortunately, add_to_iob() has thoughtfully null-terminated
1232 * the buffer; we can just increment the end pointer to include
1239 log_error(LOG_LEVEL_ERROR,
1240 "Unable to determine compression format for decompression");
1241 return JB_ERR_COMPRESS;
1244 /* Set up the fields required by zlib. */
1245 zstr.next_in = (Bytef *)cur;
1246 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1247 zstr.zalloc = Z_NULL;
1248 zstr.zfree = Z_NULL;
1249 zstr.opaque = Z_NULL;
1252 * Passing -MAX_WBITS to inflateInit2 tells the library
1253 * that there is no zlib header.
1255 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1257 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1258 return JB_ERR_COMPRESS;
1262 * Next, we allocate new storage for the inflated data.
1263 * We don't modify the existing iob yet, so in case there
1264 * is error in decompression we can recover gracefully.
1266 buf = zalloc(bufsize);
1269 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1270 return JB_ERR_MEMORY;
1273 assert(bufsize >= skip_size);
1274 memcpy(buf, csp->iob->buf, skip_size);
1275 zstr.avail_out = bufsize - skip_size;
1276 zstr.next_out = (Bytef *)buf + skip_size;
1278 /* Try to decompress the whole stream in one shot. */
1279 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1281 /* We need to allocate more memory for the output buffer. */
1283 char *tmpbuf; /* used for realloc'ing the buffer */
1284 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1287 * If zlib wants more data then there's a problem, because
1288 * the complete compressed file should have been buffered.
1290 if (0 == zstr.avail_in)
1292 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1293 return JB_ERR_COMPRESS;
1297 * If we tried the limit and still didn't have enough
1298 * memory, just give up.
1300 if (bufsize == csp->config->buffer_limit)
1302 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1303 return JB_ERR_MEMORY;
1306 /* Try doubling the buffer size each time. */
1309 /* Don't exceed the buffer limit. */
1310 if (bufsize > csp->config->buffer_limit)
1312 bufsize = csp->config->buffer_limit;
1315 /* Try to allocate the new buffer. */
1316 tmpbuf = realloc(buf, bufsize);
1319 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1321 return JB_ERR_MEMORY;
1325 char *oldnext_out = (char *)zstr.next_out;
1328 * Update the fields for inflate() to use the new
1329 * buffer, which may be in a location different from
1332 zstr.avail_out += bufsize - oldbufsize;
1333 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1336 * Compare with an uglier method of calculating these values
1337 * that doesn't require the extra oldbufsize variable.
1339 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1340 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1341 assert(zstr.avail_out > 0);
1347 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1349 log_error(LOG_LEVEL_ERROR,
1350 "Inconsistent stream state after decompression: %s", zstr.msg);
1352 * XXX: Intentionally no return.
1354 * According to zlib.h, Z_STREAM_ERROR is returned
1355 * "if the stream state was inconsistent".
1357 * I assume in this case inflate()'s status
1358 * would also be something different than Z_STREAM_END
1359 * so this check should be redundant, but lets see.
1363 if (status != Z_STREAM_END)
1365 /* We failed to decompress the stream. */
1366 log_error(LOG_LEVEL_ERROR,
1367 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1368 return JB_ERR_COMPRESS;
1372 * Finally, we can actually update the iob, since the
1373 * decompression was successful. First, free the old
1376 freez(csp->iob->buf);
1378 /* Now, update the iob to use the new buffer. */
1379 csp->iob->buf = buf;
1380 csp->iob->cur = csp->iob->buf + skip_size;
1381 csp->iob->eod = (char *)zstr.next_out;
1382 csp->iob->size = bufsize;
1385 * Make sure the new uncompressed iob obeys some minimal
1386 * consistency conditions.
1388 if ((csp->iob->buf < csp->iob->cur)
1389 && (csp->iob->cur <= csp->iob->eod)
1390 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1392 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1395 log_error(LOG_LEVEL_RE_FILTER,
1396 "Decompression successful. Old size: %d, new size: %d.",
1397 old_size, new_size);
1401 /* zlib thinks this is OK, so lets do the same. */
1402 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1407 /* It seems that zlib did something weird. */
1408 log_error(LOG_LEVEL_ERROR,
1409 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1410 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1411 csp->iob->eod, csp->iob->buf + csp->iob->size);
1412 return JB_ERR_COMPRESS;
1418 #endif /* defined(FEATURE_ZLIB) */
1421 /*********************************************************************
1423 * Function : get_header
1425 * Description : This (odd) routine will parse the csp->iob
1428 * 1 : csp = Current client state (buffers, headers, etc...)
1430 * Returns : Any one of the following:
1432 * 1) a pointer to a dynamically allocated string that contains a header line
1433 * 2) NULL indicating that the end of the header was reached
1434 * 3) "" indicating that the end of the iob was reached before finding
1435 * a complete header line.
1437 *********************************************************************/
1438 char *get_header(struct client_state *csp)
1444 if ((iob->cur == NULL)
1445 || ((p = strchr(iob->cur, '\n')) == NULL))
1447 return(""); /* couldn't find a complete header */
1452 ret = strdup(iob->cur);
1455 /* FIXME No way to handle error properly */
1456 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1461 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1463 /* is this a blank line (i.e. the end of the header) ? */
1475 /*********************************************************************
1477 * Function : get_header_value
1479 * Description : Get the value of a given header from a chained list
1480 * of header lines or return NULL if no such header is
1481 * present in the list.
1484 * 1 : header_list = pointer to list
1485 * 2 : header_name = string with name of header to look for.
1486 * Trailing colon required, capitalization
1489 * Returns : NULL if not found, else value of header
1491 *********************************************************************/
1492 char *get_header_value(const struct list *header_list, const char *header_name)
1494 struct list_entry *cur_entry;
1498 assert(header_list);
1499 assert(header_name);
1500 length = strlen(header_name);
1502 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1506 if (!strncmpic(cur_entry->str, header_name, length))
1509 * Found: return pointer to start of value
1511 ret = (char *) (cur_entry->str + length);
1512 while (*ret && ijb_isspace(*ret)) ret++;
1526 /*********************************************************************
1528 * Function : scan_headers
1530 * Description : Scans headers, applies tags and updates action bits.
1533 * 1 : csp = Current client state (buffers, headers, etc...)
1535 * Returns : JB_ERR_OK
1537 *********************************************************************/
1538 static jb_err scan_headers(struct client_state *csp)
1540 struct list_entry *h; /* Header */
1541 jb_err err = JB_ERR_OK;
1543 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1545 /* Header crunch()ed in previous run? -> ignore */
1546 if (h->str == NULL) continue;
1547 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1548 err = header_tagger(csp, h->str);
1555 /*********************************************************************
1559 * Description : add, delete or modify lines in the HTTP header streams.
1560 * On entry, it receives a linked list of headers space
1561 * that was allocated dynamically (both the list nodes
1562 * and the header contents).
1564 * As a side effect it frees the space used by the original
1567 * XXX: should be split to remove the first_run hack.
1570 * 1 : pats = list of patterns to match against headers
1571 * 2 : more_headers = list of functions to add more
1572 * headers (client or server)
1573 * 3 : csp = Current client state (buffers, headers, etc...)
1575 * Returns : JB_ERR_OK in case off success, or
1576 * JB_ERR_MEMORY on out-of-memory error.
1578 *********************************************************************/
1579 jb_err sed(const struct parsers pats[],
1580 const add_header_func_ptr more_headers[],
1581 struct client_state *csp)
1583 struct list_entry *p;
1584 const struct parsers *v;
1585 const add_header_func_ptr *f;
1586 jb_err err = JB_ERR_OK;
1590 * If filtering is enabled, sed is run twice,
1591 * but most of the work needs to be done only once.
1593 first_run = (more_headers != NULL ) ? 1 : 0;
1595 if (first_run) /* Parse and print */
1599 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1601 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1603 /* Header crunch()ed in previous run? -> ignore */
1604 if (p->str == NULL) continue;
1606 /* Does the current parser handle this header? */
1607 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1609 err = v->parser(csp, (char **)&(p->str));
1613 /* place any additional headers on the csp->headers list */
1614 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1619 else /* Parse only */
1622 * The second run is only needed if the body was modified
1623 * and the content-lenght has changed.
1625 if (strncmpic(csp->http->cmd, "HEAD", 4))
1627 /*XXX: Code duplication */
1628 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1630 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1632 /* Header crunch()ed in previous run? -> ignore */
1633 if (p->str == NULL) continue;
1635 /* Does the current parser handle this header? */
1636 if (strncmpic(p->str, v->str, v->len) == 0)
1638 err = v->parser(csp, (char **)&(p->str));
1650 /*********************************************************************
1652 * Function : header_tagger
1654 * Description : Executes all text substitutions from applying
1655 * tag actions and saves the result as tag.
1657 * XXX: Shares enough code with filter_header() and
1658 * pcrs_filter_response() to warrant some helper functions.
1661 * 1 : csp = Current client state (buffers, headers, etc...)
1662 * 2 : header = Header that is used as tagger input
1664 * Returns : JB_ERR_OK on success and always succeeds
1666 *********************************************************************/
1667 static jb_err header_tagger(struct client_state *csp, char *header)
1669 int wanted_filter_type;
1670 int multi_action_index;
1674 struct file_list *fl;
1675 struct re_filterfile_spec *b;
1676 struct list_entry *tag_name;
1678 int found_filters = 0;
1679 const size_t header_length = strlen(header);
1681 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1683 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1684 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1688 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1689 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1692 /* Check if there are any filters */
1693 for (i = 0; i < MAX_AF_FILES; i++)
1706 if (0 == found_filters)
1708 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1709 "tagging enabled, but no taggers available.");
1713 for (i = 0; i < MAX_AF_FILES; i++)
1716 if ((NULL == fl) || (NULL == fl->f))
1719 * Either there are no filter files
1720 * left, or this filter file just
1721 * contains no valid filters.
1723 * Continue to be sure we don't miss
1724 * valid filter files that are chained
1725 * after empty or invalid ones.
1730 /* For all filters, */
1731 for (b = fl->f; b; b = b->next)
1733 if (b->type != wanted_filter_type)
1735 /* skip the ones we don't care about, */
1738 /* leaving only taggers that could apply, of which we use the ones, */
1739 for (tag_name = csp->action->multi[multi_action_index]->first;
1740 NULL != tag_name; tag_name = tag_name->next)
1742 /* that do apply, and */
1743 if (strcmp(b->name, tag_name->str) == 0)
1745 char *modified_tag = NULL;
1747 size_t size = header_length;
1748 pcrs_job *joblist = b->joblist;
1750 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1752 if (NULL == joblist)
1754 log_error(LOG_LEVEL_RE_FILTER,
1755 "Tagger %s has empty joblist. Nothing to do.", b->name);
1759 /* execute their pcrs_joblist on the header. */
1760 for (job = joblist; NULL != job; job = job->next)
1762 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1766 /* Success, continue with the modified version. */
1775 /* Tagger doesn't match */
1778 /* Regex failure, log it but continue anyway. */
1779 log_error(LOG_LEVEL_ERROR,
1780 "Problems with tagger \'%s\' and header \'%s\': %s",
1781 b->name, *header, pcrs_strerror(hits));
1783 freez(modified_tag);
1787 if (b->dynamic) pcrs_free_joblist(joblist);
1789 /* If this tagger matched */
1795 * There is to technical limitation which makes
1796 * it impossible to use empty tags, but I assume
1797 * no one would do it intentionally.
1800 log_error(LOG_LEVEL_INFO,
1801 "Tagger \'%s\' created an empty tag. Ignored.",
1806 if (!list_contains_item(csp->tags, tag))
1808 if (JB_ERR_OK != enlist(csp->tags, tag))
1810 log_error(LOG_LEVEL_ERROR,
1811 "Insufficient memory to add tag \'%s\', "
1812 "based on tagger \'%s\' and header \'%s\'",
1813 tag, b->name, *header);
1817 char *action_message;
1819 * update the action bits right away, to make
1820 * tagging based on tags set by earlier taggers
1821 * of the same kind possible.
1823 if (update_action_bits_for_tag(csp, tag))
1825 action_message = "Action bits updated accordingly.";
1829 action_message = "No action bits update necessary.";
1832 log_error(LOG_LEVEL_HEADER,
1833 "Tagger \'%s\' added tag \'%s\'. %s",
1834 b->name, tag, action_message);
1839 /* XXX: Is this log-worthy? */
1840 log_error(LOG_LEVEL_HEADER,
1841 "Tagger \'%s\' didn't add tag \'%s\'. "
1842 "Tag already present", b->name, tag);
1845 } /* if the tagger matched */
1846 } /* if the tagger applies */
1847 } /* for every tagger that could apply */
1848 } /* for all filters */
1849 } /* for all filter files */
1854 /* here begins the family of parser functions that reformat header lines */
1856 /*********************************************************************
1858 * Function : filter_header
1860 * Description : Executes all text substitutions from all applying
1861 * +(server|client)-header-filter actions on the header.
1862 * Most of the code was copied from pcrs_filter_response,
1863 * including the rather short variable names
1866 * 1 : csp = Current client state (buffers, headers, etc...)
1867 * 2 : header = On input, pointer to header to modify.
1868 * On output, pointer to the modified header, or NULL
1869 * to remove the header. This function frees the
1870 * original string if necessary.
1872 * Returns : JB_ERR_OK on success and always succeeds
1874 *********************************************************************/
1875 static jb_err filter_header(struct client_state *csp, char **header)
1879 size_t size = strlen(*header);
1881 char *newheader = NULL;
1884 struct file_list *fl;
1885 struct re_filterfile_spec *b;
1886 struct list_entry *filtername;
1888 int i, found_filters = 0;
1889 int wanted_filter_type;
1890 int multi_action_index;
1892 if (csp->flags & CSP_FLAG_NO_FILTERING)
1897 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1899 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1900 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1904 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1905 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1909 * Need to check the set of re_filterfiles...
1911 for (i = 0; i < MAX_AF_FILES; i++)
1924 if (0 == found_filters)
1926 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1927 "header filtering enabled, but no matching filters available.");
1931 for (i = 0; i < MAX_AF_FILES; i++)
1934 if ((NULL == fl) || (NULL == fl->f))
1937 * Either there are no filter files
1938 * left, or this filter file just
1939 * contains no valid filters.
1941 * Continue to be sure we don't miss
1942 * valid filter files that are chained
1943 * after empty or invalid ones.
1948 * For all applying +filter actions, look if a filter by that
1949 * name exists and if yes, execute its pcrs_joblist on the
1952 for (b = fl->f; b; b = b->next)
1954 if (b->type != wanted_filter_type)
1956 /* Skip other filter types */
1960 for (filtername = csp->action->multi[multi_action_index]->first;
1961 filtername ; filtername = filtername->next)
1963 if (strcmp(b->name, filtername->str) == 0)
1965 int current_hits = 0;
1966 pcrs_job *joblist = b->joblist;
1968 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1970 if (NULL == joblist)
1972 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1976 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1977 *header, size, b->name);
1979 /* Apply all jobs from the joblist */
1980 for (job = joblist; NULL != job; job = job->next)
1982 matches = pcrs_execute(job, *header, size, &newheader, &size);
1985 current_hits += matches;
1986 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1988 *header = newheader;
1990 else if ( 0 == matches )
1992 /* Filter doesn't change header */
1998 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1999 *header, b->name, pcrs_strerror(matches));
2000 if (newheader != NULL)
2002 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2008 if (b->dynamic) pcrs_free_joblist(joblist);
2010 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2011 hits += current_hits;
2018 * Additionally checking for hits is important because if
2019 * the continue hack is triggered, server headers can
2020 * arrive empty to separate multiple heads from each other.
2022 if ((0 == size) && hits)
2024 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2032 /*********************************************************************
2034 * Function : connection
2036 * Description : Makes sure that the value of the Connection: header
2037 * is "close" and signals connection_close_adder
2041 * 1 : csp = Current client state (buffers, headers, etc...)
2042 * 2 : header = On input, pointer to header to modify.
2043 * On output, pointer to the modified header, or NULL
2044 * to remove the header. This function frees the
2045 * original string if necessary.
2047 * Returns : JB_ERR_OK on success, or
2048 * JB_ERR_MEMORY on out-of-memory error.
2050 *********************************************************************/
2051 static jb_err connection(struct client_state *csp, char **header)
2053 char *old_header = *header;
2055 /* Do we have a 'Connection: close' header? */
2056 if (strcmpic(*header, "Connection: close"))
2058 /* No, create one */
2059 *header = strdup("Connection: close");
2062 return JB_ERR_MEMORY;
2064 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2068 /* Signal connection_close_adder() to return early. */
2069 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2071 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2075 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2082 /*********************************************************************
2084 * Function : crumble
2086 * Description : This is called if a header matches a pattern to "crunch"
2089 * 1 : csp = Current client state (buffers, headers, etc...)
2090 * 2 : header = On input, pointer to header to modify.
2091 * On output, pointer to the modified header, or NULL
2092 * to remove the header. This function frees the
2093 * original string if necessary.
2095 * Returns : JB_ERR_OK on success, or
2096 * JB_ERR_MEMORY on out-of-memory error.
2098 *********************************************************************/
2099 static jb_err crumble(struct client_state *csp, char **header)
2101 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2107 /*********************************************************************
2109 * Function : crunch_server_header
2111 * Description : Crunch server header if it matches a string supplied by the
2112 * user. Called from `sed'.
2115 * 1 : csp = Current client state (buffers, headers, etc...)
2116 * 2 : header = On input, pointer to header to modify.
2117 * On output, pointer to the modified header, or NULL
2118 * to remove the header. This function frees the
2119 * original string if necessary.
2121 * Returns : JB_ERR_OK on success and always succeeds
2123 *********************************************************************/
2124 static jb_err crunch_server_header(struct client_state *csp, char **header)
2126 const char *crunch_pattern;
2128 /* Do we feel like crunching? */
2129 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2131 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2133 /* Is the current header the lucky one? */
2134 if (strstr(*header, crunch_pattern))
2136 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2145 /*********************************************************************
2147 * Function : server_content_type
2149 * Description : Set the content-type for filterable types (text/.*,
2150 * .*xml.*, javascript and image/gif) unless filtering has been
2151 * forbidden (CT_TABOO) while parsing earlier headers.
2152 * NOTE: Since text/plain is commonly used by web servers
2153 * for files whose correct type is unknown, we don't
2154 * set CT_TEXT for it.
2157 * 1 : csp = Current client state (buffers, headers, etc...)
2158 * 2 : header = On input, pointer to header to modify.
2159 * On output, pointer to the modified header, or NULL
2160 * to remove the header. This function frees the
2161 * original string if necessary.
2163 * Returns : JB_ERR_OK on success, or
2164 * JB_ERR_MEMORY on out-of-memory error.
2166 *********************************************************************/
2167 static jb_err server_content_type(struct client_state *csp, char **header)
2169 /* Remove header if it isn't the first Content-Type header */
2170 if ((csp->content_type & CT_DECLARED))
2173 * Another, slightly slower, way to see if
2174 * we already parsed another Content-Type header.
2176 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2178 log_error(LOG_LEVEL_ERROR,
2179 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2187 * Signal that the Content-Type has been set.
2189 csp->content_type |= CT_DECLARED;
2191 if (!(csp->content_type & CT_TABOO))
2194 * XXX: The assumption that text/plain is a sign of
2195 * binary data seems to be somewhat unreasonable nowadays
2196 * and should be dropped after 3.0.8 is out.
2198 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2199 || strstr(*header, "xml")
2200 || strstr(*header, "application/x-javascript"))
2202 csp->content_type |= CT_TEXT;
2204 else if (strstr(*header, "image/gif"))
2206 csp->content_type |= CT_GIF;
2211 * Are we messing with the content type?
2213 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2216 * Make sure the user doesn't accidently
2217 * change the content type of binary documents.
2219 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2222 *header = strdup("Content-Type: ");
2223 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2227 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2228 return JB_ERR_MEMORY;
2230 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2234 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2235 "It doesn't look like a content type that should be filtered. "
2236 "Enable force-text-mode if you know what you're doing.", *header);
2244 /*********************************************************************
2246 * Function : server_transfer_coding
2248 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2249 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2250 * - Remove header if body was chunked but has been
2251 * de-chunked for filtering.
2254 * 1 : csp = Current client state (buffers, headers, etc...)
2255 * 2 : header = On input, pointer to header to modify.
2256 * On output, pointer to the modified header, or NULL
2257 * to remove the header. This function frees the
2258 * original string if necessary.
2260 * Returns : JB_ERR_OK on success, or
2261 * JB_ERR_MEMORY on out-of-memory error.
2263 *********************************************************************/
2264 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2267 * Turn off pcrs and gif filtering if body compressed
2269 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2273 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2275 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2276 csp->http->cmd, *header);
2277 #endif /* def FEATURE_ZLIB */
2278 csp->content_type = CT_TABOO;
2282 * Raise flag if body chunked
2284 if (strstr(*header, "chunked"))
2286 csp->flags |= CSP_FLAG_CHUNKED;
2289 * If the body was modified, it has been de-chunked first
2290 * and the header must be removed.
2292 * FIXME: If there is more than one transfer encoding,
2293 * only the "chunked" part should be removed here.
2295 if (csp->flags & CSP_FLAG_MODIFIED)
2297 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2306 /*********************************************************************
2308 * Function : server_content_encoding
2310 * Description : This function is run twice for each request,
2311 * unless FEATURE_ZLIB and filtering are disabled.
2313 * The first run is used to check if the content
2314 * is compressed, if FEATURE_ZLIB is disabled
2315 * filtering is then disabled as well, if FEATURE_ZLIB
2316 * is enabled the content is marked for decompression.
2318 * The second run is used to remove the Content-Encoding
2319 * header if the decompression was successful.
2322 * 1 : csp = Current client state (buffers, headers, etc...)
2323 * 2 : header = On input, pointer to header to modify.
2324 * On output, pointer to the modified header, or NULL
2325 * to remove the header. This function frees the
2326 * original string if necessary.
2328 * Returns : JB_ERR_OK on success, or
2329 * JB_ERR_MEMORY on out-of-memory error.
2331 *********************************************************************/
2332 static jb_err server_content_encoding(struct client_state *csp, char **header)
2335 if ((csp->flags & CSP_FLAG_MODIFIED)
2336 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2339 * We successfully decompressed the content,
2340 * and have to clean the header now, so the
2341 * client no longer expects compressed data..
2343 * XXX: There is a difference between cleaning
2344 * and removing it completely.
2346 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2349 else if (strstr(*header, "gzip"))
2351 /* Mark for gzip decompression */
2352 csp->content_type |= CT_GZIP;
2354 else if (strstr(*header, "deflate"))
2356 /* Mark for zlib decompression */
2357 csp->content_type |= CT_DEFLATE;
2359 else if (strstr(*header, "compress"))
2362 * We can't decompress this; therefore we can't filter
2365 csp->content_type |= CT_TABOO;
2367 #else /* !defined(FEATURE_ZLIB) */
2368 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2371 * Body is compressed, turn off pcrs and gif filtering.
2373 csp->content_type |= CT_TABOO;
2376 * Log a warning if the user expects the content to be filtered.
2378 if ((csp->rlist != NULL) &&
2379 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2381 log_error(LOG_LEVEL_INFO,
2382 "Compressed content detected, content filtering disabled. "
2383 "Consider recompiling Privoxy with zlib support or "
2384 "enable the prevent-compression action.");
2387 #endif /* defined(FEATURE_ZLIB) */
2394 /*********************************************************************
2396 * Function : server_content_length
2398 * Description : Adjust Content-Length header if we modified
2402 * 1 : csp = Current client state (buffers, headers, etc...)
2403 * 2 : header = On input, pointer to header to modify.
2404 * On output, pointer to the modified header, or NULL
2405 * to remove the header. This function frees the
2406 * original string if necessary.
2408 * Returns : JB_ERR_OK on success, or
2409 * JB_ERR_MEMORY on out-of-memory error.
2411 *********************************************************************/
2412 static jb_err server_content_length(struct client_state *csp, char **header)
2414 const size_t max_header_length = 80;
2416 /* Regenerate header if the content was modified. */
2417 if (csp->flags & CSP_FLAG_MODIFIED)
2420 *header = (char *) zalloc(max_header_length);
2421 if (*header == NULL)
2423 return JB_ERR_MEMORY;
2426 snprintf(*header, max_header_length, "Content-Length: %d",
2427 (int)csp->content_length);
2428 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2429 (int)csp->content_length);
2436 /*********************************************************************
2438 * Function : server_content_md5
2440 * Description : Crumble any Content-MD5 headers if the document was
2441 * modified. FIXME: Should we re-compute instead?
2444 * 1 : csp = Current client state (buffers, headers, etc...)
2445 * 2 : header = On input, pointer to header to modify.
2446 * On output, pointer to the modified header, or NULL
2447 * to remove the header. This function frees the
2448 * original string if necessary.
2450 * Returns : JB_ERR_OK on success, or
2451 * JB_ERR_MEMORY on out-of-memory error.
2453 *********************************************************************/
2454 static jb_err server_content_md5(struct client_state *csp, char **header)
2456 if (csp->flags & CSP_FLAG_MODIFIED)
2458 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2466 /*********************************************************************
2468 * Function : server_content_disposition
2470 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2471 * Called from `sed'.
2474 * 1 : csp = Current client state (buffers, headers, etc...)
2475 * 2 : header = On input, pointer to header to modify.
2476 * On output, pointer to the modified header, or NULL
2477 * to remove the header. This function frees the
2478 * original string if necessary.
2480 * Returns : JB_ERR_OK on success, or
2481 * JB_ERR_MEMORY on out-of-memory error.
2483 *********************************************************************/
2484 static jb_err server_content_disposition(struct client_state *csp, char **header)
2489 * Are we messing with the Content-Disposition header?
2491 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2497 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2499 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2502 * Blocking content-disposition header
2504 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2511 * Replacing Content-Disposition header
2514 *header = strdup("Content-Disposition: ");
2515 string_append(header, newval);
2517 if (*header != NULL)
2519 log_error(LOG_LEVEL_HEADER,
2520 "Content-Disposition header crunched and replaced with: %s", *header);
2523 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2527 /*********************************************************************
2529 * Function : server_last_modified
2531 * Description : Changes Last-Modified header to the actual date
2532 * to help hide-if-modified-since.
2533 * Called from `sed'.
2536 * 1 : csp = Current client state (buffers, headers, etc...)
2537 * 2 : header = On input, pointer to header to modify.
2538 * On output, pointer to the modified header, or NULL
2539 * to remove the header. This function frees the
2540 * original string if necessary.
2542 * Returns : JB_ERR_OK on success, or
2543 * JB_ERR_MEMORY on out-of-memory error.
2545 *********************************************************************/
2546 static jb_err server_last_modified(struct client_state *csp, char **header)
2549 char buf[BUFFER_SIZE];
2552 #ifdef HAVE_GMTIME_R
2555 struct tm *timeptr = NULL;
2556 time_t now, last_modified;
2558 long int days, hours, minutes, seconds;
2561 * Are we messing with the Last-Modified header?
2563 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2569 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2571 if (0 == strcmpic(newval, "block") )
2574 * Blocking Last-Modified header. Useless but why not.
2576 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2580 else if (0 == strcmpic(newval, "reset-to-request-time"))
2583 * Setting Last-Modified Header to now.
2585 get_http_time(0, buf);
2587 *header = strdup("Last-Modified: ");
2588 string_append(header, buf);
2590 if (*header == NULL)
2592 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2596 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2599 else if (0 == strcmpic(newval, "randomize"))
2601 const char *header_time = *header + sizeof("Last-Modified:");
2603 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2605 #ifdef HAVE_GMTIME_R
2606 timeptr = gmtime_r(&now, &gmt);
2607 #elif FEATURE_PTHREAD
2608 pthread_mutex_lock(&gmtime_mutex);
2609 timeptr = gmtime(&now);
2610 pthread_mutex_unlock(&gmtime_mutex);
2612 timeptr = gmtime(&now);
2614 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2616 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2621 rtime = (long int)difftime(now, last_modified);
2630 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2632 rtime = pick_from_range(rtime);
2633 if (negative) rtime *= -1;
2634 last_modified += rtime;
2635 #ifdef HAVE_GMTIME_R
2636 timeptr = gmtime_r(&last_modified, &gmt);
2637 #elif FEATURE_PTHREAD
2638 pthread_mutex_lock(&gmtime_mutex);
2639 timeptr = gmtime(&last_modified);
2640 pthread_mutex_unlock(&gmtime_mutex);
2642 timeptr = gmtime(&last_modified);
2644 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2646 *header = strdup("Last-Modified: ");
2647 string_append(header, newheader);
2649 if (*header == NULL)
2651 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2652 return JB_ERR_MEMORY;
2655 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2657 days = rtime / (3600 * 24);
2658 hours = rtime / 3600 % 24;
2659 minutes = rtime / 60 % 60;
2660 seconds = rtime % 60;
2662 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2663 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2664 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2669 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2678 /*********************************************************************
2680 * Function : client_accept_encoding
2682 * Description : Rewrite the client's Accept-Encoding header so that
2683 * if doesn't allow compression, if the action applies.
2684 * Note: For HTTP/1.0 the absence of the header is enough.
2687 * 1 : csp = Current client state (buffers, headers, etc...)
2688 * 2 : header = On input, pointer to header to modify.
2689 * On output, pointer to the modified header, or NULL
2690 * to remove the header. This function frees the
2691 * original string if necessary.
2693 * Returns : JB_ERR_OK on success, or
2694 * JB_ERR_MEMORY on out-of-memory error.
2696 *********************************************************************/
2697 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2699 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2701 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2705 /* Temporarily disable the correct behaviour to
2706 * work around a PHP bug.
2708 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2710 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2711 * if (*header == NULL)
2713 * return JB_ERR_MEMORY;
2724 /*********************************************************************
2726 * Function : client_te
2728 * Description : Rewrite the client's TE header so that
2729 * if doesn't allow compression, if the action applies.
2732 * 1 : csp = Current client state (buffers, headers, etc...)
2733 * 2 : header = On input, pointer to header to modify.
2734 * On output, pointer to the modified header, or NULL
2735 * to remove the header. This function frees the
2736 * original string if necessary.
2738 * Returns : JB_ERR_OK on success, or
2739 * JB_ERR_MEMORY on out-of-memory error.
2741 *********************************************************************/
2742 static jb_err client_te(struct client_state *csp, char **header)
2744 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2747 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2754 /*********************************************************************
2756 * Function : client_referrer
2758 * Description : Handle the "referer" config setting properly.
2759 * Called from `sed'.
2762 * 1 : csp = Current client state (buffers, headers, etc...)
2763 * 2 : header = On input, pointer to header to modify.
2764 * On output, pointer to the modified header, or NULL
2765 * to remove the header. This function frees the
2766 * original string if necessary.
2768 * Returns : JB_ERR_OK on success, or
2769 * JB_ERR_MEMORY on out-of-memory error.
2771 *********************************************************************/
2772 static jb_err client_referrer(struct client_state *csp, char **header)
2774 const char *parameter;
2775 /* booleans for parameters we have to check multiple times */
2776 int parameter_conditional_block;
2777 int parameter_conditional_forge;
2779 #ifdef FEATURE_FORCE_LOAD
2781 * Since the referrer can include the prefix even
2782 * if the request itself is non-forced, we must
2783 * clean it unconditionally.
2785 * XXX: strclean is too broad
2787 strclean(*header, FORCE_PREFIX);
2788 #endif /* def FEATURE_FORCE_LOAD */
2790 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2792 /* Nothing left to do */
2796 parameter = csp->action->string[ACTION_STRING_REFERER];
2797 assert(parameter != NULL);
2798 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2799 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2801 if (!parameter_conditional_block && !parameter_conditional_forge)
2804 * As conditional-block and conditional-forge are the only
2805 * parameters that rely on the original referrer, we can
2806 * remove it now for all the others.
2811 if (0 == strcmpic(parameter, "block"))
2813 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2816 else if (parameter_conditional_block || parameter_conditional_forge)
2818 return handle_conditional_hide_referrer_parameter(header,
2819 csp->http->hostport, parameter_conditional_block);
2821 else if (0 == strcmpic(parameter, "forge"))
2823 return create_forged_referrer(header, csp->http->hostport);
2827 /* interpret parameter as user-supplied referer to fake */
2828 return create_fake_referrer(header, parameter);
2833 /*********************************************************************
2835 * Function : client_accept_language
2837 * Description : Handle the "Accept-Language" config setting properly.
2838 * Called from `sed'.
2841 * 1 : csp = Current client state (buffers, headers, etc...)
2842 * 2 : header = On input, pointer to header to modify.
2843 * On output, pointer to the modified header, or NULL
2844 * to remove the header. This function frees the
2845 * original string if necessary.
2847 * Returns : JB_ERR_OK on success, or
2848 * JB_ERR_MEMORY on out-of-memory error.
2850 *********************************************************************/
2851 static jb_err client_accept_language(struct client_state *csp, char **header)
2856 * Are we messing with the Accept-Language?
2858 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2860 /*I don't think so*/
2864 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2866 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2869 * Blocking Accept-Language header
2871 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2878 * Replacing Accept-Language header
2881 *header = strdup("Accept-Language: ");
2882 string_append(header, newval);
2884 if (*header == NULL)
2886 log_error(LOG_LEVEL_ERROR,
2887 "Insufficent memory. Accept-Language header crunched without replacement.");
2891 log_error(LOG_LEVEL_HEADER,
2892 "Accept-Language header crunched and replaced with: %s", *header);
2895 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2899 /*********************************************************************
2901 * Function : crunch_client_header
2903 * Description : Crunch client header if it matches a string supplied by the
2904 * user. Called from `sed'.
2907 * 1 : csp = Current client state (buffers, headers, etc...)
2908 * 2 : header = On input, pointer to header to modify.
2909 * On output, pointer to the modified header, or NULL
2910 * to remove the header. This function frees the
2911 * original string if necessary.
2913 * Returns : JB_ERR_OK on success and always succeeds
2915 *********************************************************************/
2916 static jb_err crunch_client_header(struct client_state *csp, char **header)
2918 const char *crunch_pattern;
2920 /* Do we feel like crunching? */
2921 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2923 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2925 /* Is the current header the lucky one? */
2926 if (strstr(*header, crunch_pattern))
2928 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2936 /*********************************************************************
2938 * Function : client_uagent
2940 * Description : Handle the "user-agent" config setting properly
2941 * and remember its original value to enable browser
2942 * bug workarounds. Called from `sed'.
2945 * 1 : csp = Current client state (buffers, headers, etc...)
2946 * 2 : header = On input, pointer to header to modify.
2947 * On output, pointer to the modified header, or NULL
2948 * to remove the header. This function frees the
2949 * original string if necessary.
2951 * Returns : JB_ERR_OK on success, or
2952 * JB_ERR_MEMORY on out-of-memory error.
2954 *********************************************************************/
2955 static jb_err client_uagent(struct client_state *csp, char **header)
2959 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2964 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2971 *header = strdup("User-Agent: ");
2972 string_append(header, newval);
2974 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2976 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2980 /*********************************************************************
2982 * Function : client_ua
2984 * Description : Handle "ua-" headers properly. Called from `sed'.
2987 * 1 : csp = Current client state (buffers, headers, etc...)
2988 * 2 : header = On input, pointer to header to modify.
2989 * On output, pointer to the modified header, or NULL
2990 * to remove the header. This function frees the
2991 * original string if necessary.
2993 * Returns : JB_ERR_OK on success, or
2994 * JB_ERR_MEMORY on out-of-memory error.
2996 *********************************************************************/
2997 static jb_err client_ua(struct client_state *csp, char **header)
2999 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3001 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3009 /*********************************************************************
3011 * Function : client_from
3013 * Description : Handle the "from" config setting properly.
3014 * Called from `sed'.
3017 * 1 : csp = Current client state (buffers, headers, etc...)
3018 * 2 : header = On input, pointer to header to modify.
3019 * On output, pointer to the modified header, or NULL
3020 * to remove the header. This function frees the
3021 * original string if necessary.
3023 * Returns : JB_ERR_OK on success, or
3024 * JB_ERR_MEMORY on out-of-memory error.
3026 *********************************************************************/
3027 static jb_err client_from(struct client_state *csp, char **header)
3031 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3038 newval = csp->action->string[ACTION_STRING_FROM];
3041 * Are we blocking the e-mail address?
3043 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3045 log_error(LOG_LEVEL_HEADER, "crunched From!");
3049 log_error(LOG_LEVEL_HEADER, " modified");
3051 *header = strdup("From: ");
3052 string_append(header, newval);
3054 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3058 /*********************************************************************
3060 * Function : client_send_cookie
3062 * Description : Crunches the "cookie" header if necessary.
3063 * Called from `sed'.
3065 * XXX: Stupid name, doesn't send squat.
3068 * 1 : csp = Current client state (buffers, headers, etc...)
3069 * 2 : header = On input, pointer to header to modify.
3070 * On output, pointer to the modified header, or NULL
3071 * to remove the header. This function frees the
3072 * original string if necessary.
3074 * Returns : JB_ERR_OK on success, or
3075 * JB_ERR_MEMORY on out-of-memory error.
3077 *********************************************************************/
3078 static jb_err client_send_cookie(struct client_state *csp, char **header)
3080 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3082 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3090 /*********************************************************************
3092 * Function : client_x_forwarded
3094 * Description : Handle the "x-forwarded-for" config setting properly,
3095 * also used in the add_client_headers list. Called from `sed'.
3098 * 1 : csp = Current client state (buffers, headers, etc...)
3099 * 2 : header = On input, pointer to header to modify.
3100 * On output, pointer to the modified header, or NULL
3101 * to remove the header. This function frees the
3102 * original string if necessary.
3104 * Returns : JB_ERR_OK on success, or
3105 * JB_ERR_MEMORY on out-of-memory error.
3107 *********************************************************************/
3108 jb_err client_x_forwarded(struct client_state *csp, char **header)
3110 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3113 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3120 /*********************************************************************
3122 * Function : client_max_forwards
3124 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3125 * from the value of the Max-Forwards header field.
3128 * 1 : csp = Current client state (buffers, headers, etc...)
3129 * 2 : header = On input, pointer to header to modify.
3130 * On output, pointer to the modified header, or NULL
3131 * to remove the header. This function frees the
3132 * original string if necessary.
3134 * Returns : JB_ERR_OK on success, or
3135 * JB_ERR_MEMORY on out-of-memory error.
3137 *********************************************************************/
3138 static jb_err client_max_forwards(struct client_state *csp, char **header)
3142 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3143 (0 == strcmpic(csp->http->gpc, "options")))
3145 assert(*(*header+12) == ':');
3146 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3148 if (max_forwards > 0)
3150 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3151 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3152 csp->http->gpc, max_forwards);
3154 else if (max_forwards < 0)
3156 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3162 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3171 /*********************************************************************
3173 * Function : client_host
3175 * Description : If the request URI did not contain host and
3176 * port information, parse and evaluate the Host
3179 * Also, kill ill-formed HOST: headers as sent by
3180 * Apple's iTunes software when used with a proxy.
3183 * 1 : csp = Current client state (buffers, headers, etc...)
3184 * 2 : header = On input, pointer to header to modify.
3185 * On output, pointer to the modified header, or NULL
3186 * to remove the header. This function frees the
3187 * original string if necessary.
3189 * Returns : JB_ERR_OK on success, or
3190 * JB_ERR_MEMORY on out-of-memory error.
3192 *********************************************************************/
3193 static jb_err client_host(struct client_state *csp, char **header)
3198 * If the header field name is all upper-case, chances are that it's
3199 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3200 * not a problem -- they are regenerated later.
3202 if ((*header)[1] == 'O')
3204 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3209 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3210 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3213 if (NULL == (p = strdup((*header)+6)))
3215 return JB_ERR_MEMORY;
3218 if (NULL == (q = strdup(p)))
3221 return JB_ERR_MEMORY;
3224 freez(csp->http->hostport);
3225 csp->http->hostport = p;
3226 freez(csp->http->host);
3227 csp->http->host = q;
3228 q = strchr(csp->http->host, ':');
3231 /* Terminate hostname and evaluate port string */
3233 csp->http->port = atoi(q);
3237 csp->http->port = csp->http->ssl ? 443 : 80;
3240 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3241 csp->http->hostport, csp->http->host, csp->http->port);
3244 /* Signal client_host_adder() to return right away */
3245 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3251 /*********************************************************************
3253 * Function : client_if_modified_since
3255 * Description : Remove or modify the If-Modified-Since header.
3258 * 1 : csp = Current client state (buffers, headers, etc...)
3259 * 2 : header = On input, pointer to header to modify.
3260 * On output, pointer to the modified header, or NULL
3261 * to remove the header. This function frees the
3262 * original string if necessary.
3264 * Returns : JB_ERR_OK on success, or
3265 * JB_ERR_MEMORY on out-of-memory error.
3267 *********************************************************************/
3268 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3271 #ifdef HAVE_GMTIME_R
3274 struct tm *timeptr = NULL;
3278 long int hours, minutes, seconds;
3282 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3285 * The client got an error message because of a temporary problem,
3286 * the problem is gone and the client now tries to revalidate our
3287 * error message on the real server. The revalidation would always
3288 * end with the transmission of the whole document and there is
3289 * no need to expose the bogus If-Modified-Since header.
3291 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3294 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3296 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3298 if ((0 == strcmpic(newval, "block")))
3300 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3303 else /* add random value */
3305 const char *header_time = *header + sizeof("If-Modified-Since:");
3307 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3309 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3314 rtime = strtol(newval, &endptr, 0);
3317 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3318 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3325 rtime = pick_from_range(rtime);
3329 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3332 tm += rtime * (negative ? -1 : 1);
3333 #ifdef HAVE_GMTIME_R
3334 timeptr = gmtime_r(&tm, &gmt);
3335 #elif FEATURE_PTHREAD
3336 pthread_mutex_lock(&gmtime_mutex);
3337 timeptr = gmtime(&tm);
3338 pthread_mutex_unlock(&gmtime_mutex);
3340 timeptr = gmtime(&tm);
3342 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3345 *header = strdup("If-Modified-Since: ");
3346 string_append(header, newheader);
3348 if (*header == NULL)
3350 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3351 return JB_ERR_MEMORY;
3354 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3356 hours = rtime / 3600;
3357 minutes = rtime / 60 % 60;
3358 seconds = rtime % 60;
3360 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3361 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3362 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3372 /*********************************************************************
3374 * Function : client_if_none_match
3376 * Description : Remove the If-None-Match header.
3379 * 1 : csp = Current client state (buffers, headers, etc...)
3380 * 2 : header = On input, pointer to header to modify.
3381 * On output, pointer to the modified header, or NULL
3382 * to remove the header. This function frees the
3383 * original string if necessary.
3385 * Returns : JB_ERR_OK on success, or
3386 * JB_ERR_MEMORY on out-of-memory error.
3388 *********************************************************************/
3389 static jb_err client_if_none_match(struct client_state *csp, char **header)
3391 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3393 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3401 /*********************************************************************
3403 * Function : client_x_filter
3405 * Description : Disables filtering if the client set "X-Filter: No".
3406 * Called from `sed'.
3409 * 1 : csp = Current client state (buffers, headers, etc...)
3410 * 2 : header = On input, pointer to header to modify.
3411 * On output, pointer to the modified header, or NULL
3412 * to remove the header. This function frees the
3413 * original string if necessary.
3415 * Returns : JB_ERR_OK on success
3417 *********************************************************************/
3418 jb_err client_x_filter(struct client_state *csp, char **header)
3420 if ( 0 == strcmpic(*header, "X-Filter: No"))
3422 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3424 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3428 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3430 log_error(LOG_LEVEL_HEADER,
3431 "force-text-mode overruled the client's request to fetch without filtering!");
3435 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3436 csp->flags |= CSP_FLAG_NO_FILTERING;
3437 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3439 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3447 /*********************************************************************
3449 * Function : client_range
3451 * Description : Removes Range, Request-Range and If-Range headers if
3452 * content filtering is enabled. If the client's version
3453 * of the document has been altered by Privoxy, the server
3454 * could interpret the range differently than the client
3455 * intended in which case the user could end up with
3456 * corrupted content.
3459 * 1 : csp = Current client state (buffers, headers, etc...)
3460 * 2 : header = On input, pointer to header to modify.
3461 * On output, pointer to the modified header, or NULL
3462 * to remove the header. This function frees the
3463 * original string if necessary.
3465 * Returns : JB_ERR_OK
3467 *********************************************************************/
3468 static jb_err client_range(struct client_state *csp, char **header)
3470 if (content_filters_enabled(csp))
3472 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3473 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3480 /* the following functions add headers directly to the header list */
3482 /*********************************************************************
3484 * Function : client_host_adder
3486 * Description : Adds the Host: header field if it is missing.
3487 * Called from `sed'.
3490 * 1 : csp = Current client state (buffers, headers, etc...)
3492 * Returns : JB_ERR_OK on success, or
3493 * JB_ERR_MEMORY on out-of-memory error.
3495 *********************************************************************/
3496 static jb_err client_host_adder(struct client_state *csp)
3501 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3503 /* Header already set by the client, nothing to do. */
3507 if ( !csp->http->hostport || !*(csp->http->hostport))
3509 /* XXX: When does this happen and why is it OK? */
3510 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3515 * remove 'user:pass@' from 'proto://user:pass@host'
3517 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3523 p = csp->http->hostport;
3526 /* XXX: Just add it, we already made sure that it will be unique */
3527 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3528 err = enlist_unique_header(csp->headers, "Host", p);
3535 /*********************************************************************
3537 * Function : client_accept_encoding_adder
3539 * Description : Add an Accept-Encoding header to the client's request
3540 * that disables compression if the action applies, and
3541 * the header is not already there. Called from `sed'.
3542 * Note: For HTTP/1.0, the absence of the header is enough.
3545 * 1 : csp = Current client state (buffers, headers, etc...)
3547 * Returns : JB_ERR_OK on success, or
3548 * JB_ERR_MEMORY on out-of-memory error.
3550 *********************************************************************/
3551 static jb_err client_accept_encoding_adder(struct client_state *csp)
3553 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3554 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3556 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3564 /*********************************************************************
3566 * Function : client_xtra_adder
3568 * Description : Used in the add_client_headers list. Called from `sed'.
3571 * 1 : csp = Current client state (buffers, headers, etc...)
3573 * Returns : JB_ERR_OK on success, or
3574 * JB_ERR_MEMORY on out-of-memory error.
3576 *********************************************************************/
3577 static jb_err client_xtra_adder(struct client_state *csp)
3579 struct list_entry *lst;
3582 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3583 lst ; lst = lst->next)
3585 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3586 err = enlist(csp->headers, lst->str);
3598 /*********************************************************************
3600 * Function : connection_close_adder
3602 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3603 * support. Adds a "Connection: close" header to csp->headers
3604 * unless the header was already present. Called from `sed'.
3606 * FIXME: This whole function shouldn't be neccessary!
3609 * 1 : csp = Current client state (buffers, headers, etc...)
3611 * Returns : JB_ERR_OK on success, or
3612 * JB_ERR_MEMORY on out-of-memory error.
3614 *********************************************************************/
3615 static jb_err connection_close_adder(struct client_state *csp)
3617 const unsigned int flags = csp->flags;
3620 * Return right away if
3622 * - we're parsing server headers and the server header
3623 * "Connection: close" is already set, or if
3625 * - we're parsing client headers and the client header
3626 * "Connection: close" is already set.
3628 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3629 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3630 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3631 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3636 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3638 return enlist(csp->headers, "Connection: close");
3642 /*********************************************************************
3644 * Function : server_http
3646 * Description : - Save the HTTP Status into csp->http->status
3647 * - Set CT_TABOO to prevent filtering if the answer
3648 * is a partial range (HTTP status 206)
3649 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3653 * 1 : csp = Current client state (buffers, headers, etc...)
3654 * 2 : header = On input, pointer to header to modify.
3655 * On output, pointer to the modified header, or NULL
3656 * to remove the header. This function frees the
3657 * original string if necessary.
3659 * Returns : JB_ERR_OK on success, or
3660 * JB_ERR_MEMORY on out-of-memory error.
3662 *********************************************************************/
3663 static jb_err server_http(struct client_state *csp, char **header)
3665 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3666 if (csp->http->status == 206)
3668 csp->content_type = CT_TABOO;
3671 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3673 /* XXX: Should we do a real validity check here? */
3674 if (strlen(*header) > 8)
3677 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3682 * XXX: Should we block the request or
3683 * enlist a valid status code line here?
3685 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3686 "Downgrading to HTTP/1.0 impossible.");
3694 /*********************************************************************
3696 * Function : server_set_cookie
3698 * Description : Handle the server "cookie" header properly.
3699 * Log cookie to the jar file. Then "crunch",
3700 * accept or rewrite it to a session cookie.
3701 * Called from `sed'.
3703 * TODO: Allow the user to specify a new expiration
3704 * time to cause the cookie to expire even before the
3705 * browser is closed.
3708 * 1 : csp = Current client state (buffers, headers, etc...)
3709 * 2 : header = On input, pointer to header to modify.
3710 * On output, pointer to the modified header, or NULL
3711 * to remove the header. This function frees the
3712 * original string if necessary.
3714 * Returns : JB_ERR_OK on success, or
3715 * JB_ERR_MEMORY on out-of-memory error.
3717 *********************************************************************/
3718 static jb_err server_set_cookie(struct client_state *csp, char **header)
3725 #ifdef FEATURE_COOKIE_JAR
3726 if (csp->config->jar)
3729 * Write timestamp into outbuf.
3731 * Complex because not all OSs have tm_gmtoff or
3732 * the %z field in strftime()
3734 char tempbuf[ BUFFER_SIZE ];
3736 #ifdef HAVE_LOCALTIME_R
3737 tm_now = *localtime_r(&now, &tm_now);
3738 #elif FEATURE_PTHREAD
3739 pthread_mutex_lock(&localtime_mutex);
3740 tm_now = *localtime (&now);
3741 pthread_mutex_unlock(&localtime_mutex);
3743 tm_now = *localtime (&now);
3745 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3747 /* strlen("set-cookie: ") = 12 */
3748 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3750 #endif /* def FEATURE_COOKIE_JAR */
3752 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3754 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3757 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3759 /* Flag whether or not to log a message */
3762 /* A variable to store the tag we're working on */
3765 /* Skip "Set-Cookie:" (11 characters) in header */
3766 cur_tag = *header + 11;
3768 /* skip whitespace between "Set-Cookie:" and value */
3769 while (*cur_tag && ijb_isspace(*cur_tag))
3774 /* Loop through each tag in the cookie */
3778 char *next_tag = strchr(cur_tag, ';');
3779 if (next_tag != NULL)
3781 /* Skip the ';' character itself */
3784 /* skip whitespace ";" and start of tag */
3785 while (*next_tag && ijb_isspace(*next_tag))
3792 /* "Next tag" is the end of the string */
3793 next_tag = cur_tag + strlen(cur_tag);
3797 * Check the expiration date to see
3798 * if the cookie is still valid, if yes,
3799 * rewrite it to a session cookie.
3801 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3803 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3805 /* Did we detect the date properly? */
3806 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3809 * Nope, treat it as if it was still valid.
3811 * XXX: Should we remove the whole cookie instead?
3813 log_error(LOG_LEVEL_ERROR,
3814 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3815 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3821 * Yes. Check if the cookie is still valid.
3823 * If the cookie is already expired it's probably
3824 * a delete cookie and even if it isn't, the browser
3825 * will discard it anyway.
3829 * XXX: timegm() isn't available on some AmigaOS
3830 * versions and our replacement doesn't work.
3832 * Our options are to either:
3834 * - disable session-cookies-only completely if timegm
3837 * - to simply remove all expired tags, like it has
3838 * been done until Privoxy 3.0.6 and to live with
3839 * the consequence that it can cause login/logout
3840 * problems on servers that don't validate their
3841 * input properly, or
3843 * - to replace it with mktime in which
3844 * case there is a slight chance of valid cookies
3845 * passing as already expired.
3847 * This is the way it's currently done and it's not
3848 * as bad as it sounds. If the missing GMT offset is
3849 * enough to change the result of the expiration check
3850 * the cookie will be only valid for a few hours
3851 * anyway, which in many cases will be shorter
3852 * than a browser session.
3854 if (cookie_time - now < 0)
3856 log_error(LOG_LEVEL_HEADER,
3857 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3858 /* Just in case some clown sets more then one expiration date */
3864 * Still valid, delete expiration date by copying
3865 * the rest of the string over it.
3867 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3868 * since the behaviour of strcpy is undefined for overlapping
3871 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3873 /* That changed the header, need to issue a log message */
3877 * Note that the next tag has now been moved to *cur_tag,
3878 * so we do not need to update the cur_tag pointer.
3886 /* Move on to next cookie tag */
3893 assert(NULL != *header);
3894 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3903 #ifdef FEATURE_FORCE_LOAD
3904 /*********************************************************************
3906 * Function : strclean
3908 * Description : In-Situ-Eliminate all occurances of substring in
3912 * 1 : string = string to clean
3913 * 2 : substring = substring to eliminate
3915 * Returns : Number of eliminations
3917 *********************************************************************/
3918 int strclean(const char *string, const char *substring)
3924 len = strlen(substring);
3926 while((pos = strstr(string, substring)) != NULL)
3933 while (*p++ != '\0');
3940 #endif /* def FEATURE_FORCE_LOAD */
3943 /*********************************************************************
3945 * Function : parse_header_time
3947 * Description : Parses time formats used in HTTP header strings
3948 * to get the numerical respresentation.
3951 * 1 : header_time = HTTP header time as string.
3952 * 2 : result = storage for header_time in seconds
3954 * Returns : JB_ERR_OK if the time format was recognized, or
3955 * JB_ERR_PARSE otherwise.
3957 *********************************************************************/
3958 static jb_err parse_header_time(const char *header_time, time_t *result)
3963 * Zero out gmt to prevent time zone offsets.
3965 * While this is only necessary on some platforms
3966 * (mingw32 for example), I don't know how to
3967 * detect these automatically and doing it everywhere
3970 memset(&gmt, 0, sizeof(gmt));
3972 /* Tue, 02 Jun 2037 20:00:00 */
3973 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3974 /* Tue, 02-Jun-2037 20:00:00 */
3975 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3976 /* Tue, 02-Jun-37 20:00:00 */
3977 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3978 /* Tuesday, 02-Jun-2037 20:00:00 */
3979 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3980 /* Tuesday Jun 02 20:00:00 2037 */
3981 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3983 return JB_ERR_PARSE;
3986 *result = timegm(&gmt);
3993 /*********************************************************************
3995 * Function : get_destination_from_headers
3997 * Description : Parse the "Host:" header to get the request's destination.
3998 * Only needed if the client's request was forcefully
3999 * redirected into Privoxy.
4001 * Code mainly copied from client_host() which is currently
4002 * run too late for this purpose.
4005 * 1 : headers = List of headers (one of them hopefully being
4006 * the "Host:" header)
4007 * 2 : http = storage for the result (host, port and hostport).
4009 * Returns : JB_ERR_MEMORY in case of memory problems,
4010 * JB_ERR_PARSE if the host header couldn't be found,
4011 * JB_ERR_OK otherwise.
4013 *********************************************************************/
4014 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4020 host = get_header_value(headers, "Host:");
4024 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4025 return JB_ERR_PARSE;
4028 if (NULL == (p = strdup((host))))
4030 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4031 return JB_ERR_MEMORY;
4034 if (NULL == (q = strdup(p)))
4037 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4038 return JB_ERR_MEMORY;
4041 freez(http->hostport);
4045 q = strchr(http->host, ':');
4048 /* Terminate hostname and evaluate port string */
4050 http->port = atoi(q);
4054 http->port = http->ssl ? 443 : 80;
4057 /* Rebuild request URL */
4059 http->url = strdup(http->ssl ? "https://" : "http://");
4060 string_append(&http->url, http->hostport);
4061 string_append(&http->url, http->path);
4062 if (http->url == NULL)
4064 return JB_ERR_MEMORY;
4067 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4075 /*********************************************************************
4077 * Function : create_forged_referrer
4079 * Description : Helper for client_referrer to forge a referer as
4080 * 'http://[hostname:port/' to fool stupid
4081 * checks for in-site links
4084 * 1 : header = Pointer to header pointer
4085 * 2 : hostport = Host and optionally port as string
4087 * Returns : JB_ERR_OK in case of success, or
4088 * JB_ERR_MEMORY in case of memory problems.
4090 *********************************************************************/
4091 static jb_err create_forged_referrer(char **header, const char *hostport)
4093 assert(NULL == *header);
4095 *header = strdup("Referer: http://");
4096 string_append(header, hostport);
4097 string_append(header, "/");
4099 if (NULL == *header)
4101 return JB_ERR_MEMORY;
4104 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4111 /*********************************************************************
4113 * Function : create_fake_referrer
4115 * Description : Helper for client_referrer to create a fake referrer
4116 * based on a string supplied by the user.
4119 * 1 : header = Pointer to header pointer
4120 * 2 : hosthost = Referrer to fake
4122 * Returns : JB_ERR_OK in case of success, or
4123 * JB_ERR_MEMORY in case of memory problems.
4125 *********************************************************************/
4126 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4128 assert(NULL == *header);
4130 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4132 log_error(LOG_LEVEL_HEADER,
4133 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4135 *header = strdup("Referer: ");
4136 string_append(header, fake_referrer);
4138 if (NULL == *header)
4140 return JB_ERR_MEMORY;
4143 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4150 /*********************************************************************
4152 * Function : handle_conditional_hide_referrer_parameter
4154 * Description : Helper for client_referrer to crunch or forge
4155 * the referrer header if the host has changed.
4158 * 1 : header = Pointer to header pointer
4159 * 2 : host = The target host (may include the port)
4160 * 3 : parameter_conditional_block = Boolean to signal
4161 * if we're in conditional-block mode. If not set,
4162 * we're in conditional-forge mode.
4164 * Returns : JB_ERR_OK in case of success, or
4165 * JB_ERR_MEMORY in case of memory problems.
4167 *********************************************************************/
4168 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4169 const char *host, const int parameter_conditional_block)
4171 char *referer = strdup(*header);
4172 const size_t hostlenght = strlen(host);
4174 if (NULL == referer)
4177 return JB_ERR_MEMORY;
4180 /* referer begins with 'Referer: http[s]://' */
4181 if (hostlenght < (strlen(referer)-17))
4184 * Shorten referer to make sure the referer is blocked
4185 * if www.example.org/www.example.com-shall-see-the-referer/
4186 * links to www.example.com/
4188 referer[hostlenght+17] = '\0';
4190 if (NULL == strstr(referer, host))
4192 /* Host has changed */
4193 if (parameter_conditional_block)
4195 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4202 return create_forged_referrer(header, host);