1 const char parsers_rcs[] = "$Id: parsers.c,v 1.150 2008/12/04 18:12:19 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2009 the
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.150 2008/12/04 18:12:19 fabiankeil
48 * Fix some cparser warnings.
50 * Revision 1.149 2008/11/21 18:39:53 fabiankeil
51 * In case of CONNECT requests there's no point
52 * in trying to keep the connection alive.
54 * Revision 1.148 2008/11/16 12:43:49 fabiankeil
55 * Turn keep-alive support into a runtime feature
56 * that is disabled by setting keep-alive-timeout
57 * to a negative value.
59 * Revision 1.147 2008/11/04 17:20:31 fabiankeil
60 * HTTP/1.1 responses without Connection
61 * header imply keep-alive. Act accordingly.
63 * Revision 1.146 2008/10/12 16:46:35 fabiankeil
64 * Remove obsolete warning about delayed delivery with chunked
65 * transfer encoding and FEATURE_CONNECTION_KEEP_ALIVE enabled.
67 * Revision 1.145 2008/10/09 18:21:41 fabiankeil
68 * Flush work-in-progress changes to keep outgoing connections
69 * alive where possible. Incomplete and mostly #ifdef'd out.
71 * Revision 1.144 2008/09/21 13:59:33 fabiankeil
72 * Treat unknown change-x-forwarded-for parameters as fatal errors.
74 * Revision 1.143 2008/09/21 13:36:52 fabiankeil
75 * If change-x-forwarded-for{add} is used and the client
76 * sends multiple X-Forwarded-For headers, append the client's
77 * IP address to each one of them. "Traditionally" we would
78 * lose all but the last one.
80 * Revision 1.142 2008/09/20 10:04:33 fabiankeil
81 * Remove hide-forwarded-for-headers action which has
82 * been obsoleted by change-x-forwarded-for{block}.
84 * Revision 1.141 2008/09/19 15:26:28 fabiankeil
85 * Add change-x-forwarded-for{} action to block or add
86 * X-Forwarded-For headers. Mostly based on code removed
89 * Revision 1.140 2008/09/12 17:51:43 fabiankeil
90 * - A few style fixes.
91 * - Remove a pointless cast.
93 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
94 * Prepare for critical sections on Windows by adding a
95 * layer of indirection before the pthread mutex functions.
97 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
98 * Remove FEATURE_COOKIE_JAR.
100 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
101 * Remove questionable micro-optimizations
102 * whose usefulness has never been measured.
104 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
105 * s@Insufficent@Insufficient@
107 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
108 * The whole point of strclean() is to modify the
109 * first parameter, so don't mark it immutable,
110 * even though the compiler lets us get away with it.
112 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
113 * As the wafer actions are gone, we can stop including encode.h.
115 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
116 * Ditch cast from (char **) to (char **).
118 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
119 * Streamline sed()'s prototype and declare
120 * the header parse and add structures static.
122 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
123 * Factor update_server_headers() out of sed(), ditch the
124 * first_run hack and make server_patterns_light static.
126 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
127 * Wrap memmove() calls in string_move()
128 * to document the purpose in one place.
130 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
131 * Normalize linear header white space.
133 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
134 * If a header is split across multiple lines,
135 * merge them to a single line before parsing them.
137 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
138 * Don't provide get_header() with the whole client state
139 * structure when it only needs access to csp->iob.
141 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
142 * Change content_filters_enabled()'s parameter from
143 * csp->action to action so it can be also used in the
144 * CGI code. Don't bother checking if there are filters
145 * loaded, as that's somewhat besides the point.
147 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
148 * Provide get_http_time() with the buffer size so it doesn't
149 * have to blindly assume that the buffer is big enough.
151 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
152 * Don't pass the whole csp structure to flush_socket()
153 * when it only needs a file descriptor and a buffer.
155 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
156 * Remove send-wafer and send-vanilla-wafer actions.
158 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
159 * Remove inspect-jpegs action.
161 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
162 * Let client_range() also handle Request-Range headers
163 * which apparently are still supported by many servers.
165 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
166 * Improve the warning messages that get logged if the action files
167 * "enable" filters but no filters of that type have been loaded.
169 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
170 * In server_content_type():
171 * - Don't require leading white space when detecting image content types.
172 * - Change '... not replaced ...' message to sound less crazy if the text
173 * type actually is 'text/plain'.
174 * - Mark the 'text/plain == binary data' assumption for removal.
175 * - Remove a bunch of trailing white space.
177 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
178 * Minor server_content_disposition() changes:
179 * - Don't regenerate the header name all lower-case.
180 * - Some white space fixes.
181 * - Remove useless log message in case of ENOMEM.
183 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
184 * Garbage-collect the code to add a X-Forwarded-For
185 * header as it seems to be mostly used by accident.
187 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
188 * Fix a crash on mingw32 with some Last Modified times in the future.
190 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
191 * Remove a "can't happen" error block which, over
192 * time, mutated into a "guaranteed to happen" block.
194 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
195 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
196 * - Use shiny new content_filters_enabled() in client_range().
198 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
199 * I forgot about Poland.
201 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
202 * Remove Range and If-Range headers if content filtering is enabled.
204 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
205 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
206 * client_cookie_adder() to make sure send-vanilla-wafer can be
207 * controlled through tags (and thus regression-tested).
209 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
210 * - Remove "scanning headers for" log message again.
211 * - Some more whitespace fixes.
213 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
214 * Refactor client_referrer() and add conditional-forge parameter.
216 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
217 * A bunch of whitespace fixes, pointy hat to me.
219 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
220 * Fix possible memory corruption in server_http, make sure it's not
221 * executed for ordinary server headers and mark some problems for later.
223 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
224 * Let content-type-overwrite{} honour force-text-mode again.
226 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
227 * - Add prototpyes for the header parsers and make them static.
228 * - Comment out client_accept_encoding_adder() which isn't used right now.
230 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
231 * Move the ACTION_FORCE_TEXT_MODE check out of
232 * server_content_type(). Signal other functions
233 * whether or not a content type has been declared.
234 * Part of the fix for BR#1750917.
236 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
237 * Change sed() to return a jb_err in preparation for forward-override{}.
239 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
240 * Adjust "X-Filter: No" to disable dedicated header filters.
242 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
243 * Streamline client_cookie_adder().
245 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
246 * Make sure filters with dynamic jobs actually use them.
248 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
249 * - Introduce dynamic pcrs jobs that can resolve variables.
250 * - Remove unnecessary update_action_bits_for_all_tags() call.
252 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
253 * - Make tagging based on tags set by earlier taggers
254 * of the same kind possible.
255 * - Log whether or not new tags cause action bits updates
256 * (in which case a matching tag-pattern section exists).
257 * - Log if the user tries to set a tag that is already set.
259 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
260 * Introduce tags as alternative way to specify which
261 * actions apply to a request. At the moment tags can be
262 * created based on client and server headers.
264 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
265 * Log a warning if the content is compressed, filtering is
266 * enabled and Privoxy was compiled without zlib support.
269 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
270 * - Fix warnings when compiled with glibc.
271 * - Don't use crumble() for cookie crunching.
272 * - Move cookie time parsing into parse_header_time().
273 * - Let parse_header_time() return a jb_err code
274 * instead of a pointer that can only be used to
275 * check for NULL anyway.
277 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
278 * - Add better protection against malicious gzip headers.
279 * - Stop logging the first hundred bytes of decompressed content.
280 * It looks like it's working and there is always debug 16.
281 * - Log the content size after decompression in decompress_iob()
282 * instead of pcrs_filter_response().
284 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
285 * - Use dedicated header filter actions instead of abusing "filter".
286 * Replace "filter-client-headers" and "filter-client-headers"
287 * with "server-header-filter" and "client-header-filter".
288 * - Remove filter_client_header() and filter_client_header(),
289 * filter_header() now checks the shiny new
290 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
292 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
293 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
294 * - Handle "Cookie:" and "Connection:" headers a bit smarter
295 * (don't crunch them just to recreate them later on).
296 * - Add another non-standard time format for the cookie
297 * expiration date detection.
298 * - Fix a valgrind warning.
300 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
301 * Improve cookie expiration date detection.
303 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
304 * Don't run server_content_length() the first time
305 * sed() parses server headers; only adjust the
306 * Content-Length header if the page was modified.
308 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
309 * Fix log messages regarding the cookie time format
310 * (cookie and request URL were mixed up).
312 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
313 * - Let decompress_iob()
314 * - not corrupt the content if decompression fails
315 * early. (the first byte(s) were lost).
316 * - use pointer arithmetics with defined outcome for
318 * - Use a different kludge to remember a failed decompression.
320 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
321 * Search for Max-Forwards headers case-insensitive,
322 * don't generate the "501 unsupported" message for invalid
323 * Max-Forwards values and don't increase negative ones.
325 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
326 * - Let server_set_cookie() check the expiration date
327 * of cookies and don't touch the ones that are already
328 * expired. Fixes problems with low quality web applications
329 * as described in BR 932612.
331 * - Adjust comment in client_max_forwards to reality;
332 * remove invalid Max-Forwards headers.
334 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
335 * Stop filter_header() from unintentionally removing
336 * empty header lines that were enlisted by the continue
339 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
340 * - Repeat the request URL before logging any headers.
341 * Makes reading the log easier in case of simultaneous requests.
342 * - If there are more than one Content-Type headers in one request,
343 * use the first one and remove the others.
344 * - Remove "newval" variable in server_content_type().
345 * It's only used once.
347 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
348 * Correct a cast, check inflateEnd() exit code
349 * to see if we have to, replace sprintf calls
352 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
353 * Integrate a modified version of Wil Mahan's
354 * zlib patch (PR #895531).
356 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
357 * Skip empty filter files in filter_header()
358 * but don't ignore the ones that come afterwards.
359 * Fixes BR 1619208, this time for real.
361 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
362 * Reverted parts of my last commit
363 * to keep error handling working.
365 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
366 * Fixed gcc43 conversion warnings.
368 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
369 * Bringing back the "useless" localtime() call
370 * I removed in revision 1.67. On some platforms
371 * it's necessary to prevent time zone offsets.
373 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
374 * Rebuild request URL in get_destination_from_headers()
375 * to make sure redirect{pcrs command} works as expected
376 * for intercepted requests.
378 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
379 * Added get_destination_from_headers().
381 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
382 * Make pthread mutex locking more generic. Instead of
383 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
384 * and use mutex locking unless there is an _r function
385 * available. Better safe than sorry.
387 * Fixes "./configure --disable-pthread" and should result
388 * in less threading-related problems on pthread-using platforms,
389 * but it still doesn't fix BR#1122404.
391 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
392 * The special header "X-Filter: No" now disables
393 * header filtering as well.
395 * Revision 1.73 2006/09/23 13:26:38 roro
396 * Replace TABs by spaces in source code.
398 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
399 * Don't print a log message every time filter_headers is
400 * entered or left. It only creates noise without any real
403 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
404 * Fix +hide-if-modified-since{-n}.
406 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
407 * Have hide-if-modified-since interpret the random
408 * range value as minutes instead of hours. Allows
409 * more fine-grained configuration.
411 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
412 * Always have parse_header_time return a pointer
413 * that actual makes sense, even though we currently
414 * only need it to detect problems.
416 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
417 * Added config option enable-remote-http-toggle
418 * to specify if Privoxy should recognize special
419 * headers (currently only X-Filter) to change its
420 * behaviour. Disabled by default.
422 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
423 * After filtering de-chunked instances, remove
424 * "Transfer-Encoding" header entirely instead of changing
425 * it to "Transfer-Encoding: identity", which is invalid.
426 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
428 * Don't use localtime in parse_header_time. An empty time struct
429 * is good enough, it gets overwritten by strptime anyway.
431 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
432 * Use gmtime_r if available, fallback to gmtime with mutex
433 * protection for MacOSX and use vanilla gmtime for the rest.
435 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
436 * Changed client_referrer to use the right type (size_t) for
437 * hostlenght and to shorten the temporary referrer string with
438 * '\0' instead of adding a useless line break.
440 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
441 * - Back to timegm() using GnuPG's replacement if necessary.
442 * Using mktime() and localtime() could add a on hour offset if
443 * the randomize factor was big enough to lead to a summer/wintertime
446 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
448 * - Moved randomization code into pick_from_range().
450 * - Changed parse_header_time definition.
451 * time_t isn't guaranteed to be signed and
452 * if it isn't, -1 isn't available as error code.
453 * Changed some variable types in client_if_modified_since()
454 * because of the same reason.
456 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
457 * OS/2 compilation compatibility fixups
459 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
460 * Changed include from strptime.c to strptime.h
462 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
463 * Split filter-headers{} into filter-client-headers{}
464 * and filter-server-headers{}.
465 * Added parse_header_time() to share some code.
466 * Replaced timegm() with mktime().
468 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
469 * Windows service integration
471 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
472 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
474 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
475 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
476 * with what was really the latest development (the v_3_0_branch branch)
478 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
479 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
481 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
482 * Add the ability to check jpeg images for invalid
483 * lengths of comment blocks. Defensive strategy
484 * against the exploit:
485 * Microsoft Security Bulletin MS04-028
486 * Buffer Overrun in JPEG Processing (GDI+) Could
487 * Allow Code Execution (833987)
488 * Enabled with +inspect-jpegs in actions files.
490 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
491 * Excluded text/plain objects from filtering. This fixes a
492 * couple of client-crashing, download corruption and
493 * Privoxy performance issues, whose root cause lies in
494 * web servers labelling content of unknown type as text/plain.
496 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
497 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
499 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
500 * Completing the previous change
502 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
503 * Added temporary workaround for bug in PHP < 4.2.3
505 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
506 * 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.
508 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
509 * Fix typo: supressed -> suppressed
511 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
512 * Improved cookie logging
514 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
515 * Added basic support for OPTIONS and TRACE HTTP methods:
516 * - New parser function client_max_forwards which decrements
517 * the Max-Forwards HTTP header field of OPTIONS and TRACE
518 * requests by one before forwarding
519 * - New parser function client_host which extracts the host
520 * and port information from the HTTP header field if the
521 * request URI was not absolute
522 * - Don't crumble and re-add the Host: header, but only generate
523 * and append if missing
525 * Revision 1.56 2002/05/12 15:34:22 jongfoster
526 * Fixing typo in a comment
528 * Revision 1.55 2002/05/08 16:01:07 oes
529 * Optimized add_to_iob:
530 * - Use realloc instead of malloc(), memcpy(), free()
531 * - Expand to powers of two if possible, to get
532 * O(log n) reallocs instead of O(n).
533 * - Moved check for buffer limit here from chat
534 * - Report failure via returncode
536 * Revision 1.54 2002/04/02 15:03:16 oes
537 * Tiny code cosmetics
539 * Revision 1.53 2002/03/26 22:29:55 swa
540 * we have a new homepage!
542 * Revision 1.52 2002/03/24 13:25:43 swa
543 * name change related issues
545 * Revision 1.51 2002/03/13 00:27:05 jongfoster
548 * Revision 1.50 2002/03/12 01:45:35 oes
549 * More verbose logging
551 * Revision 1.49 2002/03/09 20:03:52 jongfoster
552 * - Making various functions return int rather than size_t.
553 * (Undoing a recent change). Since size_t is unsigned on
554 * Windows, functions like read_socket that return -1 on
555 * error cannot return a size_t.
557 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
558 * crashes, and also frequently caused JB to jump to 100%
559 * CPU and stay there. (Because it thought it had just
560 * read ((unsigned)-1) == 4Gb of data...)
562 * - The signature of write_socket has changed, it now simply
563 * returns success=0/failure=nonzero.
565 * - Trying to get rid of a few warnings --with-debug on
566 * Windows, I've introduced a new type "jb_socket". This is
567 * used for the socket file descriptors. On Windows, this
568 * is SOCKET (a typedef for unsigned). Everywhere else, it's
569 * an int. The error value can't be -1 any more, so it's
570 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
571 * Windows it maps to the #define INVALID_SOCKET.)
573 * - The signature of bind_port has changed.
575 * Revision 1.48 2002/03/07 03:46:53 oes
576 * Fixed compiler warnings etc
578 * Revision 1.47 2002/02/20 23:15:13 jongfoster
579 * Parsing functions now handle out-of-memory gracefully by returning
582 * Revision 1.46 2002/01/17 21:03:47 jongfoster
583 * Moving all our URL and URL pattern parsing code to urlmatch.c.
585 * Revision 1.45 2002/01/09 14:33:03 oes
586 * Added support for localtime_r.
588 * Revision 1.44 2001/12/14 01:22:54 steudten
589 * Remove 'user:pass@' from 'proto://user:pass@host' for the
590 * new added header 'Host: ..'. (See Req ID 491818)
592 * Revision 1.43 2001/11/23 00:26:38 jongfoster
593 * Fixing two really stupid errors in my previous commit
595 * Revision 1.42 2001/11/22 21:59:30 jongfoster
596 * Adding code to handle +no-cookies-keep
598 * Revision 1.41 2001/11/05 23:43:05 steudten
599 * Add time+date to log files.
601 * Revision 1.40 2001/10/26 20:13:09 jongfoster
602 * ctype.h is needed in Windows, too.
604 * Revision 1.39 2001/10/26 17:40:04 oes
605 * Introduced get_header_value()
606 * Removed http->user_agent, csp->referrer and csp->accept_types
607 * Removed client_accept()
609 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
610 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
611 * threads to call select() simultaneously. So, it's time to do a real, live,
612 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
613 * (native). Both versions will work, but using __OS2__ offers multi-threading.
615 * Revision 1.37 2001/10/23 21:36:02 jongfoster
616 * Documenting sed()'s error behaviou (doc change only)
618 * Revision 1.36 2001/10/13 12:51:51 joergs
619 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
620 * force-load), instead crumble Host: and add it (again) in client_host_adder
621 * (in case we get a HTTP/1.0 request without Host: header and forward it to
622 * a HTTP/1.1 server/proxy).
624 * Revision 1.35 2001/10/09 22:39:21 jongfoster
625 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
628 * Revision 1.34 2001/10/07 18:50:55 oes
629 * Added server_content_encoding, renamed server_transfer_encoding
631 * Revision 1.33 2001/10/07 18:04:49 oes
632 * Changed server_http11 to server_http and its pattern to "HTTP".
633 * Additional functionality: it now saves the HTTP status into
634 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
636 * Revision 1.32 2001/10/07 15:43:28 oes
637 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
638 * client_te and client_accept_encoding_adder, triggered by the new
639 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
640 * changed to allow only identity and chunked, and the TE header is
641 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
643 * parse_http_request no longer does anything than parsing. The rewriting
644 * of http->cmd and version mangling are gone. It now also recognizes
645 * the put and delete methods and saves the url in http->url. Removed
648 * renamed content_type and content_length to have the server_ prefix
650 * server_content_type now only works if csp->content_type != CT_TABOO
652 * added server_transfer_encoding, which
653 * - Sets CT_TABOO to prohibit filtering if encoding compresses
654 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
655 * - Change from "chunked" to "identity" if body was chunked
656 * but has been de-chunked for filtering.
658 * added server_content_md5 which crunches any Content-MD5 headers
659 * if the body was modified.
661 * made server_http11 conditional on +downgrade action
663 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
665 * Revision 1.31 2001/10/05 14:25:02 oes
666 * Crumble Keep-Alive from Server
668 * Revision 1.30 2001/09/29 12:56:03 joergs
669 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
671 * Revision 1.29 2001/09/24 21:09:24 jongfoster
672 * Fixing 2 memory leaks that Guy spotted, where the paramater to
673 * enlist() was not being free()d.
675 * Revision 1.28 2001/09/22 16:32:28 jongfoster
676 * Removing unused #includes.
678 * Revision 1.27 2001/09/20 15:45:25 steudten
680 * add casting from size_t to int for printf()
681 * remove local variable shadow s2
683 * Revision 1.26 2001/09/16 17:05:14 jongfoster
684 * Removing unused #include showarg.h
686 * Revision 1.25 2001/09/16 13:21:27 jongfoster
687 * Changes to use new list functions.
689 * Revision 1.24 2001/09/13 23:05:50 jongfoster
690 * Changing the string paramater to the header parsers a "const".
692 * Revision 1.23 2001/09/12 18:08:19 steudten
694 * In parse_http_request() header rewriting miss the host value, so
695 * from http://www.mydomain.com the result was just " / " not
696 * http://www.mydomain.com/ in case we forward.
698 * Revision 1.22 2001/09/10 10:58:53 oes
699 * Silenced compiler warnings
701 * Revision 1.21 2001/07/31 14:46:00 oes
702 * - Persistant connections now suppressed
703 * - sed() no longer appends empty header to csp->headers
705 * Revision 1.20 2001/07/30 22:08:36 jongfoster
706 * Tidying up #defines:
707 * - All feature #defines are now of the form FEATURE_xxx
708 * - Permanently turned off WIN_GUI_EDIT
709 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
711 * Revision 1.19 2001/07/25 17:21:54 oes
712 * client_uagent now saves copy of User-Agent: header value
714 * Revision 1.18 2001/07/13 14:02:46 oes
715 * - Included fix to repair broken HTTP requests that
716 * don't contain a path, not even '/'.
717 * - Removed all #ifdef PCRS
718 * - content_type now always inspected and classified as
719 * text, gif or other.
720 * - formatting / comments
722 * Revision 1.17 2001/06/29 21:45:41 oes
723 * Indentation, CRLF->LF, Tab-> Space
725 * Revision 1.16 2001/06/29 13:32:42 oes
727 * - Adapted free_http_request
728 * - Removed logentry from cancelled commit
730 * Revision 1.15 2001/06/03 19:12:38 oes
731 * deleted const struct interceptors
733 * Revision 1.14 2001/06/01 18:49:17 jongfoster
734 * Replaced "list_share" with "list" - the tiny memory gain was not
735 * worth the extra complexity.
737 * Revision 1.13 2001/05/31 21:30:33 jongfoster
738 * Removed list code - it's now in list.[ch]
739 * Renamed "permission" to "action", and changed many features
740 * to use the actions file rather than the global config.
742 * Revision 1.12 2001/05/31 17:33:13 oes
746 * Revision 1.11 2001/05/29 20:11:19 joergs
747 * '/ * inside comment' warning removed.
749 * Revision 1.10 2001/05/29 09:50:24 jongfoster
750 * Unified blocklist/imagelist/permissionslist.
751 * File format is still under discussion, but the internal changes
754 * Also modified interceptor behaviour:
755 * - We now intercept all URLs beginning with one of the following
756 * prefixes (and *only* these prefixes):
758 * * http://ijbswa.sf.net/config/
759 * * http://ijbswa.sourceforge.net/config/
760 * - New interceptors "home page" - go to http://i.j.b/ to see it.
761 * - Internal changes so that intercepted and fast redirect pages
762 * are not replaced with an image.
763 * - Interceptors now have the option to send a binary page direct
764 * to the client. (i.e. ijb-send-banner uses this)
765 * - Implemented show-url-info interceptor. (Which is why I needed
766 * the above interceptors changes - a typical URL is
767 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
768 * The previous mechanism would not have intercepted that, and
769 * if it had been intercepted then it then it would have replaced
772 * Revision 1.9 2001/05/28 17:26:33 jongfoster
773 * Fixing segfault if last header was crunched.
774 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
775 * can use the cross-platform sprintf() instead.)
777 * Revision 1.8 2001/05/27 22:17:04 oes
779 * - re_process_buffer no longer writes the modified buffer
780 * to the client, which was very ugly. It now returns the
781 * buffer, which it is then written by chat.
783 * - content_length now adjusts the Content-Length: header
784 * for modified documents rather than crunch()ing it.
785 * (Length info in csp->content_length, which is 0 for
786 * unmodified documents)
788 * - For this to work, sed() is called twice when filtering.
790 * Revision 1.7 2001/05/27 13:19:06 oes
791 * Patched Joergs solution for the content-length in.
793 * Revision 1.6 2001/05/26 13:39:32 jongfoster
794 * Only crunches Content-Length header if applying RE filtering.
795 * Without this fix, Microsoft Windows Update wouldn't work.
797 * Revision 1.5 2001/05/26 00:28:36 jongfoster
798 * Automatic reloading of config file.
799 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
800 * Most of the global variables have been moved to a new
801 * struct configuration_spec, accessed through csp->config->globalname
802 * Most of the globals remaining are used by the Win32 GUI.
804 * Revision 1.4 2001/05/22 18:46:04 oes
806 * - Enabled filtering banners by size rather than URL
807 * by adding patterns that replace all standard banner
808 * sizes with the "Junkbuster" gif to the re_filterfile
810 * - Enabled filtering WebBugs by providing a pattern
811 * which kills all 1x1 images
813 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
814 * which is selected by the (nonstandard and therefore
815 * capital) letter 'U' in the option string.
816 * It causes the quantifiers to be ungreedy by default.
817 * Appending a ? turns back to greedy (!).
819 * - Added a new interceptor ijb-send-banner, which
820 * sends back the "Junkbuster" gif. Without imagelist or
821 * MSIE detection support, or if tinygif = 1, or the
822 * URL isn't recognized as an imageurl, a lame HTML
823 * explanation is sent instead.
825 * - Added new feature, which permits blocking remote
826 * script redirects and firing back a local redirect
828 * The feature is conditionally compiled, i.e. it
829 * can be disabled with --disable-fast-redirects,
830 * plus it must be activated by a "fast-redirects"
831 * line in the config file, has its own log level
832 * and of course wants to be displayed by show-proxy-args
833 * Note: Boy, all the #ifdefs in 1001 locations and
834 * all the fumbling with configure.in and acconfig.h
835 * were *way* more work than the feature itself :-(
837 * - Because a generic redirect template was needed for
838 * this, tinygif = 3 now uses the same.
840 * - Moved GIFs, and other static HTTP response templates
845 * - Removed some >400 CRs again (Jon, you really worked
848 * Revision 1.3 2001/05/20 01:21:20 jongfoster
849 * Version 2.9.4 checkin.
850 * - Merged popupfile and cookiefile, and added control over PCRS
851 * filtering, in new "permissionsfile".
852 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
853 * file error you now get a message box (in the Win32 GUI) rather
854 * than the program exiting with no explanation.
855 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
857 * - Removed tabs from "config"
858 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
859 * - Bumped up version number.
861 * Revision 1.2 2001/05/17 23:02:36 oes
862 * - Made referrer option accept 'L' as a substitute for '§'
864 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
865 * Initial import of version 2.9.3 source tree
868 *********************************************************************/
875 #include <sys/types.h>
885 * Convince GNU's libc to provide a strptime prototype.
888 #endif /*__GLIBC__ */
895 #if !defined(_WIN32) && !defined(__OS2__)
901 #ifdef FEATURE_PTHREAD
903 /* jcc.h is for mutex semapores only */
904 #endif /* def FEATURE_PTHREAD */
909 #include "jbsockets.h"
910 #include "miscutil.h"
915 #ifndef HAVE_STRPTIME
916 #include "strptime.h"
919 const char parsers_h_rcs[] = PARSERS_H_VERSION;
921 /* Fix a problem with Solaris. There should be no effect on other
923 * Solaris's isspace() is a macro which uses its argument directly
924 * as an array index. Therefore we need to make sure that high-bit
925 * characters generate +ve values, and ideally we also want to make
926 * the argument match the declared parameter type of "int".
928 * Why did they write a character function that can't take a simple
929 * "char" argument? Doh!
931 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
932 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
934 static char *get_header_line(struct iob *iob);
935 static jb_err scan_headers(struct client_state *csp);
936 static jb_err header_tagger(struct client_state *csp, char *header);
937 static jb_err parse_header_time(const char *header_time, time_t *result);
939 static jb_err crumble (struct client_state *csp, char **header);
940 static jb_err filter_header (struct client_state *csp, char **header);
941 static jb_err client_connection (struct client_state *csp, char **header);
942 static jb_err client_referrer (struct client_state *csp, char **header);
943 static jb_err client_uagent (struct client_state *csp, char **header);
944 static jb_err client_ua (struct client_state *csp, char **header);
945 static jb_err client_from (struct client_state *csp, char **header);
946 static jb_err client_send_cookie (struct client_state *csp, char **header);
947 static jb_err client_x_forwarded (struct client_state *csp, char **header);
948 static jb_err client_accept_encoding (struct client_state *csp, char **header);
949 static jb_err client_te (struct client_state *csp, char **header);
950 static jb_err client_max_forwards (struct client_state *csp, char **header);
951 static jb_err client_host (struct client_state *csp, char **header);
952 static jb_err client_if_modified_since (struct client_state *csp, char **header);
953 static jb_err client_accept_language (struct client_state *csp, char **header);
954 static jb_err client_if_none_match (struct client_state *csp, char **header);
955 static jb_err crunch_client_header (struct client_state *csp, char **header);
956 static jb_err client_x_filter (struct client_state *csp, char **header);
957 static jb_err client_range (struct client_state *csp, char **header);
958 static jb_err server_set_cookie (struct client_state *csp, char **header);
959 static jb_err server_connection (struct client_state *csp, char **header);
960 static jb_err server_content_type (struct client_state *csp, char **header);
961 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
962 static jb_err server_content_md5 (struct client_state *csp, char **header);
963 static jb_err server_content_encoding (struct client_state *csp, char **header);
964 static jb_err server_transfer_coding (struct client_state *csp, char **header);
965 static jb_err server_http (struct client_state *csp, char **header);
966 static jb_err crunch_server_header (struct client_state *csp, char **header);
967 static jb_err server_last_modified (struct client_state *csp, char **header);
968 static jb_err server_content_disposition(struct client_state *csp, char **header);
970 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
971 static jb_err server_save_content_length(struct client_state *csp, char **header);
972 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
974 static jb_err client_host_adder (struct client_state *csp);
975 static jb_err client_xtra_adder (struct client_state *csp);
976 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
977 static jb_err client_connection_header_adder(struct client_state *csp);
978 static jb_err server_connection_close_adder(struct client_state *csp);
980 static jb_err create_forged_referrer(char **header, const char *hostport);
981 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
982 static jb_err handle_conditional_hide_referrer_parameter(char **header,
983 const char *host, const int parameter_conditional_block);
984 static const char *get_appropiate_connection_header(const struct client_state *csp);
987 * List of functions to run on a list of headers.
991 /** The header prefix to match */
994 /** The length of the prefix to match */
997 /** The function to apply to this line */
998 const parser_func_ptr parser;
1001 static const struct parsers client_patterns[] = {
1002 { "referer:", 8, client_referrer },
1003 { "user-agent:", 11, client_uagent },
1004 { "ua-", 3, client_ua },
1005 { "from:", 5, client_from },
1006 { "cookie:", 7, client_send_cookie },
1007 { "x-forwarded-for:", 16, client_x_forwarded },
1008 { "Accept-Encoding:", 16, client_accept_encoding },
1009 { "TE:", 3, client_te },
1010 { "Host:", 5, client_host },
1011 { "if-modified-since:", 18, client_if_modified_since },
1012 { "Keep-Alive:", 11, crumble },
1013 { "connection:", 11, client_connection },
1014 { "proxy-connection:", 17, crumble },
1015 { "max-forwards:", 13, client_max_forwards },
1016 { "Accept-Language:", 16, client_accept_language },
1017 { "if-none-match:", 14, client_if_none_match },
1018 { "Range:", 6, client_range },
1019 { "Request-Range:", 14, client_range },
1020 { "If-Range:", 9, client_range },
1021 { "X-Filter:", 9, client_x_filter },
1022 { "*", 0, crunch_client_header },
1023 { "*", 0, filter_header },
1027 static const struct parsers server_patterns[] = {
1028 { "HTTP/", 5, server_http },
1029 { "set-cookie:", 11, server_set_cookie },
1030 { "connection:", 11, server_connection },
1031 { "Content-Type:", 13, server_content_type },
1032 { "Content-MD5:", 12, server_content_md5 },
1033 { "Content-Encoding:", 17, server_content_encoding },
1034 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1035 { "Content-Length:", 15, server_save_content_length },
1036 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1037 { "Transfer-Encoding:", 18, server_transfer_coding },
1038 { "Keep-Alive:", 11, crumble },
1039 { "content-disposition:", 20, server_content_disposition },
1040 { "Last-Modified:", 14, server_last_modified },
1041 { "*", 0, crunch_server_header },
1042 { "*", 0, filter_header },
1046 static const add_header_func_ptr add_client_headers[] = {
1048 client_x_forwarded_for_adder,
1050 /* Temporarily disabled: client_accept_encoding_adder, */
1051 client_connection_header_adder,
1055 static const add_header_func_ptr add_server_headers[] = {
1056 server_connection_close_adder,
1060 /*********************************************************************
1062 * Function : flush_socket
1064 * Description : Write any pending "buffered" content.
1067 * 1 : fd = file descriptor of the socket to read
1068 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1070 * Returns : On success, the number of bytes written are returned (zero
1071 * indicates nothing was written). On error, -1 is returned,
1072 * and errno is set appropriately. If count is zero and the
1073 * file descriptor refers to a regular file, 0 will be
1074 * returned without causing any other effect. For a special
1075 * file, the results are not portable.
1077 *********************************************************************/
1078 int flush_socket(jb_socket fd, struct iob *iob)
1080 int len = iob->eod - iob->cur;
1087 if (write_socket(fd, iob->cur, (size_t)len))
1091 iob->eod = iob->cur = iob->buf;
1097 /*********************************************************************
1099 * Function : add_to_iob
1101 * Description : Add content to the buffered page, expanding the
1102 * buffer if necessary.
1105 * 1 : csp = Current client state (buffers, headers, etc...)
1106 * 2 : buf = holds the content to be added to the page
1107 * 3 : n = number of bytes to be added
1109 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1110 * or buffer limit reached.
1112 *********************************************************************/
1113 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1115 struct iob *iob = csp->iob;
1116 size_t used, offset, need, want;
1119 if (n <= 0) return JB_ERR_OK;
1121 used = (size_t)(iob->eod - iob->buf);
1122 offset = (size_t)(iob->cur - iob->buf);
1123 need = used + (size_t)n + 1;
1126 * If the buffer can't hold the new data, extend it first.
1127 * Use the next power of two if possible, else use the actual need.
1129 if (need > csp->config->buffer_limit)
1131 log_error(LOG_LEVEL_INFO,
1132 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
1133 need, csp->config->buffer_limit);
1134 return JB_ERR_MEMORY;
1137 if (need > iob->size)
1139 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1141 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1145 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1151 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1152 return JB_ERR_MEMORY;
1155 /* Update the iob pointers */
1156 iob->cur = p + offset;
1157 iob->eod = p + used;
1161 /* copy the new data into the iob buffer */
1162 memcpy(iob->eod, buf, (size_t)n);
1164 /* point to the end of the data */
1167 /* null terminate == cheap insurance */
1176 /*********************************************************************
1178 * Function : decompress_iob
1180 * Description : Decompress buffered page, expanding the
1181 * buffer as necessary. csp->iob->cur
1182 * should point to the the beginning of the
1183 * compressed data block.
1186 * 1 : csp = Current client state (buffers, headers, etc...)
1188 * Returns : JB_ERR_OK on success,
1189 * JB_ERR_MEMORY if out-of-memory limit reached, and
1190 * JB_ERR_COMPRESS if error decompressing buffer.
1192 *********************************************************************/
1193 jb_err decompress_iob(struct client_state *csp)
1195 char *buf; /* new, uncompressed buffer */
1196 char *cur; /* Current iob position (to keep the original
1197 * iob->cur unmodified if we return early) */
1198 size_t bufsize; /* allocated size of the new buffer */
1199 size_t old_size; /* Content size before decompression */
1200 size_t skip_size; /* Number of bytes at the beginning of the iob
1201 that we should NOT decompress. */
1202 int status; /* return status of the inflate() call */
1203 z_stream zstr; /* used by calls to zlib */
1205 assert(csp->iob->cur - csp->iob->buf > 0);
1206 assert(csp->iob->eod - csp->iob->cur > 0);
1208 bufsize = csp->iob->size;
1209 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1210 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1212 cur = csp->iob->cur;
1214 if (bufsize < (size_t)10)
1217 * This is to protect the parsing of gzipped data,
1218 * but it should(?) be valid for deflated data also.
1220 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1221 return JB_ERR_COMPRESS;
1224 if (csp->content_type & CT_GZIP)
1227 * Our task is slightly complicated by the facts that data
1228 * compressed by gzip does not include a zlib header, and
1229 * that there is no easily accessible interface in zlib to
1230 * handle a gzip header. We strip off the gzip header by
1231 * hand, and later inform zlib not to expect a header.
1235 * Strip off the gzip header. Please see RFC 1952 for more
1236 * explanation of the appropriate fields.
1238 if ((*cur++ != (char)0x1f)
1239 || (*cur++ != (char)0x8b)
1240 || (*cur++ != Z_DEFLATED))
1242 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1243 return JB_ERR_COMPRESS;
1249 * XXX: These magic numbers should be replaced
1250 * with macros to give a better idea what they do.
1254 /* The gzip header has reserved bits set; bail out. */
1255 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1256 return JB_ERR_COMPRESS;
1260 /* Skip extra fields if necessary. */
1264 * Skip a given number of bytes, specified
1265 * as a 16-bit little-endian value.
1268 * XXX: This code used to be:
1270 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1272 * which I had to change into:
1274 * cur += *cur++ + (*cur++ << 8);
1276 * at which point gcc43 finally noticed that the value
1277 * of cur is undefined (it depends on which of the
1278 * summands is evaluated first).
1280 * I haven't come across a site where this
1281 * code is actually executed yet, but I hope
1285 skip_bytes = *cur++;
1286 skip_bytes = *cur++ << 8;
1288 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1291 * The number of bytes to skip should be positive
1292 * and we'd like to stay in the buffer.
1294 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1296 log_error(LOG_LEVEL_ERROR,
1297 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1299 return JB_ERR_COMPRESS;
1301 log_error(LOG_LEVEL_INFO,
1302 "Skipping %d bytes for gzip compression. Does this sound right?",
1307 /* Skip the filename if necessary. */
1310 /* A null-terminated string is supposed to follow. */
1311 while (*cur++ && (cur < csp->iob->eod));
1315 /* Skip the comment if necessary. */
1318 /* A null-terminated string is supposed to follow. */
1319 while (*cur++ && (cur < csp->iob->eod));
1322 /* Skip the CRC if necessary. */
1328 if (cur >= csp->iob->eod)
1331 * If the current position pointer reached or passed
1332 * the buffer end, we were obviously tricked to skip
1335 log_error(LOG_LEVEL_ERROR,
1336 "Malformed gzip header detected. Aborting decompression.");
1337 return JB_ERR_COMPRESS;
1341 else if (csp->content_type & CT_DEFLATE)
1344 * XXX: The debug level should be lowered
1345 * before the next stable release.
1347 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1349 * In theory (that is, according to RFC 1950), deflate-compressed
1350 * data should begin with a two-byte zlib header and have an
1351 * adler32 checksum at the end. It seems that in practice only
1352 * the raw compressed data is sent. Note that this means that
1353 * we are not RFC 1950-compliant here, but the advantage is that
1354 * this actually works. :)
1356 * We add a dummy null byte to tell zlib where the data ends,
1357 * and later inform it not to expect a header.
1359 * Fortunately, add_to_iob() has thoughtfully null-terminated
1360 * the buffer; we can just increment the end pointer to include
1367 log_error(LOG_LEVEL_ERROR,
1368 "Unable to determine compression format for decompression");
1369 return JB_ERR_COMPRESS;
1372 /* Set up the fields required by zlib. */
1373 zstr.next_in = (Bytef *)cur;
1374 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1375 zstr.zalloc = Z_NULL;
1376 zstr.zfree = Z_NULL;
1377 zstr.opaque = Z_NULL;
1380 * Passing -MAX_WBITS to inflateInit2 tells the library
1381 * that there is no zlib header.
1383 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1385 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1386 return JB_ERR_COMPRESS;
1390 * Next, we allocate new storage for the inflated data.
1391 * We don't modify the existing iob yet, so in case there
1392 * is error in decompression we can recover gracefully.
1394 buf = zalloc(bufsize);
1397 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1398 return JB_ERR_MEMORY;
1401 assert(bufsize >= skip_size);
1402 memcpy(buf, csp->iob->buf, skip_size);
1403 zstr.avail_out = bufsize - skip_size;
1404 zstr.next_out = (Bytef *)buf + skip_size;
1406 /* Try to decompress the whole stream in one shot. */
1407 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1409 /* We need to allocate more memory for the output buffer. */
1411 char *tmpbuf; /* used for realloc'ing the buffer */
1412 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1415 * If zlib wants more data then there's a problem, because
1416 * the complete compressed file should have been buffered.
1418 if (0 == zstr.avail_in)
1420 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1421 return JB_ERR_COMPRESS;
1425 * If we tried the limit and still didn't have enough
1426 * memory, just give up.
1428 if (bufsize == csp->config->buffer_limit)
1430 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1431 return JB_ERR_MEMORY;
1434 /* Try doubling the buffer size each time. */
1437 /* Don't exceed the buffer limit. */
1438 if (bufsize > csp->config->buffer_limit)
1440 bufsize = csp->config->buffer_limit;
1443 /* Try to allocate the new buffer. */
1444 tmpbuf = realloc(buf, bufsize);
1447 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1449 return JB_ERR_MEMORY;
1453 char *oldnext_out = (char *)zstr.next_out;
1456 * Update the fields for inflate() to use the new
1457 * buffer, which may be in a location different from
1460 zstr.avail_out += bufsize - oldbufsize;
1461 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1464 * Compare with an uglier method of calculating these values
1465 * that doesn't require the extra oldbufsize variable.
1467 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1468 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1469 assert(zstr.avail_out > 0U);
1475 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1477 log_error(LOG_LEVEL_ERROR,
1478 "Inconsistent stream state after decompression: %s", zstr.msg);
1480 * XXX: Intentionally no return.
1482 * According to zlib.h, Z_STREAM_ERROR is returned
1483 * "if the stream state was inconsistent".
1485 * I assume in this case inflate()'s status
1486 * would also be something different than Z_STREAM_END
1487 * so this check should be redundant, but lets see.
1491 if (status != Z_STREAM_END)
1493 /* We failed to decompress the stream. */
1494 log_error(LOG_LEVEL_ERROR,
1495 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1496 return JB_ERR_COMPRESS;
1500 * Finally, we can actually update the iob, since the
1501 * decompression was successful. First, free the old
1504 freez(csp->iob->buf);
1506 /* Now, update the iob to use the new buffer. */
1507 csp->iob->buf = buf;
1508 csp->iob->cur = csp->iob->buf + skip_size;
1509 csp->iob->eod = (char *)zstr.next_out;
1510 csp->iob->size = bufsize;
1513 * Make sure the new uncompressed iob obeys some minimal
1514 * consistency conditions.
1516 if ((csp->iob->buf < csp->iob->cur)
1517 && (csp->iob->cur <= csp->iob->eod)
1518 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1520 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1521 if (new_size > (size_t)0)
1523 log_error(LOG_LEVEL_RE_FILTER,
1524 "Decompression successful. Old size: %d, new size: %d.",
1525 old_size, new_size);
1529 /* zlib thinks this is OK, so lets do the same. */
1530 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1535 /* It seems that zlib did something weird. */
1536 log_error(LOG_LEVEL_ERROR,
1537 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1538 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1539 csp->iob->eod, csp->iob->buf + csp->iob->size);
1540 return JB_ERR_COMPRESS;
1546 #endif /* defined(FEATURE_ZLIB) */
1549 /*********************************************************************
1551 * Function : string_move
1553 * Description : memmove wrapper to move the last part of a string
1554 * towards the beginning, overwriting the part in
1555 * the middle. strlcpy() can't be used here as the
1559 * 1 : dst = Destination to overwrite
1560 * 2 : src = Source to move.
1564 *********************************************************************/
1565 static void string_move(char *dst, char *src)
1569 /* +1 to copy the terminating nul as well. */
1570 memmove(dst, src, strlen(src)+1);
1574 /*********************************************************************
1576 * Function : normalize_lws
1578 * Description : Reduces unquoted linear white space in headers
1579 * to a single space in accordance with RFC 2616 2.2.
1580 * This simplifies parsing and filtering later on.
1582 * XXX: Remove log messages before
1583 * the next stable release?
1586 * 1 : header = A header with linear white space to reduce.
1590 *********************************************************************/
1591 static void normalize_lws(char *header)
1597 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1601 while (ijb_isspace(*q))
1605 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1606 string_move(p+1, q);
1611 log_error(LOG_LEVEL_HEADER,
1612 "Converting tab to space in '%s'", header);
1617 char *end_of_token = strstr(p+1, "\"");
1619 if (NULL != end_of_token)
1621 /* Don't mess with quoted text. */
1626 log_error(LOG_LEVEL_HEADER,
1627 "Ignoring single quote in '%s'", header);
1633 p = strchr(header, ':');
1634 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1637 * There's still space before the colon.
1640 string_move(p-1, p);
1645 /*********************************************************************
1647 * Function : get_header
1649 * Description : This (odd) routine will parse the csp->iob
1650 * to get the next complete header.
1653 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1655 * Returns : Any one of the following:
1657 * 1) a pointer to a dynamically allocated string that contains a header line
1658 * 2) NULL indicating that the end of the header was reached
1659 * 3) "" indicating that the end of the iob was reached before finding
1660 * a complete header line.
1662 *********************************************************************/
1663 char *get_header(struct iob *iob)
1667 header = get_header_line(iob);
1669 if ((header == NULL) || (*header == '\0'))
1672 * No complete header read yet, tell the client.
1677 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1680 * Header spans multiple lines, append the next one.
1682 char *continued_header;
1684 continued_header = get_header_line(iob);
1685 if ((continued_header == NULL) || (*continued_header == '\0'))
1688 * No complete header read yet, return what we got.
1689 * XXX: Should "unread" header instead.
1691 log_error(LOG_LEVEL_INFO,
1692 "Failed to read a multi-line header properly: '%s'",
1697 if (JB_ERR_OK != string_join(&header, continued_header))
1699 log_error(LOG_LEVEL_FATAL,
1700 "Out of memory while appending multiple headers.");
1704 /* XXX: remove before next stable release. */
1705 log_error(LOG_LEVEL_HEADER,
1706 "Merged multiple header lines to: '%s'",
1711 normalize_lws(header);
1718 /*********************************************************************
1720 * Function : get_header_line
1722 * Description : This (odd) routine will parse the csp->iob
1723 * to get the next header line.
1726 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1728 * Returns : Any one of the following:
1730 * 1) a pointer to a dynamically allocated string that contains a header line
1731 * 2) NULL indicating that the end of the header was reached
1732 * 3) "" indicating that the end of the iob was reached before finding
1733 * a complete header line.
1735 *********************************************************************/
1736 static char *get_header_line(struct iob *iob)
1740 if ((iob->cur == NULL)
1741 || ((p = strchr(iob->cur, '\n')) == NULL))
1743 return(""); /* couldn't find a complete header */
1748 ret = strdup(iob->cur);
1751 /* FIXME No way to handle error properly */
1752 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1757 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1759 /* is this a blank line (i.e. the end of the header) ? */
1771 /*********************************************************************
1773 * Function : get_header_value
1775 * Description : Get the value of a given header from a chained list
1776 * of header lines or return NULL if no such header is
1777 * present in the list.
1780 * 1 : header_list = pointer to list
1781 * 2 : header_name = string with name of header to look for.
1782 * Trailing colon required, capitalization
1785 * Returns : NULL if not found, else value of header
1787 *********************************************************************/
1788 char *get_header_value(const struct list *header_list, const char *header_name)
1790 struct list_entry *cur_entry;
1794 assert(header_list);
1795 assert(header_name);
1796 length = strlen(header_name);
1798 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1802 if (!strncmpic(cur_entry->str, header_name, length))
1805 * Found: return pointer to start of value
1807 ret = cur_entry->str + length;
1808 while (*ret && ijb_isspace(*ret)) ret++;
1822 /*********************************************************************
1824 * Function : scan_headers
1826 * Description : Scans headers, applies tags and updates action bits.
1829 * 1 : csp = Current client state (buffers, headers, etc...)
1831 * Returns : JB_ERR_OK
1833 *********************************************************************/
1834 static jb_err scan_headers(struct client_state *csp)
1836 struct list_entry *h; /* Header */
1837 jb_err err = JB_ERR_OK;
1839 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1841 /* Header crunch()ed in previous run? -> ignore */
1842 if (h->str == NULL) continue;
1843 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1844 err = header_tagger(csp, h->str);
1851 /*********************************************************************
1855 * Description : add, delete or modify lines in the HTTP header streams.
1856 * On entry, it receives a linked list of headers space
1857 * that was allocated dynamically (both the list nodes
1858 * and the header contents).
1860 * As a side effect it frees the space used by the original
1864 * 1 : csp = Current client state (buffers, headers, etc...)
1865 * 2 : filter_server_headers = Boolean to switch between
1866 * server and header filtering.
1868 * Returns : JB_ERR_OK in case off success, or
1869 * JB_ERR_MEMORY on out-of-memory error.
1871 *********************************************************************/
1872 jb_err sed(struct client_state *csp, int filter_server_headers)
1874 /* XXX: use more descriptive names. */
1875 struct list_entry *p;
1876 const struct parsers *v;
1877 const add_header_func_ptr *f;
1878 jb_err err = JB_ERR_OK;
1880 if (filter_server_headers)
1882 v = server_patterns;
1883 f = add_server_headers;
1887 v = client_patterns;
1888 f = add_client_headers;
1893 while ((err == JB_ERR_OK) && (v->str != NULL))
1895 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1897 /* Header crunch()ed in previous run? -> ignore */
1898 if (p->str == NULL) continue;
1900 /* Does the current parser handle this header? */
1901 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1902 (v->len == CHECK_EVERY_HEADER_REMAINING))
1904 err = v->parser(csp, &(p->str));
1910 /* place additional headers on the csp->headers list */
1911 while ((err == JB_ERR_OK) && (*f))
1921 /*********************************************************************
1923 * Function : update_server_headers
1925 * Description : Updates server headers after the body has been modified.
1928 * 1 : csp = Current client state (buffers, headers, etc...)
1930 * Returns : JB_ERR_OK in case off success, or
1931 * JB_ERR_MEMORY on out-of-memory error.
1933 *********************************************************************/
1934 jb_err update_server_headers(struct client_state *csp)
1936 jb_err err = JB_ERR_OK;
1938 static const struct parsers server_patterns_light[] = {
1939 { "Content-Length:", 15, server_adjust_content_length },
1940 { "Transfer-Encoding:", 18, server_transfer_coding },
1942 { "Content-Encoding:", 17, server_content_encoding },
1943 #endif /* def FEATURE_ZLIB */
1947 if (strncmpic(csp->http->cmd, "HEAD", 4))
1949 const struct parsers *v;
1950 struct list_entry *p;
1952 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1954 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1956 /* Header crunch()ed in previous run? -> ignore */
1957 if (p->str == NULL) continue;
1959 /* Does the current parser handle this header? */
1960 if (strncmpic(p->str, v->str, v->len) == 0)
1962 err = v->parser(csp, (char **)&(p->str));
1972 /*********************************************************************
1974 * Function : header_tagger
1976 * Description : Executes all text substitutions from applying
1977 * tag actions and saves the result as tag.
1979 * XXX: Shares enough code with filter_header() and
1980 * pcrs_filter_response() to warrant some helper functions.
1983 * 1 : csp = Current client state (buffers, headers, etc...)
1984 * 2 : header = Header that is used as tagger input
1986 * Returns : JB_ERR_OK on success and always succeeds
1988 *********************************************************************/
1989 static jb_err header_tagger(struct client_state *csp, char *header)
1991 int wanted_filter_type;
1992 int multi_action_index;
1996 struct file_list *fl;
1997 struct re_filterfile_spec *b;
1998 struct list_entry *tag_name;
2000 int found_filters = 0;
2001 const size_t header_length = strlen(header);
2003 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2005 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
2006 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
2010 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
2011 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
2014 /* Check if there are any filters */
2015 for (i = 0; i < MAX_AF_FILES; i++)
2028 if (0 == found_filters)
2030 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2031 "tagging enabled, but no taggers available.");
2035 for (i = 0; i < MAX_AF_FILES; i++)
2038 if ((NULL == fl) || (NULL == fl->f))
2041 * Either there are no filter files
2042 * left, or this filter file just
2043 * contains no valid filters.
2045 * Continue to be sure we don't miss
2046 * valid filter files that are chained
2047 * after empty or invalid ones.
2052 /* For all filters, */
2053 for (b = fl->f; b; b = b->next)
2055 if (b->type != wanted_filter_type)
2057 /* skip the ones we don't care about, */
2060 /* leaving only taggers that could apply, of which we use the ones, */
2061 for (tag_name = csp->action->multi[multi_action_index]->first;
2062 NULL != tag_name; tag_name = tag_name->next)
2064 /* that do apply, and */
2065 if (strcmp(b->name, tag_name->str) == 0)
2067 char *modified_tag = NULL;
2069 size_t size = header_length;
2070 pcrs_job *joblist = b->joblist;
2072 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2074 if (NULL == joblist)
2076 log_error(LOG_LEVEL_RE_FILTER,
2077 "Tagger %s has empty joblist. Nothing to do.", b->name);
2081 /* execute their pcrs_joblist on the header. */
2082 for (job = joblist; NULL != job; job = job->next)
2084 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2088 /* Success, continue with the modified version. */
2097 /* Tagger doesn't match */
2100 /* Regex failure, log it but continue anyway. */
2101 log_error(LOG_LEVEL_ERROR,
2102 "Problems with tagger \'%s\' and header \'%s\': %s",
2103 b->name, *header, pcrs_strerror(hits));
2105 freez(modified_tag);
2109 if (b->dynamic) pcrs_free_joblist(joblist);
2111 /* If this tagger matched */
2117 * There is to technical limitation which makes
2118 * it impossible to use empty tags, but I assume
2119 * no one would do it intentionally.
2122 log_error(LOG_LEVEL_INFO,
2123 "Tagger \'%s\' created an empty tag. Ignored.",
2128 if (!list_contains_item(csp->tags, tag))
2130 if (JB_ERR_OK != enlist(csp->tags, tag))
2132 log_error(LOG_LEVEL_ERROR,
2133 "Insufficient memory to add tag \'%s\', "
2134 "based on tagger \'%s\' and header \'%s\'",
2135 tag, b->name, *header);
2139 char *action_message;
2141 * update the action bits right away, to make
2142 * tagging based on tags set by earlier taggers
2143 * of the same kind possible.
2145 if (update_action_bits_for_tag(csp, tag))
2147 action_message = "Action bits updated accordingly.";
2151 action_message = "No action bits update necessary.";
2154 log_error(LOG_LEVEL_HEADER,
2155 "Tagger \'%s\' added tag \'%s\'. %s",
2156 b->name, tag, action_message);
2161 /* XXX: Is this log-worthy? */
2162 log_error(LOG_LEVEL_HEADER,
2163 "Tagger \'%s\' didn't add tag \'%s\'. "
2164 "Tag already present", b->name, tag);
2167 } /* if the tagger matched */
2168 } /* if the tagger applies */
2169 } /* for every tagger that could apply */
2170 } /* for all filters */
2171 } /* for all filter files */
2176 /* here begins the family of parser functions that reformat header lines */
2178 /*********************************************************************
2180 * Function : filter_header
2182 * Description : Executes all text substitutions from all applying
2183 * +(server|client)-header-filter actions on the header.
2184 * Most of the code was copied from pcrs_filter_response,
2185 * including the rather short variable names
2188 * 1 : csp = Current client state (buffers, headers, etc...)
2189 * 2 : header = On input, pointer to header to modify.
2190 * On output, pointer to the modified header, or NULL
2191 * to remove the header. This function frees the
2192 * original string if necessary.
2194 * Returns : JB_ERR_OK on success and always succeeds
2196 *********************************************************************/
2197 static jb_err filter_header(struct client_state *csp, char **header)
2201 size_t size = strlen(*header);
2203 char *newheader = NULL;
2206 struct file_list *fl;
2207 struct re_filterfile_spec *b;
2208 struct list_entry *filtername;
2210 int i, found_filters = 0;
2211 int wanted_filter_type;
2212 int multi_action_index;
2214 if (csp->flags & CSP_FLAG_NO_FILTERING)
2219 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2221 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2222 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2226 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2227 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2231 * Need to check the set of re_filterfiles...
2233 for (i = 0; i < MAX_AF_FILES; i++)
2246 if (0 == found_filters)
2248 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2249 "header filtering enabled, but no matching filters available.");
2253 for (i = 0; i < MAX_AF_FILES; i++)
2256 if ((NULL == fl) || (NULL == fl->f))
2259 * Either there are no filter files
2260 * left, or this filter file just
2261 * contains no valid filters.
2263 * Continue to be sure we don't miss
2264 * valid filter files that are chained
2265 * after empty or invalid ones.
2270 * For all applying +filter actions, look if a filter by that
2271 * name exists and if yes, execute its pcrs_joblist on the
2274 for (b = fl->f; b; b = b->next)
2276 if (b->type != wanted_filter_type)
2278 /* Skip other filter types */
2282 for (filtername = csp->action->multi[multi_action_index]->first;
2283 filtername ; filtername = filtername->next)
2285 if (strcmp(b->name, filtername->str) == 0)
2287 int current_hits = 0;
2288 pcrs_job *joblist = b->joblist;
2290 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2292 if (NULL == joblist)
2294 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2298 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2299 *header, size, b->name);
2301 /* Apply all jobs from the joblist */
2302 for (job = joblist; NULL != job; job = job->next)
2304 matches = pcrs_execute(job, *header, size, &newheader, &size);
2307 current_hits += matches;
2308 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2310 *header = newheader;
2312 else if ( 0 == matches )
2314 /* Filter doesn't change header */
2320 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2321 *header, b->name, pcrs_strerror(matches));
2322 if (newheader != NULL)
2324 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2330 if (b->dynamic) pcrs_free_joblist(joblist);
2332 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2333 hits += current_hits;
2340 * Additionally checking for hits is important because if
2341 * the continue hack is triggered, server headers can
2342 * arrive empty to separate multiple heads from each other.
2344 if ((0 == size) && hits)
2346 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2354 /*********************************************************************
2356 * Function : server_connection
2358 * Description : Makes sure that the value of the Connection: header
2359 * is "close" and signals server_connection_close_adder
2363 * 1 : csp = Current client state (buffers, headers, etc...)
2364 * 2 : header = On input, pointer to header to modify.
2365 * On output, pointer to the modified header, or NULL
2366 * to remove the header. This function frees the
2367 * original string if necessary.
2369 * Returns : JB_ERR_OK on success, or
2370 * JB_ERR_MEMORY on out-of-memory error.
2372 *********************************************************************/
2373 static jb_err server_connection(struct client_state *csp, char **header)
2375 char *old_header = *header;
2377 /* Do we have a 'Connection: close' header? */
2378 if (strcmpic(*header, "Connection: close"))
2380 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2381 if ((csp->config->feature_flags &
2382 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2383 && !strcmpic(*header, "Connection: keep-alive"))
2385 /* Remember to keep the connection alive. */
2386 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
2388 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2390 *header = strdup("Connection: close");
2393 return JB_ERR_MEMORY;
2395 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2399 /* Signal server_connection_close_adder() to return early. */
2400 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2405 /*********************************************************************
2407 * Function : client_connection
2409 * Description : Makes sure a proper "Connection:" header is
2410 * set and signals connection_header_adder
2414 * 1 : csp = Current client state (buffers, headers, etc...)
2415 * 2 : header = On input, pointer to header to modify.
2416 * On output, pointer to the modified header, or NULL
2417 * to remove the header. This function frees the
2418 * original string if necessary.
2420 * Returns : JB_ERR_OK on success, or
2421 * JB_ERR_MEMORY on out-of-memory error.
2423 *********************************************************************/
2424 static jb_err client_connection(struct client_state *csp, char **header)
2426 char *old_header = *header;
2427 const char *wanted_header = get_appropiate_connection_header(csp);
2429 if (strcmpic(*header, wanted_header))
2431 *header = strdup(wanted_header);
2434 return JB_ERR_MEMORY;
2436 log_error(LOG_LEVEL_HEADER,
2437 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2441 /* Signal client_connection_close_adder() to return early. */
2442 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2448 /*********************************************************************
2450 * Function : crumble
2452 * Description : This is called if a header matches a pattern to "crunch"
2455 * 1 : csp = Current client state (buffers, headers, etc...)
2456 * 2 : header = On input, pointer to header to modify.
2457 * On output, pointer to the modified header, or NULL
2458 * to remove the header. This function frees the
2459 * original string if necessary.
2461 * Returns : JB_ERR_OK on success, or
2462 * JB_ERR_MEMORY on out-of-memory error.
2464 *********************************************************************/
2465 static jb_err crumble(struct client_state *csp, char **header)
2468 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2474 /*********************************************************************
2476 * Function : crunch_server_header
2478 * Description : Crunch server header if it matches a string supplied by the
2479 * user. Called from `sed'.
2482 * 1 : csp = Current client state (buffers, headers, etc...)
2483 * 2 : header = On input, pointer to header to modify.
2484 * On output, pointer to the modified header, or NULL
2485 * to remove the header. This function frees the
2486 * original string if necessary.
2488 * Returns : JB_ERR_OK on success and always succeeds
2490 *********************************************************************/
2491 static jb_err crunch_server_header(struct client_state *csp, char **header)
2493 const char *crunch_pattern;
2495 /* Do we feel like crunching? */
2496 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2498 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2500 /* Is the current header the lucky one? */
2501 if (strstr(*header, crunch_pattern))
2503 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2512 /*********************************************************************
2514 * Function : server_content_type
2516 * Description : Set the content-type for filterable types (text/.*,
2517 * .*xml.*, javascript and image/gif) unless filtering has been
2518 * forbidden (CT_TABOO) while parsing earlier headers.
2519 * NOTE: Since text/plain is commonly used by web servers
2520 * for files whose correct type is unknown, we don't
2521 * set CT_TEXT for it.
2524 * 1 : csp = Current client state (buffers, headers, etc...)
2525 * 2 : header = On input, pointer to header to modify.
2526 * On output, pointer to the modified header, or NULL
2527 * to remove the header. This function frees the
2528 * original string if necessary.
2530 * Returns : JB_ERR_OK on success, or
2531 * JB_ERR_MEMORY on out-of-memory error.
2533 *********************************************************************/
2534 static jb_err server_content_type(struct client_state *csp, char **header)
2536 /* Remove header if it isn't the first Content-Type header */
2537 if ((csp->content_type & CT_DECLARED))
2540 * Another, slightly slower, way to see if
2541 * we already parsed another Content-Type header.
2543 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2545 log_error(LOG_LEVEL_ERROR,
2546 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2554 * Signal that the Content-Type has been set.
2556 csp->content_type |= CT_DECLARED;
2558 if (!(csp->content_type & CT_TABOO))
2561 * XXX: The assumption that text/plain is a sign of
2562 * binary data seems to be somewhat unreasonable nowadays
2563 * and should be dropped after 3.0.8 is out.
2565 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2566 || strstr(*header, "xml")
2567 || strstr(*header, "application/x-javascript"))
2569 csp->content_type |= CT_TEXT;
2571 else if (strstr(*header, "image/gif"))
2573 csp->content_type |= CT_GIF;
2578 * Are we messing with the content type?
2580 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2583 * Make sure the user doesn't accidently
2584 * change the content type of binary documents.
2586 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2589 *header = strdup("Content-Type: ");
2590 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2594 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2595 return JB_ERR_MEMORY;
2597 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2601 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2602 "It doesn't look like a content type that should be filtered. "
2603 "Enable force-text-mode if you know what you're doing.", *header);
2611 /*********************************************************************
2613 * Function : server_transfer_coding
2615 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2616 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2617 * - Remove header if body was chunked but has been
2618 * de-chunked for filtering.
2621 * 1 : csp = Current client state (buffers, headers, etc...)
2622 * 2 : header = On input, pointer to header to modify.
2623 * On output, pointer to the modified header, or NULL
2624 * to remove the header. This function frees the
2625 * original string if necessary.
2627 * Returns : JB_ERR_OK on success, or
2628 * JB_ERR_MEMORY on out-of-memory error.
2630 *********************************************************************/
2631 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2634 * Turn off pcrs and gif filtering if body compressed
2636 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2640 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2642 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2643 csp->http->cmd, *header);
2644 #endif /* def FEATURE_ZLIB */
2645 csp->content_type = CT_TABOO;
2649 * Raise flag if body chunked
2651 if (strstr(*header, "chunked"))
2653 csp->flags |= CSP_FLAG_CHUNKED;
2656 * If the body was modified, it has been de-chunked first
2657 * and the header must be removed.
2659 * FIXME: If there is more than one transfer encoding,
2660 * only the "chunked" part should be removed here.
2662 if (csp->flags & CSP_FLAG_MODIFIED)
2664 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2673 /*********************************************************************
2675 * Function : server_content_encoding
2677 * Description : This function is run twice for each request,
2678 * unless FEATURE_ZLIB and filtering are disabled.
2680 * The first run is used to check if the content
2681 * is compressed, if FEATURE_ZLIB is disabled
2682 * filtering is then disabled as well, if FEATURE_ZLIB
2683 * is enabled the content is marked for decompression.
2685 * The second run is used to remove the Content-Encoding
2686 * header if the decompression was successful.
2689 * 1 : csp = Current client state (buffers, headers, etc...)
2690 * 2 : header = On input, pointer to header to modify.
2691 * On output, pointer to the modified header, or NULL
2692 * to remove the header. This function frees the
2693 * original string if necessary.
2695 * Returns : JB_ERR_OK on success, or
2696 * JB_ERR_MEMORY on out-of-memory error.
2698 *********************************************************************/
2699 static jb_err server_content_encoding(struct client_state *csp, char **header)
2702 if ((csp->flags & CSP_FLAG_MODIFIED)
2703 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2706 * We successfully decompressed the content,
2707 * and have to clean the header now, so the
2708 * client no longer expects compressed data..
2710 * XXX: There is a difference between cleaning
2711 * and removing it completely.
2713 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2716 else if (strstr(*header, "gzip"))
2718 /* Mark for gzip decompression */
2719 csp->content_type |= CT_GZIP;
2721 else if (strstr(*header, "deflate"))
2723 /* Mark for zlib decompression */
2724 csp->content_type |= CT_DEFLATE;
2726 else if (strstr(*header, "compress"))
2729 * We can't decompress this; therefore we can't filter
2732 csp->content_type |= CT_TABOO;
2734 #else /* !defined(FEATURE_ZLIB) */
2735 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2738 * Body is compressed, turn off pcrs and gif filtering.
2740 csp->content_type |= CT_TABOO;
2743 * Log a warning if the user expects the content to be filtered.
2745 if ((csp->rlist != NULL) &&
2746 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2748 log_error(LOG_LEVEL_INFO,
2749 "Compressed content detected, content filtering disabled. "
2750 "Consider recompiling Privoxy with zlib support or "
2751 "enable the prevent-compression action.");
2754 #endif /* defined(FEATURE_ZLIB) */
2761 /*********************************************************************
2763 * Function : server_adjust_content_length
2765 * Description : Adjust Content-Length header if we modified
2769 * 1 : csp = Current client state (buffers, headers, etc...)
2770 * 2 : header = On input, pointer to header to modify.
2771 * On output, pointer to the modified header, or NULL
2772 * to remove the header. This function frees the
2773 * original string if necessary.
2775 * Returns : JB_ERR_OK on success, or
2776 * JB_ERR_MEMORY on out-of-memory error.
2778 *********************************************************************/
2779 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2781 const size_t max_header_length = 80;
2783 /* Regenerate header if the content was modified. */
2784 if (csp->flags & CSP_FLAG_MODIFIED)
2787 *header = (char *) zalloc(max_header_length);
2788 if (*header == NULL)
2790 return JB_ERR_MEMORY;
2793 snprintf(*header, max_header_length, "Content-Length: %d",
2794 (int)csp->content_length);
2795 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2796 (int)csp->content_length);
2803 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2804 /*********************************************************************
2806 * Function : server_save_content_length
2808 * Description : Save the Content-Length sent by the server.
2811 * 1 : csp = Current client state (buffers, headers, etc...)
2812 * 2 : header = On input, pointer to header to modify.
2813 * On output, pointer to the modified header, or NULL
2814 * to remove the header. This function frees the
2815 * original string if necessary.
2817 * Returns : JB_ERR_OK on success, or
2818 * JB_ERR_MEMORY on out-of-memory error.
2820 *********************************************************************/
2821 static jb_err server_save_content_length(struct client_state *csp, char **header)
2823 unsigned int content_length = 0;
2825 assert(*(*header+14) == ':');
2827 if (1 != sscanf(*header+14, ": %u", &content_length))
2829 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2834 csp->expected_content_length = content_length;
2835 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2840 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2843 /*********************************************************************
2845 * Function : server_content_md5
2847 * Description : Crumble any Content-MD5 headers if the document was
2848 * modified. FIXME: Should we re-compute instead?
2851 * 1 : csp = Current client state (buffers, headers, etc...)
2852 * 2 : header = On input, pointer to header to modify.
2853 * On output, pointer to the modified header, or NULL
2854 * to remove the header. This function frees the
2855 * original string if necessary.
2857 * Returns : JB_ERR_OK on success, or
2858 * JB_ERR_MEMORY on out-of-memory error.
2860 *********************************************************************/
2861 static jb_err server_content_md5(struct client_state *csp, char **header)
2863 if (csp->flags & CSP_FLAG_MODIFIED)
2865 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2873 /*********************************************************************
2875 * Function : server_content_disposition
2877 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2878 * Called from `sed'.
2881 * 1 : csp = Current client state (buffers, headers, etc...)
2882 * 2 : header = On input, pointer to header to modify.
2883 * On output, pointer to the modified header, or NULL
2884 * to remove the header. This function frees the
2885 * original string if necessary.
2887 * Returns : JB_ERR_OK on success, or
2888 * JB_ERR_MEMORY on out-of-memory error.
2890 *********************************************************************/
2891 static jb_err server_content_disposition(struct client_state *csp, char **header)
2896 * Are we messing with the Content-Disposition header?
2898 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2904 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2906 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2909 * Blocking content-disposition header
2911 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2918 * Replacing Content-Disposition header
2921 *header = strdup("Content-Disposition: ");
2922 string_append(header, newval);
2924 if (*header != NULL)
2926 log_error(LOG_LEVEL_HEADER,
2927 "Content-Disposition header crunched and replaced with: %s", *header);
2930 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2934 /*********************************************************************
2936 * Function : server_last_modified
2938 * Description : Changes Last-Modified header to the actual date
2939 * to help hide-if-modified-since.
2940 * Called from `sed'.
2943 * 1 : csp = Current client state (buffers, headers, etc...)
2944 * 2 : header = On input, pointer to header to modify.
2945 * On output, pointer to the modified header, or NULL
2946 * to remove the header. This function frees the
2947 * original string if necessary.
2949 * Returns : JB_ERR_OK on success, or
2950 * JB_ERR_MEMORY on out-of-memory error.
2952 *********************************************************************/
2953 static jb_err server_last_modified(struct client_state *csp, char **header)
2956 char buf[BUFFER_SIZE];
2959 #ifdef HAVE_GMTIME_R
2962 struct tm *timeptr = NULL;
2963 time_t now, last_modified;
2965 long int days, hours, minutes, seconds;
2968 * Are we messing with the Last-Modified header?
2970 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2976 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2978 if (0 == strcmpic(newval, "block") )
2981 * Blocking Last-Modified header. Useless but why not.
2983 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2987 else if (0 == strcmpic(newval, "reset-to-request-time"))
2990 * Setting Last-Modified Header to now.
2992 get_http_time(0, buf, sizeof(buf));
2994 *header = strdup("Last-Modified: ");
2995 string_append(header, buf);
2997 if (*header == NULL)
2999 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
3003 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
3006 else if (0 == strcmpic(newval, "randomize"))
3008 const char *header_time = *header + sizeof("Last-Modified:");
3010 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
3012 #ifdef HAVE_GMTIME_R
3013 timeptr = gmtime_r(&now, &gmt);
3014 #elif FEATURE_PTHREAD
3015 privoxy_mutex_lock(&gmtime_mutex);
3016 timeptr = gmtime(&now);
3017 privoxy_mutex_unlock(&gmtime_mutex);
3019 timeptr = gmtime(&now);
3021 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
3023 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3028 rtime = (long int)difftime(now, last_modified);
3037 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
3039 rtime = pick_from_range(rtime);
3040 if (negative) rtime *= -1;
3041 last_modified += rtime;
3042 #ifdef HAVE_GMTIME_R
3043 timeptr = gmtime_r(&last_modified, &gmt);
3044 #elif FEATURE_PTHREAD
3045 privoxy_mutex_lock(&gmtime_mutex);
3046 timeptr = gmtime(&last_modified);
3047 privoxy_mutex_unlock(&gmtime_mutex);
3049 timeptr = gmtime(&last_modified);
3051 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3053 *header = strdup("Last-Modified: ");
3054 string_append(header, newheader);
3056 if (*header == NULL)
3058 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
3059 return JB_ERR_MEMORY;
3062 days = rtime / (3600 * 24);
3063 hours = rtime / 3600 % 24;
3064 minutes = rtime / 60 % 60;
3065 seconds = rtime % 60;
3067 log_error(LOG_LEVEL_HEADER,
3068 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
3069 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
3070 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3074 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
3083 /*********************************************************************
3085 * Function : client_accept_encoding
3087 * Description : Rewrite the client's Accept-Encoding header so that
3088 * if doesn't allow compression, if the action applies.
3089 * Note: For HTTP/1.0 the absence of the header is enough.
3092 * 1 : csp = Current client state (buffers, headers, etc...)
3093 * 2 : header = On input, pointer to header to modify.
3094 * On output, pointer to the modified header, or NULL
3095 * to remove the header. This function frees the
3096 * original string if necessary.
3098 * Returns : JB_ERR_OK on success, or
3099 * JB_ERR_MEMORY on out-of-memory error.
3101 *********************************************************************/
3102 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3104 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3106 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3110 /* Temporarily disable the correct behaviour to
3111 * work around a PHP bug.
3113 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
3115 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
3116 * if (*header == NULL)
3118 * return JB_ERR_MEMORY;
3129 /*********************************************************************
3131 * Function : client_te
3133 * Description : Rewrite the client's TE header so that
3134 * if doesn't allow compression, if the action applies.
3137 * 1 : csp = Current client state (buffers, headers, etc...)
3138 * 2 : header = On input, pointer to header to modify.
3139 * On output, pointer to the modified header, or NULL
3140 * to remove the header. This function frees the
3141 * original string if necessary.
3143 * Returns : JB_ERR_OK on success, or
3144 * JB_ERR_MEMORY on out-of-memory error.
3146 *********************************************************************/
3147 static jb_err client_te(struct client_state *csp, char **header)
3149 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3152 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3159 /*********************************************************************
3161 * Function : client_referrer
3163 * Description : Handle the "referer" config setting properly.
3164 * Called from `sed'.
3167 * 1 : csp = Current client state (buffers, headers, etc...)
3168 * 2 : header = On input, pointer to header to modify.
3169 * On output, pointer to the modified header, or NULL
3170 * to remove the header. This function frees the
3171 * original string if necessary.
3173 * Returns : JB_ERR_OK on success, or
3174 * JB_ERR_MEMORY on out-of-memory error.
3176 *********************************************************************/
3177 static jb_err client_referrer(struct client_state *csp, char **header)
3179 const char *parameter;
3180 /* booleans for parameters we have to check multiple times */
3181 int parameter_conditional_block;
3182 int parameter_conditional_forge;
3184 #ifdef FEATURE_FORCE_LOAD
3186 * Since the referrer can include the prefix even
3187 * if the request itself is non-forced, we must
3188 * clean it unconditionally.
3190 * XXX: strclean is too broad
3192 strclean(*header, FORCE_PREFIX);
3193 #endif /* def FEATURE_FORCE_LOAD */
3195 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3197 /* Nothing left to do */
3201 parameter = csp->action->string[ACTION_STRING_REFERER];
3202 assert(parameter != NULL);
3203 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3204 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3206 if (!parameter_conditional_block && !parameter_conditional_forge)
3209 * As conditional-block and conditional-forge are the only
3210 * parameters that rely on the original referrer, we can
3211 * remove it now for all the others.
3216 if (0 == strcmpic(parameter, "block"))
3218 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3221 else if (parameter_conditional_block || parameter_conditional_forge)
3223 return handle_conditional_hide_referrer_parameter(header,
3224 csp->http->hostport, parameter_conditional_block);
3226 else if (0 == strcmpic(parameter, "forge"))
3228 return create_forged_referrer(header, csp->http->hostport);
3232 /* interpret parameter as user-supplied referer to fake */
3233 return create_fake_referrer(header, parameter);
3238 /*********************************************************************
3240 * Function : client_accept_language
3242 * Description : Handle the "Accept-Language" config setting properly.
3243 * Called from `sed'.
3246 * 1 : csp = Current client state (buffers, headers, etc...)
3247 * 2 : header = On input, pointer to header to modify.
3248 * On output, pointer to the modified header, or NULL
3249 * to remove the header. This function frees the
3250 * original string if necessary.
3252 * Returns : JB_ERR_OK on success, or
3253 * JB_ERR_MEMORY on out-of-memory error.
3255 *********************************************************************/
3256 static jb_err client_accept_language(struct client_state *csp, char **header)
3261 * Are we messing with the Accept-Language?
3263 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3265 /*I don't think so*/
3269 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3271 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3274 * Blocking Accept-Language header
3276 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3283 * Replacing Accept-Language header
3286 *header = strdup("Accept-Language: ");
3287 string_append(header, newval);
3289 if (*header == NULL)
3291 log_error(LOG_LEVEL_ERROR,
3292 "Insufficient memory. Accept-Language header crunched without replacement.");
3296 log_error(LOG_LEVEL_HEADER,
3297 "Accept-Language header crunched and replaced with: %s", *header);
3300 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3304 /*********************************************************************
3306 * Function : crunch_client_header
3308 * Description : Crunch client header if it matches a string supplied by the
3309 * user. Called from `sed'.
3312 * 1 : csp = Current client state (buffers, headers, etc...)
3313 * 2 : header = On input, pointer to header to modify.
3314 * On output, pointer to the modified header, or NULL
3315 * to remove the header. This function frees the
3316 * original string if necessary.
3318 * Returns : JB_ERR_OK on success and always succeeds
3320 *********************************************************************/
3321 static jb_err crunch_client_header(struct client_state *csp, char **header)
3323 const char *crunch_pattern;
3325 /* Do we feel like crunching? */
3326 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3328 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3330 /* Is the current header the lucky one? */
3331 if (strstr(*header, crunch_pattern))
3333 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3341 /*********************************************************************
3343 * Function : client_uagent
3345 * Description : Handle the "user-agent" config setting properly
3346 * and remember its original value to enable browser
3347 * bug workarounds. Called from `sed'.
3350 * 1 : csp = Current client state (buffers, headers, etc...)
3351 * 2 : header = On input, pointer to header to modify.
3352 * On output, pointer to the modified header, or NULL
3353 * to remove the header. This function frees the
3354 * original string if necessary.
3356 * Returns : JB_ERR_OK on success, or
3357 * JB_ERR_MEMORY on out-of-memory error.
3359 *********************************************************************/
3360 static jb_err client_uagent(struct client_state *csp, char **header)
3364 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3369 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3376 *header = strdup("User-Agent: ");
3377 string_append(header, newval);
3379 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3381 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3385 /*********************************************************************
3387 * Function : client_ua
3389 * Description : Handle "ua-" headers properly. Called from `sed'.
3392 * 1 : csp = Current client state (buffers, headers, etc...)
3393 * 2 : header = On input, pointer to header to modify.
3394 * On output, pointer to the modified header, or NULL
3395 * to remove the header. This function frees the
3396 * original string if necessary.
3398 * Returns : JB_ERR_OK on success, or
3399 * JB_ERR_MEMORY on out-of-memory error.
3401 *********************************************************************/
3402 static jb_err client_ua(struct client_state *csp, char **header)
3404 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3406 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3414 /*********************************************************************
3416 * Function : client_from
3418 * Description : Handle the "from" config setting properly.
3419 * Called from `sed'.
3422 * 1 : csp = Current client state (buffers, headers, etc...)
3423 * 2 : header = On input, pointer to header to modify.
3424 * On output, pointer to the modified header, or NULL
3425 * to remove the header. This function frees the
3426 * original string if necessary.
3428 * Returns : JB_ERR_OK on success, or
3429 * JB_ERR_MEMORY on out-of-memory error.
3431 *********************************************************************/
3432 static jb_err client_from(struct client_state *csp, char **header)
3436 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3443 newval = csp->action->string[ACTION_STRING_FROM];
3446 * Are we blocking the e-mail address?
3448 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3450 log_error(LOG_LEVEL_HEADER, "crunched From!");
3454 log_error(LOG_LEVEL_HEADER, " modified");
3456 *header = strdup("From: ");
3457 string_append(header, newval);
3459 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3463 /*********************************************************************
3465 * Function : client_send_cookie
3467 * Description : Crunches the "cookie" header if necessary.
3468 * Called from `sed'.
3470 * XXX: Stupid name, doesn't send squat.
3473 * 1 : csp = Current client state (buffers, headers, etc...)
3474 * 2 : header = On input, pointer to header to modify.
3475 * On output, pointer to the modified header, or NULL
3476 * to remove the header. This function frees the
3477 * original string if necessary.
3479 * Returns : JB_ERR_OK on success, or
3480 * JB_ERR_MEMORY on out-of-memory error.
3482 *********************************************************************/
3483 static jb_err client_send_cookie(struct client_state *csp, char **header)
3485 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3487 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3495 /*********************************************************************
3497 * Function : client_x_forwarded
3499 * Description : Handle the "x-forwarded-for" config setting properly,
3500 * also used in the add_client_headers list. Called from `sed'.
3503 * 1 : csp = Current client state (buffers, headers, etc...)
3504 * 2 : header = On input, pointer to header to modify.
3505 * On output, pointer to the modified header, or NULL
3506 * to remove the header. This function frees the
3507 * original string if necessary.
3509 * Returns : JB_ERR_OK on success, or
3510 * JB_ERR_MEMORY on out-of-memory error.
3512 *********************************************************************/
3513 jb_err client_x_forwarded(struct client_state *csp, char **header)
3515 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3517 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3519 if (0 == strcmpic(parameter, "block"))
3522 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3524 else if (0 == strcmpic(parameter, "add"))
3526 string_append(header, ", ");
3527 string_append(header, csp->ip_addr_str);
3529 if (*header == NULL)
3531 return JB_ERR_MEMORY;
3533 log_error(LOG_LEVEL_HEADER,
3534 "Appended client IP address to %s", *header);
3535 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3539 log_error(LOG_LEVEL_FATAL,
3540 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3548 /*********************************************************************
3550 * Function : client_max_forwards
3552 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3553 * from the value of the Max-Forwards header field.
3556 * 1 : csp = Current client state (buffers, headers, etc...)
3557 * 2 : header = On input, pointer to header to modify.
3558 * On output, pointer to the modified header, or NULL
3559 * to remove the header. This function frees the
3560 * original string if necessary.
3562 * Returns : JB_ERR_OK on success, or
3563 * JB_ERR_MEMORY on out-of-memory error.
3565 *********************************************************************/
3566 static jb_err client_max_forwards(struct client_state *csp, char **header)
3570 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3571 (0 == strcmpic(csp->http->gpc, "options")))
3573 assert(*(*header+12) == ':');
3574 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3576 if (max_forwards > 0)
3578 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3579 log_error(LOG_LEVEL_HEADER,
3580 "Max-Forwards value for %s request reduced to %d.",
3581 csp->http->gpc, max_forwards);
3583 else if (max_forwards < 0)
3585 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3591 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3600 /*********************************************************************
3602 * Function : client_host
3604 * Description : If the request URI did not contain host and
3605 * port information, parse and evaluate the Host
3608 * Also, kill ill-formed HOST: headers as sent by
3609 * Apple's iTunes software when used with a proxy.
3612 * 1 : csp = Current client state (buffers, headers, etc...)
3613 * 2 : header = On input, pointer to header to modify.
3614 * On output, pointer to the modified header, or NULL
3615 * to remove the header. This function frees the
3616 * original string if necessary.
3618 * Returns : JB_ERR_OK on success, or
3619 * JB_ERR_MEMORY on out-of-memory error.
3621 *********************************************************************/
3622 static jb_err client_host(struct client_state *csp, char **header)
3627 * If the header field name is all upper-case, chances are that it's
3628 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3629 * not a problem -- they are regenerated later.
3631 if ((*header)[1] == 'O')
3633 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3638 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3639 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3642 if (NULL == (p = strdup((*header)+6)))
3644 return JB_ERR_MEMORY;
3647 if (NULL == (q = strdup(p)))
3650 return JB_ERR_MEMORY;
3653 freez(csp->http->hostport);
3654 csp->http->hostport = p;
3655 freez(csp->http->host);
3656 csp->http->host = q;
3657 q = strchr(csp->http->host, ':');
3660 /* Terminate hostname and evaluate port string */
3662 csp->http->port = atoi(q);
3666 csp->http->port = csp->http->ssl ? 443 : 80;
3669 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3670 csp->http->hostport, csp->http->host, csp->http->port);
3673 /* Signal client_host_adder() to return right away */
3674 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3680 /*********************************************************************
3682 * Function : client_if_modified_since
3684 * Description : Remove or modify the If-Modified-Since header.
3687 * 1 : csp = Current client state (buffers, headers, etc...)
3688 * 2 : header = On input, pointer to header to modify.
3689 * On output, pointer to the modified header, or NULL
3690 * to remove the header. This function frees the
3691 * original string if necessary.
3693 * Returns : JB_ERR_OK on success, or
3694 * JB_ERR_MEMORY on out-of-memory error.
3696 *********************************************************************/
3697 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3700 #ifdef HAVE_GMTIME_R
3703 struct tm *timeptr = NULL;
3707 long int hours, minutes, seconds;
3711 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3714 * The client got an error message because of a temporary problem,
3715 * the problem is gone and the client now tries to revalidate our
3716 * error message on the real server. The revalidation would always
3717 * end with the transmission of the whole document and there is
3718 * no need to expose the bogus If-Modified-Since header.
3720 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3723 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3725 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3727 if ((0 == strcmpic(newval, "block")))
3729 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3732 else /* add random value */
3734 const char *header_time = *header + sizeof("If-Modified-Since:");
3736 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3738 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3743 rtime = strtol(newval, &endptr, 0);
3746 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3747 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3754 rtime = pick_from_range(rtime);
3758 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3761 tm += rtime * (negative ? -1 : 1);
3762 #ifdef HAVE_GMTIME_R
3763 timeptr = gmtime_r(&tm, &gmt);
3764 #elif FEATURE_PTHREAD
3765 privoxy_mutex_lock(&gmtime_mutex);
3766 timeptr = gmtime(&tm);
3767 privoxy_mutex_unlock(&gmtime_mutex);
3769 timeptr = gmtime(&tm);
3771 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3774 *header = strdup("If-Modified-Since: ");
3775 string_append(header, newheader);
3777 if (*header == NULL)
3779 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3780 return JB_ERR_MEMORY;
3783 hours = rtime / 3600;
3784 minutes = rtime / 60 % 60;
3785 seconds = rtime % 60;
3787 log_error(LOG_LEVEL_HEADER,
3788 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3789 *header, (negative) ? "subtracted" : "added", hours,
3790 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3791 seconds, (seconds == 1) ? ")" : "s)");
3800 /*********************************************************************
3802 * Function : client_if_none_match
3804 * Description : Remove the If-None-Match header.
3807 * 1 : csp = Current client state (buffers, headers, etc...)
3808 * 2 : header = On input, pointer to header to modify.
3809 * On output, pointer to the modified header, or NULL
3810 * to remove the header. This function frees the
3811 * original string if necessary.
3813 * Returns : JB_ERR_OK on success, or
3814 * JB_ERR_MEMORY on out-of-memory error.
3816 *********************************************************************/
3817 static jb_err client_if_none_match(struct client_state *csp, char **header)
3819 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3821 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3829 /*********************************************************************
3831 * Function : client_x_filter
3833 * Description : Disables filtering if the client set "X-Filter: No".
3834 * Called from `sed'.
3837 * 1 : csp = Current client state (buffers, headers, etc...)
3838 * 2 : header = On input, pointer to header to modify.
3839 * On output, pointer to the modified header, or NULL
3840 * to remove the header. This function frees the
3841 * original string if necessary.
3843 * Returns : JB_ERR_OK on success
3845 *********************************************************************/
3846 jb_err client_x_filter(struct client_state *csp, char **header)
3848 if ( 0 == strcmpic(*header, "X-Filter: No"))
3850 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3852 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3856 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3858 log_error(LOG_LEVEL_HEADER,
3859 "force-text-mode overruled the client's request to fetch without filtering!");
3863 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3864 csp->flags |= CSP_FLAG_NO_FILTERING;
3865 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3867 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3875 /*********************************************************************
3877 * Function : client_range
3879 * Description : Removes Range, Request-Range and If-Range headers if
3880 * content filtering is enabled. If the client's version
3881 * of the document has been altered by Privoxy, the server
3882 * could interpret the range differently than the client
3883 * intended in which case the user could end up with
3884 * corrupted content.
3887 * 1 : csp = Current client state (buffers, headers, etc...)
3888 * 2 : header = On input, pointer to header to modify.
3889 * On output, pointer to the modified header, or NULL
3890 * to remove the header. This function frees the
3891 * original string if necessary.
3893 * Returns : JB_ERR_OK
3895 *********************************************************************/
3896 static jb_err client_range(struct client_state *csp, char **header)
3898 if (content_filters_enabled(csp->action))
3900 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3901 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3908 /* the following functions add headers directly to the header list */
3910 /*********************************************************************
3912 * Function : client_host_adder
3914 * Description : Adds the Host: header field if it is missing.
3915 * Called from `sed'.
3918 * 1 : csp = Current client state (buffers, headers, etc...)
3920 * Returns : JB_ERR_OK on success, or
3921 * JB_ERR_MEMORY on out-of-memory error.
3923 *********************************************************************/
3924 static jb_err client_host_adder(struct client_state *csp)
3929 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3931 /* Header already set by the client, nothing to do. */
3935 if ( !csp->http->hostport || !*(csp->http->hostport))
3937 /* XXX: When does this happen and why is it OK? */
3938 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3943 * remove 'user:pass@' from 'proto://user:pass@host'
3945 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3951 p = csp->http->hostport;
3954 /* XXX: Just add it, we already made sure that it will be unique */
3955 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3956 err = enlist_unique_header(csp->headers, "Host", p);
3963 /*********************************************************************
3965 * Function : client_accept_encoding_adder
3967 * Description : Add an Accept-Encoding header to the client's request
3968 * that disables compression if the action applies, and
3969 * the header is not already there. Called from `sed'.
3970 * Note: For HTTP/1.0, the absence of the header is enough.
3973 * 1 : csp = Current client state (buffers, headers, etc...)
3975 * Returns : JB_ERR_OK on success, or
3976 * JB_ERR_MEMORY on out-of-memory error.
3978 *********************************************************************/
3979 static jb_err client_accept_encoding_adder(struct client_state *csp)
3981 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3982 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3984 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3992 /*********************************************************************
3994 * Function : client_xtra_adder
3996 * Description : Used in the add_client_headers list. Called from `sed'.
3999 * 1 : csp = Current client state (buffers, headers, etc...)
4001 * Returns : JB_ERR_OK on success, or
4002 * JB_ERR_MEMORY on out-of-memory error.
4004 *********************************************************************/
4005 static jb_err client_xtra_adder(struct client_state *csp)
4007 struct list_entry *lst;
4010 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
4011 lst ; lst = lst->next)
4013 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
4014 err = enlist(csp->headers, lst->str);
4026 /*********************************************************************
4028 * Function : client_x_forwarded_for_adder
4030 * Description : Used in the add_client_headers list. Called from `sed'.
4033 * 1 : csp = Current client state (buffers, headers, etc...)
4035 * Returns : JB_ERR_OK on success, or
4036 * JB_ERR_MEMORY on out-of-memory error.
4038 *********************************************************************/
4039 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
4041 char *header = NULL;
4044 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
4045 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
4046 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
4049 * If we aren't adding X-Forwarded-For headers,
4050 * or we already appended an existing X-Forwarded-For
4051 * header, there's nothing left to do here.
4056 header = strdup("X-Forwarded-For: ");
4057 string_append(&header, csp->ip_addr_str);
4061 return JB_ERR_MEMORY;
4064 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
4065 err = enlist(csp->headers, header);
4072 /*********************************************************************
4074 * Function : server_connection_close_adder
4076 * Description : "Temporary" fix for the needed but missing HTTP/1.1
4077 * support. Adds a "Connection: close" header to csp->headers
4078 * unless the header was already present. Called from `sed'.
4080 * FIXME: This whole function shouldn't be neccessary!
4083 * 1 : csp = Current client state (buffers, headers, etc...)
4085 * Returns : JB_ERR_OK on success, or
4086 * JB_ERR_MEMORY on out-of-memory error.
4088 *********************************************************************/
4089 static jb_err server_connection_close_adder(struct client_state *csp)
4091 const unsigned int flags = csp->flags;
4092 const char *response_status_line = csp->headers->first->str;
4094 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4095 && (flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET))
4101 * XXX: if we downgraded the response, this check will fail.
4103 if ((csp->config->feature_flags &
4104 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4105 && (NULL != response_status_line)
4106 && !strncmpic(response_status_line, "HTTP/1.1", 8))
4108 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
4109 "without Connection header implies keep-alive.");
4110 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
4113 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
4115 return enlist(csp->headers, "Connection: close");
4119 /*********************************************************************
4121 * Function : client_connection_header_adder
4123 * Description : Adds a proper "Connection:" header to csp->headers
4124 * unless the header was already present. Called from `sed'.
4127 * 1 : csp = Current client state (buffers, headers, etc...)
4129 * Returns : JB_ERR_OK on success, or
4130 * JB_ERR_MEMORY on out-of-memory error.
4132 *********************************************************************/
4133 static jb_err client_connection_header_adder(struct client_state *csp)
4135 const unsigned int flags = csp->flags;
4136 const char *wanted_header = get_appropiate_connection_header(csp);
4138 if (!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4139 && (flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4144 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
4146 return enlist(csp->headers, wanted_header);
4150 /*********************************************************************
4152 * Function : server_http
4154 * Description : - Save the HTTP Status into csp->http->status
4155 * - Set CT_TABOO to prevent filtering if the answer
4156 * is a partial range (HTTP status 206)
4157 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4161 * 1 : csp = Current client state (buffers, headers, etc...)
4162 * 2 : header = On input, pointer to header to modify.
4163 * On output, pointer to the modified header, or NULL
4164 * to remove the header. This function frees the
4165 * original string if necessary.
4167 * Returns : JB_ERR_OK on success, or
4168 * JB_ERR_MEMORY on out-of-memory error.
4170 *********************************************************************/
4171 static jb_err server_http(struct client_state *csp, char **header)
4173 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
4174 if (csp->http->status == 206)
4176 csp->content_type = CT_TABOO;
4179 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
4181 /* XXX: Should we do a real validity check here? */
4182 if (strlen(*header) > 8)
4185 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
4190 * XXX: Should we block the request or
4191 * enlist a valid status code line here?
4193 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
4194 "Downgrading to HTTP/1.0 impossible.");
4202 /*********************************************************************
4204 * Function : server_set_cookie
4206 * Description : Handle the server "cookie" header properly.
4207 * Log cookie to the jar file. Then "crunch",
4208 * accept or rewrite it to a session cookie.
4209 * Called from `sed'.
4211 * TODO: Allow the user to specify a new expiration
4212 * time to cause the cookie to expire even before the
4213 * browser is closed.
4216 * 1 : csp = Current client state (buffers, headers, etc...)
4217 * 2 : header = On input, pointer to header to modify.
4218 * On output, pointer to the modified header, or NULL
4219 * to remove the header. This function frees the
4220 * original string if necessary.
4222 * Returns : JB_ERR_OK on success, or
4223 * JB_ERR_MEMORY on out-of-memory error.
4225 *********************************************************************/
4226 static jb_err server_set_cookie(struct client_state *csp, char **header)
4233 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4235 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4238 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4240 /* Flag whether or not to log a message */
4243 /* A variable to store the tag we're working on */
4246 /* Skip "Set-Cookie:" (11 characters) in header */
4247 cur_tag = *header + 11;
4249 /* skip whitespace between "Set-Cookie:" and value */
4250 while (*cur_tag && ijb_isspace(*cur_tag))
4255 /* Loop through each tag in the cookie */
4259 char *next_tag = strchr(cur_tag, ';');
4260 if (next_tag != NULL)
4262 /* Skip the ';' character itself */
4265 /* skip whitespace ";" and start of tag */
4266 while (*next_tag && ijb_isspace(*next_tag))
4273 /* "Next tag" is the end of the string */
4274 next_tag = cur_tag + strlen(cur_tag);
4278 * Check the expiration date to see
4279 * if the cookie is still valid, if yes,
4280 * rewrite it to a session cookie.
4282 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4284 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4286 /* Did we detect the date properly? */
4287 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4290 * Nope, treat it as if it was still valid.
4292 * XXX: Should we remove the whole cookie instead?
4294 log_error(LOG_LEVEL_ERROR,
4295 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4296 string_move(cur_tag, next_tag);
4302 * Yes. Check if the cookie is still valid.
4304 * If the cookie is already expired it's probably
4305 * a delete cookie and even if it isn't, the browser
4306 * will discard it anyway.
4310 * XXX: timegm() isn't available on some AmigaOS
4311 * versions and our replacement doesn't work.
4313 * Our options are to either:
4315 * - disable session-cookies-only completely if timegm
4318 * - to simply remove all expired tags, like it has
4319 * been done until Privoxy 3.0.6 and to live with
4320 * the consequence that it can cause login/logout
4321 * problems on servers that don't validate their
4322 * input properly, or
4324 * - to replace it with mktime in which
4325 * case there is a slight chance of valid cookies
4326 * passing as already expired.
4328 * This is the way it's currently done and it's not
4329 * as bad as it sounds. If the missing GMT offset is
4330 * enough to change the result of the expiration check
4331 * the cookie will be only valid for a few hours
4332 * anyway, which in many cases will be shorter
4333 * than a browser session.
4335 if (cookie_time - now < 0)
4337 log_error(LOG_LEVEL_HEADER,
4338 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4339 /* Just in case some clown sets more then one expiration date */
4345 * Still valid, delete expiration date by copying
4346 * the rest of the string over it.
4348 string_move(cur_tag, next_tag);
4350 /* That changed the header, need to issue a log message */
4354 * Note that the next tag has now been moved to *cur_tag,
4355 * so we do not need to update the cur_tag pointer.
4363 /* Move on to next cookie tag */
4370 assert(NULL != *header);
4371 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4380 #ifdef FEATURE_FORCE_LOAD
4381 /*********************************************************************
4383 * Function : strclean
4385 * Description : In-Situ-Eliminate all occurances of substring in
4389 * 1 : string = string to clean
4390 * 2 : substring = substring to eliminate
4392 * Returns : Number of eliminations
4394 *********************************************************************/
4395 int strclean(char *string, const char *substring)
4401 len = strlen(substring);
4403 while((pos = strstr(string, substring)) != NULL)
4410 while (*p++ != '\0');
4417 #endif /* def FEATURE_FORCE_LOAD */
4420 /*********************************************************************
4422 * Function : parse_header_time
4424 * Description : Parses time formats used in HTTP header strings
4425 * to get the numerical respresentation.
4428 * 1 : header_time = HTTP header time as string.
4429 * 2 : result = storage for header_time in seconds
4431 * Returns : JB_ERR_OK if the time format was recognized, or
4432 * JB_ERR_PARSE otherwise.
4434 *********************************************************************/
4435 static jb_err parse_header_time(const char *header_time, time_t *result)
4440 * Zero out gmt to prevent time zone offsets.
4442 * While this is only necessary on some platforms
4443 * (mingw32 for example), I don't know how to
4444 * detect these automatically and doing it everywhere
4447 memset(&gmt, 0, sizeof(gmt));
4449 /* Tue, 02 Jun 2037 20:00:00 */
4450 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4451 /* Tue, 02-Jun-2037 20:00:00 */
4452 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4453 /* Tue, 02-Jun-37 20:00:00 */
4454 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4455 /* Tuesday, 02-Jun-2037 20:00:00 */
4456 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4457 /* Tuesday Jun 02 20:00:00 2037 */
4458 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4460 return JB_ERR_PARSE;
4463 *result = timegm(&gmt);
4470 /*********************************************************************
4472 * Function : get_destination_from_headers
4474 * Description : Parse the "Host:" header to get the request's destination.
4475 * Only needed if the client's request was forcefully
4476 * redirected into Privoxy.
4478 * Code mainly copied from client_host() which is currently
4479 * run too late for this purpose.
4482 * 1 : headers = List of headers (one of them hopefully being
4483 * the "Host:" header)
4484 * 2 : http = storage for the result (host, port and hostport).
4486 * Returns : JB_ERR_MEMORY in case of memory problems,
4487 * JB_ERR_PARSE if the host header couldn't be found,
4488 * JB_ERR_OK otherwise.
4490 *********************************************************************/
4491 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4497 host = get_header_value(headers, "Host:");
4501 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4502 return JB_ERR_PARSE;
4505 if (NULL == (p = strdup((host))))
4507 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4508 return JB_ERR_MEMORY;
4511 if (NULL == (q = strdup(p)))
4514 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4515 return JB_ERR_MEMORY;
4518 freez(http->hostport);
4522 q = strchr(http->host, ':');
4525 /* Terminate hostname and evaluate port string */
4527 http->port = atoi(q);
4531 http->port = http->ssl ? 443 : 80;
4534 /* Rebuild request URL */
4536 http->url = strdup(http->ssl ? "https://" : "http://");
4537 string_append(&http->url, http->hostport);
4538 string_append(&http->url, http->path);
4539 if (http->url == NULL)
4541 return JB_ERR_MEMORY;
4544 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4552 /*********************************************************************
4554 * Function : create_forged_referrer
4556 * Description : Helper for client_referrer to forge a referer as
4557 * 'http://[hostname:port/' to fool stupid
4558 * checks for in-site links
4561 * 1 : header = Pointer to header pointer
4562 * 2 : hostport = Host and optionally port as string
4564 * Returns : JB_ERR_OK in case of success, or
4565 * JB_ERR_MEMORY in case of memory problems.
4567 *********************************************************************/
4568 static jb_err create_forged_referrer(char **header, const char *hostport)
4570 assert(NULL == *header);
4572 *header = strdup("Referer: http://");
4573 string_append(header, hostport);
4574 string_append(header, "/");
4576 if (NULL == *header)
4578 return JB_ERR_MEMORY;
4581 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4588 /*********************************************************************
4590 * Function : create_fake_referrer
4592 * Description : Helper for client_referrer to create a fake referrer
4593 * based on a string supplied by the user.
4596 * 1 : header = Pointer to header pointer
4597 * 2 : hosthost = Referrer to fake
4599 * Returns : JB_ERR_OK in case of success, or
4600 * JB_ERR_MEMORY in case of memory problems.
4602 *********************************************************************/
4603 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4605 assert(NULL == *header);
4607 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4609 log_error(LOG_LEVEL_HEADER,
4610 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4612 *header = strdup("Referer: ");
4613 string_append(header, fake_referrer);
4615 if (NULL == *header)
4617 return JB_ERR_MEMORY;
4620 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4627 /*********************************************************************
4629 * Function : handle_conditional_hide_referrer_parameter
4631 * Description : Helper for client_referrer to crunch or forge
4632 * the referrer header if the host has changed.
4635 * 1 : header = Pointer to header pointer
4636 * 2 : host = The target host (may include the port)
4637 * 3 : parameter_conditional_block = Boolean to signal
4638 * if we're in conditional-block mode. If not set,
4639 * we're in conditional-forge mode.
4641 * Returns : JB_ERR_OK in case of success, or
4642 * JB_ERR_MEMORY in case of memory problems.
4644 *********************************************************************/
4645 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4646 const char *host, const int parameter_conditional_block)
4648 char *referer = strdup(*header);
4649 const size_t hostlenght = strlen(host);
4650 const char *referer_url = NULL;
4652 if (NULL == referer)
4655 return JB_ERR_MEMORY;
4658 /* referer begins with 'Referer: http[s]://' */
4659 if ((hostlenght+17) < strlen(referer))
4662 * Shorten referer to make sure the referer is blocked
4663 * if www.example.org/www.example.com-shall-see-the-referer/
4664 * links to www.example.com/
4666 referer[hostlenght+17] = '\0';
4668 referer_url = strstr(referer, "http://");
4669 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4671 /* Host has changed, Referer is invalid or a https URL. */
4672 if (parameter_conditional_block)
4674 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4681 return create_forged_referrer(header, host);
4691 /*********************************************************************
4693 * Function : get_appropiate_connection_header
4695 * Description : Returns an appropiate Connection header
4696 * depending on whether or not we try to keep
4697 * the connection to the server alive.
4700 * 1 : csp = Current client state (buffers, headers, etc...)
4702 * Returns : Pointer to statically allocated header buffer.
4704 *********************************************************************/
4705 static const char *get_appropiate_connection_header(const struct client_state *csp)
4707 static const char connection_keep_alive[] = "Connection: keep-alive";
4708 static const char connection_close[] = "Connection: close";
4710 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4711 && (csp->http->ssl == 0))
4713 return connection_keep_alive;
4715 return connection_close;