1 const char parsers_rcs[] = "$Id: parsers.c,v 1.155 2009/05/10 10:12:30 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2009 the
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.155 2009/05/10 10:12:30 fabiankeil
48 * Initial keep-alive support for the client socket.
49 * Temporarily disable the server-side-only keep-alive code.
51 * Revision 1.154 2009/03/13 14:10:07 fabiankeil
52 * Fix some more harmless warnings on amd64.
54 * Revision 1.153 2009/03/07 13:09:17 fabiankeil
55 * Change csp->expected_content and_csp->expected_content_length from
56 * size_t to unsigned long long to reduce the likelihood of integer
57 * overflows that would let us close the connection prematurely.
58 * Bug found while investigating #2669131, reported by cyberpatrol.
60 * Revision 1.152 2009/03/01 18:43:48 fabiankeil
61 * Help clang understand that we aren't dereferencing
64 * Revision 1.151 2009/02/15 14:46:35 fabiankeil
65 * Don't let hide-referrer{conditional-*}} pass
66 * Referer headers without http URLs.
68 * Revision 1.150 2008/12/04 18:12:19 fabiankeil
69 * Fix some cparser warnings.
71 * Revision 1.149 2008/11/21 18:39:53 fabiankeil
72 * In case of CONNECT requests there's no point
73 * in trying to keep the connection alive.
75 * Revision 1.148 2008/11/16 12:43:49 fabiankeil
76 * Turn keep-alive support into a runtime feature
77 * that is disabled by setting keep-alive-timeout
78 * to a negative value.
80 * Revision 1.147 2008/11/04 17:20:31 fabiankeil
81 * HTTP/1.1 responses without Connection
82 * header imply keep-alive. Act accordingly.
84 * Revision 1.146 2008/10/12 16:46:35 fabiankeil
85 * Remove obsolete warning about delayed delivery with chunked
86 * transfer encoding and FEATURE_CONNECTION_KEEP_ALIVE enabled.
88 * Revision 1.145 2008/10/09 18:21:41 fabiankeil
89 * Flush work-in-progress changes to keep outgoing connections
90 * alive where possible. Incomplete and mostly #ifdef'd out.
92 * Revision 1.144 2008/09/21 13:59:33 fabiankeil
93 * Treat unknown change-x-forwarded-for parameters as fatal errors.
95 * Revision 1.143 2008/09/21 13:36:52 fabiankeil
96 * If change-x-forwarded-for{add} is used and the client
97 * sends multiple X-Forwarded-For headers, append the client's
98 * IP address to each one of them. "Traditionally" we would
99 * lose all but the last one.
101 * Revision 1.142 2008/09/20 10:04:33 fabiankeil
102 * Remove hide-forwarded-for-headers action which has
103 * been obsoleted by change-x-forwarded-for{block}.
105 * Revision 1.141 2008/09/19 15:26:28 fabiankeil
106 * Add change-x-forwarded-for{} action to block or add
107 * X-Forwarded-For headers. Mostly based on code removed
110 * Revision 1.140 2008/09/12 17:51:43 fabiankeil
111 * - A few style fixes.
112 * - Remove a pointless cast.
114 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
115 * Prepare for critical sections on Windows by adding a
116 * layer of indirection before the pthread mutex functions.
118 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
119 * Remove FEATURE_COOKIE_JAR.
121 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
122 * Remove questionable micro-optimizations
123 * whose usefulness has never been measured.
125 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
126 * s@Insufficent@Insufficient@
128 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
129 * The whole point of strclean() is to modify the
130 * first parameter, so don't mark it immutable,
131 * even though the compiler lets us get away with it.
133 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
134 * As the wafer actions are gone, we can stop including encode.h.
136 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
137 * Ditch cast from (char **) to (char **).
139 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
140 * Streamline sed()'s prototype and declare
141 * the header parse and add structures static.
143 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
144 * Factor update_server_headers() out of sed(), ditch the
145 * first_run hack and make server_patterns_light static.
147 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
148 * Wrap memmove() calls in string_move()
149 * to document the purpose in one place.
151 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
152 * Normalize linear header white space.
154 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
155 * If a header is split across multiple lines,
156 * merge them to a single line before parsing them.
158 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
159 * Don't provide get_header() with the whole client state
160 * structure when it only needs access to csp->iob.
162 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
163 * Change content_filters_enabled()'s parameter from
164 * csp->action to action so it can be also used in the
165 * CGI code. Don't bother checking if there are filters
166 * loaded, as that's somewhat besides the point.
168 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
169 * Provide get_http_time() with the buffer size so it doesn't
170 * have to blindly assume that the buffer is big enough.
172 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
173 * Don't pass the whole csp structure to flush_socket()
174 * when it only needs a file descriptor and a buffer.
176 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
177 * Remove send-wafer and send-vanilla-wafer actions.
179 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
180 * Remove inspect-jpegs action.
182 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
183 * Let client_range() also handle Request-Range headers
184 * which apparently are still supported by many servers.
186 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
187 * Improve the warning messages that get logged if the action files
188 * "enable" filters but no filters of that type have been loaded.
190 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
191 * In server_content_type():
192 * - Don't require leading white space when detecting image content types.
193 * - Change '... not replaced ...' message to sound less crazy if the text
194 * type actually is 'text/plain'.
195 * - Mark the 'text/plain == binary data' assumption for removal.
196 * - Remove a bunch of trailing white space.
198 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
199 * Minor server_content_disposition() changes:
200 * - Don't regenerate the header name all lower-case.
201 * - Some white space fixes.
202 * - Remove useless log message in case of ENOMEM.
204 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
205 * Garbage-collect the code to add a X-Forwarded-For
206 * header as it seems to be mostly used by accident.
208 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
209 * Fix a crash on mingw32 with some Last Modified times in the future.
211 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
212 * Remove a "can't happen" error block which, over
213 * time, mutated into a "guaranteed to happen" block.
215 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
216 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
217 * - Use shiny new content_filters_enabled() in client_range().
219 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
220 * I forgot about Poland.
222 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
223 * Remove Range and If-Range headers if content filtering is enabled.
225 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
226 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
227 * client_cookie_adder() to make sure send-vanilla-wafer can be
228 * controlled through tags (and thus regression-tested).
230 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
231 * - Remove "scanning headers for" log message again.
232 * - Some more whitespace fixes.
234 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
235 * Refactor client_referrer() and add conditional-forge parameter.
237 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
238 * A bunch of whitespace fixes, pointy hat to me.
240 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
241 * Fix possible memory corruption in server_http, make sure it's not
242 * executed for ordinary server headers and mark some problems for later.
244 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
245 * Let content-type-overwrite{} honour force-text-mode again.
247 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
248 * - Add prototpyes for the header parsers and make them static.
249 * - Comment out client_accept_encoding_adder() which isn't used right now.
251 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
252 * Move the ACTION_FORCE_TEXT_MODE check out of
253 * server_content_type(). Signal other functions
254 * whether or not a content type has been declared.
255 * Part of the fix for BR#1750917.
257 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
258 * Change sed() to return a jb_err in preparation for forward-override{}.
260 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
261 * Adjust "X-Filter: No" to disable dedicated header filters.
263 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
264 * Streamline client_cookie_adder().
266 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
267 * Make sure filters with dynamic jobs actually use them.
269 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
270 * - Introduce dynamic pcrs jobs that can resolve variables.
271 * - Remove unnecessary update_action_bits_for_all_tags() call.
273 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
274 * - Make tagging based on tags set by earlier taggers
275 * of the same kind possible.
276 * - Log whether or not new tags cause action bits updates
277 * (in which case a matching tag-pattern section exists).
278 * - Log if the user tries to set a tag that is already set.
280 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
281 * Introduce tags as alternative way to specify which
282 * actions apply to a request. At the moment tags can be
283 * created based on client and server headers.
285 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
286 * Log a warning if the content is compressed, filtering is
287 * enabled and Privoxy was compiled without zlib support.
290 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
291 * - Fix warnings when compiled with glibc.
292 * - Don't use crumble() for cookie crunching.
293 * - Move cookie time parsing into parse_header_time().
294 * - Let parse_header_time() return a jb_err code
295 * instead of a pointer that can only be used to
296 * check for NULL anyway.
298 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
299 * - Add better protection against malicious gzip headers.
300 * - Stop logging the first hundred bytes of decompressed content.
301 * It looks like it's working and there is always debug 16.
302 * - Log the content size after decompression in decompress_iob()
303 * instead of pcrs_filter_response().
305 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
306 * - Use dedicated header filter actions instead of abusing "filter".
307 * Replace "filter-client-headers" and "filter-client-headers"
308 * with "server-header-filter" and "client-header-filter".
309 * - Remove filter_client_header() and filter_client_header(),
310 * filter_header() now checks the shiny new
311 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
313 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
314 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
315 * - Handle "Cookie:" and "Connection:" headers a bit smarter
316 * (don't crunch them just to recreate them later on).
317 * - Add another non-standard time format for the cookie
318 * expiration date detection.
319 * - Fix a valgrind warning.
321 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
322 * Improve cookie expiration date detection.
324 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
325 * Don't run server_content_length() the first time
326 * sed() parses server headers; only adjust the
327 * Content-Length header if the page was modified.
329 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
330 * Fix log messages regarding the cookie time format
331 * (cookie and request URL were mixed up).
333 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
334 * - Let decompress_iob()
335 * - not corrupt the content if decompression fails
336 * early. (the first byte(s) were lost).
337 * - use pointer arithmetics with defined outcome for
339 * - Use a different kludge to remember a failed decompression.
341 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
342 * Search for Max-Forwards headers case-insensitive,
343 * don't generate the "501 unsupported" message for invalid
344 * Max-Forwards values and don't increase negative ones.
346 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
347 * - Let server_set_cookie() check the expiration date
348 * of cookies and don't touch the ones that are already
349 * expired. Fixes problems with low quality web applications
350 * as described in BR 932612.
352 * - Adjust comment in client_max_forwards to reality;
353 * remove invalid Max-Forwards headers.
355 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
356 * Stop filter_header() from unintentionally removing
357 * empty header lines that were enlisted by the continue
360 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
361 * - Repeat the request URL before logging any headers.
362 * Makes reading the log easier in case of simultaneous requests.
363 * - If there are more than one Content-Type headers in one request,
364 * use the first one and remove the others.
365 * - Remove "newval" variable in server_content_type().
366 * It's only used once.
368 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
369 * Correct a cast, check inflateEnd() exit code
370 * to see if we have to, replace sprintf calls
373 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
374 * Integrate a modified version of Wil Mahan's
375 * zlib patch (PR #895531).
377 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
378 * Skip empty filter files in filter_header()
379 * but don't ignore the ones that come afterwards.
380 * Fixes BR 1619208, this time for real.
382 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
383 * Reverted parts of my last commit
384 * to keep error handling working.
386 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
387 * Fixed gcc43 conversion warnings.
389 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
390 * Bringing back the "useless" localtime() call
391 * I removed in revision 1.67. On some platforms
392 * it's necessary to prevent time zone offsets.
394 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
395 * Rebuild request URL in get_destination_from_headers()
396 * to make sure redirect{pcrs command} works as expected
397 * for intercepted requests.
399 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
400 * Added get_destination_from_headers().
402 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
403 * Make pthread mutex locking more generic. Instead of
404 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
405 * and use mutex locking unless there is an _r function
406 * available. Better safe than sorry.
408 * Fixes "./configure --disable-pthread" and should result
409 * in less threading-related problems on pthread-using platforms,
410 * but it still doesn't fix BR#1122404.
412 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
413 * The special header "X-Filter: No" now disables
414 * header filtering as well.
416 * Revision 1.73 2006/09/23 13:26:38 roro
417 * Replace TABs by spaces in source code.
419 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
420 * Don't print a log message every time filter_headers is
421 * entered or left. It only creates noise without any real
424 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
425 * Fix +hide-if-modified-since{-n}.
427 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
428 * Have hide-if-modified-since interpret the random
429 * range value as minutes instead of hours. Allows
430 * more fine-grained configuration.
432 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
433 * Always have parse_header_time return a pointer
434 * that actual makes sense, even though we currently
435 * only need it to detect problems.
437 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
438 * Added config option enable-remote-http-toggle
439 * to specify if Privoxy should recognize special
440 * headers (currently only X-Filter) to change its
441 * behaviour. Disabled by default.
443 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
444 * After filtering de-chunked instances, remove
445 * "Transfer-Encoding" header entirely instead of changing
446 * it to "Transfer-Encoding: identity", which is invalid.
447 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
449 * Don't use localtime in parse_header_time. An empty time struct
450 * is good enough, it gets overwritten by strptime anyway.
452 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
453 * Use gmtime_r if available, fallback to gmtime with mutex
454 * protection for MacOSX and use vanilla gmtime for the rest.
456 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
457 * Changed client_referrer to use the right type (size_t) for
458 * hostlenght and to shorten the temporary referrer string with
459 * '\0' instead of adding a useless line break.
461 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
462 * - Back to timegm() using GnuPG's replacement if necessary.
463 * Using mktime() and localtime() could add a on hour offset if
464 * the randomize factor was big enough to lead to a summer/wintertime
467 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
469 * - Moved randomization code into pick_from_range().
471 * - Changed parse_header_time definition.
472 * time_t isn't guaranteed to be signed and
473 * if it isn't, -1 isn't available as error code.
474 * Changed some variable types in client_if_modified_since()
475 * because of the same reason.
477 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
478 * OS/2 compilation compatibility fixups
480 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
481 * Changed include from strptime.c to strptime.h
483 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
484 * Split filter-headers{} into filter-client-headers{}
485 * and filter-server-headers{}.
486 * Added parse_header_time() to share some code.
487 * Replaced timegm() with mktime().
489 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
490 * Windows service integration
492 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
493 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
495 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
496 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
497 * with what was really the latest development (the v_3_0_branch branch)
499 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
500 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
502 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
503 * Add the ability to check jpeg images for invalid
504 * lengths of comment blocks. Defensive strategy
505 * against the exploit:
506 * Microsoft Security Bulletin MS04-028
507 * Buffer Overrun in JPEG Processing (GDI+) Could
508 * Allow Code Execution (833987)
509 * Enabled with +inspect-jpegs in actions files.
511 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
512 * Excluded text/plain objects from filtering. This fixes a
513 * couple of client-crashing, download corruption and
514 * Privoxy performance issues, whose root cause lies in
515 * web servers labelling content of unknown type as text/plain.
517 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
518 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
520 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
521 * Completing the previous change
523 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
524 * Added temporary workaround for bug in PHP < 4.2.3
526 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
527 * 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.
529 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
530 * Fix typo: supressed -> suppressed
532 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
533 * Improved cookie logging
535 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
536 * Added basic support for OPTIONS and TRACE HTTP methods:
537 * - New parser function client_max_forwards which decrements
538 * the Max-Forwards HTTP header field of OPTIONS and TRACE
539 * requests by one before forwarding
540 * - New parser function client_host which extracts the host
541 * and port information from the HTTP header field if the
542 * request URI was not absolute
543 * - Don't crumble and re-add the Host: header, but only generate
544 * and append if missing
546 * Revision 1.56 2002/05/12 15:34:22 jongfoster
547 * Fixing typo in a comment
549 * Revision 1.55 2002/05/08 16:01:07 oes
550 * Optimized add_to_iob:
551 * - Use realloc instead of malloc(), memcpy(), free()
552 * - Expand to powers of two if possible, to get
553 * O(log n) reallocs instead of O(n).
554 * - Moved check for buffer limit here from chat
555 * - Report failure via returncode
557 * Revision 1.54 2002/04/02 15:03:16 oes
558 * Tiny code cosmetics
560 * Revision 1.53 2002/03/26 22:29:55 swa
561 * we have a new homepage!
563 * Revision 1.52 2002/03/24 13:25:43 swa
564 * name change related issues
566 * Revision 1.51 2002/03/13 00:27:05 jongfoster
569 * Revision 1.50 2002/03/12 01:45:35 oes
570 * More verbose logging
572 * Revision 1.49 2002/03/09 20:03:52 jongfoster
573 * - Making various functions return int rather than size_t.
574 * (Undoing a recent change). Since size_t is unsigned on
575 * Windows, functions like read_socket that return -1 on
576 * error cannot return a size_t.
578 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
579 * crashes, and also frequently caused JB to jump to 100%
580 * CPU and stay there. (Because it thought it had just
581 * read ((unsigned)-1) == 4Gb of data...)
583 * - The signature of write_socket has changed, it now simply
584 * returns success=0/failure=nonzero.
586 * - Trying to get rid of a few warnings --with-debug on
587 * Windows, I've introduced a new type "jb_socket". This is
588 * used for the socket file descriptors. On Windows, this
589 * is SOCKET (a typedef for unsigned). Everywhere else, it's
590 * an int. The error value can't be -1 any more, so it's
591 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
592 * Windows it maps to the #define INVALID_SOCKET.)
594 * - The signature of bind_port has changed.
596 * Revision 1.48 2002/03/07 03:46:53 oes
597 * Fixed compiler warnings etc
599 * Revision 1.47 2002/02/20 23:15:13 jongfoster
600 * Parsing functions now handle out-of-memory gracefully by returning
603 * Revision 1.46 2002/01/17 21:03:47 jongfoster
604 * Moving all our URL and URL pattern parsing code to urlmatch.c.
606 * Revision 1.45 2002/01/09 14:33:03 oes
607 * Added support for localtime_r.
609 * Revision 1.44 2001/12/14 01:22:54 steudten
610 * Remove 'user:pass@' from 'proto://user:pass@host' for the
611 * new added header 'Host: ..'. (See Req ID 491818)
613 * Revision 1.43 2001/11/23 00:26:38 jongfoster
614 * Fixing two really stupid errors in my previous commit
616 * Revision 1.42 2001/11/22 21:59:30 jongfoster
617 * Adding code to handle +no-cookies-keep
619 * Revision 1.41 2001/11/05 23:43:05 steudten
620 * Add time+date to log files.
622 * Revision 1.40 2001/10/26 20:13:09 jongfoster
623 * ctype.h is needed in Windows, too.
625 * Revision 1.39 2001/10/26 17:40:04 oes
626 * Introduced get_header_value()
627 * Removed http->user_agent, csp->referrer and csp->accept_types
628 * Removed client_accept()
630 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
631 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
632 * threads to call select() simultaneously. So, it's time to do a real, live,
633 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
634 * (native). Both versions will work, but using __OS2__ offers multi-threading.
636 * Revision 1.37 2001/10/23 21:36:02 jongfoster
637 * Documenting sed()'s error behaviou (doc change only)
639 * Revision 1.36 2001/10/13 12:51:51 joergs
640 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
641 * force-load), instead crumble Host: and add it (again) in client_host_adder
642 * (in case we get a HTTP/1.0 request without Host: header and forward it to
643 * a HTTP/1.1 server/proxy).
645 * Revision 1.35 2001/10/09 22:39:21 jongfoster
646 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
649 * Revision 1.34 2001/10/07 18:50:55 oes
650 * Added server_content_encoding, renamed server_transfer_encoding
652 * Revision 1.33 2001/10/07 18:04:49 oes
653 * Changed server_http11 to server_http and its pattern to "HTTP".
654 * Additional functionality: it now saves the HTTP status into
655 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
657 * Revision 1.32 2001/10/07 15:43:28 oes
658 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
659 * client_te and client_accept_encoding_adder, triggered by the new
660 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
661 * changed to allow only identity and chunked, and the TE header is
662 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
664 * parse_http_request no longer does anything than parsing. The rewriting
665 * of http->cmd and version mangling are gone. It now also recognizes
666 * the put and delete methods and saves the url in http->url. Removed
669 * renamed content_type and content_length to have the server_ prefix
671 * server_content_type now only works if csp->content_type != CT_TABOO
673 * added server_transfer_encoding, which
674 * - Sets CT_TABOO to prohibit filtering if encoding compresses
675 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
676 * - Change from "chunked" to "identity" if body was chunked
677 * but has been de-chunked for filtering.
679 * added server_content_md5 which crunches any Content-MD5 headers
680 * if the body was modified.
682 * made server_http11 conditional on +downgrade action
684 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
686 * Revision 1.31 2001/10/05 14:25:02 oes
687 * Crumble Keep-Alive from Server
689 * Revision 1.30 2001/09/29 12:56:03 joergs
690 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
692 * Revision 1.29 2001/09/24 21:09:24 jongfoster
693 * Fixing 2 memory leaks that Guy spotted, where the paramater to
694 * enlist() was not being free()d.
696 * Revision 1.28 2001/09/22 16:32:28 jongfoster
697 * Removing unused #includes.
699 * Revision 1.27 2001/09/20 15:45:25 steudten
701 * add casting from size_t to int for printf()
702 * remove local variable shadow s2
704 * Revision 1.26 2001/09/16 17:05:14 jongfoster
705 * Removing unused #include showarg.h
707 * Revision 1.25 2001/09/16 13:21:27 jongfoster
708 * Changes to use new list functions.
710 * Revision 1.24 2001/09/13 23:05:50 jongfoster
711 * Changing the string paramater to the header parsers a "const".
713 * Revision 1.23 2001/09/12 18:08:19 steudten
715 * In parse_http_request() header rewriting miss the host value, so
716 * from http://www.mydomain.com the result was just " / " not
717 * http://www.mydomain.com/ in case we forward.
719 * Revision 1.22 2001/09/10 10:58:53 oes
720 * Silenced compiler warnings
722 * Revision 1.21 2001/07/31 14:46:00 oes
723 * - Persistant connections now suppressed
724 * - sed() no longer appends empty header to csp->headers
726 * Revision 1.20 2001/07/30 22:08:36 jongfoster
727 * Tidying up #defines:
728 * - All feature #defines are now of the form FEATURE_xxx
729 * - Permanently turned off WIN_GUI_EDIT
730 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
732 * Revision 1.19 2001/07/25 17:21:54 oes
733 * client_uagent now saves copy of User-Agent: header value
735 * Revision 1.18 2001/07/13 14:02:46 oes
736 * - Included fix to repair broken HTTP requests that
737 * don't contain a path, not even '/'.
738 * - Removed all #ifdef PCRS
739 * - content_type now always inspected and classified as
740 * text, gif or other.
741 * - formatting / comments
743 * Revision 1.17 2001/06/29 21:45:41 oes
744 * Indentation, CRLF->LF, Tab-> Space
746 * Revision 1.16 2001/06/29 13:32:42 oes
748 * - Adapted free_http_request
749 * - Removed logentry from cancelled commit
751 * Revision 1.15 2001/06/03 19:12:38 oes
752 * deleted const struct interceptors
754 * Revision 1.14 2001/06/01 18:49:17 jongfoster
755 * Replaced "list_share" with "list" - the tiny memory gain was not
756 * worth the extra complexity.
758 * Revision 1.13 2001/05/31 21:30:33 jongfoster
759 * Removed list code - it's now in list.[ch]
760 * Renamed "permission" to "action", and changed many features
761 * to use the actions file rather than the global config.
763 * Revision 1.12 2001/05/31 17:33:13 oes
767 * Revision 1.11 2001/05/29 20:11:19 joergs
768 * '/ * inside comment' warning removed.
770 * Revision 1.10 2001/05/29 09:50:24 jongfoster
771 * Unified blocklist/imagelist/permissionslist.
772 * File format is still under discussion, but the internal changes
775 * Also modified interceptor behaviour:
776 * - We now intercept all URLs beginning with one of the following
777 * prefixes (and *only* these prefixes):
779 * * http://ijbswa.sf.net/config/
780 * * http://ijbswa.sourceforge.net/config/
781 * - New interceptors "home page" - go to http://i.j.b/ to see it.
782 * - Internal changes so that intercepted and fast redirect pages
783 * are not replaced with an image.
784 * - Interceptors now have the option to send a binary page direct
785 * to the client. (i.e. ijb-send-banner uses this)
786 * - Implemented show-url-info interceptor. (Which is why I needed
787 * the above interceptors changes - a typical URL is
788 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
789 * The previous mechanism would not have intercepted that, and
790 * if it had been intercepted then it then it would have replaced
793 * Revision 1.9 2001/05/28 17:26:33 jongfoster
794 * Fixing segfault if last header was crunched.
795 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
796 * can use the cross-platform sprintf() instead.)
798 * Revision 1.8 2001/05/27 22:17:04 oes
800 * - re_process_buffer no longer writes the modified buffer
801 * to the client, which was very ugly. It now returns the
802 * buffer, which it is then written by chat.
804 * - content_length now adjusts the Content-Length: header
805 * for modified documents rather than crunch()ing it.
806 * (Length info in csp->content_length, which is 0 for
807 * unmodified documents)
809 * - For this to work, sed() is called twice when filtering.
811 * Revision 1.7 2001/05/27 13:19:06 oes
812 * Patched Joergs solution for the content-length in.
814 * Revision 1.6 2001/05/26 13:39:32 jongfoster
815 * Only crunches Content-Length header if applying RE filtering.
816 * Without this fix, Microsoft Windows Update wouldn't work.
818 * Revision 1.5 2001/05/26 00:28:36 jongfoster
819 * Automatic reloading of config file.
820 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
821 * Most of the global variables have been moved to a new
822 * struct configuration_spec, accessed through csp->config->globalname
823 * Most of the globals remaining are used by the Win32 GUI.
825 * Revision 1.4 2001/05/22 18:46:04 oes
827 * - Enabled filtering banners by size rather than URL
828 * by adding patterns that replace all standard banner
829 * sizes with the "Junkbuster" gif to the re_filterfile
831 * - Enabled filtering WebBugs by providing a pattern
832 * which kills all 1x1 images
834 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
835 * which is selected by the (nonstandard and therefore
836 * capital) letter 'U' in the option string.
837 * It causes the quantifiers to be ungreedy by default.
838 * Appending a ? turns back to greedy (!).
840 * - Added a new interceptor ijb-send-banner, which
841 * sends back the "Junkbuster" gif. Without imagelist or
842 * MSIE detection support, or if tinygif = 1, or the
843 * URL isn't recognized as an imageurl, a lame HTML
844 * explanation is sent instead.
846 * - Added new feature, which permits blocking remote
847 * script redirects and firing back a local redirect
849 * The feature is conditionally compiled, i.e. it
850 * can be disabled with --disable-fast-redirects,
851 * plus it must be activated by a "fast-redirects"
852 * line in the config file, has its own log level
853 * and of course wants to be displayed by show-proxy-args
854 * Note: Boy, all the #ifdefs in 1001 locations and
855 * all the fumbling with configure.in and acconfig.h
856 * were *way* more work than the feature itself :-(
858 * - Because a generic redirect template was needed for
859 * this, tinygif = 3 now uses the same.
861 * - Moved GIFs, and other static HTTP response templates
866 * - Removed some >400 CRs again (Jon, you really worked
869 * Revision 1.3 2001/05/20 01:21:20 jongfoster
870 * Version 2.9.4 checkin.
871 * - Merged popupfile and cookiefile, and added control over PCRS
872 * filtering, in new "permissionsfile".
873 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
874 * file error you now get a message box (in the Win32 GUI) rather
875 * than the program exiting with no explanation.
876 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
878 * - Removed tabs from "config"
879 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
880 * - Bumped up version number.
882 * Revision 1.2 2001/05/17 23:02:36 oes
883 * - Made referrer option accept 'L' as a substitute for '§'
885 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
886 * Initial import of version 2.9.3 source tree
889 *********************************************************************/
896 #include <sys/types.h>
906 * Convince GNU's libc to provide a strptime prototype.
909 #endif /*__GLIBC__ */
916 #if !defined(_WIN32) && !defined(__OS2__)
922 #ifdef FEATURE_PTHREAD
924 /* jcc.h is for mutex semapores only */
925 #endif /* def FEATURE_PTHREAD */
930 #include "jbsockets.h"
931 #include "miscutil.h"
936 #ifndef HAVE_STRPTIME
937 #include "strptime.h"
940 const char parsers_h_rcs[] = PARSERS_H_VERSION;
942 /* Fix a problem with Solaris. There should be no effect on other
944 * Solaris's isspace() is a macro which uses its argument directly
945 * as an array index. Therefore we need to make sure that high-bit
946 * characters generate +ve values, and ideally we also want to make
947 * the argument match the declared parameter type of "int".
949 * Why did they write a character function that can't take a simple
950 * "char" argument? Doh!
952 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
953 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
955 static char *get_header_line(struct iob *iob);
956 static jb_err scan_headers(struct client_state *csp);
957 static jb_err header_tagger(struct client_state *csp, char *header);
958 static jb_err parse_header_time(const char *header_time, time_t *result);
960 static jb_err crumble (struct client_state *csp, char **header);
961 static jb_err filter_header (struct client_state *csp, char **header);
962 static jb_err client_connection (struct client_state *csp, char **header);
963 static jb_err client_referrer (struct client_state *csp, char **header);
964 static jb_err client_uagent (struct client_state *csp, char **header);
965 static jb_err client_ua (struct client_state *csp, char **header);
966 static jb_err client_from (struct client_state *csp, char **header);
967 static jb_err client_send_cookie (struct client_state *csp, char **header);
968 static jb_err client_x_forwarded (struct client_state *csp, char **header);
969 static jb_err client_accept_encoding (struct client_state *csp, char **header);
970 static jb_err client_te (struct client_state *csp, char **header);
971 static jb_err client_max_forwards (struct client_state *csp, char **header);
972 static jb_err client_host (struct client_state *csp, char **header);
973 static jb_err client_if_modified_since (struct client_state *csp, char **header);
974 static jb_err client_accept_language (struct client_state *csp, char **header);
975 static jb_err client_if_none_match (struct client_state *csp, char **header);
976 static jb_err crunch_client_header (struct client_state *csp, char **header);
977 static jb_err client_x_filter (struct client_state *csp, char **header);
978 static jb_err client_range (struct client_state *csp, char **header);
979 static jb_err server_set_cookie (struct client_state *csp, char **header);
980 static jb_err server_connection (struct client_state *csp, char **header);
981 static jb_err server_content_type (struct client_state *csp, char **header);
982 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
983 static jb_err server_content_md5 (struct client_state *csp, char **header);
984 static jb_err server_content_encoding (struct client_state *csp, char **header);
985 static jb_err server_transfer_coding (struct client_state *csp, char **header);
986 static jb_err server_http (struct client_state *csp, char **header);
987 static jb_err crunch_server_header (struct client_state *csp, char **header);
988 static jb_err server_last_modified (struct client_state *csp, char **header);
989 static jb_err server_content_disposition(struct client_state *csp, char **header);
991 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
992 static jb_err server_save_content_length(struct client_state *csp, char **header);
993 static jb_err server_keep_alive(struct client_state *csp, char **header);
994 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
996 static jb_err client_host_adder (struct client_state *csp);
997 static jb_err client_xtra_adder (struct client_state *csp);
998 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
999 static jb_err client_connection_header_adder(struct client_state *csp);
1000 static jb_err server_connection_adder(struct client_state *csp);
1001 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1002 static jb_err server_proxy_connection_adder(struct client_state *csp);
1003 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1005 static jb_err create_forged_referrer(char **header, const char *hostport);
1006 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
1007 static jb_err handle_conditional_hide_referrer_parameter(char **header,
1008 const char *host, const int parameter_conditional_block);
1009 static const char *get_appropiate_connection_header(const struct client_state *csp);
1012 * List of functions to run on a list of headers.
1016 /** The header prefix to match */
1019 /** The length of the prefix to match */
1022 /** The function to apply to this line */
1023 const parser_func_ptr parser;
1026 static const struct parsers client_patterns[] = {
1027 { "referer:", 8, client_referrer },
1028 { "user-agent:", 11, client_uagent },
1029 { "ua-", 3, client_ua },
1030 { "from:", 5, client_from },
1031 { "cookie:", 7, client_send_cookie },
1032 { "x-forwarded-for:", 16, client_x_forwarded },
1033 { "Accept-Encoding:", 16, client_accept_encoding },
1034 { "TE:", 3, client_te },
1035 { "Host:", 5, client_host },
1036 { "if-modified-since:", 18, client_if_modified_since },
1037 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
1038 { "Keep-Alive:", 11, crumble },
1040 { "connection:", 11, client_connection },
1041 { "proxy-connection:", 17, crumble },
1042 { "max-forwards:", 13, client_max_forwards },
1043 { "Accept-Language:", 16, client_accept_language },
1044 { "if-none-match:", 14, client_if_none_match },
1045 { "Range:", 6, client_range },
1046 { "Request-Range:", 14, client_range },
1047 { "If-Range:", 9, client_range },
1048 { "X-Filter:", 9, client_x_filter },
1049 { "*", 0, crunch_client_header },
1050 { "*", 0, filter_header },
1054 static const struct parsers server_patterns[] = {
1055 { "HTTP/", 5, server_http },
1056 { "set-cookie:", 11, server_set_cookie },
1057 { "connection:", 11, server_connection },
1058 { "Content-Type:", 13, server_content_type },
1059 { "Content-MD5:", 12, server_content_md5 },
1060 { "Content-Encoding:", 17, server_content_encoding },
1061 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1062 { "Content-Length:", 15, server_save_content_length },
1063 { "Keep-Alive:", 11, server_keep_alive },
1065 { "Keep-Alive:", 11, crumble },
1066 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1067 { "Transfer-Encoding:", 18, server_transfer_coding },
1068 { "content-disposition:", 20, server_content_disposition },
1069 { "Last-Modified:", 14, server_last_modified },
1070 { "*", 0, crunch_server_header },
1071 { "*", 0, filter_header },
1075 static const add_header_func_ptr add_client_headers[] = {
1077 client_x_forwarded_for_adder,
1079 /* Temporarily disabled: client_accept_encoding_adder, */
1080 client_connection_header_adder,
1084 static const add_header_func_ptr add_server_headers[] = {
1085 server_connection_adder,
1086 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1087 server_proxy_connection_adder,
1088 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1092 /*********************************************************************
1094 * Function : flush_socket
1096 * Description : Write any pending "buffered" content.
1099 * 1 : fd = file descriptor of the socket to read
1100 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1102 * Returns : On success, the number of bytes written are returned (zero
1103 * indicates nothing was written). On error, -1 is returned,
1104 * and errno is set appropriately. If count is zero and the
1105 * file descriptor refers to a regular file, 0 will be
1106 * returned without causing any other effect. For a special
1107 * file, the results are not portable.
1109 *********************************************************************/
1110 long flush_socket(jb_socket fd, struct iob *iob)
1112 long len = iob->eod - iob->cur;
1119 if (write_socket(fd, iob->cur, (size_t)len))
1123 iob->eod = iob->cur = iob->buf;
1129 /*********************************************************************
1131 * Function : add_to_iob
1133 * Description : Add content to the buffered page, expanding the
1134 * buffer if necessary.
1137 * 1 : csp = Current client state (buffers, headers, etc...)
1138 * 2 : buf = holds the content to be added to the page
1139 * 3 : n = number of bytes to be added
1141 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1142 * or buffer limit reached.
1144 *********************************************************************/
1145 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
1147 struct iob *iob = csp->iob;
1148 size_t used, offset, need, want;
1151 if (n <= 0) return JB_ERR_OK;
1153 used = (size_t)(iob->eod - iob->buf);
1154 offset = (size_t)(iob->cur - iob->buf);
1155 need = used + (size_t)n + 1;
1158 * If the buffer can't hold the new data, extend it first.
1159 * Use the next power of two if possible, else use the actual need.
1161 if (need > csp->config->buffer_limit)
1163 log_error(LOG_LEVEL_INFO,
1164 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
1165 need, csp->config->buffer_limit);
1166 return JB_ERR_MEMORY;
1169 if (need > iob->size)
1171 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1173 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1177 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1183 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1184 return JB_ERR_MEMORY;
1187 /* Update the iob pointers */
1188 iob->cur = p + offset;
1189 iob->eod = p + used;
1193 /* copy the new data into the iob buffer */
1194 memcpy(iob->eod, buf, (size_t)n);
1196 /* point to the end of the data */
1199 /* null terminate == cheap insurance */
1208 /*********************************************************************
1210 * Function : decompress_iob
1212 * Description : Decompress buffered page, expanding the
1213 * buffer as necessary. csp->iob->cur
1214 * should point to the the beginning of the
1215 * compressed data block.
1218 * 1 : csp = Current client state (buffers, headers, etc...)
1220 * Returns : JB_ERR_OK on success,
1221 * JB_ERR_MEMORY if out-of-memory limit reached, and
1222 * JB_ERR_COMPRESS if error decompressing buffer.
1224 *********************************************************************/
1225 jb_err decompress_iob(struct client_state *csp)
1227 char *buf; /* new, uncompressed buffer */
1228 char *cur; /* Current iob position (to keep the original
1229 * iob->cur unmodified if we return early) */
1230 size_t bufsize; /* allocated size of the new buffer */
1231 size_t old_size; /* Content size before decompression */
1232 size_t skip_size; /* Number of bytes at the beginning of the iob
1233 that we should NOT decompress. */
1234 int status; /* return status of the inflate() call */
1235 z_stream zstr; /* used by calls to zlib */
1237 assert(csp->iob->cur - csp->iob->buf > 0);
1238 assert(csp->iob->eod - csp->iob->cur > 0);
1240 bufsize = csp->iob->size;
1241 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1242 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1244 cur = csp->iob->cur;
1246 if (bufsize < (size_t)10)
1249 * This is to protect the parsing of gzipped data,
1250 * but it should(?) be valid for deflated data also.
1252 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1253 return JB_ERR_COMPRESS;
1256 if (csp->content_type & CT_GZIP)
1259 * Our task is slightly complicated by the facts that data
1260 * compressed by gzip does not include a zlib header, and
1261 * that there is no easily accessible interface in zlib to
1262 * handle a gzip header. We strip off the gzip header by
1263 * hand, and later inform zlib not to expect a header.
1267 * Strip off the gzip header. Please see RFC 1952 for more
1268 * explanation of the appropriate fields.
1270 if ((*cur++ != (char)0x1f)
1271 || (*cur++ != (char)0x8b)
1272 || (*cur++ != Z_DEFLATED))
1274 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1275 return JB_ERR_COMPRESS;
1281 * XXX: These magic numbers should be replaced
1282 * with macros to give a better idea what they do.
1286 /* The gzip header has reserved bits set; bail out. */
1287 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1288 return JB_ERR_COMPRESS;
1292 /* Skip extra fields if necessary. */
1296 * Skip a given number of bytes, specified
1297 * as a 16-bit little-endian value.
1300 * XXX: This code used to be:
1302 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1304 * which I had to change into:
1306 * cur += *cur++ + (*cur++ << 8);
1308 * at which point gcc43 finally noticed that the value
1309 * of cur is undefined (it depends on which of the
1310 * summands is evaluated first).
1312 * I haven't come across a site where this
1313 * code is actually executed yet, but I hope
1317 skip_bytes = *cur++;
1318 skip_bytes = *cur++ << 8;
1320 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1323 * The number of bytes to skip should be positive
1324 * and we'd like to stay in the buffer.
1326 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1328 log_error(LOG_LEVEL_ERROR,
1329 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1331 return JB_ERR_COMPRESS;
1333 log_error(LOG_LEVEL_INFO,
1334 "Skipping %d bytes for gzip compression. Does this sound right?",
1339 /* Skip the filename if necessary. */
1342 /* A null-terminated string is supposed to follow. */
1343 while (*cur++ && (cur < csp->iob->eod));
1347 /* Skip the comment if necessary. */
1350 /* A null-terminated string is supposed to follow. */
1351 while (*cur++ && (cur < csp->iob->eod));
1354 /* Skip the CRC if necessary. */
1360 if (cur >= csp->iob->eod)
1363 * If the current position pointer reached or passed
1364 * the buffer end, we were obviously tricked to skip
1367 log_error(LOG_LEVEL_ERROR,
1368 "Malformed gzip header detected. Aborting decompression.");
1369 return JB_ERR_COMPRESS;
1373 else if (csp->content_type & CT_DEFLATE)
1376 * XXX: The debug level should be lowered
1377 * before the next stable release.
1379 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1381 * In theory (that is, according to RFC 1950), deflate-compressed
1382 * data should begin with a two-byte zlib header and have an
1383 * adler32 checksum at the end. It seems that in practice only
1384 * the raw compressed data is sent. Note that this means that
1385 * we are not RFC 1950-compliant here, but the advantage is that
1386 * this actually works. :)
1388 * We add a dummy null byte to tell zlib where the data ends,
1389 * and later inform it not to expect a header.
1391 * Fortunately, add_to_iob() has thoughtfully null-terminated
1392 * the buffer; we can just increment the end pointer to include
1399 log_error(LOG_LEVEL_ERROR,
1400 "Unable to determine compression format for decompression");
1401 return JB_ERR_COMPRESS;
1404 /* Set up the fields required by zlib. */
1405 zstr.next_in = (Bytef *)cur;
1406 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1407 zstr.zalloc = Z_NULL;
1408 zstr.zfree = Z_NULL;
1409 zstr.opaque = Z_NULL;
1412 * Passing -MAX_WBITS to inflateInit2 tells the library
1413 * that there is no zlib header.
1415 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1417 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1418 return JB_ERR_COMPRESS;
1422 * Next, we allocate new storage for the inflated data.
1423 * We don't modify the existing iob yet, so in case there
1424 * is error in decompression we can recover gracefully.
1426 buf = zalloc(bufsize);
1429 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1430 return JB_ERR_MEMORY;
1433 assert(bufsize >= skip_size);
1434 memcpy(buf, csp->iob->buf, skip_size);
1435 zstr.avail_out = bufsize - skip_size;
1436 zstr.next_out = (Bytef *)buf + skip_size;
1438 /* Try to decompress the whole stream in one shot. */
1439 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1441 /* We need to allocate more memory for the output buffer. */
1443 char *tmpbuf; /* used for realloc'ing the buffer */
1444 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1447 * If zlib wants more data then there's a problem, because
1448 * the complete compressed file should have been buffered.
1450 if (0 == zstr.avail_in)
1452 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1453 return JB_ERR_COMPRESS;
1457 * If we tried the limit and still didn't have enough
1458 * memory, just give up.
1460 if (bufsize == csp->config->buffer_limit)
1462 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1463 return JB_ERR_MEMORY;
1466 /* Try doubling the buffer size each time. */
1469 /* Don't exceed the buffer limit. */
1470 if (bufsize > csp->config->buffer_limit)
1472 bufsize = csp->config->buffer_limit;
1475 /* Try to allocate the new buffer. */
1476 tmpbuf = realloc(buf, bufsize);
1479 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1481 return JB_ERR_MEMORY;
1485 char *oldnext_out = (char *)zstr.next_out;
1488 * Update the fields for inflate() to use the new
1489 * buffer, which may be in a location different from
1492 zstr.avail_out += bufsize - oldbufsize;
1493 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1496 * Compare with an uglier method of calculating these values
1497 * that doesn't require the extra oldbufsize variable.
1499 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1500 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1501 assert(zstr.avail_out > 0U);
1507 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1509 log_error(LOG_LEVEL_ERROR,
1510 "Inconsistent stream state after decompression: %s", zstr.msg);
1512 * XXX: Intentionally no return.
1514 * According to zlib.h, Z_STREAM_ERROR is returned
1515 * "if the stream state was inconsistent".
1517 * I assume in this case inflate()'s status
1518 * would also be something different than Z_STREAM_END
1519 * so this check should be redundant, but lets see.
1523 if (status != Z_STREAM_END)
1525 /* We failed to decompress the stream. */
1526 log_error(LOG_LEVEL_ERROR,
1527 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1528 return JB_ERR_COMPRESS;
1532 * Finally, we can actually update the iob, since the
1533 * decompression was successful. First, free the old
1536 freez(csp->iob->buf);
1538 /* Now, update the iob to use the new buffer. */
1539 csp->iob->buf = buf;
1540 csp->iob->cur = csp->iob->buf + skip_size;
1541 csp->iob->eod = (char *)zstr.next_out;
1542 csp->iob->size = bufsize;
1545 * Make sure the new uncompressed iob obeys some minimal
1546 * consistency conditions.
1548 if ((csp->iob->buf < csp->iob->cur)
1549 && (csp->iob->cur <= csp->iob->eod)
1550 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1552 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1553 if (new_size > (size_t)0)
1555 log_error(LOG_LEVEL_RE_FILTER,
1556 "Decompression successful. Old size: %d, new size: %d.",
1557 old_size, new_size);
1561 /* zlib thinks this is OK, so lets do the same. */
1562 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1567 /* It seems that zlib did something weird. */
1568 log_error(LOG_LEVEL_ERROR,
1569 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1570 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1571 csp->iob->eod, csp->iob->buf + csp->iob->size);
1572 return JB_ERR_COMPRESS;
1578 #endif /* defined(FEATURE_ZLIB) */
1581 /*********************************************************************
1583 * Function : string_move
1585 * Description : memmove wrapper to move the last part of a string
1586 * towards the beginning, overwriting the part in
1587 * the middle. strlcpy() can't be used here as the
1591 * 1 : dst = Destination to overwrite
1592 * 2 : src = Source to move.
1596 *********************************************************************/
1597 static void string_move(char *dst, char *src)
1601 /* +1 to copy the terminating nul as well. */
1602 memmove(dst, src, strlen(src)+1);
1606 /*********************************************************************
1608 * Function : normalize_lws
1610 * Description : Reduces unquoted linear white space in headers
1611 * to a single space in accordance with RFC 2616 2.2.
1612 * This simplifies parsing and filtering later on.
1614 * XXX: Remove log messages before
1615 * the next stable release?
1618 * 1 : header = A header with linear white space to reduce.
1622 *********************************************************************/
1623 static void normalize_lws(char *header)
1629 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1633 while (ijb_isspace(*q))
1637 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1638 string_move(p+1, q);
1643 log_error(LOG_LEVEL_HEADER,
1644 "Converting tab to space in '%s'", header);
1649 char *end_of_token = strstr(p+1, "\"");
1651 if (NULL != end_of_token)
1653 /* Don't mess with quoted text. */
1658 log_error(LOG_LEVEL_HEADER,
1659 "Ignoring single quote in '%s'", header);
1665 p = strchr(header, ':');
1666 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1669 * There's still space before the colon.
1672 string_move(p-1, p);
1677 /*********************************************************************
1679 * Function : get_header
1681 * Description : This (odd) routine will parse the csp->iob
1682 * to get the next complete header.
1685 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1687 * Returns : Any one of the following:
1689 * 1) a pointer to a dynamically allocated string that contains a header line
1690 * 2) NULL indicating that the end of the header was reached
1691 * 3) "" indicating that the end of the iob was reached before finding
1692 * a complete header line.
1694 *********************************************************************/
1695 char *get_header(struct iob *iob)
1699 header = get_header_line(iob);
1701 if ((header == NULL) || (*header == '\0'))
1704 * No complete header read yet, tell the client.
1709 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1712 * Header spans multiple lines, append the next one.
1714 char *continued_header;
1716 continued_header = get_header_line(iob);
1717 if ((continued_header == NULL) || (*continued_header == '\0'))
1720 * No complete header read yet, return what we got.
1721 * XXX: Should "unread" header instead.
1723 log_error(LOG_LEVEL_INFO,
1724 "Failed to read a multi-line header properly: '%s'",
1729 if (JB_ERR_OK != string_join(&header, continued_header))
1731 log_error(LOG_LEVEL_FATAL,
1732 "Out of memory while appending multiple headers.");
1736 /* XXX: remove before next stable release. */
1737 log_error(LOG_LEVEL_HEADER,
1738 "Merged multiple header lines to: '%s'",
1743 normalize_lws(header);
1750 /*********************************************************************
1752 * Function : get_header_line
1754 * Description : This (odd) routine will parse the csp->iob
1755 * to get the next header line.
1758 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1760 * Returns : Any one of the following:
1762 * 1) a pointer to a dynamically allocated string that contains a header line
1763 * 2) NULL indicating that the end of the header was reached
1764 * 3) "" indicating that the end of the iob was reached before finding
1765 * a complete header line.
1767 *********************************************************************/
1768 static char *get_header_line(struct iob *iob)
1772 if ((iob->cur == NULL)
1773 || ((p = strchr(iob->cur, '\n')) == NULL))
1775 return(""); /* couldn't find a complete header */
1780 ret = strdup(iob->cur);
1783 /* FIXME No way to handle error properly */
1784 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1786 assert(ret != NULL);
1790 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1792 /* is this a blank line (i.e. the end of the header) ? */
1804 /*********************************************************************
1806 * Function : get_header_value
1808 * Description : Get the value of a given header from a chained list
1809 * of header lines or return NULL if no such header is
1810 * present in the list.
1813 * 1 : header_list = pointer to list
1814 * 2 : header_name = string with name of header to look for.
1815 * Trailing colon required, capitalization
1818 * Returns : NULL if not found, else value of header
1820 *********************************************************************/
1821 char *get_header_value(const struct list *header_list, const char *header_name)
1823 struct list_entry *cur_entry;
1827 assert(header_list);
1828 assert(header_name);
1829 length = strlen(header_name);
1831 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1835 if (!strncmpic(cur_entry->str, header_name, length))
1838 * Found: return pointer to start of value
1840 ret = cur_entry->str + length;
1841 while (*ret && ijb_isspace(*ret)) ret++;
1855 /*********************************************************************
1857 * Function : scan_headers
1859 * Description : Scans headers, applies tags and updates action bits.
1862 * 1 : csp = Current client state (buffers, headers, etc...)
1864 * Returns : JB_ERR_OK
1866 *********************************************************************/
1867 static jb_err scan_headers(struct client_state *csp)
1869 struct list_entry *h; /* Header */
1870 jb_err err = JB_ERR_OK;
1872 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1874 /* Header crunch()ed in previous run? -> ignore */
1875 if (h->str == NULL) continue;
1876 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1877 err = header_tagger(csp, h->str);
1884 /*********************************************************************
1888 * Description : add, delete or modify lines in the HTTP header streams.
1889 * On entry, it receives a linked list of headers space
1890 * that was allocated dynamically (both the list nodes
1891 * and the header contents).
1893 * As a side effect it frees the space used by the original
1897 * 1 : csp = Current client state (buffers, headers, etc...)
1898 * 2 : filter_server_headers = Boolean to switch between
1899 * server and header filtering.
1901 * Returns : JB_ERR_OK in case off success, or
1902 * JB_ERR_MEMORY on out-of-memory error.
1904 *********************************************************************/
1905 jb_err sed(struct client_state *csp, int filter_server_headers)
1907 /* XXX: use more descriptive names. */
1908 struct list_entry *p;
1909 const struct parsers *v;
1910 const add_header_func_ptr *f;
1911 jb_err err = JB_ERR_OK;
1913 if (filter_server_headers)
1915 v = server_patterns;
1916 f = add_server_headers;
1920 v = client_patterns;
1921 f = add_client_headers;
1926 while ((err == JB_ERR_OK) && (v->str != NULL))
1928 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1930 /* Header crunch()ed in previous run? -> ignore */
1931 if (p->str == NULL) continue;
1933 /* Does the current parser handle this header? */
1934 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1935 (v->len == CHECK_EVERY_HEADER_REMAINING))
1937 err = v->parser(csp, &(p->str));
1943 /* place additional headers on the csp->headers list */
1944 while ((err == JB_ERR_OK) && (*f))
1954 /*********************************************************************
1956 * Function : update_server_headers
1958 * Description : Updates server headers after the body has been modified.
1961 * 1 : csp = Current client state (buffers, headers, etc...)
1963 * Returns : JB_ERR_OK in case off success, or
1964 * JB_ERR_MEMORY on out-of-memory error.
1966 *********************************************************************/
1967 jb_err update_server_headers(struct client_state *csp)
1969 jb_err err = JB_ERR_OK;
1971 static const struct parsers server_patterns_light[] = {
1972 { "Content-Length:", 15, server_adjust_content_length },
1973 { "Transfer-Encoding:", 18, server_transfer_coding },
1975 { "Content-Encoding:", 17, server_content_encoding },
1976 #endif /* def FEATURE_ZLIB */
1980 if (strncmpic(csp->http->cmd, "HEAD", 4))
1982 const struct parsers *v;
1983 struct list_entry *p;
1985 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1987 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1989 /* Header crunch()ed in previous run? -> ignore */
1990 if (p->str == NULL) continue;
1992 /* Does the current parser handle this header? */
1993 if (strncmpic(p->str, v->str, v->len) == 0)
1995 err = v->parser(csp, (char **)&(p->str));
2005 /*********************************************************************
2007 * Function : header_tagger
2009 * Description : Executes all text substitutions from applying
2010 * tag actions and saves the result as tag.
2012 * XXX: Shares enough code with filter_header() and
2013 * pcrs_filter_response() to warrant some helper functions.
2016 * 1 : csp = Current client state (buffers, headers, etc...)
2017 * 2 : header = Header that is used as tagger input
2019 * Returns : JB_ERR_OK on success and always succeeds
2021 *********************************************************************/
2022 static jb_err header_tagger(struct client_state *csp, char *header)
2024 int wanted_filter_type;
2025 int multi_action_index;
2029 struct file_list *fl;
2030 struct re_filterfile_spec *b;
2031 struct list_entry *tag_name;
2033 int found_filters = 0;
2034 const size_t header_length = strlen(header);
2036 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2038 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
2039 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
2043 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
2044 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
2047 /* Check if there are any filters */
2048 for (i = 0; i < MAX_AF_FILES; i++)
2061 if (0 == found_filters)
2063 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2064 "tagging enabled, but no taggers available.");
2068 for (i = 0; i < MAX_AF_FILES; i++)
2071 if ((NULL == fl) || (NULL == fl->f))
2074 * Either there are no filter files
2075 * left, or this filter file just
2076 * contains no valid filters.
2078 * Continue to be sure we don't miss
2079 * valid filter files that are chained
2080 * after empty or invalid ones.
2085 /* For all filters, */
2086 for (b = fl->f; b; b = b->next)
2088 if (b->type != wanted_filter_type)
2090 /* skip the ones we don't care about, */
2093 /* leaving only taggers that could apply, of which we use the ones, */
2094 for (tag_name = csp->action->multi[multi_action_index]->first;
2095 NULL != tag_name; tag_name = tag_name->next)
2097 /* that do apply, and */
2098 if (strcmp(b->name, tag_name->str) == 0)
2100 char *modified_tag = NULL;
2102 size_t size = header_length;
2103 pcrs_job *joblist = b->joblist;
2105 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2107 if (NULL == joblist)
2109 log_error(LOG_LEVEL_RE_FILTER,
2110 "Tagger %s has empty joblist. Nothing to do.", b->name);
2114 /* execute their pcrs_joblist on the header. */
2115 for (job = joblist; NULL != job; job = job->next)
2117 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2121 /* Success, continue with the modified version. */
2130 /* Tagger doesn't match */
2133 /* Regex failure, log it but continue anyway. */
2134 assert(NULL != header);
2135 log_error(LOG_LEVEL_ERROR,
2136 "Problems with tagger \'%s\' and header \'%s\': %s",
2137 b->name, *header, pcrs_strerror(hits));
2139 freez(modified_tag);
2143 if (b->dynamic) pcrs_free_joblist(joblist);
2145 /* If this tagger matched */
2151 * There is to technical limitation which makes
2152 * it impossible to use empty tags, but I assume
2153 * no one would do it intentionally.
2156 log_error(LOG_LEVEL_INFO,
2157 "Tagger \'%s\' created an empty tag. Ignored.",
2162 if (!list_contains_item(csp->tags, tag))
2164 if (JB_ERR_OK != enlist(csp->tags, tag))
2166 log_error(LOG_LEVEL_ERROR,
2167 "Insufficient memory to add tag \'%s\', "
2168 "based on tagger \'%s\' and header \'%s\'",
2169 tag, b->name, *header);
2173 char *action_message;
2175 * update the action bits right away, to make
2176 * tagging based on tags set by earlier taggers
2177 * of the same kind possible.
2179 if (update_action_bits_for_tag(csp, tag))
2181 action_message = "Action bits updated accordingly.";
2185 action_message = "No action bits update necessary.";
2188 log_error(LOG_LEVEL_HEADER,
2189 "Tagger \'%s\' added tag \'%s\'. %s",
2190 b->name, tag, action_message);
2195 /* XXX: Is this log-worthy? */
2196 log_error(LOG_LEVEL_HEADER,
2197 "Tagger \'%s\' didn't add tag \'%s\'. "
2198 "Tag already present", b->name, tag);
2201 } /* if the tagger matched */
2202 } /* if the tagger applies */
2203 } /* for every tagger that could apply */
2204 } /* for all filters */
2205 } /* for all filter files */
2210 /* here begins the family of parser functions that reformat header lines */
2212 /*********************************************************************
2214 * Function : filter_header
2216 * Description : Executes all text substitutions from all applying
2217 * +(server|client)-header-filter actions on the header.
2218 * Most of the code was copied from pcrs_filter_response,
2219 * including the rather short variable names
2222 * 1 : csp = Current client state (buffers, headers, etc...)
2223 * 2 : header = On input, pointer to header to modify.
2224 * On output, pointer to the modified header, or NULL
2225 * to remove the header. This function frees the
2226 * original string if necessary.
2228 * Returns : JB_ERR_OK on success and always succeeds
2230 *********************************************************************/
2231 static jb_err filter_header(struct client_state *csp, char **header)
2235 size_t size = strlen(*header);
2237 char *newheader = NULL;
2240 struct file_list *fl;
2241 struct re_filterfile_spec *b;
2242 struct list_entry *filtername;
2244 int i, found_filters = 0;
2245 int wanted_filter_type;
2246 int multi_action_index;
2248 if (csp->flags & CSP_FLAG_NO_FILTERING)
2253 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2255 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2256 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2260 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2261 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2265 * Need to check the set of re_filterfiles...
2267 for (i = 0; i < MAX_AF_FILES; i++)
2280 if (0 == found_filters)
2282 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2283 "header filtering enabled, but no matching filters available.");
2287 for (i = 0; i < MAX_AF_FILES; i++)
2290 if ((NULL == fl) || (NULL == fl->f))
2293 * Either there are no filter files
2294 * left, or this filter file just
2295 * contains no valid filters.
2297 * Continue to be sure we don't miss
2298 * valid filter files that are chained
2299 * after empty or invalid ones.
2304 * For all applying +filter actions, look if a filter by that
2305 * name exists and if yes, execute its pcrs_joblist on the
2308 for (b = fl->f; b; b = b->next)
2310 if (b->type != wanted_filter_type)
2312 /* Skip other filter types */
2316 for (filtername = csp->action->multi[multi_action_index]->first;
2317 filtername ; filtername = filtername->next)
2319 if (strcmp(b->name, filtername->str) == 0)
2321 int current_hits = 0;
2322 pcrs_job *joblist = b->joblist;
2324 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2326 if (NULL == joblist)
2328 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2332 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2333 *header, size, b->name);
2335 /* Apply all jobs from the joblist */
2336 for (job = joblist; NULL != job; job = job->next)
2338 matches = pcrs_execute(job, *header, size, &newheader, &size);
2341 current_hits += matches;
2342 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2344 *header = newheader;
2346 else if ( 0 == matches )
2348 /* Filter doesn't change header */
2354 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2355 *header, b->name, pcrs_strerror(matches));
2356 if (newheader != NULL)
2358 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2364 if (b->dynamic) pcrs_free_joblist(joblist);
2366 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2367 hits += current_hits;
2374 * Additionally checking for hits is important because if
2375 * the continue hack is triggered, server headers can
2376 * arrive empty to separate multiple heads from each other.
2378 if ((0 == size) && hits)
2380 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2388 /*********************************************************************
2390 * Function : server_connection
2392 * Description : Makes sure a proper "Connection:" header is
2393 * set and signals connection_header_adder to
2397 * 1 : csp = Current client state (buffers, headers, etc...)
2398 * 2 : header = On input, pointer to header to modify.
2399 * On output, pointer to the modified header, or NULL
2400 * to remove the header. This function frees the
2401 * original string if necessary.
2403 * Returns : JB_ERR_OK on success, or
2404 * JB_ERR_MEMORY on out-of-memory error.
2406 *********************************************************************/
2407 static jb_err server_connection(struct client_state *csp, char **header)
2409 /* Do we have a 'Connection: close' header? */
2410 if (strcmpic(*header, "Connection: close"))
2412 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2413 if ((csp->config->feature_flags &
2414 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2415 && !strcmpic(*header, "Connection: keep-alive"))
2417 /* Remember to keep the connection alive. */
2418 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
2420 log_error(LOG_LEVEL_HEADER,
2421 "Keeping the server header '%s' around.", *header);
2423 char *old_header = *header;
2425 *header = strdup("Connection: close");
2428 return JB_ERR_MEMORY;
2430 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2432 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2435 /* Signal server_connection_adder() to return early. */
2436 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
2442 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2443 /*********************************************************************
2445 * Function : server_keep_alive
2447 * Description : Stores the servers keep alive timeout.
2450 * 1 : csp = Current client state (buffers, headers, etc...)
2451 * 2 : header = On input, pointer to header to modify.
2452 * On output, pointer to the modified header, or NULL
2453 * to remove the header. This function frees the
2454 * original string if necessary.
2456 * Returns : JB_ERR_OK.
2458 *********************************************************************/
2459 static jb_err server_keep_alive(struct client_state *csp, char **header)
2461 unsigned int keep_alive_timeout;
2462 const char *timeout_position = strstr(*header, "timeout=");
2464 if ((NULL != timeout_position)
2465 && (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
2467 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
2471 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
2473 log_error(LOG_LEVEL_HEADER,
2474 "Reducing keep-alive timeout from %u to %u.",
2475 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
2476 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
2480 /* XXX: Is this log worthy? */
2481 log_error(LOG_LEVEL_HEADER,
2482 "Server keep-alive timeout is %u. Sticking with %u.",
2483 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
2489 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2493 /*********************************************************************
2495 * Function : client_connection
2497 * Description : Makes sure a proper "Connection:" header is
2498 * set and signals connection_header_adder
2502 * 1 : csp = Current client state (buffers, headers, etc...)
2503 * 2 : header = On input, pointer to header to modify.
2504 * On output, pointer to the modified header, or NULL
2505 * to remove the header. This function frees the
2506 * original string if necessary.
2508 * Returns : JB_ERR_OK on success, or
2509 * JB_ERR_MEMORY on out-of-memory error.
2511 *********************************************************************/
2512 static jb_err client_connection(struct client_state *csp, char **header)
2514 const char *wanted_header = get_appropiate_connection_header(csp);
2516 if (strcmpic(*header, wanted_header))
2518 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2519 log_error(LOG_LEVEL_HEADER,
2520 "Keeping the client header '%s' around. "
2521 "The connection will not be kept alive.",
2524 char *old_header = *header;
2526 *header = strdup(wanted_header);
2529 return JB_ERR_MEMORY;
2531 log_error(LOG_LEVEL_HEADER,
2532 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2534 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2536 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2539 log_error(LOG_LEVEL_HEADER,
2540 "Keeping the client header '%s' around. "
2541 "The server connection will be kept alive if possible.",
2543 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2545 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2547 /* Signal client_connection_adder() to return early. */
2548 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2554 /*********************************************************************
2556 * Function : crumble
2558 * Description : This is called if a header matches a pattern to "crunch"
2561 * 1 : csp = Current client state (buffers, headers, etc...)
2562 * 2 : header = On input, pointer to header to modify.
2563 * On output, pointer to the modified header, or NULL
2564 * to remove the header. This function frees the
2565 * original string if necessary.
2567 * Returns : JB_ERR_OK on success, or
2568 * JB_ERR_MEMORY on out-of-memory error.
2570 *********************************************************************/
2571 static jb_err crumble(struct client_state *csp, char **header)
2574 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2580 /*********************************************************************
2582 * Function : crunch_server_header
2584 * Description : Crunch server header if it matches a string supplied by the
2585 * user. Called from `sed'.
2588 * 1 : csp = Current client state (buffers, headers, etc...)
2589 * 2 : header = On input, pointer to header to modify.
2590 * On output, pointer to the modified header, or NULL
2591 * to remove the header. This function frees the
2592 * original string if necessary.
2594 * Returns : JB_ERR_OK on success and always succeeds
2596 *********************************************************************/
2597 static jb_err crunch_server_header(struct client_state *csp, char **header)
2599 const char *crunch_pattern;
2601 /* Do we feel like crunching? */
2602 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2604 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2606 /* Is the current header the lucky one? */
2607 if (strstr(*header, crunch_pattern))
2609 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2618 /*********************************************************************
2620 * Function : server_content_type
2622 * Description : Set the content-type for filterable types (text/.*,
2623 * .*xml.*, javascript and image/gif) unless filtering has been
2624 * forbidden (CT_TABOO) while parsing earlier headers.
2625 * NOTE: Since text/plain is commonly used by web servers
2626 * for files whose correct type is unknown, we don't
2627 * set CT_TEXT for it.
2630 * 1 : csp = Current client state (buffers, headers, etc...)
2631 * 2 : header = On input, pointer to header to modify.
2632 * On output, pointer to the modified header, or NULL
2633 * to remove the header. This function frees the
2634 * original string if necessary.
2636 * Returns : JB_ERR_OK on success, or
2637 * JB_ERR_MEMORY on out-of-memory error.
2639 *********************************************************************/
2640 static jb_err server_content_type(struct client_state *csp, char **header)
2642 /* Remove header if it isn't the first Content-Type header */
2643 if ((csp->content_type & CT_DECLARED))
2646 * Another, slightly slower, way to see if
2647 * we already parsed another Content-Type header.
2649 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2651 log_error(LOG_LEVEL_ERROR,
2652 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2660 * Signal that the Content-Type has been set.
2662 csp->content_type |= CT_DECLARED;
2664 if (!(csp->content_type & CT_TABOO))
2667 * XXX: The assumption that text/plain is a sign of
2668 * binary data seems to be somewhat unreasonable nowadays
2669 * and should be dropped after 3.0.8 is out.
2671 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2672 || strstr(*header, "xml")
2673 || strstr(*header, "application/x-javascript"))
2675 csp->content_type |= CT_TEXT;
2677 else if (strstr(*header, "image/gif"))
2679 csp->content_type |= CT_GIF;
2684 * Are we messing with the content type?
2686 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2689 * Make sure the user doesn't accidently
2690 * change the content type of binary documents.
2692 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2695 *header = strdup("Content-Type: ");
2696 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2700 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2701 return JB_ERR_MEMORY;
2703 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2707 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2708 "It doesn't look like a content type that should be filtered. "
2709 "Enable force-text-mode if you know what you're doing.", *header);
2717 /*********************************************************************
2719 * Function : server_transfer_coding
2721 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2722 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2723 * - Remove header if body was chunked but has been
2724 * de-chunked for filtering.
2727 * 1 : csp = Current client state (buffers, headers, etc...)
2728 * 2 : header = On input, pointer to header to modify.
2729 * On output, pointer to the modified header, or NULL
2730 * to remove the header. This function frees the
2731 * original string if necessary.
2733 * Returns : JB_ERR_OK on success, or
2734 * JB_ERR_MEMORY on out-of-memory error.
2736 *********************************************************************/
2737 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2740 * Turn off pcrs and gif filtering if body compressed
2742 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2746 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2748 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2749 csp->http->cmd, *header);
2750 #endif /* def FEATURE_ZLIB */
2751 csp->content_type = CT_TABOO;
2755 * Raise flag if body chunked
2757 if (strstr(*header, "chunked"))
2759 csp->flags |= CSP_FLAG_CHUNKED;
2762 * If the body was modified, it has been de-chunked first
2763 * and the header must be removed.
2765 * FIXME: If there is more than one transfer encoding,
2766 * only the "chunked" part should be removed here.
2768 if (csp->flags & CSP_FLAG_MODIFIED)
2770 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2779 /*********************************************************************
2781 * Function : server_content_encoding
2783 * Description : This function is run twice for each request,
2784 * unless FEATURE_ZLIB and filtering are disabled.
2786 * The first run is used to check if the content
2787 * is compressed, if FEATURE_ZLIB is disabled
2788 * filtering is then disabled as well, if FEATURE_ZLIB
2789 * is enabled the content is marked for decompression.
2791 * The second run is used to remove the Content-Encoding
2792 * header if the decompression was successful.
2795 * 1 : csp = Current client state (buffers, headers, etc...)
2796 * 2 : header = On input, pointer to header to modify.
2797 * On output, pointer to the modified header, or NULL
2798 * to remove the header. This function frees the
2799 * original string if necessary.
2801 * Returns : JB_ERR_OK on success, or
2802 * JB_ERR_MEMORY on out-of-memory error.
2804 *********************************************************************/
2805 static jb_err server_content_encoding(struct client_state *csp, char **header)
2808 if ((csp->flags & CSP_FLAG_MODIFIED)
2809 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2812 * We successfully decompressed the content,
2813 * and have to clean the header now, so the
2814 * client no longer expects compressed data..
2816 * XXX: There is a difference between cleaning
2817 * and removing it completely.
2819 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2822 else if (strstr(*header, "gzip"))
2824 /* Mark for gzip decompression */
2825 csp->content_type |= CT_GZIP;
2827 else if (strstr(*header, "deflate"))
2829 /* Mark for zlib decompression */
2830 csp->content_type |= CT_DEFLATE;
2832 else if (strstr(*header, "compress"))
2835 * We can't decompress this; therefore we can't filter
2838 csp->content_type |= CT_TABOO;
2840 #else /* !defined(FEATURE_ZLIB) */
2841 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2844 * Body is compressed, turn off pcrs and gif filtering.
2846 csp->content_type |= CT_TABOO;
2849 * Log a warning if the user expects the content to be filtered.
2851 if ((csp->rlist != NULL) &&
2852 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2854 log_error(LOG_LEVEL_INFO,
2855 "Compressed content detected, content filtering disabled. "
2856 "Consider recompiling Privoxy with zlib support or "
2857 "enable the prevent-compression action.");
2860 #endif /* defined(FEATURE_ZLIB) */
2867 /*********************************************************************
2869 * Function : server_adjust_content_length
2871 * Description : Adjust Content-Length header if we modified
2875 * 1 : csp = Current client state (buffers, headers, etc...)
2876 * 2 : header = On input, pointer to header to modify.
2877 * On output, pointer to the modified header, or NULL
2878 * to remove the header. This function frees the
2879 * original string if necessary.
2881 * Returns : JB_ERR_OK on success, or
2882 * JB_ERR_MEMORY on out-of-memory error.
2884 *********************************************************************/
2885 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2887 const size_t max_header_length = 80;
2889 /* Regenerate header if the content was modified. */
2890 if (csp->flags & CSP_FLAG_MODIFIED)
2893 *header = (char *) zalloc(max_header_length);
2894 if (*header == NULL)
2896 return JB_ERR_MEMORY;
2899 snprintf(*header, max_header_length, "Content-Length: %d",
2900 (int)csp->content_length);
2901 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2902 (int)csp->content_length);
2909 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2910 /*********************************************************************
2912 * Function : server_save_content_length
2914 * Description : Save the Content-Length sent by the server.
2917 * 1 : csp = Current client state (buffers, headers, etc...)
2918 * 2 : header = On input, pointer to header to modify.
2919 * On output, pointer to the modified header, or NULL
2920 * to remove the header. This function frees the
2921 * original string if necessary.
2923 * Returns : JB_ERR_OK on success, or
2924 * JB_ERR_MEMORY on out-of-memory error.
2926 *********************************************************************/
2927 static jb_err server_save_content_length(struct client_state *csp, char **header)
2929 unsigned long long content_length = 0;
2931 assert(*(*header+14) == ':');
2933 if (1 != sscanf(*header+14, ": %llu", &content_length))
2935 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2940 csp->expected_content_length = content_length;
2941 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2946 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2949 /*********************************************************************
2951 * Function : server_content_md5
2953 * Description : Crumble any Content-MD5 headers if the document was
2954 * modified. FIXME: Should we re-compute instead?
2957 * 1 : csp = Current client state (buffers, headers, etc...)
2958 * 2 : header = On input, pointer to header to modify.
2959 * On output, pointer to the modified header, or NULL
2960 * to remove the header. This function frees the
2961 * original string if necessary.
2963 * Returns : JB_ERR_OK on success, or
2964 * JB_ERR_MEMORY on out-of-memory error.
2966 *********************************************************************/
2967 static jb_err server_content_md5(struct client_state *csp, char **header)
2969 if (csp->flags & CSP_FLAG_MODIFIED)
2971 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2979 /*********************************************************************
2981 * Function : server_content_disposition
2983 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2984 * 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 server_content_disposition(struct client_state *csp, char **header)
3002 * Are we messing with the Content-Disposition header?
3004 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
3010 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
3012 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3015 * Blocking content-disposition header
3017 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
3024 * Replacing Content-Disposition header
3027 *header = strdup("Content-Disposition: ");
3028 string_append(header, newval);
3030 if (*header != NULL)
3032 log_error(LOG_LEVEL_HEADER,
3033 "Content-Disposition header crunched and replaced with: %s", *header);
3036 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3040 /*********************************************************************
3042 * Function : server_last_modified
3044 * Description : Changes Last-Modified header to the actual date
3045 * to help hide-if-modified-since.
3046 * Called from `sed'.
3049 * 1 : csp = Current client state (buffers, headers, etc...)
3050 * 2 : header = On input, pointer to header to modify.
3051 * On output, pointer to the modified header, or NULL
3052 * to remove the header. This function frees the
3053 * original string if necessary.
3055 * Returns : JB_ERR_OK on success, or
3056 * JB_ERR_MEMORY on out-of-memory error.
3058 *********************************************************************/
3059 static jb_err server_last_modified(struct client_state *csp, char **header)
3062 char buf[BUFFER_SIZE];
3065 #ifdef HAVE_GMTIME_R
3068 struct tm *timeptr = NULL;
3069 time_t now, last_modified;
3071 long int days, hours, minutes, seconds;
3074 * Are we messing with the Last-Modified header?
3076 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
3082 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
3084 if (0 == strcmpic(newval, "block") )
3087 * Blocking Last-Modified header. Useless but why not.
3089 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
3093 else if (0 == strcmpic(newval, "reset-to-request-time"))
3096 * Setting Last-Modified Header to now.
3098 get_http_time(0, buf, sizeof(buf));
3100 *header = strdup("Last-Modified: ");
3101 string_append(header, buf);
3103 if (*header == NULL)
3105 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
3109 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
3112 else if (0 == strcmpic(newval, "randomize"))
3114 const char *header_time = *header + sizeof("Last-Modified:");
3116 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
3118 #ifdef HAVE_GMTIME_R
3119 timeptr = gmtime_r(&now, &gmt);
3120 #elif FEATURE_PTHREAD
3121 privoxy_mutex_lock(&gmtime_mutex);
3122 timeptr = gmtime(&now);
3123 privoxy_mutex_unlock(&gmtime_mutex);
3125 timeptr = gmtime(&now);
3127 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
3129 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3134 rtime = (long int)difftime(now, last_modified);
3143 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
3145 rtime = pick_from_range(rtime);
3146 if (negative) rtime *= -1;
3147 last_modified += rtime;
3148 #ifdef HAVE_GMTIME_R
3149 timeptr = gmtime_r(&last_modified, &gmt);
3150 #elif FEATURE_PTHREAD
3151 privoxy_mutex_lock(&gmtime_mutex);
3152 timeptr = gmtime(&last_modified);
3153 privoxy_mutex_unlock(&gmtime_mutex);
3155 timeptr = gmtime(&last_modified);
3157 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3159 *header = strdup("Last-Modified: ");
3160 string_append(header, newheader);
3162 if (*header == NULL)
3164 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
3165 return JB_ERR_MEMORY;
3168 days = rtime / (3600 * 24);
3169 hours = rtime / 3600 % 24;
3170 minutes = rtime / 60 % 60;
3171 seconds = rtime % 60;
3173 log_error(LOG_LEVEL_HEADER,
3174 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
3175 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
3176 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3180 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
3189 /*********************************************************************
3191 * Function : client_accept_encoding
3193 * Description : Rewrite the client's Accept-Encoding header so that
3194 * if doesn't allow compression, if the action applies.
3195 * Note: For HTTP/1.0 the absence of the header is enough.
3198 * 1 : csp = Current client state (buffers, headers, etc...)
3199 * 2 : header = On input, pointer to header to modify.
3200 * On output, pointer to the modified header, or NULL
3201 * to remove the header. This function frees the
3202 * original string if necessary.
3204 * Returns : JB_ERR_OK on success, or
3205 * JB_ERR_MEMORY on out-of-memory error.
3207 *********************************************************************/
3208 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3210 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3212 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3216 /* Temporarily disable the correct behaviour to
3217 * work around a PHP bug.
3219 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
3221 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
3222 * if (*header == NULL)
3224 * return JB_ERR_MEMORY;
3235 /*********************************************************************
3237 * Function : client_te
3239 * Description : Rewrite the client's TE header so that
3240 * if doesn't allow compression, if the action applies.
3243 * 1 : csp = Current client state (buffers, headers, etc...)
3244 * 2 : header = On input, pointer to header to modify.
3245 * On output, pointer to the modified header, or NULL
3246 * to remove the header. This function frees the
3247 * original string if necessary.
3249 * Returns : JB_ERR_OK on success, or
3250 * JB_ERR_MEMORY on out-of-memory error.
3252 *********************************************************************/
3253 static jb_err client_te(struct client_state *csp, char **header)
3255 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3258 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3265 /*********************************************************************
3267 * Function : client_referrer
3269 * Description : Handle the "referer" config setting properly.
3270 * Called from `sed'.
3273 * 1 : csp = Current client state (buffers, headers, etc...)
3274 * 2 : header = On input, pointer to header to modify.
3275 * On output, pointer to the modified header, or NULL
3276 * to remove the header. This function frees the
3277 * original string if necessary.
3279 * Returns : JB_ERR_OK on success, or
3280 * JB_ERR_MEMORY on out-of-memory error.
3282 *********************************************************************/
3283 static jb_err client_referrer(struct client_state *csp, char **header)
3285 const char *parameter;
3286 /* booleans for parameters we have to check multiple times */
3287 int parameter_conditional_block;
3288 int parameter_conditional_forge;
3290 #ifdef FEATURE_FORCE_LOAD
3292 * Since the referrer can include the prefix even
3293 * if the request itself is non-forced, we must
3294 * clean it unconditionally.
3296 * XXX: strclean is too broad
3298 strclean(*header, FORCE_PREFIX);
3299 #endif /* def FEATURE_FORCE_LOAD */
3301 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3303 /* Nothing left to do */
3307 parameter = csp->action->string[ACTION_STRING_REFERER];
3308 assert(parameter != NULL);
3309 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3310 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3312 if (!parameter_conditional_block && !parameter_conditional_forge)
3315 * As conditional-block and conditional-forge are the only
3316 * parameters that rely on the original referrer, we can
3317 * remove it now for all the others.
3322 if (0 == strcmpic(parameter, "block"))
3324 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3327 else if (parameter_conditional_block || parameter_conditional_forge)
3329 return handle_conditional_hide_referrer_parameter(header,
3330 csp->http->hostport, parameter_conditional_block);
3332 else if (0 == strcmpic(parameter, "forge"))
3334 return create_forged_referrer(header, csp->http->hostport);
3338 /* interpret parameter as user-supplied referer to fake */
3339 return create_fake_referrer(header, parameter);
3344 /*********************************************************************
3346 * Function : client_accept_language
3348 * Description : Handle the "Accept-Language" config setting properly.
3349 * Called from `sed'.
3352 * 1 : csp = Current client state (buffers, headers, etc...)
3353 * 2 : header = On input, pointer to header to modify.
3354 * On output, pointer to the modified header, or NULL
3355 * to remove the header. This function frees the
3356 * original string if necessary.
3358 * Returns : JB_ERR_OK on success, or
3359 * JB_ERR_MEMORY on out-of-memory error.
3361 *********************************************************************/
3362 static jb_err client_accept_language(struct client_state *csp, char **header)
3367 * Are we messing with the Accept-Language?
3369 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3371 /*I don't think so*/
3375 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3377 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3380 * Blocking Accept-Language header
3382 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3389 * Replacing Accept-Language header
3392 *header = strdup("Accept-Language: ");
3393 string_append(header, newval);
3395 if (*header == NULL)
3397 log_error(LOG_LEVEL_ERROR,
3398 "Insufficient memory. Accept-Language header crunched without replacement.");
3402 log_error(LOG_LEVEL_HEADER,
3403 "Accept-Language header crunched and replaced with: %s", *header);
3406 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3410 /*********************************************************************
3412 * Function : crunch_client_header
3414 * Description : Crunch client header if it matches a string supplied by the
3415 * user. Called from `sed'.
3418 * 1 : csp = Current client state (buffers, headers, etc...)
3419 * 2 : header = On input, pointer to header to modify.
3420 * On output, pointer to the modified header, or NULL
3421 * to remove the header. This function frees the
3422 * original string if necessary.
3424 * Returns : JB_ERR_OK on success and always succeeds
3426 *********************************************************************/
3427 static jb_err crunch_client_header(struct client_state *csp, char **header)
3429 const char *crunch_pattern;
3431 /* Do we feel like crunching? */
3432 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3434 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3436 /* Is the current header the lucky one? */
3437 if (strstr(*header, crunch_pattern))
3439 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3447 /*********************************************************************
3449 * Function : client_uagent
3451 * Description : Handle the "user-agent" config setting properly
3452 * and remember its original value to enable browser
3453 * bug workarounds. Called from `sed'.
3456 * 1 : csp = Current client state (buffers, headers, etc...)
3457 * 2 : header = On input, pointer to header to modify.
3458 * On output, pointer to the modified header, or NULL
3459 * to remove the header. This function frees the
3460 * original string if necessary.
3462 * Returns : JB_ERR_OK on success, or
3463 * JB_ERR_MEMORY on out-of-memory error.
3465 *********************************************************************/
3466 static jb_err client_uagent(struct client_state *csp, char **header)
3470 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3475 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3482 *header = strdup("User-Agent: ");
3483 string_append(header, newval);
3485 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3487 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3491 /*********************************************************************
3493 * Function : client_ua
3495 * Description : Handle "ua-" headers properly. Called from `sed'.
3498 * 1 : csp = Current client state (buffers, headers, etc...)
3499 * 2 : header = On input, pointer to header to modify.
3500 * On output, pointer to the modified header, or NULL
3501 * to remove the header. This function frees the
3502 * original string if necessary.
3504 * Returns : JB_ERR_OK on success, or
3505 * JB_ERR_MEMORY on out-of-memory error.
3507 *********************************************************************/
3508 static jb_err client_ua(struct client_state *csp, char **header)
3510 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3512 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3520 /*********************************************************************
3522 * Function : client_from
3524 * Description : Handle the "from" config setting properly.
3525 * Called from `sed'.
3528 * 1 : csp = Current client state (buffers, headers, etc...)
3529 * 2 : header = On input, pointer to header to modify.
3530 * On output, pointer to the modified header, or NULL
3531 * to remove the header. This function frees the
3532 * original string if necessary.
3534 * Returns : JB_ERR_OK on success, or
3535 * JB_ERR_MEMORY on out-of-memory error.
3537 *********************************************************************/
3538 static jb_err client_from(struct client_state *csp, char **header)
3542 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3549 newval = csp->action->string[ACTION_STRING_FROM];
3552 * Are we blocking the e-mail address?
3554 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3556 log_error(LOG_LEVEL_HEADER, "crunched From!");
3560 log_error(LOG_LEVEL_HEADER, " modified");
3562 *header = strdup("From: ");
3563 string_append(header, newval);
3565 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3569 /*********************************************************************
3571 * Function : client_send_cookie
3573 * Description : Crunches the "cookie" header if necessary.
3574 * Called from `sed'.
3576 * XXX: Stupid name, doesn't send squat.
3579 * 1 : csp = Current client state (buffers, headers, etc...)
3580 * 2 : header = On input, pointer to header to modify.
3581 * On output, pointer to the modified header, or NULL
3582 * to remove the header. This function frees the
3583 * original string if necessary.
3585 * Returns : JB_ERR_OK on success, or
3586 * JB_ERR_MEMORY on out-of-memory error.
3588 *********************************************************************/
3589 static jb_err client_send_cookie(struct client_state *csp, char **header)
3591 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3593 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3601 /*********************************************************************
3603 * Function : client_x_forwarded
3605 * Description : Handle the "x-forwarded-for" config setting properly,
3606 * also used in the add_client_headers list. Called from `sed'.
3609 * 1 : csp = Current client state (buffers, headers, etc...)
3610 * 2 : header = On input, pointer to header to modify.
3611 * On output, pointer to the modified header, or NULL
3612 * to remove the header. This function frees the
3613 * original string if necessary.
3615 * Returns : JB_ERR_OK on success, or
3616 * JB_ERR_MEMORY on out-of-memory error.
3618 *********************************************************************/
3619 jb_err client_x_forwarded(struct client_state *csp, char **header)
3621 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3623 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3625 if (0 == strcmpic(parameter, "block"))
3628 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3630 else if (0 == strcmpic(parameter, "add"))
3632 string_append(header, ", ");
3633 string_append(header, csp->ip_addr_str);
3635 if (*header == NULL)
3637 return JB_ERR_MEMORY;
3639 log_error(LOG_LEVEL_HEADER,
3640 "Appended client IP address to %s", *header);
3641 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3645 log_error(LOG_LEVEL_FATAL,
3646 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3654 /*********************************************************************
3656 * Function : client_max_forwards
3658 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3659 * from the value of the Max-Forwards header field.
3662 * 1 : csp = Current client state (buffers, headers, etc...)
3663 * 2 : header = On input, pointer to header to modify.
3664 * On output, pointer to the modified header, or NULL
3665 * to remove the header. This function frees the
3666 * original string if necessary.
3668 * Returns : JB_ERR_OK on success, or
3669 * JB_ERR_MEMORY on out-of-memory error.
3671 *********************************************************************/
3672 static jb_err client_max_forwards(struct client_state *csp, char **header)
3676 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3677 (0 == strcmpic(csp->http->gpc, "options")))
3679 assert(*(*header+12) == ':');
3680 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3682 if (max_forwards > 0)
3684 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3685 log_error(LOG_LEVEL_HEADER,
3686 "Max-Forwards value for %s request reduced to %d.",
3687 csp->http->gpc, max_forwards);
3689 else if (max_forwards < 0)
3691 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3697 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3706 /*********************************************************************
3708 * Function : client_host
3710 * Description : If the request URI did not contain host and
3711 * port information, parse and evaluate the Host
3714 * Also, kill ill-formed HOST: headers as sent by
3715 * Apple's iTunes software when used with a proxy.
3718 * 1 : csp = Current client state (buffers, headers, etc...)
3719 * 2 : header = On input, pointer to header to modify.
3720 * On output, pointer to the modified header, or NULL
3721 * to remove the header. This function frees the
3722 * original string if necessary.
3724 * Returns : JB_ERR_OK on success, or
3725 * JB_ERR_MEMORY on out-of-memory error.
3727 *********************************************************************/
3728 static jb_err client_host(struct client_state *csp, char **header)
3733 * If the header field name is all upper-case, chances are that it's
3734 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3735 * not a problem -- they are regenerated later.
3737 if ((*header)[1] == 'O')
3739 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3744 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3745 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3748 if (NULL == (p = strdup((*header)+6)))
3750 return JB_ERR_MEMORY;
3753 if (NULL == (q = strdup(p)))
3756 return JB_ERR_MEMORY;
3759 freez(csp->http->hostport);
3760 csp->http->hostport = p;
3761 freez(csp->http->host);
3762 csp->http->host = q;
3763 q = strchr(csp->http->host, ':');
3766 /* Terminate hostname and evaluate port string */
3768 csp->http->port = atoi(q);
3772 csp->http->port = csp->http->ssl ? 443 : 80;
3775 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3776 csp->http->hostport, csp->http->host, csp->http->port);
3779 /* Signal client_host_adder() to return right away */
3780 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3786 /*********************************************************************
3788 * Function : client_if_modified_since
3790 * Description : Remove or modify the If-Modified-Since header.
3793 * 1 : csp = Current client state (buffers, headers, etc...)
3794 * 2 : header = On input, pointer to header to modify.
3795 * On output, pointer to the modified header, or NULL
3796 * to remove the header. This function frees the
3797 * original string if necessary.
3799 * Returns : JB_ERR_OK on success, or
3800 * JB_ERR_MEMORY on out-of-memory error.
3802 *********************************************************************/
3803 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3806 #ifdef HAVE_GMTIME_R
3809 struct tm *timeptr = NULL;
3813 long int hours, minutes, seconds;
3817 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3820 * The client got an error message because of a temporary problem,
3821 * the problem is gone and the client now tries to revalidate our
3822 * error message on the real server. The revalidation would always
3823 * end with the transmission of the whole document and there is
3824 * no need to expose the bogus If-Modified-Since header.
3826 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3829 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3831 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3833 if ((0 == strcmpic(newval, "block")))
3835 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3838 else /* add random value */
3840 const char *header_time = *header + sizeof("If-Modified-Since:");
3842 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3844 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3849 rtime = strtol(newval, &endptr, 0);
3852 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3853 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3860 rtime = pick_from_range(rtime);
3864 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3867 tm += rtime * (negative ? -1 : 1);
3868 #ifdef HAVE_GMTIME_R
3869 timeptr = gmtime_r(&tm, &gmt);
3870 #elif FEATURE_PTHREAD
3871 privoxy_mutex_lock(&gmtime_mutex);
3872 timeptr = gmtime(&tm);
3873 privoxy_mutex_unlock(&gmtime_mutex);
3875 timeptr = gmtime(&tm);
3877 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3880 *header = strdup("If-Modified-Since: ");
3881 string_append(header, newheader);
3883 if (*header == NULL)
3885 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3886 return JB_ERR_MEMORY;
3889 hours = rtime / 3600;
3890 minutes = rtime / 60 % 60;
3891 seconds = rtime % 60;
3893 log_error(LOG_LEVEL_HEADER,
3894 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3895 *header, (negative) ? "subtracted" : "added", hours,
3896 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3897 seconds, (seconds == 1) ? ")" : "s)");
3906 /*********************************************************************
3908 * Function : client_if_none_match
3910 * Description : Remove the If-None-Match header.
3913 * 1 : csp = Current client state (buffers, headers, etc...)
3914 * 2 : header = On input, pointer to header to modify.
3915 * On output, pointer to the modified header, or NULL
3916 * to remove the header. This function frees the
3917 * original string if necessary.
3919 * Returns : JB_ERR_OK on success, or
3920 * JB_ERR_MEMORY on out-of-memory error.
3922 *********************************************************************/
3923 static jb_err client_if_none_match(struct client_state *csp, char **header)
3925 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3927 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3935 /*********************************************************************
3937 * Function : client_x_filter
3939 * Description : Disables filtering if the client set "X-Filter: No".
3940 * Called from `sed'.
3943 * 1 : csp = Current client state (buffers, headers, etc...)
3944 * 2 : header = On input, pointer to header to modify.
3945 * On output, pointer to the modified header, or NULL
3946 * to remove the header. This function frees the
3947 * original string if necessary.
3949 * Returns : JB_ERR_OK on success
3951 *********************************************************************/
3952 jb_err client_x_filter(struct client_state *csp, char **header)
3954 if ( 0 == strcmpic(*header, "X-Filter: No"))
3956 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3958 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3962 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3964 log_error(LOG_LEVEL_HEADER,
3965 "force-text-mode overruled the client's request to fetch without filtering!");
3969 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3970 csp->flags |= CSP_FLAG_NO_FILTERING;
3971 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3973 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3981 /*********************************************************************
3983 * Function : client_range
3985 * Description : Removes Range, Request-Range and If-Range headers if
3986 * content filtering is enabled. If the client's version
3987 * of the document has been altered by Privoxy, the server
3988 * could interpret the range differently than the client
3989 * intended in which case the user could end up with
3990 * corrupted content.
3993 * 1 : csp = Current client state (buffers, headers, etc...)
3994 * 2 : header = On input, pointer to header to modify.
3995 * On output, pointer to the modified header, or NULL
3996 * to remove the header. This function frees the
3997 * original string if necessary.
3999 * Returns : JB_ERR_OK
4001 *********************************************************************/
4002 static jb_err client_range(struct client_state *csp, char **header)
4004 if (content_filters_enabled(csp->action))
4006 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
4007 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
4014 /* the following functions add headers directly to the header list */
4016 /*********************************************************************
4018 * Function : client_host_adder
4020 * Description : Adds the Host: header field if it is missing.
4021 * Called from `sed'.
4024 * 1 : csp = Current client state (buffers, headers, etc...)
4026 * Returns : JB_ERR_OK on success, or
4027 * JB_ERR_MEMORY on out-of-memory error.
4029 *********************************************************************/
4030 static jb_err client_host_adder(struct client_state *csp)
4035 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
4037 /* Header already set by the client, nothing to do. */
4041 if ( !csp->http->hostport || !*(csp->http->hostport))
4043 /* XXX: When does this happen and why is it OK? */
4044 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
4049 * remove 'user:pass@' from 'proto://user:pass@host'
4051 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
4057 p = csp->http->hostport;
4060 /* XXX: Just add it, we already made sure that it will be unique */
4061 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
4062 err = enlist_unique_header(csp->headers, "Host", p);
4069 /*********************************************************************
4071 * Function : client_accept_encoding_adder
4073 * Description : Add an Accept-Encoding header to the client's request
4074 * that disables compression if the action applies, and
4075 * the header is not already there. Called from `sed'.
4076 * Note: For HTTP/1.0, the absence of the header is enough.
4079 * 1 : csp = Current client state (buffers, headers, etc...)
4081 * Returns : JB_ERR_OK on success, or
4082 * JB_ERR_MEMORY on out-of-memory error.
4084 *********************************************************************/
4085 static jb_err client_accept_encoding_adder(struct client_state *csp)
4087 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
4088 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
4090 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
4098 /*********************************************************************
4100 * Function : client_xtra_adder
4102 * Description : Used in the add_client_headers list. Called from `sed'.
4105 * 1 : csp = Current client state (buffers, headers, etc...)
4107 * Returns : JB_ERR_OK on success, or
4108 * JB_ERR_MEMORY on out-of-memory error.
4110 *********************************************************************/
4111 static jb_err client_xtra_adder(struct client_state *csp)
4113 struct list_entry *lst;
4116 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
4117 lst ; lst = lst->next)
4119 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
4120 err = enlist(csp->headers, lst->str);
4132 /*********************************************************************
4134 * Function : client_x_forwarded_for_adder
4136 * Description : Used in the add_client_headers list. Called from `sed'.
4139 * 1 : csp = Current client state (buffers, headers, etc...)
4141 * Returns : JB_ERR_OK on success, or
4142 * JB_ERR_MEMORY on out-of-memory error.
4144 *********************************************************************/
4145 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
4147 char *header = NULL;
4150 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
4151 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
4152 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
4155 * If we aren't adding X-Forwarded-For headers,
4156 * or we already appended an existing X-Forwarded-For
4157 * header, there's nothing left to do here.
4162 header = strdup("X-Forwarded-For: ");
4163 string_append(&header, csp->ip_addr_str);
4167 return JB_ERR_MEMORY;
4170 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
4171 err = enlist(csp->headers, header);
4178 /*********************************************************************
4180 * Function : server_connection_adder
4182 * Description : Adds an appropiate "Connection:" header to csp->headers
4183 * unless the header was already present. Called from `sed'.
4186 * 1 : csp = Current client state (buffers, headers, etc...)
4188 * Returns : JB_ERR_OK on success, or
4189 * JB_ERR_MEMORY on out-of-memory error.
4191 *********************************************************************/
4192 static jb_err server_connection_adder(struct client_state *csp)
4194 const unsigned int flags = csp->flags;
4195 const char *response_status_line = csp->headers->first->str;
4196 const char *wanted_header = get_appropiate_connection_header(csp);
4198 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4199 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
4205 * XXX: if we downgraded the response, this check will fail.
4207 if ((csp->config->feature_flags &
4208 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4209 && (NULL != response_status_line)
4210 && !strncmpic(response_status_line, "HTTP/1.1", 8))
4212 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
4213 "without Connection header implies keep-alive.");
4214 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
4217 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
4219 return enlist(csp->headers, wanted_header);
4223 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4224 /*********************************************************************
4226 * Function : server_proxy_connection_adder
4228 * Description : Adds a "Proxy-Connection: keep-alive" header to
4229 * csp->headers. XXX: We should reuse existant ones.
4232 * 1 : csp = Current client state (buffers, headers, etc...)
4234 * Returns : JB_ERR_OK on success, or
4235 * JB_ERR_MEMORY on out-of-memory error.
4237 *********************************************************************/
4238 static jb_err server_proxy_connection_adder(struct client_state *csp)
4240 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
4241 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
4242 return enlist(csp->headers, proxy_connection_header);
4244 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4247 /*********************************************************************
4249 * Function : client_connection_header_adder
4251 * Description : Adds a proper "Connection:" header to csp->headers
4252 * unless the header was already present. Called from `sed'.
4255 * 1 : csp = Current client state (buffers, headers, etc...)
4257 * Returns : JB_ERR_OK on success, or
4258 * JB_ERR_MEMORY on out-of-memory error.
4260 *********************************************************************/
4261 static jb_err client_connection_header_adder(struct client_state *csp)
4263 const unsigned int flags = csp->flags;
4264 const char *wanted_header = get_appropiate_connection_header(csp);
4266 if (!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4267 && (flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4272 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
4274 return enlist(csp->headers, wanted_header);
4278 /*********************************************************************
4280 * Function : server_http
4282 * Description : - Save the HTTP Status into csp->http->status
4283 * - Set CT_TABOO to prevent filtering if the answer
4284 * is a partial range (HTTP status 206)
4285 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4289 * 1 : csp = Current client state (buffers, headers, etc...)
4290 * 2 : header = On input, pointer to header to modify.
4291 * On output, pointer to the modified header, or NULL
4292 * to remove the header. This function frees the
4293 * original string if necessary.
4295 * Returns : JB_ERR_OK on success, or
4296 * JB_ERR_MEMORY on out-of-memory error.
4298 *********************************************************************/
4299 static jb_err server_http(struct client_state *csp, char **header)
4301 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
4302 if (csp->http->status == 206)
4304 csp->content_type = CT_TABOO;
4307 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
4309 /* XXX: Should we do a real validity check here? */
4310 if (strlen(*header) > 8)
4313 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
4318 * XXX: Should we block the request or
4319 * enlist a valid status code line here?
4321 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
4322 "Downgrading to HTTP/1.0 impossible.");
4330 /*********************************************************************
4332 * Function : server_set_cookie
4334 * Description : Handle the server "cookie" header properly.
4335 * Log cookie to the jar file. Then "crunch",
4336 * accept or rewrite it to a session cookie.
4337 * Called from `sed'.
4339 * TODO: Allow the user to specify a new expiration
4340 * time to cause the cookie to expire even before the
4341 * browser is closed.
4344 * 1 : csp = Current client state (buffers, headers, etc...)
4345 * 2 : header = On input, pointer to header to modify.
4346 * On output, pointer to the modified header, or NULL
4347 * to remove the header. This function frees the
4348 * original string if necessary.
4350 * Returns : JB_ERR_OK on success, or
4351 * JB_ERR_MEMORY on out-of-memory error.
4353 *********************************************************************/
4354 static jb_err server_set_cookie(struct client_state *csp, char **header)
4361 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4363 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4366 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4368 /* Flag whether or not to log a message */
4371 /* A variable to store the tag we're working on */
4374 /* Skip "Set-Cookie:" (11 characters) in header */
4375 cur_tag = *header + 11;
4377 /* skip whitespace between "Set-Cookie:" and value */
4378 while (*cur_tag && ijb_isspace(*cur_tag))
4383 /* Loop through each tag in the cookie */
4387 char *next_tag = strchr(cur_tag, ';');
4388 if (next_tag != NULL)
4390 /* Skip the ';' character itself */
4393 /* skip whitespace ";" and start of tag */
4394 while (*next_tag && ijb_isspace(*next_tag))
4401 /* "Next tag" is the end of the string */
4402 next_tag = cur_tag + strlen(cur_tag);
4406 * Check the expiration date to see
4407 * if the cookie is still valid, if yes,
4408 * rewrite it to a session cookie.
4410 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4412 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4414 /* Did we detect the date properly? */
4415 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4418 * Nope, treat it as if it was still valid.
4420 * XXX: Should we remove the whole cookie instead?
4422 log_error(LOG_LEVEL_ERROR,
4423 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4424 string_move(cur_tag, next_tag);
4430 * Yes. Check if the cookie is still valid.
4432 * If the cookie is already expired it's probably
4433 * a delete cookie and even if it isn't, the browser
4434 * will discard it anyway.
4438 * XXX: timegm() isn't available on some AmigaOS
4439 * versions and our replacement doesn't work.
4441 * Our options are to either:
4443 * - disable session-cookies-only completely if timegm
4446 * - to simply remove all expired tags, like it has
4447 * been done until Privoxy 3.0.6 and to live with
4448 * the consequence that it can cause login/logout
4449 * problems on servers that don't validate their
4450 * input properly, or
4452 * - to replace it with mktime in which
4453 * case there is a slight chance of valid cookies
4454 * passing as already expired.
4456 * This is the way it's currently done and it's not
4457 * as bad as it sounds. If the missing GMT offset is
4458 * enough to change the result of the expiration check
4459 * the cookie will be only valid for a few hours
4460 * anyway, which in many cases will be shorter
4461 * than a browser session.
4463 if (cookie_time - now < 0)
4465 log_error(LOG_LEVEL_HEADER,
4466 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4467 /* Just in case some clown sets more then one expiration date */
4473 * Still valid, delete expiration date by copying
4474 * the rest of the string over it.
4476 string_move(cur_tag, next_tag);
4478 /* That changed the header, need to issue a log message */
4482 * Note that the next tag has now been moved to *cur_tag,
4483 * so we do not need to update the cur_tag pointer.
4491 /* Move on to next cookie tag */
4498 assert(NULL != *header);
4499 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4508 #ifdef FEATURE_FORCE_LOAD
4509 /*********************************************************************
4511 * Function : strclean
4513 * Description : In-Situ-Eliminate all occurances of substring in
4517 * 1 : string = string to clean
4518 * 2 : substring = substring to eliminate
4520 * Returns : Number of eliminations
4522 *********************************************************************/
4523 int strclean(char *string, const char *substring)
4529 len = strlen(substring);
4531 while((pos = strstr(string, substring)) != NULL)
4538 while (*p++ != '\0');
4545 #endif /* def FEATURE_FORCE_LOAD */
4548 /*********************************************************************
4550 * Function : parse_header_time
4552 * Description : Parses time formats used in HTTP header strings
4553 * to get the numerical respresentation.
4556 * 1 : header_time = HTTP header time as string.
4557 * 2 : result = storage for header_time in seconds
4559 * Returns : JB_ERR_OK if the time format was recognized, or
4560 * JB_ERR_PARSE otherwise.
4562 *********************************************************************/
4563 static jb_err parse_header_time(const char *header_time, time_t *result)
4568 * Zero out gmt to prevent time zone offsets.
4570 * While this is only necessary on some platforms
4571 * (mingw32 for example), I don't know how to
4572 * detect these automatically and doing it everywhere
4575 memset(&gmt, 0, sizeof(gmt));
4577 /* Tue, 02 Jun 2037 20:00:00 */
4578 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4579 /* Tue, 02-Jun-2037 20:00:00 */
4580 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4581 /* Tue, 02-Jun-37 20:00:00 */
4582 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4583 /* Tuesday, 02-Jun-2037 20:00:00 */
4584 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4585 /* Tuesday Jun 02 20:00:00 2037 */
4586 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4588 return JB_ERR_PARSE;
4591 *result = timegm(&gmt);
4598 /*********************************************************************
4600 * Function : get_destination_from_headers
4602 * Description : Parse the "Host:" header to get the request's destination.
4603 * Only needed if the client's request was forcefully
4604 * redirected into Privoxy.
4606 * Code mainly copied from client_host() which is currently
4607 * run too late for this purpose.
4610 * 1 : headers = List of headers (one of them hopefully being
4611 * the "Host:" header)
4612 * 2 : http = storage for the result (host, port and hostport).
4614 * Returns : JB_ERR_MEMORY in case of memory problems,
4615 * JB_ERR_PARSE if the host header couldn't be found,
4616 * JB_ERR_OK otherwise.
4618 *********************************************************************/
4619 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4625 host = get_header_value(headers, "Host:");
4629 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4630 return JB_ERR_PARSE;
4633 if (NULL == (p = strdup((host))))
4635 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4636 return JB_ERR_MEMORY;
4639 if (NULL == (q = strdup(p)))
4642 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4643 return JB_ERR_MEMORY;
4646 freez(http->hostport);
4650 q = strchr(http->host, ':');
4653 /* Terminate hostname and evaluate port string */
4655 http->port = atoi(q);
4659 http->port = http->ssl ? 443 : 80;
4662 /* Rebuild request URL */
4664 http->url = strdup(http->ssl ? "https://" : "http://");
4665 string_append(&http->url, http->hostport);
4666 string_append(&http->url, http->path);
4667 if (http->url == NULL)
4669 return JB_ERR_MEMORY;
4672 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4680 /*********************************************************************
4682 * Function : create_forged_referrer
4684 * Description : Helper for client_referrer to forge a referer as
4685 * 'http://[hostname:port/' to fool stupid
4686 * checks for in-site links
4689 * 1 : header = Pointer to header pointer
4690 * 2 : hostport = Host and optionally port as string
4692 * Returns : JB_ERR_OK in case of success, or
4693 * JB_ERR_MEMORY in case of memory problems.
4695 *********************************************************************/
4696 static jb_err create_forged_referrer(char **header, const char *hostport)
4698 assert(NULL == *header);
4700 *header = strdup("Referer: http://");
4701 string_append(header, hostport);
4702 string_append(header, "/");
4704 if (NULL == *header)
4706 return JB_ERR_MEMORY;
4709 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4716 /*********************************************************************
4718 * Function : create_fake_referrer
4720 * Description : Helper for client_referrer to create a fake referrer
4721 * based on a string supplied by the user.
4724 * 1 : header = Pointer to header pointer
4725 * 2 : hosthost = Referrer to fake
4727 * Returns : JB_ERR_OK in case of success, or
4728 * JB_ERR_MEMORY in case of memory problems.
4730 *********************************************************************/
4731 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4733 assert(NULL == *header);
4735 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4737 log_error(LOG_LEVEL_HEADER,
4738 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4740 *header = strdup("Referer: ");
4741 string_append(header, fake_referrer);
4743 if (NULL == *header)
4745 return JB_ERR_MEMORY;
4748 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4755 /*********************************************************************
4757 * Function : handle_conditional_hide_referrer_parameter
4759 * Description : Helper for client_referrer to crunch or forge
4760 * the referrer header if the host has changed.
4763 * 1 : header = Pointer to header pointer
4764 * 2 : host = The target host (may include the port)
4765 * 3 : parameter_conditional_block = Boolean to signal
4766 * if we're in conditional-block mode. If not set,
4767 * we're in conditional-forge mode.
4769 * Returns : JB_ERR_OK in case of success, or
4770 * JB_ERR_MEMORY in case of memory problems.
4772 *********************************************************************/
4773 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4774 const char *host, const int parameter_conditional_block)
4776 char *referer = strdup(*header);
4777 const size_t hostlenght = strlen(host);
4778 const char *referer_url = NULL;
4780 if (NULL == referer)
4783 return JB_ERR_MEMORY;
4786 /* referer begins with 'Referer: http[s]://' */
4787 if ((hostlenght+17) < strlen(referer))
4790 * Shorten referer to make sure the referer is blocked
4791 * if www.example.org/www.example.com-shall-see-the-referer/
4792 * links to www.example.com/
4794 referer[hostlenght+17] = '\0';
4796 referer_url = strstr(referer, "http://");
4797 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4799 /* Host has changed, Referer is invalid or a https URL. */
4800 if (parameter_conditional_block)
4802 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4809 return create_forged_referrer(header, host);
4819 /*********************************************************************
4821 * Function : get_appropiate_connection_header
4823 * Description : Returns an appropiate Connection header
4824 * depending on whether or not we try to keep
4825 * the connection to the server alive.
4828 * 1 : csp = Current client state (buffers, headers, etc...)
4830 * Returns : Pointer to statically allocated header buffer.
4832 *********************************************************************/
4833 static const char *get_appropiate_connection_header(const struct client_state *csp)
4835 static const char connection_keep_alive[] = "Connection: keep-alive";
4836 static const char connection_close[] = "Connection: close";
4838 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4839 && (csp->http->ssl == 0))
4841 return connection_keep_alive;
4843 return connection_close;