1 const char parsers_rcs[] = "$Id: parsers.c,v 1.145 2008/10/09 18:21:41 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2008 the SourceForge
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.145 2008/10/09 18:21:41 fabiankeil
48 * Flush work-in-progress changes to keep outgoing connections
49 * alive where possible. Incomplete and mostly #ifdef'd out.
51 * Revision 1.144 2008/09/21 13:59:33 fabiankeil
52 * Treat unknown change-x-forwarded-for parameters as fatal errors.
54 * Revision 1.143 2008/09/21 13:36:52 fabiankeil
55 * If change-x-forwarded-for{add} is used and the client
56 * sends multiple X-Forwarded-For headers, append the client's
57 * IP address to each one of them. "Traditionally" we would
58 * lose all but the last one.
60 * Revision 1.142 2008/09/20 10:04:33 fabiankeil
61 * Remove hide-forwarded-for-headers action which has
62 * been obsoleted by change-x-forwarded-for{block}.
64 * Revision 1.141 2008/09/19 15:26:28 fabiankeil
65 * Add change-x-forwarded-for{} action to block or add
66 * X-Forwarded-For headers. Mostly based on code removed
69 * Revision 1.140 2008/09/12 17:51:43 fabiankeil
70 * - A few style fixes.
71 * - Remove a pointless cast.
73 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
74 * Prepare for critical sections on Windows by adding a
75 * layer of indirection before the pthread mutex functions.
77 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
78 * Remove FEATURE_COOKIE_JAR.
80 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
81 * Remove questionable micro-optimizations
82 * whose usefulness has never been measured.
84 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
85 * s@Insufficent@Insufficient@
87 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
88 * The whole point of strclean() is to modify the
89 * first parameter, so don't mark it immutable,
90 * even though the compiler lets us get away with it.
92 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
93 * As the wafer actions are gone, we can stop including encode.h.
95 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
96 * Ditch cast from (char **) to (char **).
98 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
99 * Streamline sed()'s prototype and declare
100 * the header parse and add structures static.
102 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
103 * Factor update_server_headers() out of sed(), ditch the
104 * first_run hack and make server_patterns_light static.
106 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
107 * Wrap memmove() calls in string_move()
108 * to document the purpose in one place.
110 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
111 * Normalize linear header white space.
113 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
114 * If a header is split across multiple lines,
115 * merge them to a single line before parsing them.
117 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
118 * Don't provide get_header() with the whole client state
119 * structure when it only needs access to csp->iob.
121 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
122 * Change content_filters_enabled()'s parameter from
123 * csp->action to action so it can be also used in the
124 * CGI code. Don't bother checking if there are filters
125 * loaded, as that's somewhat besides the point.
127 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
128 * Provide get_http_time() with the buffer size so it doesn't
129 * have to blindly assume that the buffer is big enough.
131 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
132 * Don't pass the whole csp structure to flush_socket()
133 * when it only needs a file descriptor and a buffer.
135 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
136 * Remove send-wafer and send-vanilla-wafer actions.
138 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
139 * Remove inspect-jpegs action.
141 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
142 * Let client_range() also handle Request-Range headers
143 * which apparently are still supported by many servers.
145 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
146 * Improve the warning messages that get logged if the action files
147 * "enable" filters but no filters of that type have been loaded.
149 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
150 * In server_content_type():
151 * - Don't require leading white space when detecting image content types.
152 * - Change '... not replaced ...' message to sound less crazy if the text
153 * type actually is 'text/plain'.
154 * - Mark the 'text/plain == binary data' assumption for removal.
155 * - Remove a bunch of trailing white space.
157 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
158 * Minor server_content_disposition() changes:
159 * - Don't regenerate the header name all lower-case.
160 * - Some white space fixes.
161 * - Remove useless log message in case of ENOMEM.
163 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
164 * Garbage-collect the code to add a X-Forwarded-For
165 * header as it seems to be mostly used by accident.
167 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
168 * Fix a crash on mingw32 with some Last Modified times in the future.
170 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
171 * Remove a "can't happen" error block which, over
172 * time, mutated into a "guaranteed to happen" block.
174 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
175 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
176 * - Use shiny new content_filters_enabled() in client_range().
178 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
179 * I forgot about Poland.
181 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
182 * Remove Range and If-Range headers if content filtering is enabled.
184 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
185 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
186 * client_cookie_adder() to make sure send-vanilla-wafer can be
187 * controlled through tags (and thus regression-tested).
189 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
190 * - Remove "scanning headers for" log message again.
191 * - Some more whitespace fixes.
193 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
194 * Refactor client_referrer() and add conditional-forge parameter.
196 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
197 * A bunch of whitespace fixes, pointy hat to me.
199 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
200 * Fix possible memory corruption in server_http, make sure it's not
201 * executed for ordinary server headers and mark some problems for later.
203 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
204 * Let content-type-overwrite{} honour force-text-mode again.
206 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
207 * - Add prototpyes for the header parsers and make them static.
208 * - Comment out client_accept_encoding_adder() which isn't used right now.
210 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
211 * Move the ACTION_FORCE_TEXT_MODE check out of
212 * server_content_type(). Signal other functions
213 * whether or not a content type has been declared.
214 * Part of the fix for BR#1750917.
216 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
217 * Change sed() to return a jb_err in preparation for forward-override{}.
219 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
220 * Adjust "X-Filter: No" to disable dedicated header filters.
222 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
223 * Streamline client_cookie_adder().
225 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
226 * Make sure filters with dynamic jobs actually use them.
228 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
229 * - Introduce dynamic pcrs jobs that can resolve variables.
230 * - Remove unnecessary update_action_bits_for_all_tags() call.
232 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
233 * - Make tagging based on tags set by earlier taggers
234 * of the same kind possible.
235 * - Log whether or not new tags cause action bits updates
236 * (in which case a matching tag-pattern section exists).
237 * - Log if the user tries to set a tag that is already set.
239 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
240 * Introduce tags as alternative way to specify which
241 * actions apply to a request. At the moment tags can be
242 * created based on client and server headers.
244 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
245 * Log a warning if the content is compressed, filtering is
246 * enabled and Privoxy was compiled without zlib support.
249 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
250 * - Fix warnings when compiled with glibc.
251 * - Don't use crumble() for cookie crunching.
252 * - Move cookie time parsing into parse_header_time().
253 * - Let parse_header_time() return a jb_err code
254 * instead of a pointer that can only be used to
255 * check for NULL anyway.
257 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
258 * - Add better protection against malicious gzip headers.
259 * - Stop logging the first hundred bytes of decompressed content.
260 * It looks like it's working and there is always debug 16.
261 * - Log the content size after decompression in decompress_iob()
262 * instead of pcrs_filter_response().
264 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
265 * - Use dedicated header filter actions instead of abusing "filter".
266 * Replace "filter-client-headers" and "filter-client-headers"
267 * with "server-header-filter" and "client-header-filter".
268 * - Remove filter_client_header() and filter_client_header(),
269 * filter_header() now checks the shiny new
270 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
272 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
273 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
274 * - Handle "Cookie:" and "Connection:" headers a bit smarter
275 * (don't crunch them just to recreate them later on).
276 * - Add another non-standard time format for the cookie
277 * expiration date detection.
278 * - Fix a valgrind warning.
280 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
281 * Improve cookie expiration date detection.
283 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
284 * Don't run server_content_length() the first time
285 * sed() parses server headers; only adjust the
286 * Content-Length header if the page was modified.
288 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
289 * Fix log messages regarding the cookie time format
290 * (cookie and request URL were mixed up).
292 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
293 * - Let decompress_iob()
294 * - not corrupt the content if decompression fails
295 * early. (the first byte(s) were lost).
296 * - use pointer arithmetics with defined outcome for
298 * - Use a different kludge to remember a failed decompression.
300 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
301 * Search for Max-Forwards headers case-insensitive,
302 * don't generate the "501 unsupported" message for invalid
303 * Max-Forwards values and don't increase negative ones.
305 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
306 * - Let server_set_cookie() check the expiration date
307 * of cookies and don't touch the ones that are already
308 * expired. Fixes problems with low quality web applications
309 * as described in BR 932612.
311 * - Adjust comment in client_max_forwards to reality;
312 * remove invalid Max-Forwards headers.
314 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
315 * Stop filter_header() from unintentionally removing
316 * empty header lines that were enlisted by the continue
319 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
320 * - Repeat the request URL before logging any headers.
321 * Makes reading the log easier in case of simultaneous requests.
322 * - If there are more than one Content-Type headers in one request,
323 * use the first one and remove the others.
324 * - Remove "newval" variable in server_content_type().
325 * It's only used once.
327 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
328 * Correct a cast, check inflateEnd() exit code
329 * to see if we have to, replace sprintf calls
332 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
333 * Integrate a modified version of Wil Mahan's
334 * zlib patch (PR #895531).
336 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
337 * Skip empty filter files in filter_header()
338 * but don't ignore the ones that come afterwards.
339 * Fixes BR 1619208, this time for real.
341 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
342 * Reverted parts of my last commit
343 * to keep error handling working.
345 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
346 * Fixed gcc43 conversion warnings.
348 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
349 * Bringing back the "useless" localtime() call
350 * I removed in revision 1.67. On some platforms
351 * it's necessary to prevent time zone offsets.
353 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
354 * Rebuild request URL in get_destination_from_headers()
355 * to make sure redirect{pcrs command} works as expected
356 * for intercepted requests.
358 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
359 * Added get_destination_from_headers().
361 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
362 * Make pthread mutex locking more generic. Instead of
363 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
364 * and use mutex locking unless there is an _r function
365 * available. Better safe than sorry.
367 * Fixes "./configure --disable-pthread" and should result
368 * in less threading-related problems on pthread-using platforms,
369 * but it still doesn't fix BR#1122404.
371 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
372 * The special header "X-Filter: No" now disables
373 * header filtering as well.
375 * Revision 1.73 2006/09/23 13:26:38 roro
376 * Replace TABs by spaces in source code.
378 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
379 * Don't print a log message every time filter_headers is
380 * entered or left. It only creates noise without any real
383 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
384 * Fix +hide-if-modified-since{-n}.
386 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
387 * Have hide-if-modified-since interpret the random
388 * range value as minutes instead of hours. Allows
389 * more fine-grained configuration.
391 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
392 * Always have parse_header_time return a pointer
393 * that actual makes sense, even though we currently
394 * only need it to detect problems.
396 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
397 * Added config option enable-remote-http-toggle
398 * to specify if Privoxy should recognize special
399 * headers (currently only X-Filter) to change its
400 * behaviour. Disabled by default.
402 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
403 * After filtering de-chunked instances, remove
404 * "Transfer-Encoding" header entirely instead of changing
405 * it to "Transfer-Encoding: identity", which is invalid.
406 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
408 * Don't use localtime in parse_header_time. An empty time struct
409 * is good enough, it gets overwritten by strptime anyway.
411 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
412 * Use gmtime_r if available, fallback to gmtime with mutex
413 * protection for MacOSX and use vanilla gmtime for the rest.
415 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
416 * Changed client_referrer to use the right type (size_t) for
417 * hostlenght and to shorten the temporary referrer string with
418 * '\0' instead of adding a useless line break.
420 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
421 * - Back to timegm() using GnuPG's replacement if necessary.
422 * Using mktime() and localtime() could add a on hour offset if
423 * the randomize factor was big enough to lead to a summer/wintertime
426 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
428 * - Moved randomization code into pick_from_range().
430 * - Changed parse_header_time definition.
431 * time_t isn't guaranteed to be signed and
432 * if it isn't, -1 isn't available as error code.
433 * Changed some variable types in client_if_modified_since()
434 * because of the same reason.
436 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
437 * OS/2 compilation compatibility fixups
439 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
440 * Changed include from strptime.c to strptime.h
442 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
443 * Split filter-headers{} into filter-client-headers{}
444 * and filter-server-headers{}.
445 * Added parse_header_time() to share some code.
446 * Replaced timegm() with mktime().
448 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
449 * Windows service integration
451 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
452 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
454 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
455 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
456 * with what was really the latest development (the v_3_0_branch branch)
458 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
459 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
461 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
462 * Add the ability to check jpeg images for invalid
463 * lengths of comment blocks. Defensive strategy
464 * against the exploit:
465 * Microsoft Security Bulletin MS04-028
466 * Buffer Overrun in JPEG Processing (GDI+) Could
467 * Allow Code Execution (833987)
468 * Enabled with +inspect-jpegs in actions files.
470 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
471 * Excluded text/plain objects from filtering. This fixes a
472 * couple of client-crashing, download corruption and
473 * Privoxy performance issues, whose root cause lies in
474 * web servers labelling content of unknown type as text/plain.
476 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
477 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
479 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
480 * Completing the previous change
482 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
483 * Added temporary workaround for bug in PHP < 4.2.3
485 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
486 * 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.
488 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
489 * Fix typo: supressed -> suppressed
491 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
492 * Improved cookie logging
494 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
495 * Added basic support for OPTIONS and TRACE HTTP methods:
496 * - New parser function client_max_forwards which decrements
497 * the Max-Forwards HTTP header field of OPTIONS and TRACE
498 * requests by one before forwarding
499 * - New parser function client_host which extracts the host
500 * and port information from the HTTP header field if the
501 * request URI was not absolute
502 * - Don't crumble and re-add the Host: header, but only generate
503 * and append if missing
505 * Revision 1.56 2002/05/12 15:34:22 jongfoster
506 * Fixing typo in a comment
508 * Revision 1.55 2002/05/08 16:01:07 oes
509 * Optimized add_to_iob:
510 * - Use realloc instead of malloc(), memcpy(), free()
511 * - Expand to powers of two if possible, to get
512 * O(log n) reallocs instead of O(n).
513 * - Moved check for buffer limit here from chat
514 * - Report failure via returncode
516 * Revision 1.54 2002/04/02 15:03:16 oes
517 * Tiny code cosmetics
519 * Revision 1.53 2002/03/26 22:29:55 swa
520 * we have a new homepage!
522 * Revision 1.52 2002/03/24 13:25:43 swa
523 * name change related issues
525 * Revision 1.51 2002/03/13 00:27:05 jongfoster
528 * Revision 1.50 2002/03/12 01:45:35 oes
529 * More verbose logging
531 * Revision 1.49 2002/03/09 20:03:52 jongfoster
532 * - Making various functions return int rather than size_t.
533 * (Undoing a recent change). Since size_t is unsigned on
534 * Windows, functions like read_socket that return -1 on
535 * error cannot return a size_t.
537 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
538 * crashes, and also frequently caused JB to jump to 100%
539 * CPU and stay there. (Because it thought it had just
540 * read ((unsigned)-1) == 4Gb of data...)
542 * - The signature of write_socket has changed, it now simply
543 * returns success=0/failure=nonzero.
545 * - Trying to get rid of a few warnings --with-debug on
546 * Windows, I've introduced a new type "jb_socket". This is
547 * used for the socket file descriptors. On Windows, this
548 * is SOCKET (a typedef for unsigned). Everywhere else, it's
549 * an int. The error value can't be -1 any more, so it's
550 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
551 * Windows it maps to the #define INVALID_SOCKET.)
553 * - The signature of bind_port has changed.
555 * Revision 1.48 2002/03/07 03:46:53 oes
556 * Fixed compiler warnings etc
558 * Revision 1.47 2002/02/20 23:15:13 jongfoster
559 * Parsing functions now handle out-of-memory gracefully by returning
562 * Revision 1.46 2002/01/17 21:03:47 jongfoster
563 * Moving all our URL and URL pattern parsing code to urlmatch.c.
565 * Revision 1.45 2002/01/09 14:33:03 oes
566 * Added support for localtime_r.
568 * Revision 1.44 2001/12/14 01:22:54 steudten
569 * Remove 'user:pass@' from 'proto://user:pass@host' for the
570 * new added header 'Host: ..'. (See Req ID 491818)
572 * Revision 1.43 2001/11/23 00:26:38 jongfoster
573 * Fixing two really stupid errors in my previous commit
575 * Revision 1.42 2001/11/22 21:59:30 jongfoster
576 * Adding code to handle +no-cookies-keep
578 * Revision 1.41 2001/11/05 23:43:05 steudten
579 * Add time+date to log files.
581 * Revision 1.40 2001/10/26 20:13:09 jongfoster
582 * ctype.h is needed in Windows, too.
584 * Revision 1.39 2001/10/26 17:40:04 oes
585 * Introduced get_header_value()
586 * Removed http->user_agent, csp->referrer and csp->accept_types
587 * Removed client_accept()
589 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
590 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
591 * threads to call select() simultaneously. So, it's time to do a real, live,
592 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
593 * (native). Both versions will work, but using __OS2__ offers multi-threading.
595 * Revision 1.37 2001/10/23 21:36:02 jongfoster
596 * Documenting sed()'s error behaviou (doc change only)
598 * Revision 1.36 2001/10/13 12:51:51 joergs
599 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
600 * force-load), instead crumble Host: and add it (again) in client_host_adder
601 * (in case we get a HTTP/1.0 request without Host: header and forward it to
602 * a HTTP/1.1 server/proxy).
604 * Revision 1.35 2001/10/09 22:39:21 jongfoster
605 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
608 * Revision 1.34 2001/10/07 18:50:55 oes
609 * Added server_content_encoding, renamed server_transfer_encoding
611 * Revision 1.33 2001/10/07 18:04:49 oes
612 * Changed server_http11 to server_http and its pattern to "HTTP".
613 * Additional functionality: it now saves the HTTP status into
614 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
616 * Revision 1.32 2001/10/07 15:43:28 oes
617 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
618 * client_te and client_accept_encoding_adder, triggered by the new
619 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
620 * changed to allow only identity and chunked, and the TE header is
621 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
623 * parse_http_request no longer does anything than parsing. The rewriting
624 * of http->cmd and version mangling are gone. It now also recognizes
625 * the put and delete methods and saves the url in http->url. Removed
628 * renamed content_type and content_length to have the server_ prefix
630 * server_content_type now only works if csp->content_type != CT_TABOO
632 * added server_transfer_encoding, which
633 * - Sets CT_TABOO to prohibit filtering if encoding compresses
634 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
635 * - Change from "chunked" to "identity" if body was chunked
636 * but has been de-chunked for filtering.
638 * added server_content_md5 which crunches any Content-MD5 headers
639 * if the body was modified.
641 * made server_http11 conditional on +downgrade action
643 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
645 * Revision 1.31 2001/10/05 14:25:02 oes
646 * Crumble Keep-Alive from Server
648 * Revision 1.30 2001/09/29 12:56:03 joergs
649 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
651 * Revision 1.29 2001/09/24 21:09:24 jongfoster
652 * Fixing 2 memory leaks that Guy spotted, where the paramater to
653 * enlist() was not being free()d.
655 * Revision 1.28 2001/09/22 16:32:28 jongfoster
656 * Removing unused #includes.
658 * Revision 1.27 2001/09/20 15:45:25 steudten
660 * add casting from size_t to int for printf()
661 * remove local variable shadow s2
663 * Revision 1.26 2001/09/16 17:05:14 jongfoster
664 * Removing unused #include showarg.h
666 * Revision 1.25 2001/09/16 13:21:27 jongfoster
667 * Changes to use new list functions.
669 * Revision 1.24 2001/09/13 23:05:50 jongfoster
670 * Changing the string paramater to the header parsers a "const".
672 * Revision 1.23 2001/09/12 18:08:19 steudten
674 * In parse_http_request() header rewriting miss the host value, so
675 * from http://www.mydomain.com the result was just " / " not
676 * http://www.mydomain.com/ in case we forward.
678 * Revision 1.22 2001/09/10 10:58:53 oes
679 * Silenced compiler warnings
681 * Revision 1.21 2001/07/31 14:46:00 oes
682 * - Persistant connections now suppressed
683 * - sed() no longer appends empty header to csp->headers
685 * Revision 1.20 2001/07/30 22:08:36 jongfoster
686 * Tidying up #defines:
687 * - All feature #defines are now of the form FEATURE_xxx
688 * - Permanently turned off WIN_GUI_EDIT
689 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
691 * Revision 1.19 2001/07/25 17:21:54 oes
692 * client_uagent now saves copy of User-Agent: header value
694 * Revision 1.18 2001/07/13 14:02:46 oes
695 * - Included fix to repair broken HTTP requests that
696 * don't contain a path, not even '/'.
697 * - Removed all #ifdef PCRS
698 * - content_type now always inspected and classified as
699 * text, gif or other.
700 * - formatting / comments
702 * Revision 1.17 2001/06/29 21:45:41 oes
703 * Indentation, CRLF->LF, Tab-> Space
705 * Revision 1.16 2001/06/29 13:32:42 oes
707 * - Adapted free_http_request
708 * - Removed logentry from cancelled commit
710 * Revision 1.15 2001/06/03 19:12:38 oes
711 * deleted const struct interceptors
713 * Revision 1.14 2001/06/01 18:49:17 jongfoster
714 * Replaced "list_share" with "list" - the tiny memory gain was not
715 * worth the extra complexity.
717 * Revision 1.13 2001/05/31 21:30:33 jongfoster
718 * Removed list code - it's now in list.[ch]
719 * Renamed "permission" to "action", and changed many features
720 * to use the actions file rather than the global config.
722 * Revision 1.12 2001/05/31 17:33:13 oes
726 * Revision 1.11 2001/05/29 20:11:19 joergs
727 * '/ * inside comment' warning removed.
729 * Revision 1.10 2001/05/29 09:50:24 jongfoster
730 * Unified blocklist/imagelist/permissionslist.
731 * File format is still under discussion, but the internal changes
734 * Also modified interceptor behaviour:
735 * - We now intercept all URLs beginning with one of the following
736 * prefixes (and *only* these prefixes):
738 * * http://ijbswa.sf.net/config/
739 * * http://ijbswa.sourceforge.net/config/
740 * - New interceptors "home page" - go to http://i.j.b/ to see it.
741 * - Internal changes so that intercepted and fast redirect pages
742 * are not replaced with an image.
743 * - Interceptors now have the option to send a binary page direct
744 * to the client. (i.e. ijb-send-banner uses this)
745 * - Implemented show-url-info interceptor. (Which is why I needed
746 * the above interceptors changes - a typical URL is
747 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
748 * The previous mechanism would not have intercepted that, and
749 * if it had been intercepted then it then it would have replaced
752 * Revision 1.9 2001/05/28 17:26:33 jongfoster
753 * Fixing segfault if last header was crunched.
754 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
755 * can use the cross-platform sprintf() instead.)
757 * Revision 1.8 2001/05/27 22:17:04 oes
759 * - re_process_buffer no longer writes the modified buffer
760 * to the client, which was very ugly. It now returns the
761 * buffer, which it is then written by chat.
763 * - content_length now adjusts the Content-Length: header
764 * for modified documents rather than crunch()ing it.
765 * (Length info in csp->content_length, which is 0 for
766 * unmodified documents)
768 * - For this to work, sed() is called twice when filtering.
770 * Revision 1.7 2001/05/27 13:19:06 oes
771 * Patched Joergs solution for the content-length in.
773 * Revision 1.6 2001/05/26 13:39:32 jongfoster
774 * Only crunches Content-Length header if applying RE filtering.
775 * Without this fix, Microsoft Windows Update wouldn't work.
777 * Revision 1.5 2001/05/26 00:28:36 jongfoster
778 * Automatic reloading of config file.
779 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
780 * Most of the global variables have been moved to a new
781 * struct configuration_spec, accessed through csp->config->globalname
782 * Most of the globals remaining are used by the Win32 GUI.
784 * Revision 1.4 2001/05/22 18:46:04 oes
786 * - Enabled filtering banners by size rather than URL
787 * by adding patterns that replace all standard banner
788 * sizes with the "Junkbuster" gif to the re_filterfile
790 * - Enabled filtering WebBugs by providing a pattern
791 * which kills all 1x1 images
793 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
794 * which is selected by the (nonstandard and therefore
795 * capital) letter 'U' in the option string.
796 * It causes the quantifiers to be ungreedy by default.
797 * Appending a ? turns back to greedy (!).
799 * - Added a new interceptor ijb-send-banner, which
800 * sends back the "Junkbuster" gif. Without imagelist or
801 * MSIE detection support, or if tinygif = 1, or the
802 * URL isn't recognized as an imageurl, a lame HTML
803 * explanation is sent instead.
805 * - Added new feature, which permits blocking remote
806 * script redirects and firing back a local redirect
808 * The feature is conditionally compiled, i.e. it
809 * can be disabled with --disable-fast-redirects,
810 * plus it must be activated by a "fast-redirects"
811 * line in the config file, has its own log level
812 * and of course wants to be displayed by show-proxy-args
813 * Note: Boy, all the #ifdefs in 1001 locations and
814 * all the fumbling with configure.in and acconfig.h
815 * were *way* more work than the feature itself :-(
817 * - Because a generic redirect template was needed for
818 * this, tinygif = 3 now uses the same.
820 * - Moved GIFs, and other static HTTP response templates
825 * - Removed some >400 CRs again (Jon, you really worked
828 * Revision 1.3 2001/05/20 01:21:20 jongfoster
829 * Version 2.9.4 checkin.
830 * - Merged popupfile and cookiefile, and added control over PCRS
831 * filtering, in new "permissionsfile".
832 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
833 * file error you now get a message box (in the Win32 GUI) rather
834 * than the program exiting with no explanation.
835 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
837 * - Removed tabs from "config"
838 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
839 * - Bumped up version number.
841 * Revision 1.2 2001/05/17 23:02:36 oes
842 * - Made referrer option accept 'L' as a substitute for '§'
844 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
845 * Initial import of version 2.9.3 source tree
848 *********************************************************************/
855 #include <sys/types.h>
865 * Convince GNU's libc to provide a strptime prototype.
868 #endif /*__GLIBC__ */
875 #if !defined(_WIN32) && !defined(__OS2__)
881 #ifdef FEATURE_PTHREAD
883 /* jcc.h is for mutex semapores only */
884 #endif /* def FEATURE_PTHREAD */
889 #include "jbsockets.h"
890 #include "miscutil.h"
895 #ifndef HAVE_STRPTIME
896 #include "strptime.h"
899 const char parsers_h_rcs[] = PARSERS_H_VERSION;
901 /* Fix a problem with Solaris. There should be no effect on other
903 * Solaris's isspace() is a macro which uses its argument directly
904 * as an array index. Therefore we need to make sure that high-bit
905 * characters generate +ve values, and ideally we also want to make
906 * the argument match the declared parameter type of "int".
908 * Why did they write a character function that can't take a simple
909 * "char" argument? Doh!
911 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
912 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
914 static char *get_header_line(struct iob *iob);
915 static jb_err scan_headers(struct client_state *csp);
916 static jb_err header_tagger(struct client_state *csp, char *header);
917 static jb_err parse_header_time(const char *header_time, time_t *result);
919 static jb_err crumble (struct client_state *csp, char **header);
920 static jb_err filter_header (struct client_state *csp, char **header);
921 static jb_err client_connection (struct client_state *csp, char **header);
922 static jb_err client_referrer (struct client_state *csp, char **header);
923 static jb_err client_uagent (struct client_state *csp, char **header);
924 static jb_err client_ua (struct client_state *csp, char **header);
925 static jb_err client_from (struct client_state *csp, char **header);
926 static jb_err client_send_cookie (struct client_state *csp, char **header);
927 static jb_err client_x_forwarded (struct client_state *csp, char **header);
928 static jb_err client_accept_encoding (struct client_state *csp, char **header);
929 static jb_err client_te (struct client_state *csp, char **header);
930 static jb_err client_max_forwards (struct client_state *csp, char **header);
931 static jb_err client_host (struct client_state *csp, char **header);
932 static jb_err client_if_modified_since (struct client_state *csp, char **header);
933 static jb_err client_accept_language (struct client_state *csp, char **header);
934 static jb_err client_if_none_match (struct client_state *csp, char **header);
935 static jb_err crunch_client_header (struct client_state *csp, char **header);
936 static jb_err client_x_filter (struct client_state *csp, char **header);
937 static jb_err client_range (struct client_state *csp, char **header);
938 static jb_err server_set_cookie (struct client_state *csp, char **header);
939 static jb_err server_connection (struct client_state *csp, char **header);
940 static jb_err server_content_type (struct client_state *csp, char **header);
941 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
942 static jb_err server_content_md5 (struct client_state *csp, char **header);
943 static jb_err server_content_encoding (struct client_state *csp, char **header);
944 static jb_err server_transfer_coding (struct client_state *csp, char **header);
945 static jb_err server_http (struct client_state *csp, char **header);
946 static jb_err crunch_server_header (struct client_state *csp, char **header);
947 static jb_err server_last_modified (struct client_state *csp, char **header);
948 static jb_err server_content_disposition(struct client_state *csp, char **header);
950 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
951 static jb_err server_save_content_length(struct client_state *csp, char **header);
952 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
954 static jb_err client_host_adder (struct client_state *csp);
955 static jb_err client_xtra_adder (struct client_state *csp);
956 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
957 static jb_err client_connection_header_adder(struct client_state *csp);
958 static jb_err server_connection_close_adder(struct client_state *csp);
960 static jb_err create_forged_referrer(char **header, const char *hostport);
961 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
962 static jb_err handle_conditional_hide_referrer_parameter(char **header,
963 const char *host, const int parameter_conditional_block);
966 * List of functions to run on a list of headers.
970 /** The header prefix to match */
973 /** The length of the prefix to match */
976 /** The function to apply to this line */
977 const parser_func_ptr parser;
980 static const struct parsers client_patterns[] = {
981 { "referer:", 8, client_referrer },
982 { "user-agent:", 11, client_uagent },
983 { "ua-", 3, client_ua },
984 { "from:", 5, client_from },
985 { "cookie:", 7, client_send_cookie },
986 { "x-forwarded-for:", 16, client_x_forwarded },
987 { "Accept-Encoding:", 16, client_accept_encoding },
988 { "TE:", 3, client_te },
989 { "Host:", 5, client_host },
990 { "if-modified-since:", 18, client_if_modified_since },
991 { "Keep-Alive:", 11, crumble },
992 { "connection:", 11, client_connection },
993 { "proxy-connection:", 17, crumble },
994 { "max-forwards:", 13, client_max_forwards },
995 { "Accept-Language:", 16, client_accept_language },
996 { "if-none-match:", 14, client_if_none_match },
997 { "Range:", 6, client_range },
998 { "Request-Range:", 14, client_range },
999 { "If-Range:", 9, client_range },
1000 { "X-Filter:", 9, client_x_filter },
1001 { "*", 0, crunch_client_header },
1002 { "*", 0, filter_header },
1006 static const struct parsers server_patterns[] = {
1007 { "HTTP/", 5, server_http },
1008 { "set-cookie:", 11, server_set_cookie },
1009 { "connection:", 11, server_connection },
1010 { "Content-Type:", 13, server_content_type },
1011 { "Content-MD5:", 12, server_content_md5 },
1012 { "Content-Encoding:", 17, server_content_encoding },
1013 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1014 { "Content-Length:", 15, server_save_content_length },
1015 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1016 { "Transfer-Encoding:", 18, server_transfer_coding },
1017 { "Keep-Alive:", 11, crumble },
1018 { "content-disposition:", 20, server_content_disposition },
1019 { "Last-Modified:", 14, server_last_modified },
1020 { "*", 0, crunch_server_header },
1021 { "*", 0, filter_header },
1025 static const add_header_func_ptr add_client_headers[] = {
1027 client_x_forwarded_for_adder,
1029 /* Temporarily disabled: client_accept_encoding_adder, */
1030 client_connection_header_adder,
1034 static const add_header_func_ptr add_server_headers[] = {
1035 server_connection_close_adder,
1039 /*********************************************************************
1041 * Function : flush_socket
1043 * Description : Write any pending "buffered" content.
1046 * 1 : fd = file descriptor of the socket to read
1047 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1049 * Returns : On success, the number of bytes written are returned (zero
1050 * indicates nothing was written). On error, -1 is returned,
1051 * and errno is set appropriately. If count is zero and the
1052 * file descriptor refers to a regular file, 0 will be
1053 * returned without causing any other effect. For a special
1054 * file, the results are not portable.
1056 *********************************************************************/
1057 int flush_socket(jb_socket fd, struct iob *iob)
1059 int len = iob->eod - iob->cur;
1066 if (write_socket(fd, iob->cur, (size_t)len))
1070 iob->eod = iob->cur = iob->buf;
1076 /*********************************************************************
1078 * Function : add_to_iob
1080 * Description : Add content to the buffered page, expanding the
1081 * buffer if necessary.
1084 * 1 : csp = Current client state (buffers, headers, etc...)
1085 * 2 : buf = holds the content to be added to the page
1086 * 3 : n = number of bytes to be added
1088 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1089 * or buffer limit reached.
1091 *********************************************************************/
1092 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1094 struct iob *iob = csp->iob;
1095 size_t used, offset, need, want;
1098 if (n <= 0) return JB_ERR_OK;
1100 used = (size_t)(iob->eod - iob->buf);
1101 offset = (size_t)(iob->cur - iob->buf);
1102 need = used + (size_t)n + 1;
1105 * If the buffer can't hold the new data, extend it first.
1106 * Use the next power of two if possible, else use the actual need.
1108 if (need > csp->config->buffer_limit)
1110 log_error(LOG_LEVEL_INFO,
1111 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
1112 need, csp->config->buffer_limit);
1113 return JB_ERR_MEMORY;
1116 if (need > iob->size)
1118 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1120 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1124 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1130 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1131 return JB_ERR_MEMORY;
1134 /* Update the iob pointers */
1135 iob->cur = p + offset;
1136 iob->eod = p + used;
1140 /* copy the new data into the iob buffer */
1141 memcpy(iob->eod, buf, (size_t)n);
1143 /* point to the end of the data */
1146 /* null terminate == cheap insurance */
1155 /*********************************************************************
1157 * Function : decompress_iob
1159 * Description : Decompress buffered page, expanding the
1160 * buffer as necessary. csp->iob->cur
1161 * should point to the the beginning of the
1162 * compressed data block.
1165 * 1 : csp = Current client state (buffers, headers, etc...)
1167 * Returns : JB_ERR_OK on success,
1168 * JB_ERR_MEMORY if out-of-memory limit reached, and
1169 * JB_ERR_COMPRESS if error decompressing buffer.
1171 *********************************************************************/
1172 jb_err decompress_iob(struct client_state *csp)
1174 char *buf; /* new, uncompressed buffer */
1175 char *cur; /* Current iob position (to keep the original
1176 * iob->cur unmodified if we return early) */
1177 size_t bufsize; /* allocated size of the new buffer */
1178 size_t old_size; /* Content size before decompression */
1179 size_t skip_size; /* Number of bytes at the beginning of the iob
1180 that we should NOT decompress. */
1181 int status; /* return status of the inflate() call */
1182 z_stream zstr; /* used by calls to zlib */
1184 assert(csp->iob->cur - csp->iob->buf > 0);
1185 assert(csp->iob->eod - csp->iob->cur > 0);
1187 bufsize = csp->iob->size;
1188 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1189 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1191 cur = csp->iob->cur;
1196 * This is to protect the parsing of gzipped data,
1197 * but it should(?) be valid for deflated data also.
1199 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1200 return JB_ERR_COMPRESS;
1203 if (csp->content_type & CT_GZIP)
1206 * Our task is slightly complicated by the facts that data
1207 * compressed by gzip does not include a zlib header, and
1208 * that there is no easily accessible interface in zlib to
1209 * handle a gzip header. We strip off the gzip header by
1210 * hand, and later inform zlib not to expect a header.
1214 * Strip off the gzip header. Please see RFC 1952 for more
1215 * explanation of the appropriate fields.
1217 if ((*cur++ != (char)0x1f)
1218 || (*cur++ != (char)0x8b)
1219 || (*cur++ != Z_DEFLATED))
1221 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1222 return JB_ERR_COMPRESS;
1228 * XXX: These magic numbers should be replaced
1229 * with macros to give a better idea what they do.
1233 /* The gzip header has reserved bits set; bail out. */
1234 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1235 return JB_ERR_COMPRESS;
1239 /* Skip extra fields if necessary. */
1243 * Skip a given number of bytes, specified
1244 * as a 16-bit little-endian value.
1247 * XXX: This code used to be:
1249 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1251 * which I had to change into:
1253 * cur += *cur++ + (*cur++ << 8);
1255 * at which point gcc43 finally noticed that the value
1256 * of cur is undefined (it depends on which of the
1257 * summands is evaluated first).
1259 * I haven't come across a site where this
1260 * code is actually executed yet, but I hope
1264 skip_bytes = *cur++;
1265 skip_bytes = *cur++ << 8;
1267 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1270 * The number of bytes to skip should be positive
1271 * and we'd like to stay in the buffer.
1273 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1275 log_error(LOG_LEVEL_ERROR,
1276 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1278 return JB_ERR_COMPRESS;
1280 log_error(LOG_LEVEL_INFO,
1281 "Skipping %d bytes for gzip compression. Does this sound right?",
1286 /* Skip the filename if necessary. */
1289 /* A null-terminated string is supposed to follow. */
1290 while (*cur++ && (cur < csp->iob->eod));
1294 /* Skip the comment if necessary. */
1297 /* A null-terminated string is supposed to follow. */
1298 while (*cur++ && (cur < csp->iob->eod));
1301 /* Skip the CRC if necessary. */
1307 if (cur >= csp->iob->eod)
1310 * If the current position pointer reached or passed
1311 * the buffer end, we were obviously tricked to skip
1314 log_error(LOG_LEVEL_ERROR,
1315 "Malformed gzip header detected. Aborting decompression.");
1316 return JB_ERR_COMPRESS;
1320 else if (csp->content_type & CT_DEFLATE)
1323 * XXX: The debug level should be lowered
1324 * before the next stable release.
1326 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1328 * In theory (that is, according to RFC 1950), deflate-compressed
1329 * data should begin with a two-byte zlib header and have an
1330 * adler32 checksum at the end. It seems that in practice only
1331 * the raw compressed data is sent. Note that this means that
1332 * we are not RFC 1950-compliant here, but the advantage is that
1333 * this actually works. :)
1335 * We add a dummy null byte to tell zlib where the data ends,
1336 * and later inform it not to expect a header.
1338 * Fortunately, add_to_iob() has thoughtfully null-terminated
1339 * the buffer; we can just increment the end pointer to include
1346 log_error(LOG_LEVEL_ERROR,
1347 "Unable to determine compression format for decompression");
1348 return JB_ERR_COMPRESS;
1351 /* Set up the fields required by zlib. */
1352 zstr.next_in = (Bytef *)cur;
1353 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1354 zstr.zalloc = Z_NULL;
1355 zstr.zfree = Z_NULL;
1356 zstr.opaque = Z_NULL;
1359 * Passing -MAX_WBITS to inflateInit2 tells the library
1360 * that there is no zlib header.
1362 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1364 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1365 return JB_ERR_COMPRESS;
1369 * Next, we allocate new storage for the inflated data.
1370 * We don't modify the existing iob yet, so in case there
1371 * is error in decompression we can recover gracefully.
1373 buf = zalloc(bufsize);
1376 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1377 return JB_ERR_MEMORY;
1380 assert(bufsize >= skip_size);
1381 memcpy(buf, csp->iob->buf, skip_size);
1382 zstr.avail_out = bufsize - skip_size;
1383 zstr.next_out = (Bytef *)buf + skip_size;
1385 /* Try to decompress the whole stream in one shot. */
1386 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1388 /* We need to allocate more memory for the output buffer. */
1390 char *tmpbuf; /* used for realloc'ing the buffer */
1391 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1394 * If zlib wants more data then there's a problem, because
1395 * the complete compressed file should have been buffered.
1397 if (0 == zstr.avail_in)
1399 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1400 return JB_ERR_COMPRESS;
1404 * If we tried the limit and still didn't have enough
1405 * memory, just give up.
1407 if (bufsize == csp->config->buffer_limit)
1409 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1410 return JB_ERR_MEMORY;
1413 /* Try doubling the buffer size each time. */
1416 /* Don't exceed the buffer limit. */
1417 if (bufsize > csp->config->buffer_limit)
1419 bufsize = csp->config->buffer_limit;
1422 /* Try to allocate the new buffer. */
1423 tmpbuf = realloc(buf, bufsize);
1426 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1428 return JB_ERR_MEMORY;
1432 char *oldnext_out = (char *)zstr.next_out;
1435 * Update the fields for inflate() to use the new
1436 * buffer, which may be in a location different from
1439 zstr.avail_out += bufsize - oldbufsize;
1440 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1443 * Compare with an uglier method of calculating these values
1444 * that doesn't require the extra oldbufsize variable.
1446 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1447 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1448 assert(zstr.avail_out > 0);
1454 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1456 log_error(LOG_LEVEL_ERROR,
1457 "Inconsistent stream state after decompression: %s", zstr.msg);
1459 * XXX: Intentionally no return.
1461 * According to zlib.h, Z_STREAM_ERROR is returned
1462 * "if the stream state was inconsistent".
1464 * I assume in this case inflate()'s status
1465 * would also be something different than Z_STREAM_END
1466 * so this check should be redundant, but lets see.
1470 if (status != Z_STREAM_END)
1472 /* We failed to decompress the stream. */
1473 log_error(LOG_LEVEL_ERROR,
1474 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1475 return JB_ERR_COMPRESS;
1479 * Finally, we can actually update the iob, since the
1480 * decompression was successful. First, free the old
1483 freez(csp->iob->buf);
1485 /* Now, update the iob to use the new buffer. */
1486 csp->iob->buf = buf;
1487 csp->iob->cur = csp->iob->buf + skip_size;
1488 csp->iob->eod = (char *)zstr.next_out;
1489 csp->iob->size = bufsize;
1492 * Make sure the new uncompressed iob obeys some minimal
1493 * consistency conditions.
1495 if ((csp->iob->buf < csp->iob->cur)
1496 && (csp->iob->cur <= csp->iob->eod)
1497 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1499 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1502 log_error(LOG_LEVEL_RE_FILTER,
1503 "Decompression successful. Old size: %d, new size: %d.",
1504 old_size, new_size);
1508 /* zlib thinks this is OK, so lets do the same. */
1509 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1514 /* It seems that zlib did something weird. */
1515 log_error(LOG_LEVEL_ERROR,
1516 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1517 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1518 csp->iob->eod, csp->iob->buf + csp->iob->size);
1519 return JB_ERR_COMPRESS;
1525 #endif /* defined(FEATURE_ZLIB) */
1528 /*********************************************************************
1530 * Function : string_move
1532 * Description : memmove wrapper to move the last part of a string
1533 * towards the beginning, overwriting the part in
1534 * the middle. strlcpy() can't be used here as the
1538 * 1 : dst = Destination to overwrite
1539 * 2 : src = Source to move.
1543 *********************************************************************/
1544 static void string_move(char *dst, char *src)
1548 /* +1 to copy the terminating nul as well. */
1549 memmove(dst, src, strlen(src)+1);
1553 /*********************************************************************
1555 * Function : normalize_lws
1557 * Description : Reduces unquoted linear white space in headers
1558 * to a single space in accordance with RFC 2616 2.2.
1559 * This simplifies parsing and filtering later on.
1561 * XXX: Remove log messages before
1562 * the next stable release?
1565 * 1 : header = A header with linear white space to reduce.
1569 *********************************************************************/
1570 static void normalize_lws(char *header)
1576 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1580 while (ijb_isspace(*q))
1584 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1585 string_move(p+1, q);
1590 log_error(LOG_LEVEL_HEADER,
1591 "Converting tab to space in '%s'", header);
1596 char *end_of_token = strstr(p+1, "\"");
1598 if (NULL != end_of_token)
1600 /* Don't mess with quoted text. */
1605 log_error(LOG_LEVEL_HEADER,
1606 "Ignoring single quote in '%s'", header);
1612 p = strchr(header, ':');
1613 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1616 * There's still space before the colon.
1619 string_move(p-1, p);
1624 /*********************************************************************
1626 * Function : get_header
1628 * Description : This (odd) routine will parse the csp->iob
1629 * to get the next complete header.
1632 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1634 * Returns : Any one of the following:
1636 * 1) a pointer to a dynamically allocated string that contains a header line
1637 * 2) NULL indicating that the end of the header was reached
1638 * 3) "" indicating that the end of the iob was reached before finding
1639 * a complete header line.
1641 *********************************************************************/
1642 char *get_header(struct iob *iob)
1646 header = get_header_line(iob);
1648 if ((header == NULL) || (*header == '\0'))
1651 * No complete header read yet, tell the client.
1656 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1659 * Header spans multiple lines, append the next one.
1661 char *continued_header;
1663 continued_header = get_header_line(iob);
1664 if ((continued_header == NULL) || (*continued_header == '\0'))
1667 * No complete header read yet, return what we got.
1668 * XXX: Should "unread" header instead.
1670 log_error(LOG_LEVEL_INFO,
1671 "Failed to read a multi-line header properly: '%s'",
1676 if (JB_ERR_OK != string_join(&header, continued_header))
1678 log_error(LOG_LEVEL_FATAL,
1679 "Out of memory while appending multiple headers.");
1683 /* XXX: remove before next stable release. */
1684 log_error(LOG_LEVEL_HEADER,
1685 "Merged multiple header lines to: '%s'",
1690 normalize_lws(header);
1697 /*********************************************************************
1699 * Function : get_header_line
1701 * Description : This (odd) routine will parse the csp->iob
1702 * to get the next header line.
1705 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1707 * Returns : Any one of the following:
1709 * 1) a pointer to a dynamically allocated string that contains a header line
1710 * 2) NULL indicating that the end of the header was reached
1711 * 3) "" indicating that the end of the iob was reached before finding
1712 * a complete header line.
1714 *********************************************************************/
1715 static char *get_header_line(struct iob *iob)
1719 if ((iob->cur == NULL)
1720 || ((p = strchr(iob->cur, '\n')) == NULL))
1722 return(""); /* couldn't find a complete header */
1727 ret = strdup(iob->cur);
1730 /* FIXME No way to handle error properly */
1731 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1736 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1738 /* is this a blank line (i.e. the end of the header) ? */
1750 /*********************************************************************
1752 * Function : get_header_value
1754 * Description : Get the value of a given header from a chained list
1755 * of header lines or return NULL if no such header is
1756 * present in the list.
1759 * 1 : header_list = pointer to list
1760 * 2 : header_name = string with name of header to look for.
1761 * Trailing colon required, capitalization
1764 * Returns : NULL if not found, else value of header
1766 *********************************************************************/
1767 char *get_header_value(const struct list *header_list, const char *header_name)
1769 struct list_entry *cur_entry;
1773 assert(header_list);
1774 assert(header_name);
1775 length = strlen(header_name);
1777 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1781 if (!strncmpic(cur_entry->str, header_name, length))
1784 * Found: return pointer to start of value
1786 ret = cur_entry->str + length;
1787 while (*ret && ijb_isspace(*ret)) ret++;
1801 /*********************************************************************
1803 * Function : scan_headers
1805 * Description : Scans headers, applies tags and updates action bits.
1808 * 1 : csp = Current client state (buffers, headers, etc...)
1810 * Returns : JB_ERR_OK
1812 *********************************************************************/
1813 static jb_err scan_headers(struct client_state *csp)
1815 struct list_entry *h; /* Header */
1816 jb_err err = JB_ERR_OK;
1818 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1820 /* Header crunch()ed in previous run? -> ignore */
1821 if (h->str == NULL) continue;
1822 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1823 err = header_tagger(csp, h->str);
1830 /*********************************************************************
1834 * Description : add, delete or modify lines in the HTTP header streams.
1835 * On entry, it receives a linked list of headers space
1836 * that was allocated dynamically (both the list nodes
1837 * and the header contents).
1839 * As a side effect it frees the space used by the original
1843 * 1 : csp = Current client state (buffers, headers, etc...)
1844 * 2 : filter_server_headers = Boolean to switch between
1845 * server and header filtering.
1847 * Returns : JB_ERR_OK in case off success, or
1848 * JB_ERR_MEMORY on out-of-memory error.
1850 *********************************************************************/
1851 jb_err sed(struct client_state *csp, int filter_server_headers)
1853 /* XXX: use more descriptive names. */
1854 struct list_entry *p;
1855 const struct parsers *v;
1856 const add_header_func_ptr *f;
1857 jb_err err = JB_ERR_OK;
1859 if (filter_server_headers)
1861 v = server_patterns;
1862 f = add_server_headers;
1866 v = client_patterns;
1867 f = add_client_headers;
1872 while ((err == JB_ERR_OK) && (v->str != NULL))
1874 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1876 /* Header crunch()ed in previous run? -> ignore */
1877 if (p->str == NULL) continue;
1879 /* Does the current parser handle this header? */
1880 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1881 (v->len == CHECK_EVERY_HEADER_REMAINING))
1883 err = v->parser(csp, &(p->str));
1889 /* place additional headers on the csp->headers list */
1890 while ((err == JB_ERR_OK) && (*f))
1900 /*********************************************************************
1902 * Function : update_server_headers
1904 * Description : Updates server headers after the body has been modified.
1907 * 1 : csp = Current client state (buffers, headers, etc...)
1909 * Returns : JB_ERR_OK in case off success, or
1910 * JB_ERR_MEMORY on out-of-memory error.
1912 *********************************************************************/
1913 jb_err update_server_headers(struct client_state *csp)
1915 jb_err err = JB_ERR_OK;
1917 static const struct parsers server_patterns_light[] = {
1918 { "Content-Length:", 15, server_adjust_content_length },
1919 { "Transfer-Encoding:", 18, server_transfer_coding },
1921 { "Content-Encoding:", 17, server_content_encoding },
1922 #endif /* def FEATURE_ZLIB */
1926 if (strncmpic(csp->http->cmd, "HEAD", 4))
1928 const struct parsers *v;
1929 struct list_entry *p;
1931 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1933 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1935 /* Header crunch()ed in previous run? -> ignore */
1936 if (p->str == NULL) continue;
1938 /* Does the current parser handle this header? */
1939 if (strncmpic(p->str, v->str, v->len) == 0)
1941 err = v->parser(csp, (char **)&(p->str));
1951 /*********************************************************************
1953 * Function : header_tagger
1955 * Description : Executes all text substitutions from applying
1956 * tag actions and saves the result as tag.
1958 * XXX: Shares enough code with filter_header() and
1959 * pcrs_filter_response() to warrant some helper functions.
1962 * 1 : csp = Current client state (buffers, headers, etc...)
1963 * 2 : header = Header that is used as tagger input
1965 * Returns : JB_ERR_OK on success and always succeeds
1967 *********************************************************************/
1968 static jb_err header_tagger(struct client_state *csp, char *header)
1970 int wanted_filter_type;
1971 int multi_action_index;
1975 struct file_list *fl;
1976 struct re_filterfile_spec *b;
1977 struct list_entry *tag_name;
1979 int found_filters = 0;
1980 const size_t header_length = strlen(header);
1982 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1984 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1985 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1989 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1990 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1993 /* Check if there are any filters */
1994 for (i = 0; i < MAX_AF_FILES; i++)
2007 if (0 == found_filters)
2009 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2010 "tagging enabled, but no taggers available.");
2014 for (i = 0; i < MAX_AF_FILES; i++)
2017 if ((NULL == fl) || (NULL == fl->f))
2020 * Either there are no filter files
2021 * left, or this filter file just
2022 * contains no valid filters.
2024 * Continue to be sure we don't miss
2025 * valid filter files that are chained
2026 * after empty or invalid ones.
2031 /* For all filters, */
2032 for (b = fl->f; b; b = b->next)
2034 if (b->type != wanted_filter_type)
2036 /* skip the ones we don't care about, */
2039 /* leaving only taggers that could apply, of which we use the ones, */
2040 for (tag_name = csp->action->multi[multi_action_index]->first;
2041 NULL != tag_name; tag_name = tag_name->next)
2043 /* that do apply, and */
2044 if (strcmp(b->name, tag_name->str) == 0)
2046 char *modified_tag = NULL;
2048 size_t size = header_length;
2049 pcrs_job *joblist = b->joblist;
2051 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2053 if (NULL == joblist)
2055 log_error(LOG_LEVEL_RE_FILTER,
2056 "Tagger %s has empty joblist. Nothing to do.", b->name);
2060 /* execute their pcrs_joblist on the header. */
2061 for (job = joblist; NULL != job; job = job->next)
2063 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2067 /* Success, continue with the modified version. */
2076 /* Tagger doesn't match */
2079 /* Regex failure, log it but continue anyway. */
2080 log_error(LOG_LEVEL_ERROR,
2081 "Problems with tagger \'%s\' and header \'%s\': %s",
2082 b->name, *header, pcrs_strerror(hits));
2084 freez(modified_tag);
2088 if (b->dynamic) pcrs_free_joblist(joblist);
2090 /* If this tagger matched */
2096 * There is to technical limitation which makes
2097 * it impossible to use empty tags, but I assume
2098 * no one would do it intentionally.
2101 log_error(LOG_LEVEL_INFO,
2102 "Tagger \'%s\' created an empty tag. Ignored.",
2107 if (!list_contains_item(csp->tags, tag))
2109 if (JB_ERR_OK != enlist(csp->tags, tag))
2111 log_error(LOG_LEVEL_ERROR,
2112 "Insufficient memory to add tag \'%s\', "
2113 "based on tagger \'%s\' and header \'%s\'",
2114 tag, b->name, *header);
2118 char *action_message;
2120 * update the action bits right away, to make
2121 * tagging based on tags set by earlier taggers
2122 * of the same kind possible.
2124 if (update_action_bits_for_tag(csp, tag))
2126 action_message = "Action bits updated accordingly.";
2130 action_message = "No action bits update necessary.";
2133 log_error(LOG_LEVEL_HEADER,
2134 "Tagger \'%s\' added tag \'%s\'. %s",
2135 b->name, tag, action_message);
2140 /* XXX: Is this log-worthy? */
2141 log_error(LOG_LEVEL_HEADER,
2142 "Tagger \'%s\' didn't add tag \'%s\'. "
2143 "Tag already present", b->name, tag);
2146 } /* if the tagger matched */
2147 } /* if the tagger applies */
2148 } /* for every tagger that could apply */
2149 } /* for all filters */
2150 } /* for all filter files */
2155 /* here begins the family of parser functions that reformat header lines */
2157 /*********************************************************************
2159 * Function : filter_header
2161 * Description : Executes all text substitutions from all applying
2162 * +(server|client)-header-filter actions on the header.
2163 * Most of the code was copied from pcrs_filter_response,
2164 * including the rather short variable names
2167 * 1 : csp = Current client state (buffers, headers, etc...)
2168 * 2 : header = On input, pointer to header to modify.
2169 * On output, pointer to the modified header, or NULL
2170 * to remove the header. This function frees the
2171 * original string if necessary.
2173 * Returns : JB_ERR_OK on success and always succeeds
2175 *********************************************************************/
2176 static jb_err filter_header(struct client_state *csp, char **header)
2180 size_t size = strlen(*header);
2182 char *newheader = NULL;
2185 struct file_list *fl;
2186 struct re_filterfile_spec *b;
2187 struct list_entry *filtername;
2189 int i, found_filters = 0;
2190 int wanted_filter_type;
2191 int multi_action_index;
2193 if (csp->flags & CSP_FLAG_NO_FILTERING)
2198 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2200 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2201 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2205 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2206 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2210 * Need to check the set of re_filterfiles...
2212 for (i = 0; i < MAX_AF_FILES; i++)
2225 if (0 == found_filters)
2227 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2228 "header filtering enabled, but no matching filters available.");
2232 for (i = 0; i < MAX_AF_FILES; i++)
2235 if ((NULL == fl) || (NULL == fl->f))
2238 * Either there are no filter files
2239 * left, or this filter file just
2240 * contains no valid filters.
2242 * Continue to be sure we don't miss
2243 * valid filter files that are chained
2244 * after empty or invalid ones.
2249 * For all applying +filter actions, look if a filter by that
2250 * name exists and if yes, execute its pcrs_joblist on the
2253 for (b = fl->f; b; b = b->next)
2255 if (b->type != wanted_filter_type)
2257 /* Skip other filter types */
2261 for (filtername = csp->action->multi[multi_action_index]->first;
2262 filtername ; filtername = filtername->next)
2264 if (strcmp(b->name, filtername->str) == 0)
2266 int current_hits = 0;
2267 pcrs_job *joblist = b->joblist;
2269 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2271 if (NULL == joblist)
2273 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2277 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2278 *header, size, b->name);
2280 /* Apply all jobs from the joblist */
2281 for (job = joblist; NULL != job; job = job->next)
2283 matches = pcrs_execute(job, *header, size, &newheader, &size);
2286 current_hits += matches;
2287 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2289 *header = newheader;
2291 else if ( 0 == matches )
2293 /* Filter doesn't change header */
2299 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2300 *header, b->name, pcrs_strerror(matches));
2301 if (newheader != NULL)
2303 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2309 if (b->dynamic) pcrs_free_joblist(joblist);
2311 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2312 hits += current_hits;
2319 * Additionally checking for hits is important because if
2320 * the continue hack is triggered, server headers can
2321 * arrive empty to separate multiple heads from each other.
2323 if ((0 == size) && hits)
2325 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2333 /*********************************************************************
2335 * Function : server_connection
2337 * Description : Makes sure that the value of the Connection: header
2338 * is "close" and signals server_connection_close_adder
2342 * 1 : csp = Current client state (buffers, headers, etc...)
2343 * 2 : header = On input, pointer to header to modify.
2344 * On output, pointer to the modified header, or NULL
2345 * to remove the header. This function frees the
2346 * original string if necessary.
2348 * Returns : JB_ERR_OK on success, or
2349 * JB_ERR_MEMORY on out-of-memory error.
2351 *********************************************************************/
2352 static jb_err server_connection(struct client_state *csp, char **header)
2354 char *old_header = *header;
2356 /* Do we have a 'Connection: close' header? */
2357 if (strcmpic(*header, "Connection: close"))
2359 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2360 if (!strcmpic(*header, "Connection: keep-alive"))
2362 /* Remember to keep the connection alive. */
2363 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
2365 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2367 *header = strdup("Connection: close");
2370 return JB_ERR_MEMORY;
2372 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2376 /* Signal server_connection_close_adder() to return early. */
2377 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2382 /*********************************************************************
2384 * Function : client_connection
2386 * Description : Makes sure a proper "Connection:" header is
2387 * set and signals connection_header_adder
2391 * 1 : csp = Current client state (buffers, headers, etc...)
2392 * 2 : header = On input, pointer to header to modify.
2393 * On output, pointer to the modified header, or NULL
2394 * to remove the header. This function frees the
2395 * original string if necessary.
2397 * Returns : JB_ERR_OK on success, or
2398 * JB_ERR_MEMORY on out-of-memory error.
2400 *********************************************************************/
2401 static jb_err client_connection(struct client_state *csp, char **header)
2403 char *old_header = *header;
2404 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2405 static const char wanted_header[] = "Connection: keep-alive";
2407 static const char wanted_header[] = "Connection: close";
2408 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2410 if (strcmpic(*header, wanted_header))
2412 *header = strdup(wanted_header);
2415 return JB_ERR_MEMORY;
2417 log_error(LOG_LEVEL_HEADER,
2418 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2422 /* Signal client_connection_close_adder() to return early. */
2423 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2429 /*********************************************************************
2431 * Function : crumble
2433 * Description : This is called if a header matches a pattern to "crunch"
2436 * 1 : csp = Current client state (buffers, headers, etc...)
2437 * 2 : header = On input, pointer to header to modify.
2438 * On output, pointer to the modified header, or NULL
2439 * to remove the header. This function frees the
2440 * original string if necessary.
2442 * Returns : JB_ERR_OK on success, or
2443 * JB_ERR_MEMORY on out-of-memory error.
2445 *********************************************************************/
2446 static jb_err crumble(struct client_state *csp, char **header)
2448 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2454 /*********************************************************************
2456 * Function : crunch_server_header
2458 * Description : Crunch server header if it matches a string supplied by the
2459 * user. Called from `sed'.
2462 * 1 : csp = Current client state (buffers, headers, etc...)
2463 * 2 : header = On input, pointer to header to modify.
2464 * On output, pointer to the modified header, or NULL
2465 * to remove the header. This function frees the
2466 * original string if necessary.
2468 * Returns : JB_ERR_OK on success and always succeeds
2470 *********************************************************************/
2471 static jb_err crunch_server_header(struct client_state *csp, char **header)
2473 const char *crunch_pattern;
2475 /* Do we feel like crunching? */
2476 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2478 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2480 /* Is the current header the lucky one? */
2481 if (strstr(*header, crunch_pattern))
2483 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2492 /*********************************************************************
2494 * Function : server_content_type
2496 * Description : Set the content-type for filterable types (text/.*,
2497 * .*xml.*, javascript and image/gif) unless filtering has been
2498 * forbidden (CT_TABOO) while parsing earlier headers.
2499 * NOTE: Since text/plain is commonly used by web servers
2500 * for files whose correct type is unknown, we don't
2501 * set CT_TEXT for it.
2504 * 1 : csp = Current client state (buffers, headers, etc...)
2505 * 2 : header = On input, pointer to header to modify.
2506 * On output, pointer to the modified header, or NULL
2507 * to remove the header. This function frees the
2508 * original string if necessary.
2510 * Returns : JB_ERR_OK on success, or
2511 * JB_ERR_MEMORY on out-of-memory error.
2513 *********************************************************************/
2514 static jb_err server_content_type(struct client_state *csp, char **header)
2516 /* Remove header if it isn't the first Content-Type header */
2517 if ((csp->content_type & CT_DECLARED))
2520 * Another, slightly slower, way to see if
2521 * we already parsed another Content-Type header.
2523 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2525 log_error(LOG_LEVEL_ERROR,
2526 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2534 * Signal that the Content-Type has been set.
2536 csp->content_type |= CT_DECLARED;
2538 if (!(csp->content_type & CT_TABOO))
2541 * XXX: The assumption that text/plain is a sign of
2542 * binary data seems to be somewhat unreasonable nowadays
2543 * and should be dropped after 3.0.8 is out.
2545 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2546 || strstr(*header, "xml")
2547 || strstr(*header, "application/x-javascript"))
2549 csp->content_type |= CT_TEXT;
2551 else if (strstr(*header, "image/gif"))
2553 csp->content_type |= CT_GIF;
2558 * Are we messing with the content type?
2560 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2563 * Make sure the user doesn't accidently
2564 * change the content type of binary documents.
2566 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2569 *header = strdup("Content-Type: ");
2570 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2574 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2575 return JB_ERR_MEMORY;
2577 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2581 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2582 "It doesn't look like a content type that should be filtered. "
2583 "Enable force-text-mode if you know what you're doing.", *header);
2591 /*********************************************************************
2593 * Function : server_transfer_coding
2595 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2596 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2597 * - Remove header if body was chunked but has been
2598 * de-chunked for filtering.
2601 * 1 : csp = Current client state (buffers, headers, etc...)
2602 * 2 : header = On input, pointer to header to modify.
2603 * On output, pointer to the modified header, or NULL
2604 * to remove the header. This function frees the
2605 * original string if necessary.
2607 * Returns : JB_ERR_OK on success, or
2608 * JB_ERR_MEMORY on out-of-memory error.
2610 *********************************************************************/
2611 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2614 * Turn off pcrs and gif filtering if body compressed
2616 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2620 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2622 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2623 csp->http->cmd, *header);
2624 #endif /* def FEATURE_ZLIB */
2625 csp->content_type = CT_TABOO;
2629 * Raise flag if body chunked
2631 if (strstr(*header, "chunked"))
2633 csp->flags |= CSP_FLAG_CHUNKED;
2636 * If the body was modified, it has been de-chunked first
2637 * and the header must be removed.
2639 * FIXME: If there is more than one transfer encoding,
2640 * only the "chunked" part should be removed here.
2642 if (csp->flags & CSP_FLAG_MODIFIED)
2644 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2653 /*********************************************************************
2655 * Function : server_content_encoding
2657 * Description : This function is run twice for each request,
2658 * unless FEATURE_ZLIB and filtering are disabled.
2660 * The first run is used to check if the content
2661 * is compressed, if FEATURE_ZLIB is disabled
2662 * filtering is then disabled as well, if FEATURE_ZLIB
2663 * is enabled the content is marked for decompression.
2665 * The second run is used to remove the Content-Encoding
2666 * header if the decompression was successful.
2669 * 1 : csp = Current client state (buffers, headers, etc...)
2670 * 2 : header = On input, pointer to header to modify.
2671 * On output, pointer to the modified header, or NULL
2672 * to remove the header. This function frees the
2673 * original string if necessary.
2675 * Returns : JB_ERR_OK on success, or
2676 * JB_ERR_MEMORY on out-of-memory error.
2678 *********************************************************************/
2679 static jb_err server_content_encoding(struct client_state *csp, char **header)
2682 if ((csp->flags & CSP_FLAG_MODIFIED)
2683 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2686 * We successfully decompressed the content,
2687 * and have to clean the header now, so the
2688 * client no longer expects compressed data..
2690 * XXX: There is a difference between cleaning
2691 * and removing it completely.
2693 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2696 else if (strstr(*header, "gzip"))
2698 /* Mark for gzip decompression */
2699 csp->content_type |= CT_GZIP;
2701 else if (strstr(*header, "deflate"))
2703 /* Mark for zlib decompression */
2704 csp->content_type |= CT_DEFLATE;
2706 else if (strstr(*header, "compress"))
2709 * We can't decompress this; therefore we can't filter
2712 csp->content_type |= CT_TABOO;
2714 #else /* !defined(FEATURE_ZLIB) */
2715 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2718 * Body is compressed, turn off pcrs and gif filtering.
2720 csp->content_type |= CT_TABOO;
2723 * Log a warning if the user expects the content to be filtered.
2725 if ((csp->rlist != NULL) &&
2726 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2728 log_error(LOG_LEVEL_INFO,
2729 "Compressed content detected, content filtering disabled. "
2730 "Consider recompiling Privoxy with zlib support or "
2731 "enable the prevent-compression action.");
2734 #endif /* defined(FEATURE_ZLIB) */
2741 /*********************************************************************
2743 * Function : server_adjust_content_length
2745 * Description : Adjust Content-Length header if we modified
2749 * 1 : csp = Current client state (buffers, headers, etc...)
2750 * 2 : header = On input, pointer to header to modify.
2751 * On output, pointer to the modified header, or NULL
2752 * to remove the header. This function frees the
2753 * original string if necessary.
2755 * Returns : JB_ERR_OK on success, or
2756 * JB_ERR_MEMORY on out-of-memory error.
2758 *********************************************************************/
2759 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2761 const size_t max_header_length = 80;
2763 /* Regenerate header if the content was modified. */
2764 if (csp->flags & CSP_FLAG_MODIFIED)
2767 *header = (char *) zalloc(max_header_length);
2768 if (*header == NULL)
2770 return JB_ERR_MEMORY;
2773 snprintf(*header, max_header_length, "Content-Length: %d",
2774 (int)csp->content_length);
2775 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2776 (int)csp->content_length);
2783 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2784 /*********************************************************************
2786 * Function : server_save_content_length
2788 * Description : Save the Content-Length sent by the server.
2791 * 1 : csp = Current client state (buffers, headers, etc...)
2792 * 2 : header = On input, pointer to header to modify.
2793 * On output, pointer to the modified header, or NULL
2794 * to remove the header. This function frees the
2795 * original string if necessary.
2797 * Returns : JB_ERR_OK on success, or
2798 * JB_ERR_MEMORY on out-of-memory error.
2800 *********************************************************************/
2801 static jb_err server_save_content_length(struct client_state *csp, char **header)
2803 unsigned int content_length = 0;
2805 assert(*(*header+14) == ':');
2807 if (1 != sscanf(*header+14, ": %u", &content_length))
2809 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2814 csp->expected_content_length = content_length;
2815 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2820 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2823 /*********************************************************************
2825 * Function : server_content_md5
2827 * Description : Crumble any Content-MD5 headers if the document was
2828 * modified. FIXME: Should we re-compute instead?
2831 * 1 : csp = Current client state (buffers, headers, etc...)
2832 * 2 : header = On input, pointer to header to modify.
2833 * On output, pointer to the modified header, or NULL
2834 * to remove the header. This function frees the
2835 * original string if necessary.
2837 * Returns : JB_ERR_OK on success, or
2838 * JB_ERR_MEMORY on out-of-memory error.
2840 *********************************************************************/
2841 static jb_err server_content_md5(struct client_state *csp, char **header)
2843 if (csp->flags & CSP_FLAG_MODIFIED)
2845 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2853 /*********************************************************************
2855 * Function : server_content_disposition
2857 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2858 * Called from `sed'.
2861 * 1 : csp = Current client state (buffers, headers, etc...)
2862 * 2 : header = On input, pointer to header to modify.
2863 * On output, pointer to the modified header, or NULL
2864 * to remove the header. This function frees the
2865 * original string if necessary.
2867 * Returns : JB_ERR_OK on success, or
2868 * JB_ERR_MEMORY on out-of-memory error.
2870 *********************************************************************/
2871 static jb_err server_content_disposition(struct client_state *csp, char **header)
2876 * Are we messing with the Content-Disposition header?
2878 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2884 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2886 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2889 * Blocking content-disposition header
2891 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2898 * Replacing Content-Disposition header
2901 *header = strdup("Content-Disposition: ");
2902 string_append(header, newval);
2904 if (*header != NULL)
2906 log_error(LOG_LEVEL_HEADER,
2907 "Content-Disposition header crunched and replaced with: %s", *header);
2910 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2914 /*********************************************************************
2916 * Function : server_last_modified
2918 * Description : Changes Last-Modified header to the actual date
2919 * to help hide-if-modified-since.
2920 * Called from `sed'.
2923 * 1 : csp = Current client state (buffers, headers, etc...)
2924 * 2 : header = On input, pointer to header to modify.
2925 * On output, pointer to the modified header, or NULL
2926 * to remove the header. This function frees the
2927 * original string if necessary.
2929 * Returns : JB_ERR_OK on success, or
2930 * JB_ERR_MEMORY on out-of-memory error.
2932 *********************************************************************/
2933 static jb_err server_last_modified(struct client_state *csp, char **header)
2936 char buf[BUFFER_SIZE];
2939 #ifdef HAVE_GMTIME_R
2942 struct tm *timeptr = NULL;
2943 time_t now, last_modified;
2945 long int days, hours, minutes, seconds;
2948 * Are we messing with the Last-Modified header?
2950 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2956 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2958 if (0 == strcmpic(newval, "block") )
2961 * Blocking Last-Modified header. Useless but why not.
2963 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2967 else if (0 == strcmpic(newval, "reset-to-request-time"))
2970 * Setting Last-Modified Header to now.
2972 get_http_time(0, buf, sizeof(buf));
2974 *header = strdup("Last-Modified: ");
2975 string_append(header, buf);
2977 if (*header == NULL)
2979 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2983 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2986 else if (0 == strcmpic(newval, "randomize"))
2988 const char *header_time = *header + sizeof("Last-Modified:");
2990 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2992 #ifdef HAVE_GMTIME_R
2993 timeptr = gmtime_r(&now, &gmt);
2994 #elif FEATURE_PTHREAD
2995 privoxy_mutex_lock(&gmtime_mutex);
2996 timeptr = gmtime(&now);
2997 privoxy_mutex_unlock(&gmtime_mutex);
2999 timeptr = gmtime(&now);
3001 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
3003 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3008 rtime = (long int)difftime(now, last_modified);
3017 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
3019 rtime = pick_from_range(rtime);
3020 if (negative) rtime *= -1;
3021 last_modified += rtime;
3022 #ifdef HAVE_GMTIME_R
3023 timeptr = gmtime_r(&last_modified, &gmt);
3024 #elif FEATURE_PTHREAD
3025 privoxy_mutex_lock(&gmtime_mutex);
3026 timeptr = gmtime(&last_modified);
3027 privoxy_mutex_unlock(&gmtime_mutex);
3029 timeptr = gmtime(&last_modified);
3031 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3033 *header = strdup("Last-Modified: ");
3034 string_append(header, newheader);
3036 if (*header == NULL)
3038 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
3039 return JB_ERR_MEMORY;
3042 days = rtime / (3600 * 24);
3043 hours = rtime / 3600 % 24;
3044 minutes = rtime / 60 % 60;
3045 seconds = rtime % 60;
3047 log_error(LOG_LEVEL_HEADER,
3048 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
3049 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
3050 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3054 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
3063 /*********************************************************************
3065 * Function : client_accept_encoding
3067 * Description : Rewrite the client's Accept-Encoding header so that
3068 * if doesn't allow compression, if the action applies.
3069 * Note: For HTTP/1.0 the absence of the header is enough.
3072 * 1 : csp = Current client state (buffers, headers, etc...)
3073 * 2 : header = On input, pointer to header to modify.
3074 * On output, pointer to the modified header, or NULL
3075 * to remove the header. This function frees the
3076 * original string if necessary.
3078 * Returns : JB_ERR_OK on success, or
3079 * JB_ERR_MEMORY on out-of-memory error.
3081 *********************************************************************/
3082 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3084 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3086 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3090 /* Temporarily disable the correct behaviour to
3091 * work around a PHP bug.
3093 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
3095 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
3096 * if (*header == NULL)
3098 * return JB_ERR_MEMORY;
3109 /*********************************************************************
3111 * Function : client_te
3113 * Description : Rewrite the client's TE header so that
3114 * if doesn't allow compression, if the action applies.
3117 * 1 : csp = Current client state (buffers, headers, etc...)
3118 * 2 : header = On input, pointer to header to modify.
3119 * On output, pointer to the modified header, or NULL
3120 * to remove the header. This function frees the
3121 * original string if necessary.
3123 * Returns : JB_ERR_OK on success, or
3124 * JB_ERR_MEMORY on out-of-memory error.
3126 *********************************************************************/
3127 static jb_err client_te(struct client_state *csp, char **header)
3129 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3132 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3139 /*********************************************************************
3141 * Function : client_referrer
3143 * Description : Handle the "referer" config setting properly.
3144 * Called from `sed'.
3147 * 1 : csp = Current client state (buffers, headers, etc...)
3148 * 2 : header = On input, pointer to header to modify.
3149 * On output, pointer to the modified header, or NULL
3150 * to remove the header. This function frees the
3151 * original string if necessary.
3153 * Returns : JB_ERR_OK on success, or
3154 * JB_ERR_MEMORY on out-of-memory error.
3156 *********************************************************************/
3157 static jb_err client_referrer(struct client_state *csp, char **header)
3159 const char *parameter;
3160 /* booleans for parameters we have to check multiple times */
3161 int parameter_conditional_block;
3162 int parameter_conditional_forge;
3164 #ifdef FEATURE_FORCE_LOAD
3166 * Since the referrer can include the prefix even
3167 * if the request itself is non-forced, we must
3168 * clean it unconditionally.
3170 * XXX: strclean is too broad
3172 strclean(*header, FORCE_PREFIX);
3173 #endif /* def FEATURE_FORCE_LOAD */
3175 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3177 /* Nothing left to do */
3181 parameter = csp->action->string[ACTION_STRING_REFERER];
3182 assert(parameter != NULL);
3183 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3184 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3186 if (!parameter_conditional_block && !parameter_conditional_forge)
3189 * As conditional-block and conditional-forge are the only
3190 * parameters that rely on the original referrer, we can
3191 * remove it now for all the others.
3196 if (0 == strcmpic(parameter, "block"))
3198 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3201 else if (parameter_conditional_block || parameter_conditional_forge)
3203 return handle_conditional_hide_referrer_parameter(header,
3204 csp->http->hostport, parameter_conditional_block);
3206 else if (0 == strcmpic(parameter, "forge"))
3208 return create_forged_referrer(header, csp->http->hostport);
3212 /* interpret parameter as user-supplied referer to fake */
3213 return create_fake_referrer(header, parameter);
3218 /*********************************************************************
3220 * Function : client_accept_language
3222 * Description : Handle the "Accept-Language" config setting properly.
3223 * Called from `sed'.
3226 * 1 : csp = Current client state (buffers, headers, etc...)
3227 * 2 : header = On input, pointer to header to modify.
3228 * On output, pointer to the modified header, or NULL
3229 * to remove the header. This function frees the
3230 * original string if necessary.
3232 * Returns : JB_ERR_OK on success, or
3233 * JB_ERR_MEMORY on out-of-memory error.
3235 *********************************************************************/
3236 static jb_err client_accept_language(struct client_state *csp, char **header)
3241 * Are we messing with the Accept-Language?
3243 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3245 /*I don't think so*/
3249 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3251 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3254 * Blocking Accept-Language header
3256 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3263 * Replacing Accept-Language header
3266 *header = strdup("Accept-Language: ");
3267 string_append(header, newval);
3269 if (*header == NULL)
3271 log_error(LOG_LEVEL_ERROR,
3272 "Insufficient memory. Accept-Language header crunched without replacement.");
3276 log_error(LOG_LEVEL_HEADER,
3277 "Accept-Language header crunched and replaced with: %s", *header);
3280 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3284 /*********************************************************************
3286 * Function : crunch_client_header
3288 * Description : Crunch client header if it matches a string supplied by the
3289 * user. Called from `sed'.
3292 * 1 : csp = Current client state (buffers, headers, etc...)
3293 * 2 : header = On input, pointer to header to modify.
3294 * On output, pointer to the modified header, or NULL
3295 * to remove the header. This function frees the
3296 * original string if necessary.
3298 * Returns : JB_ERR_OK on success and always succeeds
3300 *********************************************************************/
3301 static jb_err crunch_client_header(struct client_state *csp, char **header)
3303 const char *crunch_pattern;
3305 /* Do we feel like crunching? */
3306 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3308 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3310 /* Is the current header the lucky one? */
3311 if (strstr(*header, crunch_pattern))
3313 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3321 /*********************************************************************
3323 * Function : client_uagent
3325 * Description : Handle the "user-agent" config setting properly
3326 * and remember its original value to enable browser
3327 * bug workarounds. Called from `sed'.
3330 * 1 : csp = Current client state (buffers, headers, etc...)
3331 * 2 : header = On input, pointer to header to modify.
3332 * On output, pointer to the modified header, or NULL
3333 * to remove the header. This function frees the
3334 * original string if necessary.
3336 * Returns : JB_ERR_OK on success, or
3337 * JB_ERR_MEMORY on out-of-memory error.
3339 *********************************************************************/
3340 static jb_err client_uagent(struct client_state *csp, char **header)
3344 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3349 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3356 *header = strdup("User-Agent: ");
3357 string_append(header, newval);
3359 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3361 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3365 /*********************************************************************
3367 * Function : client_ua
3369 * Description : Handle "ua-" headers properly. Called from `sed'.
3372 * 1 : csp = Current client state (buffers, headers, etc...)
3373 * 2 : header = On input, pointer to header to modify.
3374 * On output, pointer to the modified header, or NULL
3375 * to remove the header. This function frees the
3376 * original string if necessary.
3378 * Returns : JB_ERR_OK on success, or
3379 * JB_ERR_MEMORY on out-of-memory error.
3381 *********************************************************************/
3382 static jb_err client_ua(struct client_state *csp, char **header)
3384 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3386 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3394 /*********************************************************************
3396 * Function : client_from
3398 * Description : Handle the "from" config setting properly.
3399 * Called from `sed'.
3402 * 1 : csp = Current client state (buffers, headers, etc...)
3403 * 2 : header = On input, pointer to header to modify.
3404 * On output, pointer to the modified header, or NULL
3405 * to remove the header. This function frees the
3406 * original string if necessary.
3408 * Returns : JB_ERR_OK on success, or
3409 * JB_ERR_MEMORY on out-of-memory error.
3411 *********************************************************************/
3412 static jb_err client_from(struct client_state *csp, char **header)
3416 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3423 newval = csp->action->string[ACTION_STRING_FROM];
3426 * Are we blocking the e-mail address?
3428 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3430 log_error(LOG_LEVEL_HEADER, "crunched From!");
3434 log_error(LOG_LEVEL_HEADER, " modified");
3436 *header = strdup("From: ");
3437 string_append(header, newval);
3439 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3443 /*********************************************************************
3445 * Function : client_send_cookie
3447 * Description : Crunches the "cookie" header if necessary.
3448 * Called from `sed'.
3450 * XXX: Stupid name, doesn't send squat.
3453 * 1 : csp = Current client state (buffers, headers, etc...)
3454 * 2 : header = On input, pointer to header to modify.
3455 * On output, pointer to the modified header, or NULL
3456 * to remove the header. This function frees the
3457 * original string if necessary.
3459 * Returns : JB_ERR_OK on success, or
3460 * JB_ERR_MEMORY on out-of-memory error.
3462 *********************************************************************/
3463 static jb_err client_send_cookie(struct client_state *csp, char **header)
3465 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3467 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3475 /*********************************************************************
3477 * Function : client_x_forwarded
3479 * Description : Handle the "x-forwarded-for" config setting properly,
3480 * also used in the add_client_headers list. Called from `sed'.
3483 * 1 : csp = Current client state (buffers, headers, etc...)
3484 * 2 : header = On input, pointer to header to modify.
3485 * On output, pointer to the modified header, or NULL
3486 * to remove the header. This function frees the
3487 * original string if necessary.
3489 * Returns : JB_ERR_OK on success, or
3490 * JB_ERR_MEMORY on out-of-memory error.
3492 *********************************************************************/
3493 jb_err client_x_forwarded(struct client_state *csp, char **header)
3495 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3497 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3499 if (0 == strcmpic(parameter, "block"))
3502 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3504 else if (0 == strcmpic(parameter, "add"))
3506 string_append(header, ", ");
3507 string_append(header, csp->ip_addr_str);
3509 if (*header == NULL)
3511 return JB_ERR_MEMORY;
3513 log_error(LOG_LEVEL_HEADER,
3514 "Appended client IP address to %s", *header);
3515 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3519 log_error(LOG_LEVEL_FATAL,
3520 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3528 /*********************************************************************
3530 * Function : client_max_forwards
3532 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3533 * from the value of the Max-Forwards header field.
3536 * 1 : csp = Current client state (buffers, headers, etc...)
3537 * 2 : header = On input, pointer to header to modify.
3538 * On output, pointer to the modified header, or NULL
3539 * to remove the header. This function frees the
3540 * original string if necessary.
3542 * Returns : JB_ERR_OK on success, or
3543 * JB_ERR_MEMORY on out-of-memory error.
3545 *********************************************************************/
3546 static jb_err client_max_forwards(struct client_state *csp, char **header)
3550 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3551 (0 == strcmpic(csp->http->gpc, "options")))
3553 assert(*(*header+12) == ':');
3554 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3556 if (max_forwards > 0)
3558 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3559 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3560 csp->http->gpc, max_forwards);
3562 else if (max_forwards < 0)
3564 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3570 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3579 /*********************************************************************
3581 * Function : client_host
3583 * Description : If the request URI did not contain host and
3584 * port information, parse and evaluate the Host
3587 * Also, kill ill-formed HOST: headers as sent by
3588 * Apple's iTunes software when used with a proxy.
3591 * 1 : csp = Current client state (buffers, headers, etc...)
3592 * 2 : header = On input, pointer to header to modify.
3593 * On output, pointer to the modified header, or NULL
3594 * to remove the header. This function frees the
3595 * original string if necessary.
3597 * Returns : JB_ERR_OK on success, or
3598 * JB_ERR_MEMORY on out-of-memory error.
3600 *********************************************************************/
3601 static jb_err client_host(struct client_state *csp, char **header)
3606 * If the header field name is all upper-case, chances are that it's
3607 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3608 * not a problem -- they are regenerated later.
3610 if ((*header)[1] == 'O')
3612 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3617 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3618 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3621 if (NULL == (p = strdup((*header)+6)))
3623 return JB_ERR_MEMORY;
3626 if (NULL == (q = strdup(p)))
3629 return JB_ERR_MEMORY;
3632 freez(csp->http->hostport);
3633 csp->http->hostport = p;
3634 freez(csp->http->host);
3635 csp->http->host = q;
3636 q = strchr(csp->http->host, ':');
3639 /* Terminate hostname and evaluate port string */
3641 csp->http->port = atoi(q);
3645 csp->http->port = csp->http->ssl ? 443 : 80;
3648 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3649 csp->http->hostport, csp->http->host, csp->http->port);
3652 /* Signal client_host_adder() to return right away */
3653 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3659 /*********************************************************************
3661 * Function : client_if_modified_since
3663 * Description : Remove or modify the If-Modified-Since header.
3666 * 1 : csp = Current client state (buffers, headers, etc...)
3667 * 2 : header = On input, pointer to header to modify.
3668 * On output, pointer to the modified header, or NULL
3669 * to remove the header. This function frees the
3670 * original string if necessary.
3672 * Returns : JB_ERR_OK on success, or
3673 * JB_ERR_MEMORY on out-of-memory error.
3675 *********************************************************************/
3676 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3679 #ifdef HAVE_GMTIME_R
3682 struct tm *timeptr = NULL;
3686 long int hours, minutes, seconds;
3690 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3693 * The client got an error message because of a temporary problem,
3694 * the problem is gone and the client now tries to revalidate our
3695 * error message on the real server. The revalidation would always
3696 * end with the transmission of the whole document and there is
3697 * no need to expose the bogus If-Modified-Since header.
3699 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3702 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3704 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3706 if ((0 == strcmpic(newval, "block")))
3708 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3711 else /* add random value */
3713 const char *header_time = *header + sizeof("If-Modified-Since:");
3715 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3717 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3722 rtime = strtol(newval, &endptr, 0);
3725 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3726 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3733 rtime = pick_from_range(rtime);
3737 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3740 tm += rtime * (negative ? -1 : 1);
3741 #ifdef HAVE_GMTIME_R
3742 timeptr = gmtime_r(&tm, &gmt);
3743 #elif FEATURE_PTHREAD
3744 privoxy_mutex_lock(&gmtime_mutex);
3745 timeptr = gmtime(&tm);
3746 privoxy_mutex_unlock(&gmtime_mutex);
3748 timeptr = gmtime(&tm);
3750 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3753 *header = strdup("If-Modified-Since: ");
3754 string_append(header, newheader);
3756 if (*header == NULL)
3758 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3759 return JB_ERR_MEMORY;
3762 hours = rtime / 3600;
3763 minutes = rtime / 60 % 60;
3764 seconds = rtime % 60;
3766 log_error(LOG_LEVEL_HEADER,
3767 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3768 *header, (negative) ? "subtracted" : "added", hours,
3769 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3770 seconds, (seconds == 1) ? ")" : "s)");
3779 /*********************************************************************
3781 * Function : client_if_none_match
3783 * Description : Remove the If-None-Match header.
3786 * 1 : csp = Current client state (buffers, headers, etc...)
3787 * 2 : header = On input, pointer to header to modify.
3788 * On output, pointer to the modified header, or NULL
3789 * to remove the header. This function frees the
3790 * original string if necessary.
3792 * Returns : JB_ERR_OK on success, or
3793 * JB_ERR_MEMORY on out-of-memory error.
3795 *********************************************************************/
3796 static jb_err client_if_none_match(struct client_state *csp, char **header)
3798 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3800 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3808 /*********************************************************************
3810 * Function : client_x_filter
3812 * Description : Disables filtering if the client set "X-Filter: No".
3813 * Called from `sed'.
3816 * 1 : csp = Current client state (buffers, headers, etc...)
3817 * 2 : header = On input, pointer to header to modify.
3818 * On output, pointer to the modified header, or NULL
3819 * to remove the header. This function frees the
3820 * original string if necessary.
3822 * Returns : JB_ERR_OK on success
3824 *********************************************************************/
3825 jb_err client_x_filter(struct client_state *csp, char **header)
3827 if ( 0 == strcmpic(*header, "X-Filter: No"))
3829 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3831 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3835 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3837 log_error(LOG_LEVEL_HEADER,
3838 "force-text-mode overruled the client's request to fetch without filtering!");
3842 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3843 csp->flags |= CSP_FLAG_NO_FILTERING;
3844 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3846 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3854 /*********************************************************************
3856 * Function : client_range
3858 * Description : Removes Range, Request-Range and If-Range headers if
3859 * content filtering is enabled. If the client's version
3860 * of the document has been altered by Privoxy, the server
3861 * could interpret the range differently than the client
3862 * intended in which case the user could end up with
3863 * corrupted content.
3866 * 1 : csp = Current client state (buffers, headers, etc...)
3867 * 2 : header = On input, pointer to header to modify.
3868 * On output, pointer to the modified header, or NULL
3869 * to remove the header. This function frees the
3870 * original string if necessary.
3872 * Returns : JB_ERR_OK
3874 *********************************************************************/
3875 static jb_err client_range(struct client_state *csp, char **header)
3877 if (content_filters_enabled(csp->action))
3879 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3880 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3887 /* the following functions add headers directly to the header list */
3889 /*********************************************************************
3891 * Function : client_host_adder
3893 * Description : Adds the Host: header field if it is missing.
3894 * Called from `sed'.
3897 * 1 : csp = Current client state (buffers, headers, etc...)
3899 * Returns : JB_ERR_OK on success, or
3900 * JB_ERR_MEMORY on out-of-memory error.
3902 *********************************************************************/
3903 static jb_err client_host_adder(struct client_state *csp)
3908 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3910 /* Header already set by the client, nothing to do. */
3914 if ( !csp->http->hostport || !*(csp->http->hostport))
3916 /* XXX: When does this happen and why is it OK? */
3917 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3922 * remove 'user:pass@' from 'proto://user:pass@host'
3924 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3930 p = csp->http->hostport;
3933 /* XXX: Just add it, we already made sure that it will be unique */
3934 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3935 err = enlist_unique_header(csp->headers, "Host", p);
3942 /*********************************************************************
3944 * Function : client_accept_encoding_adder
3946 * Description : Add an Accept-Encoding header to the client's request
3947 * that disables compression if the action applies, and
3948 * the header is not already there. Called from `sed'.
3949 * Note: For HTTP/1.0, the absence of the header is enough.
3952 * 1 : csp = Current client state (buffers, headers, etc...)
3954 * Returns : JB_ERR_OK on success, or
3955 * JB_ERR_MEMORY on out-of-memory error.
3957 *********************************************************************/
3958 static jb_err client_accept_encoding_adder(struct client_state *csp)
3960 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3961 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3963 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3971 /*********************************************************************
3973 * Function : client_xtra_adder
3975 * Description : Used in the add_client_headers list. Called from `sed'.
3978 * 1 : csp = Current client state (buffers, headers, etc...)
3980 * Returns : JB_ERR_OK on success, or
3981 * JB_ERR_MEMORY on out-of-memory error.
3983 *********************************************************************/
3984 static jb_err client_xtra_adder(struct client_state *csp)
3986 struct list_entry *lst;
3989 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3990 lst ; lst = lst->next)
3992 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3993 err = enlist(csp->headers, lst->str);
4005 /*********************************************************************
4007 * Function : client_x_forwarded_for_adder
4009 * Description : Used in the add_client_headers list. Called from `sed'.
4012 * 1 : csp = Current client state (buffers, headers, etc...)
4014 * Returns : JB_ERR_OK on success, or
4015 * JB_ERR_MEMORY on out-of-memory error.
4017 *********************************************************************/
4018 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
4020 char *header = NULL;
4023 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
4024 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
4025 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
4028 * If we aren't adding X-Forwarded-For headers,
4029 * or we already appended an existing X-Forwarded-For
4030 * header, there's nothing left to do here.
4035 header = strdup("X-Forwarded-For: ");
4036 string_append(&header, csp->ip_addr_str);
4040 return JB_ERR_MEMORY;
4043 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
4044 err = enlist(csp->headers, header);
4051 /*********************************************************************
4053 * Function : server_connection_close_adder
4055 * Description : "Temporary" fix for the needed but missing HTTP/1.1
4056 * support. Adds a "Connection: close" header to csp->headers
4057 * unless the header was already present. Called from `sed'.
4059 * FIXME: This whole function shouldn't be neccessary!
4062 * 1 : csp = Current client state (buffers, headers, etc...)
4064 * Returns : JB_ERR_OK on success, or
4065 * JB_ERR_MEMORY on out-of-memory error.
4067 *********************************************************************/
4068 static jb_err server_connection_close_adder(struct client_state *csp)
4070 const unsigned int flags = csp->flags;
4072 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4073 && (flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET))
4078 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
4080 return enlist(csp->headers, "Connection: close");
4084 /*********************************************************************
4086 * Function : client_connection_header_adder
4088 * Description : Adds a proper "Connection:" header to csp->headers
4089 * unless the header was already present. Called from `sed'.
4092 * 1 : csp = Current client state (buffers, headers, etc...)
4094 * Returns : JB_ERR_OK on success, or
4095 * JB_ERR_MEMORY on out-of-memory error.
4097 *********************************************************************/
4098 static jb_err client_connection_header_adder(struct client_state *csp)
4100 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4101 static const char wanted_header[] = "Connection: keep-alive";
4103 static const char wanted_header[] = "Connection: close";
4104 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4105 const unsigned int flags = csp->flags;
4107 if (!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4108 && (flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4113 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
4115 return enlist(csp->headers, wanted_header);
4119 /*********************************************************************
4121 * Function : server_http
4123 * Description : - Save the HTTP Status into csp->http->status
4124 * - Set CT_TABOO to prevent filtering if the answer
4125 * is a partial range (HTTP status 206)
4126 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4130 * 1 : csp = Current client state (buffers, headers, etc...)
4131 * 2 : header = On input, pointer to header to modify.
4132 * On output, pointer to the modified header, or NULL
4133 * to remove the header. This function frees the
4134 * original string if necessary.
4136 * Returns : JB_ERR_OK on success, or
4137 * JB_ERR_MEMORY on out-of-memory error.
4139 *********************************************************************/
4140 static jb_err server_http(struct client_state *csp, char **header)
4142 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
4143 if (csp->http->status == 206)
4145 csp->content_type = CT_TABOO;
4148 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
4150 /* XXX: Should we do a real validity check here? */
4151 if (strlen(*header) > 8)
4154 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
4159 * XXX: Should we block the request or
4160 * enlist a valid status code line here?
4162 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
4163 "Downgrading to HTTP/1.0 impossible.");
4171 /*********************************************************************
4173 * Function : server_set_cookie
4175 * Description : Handle the server "cookie" header properly.
4176 * Log cookie to the jar file. Then "crunch",
4177 * accept or rewrite it to a session cookie.
4178 * Called from `sed'.
4180 * TODO: Allow the user to specify a new expiration
4181 * time to cause the cookie to expire even before the
4182 * browser is closed.
4185 * 1 : csp = Current client state (buffers, headers, etc...)
4186 * 2 : header = On input, pointer to header to modify.
4187 * On output, pointer to the modified header, or NULL
4188 * to remove the header. This function frees the
4189 * original string if necessary.
4191 * Returns : JB_ERR_OK on success, or
4192 * JB_ERR_MEMORY on out-of-memory error.
4194 *********************************************************************/
4195 static jb_err server_set_cookie(struct client_state *csp, char **header)
4202 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4204 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4207 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4209 /* Flag whether or not to log a message */
4212 /* A variable to store the tag we're working on */
4215 /* Skip "Set-Cookie:" (11 characters) in header */
4216 cur_tag = *header + 11;
4218 /* skip whitespace between "Set-Cookie:" and value */
4219 while (*cur_tag && ijb_isspace(*cur_tag))
4224 /* Loop through each tag in the cookie */
4228 char *next_tag = strchr(cur_tag, ';');
4229 if (next_tag != NULL)
4231 /* Skip the ';' character itself */
4234 /* skip whitespace ";" and start of tag */
4235 while (*next_tag && ijb_isspace(*next_tag))
4242 /* "Next tag" is the end of the string */
4243 next_tag = cur_tag + strlen(cur_tag);
4247 * Check the expiration date to see
4248 * if the cookie is still valid, if yes,
4249 * rewrite it to a session cookie.
4251 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4253 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4255 /* Did we detect the date properly? */
4256 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4259 * Nope, treat it as if it was still valid.
4261 * XXX: Should we remove the whole cookie instead?
4263 log_error(LOG_LEVEL_ERROR,
4264 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4265 string_move(cur_tag, next_tag);
4271 * Yes. Check if the cookie is still valid.
4273 * If the cookie is already expired it's probably
4274 * a delete cookie and even if it isn't, the browser
4275 * will discard it anyway.
4279 * XXX: timegm() isn't available on some AmigaOS
4280 * versions and our replacement doesn't work.
4282 * Our options are to either:
4284 * - disable session-cookies-only completely if timegm
4287 * - to simply remove all expired tags, like it has
4288 * been done until Privoxy 3.0.6 and to live with
4289 * the consequence that it can cause login/logout
4290 * problems on servers that don't validate their
4291 * input properly, or
4293 * - to replace it with mktime in which
4294 * case there is a slight chance of valid cookies
4295 * passing as already expired.
4297 * This is the way it's currently done and it's not
4298 * as bad as it sounds. If the missing GMT offset is
4299 * enough to change the result of the expiration check
4300 * the cookie will be only valid for a few hours
4301 * anyway, which in many cases will be shorter
4302 * than a browser session.
4304 if (cookie_time - now < 0)
4306 log_error(LOG_LEVEL_HEADER,
4307 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4308 /* Just in case some clown sets more then one expiration date */
4314 * Still valid, delete expiration date by copying
4315 * the rest of the string over it.
4317 string_move(cur_tag, next_tag);
4319 /* That changed the header, need to issue a log message */
4323 * Note that the next tag has now been moved to *cur_tag,
4324 * so we do not need to update the cur_tag pointer.
4332 /* Move on to next cookie tag */
4339 assert(NULL != *header);
4340 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4349 #ifdef FEATURE_FORCE_LOAD
4350 /*********************************************************************
4352 * Function : strclean
4354 * Description : In-Situ-Eliminate all occurances of substring in
4358 * 1 : string = string to clean
4359 * 2 : substring = substring to eliminate
4361 * Returns : Number of eliminations
4363 *********************************************************************/
4364 int strclean(char *string, const char *substring)
4370 len = strlen(substring);
4372 while((pos = strstr(string, substring)) != NULL)
4379 while (*p++ != '\0');
4386 #endif /* def FEATURE_FORCE_LOAD */
4389 /*********************************************************************
4391 * Function : parse_header_time
4393 * Description : Parses time formats used in HTTP header strings
4394 * to get the numerical respresentation.
4397 * 1 : header_time = HTTP header time as string.
4398 * 2 : result = storage for header_time in seconds
4400 * Returns : JB_ERR_OK if the time format was recognized, or
4401 * JB_ERR_PARSE otherwise.
4403 *********************************************************************/
4404 static jb_err parse_header_time(const char *header_time, time_t *result)
4409 * Zero out gmt to prevent time zone offsets.
4411 * While this is only necessary on some platforms
4412 * (mingw32 for example), I don't know how to
4413 * detect these automatically and doing it everywhere
4416 memset(&gmt, 0, sizeof(gmt));
4418 /* Tue, 02 Jun 2037 20:00:00 */
4419 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4420 /* Tue, 02-Jun-2037 20:00:00 */
4421 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4422 /* Tue, 02-Jun-37 20:00:00 */
4423 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4424 /* Tuesday, 02-Jun-2037 20:00:00 */
4425 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4426 /* Tuesday Jun 02 20:00:00 2037 */
4427 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4429 return JB_ERR_PARSE;
4432 *result = timegm(&gmt);
4439 /*********************************************************************
4441 * Function : get_destination_from_headers
4443 * Description : Parse the "Host:" header to get the request's destination.
4444 * Only needed if the client's request was forcefully
4445 * redirected into Privoxy.
4447 * Code mainly copied from client_host() which is currently
4448 * run too late for this purpose.
4451 * 1 : headers = List of headers (one of them hopefully being
4452 * the "Host:" header)
4453 * 2 : http = storage for the result (host, port and hostport).
4455 * Returns : JB_ERR_MEMORY in case of memory problems,
4456 * JB_ERR_PARSE if the host header couldn't be found,
4457 * JB_ERR_OK otherwise.
4459 *********************************************************************/
4460 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4466 host = get_header_value(headers, "Host:");
4470 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4471 return JB_ERR_PARSE;
4474 if (NULL == (p = strdup((host))))
4476 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4477 return JB_ERR_MEMORY;
4480 if (NULL == (q = strdup(p)))
4483 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4484 return JB_ERR_MEMORY;
4487 freez(http->hostport);
4491 q = strchr(http->host, ':');
4494 /* Terminate hostname and evaluate port string */
4496 http->port = atoi(q);
4500 http->port = http->ssl ? 443 : 80;
4503 /* Rebuild request URL */
4505 http->url = strdup(http->ssl ? "https://" : "http://");
4506 string_append(&http->url, http->hostport);
4507 string_append(&http->url, http->path);
4508 if (http->url == NULL)
4510 return JB_ERR_MEMORY;
4513 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4521 /*********************************************************************
4523 * Function : create_forged_referrer
4525 * Description : Helper for client_referrer to forge a referer as
4526 * 'http://[hostname:port/' to fool stupid
4527 * checks for in-site links
4530 * 1 : header = Pointer to header pointer
4531 * 2 : hostport = Host and optionally port as string
4533 * Returns : JB_ERR_OK in case of success, or
4534 * JB_ERR_MEMORY in case of memory problems.
4536 *********************************************************************/
4537 static jb_err create_forged_referrer(char **header, const char *hostport)
4539 assert(NULL == *header);
4541 *header = strdup("Referer: http://");
4542 string_append(header, hostport);
4543 string_append(header, "/");
4545 if (NULL == *header)
4547 return JB_ERR_MEMORY;
4550 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4557 /*********************************************************************
4559 * Function : create_fake_referrer
4561 * Description : Helper for client_referrer to create a fake referrer
4562 * based on a string supplied by the user.
4565 * 1 : header = Pointer to header pointer
4566 * 2 : hosthost = Referrer to fake
4568 * Returns : JB_ERR_OK in case of success, or
4569 * JB_ERR_MEMORY in case of memory problems.
4571 *********************************************************************/
4572 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4574 assert(NULL == *header);
4576 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4578 log_error(LOG_LEVEL_HEADER,
4579 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4581 *header = strdup("Referer: ");
4582 string_append(header, fake_referrer);
4584 if (NULL == *header)
4586 return JB_ERR_MEMORY;
4589 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4596 /*********************************************************************
4598 * Function : handle_conditional_hide_referrer_parameter
4600 * Description : Helper for client_referrer to crunch or forge
4601 * the referrer header if the host has changed.
4604 * 1 : header = Pointer to header pointer
4605 * 2 : host = The target host (may include the port)
4606 * 3 : parameter_conditional_block = Boolean to signal
4607 * if we're in conditional-block mode. If not set,
4608 * we're in conditional-forge mode.
4610 * Returns : JB_ERR_OK in case of success, or
4611 * JB_ERR_MEMORY in case of memory problems.
4613 *********************************************************************/
4614 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4615 const char *host, const int parameter_conditional_block)
4617 char *referer = strdup(*header);
4618 const size_t hostlenght = strlen(host);
4620 if (NULL == referer)
4623 return JB_ERR_MEMORY;
4626 /* referer begins with 'Referer: http[s]://' */
4627 if (hostlenght < (strlen(referer)-17))
4630 * Shorten referer to make sure the referer is blocked
4631 * if www.example.org/www.example.com-shall-see-the-referer/
4632 * links to www.example.com/
4634 referer[hostlenght+17] = '\0';
4636 if (NULL == strstr(referer, host))
4638 /* Host has changed */
4639 if (parameter_conditional_block)
4641 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4648 return create_forged_referrer(header, host);