1 const char parsers_rcs[] = "$Id: parsers.c,v 1.148 2008/11/16 12:43:49 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2008 the SourceForge
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.148 2008/11/16 12:43:49 fabiankeil
48 * Turn keep-alive support into a runtime feature
49 * that is disabled by setting keep-alive-timeout
50 * to a negative value.
52 * Revision 1.147 2008/11/04 17:20:31 fabiankeil
53 * HTTP/1.1 responses without Connection
54 * header imply keep-alive. Act accordingly.
56 * Revision 1.146 2008/10/12 16:46:35 fabiankeil
57 * Remove obsolete warning about delayed delivery with chunked
58 * transfer encoding and FEATURE_CONNECTION_KEEP_ALIVE enabled.
60 * Revision 1.145 2008/10/09 18:21:41 fabiankeil
61 * Flush work-in-progress changes to keep outgoing connections
62 * alive where possible. Incomplete and mostly #ifdef'd out.
64 * Revision 1.144 2008/09/21 13:59:33 fabiankeil
65 * Treat unknown change-x-forwarded-for parameters as fatal errors.
67 * Revision 1.143 2008/09/21 13:36:52 fabiankeil
68 * If change-x-forwarded-for{add} is used and the client
69 * sends multiple X-Forwarded-For headers, append the client's
70 * IP address to each one of them. "Traditionally" we would
71 * lose all but the last one.
73 * Revision 1.142 2008/09/20 10:04:33 fabiankeil
74 * Remove hide-forwarded-for-headers action which has
75 * been obsoleted by change-x-forwarded-for{block}.
77 * Revision 1.141 2008/09/19 15:26:28 fabiankeil
78 * Add change-x-forwarded-for{} action to block or add
79 * X-Forwarded-For headers. Mostly based on code removed
82 * Revision 1.140 2008/09/12 17:51:43 fabiankeil
83 * - A few style fixes.
84 * - Remove a pointless cast.
86 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
87 * Prepare for critical sections on Windows by adding a
88 * layer of indirection before the pthread mutex functions.
90 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
91 * Remove FEATURE_COOKIE_JAR.
93 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
94 * Remove questionable micro-optimizations
95 * whose usefulness has never been measured.
97 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
98 * s@Insufficent@Insufficient@
100 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
101 * The whole point of strclean() is to modify the
102 * first parameter, so don't mark it immutable,
103 * even though the compiler lets us get away with it.
105 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
106 * As the wafer actions are gone, we can stop including encode.h.
108 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
109 * Ditch cast from (char **) to (char **).
111 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
112 * Streamline sed()'s prototype and declare
113 * the header parse and add structures static.
115 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
116 * Factor update_server_headers() out of sed(), ditch the
117 * first_run hack and make server_patterns_light static.
119 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
120 * Wrap memmove() calls in string_move()
121 * to document the purpose in one place.
123 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
124 * Normalize linear header white space.
126 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
127 * If a header is split across multiple lines,
128 * merge them to a single line before parsing them.
130 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
131 * Don't provide get_header() with the whole client state
132 * structure when it only needs access to csp->iob.
134 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
135 * Change content_filters_enabled()'s parameter from
136 * csp->action to action so it can be also used in the
137 * CGI code. Don't bother checking if there are filters
138 * loaded, as that's somewhat besides the point.
140 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
141 * Provide get_http_time() with the buffer size so it doesn't
142 * have to blindly assume that the buffer is big enough.
144 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
145 * Don't pass the whole csp structure to flush_socket()
146 * when it only needs a file descriptor and a buffer.
148 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
149 * Remove send-wafer and send-vanilla-wafer actions.
151 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
152 * Remove inspect-jpegs action.
154 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
155 * Let client_range() also handle Request-Range headers
156 * which apparently are still supported by many servers.
158 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
159 * Improve the warning messages that get logged if the action files
160 * "enable" filters but no filters of that type have been loaded.
162 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
163 * In server_content_type():
164 * - Don't require leading white space when detecting image content types.
165 * - Change '... not replaced ...' message to sound less crazy if the text
166 * type actually is 'text/plain'.
167 * - Mark the 'text/plain == binary data' assumption for removal.
168 * - Remove a bunch of trailing white space.
170 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
171 * Minor server_content_disposition() changes:
172 * - Don't regenerate the header name all lower-case.
173 * - Some white space fixes.
174 * - Remove useless log message in case of ENOMEM.
176 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
177 * Garbage-collect the code to add a X-Forwarded-For
178 * header as it seems to be mostly used by accident.
180 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
181 * Fix a crash on mingw32 with some Last Modified times in the future.
183 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
184 * Remove a "can't happen" error block which, over
185 * time, mutated into a "guaranteed to happen" block.
187 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
188 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
189 * - Use shiny new content_filters_enabled() in client_range().
191 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
192 * I forgot about Poland.
194 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
195 * Remove Range and If-Range headers if content filtering is enabled.
197 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
198 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
199 * client_cookie_adder() to make sure send-vanilla-wafer can be
200 * controlled through tags (and thus regression-tested).
202 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
203 * - Remove "scanning headers for" log message again.
204 * - Some more whitespace fixes.
206 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
207 * Refactor client_referrer() and add conditional-forge parameter.
209 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
210 * A bunch of whitespace fixes, pointy hat to me.
212 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
213 * Fix possible memory corruption in server_http, make sure it's not
214 * executed for ordinary server headers and mark some problems for later.
216 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
217 * Let content-type-overwrite{} honour force-text-mode again.
219 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
220 * - Add prototpyes for the header parsers and make them static.
221 * - Comment out client_accept_encoding_adder() which isn't used right now.
223 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
224 * Move the ACTION_FORCE_TEXT_MODE check out of
225 * server_content_type(). Signal other functions
226 * whether or not a content type has been declared.
227 * Part of the fix for BR#1750917.
229 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
230 * Change sed() to return a jb_err in preparation for forward-override{}.
232 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
233 * Adjust "X-Filter: No" to disable dedicated header filters.
235 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
236 * Streamline client_cookie_adder().
238 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
239 * Make sure filters with dynamic jobs actually use them.
241 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
242 * - Introduce dynamic pcrs jobs that can resolve variables.
243 * - Remove unnecessary update_action_bits_for_all_tags() call.
245 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
246 * - Make tagging based on tags set by earlier taggers
247 * of the same kind possible.
248 * - Log whether or not new tags cause action bits updates
249 * (in which case a matching tag-pattern section exists).
250 * - Log if the user tries to set a tag that is already set.
252 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
253 * Introduce tags as alternative way to specify which
254 * actions apply to a request. At the moment tags can be
255 * created based on client and server headers.
257 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
258 * Log a warning if the content is compressed, filtering is
259 * enabled and Privoxy was compiled without zlib support.
262 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
263 * - Fix warnings when compiled with glibc.
264 * - Don't use crumble() for cookie crunching.
265 * - Move cookie time parsing into parse_header_time().
266 * - Let parse_header_time() return a jb_err code
267 * instead of a pointer that can only be used to
268 * check for NULL anyway.
270 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
271 * - Add better protection against malicious gzip headers.
272 * - Stop logging the first hundred bytes of decompressed content.
273 * It looks like it's working and there is always debug 16.
274 * - Log the content size after decompression in decompress_iob()
275 * instead of pcrs_filter_response().
277 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
278 * - Use dedicated header filter actions instead of abusing "filter".
279 * Replace "filter-client-headers" and "filter-client-headers"
280 * with "server-header-filter" and "client-header-filter".
281 * - Remove filter_client_header() and filter_client_header(),
282 * filter_header() now checks the shiny new
283 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
285 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
286 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
287 * - Handle "Cookie:" and "Connection:" headers a bit smarter
288 * (don't crunch them just to recreate them later on).
289 * - Add another non-standard time format for the cookie
290 * expiration date detection.
291 * - Fix a valgrind warning.
293 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
294 * Improve cookie expiration date detection.
296 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
297 * Don't run server_content_length() the first time
298 * sed() parses server headers; only adjust the
299 * Content-Length header if the page was modified.
301 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
302 * Fix log messages regarding the cookie time format
303 * (cookie and request URL were mixed up).
305 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
306 * - Let decompress_iob()
307 * - not corrupt the content if decompression fails
308 * early. (the first byte(s) were lost).
309 * - use pointer arithmetics with defined outcome for
311 * - Use a different kludge to remember a failed decompression.
313 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
314 * Search for Max-Forwards headers case-insensitive,
315 * don't generate the "501 unsupported" message for invalid
316 * Max-Forwards values and don't increase negative ones.
318 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
319 * - Let server_set_cookie() check the expiration date
320 * of cookies and don't touch the ones that are already
321 * expired. Fixes problems with low quality web applications
322 * as described in BR 932612.
324 * - Adjust comment in client_max_forwards to reality;
325 * remove invalid Max-Forwards headers.
327 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
328 * Stop filter_header() from unintentionally removing
329 * empty header lines that were enlisted by the continue
332 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
333 * - Repeat the request URL before logging any headers.
334 * Makes reading the log easier in case of simultaneous requests.
335 * - If there are more than one Content-Type headers in one request,
336 * use the first one and remove the others.
337 * - Remove "newval" variable in server_content_type().
338 * It's only used once.
340 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
341 * Correct a cast, check inflateEnd() exit code
342 * to see if we have to, replace sprintf calls
345 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
346 * Integrate a modified version of Wil Mahan's
347 * zlib patch (PR #895531).
349 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
350 * Skip empty filter files in filter_header()
351 * but don't ignore the ones that come afterwards.
352 * Fixes BR 1619208, this time for real.
354 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
355 * Reverted parts of my last commit
356 * to keep error handling working.
358 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
359 * Fixed gcc43 conversion warnings.
361 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
362 * Bringing back the "useless" localtime() call
363 * I removed in revision 1.67. On some platforms
364 * it's necessary to prevent time zone offsets.
366 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
367 * Rebuild request URL in get_destination_from_headers()
368 * to make sure redirect{pcrs command} works as expected
369 * for intercepted requests.
371 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
372 * Added get_destination_from_headers().
374 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
375 * Make pthread mutex locking more generic. Instead of
376 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
377 * and use mutex locking unless there is an _r function
378 * available. Better safe than sorry.
380 * Fixes "./configure --disable-pthread" and should result
381 * in less threading-related problems on pthread-using platforms,
382 * but it still doesn't fix BR#1122404.
384 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
385 * The special header "X-Filter: No" now disables
386 * header filtering as well.
388 * Revision 1.73 2006/09/23 13:26:38 roro
389 * Replace TABs by spaces in source code.
391 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
392 * Don't print a log message every time filter_headers is
393 * entered or left. It only creates noise without any real
396 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
397 * Fix +hide-if-modified-since{-n}.
399 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
400 * Have hide-if-modified-since interpret the random
401 * range value as minutes instead of hours. Allows
402 * more fine-grained configuration.
404 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
405 * Always have parse_header_time return a pointer
406 * that actual makes sense, even though we currently
407 * only need it to detect problems.
409 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
410 * Added config option enable-remote-http-toggle
411 * to specify if Privoxy should recognize special
412 * headers (currently only X-Filter) to change its
413 * behaviour. Disabled by default.
415 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
416 * After filtering de-chunked instances, remove
417 * "Transfer-Encoding" header entirely instead of changing
418 * it to "Transfer-Encoding: identity", which is invalid.
419 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
421 * Don't use localtime in parse_header_time. An empty time struct
422 * is good enough, it gets overwritten by strptime anyway.
424 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
425 * Use gmtime_r if available, fallback to gmtime with mutex
426 * protection for MacOSX and use vanilla gmtime for the rest.
428 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
429 * Changed client_referrer to use the right type (size_t) for
430 * hostlenght and to shorten the temporary referrer string with
431 * '\0' instead of adding a useless line break.
433 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
434 * - Back to timegm() using GnuPG's replacement if necessary.
435 * Using mktime() and localtime() could add a on hour offset if
436 * the randomize factor was big enough to lead to a summer/wintertime
439 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
441 * - Moved randomization code into pick_from_range().
443 * - Changed parse_header_time definition.
444 * time_t isn't guaranteed to be signed and
445 * if it isn't, -1 isn't available as error code.
446 * Changed some variable types in client_if_modified_since()
447 * because of the same reason.
449 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
450 * OS/2 compilation compatibility fixups
452 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
453 * Changed include from strptime.c to strptime.h
455 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
456 * Split filter-headers{} into filter-client-headers{}
457 * and filter-server-headers{}.
458 * Added parse_header_time() to share some code.
459 * Replaced timegm() with mktime().
461 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
462 * Windows service integration
464 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
465 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
467 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
468 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
469 * with what was really the latest development (the v_3_0_branch branch)
471 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
472 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
474 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
475 * Add the ability to check jpeg images for invalid
476 * lengths of comment blocks. Defensive strategy
477 * against the exploit:
478 * Microsoft Security Bulletin MS04-028
479 * Buffer Overrun in JPEG Processing (GDI+) Could
480 * Allow Code Execution (833987)
481 * Enabled with +inspect-jpegs in actions files.
483 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
484 * Excluded text/plain objects from filtering. This fixes a
485 * couple of client-crashing, download corruption and
486 * Privoxy performance issues, whose root cause lies in
487 * web servers labelling content of unknown type as text/plain.
489 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
490 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
492 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
493 * Completing the previous change
495 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
496 * Added temporary workaround for bug in PHP < 4.2.3
498 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
499 * 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.
501 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
502 * Fix typo: supressed -> suppressed
504 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
505 * Improved cookie logging
507 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
508 * Added basic support for OPTIONS and TRACE HTTP methods:
509 * - New parser function client_max_forwards which decrements
510 * the Max-Forwards HTTP header field of OPTIONS and TRACE
511 * requests by one before forwarding
512 * - New parser function client_host which extracts the host
513 * and port information from the HTTP header field if the
514 * request URI was not absolute
515 * - Don't crumble and re-add the Host: header, but only generate
516 * and append if missing
518 * Revision 1.56 2002/05/12 15:34:22 jongfoster
519 * Fixing typo in a comment
521 * Revision 1.55 2002/05/08 16:01:07 oes
522 * Optimized add_to_iob:
523 * - Use realloc instead of malloc(), memcpy(), free()
524 * - Expand to powers of two if possible, to get
525 * O(log n) reallocs instead of O(n).
526 * - Moved check for buffer limit here from chat
527 * - Report failure via returncode
529 * Revision 1.54 2002/04/02 15:03:16 oes
530 * Tiny code cosmetics
532 * Revision 1.53 2002/03/26 22:29:55 swa
533 * we have a new homepage!
535 * Revision 1.52 2002/03/24 13:25:43 swa
536 * name change related issues
538 * Revision 1.51 2002/03/13 00:27:05 jongfoster
541 * Revision 1.50 2002/03/12 01:45:35 oes
542 * More verbose logging
544 * Revision 1.49 2002/03/09 20:03:52 jongfoster
545 * - Making various functions return int rather than size_t.
546 * (Undoing a recent change). Since size_t is unsigned on
547 * Windows, functions like read_socket that return -1 on
548 * error cannot return a size_t.
550 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
551 * crashes, and also frequently caused JB to jump to 100%
552 * CPU and stay there. (Because it thought it had just
553 * read ((unsigned)-1) == 4Gb of data...)
555 * - The signature of write_socket has changed, it now simply
556 * returns success=0/failure=nonzero.
558 * - Trying to get rid of a few warnings --with-debug on
559 * Windows, I've introduced a new type "jb_socket". This is
560 * used for the socket file descriptors. On Windows, this
561 * is SOCKET (a typedef for unsigned). Everywhere else, it's
562 * an int. The error value can't be -1 any more, so it's
563 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
564 * Windows it maps to the #define INVALID_SOCKET.)
566 * - The signature of bind_port has changed.
568 * Revision 1.48 2002/03/07 03:46:53 oes
569 * Fixed compiler warnings etc
571 * Revision 1.47 2002/02/20 23:15:13 jongfoster
572 * Parsing functions now handle out-of-memory gracefully by returning
575 * Revision 1.46 2002/01/17 21:03:47 jongfoster
576 * Moving all our URL and URL pattern parsing code to urlmatch.c.
578 * Revision 1.45 2002/01/09 14:33:03 oes
579 * Added support for localtime_r.
581 * Revision 1.44 2001/12/14 01:22:54 steudten
582 * Remove 'user:pass@' from 'proto://user:pass@host' for the
583 * new added header 'Host: ..'. (See Req ID 491818)
585 * Revision 1.43 2001/11/23 00:26:38 jongfoster
586 * Fixing two really stupid errors in my previous commit
588 * Revision 1.42 2001/11/22 21:59:30 jongfoster
589 * Adding code to handle +no-cookies-keep
591 * Revision 1.41 2001/11/05 23:43:05 steudten
592 * Add time+date to log files.
594 * Revision 1.40 2001/10/26 20:13:09 jongfoster
595 * ctype.h is needed in Windows, too.
597 * Revision 1.39 2001/10/26 17:40:04 oes
598 * Introduced get_header_value()
599 * Removed http->user_agent, csp->referrer and csp->accept_types
600 * Removed client_accept()
602 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
603 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
604 * threads to call select() simultaneously. So, it's time to do a real, live,
605 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
606 * (native). Both versions will work, but using __OS2__ offers multi-threading.
608 * Revision 1.37 2001/10/23 21:36:02 jongfoster
609 * Documenting sed()'s error behaviou (doc change only)
611 * Revision 1.36 2001/10/13 12:51:51 joergs
612 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
613 * force-load), instead crumble Host: and add it (again) in client_host_adder
614 * (in case we get a HTTP/1.0 request without Host: header and forward it to
615 * a HTTP/1.1 server/proxy).
617 * Revision 1.35 2001/10/09 22:39:21 jongfoster
618 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
621 * Revision 1.34 2001/10/07 18:50:55 oes
622 * Added server_content_encoding, renamed server_transfer_encoding
624 * Revision 1.33 2001/10/07 18:04:49 oes
625 * Changed server_http11 to server_http and its pattern to "HTTP".
626 * Additional functionality: it now saves the HTTP status into
627 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
629 * Revision 1.32 2001/10/07 15:43:28 oes
630 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
631 * client_te and client_accept_encoding_adder, triggered by the new
632 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
633 * changed to allow only identity and chunked, and the TE header is
634 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
636 * parse_http_request no longer does anything than parsing. The rewriting
637 * of http->cmd and version mangling are gone. It now also recognizes
638 * the put and delete methods and saves the url in http->url. Removed
641 * renamed content_type and content_length to have the server_ prefix
643 * server_content_type now only works if csp->content_type != CT_TABOO
645 * added server_transfer_encoding, which
646 * - Sets CT_TABOO to prohibit filtering if encoding compresses
647 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
648 * - Change from "chunked" to "identity" if body was chunked
649 * but has been de-chunked for filtering.
651 * added server_content_md5 which crunches any Content-MD5 headers
652 * if the body was modified.
654 * made server_http11 conditional on +downgrade action
656 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
658 * Revision 1.31 2001/10/05 14:25:02 oes
659 * Crumble Keep-Alive from Server
661 * Revision 1.30 2001/09/29 12:56:03 joergs
662 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
664 * Revision 1.29 2001/09/24 21:09:24 jongfoster
665 * Fixing 2 memory leaks that Guy spotted, where the paramater to
666 * enlist() was not being free()d.
668 * Revision 1.28 2001/09/22 16:32:28 jongfoster
669 * Removing unused #includes.
671 * Revision 1.27 2001/09/20 15:45:25 steudten
673 * add casting from size_t to int for printf()
674 * remove local variable shadow s2
676 * Revision 1.26 2001/09/16 17:05:14 jongfoster
677 * Removing unused #include showarg.h
679 * Revision 1.25 2001/09/16 13:21:27 jongfoster
680 * Changes to use new list functions.
682 * Revision 1.24 2001/09/13 23:05:50 jongfoster
683 * Changing the string paramater to the header parsers a "const".
685 * Revision 1.23 2001/09/12 18:08:19 steudten
687 * In parse_http_request() header rewriting miss the host value, so
688 * from http://www.mydomain.com the result was just " / " not
689 * http://www.mydomain.com/ in case we forward.
691 * Revision 1.22 2001/09/10 10:58:53 oes
692 * Silenced compiler warnings
694 * Revision 1.21 2001/07/31 14:46:00 oes
695 * - Persistant connections now suppressed
696 * - sed() no longer appends empty header to csp->headers
698 * Revision 1.20 2001/07/30 22:08:36 jongfoster
699 * Tidying up #defines:
700 * - All feature #defines are now of the form FEATURE_xxx
701 * - Permanently turned off WIN_GUI_EDIT
702 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
704 * Revision 1.19 2001/07/25 17:21:54 oes
705 * client_uagent now saves copy of User-Agent: header value
707 * Revision 1.18 2001/07/13 14:02:46 oes
708 * - Included fix to repair broken HTTP requests that
709 * don't contain a path, not even '/'.
710 * - Removed all #ifdef PCRS
711 * - content_type now always inspected and classified as
712 * text, gif or other.
713 * - formatting / comments
715 * Revision 1.17 2001/06/29 21:45:41 oes
716 * Indentation, CRLF->LF, Tab-> Space
718 * Revision 1.16 2001/06/29 13:32:42 oes
720 * - Adapted free_http_request
721 * - Removed logentry from cancelled commit
723 * Revision 1.15 2001/06/03 19:12:38 oes
724 * deleted const struct interceptors
726 * Revision 1.14 2001/06/01 18:49:17 jongfoster
727 * Replaced "list_share" with "list" - the tiny memory gain was not
728 * worth the extra complexity.
730 * Revision 1.13 2001/05/31 21:30:33 jongfoster
731 * Removed list code - it's now in list.[ch]
732 * Renamed "permission" to "action", and changed many features
733 * to use the actions file rather than the global config.
735 * Revision 1.12 2001/05/31 17:33:13 oes
739 * Revision 1.11 2001/05/29 20:11:19 joergs
740 * '/ * inside comment' warning removed.
742 * Revision 1.10 2001/05/29 09:50:24 jongfoster
743 * Unified blocklist/imagelist/permissionslist.
744 * File format is still under discussion, but the internal changes
747 * Also modified interceptor behaviour:
748 * - We now intercept all URLs beginning with one of the following
749 * prefixes (and *only* these prefixes):
751 * * http://ijbswa.sf.net/config/
752 * * http://ijbswa.sourceforge.net/config/
753 * - New interceptors "home page" - go to http://i.j.b/ to see it.
754 * - Internal changes so that intercepted and fast redirect pages
755 * are not replaced with an image.
756 * - Interceptors now have the option to send a binary page direct
757 * to the client. (i.e. ijb-send-banner uses this)
758 * - Implemented show-url-info interceptor. (Which is why I needed
759 * the above interceptors changes - a typical URL is
760 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
761 * The previous mechanism would not have intercepted that, and
762 * if it had been intercepted then it then it would have replaced
765 * Revision 1.9 2001/05/28 17:26:33 jongfoster
766 * Fixing segfault if last header was crunched.
767 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
768 * can use the cross-platform sprintf() instead.)
770 * Revision 1.8 2001/05/27 22:17:04 oes
772 * - re_process_buffer no longer writes the modified buffer
773 * to the client, which was very ugly. It now returns the
774 * buffer, which it is then written by chat.
776 * - content_length now adjusts the Content-Length: header
777 * for modified documents rather than crunch()ing it.
778 * (Length info in csp->content_length, which is 0 for
779 * unmodified documents)
781 * - For this to work, sed() is called twice when filtering.
783 * Revision 1.7 2001/05/27 13:19:06 oes
784 * Patched Joergs solution for the content-length in.
786 * Revision 1.6 2001/05/26 13:39:32 jongfoster
787 * Only crunches Content-Length header if applying RE filtering.
788 * Without this fix, Microsoft Windows Update wouldn't work.
790 * Revision 1.5 2001/05/26 00:28:36 jongfoster
791 * Automatic reloading of config file.
792 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
793 * Most of the global variables have been moved to a new
794 * struct configuration_spec, accessed through csp->config->globalname
795 * Most of the globals remaining are used by the Win32 GUI.
797 * Revision 1.4 2001/05/22 18:46:04 oes
799 * - Enabled filtering banners by size rather than URL
800 * by adding patterns that replace all standard banner
801 * sizes with the "Junkbuster" gif to the re_filterfile
803 * - Enabled filtering WebBugs by providing a pattern
804 * which kills all 1x1 images
806 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
807 * which is selected by the (nonstandard and therefore
808 * capital) letter 'U' in the option string.
809 * It causes the quantifiers to be ungreedy by default.
810 * Appending a ? turns back to greedy (!).
812 * - Added a new interceptor ijb-send-banner, which
813 * sends back the "Junkbuster" gif. Without imagelist or
814 * MSIE detection support, or if tinygif = 1, or the
815 * URL isn't recognized as an imageurl, a lame HTML
816 * explanation is sent instead.
818 * - Added new feature, which permits blocking remote
819 * script redirects and firing back a local redirect
821 * The feature is conditionally compiled, i.e. it
822 * can be disabled with --disable-fast-redirects,
823 * plus it must be activated by a "fast-redirects"
824 * line in the config file, has its own log level
825 * and of course wants to be displayed by show-proxy-args
826 * Note: Boy, all the #ifdefs in 1001 locations and
827 * all the fumbling with configure.in and acconfig.h
828 * were *way* more work than the feature itself :-(
830 * - Because a generic redirect template was needed for
831 * this, tinygif = 3 now uses the same.
833 * - Moved GIFs, and other static HTTP response templates
838 * - Removed some >400 CRs again (Jon, you really worked
841 * Revision 1.3 2001/05/20 01:21:20 jongfoster
842 * Version 2.9.4 checkin.
843 * - Merged popupfile and cookiefile, and added control over PCRS
844 * filtering, in new "permissionsfile".
845 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
846 * file error you now get a message box (in the Win32 GUI) rather
847 * than the program exiting with no explanation.
848 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
850 * - Removed tabs from "config"
851 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
852 * - Bumped up version number.
854 * Revision 1.2 2001/05/17 23:02:36 oes
855 * - Made referrer option accept 'L' as a substitute for '§'
857 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
858 * Initial import of version 2.9.3 source tree
861 *********************************************************************/
868 #include <sys/types.h>
878 * Convince GNU's libc to provide a strptime prototype.
881 #endif /*__GLIBC__ */
888 #if !defined(_WIN32) && !defined(__OS2__)
894 #ifdef FEATURE_PTHREAD
896 /* jcc.h is for mutex semapores only */
897 #endif /* def FEATURE_PTHREAD */
902 #include "jbsockets.h"
903 #include "miscutil.h"
908 #ifndef HAVE_STRPTIME
909 #include "strptime.h"
912 const char parsers_h_rcs[] = PARSERS_H_VERSION;
914 /* Fix a problem with Solaris. There should be no effect on other
916 * Solaris's isspace() is a macro which uses its argument directly
917 * as an array index. Therefore we need to make sure that high-bit
918 * characters generate +ve values, and ideally we also want to make
919 * the argument match the declared parameter type of "int".
921 * Why did they write a character function that can't take a simple
922 * "char" argument? Doh!
924 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
925 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
927 static char *get_header_line(struct iob *iob);
928 static jb_err scan_headers(struct client_state *csp);
929 static jb_err header_tagger(struct client_state *csp, char *header);
930 static jb_err parse_header_time(const char *header_time, time_t *result);
932 static jb_err crumble (struct client_state *csp, char **header);
933 static jb_err filter_header (struct client_state *csp, char **header);
934 static jb_err client_connection (struct client_state *csp, char **header);
935 static jb_err client_referrer (struct client_state *csp, char **header);
936 static jb_err client_uagent (struct client_state *csp, char **header);
937 static jb_err client_ua (struct client_state *csp, char **header);
938 static jb_err client_from (struct client_state *csp, char **header);
939 static jb_err client_send_cookie (struct client_state *csp, char **header);
940 static jb_err client_x_forwarded (struct client_state *csp, char **header);
941 static jb_err client_accept_encoding (struct client_state *csp, char **header);
942 static jb_err client_te (struct client_state *csp, char **header);
943 static jb_err client_max_forwards (struct client_state *csp, char **header);
944 static jb_err client_host (struct client_state *csp, char **header);
945 static jb_err client_if_modified_since (struct client_state *csp, char **header);
946 static jb_err client_accept_language (struct client_state *csp, char **header);
947 static jb_err client_if_none_match (struct client_state *csp, char **header);
948 static jb_err crunch_client_header (struct client_state *csp, char **header);
949 static jb_err client_x_filter (struct client_state *csp, char **header);
950 static jb_err client_range (struct client_state *csp, char **header);
951 static jb_err server_set_cookie (struct client_state *csp, char **header);
952 static jb_err server_connection (struct client_state *csp, char **header);
953 static jb_err server_content_type (struct client_state *csp, char **header);
954 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
955 static jb_err server_content_md5 (struct client_state *csp, char **header);
956 static jb_err server_content_encoding (struct client_state *csp, char **header);
957 static jb_err server_transfer_coding (struct client_state *csp, char **header);
958 static jb_err server_http (struct client_state *csp, char **header);
959 static jb_err crunch_server_header (struct client_state *csp, char **header);
960 static jb_err server_last_modified (struct client_state *csp, char **header);
961 static jb_err server_content_disposition(struct client_state *csp, char **header);
963 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
964 static jb_err server_save_content_length(struct client_state *csp, char **header);
965 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
967 static jb_err client_host_adder (struct client_state *csp);
968 static jb_err client_xtra_adder (struct client_state *csp);
969 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
970 static jb_err client_connection_header_adder(struct client_state *csp);
971 static jb_err server_connection_close_adder(struct client_state *csp);
973 static jb_err create_forged_referrer(char **header, const char *hostport);
974 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
975 static jb_err handle_conditional_hide_referrer_parameter(char **header,
976 const char *host, const int parameter_conditional_block);
977 static const char *get_appropiate_connection_header(const struct client_state *csp);
980 * List of functions to run on a list of headers.
984 /** The header prefix to match */
987 /** The length of the prefix to match */
990 /** The function to apply to this line */
991 const parser_func_ptr parser;
994 static const struct parsers client_patterns[] = {
995 { "referer:", 8, client_referrer },
996 { "user-agent:", 11, client_uagent },
997 { "ua-", 3, client_ua },
998 { "from:", 5, client_from },
999 { "cookie:", 7, client_send_cookie },
1000 { "x-forwarded-for:", 16, client_x_forwarded },
1001 { "Accept-Encoding:", 16, client_accept_encoding },
1002 { "TE:", 3, client_te },
1003 { "Host:", 5, client_host },
1004 { "if-modified-since:", 18, client_if_modified_since },
1005 { "Keep-Alive:", 11, crumble },
1006 { "connection:", 11, client_connection },
1007 { "proxy-connection:", 17, crumble },
1008 { "max-forwards:", 13, client_max_forwards },
1009 { "Accept-Language:", 16, client_accept_language },
1010 { "if-none-match:", 14, client_if_none_match },
1011 { "Range:", 6, client_range },
1012 { "Request-Range:", 14, client_range },
1013 { "If-Range:", 9, client_range },
1014 { "X-Filter:", 9, client_x_filter },
1015 { "*", 0, crunch_client_header },
1016 { "*", 0, filter_header },
1020 static const struct parsers server_patterns[] = {
1021 { "HTTP/", 5, server_http },
1022 { "set-cookie:", 11, server_set_cookie },
1023 { "connection:", 11, server_connection },
1024 { "Content-Type:", 13, server_content_type },
1025 { "Content-MD5:", 12, server_content_md5 },
1026 { "Content-Encoding:", 17, server_content_encoding },
1027 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1028 { "Content-Length:", 15, server_save_content_length },
1029 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1030 { "Transfer-Encoding:", 18, server_transfer_coding },
1031 { "Keep-Alive:", 11, crumble },
1032 { "content-disposition:", 20, server_content_disposition },
1033 { "Last-Modified:", 14, server_last_modified },
1034 { "*", 0, crunch_server_header },
1035 { "*", 0, filter_header },
1039 static const add_header_func_ptr add_client_headers[] = {
1041 client_x_forwarded_for_adder,
1043 /* Temporarily disabled: client_accept_encoding_adder, */
1044 client_connection_header_adder,
1048 static const add_header_func_ptr add_server_headers[] = {
1049 server_connection_close_adder,
1053 /*********************************************************************
1055 * Function : flush_socket
1057 * Description : Write any pending "buffered" content.
1060 * 1 : fd = file descriptor of the socket to read
1061 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1063 * Returns : On success, the number of bytes written are returned (zero
1064 * indicates nothing was written). On error, -1 is returned,
1065 * and errno is set appropriately. If count is zero and the
1066 * file descriptor refers to a regular file, 0 will be
1067 * returned without causing any other effect. For a special
1068 * file, the results are not portable.
1070 *********************************************************************/
1071 int flush_socket(jb_socket fd, struct iob *iob)
1073 int len = iob->eod - iob->cur;
1080 if (write_socket(fd, iob->cur, (size_t)len))
1084 iob->eod = iob->cur = iob->buf;
1090 /*********************************************************************
1092 * Function : add_to_iob
1094 * Description : Add content to the buffered page, expanding the
1095 * buffer if necessary.
1098 * 1 : csp = Current client state (buffers, headers, etc...)
1099 * 2 : buf = holds the content to be added to the page
1100 * 3 : n = number of bytes to be added
1102 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1103 * or buffer limit reached.
1105 *********************************************************************/
1106 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1108 struct iob *iob = csp->iob;
1109 size_t used, offset, need, want;
1112 if (n <= 0) return JB_ERR_OK;
1114 used = (size_t)(iob->eod - iob->buf);
1115 offset = (size_t)(iob->cur - iob->buf);
1116 need = used + (size_t)n + 1;
1119 * If the buffer can't hold the new data, extend it first.
1120 * Use the next power of two if possible, else use the actual need.
1122 if (need > csp->config->buffer_limit)
1124 log_error(LOG_LEVEL_INFO,
1125 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
1126 need, csp->config->buffer_limit);
1127 return JB_ERR_MEMORY;
1130 if (need > iob->size)
1132 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1134 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1138 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1144 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1145 return JB_ERR_MEMORY;
1148 /* Update the iob pointers */
1149 iob->cur = p + offset;
1150 iob->eod = p + used;
1154 /* copy the new data into the iob buffer */
1155 memcpy(iob->eod, buf, (size_t)n);
1157 /* point to the end of the data */
1160 /* null terminate == cheap insurance */
1169 /*********************************************************************
1171 * Function : decompress_iob
1173 * Description : Decompress buffered page, expanding the
1174 * buffer as necessary. csp->iob->cur
1175 * should point to the the beginning of the
1176 * compressed data block.
1179 * 1 : csp = Current client state (buffers, headers, etc...)
1181 * Returns : JB_ERR_OK on success,
1182 * JB_ERR_MEMORY if out-of-memory limit reached, and
1183 * JB_ERR_COMPRESS if error decompressing buffer.
1185 *********************************************************************/
1186 jb_err decompress_iob(struct client_state *csp)
1188 char *buf; /* new, uncompressed buffer */
1189 char *cur; /* Current iob position (to keep the original
1190 * iob->cur unmodified if we return early) */
1191 size_t bufsize; /* allocated size of the new buffer */
1192 size_t old_size; /* Content size before decompression */
1193 size_t skip_size; /* Number of bytes at the beginning of the iob
1194 that we should NOT decompress. */
1195 int status; /* return status of the inflate() call */
1196 z_stream zstr; /* used by calls to zlib */
1198 assert(csp->iob->cur - csp->iob->buf > 0);
1199 assert(csp->iob->eod - csp->iob->cur > 0);
1201 bufsize = csp->iob->size;
1202 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1203 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1205 cur = csp->iob->cur;
1210 * This is to protect the parsing of gzipped data,
1211 * but it should(?) be valid for deflated data also.
1213 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1214 return JB_ERR_COMPRESS;
1217 if (csp->content_type & CT_GZIP)
1220 * Our task is slightly complicated by the facts that data
1221 * compressed by gzip does not include a zlib header, and
1222 * that there is no easily accessible interface in zlib to
1223 * handle a gzip header. We strip off the gzip header by
1224 * hand, and later inform zlib not to expect a header.
1228 * Strip off the gzip header. Please see RFC 1952 for more
1229 * explanation of the appropriate fields.
1231 if ((*cur++ != (char)0x1f)
1232 || (*cur++ != (char)0x8b)
1233 || (*cur++ != Z_DEFLATED))
1235 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1236 return JB_ERR_COMPRESS;
1242 * XXX: These magic numbers should be replaced
1243 * with macros to give a better idea what they do.
1247 /* The gzip header has reserved bits set; bail out. */
1248 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1249 return JB_ERR_COMPRESS;
1253 /* Skip extra fields if necessary. */
1257 * Skip a given number of bytes, specified
1258 * as a 16-bit little-endian value.
1261 * XXX: This code used to be:
1263 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1265 * which I had to change into:
1267 * cur += *cur++ + (*cur++ << 8);
1269 * at which point gcc43 finally noticed that the value
1270 * of cur is undefined (it depends on which of the
1271 * summands is evaluated first).
1273 * I haven't come across a site where this
1274 * code is actually executed yet, but I hope
1278 skip_bytes = *cur++;
1279 skip_bytes = *cur++ << 8;
1281 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1284 * The number of bytes to skip should be positive
1285 * and we'd like to stay in the buffer.
1287 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1289 log_error(LOG_LEVEL_ERROR,
1290 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1292 return JB_ERR_COMPRESS;
1294 log_error(LOG_LEVEL_INFO,
1295 "Skipping %d bytes for gzip compression. Does this sound right?",
1300 /* Skip the filename if necessary. */
1303 /* A null-terminated string is supposed to follow. */
1304 while (*cur++ && (cur < csp->iob->eod));
1308 /* Skip the comment if necessary. */
1311 /* A null-terminated string is supposed to follow. */
1312 while (*cur++ && (cur < csp->iob->eod));
1315 /* Skip the CRC if necessary. */
1321 if (cur >= csp->iob->eod)
1324 * If the current position pointer reached or passed
1325 * the buffer end, we were obviously tricked to skip
1328 log_error(LOG_LEVEL_ERROR,
1329 "Malformed gzip header detected. Aborting decompression.");
1330 return JB_ERR_COMPRESS;
1334 else if (csp->content_type & CT_DEFLATE)
1337 * XXX: The debug level should be lowered
1338 * before the next stable release.
1340 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1342 * In theory (that is, according to RFC 1950), deflate-compressed
1343 * data should begin with a two-byte zlib header and have an
1344 * adler32 checksum at the end. It seems that in practice only
1345 * the raw compressed data is sent. Note that this means that
1346 * we are not RFC 1950-compliant here, but the advantage is that
1347 * this actually works. :)
1349 * We add a dummy null byte to tell zlib where the data ends,
1350 * and later inform it not to expect a header.
1352 * Fortunately, add_to_iob() has thoughtfully null-terminated
1353 * the buffer; we can just increment the end pointer to include
1360 log_error(LOG_LEVEL_ERROR,
1361 "Unable to determine compression format for decompression");
1362 return JB_ERR_COMPRESS;
1365 /* Set up the fields required by zlib. */
1366 zstr.next_in = (Bytef *)cur;
1367 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1368 zstr.zalloc = Z_NULL;
1369 zstr.zfree = Z_NULL;
1370 zstr.opaque = Z_NULL;
1373 * Passing -MAX_WBITS to inflateInit2 tells the library
1374 * that there is no zlib header.
1376 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1378 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1379 return JB_ERR_COMPRESS;
1383 * Next, we allocate new storage for the inflated data.
1384 * We don't modify the existing iob yet, so in case there
1385 * is error in decompression we can recover gracefully.
1387 buf = zalloc(bufsize);
1390 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1391 return JB_ERR_MEMORY;
1394 assert(bufsize >= skip_size);
1395 memcpy(buf, csp->iob->buf, skip_size);
1396 zstr.avail_out = bufsize - skip_size;
1397 zstr.next_out = (Bytef *)buf + skip_size;
1399 /* Try to decompress the whole stream in one shot. */
1400 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1402 /* We need to allocate more memory for the output buffer. */
1404 char *tmpbuf; /* used for realloc'ing the buffer */
1405 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1408 * If zlib wants more data then there's a problem, because
1409 * the complete compressed file should have been buffered.
1411 if (0 == zstr.avail_in)
1413 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1414 return JB_ERR_COMPRESS;
1418 * If we tried the limit and still didn't have enough
1419 * memory, just give up.
1421 if (bufsize == csp->config->buffer_limit)
1423 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1424 return JB_ERR_MEMORY;
1427 /* Try doubling the buffer size each time. */
1430 /* Don't exceed the buffer limit. */
1431 if (bufsize > csp->config->buffer_limit)
1433 bufsize = csp->config->buffer_limit;
1436 /* Try to allocate the new buffer. */
1437 tmpbuf = realloc(buf, bufsize);
1440 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1442 return JB_ERR_MEMORY;
1446 char *oldnext_out = (char *)zstr.next_out;
1449 * Update the fields for inflate() to use the new
1450 * buffer, which may be in a location different from
1453 zstr.avail_out += bufsize - oldbufsize;
1454 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1457 * Compare with an uglier method of calculating these values
1458 * that doesn't require the extra oldbufsize variable.
1460 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1461 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1462 assert(zstr.avail_out > 0);
1468 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1470 log_error(LOG_LEVEL_ERROR,
1471 "Inconsistent stream state after decompression: %s", zstr.msg);
1473 * XXX: Intentionally no return.
1475 * According to zlib.h, Z_STREAM_ERROR is returned
1476 * "if the stream state was inconsistent".
1478 * I assume in this case inflate()'s status
1479 * would also be something different than Z_STREAM_END
1480 * so this check should be redundant, but lets see.
1484 if (status != Z_STREAM_END)
1486 /* We failed to decompress the stream. */
1487 log_error(LOG_LEVEL_ERROR,
1488 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1489 return JB_ERR_COMPRESS;
1493 * Finally, we can actually update the iob, since the
1494 * decompression was successful. First, free the old
1497 freez(csp->iob->buf);
1499 /* Now, update the iob to use the new buffer. */
1500 csp->iob->buf = buf;
1501 csp->iob->cur = csp->iob->buf + skip_size;
1502 csp->iob->eod = (char *)zstr.next_out;
1503 csp->iob->size = bufsize;
1506 * Make sure the new uncompressed iob obeys some minimal
1507 * consistency conditions.
1509 if ((csp->iob->buf < csp->iob->cur)
1510 && (csp->iob->cur <= csp->iob->eod)
1511 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1513 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1516 log_error(LOG_LEVEL_RE_FILTER,
1517 "Decompression successful. Old size: %d, new size: %d.",
1518 old_size, new_size);
1522 /* zlib thinks this is OK, so lets do the same. */
1523 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1528 /* It seems that zlib did something weird. */
1529 log_error(LOG_LEVEL_ERROR,
1530 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1531 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1532 csp->iob->eod, csp->iob->buf + csp->iob->size);
1533 return JB_ERR_COMPRESS;
1539 #endif /* defined(FEATURE_ZLIB) */
1542 /*********************************************************************
1544 * Function : string_move
1546 * Description : memmove wrapper to move the last part of a string
1547 * towards the beginning, overwriting the part in
1548 * the middle. strlcpy() can't be used here as the
1552 * 1 : dst = Destination to overwrite
1553 * 2 : src = Source to move.
1557 *********************************************************************/
1558 static void string_move(char *dst, char *src)
1562 /* +1 to copy the terminating nul as well. */
1563 memmove(dst, src, strlen(src)+1);
1567 /*********************************************************************
1569 * Function : normalize_lws
1571 * Description : Reduces unquoted linear white space in headers
1572 * to a single space in accordance with RFC 2616 2.2.
1573 * This simplifies parsing and filtering later on.
1575 * XXX: Remove log messages before
1576 * the next stable release?
1579 * 1 : header = A header with linear white space to reduce.
1583 *********************************************************************/
1584 static void normalize_lws(char *header)
1590 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1594 while (ijb_isspace(*q))
1598 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1599 string_move(p+1, q);
1604 log_error(LOG_LEVEL_HEADER,
1605 "Converting tab to space in '%s'", header);
1610 char *end_of_token = strstr(p+1, "\"");
1612 if (NULL != end_of_token)
1614 /* Don't mess with quoted text. */
1619 log_error(LOG_LEVEL_HEADER,
1620 "Ignoring single quote in '%s'", header);
1626 p = strchr(header, ':');
1627 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1630 * There's still space before the colon.
1633 string_move(p-1, p);
1638 /*********************************************************************
1640 * Function : get_header
1642 * Description : This (odd) routine will parse the csp->iob
1643 * to get the next complete header.
1646 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1648 * Returns : Any one of the following:
1650 * 1) a pointer to a dynamically allocated string that contains a header line
1651 * 2) NULL indicating that the end of the header was reached
1652 * 3) "" indicating that the end of the iob was reached before finding
1653 * a complete header line.
1655 *********************************************************************/
1656 char *get_header(struct iob *iob)
1660 header = get_header_line(iob);
1662 if ((header == NULL) || (*header == '\0'))
1665 * No complete header read yet, tell the client.
1670 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1673 * Header spans multiple lines, append the next one.
1675 char *continued_header;
1677 continued_header = get_header_line(iob);
1678 if ((continued_header == NULL) || (*continued_header == '\0'))
1681 * No complete header read yet, return what we got.
1682 * XXX: Should "unread" header instead.
1684 log_error(LOG_LEVEL_INFO,
1685 "Failed to read a multi-line header properly: '%s'",
1690 if (JB_ERR_OK != string_join(&header, continued_header))
1692 log_error(LOG_LEVEL_FATAL,
1693 "Out of memory while appending multiple headers.");
1697 /* XXX: remove before next stable release. */
1698 log_error(LOG_LEVEL_HEADER,
1699 "Merged multiple header lines to: '%s'",
1704 normalize_lws(header);
1711 /*********************************************************************
1713 * Function : get_header_line
1715 * Description : This (odd) routine will parse the csp->iob
1716 * to get the next header line.
1719 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1721 * Returns : Any one of the following:
1723 * 1) a pointer to a dynamically allocated string that contains a header line
1724 * 2) NULL indicating that the end of the header was reached
1725 * 3) "" indicating that the end of the iob was reached before finding
1726 * a complete header line.
1728 *********************************************************************/
1729 static char *get_header_line(struct iob *iob)
1733 if ((iob->cur == NULL)
1734 || ((p = strchr(iob->cur, '\n')) == NULL))
1736 return(""); /* couldn't find a complete header */
1741 ret = strdup(iob->cur);
1744 /* FIXME No way to handle error properly */
1745 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1750 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1752 /* is this a blank line (i.e. the end of the header) ? */
1764 /*********************************************************************
1766 * Function : get_header_value
1768 * Description : Get the value of a given header from a chained list
1769 * of header lines or return NULL if no such header is
1770 * present in the list.
1773 * 1 : header_list = pointer to list
1774 * 2 : header_name = string with name of header to look for.
1775 * Trailing colon required, capitalization
1778 * Returns : NULL if not found, else value of header
1780 *********************************************************************/
1781 char *get_header_value(const struct list *header_list, const char *header_name)
1783 struct list_entry *cur_entry;
1787 assert(header_list);
1788 assert(header_name);
1789 length = strlen(header_name);
1791 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1795 if (!strncmpic(cur_entry->str, header_name, length))
1798 * Found: return pointer to start of value
1800 ret = cur_entry->str + length;
1801 while (*ret && ijb_isspace(*ret)) ret++;
1815 /*********************************************************************
1817 * Function : scan_headers
1819 * Description : Scans headers, applies tags and updates action bits.
1822 * 1 : csp = Current client state (buffers, headers, etc...)
1824 * Returns : JB_ERR_OK
1826 *********************************************************************/
1827 static jb_err scan_headers(struct client_state *csp)
1829 struct list_entry *h; /* Header */
1830 jb_err err = JB_ERR_OK;
1832 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1834 /* Header crunch()ed in previous run? -> ignore */
1835 if (h->str == NULL) continue;
1836 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1837 err = header_tagger(csp, h->str);
1844 /*********************************************************************
1848 * Description : add, delete or modify lines in the HTTP header streams.
1849 * On entry, it receives a linked list of headers space
1850 * that was allocated dynamically (both the list nodes
1851 * and the header contents).
1853 * As a side effect it frees the space used by the original
1857 * 1 : csp = Current client state (buffers, headers, etc...)
1858 * 2 : filter_server_headers = Boolean to switch between
1859 * server and header filtering.
1861 * Returns : JB_ERR_OK in case off success, or
1862 * JB_ERR_MEMORY on out-of-memory error.
1864 *********************************************************************/
1865 jb_err sed(struct client_state *csp, int filter_server_headers)
1867 /* XXX: use more descriptive names. */
1868 struct list_entry *p;
1869 const struct parsers *v;
1870 const add_header_func_ptr *f;
1871 jb_err err = JB_ERR_OK;
1873 if (filter_server_headers)
1875 v = server_patterns;
1876 f = add_server_headers;
1880 v = client_patterns;
1881 f = add_client_headers;
1886 while ((err == JB_ERR_OK) && (v->str != NULL))
1888 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1890 /* Header crunch()ed in previous run? -> ignore */
1891 if (p->str == NULL) continue;
1893 /* Does the current parser handle this header? */
1894 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1895 (v->len == CHECK_EVERY_HEADER_REMAINING))
1897 err = v->parser(csp, &(p->str));
1903 /* place additional headers on the csp->headers list */
1904 while ((err == JB_ERR_OK) && (*f))
1914 /*********************************************************************
1916 * Function : update_server_headers
1918 * Description : Updates server headers after the body has been modified.
1921 * 1 : csp = Current client state (buffers, headers, etc...)
1923 * Returns : JB_ERR_OK in case off success, or
1924 * JB_ERR_MEMORY on out-of-memory error.
1926 *********************************************************************/
1927 jb_err update_server_headers(struct client_state *csp)
1929 jb_err err = JB_ERR_OK;
1931 static const struct parsers server_patterns_light[] = {
1932 { "Content-Length:", 15, server_adjust_content_length },
1933 { "Transfer-Encoding:", 18, server_transfer_coding },
1935 { "Content-Encoding:", 17, server_content_encoding },
1936 #endif /* def FEATURE_ZLIB */
1940 if (strncmpic(csp->http->cmd, "HEAD", 4))
1942 const struct parsers *v;
1943 struct list_entry *p;
1945 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1947 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1949 /* Header crunch()ed in previous run? -> ignore */
1950 if (p->str == NULL) continue;
1952 /* Does the current parser handle this header? */
1953 if (strncmpic(p->str, v->str, v->len) == 0)
1955 err = v->parser(csp, (char **)&(p->str));
1965 /*********************************************************************
1967 * Function : header_tagger
1969 * Description : Executes all text substitutions from applying
1970 * tag actions and saves the result as tag.
1972 * XXX: Shares enough code with filter_header() and
1973 * pcrs_filter_response() to warrant some helper functions.
1976 * 1 : csp = Current client state (buffers, headers, etc...)
1977 * 2 : header = Header that is used as tagger input
1979 * Returns : JB_ERR_OK on success and always succeeds
1981 *********************************************************************/
1982 static jb_err header_tagger(struct client_state *csp, char *header)
1984 int wanted_filter_type;
1985 int multi_action_index;
1989 struct file_list *fl;
1990 struct re_filterfile_spec *b;
1991 struct list_entry *tag_name;
1993 int found_filters = 0;
1994 const size_t header_length = strlen(header);
1996 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1998 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1999 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
2003 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
2004 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
2007 /* Check if there are any filters */
2008 for (i = 0; i < MAX_AF_FILES; i++)
2021 if (0 == found_filters)
2023 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2024 "tagging enabled, but no taggers available.");
2028 for (i = 0; i < MAX_AF_FILES; i++)
2031 if ((NULL == fl) || (NULL == fl->f))
2034 * Either there are no filter files
2035 * left, or this filter file just
2036 * contains no valid filters.
2038 * Continue to be sure we don't miss
2039 * valid filter files that are chained
2040 * after empty or invalid ones.
2045 /* For all filters, */
2046 for (b = fl->f; b; b = b->next)
2048 if (b->type != wanted_filter_type)
2050 /* skip the ones we don't care about, */
2053 /* leaving only taggers that could apply, of which we use the ones, */
2054 for (tag_name = csp->action->multi[multi_action_index]->first;
2055 NULL != tag_name; tag_name = tag_name->next)
2057 /* that do apply, and */
2058 if (strcmp(b->name, tag_name->str) == 0)
2060 char *modified_tag = NULL;
2062 size_t size = header_length;
2063 pcrs_job *joblist = b->joblist;
2065 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2067 if (NULL == joblist)
2069 log_error(LOG_LEVEL_RE_FILTER,
2070 "Tagger %s has empty joblist. Nothing to do.", b->name);
2074 /* execute their pcrs_joblist on the header. */
2075 for (job = joblist; NULL != job; job = job->next)
2077 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2081 /* Success, continue with the modified version. */
2090 /* Tagger doesn't match */
2093 /* Regex failure, log it but continue anyway. */
2094 log_error(LOG_LEVEL_ERROR,
2095 "Problems with tagger \'%s\' and header \'%s\': %s",
2096 b->name, *header, pcrs_strerror(hits));
2098 freez(modified_tag);
2102 if (b->dynamic) pcrs_free_joblist(joblist);
2104 /* If this tagger matched */
2110 * There is to technical limitation which makes
2111 * it impossible to use empty tags, but I assume
2112 * no one would do it intentionally.
2115 log_error(LOG_LEVEL_INFO,
2116 "Tagger \'%s\' created an empty tag. Ignored.",
2121 if (!list_contains_item(csp->tags, tag))
2123 if (JB_ERR_OK != enlist(csp->tags, tag))
2125 log_error(LOG_LEVEL_ERROR,
2126 "Insufficient memory to add tag \'%s\', "
2127 "based on tagger \'%s\' and header \'%s\'",
2128 tag, b->name, *header);
2132 char *action_message;
2134 * update the action bits right away, to make
2135 * tagging based on tags set by earlier taggers
2136 * of the same kind possible.
2138 if (update_action_bits_for_tag(csp, tag))
2140 action_message = "Action bits updated accordingly.";
2144 action_message = "No action bits update necessary.";
2147 log_error(LOG_LEVEL_HEADER,
2148 "Tagger \'%s\' added tag \'%s\'. %s",
2149 b->name, tag, action_message);
2154 /* XXX: Is this log-worthy? */
2155 log_error(LOG_LEVEL_HEADER,
2156 "Tagger \'%s\' didn't add tag \'%s\'. "
2157 "Tag already present", b->name, tag);
2160 } /* if the tagger matched */
2161 } /* if the tagger applies */
2162 } /* for every tagger that could apply */
2163 } /* for all filters */
2164 } /* for all filter files */
2169 /* here begins the family of parser functions that reformat header lines */
2171 /*********************************************************************
2173 * Function : filter_header
2175 * Description : Executes all text substitutions from all applying
2176 * +(server|client)-header-filter actions on the header.
2177 * Most of the code was copied from pcrs_filter_response,
2178 * including the rather short variable names
2181 * 1 : csp = Current client state (buffers, headers, etc...)
2182 * 2 : header = On input, pointer to header to modify.
2183 * On output, pointer to the modified header, or NULL
2184 * to remove the header. This function frees the
2185 * original string if necessary.
2187 * Returns : JB_ERR_OK on success and always succeeds
2189 *********************************************************************/
2190 static jb_err filter_header(struct client_state *csp, char **header)
2194 size_t size = strlen(*header);
2196 char *newheader = NULL;
2199 struct file_list *fl;
2200 struct re_filterfile_spec *b;
2201 struct list_entry *filtername;
2203 int i, found_filters = 0;
2204 int wanted_filter_type;
2205 int multi_action_index;
2207 if (csp->flags & CSP_FLAG_NO_FILTERING)
2212 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2214 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2215 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2219 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2220 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2224 * Need to check the set of re_filterfiles...
2226 for (i = 0; i < MAX_AF_FILES; i++)
2239 if (0 == found_filters)
2241 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2242 "header filtering enabled, but no matching filters available.");
2246 for (i = 0; i < MAX_AF_FILES; i++)
2249 if ((NULL == fl) || (NULL == fl->f))
2252 * Either there are no filter files
2253 * left, or this filter file just
2254 * contains no valid filters.
2256 * Continue to be sure we don't miss
2257 * valid filter files that are chained
2258 * after empty or invalid ones.
2263 * For all applying +filter actions, look if a filter by that
2264 * name exists and if yes, execute its pcrs_joblist on the
2267 for (b = fl->f; b; b = b->next)
2269 if (b->type != wanted_filter_type)
2271 /* Skip other filter types */
2275 for (filtername = csp->action->multi[multi_action_index]->first;
2276 filtername ; filtername = filtername->next)
2278 if (strcmp(b->name, filtername->str) == 0)
2280 int current_hits = 0;
2281 pcrs_job *joblist = b->joblist;
2283 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2285 if (NULL == joblist)
2287 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2291 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2292 *header, size, b->name);
2294 /* Apply all jobs from the joblist */
2295 for (job = joblist; NULL != job; job = job->next)
2297 matches = pcrs_execute(job, *header, size, &newheader, &size);
2300 current_hits += matches;
2301 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2303 *header = newheader;
2305 else if ( 0 == matches )
2307 /* Filter doesn't change header */
2313 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2314 *header, b->name, pcrs_strerror(matches));
2315 if (newheader != NULL)
2317 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2323 if (b->dynamic) pcrs_free_joblist(joblist);
2325 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2326 hits += current_hits;
2333 * Additionally checking for hits is important because if
2334 * the continue hack is triggered, server headers can
2335 * arrive empty to separate multiple heads from each other.
2337 if ((0 == size) && hits)
2339 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2347 /*********************************************************************
2349 * Function : server_connection
2351 * Description : Makes sure that the value of the Connection: header
2352 * is "close" and signals server_connection_close_adder
2356 * 1 : csp = Current client state (buffers, headers, etc...)
2357 * 2 : header = On input, pointer to header to modify.
2358 * On output, pointer to the modified header, or NULL
2359 * to remove the header. This function frees the
2360 * original string if necessary.
2362 * Returns : JB_ERR_OK on success, or
2363 * JB_ERR_MEMORY on out-of-memory error.
2365 *********************************************************************/
2366 static jb_err server_connection(struct client_state *csp, char **header)
2368 char *old_header = *header;
2370 /* Do we have a 'Connection: close' header? */
2371 if (strcmpic(*header, "Connection: close"))
2373 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2374 if ((csp->config->feature_flags &
2375 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2376 && !strcmpic(*header, "Connection: keep-alive"))
2378 /* Remember to keep the connection alive. */
2379 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
2381 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2383 *header = strdup("Connection: close");
2386 return JB_ERR_MEMORY;
2388 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2392 /* Signal server_connection_close_adder() to return early. */
2393 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2398 /*********************************************************************
2400 * Function : client_connection
2402 * Description : Makes sure a proper "Connection:" header is
2403 * set and signals connection_header_adder
2407 * 1 : csp = Current client state (buffers, headers, etc...)
2408 * 2 : header = On input, pointer to header to modify.
2409 * On output, pointer to the modified header, or NULL
2410 * to remove the header. This function frees the
2411 * original string if necessary.
2413 * Returns : JB_ERR_OK on success, or
2414 * JB_ERR_MEMORY on out-of-memory error.
2416 *********************************************************************/
2417 static jb_err client_connection(struct client_state *csp, char **header)
2419 char *old_header = *header;
2420 const char *wanted_header = get_appropiate_connection_header(csp);
2422 if (strcmpic(*header, wanted_header))
2424 *header = strdup(wanted_header);
2427 return JB_ERR_MEMORY;
2429 log_error(LOG_LEVEL_HEADER,
2430 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2434 /* Signal client_connection_close_adder() to return early. */
2435 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2441 /*********************************************************************
2443 * Function : crumble
2445 * Description : This is called if a header matches a pattern to "crunch"
2448 * 1 : csp = Current client state (buffers, headers, etc...)
2449 * 2 : header = On input, pointer to header to modify.
2450 * On output, pointer to the modified header, or NULL
2451 * to remove the header. This function frees the
2452 * original string if necessary.
2454 * Returns : JB_ERR_OK on success, or
2455 * JB_ERR_MEMORY on out-of-memory error.
2457 *********************************************************************/
2458 static jb_err crumble(struct client_state *csp, char **header)
2460 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2466 /*********************************************************************
2468 * Function : crunch_server_header
2470 * Description : Crunch server header if it matches a string supplied by the
2471 * user. Called from `sed'.
2474 * 1 : csp = Current client state (buffers, headers, etc...)
2475 * 2 : header = On input, pointer to header to modify.
2476 * On output, pointer to the modified header, or NULL
2477 * to remove the header. This function frees the
2478 * original string if necessary.
2480 * Returns : JB_ERR_OK on success and always succeeds
2482 *********************************************************************/
2483 static jb_err crunch_server_header(struct client_state *csp, char **header)
2485 const char *crunch_pattern;
2487 /* Do we feel like crunching? */
2488 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2490 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2492 /* Is the current header the lucky one? */
2493 if (strstr(*header, crunch_pattern))
2495 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2504 /*********************************************************************
2506 * Function : server_content_type
2508 * Description : Set the content-type for filterable types (text/.*,
2509 * .*xml.*, javascript and image/gif) unless filtering has been
2510 * forbidden (CT_TABOO) while parsing earlier headers.
2511 * NOTE: Since text/plain is commonly used by web servers
2512 * for files whose correct type is unknown, we don't
2513 * set CT_TEXT for it.
2516 * 1 : csp = Current client state (buffers, headers, etc...)
2517 * 2 : header = On input, pointer to header to modify.
2518 * On output, pointer to the modified header, or NULL
2519 * to remove the header. This function frees the
2520 * original string if necessary.
2522 * Returns : JB_ERR_OK on success, or
2523 * JB_ERR_MEMORY on out-of-memory error.
2525 *********************************************************************/
2526 static jb_err server_content_type(struct client_state *csp, char **header)
2528 /* Remove header if it isn't the first Content-Type header */
2529 if ((csp->content_type & CT_DECLARED))
2532 * Another, slightly slower, way to see if
2533 * we already parsed another Content-Type header.
2535 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2537 log_error(LOG_LEVEL_ERROR,
2538 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2546 * Signal that the Content-Type has been set.
2548 csp->content_type |= CT_DECLARED;
2550 if (!(csp->content_type & CT_TABOO))
2553 * XXX: The assumption that text/plain is a sign of
2554 * binary data seems to be somewhat unreasonable nowadays
2555 * and should be dropped after 3.0.8 is out.
2557 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2558 || strstr(*header, "xml")
2559 || strstr(*header, "application/x-javascript"))
2561 csp->content_type |= CT_TEXT;
2563 else if (strstr(*header, "image/gif"))
2565 csp->content_type |= CT_GIF;
2570 * Are we messing with the content type?
2572 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2575 * Make sure the user doesn't accidently
2576 * change the content type of binary documents.
2578 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2581 *header = strdup("Content-Type: ");
2582 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2586 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2587 return JB_ERR_MEMORY;
2589 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2593 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2594 "It doesn't look like a content type that should be filtered. "
2595 "Enable force-text-mode if you know what you're doing.", *header);
2603 /*********************************************************************
2605 * Function : server_transfer_coding
2607 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2608 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2609 * - Remove header if body was chunked but has been
2610 * de-chunked for filtering.
2613 * 1 : csp = Current client state (buffers, headers, etc...)
2614 * 2 : header = On input, pointer to header to modify.
2615 * On output, pointer to the modified header, or NULL
2616 * to remove the header. This function frees the
2617 * original string if necessary.
2619 * Returns : JB_ERR_OK on success, or
2620 * JB_ERR_MEMORY on out-of-memory error.
2622 *********************************************************************/
2623 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2626 * Turn off pcrs and gif filtering if body compressed
2628 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2632 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2634 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2635 csp->http->cmd, *header);
2636 #endif /* def FEATURE_ZLIB */
2637 csp->content_type = CT_TABOO;
2641 * Raise flag if body chunked
2643 if (strstr(*header, "chunked"))
2645 csp->flags |= CSP_FLAG_CHUNKED;
2648 * If the body was modified, it has been de-chunked first
2649 * and the header must be removed.
2651 * FIXME: If there is more than one transfer encoding,
2652 * only the "chunked" part should be removed here.
2654 if (csp->flags & CSP_FLAG_MODIFIED)
2656 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2665 /*********************************************************************
2667 * Function : server_content_encoding
2669 * Description : This function is run twice for each request,
2670 * unless FEATURE_ZLIB and filtering are disabled.
2672 * The first run is used to check if the content
2673 * is compressed, if FEATURE_ZLIB is disabled
2674 * filtering is then disabled as well, if FEATURE_ZLIB
2675 * is enabled the content is marked for decompression.
2677 * The second run is used to remove the Content-Encoding
2678 * header if the decompression was successful.
2681 * 1 : csp = Current client state (buffers, headers, etc...)
2682 * 2 : header = On input, pointer to header to modify.
2683 * On output, pointer to the modified header, or NULL
2684 * to remove the header. This function frees the
2685 * original string if necessary.
2687 * Returns : JB_ERR_OK on success, or
2688 * JB_ERR_MEMORY on out-of-memory error.
2690 *********************************************************************/
2691 static jb_err server_content_encoding(struct client_state *csp, char **header)
2694 if ((csp->flags & CSP_FLAG_MODIFIED)
2695 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2698 * We successfully decompressed the content,
2699 * and have to clean the header now, so the
2700 * client no longer expects compressed data..
2702 * XXX: There is a difference between cleaning
2703 * and removing it completely.
2705 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2708 else if (strstr(*header, "gzip"))
2710 /* Mark for gzip decompression */
2711 csp->content_type |= CT_GZIP;
2713 else if (strstr(*header, "deflate"))
2715 /* Mark for zlib decompression */
2716 csp->content_type |= CT_DEFLATE;
2718 else if (strstr(*header, "compress"))
2721 * We can't decompress this; therefore we can't filter
2724 csp->content_type |= CT_TABOO;
2726 #else /* !defined(FEATURE_ZLIB) */
2727 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2730 * Body is compressed, turn off pcrs and gif filtering.
2732 csp->content_type |= CT_TABOO;
2735 * Log a warning if the user expects the content to be filtered.
2737 if ((csp->rlist != NULL) &&
2738 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2740 log_error(LOG_LEVEL_INFO,
2741 "Compressed content detected, content filtering disabled. "
2742 "Consider recompiling Privoxy with zlib support or "
2743 "enable the prevent-compression action.");
2746 #endif /* defined(FEATURE_ZLIB) */
2753 /*********************************************************************
2755 * Function : server_adjust_content_length
2757 * Description : Adjust Content-Length header if we modified
2761 * 1 : csp = Current client state (buffers, headers, etc...)
2762 * 2 : header = On input, pointer to header to modify.
2763 * On output, pointer to the modified header, or NULL
2764 * to remove the header. This function frees the
2765 * original string if necessary.
2767 * Returns : JB_ERR_OK on success, or
2768 * JB_ERR_MEMORY on out-of-memory error.
2770 *********************************************************************/
2771 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2773 const size_t max_header_length = 80;
2775 /* Regenerate header if the content was modified. */
2776 if (csp->flags & CSP_FLAG_MODIFIED)
2779 *header = (char *) zalloc(max_header_length);
2780 if (*header == NULL)
2782 return JB_ERR_MEMORY;
2785 snprintf(*header, max_header_length, "Content-Length: %d",
2786 (int)csp->content_length);
2787 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2788 (int)csp->content_length);
2795 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2796 /*********************************************************************
2798 * Function : server_save_content_length
2800 * Description : Save the Content-Length sent by the server.
2803 * 1 : csp = Current client state (buffers, headers, etc...)
2804 * 2 : header = On input, pointer to header to modify.
2805 * On output, pointer to the modified header, or NULL
2806 * to remove the header. This function frees the
2807 * original string if necessary.
2809 * Returns : JB_ERR_OK on success, or
2810 * JB_ERR_MEMORY on out-of-memory error.
2812 *********************************************************************/
2813 static jb_err server_save_content_length(struct client_state *csp, char **header)
2815 unsigned int content_length = 0;
2817 assert(*(*header+14) == ':');
2819 if (1 != sscanf(*header+14, ": %u", &content_length))
2821 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2826 csp->expected_content_length = content_length;
2827 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2832 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2835 /*********************************************************************
2837 * Function : server_content_md5
2839 * Description : Crumble any Content-MD5 headers if the document was
2840 * modified. FIXME: Should we re-compute instead?
2843 * 1 : csp = Current client state (buffers, headers, etc...)
2844 * 2 : header = On input, pointer to header to modify.
2845 * On output, pointer to the modified header, or NULL
2846 * to remove the header. This function frees the
2847 * original string if necessary.
2849 * Returns : JB_ERR_OK on success, or
2850 * JB_ERR_MEMORY on out-of-memory error.
2852 *********************************************************************/
2853 static jb_err server_content_md5(struct client_state *csp, char **header)
2855 if (csp->flags & CSP_FLAG_MODIFIED)
2857 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2865 /*********************************************************************
2867 * Function : server_content_disposition
2869 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2870 * Called from `sed'.
2873 * 1 : csp = Current client state (buffers, headers, etc...)
2874 * 2 : header = On input, pointer to header to modify.
2875 * On output, pointer to the modified header, or NULL
2876 * to remove the header. This function frees the
2877 * original string if necessary.
2879 * Returns : JB_ERR_OK on success, or
2880 * JB_ERR_MEMORY on out-of-memory error.
2882 *********************************************************************/
2883 static jb_err server_content_disposition(struct client_state *csp, char **header)
2888 * Are we messing with the Content-Disposition header?
2890 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2896 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2898 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2901 * Blocking content-disposition header
2903 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2910 * Replacing Content-Disposition header
2913 *header = strdup("Content-Disposition: ");
2914 string_append(header, newval);
2916 if (*header != NULL)
2918 log_error(LOG_LEVEL_HEADER,
2919 "Content-Disposition header crunched and replaced with: %s", *header);
2922 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2926 /*********************************************************************
2928 * Function : server_last_modified
2930 * Description : Changes Last-Modified header to the actual date
2931 * to help hide-if-modified-since.
2932 * Called from `sed'.
2935 * 1 : csp = Current client state (buffers, headers, etc...)
2936 * 2 : header = On input, pointer to header to modify.
2937 * On output, pointer to the modified header, or NULL
2938 * to remove the header. This function frees the
2939 * original string if necessary.
2941 * Returns : JB_ERR_OK on success, or
2942 * JB_ERR_MEMORY on out-of-memory error.
2944 *********************************************************************/
2945 static jb_err server_last_modified(struct client_state *csp, char **header)
2948 char buf[BUFFER_SIZE];
2951 #ifdef HAVE_GMTIME_R
2954 struct tm *timeptr = NULL;
2955 time_t now, last_modified;
2957 long int days, hours, minutes, seconds;
2960 * Are we messing with the Last-Modified header?
2962 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2968 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2970 if (0 == strcmpic(newval, "block") )
2973 * Blocking Last-Modified header. Useless but why not.
2975 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2979 else if (0 == strcmpic(newval, "reset-to-request-time"))
2982 * Setting Last-Modified Header to now.
2984 get_http_time(0, buf, sizeof(buf));
2986 *header = strdup("Last-Modified: ");
2987 string_append(header, buf);
2989 if (*header == NULL)
2991 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2995 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2998 else if (0 == strcmpic(newval, "randomize"))
3000 const char *header_time = *header + sizeof("Last-Modified:");
3002 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
3004 #ifdef HAVE_GMTIME_R
3005 timeptr = gmtime_r(&now, &gmt);
3006 #elif FEATURE_PTHREAD
3007 privoxy_mutex_lock(&gmtime_mutex);
3008 timeptr = gmtime(&now);
3009 privoxy_mutex_unlock(&gmtime_mutex);
3011 timeptr = gmtime(&now);
3013 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
3015 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3020 rtime = (long int)difftime(now, last_modified);
3029 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
3031 rtime = pick_from_range(rtime);
3032 if (negative) rtime *= -1;
3033 last_modified += rtime;
3034 #ifdef HAVE_GMTIME_R
3035 timeptr = gmtime_r(&last_modified, &gmt);
3036 #elif FEATURE_PTHREAD
3037 privoxy_mutex_lock(&gmtime_mutex);
3038 timeptr = gmtime(&last_modified);
3039 privoxy_mutex_unlock(&gmtime_mutex);
3041 timeptr = gmtime(&last_modified);
3043 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3045 *header = strdup("Last-Modified: ");
3046 string_append(header, newheader);
3048 if (*header == NULL)
3050 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
3051 return JB_ERR_MEMORY;
3054 days = rtime / (3600 * 24);
3055 hours = rtime / 3600 % 24;
3056 minutes = rtime / 60 % 60;
3057 seconds = rtime % 60;
3059 log_error(LOG_LEVEL_HEADER,
3060 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
3061 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
3062 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3066 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
3075 /*********************************************************************
3077 * Function : client_accept_encoding
3079 * Description : Rewrite the client's Accept-Encoding header so that
3080 * if doesn't allow compression, if the action applies.
3081 * Note: For HTTP/1.0 the absence of the header is enough.
3084 * 1 : csp = Current client state (buffers, headers, etc...)
3085 * 2 : header = On input, pointer to header to modify.
3086 * On output, pointer to the modified header, or NULL
3087 * to remove the header. This function frees the
3088 * original string if necessary.
3090 * Returns : JB_ERR_OK on success, or
3091 * JB_ERR_MEMORY on out-of-memory error.
3093 *********************************************************************/
3094 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3096 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3098 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3102 /* Temporarily disable the correct behaviour to
3103 * work around a PHP bug.
3105 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
3107 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
3108 * if (*header == NULL)
3110 * return JB_ERR_MEMORY;
3121 /*********************************************************************
3123 * Function : client_te
3125 * Description : Rewrite the client's TE header so that
3126 * if doesn't allow compression, if the action applies.
3129 * 1 : csp = Current client state (buffers, headers, etc...)
3130 * 2 : header = On input, pointer to header to modify.
3131 * On output, pointer to the modified header, or NULL
3132 * to remove the header. This function frees the
3133 * original string if necessary.
3135 * Returns : JB_ERR_OK on success, or
3136 * JB_ERR_MEMORY on out-of-memory error.
3138 *********************************************************************/
3139 static jb_err client_te(struct client_state *csp, char **header)
3141 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3144 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3151 /*********************************************************************
3153 * Function : client_referrer
3155 * Description : Handle the "referer" config setting properly.
3156 * Called from `sed'.
3159 * 1 : csp = Current client state (buffers, headers, etc...)
3160 * 2 : header = On input, pointer to header to modify.
3161 * On output, pointer to the modified header, or NULL
3162 * to remove the header. This function frees the
3163 * original string if necessary.
3165 * Returns : JB_ERR_OK on success, or
3166 * JB_ERR_MEMORY on out-of-memory error.
3168 *********************************************************************/
3169 static jb_err client_referrer(struct client_state *csp, char **header)
3171 const char *parameter;
3172 /* booleans for parameters we have to check multiple times */
3173 int parameter_conditional_block;
3174 int parameter_conditional_forge;
3176 #ifdef FEATURE_FORCE_LOAD
3178 * Since the referrer can include the prefix even
3179 * if the request itself is non-forced, we must
3180 * clean it unconditionally.
3182 * XXX: strclean is too broad
3184 strclean(*header, FORCE_PREFIX);
3185 #endif /* def FEATURE_FORCE_LOAD */
3187 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3189 /* Nothing left to do */
3193 parameter = csp->action->string[ACTION_STRING_REFERER];
3194 assert(parameter != NULL);
3195 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3196 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3198 if (!parameter_conditional_block && !parameter_conditional_forge)
3201 * As conditional-block and conditional-forge are the only
3202 * parameters that rely on the original referrer, we can
3203 * remove it now for all the others.
3208 if (0 == strcmpic(parameter, "block"))
3210 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3213 else if (parameter_conditional_block || parameter_conditional_forge)
3215 return handle_conditional_hide_referrer_parameter(header,
3216 csp->http->hostport, parameter_conditional_block);
3218 else if (0 == strcmpic(parameter, "forge"))
3220 return create_forged_referrer(header, csp->http->hostport);
3224 /* interpret parameter as user-supplied referer to fake */
3225 return create_fake_referrer(header, parameter);
3230 /*********************************************************************
3232 * Function : client_accept_language
3234 * Description : Handle the "Accept-Language" config setting properly.
3235 * Called from `sed'.
3238 * 1 : csp = Current client state (buffers, headers, etc...)
3239 * 2 : header = On input, pointer to header to modify.
3240 * On output, pointer to the modified header, or NULL
3241 * to remove the header. This function frees the
3242 * original string if necessary.
3244 * Returns : JB_ERR_OK on success, or
3245 * JB_ERR_MEMORY on out-of-memory error.
3247 *********************************************************************/
3248 static jb_err client_accept_language(struct client_state *csp, char **header)
3253 * Are we messing with the Accept-Language?
3255 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3257 /*I don't think so*/
3261 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3263 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3266 * Blocking Accept-Language header
3268 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3275 * Replacing Accept-Language header
3278 *header = strdup("Accept-Language: ");
3279 string_append(header, newval);
3281 if (*header == NULL)
3283 log_error(LOG_LEVEL_ERROR,
3284 "Insufficient memory. Accept-Language header crunched without replacement.");
3288 log_error(LOG_LEVEL_HEADER,
3289 "Accept-Language header crunched and replaced with: %s", *header);
3292 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3296 /*********************************************************************
3298 * Function : crunch_client_header
3300 * Description : Crunch client header if it matches a string supplied by the
3301 * user. Called from `sed'.
3304 * 1 : csp = Current client state (buffers, headers, etc...)
3305 * 2 : header = On input, pointer to header to modify.
3306 * On output, pointer to the modified header, or NULL
3307 * to remove the header. This function frees the
3308 * original string if necessary.
3310 * Returns : JB_ERR_OK on success and always succeeds
3312 *********************************************************************/
3313 static jb_err crunch_client_header(struct client_state *csp, char **header)
3315 const char *crunch_pattern;
3317 /* Do we feel like crunching? */
3318 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3320 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3322 /* Is the current header the lucky one? */
3323 if (strstr(*header, crunch_pattern))
3325 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3333 /*********************************************************************
3335 * Function : client_uagent
3337 * Description : Handle the "user-agent" config setting properly
3338 * and remember its original value to enable browser
3339 * bug workarounds. Called from `sed'.
3342 * 1 : csp = Current client state (buffers, headers, etc...)
3343 * 2 : header = On input, pointer to header to modify.
3344 * On output, pointer to the modified header, or NULL
3345 * to remove the header. This function frees the
3346 * original string if necessary.
3348 * Returns : JB_ERR_OK on success, or
3349 * JB_ERR_MEMORY on out-of-memory error.
3351 *********************************************************************/
3352 static jb_err client_uagent(struct client_state *csp, char **header)
3356 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3361 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3368 *header = strdup("User-Agent: ");
3369 string_append(header, newval);
3371 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3373 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3377 /*********************************************************************
3379 * Function : client_ua
3381 * Description : Handle "ua-" headers properly. Called from `sed'.
3384 * 1 : csp = Current client state (buffers, headers, etc...)
3385 * 2 : header = On input, pointer to header to modify.
3386 * On output, pointer to the modified header, or NULL
3387 * to remove the header. This function frees the
3388 * original string if necessary.
3390 * Returns : JB_ERR_OK on success, or
3391 * JB_ERR_MEMORY on out-of-memory error.
3393 *********************************************************************/
3394 static jb_err client_ua(struct client_state *csp, char **header)
3396 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3398 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3406 /*********************************************************************
3408 * Function : client_from
3410 * Description : Handle the "from" config setting properly.
3411 * Called from `sed'.
3414 * 1 : csp = Current client state (buffers, headers, etc...)
3415 * 2 : header = On input, pointer to header to modify.
3416 * On output, pointer to the modified header, or NULL
3417 * to remove the header. This function frees the
3418 * original string if necessary.
3420 * Returns : JB_ERR_OK on success, or
3421 * JB_ERR_MEMORY on out-of-memory error.
3423 *********************************************************************/
3424 static jb_err client_from(struct client_state *csp, char **header)
3428 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3435 newval = csp->action->string[ACTION_STRING_FROM];
3438 * Are we blocking the e-mail address?
3440 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3442 log_error(LOG_LEVEL_HEADER, "crunched From!");
3446 log_error(LOG_LEVEL_HEADER, " modified");
3448 *header = strdup("From: ");
3449 string_append(header, newval);
3451 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3455 /*********************************************************************
3457 * Function : client_send_cookie
3459 * Description : Crunches the "cookie" header if necessary.
3460 * Called from `sed'.
3462 * XXX: Stupid name, doesn't send squat.
3465 * 1 : csp = Current client state (buffers, headers, etc...)
3466 * 2 : header = On input, pointer to header to modify.
3467 * On output, pointer to the modified header, or NULL
3468 * to remove the header. This function frees the
3469 * original string if necessary.
3471 * Returns : JB_ERR_OK on success, or
3472 * JB_ERR_MEMORY on out-of-memory error.
3474 *********************************************************************/
3475 static jb_err client_send_cookie(struct client_state *csp, char **header)
3477 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3479 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3487 /*********************************************************************
3489 * Function : client_x_forwarded
3491 * Description : Handle the "x-forwarded-for" config setting properly,
3492 * also used in the add_client_headers list. Called from `sed'.
3495 * 1 : csp = Current client state (buffers, headers, etc...)
3496 * 2 : header = On input, pointer to header to modify.
3497 * On output, pointer to the modified header, or NULL
3498 * to remove the header. This function frees the
3499 * original string if necessary.
3501 * Returns : JB_ERR_OK on success, or
3502 * JB_ERR_MEMORY on out-of-memory error.
3504 *********************************************************************/
3505 jb_err client_x_forwarded(struct client_state *csp, char **header)
3507 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3509 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3511 if (0 == strcmpic(parameter, "block"))
3514 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3516 else if (0 == strcmpic(parameter, "add"))
3518 string_append(header, ", ");
3519 string_append(header, csp->ip_addr_str);
3521 if (*header == NULL)
3523 return JB_ERR_MEMORY;
3525 log_error(LOG_LEVEL_HEADER,
3526 "Appended client IP address to %s", *header);
3527 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3531 log_error(LOG_LEVEL_FATAL,
3532 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3540 /*********************************************************************
3542 * Function : client_max_forwards
3544 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3545 * from the value of the Max-Forwards header field.
3548 * 1 : csp = Current client state (buffers, headers, etc...)
3549 * 2 : header = On input, pointer to header to modify.
3550 * On output, pointer to the modified header, or NULL
3551 * to remove the header. This function frees the
3552 * original string if necessary.
3554 * Returns : JB_ERR_OK on success, or
3555 * JB_ERR_MEMORY on out-of-memory error.
3557 *********************************************************************/
3558 static jb_err client_max_forwards(struct client_state *csp, char **header)
3562 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3563 (0 == strcmpic(csp->http->gpc, "options")))
3565 assert(*(*header+12) == ':');
3566 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3568 if (max_forwards > 0)
3570 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3571 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3572 csp->http->gpc, max_forwards);
3574 else if (max_forwards < 0)
3576 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3582 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3591 /*********************************************************************
3593 * Function : client_host
3595 * Description : If the request URI did not contain host and
3596 * port information, parse and evaluate the Host
3599 * Also, kill ill-formed HOST: headers as sent by
3600 * Apple's iTunes software when used with a proxy.
3603 * 1 : csp = Current client state (buffers, headers, etc...)
3604 * 2 : header = On input, pointer to header to modify.
3605 * On output, pointer to the modified header, or NULL
3606 * to remove the header. This function frees the
3607 * original string if necessary.
3609 * Returns : JB_ERR_OK on success, or
3610 * JB_ERR_MEMORY on out-of-memory error.
3612 *********************************************************************/
3613 static jb_err client_host(struct client_state *csp, char **header)
3618 * If the header field name is all upper-case, chances are that it's
3619 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3620 * not a problem -- they are regenerated later.
3622 if ((*header)[1] == 'O')
3624 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3629 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3630 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3633 if (NULL == (p = strdup((*header)+6)))
3635 return JB_ERR_MEMORY;
3638 if (NULL == (q = strdup(p)))
3641 return JB_ERR_MEMORY;
3644 freez(csp->http->hostport);
3645 csp->http->hostport = p;
3646 freez(csp->http->host);
3647 csp->http->host = q;
3648 q = strchr(csp->http->host, ':');
3651 /* Terminate hostname and evaluate port string */
3653 csp->http->port = atoi(q);
3657 csp->http->port = csp->http->ssl ? 443 : 80;
3660 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3661 csp->http->hostport, csp->http->host, csp->http->port);
3664 /* Signal client_host_adder() to return right away */
3665 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3671 /*********************************************************************
3673 * Function : client_if_modified_since
3675 * Description : Remove or modify the If-Modified-Since header.
3678 * 1 : csp = Current client state (buffers, headers, etc...)
3679 * 2 : header = On input, pointer to header to modify.
3680 * On output, pointer to the modified header, or NULL
3681 * to remove the header. This function frees the
3682 * original string if necessary.
3684 * Returns : JB_ERR_OK on success, or
3685 * JB_ERR_MEMORY on out-of-memory error.
3687 *********************************************************************/
3688 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3691 #ifdef HAVE_GMTIME_R
3694 struct tm *timeptr = NULL;
3698 long int hours, minutes, seconds;
3702 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3705 * The client got an error message because of a temporary problem,
3706 * the problem is gone and the client now tries to revalidate our
3707 * error message on the real server. The revalidation would always
3708 * end with the transmission of the whole document and there is
3709 * no need to expose the bogus If-Modified-Since header.
3711 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3714 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3716 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3718 if ((0 == strcmpic(newval, "block")))
3720 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3723 else /* add random value */
3725 const char *header_time = *header + sizeof("If-Modified-Since:");
3727 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3729 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3734 rtime = strtol(newval, &endptr, 0);
3737 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3738 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3745 rtime = pick_from_range(rtime);
3749 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3752 tm += rtime * (negative ? -1 : 1);
3753 #ifdef HAVE_GMTIME_R
3754 timeptr = gmtime_r(&tm, &gmt);
3755 #elif FEATURE_PTHREAD
3756 privoxy_mutex_lock(&gmtime_mutex);
3757 timeptr = gmtime(&tm);
3758 privoxy_mutex_unlock(&gmtime_mutex);
3760 timeptr = gmtime(&tm);
3762 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3765 *header = strdup("If-Modified-Since: ");
3766 string_append(header, newheader);
3768 if (*header == NULL)
3770 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3771 return JB_ERR_MEMORY;
3774 hours = rtime / 3600;
3775 minutes = rtime / 60 % 60;
3776 seconds = rtime % 60;
3778 log_error(LOG_LEVEL_HEADER,
3779 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3780 *header, (negative) ? "subtracted" : "added", hours,
3781 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3782 seconds, (seconds == 1) ? ")" : "s)");
3791 /*********************************************************************
3793 * Function : client_if_none_match
3795 * Description : Remove the If-None-Match header.
3798 * 1 : csp = Current client state (buffers, headers, etc...)
3799 * 2 : header = On input, pointer to header to modify.
3800 * On output, pointer to the modified header, or NULL
3801 * to remove the header. This function frees the
3802 * original string if necessary.
3804 * Returns : JB_ERR_OK on success, or
3805 * JB_ERR_MEMORY on out-of-memory error.
3807 *********************************************************************/
3808 static jb_err client_if_none_match(struct client_state *csp, char **header)
3810 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3812 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3820 /*********************************************************************
3822 * Function : client_x_filter
3824 * Description : Disables filtering if the client set "X-Filter: No".
3825 * Called from `sed'.
3828 * 1 : csp = Current client state (buffers, headers, etc...)
3829 * 2 : header = On input, pointer to header to modify.
3830 * On output, pointer to the modified header, or NULL
3831 * to remove the header. This function frees the
3832 * original string if necessary.
3834 * Returns : JB_ERR_OK on success
3836 *********************************************************************/
3837 jb_err client_x_filter(struct client_state *csp, char **header)
3839 if ( 0 == strcmpic(*header, "X-Filter: No"))
3841 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3843 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3847 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3849 log_error(LOG_LEVEL_HEADER,
3850 "force-text-mode overruled the client's request to fetch without filtering!");
3854 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3855 csp->flags |= CSP_FLAG_NO_FILTERING;
3856 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3858 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3866 /*********************************************************************
3868 * Function : client_range
3870 * Description : Removes Range, Request-Range and If-Range headers if
3871 * content filtering is enabled. If the client's version
3872 * of the document has been altered by Privoxy, the server
3873 * could interpret the range differently than the client
3874 * intended in which case the user could end up with
3875 * corrupted content.
3878 * 1 : csp = Current client state (buffers, headers, etc...)
3879 * 2 : header = On input, pointer to header to modify.
3880 * On output, pointer to the modified header, or NULL
3881 * to remove the header. This function frees the
3882 * original string if necessary.
3884 * Returns : JB_ERR_OK
3886 *********************************************************************/
3887 static jb_err client_range(struct client_state *csp, char **header)
3889 if (content_filters_enabled(csp->action))
3891 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3892 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3899 /* the following functions add headers directly to the header list */
3901 /*********************************************************************
3903 * Function : client_host_adder
3905 * Description : Adds the Host: header field if it is missing.
3906 * Called from `sed'.
3909 * 1 : csp = Current client state (buffers, headers, etc...)
3911 * Returns : JB_ERR_OK on success, or
3912 * JB_ERR_MEMORY on out-of-memory error.
3914 *********************************************************************/
3915 static jb_err client_host_adder(struct client_state *csp)
3920 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3922 /* Header already set by the client, nothing to do. */
3926 if ( !csp->http->hostport || !*(csp->http->hostport))
3928 /* XXX: When does this happen and why is it OK? */
3929 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3934 * remove 'user:pass@' from 'proto://user:pass@host'
3936 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3942 p = csp->http->hostport;
3945 /* XXX: Just add it, we already made sure that it will be unique */
3946 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3947 err = enlist_unique_header(csp->headers, "Host", p);
3954 /*********************************************************************
3956 * Function : client_accept_encoding_adder
3958 * Description : Add an Accept-Encoding header to the client's request
3959 * that disables compression if the action applies, and
3960 * the header is not already there. Called from `sed'.
3961 * Note: For HTTP/1.0, the absence of the header is enough.
3964 * 1 : csp = Current client state (buffers, headers, etc...)
3966 * Returns : JB_ERR_OK on success, or
3967 * JB_ERR_MEMORY on out-of-memory error.
3969 *********************************************************************/
3970 static jb_err client_accept_encoding_adder(struct client_state *csp)
3972 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3973 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3975 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3983 /*********************************************************************
3985 * Function : client_xtra_adder
3987 * Description : Used in the add_client_headers list. Called from `sed'.
3990 * 1 : csp = Current client state (buffers, headers, etc...)
3992 * Returns : JB_ERR_OK on success, or
3993 * JB_ERR_MEMORY on out-of-memory error.
3995 *********************************************************************/
3996 static jb_err client_xtra_adder(struct client_state *csp)
3998 struct list_entry *lst;
4001 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
4002 lst ; lst = lst->next)
4004 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
4005 err = enlist(csp->headers, lst->str);
4017 /*********************************************************************
4019 * Function : client_x_forwarded_for_adder
4021 * Description : Used in the add_client_headers list. 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_x_forwarded_for_adder(struct client_state *csp)
4032 char *header = NULL;
4035 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
4036 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
4037 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
4040 * If we aren't adding X-Forwarded-For headers,
4041 * or we already appended an existing X-Forwarded-For
4042 * header, there's nothing left to do here.
4047 header = strdup("X-Forwarded-For: ");
4048 string_append(&header, csp->ip_addr_str);
4052 return JB_ERR_MEMORY;
4055 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
4056 err = enlist(csp->headers, header);
4063 /*********************************************************************
4065 * Function : server_connection_close_adder
4067 * Description : "Temporary" fix for the needed but missing HTTP/1.1
4068 * support. Adds a "Connection: close" header to csp->headers
4069 * unless the header was already present. Called from `sed'.
4071 * FIXME: This whole function shouldn't be neccessary!
4074 * 1 : csp = Current client state (buffers, headers, etc...)
4076 * Returns : JB_ERR_OK on success, or
4077 * JB_ERR_MEMORY on out-of-memory error.
4079 *********************************************************************/
4080 static jb_err server_connection_close_adder(struct client_state *csp)
4082 const unsigned int flags = csp->flags;
4083 const char *response_status_line = csp->headers->first->str;
4085 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4086 && (flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET))
4092 * XXX: if we downgraded the response, this check will fail.
4094 if ((csp->config->feature_flags &
4095 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4096 && (NULL != response_status_line)
4097 && !strncmpic(response_status_line, "HTTP/1.1", 8))
4099 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
4100 "without Connection header implies keep-alive.");
4101 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
4104 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
4106 return enlist(csp->headers, "Connection: close");
4110 /*********************************************************************
4112 * Function : client_connection_header_adder
4114 * Description : Adds a proper "Connection:" header to csp->headers
4115 * unless the header was already present. Called from `sed'.
4118 * 1 : csp = Current client state (buffers, headers, etc...)
4120 * Returns : JB_ERR_OK on success, or
4121 * JB_ERR_MEMORY on out-of-memory error.
4123 *********************************************************************/
4124 static jb_err client_connection_header_adder(struct client_state *csp)
4126 const unsigned int flags = csp->flags;
4127 const char *wanted_header = get_appropiate_connection_header(csp);
4129 if (!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4130 && (flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4135 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
4137 return enlist(csp->headers, wanted_header);
4141 /*********************************************************************
4143 * Function : server_http
4145 * Description : - Save the HTTP Status into csp->http->status
4146 * - Set CT_TABOO to prevent filtering if the answer
4147 * is a partial range (HTTP status 206)
4148 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4152 * 1 : csp = Current client state (buffers, headers, etc...)
4153 * 2 : header = On input, pointer to header to modify.
4154 * On output, pointer to the modified header, or NULL
4155 * to remove the header. This function frees the
4156 * original string if necessary.
4158 * Returns : JB_ERR_OK on success, or
4159 * JB_ERR_MEMORY on out-of-memory error.
4161 *********************************************************************/
4162 static jb_err server_http(struct client_state *csp, char **header)
4164 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
4165 if (csp->http->status == 206)
4167 csp->content_type = CT_TABOO;
4170 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
4172 /* XXX: Should we do a real validity check here? */
4173 if (strlen(*header) > 8)
4176 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
4181 * XXX: Should we block the request or
4182 * enlist a valid status code line here?
4184 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
4185 "Downgrading to HTTP/1.0 impossible.");
4193 /*********************************************************************
4195 * Function : server_set_cookie
4197 * Description : Handle the server "cookie" header properly.
4198 * Log cookie to the jar file. Then "crunch",
4199 * accept or rewrite it to a session cookie.
4200 * Called from `sed'.
4202 * TODO: Allow the user to specify a new expiration
4203 * time to cause the cookie to expire even before the
4204 * browser is closed.
4207 * 1 : csp = Current client state (buffers, headers, etc...)
4208 * 2 : header = On input, pointer to header to modify.
4209 * On output, pointer to the modified header, or NULL
4210 * to remove the header. This function frees the
4211 * original string if necessary.
4213 * Returns : JB_ERR_OK on success, or
4214 * JB_ERR_MEMORY on out-of-memory error.
4216 *********************************************************************/
4217 static jb_err server_set_cookie(struct client_state *csp, char **header)
4224 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4226 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4229 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4231 /* Flag whether or not to log a message */
4234 /* A variable to store the tag we're working on */
4237 /* Skip "Set-Cookie:" (11 characters) in header */
4238 cur_tag = *header + 11;
4240 /* skip whitespace between "Set-Cookie:" and value */
4241 while (*cur_tag && ijb_isspace(*cur_tag))
4246 /* Loop through each tag in the cookie */
4250 char *next_tag = strchr(cur_tag, ';');
4251 if (next_tag != NULL)
4253 /* Skip the ';' character itself */
4256 /* skip whitespace ";" and start of tag */
4257 while (*next_tag && ijb_isspace(*next_tag))
4264 /* "Next tag" is the end of the string */
4265 next_tag = cur_tag + strlen(cur_tag);
4269 * Check the expiration date to see
4270 * if the cookie is still valid, if yes,
4271 * rewrite it to a session cookie.
4273 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4275 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4277 /* Did we detect the date properly? */
4278 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4281 * Nope, treat it as if it was still valid.
4283 * XXX: Should we remove the whole cookie instead?
4285 log_error(LOG_LEVEL_ERROR,
4286 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4287 string_move(cur_tag, next_tag);
4293 * Yes. Check if the cookie is still valid.
4295 * If the cookie is already expired it's probably
4296 * a delete cookie and even if it isn't, the browser
4297 * will discard it anyway.
4301 * XXX: timegm() isn't available on some AmigaOS
4302 * versions and our replacement doesn't work.
4304 * Our options are to either:
4306 * - disable session-cookies-only completely if timegm
4309 * - to simply remove all expired tags, like it has
4310 * been done until Privoxy 3.0.6 and to live with
4311 * the consequence that it can cause login/logout
4312 * problems on servers that don't validate their
4313 * input properly, or
4315 * - to replace it with mktime in which
4316 * case there is a slight chance of valid cookies
4317 * passing as already expired.
4319 * This is the way it's currently done and it's not
4320 * as bad as it sounds. If the missing GMT offset is
4321 * enough to change the result of the expiration check
4322 * the cookie will be only valid for a few hours
4323 * anyway, which in many cases will be shorter
4324 * than a browser session.
4326 if (cookie_time - now < 0)
4328 log_error(LOG_LEVEL_HEADER,
4329 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4330 /* Just in case some clown sets more then one expiration date */
4336 * Still valid, delete expiration date by copying
4337 * the rest of the string over it.
4339 string_move(cur_tag, next_tag);
4341 /* That changed the header, need to issue a log message */
4345 * Note that the next tag has now been moved to *cur_tag,
4346 * so we do not need to update the cur_tag pointer.
4354 /* Move on to next cookie tag */
4361 assert(NULL != *header);
4362 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4371 #ifdef FEATURE_FORCE_LOAD
4372 /*********************************************************************
4374 * Function : strclean
4376 * Description : In-Situ-Eliminate all occurances of substring in
4380 * 1 : string = string to clean
4381 * 2 : substring = substring to eliminate
4383 * Returns : Number of eliminations
4385 *********************************************************************/
4386 int strclean(char *string, const char *substring)
4392 len = strlen(substring);
4394 while((pos = strstr(string, substring)) != NULL)
4401 while (*p++ != '\0');
4408 #endif /* def FEATURE_FORCE_LOAD */
4411 /*********************************************************************
4413 * Function : parse_header_time
4415 * Description : Parses time formats used in HTTP header strings
4416 * to get the numerical respresentation.
4419 * 1 : header_time = HTTP header time as string.
4420 * 2 : result = storage for header_time in seconds
4422 * Returns : JB_ERR_OK if the time format was recognized, or
4423 * JB_ERR_PARSE otherwise.
4425 *********************************************************************/
4426 static jb_err parse_header_time(const char *header_time, time_t *result)
4431 * Zero out gmt to prevent time zone offsets.
4433 * While this is only necessary on some platforms
4434 * (mingw32 for example), I don't know how to
4435 * detect these automatically and doing it everywhere
4438 memset(&gmt, 0, sizeof(gmt));
4440 /* Tue, 02 Jun 2037 20:00:00 */
4441 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4442 /* Tue, 02-Jun-2037 20:00:00 */
4443 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4444 /* Tue, 02-Jun-37 20:00:00 */
4445 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4446 /* Tuesday, 02-Jun-2037 20:00:00 */
4447 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4448 /* Tuesday Jun 02 20:00:00 2037 */
4449 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4451 return JB_ERR_PARSE;
4454 *result = timegm(&gmt);
4461 /*********************************************************************
4463 * Function : get_destination_from_headers
4465 * Description : Parse the "Host:" header to get the request's destination.
4466 * Only needed if the client's request was forcefully
4467 * redirected into Privoxy.
4469 * Code mainly copied from client_host() which is currently
4470 * run too late for this purpose.
4473 * 1 : headers = List of headers (one of them hopefully being
4474 * the "Host:" header)
4475 * 2 : http = storage for the result (host, port and hostport).
4477 * Returns : JB_ERR_MEMORY in case of memory problems,
4478 * JB_ERR_PARSE if the host header couldn't be found,
4479 * JB_ERR_OK otherwise.
4481 *********************************************************************/
4482 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4488 host = get_header_value(headers, "Host:");
4492 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4493 return JB_ERR_PARSE;
4496 if (NULL == (p = strdup((host))))
4498 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4499 return JB_ERR_MEMORY;
4502 if (NULL == (q = strdup(p)))
4505 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4506 return JB_ERR_MEMORY;
4509 freez(http->hostport);
4513 q = strchr(http->host, ':');
4516 /* Terminate hostname and evaluate port string */
4518 http->port = atoi(q);
4522 http->port = http->ssl ? 443 : 80;
4525 /* Rebuild request URL */
4527 http->url = strdup(http->ssl ? "https://" : "http://");
4528 string_append(&http->url, http->hostport);
4529 string_append(&http->url, http->path);
4530 if (http->url == NULL)
4532 return JB_ERR_MEMORY;
4535 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4543 /*********************************************************************
4545 * Function : create_forged_referrer
4547 * Description : Helper for client_referrer to forge a referer as
4548 * 'http://[hostname:port/' to fool stupid
4549 * checks for in-site links
4552 * 1 : header = Pointer to header pointer
4553 * 2 : hostport = Host and optionally port as string
4555 * Returns : JB_ERR_OK in case of success, or
4556 * JB_ERR_MEMORY in case of memory problems.
4558 *********************************************************************/
4559 static jb_err create_forged_referrer(char **header, const char *hostport)
4561 assert(NULL == *header);
4563 *header = strdup("Referer: http://");
4564 string_append(header, hostport);
4565 string_append(header, "/");
4567 if (NULL == *header)
4569 return JB_ERR_MEMORY;
4572 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4579 /*********************************************************************
4581 * Function : create_fake_referrer
4583 * Description : Helper for client_referrer to create a fake referrer
4584 * based on a string supplied by the user.
4587 * 1 : header = Pointer to header pointer
4588 * 2 : hosthost = Referrer to fake
4590 * Returns : JB_ERR_OK in case of success, or
4591 * JB_ERR_MEMORY in case of memory problems.
4593 *********************************************************************/
4594 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4596 assert(NULL == *header);
4598 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4600 log_error(LOG_LEVEL_HEADER,
4601 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4603 *header = strdup("Referer: ");
4604 string_append(header, fake_referrer);
4606 if (NULL == *header)
4608 return JB_ERR_MEMORY;
4611 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4618 /*********************************************************************
4620 * Function : handle_conditional_hide_referrer_parameter
4622 * Description : Helper for client_referrer to crunch or forge
4623 * the referrer header if the host has changed.
4626 * 1 : header = Pointer to header pointer
4627 * 2 : host = The target host (may include the port)
4628 * 3 : parameter_conditional_block = Boolean to signal
4629 * if we're in conditional-block mode. If not set,
4630 * we're in conditional-forge mode.
4632 * Returns : JB_ERR_OK in case of success, or
4633 * JB_ERR_MEMORY in case of memory problems.
4635 *********************************************************************/
4636 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4637 const char *host, const int parameter_conditional_block)
4639 char *referer = strdup(*header);
4640 const size_t hostlenght = strlen(host);
4642 if (NULL == referer)
4645 return JB_ERR_MEMORY;
4648 /* referer begins with 'Referer: http[s]://' */
4649 if (hostlenght < (strlen(referer)-17))
4652 * Shorten referer to make sure the referer is blocked
4653 * if www.example.org/www.example.com-shall-see-the-referer/
4654 * links to www.example.com/
4656 referer[hostlenght+17] = '\0';
4658 if (NULL == strstr(referer, host))
4660 /* Host has changed */
4661 if (parameter_conditional_block)
4663 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4670 return create_forged_referrer(header, host);
4680 /*********************************************************************
4682 * Function : get_appropiate_connection_header
4684 * Description : Returns an appropiate Connection header
4685 * depending on whether or not we try to keep
4686 * the connection to the server alive.
4689 * 1 : csp = Current client state (buffers, headers, etc...)
4691 * Returns : Pointer to statically allocated header buffer.
4693 *********************************************************************/
4694 static const char *get_appropiate_connection_header(const struct client_state *csp)
4696 static const char connection_keep_alive[] = "Connection: keep-alive";
4697 static const char connection_close[] = "Connection: close";
4699 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4700 && (csp->http->ssl == 0))
4702 return connection_keep_alive;
4704 return connection_close;