1 const char parsers_rcs[] = "$Id: parsers.c,v 1.141 2008/09/19 15:26:28 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.141 2008/09/19 15:26:28 fabiankeil
48 * Add change-x-forwarded-for{} action to block or add
49 * X-Forwarded-For headers. Mostly based on code removed
52 * Revision 1.140 2008/09/12 17:51:43 fabiankeil
53 * - A few style fixes.
54 * - Remove a pointless cast.
56 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
57 * Prepare for critical sections on Windows by adding a
58 * layer of indirection before the pthread mutex functions.
60 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
61 * Remove FEATURE_COOKIE_JAR.
63 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
64 * Remove questionable micro-optimizations
65 * whose usefulness has never been measured.
67 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
68 * s@Insufficent@Insufficient@
70 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
71 * The whole point of strclean() is to modify the
72 * first parameter, so don't mark it immutable,
73 * even though the compiler lets us get away with it.
75 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
76 * As the wafer actions are gone, we can stop including encode.h.
78 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
79 * Ditch cast from (char **) to (char **).
81 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
82 * Streamline sed()'s prototype and declare
83 * the header parse and add structures static.
85 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
86 * Factor update_server_headers() out of sed(), ditch the
87 * first_run hack and make server_patterns_light static.
89 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
90 * Wrap memmove() calls in string_move()
91 * to document the purpose in one place.
93 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
94 * Normalize linear header white space.
96 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
97 * If a header is split across multiple lines,
98 * merge them to a single line before parsing them.
100 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
101 * Don't provide get_header() with the whole client state
102 * structure when it only needs access to csp->iob.
104 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
105 * Change content_filters_enabled()'s parameter from
106 * csp->action to action so it can be also used in the
107 * CGI code. Don't bother checking if there are filters
108 * loaded, as that's somewhat besides the point.
110 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
111 * Provide get_http_time() with the buffer size so it doesn't
112 * have to blindly assume that the buffer is big enough.
114 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
115 * Don't pass the whole csp structure to flush_socket()
116 * when it only needs a file descriptor and a buffer.
118 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
119 * Remove send-wafer and send-vanilla-wafer actions.
121 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
122 * Remove inspect-jpegs action.
124 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
125 * Let client_range() also handle Request-Range headers
126 * which apparently are still supported by many servers.
128 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
129 * Improve the warning messages that get logged if the action files
130 * "enable" filters but no filters of that type have been loaded.
132 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
133 * In server_content_type():
134 * - Don't require leading white space when detecting image content types.
135 * - Change '... not replaced ...' message to sound less crazy if the text
136 * type actually is 'text/plain'.
137 * - Mark the 'text/plain == binary data' assumption for removal.
138 * - Remove a bunch of trailing white space.
140 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
141 * Minor server_content_disposition() changes:
142 * - Don't regenerate the header name all lower-case.
143 * - Some white space fixes.
144 * - Remove useless log message in case of ENOMEM.
146 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
147 * Garbage-collect the code to add a X-Forwarded-For
148 * header as it seems to be mostly used by accident.
150 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
151 * Fix a crash on mingw32 with some Last Modified times in the future.
153 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
154 * Remove a "can't happen" error block which, over
155 * time, mutated into a "guaranteed to happen" block.
157 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
158 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
159 * - Use shiny new content_filters_enabled() in client_range().
161 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
162 * I forgot about Poland.
164 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
165 * Remove Range and If-Range headers if content filtering is enabled.
167 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
168 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
169 * client_cookie_adder() to make sure send-vanilla-wafer can be
170 * controlled through tags (and thus regression-tested).
172 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
173 * - Remove "scanning headers for" log message again.
174 * - Some more whitespace fixes.
176 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
177 * Refactor client_referrer() and add conditional-forge parameter.
179 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
180 * A bunch of whitespace fixes, pointy hat to me.
182 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
183 * Fix possible memory corruption in server_http, make sure it's not
184 * executed for ordinary server headers and mark some problems for later.
186 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
187 * Let content-type-overwrite{} honour force-text-mode again.
189 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
190 * - Add prototpyes for the header parsers and make them static.
191 * - Comment out client_accept_encoding_adder() which isn't used right now.
193 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
194 * Move the ACTION_FORCE_TEXT_MODE check out of
195 * server_content_type(). Signal other functions
196 * whether or not a content type has been declared.
197 * Part of the fix for BR#1750917.
199 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
200 * Change sed() to return a jb_err in preparation for forward-override{}.
202 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
203 * Adjust "X-Filter: No" to disable dedicated header filters.
205 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
206 * Streamline client_cookie_adder().
208 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
209 * Make sure filters with dynamic jobs actually use them.
211 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
212 * - Introduce dynamic pcrs jobs that can resolve variables.
213 * - Remove unnecessary update_action_bits_for_all_tags() call.
215 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
216 * - Make tagging based on tags set by earlier taggers
217 * of the same kind possible.
218 * - Log whether or not new tags cause action bits updates
219 * (in which case a matching tag-pattern section exists).
220 * - Log if the user tries to set a tag that is already set.
222 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
223 * Introduce tags as alternative way to specify which
224 * actions apply to a request. At the moment tags can be
225 * created based on client and server headers.
227 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
228 * Log a warning if the content is compressed, filtering is
229 * enabled and Privoxy was compiled without zlib support.
232 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
233 * - Fix warnings when compiled with glibc.
234 * - Don't use crumble() for cookie crunching.
235 * - Move cookie time parsing into parse_header_time().
236 * - Let parse_header_time() return a jb_err code
237 * instead of a pointer that can only be used to
238 * check for NULL anyway.
240 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
241 * - Add better protection against malicious gzip headers.
242 * - Stop logging the first hundred bytes of decompressed content.
243 * It looks like it's working and there is always debug 16.
244 * - Log the content size after decompression in decompress_iob()
245 * instead of pcrs_filter_response().
247 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
248 * - Use dedicated header filter actions instead of abusing "filter".
249 * Replace "filter-client-headers" and "filter-client-headers"
250 * with "server-header-filter" and "client-header-filter".
251 * - Remove filter_client_header() and filter_client_header(),
252 * filter_header() now checks the shiny new
253 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
255 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
256 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
257 * - Handle "Cookie:" and "Connection:" headers a bit smarter
258 * (don't crunch them just to recreate them later on).
259 * - Add another non-standard time format for the cookie
260 * expiration date detection.
261 * - Fix a valgrind warning.
263 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
264 * Improve cookie expiration date detection.
266 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
267 * Don't run server_content_length() the first time
268 * sed() parses server headers; only adjust the
269 * Content-Length header if the page was modified.
271 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
272 * Fix log messages regarding the cookie time format
273 * (cookie and request URL were mixed up).
275 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
276 * - Let decompress_iob()
277 * - not corrupt the content if decompression fails
278 * early. (the first byte(s) were lost).
279 * - use pointer arithmetics with defined outcome for
281 * - Use a different kludge to remember a failed decompression.
283 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
284 * Search for Max-Forwards headers case-insensitive,
285 * don't generate the "501 unsupported" message for invalid
286 * Max-Forwards values and don't increase negative ones.
288 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
289 * - Let server_set_cookie() check the expiration date
290 * of cookies and don't touch the ones that are already
291 * expired. Fixes problems with low quality web applications
292 * as described in BR 932612.
294 * - Adjust comment in client_max_forwards to reality;
295 * remove invalid Max-Forwards headers.
297 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
298 * Stop filter_header() from unintentionally removing
299 * empty header lines that were enlisted by the continue
302 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
303 * - Repeat the request URL before logging any headers.
304 * Makes reading the log easier in case of simultaneous requests.
305 * - If there are more than one Content-Type headers in one request,
306 * use the first one and remove the others.
307 * - Remove "newval" variable in server_content_type().
308 * It's only used once.
310 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
311 * Correct a cast, check inflateEnd() exit code
312 * to see if we have to, replace sprintf calls
315 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
316 * Integrate a modified version of Wil Mahan's
317 * zlib patch (PR #895531).
319 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
320 * Skip empty filter files in filter_header()
321 * but don't ignore the ones that come afterwards.
322 * Fixes BR 1619208, this time for real.
324 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
325 * Reverted parts of my last commit
326 * to keep error handling working.
328 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
329 * Fixed gcc43 conversion warnings.
331 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
332 * Bringing back the "useless" localtime() call
333 * I removed in revision 1.67. On some platforms
334 * it's necessary to prevent time zone offsets.
336 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
337 * Rebuild request URL in get_destination_from_headers()
338 * to make sure redirect{pcrs command} works as expected
339 * for intercepted requests.
341 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
342 * Added get_destination_from_headers().
344 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
345 * Make pthread mutex locking more generic. Instead of
346 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
347 * and use mutex locking unless there is an _r function
348 * available. Better safe than sorry.
350 * Fixes "./configure --disable-pthread" and should result
351 * in less threading-related problems on pthread-using platforms,
352 * but it still doesn't fix BR#1122404.
354 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
355 * The special header "X-Filter: No" now disables
356 * header filtering as well.
358 * Revision 1.73 2006/09/23 13:26:38 roro
359 * Replace TABs by spaces in source code.
361 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
362 * Don't print a log message every time filter_headers is
363 * entered or left. It only creates noise without any real
366 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
367 * Fix +hide-if-modified-since{-n}.
369 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
370 * Have hide-if-modified-since interpret the random
371 * range value as minutes instead of hours. Allows
372 * more fine-grained configuration.
374 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
375 * Always have parse_header_time return a pointer
376 * that actual makes sense, even though we currently
377 * only need it to detect problems.
379 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
380 * Added config option enable-remote-http-toggle
381 * to specify if Privoxy should recognize special
382 * headers (currently only X-Filter) to change its
383 * behaviour. Disabled by default.
385 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
386 * After filtering de-chunked instances, remove
387 * "Transfer-Encoding" header entirely instead of changing
388 * it to "Transfer-Encoding: identity", which is invalid.
389 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
391 * Don't use localtime in parse_header_time. An empty time struct
392 * is good enough, it gets overwritten by strptime anyway.
394 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
395 * Use gmtime_r if available, fallback to gmtime with mutex
396 * protection for MacOSX and use vanilla gmtime for the rest.
398 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
399 * Changed client_referrer to use the right type (size_t) for
400 * hostlenght and to shorten the temporary referrer string with
401 * '\0' instead of adding a useless line break.
403 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
404 * - Back to timegm() using GnuPG's replacement if necessary.
405 * Using mktime() and localtime() could add a on hour offset if
406 * the randomize factor was big enough to lead to a summer/wintertime
409 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
411 * - Moved randomization code into pick_from_range().
413 * - Changed parse_header_time definition.
414 * time_t isn't guaranteed to be signed and
415 * if it isn't, -1 isn't available as error code.
416 * Changed some variable types in client_if_modified_since()
417 * because of the same reason.
419 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
420 * OS/2 compilation compatibility fixups
422 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
423 * Changed include from strptime.c to strptime.h
425 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
426 * Split filter-headers{} into filter-client-headers{}
427 * and filter-server-headers{}.
428 * Added parse_header_time() to share some code.
429 * Replaced timegm() with mktime().
431 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
432 * Windows service integration
434 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
435 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
437 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
438 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
439 * with what was really the latest development (the v_3_0_branch branch)
441 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
442 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
444 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
445 * Add the ability to check jpeg images for invalid
446 * lengths of comment blocks. Defensive strategy
447 * against the exploit:
448 * Microsoft Security Bulletin MS04-028
449 * Buffer Overrun in JPEG Processing (GDI+) Could
450 * Allow Code Execution (833987)
451 * Enabled with +inspect-jpegs in actions files.
453 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
454 * Excluded text/plain objects from filtering. This fixes a
455 * couple of client-crashing, download corruption and
456 * Privoxy performance issues, whose root cause lies in
457 * web servers labelling content of unknown type as text/plain.
459 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
460 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
462 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
463 * Completing the previous change
465 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
466 * Added temporary workaround for bug in PHP < 4.2.3
468 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
469 * 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.
471 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
472 * Fix typo: supressed -> suppressed
474 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
475 * Improved cookie logging
477 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
478 * Added basic support for OPTIONS and TRACE HTTP methods:
479 * - New parser function client_max_forwards which decrements
480 * the Max-Forwards HTTP header field of OPTIONS and TRACE
481 * requests by one before forwarding
482 * - New parser function client_host which extracts the host
483 * and port information from the HTTP header field if the
484 * request URI was not absolute
485 * - Don't crumble and re-add the Host: header, but only generate
486 * and append if missing
488 * Revision 1.56 2002/05/12 15:34:22 jongfoster
489 * Fixing typo in a comment
491 * Revision 1.55 2002/05/08 16:01:07 oes
492 * Optimized add_to_iob:
493 * - Use realloc instead of malloc(), memcpy(), free()
494 * - Expand to powers of two if possible, to get
495 * O(log n) reallocs instead of O(n).
496 * - Moved check for buffer limit here from chat
497 * - Report failure via returncode
499 * Revision 1.54 2002/04/02 15:03:16 oes
500 * Tiny code cosmetics
502 * Revision 1.53 2002/03/26 22:29:55 swa
503 * we have a new homepage!
505 * Revision 1.52 2002/03/24 13:25:43 swa
506 * name change related issues
508 * Revision 1.51 2002/03/13 00:27:05 jongfoster
511 * Revision 1.50 2002/03/12 01:45:35 oes
512 * More verbose logging
514 * Revision 1.49 2002/03/09 20:03:52 jongfoster
515 * - Making various functions return int rather than size_t.
516 * (Undoing a recent change). Since size_t is unsigned on
517 * Windows, functions like read_socket that return -1 on
518 * error cannot return a size_t.
520 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
521 * crashes, and also frequently caused JB to jump to 100%
522 * CPU and stay there. (Because it thought it had just
523 * read ((unsigned)-1) == 4Gb of data...)
525 * - The signature of write_socket has changed, it now simply
526 * returns success=0/failure=nonzero.
528 * - Trying to get rid of a few warnings --with-debug on
529 * Windows, I've introduced a new type "jb_socket". This is
530 * used for the socket file descriptors. On Windows, this
531 * is SOCKET (a typedef for unsigned). Everywhere else, it's
532 * an int. The error value can't be -1 any more, so it's
533 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
534 * Windows it maps to the #define INVALID_SOCKET.)
536 * - The signature of bind_port has changed.
538 * Revision 1.48 2002/03/07 03:46:53 oes
539 * Fixed compiler warnings etc
541 * Revision 1.47 2002/02/20 23:15:13 jongfoster
542 * Parsing functions now handle out-of-memory gracefully by returning
545 * Revision 1.46 2002/01/17 21:03:47 jongfoster
546 * Moving all our URL and URL pattern parsing code to urlmatch.c.
548 * Revision 1.45 2002/01/09 14:33:03 oes
549 * Added support for localtime_r.
551 * Revision 1.44 2001/12/14 01:22:54 steudten
552 * Remove 'user:pass@' from 'proto://user:pass@host' for the
553 * new added header 'Host: ..'. (See Req ID 491818)
555 * Revision 1.43 2001/11/23 00:26:38 jongfoster
556 * Fixing two really stupid errors in my previous commit
558 * Revision 1.42 2001/11/22 21:59:30 jongfoster
559 * Adding code to handle +no-cookies-keep
561 * Revision 1.41 2001/11/05 23:43:05 steudten
562 * Add time+date to log files.
564 * Revision 1.40 2001/10/26 20:13:09 jongfoster
565 * ctype.h is needed in Windows, too.
567 * Revision 1.39 2001/10/26 17:40:04 oes
568 * Introduced get_header_value()
569 * Removed http->user_agent, csp->referrer and csp->accept_types
570 * Removed client_accept()
572 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
573 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
574 * threads to call select() simultaneously. So, it's time to do a real, live,
575 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
576 * (native). Both versions will work, but using __OS2__ offers multi-threading.
578 * Revision 1.37 2001/10/23 21:36:02 jongfoster
579 * Documenting sed()'s error behaviou (doc change only)
581 * Revision 1.36 2001/10/13 12:51:51 joergs
582 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
583 * force-load), instead crumble Host: and add it (again) in client_host_adder
584 * (in case we get a HTTP/1.0 request without Host: header and forward it to
585 * a HTTP/1.1 server/proxy).
587 * Revision 1.35 2001/10/09 22:39:21 jongfoster
588 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
591 * Revision 1.34 2001/10/07 18:50:55 oes
592 * Added server_content_encoding, renamed server_transfer_encoding
594 * Revision 1.33 2001/10/07 18:04:49 oes
595 * Changed server_http11 to server_http and its pattern to "HTTP".
596 * Additional functionality: it now saves the HTTP status into
597 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
599 * Revision 1.32 2001/10/07 15:43:28 oes
600 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
601 * client_te and client_accept_encoding_adder, triggered by the new
602 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
603 * changed to allow only identity and chunked, and the TE header is
604 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
606 * parse_http_request no longer does anything than parsing. The rewriting
607 * of http->cmd and version mangling are gone. It now also recognizes
608 * the put and delete methods and saves the url in http->url. Removed
611 * renamed content_type and content_length to have the server_ prefix
613 * server_content_type now only works if csp->content_type != CT_TABOO
615 * added server_transfer_encoding, which
616 * - Sets CT_TABOO to prohibit filtering if encoding compresses
617 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
618 * - Change from "chunked" to "identity" if body was chunked
619 * but has been de-chunked for filtering.
621 * added server_content_md5 which crunches any Content-MD5 headers
622 * if the body was modified.
624 * made server_http11 conditional on +downgrade action
626 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
628 * Revision 1.31 2001/10/05 14:25:02 oes
629 * Crumble Keep-Alive from Server
631 * Revision 1.30 2001/09/29 12:56:03 joergs
632 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
634 * Revision 1.29 2001/09/24 21:09:24 jongfoster
635 * Fixing 2 memory leaks that Guy spotted, where the paramater to
636 * enlist() was not being free()d.
638 * Revision 1.28 2001/09/22 16:32:28 jongfoster
639 * Removing unused #includes.
641 * Revision 1.27 2001/09/20 15:45:25 steudten
643 * add casting from size_t to int for printf()
644 * remove local variable shadow s2
646 * Revision 1.26 2001/09/16 17:05:14 jongfoster
647 * Removing unused #include showarg.h
649 * Revision 1.25 2001/09/16 13:21:27 jongfoster
650 * Changes to use new list functions.
652 * Revision 1.24 2001/09/13 23:05:50 jongfoster
653 * Changing the string paramater to the header parsers a "const".
655 * Revision 1.23 2001/09/12 18:08:19 steudten
657 * In parse_http_request() header rewriting miss the host value, so
658 * from http://www.mydomain.com the result was just " / " not
659 * http://www.mydomain.com/ in case we forward.
661 * Revision 1.22 2001/09/10 10:58:53 oes
662 * Silenced compiler warnings
664 * Revision 1.21 2001/07/31 14:46:00 oes
665 * - Persistant connections now suppressed
666 * - sed() no longer appends empty header to csp->headers
668 * Revision 1.20 2001/07/30 22:08:36 jongfoster
669 * Tidying up #defines:
670 * - All feature #defines are now of the form FEATURE_xxx
671 * - Permanently turned off WIN_GUI_EDIT
672 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
674 * Revision 1.19 2001/07/25 17:21:54 oes
675 * client_uagent now saves copy of User-Agent: header value
677 * Revision 1.18 2001/07/13 14:02:46 oes
678 * - Included fix to repair broken HTTP requests that
679 * don't contain a path, not even '/'.
680 * - Removed all #ifdef PCRS
681 * - content_type now always inspected and classified as
682 * text, gif or other.
683 * - formatting / comments
685 * Revision 1.17 2001/06/29 21:45:41 oes
686 * Indentation, CRLF->LF, Tab-> Space
688 * Revision 1.16 2001/06/29 13:32:42 oes
690 * - Adapted free_http_request
691 * - Removed logentry from cancelled commit
693 * Revision 1.15 2001/06/03 19:12:38 oes
694 * deleted const struct interceptors
696 * Revision 1.14 2001/06/01 18:49:17 jongfoster
697 * Replaced "list_share" with "list" - the tiny memory gain was not
698 * worth the extra complexity.
700 * Revision 1.13 2001/05/31 21:30:33 jongfoster
701 * Removed list code - it's now in list.[ch]
702 * Renamed "permission" to "action", and changed many features
703 * to use the actions file rather than the global config.
705 * Revision 1.12 2001/05/31 17:33:13 oes
709 * Revision 1.11 2001/05/29 20:11:19 joergs
710 * '/ * inside comment' warning removed.
712 * Revision 1.10 2001/05/29 09:50:24 jongfoster
713 * Unified blocklist/imagelist/permissionslist.
714 * File format is still under discussion, but the internal changes
717 * Also modified interceptor behaviour:
718 * - We now intercept all URLs beginning with one of the following
719 * prefixes (and *only* these prefixes):
721 * * http://ijbswa.sf.net/config/
722 * * http://ijbswa.sourceforge.net/config/
723 * - New interceptors "home page" - go to http://i.j.b/ to see it.
724 * - Internal changes so that intercepted and fast redirect pages
725 * are not replaced with an image.
726 * - Interceptors now have the option to send a binary page direct
727 * to the client. (i.e. ijb-send-banner uses this)
728 * - Implemented show-url-info interceptor. (Which is why I needed
729 * the above interceptors changes - a typical URL is
730 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
731 * The previous mechanism would not have intercepted that, and
732 * if it had been intercepted then it then it would have replaced
735 * Revision 1.9 2001/05/28 17:26:33 jongfoster
736 * Fixing segfault if last header was crunched.
737 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
738 * can use the cross-platform sprintf() instead.)
740 * Revision 1.8 2001/05/27 22:17:04 oes
742 * - re_process_buffer no longer writes the modified buffer
743 * to the client, which was very ugly. It now returns the
744 * buffer, which it is then written by chat.
746 * - content_length now adjusts the Content-Length: header
747 * for modified documents rather than crunch()ing it.
748 * (Length info in csp->content_length, which is 0 for
749 * unmodified documents)
751 * - For this to work, sed() is called twice when filtering.
753 * Revision 1.7 2001/05/27 13:19:06 oes
754 * Patched Joergs solution for the content-length in.
756 * Revision 1.6 2001/05/26 13:39:32 jongfoster
757 * Only crunches Content-Length header if applying RE filtering.
758 * Without this fix, Microsoft Windows Update wouldn't work.
760 * Revision 1.5 2001/05/26 00:28:36 jongfoster
761 * Automatic reloading of config file.
762 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
763 * Most of the global variables have been moved to a new
764 * struct configuration_spec, accessed through csp->config->globalname
765 * Most of the globals remaining are used by the Win32 GUI.
767 * Revision 1.4 2001/05/22 18:46:04 oes
769 * - Enabled filtering banners by size rather than URL
770 * by adding patterns that replace all standard banner
771 * sizes with the "Junkbuster" gif to the re_filterfile
773 * - Enabled filtering WebBugs by providing a pattern
774 * which kills all 1x1 images
776 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
777 * which is selected by the (nonstandard and therefore
778 * capital) letter 'U' in the option string.
779 * It causes the quantifiers to be ungreedy by default.
780 * Appending a ? turns back to greedy (!).
782 * - Added a new interceptor ijb-send-banner, which
783 * sends back the "Junkbuster" gif. Without imagelist or
784 * MSIE detection support, or if tinygif = 1, or the
785 * URL isn't recognized as an imageurl, a lame HTML
786 * explanation is sent instead.
788 * - Added new feature, which permits blocking remote
789 * script redirects and firing back a local redirect
791 * The feature is conditionally compiled, i.e. it
792 * can be disabled with --disable-fast-redirects,
793 * plus it must be activated by a "fast-redirects"
794 * line in the config file, has its own log level
795 * and of course wants to be displayed by show-proxy-args
796 * Note: Boy, all the #ifdefs in 1001 locations and
797 * all the fumbling with configure.in and acconfig.h
798 * were *way* more work than the feature itself :-(
800 * - Because a generic redirect template was needed for
801 * this, tinygif = 3 now uses the same.
803 * - Moved GIFs, and other static HTTP response templates
808 * - Removed some >400 CRs again (Jon, you really worked
811 * Revision 1.3 2001/05/20 01:21:20 jongfoster
812 * Version 2.9.4 checkin.
813 * - Merged popupfile and cookiefile, and added control over PCRS
814 * filtering, in new "permissionsfile".
815 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
816 * file error you now get a message box (in the Win32 GUI) rather
817 * than the program exiting with no explanation.
818 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
820 * - Removed tabs from "config"
821 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
822 * - Bumped up version number.
824 * Revision 1.2 2001/05/17 23:02:36 oes
825 * - Made referrer option accept 'L' as a substitute for '§'
827 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
828 * Initial import of version 2.9.3 source tree
831 *********************************************************************/
838 #include <sys/types.h>
848 * Convince GNU's libc to provide a strptime prototype.
851 #endif /*__GLIBC__ */
858 #if !defined(_WIN32) && !defined(__OS2__)
864 #ifdef FEATURE_PTHREAD
866 /* jcc.h is for mutex semapores only */
867 #endif /* def FEATURE_PTHREAD */
872 #include "jbsockets.h"
873 #include "miscutil.h"
878 #ifndef HAVE_STRPTIME
879 #include "strptime.h"
882 const char parsers_h_rcs[] = PARSERS_H_VERSION;
884 /* Fix a problem with Solaris. There should be no effect on other
886 * Solaris's isspace() is a macro which uses its argument directly
887 * as an array index. Therefore we need to make sure that high-bit
888 * characters generate +ve values, and ideally we also want to make
889 * the argument match the declared parameter type of "int".
891 * Why did they write a character function that can't take a simple
892 * "char" argument? Doh!
894 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
895 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
897 static char *get_header_line(struct iob *iob);
898 static jb_err scan_headers(struct client_state *csp);
899 static jb_err header_tagger(struct client_state *csp, char *header);
900 static jb_err parse_header_time(const char *header_time, time_t *result);
902 static jb_err crumble (struct client_state *csp, char **header);
903 static jb_err connection (struct client_state *csp, char **header);
904 static jb_err filter_header (struct client_state *csp, char **header);
905 static jb_err client_referrer (struct client_state *csp, char **header);
906 static jb_err client_uagent (struct client_state *csp, char **header);
907 static jb_err client_ua (struct client_state *csp, char **header);
908 static jb_err client_from (struct client_state *csp, char **header);
909 static jb_err client_send_cookie (struct client_state *csp, char **header);
910 static jb_err client_x_forwarded (struct client_state *csp, char **header);
911 static jb_err client_accept_encoding (struct client_state *csp, char **header);
912 static jb_err client_te (struct client_state *csp, char **header);
913 static jb_err client_max_forwards (struct client_state *csp, char **header);
914 static jb_err client_host (struct client_state *csp, char **header);
915 static jb_err client_if_modified_since (struct client_state *csp, char **header);
916 static jb_err client_accept_language (struct client_state *csp, char **header);
917 static jb_err client_if_none_match (struct client_state *csp, char **header);
918 static jb_err crunch_client_header (struct client_state *csp, char **header);
919 static jb_err client_x_filter (struct client_state *csp, char **header);
920 static jb_err client_range (struct client_state *csp, char **header);
921 static jb_err server_set_cookie (struct client_state *csp, char **header);
922 static jb_err server_content_type (struct client_state *csp, char **header);
923 static jb_err server_content_length (struct client_state *csp, char **header);
924 static jb_err server_content_md5 (struct client_state *csp, char **header);
925 static jb_err server_content_encoding (struct client_state *csp, char **header);
926 static jb_err server_transfer_coding (struct client_state *csp, char **header);
927 static jb_err server_http (struct client_state *csp, char **header);
928 static jb_err crunch_server_header (struct client_state *csp, char **header);
929 static jb_err server_last_modified (struct client_state *csp, char **header);
930 static jb_err server_content_disposition(struct client_state *csp, char **header);
932 static jb_err client_host_adder (struct client_state *csp);
933 static jb_err client_xtra_adder (struct client_state *csp);
934 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
935 static jb_err connection_close_adder (struct client_state *csp);
937 static jb_err create_forged_referrer(char **header, const char *hostport);
938 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
939 static jb_err handle_conditional_hide_referrer_parameter(char **header,
940 const char *host, const int parameter_conditional_block);
943 * List of functions to run on a list of headers.
947 /** The header prefix to match */
950 /** The length of the prefix to match */
953 /** The function to apply to this line */
954 const parser_func_ptr parser;
957 static const struct parsers client_patterns[] = {
958 { "referer:", 8, client_referrer },
959 { "user-agent:", 11, client_uagent },
960 { "ua-", 3, client_ua },
961 { "from:", 5, client_from },
962 { "cookie:", 7, client_send_cookie },
963 { "x-forwarded-for:", 16, client_x_forwarded },
964 { "Accept-Encoding:", 16, client_accept_encoding },
965 { "TE:", 3, client_te },
966 { "Host:", 5, client_host },
967 { "if-modified-since:", 18, client_if_modified_since },
968 { "Keep-Alive:", 11, crumble },
969 { "connection:", 11, connection },
970 { "proxy-connection:", 17, crumble },
971 { "max-forwards:", 13, client_max_forwards },
972 { "Accept-Language:", 16, client_accept_language },
973 { "if-none-match:", 14, client_if_none_match },
974 { "Range:", 6, client_range },
975 { "Request-Range:", 14, client_range },
976 { "If-Range:", 9, client_range },
977 { "X-Filter:", 9, client_x_filter },
978 { "*", 0, crunch_client_header },
979 { "*", 0, filter_header },
983 static const struct parsers server_patterns[] = {
984 { "HTTP/", 5, server_http },
985 { "set-cookie:", 11, server_set_cookie },
986 { "connection:", 11, connection },
987 { "Content-Type:", 13, server_content_type },
988 { "Content-MD5:", 12, server_content_md5 },
989 { "Content-Encoding:", 17, server_content_encoding },
990 { "Transfer-Encoding:", 18, server_transfer_coding },
991 { "Keep-Alive:", 11, crumble },
992 { "content-disposition:", 20, server_content_disposition },
993 { "Last-Modified:", 14, server_last_modified },
994 { "*", 0, crunch_server_header },
995 { "*", 0, filter_header },
999 static const add_header_func_ptr add_client_headers[] = {
1001 client_x_forwarded_for_adder,
1003 /* Temporarily disabled: client_accept_encoding_adder, */
1004 connection_close_adder,
1008 static const add_header_func_ptr add_server_headers[] = {
1009 connection_close_adder,
1013 /*********************************************************************
1015 * Function : flush_socket
1017 * Description : Write any pending "buffered" content.
1020 * 1 : fd = file descriptor of the socket to read
1021 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1023 * Returns : On success, the number of bytes written are returned (zero
1024 * indicates nothing was written). On error, -1 is returned,
1025 * and errno is set appropriately. If count is zero and the
1026 * file descriptor refers to a regular file, 0 will be
1027 * returned without causing any other effect. For a special
1028 * file, the results are not portable.
1030 *********************************************************************/
1031 int flush_socket(jb_socket fd, struct iob *iob)
1033 int len = iob->eod - iob->cur;
1040 if (write_socket(fd, iob->cur, (size_t)len))
1044 iob->eod = iob->cur = iob->buf;
1050 /*********************************************************************
1052 * Function : add_to_iob
1054 * Description : Add content to the buffered page, expanding the
1055 * buffer if necessary.
1058 * 1 : csp = Current client state (buffers, headers, etc...)
1059 * 2 : buf = holds the content to be added to the page
1060 * 3 : n = number of bytes to be added
1062 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1063 * or buffer limit reached.
1065 *********************************************************************/
1066 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1068 struct iob *iob = csp->iob;
1069 size_t used, offset, need, want;
1072 if (n <= 0) return JB_ERR_OK;
1074 used = (size_t)(iob->eod - iob->buf);
1075 offset = (size_t)(iob->cur - iob->buf);
1076 need = used + (size_t)n + 1;
1079 * If the buffer can't hold the new data, extend it first.
1080 * Use the next power of two if possible, else use the actual need.
1082 if (need > csp->config->buffer_limit)
1084 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1085 return JB_ERR_MEMORY;
1088 if (need > iob->size)
1090 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1092 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1096 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1102 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1103 return JB_ERR_MEMORY;
1106 /* Update the iob pointers */
1107 iob->cur = p + offset;
1108 iob->eod = p + used;
1112 /* copy the new data into the iob buffer */
1113 memcpy(iob->eod, buf, (size_t)n);
1115 /* point to the end of the data */
1118 /* null terminate == cheap insurance */
1127 /*********************************************************************
1129 * Function : decompress_iob
1131 * Description : Decompress buffered page, expanding the
1132 * buffer as necessary. csp->iob->cur
1133 * should point to the the beginning of the
1134 * compressed data block.
1137 * 1 : csp = Current client state (buffers, headers, etc...)
1139 * Returns : JB_ERR_OK on success,
1140 * JB_ERR_MEMORY if out-of-memory limit reached, and
1141 * JB_ERR_COMPRESS if error decompressing buffer.
1143 *********************************************************************/
1144 jb_err decompress_iob(struct client_state *csp)
1146 char *buf; /* new, uncompressed buffer */
1147 char *cur; /* Current iob position (to keep the original
1148 * iob->cur unmodified if we return early) */
1149 size_t bufsize; /* allocated size of the new buffer */
1150 size_t old_size; /* Content size before decompression */
1151 size_t skip_size; /* Number of bytes at the beginning of the iob
1152 that we should NOT decompress. */
1153 int status; /* return status of the inflate() call */
1154 z_stream zstr; /* used by calls to zlib */
1156 assert(csp->iob->cur - csp->iob->buf > 0);
1157 assert(csp->iob->eod - csp->iob->cur > 0);
1159 bufsize = csp->iob->size;
1160 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1161 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1163 cur = csp->iob->cur;
1168 * This is to protect the parsing of gzipped data,
1169 * but it should(?) be valid for deflated data also.
1171 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1172 return JB_ERR_COMPRESS;
1175 if (csp->content_type & CT_GZIP)
1178 * Our task is slightly complicated by the facts that data
1179 * compressed by gzip does not include a zlib header, and
1180 * that there is no easily accessible interface in zlib to
1181 * handle a gzip header. We strip off the gzip header by
1182 * hand, and later inform zlib not to expect a header.
1186 * Strip off the gzip header. Please see RFC 1952 for more
1187 * explanation of the appropriate fields.
1189 if ((*cur++ != (char)0x1f)
1190 || (*cur++ != (char)0x8b)
1191 || (*cur++ != Z_DEFLATED))
1193 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1194 return JB_ERR_COMPRESS;
1200 * XXX: These magic numbers should be replaced
1201 * with macros to give a better idea what they do.
1205 /* The gzip header has reserved bits set; bail out. */
1206 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1207 return JB_ERR_COMPRESS;
1211 /* Skip extra fields if necessary. */
1215 * Skip a given number of bytes, specified
1216 * as a 16-bit little-endian value.
1219 * XXX: This code used to be:
1221 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1223 * which I had to change into:
1225 * cur += *cur++ + (*cur++ << 8);
1227 * at which point gcc43 finally noticed that the value
1228 * of cur is undefined (it depends on which of the
1229 * summands is evaluated first).
1231 * I haven't come across a site where this
1232 * code is actually executed yet, but I hope
1236 skip_bytes = *cur++;
1237 skip_bytes = *cur++ << 8;
1239 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1242 * The number of bytes to skip should be positive
1243 * and we'd like to stay in the buffer.
1245 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1247 log_error(LOG_LEVEL_ERROR,
1248 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1250 return JB_ERR_COMPRESS;
1252 log_error(LOG_LEVEL_INFO,
1253 "Skipping %d bytes for gzip compression. Does this sound right?",
1258 /* Skip the filename if necessary. */
1261 /* A null-terminated string is supposed to follow. */
1262 while (*cur++ && (cur < csp->iob->eod));
1266 /* Skip the comment if necessary. */
1269 /* A null-terminated string is supposed to follow. */
1270 while (*cur++ && (cur < csp->iob->eod));
1273 /* Skip the CRC if necessary. */
1279 if (cur >= csp->iob->eod)
1282 * If the current position pointer reached or passed
1283 * the buffer end, we were obviously tricked to skip
1286 log_error(LOG_LEVEL_ERROR,
1287 "Malformed gzip header detected. Aborting decompression.");
1288 return JB_ERR_COMPRESS;
1292 else if (csp->content_type & CT_DEFLATE)
1295 * XXX: The debug level should be lowered
1296 * before the next stable release.
1298 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1300 * In theory (that is, according to RFC 1950), deflate-compressed
1301 * data should begin with a two-byte zlib header and have an
1302 * adler32 checksum at the end. It seems that in practice only
1303 * the raw compressed data is sent. Note that this means that
1304 * we are not RFC 1950-compliant here, but the advantage is that
1305 * this actually works. :)
1307 * We add a dummy null byte to tell zlib where the data ends,
1308 * and later inform it not to expect a header.
1310 * Fortunately, add_to_iob() has thoughtfully null-terminated
1311 * the buffer; we can just increment the end pointer to include
1318 log_error(LOG_LEVEL_ERROR,
1319 "Unable to determine compression format for decompression");
1320 return JB_ERR_COMPRESS;
1323 /* Set up the fields required by zlib. */
1324 zstr.next_in = (Bytef *)cur;
1325 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1326 zstr.zalloc = Z_NULL;
1327 zstr.zfree = Z_NULL;
1328 zstr.opaque = Z_NULL;
1331 * Passing -MAX_WBITS to inflateInit2 tells the library
1332 * that there is no zlib header.
1334 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1336 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1337 return JB_ERR_COMPRESS;
1341 * Next, we allocate new storage for the inflated data.
1342 * We don't modify the existing iob yet, so in case there
1343 * is error in decompression we can recover gracefully.
1345 buf = zalloc(bufsize);
1348 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1349 return JB_ERR_MEMORY;
1352 assert(bufsize >= skip_size);
1353 memcpy(buf, csp->iob->buf, skip_size);
1354 zstr.avail_out = bufsize - skip_size;
1355 zstr.next_out = (Bytef *)buf + skip_size;
1357 /* Try to decompress the whole stream in one shot. */
1358 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1360 /* We need to allocate more memory for the output buffer. */
1362 char *tmpbuf; /* used for realloc'ing the buffer */
1363 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1366 * If zlib wants more data then there's a problem, because
1367 * the complete compressed file should have been buffered.
1369 if (0 == zstr.avail_in)
1371 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1372 return JB_ERR_COMPRESS;
1376 * If we tried the limit and still didn't have enough
1377 * memory, just give up.
1379 if (bufsize == csp->config->buffer_limit)
1381 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1382 return JB_ERR_MEMORY;
1385 /* Try doubling the buffer size each time. */
1388 /* Don't exceed the buffer limit. */
1389 if (bufsize > csp->config->buffer_limit)
1391 bufsize = csp->config->buffer_limit;
1394 /* Try to allocate the new buffer. */
1395 tmpbuf = realloc(buf, bufsize);
1398 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1400 return JB_ERR_MEMORY;
1404 char *oldnext_out = (char *)zstr.next_out;
1407 * Update the fields for inflate() to use the new
1408 * buffer, which may be in a location different from
1411 zstr.avail_out += bufsize - oldbufsize;
1412 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1415 * Compare with an uglier method of calculating these values
1416 * that doesn't require the extra oldbufsize variable.
1418 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1419 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1420 assert(zstr.avail_out > 0);
1426 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1428 log_error(LOG_LEVEL_ERROR,
1429 "Inconsistent stream state after decompression: %s", zstr.msg);
1431 * XXX: Intentionally no return.
1433 * According to zlib.h, Z_STREAM_ERROR is returned
1434 * "if the stream state was inconsistent".
1436 * I assume in this case inflate()'s status
1437 * would also be something different than Z_STREAM_END
1438 * so this check should be redundant, but lets see.
1442 if (status != Z_STREAM_END)
1444 /* We failed to decompress the stream. */
1445 log_error(LOG_LEVEL_ERROR,
1446 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1447 return JB_ERR_COMPRESS;
1451 * Finally, we can actually update the iob, since the
1452 * decompression was successful. First, free the old
1455 freez(csp->iob->buf);
1457 /* Now, update the iob to use the new buffer. */
1458 csp->iob->buf = buf;
1459 csp->iob->cur = csp->iob->buf + skip_size;
1460 csp->iob->eod = (char *)zstr.next_out;
1461 csp->iob->size = bufsize;
1464 * Make sure the new uncompressed iob obeys some minimal
1465 * consistency conditions.
1467 if ((csp->iob->buf < csp->iob->cur)
1468 && (csp->iob->cur <= csp->iob->eod)
1469 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1471 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1474 log_error(LOG_LEVEL_RE_FILTER,
1475 "Decompression successful. Old size: %d, new size: %d.",
1476 old_size, new_size);
1480 /* zlib thinks this is OK, so lets do the same. */
1481 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1486 /* It seems that zlib did something weird. */
1487 log_error(LOG_LEVEL_ERROR,
1488 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1489 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1490 csp->iob->eod, csp->iob->buf + csp->iob->size);
1491 return JB_ERR_COMPRESS;
1497 #endif /* defined(FEATURE_ZLIB) */
1500 /*********************************************************************
1502 * Function : string_move
1504 * Description : memmove wrapper to move the last part of a string
1505 * towards the beginning, overwriting the part in
1506 * the middle. strlcpy() can't be used here as the
1510 * 1 : dst = Destination to overwrite
1511 * 2 : src = Source to move.
1515 *********************************************************************/
1516 static void string_move(char *dst, char *src)
1520 /* +1 to copy the terminating nul as well. */
1521 memmove(dst, src, strlen(src)+1);
1525 /*********************************************************************
1527 * Function : normalize_lws
1529 * Description : Reduces unquoted linear white space in headers
1530 * to a single space in accordance with RFC 2616 2.2.
1531 * This simplifies parsing and filtering later on.
1533 * XXX: Remove log messages before
1534 * the next stable release?
1537 * 1 : header = A header with linear white space to reduce.
1541 *********************************************************************/
1542 static void normalize_lws(char *header)
1548 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1552 while (ijb_isspace(*q))
1556 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1557 string_move(p+1, q);
1562 log_error(LOG_LEVEL_HEADER,
1563 "Converting tab to space in '%s'", header);
1568 char *end_of_token = strstr(p+1, "\"");
1570 if (NULL != end_of_token)
1572 /* Don't mess with quoted text. */
1577 log_error(LOG_LEVEL_HEADER,
1578 "Ignoring single quote in '%s'", header);
1584 p = strchr(header, ':');
1585 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1588 * There's still space before the colon.
1591 string_move(p-1, p);
1596 /*********************************************************************
1598 * Function : get_header
1600 * Description : This (odd) routine will parse the csp->iob
1601 * to get the next complete header.
1604 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1606 * Returns : Any one of the following:
1608 * 1) a pointer to a dynamically allocated string that contains a header line
1609 * 2) NULL indicating that the end of the header was reached
1610 * 3) "" indicating that the end of the iob was reached before finding
1611 * a complete header line.
1613 *********************************************************************/
1614 char *get_header(struct iob *iob)
1618 header = get_header_line(iob);
1620 if ((header == NULL) || (*header == '\0'))
1623 * No complete header read yet, tell the client.
1628 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1631 * Header spans multiple lines, append the next one.
1633 char *continued_header;
1635 continued_header = get_header_line(iob);
1636 if ((continued_header == NULL) || (*continued_header == '\0'))
1639 * No complete header read yet, return what we got.
1640 * XXX: Should "unread" header instead.
1642 log_error(LOG_LEVEL_INFO,
1643 "Failed to read a multi-line header properly: '%s'",
1648 if (JB_ERR_OK != string_join(&header, continued_header))
1650 log_error(LOG_LEVEL_FATAL,
1651 "Out of memory while appending multiple headers.");
1655 /* XXX: remove before next stable release. */
1656 log_error(LOG_LEVEL_HEADER,
1657 "Merged multiple header lines to: '%s'",
1662 normalize_lws(header);
1669 /*********************************************************************
1671 * Function : get_header_line
1673 * Description : This (odd) routine will parse the csp->iob
1674 * to get the next header line.
1677 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1679 * Returns : Any one of the following:
1681 * 1) a pointer to a dynamically allocated string that contains a header line
1682 * 2) NULL indicating that the end of the header was reached
1683 * 3) "" indicating that the end of the iob was reached before finding
1684 * a complete header line.
1686 *********************************************************************/
1687 static char *get_header_line(struct iob *iob)
1691 if ((iob->cur == NULL)
1692 || ((p = strchr(iob->cur, '\n')) == NULL))
1694 return(""); /* couldn't find a complete header */
1699 ret = strdup(iob->cur);
1702 /* FIXME No way to handle error properly */
1703 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1708 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1710 /* is this a blank line (i.e. the end of the header) ? */
1722 /*********************************************************************
1724 * Function : get_header_value
1726 * Description : Get the value of a given header from a chained list
1727 * of header lines or return NULL if no such header is
1728 * present in the list.
1731 * 1 : header_list = pointer to list
1732 * 2 : header_name = string with name of header to look for.
1733 * Trailing colon required, capitalization
1736 * Returns : NULL if not found, else value of header
1738 *********************************************************************/
1739 char *get_header_value(const struct list *header_list, const char *header_name)
1741 struct list_entry *cur_entry;
1745 assert(header_list);
1746 assert(header_name);
1747 length = strlen(header_name);
1749 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1753 if (!strncmpic(cur_entry->str, header_name, length))
1756 * Found: return pointer to start of value
1758 ret = cur_entry->str + length;
1759 while (*ret && ijb_isspace(*ret)) ret++;
1773 /*********************************************************************
1775 * Function : scan_headers
1777 * Description : Scans headers, applies tags and updates action bits.
1780 * 1 : csp = Current client state (buffers, headers, etc...)
1782 * Returns : JB_ERR_OK
1784 *********************************************************************/
1785 static jb_err scan_headers(struct client_state *csp)
1787 struct list_entry *h; /* Header */
1788 jb_err err = JB_ERR_OK;
1790 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1792 /* Header crunch()ed in previous run? -> ignore */
1793 if (h->str == NULL) continue;
1794 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1795 err = header_tagger(csp, h->str);
1802 /*********************************************************************
1806 * Description : add, delete or modify lines in the HTTP header streams.
1807 * On entry, it receives a linked list of headers space
1808 * that was allocated dynamically (both the list nodes
1809 * and the header contents).
1811 * As a side effect it frees the space used by the original
1815 * 1 : csp = Current client state (buffers, headers, etc...)
1816 * 2 : filter_server_headers = Boolean to switch between
1817 * server and header filtering.
1819 * Returns : JB_ERR_OK in case off success, or
1820 * JB_ERR_MEMORY on out-of-memory error.
1822 *********************************************************************/
1823 jb_err sed(struct client_state *csp, int filter_server_headers)
1825 /* XXX: use more descriptive names. */
1826 struct list_entry *p;
1827 const struct parsers *v;
1828 const add_header_func_ptr *f;
1829 jb_err err = JB_ERR_OK;
1831 if (filter_server_headers)
1833 v = server_patterns;
1834 f = add_server_headers;
1838 v = client_patterns;
1839 f = add_client_headers;
1844 while ((err == JB_ERR_OK) && (v->str != NULL))
1846 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1848 /* Header crunch()ed in previous run? -> ignore */
1849 if (p->str == NULL) continue;
1851 /* Does the current parser handle this header? */
1852 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1853 (v->len == CHECK_EVERY_HEADER_REMAINING))
1855 err = v->parser(csp, &(p->str));
1861 /* place additional headers on the csp->headers list */
1862 while ((err == JB_ERR_OK) && (*f))
1872 /*********************************************************************
1874 * Function : update_server_headers
1876 * Description : Updates server headers after the body has been modified.
1879 * 1 : csp = Current client state (buffers, headers, etc...)
1881 * Returns : JB_ERR_OK in case off success, or
1882 * JB_ERR_MEMORY on out-of-memory error.
1884 *********************************************************************/
1885 jb_err update_server_headers(struct client_state *csp)
1887 jb_err err = JB_ERR_OK;
1889 static const struct parsers server_patterns_light[] = {
1890 { "Content-Length:", 15, server_content_length },
1891 { "Transfer-Encoding:", 18, server_transfer_coding },
1893 { "Content-Encoding:", 17, server_content_encoding },
1894 #endif /* def FEATURE_ZLIB */
1898 if (strncmpic(csp->http->cmd, "HEAD", 4))
1900 const struct parsers *v;
1901 struct list_entry *p;
1903 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1905 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1907 /* Header crunch()ed in previous run? -> ignore */
1908 if (p->str == NULL) continue;
1910 /* Does the current parser handle this header? */
1911 if (strncmpic(p->str, v->str, v->len) == 0)
1913 err = v->parser(csp, (char **)&(p->str));
1923 /*********************************************************************
1925 * Function : header_tagger
1927 * Description : Executes all text substitutions from applying
1928 * tag actions and saves the result as tag.
1930 * XXX: Shares enough code with filter_header() and
1931 * pcrs_filter_response() to warrant some helper functions.
1934 * 1 : csp = Current client state (buffers, headers, etc...)
1935 * 2 : header = Header that is used as tagger input
1937 * Returns : JB_ERR_OK on success and always succeeds
1939 *********************************************************************/
1940 static jb_err header_tagger(struct client_state *csp, char *header)
1942 int wanted_filter_type;
1943 int multi_action_index;
1947 struct file_list *fl;
1948 struct re_filterfile_spec *b;
1949 struct list_entry *tag_name;
1951 int found_filters = 0;
1952 const size_t header_length = strlen(header);
1954 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1956 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1957 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1961 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1962 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1965 /* Check if there are any filters */
1966 for (i = 0; i < MAX_AF_FILES; i++)
1979 if (0 == found_filters)
1981 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1982 "tagging enabled, but no taggers available.");
1986 for (i = 0; i < MAX_AF_FILES; i++)
1989 if ((NULL == fl) || (NULL == fl->f))
1992 * Either there are no filter files
1993 * left, or this filter file just
1994 * contains no valid filters.
1996 * Continue to be sure we don't miss
1997 * valid filter files that are chained
1998 * after empty or invalid ones.
2003 /* For all filters, */
2004 for (b = fl->f; b; b = b->next)
2006 if (b->type != wanted_filter_type)
2008 /* skip the ones we don't care about, */
2011 /* leaving only taggers that could apply, of which we use the ones, */
2012 for (tag_name = csp->action->multi[multi_action_index]->first;
2013 NULL != tag_name; tag_name = tag_name->next)
2015 /* that do apply, and */
2016 if (strcmp(b->name, tag_name->str) == 0)
2018 char *modified_tag = NULL;
2020 size_t size = header_length;
2021 pcrs_job *joblist = b->joblist;
2023 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2025 if (NULL == joblist)
2027 log_error(LOG_LEVEL_RE_FILTER,
2028 "Tagger %s has empty joblist. Nothing to do.", b->name);
2032 /* execute their pcrs_joblist on the header. */
2033 for (job = joblist; NULL != job; job = job->next)
2035 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2039 /* Success, continue with the modified version. */
2048 /* Tagger doesn't match */
2051 /* Regex failure, log it but continue anyway. */
2052 log_error(LOG_LEVEL_ERROR,
2053 "Problems with tagger \'%s\' and header \'%s\': %s",
2054 b->name, *header, pcrs_strerror(hits));
2056 freez(modified_tag);
2060 if (b->dynamic) pcrs_free_joblist(joblist);
2062 /* If this tagger matched */
2068 * There is to technical limitation which makes
2069 * it impossible to use empty tags, but I assume
2070 * no one would do it intentionally.
2073 log_error(LOG_LEVEL_INFO,
2074 "Tagger \'%s\' created an empty tag. Ignored.",
2079 if (!list_contains_item(csp->tags, tag))
2081 if (JB_ERR_OK != enlist(csp->tags, tag))
2083 log_error(LOG_LEVEL_ERROR,
2084 "Insufficient memory to add tag \'%s\', "
2085 "based on tagger \'%s\' and header \'%s\'",
2086 tag, b->name, *header);
2090 char *action_message;
2092 * update the action bits right away, to make
2093 * tagging based on tags set by earlier taggers
2094 * of the same kind possible.
2096 if (update_action_bits_for_tag(csp, tag))
2098 action_message = "Action bits updated accordingly.";
2102 action_message = "No action bits update necessary.";
2105 log_error(LOG_LEVEL_HEADER,
2106 "Tagger \'%s\' added tag \'%s\'. %s",
2107 b->name, tag, action_message);
2112 /* XXX: Is this log-worthy? */
2113 log_error(LOG_LEVEL_HEADER,
2114 "Tagger \'%s\' didn't add tag \'%s\'. "
2115 "Tag already present", b->name, tag);
2118 } /* if the tagger matched */
2119 } /* if the tagger applies */
2120 } /* for every tagger that could apply */
2121 } /* for all filters */
2122 } /* for all filter files */
2127 /* here begins the family of parser functions that reformat header lines */
2129 /*********************************************************************
2131 * Function : filter_header
2133 * Description : Executes all text substitutions from all applying
2134 * +(server|client)-header-filter actions on the header.
2135 * Most of the code was copied from pcrs_filter_response,
2136 * including the rather short variable names
2139 * 1 : csp = Current client state (buffers, headers, etc...)
2140 * 2 : header = On input, pointer to header to modify.
2141 * On output, pointer to the modified header, or NULL
2142 * to remove the header. This function frees the
2143 * original string if necessary.
2145 * Returns : JB_ERR_OK on success and always succeeds
2147 *********************************************************************/
2148 static jb_err filter_header(struct client_state *csp, char **header)
2152 size_t size = strlen(*header);
2154 char *newheader = NULL;
2157 struct file_list *fl;
2158 struct re_filterfile_spec *b;
2159 struct list_entry *filtername;
2161 int i, found_filters = 0;
2162 int wanted_filter_type;
2163 int multi_action_index;
2165 if (csp->flags & CSP_FLAG_NO_FILTERING)
2170 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2172 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2173 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2177 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2178 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2182 * Need to check the set of re_filterfiles...
2184 for (i = 0; i < MAX_AF_FILES; i++)
2197 if (0 == found_filters)
2199 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2200 "header filtering enabled, but no matching filters available.");
2204 for (i = 0; i < MAX_AF_FILES; i++)
2207 if ((NULL == fl) || (NULL == fl->f))
2210 * Either there are no filter files
2211 * left, or this filter file just
2212 * contains no valid filters.
2214 * Continue to be sure we don't miss
2215 * valid filter files that are chained
2216 * after empty or invalid ones.
2221 * For all applying +filter actions, look if a filter by that
2222 * name exists and if yes, execute its pcrs_joblist on the
2225 for (b = fl->f; b; b = b->next)
2227 if (b->type != wanted_filter_type)
2229 /* Skip other filter types */
2233 for (filtername = csp->action->multi[multi_action_index]->first;
2234 filtername ; filtername = filtername->next)
2236 if (strcmp(b->name, filtername->str) == 0)
2238 int current_hits = 0;
2239 pcrs_job *joblist = b->joblist;
2241 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2243 if (NULL == joblist)
2245 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2249 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2250 *header, size, b->name);
2252 /* Apply all jobs from the joblist */
2253 for (job = joblist; NULL != job; job = job->next)
2255 matches = pcrs_execute(job, *header, size, &newheader, &size);
2258 current_hits += matches;
2259 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2261 *header = newheader;
2263 else if ( 0 == matches )
2265 /* Filter doesn't change header */
2271 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2272 *header, b->name, pcrs_strerror(matches));
2273 if (newheader != NULL)
2275 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2281 if (b->dynamic) pcrs_free_joblist(joblist);
2283 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2284 hits += current_hits;
2291 * Additionally checking for hits is important because if
2292 * the continue hack is triggered, server headers can
2293 * arrive empty to separate multiple heads from each other.
2295 if ((0 == size) && hits)
2297 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2305 /*********************************************************************
2307 * Function : connection
2309 * Description : Makes sure that the value of the Connection: header
2310 * is "close" and signals connection_close_adder
2314 * 1 : csp = Current client state (buffers, headers, etc...)
2315 * 2 : header = On input, pointer to header to modify.
2316 * On output, pointer to the modified header, or NULL
2317 * to remove the header. This function frees the
2318 * original string if necessary.
2320 * Returns : JB_ERR_OK on success, or
2321 * JB_ERR_MEMORY on out-of-memory error.
2323 *********************************************************************/
2324 static jb_err connection(struct client_state *csp, char **header)
2326 char *old_header = *header;
2328 /* Do we have a 'Connection: close' header? */
2329 if (strcmpic(*header, "Connection: close"))
2331 /* No, create one */
2332 *header = strdup("Connection: close");
2335 return JB_ERR_MEMORY;
2337 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2341 /* Signal connection_close_adder() to return early. */
2342 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2344 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2348 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2355 /*********************************************************************
2357 * Function : crumble
2359 * Description : This is called if a header matches a pattern to "crunch"
2362 * 1 : csp = Current client state (buffers, headers, etc...)
2363 * 2 : header = On input, pointer to header to modify.
2364 * On output, pointer to the modified header, or NULL
2365 * to remove the header. This function frees the
2366 * original string if necessary.
2368 * Returns : JB_ERR_OK on success, or
2369 * JB_ERR_MEMORY on out-of-memory error.
2371 *********************************************************************/
2372 static jb_err crumble(struct client_state *csp, char **header)
2374 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2380 /*********************************************************************
2382 * Function : crunch_server_header
2384 * Description : Crunch server header if it matches a string supplied by the
2385 * user. Called from `sed'.
2388 * 1 : csp = Current client state (buffers, headers, etc...)
2389 * 2 : header = On input, pointer to header to modify.
2390 * On output, pointer to the modified header, or NULL
2391 * to remove the header. This function frees the
2392 * original string if necessary.
2394 * Returns : JB_ERR_OK on success and always succeeds
2396 *********************************************************************/
2397 static jb_err crunch_server_header(struct client_state *csp, char **header)
2399 const char *crunch_pattern;
2401 /* Do we feel like crunching? */
2402 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2404 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2406 /* Is the current header the lucky one? */
2407 if (strstr(*header, crunch_pattern))
2409 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2418 /*********************************************************************
2420 * Function : server_content_type
2422 * Description : Set the content-type for filterable types (text/.*,
2423 * .*xml.*, javascript and image/gif) unless filtering has been
2424 * forbidden (CT_TABOO) while parsing earlier headers.
2425 * NOTE: Since text/plain is commonly used by web servers
2426 * for files whose correct type is unknown, we don't
2427 * set CT_TEXT for it.
2430 * 1 : csp = Current client state (buffers, headers, etc...)
2431 * 2 : header = On input, pointer to header to modify.
2432 * On output, pointer to the modified header, or NULL
2433 * to remove the header. This function frees the
2434 * original string if necessary.
2436 * Returns : JB_ERR_OK on success, or
2437 * JB_ERR_MEMORY on out-of-memory error.
2439 *********************************************************************/
2440 static jb_err server_content_type(struct client_state *csp, char **header)
2442 /* Remove header if it isn't the first Content-Type header */
2443 if ((csp->content_type & CT_DECLARED))
2446 * Another, slightly slower, way to see if
2447 * we already parsed another Content-Type header.
2449 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2451 log_error(LOG_LEVEL_ERROR,
2452 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2460 * Signal that the Content-Type has been set.
2462 csp->content_type |= CT_DECLARED;
2464 if (!(csp->content_type & CT_TABOO))
2467 * XXX: The assumption that text/plain is a sign of
2468 * binary data seems to be somewhat unreasonable nowadays
2469 * and should be dropped after 3.0.8 is out.
2471 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2472 || strstr(*header, "xml")
2473 || strstr(*header, "application/x-javascript"))
2475 csp->content_type |= CT_TEXT;
2477 else if (strstr(*header, "image/gif"))
2479 csp->content_type |= CT_GIF;
2484 * Are we messing with the content type?
2486 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2489 * Make sure the user doesn't accidently
2490 * change the content type of binary documents.
2492 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2495 *header = strdup("Content-Type: ");
2496 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2500 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2501 return JB_ERR_MEMORY;
2503 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2507 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2508 "It doesn't look like a content type that should be filtered. "
2509 "Enable force-text-mode if you know what you're doing.", *header);
2517 /*********************************************************************
2519 * Function : server_transfer_coding
2521 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2522 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2523 * - Remove header if body was chunked but has been
2524 * de-chunked for filtering.
2527 * 1 : csp = Current client state (buffers, headers, etc...)
2528 * 2 : header = On input, pointer to header to modify.
2529 * On output, pointer to the modified header, or NULL
2530 * to remove the header. This function frees the
2531 * original string if necessary.
2533 * Returns : JB_ERR_OK on success, or
2534 * JB_ERR_MEMORY on out-of-memory error.
2536 *********************************************************************/
2537 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2540 * Turn off pcrs and gif filtering if body compressed
2542 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2546 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2548 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2549 csp->http->cmd, *header);
2550 #endif /* def FEATURE_ZLIB */
2551 csp->content_type = CT_TABOO;
2555 * Raise flag if body chunked
2557 if (strstr(*header, "chunked"))
2559 csp->flags |= CSP_FLAG_CHUNKED;
2562 * If the body was modified, it has been de-chunked first
2563 * and the header must be removed.
2565 * FIXME: If there is more than one transfer encoding,
2566 * only the "chunked" part should be removed here.
2568 if (csp->flags & CSP_FLAG_MODIFIED)
2570 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2579 /*********************************************************************
2581 * Function : server_content_encoding
2583 * Description : This function is run twice for each request,
2584 * unless FEATURE_ZLIB and filtering are disabled.
2586 * The first run is used to check if the content
2587 * is compressed, if FEATURE_ZLIB is disabled
2588 * filtering is then disabled as well, if FEATURE_ZLIB
2589 * is enabled the content is marked for decompression.
2591 * The second run is used to remove the Content-Encoding
2592 * header if the decompression was successful.
2595 * 1 : csp = Current client state (buffers, headers, etc...)
2596 * 2 : header = On input, pointer to header to modify.
2597 * On output, pointer to the modified header, or NULL
2598 * to remove the header. This function frees the
2599 * original string if necessary.
2601 * Returns : JB_ERR_OK on success, or
2602 * JB_ERR_MEMORY on out-of-memory error.
2604 *********************************************************************/
2605 static jb_err server_content_encoding(struct client_state *csp, char **header)
2608 if ((csp->flags & CSP_FLAG_MODIFIED)
2609 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2612 * We successfully decompressed the content,
2613 * and have to clean the header now, so the
2614 * client no longer expects compressed data..
2616 * XXX: There is a difference between cleaning
2617 * and removing it completely.
2619 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2622 else if (strstr(*header, "gzip"))
2624 /* Mark for gzip decompression */
2625 csp->content_type |= CT_GZIP;
2627 else if (strstr(*header, "deflate"))
2629 /* Mark for zlib decompression */
2630 csp->content_type |= CT_DEFLATE;
2632 else if (strstr(*header, "compress"))
2635 * We can't decompress this; therefore we can't filter
2638 csp->content_type |= CT_TABOO;
2640 #else /* !defined(FEATURE_ZLIB) */
2641 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2644 * Body is compressed, turn off pcrs and gif filtering.
2646 csp->content_type |= CT_TABOO;
2649 * Log a warning if the user expects the content to be filtered.
2651 if ((csp->rlist != NULL) &&
2652 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2654 log_error(LOG_LEVEL_INFO,
2655 "Compressed content detected, content filtering disabled. "
2656 "Consider recompiling Privoxy with zlib support or "
2657 "enable the prevent-compression action.");
2660 #endif /* defined(FEATURE_ZLIB) */
2667 /*********************************************************************
2669 * Function : server_content_length
2671 * Description : Adjust Content-Length header if we modified
2675 * 1 : csp = Current client state (buffers, headers, etc...)
2676 * 2 : header = On input, pointer to header to modify.
2677 * On output, pointer to the modified header, or NULL
2678 * to remove the header. This function frees the
2679 * original string if necessary.
2681 * Returns : JB_ERR_OK on success, or
2682 * JB_ERR_MEMORY on out-of-memory error.
2684 *********************************************************************/
2685 static jb_err server_content_length(struct client_state *csp, char **header)
2687 const size_t max_header_length = 80;
2689 /* Regenerate header if the content was modified. */
2690 if (csp->flags & CSP_FLAG_MODIFIED)
2693 *header = (char *) zalloc(max_header_length);
2694 if (*header == NULL)
2696 return JB_ERR_MEMORY;
2699 snprintf(*header, max_header_length, "Content-Length: %d",
2700 (int)csp->content_length);
2701 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2702 (int)csp->content_length);
2709 /*********************************************************************
2711 * Function : server_content_md5
2713 * Description : Crumble any Content-MD5 headers if the document was
2714 * modified. FIXME: Should we re-compute instead?
2717 * 1 : csp = Current client state (buffers, headers, etc...)
2718 * 2 : header = On input, pointer to header to modify.
2719 * On output, pointer to the modified header, or NULL
2720 * to remove the header. This function frees the
2721 * original string if necessary.
2723 * Returns : JB_ERR_OK on success, or
2724 * JB_ERR_MEMORY on out-of-memory error.
2726 *********************************************************************/
2727 static jb_err server_content_md5(struct client_state *csp, char **header)
2729 if (csp->flags & CSP_FLAG_MODIFIED)
2731 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2739 /*********************************************************************
2741 * Function : server_content_disposition
2743 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2744 * Called from `sed'.
2747 * 1 : csp = Current client state (buffers, headers, etc...)
2748 * 2 : header = On input, pointer to header to modify.
2749 * On output, pointer to the modified header, or NULL
2750 * to remove the header. This function frees the
2751 * original string if necessary.
2753 * Returns : JB_ERR_OK on success, or
2754 * JB_ERR_MEMORY on out-of-memory error.
2756 *********************************************************************/
2757 static jb_err server_content_disposition(struct client_state *csp, char **header)
2762 * Are we messing with the Content-Disposition header?
2764 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2770 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2772 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2775 * Blocking content-disposition header
2777 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2784 * Replacing Content-Disposition header
2787 *header = strdup("Content-Disposition: ");
2788 string_append(header, newval);
2790 if (*header != NULL)
2792 log_error(LOG_LEVEL_HEADER,
2793 "Content-Disposition header crunched and replaced with: %s", *header);
2796 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2800 /*********************************************************************
2802 * Function : server_last_modified
2804 * Description : Changes Last-Modified header to the actual date
2805 * to help hide-if-modified-since.
2806 * Called from `sed'.
2809 * 1 : csp = Current client state (buffers, headers, etc...)
2810 * 2 : header = On input, pointer to header to modify.
2811 * On output, pointer to the modified header, or NULL
2812 * to remove the header. This function frees the
2813 * original string if necessary.
2815 * Returns : JB_ERR_OK on success, or
2816 * JB_ERR_MEMORY on out-of-memory error.
2818 *********************************************************************/
2819 static jb_err server_last_modified(struct client_state *csp, char **header)
2822 char buf[BUFFER_SIZE];
2825 #ifdef HAVE_GMTIME_R
2828 struct tm *timeptr = NULL;
2829 time_t now, last_modified;
2831 long int days, hours, minutes, seconds;
2834 * Are we messing with the Last-Modified header?
2836 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2842 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2844 if (0 == strcmpic(newval, "block") )
2847 * Blocking Last-Modified header. Useless but why not.
2849 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2853 else if (0 == strcmpic(newval, "reset-to-request-time"))
2856 * Setting Last-Modified Header to now.
2858 get_http_time(0, buf, sizeof(buf));
2860 *header = strdup("Last-Modified: ");
2861 string_append(header, buf);
2863 if (*header == NULL)
2865 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2869 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2872 else if (0 == strcmpic(newval, "randomize"))
2874 const char *header_time = *header + sizeof("Last-Modified:");
2876 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2878 #ifdef HAVE_GMTIME_R
2879 timeptr = gmtime_r(&now, &gmt);
2880 #elif FEATURE_PTHREAD
2881 privoxy_mutex_lock(&gmtime_mutex);
2882 timeptr = gmtime(&now);
2883 privoxy_mutex_unlock(&gmtime_mutex);
2885 timeptr = gmtime(&now);
2887 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2889 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2894 rtime = (long int)difftime(now, last_modified);
2903 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2905 rtime = pick_from_range(rtime);
2906 if (negative) rtime *= -1;
2907 last_modified += rtime;
2908 #ifdef HAVE_GMTIME_R
2909 timeptr = gmtime_r(&last_modified, &gmt);
2910 #elif FEATURE_PTHREAD
2911 privoxy_mutex_lock(&gmtime_mutex);
2912 timeptr = gmtime(&last_modified);
2913 privoxy_mutex_unlock(&gmtime_mutex);
2915 timeptr = gmtime(&last_modified);
2917 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2919 *header = strdup("Last-Modified: ");
2920 string_append(header, newheader);
2922 if (*header == NULL)
2924 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2925 return JB_ERR_MEMORY;
2928 days = rtime / (3600 * 24);
2929 hours = rtime / 3600 % 24;
2930 minutes = rtime / 60 % 60;
2931 seconds = rtime % 60;
2933 log_error(LOG_LEVEL_HEADER,
2934 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2935 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2936 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2940 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2949 /*********************************************************************
2951 * Function : client_accept_encoding
2953 * Description : Rewrite the client's Accept-Encoding header so that
2954 * if doesn't allow compression, if the action applies.
2955 * Note: For HTTP/1.0 the absence of the header is enough.
2958 * 1 : csp = Current client state (buffers, headers, etc...)
2959 * 2 : header = On input, pointer to header to modify.
2960 * On output, pointer to the modified header, or NULL
2961 * to remove the header. This function frees the
2962 * original string if necessary.
2964 * Returns : JB_ERR_OK on success, or
2965 * JB_ERR_MEMORY on out-of-memory error.
2967 *********************************************************************/
2968 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2970 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2972 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2976 /* Temporarily disable the correct behaviour to
2977 * work around a PHP bug.
2979 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2981 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2982 * if (*header == NULL)
2984 * return JB_ERR_MEMORY;
2995 /*********************************************************************
2997 * Function : client_te
2999 * Description : Rewrite the client's TE header so that
3000 * if doesn't allow compression, if the action applies.
3003 * 1 : csp = Current client state (buffers, headers, etc...)
3004 * 2 : header = On input, pointer to header to modify.
3005 * On output, pointer to the modified header, or NULL
3006 * to remove the header. This function frees the
3007 * original string if necessary.
3009 * Returns : JB_ERR_OK on success, or
3010 * JB_ERR_MEMORY on out-of-memory error.
3012 *********************************************************************/
3013 static jb_err client_te(struct client_state *csp, char **header)
3015 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3018 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3025 /*********************************************************************
3027 * Function : client_referrer
3029 * Description : Handle the "referer" config setting properly.
3030 * Called from `sed'.
3033 * 1 : csp = Current client state (buffers, headers, etc...)
3034 * 2 : header = On input, pointer to header to modify.
3035 * On output, pointer to the modified header, or NULL
3036 * to remove the header. This function frees the
3037 * original string if necessary.
3039 * Returns : JB_ERR_OK on success, or
3040 * JB_ERR_MEMORY on out-of-memory error.
3042 *********************************************************************/
3043 static jb_err client_referrer(struct client_state *csp, char **header)
3045 const char *parameter;
3046 /* booleans for parameters we have to check multiple times */
3047 int parameter_conditional_block;
3048 int parameter_conditional_forge;
3050 #ifdef FEATURE_FORCE_LOAD
3052 * Since the referrer can include the prefix even
3053 * if the request itself is non-forced, we must
3054 * clean it unconditionally.
3056 * XXX: strclean is too broad
3058 strclean(*header, FORCE_PREFIX);
3059 #endif /* def FEATURE_FORCE_LOAD */
3061 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3063 /* Nothing left to do */
3067 parameter = csp->action->string[ACTION_STRING_REFERER];
3068 assert(parameter != NULL);
3069 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3070 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3072 if (!parameter_conditional_block && !parameter_conditional_forge)
3075 * As conditional-block and conditional-forge are the only
3076 * parameters that rely on the original referrer, we can
3077 * remove it now for all the others.
3082 if (0 == strcmpic(parameter, "block"))
3084 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3087 else if (parameter_conditional_block || parameter_conditional_forge)
3089 return handle_conditional_hide_referrer_parameter(header,
3090 csp->http->hostport, parameter_conditional_block);
3092 else if (0 == strcmpic(parameter, "forge"))
3094 return create_forged_referrer(header, csp->http->hostport);
3098 /* interpret parameter as user-supplied referer to fake */
3099 return create_fake_referrer(header, parameter);
3104 /*********************************************************************
3106 * Function : client_accept_language
3108 * Description : Handle the "Accept-Language" config setting properly.
3109 * Called from `sed'.
3112 * 1 : csp = Current client state (buffers, headers, etc...)
3113 * 2 : header = On input, pointer to header to modify.
3114 * On output, pointer to the modified header, or NULL
3115 * to remove the header. This function frees the
3116 * original string if necessary.
3118 * Returns : JB_ERR_OK on success, or
3119 * JB_ERR_MEMORY on out-of-memory error.
3121 *********************************************************************/
3122 static jb_err client_accept_language(struct client_state *csp, char **header)
3127 * Are we messing with the Accept-Language?
3129 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3131 /*I don't think so*/
3135 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3137 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3140 * Blocking Accept-Language header
3142 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3149 * Replacing Accept-Language header
3152 *header = strdup("Accept-Language: ");
3153 string_append(header, newval);
3155 if (*header == NULL)
3157 log_error(LOG_LEVEL_ERROR,
3158 "Insufficient memory. Accept-Language header crunched without replacement.");
3162 log_error(LOG_LEVEL_HEADER,
3163 "Accept-Language header crunched and replaced with: %s", *header);
3166 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3170 /*********************************************************************
3172 * Function : crunch_client_header
3174 * Description : Crunch client header if it matches a string supplied by the
3175 * user. Called from `sed'.
3178 * 1 : csp = Current client state (buffers, headers, etc...)
3179 * 2 : header = On input, pointer to header to modify.
3180 * On output, pointer to the modified header, or NULL
3181 * to remove the header. This function frees the
3182 * original string if necessary.
3184 * Returns : JB_ERR_OK on success and always succeeds
3186 *********************************************************************/
3187 static jb_err crunch_client_header(struct client_state *csp, char **header)
3189 const char *crunch_pattern;
3191 /* Do we feel like crunching? */
3192 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3194 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3196 /* Is the current header the lucky one? */
3197 if (strstr(*header, crunch_pattern))
3199 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3207 /*********************************************************************
3209 * Function : client_uagent
3211 * Description : Handle the "user-agent" config setting properly
3212 * and remember its original value to enable browser
3213 * bug workarounds. Called from `sed'.
3216 * 1 : csp = Current client state (buffers, headers, etc...)
3217 * 2 : header = On input, pointer to header to modify.
3218 * On output, pointer to the modified header, or NULL
3219 * to remove the header. This function frees the
3220 * original string if necessary.
3222 * Returns : JB_ERR_OK on success, or
3223 * JB_ERR_MEMORY on out-of-memory error.
3225 *********************************************************************/
3226 static jb_err client_uagent(struct client_state *csp, char **header)
3230 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3235 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3242 *header = strdup("User-Agent: ");
3243 string_append(header, newval);
3245 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3247 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3251 /*********************************************************************
3253 * Function : client_ua
3255 * Description : Handle "ua-" headers properly. Called from `sed'.
3258 * 1 : csp = Current client state (buffers, headers, etc...)
3259 * 2 : header = On input, pointer to header to modify.
3260 * On output, pointer to the modified header, or NULL
3261 * to remove the header. This function frees the
3262 * original string if necessary.
3264 * Returns : JB_ERR_OK on success, or
3265 * JB_ERR_MEMORY on out-of-memory error.
3267 *********************************************************************/
3268 static jb_err client_ua(struct client_state *csp, char **header)
3270 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3272 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3280 /*********************************************************************
3282 * Function : client_from
3284 * Description : Handle the "from" config setting properly.
3285 * Called from `sed'.
3288 * 1 : csp = Current client state (buffers, headers, etc...)
3289 * 2 : header = On input, pointer to header to modify.
3290 * On output, pointer to the modified header, or NULL
3291 * to remove the header. This function frees the
3292 * original string if necessary.
3294 * Returns : JB_ERR_OK on success, or
3295 * JB_ERR_MEMORY on out-of-memory error.
3297 *********************************************************************/
3298 static jb_err client_from(struct client_state *csp, char **header)
3302 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3309 newval = csp->action->string[ACTION_STRING_FROM];
3312 * Are we blocking the e-mail address?
3314 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3316 log_error(LOG_LEVEL_HEADER, "crunched From!");
3320 log_error(LOG_LEVEL_HEADER, " modified");
3322 *header = strdup("From: ");
3323 string_append(header, newval);
3325 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3329 /*********************************************************************
3331 * Function : client_send_cookie
3333 * Description : Crunches the "cookie" header if necessary.
3334 * Called from `sed'.
3336 * XXX: Stupid name, doesn't send squat.
3339 * 1 : csp = Current client state (buffers, headers, etc...)
3340 * 2 : header = On input, pointer to header to modify.
3341 * On output, pointer to the modified header, or NULL
3342 * to remove the header. This function frees the
3343 * original string if necessary.
3345 * Returns : JB_ERR_OK on success, or
3346 * JB_ERR_MEMORY on out-of-memory error.
3348 *********************************************************************/
3349 static jb_err client_send_cookie(struct client_state *csp, char **header)
3351 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3353 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3361 /*********************************************************************
3363 * Function : client_x_forwarded
3365 * Description : Handle the "x-forwarded-for" config setting properly,
3366 * also used in the add_client_headers list. Called from `sed'.
3369 * 1 : csp = Current client state (buffers, headers, etc...)
3370 * 2 : header = On input, pointer to header to modify.
3371 * On output, pointer to the modified header, or NULL
3372 * to remove the header. This function frees the
3373 * original string if necessary.
3375 * Returns : JB_ERR_OK on success, or
3376 * JB_ERR_MEMORY on out-of-memory error.
3378 *********************************************************************/
3379 jb_err client_x_forwarded(struct client_state *csp, char **header)
3381 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3383 const char *param = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3385 if (0 == strcmpic(param, "block"))
3388 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3390 else if (0 == strcmpic(param, "add"))
3392 /* Save it so we can re-add it later */
3393 freez(csp->x_forwarded_for);
3394 csp->x_forwarded_for = *header;
3397 * Always set *header = NULL, since this information
3398 * will be sent at the end of the header.
3408 /*********************************************************************
3410 * Function : client_max_forwards
3412 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3413 * from the value of the Max-Forwards header field.
3416 * 1 : csp = Current client state (buffers, headers, etc...)
3417 * 2 : header = On input, pointer to header to modify.
3418 * On output, pointer to the modified header, or NULL
3419 * to remove the header. This function frees the
3420 * original string if necessary.
3422 * Returns : JB_ERR_OK on success, or
3423 * JB_ERR_MEMORY on out-of-memory error.
3425 *********************************************************************/
3426 static jb_err client_max_forwards(struct client_state *csp, char **header)
3430 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3431 (0 == strcmpic(csp->http->gpc, "options")))
3433 assert(*(*header+12) == ':');
3434 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3436 if (max_forwards > 0)
3438 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3439 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3440 csp->http->gpc, max_forwards);
3442 else if (max_forwards < 0)
3444 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3450 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3459 /*********************************************************************
3461 * Function : client_host
3463 * Description : If the request URI did not contain host and
3464 * port information, parse and evaluate the Host
3467 * Also, kill ill-formed HOST: headers as sent by
3468 * Apple's iTunes software when used with a proxy.
3471 * 1 : csp = Current client state (buffers, headers, etc...)
3472 * 2 : header = On input, pointer to header to modify.
3473 * On output, pointer to the modified header, or NULL
3474 * to remove the header. This function frees the
3475 * original string if necessary.
3477 * Returns : JB_ERR_OK on success, or
3478 * JB_ERR_MEMORY on out-of-memory error.
3480 *********************************************************************/
3481 static jb_err client_host(struct client_state *csp, char **header)
3486 * If the header field name is all upper-case, chances are that it's
3487 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3488 * not a problem -- they are regenerated later.
3490 if ((*header)[1] == 'O')
3492 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3497 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3498 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3501 if (NULL == (p = strdup((*header)+6)))
3503 return JB_ERR_MEMORY;
3506 if (NULL == (q = strdup(p)))
3509 return JB_ERR_MEMORY;
3512 freez(csp->http->hostport);
3513 csp->http->hostport = p;
3514 freez(csp->http->host);
3515 csp->http->host = q;
3516 q = strchr(csp->http->host, ':');
3519 /* Terminate hostname and evaluate port string */
3521 csp->http->port = atoi(q);
3525 csp->http->port = csp->http->ssl ? 443 : 80;
3528 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3529 csp->http->hostport, csp->http->host, csp->http->port);
3532 /* Signal client_host_adder() to return right away */
3533 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3539 /*********************************************************************
3541 * Function : client_if_modified_since
3543 * Description : Remove or modify the If-Modified-Since header.
3546 * 1 : csp = Current client state (buffers, headers, etc...)
3547 * 2 : header = On input, pointer to header to modify.
3548 * On output, pointer to the modified header, or NULL
3549 * to remove the header. This function frees the
3550 * original string if necessary.
3552 * Returns : JB_ERR_OK on success, or
3553 * JB_ERR_MEMORY on out-of-memory error.
3555 *********************************************************************/
3556 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3559 #ifdef HAVE_GMTIME_R
3562 struct tm *timeptr = NULL;
3566 long int hours, minutes, seconds;
3570 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3573 * The client got an error message because of a temporary problem,
3574 * the problem is gone and the client now tries to revalidate our
3575 * error message on the real server. The revalidation would always
3576 * end with the transmission of the whole document and there is
3577 * no need to expose the bogus If-Modified-Since header.
3579 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3582 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3584 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3586 if ((0 == strcmpic(newval, "block")))
3588 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3591 else /* add random value */
3593 const char *header_time = *header + sizeof("If-Modified-Since:");
3595 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3597 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3602 rtime = strtol(newval, &endptr, 0);
3605 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3606 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3613 rtime = pick_from_range(rtime);
3617 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3620 tm += rtime * (negative ? -1 : 1);
3621 #ifdef HAVE_GMTIME_R
3622 timeptr = gmtime_r(&tm, &gmt);
3623 #elif FEATURE_PTHREAD
3624 privoxy_mutex_lock(&gmtime_mutex);
3625 timeptr = gmtime(&tm);
3626 privoxy_mutex_unlock(&gmtime_mutex);
3628 timeptr = gmtime(&tm);
3630 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3633 *header = strdup("If-Modified-Since: ");
3634 string_append(header, newheader);
3636 if (*header == NULL)
3638 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3639 return JB_ERR_MEMORY;
3642 hours = rtime / 3600;
3643 minutes = rtime / 60 % 60;
3644 seconds = rtime % 60;
3646 log_error(LOG_LEVEL_HEADER,
3647 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3648 *header, (negative) ? "subtracted" : "added", hours,
3649 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3650 seconds, (seconds == 1) ? ")" : "s)");
3659 /*********************************************************************
3661 * Function : client_if_none_match
3663 * Description : Remove the If-None-Match 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_none_match(struct client_state *csp, char **header)
3678 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3680 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3688 /*********************************************************************
3690 * Function : client_x_filter
3692 * Description : Disables filtering if the client set "X-Filter: No".
3693 * Called from `sed'.
3696 * 1 : csp = Current client state (buffers, headers, etc...)
3697 * 2 : header = On input, pointer to header to modify.
3698 * On output, pointer to the modified header, or NULL
3699 * to remove the header. This function frees the
3700 * original string if necessary.
3702 * Returns : JB_ERR_OK on success
3704 *********************************************************************/
3705 jb_err client_x_filter(struct client_state *csp, char **header)
3707 if ( 0 == strcmpic(*header, "X-Filter: No"))
3709 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3711 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3715 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3717 log_error(LOG_LEVEL_HEADER,
3718 "force-text-mode overruled the client's request to fetch without filtering!");
3722 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3723 csp->flags |= CSP_FLAG_NO_FILTERING;
3724 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3726 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3734 /*********************************************************************
3736 * Function : client_range
3738 * Description : Removes Range, Request-Range and If-Range headers if
3739 * content filtering is enabled. If the client's version
3740 * of the document has been altered by Privoxy, the server
3741 * could interpret the range differently than the client
3742 * intended in which case the user could end up with
3743 * corrupted content.
3746 * 1 : csp = Current client state (buffers, headers, etc...)
3747 * 2 : header = On input, pointer to header to modify.
3748 * On output, pointer to the modified header, or NULL
3749 * to remove the header. This function frees the
3750 * original string if necessary.
3752 * Returns : JB_ERR_OK
3754 *********************************************************************/
3755 static jb_err client_range(struct client_state *csp, char **header)
3757 if (content_filters_enabled(csp->action))
3759 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3760 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3767 /* the following functions add headers directly to the header list */
3769 /*********************************************************************
3771 * Function : client_host_adder
3773 * Description : Adds the Host: header field if it is missing.
3774 * Called from `sed'.
3777 * 1 : csp = Current client state (buffers, headers, etc...)
3779 * Returns : JB_ERR_OK on success, or
3780 * JB_ERR_MEMORY on out-of-memory error.
3782 *********************************************************************/
3783 static jb_err client_host_adder(struct client_state *csp)
3788 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3790 /* Header already set by the client, nothing to do. */
3794 if ( !csp->http->hostport || !*(csp->http->hostport))
3796 /* XXX: When does this happen and why is it OK? */
3797 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3802 * remove 'user:pass@' from 'proto://user:pass@host'
3804 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3810 p = csp->http->hostport;
3813 /* XXX: Just add it, we already made sure that it will be unique */
3814 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3815 err = enlist_unique_header(csp->headers, "Host", p);
3822 /*********************************************************************
3824 * Function : client_accept_encoding_adder
3826 * Description : Add an Accept-Encoding header to the client's request
3827 * that disables compression if the action applies, and
3828 * the header is not already there. Called from `sed'.
3829 * Note: For HTTP/1.0, the absence of the header is enough.
3832 * 1 : csp = Current client state (buffers, headers, etc...)
3834 * Returns : JB_ERR_OK on success, or
3835 * JB_ERR_MEMORY on out-of-memory error.
3837 *********************************************************************/
3838 static jb_err client_accept_encoding_adder(struct client_state *csp)
3840 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3841 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3843 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3851 /*********************************************************************
3853 * Function : client_xtra_adder
3855 * Description : Used in the add_client_headers list. Called from `sed'.
3858 * 1 : csp = Current client state (buffers, headers, etc...)
3860 * Returns : JB_ERR_OK on success, or
3861 * JB_ERR_MEMORY on out-of-memory error.
3863 *********************************************************************/
3864 static jb_err client_xtra_adder(struct client_state *csp)
3866 struct list_entry *lst;
3869 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3870 lst ; lst = lst->next)
3872 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3873 err = enlist(csp->headers, lst->str);
3885 /*********************************************************************
3887 * Function : client_x_forwarded_for_adder
3889 * Description : Used in the add_client_headers list. Called from `sed'.
3892 * 1 : csp = Current client state (buffers, headers, etc...)
3894 * Returns : JB_ERR_OK on success, or
3895 * JB_ERR_MEMORY on out-of-memory error.
3897 *********************************************************************/
3898 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3900 char *header = NULL;
3903 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR) &&
3904 (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add"))))
3909 if (csp->x_forwarded_for)
3911 header = strdup(csp->x_forwarded_for);
3912 string_append(&header, ", ");
3916 header = strdup("X-Forwarded-For: ");
3918 string_append(&header, csp->ip_addr_str);
3922 return JB_ERR_MEMORY;
3925 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3926 err = enlist(csp->headers, header);
3933 /*********************************************************************
3935 * Function : connection_close_adder
3937 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3938 * support. Adds a "Connection: close" header to csp->headers
3939 * unless the header was already present. Called from `sed'.
3941 * FIXME: This whole function shouldn't be neccessary!
3944 * 1 : csp = Current client state (buffers, headers, etc...)
3946 * Returns : JB_ERR_OK on success, or
3947 * JB_ERR_MEMORY on out-of-memory error.
3949 *********************************************************************/
3950 static jb_err connection_close_adder(struct client_state *csp)
3952 const unsigned int flags = csp->flags;
3955 * Return right away if
3957 * - we're parsing server headers and the server header
3958 * "Connection: close" is already set, or if
3960 * - we're parsing client headers and the client header
3961 * "Connection: close" is already set.
3963 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3964 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3965 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3966 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3971 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3973 return enlist(csp->headers, "Connection: close");
3977 /*********************************************************************
3979 * Function : server_http
3981 * Description : - Save the HTTP Status into csp->http->status
3982 * - Set CT_TABOO to prevent filtering if the answer
3983 * is a partial range (HTTP status 206)
3984 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3988 * 1 : csp = Current client state (buffers, headers, etc...)
3989 * 2 : header = On input, pointer to header to modify.
3990 * On output, pointer to the modified header, or NULL
3991 * to remove the header. This function frees the
3992 * original string if necessary.
3994 * Returns : JB_ERR_OK on success, or
3995 * JB_ERR_MEMORY on out-of-memory error.
3997 *********************************************************************/
3998 static jb_err server_http(struct client_state *csp, char **header)
4000 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
4001 if (csp->http->status == 206)
4003 csp->content_type = CT_TABOO;
4006 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
4008 /* XXX: Should we do a real validity check here? */
4009 if (strlen(*header) > 8)
4012 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
4017 * XXX: Should we block the request or
4018 * enlist a valid status code line here?
4020 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
4021 "Downgrading to HTTP/1.0 impossible.");
4029 /*********************************************************************
4031 * Function : server_set_cookie
4033 * Description : Handle the server "cookie" header properly.
4034 * Log cookie to the jar file. Then "crunch",
4035 * accept or rewrite it to a session cookie.
4036 * Called from `sed'.
4038 * TODO: Allow the user to specify a new expiration
4039 * time to cause the cookie to expire even before the
4040 * browser is closed.
4043 * 1 : csp = Current client state (buffers, headers, etc...)
4044 * 2 : header = On input, pointer to header to modify.
4045 * On output, pointer to the modified header, or NULL
4046 * to remove the header. This function frees the
4047 * original string if necessary.
4049 * Returns : JB_ERR_OK on success, or
4050 * JB_ERR_MEMORY on out-of-memory error.
4052 *********************************************************************/
4053 static jb_err server_set_cookie(struct client_state *csp, char **header)
4060 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4062 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4065 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4067 /* Flag whether or not to log a message */
4070 /* A variable to store the tag we're working on */
4073 /* Skip "Set-Cookie:" (11 characters) in header */
4074 cur_tag = *header + 11;
4076 /* skip whitespace between "Set-Cookie:" and value */
4077 while (*cur_tag && ijb_isspace(*cur_tag))
4082 /* Loop through each tag in the cookie */
4086 char *next_tag = strchr(cur_tag, ';');
4087 if (next_tag != NULL)
4089 /* Skip the ';' character itself */
4092 /* skip whitespace ";" and start of tag */
4093 while (*next_tag && ijb_isspace(*next_tag))
4100 /* "Next tag" is the end of the string */
4101 next_tag = cur_tag + strlen(cur_tag);
4105 * Check the expiration date to see
4106 * if the cookie is still valid, if yes,
4107 * rewrite it to a session cookie.
4109 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4111 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4113 /* Did we detect the date properly? */
4114 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4117 * Nope, treat it as if it was still valid.
4119 * XXX: Should we remove the whole cookie instead?
4121 log_error(LOG_LEVEL_ERROR,
4122 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4123 string_move(cur_tag, next_tag);
4129 * Yes. Check if the cookie is still valid.
4131 * If the cookie is already expired it's probably
4132 * a delete cookie and even if it isn't, the browser
4133 * will discard it anyway.
4137 * XXX: timegm() isn't available on some AmigaOS
4138 * versions and our replacement doesn't work.
4140 * Our options are to either:
4142 * - disable session-cookies-only completely if timegm
4145 * - to simply remove all expired tags, like it has
4146 * been done until Privoxy 3.0.6 and to live with
4147 * the consequence that it can cause login/logout
4148 * problems on servers that don't validate their
4149 * input properly, or
4151 * - to replace it with mktime in which
4152 * case there is a slight chance of valid cookies
4153 * passing as already expired.
4155 * This is the way it's currently done and it's not
4156 * as bad as it sounds. If the missing GMT offset is
4157 * enough to change the result of the expiration check
4158 * the cookie will be only valid for a few hours
4159 * anyway, which in many cases will be shorter
4160 * than a browser session.
4162 if (cookie_time - now < 0)
4164 log_error(LOG_LEVEL_HEADER,
4165 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4166 /* Just in case some clown sets more then one expiration date */
4172 * Still valid, delete expiration date by copying
4173 * the rest of the string over it.
4175 string_move(cur_tag, next_tag);
4177 /* That changed the header, need to issue a log message */
4181 * Note that the next tag has now been moved to *cur_tag,
4182 * so we do not need to update the cur_tag pointer.
4190 /* Move on to next cookie tag */
4197 assert(NULL != *header);
4198 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4207 #ifdef FEATURE_FORCE_LOAD
4208 /*********************************************************************
4210 * Function : strclean
4212 * Description : In-Situ-Eliminate all occurances of substring in
4216 * 1 : string = string to clean
4217 * 2 : substring = substring to eliminate
4219 * Returns : Number of eliminations
4221 *********************************************************************/
4222 int strclean(char *string, const char *substring)
4228 len = strlen(substring);
4230 while((pos = strstr(string, substring)) != NULL)
4237 while (*p++ != '\0');
4244 #endif /* def FEATURE_FORCE_LOAD */
4247 /*********************************************************************
4249 * Function : parse_header_time
4251 * Description : Parses time formats used in HTTP header strings
4252 * to get the numerical respresentation.
4255 * 1 : header_time = HTTP header time as string.
4256 * 2 : result = storage for header_time in seconds
4258 * Returns : JB_ERR_OK if the time format was recognized, or
4259 * JB_ERR_PARSE otherwise.
4261 *********************************************************************/
4262 static jb_err parse_header_time(const char *header_time, time_t *result)
4267 * Zero out gmt to prevent time zone offsets.
4269 * While this is only necessary on some platforms
4270 * (mingw32 for example), I don't know how to
4271 * detect these automatically and doing it everywhere
4274 memset(&gmt, 0, sizeof(gmt));
4276 /* Tue, 02 Jun 2037 20:00:00 */
4277 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4278 /* Tue, 02-Jun-2037 20:00:00 */
4279 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4280 /* Tue, 02-Jun-37 20:00:00 */
4281 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4282 /* Tuesday, 02-Jun-2037 20:00:00 */
4283 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4284 /* Tuesday Jun 02 20:00:00 2037 */
4285 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4287 return JB_ERR_PARSE;
4290 *result = timegm(&gmt);
4297 /*********************************************************************
4299 * Function : get_destination_from_headers
4301 * Description : Parse the "Host:" header to get the request's destination.
4302 * Only needed if the client's request was forcefully
4303 * redirected into Privoxy.
4305 * Code mainly copied from client_host() which is currently
4306 * run too late for this purpose.
4309 * 1 : headers = List of headers (one of them hopefully being
4310 * the "Host:" header)
4311 * 2 : http = storage for the result (host, port and hostport).
4313 * Returns : JB_ERR_MEMORY in case of memory problems,
4314 * JB_ERR_PARSE if the host header couldn't be found,
4315 * JB_ERR_OK otherwise.
4317 *********************************************************************/
4318 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4324 host = get_header_value(headers, "Host:");
4328 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4329 return JB_ERR_PARSE;
4332 if (NULL == (p = strdup((host))))
4334 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4335 return JB_ERR_MEMORY;
4338 if (NULL == (q = strdup(p)))
4341 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4342 return JB_ERR_MEMORY;
4345 freez(http->hostport);
4349 q = strchr(http->host, ':');
4352 /* Terminate hostname and evaluate port string */
4354 http->port = atoi(q);
4358 http->port = http->ssl ? 443 : 80;
4361 /* Rebuild request URL */
4363 http->url = strdup(http->ssl ? "https://" : "http://");
4364 string_append(&http->url, http->hostport);
4365 string_append(&http->url, http->path);
4366 if (http->url == NULL)
4368 return JB_ERR_MEMORY;
4371 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4379 /*********************************************************************
4381 * Function : create_forged_referrer
4383 * Description : Helper for client_referrer to forge a referer as
4384 * 'http://[hostname:port/' to fool stupid
4385 * checks for in-site links
4388 * 1 : header = Pointer to header pointer
4389 * 2 : hostport = Host and optionally port as string
4391 * Returns : JB_ERR_OK in case of success, or
4392 * JB_ERR_MEMORY in case of memory problems.
4394 *********************************************************************/
4395 static jb_err create_forged_referrer(char **header, const char *hostport)
4397 assert(NULL == *header);
4399 *header = strdup("Referer: http://");
4400 string_append(header, hostport);
4401 string_append(header, "/");
4403 if (NULL == *header)
4405 return JB_ERR_MEMORY;
4408 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4415 /*********************************************************************
4417 * Function : create_fake_referrer
4419 * Description : Helper for client_referrer to create a fake referrer
4420 * based on a string supplied by the user.
4423 * 1 : header = Pointer to header pointer
4424 * 2 : hosthost = Referrer to fake
4426 * Returns : JB_ERR_OK in case of success, or
4427 * JB_ERR_MEMORY in case of memory problems.
4429 *********************************************************************/
4430 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4432 assert(NULL == *header);
4434 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4436 log_error(LOG_LEVEL_HEADER,
4437 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4439 *header = strdup("Referer: ");
4440 string_append(header, fake_referrer);
4442 if (NULL == *header)
4444 return JB_ERR_MEMORY;
4447 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4454 /*********************************************************************
4456 * Function : handle_conditional_hide_referrer_parameter
4458 * Description : Helper for client_referrer to crunch or forge
4459 * the referrer header if the host has changed.
4462 * 1 : header = Pointer to header pointer
4463 * 2 : host = The target host (may include the port)
4464 * 3 : parameter_conditional_block = Boolean to signal
4465 * if we're in conditional-block mode. If not set,
4466 * we're in conditional-forge mode.
4468 * Returns : JB_ERR_OK in case of success, or
4469 * JB_ERR_MEMORY in case of memory problems.
4471 *********************************************************************/
4472 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4473 const char *host, const int parameter_conditional_block)
4475 char *referer = strdup(*header);
4476 const size_t hostlenght = strlen(host);
4478 if (NULL == referer)
4481 return JB_ERR_MEMORY;
4484 /* referer begins with 'Referer: http[s]://' */
4485 if (hostlenght < (strlen(referer)-17))
4488 * Shorten referer to make sure the referer is blocked
4489 * if www.example.org/www.example.com-shall-see-the-referer/
4490 * links to www.example.com/
4492 referer[hostlenght+17] = '\0';
4494 if (NULL == strstr(referer, host))
4496 /* Host has changed */
4497 if (parameter_conditional_block)
4499 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4506 return create_forged_referrer(header, host);